const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./GraphView-D1V4EJXE.js","./vendor-vue-B7YUw5vA.js","./vendor-primevue-jcK-2oYL.js","./vendor-vue-i18n-CdFxvEOa.js","./UserAvatar-CLuKxYMs.js","./keybindingService-RcbscmCB.js","./serverConfigStore-B9c3gGty.js","./GraphView-Xpax26U9.css","./UserSelectView-D47mThhN.js","./BaseViewTemplate-DVC1R0sk.js","./ServerStartView-DBkhOGrG.js","./ServerStartView-DpZrG3I7.css","./InstallView-n1yIGren.js","./uvMirrors-bGzd1syV.js","./InstallView--d1FxhPB.css","./WelcomeView-D5JBR5jL.js","./WelcomeView-Dyp2dF6q.css","./NotSupportedView-D9DpH9zy.js","./NotSupportedView-BBM3volz.css","./DownloadGitView-CI2P920b.js","./ManualConfigurationView-6hm2NmAw.js","./ManualConfigurationView-CDSFxfkz.css","./MetricsConsentView-C4pUTn28.js","./DesktopStartView-DQVeDhKD.js","./MaintenanceView-CmPBr2TJ.js","./TerminalOutputDrawer-BV-rIdd5.js","./MaintenanceView-PVV146l6.css","./DesktopUpdateView-D0MR0yAS.js","./DesktopUpdateView-CoZUcBzh.css","./AboutPanel-Cq6ejTBZ.js","./CreditsPanel-BnuIPg_X.js","./UserPanel-B_YCqmUQ.js","./KeybindingPanel-DH9CRsRH.js","./KeybindingPanel-tsP0vxL-.css","./ExtensionPanel-GFGmjfDu.js","./ServerConfigPanel-De4zH79o.js","./index-DCPa4E5D.js","./index-8Q_RMs6B.css"])))=>i.map(i=>d[i]);
var __defProp2 = Object.defineProperty;
var __name = (target, value) => __defProp2(target, "name", { value, configurable: true });
import { BaseStyle as BaseStyle$1, usePrimeVue, ZIndex as ZIndex$1, script as script$4, script$1 as script$5, script$2 as script$6, script$3 as script$7, script$4 as script$8, script$5 as script$9, useToast, script$6 as script$a, script$7 as script$b, script$8 as script$c, script$9 as script$d, script$10 as script$e, script$11 as script$f, script$12 as script$g, script$13 as script$h, script$14 as script$i, script$15 as script$j, script$16 as script$k, script$17 as script$l, script$18 as script$m, script$19 as script$n, script$20 as script$o, script$21 as script$p, script$22 as script$q, script$23 as script$r, script$24 as script$s, script$25 as script$t, script$26 as script$u, script$27 as script$v, script$28 as script$w, script$29 as script$x, script$30 as script$y, script$31 as script$z, script$32 as script$A, script$33 as script$B, script$34 as script$C, script$35 as script$D, script$36 as script$E, script$37 as script$F, script$38 as script$G, script$39 as script$H, script$40 as script$I, script$41 as script$J, script$42 as script$K, script$43 as script$L, script$44 as script$M, useConfirm, script$45 as script$N, script$46 as script$O, script$47 as script$P, definePreset as definePreset$1, Tooltip, PrimeVue, ConfirmationService, ToastService } from "./vendor-primevue-jcK-2oYL.js";
import { hasInjectionContext, inject, toRaw, watch, unref, markRaw, effectScope, ref as ref$3, isRef, isReactive, getCurrentScope as getCurrentScope$1, onScopeDispose, toRefs as toRefs$1, computed, nextTick, reactive, toRef as toRef$1, getCurrentInstance, toValue as toValue$4, shallowRef, onServerPrefetch, onUnmounted, onDeactivated, onActivated, watchEffect, defineComponent, h as h$2, provide, shallowReactive, readonly, customRef, version as version$6, onBeforeMount, onBeforeUnmount, onMounted, Fragment as Fragment$1, TransitionGroup, onUpdated, isReadonly, onBeforeUpdate, resolveComponent, openBlock, createElementBlock, createVNode, renderList, createBlock, mergeProps as mergeProps$1, createSlots, withCtx, resolveDynamicComponent, toDisplayString, createBaseVNode, createTextVNode, createCommentVNode, normalizeClass, withModifiers, renderSlot, resolveDirective, withDirectives, vShow, Suspense, withKeys, defineAsyncComponent, mergeModels, useModel, normalizeStyle, useId, Teleport, render as render$3, createApp } from "./vendor-vue-B7YUw5vA.js";
import { setupDevtoolsPlugin, createI18n, useI18n } from "./vendor-vue-i18n-CdFxvEOa.js";
(/* @__PURE__ */ __name(function polyfill2() {
  const relList = document.createElement("link").relList;
  if (relList && relList.supports && relList.supports("modulepreload")) {
    return;
  }
  for (const link2 of document.querySelectorAll('link[rel="modulepreload"]')) {
    processPreload(link2);
  }
  new MutationObserver((mutations) => {
    for (const mutation of mutations) {
      if (mutation.type !== "childList") {
        continue;
      }
      for (const node2 of mutation.addedNodes) {
        if (node2.tagName === "LINK" && node2.rel === "modulepreload")
          processPreload(node2);
      }
    }
  }).observe(document, { childList: true, subtree: true });
  function getFetchOpts(link2) {
    const fetchOpts = {};
    if (link2.integrity) fetchOpts.integrity = link2.integrity;
    if (link2.referrerPolicy) fetchOpts.referrerPolicy = link2.referrerPolicy;
    if (link2.crossOrigin === "use-credentials")
      fetchOpts.credentials = "include";
    else if (link2.crossOrigin === "anonymous") fetchOpts.credentials = "omit";
    else fetchOpts.credentials = "same-origin";
    return fetchOpts;
  }
  __name(getFetchOpts, "getFetchOpts");
  function processPreload(link2) {
    if (link2.ep)
      return;
    link2.ep = true;
    const fetchOpts = getFetchOpts(link2);
    fetch(link2.href, fetchOpts);
  }
  __name(processPreload, "processPreload");
}, "polyfill"))();
var index$1r = {
  root: {
    transitionDuration: "{transition.duration}"
  },
  panel: {
    borderWidth: "0 0 1px 0",
    borderColor: "{content.border.color}"
  },
  header: {
    color: "{text.muted.color}",
    hoverColor: "{text.color}",
    activeColor: "{text.color}",
    padding: "1.125rem",
    fontWeight: "600",
    borderRadius: "0",
    borderWidth: "0",
    borderColor: "{content.border.color}",
    background: "{content.background}",
    hoverBackground: "{content.background}",
    activeBackground: "{content.background}",
    activeHoverBackground: "{content.background}",
    focusRing: {
      width: "{focus.ring.width}",
      style: "{focus.ring.style}",
      color: "{focus.ring.color}",
      offset: "-1px",
      shadow: "{focus.ring.shadow}"
    },
    toggleIcon: {
      color: "{text.muted.color}",
      hoverColor: "{text.color}",
      activeColor: "{text.color}",
      activeHoverColor: "{text.color}"
    },
    first: {
      topBorderRadius: "{content.border.radius}",
      borderWidth: "0"
    },
    last: {
      bottomBorderRadius: "{content.border.radius}",
      activeBottomBorderRadius: "0"
    }
  },
  content: {
    borderWidth: "0",
    borderColor: "{content.border.color}",
    background: "{content.background}",
    color: "{text.color}",
    padding: "0 1.125rem 1.125rem 1.125rem"
  }
};
var index$1q = {
  root: {
    background: "{form.field.background}",
    disabledBackground: "{form.field.disabled.background}",
    filledBackground: "{form.field.filled.background}",
    filledHoverBackground: "{form.field.filled.hover.background}",
    filledFocusBackground: "{form.field.filled.focus.background}",
    borderColor: "{form.field.border.color}",
    hoverBorderColor: "{form.field.hover.border.color}",
    focusBorderColor: "{form.field.focus.border.color}",
    invalidBorderColor: "{form.field.invalid.border.color}",
    color: "{form.field.color}",
    disabledColor: "{form.field.disabled.color}",
    placeholderColor: "{form.field.placeholder.color}",
    invalidPlaceholderColor: "{form.field.invalid.placeholder.color}",
    shadow: "{form.field.shadow}",
    paddingX: "{form.field.padding.x}",
    paddingY: "{form.field.padding.y}",
    borderRadius: "{form.field.border.radius}",
    focusRing: {
      width: "{form.field.focus.ring.width}",
      style: "{form.field.focus.ring.style}",
      color: "{form.field.focus.ring.color}",
      offset: "{form.field.focus.ring.offset}",
      shadow: "{form.field.focus.ring.shadow}"
    },
    transitionDuration: "{form.field.transition.duration}"
  },
  overlay: {
    background: "{overlay.select.background}",
    borderColor: "{overlay.select.border.color}",
    borderRadius: "{overlay.select.border.radius}",
    color: "{overlay.select.color}",
    shadow: "{overlay.select.shadow}"
  },
  list: {
    padding: "{list.padding}",
    gap: "{list.gap}"
  },
  option: {
    focusBackground: "{list.option.focus.background}",
    selectedBackground: "{list.option.selected.background}",
    selectedFocusBackground: "{list.option.selected.focus.background}",
    color: "{list.option.color}",
    focusColor: "{list.option.focus.color}",
    selectedColor: "{list.option.selected.color}",
    selectedFocusColor: "{list.option.selected.focus.color}",
    padding: "{list.option.padding}",
    borderRadius: "{list.option.border.radius}"
  },
  optionGroup: {
    background: "{list.option.group.background}",
    color: "{list.option.group.color}",
    fontWeight: "{list.option.group.font.weight}",
    padding: "{list.option.group.padding}"
  },
  dropdown: {
    width: "2.5rem",
    sm: {
      width: "2rem"
    },
    lg: {
      width: "3rem"
    },
    borderColor: "{form.field.border.color}",
    hoverBorderColor: "{form.field.border.color}",
    activeBorderColor: "{form.field.border.color}",
    borderRadius: "{form.field.border.radius}",
    focusRing: {
      width: "{focus.ring.width}",
      style: "{focus.ring.style}",
      color: "{focus.ring.color}",
      offset: "{focus.ring.offset}",
      shadow: "{focus.ring.shadow}"
    }
  },
  chip: {
    borderRadius: "{border.radius.sm}"
  },
  emptyMessage: {
    padding: "{list.option.padding}"
  },
  colorScheme: {
    light: {
      chip: {
        focusBackground: "{surface.200}",
        focusColor: "{surface.800}"
      },
      dropdown: {
        background: "{surface.100}",
        hoverBackground: "{surface.200}",
        activeBackground: "{surface.300}",
        color: "{surface.600}",
        hoverColor: "{surface.700}",
        activeColor: "{surface.800}"
      }
    },
    dark: {
      chip: {
        focusBackground: "{surface.700}",
        focusColor: "{surface.0}"
      },
      dropdown: {
        background: "{surface.800}",
        hoverBackground: "{surface.700}",
        activeBackground: "{surface.600}",
        color: "{surface.300}",
        hoverColor: "{surface.200}",
        activeColor: "{surface.100}"
      }
    }
  }
};
var index$1p = {
  root: {
    width: "2rem",
    height: "2rem",
    fontSize: "1rem",
    background: "{content.border.color}",
    color: "{content.color}",
    borderRadius: "{content.border.radius}"
  },
  icon: {
    size: "1rem"
  },
  group: {
    borderColor: "{content.background}",
    offset: "-0.75rem"
  },
  lg: {
    width: "3rem",
    height: "3rem",
    fontSize: "1.5rem",
    icon: {
      size: "1.5rem"
    },
    group: {
      offset: "-1rem"
    }
  },
  xl: {
    width: "4rem",
    height: "4rem",
    fontSize: "2rem",
    icon: {
      size: "2rem"
    },
    group: {
      offset: "-1.5rem"
    }
  }
};
var index$1o = {
  root: {
    borderRadius: "{border.radius.md}",
    padding: "0 0.5rem",
    fontSize: "0.75rem",
    fontWeight: "700",
    minWidth: "1.5rem",
    height: "1.5rem"
  },
  dot: {
    size: "0.5rem"
  },
  sm: {
    fontSize: "0.625rem",
    minWidth: "1.25rem",
    height: "1.25rem"
  },
  lg: {
    fontSize: "0.875rem",
    minWidth: "1.75rem",
    height: "1.75rem"
  },
  xl: {
    fontSize: "1rem",
    minWidth: "2rem",
    height: "2rem"
  },
  colorScheme: {
    light: {
      primary: {
        background: "{primary.color}",
        color: "{primary.contrast.color}"
      },
      secondary: {
        background: "{surface.100}",
        color: "{surface.600}"
      },
      success: {
        background: "{green.500}",
        color: "{surface.0}"
      },
      info: {
        background: "{sky.500}",
        color: "{surface.0}"
      },
      warn: {
        background: "{orange.500}",
        color: "{surface.0}"
      },
      danger: {
        background: "{red.500}",
        color: "{surface.0}"
      },
      contrast: {
        background: "{surface.950}",
        color: "{surface.0}"
      }
    },
    dark: {
      primary: {
        background: "{primary.color}",
        color: "{primary.contrast.color}"
      },
      secondary: {
        background: "{surface.800}",
        color: "{surface.300}"
      },
      success: {
        background: "{green.400}",
        color: "{green.950}"
      },
      info: {
        background: "{sky.400}",
        color: "{sky.950}"
      },
      warn: {
        background: "{orange.400}",
        color: "{orange.950}"
      },
      danger: {
        background: "{red.400}",
        color: "{red.950}"
      },
      contrast: {
        background: "{surface.0}",
        color: "{surface.950}"
      }
    }
  }
};
var index$1n = {
  primitive: {
    borderRadius: {
      none: "0",
      xs: "2px",
      sm: "4px",
      md: "6px",
      lg: "8px",
      xl: "12px"
    },
    emerald: {
      50: "#ecfdf5",
      100: "#d1fae5",
      200: "#a7f3d0",
      300: "#6ee7b7",
      400: "#34d399",
      500: "#10b981",
      600: "#059669",
      700: "#047857",
      800: "#065f46",
      900: "#064e3b",
      950: "#022c22"
    },
    green: {
      50: "#f0fdf4",
      100: "#dcfce7",
      200: "#bbf7d0",
      300: "#86efac",
      400: "#4ade80",
      500: "#22c55e",
      600: "#16a34a",
      700: "#15803d",
      800: "#166534",
      900: "#14532d",
      950: "#052e16"
    },
    lime: {
      50: "#f7fee7",
      100: "#ecfccb",
      200: "#d9f99d",
      300: "#bef264",
      400: "#a3e635",
      500: "#84cc16",
      600: "#65a30d",
      700: "#4d7c0f",
      800: "#3f6212",
      900: "#365314",
      950: "#1a2e05"
    },
    red: {
      50: "#fef2f2",
      100: "#fee2e2",
      200: "#fecaca",
      300: "#fca5a5",
      400: "#f87171",
      500: "#ef4444",
      600: "#dc2626",
      700: "#b91c1c",
      800: "#991b1b",
      900: "#7f1d1d",
      950: "#450a0a"
    },
    orange: {
      50: "#fff7ed",
      100: "#ffedd5",
      200: "#fed7aa",
      300: "#fdba74",
      400: "#fb923c",
      500: "#f97316",
      600: "#ea580c",
      700: "#c2410c",
      800: "#9a3412",
      900: "#7c2d12",
      950: "#431407"
    },
    amber: {
      50: "#fffbeb",
      100: "#fef3c7",
      200: "#fde68a",
      300: "#fcd34d",
      400: "#fbbf24",
      500: "#f59e0b",
      600: "#d97706",
      700: "#b45309",
      800: "#92400e",
      900: "#78350f",
      950: "#451a03"
    },
    yellow: {
      50: "#fefce8",
      100: "#fef9c3",
      200: "#fef08a",
      300: "#fde047",
      400: "#facc15",
      500: "#eab308",
      600: "#ca8a04",
      700: "#a16207",
      800: "#854d0e",
      900: "#713f12",
      950: "#422006"
    },
    teal: {
      50: "#f0fdfa",
      100: "#ccfbf1",
      200: "#99f6e4",
      300: "#5eead4",
      400: "#2dd4bf",
      500: "#14b8a6",
      600: "#0d9488",
      700: "#0f766e",
      800: "#115e59",
      900: "#134e4a",
      950: "#042f2e"
    },
    cyan: {
      50: "#ecfeff",
      100: "#cffafe",
      200: "#a5f3fc",
      300: "#67e8f9",
      400: "#22d3ee",
      500: "#06b6d4",
      600: "#0891b2",
      700: "#0e7490",
      800: "#155e75",
      900: "#164e63",
      950: "#083344"
    },
    sky: {
      50: "#f0f9ff",
      100: "#e0f2fe",
      200: "#bae6fd",
      300: "#7dd3fc",
      400: "#38bdf8",
      500: "#0ea5e9",
      600: "#0284c7",
      700: "#0369a1",
      800: "#075985",
      900: "#0c4a6e",
      950: "#082f49"
    },
    blue: {
      50: "#eff6ff",
      100: "#dbeafe",
      200: "#bfdbfe",
      300: "#93c5fd",
      400: "#60a5fa",
      500: "#3b82f6",
      600: "#2563eb",
      700: "#1d4ed8",
      800: "#1e40af",
      900: "#1e3a8a",
      950: "#172554"
    },
    indigo: {
      50: "#eef2ff",
      100: "#e0e7ff",
      200: "#c7d2fe",
      300: "#a5b4fc",
      400: "#818cf8",
      500: "#6366f1",
      600: "#4f46e5",
      700: "#4338ca",
      800: "#3730a3",
      900: "#312e81",
      950: "#1e1b4b"
    },
    violet: {
      50: "#f5f3ff",
      100: "#ede9fe",
      200: "#ddd6fe",
      300: "#c4b5fd",
      400: "#a78bfa",
      500: "#8b5cf6",
      600: "#7c3aed",
      700: "#6d28d9",
      800: "#5b21b6",
      900: "#4c1d95",
      950: "#2e1065"
    },
    purple: {
      50: "#faf5ff",
      100: "#f3e8ff",
      200: "#e9d5ff",
      300: "#d8b4fe",
      400: "#c084fc",
      500: "#a855f7",
      600: "#9333ea",
      700: "#7e22ce",
      800: "#6b21a8",
      900: "#581c87",
      950: "#3b0764"
    },
    fuchsia: {
      50: "#fdf4ff",
      100: "#fae8ff",
      200: "#f5d0fe",
      300: "#f0abfc",
      400: "#e879f9",
      500: "#d946ef",
      600: "#c026d3",
      700: "#a21caf",
      800: "#86198f",
      900: "#701a75",
      950: "#4a044e"
    },
    pink: {
      50: "#fdf2f8",
      100: "#fce7f3",
      200: "#fbcfe8",
      300: "#f9a8d4",
      400: "#f472b6",
      500: "#ec4899",
      600: "#db2777",
      700: "#be185d",
      800: "#9d174d",
      900: "#831843",
      950: "#500724"
    },
    rose: {
      50: "#fff1f2",
      100: "#ffe4e6",
      200: "#fecdd3",
      300: "#fda4af",
      400: "#fb7185",
      500: "#f43f5e",
      600: "#e11d48",
      700: "#be123c",
      800: "#9f1239",
      900: "#881337",
      950: "#4c0519"
    },
    slate: {
      50: "#f8fafc",
      100: "#f1f5f9",
      200: "#e2e8f0",
      300: "#cbd5e1",
      400: "#94a3b8",
      500: "#64748b",
      600: "#475569",
      700: "#334155",
      800: "#1e293b",
      900: "#0f172a",
      950: "#020617"
    },
    gray: {
      50: "#f9fafb",
      100: "#f3f4f6",
      200: "#e5e7eb",
      300: "#d1d5db",
      400: "#9ca3af",
      500: "#6b7280",
      600: "#4b5563",
      700: "#374151",
      800: "#1f2937",
      900: "#111827",
      950: "#030712"
    },
    zinc: {
      50: "#fafafa",
      100: "#f4f4f5",
      200: "#e4e4e7",
      300: "#d4d4d8",
      400: "#a1a1aa",
      500: "#71717a",
      600: "#52525b",
      700: "#3f3f46",
      800: "#27272a",
      900: "#18181b",
      950: "#09090b"
    },
    neutral: {
      50: "#fafafa",
      100: "#f5f5f5",
      200: "#e5e5e5",
      300: "#d4d4d4",
      400: "#a3a3a3",
      500: "#737373",
      600: "#525252",
      700: "#404040",
      800: "#262626",
      900: "#171717",
      950: "#0a0a0a"
    },
    stone: {
      50: "#fafaf9",
      100: "#f5f5f4",
      200: "#e7e5e4",
      300: "#d6d3d1",
      400: "#a8a29e",
      500: "#78716c",
      600: "#57534e",
      700: "#44403c",
      800: "#292524",
      900: "#1c1917",
      950: "#0c0a09"
    }
  },
  semantic: {
    transitionDuration: "0.2s",
    focusRing: {
      width: "1px",
      style: "solid",
      color: "{primary.color}",
      offset: "2px",
      shadow: "none"
    },
    disabledOpacity: "0.6",
    iconSize: "1rem",
    anchorGutter: "2px",
    primary: {
      50: "{emerald.50}",
      100: "{emerald.100}",
      200: "{emerald.200}",
      300: "{emerald.300}",
      400: "{emerald.400}",
      500: "{emerald.500}",
      600: "{emerald.600}",
      700: "{emerald.700}",
      800: "{emerald.800}",
      900: "{emerald.900}",
      950: "{emerald.950}"
    },
    formField: {
      paddingX: "0.75rem",
      paddingY: "0.5rem",
      sm: {
        fontSize: "0.875rem",
        paddingX: "0.625rem",
        paddingY: "0.375rem"
      },
      lg: {
        fontSize: "1.125rem",
        paddingX: "0.875rem",
        paddingY: "0.625rem"
      },
      borderRadius: "{border.radius.md}",
      focusRing: {
        width: "0",
        style: "none",
        color: "transparent",
        offset: "0",
        shadow: "none"
      },
      transitionDuration: "{transition.duration}"
    },
    list: {
      padding: "0.25rem 0.25rem",
      gap: "2px",
      header: {
        padding: "0.5rem 1rem 0.25rem 1rem"
      },
      option: {
        padding: "0.5rem 0.75rem",
        borderRadius: "{border.radius.sm}"
      },
      optionGroup: {
        padding: "0.5rem 0.75rem",
        fontWeight: "600"
      }
    },
    content: {
      borderRadius: "{border.radius.md}"
    },
    mask: {
      transitionDuration: "0.15s"
    },
    navigation: {
      list: {
        padding: "0.25rem 0.25rem",
        gap: "2px"
      },
      item: {
        padding: "0.5rem 0.75rem",
        borderRadius: "{border.radius.sm}",
        gap: "0.5rem"
      },
      submenuLabel: {
        padding: "0.5rem 0.75rem",
        fontWeight: "600"
      },
      submenuIcon: {
        size: "0.875rem"
      }
    },
    overlay: {
      select: {
        borderRadius: "{border.radius.md}",
        shadow: "0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1)"
      },
      popover: {
        borderRadius: "{border.radius.md}",
        padding: "0.75rem",
        shadow: "0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1)"
      },
      modal: {
        borderRadius: "{border.radius.xl}",
        padding: "1.25rem",
        shadow: "0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 8px 10px -6px rgba(0, 0, 0, 0.1)"
      },
      navigation: {
        shadow: "0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1)"
      }
    },
    colorScheme: {
      light: {
        surface: {
          0: "#ffffff",
          50: "{slate.50}",
          100: "{slate.100}",
          200: "{slate.200}",
          300: "{slate.300}",
          400: "{slate.400}",
          500: "{slate.500}",
          600: "{slate.600}",
          700: "{slate.700}",
          800: "{slate.800}",
          900: "{slate.900}",
          950: "{slate.950}"
        },
        primary: {
          color: "{primary.500}",
          contrastColor: "#ffffff",
          hoverColor: "{primary.600}",
          activeColor: "{primary.700}"
        },
        highlight: {
          background: "{primary.50}",
          focusBackground: "{primary.100}",
          color: "{primary.700}",
          focusColor: "{primary.800}"
        },
        mask: {
          background: "rgba(0,0,0,0.4)",
          color: "{surface.200}"
        },
        formField: {
          background: "{surface.0}",
          disabledBackground: "{surface.200}",
          filledBackground: "{surface.50}",
          filledHoverBackground: "{surface.50}",
          filledFocusBackground: "{surface.50}",
          borderColor: "{surface.300}",
          hoverBorderColor: "{surface.400}",
          focusBorderColor: "{primary.color}",
          invalidBorderColor: "{red.400}",
          color: "{surface.700}",
          disabledColor: "{surface.500}",
          placeholderColor: "{surface.500}",
          invalidPlaceholderColor: "{red.600}",
          floatLabelColor: "{surface.500}",
          floatLabelFocusColor: "{primary.600}",
          floatLabelActiveColor: "{surface.500}",
          floatLabelInvalidColor: "{form.field.invalid.placeholder.color}",
          iconColor: "{surface.400}",
          shadow: "0 0 #0000, 0 0 #0000, 0 1px 2px 0 rgba(18, 18, 23, 0.05)"
        },
        text: {
          color: "{surface.700}",
          hoverColor: "{surface.800}",
          mutedColor: "{surface.500}",
          hoverMutedColor: "{surface.600}"
        },
        content: {
          background: "{surface.0}",
          hoverBackground: "{surface.100}",
          borderColor: "{surface.200}",
          color: "{text.color}",
          hoverColor: "{text.hover.color}"
        },
        overlay: {
          select: {
            background: "{surface.0}",
            borderColor: "{surface.200}",
            color: "{text.color}"
          },
          popover: {
            background: "{surface.0}",
            borderColor: "{surface.200}",
            color: "{text.color}"
          },
          modal: {
            background: "{surface.0}",
            borderColor: "{surface.200}",
            color: "{text.color}"
          }
        },
        list: {
          option: {
            focusBackground: "{surface.100}",
            selectedBackground: "{highlight.background}",
            selectedFocusBackground: "{highlight.focus.background}",
            color: "{text.color}",
            focusColor: "{text.hover.color}",
            selectedColor: "{highlight.color}",
            selectedFocusColor: "{highlight.focus.color}",
            icon: {
              color: "{surface.400}",
              focusColor: "{surface.500}"
            }
          },
          optionGroup: {
            background: "transparent",
            color: "{text.muted.color}"
          }
        },
        navigation: {
          item: {
            focusBackground: "{surface.100}",
            activeBackground: "{surface.100}",
            color: "{text.color}",
            focusColor: "{text.hover.color}",
            activeColor: "{text.hover.color}",
            icon: {
              color: "{surface.400}",
              focusColor: "{surface.500}",
              activeColor: "{surface.500}"
            }
          },
          submenuLabel: {
            background: "transparent",
            color: "{text.muted.color}"
          },
          submenuIcon: {
            color: "{surface.400}",
            focusColor: "{surface.500}",
            activeColor: "{surface.500}"
          }
        }
      },
      dark: {
        surface: {
          0: "#ffffff",
          50: "{zinc.50}",
          100: "{zinc.100}",
          200: "{zinc.200}",
          300: "{zinc.300}",
          400: "{zinc.400}",
          500: "{zinc.500}",
          600: "{zinc.600}",
          700: "{zinc.700}",
          800: "{zinc.800}",
          900: "{zinc.900}",
          950: "{zinc.950}"
        },
        primary: {
          color: "{primary.400}",
          contrastColor: "{surface.900}",
          hoverColor: "{primary.300}",
          activeColor: "{primary.200}"
        },
        highlight: {
          background: "color-mix(in srgb, {primary.400}, transparent 84%)",
          focusBackground: "color-mix(in srgb, {primary.400}, transparent 76%)",
          color: "rgba(255,255,255,.87)",
          focusColor: "rgba(255,255,255,.87)"
        },
        mask: {
          background: "rgba(0,0,0,0.6)",
          color: "{surface.200}"
        },
        formField: {
          background: "{surface.950}",
          disabledBackground: "{surface.700}",
          filledBackground: "{surface.800}",
          filledHoverBackground: "{surface.800}",
          filledFocusBackground: "{surface.800}",
          borderColor: "{surface.600}",
          hoverBorderColor: "{surface.500}",
          focusBorderColor: "{primary.color}",
          invalidBorderColor: "{red.300}",
          color: "{surface.0}",
          disabledColor: "{surface.400}",
          placeholderColor: "{surface.400}",
          invalidPlaceholderColor: "{red.400}",
          floatLabelColor: "{surface.400}",
          floatLabelFocusColor: "{primary.color}",
          floatLabelActiveColor: "{surface.400}",
          floatLabelInvalidColor: "{form.field.invalid.placeholder.color}",
          iconColor: "{surface.400}",
          shadow: "0 0 #0000, 0 0 #0000, 0 1px 2px 0 rgba(18, 18, 23, 0.05)"
        },
        text: {
          color: "{surface.0}",
          hoverColor: "{surface.0}",
          mutedColor: "{surface.400}",
          hoverMutedColor: "{surface.300}"
        },
        content: {
          background: "{surface.900}",
          hoverBackground: "{surface.800}",
          borderColor: "{surface.700}",
          color: "{text.color}",
          hoverColor: "{text.hover.color}"
        },
        overlay: {
          select: {
            background: "{surface.900}",
            borderColor: "{surface.700}",
            color: "{text.color}"
          },
          popover: {
            background: "{surface.900}",
            borderColor: "{surface.700}",
            color: "{text.color}"
          },
          modal: {
            background: "{surface.900}",
            borderColor: "{surface.700}",
            color: "{text.color}"
          }
        },
        list: {
          option: {
            focusBackground: "{surface.800}",
            selectedBackground: "{highlight.background}",
            selectedFocusBackground: "{highlight.focus.background}",
            color: "{text.color}",
            focusColor: "{text.hover.color}",
            selectedColor: "{highlight.color}",
            selectedFocusColor: "{highlight.focus.color}",
            icon: {
              color: "{surface.500}",
              focusColor: "{surface.400}"
            }
          },
          optionGroup: {
            background: "transparent",
            color: "{text.muted.color}"
          }
        },
        navigation: {
          item: {
            focusBackground: "{surface.800}",
            activeBackground: "{surface.800}",
            color: "{text.color}",
            focusColor: "{text.hover.color}",
            activeColor: "{text.hover.color}",
            icon: {
              color: "{surface.500}",
              focusColor: "{surface.400}",
              activeColor: "{surface.400}"
            }
          },
          submenuLabel: {
            background: "transparent",
            color: "{text.muted.color}"
          },
          submenuIcon: {
            color: "{surface.500}",
            focusColor: "{surface.400}",
            activeColor: "{surface.400}"
          }
        }
      }
    }
  }
};
var index$1m = {
  root: {
    borderRadius: "{content.border.radius}"
  }
};
var index$1l = {
  root: {
    padding: "1rem",
    background: "{content.background}",
    gap: "0.5rem",
    transitionDuration: "{transition.duration}"
  },
  item: {
    color: "{text.muted.color}",
    hoverColor: "{text.color}",
    borderRadius: "{content.border.radius}",
    gap: "{navigation.item.gap}",
    icon: {
      color: "{navigation.item.icon.color}",
      hoverColor: "{navigation.item.icon.focus.color}"
    },
    focusRing: {
      width: "{focus.ring.width}",
      style: "{focus.ring.style}",
      color: "{focus.ring.color}",
      offset: "{focus.ring.offset}",
      shadow: "{focus.ring.shadow}"
    }
  },
  separator: {
    color: "{navigation.item.icon.color}"
  }
};
var index$1k = {
  root: {
    borderRadius: "{form.field.border.radius}",
    roundedBorderRadius: "2rem",
    gap: "0.5rem",
    paddingX: "{form.field.padding.x}",
    paddingY: "{form.field.padding.y}",
    iconOnlyWidth: "2.5rem",
    sm: {
      fontSize: "{form.field.sm.font.size}",
      paddingX: "{form.field.sm.padding.x}",
      paddingY: "{form.field.sm.padding.y}"
    },
    lg: {
      fontSize: "{form.field.lg.font.size}",
      paddingX: "{form.field.lg.padding.x}",
      paddingY: "{form.field.lg.padding.y}"
    },
    label: {
      fontWeight: "500"
    },
    raisedShadow: "0 3px 1px -2px rgba(0, 0, 0, 0.2), 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 1px 5px 0 rgba(0, 0, 0, 0.12)",
    focusRing: {
      width: "{focus.ring.width}",
      style: "{focus.ring.style}",
      offset: "{focus.ring.offset}"
    },
    badgeSize: "1rem",
    transitionDuration: "{form.field.transition.duration}"
  },
  colorScheme: {
    light: {
      root: {
        primary: {
          background: "{primary.color}",
          hoverBackground: "{primary.hover.color}",
          activeBackground: "{primary.active.color}",
          borderColor: "{primary.color}",
          hoverBorderColor: "{primary.hover.color}",
          activeBorderColor: "{primary.active.color}",
          color: "{primary.contrast.color}",
          hoverColor: "{primary.contrast.color}",
          activeColor: "{primary.contrast.color}",
          focusRing: {
            color: "{primary.color}",
            shadow: "none"
          }
        },
        secondary: {
          background: "{surface.100}",
          hoverBackground: "{surface.200}",
          activeBackground: "{surface.300}",
          borderColor: "{surface.100}",
          hoverBorderColor: "{surface.200}",
          activeBorderColor: "{surface.300}",
          color: "{surface.600}",
          hoverColor: "{surface.700}",
          activeColor: "{surface.800}",
          focusRing: {
            color: "{surface.600}",
            shadow: "none"
          }
        },
        info: {
          background: "{sky.500}",
          hoverBackground: "{sky.600}",
          activeBackground: "{sky.700}",
          borderColor: "{sky.500}",
          hoverBorderColor: "{sky.600}",
          activeBorderColor: "{sky.700}",
          color: "#ffffff",
          hoverColor: "#ffffff",
          activeColor: "#ffffff",
          focusRing: {
            color: "{sky.500}",
            shadow: "none"
          }
        },
        success: {
          background: "{green.500}",
          hoverBackground: "{green.600}",
          activeBackground: "{green.700}",
          borderColor: "{green.500}",
          hoverBorderColor: "{green.600}",
          activeBorderColor: "{green.700}",
          color: "#ffffff",
          hoverColor: "#ffffff",
          activeColor: "#ffffff",
          focusRing: {
            color: "{green.500}",
            shadow: "none"
          }
        },
        warn: {
          background: "{orange.500}",
          hoverBackground: "{orange.600}",
          activeBackground: "{orange.700}",
          borderColor: "{orange.500}",
          hoverBorderColor: "{orange.600}",
          activeBorderColor: "{orange.700}",
          color: "#ffffff",
          hoverColor: "#ffffff",
          activeColor: "#ffffff",
          focusRing: {
            color: "{orange.500}",
            shadow: "none"
          }
        },
        help: {
          background: "{purple.500}",
          hoverBackground: "{purple.600}",
          activeBackground: "{purple.700}",
          borderColor: "{purple.500}",
          hoverBorderColor: "{purple.600}",
          activeBorderColor: "{purple.700}",
          color: "#ffffff",
          hoverColor: "#ffffff",
          activeColor: "#ffffff",
          focusRing: {
            color: "{purple.500}",
            shadow: "none"
          }
        },
        danger: {
          background: "{red.500}",
          hoverBackground: "{red.600}",
          activeBackground: "{red.700}",
          borderColor: "{red.500}",
          hoverBorderColor: "{red.600}",
          activeBorderColor: "{red.700}",
          color: "#ffffff",
          hoverColor: "#ffffff",
          activeColor: "#ffffff",
          focusRing: {
            color: "{red.500}",
            shadow: "none"
          }
        },
        contrast: {
          background: "{surface.950}",
          hoverBackground: "{surface.900}",
          activeBackground: "{surface.800}",
          borderColor: "{surface.950}",
          hoverBorderColor: "{surface.900}",
          activeBorderColor: "{surface.800}",
          color: "{surface.0}",
          hoverColor: "{surface.0}",
          activeColor: "{surface.0}",
          focusRing: {
            color: "{surface.950}",
            shadow: "none"
          }
        }
      },
      outlined: {
        primary: {
          hoverBackground: "{primary.50}",
          activeBackground: "{primary.100}",
          borderColor: "{primary.200}",
          color: "{primary.color}"
        },
        secondary: {
          hoverBackground: "{surface.50}",
          activeBackground: "{surface.100}",
          borderColor: "{surface.200}",
          color: "{surface.500}"
        },
        success: {
          hoverBackground: "{green.50}",
          activeBackground: "{green.100}",
          borderColor: "{green.200}",
          color: "{green.500}"
        },
        info: {
          hoverBackground: "{sky.50}",
          activeBackground: "{sky.100}",
          borderColor: "{sky.200}",
          color: "{sky.500}"
        },
        warn: {
          hoverBackground: "{orange.50}",
          activeBackground: "{orange.100}",
          borderColor: "{orange.200}",
          color: "{orange.500}"
        },
        help: {
          hoverBackground: "{purple.50}",
          activeBackground: "{purple.100}",
          borderColor: "{purple.200}",
          color: "{purple.500}"
        },
        danger: {
          hoverBackground: "{red.50}",
          activeBackground: "{red.100}",
          borderColor: "{red.200}",
          color: "{red.500}"
        },
        contrast: {
          hoverBackground: "{surface.50}",
          activeBackground: "{surface.100}",
          borderColor: "{surface.700}",
          color: "{surface.950}"
        },
        plain: {
          hoverBackground: "{surface.50}",
          activeBackground: "{surface.100}",
          borderColor: "{surface.200}",
          color: "{surface.700}"
        }
      },
      text: {
        primary: {
          hoverBackground: "{primary.50}",
          activeBackground: "{primary.100}",
          color: "{primary.color}"
        },
        secondary: {
          hoverBackground: "{surface.50}",
          activeBackground: "{surface.100}",
          color: "{surface.500}"
        },
        success: {
          hoverBackground: "{green.50}",
          activeBackground: "{green.100}",
          color: "{green.500}"
        },
        info: {
          hoverBackground: "{sky.50}",
          activeBackground: "{sky.100}",
          color: "{sky.500}"
        },
        warn: {
          hoverBackground: "{orange.50}",
          activeBackground: "{orange.100}",
          color: "{orange.500}"
        },
        help: {
          hoverBackground: "{purple.50}",
          activeBackground: "{purple.100}",
          color: "{purple.500}"
        },
        danger: {
          hoverBackground: "{red.50}",
          activeBackground: "{red.100}",
          color: "{red.500}"
        },
        contrast: {
          hoverBackground: "{surface.50}",
          activeBackground: "{surface.100}",
          color: "{surface.950}"
        },
        plain: {
          hoverBackground: "{surface.50}",
          activeBackground: "{surface.100}",
          color: "{surface.700}"
        }
      },
      link: {
        color: "{primary.color}",
        hoverColor: "{primary.color}",
        activeColor: "{primary.color}"
      }
    },
    dark: {
      root: {
        primary: {
          background: "{primary.color}",
          hoverBackground: "{primary.hover.color}",
          activeBackground: "{primary.active.color}",
          borderColor: "{primary.color}",
          hoverBorderColor: "{primary.hover.color}",
          activeBorderColor: "{primary.active.color}",
          color: "{primary.contrast.color}",
          hoverColor: "{primary.contrast.color}",
          activeColor: "{primary.contrast.color}",
          focusRing: {
            color: "{primary.color}",
            shadow: "none"
          }
        },
        secondary: {
          background: "{surface.800}",
          hoverBackground: "{surface.700}",
          activeBackground: "{surface.600}",
          borderColor: "{surface.800}",
          hoverBorderColor: "{surface.700}",
          activeBorderColor: "{surface.600}",
          color: "{surface.300}",
          hoverColor: "{surface.200}",
          activeColor: "{surface.100}",
          focusRing: {
            color: "{surface.300}",
            shadow: "none"
          }
        },
        info: {
          background: "{sky.400}",
          hoverBackground: "{sky.300}",
          activeBackground: "{sky.200}",
          borderColor: "{sky.400}",
          hoverBorderColor: "{sky.300}",
          activeBorderColor: "{sky.200}",
          color: "{sky.950}",
          hoverColor: "{sky.950}",
          activeColor: "{sky.950}",
          focusRing: {
            color: "{sky.400}",
            shadow: "none"
          }
        },
        success: {
          background: "{green.400}",
          hoverBackground: "{green.300}",
          activeBackground: "{green.200}",
          borderColor: "{green.400}",
          hoverBorderColor: "{green.300}",
          activeBorderColor: "{green.200}",
          color: "{green.950}",
          hoverColor: "{green.950}",
          activeColor: "{green.950}",
          focusRing: {
            color: "{green.400}",
            shadow: "none"
          }
        },
        warn: {
          background: "{orange.400}",
          hoverBackground: "{orange.300}",
          activeBackground: "{orange.200}",
          borderColor: "{orange.400}",
          hoverBorderColor: "{orange.300}",
          activeBorderColor: "{orange.200}",
          color: "{orange.950}",
          hoverColor: "{orange.950}",
          activeColor: "{orange.950}",
          focusRing: {
            color: "{orange.400}",
            shadow: "none"
          }
        },
        help: {
          background: "{purple.400}",
          hoverBackground: "{purple.300}",
          activeBackground: "{purple.200}",
          borderColor: "{purple.400}",
          hoverBorderColor: "{purple.300}",
          activeBorderColor: "{purple.200}",
          color: "{purple.950}",
          hoverColor: "{purple.950}",
          activeColor: "{purple.950}",
          focusRing: {
            color: "{purple.400}",
            shadow: "none"
          }
        },
        danger: {
          background: "{red.400}",
          hoverBackground: "{red.300}",
          activeBackground: "{red.200}",
          borderColor: "{red.400}",
          hoverBorderColor: "{red.300}",
          activeBorderColor: "{red.200}",
          color: "{red.950}",
          hoverColor: "{red.950}",
          activeColor: "{red.950}",
          focusRing: {
            color: "{red.400}",
            shadow: "none"
          }
        },
        contrast: {
          background: "{surface.0}",
          hoverBackground: "{surface.100}",
          activeBackground: "{surface.200}",
          borderColor: "{surface.0}",
          hoverBorderColor: "{surface.100}",
          activeBorderColor: "{surface.200}",
          color: "{surface.950}",
          hoverColor: "{surface.950}",
          activeColor: "{surface.950}",
          focusRing: {
            color: "{surface.0}",
            shadow: "none"
          }
        }
      },
      outlined: {
        primary: {
          hoverBackground: "color-mix(in srgb, {primary.color}, transparent 96%)",
          activeBackground: "color-mix(in srgb, {primary.color}, transparent 84%)",
          borderColor: "{primary.700}",
          color: "{primary.color}"
        },
        secondary: {
          hoverBackground: "rgba(255,255,255,0.04)",
          activeBackground: "rgba(255,255,255,0.16)",
          borderColor: "{surface.700}",
          color: "{surface.400}"
        },
        success: {
          hoverBackground: "color-mix(in srgb, {green.400}, transparent 96%)",
          activeBackground: "color-mix(in srgb, {green.400}, transparent 84%)",
          borderColor: "{green.700}",
          color: "{green.400}"
        },
        info: {
          hoverBackground: "color-mix(in srgb, {sky.400}, transparent 96%)",
          activeBackground: "color-mix(in srgb, {sky.400}, transparent 84%)",
          borderColor: "{sky.700}",
          color: "{sky.400}"
        },
        warn: {
          hoverBackground: "color-mix(in srgb, {orange.400}, transparent 96%)",
          activeBackground: "color-mix(in srgb, {orange.400}, transparent 84%)",
          borderColor: "{orange.700}",
          color: "{orange.400}"
        },
        help: {
          hoverBackground: "color-mix(in srgb, {purple.400}, transparent 96%)",
          activeBackground: "color-mix(in srgb, {purple.400}, transparent 84%)",
          borderColor: "{purple.700}",
          color: "{purple.400}"
        },
        danger: {
          hoverBackground: "color-mix(in srgb, {red.400}, transparent 96%)",
          activeBackground: "color-mix(in srgb, {red.400}, transparent 84%)",
          borderColor: "{red.700}",
          color: "{red.400}"
        },
        contrast: {
          hoverBackground: "{surface.800}",
          activeBackground: "{surface.700}",
          borderColor: "{surface.500}",
          color: "{surface.0}"
        },
        plain: {
          hoverBackground: "{surface.800}",
          activeBackground: "{surface.700}",
          borderColor: "{surface.600}",
          color: "{surface.0}"
        }
      },
      text: {
        primary: {
          hoverBackground: "color-mix(in srgb, {primary.color}, transparent 96%)",
          activeBackground: "color-mix(in srgb, {primary.color}, transparent 84%)",
          color: "{primary.color}"
        },
        secondary: {
          hoverBackground: "{surface.800}",
          activeBackground: "{surface.700}",
          color: "{surface.400}"
        },
        success: {
          hoverBackground: "color-mix(in srgb, {green.400}, transparent 96%)",
          activeBackground: "color-mix(in srgb, {green.400}, transparent 84%)",
          color: "{green.400}"
        },
        info: {
          hoverBackground: "color-mix(in srgb, {sky.400}, transparent 96%)",
          activeBackground: "color-mix(in srgb, {sky.400}, transparent 84%)",
          color: "{sky.400}"
        },
        warn: {
          hoverBackground: "color-mix(in srgb, {orange.400}, transparent 96%)",
          activeBackground: "color-mix(in srgb, {orange.400}, transparent 84%)",
          color: "{orange.400}"
        },
        help: {
          hoverBackground: "color-mix(in srgb, {purple.400}, transparent 96%)",
          activeBackground: "color-mix(in srgb, {purple.400}, transparent 84%)",
          color: "{purple.400}"
        },
        danger: {
          hoverBackground: "color-mix(in srgb, {red.400}, transparent 96%)",
          activeBackground: "color-mix(in srgb, {red.400}, transparent 84%)",
          color: "{red.400}"
        },
        contrast: {
          hoverBackground: "{surface.800}",
          activeBackground: "{surface.700}",
          color: "{surface.0}"
        },
        plain: {
          hoverBackground: "{surface.800}",
          activeBackground: "{surface.700}",
          color: "{surface.0}"
        }
      },
      link: {
        color: "{primary.color}",
        hoverColor: "{primary.color}",
        activeColor: "{primary.color}"
      }
    }
  }
};
var index$1j = {
  root: {
    background: "{content.background}",
    borderRadius: "{border.radius.xl}",
    color: "{content.color}",
    shadow: "0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px -1px rgba(0, 0, 0, 0.1)"
  },
  body: {
    padding: "1.25rem",
    gap: "0.5rem"
  },
  caption: {
    gap: "0.5rem"
  },
  title: {
    fontSize: "1.25rem",
    fontWeight: "500"
  },
  subtitle: {
    color: "{text.muted.color}"
  }
};
var index$1i = {
  root: {
    transitionDuration: "{transition.duration}"
  },
  content: {
    gap: "0.25rem"
  },
  indicatorList: {
    padding: "1rem",
    gap: "0.5rem"
  },
  indicator: {
    width: "2rem",
    height: "0.5rem",
    borderRadius: "{content.border.radius}",
    focusRing: {
      width: "{focus.ring.width}",
      style: "{focus.ring.style}",
      color: "{focus.ring.color}",
      offset: "{focus.ring.offset}",
      shadow: "{focus.ring.shadow}"
    }
  },
  colorScheme: {
    light: {
      indicator: {
        background: "{surface.200}",
        hoverBackground: "{surface.300}",
        activeBackground: "{primary.color}"
      }
    },
    dark: {
      indicator: {
        background: "{surface.700}",
        hoverBackground: "{surface.600}",
        activeBackground: "{primary.color}"
      }
    }
  }
};
var index$1h = {
  root: {
    background: "{form.field.background}",
    disabledBackground: "{form.field.disabled.background}",
    filledBackground: "{form.field.filled.background}",
    filledHoverBackground: "{form.field.filled.hover.background}",
    filledFocusBackground: "{form.field.filled.focus.background}",
    borderColor: "{form.field.border.color}",
    hoverBorderColor: "{form.field.hover.border.color}",
    focusBorderColor: "{form.field.focus.border.color}",
    invalidBorderColor: "{form.field.invalid.border.color}",
    color: "{form.field.color}",
    disabledColor: "{form.field.disabled.color}",
    placeholderColor: "{form.field.placeholder.color}",
    invalidPlaceholderColor: "{form.field.invalid.placeholder.color}",
    shadow: "{form.field.shadow}",
    paddingX: "{form.field.padding.x}",
    paddingY: "{form.field.padding.y}",
    borderRadius: "{form.field.border.radius}",
    focusRing: {
      width: "{form.field.focus.ring.width}",
      style: "{form.field.focus.ring.style}",
      color: "{form.field.focus.ring.color}",
      offset: "{form.field.focus.ring.offset}",
      shadow: "{form.field.focus.ring.shadow}"
    },
    transitionDuration: "{form.field.transition.duration}",
    sm: {
      fontSize: "{form.field.sm.font.size}",
      paddingX: "{form.field.sm.padding.x}",
      paddingY: "{form.field.sm.padding.y}"
    },
    lg: {
      fontSize: "{form.field.lg.font.size}",
      paddingX: "{form.field.lg.padding.x}",
      paddingY: "{form.field.lg.padding.y}"
    }
  },
  dropdown: {
    width: "2.5rem",
    color: "{form.field.icon.color}"
  },
  overlay: {
    background: "{overlay.select.background}",
    borderColor: "{overlay.select.border.color}",
    borderRadius: "{overlay.select.border.radius}",
    color: "{overlay.select.color}",
    shadow: "{overlay.select.shadow}"
  },
  list: {
    padding: "{list.padding}",
    gap: "{list.gap}",
    mobileIndent: "1rem"
  },
  option: {
    focusBackground: "{list.option.focus.background}",
    selectedBackground: "{list.option.selected.background}",
    selectedFocusBackground: "{list.option.selected.focus.background}",
    color: "{list.option.color}",
    focusColor: "{list.option.focus.color}",
    selectedColor: "{list.option.selected.color}",
    selectedFocusColor: "{list.option.selected.focus.color}",
    padding: "{list.option.padding}",
    borderRadius: "{list.option.border.radius}",
    icon: {
      color: "{list.option.icon.color}",
      focusColor: "{list.option.icon.focus.color}",
      size: "0.875rem"
    }
  },
  clearIcon: {
    color: "{form.field.icon.color}"
  }
};
var index$1g = {
  root: {
    borderRadius: "{border.radius.sm}",
    width: "1.25rem",
    height: "1.25rem",
    background: "{form.field.background}",
    checkedBackground: "{primary.color}",
    checkedHoverBackground: "{primary.hover.color}",
    disabledBackground: "{form.field.disabled.background}",
    filledBackground: "{form.field.filled.background}",
    borderColor: "{form.field.border.color}",
    hoverBorderColor: "{form.field.hover.border.color}",
    focusBorderColor: "{form.field.border.color}",
    checkedBorderColor: "{primary.color}",
    checkedHoverBorderColor: "{primary.hover.color}",
    checkedFocusBorderColor: "{primary.color}",
    checkedDisabledBorderColor: "{form.field.border.color}",
    invalidBorderColor: "{form.field.invalid.border.color}",
    shadow: "{form.field.shadow}",
    focusRing: {
      width: "{focus.ring.width}",
      style: "{focus.ring.style}",
      color: "{focus.ring.color}",
      offset: "{focus.ring.offset}",
      shadow: "{focus.ring.shadow}"
    },
    transitionDuration: "{form.field.transition.duration}",
    sm: {
      width: "1rem",
      height: "1rem"
    },
    lg: {
      width: "1.5rem",
      height: "1.5rem"
    }
  },
  icon: {
    size: "0.875rem",
    color: "{form.field.color}",
    checkedColor: "{primary.contrast.color}",
    checkedHoverColor: "{primary.contrast.color}",
    disabledColor: "{form.field.disabled.color}",
    sm: {
      size: "0.75rem"
    },
    lg: {
      size: "1rem"
    }
  }
};
var index$1f = {
  root: {
    borderRadius: "16px",
    paddingX: "0.75rem",
    paddingY: "0.5rem",
    gap: "0.5rem",
    transitionDuration: "{transition.duration}"
  },
  image: {
    width: "2rem",
    height: "2rem"
  },
  icon: {
    size: "1rem"
  },
  removeIcon: {
    size: "1rem",
    focusRing: {
      width: "{focus.ring.width}",
      style: "{focus.ring.style}",
      color: "{focus.ring.color}",
      offset: "{focus.ring.offset}",
      shadow: "{form.field.focus.ring.shadow}"
    }
  },
  colorScheme: {
    light: {
      root: {
        background: "{surface.100}",
        color: "{surface.800}"
      },
      icon: {
        color: "{surface.800}"
      },
      removeIcon: {
        color: "{surface.800}"
      }
    },
    dark: {
      root: {
        background: "{surface.800}",
        color: "{surface.0}"
      },
      icon: {
        color: "{surface.0}"
      },
      removeIcon: {
        color: "{surface.0}"
      }
    }
  }
};
var index$1e = {
  root: {
    transitionDuration: "{transition.duration}"
  },
  preview: {
    width: "1.5rem",
    height: "1.5rem",
    borderRadius: "{form.field.border.radius}",
    focusRing: {
      width: "{focus.ring.width}",
      style: "{focus.ring.style}",
      color: "{focus.ring.color}",
      offset: "{focus.ring.offset}",
      shadow: "{focus.ring.shadow}"
    }
  },
  panel: {
    shadow: "{overlay.popover.shadow}",
    borderRadius: "{overlay.popover.borderRadius}"
  },
  colorScheme: {
    light: {
      panel: {
        background: "{surface.800}",
        borderColor: "{surface.900}"
      },
      handle: {
        color: "{surface.0}"
      }
    },
    dark: {
      panel: {
        background: "{surface.900}",
        borderColor: "{surface.700}"
      },
      handle: {
        color: "{surface.0}"
      }
    }
  }
};
var index$1d = {
  icon: {
    size: "2rem",
    color: "{overlay.modal.color}"
  },
  content: {
    gap: "1rem"
  }
};
var index$1c = {
  root: {
    background: "{overlay.popover.background}",
    borderColor: "{overlay.popover.border.color}",
    color: "{overlay.popover.color}",
    borderRadius: "{overlay.popover.border.radius}",
    shadow: "{overlay.popover.shadow}",
    gutter: "10px",
    arrowOffset: "1.25rem"
  },
  content: {
    padding: "{overlay.popover.padding}",
    gap: "1rem"
  },
  icon: {
    size: "1.5rem",
    color: "{overlay.popover.color}"
  },
  footer: {
    gap: "0.5rem",
    padding: "0 {overlay.popover.padding} {overlay.popover.padding} {overlay.popover.padding}"
  }
};
var index$1b = {
  root: {
    background: "{content.background}",
    borderColor: "{content.border.color}",
    color: "{content.color}",
    borderRadius: "{content.border.radius}",
    shadow: "{overlay.navigation.shadow}",
    transitionDuration: "{transition.duration}"
  },
  list: {
    padding: "{navigation.list.padding}",
    gap: "{navigation.list.gap}"
  },
  item: {
    focusBackground: "{navigation.item.focus.background}",
    activeBackground: "{navigation.item.active.background}",
    color: "{navigation.item.color}",
    focusColor: "{navigation.item.focus.color}",
    activeColor: "{navigation.item.active.color}",
    padding: "{navigation.item.padding}",
    borderRadius: "{navigation.item.border.radius}",
    gap: "{navigation.item.gap}",
    icon: {
      color: "{navigation.item.icon.color}",
      focusColor: "{navigation.item.icon.focus.color}",
      activeColor: "{navigation.item.icon.active.color}"
    }
  },
  submenu: {
    mobileIndent: "1rem"
  },
  submenuIcon: {
    size: "{navigation.submenu.icon.size}",
    color: "{navigation.submenu.icon.color}",
    focusColor: "{navigation.submenu.icon.focus.color}",
    activeColor: "{navigation.submenu.icon.active.color}"
  },
  separator: {
    borderColor: "{content.border.color}"
  }
};
var index$1a = {
  root: {
    transitionDuration: "{transition.duration}"
  },
  header: {
    background: "{content.background}",
    borderColor: "{datatable.border.color}",
    color: "{content.color}",
    borderWidth: "0 0 1px 0",
    padding: "0.75rem 1rem"
  },
  headerCell: {
    background: "{content.background}",
    hoverBackground: "{content.hover.background}",
    selectedBackground: "{highlight.background}",
    borderColor: "{datatable.border.color}",
    color: "{content.color}",
    hoverColor: "{content.hover.color}",
    selectedColor: "{highlight.color}",
    gap: "0.5rem",
    padding: "0.75rem 1rem",
    focusRing: {
      width: "{focus.ring.width}",
      style: "{focus.ring.style}",
      color: "{focus.ring.color}",
      offset: "-1px",
      shadow: "{focus.ring.shadow}"
    }
  },
  columnTitle: {
    fontWeight: "600"
  },
  row: {
    background: "{content.background}",
    hoverBackground: "{content.hover.background}",
    selectedBackground: "{highlight.background}",
    color: "{content.color}",
    hoverColor: "{content.hover.color}",
    selectedColor: "{highlight.color}",
    focusRing: {
      width: "{focus.ring.width}",
      style: "{focus.ring.style}",
      color: "{focus.ring.color}",
      offset: "-1px",
      shadow: "{focus.ring.shadow}"
    }
  },
  bodyCell: {
    borderColor: "{datatable.border.color}",
    padding: "0.75rem 1rem"
  },
  footerCell: {
    background: "{content.background}",
    borderColor: "{datatable.border.color}",
    color: "{content.color}",
    padding: "0.75rem 1rem"
  },
  columnFooter: {
    fontWeight: "600"
  },
  footer: {
    background: "{content.background}",
    borderColor: "{datatable.border.color}",
    color: "{content.color}",
    borderWidth: "0 0 1px 0",
    padding: "0.75rem 1rem"
  },
  dropPoint: {
    color: "{primary.color}"
  },
  columnResizerWidth: "0.5rem",
  resizeIndicator: {
    width: "1px",
    color: "{primary.color}"
  },
  sortIcon: {
    color: "{text.muted.color}",
    hoverColor: "{text.hover.muted.color}",
    size: "0.875rem"
  },
  loadingIcon: {
    size: "2rem"
  },
  rowToggleButton: {
    hoverBackground: "{content.hover.background}",
    selectedHoverBackground: "{content.background}",
    color: "{text.muted.color}",
    hoverColor: "{text.color}",
    selectedHoverColor: "{primary.color}",
    size: "1.75rem",
    borderRadius: "50%",
    focusRing: {
      width: "{focus.ring.width}",
      style: "{focus.ring.style}",
      color: "{focus.ring.color}",
      offset: "{focus.ring.offset}",
      shadow: "{focus.ring.shadow}"
    }
  },
  filter: {
    inlineGap: "0.5rem",
    overlaySelect: {
      background: "{overlay.select.background}",
      borderColor: "{overlay.select.border.color}",
      borderRadius: "{overlay.select.border.radius}",
      color: "{overlay.select.color}",
      shadow: "{overlay.select.shadow}"
    },
    overlayPopover: {
      background: "{overlay.popover.background}",
      borderColor: "{overlay.popover.border.color}",
      borderRadius: "{overlay.popover.border.radius}",
      color: "{overlay.popover.color}",
      shadow: "{overlay.popover.shadow}",
      padding: "{overlay.popover.padding}",
      gap: "0.5rem"
    },
    rule: {
      borderColor: "{content.border.color}"
    },
    constraintList: {
      padding: "{list.padding}",
      gap: "{list.gap}"
    },
    constraint: {
      focusBackground: "{list.option.focus.background}",
      selectedBackground: "{list.option.selected.background}",
      selectedFocusBackground: "{list.option.selected.focus.background}",
      color: "{list.option.color}",
      focusColor: "{list.option.focus.color}",
      selectedColor: "{list.option.selected.color}",
      selectedFocusColor: "{list.option.selected.focus.color}",
      separator: {
        borderColor: "{content.border.color}"
      },
      padding: "{list.option.padding}",
      borderRadius: "{list.option.border.radius}"
    }
  },
  paginatorTop: {
    borderColor: "{datatable.border.color}",
    borderWidth: "0 0 1px 0"
  },
  paginatorBottom: {
    borderColor: "{datatable.border.color}",
    borderWidth: "0 0 1px 0"
  },
  colorScheme: {
    light: {
      root: {
        borderColor: "{content.border.color}"
      },
      row: {
        stripedBackground: "{surface.50}"
      },
      bodyCell: {
        selectedBorderColor: "{primary.100}"
      }
    },
    dark: {
      root: {
        borderColor: "{surface.800}"
      },
      row: {
        stripedBackground: "{surface.950}"
      },
      bodyCell: {
        selectedBorderColor: "{primary.900}"
      }
    }
  }
};
var index$19 = {
  root: {
    borderColor: "transparent",
    borderWidth: "0",
    borderRadius: "0",
    padding: "0"
  },
  header: {
    background: "{content.background}",
    color: "{content.color}",
    borderColor: "{content.border.color}",
    borderWidth: "0 0 1px 0",
    padding: "0.75rem 1rem",
    borderRadius: "0"
  },
  content: {
    background: "{content.background}",
    color: "{content.color}",
    borderColor: "transparent",
    borderWidth: "0",
    padding: "0",
    borderRadius: "0"
  },
  footer: {
    background: "{content.background}",
    color: "{content.color}",
    borderColor: "{content.border.color}",
    borderWidth: "1px 0 0 0",
    padding: "0.75rem 1rem",
    borderRadius: "0"
  },
  paginatorTop: {
    borderColor: "{content.border.color}",
    borderWidth: "0 0 1px 0"
  },
  paginatorBottom: {
    borderColor: "{content.border.color}",
    borderWidth: "1px 0 0 0"
  }
};
var index$18 = {
  root: {
    transitionDuration: "{transition.duration}"
  },
  panel: {
    background: "{content.background}",
    borderColor: "{content.border.color}",
    color: "{content.color}",
    borderRadius: "{content.border.radius}",
    shadow: "{overlay.popover.shadow}",
    padding: "{overlay.popover.padding}"
  },
  header: {
    background: "{content.background}",
    borderColor: "{content.border.color}",
    color: "{content.color}",
    padding: "0 0 0.5rem 0"
  },
  title: {
    gap: "0.5rem",
    fontWeight: "500"
  },
  dropdown: {
    width: "2.5rem",
    sm: {
      width: "2rem"
    },
    lg: {
      width: "3rem"
    },
    borderColor: "{form.field.border.color}",
    hoverBorderColor: "{form.field.border.color}",
    activeBorderColor: "{form.field.border.color}",
    borderRadius: "{form.field.border.radius}",
    focusRing: {
      width: "{focus.ring.width}",
      style: "{focus.ring.style}",
      color: "{focus.ring.color}",
      offset: "{focus.ring.offset}",
      shadow: "{focus.ring.shadow}"
    }
  },
  inputIcon: {
    color: "{form.field.icon.color}"
  },
  selectMonth: {
    hoverBackground: "{content.hover.background}",
    color: "{content.color}",
    hoverColor: "{content.hover.color}",
    padding: "0.25rem 0.5rem",
    borderRadius: "{content.border.radius}"
  },
  selectYear: {
    hoverBackground: "{content.hover.background}",
    color: "{content.color}",
    hoverColor: "{content.hover.color}",
    padding: "0.25rem 0.5rem",
    borderRadius: "{content.border.radius}"
  },
  group: {
    borderColor: "{content.border.color}",
    gap: "{overlay.popover.padding}"
  },
  dayView: {
    margin: "0.5rem 0 0 0"
  },
  weekDay: {
    padding: "0.25rem",
    fontWeight: "500",
    color: "{content.color}"
  },
  date: {
    hoverBackground: "{content.hover.background}",
    selectedBackground: "{primary.color}",
    rangeSelectedBackground: "{highlight.background}",
    color: "{content.color}",
    hoverColor: "{content.hover.color}",
    selectedColor: "{primary.contrast.color}",
    rangeSelectedColor: "{highlight.color}",
    width: "2rem",
    height: "2rem",
    borderRadius: "50%",
    padding: "0.25rem",
    focusRing: {
      width: "{focus.ring.width}",
      style: "{focus.ring.style}",
      color: "{focus.ring.color}",
      offset: "{focus.ring.offset}",
      shadow: "{focus.ring.shadow}"
    }
  },
  monthView: {
    margin: "0.5rem 0 0 0"
  },
  month: {
    padding: "0.375rem",
    borderRadius: "{content.border.radius}"
  },
  yearView: {
    margin: "0.5rem 0 0 0"
  },
  year: {
    padding: "0.375rem",
    borderRadius: "{content.border.radius}"
  },
  buttonbar: {
    padding: "0.5rem 0 0 0",
    borderColor: "{content.border.color}"
  },
  timePicker: {
    padding: "0.5rem 0 0 0",
    borderColor: "{content.border.color}",
    gap: "0.5rem",
    buttonGap: "0.25rem"
  },
  colorScheme: {
    light: {
      dropdown: {
        background: "{surface.100}",
        hoverBackground: "{surface.200}",
        activeBackground: "{surface.300}",
        color: "{surface.600}",
        hoverColor: "{surface.700}",
        activeColor: "{surface.800}"
      },
      today: {
        background: "{surface.200}",
        color: "{surface.900}"
      }
    },
    dark: {
      dropdown: {
        background: "{surface.800}",
        hoverBackground: "{surface.700}",
        activeBackground: "{surface.600}",
        color: "{surface.300}",
        hoverColor: "{surface.200}",
        activeColor: "{surface.100}"
      },
      today: {
        background: "{surface.700}",
        color: "{surface.0}"
      }
    }
  }
};
var index$17 = {
  root: {
    background: "{overlay.modal.background}",
    borderColor: "{overlay.modal.border.color}",
    color: "{overlay.modal.color}",
    borderRadius: "{overlay.modal.border.radius}",
    shadow: "{overlay.modal.shadow}"
  },
  header: {
    padding: "{overlay.modal.padding}",
    gap: "0.5rem"
  },
  title: {
    fontSize: "1.25rem",
    fontWeight: "600"
  },
  content: {
    padding: "0 {overlay.modal.padding} {overlay.modal.padding} {overlay.modal.padding}"
  },
  footer: {
    padding: "0 {overlay.modal.padding} {overlay.modal.padding} {overlay.modal.padding}",
    gap: "0.5rem"
  }
};
var index$16 = {
  root: {
    borderColor: "{content.border.color}"
  },
  content: {
    background: "{content.background}",
    color: "{text.color}"
  },
  horizontal: {
    margin: "1rem 0",
    padding: "0 1rem",
    content: {
      padding: "0 0.5rem"
    }
  },
  vertical: {
    margin: "0 1rem",
    padding: "0.5rem 0",
    content: {
      padding: "0.5rem 0"
    }
  }
};
var index$15 = {
  root: {
    background: "rgba(255, 255, 255, 0.1)",
    borderColor: "rgba(255, 255, 255, 0.2)",
    padding: "0.5rem",
    borderRadius: "{border.radius.xl}"
  },
  item: {
    borderRadius: "{content.border.radius}",
    padding: "0.5rem",
    size: "3rem",
    focusRing: {
      width: "{focus.ring.width}",
      style: "{focus.ring.style}",
      color: "{focus.ring.color}",
      offset: "{focus.ring.offset}",
      shadow: "{focus.ring.shadow}"
    }
  }
};
var index$14 = {
  root: {
    background: "{overlay.modal.background}",
    borderColor: "{overlay.modal.border.color}",
    color: "{overlay.modal.color}",
    shadow: "{overlay.modal.shadow}"
  },
  header: {
    padding: "{overlay.modal.padding}"
  },
  title: {
    fontSize: "1.5rem",
    fontWeight: "600"
  },
  content: {
    padding: "0 {overlay.modal.padding} {overlay.modal.padding} {overlay.modal.padding}"
  },
  footer: {
    padding: "{overlay.modal.padding}"
  }
};
var index$13 = {
  toolbar: {
    background: "{content.background}",
    borderColor: "{content.border.color}",
    borderRadius: "{content.border.radius}"
  },
  toolbarItem: {
    color: "{text.muted.color}",
    hoverColor: "{text.color}",
    activeColor: "{primary.color}"
  },
  overlay: {
    background: "{overlay.select.background}",
    borderColor: "{overlay.select.border.color}",
    borderRadius: "{overlay.select.border.radius}",
    color: "{overlay.select.color}",
    shadow: "{overlay.select.shadow}",
    padding: "{list.padding}"
  },
  overlayOption: {
    focusBackground: "{list.option.focus.background}",
    color: "{list.option.color}",
    focusColor: "{list.option.focus.color}",
    padding: "{list.option.padding}",
    borderRadius: "{list.option.border.radius}"
  },
  content: {
    background: "{content.background}",
    borderColor: "{content.border.color}",
    color: "{content.color}",
    borderRadius: "{content.border.radius}"
  }
};
var index$12 = {
  root: {
    background: "{content.background}",
    borderColor: "{content.border.color}",
    borderRadius: "{content.border.radius}",
    color: "{content.color}",
    padding: "0 1.125rem 1.125rem 1.125rem",
    transitionDuration: "{transition.duration}"
  },
  legend: {
    background: "{content.background}",
    hoverBackground: "{content.hover.background}",
    color: "{content.color}",
    hoverColor: "{content.hover.color}",
    borderRadius: "{content.border.radius}",
    borderWidth: "1px",
    borderColor: "transparent",
    padding: "0.5rem 0.75rem",
    gap: "0.5rem",
    fontWeight: "600",
    focusRing: {
      width: "{focus.ring.width}",
      style: "{focus.ring.style}",
      color: "{focus.ring.color}",
      offset: "{focus.ring.offset}",
      shadow: "{focus.ring.shadow}"
    }
  },
  toggleIcon: {
    color: "{text.muted.color}",
    hoverColor: "{text.hover.muted.color}"
  },
  content: {
    padding: "0"
  }
};
var index$11 = {
  root: {
    background: "{content.background}",
    borderColor: "{content.border.color}",
    color: "{content.color}",
    borderRadius: "{content.border.radius}",
    transitionDuration: "{transition.duration}"
  },
  header: {
    background: "transparent",
    color: "{text.color}",
    padding: "1.125rem",
    borderColor: "unset",
    borderWidth: "0",
    borderRadius: "0",
    gap: "0.5rem"
  },
  content: {
    highlightBorderColor: "{primary.color}",
    padding: "0 1.125rem 1.125rem 1.125rem",
    gap: "1rem"
  },
  file: {
    padding: "1rem",
    gap: "1rem",
    borderColor: "{content.border.color}",
    info: {
      gap: "0.5rem"
    }
  },
  fileList: {
    gap: "0.5rem"
  },
  progressbar: {
    height: "0.25rem"
  },
  basic: {
    gap: "0.5rem"
  }
};
var index$10 = {
  root: {
    color: "{form.field.float.label.color}",
    focusColor: "{form.field.float.label.focus.color}",
    activeColor: "{form.field.float.label.active.color}",
    invalidColor: "{form.field.float.label.invalid.color}",
    transitionDuration: "0.2s",
    positionX: "{form.field.padding.x}",
    positionY: "{form.field.padding.y}",
    fontWeight: "500",
    active: {
      fontSize: "0.75rem",
      fontWeight: "400"
    }
  },
  over: {
    active: {
      top: "-1.25rem"
    }
  },
  "in": {
    input: {
      paddingTop: "1.5rem",
      paddingBottom: "{form.field.padding.y}"
    },
    active: {
      top: "{form.field.padding.y}"
    }
  },
  on: {
    borderRadius: "{border.radius.xs}",
    active: {
      background: "{form.field.background}",
      padding: "0 0.125rem"
    }
  }
};
var index$$ = {
  root: {
    borderWidth: "1px",
    borderColor: "{content.border.color}",
    borderRadius: "{content.border.radius}",
    transitionDuration: "{transition.duration}"
  },
  navButton: {
    background: "rgba(255, 255, 255, 0.1)",
    hoverBackground: "rgba(255, 255, 255, 0.2)",
    color: "{surface.100}",
    hoverColor: "{surface.0}",
    size: "3rem",
    gutter: "0.5rem",
    prev: {
      borderRadius: "50%"
    },
    next: {
      borderRadius: "50%"
    },
    focusRing: {
      width: "{focus.ring.width}",
      style: "{focus.ring.style}",
      color: "{focus.ring.color}",
      offset: "{focus.ring.offset}",
      shadow: "{focus.ring.shadow}"
    }
  },
  navIcon: {
    size: "1.5rem"
  },
  thumbnailsContent: {
    background: "{content.background}",
    padding: "1rem 0.25rem"
  },
  thumbnailNavButton: {
    size: "2rem",
    borderRadius: "{content.border.radius}",
    gutter: "0.5rem",
    focusRing: {
      width: "{focus.ring.width}",
      style: "{focus.ring.style}",
      color: "{focus.ring.color}",
      offset: "{focus.ring.offset}",
      shadow: "{focus.ring.shadow}"
    }
  },
  thumbnailNavButtonIcon: {
    size: "1rem"
  },
  caption: {
    background: "rgba(0, 0, 0, 0.5)",
    color: "{surface.100}",
    padding: "1rem"
  },
  indicatorList: {
    gap: "0.5rem",
    padding: "1rem"
  },
  indicatorButton: {
    width: "1rem",
    height: "1rem",
    activeBackground: "{primary.color}",
    borderRadius: "50%",
    focusRing: {
      width: "{focus.ring.width}",
      style: "{focus.ring.style}",
      color: "{focus.ring.color}",
      offset: "{focus.ring.offset}",
      shadow: "{focus.ring.shadow}"
    }
  },
  insetIndicatorList: {
    background: "rgba(0, 0, 0, 0.5)"
  },
  insetIndicatorButton: {
    background: "rgba(255, 255, 255, 0.4)",
    hoverBackground: "rgba(255, 255, 255, 0.6)",
    activeBackground: "rgba(255, 255, 255, 0.9)"
  },
  closeButton: {
    size: "3rem",
    gutter: "0.5rem",
    background: "rgba(255, 255, 255, 0.1)",
    hoverBackground: "rgba(255, 255, 255, 0.2)",
    color: "{surface.50}",
    hoverColor: "{surface.0}",
    borderRadius: "50%",
    focusRing: {
      width: "{focus.ring.width}",
      style: "{focus.ring.style}",
      color: "{focus.ring.color}",
      offset: "{focus.ring.offset}",
      shadow: "{focus.ring.shadow}"
    }
  },
  closeButtonIcon: {
    size: "1.5rem"
  },
  colorScheme: {
    light: {
      thumbnailNavButton: {
        hoverBackground: "{surface.100}",
        color: "{surface.600}",
        hoverColor: "{surface.700}"
      },
      indicatorButton: {
        background: "{surface.200}",
        hoverBackground: "{surface.300}"
      }
    },
    dark: {
      thumbnailNavButton: {
        hoverBackground: "{surface.700}",
        color: "{surface.400}",
        hoverColor: "{surface.0}"
      },
      indicatorButton: {
        background: "{surface.700}",
        hoverBackground: "{surface.600}"
      }
    }
  }
};
var index$_ = {
  icon: {
    color: "{form.field.icon.color}"
  }
};
var index$Z = {
  root: {
    color: "{form.field.float.label.color}",
    focusColor: "{form.field.float.label.focus.color}",
    invalidColor: "{form.field.float.label.invalid.color}",
    transitionDuration: "0.2s",
    positionX: "{form.field.padding.x}",
    top: "{form.field.padding.y}",
    fontSize: "0.75rem",
    fontWeight: "400"
  },
  input: {
    paddingTop: "1.5rem",
    paddingBottom: "{form.field.padding.y}"
  }
};
var index$Y = {
  root: {
    transitionDuration: "{transition.duration}"
  },
  preview: {
    icon: {
      size: "1.5rem"
    },
    mask: {
      background: "{mask.background}",
      color: "{mask.color}"
    }
  },
  toolbar: {
    position: {
      left: "auto",
      right: "1rem",
      top: "1rem",
      bottom: "auto"
    },
    blur: "8px",
    background: "rgba(255,255,255,0.1)",
    borderColor: "rgba(255,255,255,0.2)",
    borderWidth: "1px",
    borderRadius: "30px",
    padding: ".5rem",
    gap: "0.5rem"
  },
  action: {
    hoverBackground: "rgba(255,255,255,0.1)",
    color: "{surface.50}",
    hoverColor: "{surface.0}",
    size: "3rem",
    iconSize: "1.5rem",
    borderRadius: "50%",
    focusRing: {
      width: "{focus.ring.width}",
      style: "{focus.ring.style}",
      color: "{focus.ring.color}",
      offset: "{focus.ring.offset}",
      shadow: "{focus.ring.shadow}"
    }
  }
};
var index$X = {
  handle: {
    size: "15px",
    hoverSize: "30px",
    background: "rgba(255,255,255,0.3)",
    hoverBackground: "rgba(255,255,255,0.3)",
    borderColor: "unset",
    hoverBorderColor: "unset",
    borderWidth: "0",
    borderRadius: "50%",
    transitionDuration: "{transition.duration}",
    focusRing: {
      width: "{focus.ring.width}",
      style: "{focus.ring.style}",
      color: "rgba(255,255,255,0.3)",
      offset: "{focus.ring.offset}",
      shadow: "{focus.ring.shadow}"
    }
  }
};
var index$W = {
  root: {
    padding: "{form.field.padding.y} {form.field.padding.x}",
    borderRadius: "{content.border.radius}",
    gap: "0.5rem"
  },
  text: {
    fontWeight: "500"
  },
  icon: {
    size: "1rem"
  },
  colorScheme: {
    light: {
      info: {
        background: "color-mix(in srgb, {blue.50}, transparent 5%)",
        borderColor: "{blue.200}",
        color: "{blue.600}",
        shadow: "0px 4px 8px 0px color-mix(in srgb, {blue.500}, transparent 96%)"
      },
      success: {
        background: "color-mix(in srgb, {green.50}, transparent 5%)",
        borderColor: "{green.200}",
        color: "{green.600}",
        shadow: "0px 4px 8px 0px color-mix(in srgb, {green.500}, transparent 96%)"
      },
      warn: {
        background: "color-mix(in srgb,{yellow.50}, transparent 5%)",
        borderColor: "{yellow.200}",
        color: "{yellow.600}",
        shadow: "0px 4px 8px 0px color-mix(in srgb, {yellow.500}, transparent 96%)"
      },
      error: {
        background: "color-mix(in srgb, {red.50}, transparent 5%)",
        borderColor: "{red.200}",
        color: "{red.600}",
        shadow: "0px 4px 8px 0px color-mix(in srgb, {red.500}, transparent 96%)"
      },
      secondary: {
        background: "{surface.100}",
        borderColor: "{surface.200}",
        color: "{surface.600}",
        shadow: "0px 4px 8px 0px color-mix(in srgb, {surface.500}, transparent 96%)"
      },
      contrast: {
        background: "{surface.900}",
        borderColor: "{surface.950}",
        color: "{surface.50}",
        shadow: "0px 4px 8px 0px color-mix(in srgb, {surface.950}, transparent 96%)"
      }
    },
    dark: {
      info: {
        background: "color-mix(in srgb, {blue.500}, transparent 84%)",
        borderColor: "color-mix(in srgb, {blue.700}, transparent 64%)",
        color: "{blue.500}",
        shadow: "0px 4px 8px 0px color-mix(in srgb, {blue.500}, transparent 96%)"
      },
      success: {
        background: "color-mix(in srgb, {green.500}, transparent 84%)",
        borderColor: "color-mix(in srgb, {green.700}, transparent 64%)",
        color: "{green.500}",
        shadow: "0px 4px 8px 0px color-mix(in srgb, {green.500}, transparent 96%)"
      },
      warn: {
        background: "color-mix(in srgb, {yellow.500}, transparent 84%)",
        borderColor: "color-mix(in srgb, {yellow.700}, transparent 64%)",
        color: "{yellow.500}",
        shadow: "0px 4px 8px 0px color-mix(in srgb, {yellow.500}, transparent 96%)"
      },
      error: {
        background: "color-mix(in srgb, {red.500}, transparent 84%)",
        borderColor: "color-mix(in srgb, {red.700}, transparent 64%)",
        color: "{red.500}",
        shadow: "0px 4px 8px 0px color-mix(in srgb, {red.500}, transparent 96%)"
      },
      secondary: {
        background: "{surface.800}",
        borderColor: "{surface.700}",
        color: "{surface.300}",
        shadow: "0px 4px 8px 0px color-mix(in srgb, {surface.500}, transparent 96%)"
      },
      contrast: {
        background: "{surface.0}",
        borderColor: "{surface.100}",
        color: "{surface.950}",
        shadow: "0px 4px 8px 0px color-mix(in srgb, {surface.950}, transparent 96%)"
      }
    }
  }
};
var index$V = {
  root: {
    padding: "{form.field.padding.y} {form.field.padding.x}",
    borderRadius: "{content.border.radius}",
    focusRing: {
      width: "{focus.ring.width}",
      style: "{focus.ring.style}",
      color: "{focus.ring.color}",
      offset: "{focus.ring.offset}",
      shadow: "{focus.ring.shadow}"
    },
    transitionDuration: "{transition.duration}"
  },
  display: {
    hoverBackground: "{content.hover.background}",
    hoverColor: "{content.hover.color}"
  }
};
var index$U = {
  root: {
    background: "{form.field.background}",
    disabledBackground: "{form.field.disabled.background}",
    filledBackground: "{form.field.filled.background}",
    filledFocusBackground: "{form.field.filled.focus.background}",
    borderColor: "{form.field.border.color}",
    hoverBorderColor: "{form.field.hover.border.color}",
    focusBorderColor: "{form.field.focus.border.color}",
    invalidBorderColor: "{form.field.invalid.border.color}",
    color: "{form.field.color}",
    disabledColor: "{form.field.disabled.color}",
    placeholderColor: "{form.field.placeholder.color}",
    shadow: "{form.field.shadow}",
    paddingX: "{form.field.padding.x}",
    paddingY: "{form.field.padding.y}",
    borderRadius: "{form.field.border.radius}",
    focusRing: {
      width: "{form.field.focus.ring.width}",
      style: "{form.field.focus.ring.style}",
      color: "{form.field.focus.ring.color}",
      offset: "{form.field.focus.ring.offset}",
      shadow: "{form.field.focus.ring.shadow}"
    },
    transitionDuration: "{form.field.transition.duration}"
  },
  chip: {
    borderRadius: "{border.radius.sm}"
  },
  colorScheme: {
    light: {
      chip: {
        focusBackground: "{surface.200}",
        color: "{surface.800}"
      }
    },
    dark: {
      chip: {
        focusBackground: "{surface.700}",
        color: "{surface.0}"
      }
    }
  }
};
var index$T = {
  addon: {
    background: "{form.field.background}",
    borderColor: "{form.field.border.color}",
    color: "{form.field.icon.color}",
    borderRadius: "{form.field.border.radius}",
    padding: "0.5rem",
    minWidth: "2.5rem"
  }
};
var index$S = {
  root: {
    transitionDuration: "{transition.duration}"
  },
  button: {
    width: "2.5rem",
    borderRadius: "{form.field.border.radius}",
    verticalPadding: "{form.field.padding.y}"
  },
  colorScheme: {
    light: {
      button: {
        background: "transparent",
        hoverBackground: "{surface.100}",
        activeBackground: "{surface.200}",
        borderColor: "{form.field.border.color}",
        hoverBorderColor: "{form.field.border.color}",
        activeBorderColor: "{form.field.border.color}",
        color: "{surface.400}",
        hoverColor: "{surface.500}",
        activeColor: "{surface.600}"
      }
    },
    dark: {
      button: {
        background: "transparent",
        hoverBackground: "{surface.800}",
        activeBackground: "{surface.700}",
        borderColor: "{form.field.border.color}",
        hoverBorderColor: "{form.field.border.color}",
        activeBorderColor: "{form.field.border.color}",
        color: "{surface.400}",
        hoverColor: "{surface.300}",
        activeColor: "{surface.200}"
      }
    }
  }
};
var index$R = {
  root: {
    gap: "0.5rem"
  },
  input: {
    width: "2.5rem",
    sm: {
      width: "2rem"
    },
    lg: {
      width: "3rem"
    }
  }
};
var index$Q = {
  root: {
    background: "{form.field.background}",
    disabledBackground: "{form.field.disabled.background}",
    filledBackground: "{form.field.filled.background}",
    filledHoverBackground: "{form.field.filled.hover.background}",
    filledFocusBackground: "{form.field.filled.focus.background}",
    borderColor: "{form.field.border.color}",
    hoverBorderColor: "{form.field.hover.border.color}",
    focusBorderColor: "{form.field.focus.border.color}",
    invalidBorderColor: "{form.field.invalid.border.color}",
    color: "{form.field.color}",
    disabledColor: "{form.field.disabled.color}",
    placeholderColor: "{form.field.placeholder.color}",
    invalidPlaceholderColor: "{form.field.invalid.placeholder.color}",
    shadow: "{form.field.shadow}",
    paddingX: "{form.field.padding.x}",
    paddingY: "{form.field.padding.y}",
    borderRadius: "{form.field.border.radius}",
    focusRing: {
      width: "{form.field.focus.ring.width}",
      style: "{form.field.focus.ring.style}",
      color: "{form.field.focus.ring.color}",
      offset: "{form.field.focus.ring.offset}",
      shadow: "{form.field.focus.ring.shadow}"
    },
    transitionDuration: "{form.field.transition.duration}",
    sm: {
      fontSize: "{form.field.sm.font.size}",
      paddingX: "{form.field.sm.padding.x}",
      paddingY: "{form.field.sm.padding.y}"
    },
    lg: {
      fontSize: "{form.field.lg.font.size}",
      paddingX: "{form.field.lg.padding.x}",
      paddingY: "{form.field.lg.padding.y}"
    }
  }
};
var index$P = {
  root: {
    transitionDuration: "{transition.duration}",
    focusRing: {
      width: "{focus.ring.width}",
      style: "{focus.ring.style}",
      color: "{focus.ring.color}",
      offset: "{focus.ring.offset}",
      shadow: "{focus.ring.shadow}"
    }
  },
  value: {
    background: "{primary.color}"
  },
  range: {
    background: "{content.border.color}"
  },
  text: {
    color: "{text.muted.color}"
  }
};
var index$O = {
  root: {
    background: "{form.field.background}",
    disabledBackground: "{form.field.disabled.background}",
    borderColor: "{form.field.border.color}",
    invalidBorderColor: "{form.field.invalid.border.color}",
    color: "{form.field.color}",
    disabledColor: "{form.field.disabled.color}",
    shadow: "{form.field.shadow}",
    borderRadius: "{form.field.border.radius}",
    transitionDuration: "{form.field.transition.duration}"
  },
  list: {
    padding: "{list.padding}",
    gap: "{list.gap}",
    header: {
      padding: "{list.header.padding}"
    }
  },
  option: {
    focusBackground: "{list.option.focus.background}",
    selectedBackground: "{list.option.selected.background}",
    selectedFocusBackground: "{list.option.selected.focus.background}",
    color: "{list.option.color}",
    focusColor: "{list.option.focus.color}",
    selectedColor: "{list.option.selected.color}",
    selectedFocusColor: "{list.option.selected.focus.color}",
    padding: "{list.option.padding}",
    borderRadius: "{list.option.border.radius}"
  },
  optionGroup: {
    background: "{list.option.group.background}",
    color: "{list.option.group.color}",
    fontWeight: "{list.option.group.font.weight}",
    padding: "{list.option.group.padding}"
  },
  checkmark: {
    color: "{list.option.color}",
    gutterStart: "-0.375rem",
    gutterEnd: "0.375rem"
  },
  emptyMessage: {
    padding: "{list.option.padding}"
  },
  colorScheme: {
    light: {
      option: {
        stripedBackground: "{surface.50}"
      }
    },
    dark: {
      option: {
        stripedBackground: "{surface.900}"
      }
    }
  }
};
var index$N = {
  root: {
    background: "{content.background}",
    borderColor: "{content.border.color}",
    borderRadius: "{content.border.radius}",
    color: "{content.color}",
    gap: "0.5rem",
    verticalOrientation: {
      padding: "{navigation.list.padding}",
      gap: "{navigation.list.gap}"
    },
    horizontalOrientation: {
      padding: "0.5rem 0.75rem",
      gap: "0.5rem"
    },
    transitionDuration: "{transition.duration}"
  },
  baseItem: {
    borderRadius: "{content.border.radius}",
    padding: "{navigation.item.padding}"
  },
  item: {
    focusBackground: "{navigation.item.focus.background}",
    activeBackground: "{navigation.item.active.background}",
    color: "{navigation.item.color}",
    focusColor: "{navigation.item.focus.color}",
    activeColor: "{navigation.item.active.color}",
    padding: "{navigation.item.padding}",
    borderRadius: "{navigation.item.border.radius}",
    gap: "{navigation.item.gap}",
    icon: {
      color: "{navigation.item.icon.color}",
      focusColor: "{navigation.item.icon.focus.color}",
      activeColor: "{navigation.item.icon.active.color}"
    }
  },
  overlay: {
    padding: "0",
    background: "{content.background}",
    borderColor: "{content.border.color}",
    borderRadius: "{content.border.radius}",
    color: "{content.color}",
    shadow: "{overlay.navigation.shadow}",
    gap: "0.5rem"
  },
  submenu: {
    padding: "{navigation.list.padding}",
    gap: "{navigation.list.gap}"
  },
  submenuLabel: {
    padding: "{navigation.submenu.label.padding}",
    fontWeight: "{navigation.submenu.label.font.weight}",
    background: "{navigation.submenu.label.background.}",
    color: "{navigation.submenu.label.color}"
  },
  submenuIcon: {
    size: "{navigation.submenu.icon.size}",
    color: "{navigation.submenu.icon.color}",
    focusColor: "{navigation.submenu.icon.focus.color}",
    activeColor: "{navigation.submenu.icon.active.color}"
  },
  separator: {
    borderColor: "{content.border.color}"
  },
  mobileButton: {
    borderRadius: "50%",
    size: "1.75rem",
    color: "{text.muted.color}",
    hoverColor: "{text.hover.muted.color}",
    hoverBackground: "{content.hover.background}",
    focusRing: {
      width: "{focus.ring.width}",
      style: "{focus.ring.style}",
      color: "{focus.ring.color}",
      offset: "{focus.ring.offset}",
      shadow: "{focus.ring.shadow}"
    }
  }
};
var index$M = {
  root: {
    background: "{content.background}",
    borderColor: "{content.border.color}",
    color: "{content.color}",
    borderRadius: "{content.border.radius}",
    shadow: "{overlay.navigation.shadow}",
    transitionDuration: "{transition.duration}"
  },
  list: {
    padding: "{navigation.list.padding}",
    gap: "{navigation.list.gap}"
  },
  item: {
    focusBackground: "{navigation.item.focus.background}",
    color: "{navigation.item.color}",
    focusColor: "{navigation.item.focus.color}",
    padding: "{navigation.item.padding}",
    borderRadius: "{navigation.item.border.radius}",
    gap: "{navigation.item.gap}",
    icon: {
      color: "{navigation.item.icon.color}",
      focusColor: "{navigation.item.icon.focus.color}"
    }
  },
  submenuLabel: {
    padding: "{navigation.submenu.label.padding}",
    fontWeight: "{navigation.submenu.label.font.weight}",
    background: "{navigation.submenu.label.background}",
    color: "{navigation.submenu.label.color}"
  },
  separator: {
    borderColor: "{content.border.color}"
  }
};
var index$L = {
  root: {
    background: "{content.background}",
    borderColor: "{content.border.color}",
    borderRadius: "{content.border.radius}",
    color: "{content.color}",
    gap: "0.5rem",
    padding: "0.5rem 0.75rem",
    transitionDuration: "{transition.duration}"
  },
  baseItem: {
    borderRadius: "{content.border.radius}",
    padding: "{navigation.item.padding}"
  },
  item: {
    focusBackground: "{navigation.item.focus.background}",
    activeBackground: "{navigation.item.active.background}",
    color: "{navigation.item.color}",
    focusColor: "{navigation.item.focus.color}",
    activeColor: "{navigation.item.active.color}",
    padding: "{navigation.item.padding}",
    borderRadius: "{navigation.item.border.radius}",
    gap: "{navigation.item.gap}",
    icon: {
      color: "{navigation.item.icon.color}",
      focusColor: "{navigation.item.icon.focus.color}",
      activeColor: "{navigation.item.icon.active.color}"
    }
  },
  submenu: {
    padding: "{navigation.list.padding}",
    gap: "{navigation.list.gap}",
    background: "{content.background}",
    borderColor: "{content.border.color}",
    borderRadius: "{content.border.radius}",
    shadow: "{overlay.navigation.shadow}",
    mobileIndent: "1rem",
    icon: {
      size: "{navigation.submenu.icon.size}",
      color: "{navigation.submenu.icon.color}",
      focusColor: "{navigation.submenu.icon.focus.color}",
      activeColor: "{navigation.submenu.icon.active.color}"
    }
  },
  separator: {
    borderColor: "{content.border.color}"
  },
  mobileButton: {
    borderRadius: "50%",
    size: "1.75rem",
    color: "{text.muted.color}",
    hoverColor: "{text.hover.muted.color}",
    hoverBackground: "{content.hover.background}",
    focusRing: {
      width: "{focus.ring.width}",
      style: "{focus.ring.style}",
      color: "{focus.ring.color}",
      offset: "{focus.ring.offset}",
      shadow: "{focus.ring.shadow}"
    }
  }
};
var index$K = {
  root: {
    borderRadius: "{content.border.radius}",
    borderWidth: "1px",
    transitionDuration: "{transition.duration}"
  },
  content: {
    padding: "0.5rem 0.75rem",
    gap: "0.5rem",
    sm: {
      padding: "0.375rem 0.625rem"
    },
    lg: {
      padding: "0.625rem 0.875rem"
    }
  },
  text: {
    fontSize: "1rem",
    fontWeight: "500",
    sm: {
      fontSize: "0.875rem"
    },
    lg: {
      fontSize: "1.125rem"
    }
  },
  icon: {
    size: "1.125rem",
    sm: {
      size: "1rem"
    },
    lg: {
      size: "1.25rem"
    }
  },
  closeButton: {
    width: "1.75rem",
    height: "1.75rem",
    borderRadius: "50%",
    focusRing: {
      width: "{focus.ring.width}",
      style: "{focus.ring.style}",
      offset: "{focus.ring.offset}"
    }
  },
  closeIcon: {
    size: "1rem",
    sm: {
      size: "0.875rem"
    },
    lg: {
      size: "1.125rem"
    }
  },
  outlined: {
    root: {
      borderWidth: "1px"
    }
  },
  simple: {
    content: {
      padding: "0"
    }
  },
  colorScheme: {
    light: {
      info: {
        background: "color-mix(in srgb, {blue.50}, transparent 5%)",
        borderColor: "{blue.200}",
        color: "{blue.600}",
        shadow: "0px 4px 8px 0px color-mix(in srgb, {blue.500}, transparent 96%)",
        closeButton: {
          hoverBackground: "{blue.100}",
          focusRing: {
            color: "{blue.600}",
            shadow: "none"
          }
        },
        outlined: {
          color: "{blue.600}",
          borderColor: "{blue.600}"
        },
        simple: {
          color: "{blue.600}"
        }
      },
      success: {
        background: "color-mix(in srgb, {green.50}, transparent 5%)",
        borderColor: "{green.200}",
        color: "{green.600}",
        shadow: "0px 4px 8px 0px color-mix(in srgb, {green.500}, transparent 96%)",
        closeButton: {
          hoverBackground: "{green.100}",
          focusRing: {
            color: "{green.600}",
            shadow: "none"
          }
        },
        outlined: {
          color: "{green.600}",
          borderColor: "{green.600}"
        },
        simple: {
          color: "{green.600}"
        }
      },
      warn: {
        background: "color-mix(in srgb,{yellow.50}, transparent 5%)",
        borderColor: "{yellow.200}",
        color: "{yellow.600}",
        shadow: "0px 4px 8px 0px color-mix(in srgb, {yellow.500}, transparent 96%)",
        closeButton: {
          hoverBackground: "{yellow.100}",
          focusRing: {
            color: "{yellow.600}",
            shadow: "none"
          }
        },
        outlined: {
          color: "{yellow.600}",
          borderColor: "{yellow.600}"
        },
        simple: {
          color: "{yellow.600}"
        }
      },
      error: {
        background: "color-mix(in srgb, {red.50}, transparent 5%)",
        borderColor: "{red.200}",
        color: "{red.600}",
        shadow: "0px 4px 8px 0px color-mix(in srgb, {red.500}, transparent 96%)",
        closeButton: {
          hoverBackground: "{red.100}",
          focusRing: {
            color: "{red.600}",
            shadow: "none"
          }
        },
        outlined: {
          color: "{red.600}",
          borderColor: "{red.600}"
        },
        simple: {
          color: "{red.600}"
        }
      },
      secondary: {
        background: "{surface.100}",
        borderColor: "{surface.200}",
        color: "{surface.600}",
        shadow: "0px 4px 8px 0px color-mix(in srgb, {surface.500}, transparent 96%)",
        closeButton: {
          hoverBackground: "{surface.200}",
          focusRing: {
            color: "{surface.600}",
            shadow: "none"
          }
        },
        outlined: {
          color: "{surface.500}",
          borderColor: "{surface.500}"
        },
        simple: {
          color: "{surface.500}"
        }
      },
      contrast: {
        background: "{surface.900}",
        borderColor: "{surface.950}",
        color: "{surface.50}",
        shadow: "0px 4px 8px 0px color-mix(in srgb, {surface.950}, transparent 96%)",
        closeButton: {
          hoverBackground: "{surface.800}",
          focusRing: {
            color: "{surface.50}",
            shadow: "none"
          }
        },
        outlined: {
          color: "{surface.950}",
          borderColor: "{surface.950}"
        },
        simple: {
          color: "{surface.950}"
        }
      }
    },
    dark: {
      info: {
        background: "color-mix(in srgb, {blue.500}, transparent 84%)",
        borderColor: "color-mix(in srgb, {blue.700}, transparent 64%)",
        color: "{blue.500}",
        shadow: "0px 4px 8px 0px color-mix(in srgb, {blue.500}, transparent 96%)",
        closeButton: {
          hoverBackground: "rgba(255, 255, 255, 0.05)",
          focusRing: {
            color: "{blue.500}",
            shadow: "none"
          }
        },
        outlined: {
          color: "{blue.500}",
          borderColor: "{blue.500}"
        },
        simple: {
          color: "{blue.500}"
        }
      },
      success: {
        background: "color-mix(in srgb, {green.500}, transparent 84%)",
        borderColor: "color-mix(in srgb, {green.700}, transparent 64%)",
        color: "{green.500}",
        shadow: "0px 4px 8px 0px color-mix(in srgb, {green.500}, transparent 96%)",
        closeButton: {
          hoverBackground: "rgba(255, 255, 255, 0.05)",
          focusRing: {
            color: "{green.500}",
            shadow: "none"
          }
        },
        outlined: {
          color: "{green.500}",
          borderColor: "{green.500}"
        },
        simple: {
          color: "{green.500}"
        }
      },
      warn: {
        background: "color-mix(in srgb, {yellow.500}, transparent 84%)",
        borderColor: "color-mix(in srgb, {yellow.700}, transparent 64%)",
        color: "{yellow.500}",
        shadow: "0px 4px 8px 0px color-mix(in srgb, {yellow.500}, transparent 96%)",
        closeButton: {
          hoverBackground: "rgba(255, 255, 255, 0.05)",
          focusRing: {
            color: "{yellow.500}",
            shadow: "none"
          }
        },
        outlined: {
          color: "{yellow.500}",
          borderColor: "{yellow.500}"
        },
        simple: {
          color: "{yellow.500}"
        }
      },
      error: {
        background: "color-mix(in srgb, {red.500}, transparent 84%)",
        borderColor: "color-mix(in srgb, {red.700}, transparent 64%)",
        color: "{red.500}",
        shadow: "0px 4px 8px 0px color-mix(in srgb, {red.500}, transparent 96%)",
        closeButton: {
          hoverBackground: "rgba(255, 255, 255, 0.05)",
          focusRing: {
            color: "{red.500}",
            shadow: "none"
          }
        },
        outlined: {
          color: "{red.500}",
          borderColor: "{red.500}"
        },
        simple: {
          color: "{red.500}"
        }
      },
      secondary: {
        background: "{surface.800}",
        borderColor: "{surface.700}",
        color: "{surface.300}",
        shadow: "0px 4px 8px 0px color-mix(in srgb, {surface.500}, transparent 96%)",
        closeButton: {
          hoverBackground: "{surface.700}",
          focusRing: {
            color: "{surface.300}",
            shadow: "none"
          }
        },
        outlined: {
          color: "{surface.400}",
          borderColor: "{surface.400}"
        },
        simple: {
          color: "{surface.400}"
        }
      },
      contrast: {
        background: "{surface.0}",
        borderColor: "{surface.100}",
        color: "{surface.950}",
        shadow: "0px 4px 8px 0px color-mix(in srgb, {surface.950}, transparent 96%)",
        closeButton: {
          hoverBackground: "{surface.100}",
          focusRing: {
            color: "{surface.950}",
            shadow: "none"
          }
        },
        outlined: {
          color: "{surface.0}",
          borderColor: "{surface.0}"
        },
        simple: {
          color: "{surface.0}"
        }
      }
    }
  }
};
var index$J = {
  root: {
    borderRadius: "{content.border.radius}",
    gap: "1rem"
  },
  meters: {
    background: "{content.border.color}",
    size: "0.5rem"
  },
  label: {
    gap: "0.5rem"
  },
  labelMarker: {
    size: "0.5rem"
  },
  labelIcon: {
    size: "1rem"
  },
  labelList: {
    verticalGap: "0.5rem",
    horizontalGap: "1rem"
  }
};
var index$I = {
  root: {
    background: "{form.field.background}",
    disabledBackground: "{form.field.disabled.background}",
    filledBackground: "{form.field.filled.background}",
    filledHoverBackground: "{form.field.filled.hover.background}",
    filledFocusBackground: "{form.field.filled.focus.background}",
    borderColor: "{form.field.border.color}",
    hoverBorderColor: "{form.field.hover.border.color}",
    focusBorderColor: "{form.field.focus.border.color}",
    invalidBorderColor: "{form.field.invalid.border.color}",
    color: "{form.field.color}",
    disabledColor: "{form.field.disabled.color}",
    placeholderColor: "{form.field.placeholder.color}",
    invalidPlaceholderColor: "{form.field.invalid.placeholder.color}",
    shadow: "{form.field.shadow}",
    paddingX: "{form.field.padding.x}",
    paddingY: "{form.field.padding.y}",
    borderRadius: "{form.field.border.radius}",
    focusRing: {
      width: "{form.field.focus.ring.width}",
      style: "{form.field.focus.ring.style}",
      color: "{form.field.focus.ring.color}",
      offset: "{form.field.focus.ring.offset}",
      shadow: "{form.field.focus.ring.shadow}"
    },
    transitionDuration: "{form.field.transition.duration}",
    sm: {
      fontSize: "{form.field.sm.font.size}",
      paddingX: "{form.field.sm.padding.x}",
      paddingY: "{form.field.sm.padding.y}"
    },
    lg: {
      fontSize: "{form.field.lg.font.size}",
      paddingX: "{form.field.lg.padding.x}",
      paddingY: "{form.field.lg.padding.y}"
    }
  },
  dropdown: {
    width: "2.5rem",
    color: "{form.field.icon.color}"
  },
  overlay: {
    background: "{overlay.select.background}",
    borderColor: "{overlay.select.border.color}",
    borderRadius: "{overlay.select.border.radius}",
    color: "{overlay.select.color}",
    shadow: "{overlay.select.shadow}"
  },
  list: {
    padding: "{list.padding}",
    gap: "{list.gap}",
    header: {
      padding: "{list.header.padding}"
    }
  },
  option: {
    focusBackground: "{list.option.focus.background}",
    selectedBackground: "{list.option.selected.background}",
    selectedFocusBackground: "{list.option.selected.focus.background}",
    color: "{list.option.color}",
    focusColor: "{list.option.focus.color}",
    selectedColor: "{list.option.selected.color}",
    selectedFocusColor: "{list.option.selected.focus.color}",
    padding: "{list.option.padding}",
    borderRadius: "{list.option.border.radius}",
    gap: "0.5rem"
  },
  optionGroup: {
    background: "{list.option.group.background}",
    color: "{list.option.group.color}",
    fontWeight: "{list.option.group.font.weight}",
    padding: "{list.option.group.padding}"
  },
  clearIcon: {
    color: "{form.field.icon.color}"
  },
  chip: {
    borderRadius: "{border.radius.sm}"
  },
  emptyMessage: {
    padding: "{list.option.padding}"
  }
};
var index$H = {
  root: {
    gap: "1.125rem"
  },
  controls: {
    gap: "0.5rem"
  }
};
var index$G = {
  root: {
    gutter: "0.75rem",
    transitionDuration: "{transition.duration}"
  },
  node: {
    background: "{content.background}",
    hoverBackground: "{content.hover.background}",
    selectedBackground: "{highlight.background}",
    borderColor: "{content.border.color}",
    color: "{content.color}",
    selectedColor: "{highlight.color}",
    hoverColor: "{content.hover.color}",
    padding: "0.75rem 1rem",
    toggleablePadding: "0.75rem 1rem 1.25rem 1rem",
    borderRadius: "{content.border.radius}"
  },
  nodeToggleButton: {
    background: "{content.background}",
    hoverBackground: "{content.hover.background}",
    borderColor: "{content.border.color}",
    color: "{text.muted.color}",
    hoverColor: "{text.color}",
    size: "1.5rem",
    borderRadius: "50%",
    focusRing: {
      width: "{focus.ring.width}",
      style: "{focus.ring.style}",
      color: "{focus.ring.color}",
      offset: "{focus.ring.offset}",
      shadow: "{focus.ring.shadow}"
    }
  },
  connector: {
    color: "{content.border.color}",
    borderRadius: "{content.border.radius}",
    height: "24px"
  }
};
var index$F = {
  root: {
    outline: {
      width: "2px",
      color: "{content.background}"
    }
  }
};
var index$E = {
  root: {
    padding: "0.5rem 1rem",
    gap: "0.25rem",
    borderRadius: "{content.border.radius}",
    background: "{content.background}",
    color: "{content.color}",
    transitionDuration: "{transition.duration}"
  },
  navButton: {
    background: "transparent",
    hoverBackground: "{content.hover.background}",
    selectedBackground: "{highlight.background}",
    color: "{text.muted.color}",
    hoverColor: "{text.hover.muted.color}",
    selectedColor: "{highlight.color}",
    width: "2.5rem",
    height: "2.5rem",
    borderRadius: "50%",
    focusRing: {
      width: "{focus.ring.width}",
      style: "{focus.ring.style}",
      color: "{focus.ring.color}",
      offset: "{focus.ring.offset}",
      shadow: "{focus.ring.shadow}"
    }
  },
  currentPageReport: {
    color: "{text.muted.color}"
  },
  jumpToPageInput: {
    maxWidth: "2.5rem"
  }
};
var index$D = {
  root: {
    background: "{content.background}",
    borderColor: "{content.border.color}",
    color: "{content.color}",
    borderRadius: "{content.border.radius}"
  },
  header: {
    background: "transparent",
    color: "{text.color}",
    padding: "1.125rem",
    borderColor: "{content.border.color}",
    borderWidth: "0",
    borderRadius: "0"
  },
  toggleableHeader: {
    padding: "0.375rem 1.125rem"
  },
  title: {
    fontWeight: "600"
  },
  content: {
    padding: "0 1.125rem 1.125rem 1.125rem"
  },
  footer: {
    padding: "0 1.125rem 1.125rem 1.125rem"
  }
};
var index$C = {
  root: {
    gap: "0.5rem",
    transitionDuration: "{transition.duration}"
  },
  panel: {
    background: "{content.background}",
    borderColor: "{content.border.color}",
    borderWidth: "1px",
    color: "{content.color}",
    padding: "0.25rem 0.25rem",
    borderRadius: "{content.border.radius}",
    first: {
      borderWidth: "1px",
      topBorderRadius: "{content.border.radius}"
    },
    last: {
      borderWidth: "1px",
      bottomBorderRadius: "{content.border.radius}"
    }
  },
  item: {
    focusBackground: "{navigation.item.focus.background}",
    color: "{navigation.item.color}",
    focusColor: "{navigation.item.focus.color}",
    gap: "0.5rem",
    padding: "{navigation.item.padding}",
    borderRadius: "{content.border.radius}",
    icon: {
      color: "{navigation.item.icon.color}",
      focusColor: "{navigation.item.icon.focus.color}"
    }
  },
  submenu: {
    indent: "1rem"
  },
  submenuIcon: {
    color: "{navigation.submenu.icon.color}",
    focusColor: "{navigation.submenu.icon.focus.color}"
  }
};
var index$B = {
  meter: {
    background: "{content.border.color}",
    borderRadius: "{content.border.radius}",
    height: ".75rem"
  },
  icon: {
    color: "{form.field.icon.color}"
  },
  overlay: {
    background: "{overlay.popover.background}",
    borderColor: "{overlay.popover.border.color}",
    borderRadius: "{overlay.popover.border.radius}",
    color: "{overlay.popover.color}",
    padding: "{overlay.popover.padding}",
    shadow: "{overlay.popover.shadow}"
  },
  content: {
    gap: "0.5rem"
  },
  colorScheme: {
    light: {
      strength: {
        weakBackground: "{red.500}",
        mediumBackground: "{amber.500}",
        strongBackground: "{green.500}"
      }
    },
    dark: {
      strength: {
        weakBackground: "{red.400}",
        mediumBackground: "{amber.400}",
        strongBackground: "{green.400}"
      }
    }
  }
};
var index$A = {
  root: {
    gap: "1.125rem"
  },
  controls: {
    gap: "0.5rem"
  }
};
var index$z = {
  root: {
    background: "{overlay.popover.background}",
    borderColor: "{overlay.popover.border.color}",
    color: "{overlay.popover.color}",
    borderRadius: "{overlay.popover.border.radius}",
    shadow: "{overlay.popover.shadow}",
    gutter: "10px",
    arrowOffset: "1.25rem"
  },
  content: {
    padding: "{overlay.popover.padding}"
  }
};
var index$y = {
  root: {
    background: "{content.border.color}",
    borderRadius: "{content.border.radius}",
    height: "1.25rem"
  },
  value: {
    background: "{primary.color}"
  },
  label: {
    color: "{primary.contrast.color}",
    fontSize: "0.75rem",
    fontWeight: "600"
  }
};
var index$x = {
  colorScheme: {
    light: {
      root: {
        "color.1": "{red.500}",
        "color.2": "{blue.500}",
        "color.3": "{green.500}",
        "color.4": "{yellow.500}"
      }
    },
    dark: {
      root: {
        "color.1": "{red.400}",
        "color.2": "{blue.400}",
        "color.3": "{green.400}",
        "color.4": "{yellow.400}"
      }
    }
  }
};
var index$w = {
  root: {
    width: "1.25rem",
    height: "1.25rem",
    background: "{form.field.background}",
    checkedBackground: "{primary.color}",
    checkedHoverBackground: "{primary.hover.color}",
    disabledBackground: "{form.field.disabled.background}",
    filledBackground: "{form.field.filled.background}",
    borderColor: "{form.field.border.color}",
    hoverBorderColor: "{form.field.hover.border.color}",
    focusBorderColor: "{form.field.border.color}",
    checkedBorderColor: "{primary.color}",
    checkedHoverBorderColor: "{primary.hover.color}",
    checkedFocusBorderColor: "{primary.color}",
    checkedDisabledBorderColor: "{form.field.border.color}",
    invalidBorderColor: "{form.field.invalid.border.color}",
    shadow: "{form.field.shadow}",
    focusRing: {
      width: "{focus.ring.width}",
      style: "{focus.ring.style}",
      color: "{focus.ring.color}",
      offset: "{focus.ring.offset}",
      shadow: "{focus.ring.shadow}"
    },
    transitionDuration: "{form.field.transition.duration}",
    sm: {
      width: "1rem",
      height: "1rem"
    },
    lg: {
      width: "1.5rem",
      height: "1.5rem"
    }
  },
  icon: {
    size: "0.75rem",
    checkedColor: "{primary.contrast.color}",
    checkedHoverColor: "{primary.contrast.color}",
    disabledColor: "{form.field.disabled.color}",
    sm: {
      size: "0.5rem"
    },
    lg: {
      size: "1rem"
    }
  }
};
var index$v = {
  root: {
    gap: "0.25rem",
    transitionDuration: "{transition.duration}",
    focusRing: {
      width: "{focus.ring.width}",
      style: "{focus.ring.style}",
      color: "{focus.ring.color}",
      offset: "{focus.ring.offset}",
      shadow: "{focus.ring.shadow}"
    }
  },
  icon: {
    size: "1rem",
    color: "{text.muted.color}",
    hoverColor: "{primary.color}",
    activeColor: "{primary.color}"
  }
};
var index$u = {
  colorScheme: {
    light: {
      root: {
        background: "rgba(0,0,0,0.1)"
      }
    },
    dark: {
      root: {
        background: "rgba(255,255,255,0.3)"
      }
    }
  }
};
var index$t = {
  root: {
    transitionDuration: "{transition.duration}"
  },
  bar: {
    size: "9px",
    borderRadius: "{border.radius.sm}",
    focusRing: {
      width: "{focus.ring.width}",
      style: "{focus.ring.style}",
      color: "{focus.ring.color}",
      offset: "{focus.ring.offset}",
      shadow: "{focus.ring.shadow}"
    }
  },
  colorScheme: {
    light: {
      bar: {
        background: "{surface.100}"
      }
    },
    dark: {
      bar: {
        background: "{surface.800}"
      }
    }
  }
};
var index$s = {
  root: {
    background: "{form.field.background}",
    disabledBackground: "{form.field.disabled.background}",
    filledBackground: "{form.field.filled.background}",
    filledHoverBackground: "{form.field.filled.hover.background}",
    filledFocusBackground: "{form.field.filled.focus.background}",
    borderColor: "{form.field.border.color}",
    hoverBorderColor: "{form.field.hover.border.color}",
    focusBorderColor: "{form.field.focus.border.color}",
    invalidBorderColor: "{form.field.invalid.border.color}",
    color: "{form.field.color}",
    disabledColor: "{form.field.disabled.color}",
    placeholderColor: "{form.field.placeholder.color}",
    invalidPlaceholderColor: "{form.field.invalid.placeholder.color}",
    shadow: "{form.field.shadow}",
    paddingX: "{form.field.padding.x}",
    paddingY: "{form.field.padding.y}",
    borderRadius: "{form.field.border.radius}",
    focusRing: {
      width: "{form.field.focus.ring.width}",
      style: "{form.field.focus.ring.style}",
      color: "{form.field.focus.ring.color}",
      offset: "{form.field.focus.ring.offset}",
      shadow: "{form.field.focus.ring.shadow}"
    },
    transitionDuration: "{form.field.transition.duration}",
    sm: {
      fontSize: "{form.field.sm.font.size}",
      paddingX: "{form.field.sm.padding.x}",
      paddingY: "{form.field.sm.padding.y}"
    },
    lg: {
      fontSize: "{form.field.lg.font.size}",
      paddingX: "{form.field.lg.padding.x}",
      paddingY: "{form.field.lg.padding.y}"
    }
  },
  dropdown: {
    width: "2.5rem",
    color: "{form.field.icon.color}"
  },
  overlay: {
    background: "{overlay.select.background}",
    borderColor: "{overlay.select.border.color}",
    borderRadius: "{overlay.select.border.radius}",
    color: "{overlay.select.color}",
    shadow: "{overlay.select.shadow}"
  },
  list: {
    padding: "{list.padding}",
    gap: "{list.gap}",
    header: {
      padding: "{list.header.padding}"
    }
  },
  option: {
    focusBackground: "{list.option.focus.background}",
    selectedBackground: "{list.option.selected.background}",
    selectedFocusBackground: "{list.option.selected.focus.background}",
    color: "{list.option.color}",
    focusColor: "{list.option.focus.color}",
    selectedColor: "{list.option.selected.color}",
    selectedFocusColor: "{list.option.selected.focus.color}",
    padding: "{list.option.padding}",
    borderRadius: "{list.option.border.radius}"
  },
  optionGroup: {
    background: "{list.option.group.background}",
    color: "{list.option.group.color}",
    fontWeight: "{list.option.group.font.weight}",
    padding: "{list.option.group.padding}"
  },
  clearIcon: {
    color: "{form.field.icon.color}"
  },
  checkmark: {
    color: "{list.option.color}",
    gutterStart: "-0.375rem",
    gutterEnd: "0.375rem"
  },
  emptyMessage: {
    padding: "{list.option.padding}"
  }
};
var index$r = {
  root: {
    borderRadius: "{form.field.border.radius}"
  },
  colorScheme: {
    light: {
      root: {
        invalidBorderColor: "{form.field.invalid.border.color}"
      }
    },
    dark: {
      root: {
        invalidBorderColor: "{form.field.invalid.border.color}"
      }
    }
  }
};
var index$q = {
  root: {
    borderRadius: "{content.border.radius}"
  },
  colorScheme: {
    light: {
      root: {
        background: "{surface.200}",
        animationBackground: "rgba(255,255,255,0.4)"
      }
    },
    dark: {
      root: {
        background: "rgba(255, 255, 255, 0.06)",
        animationBackground: "rgba(255, 255, 255, 0.04)"
      }
    }
  }
};
var index$p = {
  root: {
    transitionDuration: "{transition.duration}"
  },
  track: {
    background: "{content.border.color}",
    borderRadius: "{content.border.radius}",
    size: "3px"
  },
  range: {
    background: "{primary.color}"
  },
  handle: {
    width: "20px",
    height: "20px",
    borderRadius: "50%",
    background: "{content.border.color}",
    hoverBackground: "{content.border.color}",
    content: {
      borderRadius: "50%",
      hoverBackground: "{content.background}",
      width: "16px",
      height: "16px",
      shadow: "0px 0.5px 0px 0px rgba(0, 0, 0, 0.08), 0px 1px 1px 0px rgba(0, 0, 0, 0.14)"
    },
    focusRing: {
      width: "{focus.ring.width}",
      style: "{focus.ring.style}",
      color: "{focus.ring.color}",
      offset: "{focus.ring.offset}",
      shadow: "{focus.ring.shadow}"
    }
  },
  colorScheme: {
    light: {
      handle: {
        contentBackground: "{surface.0}"
      }
    },
    dark: {
      handle: {
        contentBackground: "{surface.950}"
      }
    }
  }
};
var index$o = {
  root: {
    gap: "0.5rem",
    transitionDuration: "{transition.duration}"
  }
};
var index$n = {
  root: {
    borderRadius: "{form.field.border.radius}",
    roundedBorderRadius: "2rem",
    raisedShadow: "0 3px 1px -2px rgba(0, 0, 0, 0.2), 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 1px 5px 0 rgba(0, 0, 0, 0.12)"
  }
};
var index$m = {
  root: {
    background: "{content.background}",
    borderColor: "{content.border.color}",
    color: "{content.color}",
    transitionDuration: "{transition.duration}"
  },
  gutter: {
    background: "{content.border.color}"
  },
  handle: {
    size: "24px",
    background: "transparent",
    borderRadius: "{content.border.radius}",
    focusRing: {
      width: "{focus.ring.width}",
      style: "{focus.ring.style}",
      color: "{focus.ring.color}",
      offset: "{focus.ring.offset}",
      shadow: "{focus.ring.shadow}"
    }
  }
};
var index$l = {
  root: {
    transitionDuration: "{transition.duration}"
  },
  separator: {
    background: "{content.border.color}",
    activeBackground: "{primary.color}",
    margin: "0 0 0 1.625rem",
    size: "2px"
  },
  step: {
    padding: "0.5rem",
    gap: "1rem"
  },
  stepHeader: {
    padding: "0",
    borderRadius: "{content.border.radius}",
    focusRing: {
      width: "{focus.ring.width}",
      style: "{focus.ring.style}",
      color: "{focus.ring.color}",
      offset: "{focus.ring.offset}",
      shadow: "{focus.ring.shadow}"
    },
    gap: "0.5rem"
  },
  stepTitle: {
    color: "{text.muted.color}",
    activeColor: "{primary.color}",
    fontWeight: "500"
  },
  stepNumber: {
    background: "{content.background}",
    activeBackground: "{content.background}",
    borderColor: "{content.border.color}",
    activeBorderColor: "{content.border.color}",
    color: "{text.muted.color}",
    activeColor: "{primary.color}",
    size: "2rem",
    fontSize: "1.143rem",
    fontWeight: "500",
    borderRadius: "50%",
    shadow: "0px 0.5px 0px 0px rgba(0, 0, 0, 0.06), 0px 1px 1px 0px rgba(0, 0, 0, 0.12)"
  },
  steppanels: {
    padding: "0.875rem 0.5rem 1.125rem 0.5rem"
  },
  steppanel: {
    background: "{content.background}",
    color: "{content.color}",
    padding: "0",
    indent: "1rem"
  }
};
var index$k = {
  root: {
    transitionDuration: "{transition.duration}"
  },
  separator: {
    background: "{content.border.color}"
  },
  itemLink: {
    borderRadius: "{content.border.radius}",
    focusRing: {
      width: "{focus.ring.width}",
      style: "{focus.ring.style}",
      color: "{focus.ring.color}",
      offset: "{focus.ring.offset}",
      shadow: "{focus.ring.shadow}"
    },
    gap: "0.5rem"
  },
  itemLabel: {
    color: "{text.muted.color}",
    activeColor: "{primary.color}",
    fontWeight: "500"
  },
  itemNumber: {
    background: "{content.background}",
    activeBackground: "{content.background}",
    borderColor: "{content.border.color}",
    activeBorderColor: "{content.border.color}",
    color: "{text.muted.color}",
    activeColor: "{primary.color}",
    size: "2rem",
    fontSize: "1.143rem",
    fontWeight: "500",
    borderRadius: "50%",
    shadow: "0px 0.5px 0px 0px rgba(0, 0, 0, 0.06), 0px 1px 1px 0px rgba(0, 0, 0, 0.12)"
  }
};
var index$j = {
  root: {
    transitionDuration: "{transition.duration}"
  },
  tablist: {
    borderWidth: "0 0 1px 0",
    background: "{content.background}",
    borderColor: "{content.border.color}"
  },
  item: {
    background: "transparent",
    hoverBackground: "transparent",
    activeBackground: "transparent",
    borderWidth: "0 0 1px 0",
    borderColor: "{content.border.color}",
    hoverBorderColor: "{content.border.color}",
    activeBorderColor: "{primary.color}",
    color: "{text.muted.color}",
    hoverColor: "{text.color}",
    activeColor: "{primary.color}",
    padding: "1rem 1.125rem",
    fontWeight: "600",
    margin: "0 0 -1px 0",
    gap: "0.5rem",
    focusRing: {
      width: "{focus.ring.width}",
      style: "{focus.ring.style}",
      color: "{focus.ring.color}",
      offset: "{focus.ring.offset}",
      shadow: "{focus.ring.shadow}"
    }
  },
  itemIcon: {
    color: "{text.muted.color}",
    hoverColor: "{text.color}",
    activeColor: "{primary.color}"
  },
  activeBar: {
    height: "1px",
    bottom: "-1px",
    background: "{primary.color}"
  }
};
var index$i = {
  root: {
    transitionDuration: "{transition.duration}"
  },
  tablist: {
    borderWidth: "0 0 1px 0",
    background: "{content.background}",
    borderColor: "{content.border.color}"
  },
  tab: {
    background: "transparent",
    hoverBackground: "transparent",
    activeBackground: "transparent",
    borderWidth: "0 0 1px 0",
    borderColor: "{content.border.color}",
    hoverBorderColor: "{content.border.color}",
    activeBorderColor: "{primary.color}",
    color: "{text.muted.color}",
    hoverColor: "{text.color}",
    activeColor: "{primary.color}",
    padding: "1rem 1.125rem",
    fontWeight: "600",
    margin: "0 0 -1px 0",
    gap: "0.5rem",
    focusRing: {
      width: "{focus.ring.width}",
      style: "{focus.ring.style}",
      color: "{focus.ring.color}",
      offset: "-1px",
      shadow: "{focus.ring.shadow}"
    }
  },
  tabpanel: {
    background: "{content.background}",
    color: "{content.color}",
    padding: "0.875rem 1.125rem 1.125rem 1.125rem",
    focusRing: {
      width: "{focus.ring.width}",
      style: "{focus.ring.style}",
      color: "{focus.ring.color}",
      offset: "{focus.ring.offset}",
      shadow: "inset {focus.ring.shadow}"
    }
  },
  navButton: {
    background: "{content.background}",
    color: "{text.muted.color}",
    hoverColor: "{text.color}",
    width: "2.5rem",
    focusRing: {
      width: "{focus.ring.width}",
      style: "{focus.ring.style}",
      color: "{focus.ring.color}",
      offset: "-1px",
      shadow: "{focus.ring.shadow}"
    }
  },
  activeBar: {
    height: "1px",
    bottom: "-1px",
    background: "{primary.color}"
  },
  colorScheme: {
    light: {
      navButton: {
        shadow: "0px 0px 10px 50px rgba(255, 255, 255, 0.6)"
      }
    },
    dark: {
      navButton: {
        shadow: "0px 0px 10px 50px color-mix(in srgb, {content.background}, transparent 50%)"
      }
    }
  }
};
var index$h = {
  root: {
    transitionDuration: "{transition.duration}"
  },
  tabList: {
    background: "{content.background}",
    borderColor: "{content.border.color}"
  },
  tab: {
    borderColor: "{content.border.color}",
    activeBorderColor: "{primary.color}",
    color: "{text.muted.color}",
    hoverColor: "{text.color}",
    activeColor: "{primary.color}"
  },
  tabPanel: {
    background: "{content.background}",
    color: "{content.color}"
  },
  navButton: {
    background: "{content.background}",
    color: "{text.muted.color}",
    hoverColor: "{text.color}"
  },
  colorScheme: {
    light: {
      navButton: {
        shadow: "0px 0px 10px 50px rgba(255, 255, 255, 0.6)"
      }
    },
    dark: {
      navButton: {
        shadow: "0px 0px 10px 50px color-mix(in srgb, {content.background}, transparent 50%)"
      }
    }
  }
};
var index$g = {
  root: {
    fontSize: "0.875rem",
    fontWeight: "700",
    padding: "0.25rem 0.5rem",
    gap: "0.25rem",
    borderRadius: "{content.border.radius}",
    roundedBorderRadius: "{border.radius.xl}"
  },
  icon: {
    size: "0.75rem"
  },
  colorScheme: {
    light: {
      primary: {
        background: "{primary.100}",
        color: "{primary.700}"
      },
      secondary: {
        background: "{surface.100}",
        color: "{surface.600}"
      },
      success: {
        background: "{green.100}",
        color: "{green.700}"
      },
      info: {
        background: "{sky.100}",
        color: "{sky.700}"
      },
      warn: {
        background: "{orange.100}",
        color: "{orange.700}"
      },
      danger: {
        background: "{red.100}",
        color: "{red.700}"
      },
      contrast: {
        background: "{surface.950}",
        color: "{surface.0}"
      }
    },
    dark: {
      primary: {
        background: "color-mix(in srgb, {primary.500}, transparent 84%)",
        color: "{primary.300}"
      },
      secondary: {
        background: "{surface.800}",
        color: "{surface.300}"
      },
      success: {
        background: "color-mix(in srgb, {green.500}, transparent 84%)",
        color: "{green.300}"
      },
      info: {
        background: "color-mix(in srgb, {sky.500}, transparent 84%)",
        color: "{sky.300}"
      },
      warn: {
        background: "color-mix(in srgb, {orange.500}, transparent 84%)",
        color: "{orange.300}"
      },
      danger: {
        background: "color-mix(in srgb, {red.500}, transparent 84%)",
        color: "{red.300}"
      },
      contrast: {
        background: "{surface.0}",
        color: "{surface.950}"
      }
    }
  }
};
var index$f = {
  root: {
    background: "{form.field.background}",
    borderColor: "{form.field.border.color}",
    color: "{form.field.color}",
    height: "18rem",
    padding: "{form.field.padding.y} {form.field.padding.x}",
    borderRadius: "{form.field.border.radius}"
  },
  prompt: {
    gap: "0.25rem"
  },
  commandResponse: {
    margin: "2px 0"
  }
};
var index$e = {
  root: {
    background: "{form.field.background}",
    disabledBackground: "{form.field.disabled.background}",
    filledBackground: "{form.field.filled.background}",
    filledFocusBackground: "{form.field.filled.focus.background}",
    borderColor: "{form.field.border.color}",
    hoverBorderColor: "{form.field.hover.border.color}",
    focusBorderColor: "{form.field.focus.border.color}",
    invalidBorderColor: "{form.field.invalid.border.color}",
    color: "{form.field.color}",
    disabledColor: "{form.field.disabled.color}",
    placeholderColor: "{form.field.placeholder.color}",
    invalidPlaceholderColor: "{form.field.invalid.placeholder.color}",
    shadow: "{form.field.shadow}",
    paddingX: "{form.field.padding.x}",
    paddingY: "{form.field.padding.y}",
    borderRadius: "{form.field.border.radius}",
    focusRing: {
      width: "{form.field.focus.ring.width}",
      style: "{form.field.focus.ring.style}",
      color: "{form.field.focus.ring.color}",
      offset: "{form.field.focus.ring.offset}",
      shadow: "{form.field.focus.ring.shadow}"
    },
    transitionDuration: "{form.field.transition.duration}",
    sm: {
      fontSize: "{form.field.sm.font.size}",
      paddingX: "{form.field.sm.padding.x}",
      paddingY: "{form.field.sm.padding.y}"
    },
    lg: {
      fontSize: "{form.field.lg.font.size}",
      paddingX: "{form.field.lg.padding.x}",
      paddingY: "{form.field.lg.padding.y}"
    }
  }
};
var index$d = {
  root: {
    background: "{content.background}",
    borderColor: "{content.border.color}",
    color: "{content.color}",
    borderRadius: "{content.border.radius}",
    shadow: "{overlay.navigation.shadow}",
    transitionDuration: "{transition.duration}"
  },
  list: {
    padding: "{navigation.list.padding}",
    gap: "{navigation.list.gap}"
  },
  item: {
    focusBackground: "{navigation.item.focus.background}",
    activeBackground: "{navigation.item.active.background}",
    color: "{navigation.item.color}",
    focusColor: "{navigation.item.focus.color}",
    activeColor: "{navigation.item.active.color}",
    padding: "{navigation.item.padding}",
    borderRadius: "{navigation.item.border.radius}",
    gap: "{navigation.item.gap}",
    icon: {
      color: "{navigation.item.icon.color}",
      focusColor: "{navigation.item.icon.focus.color}",
      activeColor: "{navigation.item.icon.active.color}"
    }
  },
  submenu: {
    mobileIndent: "1rem"
  },
  submenuIcon: {
    size: "{navigation.submenu.icon.size}",
    color: "{navigation.submenu.icon.color}",
    focusColor: "{navigation.submenu.icon.focus.color}",
    activeColor: "{navigation.submenu.icon.active.color}"
  },
  separator: {
    borderColor: "{content.border.color}"
  }
};
var index$c = {
  event: {
    minHeight: "5rem"
  },
  horizontal: {
    eventContent: {
      padding: "1rem 0"
    }
  },
  vertical: {
    eventContent: {
      padding: "0 1rem"
    }
  },
  eventMarker: {
    size: "1.125rem",
    borderRadius: "50%",
    borderWidth: "2px",
    background: "{content.background}",
    borderColor: "{content.border.color}",
    content: {
      borderRadius: "50%",
      size: "0.375rem",
      background: "{primary.color}",
      insetShadow: "0px 0.5px 0px 0px rgba(0, 0, 0, 0.06), 0px 1px 1px 0px rgba(0, 0, 0, 0.12)"
    }
  },
  eventConnector: {
    color: "{content.border.color}",
    size: "2px"
  }
};
var index$b = {
  root: {
    width: "25rem",
    borderRadius: "{content.border.radius}",
    borderWidth: "1px",
    transitionDuration: "{transition.duration}"
  },
  icon: {
    size: "1.125rem"
  },
  content: {
    padding: "{overlay.popover.padding}",
    gap: "0.5rem"
  },
  text: {
    gap: "0.5rem"
  },
  summary: {
    fontWeight: "500",
    fontSize: "1rem"
  },
  detail: {
    fontWeight: "500",
    fontSize: "0.875rem"
  },
  closeButton: {
    width: "1.75rem",
    height: "1.75rem",
    borderRadius: "50%",
    focusRing: {
      width: "{focus.ring.width}",
      style: "{focus.ring.style}",
      offset: "{focus.ring.offset}"
    }
  },
  closeIcon: {
    size: "1rem"
  },
  colorScheme: {
    light: {
      blur: "1.5px",
      info: {
        background: "color-mix(in srgb, {blue.50}, transparent 5%)",
        borderColor: "{blue.200}",
        color: "{blue.600}",
        detailColor: "{surface.700}",
        shadow: "0px 4px 8px 0px color-mix(in srgb, {blue.500}, transparent 96%)",
        closeButton: {
          hoverBackground: "{blue.100}",
          focusRing: {
            color: "{blue.600}",
            shadow: "none"
          }
        }
      },
      success: {
        background: "color-mix(in srgb, {green.50}, transparent 5%)",
        borderColor: "{green.200}",
        color: "{green.600}",
        detailColor: "{surface.700}",
        shadow: "0px 4px 8px 0px color-mix(in srgb, {green.500}, transparent 96%)",
        closeButton: {
          hoverBackground: "{green.100}",
          focusRing: {
            color: "{green.600}",
            shadow: "none"
          }
        }
      },
      warn: {
        background: "color-mix(in srgb,{yellow.50}, transparent 5%)",
        borderColor: "{yellow.200}",
        color: "{yellow.600}",
        detailColor: "{surface.700}",
        shadow: "0px 4px 8px 0px color-mix(in srgb, {yellow.500}, transparent 96%)",
        closeButton: {
          hoverBackground: "{yellow.100}",
          focusRing: {
            color: "{yellow.600}",
            shadow: "none"
          }
        }
      },
      error: {
        background: "color-mix(in srgb, {red.50}, transparent 5%)",
        borderColor: "{red.200}",
        color: "{red.600}",
        detailColor: "{surface.700}",
        shadow: "0px 4px 8px 0px color-mix(in srgb, {red.500}, transparent 96%)",
        closeButton: {
          hoverBackground: "{red.100}",
          focusRing: {
            color: "{red.600}",
            shadow: "none"
          }
        }
      },
      secondary: {
        background: "{surface.100}",
        borderColor: "{surface.200}",
        color: "{surface.600}",
        detailColor: "{surface.700}",
        shadow: "0px 4px 8px 0px color-mix(in srgb, {surface.500}, transparent 96%)",
        closeButton: {
          hoverBackground: "{surface.200}",
          focusRing: {
            color: "{surface.600}",
            shadow: "none"
          }
        }
      },
      contrast: {
        background: "{surface.900}",
        borderColor: "{surface.950}",
        color: "{surface.50}",
        detailColor: "{surface.0}",
        shadow: "0px 4px 8px 0px color-mix(in srgb, {surface.950}, transparent 96%)",
        closeButton: {
          hoverBackground: "{surface.800}",
          focusRing: {
            color: "{surface.50}",
            shadow: "none"
          }
        }
      }
    },
    dark: {
      blur: "10px",
      info: {
        background: "color-mix(in srgb, {blue.500}, transparent 84%)",
        borderColor: "color-mix(in srgb, {blue.700}, transparent 64%)",
        color: "{blue.500}",
        detailColor: "{surface.0}",
        shadow: "0px 4px 8px 0px color-mix(in srgb, {blue.500}, transparent 96%)",
        closeButton: {
          hoverBackground: "rgba(255, 255, 255, 0.05)",
          focusRing: {
            color: "{blue.500}",
            shadow: "none"
          }
        }
      },
      success: {
        background: "color-mix(in srgb, {green.500}, transparent 84%)",
        borderColor: "color-mix(in srgb, {green.700}, transparent 64%)",
        color: "{green.500}",
        detailColor: "{surface.0}",
        shadow: "0px 4px 8px 0px color-mix(in srgb, {green.500}, transparent 96%)",
        closeButton: {
          hoverBackground: "rgba(255, 255, 255, 0.05)",
          focusRing: {
            color: "{green.500}",
            shadow: "none"
          }
        }
      },
      warn: {
        background: "color-mix(in srgb, {yellow.500}, transparent 84%)",
        borderColor: "color-mix(in srgb, {yellow.700}, transparent 64%)",
        color: "{yellow.500}",
        detailColor: "{surface.0}",
        shadow: "0px 4px 8px 0px color-mix(in srgb, {yellow.500}, transparent 96%)",
        closeButton: {
          hoverBackground: "rgba(255, 255, 255, 0.05)",
          focusRing: {
            color: "{yellow.500}",
            shadow: "none"
          }
        }
      },
      error: {
        background: "color-mix(in srgb, {red.500}, transparent 84%)",
        borderColor: "color-mix(in srgb, {red.700}, transparent 64%)",
        color: "{red.500}",
        detailColor: "{surface.0}",
        shadow: "0px 4px 8px 0px color-mix(in srgb, {red.500}, transparent 96%)",
        closeButton: {
          hoverBackground: "rgba(255, 255, 255, 0.05)",
          focusRing: {
            color: "{red.500}",
            shadow: "none"
          }
        }
      },
      secondary: {
        background: "{surface.800}",
        borderColor: "{surface.700}",
        color: "{surface.300}",
        detailColor: "{surface.0}",
        shadow: "0px 4px 8px 0px color-mix(in srgb, {surface.500}, transparent 96%)",
        closeButton: {
          hoverBackground: "{surface.700}",
          focusRing: {
            color: "{surface.300}",
            shadow: "none"
          }
        }
      },
      contrast: {
        background: "{surface.0}",
        borderColor: "{surface.100}",
        color: "{surface.950}",
        detailColor: "{surface.950}",
        shadow: "0px 4px 8px 0px color-mix(in srgb, {surface.950}, transparent 96%)",
        closeButton: {
          hoverBackground: "{surface.100}",
          focusRing: {
            color: "{surface.950}",
            shadow: "none"
          }
        }
      }
    }
  }
};
var index$a = {
  root: {
    padding: "0.5rem 1rem",
    borderRadius: "{content.border.radius}",
    gap: "0.5rem",
    fontWeight: "500",
    disabledBackground: "{form.field.disabled.background}",
    disabledBorderColor: "{form.field.disabled.background}",
    disabledColor: "{form.field.disabled.color}",
    invalidBorderColor: "{form.field.invalid.border.color}",
    focusRing: {
      width: "{focus.ring.width}",
      style: "{focus.ring.style}",
      color: "{focus.ring.color}",
      offset: "{focus.ring.offset}",
      shadow: "{focus.ring.shadow}"
    },
    transitionDuration: "{form.field.transition.duration}",
    sm: {
      fontSize: "{form.field.sm.font.size}",
      padding: "0.375rem 0.75rem"
    },
    lg: {
      fontSize: "{form.field.lg.font.size}",
      padding: "0.625rem 1.25rem"
    }
  },
  icon: {
    disabledColor: "{form.field.disabled.color}"
  },
  content: {
    left: "0.25rem",
    top: "0.25rem",
    checkedShadow: "0px 1px 2px 0px rgba(0, 0, 0, 0.02), 0px 1px 2px 0px rgba(0, 0, 0, 0.04)"
  },
  colorScheme: {
    light: {
      root: {
        background: "{surface.100}",
        checkedBackground: "{surface.100}",
        hoverBackground: "{surface.100}",
        borderColor: "{surface.100}",
        color: "{surface.500}",
        hoverColor: "{surface.700}",
        checkedColor: "{surface.900}",
        checkedBorderColor: "{surface.100}"
      },
      content: {
        checkedBackground: "{surface.0}"
      },
      icon: {
        color: "{surface.500}",
        hoverColor: "{surface.700}",
        checkedColor: "{surface.900}"
      }
    },
    dark: {
      root: {
        background: "{surface.950}",
        checkedBackground: "{surface.950}",
        hoverBackground: "{surface.950}",
        borderColor: "{surface.950}",
        color: "{surface.400}",
        hoverColor: "{surface.300}",
        checkedColor: "{surface.0}",
        checkedBorderColor: "{surface.950}"
      },
      content: {
        checkedBackground: "{surface.800}"
      },
      icon: {
        color: "{surface.400}",
        hoverColor: "{surface.300}",
        checkedColor: "{surface.0}"
      }
    }
  }
};
var index$9 = {
  root: {
    width: "2.5rem",
    height: "1.5rem",
    borderRadius: "30px",
    gap: "0.25rem",
    shadow: "{form.field.shadow}",
    focusRing: {
      width: "{focus.ring.width}",
      style: "{focus.ring.style}",
      color: "{focus.ring.color}",
      offset: "{focus.ring.offset}",
      shadow: "{focus.ring.shadow}"
    },
    borderWidth: "1px",
    borderColor: "transparent",
    hoverBorderColor: "transparent",
    checkedBorderColor: "transparent",
    checkedHoverBorderColor: "transparent",
    invalidBorderColor: "{form.field.invalid.border.color}",
    transitionDuration: "{form.field.transition.duration}",
    slideDuration: "0.2s"
  },
  handle: {
    borderRadius: "50%",
    size: "1rem"
  },
  colorScheme: {
    light: {
      root: {
        background: "{surface.300}",
        disabledBackground: "{form.field.disabled.background}",
        hoverBackground: "{surface.400}",
        checkedBackground: "{primary.color}",
        checkedHoverBackground: "{primary.hover.color}"
      },
      handle: {
        background: "{surface.0}",
        disabledBackground: "{form.field.disabled.color}",
        hoverBackground: "{surface.0}",
        checkedBackground: "{surface.0}",
        checkedHoverBackground: "{surface.0}",
        color: "{text.muted.color}",
        hoverColor: "{text.color}",
        checkedColor: "{primary.color}",
        checkedHoverColor: "{primary.hover.color}"
      }
    },
    dark: {
      root: {
        background: "{surface.700}",
        disabledBackground: "{surface.600}",
        hoverBackground: "{surface.600}",
        checkedBackground: "{primary.color}",
        checkedHoverBackground: "{primary.hover.color}"
      },
      handle: {
        background: "{surface.400}",
        disabledBackground: "{surface.900}",
        hoverBackground: "{surface.300}",
        checkedBackground: "{surface.900}",
        checkedHoverBackground: "{surface.900}",
        color: "{surface.900}",
        hoverColor: "{surface.800}",
        checkedColor: "{primary.color}",
        checkedHoverColor: "{primary.hover.color}"
      }
    }
  }
};
var index$8 = {
  root: {
    background: "{content.background}",
    borderColor: "{content.border.color}",
    borderRadius: "{content.border.radius}",
    color: "{content.color}",
    gap: "0.5rem",
    padding: "0.75rem"
  }
};
var index$7 = {
  root: {
    maxWidth: "12.5rem",
    gutter: "0.25rem",
    shadow: "{overlay.popover.shadow}",
    padding: "0.5rem 0.75rem",
    borderRadius: "{overlay.popover.border.radius}"
  },
  colorScheme: {
    light: {
      root: {
        background: "{surface.700}",
        color: "{surface.0}"
      }
    },
    dark: {
      root: {
        background: "{surface.700}",
        color: "{surface.0}"
      }
    }
  }
};
var index$6 = {
  root: {
    background: "{content.background}",
    color: "{content.color}",
    padding: "1rem",
    gap: "2px",
    indent: "1rem",
    transitionDuration: "{transition.duration}"
  },
  node: {
    padding: "0.25rem 0.5rem",
    borderRadius: "{content.border.radius}",
    hoverBackground: "{content.hover.background}",
    selectedBackground: "{highlight.background}",
    color: "{text.color}",
    hoverColor: "{text.hover.color}",
    selectedColor: "{highlight.color}",
    focusRing: {
      width: "{focus.ring.width}",
      style: "{focus.ring.style}",
      color: "{focus.ring.color}",
      offset: "-1px",
      shadow: "{focus.ring.shadow}"
    },
    gap: "0.25rem"
  },
  nodeIcon: {
    color: "{text.muted.color}",
    hoverColor: "{text.hover.muted.color}",
    selectedColor: "{highlight.color}"
  },
  nodeToggleButton: {
    borderRadius: "50%",
    size: "1.75rem",
    hoverBackground: "{content.hover.background}",
    selectedHoverBackground: "{content.background}",
    color: "{text.muted.color}",
    hoverColor: "{text.hover.muted.color}",
    selectedHoverColor: "{primary.color}",
    focusRing: {
      width: "{focus.ring.width}",
      style: "{focus.ring.style}",
      color: "{focus.ring.color}",
      offset: "{focus.ring.offset}",
      shadow: "{focus.ring.shadow}"
    }
  },
  loadingIcon: {
    size: "2rem"
  },
  filter: {
    margin: "0 0 0.5rem 0"
  }
};
var index$5 = {
  root: {
    background: "{form.field.background}",
    disabledBackground: "{form.field.disabled.background}",
    filledBackground: "{form.field.filled.background}",
    filledHoverBackground: "{form.field.filled.hover.background}",
    filledFocusBackground: "{form.field.filled.focus.background}",
    borderColor: "{form.field.border.color}",
    hoverBorderColor: "{form.field.hover.border.color}",
    focusBorderColor: "{form.field.focus.border.color}",
    invalidBorderColor: "{form.field.invalid.border.color}",
    color: "{form.field.color}",
    disabledColor: "{form.field.disabled.color}",
    placeholderColor: "{form.field.placeholder.color}",
    invalidPlaceholderColor: "{form.field.invalid.placeholder.color}",
    shadow: "{form.field.shadow}",
    paddingX: "{form.field.padding.x}",
    paddingY: "{form.field.padding.y}",
    borderRadius: "{form.field.border.radius}",
    focusRing: {
      width: "{form.field.focus.ring.width}",
      style: "{form.field.focus.ring.style}",
      color: "{form.field.focus.ring.color}",
      offset: "{form.field.focus.ring.offset}",
      shadow: "{form.field.focus.ring.shadow}"
    },
    transitionDuration: "{form.field.transition.duration}",
    sm: {
      fontSize: "{form.field.sm.font.size}",
      paddingX: "{form.field.sm.padding.x}",
      paddingY: "{form.field.sm.padding.y}"
    },
    lg: {
      fontSize: "{form.field.lg.font.size}",
      paddingX: "{form.field.lg.padding.x}",
      paddingY: "{form.field.lg.padding.y}"
    }
  },
  dropdown: {
    width: "2.5rem",
    color: "{form.field.icon.color}"
  },
  overlay: {
    background: "{overlay.select.background}",
    borderColor: "{overlay.select.border.color}",
    borderRadius: "{overlay.select.border.radius}",
    color: "{overlay.select.color}",
    shadow: "{overlay.select.shadow}"
  },
  tree: {
    padding: "{list.padding}"
  },
  clearIcon: {
    color: "{form.field.icon.color}"
  },
  emptyMessage: {
    padding: "{list.option.padding}"
  },
  chip: {
    borderRadius: "{border.radius.sm}"
  }
};
var index$4 = {
  root: {
    transitionDuration: "{transition.duration}"
  },
  header: {
    background: "{content.background}",
    borderColor: "{treetable.border.color}",
    color: "{content.color}",
    borderWidth: "0 0 1px 0",
    padding: "0.75rem 1rem"
  },
  headerCell: {
    background: "{content.background}",
    hoverBackground: "{content.hover.background}",
    selectedBackground: "{highlight.background}",
    borderColor: "{treetable.border.color}",
    color: "{content.color}",
    hoverColor: "{content.hover.color}",
    selectedColor: "{highlight.color}",
    gap: "0.5rem",
    padding: "0.75rem 1rem",
    focusRing: {
      width: "{focus.ring.width}",
      style: "{focus.ring.style}",
      color: "{focus.ring.color}",
      offset: "-1px",
      shadow: "{focus.ring.shadow}"
    }
  },
  columnTitle: {
    fontWeight: "600"
  },
  row: {
    background: "{content.background}",
    hoverBackground: "{content.hover.background}",
    selectedBackground: "{highlight.background}",
    color: "{content.color}",
    hoverColor: "{content.hover.color}",
    selectedColor: "{highlight.color}",
    focusRing: {
      width: "{focus.ring.width}",
      style: "{focus.ring.style}",
      color: "{focus.ring.color}",
      offset: "-1px",
      shadow: "{focus.ring.shadow}"
    }
  },
  bodyCell: {
    borderColor: "{treetable.border.color}",
    padding: "0.75rem 1rem",
    gap: "0.5rem"
  },
  footerCell: {
    background: "{content.background}",
    borderColor: "{treetable.border.color}",
    color: "{content.color}",
    padding: "0.75rem 1rem"
  },
  columnFooter: {
    fontWeight: "600"
  },
  footer: {
    background: "{content.background}",
    borderColor: "{treetable.border.color}",
    color: "{content.color}",
    borderWidth: "0 0 1px 0",
    padding: "0.75rem 1rem"
  },
  columnResizerWidth: "0.5rem",
  resizeIndicator: {
    width: "1px",
    color: "{primary.color}"
  },
  sortIcon: {
    color: "{text.muted.color}",
    hoverColor: "{text.hover.muted.color}",
    size: "0.875rem"
  },
  loadingIcon: {
    size: "2rem"
  },
  nodeToggleButton: {
    hoverBackground: "{content.hover.background}",
    selectedHoverBackground: "{content.background}",
    color: "{text.muted.color}",
    hoverColor: "{text.color}",
    selectedHoverColor: "{primary.color}",
    size: "1.75rem",
    borderRadius: "50%",
    focusRing: {
      width: "{focus.ring.width}",
      style: "{focus.ring.style}",
      color: "{focus.ring.color}",
      offset: "{focus.ring.offset}",
      shadow: "{focus.ring.shadow}"
    }
  },
  paginatorTop: {
    borderColor: "{content.border.color}",
    borderWidth: "0 0 1px 0"
  },
  paginatorBottom: {
    borderColor: "{content.border.color}",
    borderWidth: "0 0 1px 0"
  },
  colorScheme: {
    light: {
      root: {
        borderColor: "{content.border.color}"
      },
      bodyCell: {
        selectedBorderColor: "{primary.100}"
      }
    },
    dark: {
      root: {
        borderColor: "{surface.800}"
      },
      bodyCell: {
        selectedBorderColor: "{primary.900}"
      }
    }
  }
};
var index$3 = {
  loader: {
    mask: {
      background: "{content.background}",
      color: "{text.muted.color}"
    },
    icon: {
      size: "2rem"
    }
  }
};
function _typeof$7(o2) {
  "@babel/helpers - typeof";
  return _typeof$7 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o3) {
    return typeof o3;
  } : function(o3) {
    return o3 && "function" == typeof Symbol && o3.constructor === Symbol && o3 !== Symbol.prototype ? "symbol" : typeof o3;
  }, _typeof$7(o2);
}
__name(_typeof$7, "_typeof$7");
function ownKeys$a(e2, r2) {
  var t2 = Object.keys(e2);
  if (Object.getOwnPropertySymbols) {
    var o2 = Object.getOwnPropertySymbols(e2);
    r2 && (o2 = o2.filter(function(r3) {
      return Object.getOwnPropertyDescriptor(e2, r3).enumerable;
    })), t2.push.apply(t2, o2);
  }
  return t2;
}
__name(ownKeys$a, "ownKeys$a");
function _objectSpread$9(e2) {
  for (var r2 = 1; r2 < arguments.length; r2++) {
    var t2 = null != arguments[r2] ? arguments[r2] : {};
    r2 % 2 ? ownKeys$a(Object(t2), true).forEach(function(r3) {
      _defineProperty$9(e2, r3, t2[r3]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e2, Object.getOwnPropertyDescriptors(t2)) : ownKeys$a(Object(t2)).forEach(function(r3) {
      Object.defineProperty(e2, r3, Object.getOwnPropertyDescriptor(t2, r3));
    });
  }
  return e2;
}
__name(_objectSpread$9, "_objectSpread$9");
function _defineProperty$9(e2, r2, t2) {
  return (r2 = _toPropertyKey$6(r2)) in e2 ? Object.defineProperty(e2, r2, { value: t2, enumerable: true, configurable: true, writable: true }) : e2[r2] = t2, e2;
}
__name(_defineProperty$9, "_defineProperty$9");
function _toPropertyKey$6(t2) {
  var i2 = _toPrimitive$6(t2, "string");
  return "symbol" == _typeof$7(i2) ? i2 : i2 + "";
}
__name(_toPropertyKey$6, "_toPropertyKey$6");
function _toPrimitive$6(t2, r2) {
  if ("object" != _typeof$7(t2) || !t2) return t2;
  var e2 = t2[Symbol.toPrimitive];
  if (void 0 !== e2) {
    var i2 = e2.call(t2, r2 || "default");
    if ("object" != _typeof$7(i2)) return i2;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return ("string" === r2 ? String : Number)(t2);
}
__name(_toPrimitive$6, "_toPrimitive$6");
var index$2 = _objectSpread$9(_objectSpread$9({}, index$1n), {}, {
  components: {
    accordion: index$1r,
    autocomplete: index$1q,
    avatar: index$1p,
    badge: index$1o,
    blockui: index$1m,
    breadcrumb: index$1l,
    button: index$1k,
    datepicker: index$18,
    card: index$1j,
    carousel: index$1i,
    cascadeselect: index$1h,
    checkbox: index$1g,
    chip: index$1f,
    colorpicker: index$1e,
    confirmdialog: index$1d,
    confirmpopup: index$1c,
    contextmenu: index$1b,
    dataview: index$19,
    datatable: index$1a,
    dialog: index$17,
    divider: index$16,
    dock: index$15,
    drawer: index$14,
    editor: index$13,
    fieldset: index$12,
    fileupload: index$11,
    iftalabel: index$Z,
    floatlabel: index$10,
    galleria: index$$,
    iconfield: index$_,
    image: index$Y,
    imagecompare: index$X,
    inlinemessage: index$W,
    inplace: index$V,
    inputchips: index$U,
    inputgroup: index$T,
    inputnumber: index$S,
    inputotp: index$R,
    inputtext: index$Q,
    knob: index$P,
    listbox: index$O,
    megamenu: index$N,
    menu: index$M,
    menubar: index$L,
    message: index$K,
    metergroup: index$J,
    multiselect: index$I,
    orderlist: index$H,
    organizationchart: index$G,
    overlaybadge: index$F,
    popover: index$z,
    paginator: index$E,
    password: index$B,
    panel: index$D,
    panelmenu: index$C,
    picklist: index$A,
    progressbar: index$y,
    progressspinner: index$x,
    radiobutton: index$w,
    rating: index$v,
    scrollpanel: index$t,
    select: index$s,
    selectbutton: index$r,
    skeleton: index$q,
    slider: index$p,
    speeddial: index$o,
    splitter: index$m,
    splitbutton: index$n,
    stepper: index$l,
    steps: index$k,
    tabmenu: index$j,
    tabs: index$i,
    tabview: index$h,
    textarea: index$e,
    tieredmenu: index$d,
    tag: index$g,
    terminal: index$f,
    timeline: index$c,
    togglebutton: index$a,
    toggleswitch: index$9,
    tree: index$6,
    treeselect: index$5,
    treetable: index$4,
    toast: index$b,
    toolbar: index$8,
    virtualscroller: index$3
  },
  directives: {
    tooltip: index$7,
    ripple: index$u
  }
});
const DEBUG_BUILD$6 = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__;
const SDK_VERSION$2 = "8.48.0";
const GLOBAL_OBJ = globalThis;
function getGlobalSingleton(name2, creator, obj) {
  const gbl = obj || GLOBAL_OBJ;
  const __SENTRY__ = gbl.__SENTRY__ = gbl.__SENTRY__ || {};
  const versionedCarrier = __SENTRY__[SDK_VERSION$2] = __SENTRY__[SDK_VERSION$2] || {};
  return versionedCarrier[name2] || (versionedCarrier[name2] = creator());
}
__name(getGlobalSingleton, "getGlobalSingleton");
const DEBUG_BUILD$5 = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__;
const PREFIX$2 = "Sentry Logger ";
const CONSOLE_LEVELS$1 = [
  "debug",
  "info",
  "warn",
  "error",
  "log",
  "assert",
  "trace"
];
const originalConsoleMethods = {};
function consoleSandbox(callback) {
  if (!("console" in GLOBAL_OBJ)) {
    return callback();
  }
  const console2 = GLOBAL_OBJ.console;
  const wrappedFuncs = {};
  const wrappedLevels = Object.keys(originalConsoleMethods);
  wrappedLevels.forEach((level) => {
    const originalConsoleMethod = originalConsoleMethods[level];
    wrappedFuncs[level] = console2[level];
    console2[level] = originalConsoleMethod;
  });
  try {
    return callback();
  } finally {
    wrappedLevels.forEach((level) => {
      console2[level] = wrappedFuncs[level];
    });
  }
}
__name(consoleSandbox, "consoleSandbox");
function makeLogger() {
  let enabled = false;
  const logger2 = {
    enable: /* @__PURE__ */ __name(() => {
      enabled = true;
    }, "enable"),
    disable: /* @__PURE__ */ __name(() => {
      enabled = false;
    }, "disable"),
    isEnabled: /* @__PURE__ */ __name(() => enabled, "isEnabled")
  };
  if (DEBUG_BUILD$5) {
    CONSOLE_LEVELS$1.forEach((name2) => {
      logger2[name2] = (...args) => {
        if (enabled) {
          consoleSandbox(() => {
            GLOBAL_OBJ.console[name2](`${PREFIX$2}[${name2}]:`, ...args);
          });
        }
      };
    });
  } else {
    CONSOLE_LEVELS$1.forEach((name2) => {
      logger2[name2] = () => void 0;
    });
  }
  return logger2;
}
__name(makeLogger, "makeLogger");
const logger$5 = getGlobalSingleton("logger", makeLogger);
const STACKTRACE_FRAME_LIMIT = 50;
const UNKNOWN_FUNCTION = "?";
const WEBPACK_ERROR_REGEXP = /\(error: (.*)\)/;
const STRIP_FRAME_REGEXP = /captureMessage|captureException/;
function createStackParser(...parsers) {
  const sortedParsers = parsers.sort((a2, b2) => a2[0] - b2[0]).map((p2) => p2[1]);
  return (stack, skipFirstLines = 0, framesToPop = 0) => {
    const frames = [];
    const lines = stack.split("\n");
    for (let i2 = skipFirstLines; i2 < lines.length; i2++) {
      const line = lines[i2];
      if (line.length > 1024) {
        continue;
      }
      const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, "$1") : line;
      if (cleanedLine.match(/\S*Error: /)) {
        continue;
      }
      for (const parser of sortedParsers) {
        const frame = parser(cleanedLine);
        if (frame) {
          frames.push(frame);
          break;
        }
      }
      if (frames.length >= STACKTRACE_FRAME_LIMIT + framesToPop) {
        break;
      }
    }
    return stripSentryFramesAndReverse(frames.slice(framesToPop));
  };
}
__name(createStackParser, "createStackParser");
function stackParserFromStackParserOptions(stackParser) {
  if (Array.isArray(stackParser)) {
    return createStackParser(...stackParser);
  }
  return stackParser;
}
__name(stackParserFromStackParserOptions, "stackParserFromStackParserOptions");
function stripSentryFramesAndReverse(stack) {
  if (!stack.length) {
    return [];
  }
  const localStack = Array.from(stack);
  if (/sentryWrapped/.test(getLastStackFrame(localStack).function || "")) {
    localStack.pop();
  }
  localStack.reverse();
  if (STRIP_FRAME_REGEXP.test(getLastStackFrame(localStack).function || "")) {
    localStack.pop();
    if (STRIP_FRAME_REGEXP.test(getLastStackFrame(localStack).function || "")) {
      localStack.pop();
    }
  }
  return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map((frame) => ({
    ...frame,
    filename: frame.filename || getLastStackFrame(localStack).filename,
    function: frame.function || UNKNOWN_FUNCTION
  }));
}
__name(stripSentryFramesAndReverse, "stripSentryFramesAndReverse");
function getLastStackFrame(arr) {
  return arr[arr.length - 1] || {};
}
__name(getLastStackFrame, "getLastStackFrame");
const defaultFunctionName = "<anonymous>";
function getFunctionName(fn) {
  try {
    if (!fn || typeof fn !== "function") {
      return defaultFunctionName;
    }
    return fn.name || defaultFunctionName;
  } catch (e2) {
    return defaultFunctionName;
  }
}
__name(getFunctionName, "getFunctionName");
function getFramesFromEvent(event) {
  const exception = event.exception;
  if (exception) {
    const frames = [];
    try {
      exception.values.forEach((value) => {
        if (value.stacktrace.frames) {
          frames.push(...value.stacktrace.frames);
        }
      });
      return frames;
    } catch (_oO) {
      return void 0;
    }
  }
  return void 0;
}
__name(getFramesFromEvent, "getFramesFromEvent");
const handlers$4 = {};
const instrumented$1 = {};
function addHandler$1(type, handler5) {
  handlers$4[type] = handlers$4[type] || [];
  handlers$4[type].push(handler5);
}
__name(addHandler$1, "addHandler$1");
function resetInstrumentationHandlers() {
  Object.keys(handlers$4).forEach((key) => {
    handlers$4[key] = void 0;
  });
}
__name(resetInstrumentationHandlers, "resetInstrumentationHandlers");
function maybeInstrument(type, instrumentFn) {
  if (!instrumented$1[type]) {
    instrumented$1[type] = true;
    try {
      instrumentFn();
    } catch (e2) {
      DEBUG_BUILD$5 && logger$5.error(`Error while instrumenting ${type}`, e2);
    }
  }
}
__name(maybeInstrument, "maybeInstrument");
function triggerHandlers$1(type, data) {
  const typeHandlers = type && handlers$4[type];
  if (!typeHandlers) {
    return;
  }
  for (const handler5 of typeHandlers) {
    try {
      handler5(data);
    } catch (e2) {
      DEBUG_BUILD$5 && logger$5.error(
        `Error while triggering instrumentation handler.
Type: ${type}
Name: ${getFunctionName(handler5)}
Error:`,
        e2
      );
    }
  }
}
__name(triggerHandlers$1, "triggerHandlers$1");
let _oldOnErrorHandler = null;
function addGlobalErrorInstrumentationHandler(handler5) {
  const type = "error";
  addHandler$1(type, handler5);
  maybeInstrument(type, instrumentError);
}
__name(addGlobalErrorInstrumentationHandler, "addGlobalErrorInstrumentationHandler");
function instrumentError() {
  _oldOnErrorHandler = GLOBAL_OBJ.onerror;
  GLOBAL_OBJ.onerror = function(msg, url, line, column, error2) {
    const handlerData = {
      column,
      error: error2,
      line,
      msg,
      url
    };
    triggerHandlers$1("error", handlerData);
    if (_oldOnErrorHandler) {
      return _oldOnErrorHandler.apply(this, arguments);
    }
    return false;
  };
  GLOBAL_OBJ.onerror.__SENTRY_INSTRUMENTED__ = true;
}
__name(instrumentError, "instrumentError");
let _oldOnUnhandledRejectionHandler = null;
function addGlobalUnhandledRejectionInstrumentationHandler(handler5) {
  const type = "unhandledrejection";
  addHandler$1(type, handler5);
  maybeInstrument(type, instrumentUnhandledRejection);
}
__name(addGlobalUnhandledRejectionInstrumentationHandler, "addGlobalUnhandledRejectionInstrumentationHandler");
function instrumentUnhandledRejection() {
  _oldOnUnhandledRejectionHandler = GLOBAL_OBJ.onunhandledrejection;
  GLOBAL_OBJ.onunhandledrejection = function(e2) {
    const handlerData = e2;
    triggerHandlers$1("unhandledrejection", handlerData);
    if (_oldOnUnhandledRejectionHandler) {
      return _oldOnUnhandledRejectionHandler.apply(this, arguments);
    }
    return true;
  };
  GLOBAL_OBJ.onunhandledrejection.__SENTRY_INSTRUMENTED__ = true;
}
__name(instrumentUnhandledRejection, "instrumentUnhandledRejection");
function getMainCarrier() {
  getSentryCarrier(GLOBAL_OBJ);
  return GLOBAL_OBJ;
}
__name(getMainCarrier, "getMainCarrier");
function getSentryCarrier(carrier) {
  const __SENTRY__ = carrier.__SENTRY__ = carrier.__SENTRY__ || {};
  __SENTRY__.version = __SENTRY__.version || SDK_VERSION$2;
  return __SENTRY__[SDK_VERSION$2] = __SENTRY__[SDK_VERSION$2] || {};
}
__name(getSentryCarrier, "getSentryCarrier");
const objectToString$2 = Object.prototype.toString;
function isError(wat) {
  switch (objectToString$2.call(wat)) {
    case "[object Error]":
    case "[object Exception]":
    case "[object DOMException]":
    case "[object WebAssembly.Exception]":
      return true;
    default:
      return isInstanceOf(wat, Error);
  }
}
__name(isError, "isError");
function isBuiltin(wat, className) {
  return objectToString$2.call(wat) === `[object ${className}]`;
}
__name(isBuiltin, "isBuiltin");
function isErrorEvent$2(wat) {
  return isBuiltin(wat, "ErrorEvent");
}
__name(isErrorEvent$2, "isErrorEvent$2");
function isDOMError(wat) {
  return isBuiltin(wat, "DOMError");
}
__name(isDOMError, "isDOMError");
function isDOMException(wat) {
  return isBuiltin(wat, "DOMException");
}
__name(isDOMException, "isDOMException");
function isString$8(wat) {
  return isBuiltin(wat, "String");
}
__name(isString$8, "isString$8");
function isParameterizedString(wat) {
  return typeof wat === "object" && wat !== null && "__sentry_template_string__" in wat && "__sentry_template_values__" in wat;
}
__name(isParameterizedString, "isParameterizedString");
function isPrimitive(wat) {
  return wat === null || isParameterizedString(wat) || typeof wat !== "object" && typeof wat !== "function";
}
__name(isPrimitive, "isPrimitive");
function isPlainObject$3(wat) {
  return isBuiltin(wat, "Object");
}
__name(isPlainObject$3, "isPlainObject$3");
function isEvent(wat) {
  return typeof Event !== "undefined" && isInstanceOf(wat, Event);
}
__name(isEvent, "isEvent");
function isElement$3(wat) {
  return typeof Element !== "undefined" && isInstanceOf(wat, Element);
}
__name(isElement$3, "isElement$3");
function isRegExp$3(wat) {
  return isBuiltin(wat, "RegExp");
}
__name(isRegExp$3, "isRegExp$3");
function isThenable$1(wat) {
  return Boolean(wat && wat.then && typeof wat.then === "function");
}
__name(isThenable$1, "isThenable$1");
function isSyntheticEvent(wat) {
  return isPlainObject$3(wat) && "nativeEvent" in wat && "preventDefault" in wat && "stopPropagation" in wat;
}
__name(isSyntheticEvent, "isSyntheticEvent");
function isInstanceOf(wat, base2) {
  try {
    return wat instanceof base2;
  } catch (_e2) {
    return false;
  }
}
__name(isInstanceOf, "isInstanceOf");
function isVueViewModel(wat) {
  return !!(typeof wat === "object" && wat !== null && (wat.__isVue || wat._isVue));
}
__name(isVueViewModel, "isVueViewModel");
const WINDOW$8 = GLOBAL_OBJ;
const DEFAULT_MAX_STRING_LENGTH = 80;
function htmlTreeAsString(elem, options2 = {}) {
  if (!elem) {
    return "<unknown>";
  }
  try {
    let currentElem = elem;
    const MAX_TRAVERSE_HEIGHT = 5;
    const out = [];
    let height = 0;
    let len = 0;
    const separator = " > ";
    const sepLength = separator.length;
    let nextStr;
    const keyAttrs = Array.isArray(options2) ? options2 : options2.keyAttrs;
    const maxStringLength = !Array.isArray(options2) && options2.maxStringLength || DEFAULT_MAX_STRING_LENGTH;
    while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) {
      nextStr = _htmlElementAsString(currentElem, keyAttrs);
      if (nextStr === "html" || height > 1 && len + out.length * sepLength + nextStr.length >= maxStringLength) {
        break;
      }
      out.push(nextStr);
      len += nextStr.length;
      currentElem = currentElem.parentNode;
    }
    return out.reverse().join(separator);
  } catch (_oO) {
    return "<unknown>";
  }
}
__name(htmlTreeAsString, "htmlTreeAsString");
function _htmlElementAsString(el, keyAttrs) {
  const elem = el;
  const out = [];
  if (!elem || !elem.tagName) {
    return "";
  }
  if (WINDOW$8.HTMLElement) {
    if (elem instanceof HTMLElement && elem.dataset) {
      if (elem.dataset["sentryComponent"]) {
        return elem.dataset["sentryComponent"];
      }
      if (elem.dataset["sentryElement"]) {
        return elem.dataset["sentryElement"];
      }
    }
  }
  out.push(elem.tagName.toLowerCase());
  const keyAttrPairs = keyAttrs && keyAttrs.length ? keyAttrs.filter((keyAttr) => elem.getAttribute(keyAttr)).map((keyAttr) => [keyAttr, elem.getAttribute(keyAttr)]) : null;
  if (keyAttrPairs && keyAttrPairs.length) {
    keyAttrPairs.forEach((keyAttrPair) => {
      out.push(`[${keyAttrPair[0]}="${keyAttrPair[1]}"]`);
    });
  } else {
    if (elem.id) {
      out.push(`#${elem.id}`);
    }
    const className = elem.className;
    if (className && isString$8(className)) {
      const classes2 = className.split(/\s+/);
      for (const c2 of classes2) {
        out.push(`.${c2}`);
      }
    }
  }
  const allowedAttrs = ["aria-label", "type", "name", "title", "alt"];
  for (const k2 of allowedAttrs) {
    const attr = elem.getAttribute(k2);
    if (attr) {
      out.push(`[${k2}="${attr}"]`);
    }
  }
  return out.join("");
}
__name(_htmlElementAsString, "_htmlElementAsString");
function getLocationHref() {
  try {
    return WINDOW$8.document.location.href;
  } catch (oO) {
    return "";
  }
}
__name(getLocationHref, "getLocationHref");
function getDomElement(selector) {
  if (WINDOW$8.document && WINDOW$8.document.querySelector) {
    return WINDOW$8.document.querySelector(selector);
  }
  return null;
}
__name(getDomElement, "getDomElement");
function getComponentName(elem) {
  if (!WINDOW$8.HTMLElement) {
    return null;
  }
  let currentElem = elem;
  const MAX_TRAVERSE_HEIGHT = 5;
  for (let i2 = 0; i2 < MAX_TRAVERSE_HEIGHT; i2++) {
    if (!currentElem) {
      return null;
    }
    if (currentElem instanceof HTMLElement) {
      if (currentElem.dataset["sentryComponent"]) {
        return currentElem.dataset["sentryComponent"];
      }
      if (currentElem.dataset["sentryElement"]) {
        return currentElem.dataset["sentryElement"];
      }
    }
    currentElem = currentElem.parentNode;
  }
  return null;
}
__name(getComponentName, "getComponentName");
function truncate(str, max = 0) {
  if (typeof str !== "string" || max === 0) {
    return str;
  }
  return str.length <= max ? str : `${str.slice(0, max)}...`;
}
__name(truncate, "truncate");
function snipLine(line, colno) {
  let newLine = line;
  const lineLength = newLine.length;
  if (lineLength <= 150) {
    return newLine;
  }
  if (colno > lineLength) {
    colno = lineLength;
  }
  let start2 = Math.max(colno - 60, 0);
  if (start2 < 5) {
    start2 = 0;
  }
  let end = Math.min(start2 + 140, lineLength);
  if (end > lineLength - 5) {
    end = lineLength;
  }
  if (end === lineLength) {
    start2 = Math.max(end - 140, 0);
  }
  newLine = newLine.slice(start2, end);
  if (start2 > 0) {
    newLine = `'{snip} ${newLine}`;
  }
  if (end < lineLength) {
    newLine += " {snip}";
  }
  return newLine;
}
__name(snipLine, "snipLine");
function safeJoin(input, delimiter2) {
  if (!Array.isArray(input)) {
    return "";
  }
  const output = [];
  for (let i2 = 0; i2 < input.length; i2++) {
    const value = input[i2];
    try {
      if (isVueViewModel(value)) {
        output.push("[VueViewModel]");
      } else {
        output.push(String(value));
      }
    } catch (e2) {
      output.push("[value cannot be serialized]");
    }
  }
  return output.join(delimiter2);
}
__name(safeJoin, "safeJoin");
function isMatchingPattern(value, pattern, requireExactStringMatch = false) {
  if (!isString$8(value)) {
    return false;
  }
  if (isRegExp$3(pattern)) {
    return pattern.test(value);
  }
  if (isString$8(pattern)) {
    return requireExactStringMatch ? value === pattern : value.includes(pattern);
  }
  return false;
}
__name(isMatchingPattern, "isMatchingPattern");
function stringMatchesSomePattern(testString, patterns = [], requireExactStringMatch = false) {
  return patterns.some((pattern) => isMatchingPattern(testString, pattern, requireExactStringMatch));
}
__name(stringMatchesSomePattern, "stringMatchesSomePattern");
function fill(source, name2, replacementFactory) {
  if (!(name2 in source)) {
    return;
  }
  const original = source[name2];
  const wrapped = replacementFactory(original);
  if (typeof wrapped === "function") {
    markFunctionWrapped(wrapped, original);
  }
  try {
    source[name2] = wrapped;
  } catch (e2) {
    DEBUG_BUILD$5 && logger$5.log(`Failed to replace method "${name2}" in object`, source);
  }
}
__name(fill, "fill");
function addNonEnumerableProperty(obj, name2, value) {
  try {
    Object.defineProperty(obj, name2, {
      // enumerable: false, // the default, so we can save on bundle size by not explicitly setting it
      value,
      writable: true,
      configurable: true
    });
  } catch (o_O) {
    DEBUG_BUILD$5 && logger$5.log(`Failed to add non-enumerable property "${name2}" to object`, obj);
  }
}
__name(addNonEnumerableProperty, "addNonEnumerableProperty");
function markFunctionWrapped(wrapped, original) {
  try {
    const proto = original.prototype || {};
    wrapped.prototype = original.prototype = proto;
    addNonEnumerableProperty(wrapped, "__sentry_original__", original);
  } catch (o_O) {
  }
}
__name(markFunctionWrapped, "markFunctionWrapped");
function getOriginalFunction(func) {
  return func.__sentry_original__;
}
__name(getOriginalFunction, "getOriginalFunction");
function urlEncode(object) {
  return Object.entries(object).map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`).join("&");
}
__name(urlEncode, "urlEncode");
function convertToPlainObject(value) {
  if (isError(value)) {
    return {
      message: value.message,
      name: value.name,
      stack: value.stack,
      ...getOwnProperties(value)
    };
  } else if (isEvent(value)) {
    const newObj = {
      type: value.type,
      target: serializeEventTarget(value.target),
      currentTarget: serializeEventTarget(value.currentTarget),
      ...getOwnProperties(value)
    };
    if (typeof CustomEvent !== "undefined" && isInstanceOf(value, CustomEvent)) {
      newObj.detail = value.detail;
    }
    return newObj;
  } else {
    return value;
  }
}
__name(convertToPlainObject, "convertToPlainObject");
function serializeEventTarget(target) {
  try {
    return isElement$3(target) ? htmlTreeAsString(target) : Object.prototype.toString.call(target);
  } catch (_oO) {
    return "<unknown>";
  }
}
__name(serializeEventTarget, "serializeEventTarget");
function getOwnProperties(obj) {
  if (typeof obj === "object" && obj !== null) {
    const extractedProps = {};
    for (const property in obj) {
      if (Object.prototype.hasOwnProperty.call(obj, property)) {
        extractedProps[property] = obj[property];
      }
    }
    return extractedProps;
  } else {
    return {};
  }
}
__name(getOwnProperties, "getOwnProperties");
function extractExceptionKeysForMessage(exception, maxLength = 40) {
  const keys2 = Object.keys(convertToPlainObject(exception));
  keys2.sort();
  const firstKey = keys2[0];
  if (!firstKey) {
    return "[object has no keys]";
  }
  if (firstKey.length >= maxLength) {
    return truncate(firstKey, maxLength);
  }
  for (let includedKeys = keys2.length; includedKeys > 0; includedKeys--) {
    const serialized = keys2.slice(0, includedKeys).join(", ");
    if (serialized.length > maxLength) {
      continue;
    }
    if (includedKeys === keys2.length) {
      return serialized;
    }
    return truncate(serialized, maxLength);
  }
  return "";
}
__name(extractExceptionKeysForMessage, "extractExceptionKeysForMessage");
function dropUndefinedKeys(inputValue) {
  const memoizationMap = /* @__PURE__ */ new Map();
  return _dropUndefinedKeys(inputValue, memoizationMap);
}
__name(dropUndefinedKeys, "dropUndefinedKeys");
function _dropUndefinedKeys(inputValue, memoizationMap) {
  if (isPojo(inputValue)) {
    const memoVal = memoizationMap.get(inputValue);
    if (memoVal !== void 0) {
      return memoVal;
    }
    const returnValue = {};
    memoizationMap.set(inputValue, returnValue);
    for (const key of Object.getOwnPropertyNames(inputValue)) {
      if (typeof inputValue[key] !== "undefined") {
        returnValue[key] = _dropUndefinedKeys(inputValue[key], memoizationMap);
      }
    }
    return returnValue;
  }
  if (Array.isArray(inputValue)) {
    const memoVal = memoizationMap.get(inputValue);
    if (memoVal !== void 0) {
      return memoVal;
    }
    const returnValue = [];
    memoizationMap.set(inputValue, returnValue);
    inputValue.forEach((item) => {
      returnValue.push(_dropUndefinedKeys(item, memoizationMap));
    });
    return returnValue;
  }
  return inputValue;
}
__name(_dropUndefinedKeys, "_dropUndefinedKeys");
function isPojo(input) {
  if (!isPlainObject$3(input)) {
    return false;
  }
  try {
    const name2 = Object.getPrototypeOf(input).constructor.name;
    return !name2 || name2 === "Object";
  } catch (e2) {
    return true;
  }
}
__name(isPojo, "isPojo");
function objectify(wat) {
  let objectified;
  switch (true) {
    case wat == void 0:
      objectified = new String(wat);
      break;
    case (typeof wat === "symbol" || typeof wat === "bigint"):
      objectified = Object(wat);
      break;
    case isPrimitive(wat):
      objectified = new wat.constructor(wat);
      break;
    default:
      objectified = wat;
      break;
  }
  return objectified;
}
__name(objectify, "objectify");
const ONE_SECOND_IN_MS = 1e3;
function dateTimestampInSeconds() {
  return Date.now() / ONE_SECOND_IN_MS;
}
__name(dateTimestampInSeconds, "dateTimestampInSeconds");
function createUnixTimestampInSecondsFunc() {
  const { performance: performance2 } = GLOBAL_OBJ;
  if (!performance2 || !performance2.now) {
    return dateTimestampInSeconds;
  }
  const approxStartingTimeOrigin = Date.now() - performance2.now();
  const timeOrigin = performance2.timeOrigin == void 0 ? approxStartingTimeOrigin : performance2.timeOrigin;
  return () => {
    return (timeOrigin + performance2.now()) / ONE_SECOND_IN_MS;
  };
}
__name(createUnixTimestampInSecondsFunc, "createUnixTimestampInSecondsFunc");
const timestampInSeconds = createUnixTimestampInSecondsFunc();
let _browserPerformanceTimeOriginMode;
const browserPerformanceTimeOrigin = (() => {
  const { performance: performance2 } = GLOBAL_OBJ;
  if (!performance2 || !performance2.now) {
    _browserPerformanceTimeOriginMode = "none";
    return void 0;
  }
  const threshold = 3600 * 1e3;
  const performanceNow = performance2.now();
  const dateNow = Date.now();
  const timeOriginDelta = performance2.timeOrigin ? Math.abs(performance2.timeOrigin + performanceNow - dateNow) : threshold;
  const timeOriginIsReliable = timeOriginDelta < threshold;
  const navigationStart = performance2.timing && performance2.timing.navigationStart;
  const hasNavigationStart = typeof navigationStart === "number";
  const navigationStartDelta = hasNavigationStart ? Math.abs(navigationStart + performanceNow - dateNow) : threshold;
  const navigationStartIsReliable = navigationStartDelta < threshold;
  if (timeOriginIsReliable || navigationStartIsReliable) {
    if (timeOriginDelta <= navigationStartDelta) {
      _browserPerformanceTimeOriginMode = "timeOrigin";
      return performance2.timeOrigin;
    } else {
      _browserPerformanceTimeOriginMode = "navigationStart";
      return navigationStart;
    }
  }
  _browserPerformanceTimeOriginMode = "dateNow";
  return dateNow;
})();
function uuid4() {
  const gbl = GLOBAL_OBJ;
  const crypto2 = gbl.crypto || gbl.msCrypto;
  let getRandomByte = /* @__PURE__ */ __name(() => Math.random() * 16, "getRandomByte");
  try {
    if (crypto2 && crypto2.randomUUID) {
      return crypto2.randomUUID().replace(/-/g, "");
    }
    if (crypto2 && crypto2.getRandomValues) {
      getRandomByte = /* @__PURE__ */ __name(() => {
        const typedArray = new Uint8Array(1);
        crypto2.getRandomValues(typedArray);
        return typedArray[0];
      }, "getRandomByte");
    }
  } catch (_2) {
  }
  return ("10000000100040008000" + 1e11).replace(
    /[018]/g,
    (c2) => (
      // eslint-disable-next-line no-bitwise
      (c2 ^ (getRandomByte() & 15) >> c2 / 4).toString(16)
    )
  );
}
__name(uuid4, "uuid4");
function getFirstException(event) {
  return event.exception && event.exception.values ? event.exception.values[0] : void 0;
}
__name(getFirstException, "getFirstException");
function getEventDescription(event) {
  const { message, event_id: eventId } = event;
  if (message) {
    return message;
  }
  const firstException = getFirstException(event);
  if (firstException) {
    if (firstException.type && firstException.value) {
      return `${firstException.type}: ${firstException.value}`;
    }
    return firstException.type || firstException.value || eventId || "<unknown>";
  }
  return eventId || "<unknown>";
}
__name(getEventDescription, "getEventDescription");
function addExceptionTypeValue(event, value, type) {
  const exception = event.exception = event.exception || {};
  const values = exception.values = exception.values || [];
  const firstException = values[0] = values[0] || {};
  if (!firstException.value) {
    firstException.value = value || "";
  }
  if (!firstException.type) {
    firstException.type = type || "Error";
  }
}
__name(addExceptionTypeValue, "addExceptionTypeValue");
function addExceptionMechanism(event, newMechanism) {
  const firstException = getFirstException(event);
  if (!firstException) {
    return;
  }
  const defaultMechanism = { type: "generic", handled: true };
  const currentMechanism = firstException.mechanism;
  firstException.mechanism = { ...defaultMechanism, ...currentMechanism, ...newMechanism };
  if (newMechanism && "data" in newMechanism) {
    const mergedData = { ...currentMechanism && currentMechanism.data, ...newMechanism.data };
    firstException.mechanism.data = mergedData;
  }
}
__name(addExceptionMechanism, "addExceptionMechanism");
const SEMVER_REGEXP = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;
function _parseInt(input) {
  return parseInt(input || "", 10);
}
__name(_parseInt, "_parseInt");
function parseSemver(input) {
  const match2 = input.match(SEMVER_REGEXP) || [];
  const major = _parseInt(match2[1]);
  const minor = _parseInt(match2[2]);
  const patch2 = _parseInt(match2[3]);
  return {
    buildmetadata: match2[5],
    major: isNaN(major) ? void 0 : major,
    minor: isNaN(minor) ? void 0 : minor,
    patch: isNaN(patch2) ? void 0 : patch2,
    prerelease: match2[4]
  };
}
__name(parseSemver, "parseSemver");
function addContextToFrame(lines, frame, linesOfContext = 5) {
  if (frame.lineno === void 0) {
    return;
  }
  const maxLines = lines.length;
  const sourceLine = Math.max(Math.min(maxLines - 1, frame.lineno - 1), 0);
  frame.pre_context = lines.slice(Math.max(0, sourceLine - linesOfContext), sourceLine).map((line) => snipLine(line, 0));
  const lineIndex = Math.min(maxLines - 1, sourceLine);
  frame.context_line = snipLine(lines[lineIndex], frame.colno || 0);
  frame.post_context = lines.slice(Math.min(sourceLine + 1, maxLines), sourceLine + 1 + linesOfContext).map((line) => snipLine(line, 0));
}
__name(addContextToFrame, "addContextToFrame");
function checkOrSetAlreadyCaught(exception) {
  if (isAlreadyCaptured(exception)) {
    return true;
  }
  try {
    addNonEnumerableProperty(exception, "__sentry_captured__", true);
  } catch (err) {
  }
  return false;
}
__name(checkOrSetAlreadyCaught, "checkOrSetAlreadyCaught");
function isAlreadyCaptured(exception) {
  try {
    return exception.__sentry_captured__;
  } catch (e2) {
  }
}
__name(isAlreadyCaptured, "isAlreadyCaptured");
function arrayify(maybeArray) {
  return Array.isArray(maybeArray) ? maybeArray : [maybeArray];
}
__name(arrayify, "arrayify");
var States;
(function(States2) {
  const PENDING = 0;
  States2[States2["PENDING"] = PENDING] = "PENDING";
  const RESOLVED = 1;
  States2[States2["RESOLVED"] = RESOLVED] = "RESOLVED";
  const REJECTED = 2;
  States2[States2["REJECTED"] = REJECTED] = "REJECTED";
})(States || (States = {}));
function resolvedSyncPromise(value) {
  return new SyncPromise((resolve2) => {
    resolve2(value);
  });
}
__name(resolvedSyncPromise, "resolvedSyncPromise");
function rejectedSyncPromise(reason) {
  return new SyncPromise((_2, reject) => {
    reject(reason);
  });
}
__name(rejectedSyncPromise, "rejectedSyncPromise");
class SyncPromise {
  static {
    __name(this, "SyncPromise");
  }
  constructor(executor) {
    SyncPromise.prototype.__init.call(this);
    SyncPromise.prototype.__init2.call(this);
    SyncPromise.prototype.__init3.call(this);
    SyncPromise.prototype.__init4.call(this);
    this._state = States.PENDING;
    this._handlers = [];
    try {
      executor(this._resolve, this._reject);
    } catch (e2) {
      this._reject(e2);
    }
  }
  /** JSDoc */
  then(onfulfilled, onrejected) {
    return new SyncPromise((resolve2, reject) => {
      this._handlers.push([
        false,
        (result) => {
          if (!onfulfilled) {
            resolve2(result);
          } else {
            try {
              resolve2(onfulfilled(result));
            } catch (e2) {
              reject(e2);
            }
          }
        },
        (reason) => {
          if (!onrejected) {
            reject(reason);
          } else {
            try {
              resolve2(onrejected(reason));
            } catch (e2) {
              reject(e2);
            }
          }
        }
      ]);
      this._executeHandlers();
    });
  }
  /** JSDoc */
  catch(onrejected) {
    return this.then((val) => val, onrejected);
  }
  /** JSDoc */
  finally(onfinally) {
    return new SyncPromise((resolve2, reject) => {
      let val;
      let isRejected;
      return this.then(
        (value) => {
          isRejected = false;
          val = value;
          if (onfinally) {
            onfinally();
          }
        },
        (reason) => {
          isRejected = true;
          val = reason;
          if (onfinally) {
            onfinally();
          }
        }
      ).then(() => {
        if (isRejected) {
          reject(val);
          return;
        }
        resolve2(val);
      });
    });
  }
  /** JSDoc */
  __init() {
    this._resolve = (value) => {
      this._setResult(States.RESOLVED, value);
    };
  }
  /** JSDoc */
  __init2() {
    this._reject = (reason) => {
      this._setResult(States.REJECTED, reason);
    };
  }
  /** JSDoc */
  __init3() {
    this._setResult = (state, value) => {
      if (this._state !== States.PENDING) {
        return;
      }
      if (isThenable$1(value)) {
        void value.then(this._resolve, this._reject);
        return;
      }
      this._state = state;
      this._value = value;
      this._executeHandlers();
    };
  }
  /** JSDoc */
  __init4() {
    this._executeHandlers = () => {
      if (this._state === States.PENDING) {
        return;
      }
      const cachedHandlers = this._handlers.slice();
      this._handlers = [];
      cachedHandlers.forEach((handler5) => {
        if (handler5[0]) {
          return;
        }
        if (this._state === States.RESOLVED) {
          handler5[1](this._value);
        }
        if (this._state === States.REJECTED) {
          handler5[2](this._value);
        }
        handler5[0] = true;
      });
    };
  }
}
function makeSession$1(context) {
  const startingTime = timestampInSeconds();
  const session = {
    sid: uuid4(),
    init: true,
    timestamp: startingTime,
    started: startingTime,
    duration: 0,
    status: "ok",
    errors: 0,
    ignoreDuration: false,
    toJSON: /* @__PURE__ */ __name(() => sessionToJSON(session), "toJSON")
  };
  if (context) {
    updateSession(session, context);
  }
  return session;
}
__name(makeSession$1, "makeSession$1");
function updateSession(session, context = {}) {
  if (context.user) {
    if (!session.ipAddress && context.user.ip_address) {
      session.ipAddress = context.user.ip_address;
    }
    if (!session.did && !context.did) {
      session.did = context.user.id || context.user.email || context.user.username;
    }
  }
  session.timestamp = context.timestamp || timestampInSeconds();
  if (context.abnormal_mechanism) {
    session.abnormal_mechanism = context.abnormal_mechanism;
  }
  if (context.ignoreDuration) {
    session.ignoreDuration = context.ignoreDuration;
  }
  if (context.sid) {
    session.sid = context.sid.length === 32 ? context.sid : uuid4();
  }
  if (context.init !== void 0) {
    session.init = context.init;
  }
  if (!session.did && context.did) {
    session.did = `${context.did}`;
  }
  if (typeof context.started === "number") {
    session.started = context.started;
  }
  if (session.ignoreDuration) {
    session.duration = void 0;
  } else if (typeof context.duration === "number") {
    session.duration = context.duration;
  } else {
    const duration = session.timestamp - session.started;
    session.duration = duration >= 0 ? duration : 0;
  }
  if (context.release) {
    session.release = context.release;
  }
  if (context.environment) {
    session.environment = context.environment;
  }
  if (!session.ipAddress && context.ipAddress) {
    session.ipAddress = context.ipAddress;
  }
  if (!session.userAgent && context.userAgent) {
    session.userAgent = context.userAgent;
  }
  if (typeof context.errors === "number") {
    session.errors = context.errors;
  }
  if (context.status) {
    session.status = context.status;
  }
}
__name(updateSession, "updateSession");
function closeSession(session, status) {
  let context = {};
  if (status) {
    context = { status };
  } else if (session.status === "ok") {
    context = { status: "exited" };
  }
  updateSession(session, context);
}
__name(closeSession, "closeSession");
function sessionToJSON(session) {
  return dropUndefinedKeys({
    sid: `${session.sid}`,
    init: session.init,
    // Make sure that sec is converted to ms for date constructor
    started: new Date(session.started * 1e3).toISOString(),
    timestamp: new Date(session.timestamp * 1e3).toISOString(),
    status: session.status,
    errors: session.errors,
    did: typeof session.did === "number" || typeof session.did === "string" ? `${session.did}` : void 0,
    duration: session.duration,
    abnormal_mechanism: session.abnormal_mechanism,
    attrs: {
      release: session.release,
      environment: session.environment,
      ip_address: session.ipAddress,
      user_agent: session.userAgent
    }
  });
}
__name(sessionToJSON, "sessionToJSON");
function generatePropagationContext() {
  return {
    traceId: generateTraceId(),
    spanId: generateSpanId()
  };
}
__name(generatePropagationContext, "generatePropagationContext");
function generateTraceId() {
  return uuid4();
}
__name(generateTraceId, "generateTraceId");
function generateSpanId() {
  return uuid4().substring(16);
}
__name(generateSpanId, "generateSpanId");
function merge$2(initialObj, mergeObj, levels = 2) {
  if (!mergeObj || typeof mergeObj !== "object" || levels <= 0) {
    return mergeObj;
  }
  if (initialObj && mergeObj && Object.keys(mergeObj).length === 0) {
    return initialObj;
  }
  const output = { ...initialObj };
  for (const key in mergeObj) {
    if (Object.prototype.hasOwnProperty.call(mergeObj, key)) {
      output[key] = merge$2(output[key], mergeObj[key], levels - 1);
    }
  }
  return output;
}
__name(merge$2, "merge$2");
const SCOPE_SPAN_FIELD = "_sentrySpan";
function _setSpanForScope(scope, span) {
  if (span) {
    addNonEnumerableProperty(scope, SCOPE_SPAN_FIELD, span);
  } else {
    delete scope[SCOPE_SPAN_FIELD];
  }
}
__name(_setSpanForScope, "_setSpanForScope");
function _getSpanForScope(scope) {
  return scope[SCOPE_SPAN_FIELD];
}
__name(_getSpanForScope, "_getSpanForScope");
const DEFAULT_MAX_BREADCRUMBS = 100;
class ScopeClass {
  static {
    __name(this, "ScopeClass");
  }
  /** Flag if notifying is happening. */
  /** Callback for client to receive scope changes. */
  /** Callback list that will be called during event processing. */
  /** Array of breadcrumbs. */
  /** User */
  /** Tags */
  /** Extra */
  /** Contexts */
  /** Attachments */
  /** Propagation Context for distributed tracing */
  /**
   * A place to stash data which is needed at some point in the SDK's event processing pipeline but which shouldn't get
   * sent to Sentry
   */
  /** Fingerprint */
  /** Severity */
  /**
   * Transaction Name
   *
   * IMPORTANT: The transaction name on the scope has nothing to do with root spans/transaction objects.
   * It's purpose is to assign a transaction to the scope that's added to non-transaction events.
   */
  /** Session */
  /** Request Mode Session Status */
  // eslint-disable-next-line deprecation/deprecation
  /** The client on this scope */
  /** Contains the last event id of a captured event.  */
  // NOTE: Any field which gets added here should get added not only to the constructor but also to the `clone` method.
  constructor() {
    this._notifyingListeners = false;
    this._scopeListeners = [];
    this._eventProcessors = [];
    this._breadcrumbs = [];
    this._attachments = [];
    this._user = {};
    this._tags = {};
    this._extra = {};
    this._contexts = {};
    this._sdkProcessingMetadata = {};
    this._propagationContext = {
      traceId: generateTraceId(),
      spanId: generateSpanId()
    };
  }
  /**
   * @inheritDoc
   */
  clone() {
    const newScope = new ScopeClass();
    newScope._breadcrumbs = [...this._breadcrumbs];
    newScope._tags = { ...this._tags };
    newScope._extra = { ...this._extra };
    newScope._contexts = { ...this._contexts };
    if (this._contexts.flags) {
      newScope._contexts.flags = {
        values: [...this._contexts.flags.values]
      };
    }
    newScope._user = this._user;
    newScope._level = this._level;
    newScope._session = this._session;
    newScope._transactionName = this._transactionName;
    newScope._fingerprint = this._fingerprint;
    newScope._eventProcessors = [...this._eventProcessors];
    newScope._requestSession = this._requestSession;
    newScope._attachments = [...this._attachments];
    newScope._sdkProcessingMetadata = { ...this._sdkProcessingMetadata };
    newScope._propagationContext = { ...this._propagationContext };
    newScope._client = this._client;
    newScope._lastEventId = this._lastEventId;
    _setSpanForScope(newScope, _getSpanForScope(this));
    return newScope;
  }
  /**
   * @inheritDoc
   */
  setClient(client) {
    this._client = client;
  }
  /**
   * @inheritDoc
   */
  setLastEventId(lastEventId2) {
    this._lastEventId = lastEventId2;
  }
  /**
   * @inheritDoc
   */
  getClient() {
    return this._client;
  }
  /**
   * @inheritDoc
   */
  lastEventId() {
    return this._lastEventId;
  }
  /**
   * @inheritDoc
   */
  addScopeListener(callback) {
    this._scopeListeners.push(callback);
  }
  /**
   * @inheritDoc
   */
  addEventProcessor(callback) {
    this._eventProcessors.push(callback);
    return this;
  }
  /**
   * @inheritDoc
   */
  setUser(user) {
    this._user = user || {
      email: void 0,
      id: void 0,
      ip_address: void 0,
      username: void 0
    };
    if (this._session) {
      updateSession(this._session, { user });
    }
    this._notifyScopeListeners();
    return this;
  }
  /**
   * @inheritDoc
   */
  getUser() {
    return this._user;
  }
  /**
   * @inheritDoc
   */
  // eslint-disable-next-line deprecation/deprecation
  getRequestSession() {
    return this._requestSession;
  }
  /**
   * @inheritDoc
   */
  // eslint-disable-next-line deprecation/deprecation
  setRequestSession(requestSession) {
    this._requestSession = requestSession;
    return this;
  }
  /**
   * @inheritDoc
   */
  setTags(tags) {
    this._tags = {
      ...this._tags,
      ...tags
    };
    this._notifyScopeListeners();
    return this;
  }
  /**
   * @inheritDoc
   */
  setTag(key, value) {
    this._tags = { ...this._tags, [key]: value };
    this._notifyScopeListeners();
    return this;
  }
  /**
   * @inheritDoc
   */
  setExtras(extras) {
    this._extra = {
      ...this._extra,
      ...extras
    };
    this._notifyScopeListeners();
    return this;
  }
  /**
   * @inheritDoc
   */
  setExtra(key, extra) {
    this._extra = { ...this._extra, [key]: extra };
    this._notifyScopeListeners();
    return this;
  }
  /**
   * @inheritDoc
   */
  setFingerprint(fingerprint) {
    this._fingerprint = fingerprint;
    this._notifyScopeListeners();
    return this;
  }
  /**
   * @inheritDoc
   */
  setLevel(level) {
    this._level = level;
    this._notifyScopeListeners();
    return this;
  }
  /**
   * @inheritDoc
   */
  setTransactionName(name2) {
    this._transactionName = name2;
    this._notifyScopeListeners();
    return this;
  }
  /**
   * @inheritDoc
   */
  setContext(key, context) {
    if (context === null) {
      delete this._contexts[key];
    } else {
      this._contexts[key] = context;
    }
    this._notifyScopeListeners();
    return this;
  }
  /**
   * @inheritDoc
   */
  setSession(session) {
    if (!session) {
      delete this._session;
    } else {
      this._session = session;
    }
    this._notifyScopeListeners();
    return this;
  }
  /**
   * @inheritDoc
   */
  getSession() {
    return this._session;
  }
  /**
   * @inheritDoc
   */
  update(captureContext) {
    if (!captureContext) {
      return this;
    }
    const scopeToMerge = typeof captureContext === "function" ? captureContext(this) : captureContext;
    const [scopeInstance, requestSession] = scopeToMerge instanceof Scope ? (
      // eslint-disable-next-line deprecation/deprecation
      [scopeToMerge.getScopeData(), scopeToMerge.getRequestSession()]
    ) : isPlainObject$3(scopeToMerge) ? [captureContext, captureContext.requestSession] : [];
    const { tags, extra, user, contexts, level, fingerprint = [], propagationContext } = scopeInstance || {};
    this._tags = { ...this._tags, ...tags };
    this._extra = { ...this._extra, ...extra };
    this._contexts = { ...this._contexts, ...contexts };
    if (user && Object.keys(user).length) {
      this._user = user;
    }
    if (level) {
      this._level = level;
    }
    if (fingerprint.length) {
      this._fingerprint = fingerprint;
    }
    if (propagationContext) {
      this._propagationContext = propagationContext;
    }
    if (requestSession) {
      this._requestSession = requestSession;
    }
    return this;
  }
  /**
   * @inheritDoc
   */
  clear() {
    this._breadcrumbs = [];
    this._tags = {};
    this._extra = {};
    this._user = {};
    this._contexts = {};
    this._level = void 0;
    this._transactionName = void 0;
    this._fingerprint = void 0;
    this._requestSession = void 0;
    this._session = void 0;
    _setSpanForScope(this, void 0);
    this._attachments = [];
    this.setPropagationContext({ traceId: generateTraceId() });
    this._notifyScopeListeners();
    return this;
  }
  /**
   * @inheritDoc
   */
  addBreadcrumb(breadcrumb, maxBreadcrumbs) {
    const maxCrumbs = typeof maxBreadcrumbs === "number" ? maxBreadcrumbs : DEFAULT_MAX_BREADCRUMBS;
    if (maxCrumbs <= 0) {
      return this;
    }
    const mergedBreadcrumb = {
      timestamp: dateTimestampInSeconds(),
      ...breadcrumb
    };
    const breadcrumbs = this._breadcrumbs;
    breadcrumbs.push(mergedBreadcrumb);
    this._breadcrumbs = breadcrumbs.length > maxCrumbs ? breadcrumbs.slice(-maxCrumbs) : breadcrumbs;
    this._notifyScopeListeners();
    return this;
  }
  /**
   * @inheritDoc
   */
  getLastBreadcrumb() {
    return this._breadcrumbs[this._breadcrumbs.length - 1];
  }
  /**
   * @inheritDoc
   */
  clearBreadcrumbs() {
    this._breadcrumbs = [];
    this._notifyScopeListeners();
    return this;
  }
  /**
   * @inheritDoc
   */
  addAttachment(attachment) {
    this._attachments.push(attachment);
    return this;
  }
  /**
   * @inheritDoc
   */
  clearAttachments() {
    this._attachments = [];
    return this;
  }
  /** @inheritDoc */
  getScopeData() {
    return {
      breadcrumbs: this._breadcrumbs,
      attachments: this._attachments,
      contexts: this._contexts,
      tags: this._tags,
      extra: this._extra,
      user: this._user,
      level: this._level,
      fingerprint: this._fingerprint || [],
      eventProcessors: this._eventProcessors,
      propagationContext: this._propagationContext,
      sdkProcessingMetadata: this._sdkProcessingMetadata,
      transactionName: this._transactionName,
      span: _getSpanForScope(this)
    };
  }
  /**
   * @inheritDoc
   */
  setSDKProcessingMetadata(newData) {
    this._sdkProcessingMetadata = merge$2(this._sdkProcessingMetadata, newData, 2);
    return this;
  }
  /**
   * @inheritDoc
   */
  setPropagationContext(context) {
    this._propagationContext = {
      // eslint-disable-next-line deprecation/deprecation
      spanId: generateSpanId(),
      ...context
    };
    return this;
  }
  /**
   * @inheritDoc
   */
  getPropagationContext() {
    return this._propagationContext;
  }
  /**
   * @inheritDoc
   */
  captureException(exception, hint) {
    const eventId = hint && hint.event_id ? hint.event_id : uuid4();
    if (!this._client) {
      logger$5.warn("No client configured on scope - will not capture exception!");
      return eventId;
    }
    const syntheticException = new Error("Sentry syntheticException");
    this._client.captureException(
      exception,
      {
        originalException: exception,
        syntheticException,
        ...hint,
        event_id: eventId
      },
      this
    );
    return eventId;
  }
  /**
   * @inheritDoc
   */
  captureMessage(message, level, hint) {
    const eventId = hint && hint.event_id ? hint.event_id : uuid4();
    if (!this._client) {
      logger$5.warn("No client configured on scope - will not capture message!");
      return eventId;
    }
    const syntheticException = new Error(message);
    this._client.captureMessage(
      message,
      level,
      {
        originalException: message,
        syntheticException,
        ...hint,
        event_id: eventId
      },
      this
    );
    return eventId;
  }
  /**
   * @inheritDoc
   */
  captureEvent(event, hint) {
    const eventId = hint && hint.event_id ? hint.event_id : uuid4();
    if (!this._client) {
      logger$5.warn("No client configured on scope - will not capture event!");
      return eventId;
    }
    this._client.captureEvent(event, { ...hint, event_id: eventId }, this);
    return eventId;
  }
  /**
   * This will be called on every set call.
   */
  _notifyScopeListeners() {
    if (!this._notifyingListeners) {
      this._notifyingListeners = true;
      this._scopeListeners.forEach((callback) => {
        callback(this);
      });
      this._notifyingListeners = false;
    }
  }
}
const Scope = ScopeClass;
function getDefaultCurrentScope() {
  return getGlobalSingleton("defaultCurrentScope", () => new Scope());
}
__name(getDefaultCurrentScope, "getDefaultCurrentScope");
function getDefaultIsolationScope() {
  return getGlobalSingleton("defaultIsolationScope", () => new Scope());
}
__name(getDefaultIsolationScope, "getDefaultIsolationScope");
class AsyncContextStack {
  static {
    __name(this, "AsyncContextStack");
  }
  constructor(scope, isolationScope) {
    let assignedScope;
    if (!scope) {
      assignedScope = new Scope();
    } else {
      assignedScope = scope;
    }
    let assignedIsolationScope;
    if (!isolationScope) {
      assignedIsolationScope = new Scope();
    } else {
      assignedIsolationScope = isolationScope;
    }
    this._stack = [{ scope: assignedScope }];
    this._isolationScope = assignedIsolationScope;
  }
  /**
   * Fork a scope for the stack.
   */
  withScope(callback) {
    const scope = this._pushScope();
    let maybePromiseResult;
    try {
      maybePromiseResult = callback(scope);
    } catch (e2) {
      this._popScope();
      throw e2;
    }
    if (isThenable$1(maybePromiseResult)) {
      return maybePromiseResult.then(
        (res) => {
          this._popScope();
          return res;
        },
        (e2) => {
          this._popScope();
          throw e2;
        }
      );
    }
    this._popScope();
    return maybePromiseResult;
  }
  /**
   * Get the client of the stack.
   */
  getClient() {
    return this.getStackTop().client;
  }
  /**
   * Returns the scope of the top stack.
   */
  getScope() {
    return this.getStackTop().scope;
  }
  /**
   * Get the isolation scope for the stack.
   */
  getIsolationScope() {
    return this._isolationScope;
  }
  /**
   * Returns the topmost scope layer in the order domain > local > process.
   */
  getStackTop() {
    return this._stack[this._stack.length - 1];
  }
  /**
   * Push a scope to the stack.
   */
  _pushScope() {
    const scope = this.getScope().clone();
    this._stack.push({
      client: this.getClient(),
      scope
    });
    return scope;
  }
  /**
   * Pop a scope from the stack.
   */
  _popScope() {
    if (this._stack.length <= 1) return false;
    return !!this._stack.pop();
  }
}
function getAsyncContextStack() {
  const registry = getMainCarrier();
  const sentry = getSentryCarrier(registry);
  return sentry.stack = sentry.stack || new AsyncContextStack(getDefaultCurrentScope(), getDefaultIsolationScope());
}
__name(getAsyncContextStack, "getAsyncContextStack");
function withScope$1(callback) {
  return getAsyncContextStack().withScope(callback);
}
__name(withScope$1, "withScope$1");
function withSetScope(scope, callback) {
  const stack = getAsyncContextStack();
  return stack.withScope(() => {
    stack.getStackTop().scope = scope;
    return callback(scope);
  });
}
__name(withSetScope, "withSetScope");
function withIsolationScope$1(callback) {
  return getAsyncContextStack().withScope(() => {
    return callback(getAsyncContextStack().getIsolationScope());
  });
}
__name(withIsolationScope$1, "withIsolationScope$1");
function getStackAsyncContextStrategy() {
  return {
    withIsolationScope: withIsolationScope$1,
    withScope: withScope$1,
    withSetScope,
    withSetIsolationScope: /* @__PURE__ */ __name((_isolationScope, callback) => {
      return withIsolationScope$1(callback);
    }, "withSetIsolationScope"),
    getCurrentScope: /* @__PURE__ */ __name(() => getAsyncContextStack().getScope(), "getCurrentScope"),
    getIsolationScope: /* @__PURE__ */ __name(() => getAsyncContextStack().getIsolationScope(), "getIsolationScope")
  };
}
__name(getStackAsyncContextStrategy, "getStackAsyncContextStrategy");
function setAsyncContextStrategy(strategy) {
  const registry = getMainCarrier();
  const sentry = getSentryCarrier(registry);
  sentry.acs = strategy;
}
__name(setAsyncContextStrategy, "setAsyncContextStrategy");
function getAsyncContextStrategy(carrier) {
  const sentry = getSentryCarrier(carrier);
  if (sentry.acs) {
    return sentry.acs;
  }
  return getStackAsyncContextStrategy();
}
__name(getAsyncContextStrategy, "getAsyncContextStrategy");
function getCurrentScope() {
  const carrier = getMainCarrier();
  const acs = getAsyncContextStrategy(carrier);
  return acs.getCurrentScope();
}
__name(getCurrentScope, "getCurrentScope");
function getIsolationScope() {
  const carrier = getMainCarrier();
  const acs = getAsyncContextStrategy(carrier);
  return acs.getIsolationScope();
}
__name(getIsolationScope, "getIsolationScope");
function getGlobalScope$1() {
  return getGlobalSingleton("globalScope", () => new Scope());
}
__name(getGlobalScope$1, "getGlobalScope$1");
function withScope(...rest) {
  const carrier = getMainCarrier();
  const acs = getAsyncContextStrategy(carrier);
  if (rest.length === 2) {
    const [scope, callback] = rest;
    if (!scope) {
      return acs.withScope(callback);
    }
    return acs.withSetScope(scope, callback);
  }
  return acs.withScope(rest[0]);
}
__name(withScope, "withScope");
function withIsolationScope(...rest) {
  const carrier = getMainCarrier();
  const acs = getAsyncContextStrategy(carrier);
  if (rest.length === 2) {
    const [isolationScope, callback] = rest;
    if (!isolationScope) {
      return acs.withIsolationScope(callback);
    }
    return acs.withSetIsolationScope(isolationScope, callback);
  }
  return acs.withIsolationScope(rest[0]);
}
__name(withIsolationScope, "withIsolationScope");
function getClient() {
  return getCurrentScope().getClient();
}
__name(getClient, "getClient");
function getTraceContextFromScope(scope) {
  const propagationContext = scope.getPropagationContext();
  const { traceId, spanId, parentSpanId } = propagationContext;
  const traceContext = dropUndefinedKeys({
    trace_id: traceId,
    span_id: spanId,
    parent_span_id: parentSpanId
  });
  return traceContext;
}
__name(getTraceContextFromScope, "getTraceContextFromScope");
const METRICS_SPAN_FIELD = "_sentryMetrics";
function getMetricSummaryJsonForSpan(span) {
  const storage = span[METRICS_SPAN_FIELD];
  if (!storage) {
    return void 0;
  }
  const output = {};
  for (const [, [exportKey, summary]] of storage) {
    const arr = output[exportKey] || (output[exportKey] = []);
    arr.push(dropUndefinedKeys(summary));
  }
  return output;
}
__name(getMetricSummaryJsonForSpan, "getMetricSummaryJsonForSpan");
function updateMetricSummaryOnSpan(span, metricType, sanitizedName, value, unit, tags, bucketKey) {
  const existingStorage = span[METRICS_SPAN_FIELD];
  const storage = existingStorage || (span[METRICS_SPAN_FIELD] = /* @__PURE__ */ new Map());
  const exportKey = `${metricType}:${sanitizedName}@${unit}`;
  const bucketItem = storage.get(bucketKey);
  if (bucketItem) {
    const [, summary] = bucketItem;
    storage.set(bucketKey, [
      exportKey,
      {
        min: Math.min(summary.min, value),
        max: Math.max(summary.max, value),
        count: summary.count += 1,
        sum: summary.sum += value,
        tags: summary.tags
      }
    ]);
  } else {
    storage.set(bucketKey, [
      exportKey,
      {
        min: value,
        max: value,
        count: 1,
        sum: value,
        tags
      }
    ]);
  }
}
__name(updateMetricSummaryOnSpan, "updateMetricSummaryOnSpan");
const SEMANTIC_ATTRIBUTE_SENTRY_SOURCE = "sentry.source";
const SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE = "sentry.sample_rate";
const SEMANTIC_ATTRIBUTE_SENTRY_OP = "sentry.op";
const SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN = "sentry.origin";
const SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON = "sentry.idle_span_finish_reason";
const SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT = "sentry.measurement_unit";
const SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE = "sentry.measurement_value";
const SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME = "sentry.custom_span_name";
const SEMANTIC_ATTRIBUTE_PROFILE_ID = "sentry.profile_id";
const SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME = "sentry.exclusive_time";
const SEMANTIC_ATTRIBUTE_CACHE_HIT = "cache.hit";
const SEMANTIC_ATTRIBUTE_CACHE_KEY = "cache.key";
const SEMANTIC_ATTRIBUTE_CACHE_ITEM_SIZE = "cache.item_size";
const SEMANTIC_ATTRIBUTE_HTTP_REQUEST_METHOD = "http.request.method";
const SEMANTIC_ATTRIBUTE_URL_FULL = "url.full";
const SPAN_STATUS_UNSET = 0;
const SPAN_STATUS_OK = 1;
const SPAN_STATUS_ERROR = 2;
function getSpanStatusFromHttpCode(httpStatus) {
  if (httpStatus < 400 && httpStatus >= 100) {
    return { code: SPAN_STATUS_OK };
  }
  if (httpStatus >= 400 && httpStatus < 500) {
    switch (httpStatus) {
      case 401:
        return { code: SPAN_STATUS_ERROR, message: "unauthenticated" };
      case 403:
        return { code: SPAN_STATUS_ERROR, message: "permission_denied" };
      case 404:
        return { code: SPAN_STATUS_ERROR, message: "not_found" };
      case 409:
        return { code: SPAN_STATUS_ERROR, message: "already_exists" };
      case 413:
        return { code: SPAN_STATUS_ERROR, message: "failed_precondition" };
      case 429:
        return { code: SPAN_STATUS_ERROR, message: "resource_exhausted" };
      case 499:
        return { code: SPAN_STATUS_ERROR, message: "cancelled" };
      default:
        return { code: SPAN_STATUS_ERROR, message: "invalid_argument" };
    }
  }
  if (httpStatus >= 500 && httpStatus < 600) {
    switch (httpStatus) {
      case 501:
        return { code: SPAN_STATUS_ERROR, message: "unimplemented" };
      case 503:
        return { code: SPAN_STATUS_ERROR, message: "unavailable" };
      case 504:
        return { code: SPAN_STATUS_ERROR, message: "deadline_exceeded" };
      default:
        return { code: SPAN_STATUS_ERROR, message: "internal_error" };
    }
  }
  return { code: SPAN_STATUS_ERROR, message: "unknown_error" };
}
__name(getSpanStatusFromHttpCode, "getSpanStatusFromHttpCode");
function setHttpStatus(span, httpStatus) {
  span.setAttribute("http.response.status_code", httpStatus);
  const spanStatus = getSpanStatusFromHttpCode(httpStatus);
  if (spanStatus.message !== "unknown_error") {
    span.setStatus(spanStatus);
  }
}
__name(setHttpStatus, "setHttpStatus");
const BAGGAGE_HEADER_NAME = "baggage";
const SENTRY_BAGGAGE_KEY_PREFIX = "sentry-";
const SENTRY_BAGGAGE_KEY_PREFIX_REGEX = /^sentry-/;
const MAX_BAGGAGE_STRING_LENGTH = 8192;
function baggageHeaderToDynamicSamplingContext(baggageHeader) {
  const baggageObject = parseBaggageHeader(baggageHeader);
  if (!baggageObject) {
    return void 0;
  }
  const dynamicSamplingContext = Object.entries(baggageObject).reduce((acc, [key, value]) => {
    if (key.match(SENTRY_BAGGAGE_KEY_PREFIX_REGEX)) {
      const nonPrefixedKey = key.slice(SENTRY_BAGGAGE_KEY_PREFIX.length);
      acc[nonPrefixedKey] = value;
    }
    return acc;
  }, {});
  if (Object.keys(dynamicSamplingContext).length > 0) {
    return dynamicSamplingContext;
  } else {
    return void 0;
  }
}
__name(baggageHeaderToDynamicSamplingContext, "baggageHeaderToDynamicSamplingContext");
function dynamicSamplingContextToSentryBaggageHeader(dynamicSamplingContext) {
  if (!dynamicSamplingContext) {
    return void 0;
  }
  const sentryPrefixedDSC = Object.entries(dynamicSamplingContext).reduce(
    (acc, [dscKey, dscValue]) => {
      if (dscValue) {
        acc[`${SENTRY_BAGGAGE_KEY_PREFIX}${dscKey}`] = dscValue;
      }
      return acc;
    },
    {}
  );
  return objectToBaggageHeader(sentryPrefixedDSC);
}
__name(dynamicSamplingContextToSentryBaggageHeader, "dynamicSamplingContextToSentryBaggageHeader");
function parseBaggageHeader(baggageHeader) {
  if (!baggageHeader || !isString$8(baggageHeader) && !Array.isArray(baggageHeader)) {
    return void 0;
  }
  if (Array.isArray(baggageHeader)) {
    return baggageHeader.reduce((acc, curr) => {
      const currBaggageObject = baggageHeaderToObject(curr);
      Object.entries(currBaggageObject).forEach(([key, value]) => {
        acc[key] = value;
      });
      return acc;
    }, {});
  }
  return baggageHeaderToObject(baggageHeader);
}
__name(parseBaggageHeader, "parseBaggageHeader");
function baggageHeaderToObject(baggageHeader) {
  return baggageHeader.split(",").map((baggageEntry) => baggageEntry.split("=").map((keyOrValue) => decodeURIComponent(keyOrValue.trim()))).reduce((acc, [key, value]) => {
    if (key && value) {
      acc[key] = value;
    }
    return acc;
  }, {});
}
__name(baggageHeaderToObject, "baggageHeaderToObject");
function objectToBaggageHeader(object) {
  if (Object.keys(object).length === 0) {
    return void 0;
  }
  return Object.entries(object).reduce((baggageHeader, [objectKey, objectValue], currentIndex) => {
    const baggageEntry = `${encodeURIComponent(objectKey)}=${encodeURIComponent(objectValue)}`;
    const newBaggageHeader = currentIndex === 0 ? baggageEntry : `${baggageHeader},${baggageEntry}`;
    if (newBaggageHeader.length > MAX_BAGGAGE_STRING_LENGTH) {
      DEBUG_BUILD$5 && logger$5.warn(
        `Not adding key: ${objectKey} with val: ${objectValue} to baggage header due to exceeding baggage size limits.`
      );
      return baggageHeader;
    } else {
      return newBaggageHeader;
    }
  }, "");
}
__name(objectToBaggageHeader, "objectToBaggageHeader");
const TRACEPARENT_REGEXP = new RegExp(
  "^[ \\t]*([0-9a-f]{32})?-?([0-9a-f]{16})?-?([01])?[ \\t]*$"
  // whitespace
);
function extractTraceparentData(traceparent) {
  if (!traceparent) {
    return void 0;
  }
  const matches2 = traceparent.match(TRACEPARENT_REGEXP);
  if (!matches2) {
    return void 0;
  }
  let parentSampled;
  if (matches2[3] === "1") {
    parentSampled = true;
  } else if (matches2[3] === "0") {
    parentSampled = false;
  }
  return {
    traceId: matches2[1],
    parentSampled,
    parentSpanId: matches2[2]
  };
}
__name(extractTraceparentData, "extractTraceparentData");
function propagationContextFromHeaders(sentryTrace, baggage) {
  const traceparentData = extractTraceparentData(sentryTrace);
  const dynamicSamplingContext = baggageHeaderToDynamicSamplingContext(baggage);
  if (!traceparentData || !traceparentData.traceId) {
    return { traceId: generateTraceId(), spanId: generateSpanId() };
  }
  const { traceId, parentSpanId, parentSampled } = traceparentData;
  const virtualSpanId = generateSpanId();
  return {
    traceId,
    parentSpanId,
    spanId: virtualSpanId,
    sampled: parentSampled,
    dsc: dynamicSamplingContext || {}
    // If we have traceparent data but no DSC it means we are not head of trace and we must freeze it
  };
}
__name(propagationContextFromHeaders, "propagationContextFromHeaders");
function generateSentryTraceHeader(traceId = generateTraceId(), spanId = generateSpanId(), sampled) {
  let sampledString = "";
  if (sampled !== void 0) {
    sampledString = sampled ? "-1" : "-0";
  }
  return `${traceId}-${spanId}${sampledString}`;
}
__name(generateSentryTraceHeader, "generateSentryTraceHeader");
const TRACE_FLAG_NONE = 0;
const TRACE_FLAG_SAMPLED = 1;
let hasShownSpanDropWarning = false;
function spanToTransactionTraceContext(span) {
  const { spanId: span_id, traceId: trace_id } = span.spanContext();
  const { data, op, parent_span_id, status, origin: origin2 } = spanToJSON(span);
  return dropUndefinedKeys({
    parent_span_id,
    span_id,
    trace_id,
    data,
    op,
    status,
    origin: origin2
  });
}
__name(spanToTransactionTraceContext, "spanToTransactionTraceContext");
function spanToTraceContext(span) {
  const { spanId, traceId: trace_id, isRemote } = span.spanContext();
  const parent_span_id = isRemote ? spanId : spanToJSON(span).parent_span_id;
  const span_id = isRemote ? generateSpanId() : spanId;
  return dropUndefinedKeys({
    parent_span_id,
    span_id,
    trace_id
  });
}
__name(spanToTraceContext, "spanToTraceContext");
function spanToTraceHeader(span) {
  const { traceId, spanId } = span.spanContext();
  const sampled = spanIsSampled(span);
  return generateSentryTraceHeader(traceId, spanId, sampled);
}
__name(spanToTraceHeader, "spanToTraceHeader");
function spanTimeInputToSeconds(input) {
  if (typeof input === "number") {
    return ensureTimestampInSeconds(input);
  }
  if (Array.isArray(input)) {
    return input[0] + input[1] / 1e9;
  }
  if (input instanceof Date) {
    return ensureTimestampInSeconds(input.getTime());
  }
  return timestampInSeconds();
}
__name(spanTimeInputToSeconds, "spanTimeInputToSeconds");
function ensureTimestampInSeconds(timestamp2) {
  const isMs = timestamp2 > 9999999999;
  return isMs ? timestamp2 / 1e3 : timestamp2;
}
__name(ensureTimestampInSeconds, "ensureTimestampInSeconds");
function spanToJSON(span) {
  if (spanIsSentrySpan(span)) {
    return span.getSpanJSON();
  }
  try {
    const { spanId: span_id, traceId: trace_id } = span.spanContext();
    if (spanIsOpenTelemetrySdkTraceBaseSpan(span)) {
      const { attributes, startTime, name: name2, endTime, parentSpanId, status } = span;
      return dropUndefinedKeys({
        span_id,
        trace_id,
        data: attributes,
        description: name2,
        parent_span_id: parentSpanId,
        start_timestamp: spanTimeInputToSeconds(startTime),
        // This is [0,0] by default in OTEL, in which case we want to interpret this as no end time
        timestamp: spanTimeInputToSeconds(endTime) || void 0,
        status: getStatusMessage(status),
        op: attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP],
        origin: attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN],
        _metrics_summary: getMetricSummaryJsonForSpan(span)
      });
    }
    return {
      span_id,
      trace_id
    };
  } catch (e2) {
    return {};
  }
}
__name(spanToJSON, "spanToJSON");
function spanIsOpenTelemetrySdkTraceBaseSpan(span) {
  const castSpan = span;
  return !!castSpan.attributes && !!castSpan.startTime && !!castSpan.name && !!castSpan.endTime && !!castSpan.status;
}
__name(spanIsOpenTelemetrySdkTraceBaseSpan, "spanIsOpenTelemetrySdkTraceBaseSpan");
function spanIsSentrySpan(span) {
  return typeof span.getSpanJSON === "function";
}
__name(spanIsSentrySpan, "spanIsSentrySpan");
function spanIsSampled(span) {
  const { traceFlags } = span.spanContext();
  return traceFlags === TRACE_FLAG_SAMPLED;
}
__name(spanIsSampled, "spanIsSampled");
function getStatusMessage(status) {
  if (!status || status.code === SPAN_STATUS_UNSET) {
    return void 0;
  }
  if (status.code === SPAN_STATUS_OK) {
    return "ok";
  }
  return status.message || "unknown_error";
}
__name(getStatusMessage, "getStatusMessage");
const CHILD_SPANS_FIELD = "_sentryChildSpans";
const ROOT_SPAN_FIELD = "_sentryRootSpan";
function addChildSpanToSpan(span, childSpan) {
  const rootSpan = span[ROOT_SPAN_FIELD] || span;
  addNonEnumerableProperty(childSpan, ROOT_SPAN_FIELD, rootSpan);
  if (span[CHILD_SPANS_FIELD]) {
    span[CHILD_SPANS_FIELD].add(childSpan);
  } else {
    addNonEnumerableProperty(span, CHILD_SPANS_FIELD, /* @__PURE__ */ new Set([childSpan]));
  }
}
__name(addChildSpanToSpan, "addChildSpanToSpan");
function removeChildSpanFromSpan(span, childSpan) {
  if (span[CHILD_SPANS_FIELD]) {
    span[CHILD_SPANS_FIELD].delete(childSpan);
  }
}
__name(removeChildSpanFromSpan, "removeChildSpanFromSpan");
function getSpanDescendants(span) {
  const resultSet = /* @__PURE__ */ new Set();
  function addSpanChildren(span2) {
    if (resultSet.has(span2)) {
      return;
    } else if (spanIsSampled(span2)) {
      resultSet.add(span2);
      const childSpans = span2[CHILD_SPANS_FIELD] ? Array.from(span2[CHILD_SPANS_FIELD]) : [];
      for (const childSpan of childSpans) {
        addSpanChildren(childSpan);
      }
    }
  }
  __name(addSpanChildren, "addSpanChildren");
  addSpanChildren(span);
  return Array.from(resultSet);
}
__name(getSpanDescendants, "getSpanDescendants");
function getRootSpan(span) {
  return span[ROOT_SPAN_FIELD] || span;
}
__name(getRootSpan, "getRootSpan");
function getActiveSpan() {
  const carrier = getMainCarrier();
  const acs = getAsyncContextStrategy(carrier);
  if (acs.getActiveSpan) {
    return acs.getActiveSpan();
  }
  return _getSpanForScope(getCurrentScope());
}
__name(getActiveSpan, "getActiveSpan");
function updateMetricSummaryOnActiveSpan(metricType, sanitizedName, value, unit, tags, bucketKey) {
  const span = getActiveSpan();
  if (span) {
    updateMetricSummaryOnSpan(span, metricType, sanitizedName, value, unit, tags, bucketKey);
  }
}
__name(updateMetricSummaryOnActiveSpan, "updateMetricSummaryOnActiveSpan");
function showSpanDropWarning() {
  if (!hasShownSpanDropWarning) {
    consoleSandbox(() => {
      console.warn(
        "[Sentry] Deprecation warning: Returning null from `beforeSendSpan` will be disallowed from SDK version 9.0.0 onwards. The callback will only support mutating spans. To drop certain spans, configure the respective integrations directly."
      );
    });
    hasShownSpanDropWarning = true;
  }
}
__name(showSpanDropWarning, "showSpanDropWarning");
function updateSpanName(span, name2) {
  span.updateName(name2);
  span.setAttributes({
    [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: "custom",
    [SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME]: name2
  });
}
__name(updateSpanName, "updateSpanName");
let errorsInstrumented = false;
function registerSpanErrorInstrumentation() {
  if (errorsInstrumented) {
    return;
  }
  errorsInstrumented = true;
  addGlobalErrorInstrumentationHandler(errorCallback);
  addGlobalUnhandledRejectionInstrumentationHandler(errorCallback);
}
__name(registerSpanErrorInstrumentation, "registerSpanErrorInstrumentation");
function errorCallback() {
  const activeSpan = getActiveSpan();
  const rootSpan = activeSpan && getRootSpan(activeSpan);
  if (rootSpan) {
    const message = "internal_error";
    DEBUG_BUILD$6 && logger$5.log(`[Tracing] Root span: ${message} -> Global error occurred`);
    rootSpan.setStatus({ code: SPAN_STATUS_ERROR, message });
  }
}
__name(errorCallback, "errorCallback");
errorCallback.tag = "sentry_tracingErrorCallback";
const SCOPE_ON_START_SPAN_FIELD = "_sentryScope";
const ISOLATION_SCOPE_ON_START_SPAN_FIELD = "_sentryIsolationScope";
function setCapturedScopesOnSpan(span, scope, isolationScope) {
  if (span) {
    addNonEnumerableProperty(span, ISOLATION_SCOPE_ON_START_SPAN_FIELD, isolationScope);
    addNonEnumerableProperty(span, SCOPE_ON_START_SPAN_FIELD, scope);
  }
}
__name(setCapturedScopesOnSpan, "setCapturedScopesOnSpan");
function getCapturedScopesOnSpan(span) {
  return {
    scope: span[SCOPE_ON_START_SPAN_FIELD],
    isolationScope: span[ISOLATION_SCOPE_ON_START_SPAN_FIELD]
  };
}
__name(getCapturedScopesOnSpan, "getCapturedScopesOnSpan");
function addTracingExtensions() {
  registerSpanErrorInstrumentation();
}
__name(addTracingExtensions, "addTracingExtensions");
function hasTracingEnabled(maybeOptions) {
  if (typeof __SENTRY_TRACING__ === "boolean" && !__SENTRY_TRACING__) {
    return false;
  }
  const client = getClient();
  const options2 = maybeOptions || client && client.getOptions();
  return !!options2 && (options2.enableTracing || "tracesSampleRate" in options2 || "tracesSampler" in options2);
}
__name(hasTracingEnabled, "hasTracingEnabled");
class SentryNonRecordingSpan {
  static {
    __name(this, "SentryNonRecordingSpan");
  }
  constructor(spanContext = {}) {
    this._traceId = spanContext.traceId || generateTraceId();
    this._spanId = spanContext.spanId || generateSpanId();
  }
  /** @inheritdoc */
  spanContext() {
    return {
      spanId: this._spanId,
      traceId: this._traceId,
      traceFlags: TRACE_FLAG_NONE
    };
  }
  /** @inheritdoc */
  // eslint-disable-next-line @typescript-eslint/no-empty-function
  end(_timestamp) {
  }
  /** @inheritdoc */
  setAttribute(_key, _value) {
    return this;
  }
  /** @inheritdoc */
  setAttributes(_values) {
    return this;
  }
  /** @inheritdoc */
  setStatus(_status) {
    return this;
  }
  /** @inheritdoc */
  updateName(_name) {
    return this;
  }
  /** @inheritdoc */
  isRecording() {
    return false;
  }
  /** @inheritdoc */
  addEvent(_name, _attributesOrStartTime, _startTime) {
    return this;
  }
  /**
   * This should generally not be used,
   * but we need it for being compliant with the OTEL Span interface.
   *
   * @hidden
   * @internal
   */
  addLink(_link2) {
    return this;
  }
  /**
   * This should generally not be used,
   * but we need it for being compliant with the OTEL Span interface.
   *
   * @hidden
   * @internal
   */
  addLinks(_links) {
    return this;
  }
  /**
   * This should generally not be used,
   * but we need it for being compliant with the OTEL Span interface.
   *
   * @hidden
   * @internal
   */
  recordException(_exception, _time) {
  }
}
function handleCallbackErrors(fn, onError, onFinally = () => {
}) {
  let maybePromiseResult;
  try {
    maybePromiseResult = fn();
  } catch (e2) {
    onError(e2);
    onFinally();
    throw e2;
  }
  return maybeHandlePromiseRejection(maybePromiseResult, onError, onFinally);
}
__name(handleCallbackErrors, "handleCallbackErrors");
function maybeHandlePromiseRejection(value, onError, onFinally) {
  if (isThenable$1(value)) {
    return value.then(
      (res) => {
        onFinally();
        return res;
      },
      (e2) => {
        onError(e2);
        onFinally();
        throw e2;
      }
    );
  }
  onFinally();
  return value;
}
__name(maybeHandlePromiseRejection, "maybeHandlePromiseRejection");
const DEFAULT_ENVIRONMENT = "production";
const FROZEN_DSC_FIELD = "_frozenDsc";
function freezeDscOnSpan(span, dsc) {
  const spanWithMaybeDsc = span;
  addNonEnumerableProperty(spanWithMaybeDsc, FROZEN_DSC_FIELD, dsc);
}
__name(freezeDscOnSpan, "freezeDscOnSpan");
function getDynamicSamplingContextFromClient(trace_id, client) {
  const options2 = client.getOptions();
  const { publicKey: public_key } = client.getDsn() || {};
  const dsc = dropUndefinedKeys({
    environment: options2.environment || DEFAULT_ENVIRONMENT,
    release: options2.release,
    public_key,
    trace_id
  });
  client.emit("createDsc", dsc);
  return dsc;
}
__name(getDynamicSamplingContextFromClient, "getDynamicSamplingContextFromClient");
function getDynamicSamplingContextFromScope(client, scope) {
  const propagationContext = scope.getPropagationContext();
  return propagationContext.dsc || getDynamicSamplingContextFromClient(propagationContext.traceId, client);
}
__name(getDynamicSamplingContextFromScope, "getDynamicSamplingContextFromScope");
function getDynamicSamplingContextFromSpan(span) {
  const client = getClient();
  if (!client) {
    return {};
  }
  const rootSpan = getRootSpan(span);
  const frozenDsc = rootSpan[FROZEN_DSC_FIELD];
  if (frozenDsc) {
    return frozenDsc;
  }
  const traceState = rootSpan.spanContext().traceState;
  const traceStateDsc = traceState && traceState.get("sentry.dsc");
  const dscOnTraceState = traceStateDsc && baggageHeaderToDynamicSamplingContext(traceStateDsc);
  if (dscOnTraceState) {
    return dscOnTraceState;
  }
  const dsc = getDynamicSamplingContextFromClient(span.spanContext().traceId, client);
  const jsonSpan = spanToJSON(rootSpan);
  const attributes = jsonSpan.data || {};
  const maybeSampleRate = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE];
  if (maybeSampleRate != null) {
    dsc.sample_rate = `${maybeSampleRate}`;
  }
  const source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];
  const name2 = jsonSpan.description;
  if (source !== "url" && name2) {
    dsc.transaction = name2;
  }
  if (hasTracingEnabled()) {
    dsc.sampled = String(spanIsSampled(rootSpan));
  }
  client.emit("createDsc", dsc, rootSpan);
  return dsc;
}
__name(getDynamicSamplingContextFromSpan, "getDynamicSamplingContextFromSpan");
function spanToBaggageHeader(span) {
  const dsc = getDynamicSamplingContextFromSpan(span);
  return dynamicSamplingContextToSentryBaggageHeader(dsc);
}
__name(spanToBaggageHeader, "spanToBaggageHeader");
function logSpanStart(span) {
  if (!DEBUG_BUILD$6) return;
  const { description = "< unknown name >", op = "< unknown op >", parent_span_id: parentSpanId } = spanToJSON(span);
  const { spanId } = span.spanContext();
  const sampled = spanIsSampled(span);
  const rootSpan = getRootSpan(span);
  const isRootSpan = rootSpan === span;
  const header = `[Tracing] Starting ${sampled ? "sampled" : "unsampled"} ${isRootSpan ? "root " : ""}span`;
  const infoParts = [`op: ${op}`, `name: ${description}`, `ID: ${spanId}`];
  if (parentSpanId) {
    infoParts.push(`parent ID: ${parentSpanId}`);
  }
  if (!isRootSpan) {
    const { op: op2, description: description2 } = spanToJSON(rootSpan);
    infoParts.push(`root ID: ${rootSpan.spanContext().spanId}`);
    if (op2) {
      infoParts.push(`root op: ${op2}`);
    }
    if (description2) {
      infoParts.push(`root description: ${description2}`);
    }
  }
  logger$5.log(`${header}
  ${infoParts.join("\n  ")}`);
}
__name(logSpanStart, "logSpanStart");
function logSpanEnd(span) {
  if (!DEBUG_BUILD$6) return;
  const { description = "< unknown name >", op = "< unknown op >" } = spanToJSON(span);
  const { spanId } = span.spanContext();
  const rootSpan = getRootSpan(span);
  const isRootSpan = rootSpan === span;
  const msg = `[Tracing] Finishing "${op}" ${isRootSpan ? "root " : ""}span "${description}" with ID ${spanId}`;
  logger$5.log(msg);
}
__name(logSpanEnd, "logSpanEnd");
function parseSampleRate(sampleRate) {
  if (typeof sampleRate === "boolean") {
    return Number(sampleRate);
  }
  const rate = typeof sampleRate === "string" ? parseFloat(sampleRate) : sampleRate;
  if (typeof rate !== "number" || isNaN(rate) || rate < 0 || rate > 1) {
    DEBUG_BUILD$6 && logger$5.warn(
      `[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(
        sampleRate
      )} of type ${JSON.stringify(typeof sampleRate)}.`
    );
    return void 0;
  }
  return rate;
}
__name(parseSampleRate, "parseSampleRate");
function sampleSpan(options2, samplingContext) {
  if (!hasTracingEnabled(options2)) {
    return [false];
  }
  const normalizedRequest = getIsolationScope().getScopeData().sdkProcessingMetadata.normalizedRequest;
  const enhancedSamplingContext = {
    ...samplingContext,
    normalizedRequest: samplingContext.normalizedRequest || normalizedRequest
  };
  let sampleRate;
  if (typeof options2.tracesSampler === "function") {
    sampleRate = options2.tracesSampler(enhancedSamplingContext);
  } else if (enhancedSamplingContext.parentSampled !== void 0) {
    sampleRate = enhancedSamplingContext.parentSampled;
  } else if (typeof options2.tracesSampleRate !== "undefined") {
    sampleRate = options2.tracesSampleRate;
  } else {
    sampleRate = 1;
  }
  const parsedSampleRate = parseSampleRate(sampleRate);
  if (parsedSampleRate === void 0) {
    DEBUG_BUILD$6 && logger$5.warn("[Tracing] Discarding transaction because of invalid sample rate.");
    return [false];
  }
  if (!parsedSampleRate) {
    DEBUG_BUILD$6 && logger$5.log(
      `[Tracing] Discarding transaction because ${typeof options2.tracesSampler === "function" ? "tracesSampler returned 0 or false" : "a negative sampling decision was inherited or tracesSampleRate is set to 0"}`
    );
    return [false, parsedSampleRate];
  }
  const shouldSample = Math.random() < parsedSampleRate;
  if (!shouldSample) {
    DEBUG_BUILD$6 && logger$5.log(
      `[Tracing] Discarding transaction because it's not included in the random sample (sampling rate = ${Number(
        sampleRate
      )})`
    );
    return [false, parsedSampleRate];
  }
  return [true, parsedSampleRate];
}
__name(sampleSpan, "sampleSpan");
const DSN_REGEX = /^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)([\w.-]+)(?::(\d+))?\/(.+)/;
function isValidProtocol(protocol) {
  return protocol === "http" || protocol === "https";
}
__name(isValidProtocol, "isValidProtocol");
function dsnToString(dsn, withPassword = false) {
  const { host, path, pass, port, projectId, protocol, publicKey } = dsn;
  return `${protocol}://${publicKey}${withPassword && pass ? `:${pass}` : ""}@${host}${port ? `:${port}` : ""}/${path ? `${path}/` : path}${projectId}`;
}
__name(dsnToString, "dsnToString");
function dsnFromString(str) {
  const match2 = DSN_REGEX.exec(str);
  if (!match2) {
    consoleSandbox(() => {
      console.error(`Invalid Sentry Dsn: ${str}`);
    });
    return void 0;
  }
  const [protocol, publicKey, pass = "", host = "", port = "", lastPath = ""] = match2.slice(1);
  let path = "";
  let projectId = lastPath;
  const split2 = projectId.split("/");
  if (split2.length > 1) {
    path = split2.slice(0, -1).join("/");
    projectId = split2.pop();
  }
  if (projectId) {
    const projectMatch = projectId.match(/^\d+/);
    if (projectMatch) {
      projectId = projectMatch[0];
    }
  }
  return dsnFromComponents({ host, pass, path, projectId, port, protocol, publicKey });
}
__name(dsnFromString, "dsnFromString");
function dsnFromComponents(components) {
  return {
    protocol: components.protocol,
    publicKey: components.publicKey || "",
    pass: components.pass || "",
    host: components.host,
    port: components.port || "",
    path: components.path || "",
    projectId: components.projectId
  };
}
__name(dsnFromComponents, "dsnFromComponents");
function validateDsn(dsn) {
  if (!DEBUG_BUILD$5) {
    return true;
  }
  const { port, projectId, protocol } = dsn;
  const requiredComponents = ["protocol", "publicKey", "host", "projectId"];
  const hasMissingRequiredComponent = requiredComponents.find((component) => {
    if (!dsn[component]) {
      logger$5.error(`Invalid Sentry Dsn: ${component} missing`);
      return true;
    }
    return false;
  });
  if (hasMissingRequiredComponent) {
    return false;
  }
  if (!projectId.match(/^\d+$/)) {
    logger$5.error(`Invalid Sentry Dsn: Invalid projectId ${projectId}`);
    return false;
  }
  if (!isValidProtocol(protocol)) {
    logger$5.error(`Invalid Sentry Dsn: Invalid protocol ${protocol}`);
    return false;
  }
  if (port && isNaN(parseInt(port, 10))) {
    logger$5.error(`Invalid Sentry Dsn: Invalid port ${port}`);
    return false;
  }
  return true;
}
__name(validateDsn, "validateDsn");
function makeDsn(from2) {
  const components = typeof from2 === "string" ? dsnFromString(from2) : dsnFromComponents(from2);
  if (!components || !validateDsn(components)) {
    return void 0;
  }
  return components;
}
__name(makeDsn, "makeDsn");
function memoBuilder() {
  const hasWeakSet = typeof WeakSet === "function";
  const inner = hasWeakSet ? /* @__PURE__ */ new WeakSet() : [];
  function memoize(obj) {
    if (hasWeakSet) {
      if (inner.has(obj)) {
        return true;
      }
      inner.add(obj);
      return false;
    }
    for (let i2 = 0; i2 < inner.length; i2++) {
      const value = inner[i2];
      if (value === obj) {
        return true;
      }
    }
    inner.push(obj);
    return false;
  }
  __name(memoize, "memoize");
  function unmemoize(obj) {
    if (hasWeakSet) {
      inner.delete(obj);
    } else {
      for (let i2 = 0; i2 < inner.length; i2++) {
        if (inner[i2] === obj) {
          inner.splice(i2, 1);
          break;
        }
      }
    }
  }
  __name(unmemoize, "unmemoize");
  return [memoize, unmemoize];
}
__name(memoBuilder, "memoBuilder");
function normalize$2(input, depth = 100, maxProperties = Infinity) {
  try {
    return visit("", input, depth, maxProperties);
  } catch (err) {
    return { ERROR: `**non-serializable** (${err})` };
  }
}
__name(normalize$2, "normalize$2");
function normalizeToSize(object, depth = 3, maxSize = 100 * 1024) {
  const normalized = normalize$2(object, depth);
  if (jsonSize(normalized) > maxSize) {
    return normalizeToSize(object, depth - 1, maxSize);
  }
  return normalized;
}
__name(normalizeToSize, "normalizeToSize");
function visit(key, value, depth = Infinity, maxProperties = Infinity, memo = memoBuilder()) {
  const [memoize, unmemoize] = memo;
  if (value == null || // this matches null and undefined -> eqeq not eqeqeq
  ["boolean", "string"].includes(typeof value) || typeof value === "number" && Number.isFinite(value)) {
    return value;
  }
  const stringified = stringifyValue(key, value);
  if (!stringified.startsWith("[object ")) {
    return stringified;
  }
  if (value["__sentry_skip_normalization__"]) {
    return value;
  }
  const remainingDepth = typeof value["__sentry_override_normalization_depth__"] === "number" ? value["__sentry_override_normalization_depth__"] : depth;
  if (remainingDepth === 0) {
    return stringified.replace("object ", "");
  }
  if (memoize(value)) {
    return "[Circular ~]";
  }
  const valueWithToJSON = value;
  if (valueWithToJSON && typeof valueWithToJSON.toJSON === "function") {
    try {
      const jsonValue = valueWithToJSON.toJSON();
      return visit("", jsonValue, remainingDepth - 1, maxProperties, memo);
    } catch (err) {
    }
  }
  const normalized = Array.isArray(value) ? [] : {};
  let numAdded = 0;
  const visitable = convertToPlainObject(value);
  for (const visitKey in visitable) {
    if (!Object.prototype.hasOwnProperty.call(visitable, visitKey)) {
      continue;
    }
    if (numAdded >= maxProperties) {
      normalized[visitKey] = "[MaxProperties ~]";
      break;
    }
    const visitValue = visitable[visitKey];
    normalized[visitKey] = visit(visitKey, visitValue, remainingDepth - 1, maxProperties, memo);
    numAdded++;
  }
  unmemoize(value);
  return normalized;
}
__name(visit, "visit");
function stringifyValue(key, value) {
  try {
    if (key === "domain" && value && typeof value === "object" && value._events) {
      return "[Domain]";
    }
    if (key === "domainEmitter") {
      return "[DomainEmitter]";
    }
    if (typeof global !== "undefined" && value === global) {
      return "[Global]";
    }
    if (typeof window !== "undefined" && value === window) {
      return "[Window]";
    }
    if (typeof document !== "undefined" && value === document) {
      return "[Document]";
    }
    if (isVueViewModel(value)) {
      return "[VueViewModel]";
    }
    if (isSyntheticEvent(value)) {
      return "[SyntheticEvent]";
    }
    if (typeof value === "number" && !Number.isFinite(value)) {
      return `[${value}]`;
    }
    if (typeof value === "function") {
      return `[Function: ${getFunctionName(value)}]`;
    }
    if (typeof value === "symbol") {
      return `[${String(value)}]`;
    }
    if (typeof value === "bigint") {
      return `[BigInt: ${String(value)}]`;
    }
    const objName = getConstructorName(value);
    if (/^HTML(\w*)Element$/.test(objName)) {
      return `[HTMLElement: ${objName}]`;
    }
    return `[object ${objName}]`;
  } catch (err) {
    return `**non-serializable** (${err})`;
  }
}
__name(stringifyValue, "stringifyValue");
function getConstructorName(value) {
  const prototype2 = Object.getPrototypeOf(value);
  return prototype2 ? prototype2.constructor.name : "null prototype";
}
__name(getConstructorName, "getConstructorName");
function utf8Length(value) {
  return ~-encodeURI(value).split(/%..|./).length;
}
__name(utf8Length, "utf8Length");
function jsonSize(value) {
  return utf8Length(JSON.stringify(value));
}
__name(jsonSize, "jsonSize");
function normalizeUrlToBase(url, basePath2) {
  const escapedBase = basePath2.replace(/\\/g, "/").replace(/[|\\{}()[\]^$+*?.]/g, "\\$&");
  let newUrl = url;
  try {
    newUrl = decodeURI(url);
  } catch (_Oo) {
  }
  return newUrl.replace(/\\/g, "/").replace(/webpack:\/?/g, "").replace(new RegExp(`(file://)?/*${escapedBase}/*`, "ig"), "app:///");
}
__name(normalizeUrlToBase, "normalizeUrlToBase");
function createEnvelope(headers, items = []) {
  return [headers, items];
}
__name(createEnvelope, "createEnvelope");
function addItemToEnvelope(envelope, newItem) {
  const [headers, items] = envelope;
  return [headers, [...items, newItem]];
}
__name(addItemToEnvelope, "addItemToEnvelope");
function forEachEnvelopeItem(envelope, callback) {
  const envelopeItems = envelope[1];
  for (const envelopeItem of envelopeItems) {
    const envelopeItemType = envelopeItem[0].type;
    const result = callback(envelopeItem, envelopeItemType);
    if (result) {
      return true;
    }
  }
  return false;
}
__name(forEachEnvelopeItem, "forEachEnvelopeItem");
function envelopeContainsItemType(envelope, types) {
  return forEachEnvelopeItem(envelope, (_2, type) => types.includes(type));
}
__name(envelopeContainsItemType, "envelopeContainsItemType");
function encodeUTF8(input) {
  return GLOBAL_OBJ.__SENTRY__ && GLOBAL_OBJ.__SENTRY__.encodePolyfill ? GLOBAL_OBJ.__SENTRY__.encodePolyfill(input) : new TextEncoder().encode(input);
}
__name(encodeUTF8, "encodeUTF8");
function decodeUTF8(input) {
  return GLOBAL_OBJ.__SENTRY__ && GLOBAL_OBJ.__SENTRY__.decodePolyfill ? GLOBAL_OBJ.__SENTRY__.decodePolyfill(input) : new TextDecoder().decode(input);
}
__name(decodeUTF8, "decodeUTF8");
function serializeEnvelope(envelope) {
  const [envHeaders, items] = envelope;
  let parts2 = JSON.stringify(envHeaders);
  function append3(next) {
    if (typeof parts2 === "string") {
      parts2 = typeof next === "string" ? parts2 + next : [encodeUTF8(parts2), next];
    } else {
      parts2.push(typeof next === "string" ? encodeUTF8(next) : next);
    }
  }
  __name(append3, "append");
  for (const item of items) {
    const [itemHeaders, payload] = item;
    append3(`
${JSON.stringify(itemHeaders)}
`);
    if (typeof payload === "string" || payload instanceof Uint8Array) {
      append3(payload);
    } else {
      let stringifiedPayload;
      try {
        stringifiedPayload = JSON.stringify(payload);
      } catch (e2) {
        stringifiedPayload = JSON.stringify(normalize$2(payload));
      }
      append3(stringifiedPayload);
    }
  }
  return typeof parts2 === "string" ? parts2 : concatBuffers(parts2);
}
__name(serializeEnvelope, "serializeEnvelope");
function concatBuffers(buffers) {
  const totalLength = buffers.reduce((acc, buf) => acc + buf.length, 0);
  const merged = new Uint8Array(totalLength);
  let offset = 0;
  for (const buffer of buffers) {
    merged.set(buffer, offset);
    offset += buffer.length;
  }
  return merged;
}
__name(concatBuffers, "concatBuffers");
function parseEnvelope(env) {
  let buffer = typeof env === "string" ? encodeUTF8(env) : env;
  function readBinary(length) {
    const bin = buffer.subarray(0, length);
    buffer = buffer.subarray(length + 1);
    return bin;
  }
  __name(readBinary, "readBinary");
  function readJson2() {
    let i2 = buffer.indexOf(10);
    if (i2 < 0) {
      i2 = buffer.length;
    }
    return JSON.parse(decodeUTF8(readBinary(i2)));
  }
  __name(readJson2, "readJson");
  const envelopeHeader = readJson2();
  const items = [];
  while (buffer.length) {
    const itemHeader = readJson2();
    const binaryLength = typeof itemHeader.length === "number" ? itemHeader.length : void 0;
    items.push([itemHeader, binaryLength ? readBinary(binaryLength) : readJson2()]);
  }
  return [envelopeHeader, items];
}
__name(parseEnvelope, "parseEnvelope");
function createSpanEnvelopeItem(spanJson) {
  const spanHeaders = {
    type: "span"
  };
  return [spanHeaders, spanJson];
}
__name(createSpanEnvelopeItem, "createSpanEnvelopeItem");
function createAttachmentEnvelopeItem(attachment) {
  const buffer = typeof attachment.data === "string" ? encodeUTF8(attachment.data) : attachment.data;
  return [
    dropUndefinedKeys({
      type: "attachment",
      length: buffer.length,
      filename: attachment.filename,
      content_type: attachment.contentType,
      attachment_type: attachment.attachmentType
    }),
    buffer
  ];
}
__name(createAttachmentEnvelopeItem, "createAttachmentEnvelopeItem");
const ITEM_TYPE_TO_DATA_CATEGORY_MAP = {
  session: "session",
  sessions: "session",
  attachment: "attachment",
  transaction: "transaction",
  event: "error",
  client_report: "internal",
  user_report: "default",
  profile: "profile",
  profile_chunk: "profile",
  replay_event: "replay",
  replay_recording: "replay",
  check_in: "monitor",
  feedback: "feedback",
  span: "span",
  statsd: "metric_bucket",
  raw_security: "security"
};
function envelopeItemTypeToDataCategory(type) {
  return ITEM_TYPE_TO_DATA_CATEGORY_MAP[type];
}
__name(envelopeItemTypeToDataCategory, "envelopeItemTypeToDataCategory");
function getSdkMetadataForEnvelopeHeader(metadataOrEvent) {
  if (!metadataOrEvent || !metadataOrEvent.sdk) {
    return;
  }
  const { name: name2, version: version2 } = metadataOrEvent.sdk;
  return { name: name2, version: version2 };
}
__name(getSdkMetadataForEnvelopeHeader, "getSdkMetadataForEnvelopeHeader");
function createEventEnvelopeHeaders(event, sdkInfo, tunnel, dsn) {
  const dynamicSamplingContext = event.sdkProcessingMetadata && event.sdkProcessingMetadata.dynamicSamplingContext;
  return {
    event_id: event.event_id,
    sent_at: (/* @__PURE__ */ new Date()).toISOString(),
    ...sdkInfo && { sdk: sdkInfo },
    ...!!tunnel && dsn && { dsn: dsnToString(dsn) },
    ...dynamicSamplingContext && {
      trace: dropUndefinedKeys({ ...dynamicSamplingContext })
    }
  };
}
__name(createEventEnvelopeHeaders, "createEventEnvelopeHeaders");
function enhanceEventWithSdkInfo(event, sdkInfo) {
  if (!sdkInfo) {
    return event;
  }
  event.sdk = event.sdk || {};
  event.sdk.name = event.sdk.name || sdkInfo.name;
  event.sdk.version = event.sdk.version || sdkInfo.version;
  event.sdk.integrations = [...event.sdk.integrations || [], ...sdkInfo.integrations || []];
  event.sdk.packages = [...event.sdk.packages || [], ...sdkInfo.packages || []];
  return event;
}
__name(enhanceEventWithSdkInfo, "enhanceEventWithSdkInfo");
function createSessionEnvelope(session, dsn, metadata, tunnel) {
  const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata);
  const envelopeHeaders = {
    sent_at: (/* @__PURE__ */ new Date()).toISOString(),
    ...sdkInfo && { sdk: sdkInfo },
    ...!!tunnel && dsn && { dsn: dsnToString(dsn) }
  };
  const envelopeItem = "aggregates" in session ? [{ type: "sessions" }, session] : [{ type: "session" }, session.toJSON()];
  return createEnvelope(envelopeHeaders, [envelopeItem]);
}
__name(createSessionEnvelope, "createSessionEnvelope");
function createEventEnvelope(event, dsn, metadata, tunnel) {
  const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata);
  const eventType = event.type && event.type !== "replay_event" ? event.type : "event";
  enhanceEventWithSdkInfo(event, metadata && metadata.sdk);
  const envelopeHeaders = createEventEnvelopeHeaders(event, sdkInfo, tunnel, dsn);
  delete event.sdkProcessingMetadata;
  const eventItem = [{ type: eventType }, event];
  return createEnvelope(envelopeHeaders, [eventItem]);
}
__name(createEventEnvelope, "createEventEnvelope");
function createSpanEnvelope(spans, client) {
  function dscHasRequiredProps(dsc2) {
    return !!dsc2.trace_id && !!dsc2.public_key;
  }
  __name(dscHasRequiredProps, "dscHasRequiredProps");
  const dsc = getDynamicSamplingContextFromSpan(spans[0]);
  const dsn = client && client.getDsn();
  const tunnel = client && client.getOptions().tunnel;
  const headers = {
    sent_at: (/* @__PURE__ */ new Date()).toISOString(),
    ...dscHasRequiredProps(dsc) && { trace: dsc },
    ...!!tunnel && dsn && { dsn: dsnToString(dsn) }
  };
  const beforeSendSpan = client && client.getOptions().beforeSendSpan;
  const convertToSpanJSON = beforeSendSpan ? (span) => {
    const spanJson = beforeSendSpan(spanToJSON(span));
    if (!spanJson) {
      showSpanDropWarning();
    }
    return spanJson;
  } : (span) => spanToJSON(span);
  const items = [];
  for (const span of spans) {
    const spanJson = convertToSpanJSON(span);
    if (spanJson) {
      items.push(createSpanEnvelopeItem(spanJson));
    }
  }
  return createEnvelope(headers, items);
}
__name(createSpanEnvelope, "createSpanEnvelope");
function setMeasurement(name2, value, unit, activeSpan = getActiveSpan()) {
  const rootSpan = activeSpan && getRootSpan(activeSpan);
  if (rootSpan) {
    DEBUG_BUILD$6 && logger$5.log(`[Measurement] Setting measurement on root span: ${name2} = ${value} ${unit}`);
    rootSpan.addEvent(name2, {
      [SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE]: value,
      [SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT]: unit
    });
  }
}
__name(setMeasurement, "setMeasurement");
function timedEventsToMeasurements(events2) {
  if (!events2 || events2.length === 0) {
    return void 0;
  }
  const measurements = {};
  events2.forEach((event) => {
    const attributes = event.attributes || {};
    const unit = attributes[SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT];
    const value = attributes[SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE];
    if (typeof unit === "string" && typeof value === "number") {
      measurements[event.name] = { value, unit };
    }
  });
  return measurements;
}
__name(timedEventsToMeasurements, "timedEventsToMeasurements");
const MAX_SPAN_COUNT = 1e3;
class SentrySpan {
  static {
    __name(this, "SentrySpan");
  }
  /** Epoch timestamp in seconds when the span started. */
  /** Epoch timestamp in seconds when the span ended. */
  /** Internal keeper of the status */
  /** The timed events added to this span. */
  /** if true, treat span as a standalone span (not part of a transaction) */
  /**
   * You should never call the constructor manually, always use `Sentry.startSpan()`
   * or other span methods.
   * @internal
   * @hideconstructor
   * @hidden
   */
  constructor(spanContext = {}) {
    this._traceId = spanContext.traceId || generateTraceId();
    this._spanId = spanContext.spanId || generateSpanId();
    this._startTime = spanContext.startTimestamp || timestampInSeconds();
    this._attributes = {};
    this.setAttributes({
      [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "manual",
      [SEMANTIC_ATTRIBUTE_SENTRY_OP]: spanContext.op,
      ...spanContext.attributes
    });
    this._name = spanContext.name;
    if (spanContext.parentSpanId) {
      this._parentSpanId = spanContext.parentSpanId;
    }
    if ("sampled" in spanContext) {
      this._sampled = spanContext.sampled;
    }
    if (spanContext.endTimestamp) {
      this._endTime = spanContext.endTimestamp;
    }
    this._events = [];
    this._isStandaloneSpan = spanContext.isStandalone;
    if (this._endTime) {
      this._onSpanEnded();
    }
  }
  /**
   * This should generally not be used,
   * but it is needed for being compliant with the OTEL Span interface.
   *
   * @hidden
   * @internal
   */
  addLink(_link2) {
    return this;
  }
  /**
   * This should generally not be used,
   * but it is needed for being compliant with the OTEL Span interface.
   *
   * @hidden
   * @internal
   */
  addLinks(_links) {
    return this;
  }
  /**
   * This should generally not be used,
   * but it is needed for being compliant with the OTEL Span interface.
   *
   * @hidden
   * @internal
   */
  recordException(_exception, _time) {
  }
  /** @inheritdoc */
  spanContext() {
    const { _spanId: spanId, _traceId: traceId, _sampled: sampled } = this;
    return {
      spanId,
      traceId,
      traceFlags: sampled ? TRACE_FLAG_SAMPLED : TRACE_FLAG_NONE
    };
  }
  /** @inheritdoc */
  setAttribute(key, value) {
    if (value === void 0) {
      delete this._attributes[key];
    } else {
      this._attributes[key] = value;
    }
    return this;
  }
  /** @inheritdoc */
  setAttributes(attributes) {
    Object.keys(attributes).forEach((key) => this.setAttribute(key, attributes[key]));
    return this;
  }
  /**
   * This should generally not be used,
   * but we need it for browser tracing where we want to adjust the start time afterwards.
   * USE THIS WITH CAUTION!
   *
   * @hidden
   * @internal
   */
  updateStartTime(timeInput) {
    this._startTime = spanTimeInputToSeconds(timeInput);
  }
  /**
   * @inheritDoc
   */
  setStatus(value) {
    this._status = value;
    return this;
  }
  /**
   * @inheritDoc
   */
  updateName(name2) {
    this._name = name2;
    this.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, "custom");
    return this;
  }
  /** @inheritdoc */
  end(endTimestamp) {
    if (this._endTime) {
      return;
    }
    this._endTime = spanTimeInputToSeconds(endTimestamp);
    logSpanEnd(this);
    this._onSpanEnded();
  }
  /**
   * Get JSON representation of this span.
   *
   * @hidden
   * @internal This method is purely for internal purposes and should not be used outside
   * of SDK code. If you need to get a JSON representation of a span,
   * use `spanToJSON(span)` instead.
   */
  getSpanJSON() {
    return dropUndefinedKeys({
      data: this._attributes,
      description: this._name,
      op: this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP],
      parent_span_id: this._parentSpanId,
      span_id: this._spanId,
      start_timestamp: this._startTime,
      status: getStatusMessage(this._status),
      timestamp: this._endTime,
      trace_id: this._traceId,
      origin: this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN],
      _metrics_summary: getMetricSummaryJsonForSpan(this),
      profile_id: this._attributes[SEMANTIC_ATTRIBUTE_PROFILE_ID],
      exclusive_time: this._attributes[SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME],
      measurements: timedEventsToMeasurements(this._events),
      is_segment: this._isStandaloneSpan && getRootSpan(this) === this || void 0,
      segment_id: this._isStandaloneSpan ? getRootSpan(this).spanContext().spanId : void 0
    });
  }
  /** @inheritdoc */
  isRecording() {
    return !this._endTime && !!this._sampled;
  }
  /**
   * @inheritdoc
   */
  addEvent(name2, attributesOrStartTime, startTime) {
    DEBUG_BUILD$6 && logger$5.log("[Tracing] Adding an event to span:", name2);
    const time = isSpanTimeInput(attributesOrStartTime) ? attributesOrStartTime : startTime || timestampInSeconds();
    const attributes = isSpanTimeInput(attributesOrStartTime) ? {} : attributesOrStartTime || {};
    const event = {
      name: name2,
      time: spanTimeInputToSeconds(time),
      attributes
    };
    this._events.push(event);
    return this;
  }
  /**
   * This method should generally not be used,
   * but for now we need a way to publicly check if the `_isStandaloneSpan` flag is set.
   * USE THIS WITH CAUTION!
   * @internal
   * @hidden
   * @experimental
   */
  isStandaloneSpan() {
    return !!this._isStandaloneSpan;
  }
  /** Emit `spanEnd` when the span is ended. */
  _onSpanEnded() {
    const client = getClient();
    if (client) {
      client.emit("spanEnd", this);
    }
    const isSegmentSpan = this._isStandaloneSpan || this === getRootSpan(this);
    if (!isSegmentSpan) {
      return;
    }
    if (this._isStandaloneSpan) {
      if (this._sampled) {
        sendSpanEnvelope(createSpanEnvelope([this], client));
      } else {
        DEBUG_BUILD$6 && logger$5.log("[Tracing] Discarding standalone span because its trace was not chosen to be sampled.");
        if (client) {
          client.recordDroppedEvent("sample_rate", "span");
        }
      }
      return;
    }
    const transactionEvent = this._convertSpanToTransaction();
    if (transactionEvent) {
      const scope = getCapturedScopesOnSpan(this).scope || getCurrentScope();
      scope.captureEvent(transactionEvent);
    }
  }
  /**
   * Finish the transaction & prepare the event to send to Sentry.
   */
  _convertSpanToTransaction() {
    if (!isFullFinishedSpan(spanToJSON(this))) {
      return void 0;
    }
    if (!this._name) {
      DEBUG_BUILD$6 && logger$5.warn("Transaction has no name, falling back to `<unlabeled transaction>`.");
      this._name = "<unlabeled transaction>";
    }
    const { scope: capturedSpanScope, isolationScope: capturedSpanIsolationScope } = getCapturedScopesOnSpan(this);
    const scope = capturedSpanScope || getCurrentScope();
    const client = scope.getClient() || getClient();
    if (this._sampled !== true) {
      DEBUG_BUILD$6 && logger$5.log("[Tracing] Discarding transaction because its trace was not chosen to be sampled.");
      if (client) {
        client.recordDroppedEvent("sample_rate", "transaction");
      }
      return void 0;
    }
    const finishedSpans = getSpanDescendants(this).filter((span) => span !== this && !isStandaloneSpan(span));
    const spans = finishedSpans.map((span) => spanToJSON(span)).filter(isFullFinishedSpan);
    const source = this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];
    delete this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME];
    spans.forEach((span) => {
      span.data && delete span.data[SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME];
    });
    const transaction = {
      contexts: {
        trace: spanToTransactionTraceContext(this)
      },
      spans: (
        // spans.sort() mutates the array, but `spans` is already a copy so we can safely do this here
        // we do not use spans anymore after this point
        spans.length > MAX_SPAN_COUNT ? spans.sort((a2, b2) => a2.start_timestamp - b2.start_timestamp).slice(0, MAX_SPAN_COUNT) : spans
      ),
      start_timestamp: this._startTime,
      timestamp: this._endTime,
      transaction: this._name,
      type: "transaction",
      sdkProcessingMetadata: {
        capturedSpanScope,
        capturedSpanIsolationScope,
        ...dropUndefinedKeys({
          dynamicSamplingContext: getDynamicSamplingContextFromSpan(this)
        })
      },
      _metrics_summary: getMetricSummaryJsonForSpan(this),
      ...source && {
        transaction_info: {
          source
        }
      }
    };
    const measurements = timedEventsToMeasurements(this._events);
    const hasMeasurements = measurements && Object.keys(measurements).length;
    if (hasMeasurements) {
      DEBUG_BUILD$6 && logger$5.log(
        "[Measurements] Adding measurements to transaction event",
        JSON.stringify(measurements, void 0, 2)
      );
      transaction.measurements = measurements;
    }
    return transaction;
  }
}
function isSpanTimeInput(value) {
  return value && typeof value === "number" || value instanceof Date || Array.isArray(value);
}
__name(isSpanTimeInput, "isSpanTimeInput");
function isFullFinishedSpan(input) {
  return !!input.start_timestamp && !!input.timestamp && !!input.span_id && !!input.trace_id;
}
__name(isFullFinishedSpan, "isFullFinishedSpan");
function isStandaloneSpan(span) {
  return span instanceof SentrySpan && span.isStandaloneSpan();
}
__name(isStandaloneSpan, "isStandaloneSpan");
function sendSpanEnvelope(envelope) {
  const client = getClient();
  if (!client) {
    return;
  }
  const spanItems = envelope[1];
  if (!spanItems || spanItems.length === 0) {
    client.recordDroppedEvent("before_send", "span");
    return;
  }
  client.sendEnvelope(envelope);
}
__name(sendSpanEnvelope, "sendSpanEnvelope");
const SUPPRESS_TRACING_KEY = "__SENTRY_SUPPRESS_TRACING__";
function startSpan(options2, callback) {
  const acs = getAcs();
  if (acs.startSpan) {
    return acs.startSpan(options2, callback);
  }
  const spanArguments = parseSentrySpanArguments(options2);
  const { forceTransaction, parentSpan: customParentSpan } = options2;
  return withScope(options2.scope, () => {
    const wrapper = getActiveSpanWrapper(customParentSpan);
    return wrapper(() => {
      const scope = getCurrentScope();
      const parentSpan = getParentSpan(scope);
      const shouldSkipSpan = options2.onlyIfParent && !parentSpan;
      const activeSpan = shouldSkipSpan ? new SentryNonRecordingSpan() : createChildOrRootSpan({
        parentSpan,
        spanArguments,
        forceTransaction,
        scope
      });
      _setSpanForScope(scope, activeSpan);
      return handleCallbackErrors(
        () => callback(activeSpan),
        () => {
          const { status } = spanToJSON(activeSpan);
          if (activeSpan.isRecording() && (!status || status === "ok")) {
            activeSpan.setStatus({ code: SPAN_STATUS_ERROR, message: "internal_error" });
          }
        },
        () => activeSpan.end()
      );
    });
  });
}
__name(startSpan, "startSpan");
function startSpanManual(options2, callback) {
  const acs = getAcs();
  if (acs.startSpanManual) {
    return acs.startSpanManual(options2, callback);
  }
  const spanArguments = parseSentrySpanArguments(options2);
  const { forceTransaction, parentSpan: customParentSpan } = options2;
  return withScope(options2.scope, () => {
    const wrapper = getActiveSpanWrapper(customParentSpan);
    return wrapper(() => {
      const scope = getCurrentScope();
      const parentSpan = getParentSpan(scope);
      const shouldSkipSpan = options2.onlyIfParent && !parentSpan;
      const activeSpan = shouldSkipSpan ? new SentryNonRecordingSpan() : createChildOrRootSpan({
        parentSpan,
        spanArguments,
        forceTransaction,
        scope
      });
      _setSpanForScope(scope, activeSpan);
      function finishAndSetSpan() {
        activeSpan.end();
      }
      __name(finishAndSetSpan, "finishAndSetSpan");
      return handleCallbackErrors(
        () => callback(activeSpan, finishAndSetSpan),
        () => {
          const { status } = spanToJSON(activeSpan);
          if (activeSpan.isRecording() && (!status || status === "ok")) {
            activeSpan.setStatus({ code: SPAN_STATUS_ERROR, message: "internal_error" });
          }
        }
      );
    });
  });
}
__name(startSpanManual, "startSpanManual");
function startInactiveSpan(options2) {
  const acs = getAcs();
  if (acs.startInactiveSpan) {
    return acs.startInactiveSpan(options2);
  }
  const spanArguments = parseSentrySpanArguments(options2);
  const { forceTransaction, parentSpan: customParentSpan } = options2;
  const wrapper = options2.scope ? (callback) => withScope(options2.scope, callback) : customParentSpan !== void 0 ? (callback) => withActiveSpan(customParentSpan, callback) : (callback) => callback();
  return wrapper(() => {
    const scope = getCurrentScope();
    const parentSpan = getParentSpan(scope);
    const shouldSkipSpan = options2.onlyIfParent && !parentSpan;
    if (shouldSkipSpan) {
      return new SentryNonRecordingSpan();
    }
    return createChildOrRootSpan({
      parentSpan,
      spanArguments,
      forceTransaction,
      scope
    });
  });
}
__name(startInactiveSpan, "startInactiveSpan");
const continueTrace = /* @__PURE__ */ __name((options2, callback) => {
  const carrier = getMainCarrier();
  const acs = getAsyncContextStrategy(carrier);
  if (acs.continueTrace) {
    return acs.continueTrace(options2, callback);
  }
  const { sentryTrace, baggage } = options2;
  return withScope((scope) => {
    const propagationContext = propagationContextFromHeaders(sentryTrace, baggage);
    scope.setPropagationContext(propagationContext);
    return callback();
  });
}, "continueTrace");
function withActiveSpan(span, callback) {
  const acs = getAcs();
  if (acs.withActiveSpan) {
    return acs.withActiveSpan(span, callback);
  }
  return withScope((scope) => {
    _setSpanForScope(scope, span || void 0);
    return callback(scope);
  });
}
__name(withActiveSpan, "withActiveSpan");
function suppressTracing(callback) {
  const acs = getAcs();
  if (acs.suppressTracing) {
    return acs.suppressTracing(callback);
  }
  return withScope((scope) => {
    scope.setSDKProcessingMetadata({ [SUPPRESS_TRACING_KEY]: true });
    return callback();
  });
}
__name(suppressTracing, "suppressTracing");
function startNewTrace(callback) {
  return withScope((scope) => {
    scope.setPropagationContext({ traceId: generateTraceId() });
    DEBUG_BUILD$6 && logger$5.info(`Starting a new trace with id ${scope.getPropagationContext().traceId}`);
    return withActiveSpan(null, callback);
  });
}
__name(startNewTrace, "startNewTrace");
function createChildOrRootSpan({
  parentSpan,
  spanArguments,
  forceTransaction,
  scope
}) {
  if (!hasTracingEnabled()) {
    return new SentryNonRecordingSpan();
  }
  const isolationScope = getIsolationScope();
  let span;
  if (parentSpan && !forceTransaction) {
    span = _startChildSpan(parentSpan, scope, spanArguments);
    addChildSpanToSpan(parentSpan, span);
  } else if (parentSpan) {
    const dsc = getDynamicSamplingContextFromSpan(parentSpan);
    const { traceId, spanId: parentSpanId } = parentSpan.spanContext();
    const parentSampled = spanIsSampled(parentSpan);
    span = _startRootSpan(
      {
        traceId,
        parentSpanId,
        ...spanArguments
      },
      scope,
      parentSampled
    );
    freezeDscOnSpan(span, dsc);
  } else {
    const {
      traceId,
      dsc,
      parentSpanId,
      sampled: parentSampled
    } = {
      ...isolationScope.getPropagationContext(),
      ...scope.getPropagationContext()
    };
    span = _startRootSpan(
      {
        traceId,
        parentSpanId,
        ...spanArguments
      },
      scope,
      parentSampled
    );
    if (dsc) {
      freezeDscOnSpan(span, dsc);
    }
  }
  logSpanStart(span);
  setCapturedScopesOnSpan(span, scope, isolationScope);
  return span;
}
__name(createChildOrRootSpan, "createChildOrRootSpan");
function parseSentrySpanArguments(options2) {
  const exp = options2.experimental || {};
  const initialCtx = {
    isStandalone: exp.standalone,
    ...options2
  };
  if (options2.startTime) {
    const ctx = { ...initialCtx };
    ctx.startTimestamp = spanTimeInputToSeconds(options2.startTime);
    delete ctx.startTime;
    return ctx;
  }
  return initialCtx;
}
__name(parseSentrySpanArguments, "parseSentrySpanArguments");
function getAcs() {
  const carrier = getMainCarrier();
  return getAsyncContextStrategy(carrier);
}
__name(getAcs, "getAcs");
function _startRootSpan(spanArguments, scope, parentSampled) {
  const client = getClient();
  const options2 = client && client.getOptions() || {};
  const { name: name2 = "", attributes } = spanArguments;
  const [sampled, sampleRate] = scope.getScopeData().sdkProcessingMetadata[SUPPRESS_TRACING_KEY] ? [false] : sampleSpan(options2, {
    name: name2,
    parentSampled,
    attributes,
    transactionContext: {
      name: name2,
      parentSampled
    }
  });
  const rootSpan = new SentrySpan({
    ...spanArguments,
    attributes: {
      [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: "custom",
      ...spanArguments.attributes
    },
    sampled
  });
  if (sampleRate !== void 0) {
    rootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, sampleRate);
  }
  if (client) {
    client.emit("spanStart", rootSpan);
  }
  return rootSpan;
}
__name(_startRootSpan, "_startRootSpan");
function _startChildSpan(parentSpan, scope, spanArguments) {
  const { spanId, traceId } = parentSpan.spanContext();
  const sampled = scope.getScopeData().sdkProcessingMetadata[SUPPRESS_TRACING_KEY] ? false : spanIsSampled(parentSpan);
  const childSpan = sampled ? new SentrySpan({
    ...spanArguments,
    parentSpanId: spanId,
    traceId,
    sampled
  }) : new SentryNonRecordingSpan({ traceId });
  addChildSpanToSpan(parentSpan, childSpan);
  const client = getClient();
  if (client) {
    client.emit("spanStart", childSpan);
    if (spanArguments.endTimestamp) {
      client.emit("spanEnd", childSpan);
    }
  }
  return childSpan;
}
__name(_startChildSpan, "_startChildSpan");
function getParentSpan(scope) {
  const span = _getSpanForScope(scope);
  if (!span) {
    return void 0;
  }
  const client = getClient();
  const options2 = client ? client.getOptions() : {};
  if (options2.parentSpanIsAlwaysRootSpan) {
    return getRootSpan(span);
  }
  return span;
}
__name(getParentSpan, "getParentSpan");
function getActiveSpanWrapper(parentSpan) {
  return parentSpan !== void 0 ? (callback) => {
    return withActiveSpan(parentSpan, callback);
  } : (callback) => callback();
}
__name(getActiveSpanWrapper, "getActiveSpanWrapper");
const TRACING_DEFAULTS = {
  idleTimeout: 1e3,
  finalTimeout: 3e4,
  childSpanTimeout: 15e3
};
const FINISH_REASON_HEARTBEAT_FAILED = "heartbeatFailed";
const FINISH_REASON_IDLE_TIMEOUT = "idleTimeout";
const FINISH_REASON_FINAL_TIMEOUT = "finalTimeout";
const FINISH_REASON_EXTERNAL_FINISH = "externalFinish";
function startIdleSpan(startSpanOptions, options2 = {}) {
  const activities = /* @__PURE__ */ new Map();
  let _finished = false;
  let _idleTimeoutID;
  let _finishReason = FINISH_REASON_EXTERNAL_FINISH;
  let _autoFinishAllowed = !options2.disableAutoFinish;
  const _cleanupHooks = [];
  const {
    idleTimeout = TRACING_DEFAULTS.idleTimeout,
    finalTimeout = TRACING_DEFAULTS.finalTimeout,
    childSpanTimeout = TRACING_DEFAULTS.childSpanTimeout,
    beforeSpanEnd
  } = options2;
  const client = getClient();
  if (!client || !hasTracingEnabled()) {
    return new SentryNonRecordingSpan();
  }
  const scope = getCurrentScope();
  const previousActiveSpan = getActiveSpan();
  const span = _startIdleSpan(startSpanOptions);
  span.end = new Proxy(span.end, {
    apply(target, thisArg, args) {
      if (beforeSpanEnd) {
        beforeSpanEnd(span);
      }
      const [definedEndTimestamp, ...rest] = args;
      const timestamp2 = definedEndTimestamp || timestampInSeconds();
      const spanEndTimestamp = spanTimeInputToSeconds(timestamp2);
      const spans = getSpanDescendants(span).filter((child2) => child2 !== span);
      if (!spans.length) {
        onIdleSpanEnded(spanEndTimestamp);
        return Reflect.apply(target, thisArg, [spanEndTimestamp, ...rest]);
      }
      const childEndTimestamps = spans.map((span2) => spanToJSON(span2).timestamp).filter((timestamp3) => !!timestamp3);
      const latestSpanEndTimestamp = childEndTimestamps.length ? Math.max(...childEndTimestamps) : void 0;
      const spanStartTimestamp = spanToJSON(span).start_timestamp;
      const endTimestamp = Math.min(
        spanStartTimestamp ? spanStartTimestamp + finalTimeout / 1e3 : Infinity,
        Math.max(spanStartTimestamp || -Infinity, Math.min(spanEndTimestamp, latestSpanEndTimestamp || Infinity))
      );
      onIdleSpanEnded(endTimestamp);
      return Reflect.apply(target, thisArg, [endTimestamp, ...rest]);
    }
  });
  function _cancelIdleTimeout() {
    if (_idleTimeoutID) {
      clearTimeout(_idleTimeoutID);
      _idleTimeoutID = void 0;
    }
  }
  __name(_cancelIdleTimeout, "_cancelIdleTimeout");
  function _restartIdleTimeout(endTimestamp) {
    _cancelIdleTimeout();
    _idleTimeoutID = setTimeout(() => {
      if (!_finished && activities.size === 0 && _autoFinishAllowed) {
        _finishReason = FINISH_REASON_IDLE_TIMEOUT;
        span.end(endTimestamp);
      }
    }, idleTimeout);
  }
  __name(_restartIdleTimeout, "_restartIdleTimeout");
  function _restartChildSpanTimeout(endTimestamp) {
    _idleTimeoutID = setTimeout(() => {
      if (!_finished && _autoFinishAllowed) {
        _finishReason = FINISH_REASON_HEARTBEAT_FAILED;
        span.end(endTimestamp);
      }
    }, childSpanTimeout);
  }
  __name(_restartChildSpanTimeout, "_restartChildSpanTimeout");
  function _pushActivity(spanId) {
    _cancelIdleTimeout();
    activities.set(spanId, true);
    const endTimestamp = timestampInSeconds();
    _restartChildSpanTimeout(endTimestamp + childSpanTimeout / 1e3);
  }
  __name(_pushActivity, "_pushActivity");
  function _popActivity(spanId) {
    if (activities.has(spanId)) {
      activities.delete(spanId);
    }
    if (activities.size === 0) {
      const endTimestamp = timestampInSeconds();
      _restartIdleTimeout(endTimestamp + idleTimeout / 1e3);
    }
  }
  __name(_popActivity, "_popActivity");
  function onIdleSpanEnded(endTimestamp) {
    _finished = true;
    activities.clear();
    _cleanupHooks.forEach((cleanup) => cleanup());
    _setSpanForScope(scope, previousActiveSpan);
    const spanJSON = spanToJSON(span);
    const { start_timestamp: startTimestamp } = spanJSON;
    if (!startTimestamp) {
      return;
    }
    const attributes = spanJSON.data || {};
    if (!attributes[SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON]) {
      span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON, _finishReason);
    }
    logger$5.log(`[Tracing] Idle span "${spanJSON.op}" finished`);
    const childSpans = getSpanDescendants(span).filter((child2) => child2 !== span);
    let discardedSpans = 0;
    childSpans.forEach((childSpan) => {
      if (childSpan.isRecording()) {
        childSpan.setStatus({ code: SPAN_STATUS_ERROR, message: "cancelled" });
        childSpan.end(endTimestamp);
        DEBUG_BUILD$6 && logger$5.log("[Tracing] Cancelling span since span ended early", JSON.stringify(childSpan, void 0, 2));
      }
      const childSpanJSON = spanToJSON(childSpan);
      const { timestamp: childEndTimestamp = 0, start_timestamp: childStartTimestamp = 0 } = childSpanJSON;
      const spanStartedBeforeIdleSpanEnd = childStartTimestamp <= endTimestamp;
      const timeoutWithMarginOfError = (finalTimeout + idleTimeout) / 1e3;
      const spanEndedBeforeFinalTimeout = childEndTimestamp - childStartTimestamp <= timeoutWithMarginOfError;
      if (DEBUG_BUILD$6) {
        const stringifiedSpan = JSON.stringify(childSpan, void 0, 2);
        if (!spanStartedBeforeIdleSpanEnd) {
          logger$5.log("[Tracing] Discarding span since it happened after idle span was finished", stringifiedSpan);
        } else if (!spanEndedBeforeFinalTimeout) {
          logger$5.log("[Tracing] Discarding span since it finished after idle span final timeout", stringifiedSpan);
        }
      }
      if (!spanEndedBeforeFinalTimeout || !spanStartedBeforeIdleSpanEnd) {
        removeChildSpanFromSpan(span, childSpan);
        discardedSpans++;
      }
    });
    if (discardedSpans > 0) {
      span.setAttribute("sentry.idle_span_discarded_spans", discardedSpans);
    }
  }
  __name(onIdleSpanEnded, "onIdleSpanEnded");
  _cleanupHooks.push(
    client.on("spanStart", (startedSpan) => {
      if (_finished || startedSpan === span || !!spanToJSON(startedSpan).timestamp) {
        return;
      }
      const allSpans = getSpanDescendants(span);
      if (allSpans.includes(startedSpan)) {
        _pushActivity(startedSpan.spanContext().spanId);
      }
    })
  );
  _cleanupHooks.push(
    client.on("spanEnd", (endedSpan) => {
      if (_finished) {
        return;
      }
      _popActivity(endedSpan.spanContext().spanId);
    })
  );
  _cleanupHooks.push(
    client.on("idleSpanEnableAutoFinish", (spanToAllowAutoFinish) => {
      if (spanToAllowAutoFinish === span) {
        _autoFinishAllowed = true;
        _restartIdleTimeout();
        if (activities.size) {
          _restartChildSpanTimeout();
        }
      }
    })
  );
  if (!options2.disableAutoFinish) {
    _restartIdleTimeout();
  }
  setTimeout(() => {
    if (!_finished) {
      span.setStatus({ code: SPAN_STATUS_ERROR, message: "deadline_exceeded" });
      _finishReason = FINISH_REASON_FINAL_TIMEOUT;
      span.end();
    }
  }, finalTimeout);
  return span;
}
__name(startIdleSpan, "startIdleSpan");
function _startIdleSpan(options2) {
  const span = startInactiveSpan(options2);
  _setSpanForScope(getCurrentScope(), span);
  DEBUG_BUILD$6 && logger$5.log("[Tracing] Started span is an idle span");
  return span;
}
__name(_startIdleSpan, "_startIdleSpan");
function notifyEventProcessors(processors, event, hint, index2 = 0) {
  return new SyncPromise((resolve2, reject) => {
    const processor = processors[index2];
    if (event === null || typeof processor !== "function") {
      resolve2(event);
    } else {
      const result = processor({ ...event }, hint);
      DEBUG_BUILD$6 && processor.id && result === null && logger$5.log(`Event processor "${processor.id}" dropped event`);
      if (isThenable$1(result)) {
        void result.then((final) => notifyEventProcessors(processors, final, hint, index2 + 1).then(resolve2)).then(null, reject);
      } else {
        void notifyEventProcessors(processors, result, hint, index2 + 1).then(resolve2).then(null, reject);
      }
    }
  });
}
__name(notifyEventProcessors, "notifyEventProcessors");
let parsedStackResults;
let lastKeysCount;
let cachedFilenameDebugIds;
function getFilenameToDebugIdMap(stackParser) {
  const debugIdMap = GLOBAL_OBJ._sentryDebugIds;
  if (!debugIdMap) {
    return {};
  }
  const debugIdKeys = Object.keys(debugIdMap);
  if (cachedFilenameDebugIds && debugIdKeys.length === lastKeysCount) {
    return cachedFilenameDebugIds;
  }
  lastKeysCount = debugIdKeys.length;
  cachedFilenameDebugIds = debugIdKeys.reduce((acc, stackKey) => {
    if (!parsedStackResults) {
      parsedStackResults = {};
    }
    const result = parsedStackResults[stackKey];
    if (result) {
      acc[result[0]] = result[1];
    } else {
      const parsedStack = stackParser(stackKey);
      for (let i2 = parsedStack.length - 1; i2 >= 0; i2--) {
        const stackFrame = parsedStack[i2];
        const filename = stackFrame && stackFrame.filename;
        const debugId = debugIdMap[stackKey];
        if (filename && debugId) {
          acc[filename] = debugId;
          parsedStackResults[stackKey] = [filename, debugId];
          break;
        }
      }
    }
    return acc;
  }, {});
  return cachedFilenameDebugIds;
}
__name(getFilenameToDebugIdMap, "getFilenameToDebugIdMap");
function getDebugImagesForResources(stackParser, resource_paths) {
  const filenameDebugIdMap = getFilenameToDebugIdMap(stackParser);
  if (!filenameDebugIdMap) {
    return [];
  }
  const images = [];
  for (const path of resource_paths) {
    if (path && filenameDebugIdMap[path]) {
      images.push({
        type: "sourcemap",
        code_file: path,
        debug_id: filenameDebugIdMap[path]
      });
    }
  }
  return images;
}
__name(getDebugImagesForResources, "getDebugImagesForResources");
function applyScopeDataToEvent(event, data) {
  const { fingerprint, span, breadcrumbs, sdkProcessingMetadata } = data;
  applyDataToEvent(event, data);
  if (span) {
    applySpanToEvent(event, span);
  }
  applyFingerprintToEvent(event, fingerprint);
  applyBreadcrumbsToEvent(event, breadcrumbs);
  applySdkMetadataToEvent(event, sdkProcessingMetadata);
}
__name(applyScopeDataToEvent, "applyScopeDataToEvent");
function mergeScopeData(data, mergeData) {
  const {
    extra,
    tags,
    user,
    contexts,
    level,
    sdkProcessingMetadata,
    breadcrumbs,
    fingerprint,
    eventProcessors,
    attachments,
    propagationContext,
    transactionName,
    span
  } = mergeData;
  mergeAndOverwriteScopeData(data, "extra", extra);
  mergeAndOverwriteScopeData(data, "tags", tags);
  mergeAndOverwriteScopeData(data, "user", user);
  mergeAndOverwriteScopeData(data, "contexts", contexts);
  data.sdkProcessingMetadata = merge$2(data.sdkProcessingMetadata, sdkProcessingMetadata, 2);
  if (level) {
    data.level = level;
  }
  if (transactionName) {
    data.transactionName = transactionName;
  }
  if (span) {
    data.span = span;
  }
  if (breadcrumbs.length) {
    data.breadcrumbs = [...data.breadcrumbs, ...breadcrumbs];
  }
  if (fingerprint.length) {
    data.fingerprint = [...data.fingerprint, ...fingerprint];
  }
  if (eventProcessors.length) {
    data.eventProcessors = [...data.eventProcessors, ...eventProcessors];
  }
  if (attachments.length) {
    data.attachments = [...data.attachments, ...attachments];
  }
  data.propagationContext = { ...data.propagationContext, ...propagationContext };
}
__name(mergeScopeData, "mergeScopeData");
function mergeAndOverwriteScopeData(data, prop2, mergeVal) {
  data[prop2] = merge$2(data[prop2], mergeVal, 1);
}
__name(mergeAndOverwriteScopeData, "mergeAndOverwriteScopeData");
function applyDataToEvent(event, data) {
  const { extra, tags, user, contexts, level, transactionName } = data;
  const cleanedExtra = dropUndefinedKeys(extra);
  if (cleanedExtra && Object.keys(cleanedExtra).length) {
    event.extra = { ...cleanedExtra, ...event.extra };
  }
  const cleanedTags = dropUndefinedKeys(tags);
  if (cleanedTags && Object.keys(cleanedTags).length) {
    event.tags = { ...cleanedTags, ...event.tags };
  }
  const cleanedUser = dropUndefinedKeys(user);
  if (cleanedUser && Object.keys(cleanedUser).length) {
    event.user = { ...cleanedUser, ...event.user };
  }
  const cleanedContexts = dropUndefinedKeys(contexts);
  if (cleanedContexts && Object.keys(cleanedContexts).length) {
    event.contexts = { ...cleanedContexts, ...event.contexts };
  }
  if (level) {
    event.level = level;
  }
  if (transactionName && event.type !== "transaction") {
    event.transaction = transactionName;
  }
}
__name(applyDataToEvent, "applyDataToEvent");
function applyBreadcrumbsToEvent(event, breadcrumbs) {
  const mergedBreadcrumbs = [...event.breadcrumbs || [], ...breadcrumbs];
  event.breadcrumbs = mergedBreadcrumbs.length ? mergedBreadcrumbs : void 0;
}
__name(applyBreadcrumbsToEvent, "applyBreadcrumbsToEvent");
function applySdkMetadataToEvent(event, sdkProcessingMetadata) {
  event.sdkProcessingMetadata = {
    ...event.sdkProcessingMetadata,
    ...sdkProcessingMetadata
  };
}
__name(applySdkMetadataToEvent, "applySdkMetadataToEvent");
function applySpanToEvent(event, span) {
  event.contexts = {
    trace: spanToTraceContext(span),
    ...event.contexts
  };
  event.sdkProcessingMetadata = {
    dynamicSamplingContext: getDynamicSamplingContextFromSpan(span),
    ...event.sdkProcessingMetadata
  };
  const rootSpan = getRootSpan(span);
  const transactionName = spanToJSON(rootSpan).description;
  if (transactionName && !event.transaction && event.type === "transaction") {
    event.transaction = transactionName;
  }
}
__name(applySpanToEvent, "applySpanToEvent");
function applyFingerprintToEvent(event, fingerprint) {
  event.fingerprint = event.fingerprint ? Array.isArray(event.fingerprint) ? event.fingerprint : [event.fingerprint] : [];
  if (fingerprint) {
    event.fingerprint = event.fingerprint.concat(fingerprint);
  }
  if (event.fingerprint && !event.fingerprint.length) {
    delete event.fingerprint;
  }
}
__name(applyFingerprintToEvent, "applyFingerprintToEvent");
function prepareEvent(options2, event, hint, scope, client, isolationScope) {
  const { normalizeDepth = 3, normalizeMaxBreadth = 1e3 } = options2;
  const prepared = {
    ...event,
    event_id: event.event_id || hint.event_id || uuid4(),
    timestamp: event.timestamp || dateTimestampInSeconds()
  };
  const integrations = hint.integrations || options2.integrations.map((i2) => i2.name);
  applyClientOptions(prepared, options2);
  applyIntegrationsMetadata(prepared, integrations);
  if (client) {
    client.emit("applyFrameMetadata", event);
  }
  if (event.type === void 0) {
    applyDebugIds(prepared, options2.stackParser);
  }
  const finalScope = getFinalScope(scope, hint.captureContext);
  if (hint.mechanism) {
    addExceptionMechanism(prepared, hint.mechanism);
  }
  const clientEventProcessors = client ? client.getEventProcessors() : [];
  const data = getGlobalScope$1().getScopeData();
  if (isolationScope) {
    const isolationData = isolationScope.getScopeData();
    mergeScopeData(data, isolationData);
  }
  if (finalScope) {
    const finalScopeData = finalScope.getScopeData();
    mergeScopeData(data, finalScopeData);
  }
  const attachments = [...hint.attachments || [], ...data.attachments];
  if (attachments.length) {
    hint.attachments = attachments;
  }
  applyScopeDataToEvent(prepared, data);
  const eventProcessors = [
    ...clientEventProcessors,
    // Run scope event processors _after_ all other processors
    ...data.eventProcessors
  ];
  const result = notifyEventProcessors(eventProcessors, prepared, hint);
  return result.then((evt) => {
    if (evt) {
      applyDebugMeta(evt);
    }
    if (typeof normalizeDepth === "number" && normalizeDepth > 0) {
      return normalizeEvent(evt, normalizeDepth, normalizeMaxBreadth);
    }
    return evt;
  });
}
__name(prepareEvent, "prepareEvent");
function applyClientOptions(event, options2) {
  const { environment, release, dist: dist3, maxValueLength = 250 } = options2;
  event.environment = event.environment || environment || DEFAULT_ENVIRONMENT;
  if (!event.release && release) {
    event.release = release;
  }
  if (!event.dist && dist3) {
    event.dist = dist3;
  }
  if (event.message) {
    event.message = truncate(event.message, maxValueLength);
  }
  const exception = event.exception && event.exception.values && event.exception.values[0];
  if (exception && exception.value) {
    exception.value = truncate(exception.value, maxValueLength);
  }
  const request = event.request;
  if (request && request.url) {
    request.url = truncate(request.url, maxValueLength);
  }
}
__name(applyClientOptions, "applyClientOptions");
function applyDebugIds(event, stackParser) {
  const filenameDebugIdMap = getFilenameToDebugIdMap(stackParser);
  try {
    event.exception.values.forEach((exception) => {
      exception.stacktrace.frames.forEach((frame) => {
        if (filenameDebugIdMap && frame.filename) {
          frame.debug_id = filenameDebugIdMap[frame.filename];
        }
      });
    });
  } catch (e2) {
  }
}
__name(applyDebugIds, "applyDebugIds");
function applyDebugMeta(event) {
  const filenameDebugIdMap = {};
  try {
    event.exception.values.forEach((exception) => {
      exception.stacktrace.frames.forEach((frame) => {
        if (frame.debug_id) {
          if (frame.abs_path) {
            filenameDebugIdMap[frame.abs_path] = frame.debug_id;
          } else if (frame.filename) {
            filenameDebugIdMap[frame.filename] = frame.debug_id;
          }
          delete frame.debug_id;
        }
      });
    });
  } catch (e2) {
  }
  if (Object.keys(filenameDebugIdMap).length === 0) {
    return;
  }
  event.debug_meta = event.debug_meta || {};
  event.debug_meta.images = event.debug_meta.images || [];
  const images = event.debug_meta.images;
  Object.entries(filenameDebugIdMap).forEach(([filename, debug_id]) => {
    images.push({
      type: "sourcemap",
      code_file: filename,
      debug_id
    });
  });
}
__name(applyDebugMeta, "applyDebugMeta");
function applyIntegrationsMetadata(event, integrationNames) {
  if (integrationNames.length > 0) {
    event.sdk = event.sdk || {};
    event.sdk.integrations = [...event.sdk.integrations || [], ...integrationNames];
  }
}
__name(applyIntegrationsMetadata, "applyIntegrationsMetadata");
function normalizeEvent(event, depth, maxBreadth) {
  if (!event) {
    return null;
  }
  const normalized = {
    ...event,
    ...event.breadcrumbs && {
      breadcrumbs: event.breadcrumbs.map((b2) => ({
        ...b2,
        ...b2.data && {
          data: normalize$2(b2.data, depth, maxBreadth)
        }
      }))
    },
    ...event.user && {
      user: normalize$2(event.user, depth, maxBreadth)
    },
    ...event.contexts && {
      contexts: normalize$2(event.contexts, depth, maxBreadth)
    },
    ...event.extra && {
      extra: normalize$2(event.extra, depth, maxBreadth)
    }
  };
  if (event.contexts && event.contexts.trace && normalized.contexts) {
    normalized.contexts.trace = event.contexts.trace;
    if (event.contexts.trace.data) {
      normalized.contexts.trace.data = normalize$2(event.contexts.trace.data, depth, maxBreadth);
    }
  }
  if (event.spans) {
    normalized.spans = event.spans.map((span) => {
      return {
        ...span,
        ...span.data && {
          data: normalize$2(span.data, depth, maxBreadth)
        }
      };
    });
  }
  if (event.contexts && event.contexts.flags && normalized.contexts) {
    normalized.contexts.flags = normalize$2(event.contexts.flags, 3, maxBreadth);
  }
  return normalized;
}
__name(normalizeEvent, "normalizeEvent");
function getFinalScope(scope, captureContext) {
  if (!captureContext) {
    return scope;
  }
  const finalScope = scope ? scope.clone() : new Scope();
  finalScope.update(captureContext);
  return finalScope;
}
__name(getFinalScope, "getFinalScope");
function parseEventHintOrCaptureContext(hint) {
  if (!hint) {
    return void 0;
  }
  if (hintIsScopeOrFunction(hint)) {
    return { captureContext: hint };
  }
  if (hintIsScopeContext(hint)) {
    return {
      captureContext: hint
    };
  }
  return hint;
}
__name(parseEventHintOrCaptureContext, "parseEventHintOrCaptureContext");
function hintIsScopeOrFunction(hint) {
  return hint instanceof Scope || typeof hint === "function";
}
__name(hintIsScopeOrFunction, "hintIsScopeOrFunction");
const captureContextKeys = [
  "user",
  "level",
  "extra",
  "contexts",
  "tags",
  "fingerprint",
  "requestSession",
  "propagationContext"
];
function hintIsScopeContext(hint) {
  return Object.keys(hint).some((key) => captureContextKeys.includes(key));
}
__name(hintIsScopeContext, "hintIsScopeContext");
function captureException(exception, hint) {
  return getCurrentScope().captureException(exception, parseEventHintOrCaptureContext(hint));
}
__name(captureException, "captureException");
function captureMessage(message, captureContext) {
  const level = typeof captureContext === "string" ? captureContext : void 0;
  const context = typeof captureContext !== "string" ? { captureContext } : void 0;
  return getCurrentScope().captureMessage(message, level, context);
}
__name(captureMessage, "captureMessage");
function captureEvent(event, hint) {
  return getCurrentScope().captureEvent(event, hint);
}
__name(captureEvent, "captureEvent");
function setContext(name2, context) {
  getIsolationScope().setContext(name2, context);
}
__name(setContext, "setContext");
function setExtras(extras) {
  getIsolationScope().setExtras(extras);
}
__name(setExtras, "setExtras");
function setExtra(key, extra) {
  getIsolationScope().setExtra(key, extra);
}
__name(setExtra, "setExtra");
function setTags(tags) {
  getIsolationScope().setTags(tags);
}
__name(setTags, "setTags");
function setTag$5(key, value) {
  getIsolationScope().setTag(key, value);
}
__name(setTag$5, "setTag$5");
function setUser(user) {
  getIsolationScope().setUser(user);
}
__name(setUser, "setUser");
function lastEventId() {
  return getIsolationScope().lastEventId();
}
__name(lastEventId, "lastEventId");
function captureCheckIn(checkIn, upsertMonitorConfig) {
  const scope = getCurrentScope();
  const client = getClient();
  if (!client) {
    DEBUG_BUILD$6 && logger$5.warn("Cannot capture check-in. No client defined.");
  } else if (!client.captureCheckIn) {
    DEBUG_BUILD$6 && logger$5.warn("Cannot capture check-in. Client does not support sending check-ins.");
  } else {
    return client.captureCheckIn(checkIn, upsertMonitorConfig, scope);
  }
  return uuid4();
}
__name(captureCheckIn, "captureCheckIn");
function withMonitor(monitorSlug, callback, upsertMonitorConfig) {
  const checkInId = captureCheckIn({ monitorSlug, status: "in_progress" }, upsertMonitorConfig);
  const now2 = timestampInSeconds();
  function finishCheckIn(status) {
    captureCheckIn({ monitorSlug, status, checkInId, duration: timestampInSeconds() - now2 });
  }
  __name(finishCheckIn, "finishCheckIn");
  return withIsolationScope(() => {
    let maybePromiseResult;
    try {
      maybePromiseResult = callback();
    } catch (e2) {
      finishCheckIn("error");
      throw e2;
    }
    if (isThenable$1(maybePromiseResult)) {
      Promise.resolve(maybePromiseResult).then(
        () => {
          finishCheckIn("ok");
        },
        (e2) => {
          finishCheckIn("error");
          throw e2;
        }
      );
    } else {
      finishCheckIn("ok");
    }
    return maybePromiseResult;
  });
}
__name(withMonitor, "withMonitor");
async function flush(timeout) {
  const client = getClient();
  if (client) {
    return client.flush(timeout);
  }
  DEBUG_BUILD$6 && logger$5.warn("Cannot flush events. No client defined.");
  return Promise.resolve(false);
}
__name(flush, "flush");
async function close$1(timeout) {
  const client = getClient();
  if (client) {
    return client.close(timeout);
  }
  DEBUG_BUILD$6 && logger$5.warn("Cannot flush events and disable SDK. No client defined.");
  return Promise.resolve(false);
}
__name(close$1, "close$1");
function isInitialized$1() {
  return !!getClient();
}
__name(isInitialized$1, "isInitialized$1");
function isEnabled() {
  const client = getClient();
  return !!client && client.getOptions().enabled !== false && !!client.getTransport();
}
__name(isEnabled, "isEnabled");
function addEventProcessor(callback) {
  getIsolationScope().addEventProcessor(callback);
}
__name(addEventProcessor, "addEventProcessor");
function startSession(context) {
  const client = getClient();
  const isolationScope = getIsolationScope();
  const currentScope = getCurrentScope();
  const { release, environment = DEFAULT_ENVIRONMENT } = client && client.getOptions() || {};
  const { userAgent } = GLOBAL_OBJ.navigator || {};
  const session = makeSession$1({
    release,
    environment,
    user: currentScope.getUser() || isolationScope.getUser(),
    ...userAgent && { userAgent },
    ...context
  });
  const currentSession = isolationScope.getSession();
  if (currentSession && currentSession.status === "ok") {
    updateSession(currentSession, { status: "exited" });
  }
  endSession();
  isolationScope.setSession(session);
  currentScope.setSession(session);
  return session;
}
__name(startSession, "startSession");
function endSession() {
  const isolationScope = getIsolationScope();
  const currentScope = getCurrentScope();
  const session = currentScope.getSession() || isolationScope.getSession();
  if (session) {
    closeSession(session);
  }
  _sendSessionUpdate$1();
  isolationScope.setSession();
  currentScope.setSession();
}
__name(endSession, "endSession");
function _sendSessionUpdate$1() {
  const isolationScope = getIsolationScope();
  const currentScope = getCurrentScope();
  const client = getClient();
  const session = currentScope.getSession() || isolationScope.getSession();
  if (session && client) {
    client.captureSession(session);
  }
}
__name(_sendSessionUpdate$1, "_sendSessionUpdate$1");
function captureSession(end = false) {
  if (end) {
    endSession();
    return;
  }
  _sendSessionUpdate$1();
}
__name(captureSession, "captureSession");
class SessionFlusher {
  static {
    __name(this, "SessionFlusher");
  }
  // We adjust the type here to add the `unref()` part, as setInterval can technically return a number or a NodeJS.Timer
  constructor(client, attrs2) {
    this._client = client;
    this.flushTimeout = 60;
    this._pendingAggregates = /* @__PURE__ */ new Map();
    this._isEnabled = true;
    this._intervalId = setInterval(() => this.flush(), this.flushTimeout * 1e3);
    if (this._intervalId.unref) {
      this._intervalId.unref();
    }
    this._sessionAttrs = attrs2;
  }
  /** Checks if `pendingAggregates` has entries, and if it does flushes them by calling `sendSession` */
  flush() {
    const sessionAggregates = this.getSessionAggregates();
    if (sessionAggregates.aggregates.length === 0) {
      return;
    }
    this._pendingAggregates = /* @__PURE__ */ new Map();
    this._client.sendSession(sessionAggregates);
  }
  /** Massages the entries in `pendingAggregates` and returns aggregated sessions */
  getSessionAggregates() {
    const aggregates = Array.from(this._pendingAggregates.values());
    const sessionAggregates = {
      attrs: this._sessionAttrs,
      aggregates
    };
    return dropUndefinedKeys(sessionAggregates);
  }
  /** JSDoc */
  close() {
    clearInterval(this._intervalId);
    this._isEnabled = false;
    this.flush();
  }
  /**
   * Wrapper function for _incrementSessionStatusCount that checks if the instance of SessionFlusher is enabled then
   * fetches the session status of the request from `Scope.getRequestSession().status` on the scope and passes them to
   * `_incrementSessionStatusCount` along with the start date
   */
  incrementSessionStatusCount() {
    if (!this._isEnabled) {
      return;
    }
    const isolationScope = getIsolationScope();
    const requestSession = isolationScope.getRequestSession();
    if (requestSession && requestSession.status) {
      this._incrementSessionStatusCount(requestSession.status, /* @__PURE__ */ new Date());
      isolationScope.setRequestSession(void 0);
    }
  }
  /**
   * Increments status bucket in pendingAggregates buffer (internal state) corresponding to status of
   * the session received
   */
  // eslint-disable-next-line deprecation/deprecation
  _incrementSessionStatusCount(status, date) {
    const sessionStartedTrunc = new Date(date).setSeconds(0, 0);
    let aggregationCounts = this._pendingAggregates.get(sessionStartedTrunc);
    if (!aggregationCounts) {
      aggregationCounts = { started: new Date(sessionStartedTrunc).toISOString() };
      this._pendingAggregates.set(sessionStartedTrunc, aggregationCounts);
    }
    switch (status) {
      case "errored":
        aggregationCounts.errored = (aggregationCounts.errored || 0) + 1;
        return aggregationCounts.errored;
      case "ok":
        aggregationCounts.exited = (aggregationCounts.exited || 0) + 1;
        return aggregationCounts.exited;
      default:
        aggregationCounts.crashed = (aggregationCounts.crashed || 0) + 1;
        return aggregationCounts.crashed;
    }
  }
}
const SENTRY_API_VERSION = "7";
function getBaseApiEndpoint(dsn) {
  const protocol = dsn.protocol ? `${dsn.protocol}:` : "";
  const port = dsn.port ? `:${dsn.port}` : "";
  return `${protocol}//${dsn.host}${port}${dsn.path ? `/${dsn.path}` : ""}/api/`;
}
__name(getBaseApiEndpoint, "getBaseApiEndpoint");
function _getIngestEndpoint(dsn) {
  return `${getBaseApiEndpoint(dsn)}${dsn.projectId}/envelope/`;
}
__name(_getIngestEndpoint, "_getIngestEndpoint");
function _encodedAuth(dsn, sdkInfo) {
  const params = {
    sentry_version: SENTRY_API_VERSION
  };
  if (dsn.publicKey) {
    params.sentry_key = dsn.publicKey;
  }
  if (sdkInfo) {
    params.sentry_client = `${sdkInfo.name}/${sdkInfo.version}`;
  }
  return new URLSearchParams(params).toString();
}
__name(_encodedAuth, "_encodedAuth");
function getEnvelopeEndpointWithUrlEncodedAuth(dsn, tunnel, sdkInfo) {
  return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, sdkInfo)}`;
}
__name(getEnvelopeEndpointWithUrlEncodedAuth, "getEnvelopeEndpointWithUrlEncodedAuth");
function getReportDialogEndpoint(dsnLike, dialogOptions) {
  const dsn = makeDsn(dsnLike);
  if (!dsn) {
    return "";
  }
  const endpoint = `${getBaseApiEndpoint(dsn)}embed/error-page/`;
  let encodedOptions = `dsn=${dsnToString(dsn)}`;
  for (const key in dialogOptions) {
    if (key === "dsn") {
      continue;
    }
    if (key === "onClose") {
      continue;
    }
    if (key === "user") {
      const user = dialogOptions.user;
      if (!user) {
        continue;
      }
      if (user.name) {
        encodedOptions += `&name=${encodeURIComponent(user.name)}`;
      }
      if (user.email) {
        encodedOptions += `&email=${encodeURIComponent(user.email)}`;
      }
    } else {
      encodedOptions += `&${encodeURIComponent(key)}=${encodeURIComponent(dialogOptions[key])}`;
    }
  }
  return `${endpoint}?${encodedOptions}`;
}
__name(getReportDialogEndpoint, "getReportDialogEndpoint");
const installedIntegrations = [];
function filterDuplicates(integrations) {
  const integrationsByName = {};
  integrations.forEach((currentInstance) => {
    const { name: name2 } = currentInstance;
    const existingInstance = integrationsByName[name2];
    if (existingInstance && !existingInstance.isDefaultInstance && currentInstance.isDefaultInstance) {
      return;
    }
    integrationsByName[name2] = currentInstance;
  });
  return Object.values(integrationsByName);
}
__name(filterDuplicates, "filterDuplicates");
function getIntegrationsToSetup(options2) {
  const defaultIntegrations = options2.defaultIntegrations || [];
  const userIntegrations = options2.integrations;
  defaultIntegrations.forEach((integration) => {
    integration.isDefaultInstance = true;
  });
  let integrations;
  if (Array.isArray(userIntegrations)) {
    integrations = [...defaultIntegrations, ...userIntegrations];
  } else if (typeof userIntegrations === "function") {
    const resolvedUserIntegrations = userIntegrations(defaultIntegrations);
    integrations = Array.isArray(resolvedUserIntegrations) ? resolvedUserIntegrations : [resolvedUserIntegrations];
  } else {
    integrations = defaultIntegrations;
  }
  const finalIntegrations = filterDuplicates(integrations);
  const debugIndex = finalIntegrations.findIndex((integration) => integration.name === "Debug");
  if (debugIndex > -1) {
    const [debugInstance] = finalIntegrations.splice(debugIndex, 1);
    finalIntegrations.push(debugInstance);
  }
  return finalIntegrations;
}
__name(getIntegrationsToSetup, "getIntegrationsToSetup");
function setupIntegrations(client, integrations) {
  const integrationIndex = {};
  integrations.forEach((integration) => {
    if (integration) {
      setupIntegration(client, integration, integrationIndex);
    }
  });
  return integrationIndex;
}
__name(setupIntegrations, "setupIntegrations");
function afterSetupIntegrations(client, integrations) {
  for (const integration of integrations) {
    if (integration && integration.afterAllSetup) {
      integration.afterAllSetup(client);
    }
  }
}
__name(afterSetupIntegrations, "afterSetupIntegrations");
function setupIntegration(client, integration, integrationIndex) {
  if (integrationIndex[integration.name]) {
    DEBUG_BUILD$6 && logger$5.log(`Integration skipped because it was already installed: ${integration.name}`);
    return;
  }
  integrationIndex[integration.name] = integration;
  if (installedIntegrations.indexOf(integration.name) === -1 && typeof integration.setupOnce === "function") {
    integration.setupOnce();
    installedIntegrations.push(integration.name);
  }
  if (integration.setup && typeof integration.setup === "function") {
    integration.setup(client);
  }
  if (typeof integration.preprocessEvent === "function") {
    const callback = integration.preprocessEvent.bind(integration);
    client.on("preprocessEvent", (event, hint) => callback(event, hint, client));
  }
  if (typeof integration.processEvent === "function") {
    const callback = integration.processEvent.bind(integration);
    const processor = Object.assign((event, hint) => callback(event, hint, client), {
      id: integration.name
    });
    client.addEventProcessor(processor);
  }
  DEBUG_BUILD$6 && logger$5.log(`Integration installed: ${integration.name}`);
}
__name(setupIntegration, "setupIntegration");
function addIntegration(integration) {
  const client = getClient();
  if (!client) {
    DEBUG_BUILD$6 && logger$5.warn(`Cannot add integration "${integration.name}" because no SDK Client is available.`);
    return;
  }
  client.addIntegration(integration);
}
__name(addIntegration, "addIntegration");
function defineIntegration(fn) {
  return fn;
}
__name(defineIntegration, "defineIntegration");
function createClientReportEnvelope(discarded_events, dsn, timestamp2) {
  const clientReportItem = [
    { type: "client_report" },
    {
      timestamp: timestamp2 || dateTimestampInSeconds(),
      discarded_events
    }
  ];
  return createEnvelope(dsn ? { dsn } : {}, [clientReportItem]);
}
__name(createClientReportEnvelope, "createClientReportEnvelope");
class SentryError extends Error {
  static {
    __name(this, "SentryError");
  }
  /** Display name of this error instance. */
  constructor(message, logLevel = "warn") {
    super(message);
    this.message = message;
    this.name = new.target.prototype.constructor.name;
    Object.setPrototypeOf(this, new.target.prototype);
    this.logLevel = logLevel;
  }
}
const ALREADY_SEEN_ERROR = "Not capturing exception because it's already been captured.";
class BaseClient {
  static {
    __name(this, "BaseClient");
  }
  /** Options passed to the SDK. */
  /** The client Dsn, if specified in options. Without this Dsn, the SDK will be disabled. */
  /** Array of set up integrations. */
  /** Number of calls being processed */
  /** Holds flushable  */
  // eslint-disable-next-line @typescript-eslint/ban-types
  /**
   * Initializes this client instance.
   *
   * @param options Options for the client.
   */
  constructor(options2) {
    this._options = options2;
    this._integrations = {};
    this._numProcessing = 0;
    this._outcomes = {};
    this._hooks = {};
    this._eventProcessors = [];
    if (options2.dsn) {
      this._dsn = makeDsn(options2.dsn);
    } else {
      DEBUG_BUILD$6 && logger$5.warn("No DSN provided, client will not send events.");
    }
    if (this._dsn) {
      const url = getEnvelopeEndpointWithUrlEncodedAuth(
        this._dsn,
        options2.tunnel,
        options2._metadata ? options2._metadata.sdk : void 0
      );
      this._transport = options2.transport({
        tunnel: this._options.tunnel,
        recordDroppedEvent: this.recordDroppedEvent.bind(this),
        ...options2.transportOptions,
        url
      });
    }
    const tracingOptions = ["enableTracing", "tracesSampleRate", "tracesSampler"];
    const undefinedOption = tracingOptions.find((option) => option in options2 && options2[option] == void 0);
    if (undefinedOption) {
      consoleSandbox(() => {
        console.warn(
          `[Sentry] Deprecation warning: \`${undefinedOption}\` is set to undefined, which leads to tracing being enabled. In v9, a value of \`undefined\` will result in tracing being disabled.`
        );
      });
    }
  }
  /**
   * @inheritDoc
   */
  captureException(exception, hint, scope) {
    const eventId = uuid4();
    if (checkOrSetAlreadyCaught(exception)) {
      DEBUG_BUILD$6 && logger$5.log(ALREADY_SEEN_ERROR);
      return eventId;
    }
    const hintWithEventId = {
      event_id: eventId,
      ...hint
    };
    this._process(
      this.eventFromException(exception, hintWithEventId).then(
        (event) => this._captureEvent(event, hintWithEventId, scope)
      )
    );
    return hintWithEventId.event_id;
  }
  /**
   * @inheritDoc
   */
  captureMessage(message, level, hint, currentScope) {
    const hintWithEventId = {
      event_id: uuid4(),
      ...hint
    };
    const eventMessage = isParameterizedString(message) ? message : String(message);
    const promisedEvent = isPrimitive(message) ? this.eventFromMessage(eventMessage, level, hintWithEventId) : this.eventFromException(message, hintWithEventId);
    this._process(promisedEvent.then((event) => this._captureEvent(event, hintWithEventId, currentScope)));
    return hintWithEventId.event_id;
  }
  /**
   * @inheritDoc
   */
  captureEvent(event, hint, currentScope) {
    const eventId = uuid4();
    if (hint && hint.originalException && checkOrSetAlreadyCaught(hint.originalException)) {
      DEBUG_BUILD$6 && logger$5.log(ALREADY_SEEN_ERROR);
      return eventId;
    }
    const hintWithEventId = {
      event_id: eventId,
      ...hint
    };
    const sdkProcessingMetadata = event.sdkProcessingMetadata || {};
    const capturedSpanScope = sdkProcessingMetadata.capturedSpanScope;
    this._process(this._captureEvent(event, hintWithEventId, capturedSpanScope || currentScope));
    return hintWithEventId.event_id;
  }
  /**
   * @inheritDoc
   */
  captureSession(session) {
    if (!(typeof session.release === "string")) {
      DEBUG_BUILD$6 && logger$5.warn("Discarded session because of missing or non-string release");
    } else {
      this.sendSession(session);
      updateSession(session, { init: false });
    }
  }
  /**
   * @inheritDoc
   */
  getDsn() {
    return this._dsn;
  }
  /**
   * @inheritDoc
   */
  getOptions() {
    return this._options;
  }
  /**
   * @see SdkMetadata
   *
   * @return The metadata of the SDK
   */
  getSdkMetadata() {
    return this._options._metadata;
  }
  /**
   * @inheritDoc
   */
  getTransport() {
    return this._transport;
  }
  /**
   * @inheritDoc
   */
  flush(timeout) {
    const transport = this._transport;
    if (transport) {
      this.emit("flush");
      return this._isClientDoneProcessing(timeout).then((clientFinished) => {
        return transport.flush(timeout).then((transportFlushed) => clientFinished && transportFlushed);
      });
    } else {
      return resolvedSyncPromise(true);
    }
  }
  /**
   * @inheritDoc
   */
  close(timeout) {
    return this.flush(timeout).then((result) => {
      this.getOptions().enabled = false;
      this.emit("close");
      return result;
    });
  }
  /** Get all installed event processors. */
  getEventProcessors() {
    return this._eventProcessors;
  }
  /** @inheritDoc */
  addEventProcessor(eventProcessor) {
    this._eventProcessors.push(eventProcessor);
  }
  /** @inheritdoc */
  init() {
    if (this._isEnabled() || // Force integrations to be setup even if no DSN was set when we have
    // Spotlight enabled. This is particularly important for browser as we
    // don't support the `spotlight` option there and rely on the users
    // adding the `spotlightBrowserIntegration()` to their integrations which
    // wouldn't get initialized with the check below when there's no DSN set.
    this._options.integrations.some(({ name: name2 }) => name2.startsWith("Spotlight"))) {
      this._setupIntegrations();
    }
  }
  /**
   * Gets an installed integration by its name.
   *
   * @returns The installed integration or `undefined` if no integration with that `name` was installed.
   */
  getIntegrationByName(integrationName) {
    return this._integrations[integrationName];
  }
  /**
   * @inheritDoc
   */
  addIntegration(integration) {
    const isAlreadyInstalled = this._integrations[integration.name];
    setupIntegration(this, integration, this._integrations);
    if (!isAlreadyInstalled) {
      afterSetupIntegrations(this, [integration]);
    }
  }
  /**
   * @inheritDoc
   */
  sendEvent(event, hint = {}) {
    this.emit("beforeSendEvent", event, hint);
    let env = createEventEnvelope(event, this._dsn, this._options._metadata, this._options.tunnel);
    for (const attachment of hint.attachments || []) {
      env = addItemToEnvelope(env, createAttachmentEnvelopeItem(attachment));
    }
    const promise = this.sendEnvelope(env);
    if (promise) {
      promise.then((sendResponse) => this.emit("afterSendEvent", event, sendResponse), null);
    }
  }
  /**
   * @inheritDoc
   */
  sendSession(session) {
    const env = createSessionEnvelope(session, this._dsn, this._options._metadata, this._options.tunnel);
    this.sendEnvelope(env);
  }
  /**
   * @inheritDoc
   */
  recordDroppedEvent(reason, category, eventOrCount) {
    if (this._options.sendClientReports) {
      const count2 = typeof eventOrCount === "number" ? eventOrCount : 1;
      const key = `${reason}:${category}`;
      DEBUG_BUILD$6 && logger$5.log(`Recording outcome: "${key}"${count2 > 1 ? ` (${count2} times)` : ""}`);
      this._outcomes[key] = (this._outcomes[key] || 0) + count2;
    }
  }
  // Keep on() & emit() signatures in sync with types' client.ts interface
  /* eslint-disable @typescript-eslint/unified-signatures */
  /** @inheritdoc */
  /** @inheritdoc */
  on(hook, callback) {
    const hooks2 = this._hooks[hook] = this._hooks[hook] || [];
    hooks2.push(callback);
    return () => {
      const cbIndex = hooks2.indexOf(callback);
      if (cbIndex > -1) {
        hooks2.splice(cbIndex, 1);
      }
    };
  }
  /** @inheritdoc */
  /** @inheritdoc */
  emit(hook, ...rest) {
    const callbacks = this._hooks[hook];
    if (callbacks) {
      callbacks.forEach((callback) => callback(...rest));
    }
  }
  /**
   * @inheritdoc
   */
  sendEnvelope(envelope) {
    this.emit("beforeEnvelope", envelope);
    if (this._isEnabled() && this._transport) {
      return this._transport.send(envelope).then(null, (reason) => {
        DEBUG_BUILD$6 && logger$5.error("Error while sending envelope:", reason);
        return reason;
      });
    }
    DEBUG_BUILD$6 && logger$5.error("Transport disabled");
    return resolvedSyncPromise({});
  }
  /* eslint-enable @typescript-eslint/unified-signatures */
  /** Setup integrations for this client. */
  _setupIntegrations() {
    const { integrations } = this._options;
    this._integrations = setupIntegrations(this, integrations);
    afterSetupIntegrations(this, integrations);
  }
  /** Updates existing session based on the provided event */
  _updateSessionFromEvent(session, event) {
    let crashed = false;
    let errored = false;
    const exceptions = event.exception && event.exception.values;
    if (exceptions) {
      errored = true;
      for (const ex of exceptions) {
        const mechanism = ex.mechanism;
        if (mechanism && mechanism.handled === false) {
          crashed = true;
          break;
        }
      }
    }
    const sessionNonTerminal = session.status === "ok";
    const shouldUpdateAndSend = sessionNonTerminal && session.errors === 0 || sessionNonTerminal && crashed;
    if (shouldUpdateAndSend) {
      updateSession(session, {
        ...crashed && { status: "crashed" },
        errors: session.errors || Number(errored || crashed)
      });
      this.captureSession(session);
    }
  }
  /**
   * Determine if the client is finished processing. Returns a promise because it will wait `timeout` ms before saying
   * "no" (resolving to `false`) in order to give the client a chance to potentially finish first.
   *
   * @param timeout The time, in ms, after which to resolve to `false` if the client is still busy. Passing `0` (or not
   * passing anything) will make the promise wait as long as it takes for processing to finish before resolving to
   * `true`.
   * @returns A promise which will resolve to `true` if processing is already done or finishes before the timeout, and
   * `false` otherwise
   */
  _isClientDoneProcessing(timeout) {
    return new SyncPromise((resolve2) => {
      let ticked = 0;
      const tick = 1;
      const interval = setInterval(() => {
        if (this._numProcessing == 0) {
          clearInterval(interval);
          resolve2(true);
        } else {
          ticked += tick;
          if (timeout && ticked >= timeout) {
            clearInterval(interval);
            resolve2(false);
          }
        }
      }, tick);
    });
  }
  /** Determines whether this SDK is enabled and a transport is present. */
  _isEnabled() {
    return this.getOptions().enabled !== false && this._transport !== void 0;
  }
  /**
   * Adds common information to events.
   *
   * The information includes release and environment from `options`,
   * breadcrumbs and context (extra, tags and user) from the scope.
   *
   * Information that is already present in the event is never overwritten. For
   * nested objects, such as the context, keys are merged.
   *
   * @param event The original event.
   * @param hint May contain additional information about the original exception.
   * @param currentScope A scope containing event metadata.
   * @returns A new event with more information.
   */
  _prepareEvent(event, hint, currentScope = getCurrentScope(), isolationScope = getIsolationScope()) {
    const options2 = this.getOptions();
    const integrations = Object.keys(this._integrations);
    if (!hint.integrations && integrations.length > 0) {
      hint.integrations = integrations;
    }
    this.emit("preprocessEvent", event, hint);
    if (!event.type) {
      isolationScope.setLastEventId(event.event_id || hint.event_id);
    }
    return prepareEvent(options2, event, hint, currentScope, this, isolationScope).then((evt) => {
      if (evt === null) {
        return evt;
      }
      evt.contexts = {
        trace: getTraceContextFromScope(currentScope),
        ...evt.contexts
      };
      const dynamicSamplingContext = getDynamicSamplingContextFromScope(this, currentScope);
      evt.sdkProcessingMetadata = {
        dynamicSamplingContext,
        ...evt.sdkProcessingMetadata
      };
      return evt;
    });
  }
  /**
   * Processes the event and logs an error in case of rejection
   * @param event
   * @param hint
   * @param scope
   */
  _captureEvent(event, hint = {}, scope) {
    return this._processEvent(event, hint, scope).then(
      (finalEvent) => {
        return finalEvent.event_id;
      },
      (reason) => {
        if (DEBUG_BUILD$6) {
          const sentryError = reason;
          if (sentryError.logLevel === "log") {
            logger$5.log(sentryError.message);
          } else {
            logger$5.warn(sentryError);
          }
        }
        return void 0;
      }
    );
  }
  /**
   * Processes an event (either error or message) and sends it to Sentry.
   *
   * This also adds breadcrumbs and context information to the event. However,
   * platform specific meta data (such as the User's IP address) must be added
   * by the SDK implementor.
   *
   *
   * @param event The event to send to Sentry.
   * @param hint May contain additional information about the original exception.
   * @param currentScope A scope containing event metadata.
   * @returns A SyncPromise that resolves with the event or rejects in case event was/will not be send.
   */
  _processEvent(event, hint, currentScope) {
    const options2 = this.getOptions();
    const { sampleRate } = options2;
    const isTransaction = isTransactionEvent$1(event);
    const isError2 = isErrorEvent$1(event);
    const eventType = event.type || "error";
    const beforeSendLabel = `before send for type \`${eventType}\``;
    const parsedSampleRate = typeof sampleRate === "undefined" ? void 0 : parseSampleRate(sampleRate);
    if (isError2 && typeof parsedSampleRate === "number" && Math.random() > parsedSampleRate) {
      this.recordDroppedEvent("sample_rate", "error", event);
      return rejectedSyncPromise(
        new SentryError(
          `Discarding event because it's not included in the random sample (sampling rate = ${sampleRate})`,
          "log"
        )
      );
    }
    const dataCategory = eventType === "replay_event" ? "replay" : eventType;
    const sdkProcessingMetadata = event.sdkProcessingMetadata || {};
    const capturedSpanIsolationScope = sdkProcessingMetadata.capturedSpanIsolationScope;
    return this._prepareEvent(event, hint, currentScope, capturedSpanIsolationScope).then((prepared) => {
      if (prepared === null) {
        this.recordDroppedEvent("event_processor", dataCategory, event);
        throw new SentryError("An event processor returned `null`, will not send event.", "log");
      }
      const isInternalException = hint.data && hint.data.__sentry__ === true;
      if (isInternalException) {
        return prepared;
      }
      const result = processBeforeSend(this, options2, prepared, hint);
      return _validateBeforeSendResult(result, beforeSendLabel);
    }).then((processedEvent) => {
      if (processedEvent === null) {
        this.recordDroppedEvent("before_send", dataCategory, event);
        if (isTransaction) {
          const spans = event.spans || [];
          const spanCount = 1 + spans.length;
          this.recordDroppedEvent("before_send", "span", spanCount);
        }
        throw new SentryError(`${beforeSendLabel} returned \`null\`, will not send event.`, "log");
      }
      const session = currentScope && currentScope.getSession();
      if (!isTransaction && session) {
        this._updateSessionFromEvent(session, processedEvent);
      }
      if (isTransaction) {
        const spanCountBefore = processedEvent.sdkProcessingMetadata && processedEvent.sdkProcessingMetadata.spanCountBeforeProcessing || 0;
        const spanCountAfter = processedEvent.spans ? processedEvent.spans.length : 0;
        const droppedSpanCount = spanCountBefore - spanCountAfter;
        if (droppedSpanCount > 0) {
          this.recordDroppedEvent("before_send", "span", droppedSpanCount);
        }
      }
      const transactionInfo = processedEvent.transaction_info;
      if (isTransaction && transactionInfo && processedEvent.transaction !== event.transaction) {
        const source = "custom";
        processedEvent.transaction_info = {
          ...transactionInfo,
          source
        };
      }
      this.sendEvent(processedEvent, hint);
      return processedEvent;
    }).then(null, (reason) => {
      if (reason instanceof SentryError) {
        throw reason;
      }
      this.captureException(reason, {
        data: {
          __sentry__: true
        },
        originalException: reason
      });
      throw new SentryError(
        `Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.
Reason: ${reason}`
      );
    });
  }
  /**
   * Occupies the client with processing and event
   */
  _process(promise) {
    this._numProcessing++;
    void promise.then(
      (value) => {
        this._numProcessing--;
        return value;
      },
      (reason) => {
        this._numProcessing--;
        return reason;
      }
    );
  }
  /**
   * Clears outcomes on this client and returns them.
   */
  _clearOutcomes() {
    const outcomes = this._outcomes;
    this._outcomes = {};
    return Object.entries(outcomes).map(([key, quantity]) => {
      const [reason, category] = key.split(":");
      return {
        reason,
        category,
        quantity
      };
    });
  }
  /**
   * Sends client reports as an envelope.
   */
  _flushOutcomes() {
    DEBUG_BUILD$6 && logger$5.log("Flushing outcomes...");
    const outcomes = this._clearOutcomes();
    if (outcomes.length === 0) {
      DEBUG_BUILD$6 && logger$5.log("No outcomes to send");
      return;
    }
    if (!this._dsn) {
      DEBUG_BUILD$6 && logger$5.log("No dsn provided, will not send outcomes");
      return;
    }
    DEBUG_BUILD$6 && logger$5.log("Sending outcomes:", outcomes);
    const envelope = createClientReportEnvelope(outcomes, this._options.tunnel && dsnToString(this._dsn));
    this.sendEnvelope(envelope);
  }
  /**
   * @inheritDoc
   */
}
function _validateBeforeSendResult(beforeSendResult, beforeSendLabel) {
  const invalidValueError = `${beforeSendLabel} must return \`null\` or a valid event.`;
  if (isThenable$1(beforeSendResult)) {
    return beforeSendResult.then(
      (event) => {
        if (!isPlainObject$3(event) && event !== null) {
          throw new SentryError(invalidValueError);
        }
        return event;
      },
      (e2) => {
        throw new SentryError(`${beforeSendLabel} rejected with ${e2}`);
      }
    );
  } else if (!isPlainObject$3(beforeSendResult) && beforeSendResult !== null) {
    throw new SentryError(invalidValueError);
  }
  return beforeSendResult;
}
__name(_validateBeforeSendResult, "_validateBeforeSendResult");
function processBeforeSend(client, options2, event, hint) {
  const { beforeSend, beforeSendTransaction, beforeSendSpan } = options2;
  if (isErrorEvent$1(event) && beforeSend) {
    return beforeSend(event, hint);
  }
  if (isTransactionEvent$1(event)) {
    if (event.spans && beforeSendSpan) {
      const processedSpans = [];
      for (const span of event.spans) {
        const processedSpan = beforeSendSpan(span);
        if (processedSpan) {
          processedSpans.push(processedSpan);
        } else {
          showSpanDropWarning();
          client.recordDroppedEvent("before_send", "span");
        }
      }
      event.spans = processedSpans;
    }
    if (beforeSendTransaction) {
      if (event.spans) {
        const spanCountBefore = event.spans.length;
        event.sdkProcessingMetadata = {
          ...event.sdkProcessingMetadata,
          spanCountBeforeProcessing: spanCountBefore
        };
      }
      return beforeSendTransaction(event, hint);
    }
  }
  return event;
}
__name(processBeforeSend, "processBeforeSend");
function isErrorEvent$1(event) {
  return event.type === void 0;
}
__name(isErrorEvent$1, "isErrorEvent$1");
function isTransactionEvent$1(event) {
  return event.type === "transaction";
}
__name(isTransactionEvent$1, "isTransactionEvent$1");
function createCheckInEnvelope(checkIn, dynamicSamplingContext, metadata, tunnel, dsn) {
  const headers = {
    sent_at: (/* @__PURE__ */ new Date()).toISOString()
  };
  if (metadata && metadata.sdk) {
    headers.sdk = {
      name: metadata.sdk.name,
      version: metadata.sdk.version
    };
  }
  if (!!tunnel && !!dsn) {
    headers.dsn = dsnToString(dsn);
  }
  if (dynamicSamplingContext) {
    headers.trace = dropUndefinedKeys(dynamicSamplingContext);
  }
  const item = createCheckInEnvelopeItem(checkIn);
  return createEnvelope(headers, [item]);
}
__name(createCheckInEnvelope, "createCheckInEnvelope");
function createCheckInEnvelopeItem(checkIn) {
  const checkInHeaders = {
    type: "check_in"
  };
  return [checkInHeaders, checkIn];
}
__name(createCheckInEnvelopeItem, "createCheckInEnvelopeItem");
function parseStackFrames$1(stackParser, error2) {
  return stackParser(error2.stack || "", 1);
}
__name(parseStackFrames$1, "parseStackFrames$1");
function exceptionFromError$1(stackParser, error2) {
  const exception = {
    type: error2.name || error2.constructor.name,
    value: error2.message
  };
  const frames = parseStackFrames$1(stackParser, error2);
  if (frames.length) {
    exception.stacktrace = { frames };
  }
  return exception;
}
__name(exceptionFromError$1, "exceptionFromError$1");
function getErrorPropertyFromObject$1(obj) {
  for (const prop2 in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, prop2)) {
      const value = obj[prop2];
      if (value instanceof Error) {
        return value;
      }
    }
  }
  return void 0;
}
__name(getErrorPropertyFromObject$1, "getErrorPropertyFromObject$1");
function getMessageForObject(exception) {
  if ("name" in exception && typeof exception.name === "string") {
    let message = `'${exception.name}' captured as exception`;
    if ("message" in exception && typeof exception.message === "string") {
      message += ` with message '${exception.message}'`;
    }
    return message;
  } else if ("message" in exception && typeof exception.message === "string") {
    return exception.message;
  }
  const keys2 = extractExceptionKeysForMessage(exception);
  if (isErrorEvent$2(exception)) {
    return `Event \`ErrorEvent\` captured as exception with message \`${exception.message}\``;
  }
  const className = getObjectClassName$1(exception);
  return `${className && className !== "Object" ? `'${className}'` : "Object"} captured as exception with keys: ${keys2}`;
}
__name(getMessageForObject, "getMessageForObject");
function getObjectClassName$1(obj) {
  try {
    const prototype2 = Object.getPrototypeOf(obj);
    return prototype2 ? prototype2.constructor.name : void 0;
  } catch (e2) {
  }
}
__name(getObjectClassName$1, "getObjectClassName$1");
function getException(client, mechanism, exception, hint) {
  if (isError(exception)) {
    return [exception, void 0];
  }
  mechanism.synthetic = true;
  if (isPlainObject$3(exception)) {
    const normalizeDepth = client && client.getOptions().normalizeDepth;
    const extras = { ["__serialized__"]: normalizeToSize(exception, normalizeDepth) };
    const errorFromProp = getErrorPropertyFromObject$1(exception);
    if (errorFromProp) {
      return [errorFromProp, extras];
    }
    const message = getMessageForObject(exception);
    const ex2 = hint && hint.syntheticException || new Error(message);
    ex2.message = message;
    return [ex2, extras];
  }
  const ex = hint && hint.syntheticException || new Error(exception);
  ex.message = `${exception}`;
  return [ex, void 0];
}
__name(getException, "getException");
function eventFromUnknownInput$1(client, stackParser, exception, hint) {
  const providedMechanism = hint && hint.data && hint.data.mechanism;
  const mechanism = providedMechanism || {
    handled: true,
    type: "generic"
  };
  const [ex, extras] = getException(client, mechanism, exception, hint);
  const event = {
    exception: {
      values: [exceptionFromError$1(stackParser, ex)]
    }
  };
  if (extras) {
    event.extra = extras;
  }
  addExceptionTypeValue(event, void 0, void 0);
  addExceptionMechanism(event, mechanism);
  return {
    ...event,
    event_id: hint && hint.event_id
  };
}
__name(eventFromUnknownInput$1, "eventFromUnknownInput$1");
function eventFromMessage$1(stackParser, message, level = "info", hint, attachStacktrace) {
  const event = {
    event_id: hint && hint.event_id,
    level
  };
  if (attachStacktrace && hint && hint.syntheticException) {
    const frames = parseStackFrames$1(stackParser, hint.syntheticException);
    if (frames.length) {
      event.exception = {
        values: [
          {
            value: message,
            stacktrace: { frames }
          }
        ]
      };
      addExceptionMechanism(event, { synthetic: true });
    }
  }
  if (isParameterizedString(message)) {
    const { __sentry_template_string__, __sentry_template_values__ } = message;
    event.logentry = {
      message: __sentry_template_string__,
      params: __sentry_template_values__
    };
    return event;
  }
  event.message = message;
  return event;
}
__name(eventFromMessage$1, "eventFromMessage$1");
class ServerRuntimeClient extends BaseClient {
  static {
    __name(this, "ServerRuntimeClient");
  }
  // eslint-disable-next-line deprecation/deprecation
  /**
   * Creates a new Edge SDK instance.
   * @param options Configuration options for this SDK.
   */
  constructor(options2) {
    registerSpanErrorInstrumentation();
    super(options2);
  }
  /**
   * @inheritDoc
   */
  eventFromException(exception, hint) {
    const event = eventFromUnknownInput$1(this, this._options.stackParser, exception, hint);
    event.level = "error";
    return resolvedSyncPromise(event);
  }
  /**
   * @inheritDoc
   */
  eventFromMessage(message, level = "info", hint) {
    return resolvedSyncPromise(
      eventFromMessage$1(this._options.stackParser, message, level, hint, this._options.attachStacktrace)
    );
  }
  /**
   * @inheritDoc
   */
  captureException(exception, hint, scope) {
    if (this._options.autoSessionTracking && this._sessionFlusher) {
      const requestSession = getIsolationScope().getRequestSession();
      if (requestSession && requestSession.status === "ok") {
        requestSession.status = "errored";
      }
    }
    return super.captureException(exception, hint, scope);
  }
  /**
   * @inheritDoc
   */
  captureEvent(event, hint, scope) {
    if (this._options.autoSessionTracking && this._sessionFlusher) {
      const eventType = event.type || "exception";
      const isException = eventType === "exception" && event.exception && event.exception.values && event.exception.values.length > 0;
      if (isException) {
        const requestSession = getIsolationScope().getRequestSession();
        if (requestSession && requestSession.status === "ok") {
          requestSession.status = "errored";
        }
      }
    }
    return super.captureEvent(event, hint, scope);
  }
  /**
   *
   * @inheritdoc
   */
  close(timeout) {
    if (this._sessionFlusher) {
      this._sessionFlusher.close();
    }
    return super.close(timeout);
  }
  /**
   * Initializes an instance of SessionFlusher on the client which will aggregate and periodically flush session data.
   *
   * NOTICE: This method will implicitly create an interval that is periodically called.
   * To clean up this resources, call `.close()` when you no longer intend to use the client.
   * Not doing so will result in a memory leak.
   */
  initSessionFlusher() {
    const { release, environment } = this._options;
    if (!release) {
      DEBUG_BUILD$6 && logger$5.warn("Cannot initialize an instance of SessionFlusher if no release is provided!");
    } else {
      this._sessionFlusher = new SessionFlusher(this, {
        release,
        environment
      });
    }
  }
  /**
   * Create a cron monitor check in and send it to Sentry.
   *
   * @param checkIn An object that describes a check in.
   * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want
   * to create a monitor automatically when sending a check in.
   */
  captureCheckIn(checkIn, monitorConfig, scope) {
    const id2 = "checkInId" in checkIn && checkIn.checkInId ? checkIn.checkInId : uuid4();
    if (!this._isEnabled()) {
      DEBUG_BUILD$6 && logger$5.warn("SDK not enabled, will not capture checkin.");
      return id2;
    }
    const options2 = this.getOptions();
    const { release, environment, tunnel } = options2;
    const serializedCheckIn = {
      check_in_id: id2,
      monitor_slug: checkIn.monitorSlug,
      status: checkIn.status,
      release,
      environment
    };
    if ("duration" in checkIn) {
      serializedCheckIn.duration = checkIn.duration;
    }
    if (monitorConfig) {
      serializedCheckIn.monitor_config = {
        schedule: monitorConfig.schedule,
        checkin_margin: monitorConfig.checkinMargin,
        max_runtime: monitorConfig.maxRuntime,
        timezone: monitorConfig.timezone,
        failure_issue_threshold: monitorConfig.failureIssueThreshold,
        recovery_threshold: monitorConfig.recoveryThreshold
      };
    }
    const [dynamicSamplingContext, traceContext] = this._getTraceInfoFromScope(scope);
    if (traceContext) {
      serializedCheckIn.contexts = {
        trace: traceContext
      };
    }
    const envelope = createCheckInEnvelope(
      serializedCheckIn,
      dynamicSamplingContext,
      this.getSdkMetadata(),
      tunnel,
      this.getDsn()
    );
    DEBUG_BUILD$6 && logger$5.info("Sending checkin:", checkIn.monitorSlug, checkIn.status);
    this.sendEnvelope(envelope);
    return id2;
  }
  /**
   * Method responsible for capturing/ending a request session by calling `incrementSessionStatusCount` to increment
   * appropriate session aggregates bucket
   *
   * @deprecated This method should not be used or extended. It's functionality will move into the `httpIntegration` and not be part of any public API.
   */
  _captureRequestSession() {
    if (!this._sessionFlusher) {
      DEBUG_BUILD$6 && logger$5.warn("Discarded request mode session because autoSessionTracking option was disabled");
    } else {
      this._sessionFlusher.incrementSessionStatusCount();
    }
  }
  /**
   * @inheritDoc
   */
  _prepareEvent(event, hint, scope, isolationScope) {
    if (this._options.platform) {
      event.platform = event.platform || this._options.platform;
    }
    if (this._options.runtime) {
      event.contexts = {
        ...event.contexts,
        runtime: (event.contexts || {}).runtime || this._options.runtime
      };
    }
    if (this._options.serverName) {
      event.server_name = event.server_name || this._options.serverName;
    }
    return super._prepareEvent(event, hint, scope, isolationScope);
  }
  /** Extract trace information from scope */
  _getTraceInfoFromScope(scope) {
    if (!scope) {
      return [void 0, void 0];
    }
    const span = _getSpanForScope(scope);
    const traceContext = span ? spanToTraceContext(span) : getTraceContextFromScope(scope);
    const dynamicSamplingContext = span ? getDynamicSamplingContextFromSpan(span) : getDynamicSamplingContextFromScope(this, scope);
    return [dynamicSamplingContext, traceContext];
  }
}
function initAndBind(clientClass, options2) {
  if (options2.debug === true) {
    if (DEBUG_BUILD$6) {
      logger$5.enable();
    } else {
      consoleSandbox(() => {
        console.warn("[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.");
      });
    }
  }
  const scope = getCurrentScope();
  scope.update(options2.initialScope);
  const client = new clientClass(options2);
  setCurrentClient(client);
  client.init();
  return client;
}
__name(initAndBind, "initAndBind");
function setCurrentClient(client) {
  getCurrentScope().setClient(client);
}
__name(setCurrentClient, "setCurrentClient");
function makePromiseBuffer(limit2) {
  const buffer = [];
  function isReady() {
    return limit2 === void 0 || buffer.length < limit2;
  }
  __name(isReady, "isReady");
  function remove2(task) {
    return buffer.splice(buffer.indexOf(task), 1)[0] || Promise.resolve(void 0);
  }
  __name(remove2, "remove");
  function add3(taskProducer) {
    if (!isReady()) {
      return rejectedSyncPromise(new SentryError("Not adding Promise because buffer limit was reached."));
    }
    const task = taskProducer();
    if (buffer.indexOf(task) === -1) {
      buffer.push(task);
    }
    void task.then(() => remove2(task)).then(
      null,
      () => remove2(task).then(null, () => {
      })
    );
    return task;
  }
  __name(add3, "add");
  function drain(timeout) {
    return new SyncPromise((resolve2, reject) => {
      let counter = buffer.length;
      if (!counter) {
        return resolve2(true);
      }
      const capturedSetTimeout = setTimeout(() => {
        if (timeout && timeout > 0) {
          resolve2(false);
        }
      }, timeout);
      buffer.forEach((item) => {
        void resolvedSyncPromise(item).then(() => {
          if (!--counter) {
            clearTimeout(capturedSetTimeout);
            resolve2(true);
          }
        }, reject);
      });
    });
  }
  __name(drain, "drain");
  return {
    $: buffer,
    add: add3,
    drain
  };
}
__name(makePromiseBuffer, "makePromiseBuffer");
const DEFAULT_RETRY_AFTER = 60 * 1e3;
function parseRetryAfterHeader(header, now2 = Date.now()) {
  const headerDelay = parseInt(`${header}`, 10);
  if (!isNaN(headerDelay)) {
    return headerDelay * 1e3;
  }
  const headerDate = Date.parse(`${header}`);
  if (!isNaN(headerDate)) {
    return headerDate - now2;
  }
  return DEFAULT_RETRY_AFTER;
}
__name(parseRetryAfterHeader, "parseRetryAfterHeader");
function disabledUntil(limits, dataCategory) {
  return limits[dataCategory] || limits.all || 0;
}
__name(disabledUntil, "disabledUntil");
function isRateLimited(limits, dataCategory, now2 = Date.now()) {
  return disabledUntil(limits, dataCategory) > now2;
}
__name(isRateLimited, "isRateLimited");
function updateRateLimits(limits, { statusCode, headers }, now2 = Date.now()) {
  const updatedRateLimits = {
    ...limits
  };
  const rateLimitHeader = headers && headers["x-sentry-rate-limits"];
  const retryAfterHeader = headers && headers["retry-after"];
  if (rateLimitHeader) {
    for (const limit2 of rateLimitHeader.trim().split(",")) {
      const [retryAfter, categories, , , namespaces] = limit2.split(":", 5);
      const headerDelay = parseInt(retryAfter, 10);
      const delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1e3;
      if (!categories) {
        updatedRateLimits.all = now2 + delay;
      } else {
        for (const category of categories.split(";")) {
          if (category === "metric_bucket") {
            if (!namespaces || namespaces.split(";").includes("custom")) {
              updatedRateLimits[category] = now2 + delay;
            }
          } else {
            updatedRateLimits[category] = now2 + delay;
          }
        }
      }
    }
  } else if (retryAfterHeader) {
    updatedRateLimits.all = now2 + parseRetryAfterHeader(retryAfterHeader, now2);
  } else if (statusCode === 429) {
    updatedRateLimits.all = now2 + 60 * 1e3;
  }
  return updatedRateLimits;
}
__name(updateRateLimits, "updateRateLimits");
const DEFAULT_TRANSPORT_BUFFER_SIZE = 64;
function createTransport(options2, makeRequest2, buffer = makePromiseBuffer(
  options2.bufferSize || DEFAULT_TRANSPORT_BUFFER_SIZE
)) {
  let rateLimits = {};
  const flush2 = /* @__PURE__ */ __name((timeout) => buffer.drain(timeout), "flush");
  function send(envelope) {
    const filteredEnvelopeItems = [];
    forEachEnvelopeItem(envelope, (item, type) => {
      const dataCategory = envelopeItemTypeToDataCategory(type);
      if (isRateLimited(rateLimits, dataCategory)) {
        const event = getEventForEnvelopeItem(item, type);
        options2.recordDroppedEvent("ratelimit_backoff", dataCategory, event);
      } else {
        filteredEnvelopeItems.push(item);
      }
    });
    if (filteredEnvelopeItems.length === 0) {
      return resolvedSyncPromise({});
    }
    const filteredEnvelope = createEnvelope(envelope[0], filteredEnvelopeItems);
    const recordEnvelopeLoss = /* @__PURE__ */ __name((reason) => {
      forEachEnvelopeItem(filteredEnvelope, (item, type) => {
        const event = getEventForEnvelopeItem(item, type);
        options2.recordDroppedEvent(reason, envelopeItemTypeToDataCategory(type), event);
      });
    }, "recordEnvelopeLoss");
    const requestTask = /* @__PURE__ */ __name(() => makeRequest2({ body: serializeEnvelope(filteredEnvelope) }).then(
      (response) => {
        if (response.statusCode !== void 0 && (response.statusCode < 200 || response.statusCode >= 300)) {
          DEBUG_BUILD$6 && logger$5.warn(`Sentry responded with status code ${response.statusCode} to sent event.`);
        }
        rateLimits = updateRateLimits(rateLimits, response);
        return response;
      },
      (error2) => {
        recordEnvelopeLoss("network_error");
        throw error2;
      }
    ), "requestTask");
    return buffer.add(requestTask).then(
      (result) => result,
      (error2) => {
        if (error2 instanceof SentryError) {
          DEBUG_BUILD$6 && logger$5.error("Skipped sending event because buffer is full.");
          recordEnvelopeLoss("queue_overflow");
          return resolvedSyncPromise({});
        } else {
          throw error2;
        }
      }
    );
  }
  __name(send, "send");
  return {
    send,
    flush: flush2
  };
}
__name(createTransport, "createTransport");
function getEventForEnvelopeItem(item, type) {
  if (type !== "event" && type !== "transaction") {
    return void 0;
  }
  return Array.isArray(item) ? item[1] : void 0;
}
__name(getEventForEnvelopeItem, "getEventForEnvelopeItem");
const MIN_DELAY = 100;
const START_DELAY = 5e3;
const MAX_DELAY = 36e5;
function makeOfflineTransport(createTransport2) {
  function log2(...args) {
    DEBUG_BUILD$6 && logger$5.info("[Offline]:", ...args);
  }
  __name(log2, "log");
  return (options2) => {
    const transport = createTransport2(options2);
    if (!options2.createStore) {
      throw new Error("No `createStore` function was provided");
    }
    const store = options2.createStore(options2);
    let retryDelay = START_DELAY;
    let flushTimer;
    function shouldQueue(env, error2, retryDelay2) {
      if (envelopeContainsItemType(env, ["client_report"])) {
        return false;
      }
      if (options2.shouldStore) {
        return options2.shouldStore(env, error2, retryDelay2);
      }
      return true;
    }
    __name(shouldQueue, "shouldQueue");
    function flushIn(delay) {
      if (flushTimer) {
        clearTimeout(flushTimer);
      }
      flushTimer = setTimeout(async () => {
        flushTimer = void 0;
        const found2 = await store.shift();
        if (found2) {
          log2("Attempting to send previously queued event");
          found2[0].sent_at = (/* @__PURE__ */ new Date()).toISOString();
          void send(found2, true).catch((e2) => {
            log2("Failed to retry sending", e2);
          });
        }
      }, delay);
      if (typeof flushTimer !== "number" && flushTimer.unref) {
        flushTimer.unref();
      }
    }
    __name(flushIn, "flushIn");
    function flushWithBackOff() {
      if (flushTimer) {
        return;
      }
      flushIn(retryDelay);
      retryDelay = Math.min(retryDelay * 2, MAX_DELAY);
    }
    __name(flushWithBackOff, "flushWithBackOff");
    async function send(envelope, isRetry = false) {
      if (!isRetry && envelopeContainsItemType(envelope, ["replay_event", "replay_recording"])) {
        await store.push(envelope);
        flushIn(MIN_DELAY);
        return {};
      }
      try {
        const result = await transport.send(envelope);
        let delay = MIN_DELAY;
        if (result) {
          if (result.headers && result.headers["retry-after"]) {
            delay = parseRetryAfterHeader(result.headers["retry-after"]);
          } else if (result.headers && result.headers["x-sentry-rate-limits"]) {
            delay = 6e4;
          } else if ((result.statusCode || 0) >= 400) {
            return result;
          }
        }
        flushIn(delay);
        retryDelay = START_DELAY;
        return result;
      } catch (e2) {
        if (await shouldQueue(envelope, e2, retryDelay)) {
          if (isRetry) {
            await store.unshift(envelope);
          } else {
            await store.push(envelope);
          }
          flushWithBackOff();
          log2("Error sending. Event queued.", e2);
          return {};
        } else {
          throw e2;
        }
      }
    }
    __name(send, "send");
    if (options2.flushAtStartup) {
      flushWithBackOff();
    }
    return {
      send,
      flush: /* @__PURE__ */ __name((t2) => transport.flush(t2), "flush")
    };
  };
}
__name(makeOfflineTransport, "makeOfflineTransport");
function eventFromEnvelope(env, types) {
  let event;
  forEachEnvelopeItem(env, (item, type) => {
    if (types.includes(type)) {
      event = Array.isArray(item) ? item[1] : void 0;
    }
    return !!event;
  });
  return event;
}
__name(eventFromEnvelope, "eventFromEnvelope");
function makeOverrideReleaseTransport(createTransport2, release) {
  return (options2) => {
    const transport = createTransport2(options2);
    return {
      ...transport,
      send: /* @__PURE__ */ __name(async (envelope) => {
        const event = eventFromEnvelope(envelope, ["event", "transaction", "profile", "replay_event"]);
        if (event) {
          event.release = release;
        }
        return transport.send(envelope);
      }, "send")
    };
  };
}
__name(makeOverrideReleaseTransport, "makeOverrideReleaseTransport");
function overrideDsn(envelope, dsn) {
  return createEnvelope(
    dsn ? {
      ...envelope[0],
      dsn
    } : envelope[0],
    envelope[1]
  );
}
__name(overrideDsn, "overrideDsn");
function makeMultiplexedTransport(createTransport2, matcher) {
  return (options2) => {
    const fallbackTransport = createTransport2(options2);
    const otherTransports = /* @__PURE__ */ new Map();
    function getTransport(dsn, release) {
      const key = release ? `${dsn}:${release}` : dsn;
      let transport = otherTransports.get(key);
      if (!transport) {
        const validatedDsn = dsnFromString(dsn);
        if (!validatedDsn) {
          return void 0;
        }
        const url = getEnvelopeEndpointWithUrlEncodedAuth(validatedDsn, options2.tunnel);
        transport = release ? makeOverrideReleaseTransport(createTransport2, release)({ ...options2, url }) : createTransport2({ ...options2, url });
        otherTransports.set(key, transport);
      }
      return [dsn, transport];
    }
    __name(getTransport, "getTransport");
    async function send(envelope) {
      function getEvent(types) {
        const eventTypes = types && types.length ? types : ["event"];
        return eventFromEnvelope(envelope, eventTypes);
      }
      __name(getEvent, "getEvent");
      const transports = matcher({ envelope, getEvent }).map((result) => {
        if (typeof result === "string") {
          return getTransport(result, void 0);
        } else {
          return getTransport(result.dsn, result.release);
        }
      }).filter((t2) => !!t2);
      const transportsWithFallback = transports.length ? transports : [["", fallbackTransport]];
      const results = await Promise.all(
        transportsWithFallback.map(([dsn, transport]) => transport.send(overrideDsn(envelope, dsn)))
      );
      return results[0];
    }
    __name(send, "send");
    async function flush2(timeout) {
      const allTransports = [...otherTransports.values(), fallbackTransport];
      const results = await Promise.all(allTransports.map((transport) => transport.flush(timeout)));
      return results.every((r2) => r2);
    }
    __name(flush2, "flush");
    return {
      send,
      flush: flush2
    };
  };
}
__name(makeMultiplexedTransport, "makeMultiplexedTransport");
function isSentryRequestUrl(url, client) {
  const dsn = client && client.getDsn();
  const tunnel = client && client.getOptions().tunnel;
  return checkDsn(url, dsn) || checkTunnel(url, tunnel);
}
__name(isSentryRequestUrl, "isSentryRequestUrl");
function checkTunnel(url, tunnel) {
  if (!tunnel) {
    return false;
  }
  return removeTrailingSlash$1(url) === removeTrailingSlash$1(tunnel);
}
__name(checkTunnel, "checkTunnel");
function checkDsn(url, dsn) {
  return dsn ? url.includes(dsn.host) : false;
}
__name(checkDsn, "checkDsn");
function removeTrailingSlash$1(str) {
  return str[str.length - 1] === "/" ? str.slice(0, -1) : str;
}
__name(removeTrailingSlash$1, "removeTrailingSlash$1");
function parameterize(strings, ...values) {
  const formatted = new String(String.raw(strings, ...values));
  formatted.__sentry_template_string__ = strings.join("\0").replace(/%/g, "%%").replace(/\0/g, "%s");
  formatted.__sentry_template_values__ = values;
  return formatted;
}
__name(parameterize, "parameterize");
function applySdkMetadata(options2, name2, names = [name2], source = "npm") {
  const metadata = options2._metadata || {};
  if (!metadata.sdk) {
    metadata.sdk = {
      name: `sentry.javascript.${name2}`,
      packages: names.map((name3) => ({
        name: `${source}:@sentry/${name3}`,
        version: SDK_VERSION$2
      })),
      version: SDK_VERSION$2
    };
  }
  options2._metadata = metadata;
}
__name(applySdkMetadata, "applySdkMetadata");
function getTraceData(options2 = {}) {
  const client = getClient();
  if (!isEnabled() || !client) {
    return {};
  }
  const carrier = getMainCarrier();
  const acs = getAsyncContextStrategy(carrier);
  if (acs.getTraceData) {
    return acs.getTraceData(options2);
  }
  const scope = getCurrentScope();
  const span = options2.span || getActiveSpan();
  const sentryTrace = span ? spanToTraceHeader(span) : scopeToTraceHeader(scope);
  const dsc = span ? getDynamicSamplingContextFromSpan(span) : getDynamicSamplingContextFromScope(client, scope);
  const baggage = dynamicSamplingContextToSentryBaggageHeader(dsc);
  const isValidSentryTraceHeader = TRACEPARENT_REGEXP.test(sentryTrace);
  if (!isValidSentryTraceHeader) {
    logger$5.warn("Invalid sentry-trace data. Cannot generate trace data");
    return {};
  }
  return {
    "sentry-trace": sentryTrace,
    baggage
  };
}
__name(getTraceData, "getTraceData");
function scopeToTraceHeader(scope) {
  const { traceId, sampled, spanId } = scope.getPropagationContext();
  return generateSentryTraceHeader(traceId, spanId, sampled);
}
__name(scopeToTraceHeader, "scopeToTraceHeader");
function getTraceMetaTags() {
  return Object.entries(getTraceData()).map(([key, value]) => `<meta name="${key}" content="${value}"/>`).join("\n");
}
__name(getTraceMetaTags, "getTraceMetaTags");
const DEFAULT_BREADCRUMBS = 100;
function addBreadcrumb(breadcrumb, hint) {
  const client = getClient();
  const isolationScope = getIsolationScope();
  if (!client) return;
  const { beforeBreadcrumb = null, maxBreadcrumbs = DEFAULT_BREADCRUMBS } = client.getOptions();
  if (maxBreadcrumbs <= 0) return;
  const timestamp2 = dateTimestampInSeconds();
  const mergedBreadcrumb = { timestamp: timestamp2, ...breadcrumb };
  const finalBreadcrumb = beforeBreadcrumb ? consoleSandbox(() => beforeBreadcrumb(mergedBreadcrumb, hint)) : mergedBreadcrumb;
  if (finalBreadcrumb === null) return;
  if (client.emit) {
    client.emit("beforeAddBreadcrumb", finalBreadcrumb, hint);
  }
  isolationScope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs);
}
__name(addBreadcrumb, "addBreadcrumb");
let originalFunctionToString;
const INTEGRATION_NAME$l = "FunctionToString";
const SETUP_CLIENTS$1 = /* @__PURE__ */ new WeakMap();
const _functionToStringIntegration = /* @__PURE__ */ __name(() => {
  return {
    name: INTEGRATION_NAME$l,
    setupOnce() {
      originalFunctionToString = Function.prototype.toString;
      try {
        Function.prototype.toString = function(...args) {
          const originalFunction = getOriginalFunction(this);
          const context = SETUP_CLIENTS$1.has(getClient()) && originalFunction !== void 0 ? originalFunction : this;
          return originalFunctionToString.apply(context, args);
        };
      } catch (e2) {
      }
    },
    setup(client) {
      SETUP_CLIENTS$1.set(client, true);
    }
  };
}, "_functionToStringIntegration");
const functionToStringIntegration = defineIntegration(_functionToStringIntegration);
const DEFAULT_IGNORE_ERRORS = [
  /^Script error\.?$/,
  /^Javascript error: Script error\.? on line 0$/,
  /^ResizeObserver loop completed with undelivered notifications.$/,
  // The browser logs this when a ResizeObserver handler takes a bit longer. Usually this is not an actual issue though. It indicates slowness.
  /^Cannot redefine property: googletag$/,
  // This is thrown when google tag manager is used in combination with an ad blocker
  "undefined is not an object (evaluating 'a.L')",
  // Random error that happens but not actionable or noticeable to end-users.
  `can't redefine non-configurable property "solana"`,
  // Probably a browser extension or custom browser (Brave) throwing this error
  "vv().getRestrictions is not a function. (In 'vv().getRestrictions(1,a)', 'vv().getRestrictions' is undefined)",
  // Error thrown by GTM, seemingly not affecting end-users
  "Can't find variable: _AutofillCallbackHandler",
  // Unactionable error in instagram webview https://developers.facebook.com/community/threads/320013549791141/
  /^Non-Error promise rejection captured with value: Object Not Found Matching Id:\d+, MethodName:simulateEvent, ParamCount:\d+$/
  // unactionable error from CEFSharp, a .NET library that embeds chromium in .NET apps
];
const INTEGRATION_NAME$k = "InboundFilters";
const _inboundFiltersIntegration = /* @__PURE__ */ __name((options2 = {}) => {
  return {
    name: INTEGRATION_NAME$k,
    processEvent(event, _hint, client) {
      const clientOptions = client.getOptions();
      const mergedOptions = _mergeOptions(options2, clientOptions);
      return _shouldDropEvent$1(event, mergedOptions) ? null : event;
    }
  };
}, "_inboundFiltersIntegration");
const inboundFiltersIntegration = defineIntegration(_inboundFiltersIntegration);
function _mergeOptions(internalOptions = {}, clientOptions = {}) {
  return {
    allowUrls: [...internalOptions.allowUrls || [], ...clientOptions.allowUrls || []],
    denyUrls: [...internalOptions.denyUrls || [], ...clientOptions.denyUrls || []],
    ignoreErrors: [
      ...internalOptions.ignoreErrors || [],
      ...clientOptions.ignoreErrors || [],
      ...internalOptions.disableErrorDefaults ? [] : DEFAULT_IGNORE_ERRORS
    ],
    ignoreTransactions: [...internalOptions.ignoreTransactions || [], ...clientOptions.ignoreTransactions || []],
    ignoreInternal: internalOptions.ignoreInternal !== void 0 ? internalOptions.ignoreInternal : true
  };
}
__name(_mergeOptions, "_mergeOptions");
function _shouldDropEvent$1(event, options2) {
  if (options2.ignoreInternal && _isSentryError(event)) {
    DEBUG_BUILD$6 && logger$5.warn(`Event dropped due to being internal Sentry Error.
Event: ${getEventDescription(event)}`);
    return true;
  }
  if (_isIgnoredError(event, options2.ignoreErrors)) {
    DEBUG_BUILD$6 && logger$5.warn(
      `Event dropped due to being matched by \`ignoreErrors\` option.
Event: ${getEventDescription(event)}`
    );
    return true;
  }
  if (_isUselessError(event)) {
    DEBUG_BUILD$6 && logger$5.warn(
      `Event dropped due to not having an error message, error type or stacktrace.
Event: ${getEventDescription(
        event
      )}`
    );
    return true;
  }
  if (_isIgnoredTransaction(event, options2.ignoreTransactions)) {
    DEBUG_BUILD$6 && logger$5.warn(
      `Event dropped due to being matched by \`ignoreTransactions\` option.
Event: ${getEventDescription(event)}`
    );
    return true;
  }
  if (_isDeniedUrl(event, options2.denyUrls)) {
    DEBUG_BUILD$6 && logger$5.warn(
      `Event dropped due to being matched by \`denyUrls\` option.
Event: ${getEventDescription(
        event
      )}.
Url: ${_getEventFilterUrl(event)}`
    );
    return true;
  }
  if (!_isAllowedUrl(event, options2.allowUrls)) {
    DEBUG_BUILD$6 && logger$5.warn(
      `Event dropped due to not being matched by \`allowUrls\` option.
Event: ${getEventDescription(
        event
      )}.
Url: ${_getEventFilterUrl(event)}`
    );
    return true;
  }
  return false;
}
__name(_shouldDropEvent$1, "_shouldDropEvent$1");
function _isIgnoredError(event, ignoreErrors) {
  if (event.type || !ignoreErrors || !ignoreErrors.length) {
    return false;
  }
  return _getPossibleEventMessages(event).some((message) => stringMatchesSomePattern(message, ignoreErrors));
}
__name(_isIgnoredError, "_isIgnoredError");
function _isIgnoredTransaction(event, ignoreTransactions) {
  if (event.type !== "transaction" || !ignoreTransactions || !ignoreTransactions.length) {
    return false;
  }
  const name2 = event.transaction;
  return name2 ? stringMatchesSomePattern(name2, ignoreTransactions) : false;
}
__name(_isIgnoredTransaction, "_isIgnoredTransaction");
function _isDeniedUrl(event, denyUrls) {
  if (!denyUrls || !denyUrls.length) {
    return false;
  }
  const url = _getEventFilterUrl(event);
  return !url ? false : stringMatchesSomePattern(url, denyUrls);
}
__name(_isDeniedUrl, "_isDeniedUrl");
function _isAllowedUrl(event, allowUrls) {
  if (!allowUrls || !allowUrls.length) {
    return true;
  }
  const url = _getEventFilterUrl(event);
  return !url ? true : stringMatchesSomePattern(url, allowUrls);
}
__name(_isAllowedUrl, "_isAllowedUrl");
function _getPossibleEventMessages(event) {
  const possibleMessages = [];
  if (event.message) {
    possibleMessages.push(event.message);
  }
  let lastException;
  try {
    lastException = event.exception.values[event.exception.values.length - 1];
  } catch (e2) {
  }
  if (lastException) {
    if (lastException.value) {
      possibleMessages.push(lastException.value);
      if (lastException.type) {
        possibleMessages.push(`${lastException.type}: ${lastException.value}`);
      }
    }
  }
  return possibleMessages;
}
__name(_getPossibleEventMessages, "_getPossibleEventMessages");
function _isSentryError(event) {
  try {
    return event.exception.values[0].type === "SentryError";
  } catch (e2) {
  }
  return false;
}
__name(_isSentryError, "_isSentryError");
function _getLastValidUrl(frames = []) {
  for (let i2 = frames.length - 1; i2 >= 0; i2--) {
    const frame = frames[i2];
    if (frame && frame.filename !== "<anonymous>" && frame.filename !== "[native code]") {
      return frame.filename || null;
    }
  }
  return null;
}
__name(_getLastValidUrl, "_getLastValidUrl");
function _getEventFilterUrl(event) {
  try {
    let frames;
    try {
      frames = event.exception.values[0].stacktrace.frames;
    } catch (e2) {
    }
    return frames ? _getLastValidUrl(frames) : null;
  } catch (oO) {
    DEBUG_BUILD$6 && logger$5.error(`Cannot extract url for event ${getEventDescription(event)}`);
    return null;
  }
}
__name(_getEventFilterUrl, "_getEventFilterUrl");
function _isUselessError(event) {
  if (event.type) {
    return false;
  }
  if (!event.exception || !event.exception.values || event.exception.values.length === 0) {
    return false;
  }
  return (
    // No top-level message
    !event.message && // There are no exception values that have a stacktrace, a non-generic-Error type or value
    !event.exception.values.some((value) => value.stacktrace || value.type && value.type !== "Error" || value.value)
  );
}
__name(_isUselessError, "_isUselessError");
function applyAggregateErrorsToEvent(exceptionFromErrorImplementation, parser, maxValueLimit = 250, key, limit2, event, hint) {
  if (!event.exception || !event.exception.values || !hint || !isInstanceOf(hint.originalException, Error)) {
    return;
  }
  const originalException = event.exception.values.length > 0 ? event.exception.values[event.exception.values.length - 1] : void 0;
  if (originalException) {
    event.exception.values = truncateAggregateExceptions(
      aggregateExceptionsFromError(
        exceptionFromErrorImplementation,
        parser,
        limit2,
        hint.originalException,
        key,
        event.exception.values,
        originalException,
        0
      ),
      maxValueLimit
    );
  }
}
__name(applyAggregateErrorsToEvent, "applyAggregateErrorsToEvent");
function aggregateExceptionsFromError(exceptionFromErrorImplementation, parser, limit2, error2, key, prevExceptions, exception, exceptionId) {
  if (prevExceptions.length >= limit2 + 1) {
    return prevExceptions;
  }
  let newExceptions = [...prevExceptions];
  if (isInstanceOf(error2[key], Error)) {
    applyExceptionGroupFieldsForParentException(exception, exceptionId);
    const newException = exceptionFromErrorImplementation(parser, error2[key]);
    const newExceptionId = newExceptions.length;
    applyExceptionGroupFieldsForChildException(newException, key, newExceptionId, exceptionId);
    newExceptions = aggregateExceptionsFromError(
      exceptionFromErrorImplementation,
      parser,
      limit2,
      error2[key],
      key,
      [newException, ...newExceptions],
      newException,
      newExceptionId
    );
  }
  if (Array.isArray(error2.errors)) {
    error2.errors.forEach((childError, i2) => {
      if (isInstanceOf(childError, Error)) {
        applyExceptionGroupFieldsForParentException(exception, exceptionId);
        const newException = exceptionFromErrorImplementation(parser, childError);
        const newExceptionId = newExceptions.length;
        applyExceptionGroupFieldsForChildException(newException, `errors[${i2}]`, newExceptionId, exceptionId);
        newExceptions = aggregateExceptionsFromError(
          exceptionFromErrorImplementation,
          parser,
          limit2,
          childError,
          key,
          [newException, ...newExceptions],
          newException,
          newExceptionId
        );
      }
    });
  }
  return newExceptions;
}
__name(aggregateExceptionsFromError, "aggregateExceptionsFromError");
function applyExceptionGroupFieldsForParentException(exception, exceptionId) {
  exception.mechanism = exception.mechanism || { type: "generic", handled: true };
  exception.mechanism = {
    ...exception.mechanism,
    ...exception.type === "AggregateError" && { is_exception_group: true },
    exception_id: exceptionId
  };
}
__name(applyExceptionGroupFieldsForParentException, "applyExceptionGroupFieldsForParentException");
function applyExceptionGroupFieldsForChildException(exception, source, exceptionId, parentId) {
  exception.mechanism = exception.mechanism || { type: "generic", handled: true };
  exception.mechanism = {
    ...exception.mechanism,
    type: "chained",
    source,
    exception_id: exceptionId,
    parent_id: parentId
  };
}
__name(applyExceptionGroupFieldsForChildException, "applyExceptionGroupFieldsForChildException");
function truncateAggregateExceptions(exceptions, maxValueLength) {
  return exceptions.map((exception) => {
    if (exception.value) {
      exception.value = truncate(exception.value, maxValueLength);
    }
    return exception;
  });
}
__name(truncateAggregateExceptions, "truncateAggregateExceptions");
const DEFAULT_KEY$1 = "cause";
const DEFAULT_LIMIT$2 = 5;
const INTEGRATION_NAME$j = "LinkedErrors";
const _linkedErrorsIntegration$1 = /* @__PURE__ */ __name((options2 = {}) => {
  const limit2 = options2.limit || DEFAULT_LIMIT$2;
  const key = options2.key || DEFAULT_KEY$1;
  return {
    name: INTEGRATION_NAME$j,
    preprocessEvent(event, hint, client) {
      const options3 = client.getOptions();
      applyAggregateErrorsToEvent(
        exceptionFromError$1,
        options3.stackParser,
        options3.maxValueLength,
        key,
        limit2,
        event,
        hint
      );
    }
  };
}, "_linkedErrorsIntegration$1");
const linkedErrorsIntegration$1 = defineIntegration(_linkedErrorsIntegration$1);
const filenameMetadataMap = /* @__PURE__ */ new Map();
const parsedStacks = /* @__PURE__ */ new Set();
function ensureMetadataStacksAreParsed(parser) {
  if (!GLOBAL_OBJ._sentryModuleMetadata) {
    return;
  }
  for (const stack of Object.keys(GLOBAL_OBJ._sentryModuleMetadata)) {
    const metadata = GLOBAL_OBJ._sentryModuleMetadata[stack];
    if (parsedStacks.has(stack)) {
      continue;
    }
    parsedStacks.add(stack);
    const frames = parser(stack);
    for (const frame of frames.reverse()) {
      if (frame.filename) {
        filenameMetadataMap.set(frame.filename, metadata);
        break;
      }
    }
  }
}
__name(ensureMetadataStacksAreParsed, "ensureMetadataStacksAreParsed");
function getMetadataForUrl(parser, filename) {
  ensureMetadataStacksAreParsed(parser);
  return filenameMetadataMap.get(filename);
}
__name(getMetadataForUrl, "getMetadataForUrl");
function addMetadataToStackFrames(parser, event) {
  try {
    event.exception.values.forEach((exception) => {
      if (!exception.stacktrace) {
        return;
      }
      for (const frame of exception.stacktrace.frames || []) {
        if (!frame.filename || frame.module_metadata) {
          continue;
        }
        const metadata = getMetadataForUrl(parser, frame.filename);
        if (metadata) {
          frame.module_metadata = metadata;
        }
      }
    });
  } catch (_2) {
  }
}
__name(addMetadataToStackFrames, "addMetadataToStackFrames");
function stripMetadataFromStackFrames(event) {
  try {
    event.exception.values.forEach((exception) => {
      if (!exception.stacktrace) {
        return;
      }
      for (const frame of exception.stacktrace.frames || []) {
        delete frame.module_metadata;
      }
    });
  } catch (_2) {
  }
}
__name(stripMetadataFromStackFrames, "stripMetadataFromStackFrames");
const moduleMetadataIntegration = defineIntegration(() => {
  return {
    name: "ModuleMetadata",
    setup(client) {
      client.on("beforeEnvelope", (envelope) => {
        forEachEnvelopeItem(envelope, (item, type) => {
          if (type === "event") {
            const event = Array.isArray(item) ? item[1] : void 0;
            if (event) {
              stripMetadataFromStackFrames(event);
              item[1] = event;
            }
          }
        });
      });
      client.on("applyFrameMetadata", (event) => {
        if (event.type) {
          return;
        }
        const stackParser = client.getOptions().stackParser;
        addMetadataToStackFrames(stackParser, event);
      });
    }
  };
});
function parseCookie(str) {
  const obj = {};
  let index2 = 0;
  while (index2 < str.length) {
    const eqIdx = str.indexOf("=", index2);
    if (eqIdx === -1) {
      break;
    }
    let endIdx = str.indexOf(";", index2);
    if (endIdx === -1) {
      endIdx = str.length;
    } else if (endIdx < eqIdx) {
      index2 = str.lastIndexOf(";", eqIdx - 1) + 1;
      continue;
    }
    const key = str.slice(index2, eqIdx).trim();
    if (void 0 === obj[key]) {
      let val = str.slice(eqIdx + 1, endIdx).trim();
      if (val.charCodeAt(0) === 34) {
        val = val.slice(1, -1);
      }
      try {
        obj[key] = val.indexOf("%") !== -1 ? decodeURIComponent(val) : val;
      } catch (e2) {
        obj[key] = val;
      }
    }
    index2 = endIdx + 1;
  }
  return obj;
}
__name(parseCookie, "parseCookie");
function parseUrl$1(url) {
  if (!url) {
    return {};
  }
  const match2 = url.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);
  if (!match2) {
    return {};
  }
  const query2 = match2[6] || "";
  const fragment = match2[8] || "";
  return {
    host: match2[4],
    path: match2[5],
    protocol: match2[2],
    search: query2,
    hash: fragment,
    relative: match2[5] + query2 + fragment
    // everything minus origin
  };
}
__name(parseUrl$1, "parseUrl$1");
function stripUrlQueryAndFragment(urlPath) {
  return urlPath.split(/[?#]/, 1)[0];
}
__name(stripUrlQueryAndFragment, "stripUrlQueryAndFragment");
function getNumberOfUrlSegments(url) {
  return url.split(/\\?\//).filter((s2) => s2.length > 0 && s2 !== ",").length;
}
__name(getNumberOfUrlSegments, "getNumberOfUrlSegments");
function getSanitizedUrlString(url) {
  const { protocol, host, path } = url;
  const filteredHost = host && host.replace(/^.*@/, "[filtered]:[filtered]@").replace(/(:80)$/, "").replace(/(:443)$/, "") || "";
  return `${protocol ? `${protocol}://` : ""}${filteredHost}${path}`;
}
__name(getSanitizedUrlString, "getSanitizedUrlString");
const ipHeaderNames = [
  "X-Client-IP",
  "X-Forwarded-For",
  "Fly-Client-IP",
  "CF-Connecting-IP",
  "Fastly-Client-Ip",
  "True-Client-Ip",
  "X-Real-IP",
  "X-Cluster-Client-IP",
  "X-Forwarded",
  "Forwarded-For",
  "Forwarded",
  "X-Vercel-Forwarded-For"
];
function getClientIPAddress(headers) {
  const headerValues = ipHeaderNames.map((headerName) => {
    const rawValue = headers[headerName];
    const value = Array.isArray(rawValue) ? rawValue.join(";") : rawValue;
    if (headerName === "Forwarded") {
      return parseForwardedHeader(value);
    }
    return value && value.split(",").map((v2) => v2.trim());
  });
  const flattenedHeaderValues = headerValues.reduce((acc, val) => {
    if (!val) {
      return acc;
    }
    return acc.concat(val);
  }, []);
  const ipAddress = flattenedHeaderValues.find((ip) => ip !== null && isIP(ip));
  return ipAddress || null;
}
__name(getClientIPAddress, "getClientIPAddress");
function parseForwardedHeader(value) {
  if (!value) {
    return null;
  }
  for (const part of value.split(";")) {
    if (part.startsWith("for=")) {
      return part.slice(4);
    }
  }
  return null;
}
__name(parseForwardedHeader, "parseForwardedHeader");
function isIP(str) {
  const regex2 = /(?:^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$)|(?:^(?:(?:[a-fA-F\d]{1,4}:){7}(?:[a-fA-F\d]{1,4}|:)|(?:[a-fA-F\d]{1,4}:){6}(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|:[a-fA-F\d]{1,4}|:)|(?:[a-fA-F\d]{1,4}:){5}(?::(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,2}|:)|(?:[a-fA-F\d]{1,4}:){4}(?:(?::[a-fA-F\d]{1,4}){0,1}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,3}|:)|(?:[a-fA-F\d]{1,4}:){3}(?:(?::[a-fA-F\d]{1,4}){0,2}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,4}|:)|(?:[a-fA-F\d]{1,4}:){2}(?:(?::[a-fA-F\d]{1,4}){0,3}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,5}|:)|(?:[a-fA-F\d]{1,4}:){1}(?:(?::[a-fA-F\d]{1,4}){0,4}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,6}|:)|(?::(?:(?::[a-fA-F\d]{1,4}){0,5}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,7}|:)))(?:%[0-9a-zA-Z]{1,})?$)/;
  return regex2.test(str);
}
__name(isIP, "isIP");
const DEFAULT_INCLUDES = {
  ip: false,
  request: true,
  user: true
};
const DEFAULT_REQUEST_INCLUDES = ["cookies", "data", "headers", "method", "query_string", "url"];
const DEFAULT_USER_INCLUDES = ["id", "username", "email"];
function extractPathForTransaction(req, options2 = {}) {
  const method = req.method && req.method.toUpperCase();
  let path = "";
  let source = "url";
  if (options2.customRoute || req.route) {
    path = options2.customRoute || `${req.baseUrl || ""}${req.route && req.route.path}`;
    source = "route";
  } else if (req.originalUrl || req.url) {
    path = stripUrlQueryAndFragment(req.originalUrl || req.url || "");
  }
  let name2 = "";
  if (options2.method && method) {
    name2 += method;
  }
  if (options2.method && options2.path) {
    name2 += " ";
  }
  if (options2.path && path) {
    name2 += path;
  }
  return [name2, source];
}
__name(extractPathForTransaction, "extractPathForTransaction");
function extractUserData(user, keys2) {
  const extractedUser = {};
  const attributes = Array.isArray(keys2) ? keys2 : DEFAULT_USER_INCLUDES;
  attributes.forEach((key) => {
    if (user && key in user) {
      extractedUser[key] = user[key];
    }
  });
  return extractedUser;
}
__name(extractUserData, "extractUserData");
function extractRequestData(req, options2 = {}) {
  const { include = DEFAULT_REQUEST_INCLUDES } = options2;
  const requestData = {};
  const headers = req.headers || {};
  const method = req.method;
  const host = headers.host || req.hostname || req.host || "<no host>";
  const protocol = req.protocol === "https" || req.socket && req.socket.encrypted ? "https" : "http";
  const originalUrl = req.originalUrl || req.url || "";
  const absoluteUrl = originalUrl.startsWith(protocol) ? originalUrl : `${protocol}://${host}${originalUrl}`;
  include.forEach((key) => {
    switch (key) {
      case "headers": {
        requestData.headers = headers;
        if (!include.includes("cookies")) {
          delete requestData.headers.cookie;
        }
        if (!include.includes("ip")) {
          ipHeaderNames.forEach((ipHeaderName) => {
            delete requestData.headers[ipHeaderName];
          });
        }
        break;
      }
      case "method": {
        requestData.method = method;
        break;
      }
      case "url": {
        requestData.url = absoluteUrl;
        break;
      }
      case "cookies": {
        requestData.cookies = // TODO (v8 / #5257): We're only sending the empty object for backwards compatibility, so the last bit can
        // come off in v8
        req.cookies || headers.cookie && parseCookie(headers.cookie) || {};
        break;
      }
      case "query_string": {
        requestData.query_string = extractQueryParams(req);
        break;
      }
      case "data": {
        if (method === "GET" || method === "HEAD") {
          break;
        }
        const body = req.body;
        if (body !== void 0) {
          const stringBody = isString$8(body) ? body : isPlainObject$3(body) ? JSON.stringify(normalize$2(body)) : truncate(`${body}`, 1024);
          if (stringBody) {
            requestData.data = stringBody;
          }
        }
        break;
      }
      default: {
        if ({}.hasOwnProperty.call(req, key)) {
          requestData[key] = req[key];
        }
      }
    }
  });
  return requestData;
}
__name(extractRequestData, "extractRequestData");
function addNormalizedRequestDataToEvent(event, req, additionalData, options2) {
  const include = {
    ...DEFAULT_INCLUDES,
    ...options2 && options2.include
  };
  if (include.request) {
    const includeRequest = Array.isArray(include.request) ? [...include.request] : [...DEFAULT_REQUEST_INCLUDES];
    if (include.ip) {
      includeRequest.push("ip");
    }
    const extractedRequestData = extractNormalizedRequestData(req, { include: includeRequest });
    event.request = {
      ...event.request,
      ...extractedRequestData
    };
  }
  if (include.user) {
    const extractedUser = additionalData.user && isPlainObject$3(additionalData.user) ? extractUserData(additionalData.user, include.user) : {};
    if (Object.keys(extractedUser).length) {
      event.user = {
        ...extractedUser,
        ...event.user
      };
    }
  }
  if (include.ip) {
    const ip = req.headers && getClientIPAddress(req.headers) || additionalData.ipAddress;
    if (ip) {
      event.user = {
        ...event.user,
        ip_address: ip
      };
    }
  }
}
__name(addNormalizedRequestDataToEvent, "addNormalizedRequestDataToEvent");
function addRequestDataToEvent(event, req, options2) {
  const include = {
    ...DEFAULT_INCLUDES,
    ...options2 && options2.include
  };
  if (include.request) {
    const includeRequest = Array.isArray(include.request) ? [...include.request] : [...DEFAULT_REQUEST_INCLUDES];
    if (include.ip) {
      includeRequest.push("ip");
    }
    const extractedRequestData = extractRequestData(req, { include: includeRequest });
    event.request = {
      ...event.request,
      ...extractedRequestData
    };
  }
  if (include.user) {
    const extractedUser = req.user && isPlainObject$3(req.user) ? extractUserData(req.user, include.user) : {};
    if (Object.keys(extractedUser).length) {
      event.user = {
        ...event.user,
        ...extractedUser
      };
    }
  }
  if (include.ip) {
    const ip = req.headers && getClientIPAddress(req.headers) || req.ip || req.socket && req.socket.remoteAddress;
    if (ip) {
      event.user = {
        ...event.user,
        ip_address: ip
      };
    }
  }
  return event;
}
__name(addRequestDataToEvent, "addRequestDataToEvent");
function extractQueryParams(req) {
  let originalUrl = req.originalUrl || req.url || "";
  if (!originalUrl) {
    return;
  }
  if (originalUrl.startsWith("/")) {
    originalUrl = `http://dogs.are.great${originalUrl}`;
  }
  try {
    const queryParams = req.query || new URL(originalUrl).search.slice(1);
    return queryParams.length ? queryParams : void 0;
  } catch (e2) {
    return void 0;
  }
}
__name(extractQueryParams, "extractQueryParams");
function winterCGHeadersToDict(winterCGHeaders) {
  const headers = {};
  try {
    winterCGHeaders.forEach((value, key) => {
      if (typeof value === "string") {
        headers[key] = value;
      }
    });
  } catch (e2) {
    DEBUG_BUILD$5 && logger$5.warn("Sentry failed extracting headers from a request object. If you see this, please file an issue.");
  }
  return headers;
}
__name(winterCGHeadersToDict, "winterCGHeadersToDict");
function headersToDict(reqHeaders) {
  const headers = /* @__PURE__ */ Object.create(null);
  try {
    Object.entries(reqHeaders).forEach(([key, value]) => {
      if (typeof value === "string") {
        headers[key] = value;
      }
    });
  } catch (e2) {
    DEBUG_BUILD$5 && logger$5.warn("Sentry failed extracting headers from a request object. If you see this, please file an issue.");
  }
  return headers;
}
__name(headersToDict, "headersToDict");
function winterCGRequestToRequestData(req) {
  const headers = winterCGHeadersToDict(req.headers);
  return {
    method: req.method,
    url: req.url,
    query_string: extractQueryParamsFromUrl(req.url),
    headers
    // TODO: Can we extract body data from the request?
  };
}
__name(winterCGRequestToRequestData, "winterCGRequestToRequestData");
function httpRequestToRequestData(request) {
  const headers = request.headers || {};
  const host = headers.host || "<no host>";
  const protocol = request.socket && request.socket.encrypted ? "https" : "http";
  const originalUrl = request.url || "";
  const absoluteUrl = originalUrl.startsWith(protocol) ? originalUrl : `${protocol}://${host}${originalUrl}`;
  const data = request.body || void 0;
  const cookies2 = request.cookies;
  return dropUndefinedKeys({
    url: absoluteUrl,
    method: request.method,
    query_string: extractQueryParamsFromUrl(originalUrl),
    headers: headersToDict(headers),
    cookies: cookies2,
    data
  });
}
__name(httpRequestToRequestData, "httpRequestToRequestData");
function extractQueryParamsFromUrl(url) {
  if (!url) {
    return;
  }
  try {
    const queryParams = new URL(url, "http://dogs.are.great").search.slice(1);
    return queryParams.length ? queryParams : void 0;
  } catch (e3) {
    return void 0;
  }
}
__name(extractQueryParamsFromUrl, "extractQueryParamsFromUrl");
function extractNormalizedRequestData(normalizedRequest, { include }) {
  const includeKeys = include ? Array.isArray(include) ? include : DEFAULT_REQUEST_INCLUDES : [];
  const requestData = {};
  const headers = { ...normalizedRequest.headers };
  if (includeKeys.includes("headers")) {
    requestData.headers = headers;
    if (!include.includes("cookies")) {
      delete headers.cookie;
    }
    if (!include.includes("ip")) {
      ipHeaderNames.forEach((ipHeaderName) => {
        delete headers[ipHeaderName];
      });
    }
  }
  if (includeKeys.includes("method")) {
    requestData.method = normalizedRequest.method;
  }
  if (includeKeys.includes("url")) {
    requestData.url = normalizedRequest.url;
  }
  if (includeKeys.includes("cookies")) {
    const cookies2 = normalizedRequest.cookies || (headers && headers.cookie ? parseCookie(headers.cookie) : void 0);
    requestData.cookies = cookies2 || {};
  }
  if (includeKeys.includes("query_string")) {
    requestData.query_string = normalizedRequest.query_string;
  }
  if (includeKeys.includes("data")) {
    requestData.data = normalizedRequest.data;
  }
  return requestData;
}
__name(extractNormalizedRequestData, "extractNormalizedRequestData");
const DEFAULT_OPTIONS$3 = {
  include: {
    cookies: true,
    data: true,
    headers: true,
    ip: false,
    query_string: true,
    url: true,
    user: {
      id: true,
      username: true,
      email: true
    }
  },
  transactionNamingScheme: "methodPath"
};
const INTEGRATION_NAME$i = "RequestData";
const _requestDataIntegration = /* @__PURE__ */ __name((options2 = {}) => {
  const _options = {
    ...DEFAULT_OPTIONS$3,
    ...options2,
    include: {
      ...DEFAULT_OPTIONS$3.include,
      ...options2.include,
      user: options2.include && typeof options2.include.user === "boolean" ? options2.include.user : {
        ...DEFAULT_OPTIONS$3.include.user,
        // Unclear why TS still thinks `options.include.user` could be a boolean at this point
        ...(options2.include || {}).user
      }
    }
  };
  return {
    name: INTEGRATION_NAME$i,
    processEvent(event) {
      const { sdkProcessingMetadata = {} } = event;
      const { request, normalizedRequest } = sdkProcessingMetadata;
      const addRequestDataOptions = convertReqDataIntegrationOptsToAddReqDataOpts(_options);
      if (normalizedRequest) {
        const ipAddress = request ? request.ip || request.socket && request.socket.remoteAddress : void 0;
        const user = request ? request.user : void 0;
        addNormalizedRequestDataToEvent(event, normalizedRequest, { ipAddress, user }, addRequestDataOptions);
        return event;
      }
      if (!request) {
        return event;
      }
      return addRequestDataToEvent(event, request, addRequestDataOptions);
    }
  };
}, "_requestDataIntegration");
const requestDataIntegration = defineIntegration(_requestDataIntegration);
function convertReqDataIntegrationOptsToAddReqDataOpts(integrationOptions) {
  const {
    // eslint-disable-next-line deprecation/deprecation
    transactionNamingScheme,
    include: { ip, user, ...requestOptions }
  } = integrationOptions;
  const requestIncludeKeys = ["method"];
  for (const [key, value] of Object.entries(requestOptions)) {
    if (value) {
      requestIncludeKeys.push(key);
    }
  }
  let addReqDataUserOpt;
  if (user === void 0) {
    addReqDataUserOpt = true;
  } else if (typeof user === "boolean") {
    addReqDataUserOpt = user;
  } else {
    const userIncludeKeys = [];
    for (const [key, value] of Object.entries(user)) {
      if (value) {
        userIncludeKeys.push(key);
      }
    }
    addReqDataUserOpt = userIncludeKeys;
  }
  return {
    include: {
      ip,
      user: addReqDataUserOpt,
      request: requestIncludeKeys.length !== 0 ? requestIncludeKeys : void 0,
      transaction: transactionNamingScheme
    }
  };
}
__name(convertReqDataIntegrationOptsToAddReqDataOpts, "convertReqDataIntegrationOptsToAddReqDataOpts");
function addConsoleInstrumentationHandler(handler5) {
  const type = "console";
  addHandler$1(type, handler5);
  maybeInstrument(type, instrumentConsole);
}
__name(addConsoleInstrumentationHandler, "addConsoleInstrumentationHandler");
function instrumentConsole() {
  if (!("console" in GLOBAL_OBJ)) {
    return;
  }
  CONSOLE_LEVELS$1.forEach(function(level) {
    if (!(level in GLOBAL_OBJ.console)) {
      return;
    }
    fill(GLOBAL_OBJ.console, level, function(originalConsoleMethod) {
      originalConsoleMethods[level] = originalConsoleMethod;
      return function(...args) {
        const handlerData = { args, level };
        triggerHandlers$1("console", handlerData);
        const log2 = originalConsoleMethods[level];
        log2 && log2.apply(GLOBAL_OBJ.console, args);
      };
    });
  });
}
__name(instrumentConsole, "instrumentConsole");
const validSeverityLevels = ["fatal", "error", "warning", "log", "info", "debug"];
function severityLevelFromString(level) {
  return level === "warn" ? "warning" : ["fatal", "error", "warning", "log", "info", "debug"].includes(level) ? level : "log";
}
__name(severityLevelFromString, "severityLevelFromString");
const INTEGRATION_NAME$h = "CaptureConsole";
const _captureConsoleIntegration = /* @__PURE__ */ __name((options2 = {}) => {
  const levels = options2.levels || CONSOLE_LEVELS$1;
  const handled = !!options2.handled;
  return {
    name: INTEGRATION_NAME$h,
    setup(client) {
      if (!("console" in GLOBAL_OBJ)) {
        return;
      }
      addConsoleInstrumentationHandler(({ args, level }) => {
        if (getClient() !== client || !levels.includes(level)) {
          return;
        }
        consoleHandler(args, level, handled);
      });
    }
  };
}, "_captureConsoleIntegration");
const captureConsoleIntegration = defineIntegration(_captureConsoleIntegration);
function consoleHandler(args, level, handled) {
  const captureContext = {
    level: severityLevelFromString(level),
    extra: {
      arguments: args
    }
  };
  withScope((scope) => {
    scope.addEventProcessor((event) => {
      event.logger = "console";
      addExceptionMechanism(event, {
        handled,
        type: "console"
      });
      return event;
    });
    if (level === "assert") {
      if (!args[0]) {
        const message2 = `Assertion failed: ${safeJoin(args.slice(1), " ") || "console.assert"}`;
        scope.setExtra("arguments", args.slice(1));
        captureMessage(message2, captureContext);
      }
      return;
    }
    const error2 = args.find((arg) => arg instanceof Error);
    if (error2) {
      captureException(error2, captureContext);
      return;
    }
    const message = safeJoin(args, " ");
    captureMessage(message, captureContext);
  });
}
__name(consoleHandler, "consoleHandler");
const INTEGRATION_NAME$g = "Debug";
const _debugIntegration = /* @__PURE__ */ __name((options2 = {}) => {
  const _options = {
    debugger: false,
    stringify: false,
    ...options2
  };
  return {
    name: INTEGRATION_NAME$g,
    setup(client) {
      client.on("beforeSendEvent", (event, hint) => {
        if (_options.debugger) {
          debugger;
        }
        consoleSandbox(() => {
          if (_options.stringify) {
            console.log(JSON.stringify(event, null, 2));
            if (hint && Object.keys(hint).length) {
              console.log(JSON.stringify(hint, null, 2));
            }
          } else {
            console.log(event);
            if (hint && Object.keys(hint).length) {
              console.log(hint);
            }
          }
        });
      });
    }
  };
}, "_debugIntegration");
const debugIntegration = defineIntegration(_debugIntegration);
const INTEGRATION_NAME$f = "Dedupe";
const _dedupeIntegration = /* @__PURE__ */ __name(() => {
  let previousEvent;
  return {
    name: INTEGRATION_NAME$f,
    processEvent(currentEvent) {
      if (currentEvent.type) {
        return currentEvent;
      }
      try {
        if (_shouldDropEvent(currentEvent, previousEvent)) {
          DEBUG_BUILD$6 && logger$5.warn("Event dropped due to being a duplicate of previously captured event.");
          return null;
        }
      } catch (_oO) {
      }
      return previousEvent = currentEvent;
    }
  };
}, "_dedupeIntegration");
const dedupeIntegration = defineIntegration(_dedupeIntegration);
function _shouldDropEvent(currentEvent, previousEvent) {
  if (!previousEvent) {
    return false;
  }
  if (_isSameMessageEvent(currentEvent, previousEvent)) {
    return true;
  }
  if (_isSameExceptionEvent(currentEvent, previousEvent)) {
    return true;
  }
  return false;
}
__name(_shouldDropEvent, "_shouldDropEvent");
function _isSameMessageEvent(currentEvent, previousEvent) {
  const currentMessage = currentEvent.message;
  const previousMessage = previousEvent.message;
  if (!currentMessage && !previousMessage) {
    return false;
  }
  if (currentMessage && !previousMessage || !currentMessage && previousMessage) {
    return false;
  }
  if (currentMessage !== previousMessage) {
    return false;
  }
  if (!_isSameFingerprint(currentEvent, previousEvent)) {
    return false;
  }
  if (!_isSameStacktrace(currentEvent, previousEvent)) {
    return false;
  }
  return true;
}
__name(_isSameMessageEvent, "_isSameMessageEvent");
function _isSameExceptionEvent(currentEvent, previousEvent) {
  const previousException = _getExceptionFromEvent(previousEvent);
  const currentException = _getExceptionFromEvent(currentEvent);
  if (!previousException || !currentException) {
    return false;
  }
  if (previousException.type !== currentException.type || previousException.value !== currentException.value) {
    return false;
  }
  if (!_isSameFingerprint(currentEvent, previousEvent)) {
    return false;
  }
  if (!_isSameStacktrace(currentEvent, previousEvent)) {
    return false;
  }
  return true;
}
__name(_isSameExceptionEvent, "_isSameExceptionEvent");
function _isSameStacktrace(currentEvent, previousEvent) {
  let currentFrames = getFramesFromEvent(currentEvent);
  let previousFrames = getFramesFromEvent(previousEvent);
  if (!currentFrames && !previousFrames) {
    return true;
  }
  if (currentFrames && !previousFrames || !currentFrames && previousFrames) {
    return false;
  }
  currentFrames = currentFrames;
  previousFrames = previousFrames;
  if (previousFrames.length !== currentFrames.length) {
    return false;
  }
  for (let i2 = 0; i2 < previousFrames.length; i2++) {
    const frameA = previousFrames[i2];
    const frameB = currentFrames[i2];
    if (frameA.filename !== frameB.filename || frameA.lineno !== frameB.lineno || frameA.colno !== frameB.colno || frameA.function !== frameB.function) {
      return false;
    }
  }
  return true;
}
__name(_isSameStacktrace, "_isSameStacktrace");
function _isSameFingerprint(currentEvent, previousEvent) {
  let currentFingerprint = currentEvent.fingerprint;
  let previousFingerprint = previousEvent.fingerprint;
  if (!currentFingerprint && !previousFingerprint) {
    return true;
  }
  if (currentFingerprint && !previousFingerprint || !currentFingerprint && previousFingerprint) {
    return false;
  }
  currentFingerprint = currentFingerprint;
  previousFingerprint = previousFingerprint;
  try {
    return !!(currentFingerprint.join("") === previousFingerprint.join(""));
  } catch (_oO) {
    return false;
  }
}
__name(_isSameFingerprint, "_isSameFingerprint");
function _getExceptionFromEvent(event) {
  return event.exception && event.exception.values && event.exception.values[0];
}
__name(_getExceptionFromEvent, "_getExceptionFromEvent");
const INTEGRATION_NAME$e = "ExtraErrorData";
const _extraErrorDataIntegration = /* @__PURE__ */ __name((options2 = {}) => {
  const { depth = 3, captureErrorCause = true } = options2;
  return {
    name: INTEGRATION_NAME$e,
    processEvent(event, hint, client) {
      const { maxValueLength = 250 } = client.getOptions();
      return _enhanceEventWithErrorData(event, hint, depth, captureErrorCause, maxValueLength);
    }
  };
}, "_extraErrorDataIntegration");
const extraErrorDataIntegration = defineIntegration(_extraErrorDataIntegration);
function _enhanceEventWithErrorData(event, hint = {}, depth, captureErrorCause, maxValueLength) {
  if (!hint.originalException || !isError(hint.originalException)) {
    return event;
  }
  const exceptionName = hint.originalException.name || hint.originalException.constructor.name;
  const errorData = _extractErrorData(hint.originalException, captureErrorCause, maxValueLength);
  if (errorData) {
    const contexts = {
      ...event.contexts
    };
    const normalizedErrorData = normalize$2(errorData, depth);
    if (isPlainObject$3(normalizedErrorData)) {
      addNonEnumerableProperty(normalizedErrorData, "__sentry_skip_normalization__", true);
      contexts[exceptionName] = normalizedErrorData;
    }
    return {
      ...event,
      contexts
    };
  }
  return event;
}
__name(_enhanceEventWithErrorData, "_enhanceEventWithErrorData");
function _extractErrorData(error2, captureErrorCause, maxValueLength) {
  try {
    const nativeKeys2 = [
      "name",
      "message",
      "stack",
      "line",
      "column",
      "fileName",
      "lineNumber",
      "columnNumber",
      "toJSON"
    ];
    const extraErrorInfo = {};
    for (const key of Object.keys(error2)) {
      if (nativeKeys2.indexOf(key) !== -1) {
        continue;
      }
      const value = error2[key];
      extraErrorInfo[key] = isError(value) || typeof value === "string" ? truncate(`${value}`, maxValueLength) : value;
    }
    if (captureErrorCause && error2.cause !== void 0) {
      extraErrorInfo.cause = isError(error2.cause) ? error2.cause.toString() : error2.cause;
    }
    if (typeof error2.toJSON === "function") {
      const serializedError = error2.toJSON();
      for (const key of Object.keys(serializedError)) {
        const value = serializedError[key];
        extraErrorInfo[key] = isError(value) ? value.toString() : value;
      }
    }
    return extraErrorInfo;
  } catch (oO) {
    DEBUG_BUILD$6 && logger$5.error("Unable to extract extra data from the Error object:", oO);
  }
  return null;
}
__name(_extractErrorData, "_extractErrorData");
function normalizeArray(parts2, allowAboveRoot) {
  let up = 0;
  for (let i2 = parts2.length - 1; i2 >= 0; i2--) {
    const last = parts2[i2];
    if (last === ".") {
      parts2.splice(i2, 1);
    } else if (last === "..") {
      parts2.splice(i2, 1);
      up++;
    } else if (up) {
      parts2.splice(i2, 1);
      up--;
    }
  }
  if (allowAboveRoot) {
    for (; up--; up) {
      parts2.unshift("..");
    }
  }
  return parts2;
}
__name(normalizeArray, "normalizeArray");
const splitPathRe = /^(\S+:\\|\/?)([\s\S]*?)((?:\.{1,2}|[^/\\]+?|)(\.[^./\\]*|))(?:[/\\]*)$/;
function splitPath(filename) {
  const truncated = filename.length > 1024 ? `<truncated>${filename.slice(-1024)}` : filename;
  const parts2 = splitPathRe.exec(truncated);
  return parts2 ? parts2.slice(1) : [];
}
__name(splitPath, "splitPath");
function resolve$2(...args) {
  let resolvedPath = "";
  let resolvedAbsolute = false;
  for (let i2 = args.length - 1; i2 >= -1 && !resolvedAbsolute; i2--) {
    const path = i2 >= 0 ? args[i2] : "/";
    if (!path) {
      continue;
    }
    resolvedPath = `${path}/${resolvedPath}`;
    resolvedAbsolute = path.charAt(0) === "/";
  }
  resolvedPath = normalizeArray(
    resolvedPath.split("/").filter((p2) => !!p2),
    !resolvedAbsolute
  ).join("/");
  return (resolvedAbsolute ? "/" : "") + resolvedPath || ".";
}
__name(resolve$2, "resolve$2");
function trim$1(arr) {
  let start2 = 0;
  for (; start2 < arr.length; start2++) {
    if (arr[start2] !== "") {
      break;
    }
  }
  let end = arr.length - 1;
  for (; end >= 0; end--) {
    if (arr[end] !== "") {
      break;
    }
  }
  if (start2 > end) {
    return [];
  }
  return arr.slice(start2, end - start2 + 1);
}
__name(trim$1, "trim$1");
function relative(from2, to) {
  from2 = resolve$2(from2).slice(1);
  to = resolve$2(to).slice(1);
  const fromParts = trim$1(from2.split("/"));
  const toParts = trim$1(to.split("/"));
  const length = Math.min(fromParts.length, toParts.length);
  let samePartsLength = length;
  for (let i2 = 0; i2 < length; i2++) {
    if (fromParts[i2] !== toParts[i2]) {
      samePartsLength = i2;
      break;
    }
  }
  let outputParts = [];
  for (let i2 = samePartsLength; i2 < fromParts.length; i2++) {
    outputParts.push("..");
  }
  outputParts = outputParts.concat(toParts.slice(samePartsLength));
  return outputParts.join("/");
}
__name(relative, "relative");
function normalizePath(path) {
  const isPathAbsolute = isAbsolute(path);
  const trailingSlash = path.slice(-1) === "/";
  let normalizedPath = normalizeArray(
    path.split("/").filter((p2) => !!p2),
    !isPathAbsolute
  ).join("/");
  if (!normalizedPath && !isPathAbsolute) {
    normalizedPath = ".";
  }
  if (normalizedPath && trailingSlash) {
    normalizedPath += "/";
  }
  return (isPathAbsolute ? "/" : "") + normalizedPath;
}
__name(normalizePath, "normalizePath");
function isAbsolute(path) {
  return path.charAt(0) === "/";
}
__name(isAbsolute, "isAbsolute");
function join$1(...args) {
  return normalizePath(args.join("/"));
}
__name(join$1, "join$1");
function dirname(path) {
  const result = splitPath(path);
  const root2 = result[0] || "";
  let dir = result[1];
  if (!root2 && !dir) {
    return ".";
  }
  if (dir) {
    dir = dir.slice(0, dir.length - 1);
  }
  return root2 + dir;
}
__name(dirname, "dirname");
function basename(path, ext) {
  let f2 = splitPath(path)[2] || "";
  if (ext && f2.slice(ext.length * -1) === ext) {
    f2 = f2.slice(0, f2.length - ext.length);
  }
  return f2;
}
__name(basename, "basename");
const INTEGRATION_NAME$d = "RewriteFrames";
const rewriteFramesIntegration = defineIntegration((options2 = {}) => {
  const root2 = options2.root;
  const prefix = options2.prefix || "app:///";
  const isBrowser2 = "window" in GLOBAL_OBJ && GLOBAL_OBJ.window !== void 0;
  const iteratee = options2.iteratee || generateIteratee({ isBrowser: isBrowser2, root: root2, prefix });
  function _processExceptionsEvent(event) {
    try {
      return {
        ...event,
        exception: {
          ...event.exception,
          // The check for this is performed inside `process` call itself, safe to skip here
          // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
          values: event.exception.values.map((value) => ({
            ...value,
            ...value.stacktrace && { stacktrace: _processStacktrace(value.stacktrace) }
          }))
        }
      };
    } catch (_oO) {
      return event;
    }
  }
  __name(_processExceptionsEvent, "_processExceptionsEvent");
  function _processStacktrace(stacktrace) {
    return {
      ...stacktrace,
      frames: stacktrace && stacktrace.frames && stacktrace.frames.map((f2) => iteratee(f2))
    };
  }
  __name(_processStacktrace, "_processStacktrace");
  return {
    name: INTEGRATION_NAME$d,
    processEvent(originalEvent) {
      let processedEvent = originalEvent;
      if (originalEvent.exception && Array.isArray(originalEvent.exception.values)) {
        processedEvent = _processExceptionsEvent(processedEvent);
      }
      return processedEvent;
    }
  };
});
function generateIteratee({
  isBrowser: isBrowser2,
  root: root2,
  prefix
}) {
  return (frame) => {
    if (!frame.filename) {
      return frame;
    }
    const isWindowsFrame = /^[a-zA-Z]:\\/.test(frame.filename) || // or the presence of a backslash without a forward slash (which are not allowed on Windows)
    frame.filename.includes("\\") && !frame.filename.includes("/");
    const startsWithSlash = /^\//.test(frame.filename);
    if (isBrowser2) {
      if (root2) {
        const oldFilename = frame.filename;
        if (oldFilename.indexOf(root2) === 0) {
          frame.filename = oldFilename.replace(root2, prefix);
        }
      }
    } else {
      if (isWindowsFrame || startsWithSlash) {
        const filename = isWindowsFrame ? frame.filename.replace(/^[a-zA-Z]:/, "").replace(/\\/g, "/") : frame.filename;
        const base2 = root2 ? relative(root2, filename) : basename(filename);
        frame.filename = `${prefix}${base2}`;
      }
    }
    return frame;
  };
}
__name(generateIteratee, "generateIteratee");
const INTEGRATION_NAME$c = "SessionTiming";
const _sessionTimingIntegration = /* @__PURE__ */ __name(() => {
  const startTime = timestampInSeconds() * 1e3;
  return {
    name: INTEGRATION_NAME$c,
    processEvent(event) {
      const now2 = timestampInSeconds() * 1e3;
      return {
        ...event,
        extra: {
          ...event.extra,
          ["session:start"]: startTime,
          ["session:duration"]: now2 - startTime,
          ["session:end"]: now2
        }
      };
    }
  };
}, "_sessionTimingIntegration");
const sessionTimingIntegration = defineIntegration(_sessionTimingIntegration);
const DEFAULT_LIMIT$1 = 10;
const INTEGRATION_NAME$b = "ZodErrors";
function originalExceptionIsZodError(originalException) {
  return isError(originalException) && originalException.name === "ZodError" && Array.isArray(originalException.errors);
}
__name(originalExceptionIsZodError, "originalExceptionIsZodError");
function formatIssueTitle(issue) {
  return {
    ...issue,
    path: "path" in issue && Array.isArray(issue.path) ? issue.path.join(".") : void 0,
    keys: "keys" in issue ? JSON.stringify(issue.keys) : void 0,
    unionErrors: "unionErrors" in issue ? JSON.stringify(issue.unionErrors) : void 0
  };
}
__name(formatIssueTitle, "formatIssueTitle");
function formatIssueMessage(zodError) {
  const errorKeyMap = /* @__PURE__ */ new Set();
  for (const iss of zodError.issues) {
    if (iss.path && iss.path[0]) {
      errorKeyMap.add(iss.path[0]);
    }
  }
  const errorKeys = Array.from(errorKeyMap);
  return `Failed to validate keys: ${truncate(errorKeys.join(", "), 100)}`;
}
__name(formatIssueMessage, "formatIssueMessage");
function applyZodErrorsToEvent(limit2, event, hint) {
  if (!event.exception || !event.exception.values || !hint || !hint.originalException || !originalExceptionIsZodError(hint.originalException) || hint.originalException.issues.length === 0) {
    return event;
  }
  return {
    ...event,
    exception: {
      ...event.exception,
      values: [
        {
          ...event.exception.values[0],
          value: formatIssueMessage(hint.originalException)
        },
        ...event.exception.values.slice(1)
      ]
    },
    extra: {
      ...event.extra,
      "zoderror.issues": hint.originalException.errors.slice(0, limit2).map(formatIssueTitle)
    }
  };
}
__name(applyZodErrorsToEvent, "applyZodErrorsToEvent");
const _zodErrorsIntegration = /* @__PURE__ */ __name((options2 = {}) => {
  const limit2 = options2.limit || DEFAULT_LIMIT$1;
  return {
    name: INTEGRATION_NAME$b,
    processEvent(originalEvent, hint) {
      const processedEvent = applyZodErrorsToEvent(limit2, originalEvent, hint);
      return processedEvent;
    }
  };
}, "_zodErrorsIntegration");
const zodErrorsIntegration = defineIntegration(_zodErrorsIntegration);
const thirdPartyErrorFilterIntegration = defineIntegration((options2) => {
  return {
    name: "ThirdPartyErrorsFilter",
    setup(client) {
      client.on("beforeEnvelope", (envelope) => {
        forEachEnvelopeItem(envelope, (item, type) => {
          if (type === "event") {
            const event = Array.isArray(item) ? item[1] : void 0;
            if (event) {
              stripMetadataFromStackFrames(event);
              item[1] = event;
            }
          }
        });
      });
      client.on("applyFrameMetadata", (event) => {
        if (event.type) {
          return;
        }
        const stackParser = client.getOptions().stackParser;
        addMetadataToStackFrames(stackParser, event);
      });
    },
    processEvent(event) {
      const frameKeys = getBundleKeysForAllFramesWithFilenames(event);
      if (frameKeys) {
        const arrayMethod = options2.behaviour === "drop-error-if-contains-third-party-frames" || options2.behaviour === "apply-tag-if-contains-third-party-frames" ? "some" : "every";
        const behaviourApplies = frameKeys[arrayMethod]((keys2) => !keys2.some((key) => options2.filterKeys.includes(key)));
        if (behaviourApplies) {
          const shouldDrop = options2.behaviour === "drop-error-if-contains-third-party-frames" || options2.behaviour === "drop-error-if-exclusively-contains-third-party-frames";
          if (shouldDrop) {
            return null;
          } else {
            event.tags = {
              ...event.tags,
              third_party_code: true
            };
          }
        }
      }
      return event;
    }
  };
});
function getBundleKeysForAllFramesWithFilenames(event) {
  const frames = getFramesFromEvent(event);
  if (!frames) {
    return void 0;
  }
  return frames.filter((frame) => !!frame.filename).map((frame) => {
    if (frame.module_metadata) {
      return Object.keys(frame.module_metadata).filter((key) => key.startsWith(BUNDLER_PLUGIN_APP_KEY_PREFIX)).map((key) => key.slice(BUNDLER_PLUGIN_APP_KEY_PREFIX.length));
    }
    return [];
  });
}
__name(getBundleKeysForAllFramesWithFilenames, "getBundleKeysForAllFramesWithFilenames");
const BUNDLER_PLUGIN_APP_KEY_PREFIX = "_sentryBundlerPluginAppKey:";
const COUNTER_METRIC_TYPE = "c";
const GAUGE_METRIC_TYPE = "g";
const SET_METRIC_TYPE = "s";
const DISTRIBUTION_METRIC_TYPE = "d";
const DEFAULT_BROWSER_FLUSH_INTERVAL = 5e3;
const DEFAULT_FLUSH_INTERVAL = 1e4;
const MAX_WEIGHT = 1e4;
function getMetricsAggregatorForClient$1(client, Aggregator) {
  const globalMetricsAggregators = getGlobalSingleton(
    "globalMetricsAggregators",
    () => /* @__PURE__ */ new WeakMap()
  );
  const aggregator = globalMetricsAggregators.get(client);
  if (aggregator) {
    return aggregator;
  }
  const newAggregator = new Aggregator(client);
  client.on("flush", () => newAggregator.flush());
  client.on("close", () => newAggregator.close());
  globalMetricsAggregators.set(client, newAggregator);
  return newAggregator;
}
__name(getMetricsAggregatorForClient$1, "getMetricsAggregatorForClient$1");
function addToMetricsAggregator(Aggregator, metricType, name2, value, data = {}) {
  const client = data.client || getClient();
  if (!client) {
    return;
  }
  const span = getActiveSpan();
  const rootSpan = span ? getRootSpan(span) : void 0;
  const transactionName = rootSpan && spanToJSON(rootSpan).description;
  const { unit, tags, timestamp: timestamp2 } = data;
  const { release, environment } = client.getOptions();
  const metricTags = {};
  if (release) {
    metricTags.release = release;
  }
  if (environment) {
    metricTags.environment = environment;
  }
  if (transactionName) {
    metricTags.transaction = transactionName;
  }
  DEBUG_BUILD$6 && logger$5.log(`Adding value of ${value} to ${metricType} metric ${name2}`);
  const aggregator = getMetricsAggregatorForClient$1(client, Aggregator);
  aggregator.add(metricType, name2, value, unit, { ...metricTags, ...tags }, timestamp2);
}
__name(addToMetricsAggregator, "addToMetricsAggregator");
function increment$4(aggregator, name2, value = 1, data) {
  addToMetricsAggregator(aggregator, COUNTER_METRIC_TYPE, name2, ensureNumber(value), data);
}
__name(increment$4, "increment$4");
function distribution$2(aggregator, name2, value, data) {
  addToMetricsAggregator(aggregator, DISTRIBUTION_METRIC_TYPE, name2, ensureNumber(value), data);
}
__name(distribution$2, "distribution$2");
function timing$2(aggregator, name2, value, unit = "second", data) {
  if (typeof value === "function") {
    const startTime = timestampInSeconds();
    return startSpanManual(
      {
        op: "metrics.timing",
        name: name2,
        startTime,
        onlyIfParent: true
      },
      (span) => {
        return handleCallbackErrors(
          () => value(),
          () => {
          },
          () => {
            const endTime = timestampInSeconds();
            const timeDiff = endTime - startTime;
            distribution$2(aggregator, name2, timeDiff, { ...data, unit: "second" });
            span.end(endTime);
          }
        );
      }
    );
  }
  distribution$2(aggregator, name2, value, { ...data, unit });
}
__name(timing$2, "timing$2");
function set$5(aggregator, name2, value, data) {
  addToMetricsAggregator(aggregator, SET_METRIC_TYPE, name2, value, data);
}
__name(set$5, "set$5");
function gauge$2(aggregator, name2, value, data) {
  addToMetricsAggregator(aggregator, GAUGE_METRIC_TYPE, name2, ensureNumber(value), data);
}
__name(gauge$2, "gauge$2");
const metrics$1 = {
  increment: increment$4,
  distribution: distribution$2,
  set: set$5,
  gauge: gauge$2,
  timing: timing$2,
  /**
   * @ignore This is for internal use only.
   */
  getMetricsAggregatorForClient: getMetricsAggregatorForClient$1
};
function ensureNumber(number) {
  return typeof number === "string" ? parseInt(number) : number;
}
__name(ensureNumber, "ensureNumber");
function isProfilingIntegrationWithProfiler(integration) {
  return !!integration && typeof integration["_profiler"] !== "undefined" && typeof integration["_profiler"]["start"] === "function" && typeof integration["_profiler"]["stop"] === "function";
}
__name(isProfilingIntegrationWithProfiler, "isProfilingIntegrationWithProfiler");
function startProfiler() {
  const client = getClient();
  if (!client) {
    DEBUG_BUILD$6 && logger$5.warn("No Sentry client available, profiling is not started");
    return;
  }
  const integration = client.getIntegrationByName("ProfilingIntegration");
  if (!integration) {
    DEBUG_BUILD$6 && logger$5.warn("ProfilingIntegration is not available");
    return;
  }
  if (!isProfilingIntegrationWithProfiler(integration)) {
    DEBUG_BUILD$6 && logger$5.warn("Profiler is not available on profiling integration.");
    return;
  }
  integration._profiler.start();
}
__name(startProfiler, "startProfiler");
function stopProfiler() {
  const client = getClient();
  if (!client) {
    DEBUG_BUILD$6 && logger$5.warn("No Sentry client available, profiling is not started");
    return;
  }
  const integration = client.getIntegrationByName("ProfilingIntegration");
  if (!integration) {
    DEBUG_BUILD$6 && logger$5.warn("ProfilingIntegration is not available");
    return;
  }
  if (!isProfilingIntegrationWithProfiler(integration)) {
    DEBUG_BUILD$6 && logger$5.warn("Profiler is not available on profiling integration.");
    return;
  }
  integration._profiler.stop();
}
__name(stopProfiler, "stopProfiler");
const profiler = {
  startProfiler,
  stopProfiler
};
function getBucketKey(metricType, name2, unit, tags) {
  const stringifiedTags = Object.entries(dropUndefinedKeys(tags)).sort((a2, b2) => a2[0].localeCompare(b2[0]));
  return `${metricType}${name2}${unit}${stringifiedTags}`;
}
__name(getBucketKey, "getBucketKey");
function simpleHash(s2) {
  let rv = 0;
  for (let i2 = 0; i2 < s2.length; i2++) {
    const c2 = s2.charCodeAt(i2);
    rv = (rv << 5) - rv + c2;
    rv &= rv;
  }
  return rv >>> 0;
}
__name(simpleHash, "simpleHash");
function serializeMetricBuckets(metricBucketItems) {
  let out = "";
  for (const item of metricBucketItems) {
    const tagEntries = Object.entries(item.tags);
    const maybeTags = tagEntries.length > 0 ? `|#${tagEntries.map(([key, value]) => `${key}:${value}`).join(",")}` : "";
    out += `${item.name}@${item.unit}:${item.metric}|${item.metricType}${maybeTags}|T${item.timestamp}
`;
  }
  return out;
}
__name(serializeMetricBuckets, "serializeMetricBuckets");
function sanitizeUnit(unit) {
  return unit.replace(/[^\w]+/gi, "_");
}
__name(sanitizeUnit, "sanitizeUnit");
function sanitizeMetricKey(key) {
  return key.replace(/[^\w\-.]+/gi, "_");
}
__name(sanitizeMetricKey, "sanitizeMetricKey");
function sanitizeTagKey(key) {
  return key.replace(/[^\w\-./]+/gi, "");
}
__name(sanitizeTagKey, "sanitizeTagKey");
const tagValueReplacements = [
  ["\n", "\\n"],
  ["\r", "\\r"],
  ["	", "\\t"],
  ["\\", "\\\\"],
  ["|", "\\u{7c}"],
  [",", "\\u{2c}"]
];
function getCharOrReplacement(input) {
  for (const [search2, replacement] of tagValueReplacements) {
    if (input === search2) {
      return replacement;
    }
  }
  return input;
}
__name(getCharOrReplacement, "getCharOrReplacement");
function sanitizeTagValue(value) {
  return [...value].reduce((acc, char) => acc + getCharOrReplacement(char), "");
}
__name(sanitizeTagValue, "sanitizeTagValue");
function sanitizeTags(unsanitizedTags) {
  const tags = {};
  for (const key in unsanitizedTags) {
    if (Object.prototype.hasOwnProperty.call(unsanitizedTags, key)) {
      const sanitizedKey = sanitizeTagKey(key);
      tags[sanitizedKey] = sanitizeTagValue(String(unsanitizedTags[key]));
    }
  }
  return tags;
}
__name(sanitizeTags, "sanitizeTags");
function captureAggregateMetrics(client, metricBucketItems) {
  logger$5.log(`Flushing aggregated metrics, number of metrics: ${metricBucketItems.length}`);
  const dsn = client.getDsn();
  const metadata = client.getSdkMetadata();
  const tunnel = client.getOptions().tunnel;
  const metricsEnvelope = createMetricEnvelope(metricBucketItems, dsn, metadata, tunnel);
  client.sendEnvelope(metricsEnvelope);
}
__name(captureAggregateMetrics, "captureAggregateMetrics");
function createMetricEnvelope(metricBucketItems, dsn, metadata, tunnel) {
  const headers = {
    sent_at: (/* @__PURE__ */ new Date()).toISOString()
  };
  if (metadata && metadata.sdk) {
    headers.sdk = {
      name: metadata.sdk.name,
      version: metadata.sdk.version
    };
  }
  if (!!tunnel && dsn) {
    headers.dsn = dsnToString(dsn);
  }
  const item = createMetricEnvelopeItem(metricBucketItems);
  return createEnvelope(headers, [item]);
}
__name(createMetricEnvelope, "createMetricEnvelope");
function createMetricEnvelopeItem(metricBucketItems) {
  const payload = serializeMetricBuckets(metricBucketItems);
  const metricHeaders = {
    type: "statsd",
    length: payload.length
  };
  return [metricHeaders, payload];
}
__name(createMetricEnvelopeItem, "createMetricEnvelopeItem");
class CounterMetric {
  static {
    __name(this, "CounterMetric");
  }
  constructor(_value) {
    this._value = _value;
  }
  /** @inheritDoc */
  get weight() {
    return 1;
  }
  /** @inheritdoc */
  add(value) {
    this._value += value;
  }
  /** @inheritdoc */
  toString() {
    return `${this._value}`;
  }
}
class GaugeMetric {
  static {
    __name(this, "GaugeMetric");
  }
  constructor(value) {
    this._last = value;
    this._min = value;
    this._max = value;
    this._sum = value;
    this._count = 1;
  }
  /** @inheritDoc */
  get weight() {
    return 5;
  }
  /** @inheritdoc */
  add(value) {
    this._last = value;
    if (value < this._min) {
      this._min = value;
    }
    if (value > this._max) {
      this._max = value;
    }
    this._sum += value;
    this._count++;
  }
  /** @inheritdoc */
  toString() {
    return `${this._last}:${this._min}:${this._max}:${this._sum}:${this._count}`;
  }
}
class DistributionMetric {
  static {
    __name(this, "DistributionMetric");
  }
  constructor(first2) {
    this._value = [first2];
  }
  /** @inheritDoc */
  get weight() {
    return this._value.length;
  }
  /** @inheritdoc */
  add(value) {
    this._value.push(value);
  }
  /** @inheritdoc */
  toString() {
    return this._value.join(":");
  }
}
class SetMetric {
  static {
    __name(this, "SetMetric");
  }
  constructor(first2) {
    this.first = first2;
    this._value = /* @__PURE__ */ new Set([first2]);
  }
  /** @inheritDoc */
  get weight() {
    return this._value.size;
  }
  /** @inheritdoc */
  add(value) {
    this._value.add(value);
  }
  /** @inheritdoc */
  toString() {
    return Array.from(this._value).map((val) => typeof val === "string" ? simpleHash(val) : val).join(":");
  }
}
const METRIC_MAP = {
  [COUNTER_METRIC_TYPE]: CounterMetric,
  [GAUGE_METRIC_TYPE]: GaugeMetric,
  [DISTRIBUTION_METRIC_TYPE]: DistributionMetric,
  [SET_METRIC_TYPE]: SetMetric
};
class MetricsAggregator {
  static {
    __name(this, "MetricsAggregator");
  }
  // TODO(@anonrig): Use FinalizationRegistry to have a proper way of flushing the buckets
  // when the aggregator is garbage collected.
  // Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry
  // Different metrics have different weights. We use this to limit the number of metrics
  // that we store in memory.
  // We adjust the type here to add the `unref()` part, as setInterval can technically return a number or a NodeJS.Timer
  // SDKs are required to shift the flush interval by random() * rollup_in_seconds.
  // That shift is determined once per startup to create jittering.
  // An SDK is required to perform force flushing ahead of scheduled time if the memory
  // pressure is too high. There is no rule for this other than that SDKs should be tracking
  // abstract aggregation complexity (eg: a counter only carries a single float, whereas a
  // distribution is a float per emission).
  //
  // Force flush is used on either shutdown, flush() or when we exceed the max weight.
  constructor(_client) {
    this._client = _client;
    this._buckets = /* @__PURE__ */ new Map();
    this._bucketsTotalWeight = 0;
    this._interval = setInterval(() => this._flush(), DEFAULT_FLUSH_INTERVAL);
    if (this._interval.unref) {
      this._interval.unref();
    }
    this._flushShift = Math.floor(Math.random() * DEFAULT_FLUSH_INTERVAL / 1e3);
    this._forceFlush = false;
  }
  /**
   * @inheritDoc
   */
  add(metricType, unsanitizedName, value, unsanitizedUnit = "none", unsanitizedTags = {}, maybeFloatTimestamp = timestampInSeconds()) {
    const timestamp2 = Math.floor(maybeFloatTimestamp);
    const name2 = sanitizeMetricKey(unsanitizedName);
    const tags = sanitizeTags(unsanitizedTags);
    const unit = sanitizeUnit(unsanitizedUnit);
    const bucketKey = getBucketKey(metricType, name2, unit, tags);
    let bucketItem = this._buckets.get(bucketKey);
    const previousWeight = bucketItem && metricType === SET_METRIC_TYPE ? bucketItem.metric.weight : 0;
    if (bucketItem) {
      bucketItem.metric.add(value);
      if (bucketItem.timestamp < timestamp2) {
        bucketItem.timestamp = timestamp2;
      }
    } else {
      bucketItem = {
        // @ts-expect-error we don't need to narrow down the type of value here, saves bundle size.
        metric: new METRIC_MAP[metricType](value),
        timestamp: timestamp2,
        metricType,
        name: name2,
        unit,
        tags
      };
      this._buckets.set(bucketKey, bucketItem);
    }
    const val = typeof value === "string" ? bucketItem.metric.weight - previousWeight : value;
    updateMetricSummaryOnActiveSpan(metricType, name2, val, unit, unsanitizedTags, bucketKey);
    this._bucketsTotalWeight += bucketItem.metric.weight;
    if (this._bucketsTotalWeight >= MAX_WEIGHT) {
      this.flush();
    }
  }
  /**
   * Flushes the current metrics to the transport via the transport.
   */
  flush() {
    this._forceFlush = true;
    this._flush();
  }
  /**
   * Shuts down metrics aggregator and clears all metrics.
   */
  close() {
    this._forceFlush = true;
    clearInterval(this._interval);
    this._flush();
  }
  /**
   * Flushes the buckets according to the internal state of the aggregator.
   * If it is a force flush, which happens on shutdown, it will flush all buckets.
   * Otherwise, it will only flush buckets that are older than the flush interval,
   * and according to the flush shift.
   *
   * This function mutates `_forceFlush` and `_bucketsTotalWeight` properties.
   */
  _flush() {
    if (this._forceFlush) {
      this._forceFlush = false;
      this._bucketsTotalWeight = 0;
      this._captureMetrics(this._buckets);
      this._buckets.clear();
      return;
    }
    const cutoffSeconds = Math.floor(timestampInSeconds()) - DEFAULT_FLUSH_INTERVAL / 1e3 - this._flushShift;
    const flushedBuckets = /* @__PURE__ */ new Map();
    for (const [key, bucket] of this._buckets) {
      if (bucket.timestamp <= cutoffSeconds) {
        flushedBuckets.set(key, bucket);
        this._bucketsTotalWeight -= bucket.metric.weight;
      }
    }
    for (const [key] of flushedBuckets) {
      this._buckets.delete(key);
    }
    this._captureMetrics(flushedBuckets);
  }
  /**
   * Only captures a subset of the buckets passed to this function.
   * @param flushedBuckets
   */
  _captureMetrics(flushedBuckets) {
    if (flushedBuckets.size > 0) {
      const buckets = Array.from(flushedBuckets).map(([, bucketItem]) => bucketItem);
      captureAggregateMetrics(this._client, buckets);
    }
  }
}
function increment$3(name2, value = 1, data) {
  metrics$1.increment(MetricsAggregator, name2, value, data);
}
__name(increment$3, "increment$3");
function distribution$1(name2, value, data) {
  metrics$1.distribution(MetricsAggregator, name2, value, data);
}
__name(distribution$1, "distribution$1");
function set$4(name2, value, data) {
  metrics$1.set(MetricsAggregator, name2, value, data);
}
__name(set$4, "set$4");
function gauge$1(name2, value, data) {
  metrics$1.gauge(MetricsAggregator, name2, value, data);
}
__name(gauge$1, "gauge$1");
function timing$1(name2, value, unit = "second", data) {
  return metrics$1.timing(MetricsAggregator, name2, value, unit, data);
}
__name(timing$1, "timing$1");
function getMetricsAggregatorForClient(client) {
  return metrics$1.getMetricsAggregatorForClient(client, MetricsAggregator);
}
__name(getMetricsAggregatorForClient, "getMetricsAggregatorForClient");
const metricsDefault = {
  increment: increment$3,
  distribution: distribution$1,
  set: set$4,
  gauge: gauge$1,
  timing: timing$1,
  /**
   * @ignore This is for internal use only.
   */
  getMetricsAggregatorForClient
};
class BrowserMetricsAggregator {
  static {
    __name(this, "BrowserMetricsAggregator");
  }
  // TODO(@anonrig): Use FinalizationRegistry to have a proper way of flushing the buckets
  // when the aggregator is garbage collected.
  // Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry
  constructor(_client) {
    this._client = _client;
    this._buckets = /* @__PURE__ */ new Map();
    this._interval = setInterval(() => this.flush(), DEFAULT_BROWSER_FLUSH_INTERVAL);
  }
  /**
   * @inheritDoc
   */
  add(metricType, unsanitizedName, value, unsanitizedUnit = "none", unsanitizedTags = {}, maybeFloatTimestamp = timestampInSeconds()) {
    const timestamp2 = Math.floor(maybeFloatTimestamp);
    const name2 = sanitizeMetricKey(unsanitizedName);
    const tags = sanitizeTags(unsanitizedTags);
    const unit = sanitizeUnit(unsanitizedUnit);
    const bucketKey = getBucketKey(metricType, name2, unit, tags);
    let bucketItem = this._buckets.get(bucketKey);
    const previousWeight = bucketItem && metricType === SET_METRIC_TYPE ? bucketItem.metric.weight : 0;
    if (bucketItem) {
      bucketItem.metric.add(value);
      if (bucketItem.timestamp < timestamp2) {
        bucketItem.timestamp = timestamp2;
      }
    } else {
      bucketItem = {
        // @ts-expect-error we don't need to narrow down the type of value here, saves bundle size.
        metric: new METRIC_MAP[metricType](value),
        timestamp: timestamp2,
        metricType,
        name: name2,
        unit,
        tags
      };
      this._buckets.set(bucketKey, bucketItem);
    }
    const val = typeof value === "string" ? bucketItem.metric.weight - previousWeight : value;
    updateMetricSummaryOnActiveSpan(metricType, name2, val, unit, unsanitizedTags, bucketKey);
  }
  /**
   * @inheritDoc
   */
  flush() {
    if (this._buckets.size === 0) {
      return;
    }
    const metricBuckets = Array.from(this._buckets.values());
    captureAggregateMetrics(this._client, metricBuckets);
    this._buckets.clear();
  }
  /**
   * @inheritDoc
   */
  close() {
    clearInterval(this._interval);
    this.flush();
  }
}
function instrumentFetchRequest(handlerData, shouldCreateSpan, shouldAttachHeaders2, spans, spanOrigin = "auto.http.browser") {
  if (!handlerData.fetchData) {
    return void 0;
  }
  const shouldCreateSpanResult = hasTracingEnabled() && shouldCreateSpan(handlerData.fetchData.url);
  if (handlerData.endTimestamp && shouldCreateSpanResult) {
    const spanId = handlerData.fetchData.__span;
    if (!spanId) return;
    const span2 = spans[spanId];
    if (span2) {
      endSpan(span2, handlerData);
      delete spans[spanId];
    }
    return void 0;
  }
  const { method, url } = handlerData.fetchData;
  const fullUrl = getFullURL$1(url);
  const host = fullUrl ? parseUrl$1(fullUrl).host : void 0;
  const hasParent = !!getActiveSpan();
  const span = shouldCreateSpanResult && hasParent ? startInactiveSpan({
    name: `${method} ${url}`,
    attributes: {
      url,
      type: "fetch",
      "http.method": method,
      "http.url": fullUrl,
      "server.address": host,
      [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: spanOrigin,
      [SEMANTIC_ATTRIBUTE_SENTRY_OP]: "http.client"
    }
  }) : new SentryNonRecordingSpan();
  handlerData.fetchData.__span = span.spanContext().spanId;
  spans[span.spanContext().spanId] = span;
  if (shouldAttachHeaders2(handlerData.fetchData.url)) {
    const request = handlerData.args[0];
    const options2 = handlerData.args[1] || {};
    const headers = _addTracingHeadersToFetchRequest(
      request,
      options2,
      // If performance is disabled (TWP) or there's no active root span (pageload/navigation/interaction),
      // we do not want to use the span as base for the trace headers,
      // which means that the headers will be generated from the scope and the sampling decision is deferred
      hasTracingEnabled() && hasParent ? span : void 0
    );
    if (headers) {
      handlerData.args[1] = options2;
      options2.headers = headers;
    }
  }
  return span;
}
__name(instrumentFetchRequest, "instrumentFetchRequest");
function _addTracingHeadersToFetchRequest(request, fetchOptionsObj, span) {
  const traceHeaders = getTraceData({ span });
  const sentryTrace = traceHeaders["sentry-trace"];
  const baggage = traceHeaders.baggage;
  if (!sentryTrace) {
    return void 0;
  }
  const headers = fetchOptionsObj.headers || (isRequest$1(request) ? request.headers : void 0);
  if (!headers) {
    return { ...traceHeaders };
  } else if (isHeaders$1(headers)) {
    const newHeaders = new Headers(headers);
    newHeaders.set("sentry-trace", sentryTrace);
    if (baggage) {
      const prevBaggageHeader = newHeaders.get("baggage");
      if (prevBaggageHeader) {
        const prevHeaderStrippedFromSentryBaggage = stripBaggageHeaderOfSentryBaggageValues(prevBaggageHeader);
        newHeaders.set(
          "baggage",
          // If there are non-sentry entries (i.e. if the stripped string is non-empty/truthy) combine the stripped header and sentry baggage header
          // otherwise just set the sentry baggage header
          prevHeaderStrippedFromSentryBaggage ? `${prevHeaderStrippedFromSentryBaggage},${baggage}` : baggage
        );
      } else {
        newHeaders.set("baggage", baggage);
      }
    }
    return newHeaders;
  } else if (Array.isArray(headers)) {
    const newHeaders = [
      ...headers.filter((header) => {
        return !(Array.isArray(header) && header[0] === "sentry-trace");
      }).map((header) => {
        if (Array.isArray(header) && header[0] === "baggage" && typeof header[1] === "string") {
          const [headerName, headerValue, ...rest] = header;
          return [headerName, stripBaggageHeaderOfSentryBaggageValues(headerValue), ...rest];
        } else {
          return header;
        }
      }),
      // Attach the new sentry-trace header
      ["sentry-trace", sentryTrace]
    ];
    if (baggage) {
      newHeaders.push(["baggage", baggage]);
    }
    return newHeaders;
  } else {
    const existingBaggageHeader = "baggage" in headers ? headers.baggage : void 0;
    let newBaggageHeaders = [];
    if (Array.isArray(existingBaggageHeader)) {
      newBaggageHeaders = existingBaggageHeader.map(
        (headerItem) => typeof headerItem === "string" ? stripBaggageHeaderOfSentryBaggageValues(headerItem) : headerItem
      ).filter((headerItem) => headerItem === "");
    } else if (existingBaggageHeader) {
      newBaggageHeaders.push(stripBaggageHeaderOfSentryBaggageValues(existingBaggageHeader));
    }
    if (baggage) {
      newBaggageHeaders.push(baggage);
    }
    return {
      ...headers,
      "sentry-trace": sentryTrace,
      baggage: newBaggageHeaders.length > 0 ? newBaggageHeaders.join(",") : void 0
    };
  }
}
__name(_addTracingHeadersToFetchRequest, "_addTracingHeadersToFetchRequest");
function addTracingHeadersToFetchRequest(request, _client, _scope, fetchOptionsObj, span) {
  return _addTracingHeadersToFetchRequest(request, fetchOptionsObj, span);
}
__name(addTracingHeadersToFetchRequest, "addTracingHeadersToFetchRequest");
function getFullURL$1(url) {
  try {
    const parsed = new URL(url);
    return parsed.href;
  } catch (e2) {
    return void 0;
  }
}
__name(getFullURL$1, "getFullURL$1");
function endSpan(span, handlerData) {
  if (handlerData.response) {
    setHttpStatus(span, handlerData.response.status);
    const contentLength = handlerData.response && handlerData.response.headers && handlerData.response.headers.get("content-length");
    if (contentLength) {
      const contentLengthNum = parseInt(contentLength);
      if (contentLengthNum > 0) {
        span.setAttribute("http.response_content_length", contentLengthNum);
      }
    }
  } else if (handlerData.error) {
    span.setStatus({ code: SPAN_STATUS_ERROR, message: "internal_error" });
  }
  span.end();
}
__name(endSpan, "endSpan");
function stripBaggageHeaderOfSentryBaggageValues(baggageHeader) {
  return baggageHeader.split(",").filter((baggageEntry) => !baggageEntry.split("=")[0].startsWith(SENTRY_BAGGAGE_KEY_PREFIX)).join(",");
}
__name(stripBaggageHeaderOfSentryBaggageValues, "stripBaggageHeaderOfSentryBaggageValues");
function isRequest$1(request) {
  return typeof Request !== "undefined" && isInstanceOf(request, Request);
}
__name(isRequest$1, "isRequest$1");
function isHeaders$1(headers) {
  return typeof Headers !== "undefined" && isInstanceOf(headers, Headers);
}
__name(isHeaders$1, "isHeaders$1");
const trpcCaptureContext = { mechanism: { handled: false, data: { function: "trpcMiddleware" } } };
function captureIfError(nextResult) {
  if (typeof nextResult === "object" && nextResult !== null && "ok" in nextResult && !nextResult.ok && "error" in nextResult) {
    captureException(nextResult.error, trpcCaptureContext);
  }
}
__name(captureIfError, "captureIfError");
function trpcMiddleware(options2 = {}) {
  return async function(opts) {
    const { path, type, next, rawInput, getRawInput } = opts;
    const client = getClient();
    const clientOptions = client && client.getOptions();
    const trpcContext = {
      procedure_path: path,
      procedure_type: type
    };
    if (options2.attachRpcInput !== void 0 ? options2.attachRpcInput : clientOptions && clientOptions.sendDefaultPii) {
      if (rawInput !== void 0) {
        trpcContext.input = normalize$2(rawInput);
      }
      if (getRawInput !== void 0 && typeof getRawInput === "function") {
        try {
          const rawRes = await getRawInput();
          trpcContext.input = normalize$2(rawRes);
        } catch (err) {
        }
      }
    }
    return withScope((scope) => {
      scope.setContext("trpc", trpcContext);
      return startSpanManual(
        {
          name: `trpc/${path}`,
          op: "rpc.server",
          attributes: {
            [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: "route",
            [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.rpc.trpc"
          }
        },
        async (span) => {
          try {
            const nextResult = await next();
            captureIfError(nextResult);
            span.end();
            return nextResult;
          } catch (e2) {
            captureException(e2, trpcCaptureContext);
            span.end();
            throw e2;
          }
        }
      );
    });
  };
}
__name(trpcMiddleware, "trpcMiddleware");
function captureFeedback(params, hint = {}, scope = getCurrentScope()) {
  const { message, name: name2, email, url, source, associatedEventId, tags } = params;
  const feedbackEvent = {
    contexts: {
      feedback: dropUndefinedKeys({
        contact_email: email,
        name: name2,
        message,
        url,
        source,
        associated_event_id: associatedEventId
      })
    },
    type: "feedback",
    level: "info",
    tags
  };
  const client = scope && scope.getClient() || getClient();
  if (client) {
    client.emit("beforeSendFeedback", feedbackEvent, hint);
  }
  const eventId = scope.captureEvent(feedbackEvent, hint);
  return eventId;
}
__name(captureFeedback, "captureFeedback");
function getCurrentHubShim() {
  return {
    bindClient(client) {
      const scope = getCurrentScope();
      scope.setClient(client);
    },
    withScope,
    getClient: /* @__PURE__ */ __name(() => getClient(), "getClient"),
    getScope: getCurrentScope,
    getIsolationScope,
    captureException: /* @__PURE__ */ __name((exception, hint) => {
      return getCurrentScope().captureException(exception, hint);
    }, "captureException"),
    captureMessage: /* @__PURE__ */ __name((message, level, hint) => {
      return getCurrentScope().captureMessage(message, level, hint);
    }, "captureMessage"),
    captureEvent,
    addBreadcrumb,
    setUser,
    setTags,
    setTag: setTag$5,
    setExtra,
    setExtras,
    setContext,
    getIntegration(integration) {
      const client = getClient();
      return client && client.getIntegrationByName(integration.id) || null;
    },
    startSession,
    endSession,
    captureSession(end) {
      if (end) {
        return endSession();
      }
      _sendSessionUpdate();
    }
  };
}
__name(getCurrentHubShim, "getCurrentHubShim");
const getCurrentHub = getCurrentHubShim;
function _sendSessionUpdate() {
  const scope = getCurrentScope();
  const client = getClient();
  const session = scope.getSession();
  if (client && session) {
    client.captureSession(session);
  }
}
__name(_sendSessionUpdate, "_sendSessionUpdate");
function flatten(input) {
  const result = [];
  const flattenHelper = /* @__PURE__ */ __name((input2) => {
    input2.forEach((el) => {
      if (Array.isArray(el)) {
        flattenHelper(el);
      } else {
        result.push(el);
      }
    });
  }, "flattenHelper");
  flattenHelper(input);
  return result;
}
__name(flatten, "flatten");
function getBreadcrumbLogLevelFromHttpStatusCode(statusCode) {
  if (statusCode === void 0) {
    return void 0;
  } else if (statusCode >= 400 && statusCode < 500) {
    return "warning";
  } else if (statusCode >= 500) {
    return "error";
  } else {
    return void 0;
  }
}
__name(getBreadcrumbLogLevelFromHttpStatusCode, "getBreadcrumbLogLevelFromHttpStatusCode");
const WINDOW$7 = GLOBAL_OBJ;
function supportsErrorEvent() {
  try {
    new ErrorEvent("");
    return true;
  } catch (e2) {
    return false;
  }
}
__name(supportsErrorEvent, "supportsErrorEvent");
function supportsDOMError() {
  try {
    new DOMError("");
    return true;
  } catch (e2) {
    return false;
  }
}
__name(supportsDOMError, "supportsDOMError");
function supportsDOMException() {
  try {
    new DOMException("");
    return true;
  } catch (e2) {
    return false;
  }
}
__name(supportsDOMException, "supportsDOMException");
function supportsFetch() {
  if (!("fetch" in WINDOW$7)) {
    return false;
  }
  try {
    new Headers();
    new Request("http://www.example.com");
    new Response();
    return true;
  } catch (e2) {
    return false;
  }
}
__name(supportsFetch, "supportsFetch");
function isNativeFunction(func) {
  return func && /^function\s+\w+\(\)\s+\{\s+\[native code\]\s+\}$/.test(func.toString());
}
__name(isNativeFunction, "isNativeFunction");
function supportsNativeFetch() {
  if (typeof EdgeRuntime === "string") {
    return true;
  }
  if (!supportsFetch()) {
    return false;
  }
  if (isNativeFunction(WINDOW$7.fetch)) {
    return true;
  }
  let result = false;
  const doc2 = WINDOW$7.document;
  if (doc2 && typeof doc2.createElement === "function") {
    try {
      const sandbox = doc2.createElement("iframe");
      sandbox.hidden = true;
      doc2.head.appendChild(sandbox);
      if (sandbox.contentWindow && sandbox.contentWindow.fetch) {
        result = isNativeFunction(sandbox.contentWindow.fetch);
      }
      doc2.head.removeChild(sandbox);
    } catch (err) {
      DEBUG_BUILD$5 && logger$5.warn("Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ", err);
    }
  }
  return result;
}
__name(supportsNativeFetch, "supportsNativeFetch");
function supportsReportingObserver() {
  return "ReportingObserver" in WINDOW$7;
}
__name(supportsReportingObserver, "supportsReportingObserver");
function supportsReferrerPolicy() {
  if (!supportsFetch()) {
    return false;
  }
  try {
    new Request("_", {
      referrerPolicy: "origin"
    });
    return true;
  } catch (e2) {
    return false;
  }
}
__name(supportsReferrerPolicy, "supportsReferrerPolicy");
function addFetchInstrumentationHandler(handler5, skipNativeFetchCheck) {
  const type = "fetch";
  addHandler$1(type, handler5);
  maybeInstrument(type, () => instrumentFetch(void 0, skipNativeFetchCheck));
}
__name(addFetchInstrumentationHandler, "addFetchInstrumentationHandler");
function addFetchEndInstrumentationHandler(handler5) {
  const type = "fetch-body-resolved";
  addHandler$1(type, handler5);
  maybeInstrument(type, () => instrumentFetch(streamHandler));
}
__name(addFetchEndInstrumentationHandler, "addFetchEndInstrumentationHandler");
function instrumentFetch(onFetchResolved, skipNativeFetchCheck = false) {
  if (skipNativeFetchCheck && !supportsNativeFetch()) {
    return;
  }
  fill(GLOBAL_OBJ, "fetch", function(originalFetch) {
    return function(...args) {
      const virtualError = new Error();
      const { method, url } = parseFetchArgs(args);
      const handlerData = {
        args,
        fetchData: {
          method,
          url
        },
        startTimestamp: timestampInSeconds() * 1e3,
        // // Adding the error to be able to fingerprint the failed fetch event in HttpClient instrumentation
        virtualError
      };
      if (!onFetchResolved) {
        triggerHandlers$1("fetch", {
          ...handlerData
        });
      }
      return originalFetch.apply(GLOBAL_OBJ, args).then(
        async (response) => {
          if (onFetchResolved) {
            onFetchResolved(response);
          } else {
            triggerHandlers$1("fetch", {
              ...handlerData,
              endTimestamp: timestampInSeconds() * 1e3,
              response
            });
          }
          return response;
        },
        (error2) => {
          triggerHandlers$1("fetch", {
            ...handlerData,
            endTimestamp: timestampInSeconds() * 1e3,
            error: error2
          });
          if (isError(error2) && error2.stack === void 0) {
            error2.stack = virtualError.stack;
            addNonEnumerableProperty(error2, "framesToPop", 1);
          }
          throw error2;
        }
      );
    };
  });
}
__name(instrumentFetch, "instrumentFetch");
async function resolveResponse(res, onFinishedResolving) {
  if (res && res.body) {
    const body = res.body;
    const responseReader = body.getReader();
    const maxFetchDurationTimeout = setTimeout(
      () => {
        body.cancel().then(null, () => {
        });
      },
      90 * 1e3
      // 90s
    );
    let readingActive = true;
    while (readingActive) {
      let chunkTimeout;
      try {
        chunkTimeout = setTimeout(() => {
          body.cancel().then(null, () => {
          });
        }, 5e3);
        const { done } = await responseReader.read();
        clearTimeout(chunkTimeout);
        if (done) {
          onFinishedResolving();
          readingActive = false;
        }
      } catch (error2) {
        readingActive = false;
      } finally {
        clearTimeout(chunkTimeout);
      }
    }
    clearTimeout(maxFetchDurationTimeout);
    responseReader.releaseLock();
    body.cancel().then(null, () => {
    });
  }
}
__name(resolveResponse, "resolveResponse");
function streamHandler(response) {
  let clonedResponseForResolving;
  try {
    clonedResponseForResolving = response.clone();
  } catch (e2) {
    return;
  }
  resolveResponse(clonedResponseForResolving, () => {
    triggerHandlers$1("fetch-body-resolved", {
      endTimestamp: timestampInSeconds() * 1e3,
      response
    });
  });
}
__name(streamHandler, "streamHandler");
function hasProp(obj, prop2) {
  return !!obj && typeof obj === "object" && !!obj[prop2];
}
__name(hasProp, "hasProp");
function getUrlFromResource(resource) {
  if (typeof resource === "string") {
    return resource;
  }
  if (!resource) {
    return "";
  }
  if (hasProp(resource, "url")) {
    return resource.url;
  }
  if (resource.toString) {
    return resource.toString();
  }
  return "";
}
__name(getUrlFromResource, "getUrlFromResource");
function parseFetchArgs(fetchArgs) {
  if (fetchArgs.length === 0) {
    return { method: "GET", url: "" };
  }
  if (fetchArgs.length === 2) {
    const [url, options2] = fetchArgs;
    return {
      url: getUrlFromResource(url),
      method: hasProp(options2, "method") ? String(options2.method).toUpperCase() : "GET"
    };
  }
  const arg = fetchArgs[0];
  return {
    url: getUrlFromResource(arg),
    method: hasProp(arg, "method") ? String(arg.method).toUpperCase() : "GET"
  };
}
__name(parseFetchArgs, "parseFetchArgs");
function isBrowserBundle() {
  return typeof __SENTRY_BROWSER_BUNDLE__ !== "undefined" && !!__SENTRY_BROWSER_BUNDLE__;
}
__name(isBrowserBundle, "isBrowserBundle");
function getSDKSource() {
  return "npm";
}
__name(getSDKSource, "getSDKSource");
function isNodeEnv() {
  return !isBrowserBundle() && Object.prototype.toString.call(typeof process !== "undefined" ? process : 0) === "[object process]";
}
__name(isNodeEnv, "isNodeEnv");
function dynamicRequire(mod, request) {
  return mod.require(request);
}
__name(dynamicRequire, "dynamicRequire");
function loadModule(moduleName) {
  let mod;
  try {
    mod = dynamicRequire(module, moduleName);
  } catch (e2) {
  }
  if (!mod) {
    try {
      const { cwd } = dynamicRequire(module, "process");
      mod = dynamicRequire(module, `${cwd()}/node_modules/${moduleName}`);
    } catch (e2) {
    }
  }
  return mod;
}
__name(loadModule, "loadModule");
function isBrowser$2() {
  return typeof window !== "undefined" && (!isNodeEnv() || isElectronNodeRenderer());
}
__name(isBrowser$2, "isBrowser$2");
function isElectronNodeRenderer() {
  const process2 = GLOBAL_OBJ.process;
  return !!process2 && process2.type === "renderer";
}
__name(isElectronNodeRenderer, "isElectronNodeRenderer");
function filenameIsInApp(filename, isNative = false) {
  const isInternal = isNative || filename && // It's not internal if it's an absolute linux path
  !filename.startsWith("/") && // It's not internal if it's an absolute windows path
  !filename.match(/^[A-Z]:/) && // It's not internal if the path is starting with a dot
  !filename.startsWith(".") && // It's not internal if the frame has a protocol. In node, this is usually the case if the file got pre-processed with a bundler like webpack
  !filename.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//);
  return !isInternal && filename !== void 0 && !filename.includes("node_modules/");
}
__name(filenameIsInApp, "filenameIsInApp");
function node(getModule) {
  const FILENAME_MATCH = /^\s*[-]{4,}$/;
  const FULL_MATCH = /at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/;
  return (line) => {
    const lineMatch = line.match(FULL_MATCH);
    if (lineMatch) {
      let object;
      let method;
      let functionName;
      let typeName;
      let methodName;
      if (lineMatch[1]) {
        functionName = lineMatch[1];
        let methodStart = functionName.lastIndexOf(".");
        if (functionName[methodStart - 1] === ".") {
          methodStart--;
        }
        if (methodStart > 0) {
          object = functionName.slice(0, methodStart);
          method = functionName.slice(methodStart + 1);
          const objectEnd = object.indexOf(".Module");
          if (objectEnd > 0) {
            functionName = functionName.slice(objectEnd + 1);
            object = object.slice(0, objectEnd);
          }
        }
        typeName = void 0;
      }
      if (method) {
        typeName = object;
        methodName = method;
      }
      if (method === "<anonymous>") {
        methodName = void 0;
        functionName = void 0;
      }
      if (functionName === void 0) {
        methodName = methodName || UNKNOWN_FUNCTION;
        functionName = typeName ? `${typeName}.${methodName}` : methodName;
      }
      let filename = lineMatch[2] && lineMatch[2].startsWith("file://") ? lineMatch[2].slice(7) : lineMatch[2];
      const isNative = lineMatch[5] === "native";
      if (filename && filename.match(/\/[A-Z]:/)) {
        filename = filename.slice(1);
      }
      if (!filename && lineMatch[5] && !isNative) {
        filename = lineMatch[5];
      }
      return {
        filename: filename ? decodeURI(filename) : void 0,
        module: getModule ? getModule(filename) : void 0,
        function: functionName,
        lineno: _parseIntOrUndefined(lineMatch[3]),
        colno: _parseIntOrUndefined(lineMatch[4]),
        in_app: filenameIsInApp(filename || "", isNative)
      };
    }
    if (line.match(FILENAME_MATCH)) {
      return {
        filename: line
      };
    }
    return void 0;
  };
}
__name(node, "node");
function nodeStackLineParser(getModule) {
  return [90, node(getModule)];
}
__name(nodeStackLineParser, "nodeStackLineParser");
function _parseIntOrUndefined(input) {
  return parseInt(input || "", 10) || void 0;
}
__name(_parseIntOrUndefined, "_parseIntOrUndefined");
function makeFifoCache(size) {
  let evictionOrder = [];
  let cache = {};
  return {
    add(key, value) {
      while (evictionOrder.length >= size) {
        const evictCandidate = evictionOrder.shift();
        if (evictCandidate !== void 0) {
          delete cache[evictCandidate];
        }
      }
      if (cache[key]) {
        this.delete(key);
      }
      evictionOrder.push(key);
      cache[key] = value;
    },
    clear() {
      cache = {};
      evictionOrder = [];
    },
    get(key) {
      return cache[key];
    },
    size() {
      return evictionOrder.length;
    },
    // Delete cache key and return true if it existed, false otherwise.
    delete(key) {
      if (!cache[key]) {
        return false;
      }
      delete cache[key];
      for (let i2 = 0; i2 < evictionOrder.length; i2++) {
        if (evictionOrder[i2] === key) {
          evictionOrder.splice(i2, 1);
          break;
        }
      }
      return true;
    }
  };
}
__name(makeFifoCache, "makeFifoCache");
function watchdogTimer(createTimer, pollInterval, anrThreshold, callback) {
  const timer = createTimer();
  let triggered = false;
  let enabled = true;
  setInterval(() => {
    const diffMs = timer.getTimeMs();
    if (triggered === false && diffMs > pollInterval + anrThreshold) {
      triggered = true;
      if (enabled) {
        callback();
      }
    }
    if (diffMs < pollInterval + anrThreshold) {
      triggered = false;
    }
  }, 20);
  return {
    poll: /* @__PURE__ */ __name(() => {
      timer.reset();
    }, "poll"),
    enabled: /* @__PURE__ */ __name((state) => {
      enabled = state;
    }, "enabled")
  };
}
__name(watchdogTimer, "watchdogTimer");
function callFrameToStackFrame(frame, url, getModuleFromFilename) {
  const filename = url ? url.replace(/^file:\/\//, "") : void 0;
  const colno = frame.location.columnNumber ? frame.location.columnNumber + 1 : void 0;
  const lineno = frame.location.lineNumber ? frame.location.lineNumber + 1 : void 0;
  return dropUndefinedKeys({
    filename,
    module: getModuleFromFilename(filename),
    function: frame.functionName || UNKNOWN_FUNCTION,
    colno,
    lineno,
    in_app: filename ? filenameIsInApp(filename) : void 0
  });
}
__name(callFrameToStackFrame, "callFrameToStackFrame");
class LRUMap {
  static {
    __name(this, "LRUMap");
  }
  constructor(_maxSize) {
    this._maxSize = _maxSize;
    this._cache = /* @__PURE__ */ new Map();
  }
  /** Get the current size of the cache */
  get size() {
    return this._cache.size;
  }
  /** Get an entry or undefined if it was not in the cache. Re-inserts to update the recently used order */
  get(key) {
    const value = this._cache.get(key);
    if (value === void 0) {
      return void 0;
    }
    this._cache.delete(key);
    this._cache.set(key, value);
    return value;
  }
  /** Insert an entry and evict an older entry if we've reached maxSize */
  set(key, value) {
    if (this._cache.size >= this._maxSize) {
      this._cache.delete(this._cache.keys().next().value);
    }
    this._cache.set(key, value);
  }
  /** Remove an entry and return the entry if it was in the cache */
  remove(key) {
    const value = this._cache.get(key);
    if (value) {
      this._cache.delete(key);
    }
    return value;
  }
  /** Clear all entries */
  clear() {
    this._cache.clear();
  }
  /** Get all the keys */
  keys() {
    return Array.from(this._cache.keys());
  }
  /** Get all the values */
  values() {
    const values = [];
    this._cache.forEach((value) => values.push(value));
    return values;
  }
}
function vercelWaitUntil(task) {
  const vercelRequestContextGlobal = (
    // @ts-expect-error This is not typed
    GLOBAL_OBJ[Symbol.for("@vercel/request-context")]
  );
  const ctx = vercelRequestContextGlobal && vercelRequestContextGlobal.get && vercelRequestContextGlobal.get() ? vercelRequestContextGlobal.get() : {};
  if (ctx && ctx.waitUntil) {
    ctx.waitUntil(task);
  }
}
__name(vercelWaitUntil, "vercelWaitUntil");
function escapeStringForRegex(regexString) {
  return regexString.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&").replace(/-/g, "\\x2d");
}
__name(escapeStringForRegex, "escapeStringForRegex");
const WINDOW$6 = GLOBAL_OBJ;
function supportsHistory() {
  const chromeVar = WINDOW$6.chrome;
  const isChromePackagedApp = chromeVar && chromeVar.app && chromeVar.app.runtime;
  const hasHistoryApi = "history" in WINDOW$6 && !!WINDOW$6.history.pushState && !!WINDOW$6.history.replaceState;
  return !isChromePackagedApp && hasHistoryApi;
}
__name(supportsHistory, "supportsHistory");
function _nullishCoalesce(lhs, rhsFn) {
  return lhs != null ? lhs : rhsFn();
}
__name(_nullishCoalesce, "_nullishCoalesce");
async function _asyncNullishCoalesce(lhs, rhsFn) {
  return _nullishCoalesce(lhs, rhsFn);
}
__name(_asyncNullishCoalesce, "_asyncNullishCoalesce");
async function _asyncOptionalChain(ops2) {
  let lastAccessLHS = void 0;
  let value = ops2[0];
  let i2 = 1;
  while (i2 < ops2.length) {
    const op = ops2[i2];
    const fn = ops2[i2 + 1];
    i2 += 2;
    if ((op === "optionalAccess" || op === "optionalCall") && value == null) {
      return;
    }
    if (op === "access" || op === "optionalAccess") {
      lastAccessLHS = value;
      value = await fn(value);
    } else if (op === "call" || op === "optionalCall") {
      value = await fn((...args) => value.call(lastAccessLHS, ...args));
      lastAccessLHS = void 0;
    }
  }
  return value;
}
__name(_asyncOptionalChain, "_asyncOptionalChain");
async function _asyncOptionalChainDelete(ops2) {
  const result = await _asyncOptionalChain(ops2);
  return result == null ? true : result;
}
__name(_asyncOptionalChainDelete, "_asyncOptionalChainDelete");
function _optionalChain(ops2) {
  let lastAccessLHS = void 0;
  let value = ops2[0];
  let i2 = 1;
  while (i2 < ops2.length) {
    const op = ops2[i2];
    const fn = ops2[i2 + 1];
    i2 += 2;
    if ((op === "optionalAccess" || op === "optionalCall") && value == null) {
      return;
    }
    if (op === "access" || op === "optionalAccess") {
      lastAccessLHS = value;
      value = fn(value);
    } else if (op === "call" || op === "optionalCall") {
      value = fn((...args) => value.call(lastAccessLHS, ...args));
      lastAccessLHS = void 0;
    }
  }
  return value;
}
__name(_optionalChain, "_optionalChain");
function _optionalChainDelete(ops2) {
  const result = _optionalChain(ops2);
  return result == null ? true : result;
}
__name(_optionalChainDelete, "_optionalChainDelete");
const WINDOW$5 = GLOBAL_OBJ;
let ignoreOnError = 0;
function shouldIgnoreOnError() {
  return ignoreOnError > 0;
}
__name(shouldIgnoreOnError, "shouldIgnoreOnError");
function ignoreNextOnError() {
  ignoreOnError++;
  setTimeout(() => {
    ignoreOnError--;
  });
}
__name(ignoreNextOnError, "ignoreNextOnError");
function wrap$2(fn, options2 = {}) {
  function isFunction2(fn2) {
    return typeof fn2 === "function";
  }
  __name(isFunction2, "isFunction");
  if (!isFunction2(fn)) {
    return fn;
  }
  try {
    const wrapper = fn.__sentry_wrapped__;
    if (wrapper) {
      if (typeof wrapper === "function") {
        return wrapper;
      } else {
        return fn;
      }
    }
    if (getOriginalFunction(fn)) {
      return fn;
    }
  } catch (e2) {
    return fn;
  }
  const sentryWrapped = /* @__PURE__ */ __name(function(...args) {
    try {
      const wrappedArguments = args.map((arg) => wrap$2(arg, options2));
      return fn.apply(this, wrappedArguments);
    } catch (ex) {
      ignoreNextOnError();
      withScope((scope) => {
        scope.addEventProcessor((event) => {
          if (options2.mechanism) {
            addExceptionTypeValue(event, void 0, void 0);
            addExceptionMechanism(event, options2.mechanism);
          }
          event.extra = {
            ...event.extra,
            arguments: args
          };
          return event;
        });
        captureException(ex);
      });
      throw ex;
    }
  }, "sentryWrapped");
  try {
    for (const property in fn) {
      if (Object.prototype.hasOwnProperty.call(fn, property)) {
        sentryWrapped[property] = fn[property];
      }
    }
  } catch (e2) {
  }
  markFunctionWrapped(sentryWrapped, fn);
  addNonEnumerableProperty(fn, "__sentry_wrapped__", sentryWrapped);
  try {
    const descriptor = Object.getOwnPropertyDescriptor(sentryWrapped, "name");
    if (descriptor.configurable) {
      Object.defineProperty(sentryWrapped, "name", {
        get() {
          return fn.name;
        }
      });
    }
  } catch (e3) {
  }
  return sentryWrapped;
}
__name(wrap$2, "wrap$2");
const DEBUG_BUILD$4 = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__;
function exceptionFromError(stackParser, ex) {
  const frames = parseStackFrames(stackParser, ex);
  const exception = {
    type: extractType(ex),
    value: extractMessage(ex)
  };
  if (frames.length) {
    exception.stacktrace = { frames };
  }
  if (exception.type === void 0 && exception.value === "") {
    exception.value = "Unrecoverable error caught";
  }
  return exception;
}
__name(exceptionFromError, "exceptionFromError");
function eventFromPlainObject(stackParser, exception, syntheticException, isUnhandledRejection) {
  const client = getClient();
  const normalizeDepth = client && client.getOptions().normalizeDepth;
  const errorFromProp = getErrorPropertyFromObject(exception);
  const extra = {
    __serialized__: normalizeToSize(exception, normalizeDepth)
  };
  if (errorFromProp) {
    return {
      exception: {
        values: [exceptionFromError(stackParser, errorFromProp)]
      },
      extra
    };
  }
  const event = {
    exception: {
      values: [
        {
          type: isEvent(exception) ? exception.constructor.name : isUnhandledRejection ? "UnhandledRejection" : "Error",
          value: getNonErrorObjectExceptionValue(exception, { isUnhandledRejection })
        }
      ]
    },
    extra
  };
  if (syntheticException) {
    const frames = parseStackFrames(stackParser, syntheticException);
    if (frames.length) {
      event.exception.values[0].stacktrace = { frames };
    }
  }
  return event;
}
__name(eventFromPlainObject, "eventFromPlainObject");
function eventFromError(stackParser, ex) {
  return {
    exception: {
      values: [exceptionFromError(stackParser, ex)]
    }
  };
}
__name(eventFromError, "eventFromError");
function parseStackFrames(stackParser, ex) {
  const stacktrace = ex.stacktrace || ex.stack || "";
  const skipLines = getSkipFirstStackStringLines(ex);
  const framesToPop = getPopFirstTopFrames(ex);
  try {
    return stackParser(stacktrace, skipLines, framesToPop);
  } catch (e2) {
  }
  return [];
}
__name(parseStackFrames, "parseStackFrames");
const reactMinifiedRegexp = /Minified React error #\d+;/i;
function getSkipFirstStackStringLines(ex) {
  if (ex && reactMinifiedRegexp.test(ex.message)) {
    return 1;
  }
  return 0;
}
__name(getSkipFirstStackStringLines, "getSkipFirstStackStringLines");
function getPopFirstTopFrames(ex) {
  if (typeof ex.framesToPop === "number") {
    return ex.framesToPop;
  }
  return 0;
}
__name(getPopFirstTopFrames, "getPopFirstTopFrames");
function isWebAssemblyException(exception) {
  if (typeof WebAssembly !== "undefined" && typeof WebAssembly.Exception !== "undefined") {
    return exception instanceof WebAssembly.Exception;
  } else {
    return false;
  }
}
__name(isWebAssemblyException, "isWebAssemblyException");
function extractType(ex) {
  const name2 = ex && ex.name;
  if (!name2 && isWebAssemblyException(ex)) {
    const hasTypeInMessage = ex.message && Array.isArray(ex.message) && ex.message.length == 2;
    return hasTypeInMessage ? ex.message[0] : "WebAssembly.Exception";
  }
  return name2;
}
__name(extractType, "extractType");
function extractMessage(ex) {
  const message = ex && ex.message;
  if (!message) {
    return "No error message";
  }
  if (message.error && typeof message.error.message === "string") {
    return message.error.message;
  }
  if (isWebAssemblyException(ex) && Array.isArray(ex.message) && ex.message.length == 2) {
    return ex.message[1];
  }
  return message;
}
__name(extractMessage, "extractMessage");
function eventFromException(stackParser, exception, hint, attachStacktrace) {
  const syntheticException = hint && hint.syntheticException || void 0;
  const event = eventFromUnknownInput(stackParser, exception, syntheticException, attachStacktrace);
  addExceptionMechanism(event);
  event.level = "error";
  if (hint && hint.event_id) {
    event.event_id = hint.event_id;
  }
  return resolvedSyncPromise(event);
}
__name(eventFromException, "eventFromException");
function eventFromMessage(stackParser, message, level = "info", hint, attachStacktrace) {
  const syntheticException = hint && hint.syntheticException || void 0;
  const event = eventFromString(stackParser, message, syntheticException, attachStacktrace);
  event.level = level;
  if (hint && hint.event_id) {
    event.event_id = hint.event_id;
  }
  return resolvedSyncPromise(event);
}
__name(eventFromMessage, "eventFromMessage");
function eventFromUnknownInput(stackParser, exception, syntheticException, attachStacktrace, isUnhandledRejection) {
  let event;
  if (isErrorEvent$2(exception) && exception.error) {
    const errorEvent = exception;
    return eventFromError(stackParser, errorEvent.error);
  }
  if (isDOMError(exception) || isDOMException(exception)) {
    const domException = exception;
    if ("stack" in exception) {
      event = eventFromError(stackParser, exception);
    } else {
      const name2 = domException.name || (isDOMError(domException) ? "DOMError" : "DOMException");
      const message = domException.message ? `${name2}: ${domException.message}` : name2;
      event = eventFromString(stackParser, message, syntheticException, attachStacktrace);
      addExceptionTypeValue(event, message);
    }
    if ("code" in domException) {
      event.tags = { ...event.tags, "DOMException.code": `${domException.code}` };
    }
    return event;
  }
  if (isError(exception)) {
    return eventFromError(stackParser, exception);
  }
  if (isPlainObject$3(exception) || isEvent(exception)) {
    const objectException = exception;
    event = eventFromPlainObject(stackParser, objectException, syntheticException, isUnhandledRejection);
    addExceptionMechanism(event, {
      synthetic: true
    });
    return event;
  }
  event = eventFromString(stackParser, exception, syntheticException, attachStacktrace);
  addExceptionTypeValue(event, `${exception}`, void 0);
  addExceptionMechanism(event, {
    synthetic: true
  });
  return event;
}
__name(eventFromUnknownInput, "eventFromUnknownInput");
function eventFromString(stackParser, message, syntheticException, attachStacktrace) {
  const event = {};
  if (attachStacktrace && syntheticException) {
    const frames = parseStackFrames(stackParser, syntheticException);
    if (frames.length) {
      event.exception = {
        values: [{ value: message, stacktrace: { frames } }]
      };
    }
    addExceptionMechanism(event, { synthetic: true });
  }
  if (isParameterizedString(message)) {
    const { __sentry_template_string__, __sentry_template_values__ } = message;
    event.logentry = {
      message: __sentry_template_string__,
      params: __sentry_template_values__
    };
    return event;
  }
  event.message = message;
  return event;
}
__name(eventFromString, "eventFromString");
function getNonErrorObjectExceptionValue(exception, { isUnhandledRejection }) {
  const keys2 = extractExceptionKeysForMessage(exception);
  const captureType = isUnhandledRejection ? "promise rejection" : "exception";
  if (isErrorEvent$2(exception)) {
    return `Event \`ErrorEvent\` captured as ${captureType} with message \`${exception.message}\``;
  }
  if (isEvent(exception)) {
    const className = getObjectClassName(exception);
    return `Event \`${className}\` (type=${exception.type}) captured as ${captureType}`;
  }
  return `Object captured as ${captureType} with keys: ${keys2}`;
}
__name(getNonErrorObjectExceptionValue, "getNonErrorObjectExceptionValue");
function getObjectClassName(obj) {
  try {
    const prototype2 = Object.getPrototypeOf(obj);
    return prototype2 ? prototype2.constructor.name : void 0;
  } catch (e2) {
  }
}
__name(getObjectClassName, "getObjectClassName");
function getErrorPropertyFromObject(obj) {
  for (const prop2 in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, prop2)) {
      const value = obj[prop2];
      if (value instanceof Error) {
        return value;
      }
    }
  }
  return void 0;
}
__name(getErrorPropertyFromObject, "getErrorPropertyFromObject");
function createUserFeedbackEnvelope(feedback, {
  metadata,
  tunnel,
  dsn
}) {
  const headers = {
    event_id: feedback.event_id,
    sent_at: (/* @__PURE__ */ new Date()).toISOString(),
    ...metadata && metadata.sdk && {
      sdk: {
        name: metadata.sdk.name,
        version: metadata.sdk.version
      }
    },
    ...!!tunnel && !!dsn && { dsn: dsnToString(dsn) }
  };
  const item = createUserFeedbackEnvelopeItem(feedback);
  return createEnvelope(headers, [item]);
}
__name(createUserFeedbackEnvelope, "createUserFeedbackEnvelope");
function createUserFeedbackEnvelopeItem(feedback) {
  const feedbackHeaders = {
    type: "user_report"
  };
  return [feedbackHeaders, feedback];
}
__name(createUserFeedbackEnvelopeItem, "createUserFeedbackEnvelopeItem");
class BrowserClient extends BaseClient {
  static {
    __name(this, "BrowserClient");
  }
  /**
   * Creates a new Browser SDK instance.
   *
   * @param options Configuration options for this SDK.
   */
  constructor(options2) {
    const opts = {
      // We default this to true, as it is the safer scenario
      parentSpanIsAlwaysRootSpan: true,
      ...options2
    };
    const sdkSource = WINDOW$5.SENTRY_SDK_SOURCE || getSDKSource();
    applySdkMetadata(opts, "browser", ["browser"], sdkSource);
    super(opts);
    if (opts.sendClientReports && WINDOW$5.document) {
      WINDOW$5.document.addEventListener("visibilitychange", () => {
        if (WINDOW$5.document.visibilityState === "hidden") {
          this._flushOutcomes();
        }
      });
    }
  }
  /**
   * @inheritDoc
   */
  eventFromException(exception, hint) {
    return eventFromException(this._options.stackParser, exception, hint, this._options.attachStacktrace);
  }
  /**
   * @inheritDoc
   */
  eventFromMessage(message, level = "info", hint) {
    return eventFromMessage(this._options.stackParser, message, level, hint, this._options.attachStacktrace);
  }
  /**
   * Sends user feedback to Sentry.
   *
   * @deprecated Use `captureFeedback` instead.
   */
  captureUserFeedback(feedback) {
    if (!this._isEnabled()) {
      DEBUG_BUILD$4 && logger$5.warn("SDK not enabled, will not capture user feedback.");
      return;
    }
    const envelope = createUserFeedbackEnvelope(feedback, {
      metadata: this.getSdkMetadata(),
      dsn: this.getDsn(),
      tunnel: this.getOptions().tunnel
    });
    this.sendEnvelope(envelope);
  }
  /**
   * @inheritDoc
   */
  _prepareEvent(event, hint, scope) {
    event.platform = event.platform || "javascript";
    return super._prepareEvent(event, hint, scope);
  }
}
const DEBUG_BUILD$3 = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__;
const getRating = /* @__PURE__ */ __name((value, thresholds) => {
  if (value > thresholds[1]) {
    return "poor";
  }
  if (value > thresholds[0]) {
    return "needs-improvement";
  }
  return "good";
}, "getRating");
const bindReporter = /* @__PURE__ */ __name((callback, metric, thresholds, reportAllChanges) => {
  let prevValue;
  let delta2;
  return (forceReport) => {
    if (metric.value >= 0) {
      if (forceReport || reportAllChanges) {
        delta2 = metric.value - (prevValue || 0);
        if (delta2 || prevValue === void 0) {
          prevValue = metric.value;
          metric.delta = delta2;
          metric.rating = getRating(metric.value, thresholds);
          callback(metric);
        }
      }
    }
  };
}, "bindReporter");
const WINDOW$4 = GLOBAL_OBJ;
const generateUniqueID = /* @__PURE__ */ __name(() => {
  return `v4-${Date.now()}-${Math.floor(Math.random() * (9e12 - 1)) + 1e12}`;
}, "generateUniqueID");
const getNavigationEntry = /* @__PURE__ */ __name((checkResponseStart = true) => {
  const navigationEntry = WINDOW$4.performance && WINDOW$4.performance.getEntriesByType && WINDOW$4.performance.getEntriesByType("navigation")[0];
  if (
    // sentry-specific change:
    // We don't want to check for responseStart for our own use of `getNavigationEntry`
    !checkResponseStart || navigationEntry && navigationEntry.responseStart > 0 && navigationEntry.responseStart < performance.now()
  ) {
    return navigationEntry;
  }
}, "getNavigationEntry");
const getActivationStart = /* @__PURE__ */ __name(() => {
  const navEntry = getNavigationEntry();
  return navEntry && navEntry.activationStart || 0;
}, "getActivationStart");
const initMetric = /* @__PURE__ */ __name((name2, value) => {
  const navEntry = getNavigationEntry();
  let navigationType = "navigate";
  if (navEntry) {
    if (WINDOW$4.document && WINDOW$4.document.prerendering || getActivationStart() > 0) {
      navigationType = "prerender";
    } else if (WINDOW$4.document && WINDOW$4.document.wasDiscarded) {
      navigationType = "restore";
    } else if (navEntry.type) {
      navigationType = navEntry.type.replace(/_/g, "-");
    }
  }
  const entries = [];
  return {
    name: name2,
    value: typeof value === "undefined" ? -1 : value,
    rating: "good",
    // If needed, will be updated when reported. `const` to keep the type from widening to `string`.
    delta: 0,
    entries,
    id: generateUniqueID(),
    navigationType
  };
}, "initMetric");
const observe = /* @__PURE__ */ __name((type, callback, opts) => {
  try {
    if (PerformanceObserver.supportedEntryTypes.includes(type)) {
      const po2 = new PerformanceObserver((list2) => {
        Promise.resolve().then(() => {
          callback(list2.getEntries());
        });
      });
      po2.observe(
        Object.assign(
          {
            type,
            buffered: true
          },
          opts || {}
        )
      );
      return po2;
    }
  } catch (e2) {
  }
  return;
}, "observe");
const onHidden = /* @__PURE__ */ __name((cb) => {
  const onHiddenOrPageHide = /* @__PURE__ */ __name((event) => {
    if (event.type === "pagehide" || WINDOW$4.document && WINDOW$4.document.visibilityState === "hidden") {
      cb(event);
    }
  }, "onHiddenOrPageHide");
  if (WINDOW$4.document) {
    addEventListener("visibilitychange", onHiddenOrPageHide, true);
    addEventListener("pagehide", onHiddenOrPageHide, true);
  }
}, "onHidden");
const runOnce = /* @__PURE__ */ __name((cb) => {
  let called = false;
  return () => {
    if (!called) {
      cb();
      called = true;
    }
  };
}, "runOnce");
let firstHiddenTime = -1;
const initHiddenTime = /* @__PURE__ */ __name(() => {
  return WINDOW$4.document.visibilityState === "hidden" && !WINDOW$4.document.prerendering ? 0 : Infinity;
}, "initHiddenTime");
const onVisibilityUpdate = /* @__PURE__ */ __name((event) => {
  if (WINDOW$4.document.visibilityState === "hidden" && firstHiddenTime > -1) {
    firstHiddenTime = event.type === "visibilitychange" ? event.timeStamp : 0;
    removeChangeListeners();
  }
}, "onVisibilityUpdate");
const addChangeListeners = /* @__PURE__ */ __name(() => {
  addEventListener("visibilitychange", onVisibilityUpdate, true);
  addEventListener("prerenderingchange", onVisibilityUpdate, true);
}, "addChangeListeners");
const removeChangeListeners = /* @__PURE__ */ __name(() => {
  removeEventListener("visibilitychange", onVisibilityUpdate, true);
  removeEventListener("prerenderingchange", onVisibilityUpdate, true);
}, "removeChangeListeners");
const getVisibilityWatcher = /* @__PURE__ */ __name(() => {
  if (WINDOW$4.document && firstHiddenTime < 0) {
    firstHiddenTime = initHiddenTime();
    addChangeListeners();
  }
  return {
    get firstHiddenTime() {
      return firstHiddenTime;
    }
  };
}, "getVisibilityWatcher");
const whenActivated = /* @__PURE__ */ __name((callback) => {
  if (WINDOW$4.document && WINDOW$4.document.prerendering) {
    addEventListener("prerenderingchange", () => callback(), true);
  } else {
    callback();
  }
}, "whenActivated");
const FCPThresholds = [1800, 3e3];
const onFCP = /* @__PURE__ */ __name((onReport, opts = {}) => {
  whenActivated(() => {
    const visibilityWatcher = getVisibilityWatcher();
    const metric = initMetric("FCP");
    let report;
    const handleEntries = /* @__PURE__ */ __name((entries) => {
      entries.forEach((entry) => {
        if (entry.name === "first-contentful-paint") {
          po2.disconnect();
          if (entry.startTime < visibilityWatcher.firstHiddenTime) {
            metric.value = Math.max(entry.startTime - getActivationStart(), 0);
            metric.entries.push(entry);
            report(true);
          }
        }
      });
    }, "handleEntries");
    const po2 = observe("paint", handleEntries);
    if (po2) {
      report = bindReporter(onReport, metric, FCPThresholds, opts.reportAllChanges);
    }
  });
}, "onFCP");
const CLSThresholds = [0.1, 0.25];
const onCLS = /* @__PURE__ */ __name((onReport, opts = {}) => {
  onFCP(
    runOnce(() => {
      const metric = initMetric("CLS", 0);
      let report;
      let sessionValue = 0;
      let sessionEntries = [];
      const handleEntries = /* @__PURE__ */ __name((entries) => {
        entries.forEach((entry) => {
          if (!entry.hadRecentInput) {
            const firstSessionEntry = sessionEntries[0];
            const lastSessionEntry = sessionEntries[sessionEntries.length - 1];
            if (sessionValue && firstSessionEntry && lastSessionEntry && entry.startTime - lastSessionEntry.startTime < 1e3 && entry.startTime - firstSessionEntry.startTime < 5e3) {
              sessionValue += entry.value;
              sessionEntries.push(entry);
            } else {
              sessionValue = entry.value;
              sessionEntries = [entry];
            }
          }
        });
        if (sessionValue > metric.value) {
          metric.value = sessionValue;
          metric.entries = sessionEntries;
          report();
        }
      }, "handleEntries");
      const po2 = observe("layout-shift", handleEntries);
      if (po2) {
        report = bindReporter(onReport, metric, CLSThresholds, opts.reportAllChanges);
        onHidden(() => {
          handleEntries(po2.takeRecords());
          report(true);
        });
        setTimeout(report, 0);
      }
    })
  );
}, "onCLS");
const FIDThresholds = [100, 300];
const onFID = /* @__PURE__ */ __name((onReport, opts = {}) => {
  whenActivated(() => {
    const visibilityWatcher = getVisibilityWatcher();
    const metric = initMetric("FID");
    let report;
    const handleEntry = /* @__PURE__ */ __name((entry) => {
      if (entry.startTime < visibilityWatcher.firstHiddenTime) {
        metric.value = entry.processingStart - entry.startTime;
        metric.entries.push(entry);
        report(true);
      }
    }, "handleEntry");
    const handleEntries = /* @__PURE__ */ __name((entries) => {
      entries.forEach(handleEntry);
    }, "handleEntries");
    const po2 = observe("first-input", handleEntries);
    report = bindReporter(onReport, metric, FIDThresholds, opts.reportAllChanges);
    if (po2) {
      onHidden(
        runOnce(() => {
          handleEntries(po2.takeRecords());
          po2.disconnect();
        })
      );
    }
  });
}, "onFID");
let interactionCountEstimate = 0;
let minKnownInteractionId = Infinity;
let maxKnownInteractionId = 0;
const updateEstimate = /* @__PURE__ */ __name((entries) => {
  entries.forEach((e2) => {
    if (e2.interactionId) {
      minKnownInteractionId = Math.min(minKnownInteractionId, e2.interactionId);
      maxKnownInteractionId = Math.max(maxKnownInteractionId, e2.interactionId);
      interactionCountEstimate = maxKnownInteractionId ? (maxKnownInteractionId - minKnownInteractionId) / 7 + 1 : 0;
    }
  });
}, "updateEstimate");
let po;
const getInteractionCount = /* @__PURE__ */ __name(() => {
  return po ? interactionCountEstimate : performance.interactionCount || 0;
}, "getInteractionCount");
const initInteractionCountPolyfill = /* @__PURE__ */ __name(() => {
  if ("interactionCount" in performance || po) return;
  po = observe("event", updateEstimate, {
    type: "event",
    buffered: true,
    durationThreshold: 0
  });
}, "initInteractionCountPolyfill");
const longestInteractionList = [];
const longestInteractionMap = /* @__PURE__ */ new Map();
const DEFAULT_DURATION_THRESHOLD = 40;
let prevInteractionCount = 0;
const getInteractionCountForNavigation = /* @__PURE__ */ __name(() => {
  return getInteractionCount() - prevInteractionCount;
}, "getInteractionCountForNavigation");
const estimateP98LongestInteraction = /* @__PURE__ */ __name(() => {
  const candidateInteractionIndex = Math.min(
    longestInteractionList.length - 1,
    Math.floor(getInteractionCountForNavigation() / 50)
  );
  return longestInteractionList[candidateInteractionIndex];
}, "estimateP98LongestInteraction");
const MAX_INTERACTIONS_TO_CONSIDER = 10;
const entryPreProcessingCallbacks = [];
const processInteractionEntry = /* @__PURE__ */ __name((entry) => {
  entryPreProcessingCallbacks.forEach((cb) => cb(entry));
  if (!(entry.interactionId || entry.entryType === "first-input")) return;
  const minLongestInteraction = longestInteractionList[longestInteractionList.length - 1];
  const existingInteraction = longestInteractionMap.get(entry.interactionId);
  if (existingInteraction || longestInteractionList.length < MAX_INTERACTIONS_TO_CONSIDER || minLongestInteraction && entry.duration > minLongestInteraction.latency) {
    if (existingInteraction) {
      if (entry.duration > existingInteraction.latency) {
        existingInteraction.entries = [entry];
        existingInteraction.latency = entry.duration;
      } else if (entry.duration === existingInteraction.latency && entry.startTime === (existingInteraction.entries[0] && existingInteraction.entries[0].startTime)) {
        existingInteraction.entries.push(entry);
      }
    } else {
      const interaction = {
        id: entry.interactionId,
        latency: entry.duration,
        entries: [entry]
      };
      longestInteractionMap.set(interaction.id, interaction);
      longestInteractionList.push(interaction);
    }
    longestInteractionList.sort((a2, b2) => b2.latency - a2.latency);
    if (longestInteractionList.length > MAX_INTERACTIONS_TO_CONSIDER) {
      longestInteractionList.splice(MAX_INTERACTIONS_TO_CONSIDER).forEach((i2) => longestInteractionMap.delete(i2.id));
    }
  }
}, "processInteractionEntry");
const whenIdle = /* @__PURE__ */ __name((cb) => {
  const rIC = WINDOW$4.requestIdleCallback || WINDOW$4.setTimeout;
  let handle = -1;
  cb = runOnce(cb);
  if (WINDOW$4.document && WINDOW$4.document.visibilityState === "hidden") {
    cb();
  } else {
    handle = rIC(cb);
    onHidden(cb);
  }
  return handle;
}, "whenIdle");
const INPThresholds = [200, 500];
const onINP = /* @__PURE__ */ __name((onReport, opts = {}) => {
  if (!("PerformanceEventTiming" in WINDOW$4 && "interactionId" in PerformanceEventTiming.prototype)) {
    return;
  }
  whenActivated(() => {
    initInteractionCountPolyfill();
    const metric = initMetric("INP");
    let report;
    const handleEntries = /* @__PURE__ */ __name((entries) => {
      whenIdle(() => {
        entries.forEach(processInteractionEntry);
        const inp = estimateP98LongestInteraction();
        if (inp && inp.latency !== metric.value) {
          metric.value = inp.latency;
          metric.entries = inp.entries;
          report();
        }
      });
    }, "handleEntries");
    const po2 = observe("event", handleEntries, {
      // Event Timing entries have their durations rounded to the nearest 8ms,
      // so a duration of 40ms would be any event that spans 2.5 or more frames
      // at 60Hz. This threshold is chosen to strike a balance between usefulness
      // and performance. Running this callback for any interaction that spans
      // just one or two frames is likely not worth the insight that could be
      // gained.
      durationThreshold: opts.durationThreshold != null ? opts.durationThreshold : DEFAULT_DURATION_THRESHOLD
    });
    report = bindReporter(onReport, metric, INPThresholds, opts.reportAllChanges);
    if (po2) {
      po2.observe({ type: "first-input", buffered: true });
      onHidden(() => {
        handleEntries(po2.takeRecords());
        report(true);
      });
    }
  });
}, "onINP");
const LCPThresholds = [2500, 4e3];
const reportedMetricIDs = {};
const onLCP = /* @__PURE__ */ __name((onReport, opts = {}) => {
  whenActivated(() => {
    const visibilityWatcher = getVisibilityWatcher();
    const metric = initMetric("LCP");
    let report;
    const handleEntries = /* @__PURE__ */ __name((entries) => {
      if (!opts.reportAllChanges) {
        entries = entries.slice(-1);
      }
      entries.forEach((entry) => {
        if (entry.startTime < visibilityWatcher.firstHiddenTime) {
          metric.value = Math.max(entry.startTime - getActivationStart(), 0);
          metric.entries = [entry];
          report();
        }
      });
    }, "handleEntries");
    const po2 = observe("largest-contentful-paint", handleEntries);
    if (po2) {
      report = bindReporter(onReport, metric, LCPThresholds, opts.reportAllChanges);
      const stopListening = runOnce(() => {
        if (!reportedMetricIDs[metric.id]) {
          handleEntries(po2.takeRecords());
          po2.disconnect();
          reportedMetricIDs[metric.id] = true;
          report(true);
        }
      });
      ["keydown", "click"].forEach((type) => {
        if (WINDOW$4.document) {
          addEventListener(type, () => whenIdle(stopListening), {
            once: true,
            capture: true
          });
        }
      });
      onHidden(stopListening);
    }
  });
}, "onLCP");
const TTFBThresholds = [800, 1800];
const whenReady = /* @__PURE__ */ __name((callback) => {
  if (WINDOW$4.document && WINDOW$4.document.prerendering) {
    whenActivated(() => whenReady(callback));
  } else if (WINDOW$4.document && WINDOW$4.document.readyState !== "complete") {
    addEventListener("load", () => whenReady(callback), true);
  } else {
    setTimeout(callback, 0);
  }
}, "whenReady");
const onTTFB = /* @__PURE__ */ __name((onReport, opts = {}) => {
  const metric = initMetric("TTFB");
  const report = bindReporter(onReport, metric, TTFBThresholds, opts.reportAllChanges);
  whenReady(() => {
    const navigationEntry = getNavigationEntry();
    if (navigationEntry) {
      metric.value = Math.max(navigationEntry.responseStart - getActivationStart(), 0);
      metric.entries = [navigationEntry];
      report(true);
    }
  });
}, "onTTFB");
const handlers$3 = {};
const instrumented = {};
let _previousCls;
let _previousFid;
let _previousLcp;
let _previousTtfb;
let _previousInp;
function addClsInstrumentationHandler(callback, stopOnCallback = false) {
  return addMetricObserver("cls", callback, instrumentCls, _previousCls, stopOnCallback);
}
__name(addClsInstrumentationHandler, "addClsInstrumentationHandler");
function addLcpInstrumentationHandler(callback, stopOnCallback = false) {
  return addMetricObserver("lcp", callback, instrumentLcp, _previousLcp, stopOnCallback);
}
__name(addLcpInstrumentationHandler, "addLcpInstrumentationHandler");
function addFidInstrumentationHandler(callback) {
  return addMetricObserver("fid", callback, instrumentFid, _previousFid);
}
__name(addFidInstrumentationHandler, "addFidInstrumentationHandler");
function addTtfbInstrumentationHandler(callback) {
  return addMetricObserver("ttfb", callback, instrumentTtfb, _previousTtfb);
}
__name(addTtfbInstrumentationHandler, "addTtfbInstrumentationHandler");
function addInpInstrumentationHandler(callback) {
  return addMetricObserver("inp", callback, instrumentInp, _previousInp);
}
__name(addInpInstrumentationHandler, "addInpInstrumentationHandler");
function addPerformanceInstrumentationHandler(type, callback) {
  addHandler(type, callback);
  if (!instrumented[type]) {
    instrumentPerformanceObserver(type);
    instrumented[type] = true;
  }
  return getCleanupCallback(type, callback);
}
__name(addPerformanceInstrumentationHandler, "addPerformanceInstrumentationHandler");
function triggerHandlers(type, data) {
  const typeHandlers = handlers$3[type];
  if (!typeHandlers || !typeHandlers.length) {
    return;
  }
  for (const handler5 of typeHandlers) {
    try {
      handler5(data);
    } catch (e2) {
      DEBUG_BUILD$3 && logger$5.error(
        `Error while triggering instrumentation handler.
Type: ${type}
Name: ${getFunctionName(handler5)}
Error:`,
        e2
      );
    }
  }
}
__name(triggerHandlers, "triggerHandlers");
function instrumentCls() {
  return onCLS(
    (metric) => {
      triggerHandlers("cls", {
        metric
      });
      _previousCls = metric;
    },
    // We want the callback to be called whenever the CLS value updates.
    // By default, the callback is only called when the tab goes to the background.
    { reportAllChanges: true }
  );
}
__name(instrumentCls, "instrumentCls");
function instrumentFid() {
  return onFID((metric) => {
    triggerHandlers("fid", {
      metric
    });
    _previousFid = metric;
  });
}
__name(instrumentFid, "instrumentFid");
function instrumentLcp() {
  return onLCP(
    (metric) => {
      triggerHandlers("lcp", {
        metric
      });
      _previousLcp = metric;
    },
    // We want the callback to be called whenever the LCP value updates.
    // By default, the callback is only called when the tab goes to the background.
    { reportAllChanges: true }
  );
}
__name(instrumentLcp, "instrumentLcp");
function instrumentTtfb() {
  return onTTFB((metric) => {
    triggerHandlers("ttfb", {
      metric
    });
    _previousTtfb = metric;
  });
}
__name(instrumentTtfb, "instrumentTtfb");
function instrumentInp() {
  return onINP((metric) => {
    triggerHandlers("inp", {
      metric
    });
    _previousInp = metric;
  });
}
__name(instrumentInp, "instrumentInp");
function addMetricObserver(type, callback, instrumentFn, previousValue, stopOnCallback = false) {
  addHandler(type, callback);
  let stopListening;
  if (!instrumented[type]) {
    stopListening = instrumentFn();
    instrumented[type] = true;
  }
  if (previousValue) {
    callback({ metric: previousValue });
  }
  return getCleanupCallback(type, callback, stopOnCallback ? stopListening : void 0);
}
__name(addMetricObserver, "addMetricObserver");
function instrumentPerformanceObserver(type) {
  const options2 = {};
  if (type === "event") {
    options2.durationThreshold = 0;
  }
  observe(
    type,
    (entries) => {
      triggerHandlers(type, { entries });
    },
    options2
  );
}
__name(instrumentPerformanceObserver, "instrumentPerformanceObserver");
function addHandler(type, handler5) {
  handlers$3[type] = handlers$3[type] || [];
  handlers$3[type].push(handler5);
}
__name(addHandler, "addHandler");
function getCleanupCallback(type, callback, stopListening) {
  return () => {
    if (stopListening) {
      stopListening();
    }
    const typeHandlers = handlers$3[type];
    if (!typeHandlers) {
      return;
    }
    const index2 = typeHandlers.indexOf(callback);
    if (index2 !== -1) {
      typeHandlers.splice(index2, 1);
    }
  };
}
__name(getCleanupCallback, "getCleanupCallback");
function isPerformanceEventTiming(entry) {
  return "duration" in entry;
}
__name(isPerformanceEventTiming, "isPerformanceEventTiming");
function isMeasurementValue(value) {
  return typeof value === "number" && isFinite(value);
}
__name(isMeasurementValue, "isMeasurementValue");
function startAndEndSpan(parentSpan, startTimeInSeconds, endTime, { ...ctx }) {
  const parentStartTime = spanToJSON(parentSpan).start_timestamp;
  if (parentStartTime && parentStartTime > startTimeInSeconds) {
    if (typeof parentSpan.updateStartTime === "function") {
      parentSpan.updateStartTime(startTimeInSeconds);
    }
  }
  return withActiveSpan(parentSpan, () => {
    const span = startInactiveSpan({
      startTime: startTimeInSeconds,
      ...ctx
    });
    if (span) {
      span.end(endTime);
    }
    return span;
  });
}
__name(startAndEndSpan, "startAndEndSpan");
function startStandaloneWebVitalSpan(options2) {
  const client = getClient();
  if (!client) {
    return;
  }
  const { name: name2, transaction, attributes: passedAttributes, startTime } = options2;
  const { release, environment } = client.getOptions();
  const replay = client.getIntegrationByName("Replay");
  const replayId = replay && replay.getReplayId();
  const scope = getCurrentScope();
  const user = scope.getUser();
  const userDisplay = user !== void 0 ? user.email || user.id || user.ip_address : void 0;
  let profileId;
  try {
    profileId = scope.getScopeData().contexts.profile.profile_id;
  } catch (e2) {
  }
  const attributes = {
    release,
    environment,
    user: userDisplay || void 0,
    profile_id: profileId || void 0,
    replay_id: replayId || void 0,
    transaction,
    // Web vital score calculation relies on the user agent to account for different
    // browsers setting different thresholds for what is considered a good/meh/bad value.
    // For example: Chrome vs. Chrome Mobile
    "user_agent.original": WINDOW$4.navigator && WINDOW$4.navigator.userAgent,
    ...passedAttributes
  };
  return startInactiveSpan({
    name: name2,
    attributes,
    startTime,
    experimental: {
      standalone: true
    }
  });
}
__name(startStandaloneWebVitalSpan, "startStandaloneWebVitalSpan");
function getBrowserPerformanceAPI() {
  return WINDOW$4 && WINDOW$4.addEventListener && WINDOW$4.performance;
}
__name(getBrowserPerformanceAPI, "getBrowserPerformanceAPI");
function msToSec(time) {
  return time / 1e3;
}
__name(msToSec, "msToSec");
function trackClsAsStandaloneSpan() {
  let standaloneCLsValue = 0;
  let standaloneClsEntry;
  let pageloadSpanId;
  if (!supportsLayoutShift()) {
    return;
  }
  let sentSpan = false;
  function _collectClsOnce() {
    if (sentSpan) {
      return;
    }
    sentSpan = true;
    if (pageloadSpanId) {
      sendStandaloneClsSpan(standaloneCLsValue, standaloneClsEntry, pageloadSpanId);
    }
    cleanupClsHandler();
  }
  __name(_collectClsOnce, "_collectClsOnce");
  const cleanupClsHandler = addClsInstrumentationHandler(({ metric }) => {
    const entry = metric.entries[metric.entries.length - 1];
    if (!entry) {
      return;
    }
    standaloneCLsValue = metric.value;
    standaloneClsEntry = entry;
  }, true);
  onHidden(() => {
    _collectClsOnce();
  });
  setTimeout(() => {
    const client = getClient();
    if (!client) {
      return;
    }
    const unsubscribeStartNavigation = client.on("startNavigationSpan", () => {
      _collectClsOnce();
      unsubscribeStartNavigation && unsubscribeStartNavigation();
    });
    const activeSpan = getActiveSpan();
    const rootSpan = activeSpan && getRootSpan(activeSpan);
    const spanJSON = rootSpan && spanToJSON(rootSpan);
    if (spanJSON && spanJSON.op === "pageload") {
      pageloadSpanId = rootSpan.spanContext().spanId;
    }
  }, 0);
}
__name(trackClsAsStandaloneSpan, "trackClsAsStandaloneSpan");
function sendStandaloneClsSpan(clsValue, entry, pageloadSpanId) {
  DEBUG_BUILD$3 && logger$5.log(`Sending CLS span (${clsValue})`);
  const startTime = msToSec((browserPerformanceTimeOrigin || 0) + (entry && entry.startTime || 0));
  const routeName = getCurrentScope().getScopeData().transactionName;
  const name2 = entry ? htmlTreeAsString(entry.sources[0] && entry.sources[0].node) : "Layout shift";
  const attributes = dropUndefinedKeys({
    [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.http.browser.cls",
    [SEMANTIC_ATTRIBUTE_SENTRY_OP]: "ui.webvital.cls",
    [SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME]: entry && entry.duration || 0,
    // attach the pageload span id to the CLS span so that we can link them in the UI
    "sentry.pageload.span_id": pageloadSpanId
  });
  const span = startStandaloneWebVitalSpan({
    name: name2,
    transaction: routeName,
    attributes,
    startTime
  });
  if (span) {
    span.addEvent("cls", {
      [SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT]: "",
      [SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE]: clsValue
    });
    span.end(startTime);
  }
}
__name(sendStandaloneClsSpan, "sendStandaloneClsSpan");
function supportsLayoutShift() {
  try {
    return PerformanceObserver.supportedEntryTypes.includes("layout-shift");
  } catch (e2) {
    return false;
  }
}
__name(supportsLayoutShift, "supportsLayoutShift");
const MAX_INT_AS_BYTES = 2147483647;
let _performanceCursor = 0;
let _measurements = {};
let _lcpEntry;
let _clsEntry;
function startTrackingWebVitals({ recordClsStandaloneSpans }) {
  const performance2 = getBrowserPerformanceAPI();
  if (performance2 && browserPerformanceTimeOrigin) {
    if (performance2.mark) {
      WINDOW$4.performance.mark("sentry-tracing-init");
    }
    const fidCleanupCallback = _trackFID();
    const lcpCleanupCallback = _trackLCP();
    const ttfbCleanupCallback = _trackTtfb();
    const clsCleanupCallback = recordClsStandaloneSpans ? trackClsAsStandaloneSpan() : _trackCLS();
    return () => {
      fidCleanupCallback();
      lcpCleanupCallback();
      ttfbCleanupCallback();
      clsCleanupCallback && clsCleanupCallback();
    };
  }
  return () => void 0;
}
__name(startTrackingWebVitals, "startTrackingWebVitals");
function startTrackingLongTasks() {
  addPerformanceInstrumentationHandler("longtask", ({ entries }) => {
    const parent2 = getActiveSpan();
    if (!parent2) {
      return;
    }
    const { op: parentOp, start_timestamp: parentStartTimestamp } = spanToJSON(parent2);
    for (const entry of entries) {
      const startTime = msToSec(browserPerformanceTimeOrigin + entry.startTime);
      const duration = msToSec(entry.duration);
      if (parentOp === "navigation" && parentStartTimestamp && startTime < parentStartTimestamp) {
        continue;
      }
      startAndEndSpan(parent2, startTime, startTime + duration, {
        name: "Main UI thread blocked",
        op: "ui.long-task",
        attributes: {
          [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.ui.browser.metrics"
        }
      });
    }
  });
}
__name(startTrackingLongTasks, "startTrackingLongTasks");
function startTrackingLongAnimationFrames() {
  const observer = new PerformanceObserver((list2) => {
    const parent2 = getActiveSpan();
    if (!parent2) {
      return;
    }
    for (const entry of list2.getEntries()) {
      if (!entry.scripts[0]) {
        continue;
      }
      const startTime = msToSec(browserPerformanceTimeOrigin + entry.startTime);
      const { start_timestamp: parentStartTimestamp, op: parentOp } = spanToJSON(parent2);
      if (parentOp === "navigation" && parentStartTimestamp && startTime < parentStartTimestamp) {
        continue;
      }
      const duration = msToSec(entry.duration);
      const attributes = {
        [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.ui.browser.metrics"
      };
      const initialScript = entry.scripts[0];
      const { invoker, invokerType, sourceURL, sourceFunctionName, sourceCharPosition } = initialScript;
      attributes["browser.script.invoker"] = invoker;
      attributes["browser.script.invoker_type"] = invokerType;
      if (sourceURL) {
        attributes["code.filepath"] = sourceURL;
      }
      if (sourceFunctionName) {
        attributes["code.function"] = sourceFunctionName;
      }
      if (sourceCharPosition !== -1) {
        attributes["browser.script.source_char_position"] = sourceCharPosition;
      }
      startAndEndSpan(parent2, startTime, startTime + duration, {
        name: "Main UI thread blocked",
        op: "ui.long-animation-frame",
        attributes
      });
    }
  });
  observer.observe({ type: "long-animation-frame", buffered: true });
}
__name(startTrackingLongAnimationFrames, "startTrackingLongAnimationFrames");
function startTrackingInteractions() {
  addPerformanceInstrumentationHandler("event", ({ entries }) => {
    const parent2 = getActiveSpan();
    if (!parent2) {
      return;
    }
    for (const entry of entries) {
      if (entry.name === "click") {
        const startTime = msToSec(browserPerformanceTimeOrigin + entry.startTime);
        const duration = msToSec(entry.duration);
        const spanOptions = {
          name: htmlTreeAsString(entry.target),
          op: `ui.interaction.${entry.name}`,
          startTime,
          attributes: {
            [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.ui.browser.metrics"
          }
        };
        const componentName = getComponentName(entry.target);
        if (componentName) {
          spanOptions.attributes["ui.component_name"] = componentName;
        }
        startAndEndSpan(parent2, startTime, startTime + duration, spanOptions);
      }
    }
  });
}
__name(startTrackingInteractions, "startTrackingInteractions");
function _trackCLS() {
  return addClsInstrumentationHandler(({ metric }) => {
    const entry = metric.entries[metric.entries.length - 1];
    if (!entry) {
      return;
    }
    _measurements["cls"] = { value: metric.value, unit: "" };
    _clsEntry = entry;
  }, true);
}
__name(_trackCLS, "_trackCLS");
function _trackLCP() {
  return addLcpInstrumentationHandler(({ metric }) => {
    const entry = metric.entries[metric.entries.length - 1];
    if (!entry) {
      return;
    }
    _measurements["lcp"] = { value: metric.value, unit: "millisecond" };
    _lcpEntry = entry;
  }, true);
}
__name(_trackLCP, "_trackLCP");
function _trackFID() {
  return addFidInstrumentationHandler(({ metric }) => {
    const entry = metric.entries[metric.entries.length - 1];
    if (!entry) {
      return;
    }
    const timeOrigin = msToSec(browserPerformanceTimeOrigin);
    const startTime = msToSec(entry.startTime);
    _measurements["fid"] = { value: metric.value, unit: "millisecond" };
    _measurements["mark.fid"] = { value: timeOrigin + startTime, unit: "second" };
  });
}
__name(_trackFID, "_trackFID");
function _trackTtfb() {
  return addTtfbInstrumentationHandler(({ metric }) => {
    const entry = metric.entries[metric.entries.length - 1];
    if (!entry) {
      return;
    }
    _measurements["ttfb"] = { value: metric.value, unit: "millisecond" };
  });
}
__name(_trackTtfb, "_trackTtfb");
function addPerformanceEntries(span, options2) {
  const performance2 = getBrowserPerformanceAPI();
  if (!performance2 || !performance2.getEntries || !browserPerformanceTimeOrigin) {
    return;
  }
  const timeOrigin = msToSec(browserPerformanceTimeOrigin);
  const performanceEntries = performance2.getEntries();
  const { op, start_timestamp: transactionStartTime } = spanToJSON(span);
  performanceEntries.slice(_performanceCursor).forEach((entry) => {
    const startTime = msToSec(entry.startTime);
    const duration = msToSec(
      // Inexplicably, Chrome sometimes emits a negative duration. We need to work around this.
      // There is a SO post attempting to explain this, but it leaves one with open questions: https://stackoverflow.com/questions/23191918/peformance-getentries-and-negative-duration-display
      // The way we clamp the value is probably not accurate, since we have observed this happen for things that may take a while to load, like for example the replay worker.
      // TODO: Investigate why this happens and how to properly mitigate. For now, this is a workaround to prevent transactions being dropped due to negative duration spans.
      Math.max(0, entry.duration)
    );
    if (op === "navigation" && transactionStartTime && timeOrigin + startTime < transactionStartTime) {
      return;
    }
    switch (entry.entryType) {
      case "navigation": {
        _addNavigationSpans(span, entry, timeOrigin);
        break;
      }
      case "mark":
      case "paint":
      case "measure": {
        _addMeasureSpans(span, entry, startTime, duration, timeOrigin);
        const firstHidden = getVisibilityWatcher();
        const shouldRecord = entry.startTime < firstHidden.firstHiddenTime;
        if (entry.name === "first-paint" && shouldRecord) {
          _measurements["fp"] = { value: entry.startTime, unit: "millisecond" };
        }
        if (entry.name === "first-contentful-paint" && shouldRecord) {
          _measurements["fcp"] = { value: entry.startTime, unit: "millisecond" };
        }
        break;
      }
      case "resource": {
        _addResourceSpans(span, entry, entry.name, startTime, duration, timeOrigin);
        break;
      }
    }
  });
  _performanceCursor = Math.max(performanceEntries.length - 1, 0);
  _trackNavigator(span);
  if (op === "pageload") {
    _addTtfbRequestTimeToMeasurements(_measurements);
    const fidMark = _measurements["mark.fid"];
    if (fidMark && _measurements["fid"]) {
      startAndEndSpan(span, fidMark.value, fidMark.value + msToSec(_measurements["fid"].value), {
        name: "first input delay",
        op: "ui.action",
        attributes: {
          [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.ui.browser.metrics"
        }
      });
      delete _measurements["mark.fid"];
    }
    if (!("fcp" in _measurements) || !options2.recordClsOnPageloadSpan) {
      delete _measurements.cls;
    }
    Object.entries(_measurements).forEach(([measurementName, measurement]) => {
      setMeasurement(measurementName, measurement.value, measurement.unit);
    });
    span.setAttribute("performance.timeOrigin", timeOrigin);
    span.setAttribute("performance.activationStart", getActivationStart());
    _setWebVitalAttributes(span);
  }
  _lcpEntry = void 0;
  _clsEntry = void 0;
  _measurements = {};
}
__name(addPerformanceEntries, "addPerformanceEntries");
function _addMeasureSpans(span, entry, startTime, duration, timeOrigin) {
  const navEntry = getNavigationEntry(false);
  const requestTime = msToSec(navEntry ? navEntry.requestStart : 0);
  const measureStartTimestamp = timeOrigin + Math.max(startTime, requestTime);
  const startTimeStamp = timeOrigin + startTime;
  const measureEndTimestamp = startTimeStamp + duration;
  const attributes = {
    [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.resource.browser.metrics"
  };
  if (measureStartTimestamp !== startTimeStamp) {
    attributes["sentry.browser.measure_happened_before_request"] = true;
    attributes["sentry.browser.measure_start_time"] = measureStartTimestamp;
  }
  startAndEndSpan(span, measureStartTimestamp, measureEndTimestamp, {
    name: entry.name,
    op: entry.entryType,
    attributes
  });
  return measureStartTimestamp;
}
__name(_addMeasureSpans, "_addMeasureSpans");
function _addNavigationSpans(span, entry, timeOrigin) {
  ["unloadEvent", "redirect", "domContentLoadedEvent", "loadEvent", "connect"].forEach((event) => {
    _addPerformanceNavigationTiming(span, entry, event, timeOrigin);
  });
  _addPerformanceNavigationTiming(span, entry, "secureConnection", timeOrigin, "TLS/SSL");
  _addPerformanceNavigationTiming(span, entry, "fetch", timeOrigin, "cache");
  _addPerformanceNavigationTiming(span, entry, "domainLookup", timeOrigin, "DNS");
  _addRequest(span, entry, timeOrigin);
}
__name(_addNavigationSpans, "_addNavigationSpans");
function _addPerformanceNavigationTiming(span, entry, event, timeOrigin, name2 = event) {
  const eventEnd = _getEndPropertyNameForNavigationTiming(event);
  const end = entry[eventEnd];
  const start2 = entry[`${event}Start`];
  if (!start2 || !end) {
    return;
  }
  startAndEndSpan(span, timeOrigin + msToSec(start2), timeOrigin + msToSec(end), {
    op: `browser.${name2}`,
    name: entry.name,
    attributes: {
      [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.ui.browser.metrics"
    }
  });
}
__name(_addPerformanceNavigationTiming, "_addPerformanceNavigationTiming");
function _getEndPropertyNameForNavigationTiming(event) {
  if (event === "secureConnection") {
    return "connectEnd";
  }
  if (event === "fetch") {
    return "domainLookupStart";
  }
  return `${event}End`;
}
__name(_getEndPropertyNameForNavigationTiming, "_getEndPropertyNameForNavigationTiming");
function _addRequest(span, entry, timeOrigin) {
  const requestStartTimestamp = timeOrigin + msToSec(entry.requestStart);
  const responseEndTimestamp = timeOrigin + msToSec(entry.responseEnd);
  const responseStartTimestamp = timeOrigin + msToSec(entry.responseStart);
  if (entry.responseEnd) {
    startAndEndSpan(span, requestStartTimestamp, responseEndTimestamp, {
      op: "browser.request",
      name: entry.name,
      attributes: {
        [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.ui.browser.metrics"
      }
    });
    startAndEndSpan(span, responseStartTimestamp, responseEndTimestamp, {
      op: "browser.response",
      name: entry.name,
      attributes: {
        [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.ui.browser.metrics"
      }
    });
  }
}
__name(_addRequest, "_addRequest");
function _addResourceSpans(span, entry, resourceUrl, startTime, duration, timeOrigin) {
  if (entry.initiatorType === "xmlhttprequest" || entry.initiatorType === "fetch") {
    return;
  }
  const parsedUrl = parseUrl$1(resourceUrl);
  const attributes = {
    [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.resource.browser.metrics"
  };
  setResourceEntrySizeData(attributes, entry, "transferSize", "http.response_transfer_size");
  setResourceEntrySizeData(attributes, entry, "encodedBodySize", "http.response_content_length");
  setResourceEntrySizeData(attributes, entry, "decodedBodySize", "http.decoded_response_content_length");
  const deliveryType = entry.deliveryType;
  if (deliveryType != null) {
    attributes["http.response_delivery_type"] = deliveryType;
  }
  const renderBlockingStatus = entry.renderBlockingStatus;
  if (renderBlockingStatus) {
    attributes["resource.render_blocking_status"] = renderBlockingStatus;
  }
  if (parsedUrl.protocol) {
    attributes["url.scheme"] = parsedUrl.protocol.split(":").pop();
  }
  if (parsedUrl.host) {
    attributes["server.address"] = parsedUrl.host;
  }
  attributes["url.same_origin"] = resourceUrl.includes(WINDOW$4.location.origin);
  const startTimestamp = timeOrigin + startTime;
  const endTimestamp = startTimestamp + duration;
  startAndEndSpan(span, startTimestamp, endTimestamp, {
    name: resourceUrl.replace(WINDOW$4.location.origin, ""),
    op: entry.initiatorType ? `resource.${entry.initiatorType}` : "resource.other",
    attributes
  });
}
__name(_addResourceSpans, "_addResourceSpans");
function _trackNavigator(span) {
  const navigator2 = WINDOW$4.navigator;
  if (!navigator2) {
    return;
  }
  const connection = navigator2.connection;
  if (connection) {
    if (connection.effectiveType) {
      span.setAttribute("effectiveConnectionType", connection.effectiveType);
    }
    if (connection.type) {
      span.setAttribute("connectionType", connection.type);
    }
    if (isMeasurementValue(connection.rtt)) {
      _measurements["connection.rtt"] = { value: connection.rtt, unit: "millisecond" };
    }
  }
  if (isMeasurementValue(navigator2.deviceMemory)) {
    span.setAttribute("deviceMemory", `${navigator2.deviceMemory} GB`);
  }
  if (isMeasurementValue(navigator2.hardwareConcurrency)) {
    span.setAttribute("hardwareConcurrency", String(navigator2.hardwareConcurrency));
  }
}
__name(_trackNavigator, "_trackNavigator");
function _setWebVitalAttributes(span) {
  if (_lcpEntry) {
    if (_lcpEntry.element) {
      span.setAttribute("lcp.element", htmlTreeAsString(_lcpEntry.element));
    }
    if (_lcpEntry.id) {
      span.setAttribute("lcp.id", _lcpEntry.id);
    }
    if (_lcpEntry.url) {
      span.setAttribute("lcp.url", _lcpEntry.url.trim().slice(0, 200));
    }
    if (_lcpEntry.loadTime != null) {
      span.setAttribute("lcp.loadTime", _lcpEntry.loadTime);
    }
    if (_lcpEntry.renderTime != null) {
      span.setAttribute("lcp.renderTime", _lcpEntry.renderTime);
    }
    span.setAttribute("lcp.size", _lcpEntry.size);
  }
  if (_clsEntry && _clsEntry.sources) {
    _clsEntry.sources.forEach(
      (source, index2) => span.setAttribute(`cls.source.${index2 + 1}`, htmlTreeAsString(source.node))
    );
  }
}
__name(_setWebVitalAttributes, "_setWebVitalAttributes");
function setResourceEntrySizeData(attributes, entry, key, dataKey) {
  const entryVal = entry[key];
  if (entryVal != null && entryVal < MAX_INT_AS_BYTES) {
    attributes[dataKey] = entryVal;
  }
}
__name(setResourceEntrySizeData, "setResourceEntrySizeData");
function _addTtfbRequestTimeToMeasurements(_measurements2) {
  const navEntry = getNavigationEntry(false);
  if (!navEntry) {
    return;
  }
  const { responseStart, requestStart } = navEntry;
  if (requestStart <= responseStart) {
    _measurements2["ttfb.requestTime"] = {
      value: responseStart - requestStart,
      unit: "millisecond"
    };
  }
}
__name(_addTtfbRequestTimeToMeasurements, "_addTtfbRequestTimeToMeasurements");
const DEBOUNCE_DURATION = 1e3;
let debounceTimerID;
let lastCapturedEventType;
let lastCapturedEventTargetId;
function addClickKeypressInstrumentationHandler(handler5) {
  const type = "dom";
  addHandler$1(type, handler5);
  maybeInstrument(type, instrumentDOM);
}
__name(addClickKeypressInstrumentationHandler, "addClickKeypressInstrumentationHandler");
function instrumentDOM() {
  if (!WINDOW$4.document) {
    return;
  }
  const triggerDOMHandler = triggerHandlers$1.bind(null, "dom");
  const globalDOMEventHandler = makeDOMEventHandler(triggerDOMHandler, true);
  WINDOW$4.document.addEventListener("click", globalDOMEventHandler, false);
  WINDOW$4.document.addEventListener("keypress", globalDOMEventHandler, false);
  ["EventTarget", "Node"].forEach((target) => {
    const globalObject = WINDOW$4;
    const targetObj = globalObject[target];
    const proto = targetObj && targetObj.prototype;
    if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty("addEventListener")) {
      return;
    }
    fill(proto, "addEventListener", function(originalAddEventListener) {
      return function(type, listener, options2) {
        if (type === "click" || type == "keypress") {
          try {
            const handlers2 = this.__sentry_instrumentation_handlers__ = this.__sentry_instrumentation_handlers__ || {};
            const handlerForType = handlers2[type] = handlers2[type] || { refCount: 0 };
            if (!handlerForType.handler) {
              const handler5 = makeDOMEventHandler(triggerDOMHandler);
              handlerForType.handler = handler5;
              originalAddEventListener.call(this, type, handler5, options2);
            }
            handlerForType.refCount++;
          } catch (e2) {
          }
        }
        return originalAddEventListener.call(this, type, listener, options2);
      };
    });
    fill(
      proto,
      "removeEventListener",
      function(originalRemoveEventListener) {
        return function(type, listener, options2) {
          if (type === "click" || type == "keypress") {
            try {
              const handlers2 = this.__sentry_instrumentation_handlers__ || {};
              const handlerForType = handlers2[type];
              if (handlerForType) {
                handlerForType.refCount--;
                if (handlerForType.refCount <= 0) {
                  originalRemoveEventListener.call(this, type, handlerForType.handler, options2);
                  handlerForType.handler = void 0;
                  delete handlers2[type];
                }
                if (Object.keys(handlers2).length === 0) {
                  delete this.__sentry_instrumentation_handlers__;
                }
              }
            } catch (e2) {
            }
          }
          return originalRemoveEventListener.call(this, type, listener, options2);
        };
      }
    );
  });
}
__name(instrumentDOM, "instrumentDOM");
function isSimilarToLastCapturedEvent(event) {
  if (event.type !== lastCapturedEventType) {
    return false;
  }
  try {
    if (!event.target || event.target._sentryId !== lastCapturedEventTargetId) {
      return false;
    }
  } catch (e2) {
  }
  return true;
}
__name(isSimilarToLastCapturedEvent, "isSimilarToLastCapturedEvent");
function shouldSkipDOMEvent(eventType, target) {
  if (eventType !== "keypress") {
    return false;
  }
  if (!target || !target.tagName) {
    return true;
  }
  if (target.tagName === "INPUT" || target.tagName === "TEXTAREA" || target.isContentEditable) {
    return false;
  }
  return true;
}
__name(shouldSkipDOMEvent, "shouldSkipDOMEvent");
function makeDOMEventHandler(handler5, globalListener = false) {
  return (event) => {
    if (!event || event["_sentryCaptured"]) {
      return;
    }
    const target = getEventTarget$1(event);
    if (shouldSkipDOMEvent(event.type, target)) {
      return;
    }
    addNonEnumerableProperty(event, "_sentryCaptured", true);
    if (target && !target._sentryId) {
      addNonEnumerableProperty(target, "_sentryId", uuid4());
    }
    const name2 = event.type === "keypress" ? "input" : event.type;
    if (!isSimilarToLastCapturedEvent(event)) {
      const handlerData = { event, name: name2, global: globalListener };
      handler5(handlerData);
      lastCapturedEventType = event.type;
      lastCapturedEventTargetId = target ? target._sentryId : void 0;
    }
    clearTimeout(debounceTimerID);
    debounceTimerID = WINDOW$4.setTimeout(() => {
      lastCapturedEventTargetId = void 0;
      lastCapturedEventType = void 0;
    }, DEBOUNCE_DURATION);
  };
}
__name(makeDOMEventHandler, "makeDOMEventHandler");
function getEventTarget$1(event) {
  try {
    return event.target;
  } catch (e2) {
    return null;
  }
}
__name(getEventTarget$1, "getEventTarget$1");
let lastHref;
function addHistoryInstrumentationHandler(handler5) {
  const type = "history";
  addHandler$1(type, handler5);
  maybeInstrument(type, instrumentHistory);
}
__name(addHistoryInstrumentationHandler, "addHistoryInstrumentationHandler");
function instrumentHistory() {
  if (!supportsHistory()) {
    return;
  }
  const oldOnPopState = WINDOW$4.onpopstate;
  WINDOW$4.onpopstate = function(...args) {
    const to = WINDOW$4.location.href;
    const from2 = lastHref;
    lastHref = to;
    const handlerData = { from: from2, to };
    triggerHandlers$1("history", handlerData);
    if (oldOnPopState) {
      try {
        return oldOnPopState.apply(this, args);
      } catch (_oO) {
      }
    }
  };
  function historyReplacementFunction(originalHistoryFunction) {
    return function(...args) {
      const url = args.length > 2 ? args[2] : void 0;
      if (url) {
        const from2 = lastHref;
        const to = String(url);
        lastHref = to;
        const handlerData = { from: from2, to };
        triggerHandlers$1("history", handlerData);
      }
      return originalHistoryFunction.apply(this, args);
    };
  }
  __name(historyReplacementFunction, "historyReplacementFunction");
  fill(WINDOW$4.history, "pushState", historyReplacementFunction);
  fill(WINDOW$4.history, "replaceState", historyReplacementFunction);
}
__name(instrumentHistory, "instrumentHistory");
const cachedImplementations$3 = {};
function getNativeImplementation(name2) {
  const cached = cachedImplementations$3[name2];
  if (cached) {
    return cached;
  }
  let impl = WINDOW$4[name2];
  if (isNativeFunction(impl)) {
    return cachedImplementations$3[name2] = impl.bind(WINDOW$4);
  }
  const document2 = WINDOW$4.document;
  if (document2 && typeof document2.createElement === "function") {
    try {
      const sandbox = document2.createElement("iframe");
      sandbox.hidden = true;
      document2.head.appendChild(sandbox);
      const contentWindow = sandbox.contentWindow;
      if (contentWindow && contentWindow[name2]) {
        impl = contentWindow[name2];
      }
      document2.head.removeChild(sandbox);
    } catch (e2) {
      DEBUG_BUILD$3 && logger$5.warn(`Could not create sandbox iframe for ${name2} check, bailing to window.${name2}: `, e2);
    }
  }
  if (!impl) {
    return impl;
  }
  return cachedImplementations$3[name2] = impl.bind(WINDOW$4);
}
__name(getNativeImplementation, "getNativeImplementation");
function clearCachedImplementation(name2) {
  cachedImplementations$3[name2] = void 0;
}
__name(clearCachedImplementation, "clearCachedImplementation");
function fetch$1(...rest) {
  return getNativeImplementation("fetch")(...rest);
}
__name(fetch$1, "fetch$1");
function setTimeout$3(...rest) {
  return getNativeImplementation("setTimeout")(...rest);
}
__name(setTimeout$3, "setTimeout$3");
const SENTRY_XHR_DATA_KEY = "__sentry_xhr_v3__";
function addXhrInstrumentationHandler(handler5) {
  const type = "xhr";
  addHandler$1(type, handler5);
  maybeInstrument(type, instrumentXHR);
}
__name(addXhrInstrumentationHandler, "addXhrInstrumentationHandler");
function instrumentXHR() {
  if (!WINDOW$4.XMLHttpRequest) {
    return;
  }
  const xhrproto = XMLHttpRequest.prototype;
  xhrproto.open = new Proxy(xhrproto.open, {
    apply(originalOpen, xhrOpenThisArg, xhrOpenArgArray) {
      const virtualError = new Error();
      const startTimestamp = timestampInSeconds() * 1e3;
      const method = isString$8(xhrOpenArgArray[0]) ? xhrOpenArgArray[0].toUpperCase() : void 0;
      const url = parseUrl(xhrOpenArgArray[1]);
      if (!method || !url) {
        return originalOpen.apply(xhrOpenThisArg, xhrOpenArgArray);
      }
      xhrOpenThisArg[SENTRY_XHR_DATA_KEY] = {
        method,
        url,
        request_headers: {}
      };
      if (method === "POST" && url.match(/sentry_key/)) {
        xhrOpenThisArg.__sentry_own_request__ = true;
      }
      const onreadystatechangeHandler = /* @__PURE__ */ __name(() => {
        const xhrInfo = xhrOpenThisArg[SENTRY_XHR_DATA_KEY];
        if (!xhrInfo) {
          return;
        }
        if (xhrOpenThisArg.readyState === 4) {
          try {
            xhrInfo.status_code = xhrOpenThisArg.status;
          } catch (e2) {
          }
          const handlerData = {
            endTimestamp: timestampInSeconds() * 1e3,
            startTimestamp,
            xhr: xhrOpenThisArg,
            virtualError
          };
          triggerHandlers$1("xhr", handlerData);
        }
      }, "onreadystatechangeHandler");
      if ("onreadystatechange" in xhrOpenThisArg && typeof xhrOpenThisArg.onreadystatechange === "function") {
        xhrOpenThisArg.onreadystatechange = new Proxy(xhrOpenThisArg.onreadystatechange, {
          apply(originalOnreadystatechange, onreadystatechangeThisArg, onreadystatechangeArgArray) {
            onreadystatechangeHandler();
            return originalOnreadystatechange.apply(onreadystatechangeThisArg, onreadystatechangeArgArray);
          }
        });
      } else {
        xhrOpenThisArg.addEventListener("readystatechange", onreadystatechangeHandler);
      }
      xhrOpenThisArg.setRequestHeader = new Proxy(xhrOpenThisArg.setRequestHeader, {
        apply(originalSetRequestHeader, setRequestHeaderThisArg, setRequestHeaderArgArray) {
          const [header, value] = setRequestHeaderArgArray;
          const xhrInfo = setRequestHeaderThisArg[SENTRY_XHR_DATA_KEY];
          if (xhrInfo && isString$8(header) && isString$8(value)) {
            xhrInfo.request_headers[header.toLowerCase()] = value;
          }
          return originalSetRequestHeader.apply(setRequestHeaderThisArg, setRequestHeaderArgArray);
        }
      });
      return originalOpen.apply(xhrOpenThisArg, xhrOpenArgArray);
    }
  });
  xhrproto.send = new Proxy(xhrproto.send, {
    apply(originalSend, sendThisArg, sendArgArray) {
      const sentryXhrData = sendThisArg[SENTRY_XHR_DATA_KEY];
      if (!sentryXhrData) {
        return originalSend.apply(sendThisArg, sendArgArray);
      }
      if (sendArgArray[0] !== void 0) {
        sentryXhrData.body = sendArgArray[0];
      }
      const handlerData = {
        startTimestamp: timestampInSeconds() * 1e3,
        xhr: sendThisArg
      };
      triggerHandlers$1("xhr", handlerData);
      return originalSend.apply(sendThisArg, sendArgArray);
    }
  });
}
__name(instrumentXHR, "instrumentXHR");
function parseUrl(url) {
  if (isString$8(url)) {
    return url;
  }
  try {
    return url.toString();
  } catch (e2) {
  }
  return void 0;
}
__name(parseUrl, "parseUrl");
const LAST_INTERACTIONS = [];
const INTERACTIONS_SPAN_MAP = /* @__PURE__ */ new Map();
function startTrackingINP() {
  const performance2 = getBrowserPerformanceAPI();
  if (performance2 && browserPerformanceTimeOrigin) {
    const inpCallback = _trackINP();
    return () => {
      inpCallback();
    };
  }
  return () => void 0;
}
__name(startTrackingINP, "startTrackingINP");
const INP_ENTRY_MAP = {
  click: "click",
  pointerdown: "click",
  pointerup: "click",
  mousedown: "click",
  mouseup: "click",
  touchstart: "click",
  touchend: "click",
  mouseover: "hover",
  mouseout: "hover",
  mouseenter: "hover",
  mouseleave: "hover",
  pointerover: "hover",
  pointerout: "hover",
  pointerenter: "hover",
  pointerleave: "hover",
  dragstart: "drag",
  dragend: "drag",
  drag: "drag",
  dragenter: "drag",
  dragleave: "drag",
  dragover: "drag",
  drop: "drag",
  keydown: "press",
  keyup: "press",
  keypress: "press",
  input: "press"
};
function _trackINP() {
  return addInpInstrumentationHandler(({ metric }) => {
    if (metric.value == void 0) {
      return;
    }
    const entry = metric.entries.find((entry2) => entry2.duration === metric.value && INP_ENTRY_MAP[entry2.name]);
    if (!entry) {
      return;
    }
    const { interactionId } = entry;
    const interactionType = INP_ENTRY_MAP[entry.name];
    const startTime = msToSec(browserPerformanceTimeOrigin + entry.startTime);
    const duration = msToSec(metric.value);
    const activeSpan = getActiveSpan();
    const rootSpan = activeSpan ? getRootSpan(activeSpan) : void 0;
    const cachedSpan = interactionId != null ? INTERACTIONS_SPAN_MAP.get(interactionId) : void 0;
    const spanToUse = cachedSpan || rootSpan;
    const routeName = spanToUse ? spanToJSON(spanToUse).description : getCurrentScope().getScopeData().transactionName;
    const name2 = htmlTreeAsString(entry.target);
    const attributes = dropUndefinedKeys({
      [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.http.browser.inp",
      [SEMANTIC_ATTRIBUTE_SENTRY_OP]: `ui.interaction.${interactionType}`,
      [SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME]: entry.duration
    });
    const span = startStandaloneWebVitalSpan({
      name: name2,
      transaction: routeName,
      attributes,
      startTime
    });
    if (span) {
      span.addEvent("inp", {
        [SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT]: "millisecond",
        [SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE]: metric.value
      });
      span.end(startTime + duration);
    }
  });
}
__name(_trackINP, "_trackINP");
function registerInpInteractionListener(_latestRoute) {
  const handleEntries = /* @__PURE__ */ __name(({ entries }) => {
    const activeSpan = getActiveSpan();
    const activeRootSpan = activeSpan && getRootSpan(activeSpan);
    entries.forEach((entry) => {
      if (!isPerformanceEventTiming(entry) || !activeRootSpan) {
        return;
      }
      const interactionId = entry.interactionId;
      if (interactionId == null) {
        return;
      }
      if (INTERACTIONS_SPAN_MAP.has(interactionId)) {
        return;
      }
      if (LAST_INTERACTIONS.length > 10) {
        const last = LAST_INTERACTIONS.shift();
        INTERACTIONS_SPAN_MAP.delete(last);
      }
      LAST_INTERACTIONS.push(interactionId);
      INTERACTIONS_SPAN_MAP.set(interactionId, activeRootSpan);
    });
  }, "handleEntries");
  addPerformanceInstrumentationHandler("event", handleEntries);
  addPerformanceInstrumentationHandler("first-input", handleEntries);
}
__name(registerInpInteractionListener, "registerInpInteractionListener");
function makeFetchTransport(options2, nativeFetch = getNativeImplementation("fetch")) {
  let pendingBodySize = 0;
  let pendingCount = 0;
  function makeRequest2(request) {
    const requestSize = request.body.length;
    pendingBodySize += requestSize;
    pendingCount++;
    const requestOptions = {
      body: request.body,
      method: "POST",
      referrerPolicy: "origin",
      headers: options2.headers,
      // Outgoing requests are usually cancelled when navigating to a different page, causing a "TypeError: Failed to
      // fetch" error and sending a "network_error" client-outcome - in Chrome, the request status shows "(cancelled)".
      // The `keepalive` flag keeps outgoing requests alive, even when switching pages. We want this since we're
      // frequently sending events right before the user is switching pages (eg. when finishing navigation transactions).
      // Gotchas:
      // - `keepalive` isn't supported by Firefox
      // - As per spec (https://fetch.spec.whatwg.org/#http-network-or-cache-fetch):
      //   If the sum of contentLength and inflightKeepaliveBytes is greater than 64 kibibytes, then return a network error.
      //   We will therefore only activate the flag when we're below that limit.
      // There is also a limit of requests that can be open at the same time, so we also limit this to 15
      // See https://github.com/getsentry/sentry-javascript/pull/7553 for details
      keepalive: pendingBodySize <= 6e4 && pendingCount < 15,
      ...options2.fetchOptions
    };
    if (!nativeFetch) {
      clearCachedImplementation("fetch");
      return rejectedSyncPromise("No fetch implementation available");
    }
    try {
      return nativeFetch(options2.url, requestOptions).then((response) => {
        pendingBodySize -= requestSize;
        pendingCount--;
        return {
          statusCode: response.status,
          headers: {
            "x-sentry-rate-limits": response.headers.get("X-Sentry-Rate-Limits"),
            "retry-after": response.headers.get("Retry-After")
          }
        };
      });
    } catch (e2) {
      clearCachedImplementation("fetch");
      pendingBodySize -= requestSize;
      pendingCount--;
      return rejectedSyncPromise(e2);
    }
  }
  __name(makeRequest2, "makeRequest");
  return createTransport(options2, makeRequest2);
}
__name(makeFetchTransport, "makeFetchTransport");
const OPERA10_PRIORITY = 10;
const OPERA11_PRIORITY = 20;
const CHROME_PRIORITY = 30;
const WINJS_PRIORITY = 40;
const GECKO_PRIORITY = 50;
function createFrame(filename, func, lineno, colno) {
  const frame = {
    filename,
    function: func === "<anonymous>" ? UNKNOWN_FUNCTION : func,
    in_app: true
    // All browser frames are considered in_app
  };
  if (lineno !== void 0) {
    frame.lineno = lineno;
  }
  if (colno !== void 0) {
    frame.colno = colno;
  }
  return frame;
}
__name(createFrame, "createFrame");
const chromeRegexNoFnName = /^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i;
const chromeRegex = /^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i;
const chromeEvalRegex = /\((\S*)(?::(\d+))(?::(\d+))\)/;
const chromeStackParserFn = /* @__PURE__ */ __name((line) => {
  const noFnParts = chromeRegexNoFnName.exec(line);
  if (noFnParts) {
    const [, filename, line2, col] = noFnParts;
    return createFrame(filename, UNKNOWN_FUNCTION, +line2, +col);
  }
  const parts2 = chromeRegex.exec(line);
  if (parts2) {
    const isEval = parts2[2] && parts2[2].indexOf("eval") === 0;
    if (isEval) {
      const subMatch = chromeEvalRegex.exec(parts2[2]);
      if (subMatch) {
        parts2[2] = subMatch[1];
        parts2[3] = subMatch[2];
        parts2[4] = subMatch[3];
      }
    }
    const [func, filename] = extractSafariExtensionDetails(parts2[1] || UNKNOWN_FUNCTION, parts2[2]);
    return createFrame(filename, func, parts2[3] ? +parts2[3] : void 0, parts2[4] ? +parts2[4] : void 0);
  }
  return;
}, "chromeStackParserFn");
const chromeStackLineParser = [CHROME_PRIORITY, chromeStackParserFn];
const geckoREgex = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i;
const geckoEvalRegex = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i;
const gecko$1 = /* @__PURE__ */ __name((line) => {
  const parts2 = geckoREgex.exec(line);
  if (parts2) {
    const isEval = parts2[3] && parts2[3].indexOf(" > eval") > -1;
    if (isEval) {
      const subMatch = geckoEvalRegex.exec(parts2[3]);
      if (subMatch) {
        parts2[1] = parts2[1] || "eval";
        parts2[3] = subMatch[1];
        parts2[4] = subMatch[2];
        parts2[5] = "";
      }
    }
    let filename = parts2[3];
    let func = parts2[1] || UNKNOWN_FUNCTION;
    [func, filename] = extractSafariExtensionDetails(func, filename);
    return createFrame(filename, func, parts2[4] ? +parts2[4] : void 0, parts2[5] ? +parts2[5] : void 0);
  }
  return;
}, "gecko$1");
const geckoStackLineParser = [GECKO_PRIORITY, gecko$1];
const winjsRegex = /^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i;
const winjs = /* @__PURE__ */ __name((line) => {
  const parts2 = winjsRegex.exec(line);
  return parts2 ? createFrame(parts2[2], parts2[1] || UNKNOWN_FUNCTION, +parts2[3], parts2[4] ? +parts2[4] : void 0) : void 0;
}, "winjs");
const winjsStackLineParser = [WINJS_PRIORITY, winjs];
const opera10Regex = / line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i;
const opera10 = /* @__PURE__ */ __name((line) => {
  const parts2 = opera10Regex.exec(line);
  return parts2 ? createFrame(parts2[2], parts2[3] || UNKNOWN_FUNCTION, +parts2[1]) : void 0;
}, "opera10");
const opera10StackLineParser = [OPERA10_PRIORITY, opera10];
const opera11Regex = / line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i;
const opera11 = /* @__PURE__ */ __name((line) => {
  const parts2 = opera11Regex.exec(line);
  return parts2 ? createFrame(parts2[5], parts2[3] || parts2[4] || UNKNOWN_FUNCTION, +parts2[1], +parts2[2]) : void 0;
}, "opera11");
const opera11StackLineParser = [OPERA11_PRIORITY, opera11];
const defaultStackLineParsers = [chromeStackLineParser, geckoStackLineParser];
const defaultStackParser = createStackParser(...defaultStackLineParsers);
const extractSafariExtensionDetails = /* @__PURE__ */ __name((func, filename) => {
  const isSafariExtension = func.indexOf("safari-extension") !== -1;
  const isSafariWebExtension = func.indexOf("safari-web-extension") !== -1;
  return isSafariExtension || isSafariWebExtension ? [
    func.indexOf("@") !== -1 ? func.split("@")[0] : UNKNOWN_FUNCTION,
    isSafariExtension ? `safari-extension:${filename}` : `safari-web-extension:${filename}`
  ] : [func, filename];
}, "extractSafariExtensionDetails");
const MAX_ALLOWED_STRING_LENGTH = 1024;
const INTEGRATION_NAME$a = "Breadcrumbs";
const _breadcrumbsIntegration = /* @__PURE__ */ __name((options2 = {}) => {
  const _options = {
    console: true,
    dom: true,
    fetch: true,
    history: true,
    sentry: true,
    xhr: true,
    ...options2
  };
  return {
    name: INTEGRATION_NAME$a,
    setup(client) {
      if (_options.console) {
        addConsoleInstrumentationHandler(_getConsoleBreadcrumbHandler(client));
      }
      if (_options.dom) {
        addClickKeypressInstrumentationHandler(_getDomBreadcrumbHandler(client, _options.dom));
      }
      if (_options.xhr) {
        addXhrInstrumentationHandler(_getXhrBreadcrumbHandler(client));
      }
      if (_options.fetch) {
        addFetchInstrumentationHandler(_getFetchBreadcrumbHandler(client));
      }
      if (_options.history) {
        addHistoryInstrumentationHandler(_getHistoryBreadcrumbHandler(client));
      }
      if (_options.sentry) {
        client.on("beforeSendEvent", _getSentryBreadcrumbHandler(client));
      }
    }
  };
}, "_breadcrumbsIntegration");
const breadcrumbsIntegration = defineIntegration(_breadcrumbsIntegration);
function _getSentryBreadcrumbHandler(client) {
  return /* @__PURE__ */ __name(function addSentryBreadcrumb(event) {
    if (getClient() !== client) {
      return;
    }
    addBreadcrumb(
      {
        category: `sentry.${event.type === "transaction" ? "transaction" : "event"}`,
        event_id: event.event_id,
        level: event.level,
        message: getEventDescription(event)
      },
      {
        event
      }
    );
  }, "addSentryBreadcrumb");
}
__name(_getSentryBreadcrumbHandler, "_getSentryBreadcrumbHandler");
function _getDomBreadcrumbHandler(client, dom) {
  return /* @__PURE__ */ __name(function _innerDomBreadcrumb(handlerData) {
    if (getClient() !== client) {
      return;
    }
    let target;
    let componentName;
    let keyAttrs = typeof dom === "object" ? dom.serializeAttribute : void 0;
    let maxStringLength = typeof dom === "object" && typeof dom.maxStringLength === "number" ? dom.maxStringLength : void 0;
    if (maxStringLength && maxStringLength > MAX_ALLOWED_STRING_LENGTH) {
      DEBUG_BUILD$4 && logger$5.warn(
        `\`dom.maxStringLength\` cannot exceed ${MAX_ALLOWED_STRING_LENGTH}, but a value of ${maxStringLength} was configured. Sentry will use ${MAX_ALLOWED_STRING_LENGTH} instead.`
      );
      maxStringLength = MAX_ALLOWED_STRING_LENGTH;
    }
    if (typeof keyAttrs === "string") {
      keyAttrs = [keyAttrs];
    }
    try {
      const event = handlerData.event;
      const element = _isEvent(event) ? event.target : event;
      target = htmlTreeAsString(element, { keyAttrs, maxStringLength });
      componentName = getComponentName(element);
    } catch (e2) {
      target = "<unknown>";
    }
    if (target.length === 0) {
      return;
    }
    const breadcrumb = {
      category: `ui.${handlerData.name}`,
      message: target
    };
    if (componentName) {
      breadcrumb.data = { "ui.component_name": componentName };
    }
    addBreadcrumb(breadcrumb, {
      event: handlerData.event,
      name: handlerData.name,
      global: handlerData.global
    });
  }, "_innerDomBreadcrumb");
}
__name(_getDomBreadcrumbHandler, "_getDomBreadcrumbHandler");
function _getConsoleBreadcrumbHandler(client) {
  return /* @__PURE__ */ __name(function _consoleBreadcrumb(handlerData) {
    if (getClient() !== client) {
      return;
    }
    const breadcrumb = {
      category: "console",
      data: {
        arguments: handlerData.args,
        logger: "console"
      },
      level: severityLevelFromString(handlerData.level),
      message: safeJoin(handlerData.args, " ")
    };
    if (handlerData.level === "assert") {
      if (handlerData.args[0] === false) {
        breadcrumb.message = `Assertion failed: ${safeJoin(handlerData.args.slice(1), " ") || "console.assert"}`;
        breadcrumb.data.arguments = handlerData.args.slice(1);
      } else {
        return;
      }
    }
    addBreadcrumb(breadcrumb, {
      input: handlerData.args,
      level: handlerData.level
    });
  }, "_consoleBreadcrumb");
}
__name(_getConsoleBreadcrumbHandler, "_getConsoleBreadcrumbHandler");
function _getXhrBreadcrumbHandler(client) {
  return /* @__PURE__ */ __name(function _xhrBreadcrumb(handlerData) {
    if (getClient() !== client) {
      return;
    }
    const { startTimestamp, endTimestamp } = handlerData;
    const sentryXhrData = handlerData.xhr[SENTRY_XHR_DATA_KEY];
    if (!startTimestamp || !endTimestamp || !sentryXhrData) {
      return;
    }
    const { method, url, status_code, body } = sentryXhrData;
    const data = {
      method,
      url,
      status_code
    };
    const hint = {
      xhr: handlerData.xhr,
      input: body,
      startTimestamp,
      endTimestamp
    };
    const level = getBreadcrumbLogLevelFromHttpStatusCode(status_code);
    addBreadcrumb(
      {
        category: "xhr",
        data,
        type: "http",
        level
      },
      hint
    );
  }, "_xhrBreadcrumb");
}
__name(_getXhrBreadcrumbHandler, "_getXhrBreadcrumbHandler");
function _getFetchBreadcrumbHandler(client) {
  return /* @__PURE__ */ __name(function _fetchBreadcrumb(handlerData) {
    if (getClient() !== client) {
      return;
    }
    const { startTimestamp, endTimestamp } = handlerData;
    if (!endTimestamp) {
      return;
    }
    if (handlerData.fetchData.url.match(/sentry_key/) && handlerData.fetchData.method === "POST") {
      return;
    }
    if (handlerData.error) {
      const data = handlerData.fetchData;
      const hint = {
        data: handlerData.error,
        input: handlerData.args,
        startTimestamp,
        endTimestamp
      };
      addBreadcrumb(
        {
          category: "fetch",
          data,
          level: "error",
          type: "http"
        },
        hint
      );
    } else {
      const response = handlerData.response;
      const data = {
        ...handlerData.fetchData,
        status_code: response && response.status
      };
      const hint = {
        input: handlerData.args,
        response,
        startTimestamp,
        endTimestamp
      };
      const level = getBreadcrumbLogLevelFromHttpStatusCode(data.status_code);
      addBreadcrumb(
        {
          category: "fetch",
          data,
          type: "http",
          level
        },
        hint
      );
    }
  }, "_fetchBreadcrumb");
}
__name(_getFetchBreadcrumbHandler, "_getFetchBreadcrumbHandler");
function _getHistoryBreadcrumbHandler(client) {
  return /* @__PURE__ */ __name(function _historyBreadcrumb(handlerData) {
    if (getClient() !== client) {
      return;
    }
    let from2 = handlerData.from;
    let to = handlerData.to;
    const parsedLoc = parseUrl$1(WINDOW$5.location.href);
    let parsedFrom = from2 ? parseUrl$1(from2) : void 0;
    const parsedTo = parseUrl$1(to);
    if (!parsedFrom || !parsedFrom.path) {
      parsedFrom = parsedLoc;
    }
    if (parsedLoc.protocol === parsedTo.protocol && parsedLoc.host === parsedTo.host) {
      to = parsedTo.relative;
    }
    if (parsedLoc.protocol === parsedFrom.protocol && parsedLoc.host === parsedFrom.host) {
      from2 = parsedFrom.relative;
    }
    addBreadcrumb({
      category: "navigation",
      data: {
        from: from2,
        to
      }
    });
  }, "_historyBreadcrumb");
}
__name(_getHistoryBreadcrumbHandler, "_getHistoryBreadcrumbHandler");
function _isEvent(event) {
  return !!event && !!event.target;
}
__name(_isEvent, "_isEvent");
const DEFAULT_EVENT_TARGET = [
  "EventTarget",
  "Window",
  "Node",
  "ApplicationCache",
  "AudioTrackList",
  "BroadcastChannel",
  "ChannelMergerNode",
  "CryptoOperation",
  "EventSource",
  "FileReader",
  "HTMLUnknownElement",
  "IDBDatabase",
  "IDBRequest",
  "IDBTransaction",
  "KeyOperation",
  "MediaController",
  "MessagePort",
  "ModalWindow",
  "Notification",
  "SVGElementInstance",
  "Screen",
  "SharedWorker",
  "TextTrack",
  "TextTrackCue",
  "TextTrackList",
  "WebSocket",
  "WebSocketWorker",
  "Worker",
  "XMLHttpRequest",
  "XMLHttpRequestEventTarget",
  "XMLHttpRequestUpload"
];
const INTEGRATION_NAME$9 = "BrowserApiErrors";
const _browserApiErrorsIntegration = /* @__PURE__ */ __name((options2 = {}) => {
  const _options = {
    XMLHttpRequest: true,
    eventTarget: true,
    requestAnimationFrame: true,
    setInterval: true,
    setTimeout: true,
    ...options2
  };
  return {
    name: INTEGRATION_NAME$9,
    // TODO: This currently only works for the first client this is setup
    // We may want to adjust this to check for client etc.
    setupOnce() {
      if (_options.setTimeout) {
        fill(WINDOW$5, "setTimeout", _wrapTimeFunction);
      }
      if (_options.setInterval) {
        fill(WINDOW$5, "setInterval", _wrapTimeFunction);
      }
      if (_options.requestAnimationFrame) {
        fill(WINDOW$5, "requestAnimationFrame", _wrapRAF);
      }
      if (_options.XMLHttpRequest && "XMLHttpRequest" in WINDOW$5) {
        fill(XMLHttpRequest.prototype, "send", _wrapXHR$1);
      }
      const eventTargetOption = _options.eventTarget;
      if (eventTargetOption) {
        const eventTarget = Array.isArray(eventTargetOption) ? eventTargetOption : DEFAULT_EVENT_TARGET;
        eventTarget.forEach(_wrapEventTarget);
      }
    }
  };
}, "_browserApiErrorsIntegration");
const browserApiErrorsIntegration = defineIntegration(_browserApiErrorsIntegration);
function _wrapTimeFunction(original) {
  return function(...args) {
    const originalCallback = args[0];
    args[0] = wrap$2(originalCallback, {
      mechanism: {
        data: { function: getFunctionName(original) },
        handled: false,
        type: "instrument"
      }
    });
    return original.apply(this, args);
  };
}
__name(_wrapTimeFunction, "_wrapTimeFunction");
function _wrapRAF(original) {
  return function(callback) {
    return original.apply(this, [
      wrap$2(callback, {
        mechanism: {
          data: {
            function: "requestAnimationFrame",
            handler: getFunctionName(original)
          },
          handled: false,
          type: "instrument"
        }
      })
    ]);
  };
}
__name(_wrapRAF, "_wrapRAF");
function _wrapXHR$1(originalSend) {
  return function(...args) {
    const xhr = this;
    const xmlHttpRequestProps = ["onload", "onerror", "onprogress", "onreadystatechange"];
    xmlHttpRequestProps.forEach((prop2) => {
      if (prop2 in xhr && typeof xhr[prop2] === "function") {
        fill(xhr, prop2, function(original) {
          const wrapOptions = {
            mechanism: {
              data: {
                function: prop2,
                handler: getFunctionName(original)
              },
              handled: false,
              type: "instrument"
            }
          };
          const originalFunction = getOriginalFunction(original);
          if (originalFunction) {
            wrapOptions.mechanism.data.handler = getFunctionName(originalFunction);
          }
          return wrap$2(original, wrapOptions);
        });
      }
    });
    return originalSend.apply(this, args);
  };
}
__name(_wrapXHR$1, "_wrapXHR$1");
function _wrapEventTarget(target) {
  const globalObject = WINDOW$5;
  const targetObj = globalObject[target];
  const proto = targetObj && targetObj.prototype;
  if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty("addEventListener")) {
    return;
  }
  fill(proto, "addEventListener", function(original) {
    return function(eventName, fn, options2) {
      try {
        if (isEventListenerObject(fn)) {
          fn.handleEvent = wrap$2(fn.handleEvent, {
            mechanism: {
              data: {
                function: "handleEvent",
                handler: getFunctionName(fn),
                target
              },
              handled: false,
              type: "instrument"
            }
          });
        }
      } catch (e2) {
      }
      return original.apply(this, [
        eventName,
        wrap$2(fn, {
          mechanism: {
            data: {
              function: "addEventListener",
              handler: getFunctionName(fn),
              target
            },
            handled: false,
            type: "instrument"
          }
        }),
        options2
      ]);
    };
  });
  fill(proto, "removeEventListener", function(originalRemoveEventListener) {
    return function(eventName, fn, options2) {
      try {
        const originalEventHandler = fn.__sentry_wrapped__;
        if (originalEventHandler) {
          originalRemoveEventListener.call(this, eventName, originalEventHandler, options2);
        }
      } catch (e2) {
      }
      return originalRemoveEventListener.call(this, eventName, fn, options2);
    };
  });
}
__name(_wrapEventTarget, "_wrapEventTarget");
function isEventListenerObject(obj) {
  return typeof obj.handleEvent === "function";
}
__name(isEventListenerObject, "isEventListenerObject");
const browserSessionIntegration = defineIntegration(() => {
  return {
    name: "BrowserSession",
    setupOnce() {
      if (typeof WINDOW$5.document === "undefined") {
        DEBUG_BUILD$4 && logger$5.warn("Using the `browserSessionIntegration` in non-browser environments is not supported.");
        return;
      }
      startSession({ ignoreDuration: true });
      captureSession();
      addHistoryInstrumentationHandler(({ from: from2, to }) => {
        if (from2 !== void 0 && from2 !== to) {
          startSession({ ignoreDuration: true });
          captureSession();
        }
      });
    }
  };
});
const INTEGRATION_NAME$8 = "GlobalHandlers";
const _globalHandlersIntegration = /* @__PURE__ */ __name((options2 = {}) => {
  const _options = {
    onerror: true,
    onunhandledrejection: true,
    ...options2
  };
  return {
    name: INTEGRATION_NAME$8,
    setupOnce() {
      Error.stackTraceLimit = 50;
    },
    setup(client) {
      if (_options.onerror) {
        _installGlobalOnErrorHandler(client);
        globalHandlerLog("onerror");
      }
      if (_options.onunhandledrejection) {
        _installGlobalOnUnhandledRejectionHandler(client);
        globalHandlerLog("onunhandledrejection");
      }
    }
  };
}, "_globalHandlersIntegration");
const globalHandlersIntegration = defineIntegration(_globalHandlersIntegration);
function _installGlobalOnErrorHandler(client) {
  addGlobalErrorInstrumentationHandler((data) => {
    const { stackParser, attachStacktrace } = getOptions();
    if (getClient() !== client || shouldIgnoreOnError()) {
      return;
    }
    const { msg, url, line, column, error: error2 } = data;
    const event = _enhanceEventWithInitialFrame(
      eventFromUnknownInput(stackParser, error2 || msg, void 0, attachStacktrace, false),
      url,
      line,
      column
    );
    event.level = "error";
    captureEvent(event, {
      originalException: error2,
      mechanism: {
        handled: false,
        type: "onerror"
      }
    });
  });
}
__name(_installGlobalOnErrorHandler, "_installGlobalOnErrorHandler");
function _installGlobalOnUnhandledRejectionHandler(client) {
  addGlobalUnhandledRejectionInstrumentationHandler((e2) => {
    const { stackParser, attachStacktrace } = getOptions();
    if (getClient() !== client || shouldIgnoreOnError()) {
      return;
    }
    const error2 = _getUnhandledRejectionError(e2);
    const event = isPrimitive(error2) ? _eventFromRejectionWithPrimitive(error2) : eventFromUnknownInput(stackParser, error2, void 0, attachStacktrace, true);
    event.level = "error";
    captureEvent(event, {
      originalException: error2,
      mechanism: {
        handled: false,
        type: "onunhandledrejection"
      }
    });
  });
}
__name(_installGlobalOnUnhandledRejectionHandler, "_installGlobalOnUnhandledRejectionHandler");
function _getUnhandledRejectionError(error2) {
  if (isPrimitive(error2)) {
    return error2;
  }
  try {
    if ("reason" in error2) {
      return error2.reason;
    }
    if ("detail" in error2 && "reason" in error2.detail) {
      return error2.detail.reason;
    }
  } catch (e2) {
  }
  return error2;
}
__name(_getUnhandledRejectionError, "_getUnhandledRejectionError");
function _eventFromRejectionWithPrimitive(reason) {
  return {
    exception: {
      values: [
        {
          type: "UnhandledRejection",
          // String() is needed because the Primitive type includes symbols (which can't be automatically stringified)
          value: `Non-Error promise rejection captured with value: ${String(reason)}`
        }
      ]
    }
  };
}
__name(_eventFromRejectionWithPrimitive, "_eventFromRejectionWithPrimitive");
function _enhanceEventWithInitialFrame(event, url, line, column) {
  const e2 = event.exception = event.exception || {};
  const ev = e2.values = e2.values || [];
  const ev0 = ev[0] = ev[0] || {};
  const ev0s = ev0.stacktrace = ev0.stacktrace || {};
  const ev0sf = ev0s.frames = ev0s.frames || [];
  const colno = column;
  const lineno = line;
  const filename = isString$8(url) && url.length > 0 ? url : getLocationHref();
  if (ev0sf.length === 0) {
    ev0sf.push({
      colno,
      filename,
      function: UNKNOWN_FUNCTION,
      in_app: true,
      lineno
    });
  }
  return event;
}
__name(_enhanceEventWithInitialFrame, "_enhanceEventWithInitialFrame");
function globalHandlerLog(type) {
  DEBUG_BUILD$4 && logger$5.log(`Global Handler attached: ${type}`);
}
__name(globalHandlerLog, "globalHandlerLog");
function getOptions() {
  const client = getClient();
  const options2 = client && client.getOptions() || {
    stackParser: /* @__PURE__ */ __name(() => [], "stackParser"),
    attachStacktrace: false
  };
  return options2;
}
__name(getOptions, "getOptions");
const httpContextIntegration = defineIntegration(() => {
  return {
    name: "HttpContext",
    preprocessEvent(event) {
      if (!WINDOW$5.navigator && !WINDOW$5.location && !WINDOW$5.document) {
        return;
      }
      const url = event.request && event.request.url || WINDOW$5.location && WINDOW$5.location.href;
      const { referrer } = WINDOW$5.document || {};
      const { userAgent } = WINDOW$5.navigator || {};
      const headers = {
        ...event.request && event.request.headers,
        ...referrer && { Referer: referrer },
        ...userAgent && { "User-Agent": userAgent }
      };
      const request = { ...event.request, ...url && { url }, headers };
      event.request = request;
    }
  };
});
const DEFAULT_KEY = "cause";
const DEFAULT_LIMIT = 5;
const INTEGRATION_NAME$7 = "LinkedErrors";
const _linkedErrorsIntegration = /* @__PURE__ */ __name((options2 = {}) => {
  const limit2 = options2.limit || DEFAULT_LIMIT;
  const key = options2.key || DEFAULT_KEY;
  return {
    name: INTEGRATION_NAME$7,
    preprocessEvent(event, hint, client) {
      const options3 = client.getOptions();
      applyAggregateErrorsToEvent(
        // This differs from the LinkedErrors integration in core by using a different exceptionFromError function
        exceptionFromError,
        options3.stackParser,
        options3.maxValueLength,
        key,
        limit2,
        event,
        hint
      );
    }
  };
}, "_linkedErrorsIntegration");
const linkedErrorsIntegration = defineIntegration(_linkedErrorsIntegration);
function getDefaultIntegrations(options2) {
  const integrations = [
    inboundFiltersIntegration(),
    functionToStringIntegration(),
    browserApiErrorsIntegration(),
    breadcrumbsIntegration(),
    globalHandlersIntegration(),
    linkedErrorsIntegration(),
    dedupeIntegration(),
    httpContextIntegration()
  ];
  if (options2.autoSessionTracking !== false) {
    integrations.push(browserSessionIntegration());
  }
  return integrations;
}
__name(getDefaultIntegrations, "getDefaultIntegrations");
function applyDefaultOptions(optionsArg = {}) {
  const defaultOptions2 = {
    defaultIntegrations: getDefaultIntegrations(optionsArg),
    release: typeof __SENTRY_RELEASE__ === "string" ? __SENTRY_RELEASE__ : WINDOW$5.SENTRY_RELEASE && WINDOW$5.SENTRY_RELEASE.id ? WINDOW$5.SENTRY_RELEASE.id : void 0,
    autoSessionTracking: true,
    sendClientReports: true
  };
  if (optionsArg.defaultIntegrations == null) {
    delete optionsArg.defaultIntegrations;
  }
  return { ...defaultOptions2, ...optionsArg };
}
__name(applyDefaultOptions, "applyDefaultOptions");
function shouldShowBrowserExtensionError() {
  const windowWithMaybeExtension = typeof WINDOW$5.window !== "undefined" && WINDOW$5;
  if (!windowWithMaybeExtension) {
    return false;
  }
  const extensionKey = windowWithMaybeExtension.chrome ? "chrome" : "browser";
  const extensionObject = windowWithMaybeExtension[extensionKey];
  const runtimeId = extensionObject && extensionObject.runtime && extensionObject.runtime.id;
  const href = WINDOW$5.location && WINDOW$5.location.href || "";
  const extensionProtocols = ["chrome-extension:", "moz-extension:", "ms-browser-extension:", "safari-web-extension:"];
  const isDedicatedExtensionPage = !!runtimeId && WINDOW$5 === WINDOW$5.top && extensionProtocols.some((protocol) => href.startsWith(`${protocol}//`));
  const isNWjs = typeof windowWithMaybeExtension.nw !== "undefined";
  return !!runtimeId && !isDedicatedExtensionPage && !isNWjs;
}
__name(shouldShowBrowserExtensionError, "shouldShowBrowserExtensionError");
function init$4(browserOptions = {}) {
  const options2 = applyDefaultOptions(browserOptions);
  if (!options2.skipBrowserExtensionCheck && shouldShowBrowserExtensionError()) {
    consoleSandbox(() => {
      console.error(
        "[Sentry] You cannot run Sentry this way in a browser extension, check: https://docs.sentry.io/platforms/javascript/best-practices/browser-extensions/"
      );
    });
    return;
  }
  if (DEBUG_BUILD$4) {
    if (!supportsFetch()) {
      logger$5.warn(
        "No Fetch API detected. The Sentry SDK requires a Fetch API compatible environment to send events. Please add a Fetch API polyfill."
      );
    }
  }
  const clientOptions = {
    ...options2,
    stackParser: stackParserFromStackParserOptions(options2.stackParser || defaultStackParser),
    integrations: getIntegrationsToSetup(options2),
    transport: options2.transport || makeFetchTransport
  };
  return initAndBind(BrowserClient, clientOptions);
}
__name(init$4, "init$4");
function showReportDialog(options2 = {}) {
  if (!WINDOW$5.document) {
    DEBUG_BUILD$4 && logger$5.error("Global document not defined in showReportDialog call");
    return;
  }
  const scope = getCurrentScope();
  const client = scope.getClient();
  const dsn = client && client.getDsn();
  if (!dsn) {
    DEBUG_BUILD$4 && logger$5.error("DSN not configured for showReportDialog call");
    return;
  }
  if (scope) {
    options2.user = {
      ...scope.getUser(),
      ...options2.user
    };
  }
  if (!options2.eventId) {
    const eventId = lastEventId();
    if (eventId) {
      options2.eventId = eventId;
    }
  }
  const script2 = WINDOW$5.document.createElement("script");
  script2.async = true;
  script2.crossOrigin = "anonymous";
  script2.src = getReportDialogEndpoint(dsn, options2);
  if (options2.onLoad) {
    script2.onload = options2.onLoad;
  }
  const { onClose } = options2;
  if (onClose) {
    const reportDialogClosedMessageHandler = /* @__PURE__ */ __name((event) => {
      if (event.data === "__sentry_reportdialog_closed__") {
        try {
          onClose();
        } finally {
          WINDOW$5.removeEventListener("message", reportDialogClosedMessageHandler);
        }
      }
    }, "reportDialogClosedMessageHandler");
    WINDOW$5.addEventListener("message", reportDialogClosedMessageHandler);
  }
  const injectionPoint = WINDOW$5.document.head || WINDOW$5.document.body;
  if (injectionPoint) {
    injectionPoint.appendChild(script2);
  } else {
    DEBUG_BUILD$4 && logger$5.error("Not injecting report dialog. No injection point found in HTML");
  }
}
__name(showReportDialog, "showReportDialog");
function forceLoad() {
}
__name(forceLoad, "forceLoad");
function onLoad(callback) {
  callback();
}
__name(onLoad, "onLoad");
function captureUserFeedback(feedback) {
  const client = getClient();
  if (client) {
    client.captureUserFeedback(feedback);
  }
}
__name(captureUserFeedback, "captureUserFeedback");
const LazyLoadableIntegrations = {
  replayIntegration: "replay",
  replayCanvasIntegration: "replay-canvas",
  feedbackIntegration: "feedback",
  feedbackModalIntegration: "feedback-modal",
  feedbackScreenshotIntegration: "feedback-screenshot",
  captureConsoleIntegration: "captureconsole",
  contextLinesIntegration: "contextlines",
  linkedErrorsIntegration: "linkederrors",
  debugIntegration: "debug",
  dedupeIntegration: "dedupe",
  extraErrorDataIntegration: "extraerrordata",
  httpClientIntegration: "httpclient",
  reportingObserverIntegration: "reportingobserver",
  rewriteFramesIntegration: "rewriteframes",
  sessionTimingIntegration: "sessiontiming",
  browserProfilingIntegration: "browserprofiling",
  moduleMetadataIntegration: "modulemetadata"
};
const WindowWithMaybeIntegration = WINDOW$5;
async function lazyLoadIntegration(name2, scriptNonce) {
  const bundle = LazyLoadableIntegrations[name2];
  const sentryOnWindow = WindowWithMaybeIntegration.Sentry = WindowWithMaybeIntegration.Sentry || {};
  if (!bundle) {
    throw new Error(`Cannot lazy load integration: ${name2}`);
  }
  const existing = sentryOnWindow[name2];
  if (typeof existing === "function" && !("_isShim" in existing)) {
    return existing;
  }
  const url = getScriptURL(bundle);
  const script2 = WINDOW$5.document.createElement("script");
  script2.src = url;
  script2.crossOrigin = "anonymous";
  script2.referrerPolicy = "origin";
  if (scriptNonce) {
    script2.setAttribute("nonce", scriptNonce);
  }
  const waitForLoad = new Promise((resolve2, reject) => {
    script2.addEventListener("load", () => resolve2());
    script2.addEventListener("error", reject);
  });
  const currentScript = WINDOW$5.document.currentScript;
  const parent2 = WINDOW$5.document.body || WINDOW$5.document.head || currentScript && currentScript.parentElement;
  if (parent2) {
    parent2.appendChild(script2);
  } else {
    throw new Error(`Could not find parent element to insert lazy-loaded ${name2} script`);
  }
  try {
    await waitForLoad;
  } catch (e2) {
    throw new Error(`Error when loading integration: ${name2}`);
  }
  const integrationFn = sentryOnWindow[name2];
  if (typeof integrationFn !== "function") {
    throw new Error(`Could not load integration: ${name2}`);
  }
  return integrationFn;
}
__name(lazyLoadIntegration, "lazyLoadIntegration");
function getScriptURL(bundle) {
  const client = getClient();
  const options2 = client && client.getOptions();
  const baseURL = options2 && options2.cdnBaseUrl || "https://browser.sentry-cdn.com";
  return new URL(`/${SDK_VERSION$2}/${bundle}.min.js`, baseURL).toString();
}
__name(getScriptURL, "getScriptURL");
const WINDOW$3 = GLOBAL_OBJ;
const INTEGRATION_NAME$6 = "ReportingObserver";
const SETUP_CLIENTS = /* @__PURE__ */ new WeakMap();
const _reportingObserverIntegration = /* @__PURE__ */ __name((options2 = {}) => {
  const types = options2.types || ["crash", "deprecation", "intervention"];
  function handler5(reports) {
    if (!SETUP_CLIENTS.has(getClient())) {
      return;
    }
    for (const report of reports) {
      withScope((scope) => {
        scope.setExtra("url", report.url);
        const label = `ReportingObserver [${report.type}]`;
        let details = "No details available";
        if (report.body) {
          const plainBody = {};
          for (const prop2 in report.body) {
            plainBody[prop2] = report.body[prop2];
          }
          scope.setExtra("body", plainBody);
          if (report.type === "crash") {
            const body = report.body;
            details = [body.crashId || "", body.reason || ""].join(" ").trim() || details;
          } else {
            const body = report.body;
            details = body.message || details;
          }
        }
        captureMessage(`${label}: ${details}`);
      });
    }
  }
  __name(handler5, "handler");
  return {
    name: INTEGRATION_NAME$6,
    setupOnce() {
      if (!supportsReportingObserver()) {
        return;
      }
      const observer = new WINDOW$3.ReportingObserver(
        handler5,
        {
          buffered: true,
          types
        }
      );
      observer.observe();
    },
    setup(client) {
      SETUP_CLIENTS.set(client, true);
    }
  };
}, "_reportingObserverIntegration");
const reportingObserverIntegration = defineIntegration(_reportingObserverIntegration);
const INTEGRATION_NAME$5 = "HttpClient";
const _httpClientIntegration = /* @__PURE__ */ __name((options2 = {}) => {
  const _options = {
    failedRequestStatusCodes: [[500, 599]],
    failedRequestTargets: [/.*/],
    ...options2
  };
  return {
    name: INTEGRATION_NAME$5,
    setup(client) {
      _wrapFetch(client, _options);
      _wrapXHR(client, _options);
    }
  };
}, "_httpClientIntegration");
const httpClientIntegration = defineIntegration(_httpClientIntegration);
function _fetchResponseHandler(options2, requestInfo, response, requestInit, error2) {
  if (_shouldCaptureResponse(options2, response.status, response.url)) {
    const request = _getRequest(requestInfo, requestInit);
    let requestHeaders, responseHeaders, requestCookies, responseCookies;
    if (_shouldSendDefaultPii()) {
      [requestHeaders, requestCookies] = _parseCookieHeaders("Cookie", request);
      [responseHeaders, responseCookies] = _parseCookieHeaders("Set-Cookie", response);
    }
    const event = _createEvent({
      url: request.url,
      method: request.method,
      status: response.status,
      requestHeaders,
      responseHeaders,
      requestCookies,
      responseCookies,
      error: error2
    });
    captureEvent(event);
  }
}
__name(_fetchResponseHandler, "_fetchResponseHandler");
function _parseCookieHeaders(cookieHeader, obj) {
  const headers = _extractFetchHeaders(obj.headers);
  let cookies2;
  try {
    const cookieString = headers[cookieHeader] || headers[cookieHeader.toLowerCase()] || void 0;
    if (cookieString) {
      cookies2 = _parseCookieString(cookieString);
    }
  } catch (e2) {
  }
  return [headers, cookies2];
}
__name(_parseCookieHeaders, "_parseCookieHeaders");
function _xhrResponseHandler(options2, xhr, method, headers, error2) {
  if (_shouldCaptureResponse(options2, xhr.status, xhr.responseURL)) {
    let requestHeaders, responseCookies, responseHeaders;
    if (_shouldSendDefaultPii()) {
      try {
        const cookieString = xhr.getResponseHeader("Set-Cookie") || xhr.getResponseHeader("set-cookie") || void 0;
        if (cookieString) {
          responseCookies = _parseCookieString(cookieString);
        }
      } catch (e3) {
      }
      try {
        responseHeaders = _getXHRResponseHeaders(xhr);
      } catch (e4) {
      }
      requestHeaders = headers;
    }
    const event = _createEvent({
      url: xhr.responseURL,
      method,
      status: xhr.status,
      requestHeaders,
      // Can't access request cookies from XHR
      responseHeaders,
      responseCookies,
      error: error2
    });
    captureEvent(event);
  }
}
__name(_xhrResponseHandler, "_xhrResponseHandler");
function _getResponseSizeFromHeaders(headers) {
  if (headers) {
    const contentLength = headers["Content-Length"] || headers["content-length"];
    if (contentLength) {
      return parseInt(contentLength, 10);
    }
  }
  return void 0;
}
__name(_getResponseSizeFromHeaders, "_getResponseSizeFromHeaders");
function _parseCookieString(cookieString) {
  return cookieString.split("; ").reduce((acc, cookie) => {
    const [key, value] = cookie.split("=");
    if (key && value) {
      acc[key] = value;
    }
    return acc;
  }, {});
}
__name(_parseCookieString, "_parseCookieString");
function _extractFetchHeaders(headers) {
  const result = {};
  headers.forEach((value, key) => {
    result[key] = value;
  });
  return result;
}
__name(_extractFetchHeaders, "_extractFetchHeaders");
function _getXHRResponseHeaders(xhr) {
  const headers = xhr.getAllResponseHeaders();
  if (!headers) {
    return {};
  }
  return headers.split("\r\n").reduce((acc, line) => {
    const [key, value] = line.split(": ");
    if (key && value) {
      acc[key] = value;
    }
    return acc;
  }, {});
}
__name(_getXHRResponseHeaders, "_getXHRResponseHeaders");
function _isInGivenRequestTargets(failedRequestTargets, target) {
  return failedRequestTargets.some((givenRequestTarget) => {
    if (typeof givenRequestTarget === "string") {
      return target.includes(givenRequestTarget);
    }
    return givenRequestTarget.test(target);
  });
}
__name(_isInGivenRequestTargets, "_isInGivenRequestTargets");
function _isInGivenStatusRanges(failedRequestStatusCodes, status) {
  return failedRequestStatusCodes.some((range) => {
    if (typeof range === "number") {
      return range === status;
    }
    return status >= range[0] && status <= range[1];
  });
}
__name(_isInGivenStatusRanges, "_isInGivenStatusRanges");
function _wrapFetch(client, options2) {
  if (!supportsNativeFetch()) {
    return;
  }
  addFetchInstrumentationHandler((handlerData) => {
    if (getClient() !== client) {
      return;
    }
    const { response, args, error: error2, virtualError } = handlerData;
    const [requestInfo, requestInit] = args;
    if (!response) {
      return;
    }
    _fetchResponseHandler(options2, requestInfo, response, requestInit, error2 || virtualError);
  }, false);
}
__name(_wrapFetch, "_wrapFetch");
function _wrapXHR(client, options2) {
  if (!("XMLHttpRequest" in GLOBAL_OBJ)) {
    return;
  }
  addXhrInstrumentationHandler((handlerData) => {
    if (getClient() !== client) {
      return;
    }
    const { error: error2, virtualError } = handlerData;
    const xhr = handlerData.xhr;
    const sentryXhrData = xhr[SENTRY_XHR_DATA_KEY];
    if (!sentryXhrData) {
      return;
    }
    const { method, request_headers: headers } = sentryXhrData;
    try {
      _xhrResponseHandler(options2, xhr, method, headers, error2 || virtualError);
    } catch (e2) {
      DEBUG_BUILD$4 && logger$5.warn("Error while extracting response event form XHR response", e2);
    }
  });
}
__name(_wrapXHR, "_wrapXHR");
function _shouldCaptureResponse(options2, status, url) {
  return _isInGivenStatusRanges(options2.failedRequestStatusCodes, status) && _isInGivenRequestTargets(options2.failedRequestTargets, url) && !isSentryRequestUrl(url, getClient());
}
__name(_shouldCaptureResponse, "_shouldCaptureResponse");
function _createEvent(data) {
  const client = getClient();
  const virtualStackTrace = client && data.error && data.error instanceof Error ? data.error.stack : void 0;
  const stack = virtualStackTrace && client ? client.getOptions().stackParser(virtualStackTrace, 0, 1) : void 0;
  const message = `HTTP Client Error with status code: ${data.status}`;
  const event = {
    message,
    exception: {
      values: [
        {
          type: "Error",
          value: message,
          stacktrace: stack ? { frames: stack } : void 0
        }
      ]
    },
    request: {
      url: data.url,
      method: data.method,
      headers: data.requestHeaders,
      cookies: data.requestCookies
    },
    contexts: {
      response: {
        status_code: data.status,
        headers: data.responseHeaders,
        cookies: data.responseCookies,
        body_size: _getResponseSizeFromHeaders(data.responseHeaders)
      }
    }
  };
  addExceptionMechanism(event, {
    type: "http.client",
    handled: false
  });
  return event;
}
__name(_createEvent, "_createEvent");
function _getRequest(requestInfo, requestInit) {
  if (!requestInit && requestInfo instanceof Request) {
    return requestInfo;
  }
  if (requestInfo instanceof Request && requestInfo.bodyUsed) {
    return requestInfo;
  }
  return new Request(requestInfo, requestInit);
}
__name(_getRequest, "_getRequest");
function _shouldSendDefaultPii() {
  const client = getClient();
  return client ? Boolean(client.getOptions().sendDefaultPii) : false;
}
__name(_shouldSendDefaultPii, "_shouldSendDefaultPii");
const WINDOW$2 = GLOBAL_OBJ;
const DEFAULT_LINES_OF_CONTEXT = 7;
const INTEGRATION_NAME$4 = "ContextLines";
const _contextLinesIntegration = /* @__PURE__ */ __name((options2 = {}) => {
  const contextLines = options2.frameContextLines != null ? options2.frameContextLines : DEFAULT_LINES_OF_CONTEXT;
  return {
    name: INTEGRATION_NAME$4,
    processEvent(event) {
      return addSourceContext(event, contextLines);
    }
  };
}, "_contextLinesIntegration");
const contextLinesIntegration = defineIntegration(_contextLinesIntegration);
function addSourceContext(event, contextLines) {
  const doc2 = WINDOW$2.document;
  const htmlFilename = WINDOW$2.location && stripUrlQueryAndFragment(WINDOW$2.location.href);
  if (!doc2 || !htmlFilename) {
    return event;
  }
  const exceptions = event.exception && event.exception.values;
  if (!exceptions || !exceptions.length) {
    return event;
  }
  const html = doc2.documentElement.innerHTML;
  if (!html) {
    return event;
  }
  const htmlLines = ["<!DOCTYPE html>", "<html>", ...html.split("\n"), "</html>"];
  exceptions.forEach((exception) => {
    const stacktrace = exception.stacktrace;
    if (stacktrace && stacktrace.frames) {
      stacktrace.frames = stacktrace.frames.map(
        (frame) => applySourceContextToFrame(frame, htmlLines, htmlFilename, contextLines)
      );
    }
  });
  return event;
}
__name(addSourceContext, "addSourceContext");
function applySourceContextToFrame(frame, htmlLines, htmlFilename, linesOfContext) {
  if (frame.filename !== htmlFilename || !frame.lineno || !htmlLines.length) {
    return frame;
  }
  addContextToFrame(htmlLines, frame, linesOfContext);
  return frame;
}
__name(applySourceContextToFrame, "applySourceContextToFrame");
const WINDOW$1 = GLOBAL_OBJ;
const REPLAY_SESSION_KEY = "sentryReplaySession";
const REPLAY_EVENT_NAME = "replay_event";
const UNABLE_TO_SEND_REPLAY = "Unable to send Replay";
const SESSION_IDLE_PAUSE_DURATION = 3e5;
const SESSION_IDLE_EXPIRE_DURATION = 9e5;
const DEFAULT_FLUSH_MIN_DELAY = 5e3;
const DEFAULT_FLUSH_MAX_DELAY = 5500;
const BUFFER_CHECKOUT_TIME = 6e4;
const RETRY_BASE_INTERVAL = 5e3;
const RETRY_MAX_COUNT = 3;
const NETWORK_BODY_MAX_SIZE = 15e4;
const CONSOLE_ARG_MAX_SIZE = 5e3;
const SLOW_CLICK_THRESHOLD = 3e3;
const SLOW_CLICK_SCROLL_TIMEOUT = 300;
const REPLAY_MAX_EVENT_BUFFER_SIZE = 2e7;
const MIN_REPLAY_DURATION = 4999;
const MIN_REPLAY_DURATION_LIMIT = 15e3;
const MAX_REPLAY_DURATION = 36e5;
function _nullishCoalesce$1(lhs, rhsFn) {
  if (lhs != null) {
    return lhs;
  } else {
    return rhsFn();
  }
}
__name(_nullishCoalesce$1, "_nullishCoalesce$1");
function _optionalChain$5(ops2) {
  let lastAccessLHS = void 0;
  let value = ops2[0];
  let i2 = 1;
  while (i2 < ops2.length) {
    const op = ops2[i2];
    const fn = ops2[i2 + 1];
    i2 += 2;
    if ((op === "optionalAccess" || op === "optionalCall") && value == null) {
      return void 0;
    }
    if (op === "access" || op === "optionalAccess") {
      lastAccessLHS = value;
      value = fn(value);
    } else if (op === "call" || op === "optionalCall") {
      value = fn((...args) => value.call(lastAccessLHS, ...args));
      lastAccessLHS = void 0;
    }
  }
  return value;
}
__name(_optionalChain$5, "_optionalChain$5");
var NodeType$3;
(function(NodeType3) {
  NodeType3[NodeType3["Document"] = 0] = "Document";
  NodeType3[NodeType3["DocumentType"] = 1] = "DocumentType";
  NodeType3[NodeType3["Element"] = 2] = "Element";
  NodeType3[NodeType3["Text"] = 3] = "Text";
  NodeType3[NodeType3["CDATA"] = 4] = "CDATA";
  NodeType3[NodeType3["Comment"] = 5] = "Comment";
})(NodeType$3 || (NodeType$3 = {}));
function isElement$1(n2) {
  return n2.nodeType === n2.ELEMENT_NODE;
}
__name(isElement$1, "isElement$1");
function isShadowRoot(n2) {
  const host = _optionalChain$5([n2, "optionalAccess", (_2) => _2.host]);
  return Boolean(_optionalChain$5([host, "optionalAccess", (_2) => _2.shadowRoot]) === n2);
}
__name(isShadowRoot, "isShadowRoot");
function isNativeShadowDom(shadowRoot) {
  return Object.prototype.toString.call(shadowRoot) === "[object ShadowRoot]";
}
__name(isNativeShadowDom, "isNativeShadowDom");
function fixBrowserCompatibilityIssuesInCSS(cssText) {
  if (cssText.includes(" background-clip: text;") && !cssText.includes(" -webkit-background-clip: text;")) {
    cssText = cssText.replace(/\sbackground-clip:\s*text;/g, " -webkit-background-clip: text; background-clip: text;");
  }
  return cssText;
}
__name(fixBrowserCompatibilityIssuesInCSS, "fixBrowserCompatibilityIssuesInCSS");
function escapeImportStatement(rule) {
  const { cssText } = rule;
  if (cssText.split('"').length < 3)
    return cssText;
  const statement = ["@import", `url(${JSON.stringify(rule.href)})`];
  if (rule.layerName === "") {
    statement.push(`layer`);
  } else if (rule.layerName) {
    statement.push(`layer(${rule.layerName})`);
  }
  if (rule.supportsText) {
    statement.push(`supports(${rule.supportsText})`);
  }
  if (rule.media.length) {
    statement.push(rule.media.mediaText);
  }
  return statement.join(" ") + ";";
}
__name(escapeImportStatement, "escapeImportStatement");
function stringifyStylesheet(s2) {
  try {
    const rules = s2.rules || s2.cssRules;
    return rules ? fixBrowserCompatibilityIssuesInCSS(Array.from(rules, stringifyRule).join("")) : null;
  } catch (error2) {
    return null;
  }
}
__name(stringifyStylesheet, "stringifyStylesheet");
function fixAllCssProperty(rule) {
  let styles = "";
  for (let i2 = 0; i2 < rule.style.length; i2++) {
    const styleDeclaration = rule.style;
    const attribute2 = styleDeclaration[i2];
    const isImportant = styleDeclaration.getPropertyPriority(attribute2);
    styles += `${attribute2}:${styleDeclaration.getPropertyValue(attribute2)}${isImportant ? ` !important` : ""};`;
  }
  return `${rule.selectorText} { ${styles} }`;
}
__name(fixAllCssProperty, "fixAllCssProperty");
function stringifyRule(rule) {
  let importStringified;
  if (isCSSImportRule(rule)) {
    try {
      importStringified = stringifyStylesheet(rule.styleSheet) || escapeImportStatement(rule);
    } catch (error2) {
    }
  } else if (isCSSStyleRule(rule)) {
    let cssText = rule.cssText;
    const needsSafariColonFix = rule.selectorText.includes(":");
    const needsAllFix = typeof rule.style["all"] === "string" && rule.style["all"];
    if (needsAllFix) {
      cssText = fixAllCssProperty(rule);
    }
    if (needsSafariColonFix) {
      cssText = fixSafariColons(cssText);
    }
    if (needsSafariColonFix || needsAllFix) {
      return cssText;
    }
  }
  return importStringified || rule.cssText;
}
__name(stringifyRule, "stringifyRule");
function fixSafariColons(cssStringified) {
  const regex2 = /(\[(?:[\w-]+)[^\\])(:(?:[\w-]+)\])/gm;
  return cssStringified.replace(regex2, "$1\\$2");
}
__name(fixSafariColons, "fixSafariColons");
function isCSSImportRule(rule) {
  return "styleSheet" in rule;
}
__name(isCSSImportRule, "isCSSImportRule");
function isCSSStyleRule(rule) {
  return "selectorText" in rule;
}
__name(isCSSStyleRule, "isCSSStyleRule");
class Mirror {
  static {
    __name(this, "Mirror");
  }
  constructor() {
    this.idNodeMap = /* @__PURE__ */ new Map();
    this.nodeMetaMap = /* @__PURE__ */ new WeakMap();
  }
  getId(n2) {
    if (!n2)
      return -1;
    const id2 = _optionalChain$5([this, "access", (_3) => _3.getMeta, "call", (_4) => _4(n2), "optionalAccess", (_5) => _5.id]);
    return _nullishCoalesce$1(id2, () => -1);
  }
  getNode(id2) {
    return this.idNodeMap.get(id2) || null;
  }
  getIds() {
    return Array.from(this.idNodeMap.keys());
  }
  getMeta(n2) {
    return this.nodeMetaMap.get(n2) || null;
  }
  removeNodeFromMap(n2) {
    const id2 = this.getId(n2);
    this.idNodeMap.delete(id2);
    if (n2.childNodes) {
      n2.childNodes.forEach((childNode) => this.removeNodeFromMap(childNode));
    }
  }
  has(id2) {
    return this.idNodeMap.has(id2);
  }
  hasNode(node2) {
    return this.nodeMetaMap.has(node2);
  }
  add(n2, meta) {
    const id2 = meta.id;
    this.idNodeMap.set(id2, n2);
    this.nodeMetaMap.set(n2, meta);
  }
  replace(id2, n2) {
    const oldNode = this.getNode(id2);
    if (oldNode) {
      const meta = this.nodeMetaMap.get(oldNode);
      if (meta)
        this.nodeMetaMap.set(n2, meta);
    }
    this.idNodeMap.set(id2, n2);
  }
  reset() {
    this.idNodeMap = /* @__PURE__ */ new Map();
    this.nodeMetaMap = /* @__PURE__ */ new WeakMap();
  }
}
function createMirror() {
  return new Mirror();
}
__name(createMirror, "createMirror");
function shouldMaskInput({ maskInputOptions, tagName, type }) {
  if (tagName === "OPTION") {
    tagName = "SELECT";
  }
  return Boolean(maskInputOptions[tagName.toLowerCase()] || type && maskInputOptions[type] || type === "password" || tagName === "INPUT" && !type && maskInputOptions["text"]);
}
__name(shouldMaskInput, "shouldMaskInput");
function maskInputValue({ isMasked: isMasked2, element, value, maskInputFn }) {
  let text2 = value || "";
  if (!isMasked2) {
    return text2;
  }
  if (maskInputFn) {
    text2 = maskInputFn(text2, element);
  }
  return "*".repeat(text2.length);
}
__name(maskInputValue, "maskInputValue");
function toLowerCase(str) {
  return str.toLowerCase();
}
__name(toLowerCase, "toLowerCase");
function toUpperCase(str) {
  return str.toUpperCase();
}
__name(toUpperCase, "toUpperCase");
const ORIGINAL_ATTRIBUTE_NAME = "__rrweb_original__";
function is2DCanvasBlank(canvas2) {
  const ctx = canvas2.getContext("2d");
  if (!ctx)
    return true;
  const chunkSize = 50;
  for (let x2 = 0; x2 < canvas2.width; x2 += chunkSize) {
    for (let y2 = 0; y2 < canvas2.height; y2 += chunkSize) {
      const getImageData = ctx.getImageData;
      const originalGetImageData = ORIGINAL_ATTRIBUTE_NAME in getImageData ? getImageData[ORIGINAL_ATTRIBUTE_NAME] : getImageData;
      const pixelBuffer = new Uint32Array(originalGetImageData.call(ctx, x2, y2, Math.min(chunkSize, canvas2.width - x2), Math.min(chunkSize, canvas2.height - y2)).data.buffer);
      if (pixelBuffer.some((pixel) => pixel !== 0))
        return false;
    }
  }
  return true;
}
__name(is2DCanvasBlank, "is2DCanvasBlank");
function getInputType(element) {
  const type = element.type;
  return element.hasAttribute("data-rr-is-password") ? "password" : type ? toLowerCase(type) : null;
}
__name(getInputType, "getInputType");
function getInputValue(el, tagName, type) {
  if (tagName === "INPUT" && (type === "radio" || type === "checkbox")) {
    return el.getAttribute("value") || "";
  }
  return el.value;
}
__name(getInputValue, "getInputValue");
function extractFileExtension(path, baseURL) {
  let url;
  try {
    url = new URL(path, _nullishCoalesce$1(baseURL, () => window.location.href));
  } catch (err) {
    return null;
  }
  const regex2 = /\.([0-9a-z]+)(?:$)/i;
  const match2 = url.pathname.match(regex2);
  return _nullishCoalesce$1(_optionalChain$5([match2, "optionalAccess", (_6) => _6[1]]), () => null);
}
__name(extractFileExtension, "extractFileExtension");
const cachedImplementations$1 = {};
function getImplementation$1(name2) {
  const cached = cachedImplementations$1[name2];
  if (cached) {
    return cached;
  }
  const document2 = window.document;
  let impl = window[name2];
  if (document2 && typeof document2.createElement === "function") {
    try {
      const sandbox = document2.createElement("iframe");
      sandbox.hidden = true;
      document2.head.appendChild(sandbox);
      const contentWindow = sandbox.contentWindow;
      if (contentWindow && contentWindow[name2]) {
        impl = contentWindow[name2];
      }
      document2.head.removeChild(sandbox);
    } catch (e2) {
    }
  }
  return cachedImplementations$1[name2] = impl.bind(window);
}
__name(getImplementation$1, "getImplementation$1");
function setTimeout$2(...rest) {
  return getImplementation$1("setTimeout")(...rest);
}
__name(setTimeout$2, "setTimeout$2");
function clearTimeout$2(...rest) {
  return getImplementation$1("clearTimeout")(...rest);
}
__name(clearTimeout$2, "clearTimeout$2");
function getIframeContentDocument(iframe) {
  try {
    return iframe.contentDocument;
  } catch (e2) {
  }
}
__name(getIframeContentDocument, "getIframeContentDocument");
let _id$2 = 1;
const tagNameRegex = new RegExp("[^a-z0-9-_:]");
const IGNORED_NODE = -2;
function genId() {
  return _id$2++;
}
__name(genId, "genId");
function getValidTagName(element) {
  if (element instanceof HTMLFormElement) {
    return "form";
  }
  const processedTagName = toLowerCase(element.tagName);
  if (tagNameRegex.test(processedTagName)) {
    return "div";
  }
  return processedTagName;
}
__name(getValidTagName, "getValidTagName");
function extractOrigin(url) {
  let origin2 = "";
  if (url.indexOf("//") > -1) {
    origin2 = url.split("/").slice(0, 3).join("/");
  } else {
    origin2 = url.split("/")[0];
  }
  origin2 = origin2.split("?")[0];
  return origin2;
}
__name(extractOrigin, "extractOrigin");
let canvasService;
let canvasCtx;
const URL_IN_CSS_REF = /url\((?:(')([^']*)'|(")(.*?)"|([^)]*))\)/gm;
const URL_PROTOCOL_MATCH = /^(?:[a-z+]+:)?\/\//i;
const URL_WWW_MATCH = /^www\..*/i;
const DATA_URI = /^(data:)([^,]*),(.*)/i;
function absoluteToStylesheet(cssText, href) {
  return (cssText || "").replace(URL_IN_CSS_REF, (origin2, quote1, path1, quote2, path2, path3) => {
    const filePath = path1 || path2 || path3;
    const maybeQuote = quote1 || quote2 || "";
    if (!filePath) {
      return origin2;
    }
    if (URL_PROTOCOL_MATCH.test(filePath) || URL_WWW_MATCH.test(filePath)) {
      return `url(${maybeQuote}${filePath}${maybeQuote})`;
    }
    if (DATA_URI.test(filePath)) {
      return `url(${maybeQuote}${filePath}${maybeQuote})`;
    }
    if (filePath[0] === "/") {
      return `url(${maybeQuote}${extractOrigin(href) + filePath}${maybeQuote})`;
    }
    const stack = href.split("/");
    const parts2 = filePath.split("/");
    stack.pop();
    for (const part of parts2) {
      if (part === ".") {
        continue;
      } else if (part === "..") {
        stack.pop();
      } else {
        stack.push(part);
      }
    }
    return `url(${maybeQuote}${stack.join("/")}${maybeQuote})`;
  });
}
__name(absoluteToStylesheet, "absoluteToStylesheet");
const SRCSET_NOT_SPACES = /^[^ \t\n\r\u000c]+/;
const SRCSET_COMMAS_OR_SPACES = /^[, \t\n\r\u000c]+/;
function getAbsoluteSrcsetString(doc2, attributeValue) {
  if (attributeValue.trim() === "") {
    return attributeValue;
  }
  let pos = 0;
  function collectCharacters(regEx) {
    let chars2;
    const match2 = regEx.exec(attributeValue.substring(pos));
    if (match2) {
      chars2 = match2[0];
      pos += chars2.length;
      return chars2;
    }
    return "";
  }
  __name(collectCharacters, "collectCharacters");
  const output = [];
  while (true) {
    collectCharacters(SRCSET_COMMAS_OR_SPACES);
    if (pos >= attributeValue.length) {
      break;
    }
    let url = collectCharacters(SRCSET_NOT_SPACES);
    if (url.slice(-1) === ",") {
      url = absoluteToDoc(doc2, url.substring(0, url.length - 1));
      output.push(url);
    } else {
      let descriptorsStr = "";
      url = absoluteToDoc(doc2, url);
      let inParens = false;
      while (true) {
        const c2 = attributeValue.charAt(pos);
        if (c2 === "") {
          output.push((url + descriptorsStr).trim());
          break;
        } else if (!inParens) {
          if (c2 === ",") {
            pos += 1;
            output.push((url + descriptorsStr).trim());
            break;
          } else if (c2 === "(") {
            inParens = true;
          }
        } else {
          if (c2 === ")") {
            inParens = false;
          }
        }
        descriptorsStr += c2;
        pos += 1;
      }
    }
  }
  return output.join(", ");
}
__name(getAbsoluteSrcsetString, "getAbsoluteSrcsetString");
const cachedDocument = /* @__PURE__ */ new WeakMap();
function absoluteToDoc(doc2, attributeValue) {
  if (!attributeValue || attributeValue.trim() === "") {
    return attributeValue;
  }
  return getHref(doc2, attributeValue);
}
__name(absoluteToDoc, "absoluteToDoc");
function isSVGElement(el) {
  return Boolean(el.tagName === "svg" || el.ownerSVGElement);
}
__name(isSVGElement, "isSVGElement");
function getHref(doc2, customHref) {
  let a2 = cachedDocument.get(doc2);
  if (!a2) {
    a2 = doc2.createElement("a");
    cachedDocument.set(doc2, a2);
  }
  if (!customHref) {
    customHref = "";
  } else if (customHref.startsWith("blob:") || customHref.startsWith("data:")) {
    return customHref;
  }
  a2.setAttribute("href", customHref);
  return a2.href;
}
__name(getHref, "getHref");
function transformAttribute(doc2, tagName, name2, value, element, maskAttributeFn) {
  if (!value) {
    return value;
  }
  if (name2 === "src" || name2 === "href" && !(tagName === "use" && value[0] === "#")) {
    return absoluteToDoc(doc2, value);
  } else if (name2 === "xlink:href" && value[0] !== "#") {
    return absoluteToDoc(doc2, value);
  } else if (name2 === "background" && (tagName === "table" || tagName === "td" || tagName === "th")) {
    return absoluteToDoc(doc2, value);
  } else if (name2 === "srcset") {
    return getAbsoluteSrcsetString(doc2, value);
  } else if (name2 === "style") {
    return absoluteToStylesheet(value, getHref(doc2));
  } else if (tagName === "object" && name2 === "data") {
    return absoluteToDoc(doc2, value);
  }
  if (typeof maskAttributeFn === "function") {
    return maskAttributeFn(name2, value, element);
  }
  return value;
}
__name(transformAttribute, "transformAttribute");
function ignoreAttribute(tagName, name2, _value) {
  return (tagName === "video" || tagName === "audio") && name2 === "autoplay";
}
__name(ignoreAttribute, "ignoreAttribute");
function _isBlockedElement(element, blockClass, blockSelector, unblockSelector) {
  try {
    if (unblockSelector && element.matches(unblockSelector)) {
      return false;
    }
    if (typeof blockClass === "string") {
      if (element.classList.contains(blockClass)) {
        return true;
      }
    } else {
      for (let eIndex = element.classList.length; eIndex--; ) {
        const className = element.classList[eIndex];
        if (blockClass.test(className)) {
          return true;
        }
      }
    }
    if (blockSelector) {
      return element.matches(blockSelector);
    }
  } catch (e2) {
  }
  return false;
}
__name(_isBlockedElement, "_isBlockedElement");
function elementClassMatchesRegex$1(el, regex2) {
  for (let eIndex = el.classList.length; eIndex--; ) {
    const className = el.classList[eIndex];
    if (regex2.test(className)) {
      return true;
    }
  }
  return false;
}
__name(elementClassMatchesRegex$1, "elementClassMatchesRegex$1");
function distanceToMatch$1(node2, matchPredicate, limit2 = Infinity, distance2 = 0) {
  if (!node2)
    return -1;
  if (node2.nodeType !== node2.ELEMENT_NODE)
    return -1;
  if (distance2 > limit2)
    return -1;
  if (matchPredicate(node2))
    return distance2;
  return distanceToMatch$1(node2.parentNode, matchPredicate, limit2, distance2 + 1);
}
__name(distanceToMatch$1, "distanceToMatch$1");
function createMatchPredicate$1(className, selector) {
  return (node2) => {
    const el = node2;
    if (el === null)
      return false;
    try {
      if (className) {
        if (typeof className === "string") {
          if (el.matches(`.${className}`))
            return true;
        } else if (elementClassMatchesRegex$1(el, className)) {
          return true;
        }
      }
      if (selector && el.matches(selector))
        return true;
      return false;
    } catch (e2) {
      return false;
    }
  };
}
__name(createMatchPredicate$1, "createMatchPredicate$1");
function needMaskingText(node2, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, maskAllText) {
  try {
    const el = node2.nodeType === node2.ELEMENT_NODE ? node2 : node2.parentElement;
    if (el === null)
      return false;
    if (el.tagName === "INPUT") {
      const autocomplete = el.getAttribute("autocomplete");
      const disallowedAutocompleteValues = [
        "current-password",
        "new-password",
        "cc-number",
        "cc-exp",
        "cc-exp-month",
        "cc-exp-year",
        "cc-csc"
      ];
      if (disallowedAutocompleteValues.includes(autocomplete)) {
        return true;
      }
    }
    let maskDistance = -1;
    let unmaskDistance = -1;
    if (maskAllText) {
      unmaskDistance = distanceToMatch$1(el, createMatchPredicate$1(unmaskTextClass, unmaskTextSelector));
      if (unmaskDistance < 0) {
        return true;
      }
      maskDistance = distanceToMatch$1(el, createMatchPredicate$1(maskTextClass, maskTextSelector), unmaskDistance >= 0 ? unmaskDistance : Infinity);
    } else {
      maskDistance = distanceToMatch$1(el, createMatchPredicate$1(maskTextClass, maskTextSelector));
      if (maskDistance < 0) {
        return false;
      }
      unmaskDistance = distanceToMatch$1(el, createMatchPredicate$1(unmaskTextClass, unmaskTextSelector), maskDistance >= 0 ? maskDistance : Infinity);
    }
    return maskDistance >= 0 ? unmaskDistance >= 0 ? maskDistance <= unmaskDistance : true : unmaskDistance >= 0 ? false : !!maskAllText;
  } catch (e2) {
  }
  return !!maskAllText;
}
__name(needMaskingText, "needMaskingText");
function onceIframeLoaded(iframeEl, listener, iframeLoadTimeout) {
  const win = iframeEl.contentWindow;
  if (!win) {
    return;
  }
  let fired = false;
  let readyState;
  try {
    readyState = win.document.readyState;
  } catch (error2) {
    return;
  }
  if (readyState !== "complete") {
    const timer = setTimeout$2(() => {
      if (!fired) {
        listener();
        fired = true;
      }
    }, iframeLoadTimeout);
    iframeEl.addEventListener("load", () => {
      clearTimeout$2(timer);
      fired = true;
      listener();
    });
    return;
  }
  const blankUrl = "about:blank";
  if (win.location.href !== blankUrl || iframeEl.src === blankUrl || iframeEl.src === "") {
    setTimeout$2(listener, 0);
    return iframeEl.addEventListener("load", listener);
  }
  iframeEl.addEventListener("load", listener);
}
__name(onceIframeLoaded, "onceIframeLoaded");
function onceStylesheetLoaded(link2, listener, styleSheetLoadTimeout) {
  let fired = false;
  let styleSheetLoaded;
  try {
    styleSheetLoaded = link2.sheet;
  } catch (error2) {
    return;
  }
  if (styleSheetLoaded)
    return;
  const timer = setTimeout$2(() => {
    if (!fired) {
      listener();
      fired = true;
    }
  }, styleSheetLoadTimeout);
  link2.addEventListener("load", () => {
    clearTimeout$2(timer);
    fired = true;
    listener();
  });
}
__name(onceStylesheetLoaded, "onceStylesheetLoaded");
function serializeNode(n2, options2) {
  const { doc: doc2, mirror: mirror2, blockClass, blockSelector, unblockSelector, maskAllText, maskAttributeFn, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, inlineStylesheet, maskInputOptions = {}, maskTextFn, maskInputFn, dataURLOptions = {}, inlineImages, recordCanvas, keepIframeSrcFn, newlyAddedElement = false } = options2;
  const rootId = getRootId(doc2, mirror2);
  switch (n2.nodeType) {
    case n2.DOCUMENT_NODE:
      if (n2.compatMode !== "CSS1Compat") {
        return {
          type: NodeType$3.Document,
          childNodes: [],
          compatMode: n2.compatMode
        };
      } else {
        return {
          type: NodeType$3.Document,
          childNodes: []
        };
      }
    case n2.DOCUMENT_TYPE_NODE:
      return {
        type: NodeType$3.DocumentType,
        name: n2.name,
        publicId: n2.publicId,
        systemId: n2.systemId,
        rootId
      };
    case n2.ELEMENT_NODE:
      return serializeElementNode(n2, {
        doc: doc2,
        blockClass,
        blockSelector,
        unblockSelector,
        inlineStylesheet,
        maskAttributeFn,
        maskInputOptions,
        maskInputFn,
        dataURLOptions,
        inlineImages,
        recordCanvas,
        keepIframeSrcFn,
        newlyAddedElement,
        rootId,
        maskAllText,
        maskTextClass,
        unmaskTextClass,
        maskTextSelector,
        unmaskTextSelector
      });
    case n2.TEXT_NODE:
      return serializeTextNode(n2, {
        doc: doc2,
        maskAllText,
        maskTextClass,
        unmaskTextClass,
        maskTextSelector,
        unmaskTextSelector,
        maskTextFn,
        maskInputOptions,
        maskInputFn,
        rootId
      });
    case n2.CDATA_SECTION_NODE:
      return {
        type: NodeType$3.CDATA,
        textContent: "",
        rootId
      };
    case n2.COMMENT_NODE:
      return {
        type: NodeType$3.Comment,
        textContent: n2.textContent || "",
        rootId
      };
    default:
      return false;
  }
}
__name(serializeNode, "serializeNode");
function getRootId(doc2, mirror2) {
  if (!mirror2.hasNode(doc2))
    return void 0;
  const docId = mirror2.getId(doc2);
  return docId === 1 ? void 0 : docId;
}
__name(getRootId, "getRootId");
function serializeTextNode(n2, options2) {
  const { maskAllText, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, maskTextFn, maskInputOptions, maskInputFn, rootId } = options2;
  const parentTagName = n2.parentNode && n2.parentNode.tagName;
  let textContent = n2.textContent;
  const isStyle = parentTagName === "STYLE" ? true : void 0;
  const isScript = parentTagName === "SCRIPT" ? true : void 0;
  const isTextarea = parentTagName === "TEXTAREA" ? true : void 0;
  if (isStyle && textContent) {
    try {
      if (n2.nextSibling || n2.previousSibling) {
      } else if (_optionalChain$5([n2, "access", (_7) => _7.parentNode, "access", (_8) => _8.sheet, "optionalAccess", (_9) => _9.cssRules])) {
        textContent = stringifyStylesheet(n2.parentNode.sheet);
      }
    } catch (err) {
      console.warn(`Cannot get CSS styles from text's parentNode. Error: ${err}`, n2);
    }
    textContent = absoluteToStylesheet(textContent, getHref(options2.doc));
  }
  if (isScript) {
    textContent = "SCRIPT_PLACEHOLDER";
  }
  const forceMask = needMaskingText(n2, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, maskAllText);
  if (!isStyle && !isScript && !isTextarea && textContent && forceMask) {
    textContent = maskTextFn ? maskTextFn(textContent, n2.parentElement) : textContent.replace(/[\S]/g, "*");
  }
  if (isTextarea && textContent && (maskInputOptions.textarea || forceMask)) {
    textContent = maskInputFn ? maskInputFn(textContent, n2.parentNode) : textContent.replace(/[\S]/g, "*");
  }
  if (parentTagName === "OPTION" && textContent) {
    const isInputMasked = shouldMaskInput({
      type: null,
      tagName: parentTagName,
      maskInputOptions
    });
    textContent = maskInputValue({
      isMasked: needMaskingText(n2, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, isInputMasked),
      element: n2,
      value: textContent,
      maskInputFn
    });
  }
  return {
    type: NodeType$3.Text,
    textContent: textContent || "",
    isStyle,
    rootId
  };
}
__name(serializeTextNode, "serializeTextNode");
function serializeElementNode(n2, options2) {
  const { doc: doc2, blockClass, blockSelector, unblockSelector, inlineStylesheet, maskInputOptions = {}, maskAttributeFn, maskInputFn, dataURLOptions = {}, inlineImages, recordCanvas, keepIframeSrcFn, newlyAddedElement = false, rootId, maskAllText, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector } = options2;
  const needBlock = _isBlockedElement(n2, blockClass, blockSelector, unblockSelector);
  const tagName = getValidTagName(n2);
  let attributes = {};
  const len = n2.attributes.length;
  for (let i2 = 0; i2 < len; i2++) {
    const attr = n2.attributes[i2];
    if (attr.name && !ignoreAttribute(tagName, attr.name, attr.value)) {
      attributes[attr.name] = transformAttribute(doc2, tagName, toLowerCase(attr.name), attr.value, n2, maskAttributeFn);
    }
  }
  if (tagName === "link" && inlineStylesheet) {
    const stylesheet = Array.from(doc2.styleSheets).find((s2) => {
      return s2.href === n2.href;
    });
    let cssText = null;
    if (stylesheet) {
      cssText = stringifyStylesheet(stylesheet);
    }
    if (cssText) {
      attributes.rel = null;
      attributes.href = null;
      attributes.crossorigin = null;
      attributes._cssText = absoluteToStylesheet(cssText, stylesheet.href);
    }
  }
  if (tagName === "style" && n2.sheet && !(n2.innerText || n2.textContent || "").trim().length) {
    const cssText = stringifyStylesheet(n2.sheet);
    if (cssText) {
      attributes._cssText = absoluteToStylesheet(cssText, getHref(doc2));
    }
  }
  if (tagName === "input" || tagName === "textarea" || tagName === "select" || tagName === "option") {
    const el = n2;
    const type = getInputType(el);
    const value = getInputValue(el, toUpperCase(tagName), type);
    const checked = el.checked;
    if (type !== "submit" && type !== "button" && value) {
      const forceMask = needMaskingText(el, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, shouldMaskInput({
        type,
        tagName: toUpperCase(tagName),
        maskInputOptions
      }));
      attributes.value = maskInputValue({
        isMasked: forceMask,
        element: el,
        value,
        maskInputFn
      });
    }
    if (checked) {
      attributes.checked = checked;
    }
  }
  if (tagName === "option") {
    if (n2.selected && !maskInputOptions["select"]) {
      attributes.selected = true;
    } else {
      delete attributes.selected;
    }
  }
  if (tagName === "canvas" && recordCanvas) {
    if (n2.__context === "2d") {
      if (!is2DCanvasBlank(n2)) {
        attributes.rr_dataURL = n2.toDataURL(dataURLOptions.type, dataURLOptions.quality);
      }
    } else if (!("__context" in n2)) {
      const canvasDataURL = n2.toDataURL(dataURLOptions.type, dataURLOptions.quality);
      const blankCanvas = doc2.createElement("canvas");
      blankCanvas.width = n2.width;
      blankCanvas.height = n2.height;
      const blankCanvasDataURL = blankCanvas.toDataURL(dataURLOptions.type, dataURLOptions.quality);
      if (canvasDataURL !== blankCanvasDataURL) {
        attributes.rr_dataURL = canvasDataURL;
      }
    }
  }
  if (tagName === "img" && inlineImages) {
    if (!canvasService) {
      canvasService = doc2.createElement("canvas");
      canvasCtx = canvasService.getContext("2d");
    }
    const image2 = n2;
    const imageSrc = image2.currentSrc || image2.getAttribute("src") || "<unknown-src>";
    const priorCrossOrigin = image2.crossOrigin;
    const recordInlineImage = /* @__PURE__ */ __name(() => {
      image2.removeEventListener("load", recordInlineImage);
      try {
        canvasService.width = image2.naturalWidth;
        canvasService.height = image2.naturalHeight;
        canvasCtx.drawImage(image2, 0, 0);
        attributes.rr_dataURL = canvasService.toDataURL(dataURLOptions.type, dataURLOptions.quality);
      } catch (err) {
        if (image2.crossOrigin !== "anonymous") {
          image2.crossOrigin = "anonymous";
          if (image2.complete && image2.naturalWidth !== 0)
            recordInlineImage();
          else
            image2.addEventListener("load", recordInlineImage);
          return;
        } else {
          console.warn(`Cannot inline img src=${imageSrc}! Error: ${err}`);
        }
      }
      if (image2.crossOrigin === "anonymous") {
        priorCrossOrigin ? attributes.crossOrigin = priorCrossOrigin : image2.removeAttribute("crossorigin");
      }
    }, "recordInlineImage");
    if (image2.complete && image2.naturalWidth !== 0)
      recordInlineImage();
    else
      image2.addEventListener("load", recordInlineImage);
  }
  if (tagName === "audio" || tagName === "video") {
    attributes.rr_mediaState = n2.paused ? "paused" : "played";
    attributes.rr_mediaCurrentTime = n2.currentTime;
  }
  if (!newlyAddedElement) {
    if (n2.scrollLeft) {
      attributes.rr_scrollLeft = n2.scrollLeft;
    }
    if (n2.scrollTop) {
      attributes.rr_scrollTop = n2.scrollTop;
    }
  }
  if (needBlock) {
    const { width: width2, height } = n2.getBoundingClientRect();
    attributes = {
      class: attributes.class,
      rr_width: `${width2}px`,
      rr_height: `${height}px`
    };
  }
  if (tagName === "iframe" && !keepIframeSrcFn(attributes.src)) {
    if (!needBlock && !getIframeContentDocument(n2)) {
      attributes.rr_src = attributes.src;
    }
    delete attributes.src;
  }
  let isCustomElement;
  try {
    if (customElements.get(tagName))
      isCustomElement = true;
  } catch (e2) {
  }
  return {
    type: NodeType$3.Element,
    tagName,
    attributes,
    childNodes: [],
    isSVG: isSVGElement(n2) || void 0,
    needBlock,
    rootId,
    isCustom: isCustomElement
  };
}
__name(serializeElementNode, "serializeElementNode");
function lowerIfExists(maybeAttr) {
  if (maybeAttr === void 0 || maybeAttr === null) {
    return "";
  } else {
    return maybeAttr.toLowerCase();
  }
}
__name(lowerIfExists, "lowerIfExists");
function slimDOMExcluded(sn2, slimDOMOptions) {
  if (slimDOMOptions.comment && sn2.type === NodeType$3.Comment) {
    return true;
  } else if (sn2.type === NodeType$3.Element) {
    if (slimDOMOptions.script && (sn2.tagName === "script" || sn2.tagName === "link" && (sn2.attributes.rel === "preload" || sn2.attributes.rel === "modulepreload") || sn2.tagName === "link" && sn2.attributes.rel === "prefetch" && typeof sn2.attributes.href === "string" && extractFileExtension(sn2.attributes.href) === "js")) {
      return true;
    } else if (slimDOMOptions.headFavicon && (sn2.tagName === "link" && sn2.attributes.rel === "shortcut icon" || sn2.tagName === "meta" && (lowerIfExists(sn2.attributes.name).match(/^msapplication-tile(image|color)$/) || lowerIfExists(sn2.attributes.name) === "application-name" || lowerIfExists(sn2.attributes.rel) === "icon" || lowerIfExists(sn2.attributes.rel) === "apple-touch-icon" || lowerIfExists(sn2.attributes.rel) === "shortcut icon"))) {
      return true;
    } else if (sn2.tagName === "meta") {
      if (slimDOMOptions.headMetaDescKeywords && lowerIfExists(sn2.attributes.name).match(/^description|keywords$/)) {
        return true;
      } else if (slimDOMOptions.headMetaSocial && (lowerIfExists(sn2.attributes.property).match(/^(og|twitter|fb):/) || lowerIfExists(sn2.attributes.name).match(/^(og|twitter):/) || lowerIfExists(sn2.attributes.name) === "pinterest")) {
        return true;
      } else if (slimDOMOptions.headMetaRobots && (lowerIfExists(sn2.attributes.name) === "robots" || lowerIfExists(sn2.attributes.name) === "googlebot" || lowerIfExists(sn2.attributes.name) === "bingbot")) {
        return true;
      } else if (slimDOMOptions.headMetaHttpEquiv && sn2.attributes["http-equiv"] !== void 0) {
        return true;
      } else if (slimDOMOptions.headMetaAuthorship && (lowerIfExists(sn2.attributes.name) === "author" || lowerIfExists(sn2.attributes.name) === "generator" || lowerIfExists(sn2.attributes.name) === "framework" || lowerIfExists(sn2.attributes.name) === "publisher" || lowerIfExists(sn2.attributes.name) === "progid" || lowerIfExists(sn2.attributes.property).match(/^article:/) || lowerIfExists(sn2.attributes.property).match(/^product:/))) {
        return true;
      } else if (slimDOMOptions.headMetaVerification && (lowerIfExists(sn2.attributes.name) === "google-site-verification" || lowerIfExists(sn2.attributes.name) === "yandex-verification" || lowerIfExists(sn2.attributes.name) === "csrf-token" || lowerIfExists(sn2.attributes.name) === "p:domain_verify" || lowerIfExists(sn2.attributes.name) === "verify-v1" || lowerIfExists(sn2.attributes.name) === "verification" || lowerIfExists(sn2.attributes.name) === "shopify-checkout-api-token")) {
        return true;
      }
    }
  }
  return false;
}
__name(slimDOMExcluded, "slimDOMExcluded");
function serializeNodeWithId(n2, options2) {
  const { doc: doc2, mirror: mirror2, blockClass, blockSelector, unblockSelector, maskAllText, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, skipChild = false, inlineStylesheet = true, maskInputOptions = {}, maskAttributeFn, maskTextFn, maskInputFn, slimDOMOptions, dataURLOptions = {}, inlineImages = false, recordCanvas = false, onSerialize, onIframeLoad, iframeLoadTimeout = 5e3, onStylesheetLoad, stylesheetLoadTimeout = 5e3, keepIframeSrcFn = /* @__PURE__ */ __name(() => false, "keepIframeSrcFn"), newlyAddedElement = false } = options2;
  let { preserveWhiteSpace = true } = options2;
  const _serializedNode = serializeNode(n2, {
    doc: doc2,
    mirror: mirror2,
    blockClass,
    blockSelector,
    maskAllText,
    unblockSelector,
    maskTextClass,
    unmaskTextClass,
    maskTextSelector,
    unmaskTextSelector,
    inlineStylesheet,
    maskInputOptions,
    maskAttributeFn,
    maskTextFn,
    maskInputFn,
    dataURLOptions,
    inlineImages,
    recordCanvas,
    keepIframeSrcFn,
    newlyAddedElement
  });
  if (!_serializedNode) {
    console.warn(n2, "not serialized");
    return null;
  }
  let id2;
  if (mirror2.hasNode(n2)) {
    id2 = mirror2.getId(n2);
  } else if (slimDOMExcluded(_serializedNode, slimDOMOptions) || !preserveWhiteSpace && _serializedNode.type === NodeType$3.Text && !_serializedNode.isStyle && !_serializedNode.textContent.replace(/^\s+|\s+$/gm, "").length) {
    id2 = IGNORED_NODE;
  } else {
    id2 = genId();
  }
  const serializedNode = Object.assign(_serializedNode, { id: id2 });
  mirror2.add(n2, serializedNode);
  if (id2 === IGNORED_NODE) {
    return null;
  }
  if (onSerialize) {
    onSerialize(n2);
  }
  let recordChild = !skipChild;
  if (serializedNode.type === NodeType$3.Element) {
    recordChild = recordChild && !serializedNode.needBlock;
    delete serializedNode.needBlock;
    const shadowRoot = n2.shadowRoot;
    if (shadowRoot && isNativeShadowDom(shadowRoot))
      serializedNode.isShadowHost = true;
  }
  if ((serializedNode.type === NodeType$3.Document || serializedNode.type === NodeType$3.Element) && recordChild) {
    if (slimDOMOptions.headWhitespace && serializedNode.type === NodeType$3.Element && serializedNode.tagName === "head") {
      preserveWhiteSpace = false;
    }
    const bypassOptions = {
      doc: doc2,
      mirror: mirror2,
      blockClass,
      blockSelector,
      maskAllText,
      unblockSelector,
      maskTextClass,
      unmaskTextClass,
      maskTextSelector,
      unmaskTextSelector,
      skipChild,
      inlineStylesheet,
      maskInputOptions,
      maskAttributeFn,
      maskTextFn,
      maskInputFn,
      slimDOMOptions,
      dataURLOptions,
      inlineImages,
      recordCanvas,
      preserveWhiteSpace,
      onSerialize,
      onIframeLoad,
      iframeLoadTimeout,
      onStylesheetLoad,
      stylesheetLoadTimeout,
      keepIframeSrcFn
    };
    for (const childN of Array.from(n2.childNodes)) {
      const serializedChildNode = serializeNodeWithId(childN, bypassOptions);
      if (serializedChildNode) {
        serializedNode.childNodes.push(serializedChildNode);
      }
    }
    if (isElement$1(n2) && n2.shadowRoot) {
      for (const childN of Array.from(n2.shadowRoot.childNodes)) {
        const serializedChildNode = serializeNodeWithId(childN, bypassOptions);
        if (serializedChildNode) {
          isNativeShadowDom(n2.shadowRoot) && (serializedChildNode.isShadow = true);
          serializedNode.childNodes.push(serializedChildNode);
        }
      }
    }
  }
  if (n2.parentNode && isShadowRoot(n2.parentNode) && isNativeShadowDom(n2.parentNode)) {
    serializedNode.isShadow = true;
  }
  if (serializedNode.type === NodeType$3.Element && serializedNode.tagName === "iframe") {
    onceIframeLoaded(n2, () => {
      const iframeDoc = getIframeContentDocument(n2);
      if (iframeDoc && onIframeLoad) {
        const serializedIframeNode = serializeNodeWithId(iframeDoc, {
          doc: iframeDoc,
          mirror: mirror2,
          blockClass,
          blockSelector,
          unblockSelector,
          maskAllText,
          maskTextClass,
          unmaskTextClass,
          maskTextSelector,
          unmaskTextSelector,
          skipChild: false,
          inlineStylesheet,
          maskInputOptions,
          maskAttributeFn,
          maskTextFn,
          maskInputFn,
          slimDOMOptions,
          dataURLOptions,
          inlineImages,
          recordCanvas,
          preserveWhiteSpace,
          onSerialize,
          onIframeLoad,
          iframeLoadTimeout,
          onStylesheetLoad,
          stylesheetLoadTimeout,
          keepIframeSrcFn
        });
        if (serializedIframeNode) {
          onIframeLoad(n2, serializedIframeNode);
        }
      }
    }, iframeLoadTimeout);
  }
  if (serializedNode.type === NodeType$3.Element && serializedNode.tagName === "link" && typeof serializedNode.attributes.rel === "string" && (serializedNode.attributes.rel === "stylesheet" || serializedNode.attributes.rel === "preload" && typeof serializedNode.attributes.href === "string" && extractFileExtension(serializedNode.attributes.href) === "css")) {
    onceStylesheetLoaded(n2, () => {
      if (onStylesheetLoad) {
        const serializedLinkNode = serializeNodeWithId(n2, {
          doc: doc2,
          mirror: mirror2,
          blockClass,
          blockSelector,
          unblockSelector,
          maskAllText,
          maskTextClass,
          unmaskTextClass,
          maskTextSelector,
          unmaskTextSelector,
          skipChild: false,
          inlineStylesheet,
          maskInputOptions,
          maskAttributeFn,
          maskTextFn,
          maskInputFn,
          slimDOMOptions,
          dataURLOptions,
          inlineImages,
          recordCanvas,
          preserveWhiteSpace,
          onSerialize,
          onIframeLoad,
          iframeLoadTimeout,
          onStylesheetLoad,
          stylesheetLoadTimeout,
          keepIframeSrcFn
        });
        if (serializedLinkNode) {
          onStylesheetLoad(n2, serializedLinkNode);
        }
      }
    }, stylesheetLoadTimeout);
  }
  return serializedNode;
}
__name(serializeNodeWithId, "serializeNodeWithId");
function snapshot(n2, options2) {
  const { mirror: mirror2 = new Mirror(), blockClass = "rr-block", blockSelector = null, unblockSelector = null, maskAllText = false, maskTextClass = "rr-mask", unmaskTextClass = null, maskTextSelector = null, unmaskTextSelector = null, inlineStylesheet = true, inlineImages = false, recordCanvas = false, maskAllInputs = false, maskAttributeFn, maskTextFn, maskInputFn, slimDOM = false, dataURLOptions, preserveWhiteSpace, onSerialize, onIframeLoad, iframeLoadTimeout, onStylesheetLoad, stylesheetLoadTimeout, keepIframeSrcFn = /* @__PURE__ */ __name(() => false, "keepIframeSrcFn") } = options2 || {};
  const maskInputOptions = maskAllInputs === true ? {
    color: true,
    date: true,
    "datetime-local": true,
    email: true,
    month: true,
    number: true,
    range: true,
    search: true,
    tel: true,
    text: true,
    time: true,
    url: true,
    week: true,
    textarea: true,
    select: true
  } : maskAllInputs === false ? {} : maskAllInputs;
  const slimDOMOptions = slimDOM === true || slimDOM === "all" ? {
    script: true,
    comment: true,
    headFavicon: true,
    headWhitespace: true,
    headMetaDescKeywords: slimDOM === "all",
    headMetaSocial: true,
    headMetaRobots: true,
    headMetaHttpEquiv: true,
    headMetaAuthorship: true,
    headMetaVerification: true
  } : slimDOM === false ? {} : slimDOM;
  return serializeNodeWithId(n2, {
    doc: n2,
    mirror: mirror2,
    blockClass,
    blockSelector,
    unblockSelector,
    maskAllText,
    maskTextClass,
    unmaskTextClass,
    maskTextSelector,
    unmaskTextSelector,
    skipChild: false,
    inlineStylesheet,
    maskInputOptions,
    maskAttributeFn,
    maskTextFn,
    maskInputFn,
    slimDOMOptions,
    dataURLOptions,
    inlineImages,
    recordCanvas,
    preserveWhiteSpace,
    onSerialize,
    onIframeLoad,
    iframeLoadTimeout,
    onStylesheetLoad,
    stylesheetLoadTimeout,
    keepIframeSrcFn,
    newlyAddedElement: false
  });
}
__name(snapshot, "snapshot");
function _optionalChain$4(ops2) {
  let lastAccessLHS = void 0;
  let value = ops2[0];
  let i2 = 1;
  while (i2 < ops2.length) {
    const op = ops2[i2];
    const fn = ops2[i2 + 1];
    i2 += 2;
    if ((op === "optionalAccess" || op === "optionalCall") && value == null) {
      return void 0;
    }
    if (op === "access" || op === "optionalAccess") {
      lastAccessLHS = value;
      value = fn(value);
    } else if (op === "call" || op === "optionalCall") {
      value = fn((...args) => value.call(lastAccessLHS, ...args));
      lastAccessLHS = void 0;
    }
  }
  return value;
}
__name(_optionalChain$4, "_optionalChain$4");
function on$1(type, fn, target = document) {
  const options2 = { capture: true, passive: true };
  target.addEventListener(type, fn, options2);
  return () => target.removeEventListener(type, fn, options2);
}
__name(on$1, "on$1");
const DEPARTED_MIRROR_ACCESS_WARNING$1 = "Please stop import mirror directly. Instead of that,\r\nnow you can use replayer.getMirror() to access the mirror instance of a replayer,\r\nor you can use record.mirror to access the mirror instance during recording.";
let _mirror$1 = {
  map: {},
  getId() {
    console.error(DEPARTED_MIRROR_ACCESS_WARNING$1);
    return -1;
  },
  getNode() {
    console.error(DEPARTED_MIRROR_ACCESS_WARNING$1);
    return null;
  },
  removeNodeFromMap() {
    console.error(DEPARTED_MIRROR_ACCESS_WARNING$1);
  },
  has() {
    console.error(DEPARTED_MIRROR_ACCESS_WARNING$1);
    return false;
  },
  reset() {
    console.error(DEPARTED_MIRROR_ACCESS_WARNING$1);
  }
};
if (typeof window !== "undefined" && window.Proxy && window.Reflect) {
  _mirror$1 = new Proxy(_mirror$1, {
    get(target, prop2, receiver) {
      if (prop2 === "map") {
        console.error(DEPARTED_MIRROR_ACCESS_WARNING$1);
      }
      return Reflect.get(target, prop2, receiver);
    }
  });
}
function throttle$1(func, wait, options2 = {}) {
  let timeout = null;
  let previous = 0;
  return function(...args) {
    const now2 = Date.now();
    if (!previous && options2.leading === false) {
      previous = now2;
    }
    const remaining = wait - (now2 - previous);
    const context = this;
    if (remaining <= 0 || remaining > wait) {
      if (timeout) {
        clearTimeout$1(timeout);
        timeout = null;
      }
      previous = now2;
      func.apply(context, args);
    } else if (!timeout && options2.trailing !== false) {
      timeout = setTimeout$1$1(() => {
        previous = options2.leading === false ? 0 : Date.now();
        timeout = null;
        func.apply(context, args);
      }, remaining);
    }
  };
}
__name(throttle$1, "throttle$1");
function hookSetter$1(target, key, d2, isRevoked, win = window) {
  const original = win.Object.getOwnPropertyDescriptor(target, key);
  win.Object.defineProperty(target, key, isRevoked ? d2 : {
    set(value) {
      setTimeout$1$1(() => {
        d2.set.call(this, value);
      }, 0);
      if (original && original.set) {
        original.set.call(this, value);
      }
    }
  });
  return () => hookSetter$1(target, key, original || {}, true);
}
__name(hookSetter$1, "hookSetter$1");
function patch$2(source, name2, replacement) {
  try {
    if (!(name2 in source)) {
      return () => {
      };
    }
    const original = source[name2];
    const wrapped = replacement(original);
    if (typeof wrapped === "function") {
      wrapped.prototype = wrapped.prototype || {};
      Object.defineProperties(wrapped, {
        __rrweb_original__: {
          enumerable: false,
          value: original
        }
      });
    }
    source[name2] = wrapped;
    return () => {
      source[name2] = original;
    };
  } catch (e2) {
    return () => {
    };
  }
}
__name(patch$2, "patch$2");
let nowTimestamp = Date.now;
if (!/[1-9][0-9]{12}/.test(Date.now().toString())) {
  nowTimestamp = /* @__PURE__ */ __name(() => (/* @__PURE__ */ new Date()).getTime(), "nowTimestamp");
}
function getWindowScroll(win) {
  const doc2 = win.document;
  return {
    left: doc2.scrollingElement ? doc2.scrollingElement.scrollLeft : win.pageXOffset !== void 0 ? win.pageXOffset : _optionalChain$4([doc2, "optionalAccess", (_2) => _2.documentElement, "access", (_2) => _2.scrollLeft]) || _optionalChain$4([doc2, "optionalAccess", (_3) => _3.body, "optionalAccess", (_4) => _4.parentElement, "optionalAccess", (_5) => _5.scrollLeft]) || _optionalChain$4([doc2, "optionalAccess", (_6) => _6.body, "optionalAccess", (_7) => _7.scrollLeft]) || 0,
    top: doc2.scrollingElement ? doc2.scrollingElement.scrollTop : win.pageYOffset !== void 0 ? win.pageYOffset : _optionalChain$4([doc2, "optionalAccess", (_8) => _8.documentElement, "access", (_9) => _9.scrollTop]) || _optionalChain$4([doc2, "optionalAccess", (_10) => _10.body, "optionalAccess", (_11) => _11.parentElement, "optionalAccess", (_12) => _12.scrollTop]) || _optionalChain$4([doc2, "optionalAccess", (_13) => _13.body, "optionalAccess", (_14) => _14.scrollTop]) || 0
  };
}
__name(getWindowScroll, "getWindowScroll");
function getWindowHeight() {
  return window.innerHeight || document.documentElement && document.documentElement.clientHeight || document.body && document.body.clientHeight;
}
__name(getWindowHeight, "getWindowHeight");
function getWindowWidth() {
  return window.innerWidth || document.documentElement && document.documentElement.clientWidth || document.body && document.body.clientWidth;
}
__name(getWindowWidth, "getWindowWidth");
function closestElementOfNode$1(node2) {
  if (!node2) {
    return null;
  }
  const el = node2.nodeType === node2.ELEMENT_NODE ? node2 : node2.parentElement;
  return el;
}
__name(closestElementOfNode$1, "closestElementOfNode$1");
function isBlocked$1(node2, blockClass, blockSelector, unblockSelector, checkAncestors) {
  if (!node2) {
    return false;
  }
  const el = closestElementOfNode$1(node2);
  if (!el) {
    return false;
  }
  const blockedPredicate = createMatchPredicate$1(blockClass, blockSelector);
  if (!checkAncestors) {
    const isUnblocked = unblockSelector && el.matches(unblockSelector);
    return blockedPredicate(el) && !isUnblocked;
  }
  const blockDistance = distanceToMatch$1(el, blockedPredicate);
  let unblockDistance = -1;
  if (blockDistance < 0) {
    return false;
  }
  if (unblockSelector) {
    unblockDistance = distanceToMatch$1(el, createMatchPredicate$1(null, unblockSelector));
  }
  if (blockDistance > -1 && unblockDistance < 0) {
    return true;
  }
  return blockDistance < unblockDistance;
}
__name(isBlocked$1, "isBlocked$1");
function isSerialized(n2, mirror2) {
  return mirror2.getId(n2) !== -1;
}
__name(isSerialized, "isSerialized");
function isIgnored(n2, mirror2) {
  return mirror2.getId(n2) === IGNORED_NODE;
}
__name(isIgnored, "isIgnored");
function isAncestorRemoved(target, mirror2) {
  if (isShadowRoot(target)) {
    return false;
  }
  const id2 = mirror2.getId(target);
  if (!mirror2.has(id2)) {
    return true;
  }
  if (target.parentNode && target.parentNode.nodeType === target.DOCUMENT_NODE) {
    return false;
  }
  if (!target.parentNode) {
    return true;
  }
  return isAncestorRemoved(target.parentNode, mirror2);
}
__name(isAncestorRemoved, "isAncestorRemoved");
function legacy_isTouchEvent(event) {
  return Boolean(event.changedTouches);
}
__name(legacy_isTouchEvent, "legacy_isTouchEvent");
function polyfill(win = window) {
  if ("NodeList" in win && !win.NodeList.prototype.forEach) {
    win.NodeList.prototype.forEach = Array.prototype.forEach;
  }
  if ("DOMTokenList" in win && !win.DOMTokenList.prototype.forEach) {
    win.DOMTokenList.prototype.forEach = Array.prototype.forEach;
  }
  if (!Node.prototype.contains) {
    Node.prototype.contains = (...args) => {
      let node2 = args[0];
      if (!(0 in args)) {
        throw new TypeError("1 argument is required");
      }
      do {
        if (this === node2) {
          return true;
        }
      } while (node2 = node2 && node2.parentNode);
      return false;
    };
  }
}
__name(polyfill, "polyfill");
function isSerializedIframe(n2, mirror2) {
  return Boolean(n2.nodeName === "IFRAME" && mirror2.getMeta(n2));
}
__name(isSerializedIframe, "isSerializedIframe");
function isSerializedStylesheet(n2, mirror2) {
  return Boolean(n2.nodeName === "LINK" && n2.nodeType === n2.ELEMENT_NODE && n2.getAttribute && n2.getAttribute("rel") === "stylesheet" && mirror2.getMeta(n2));
}
__name(isSerializedStylesheet, "isSerializedStylesheet");
function hasShadowRoot(n2) {
  return Boolean(_optionalChain$4([n2, "optionalAccess", (_18) => _18.shadowRoot]));
}
__name(hasShadowRoot, "hasShadowRoot");
class StyleSheetMirror {
  static {
    __name(this, "StyleSheetMirror");
  }
  constructor() {
    this.id = 1;
    this.styleIDMap = /* @__PURE__ */ new WeakMap();
    this.idStyleMap = /* @__PURE__ */ new Map();
  }
  getId(stylesheet) {
    return _nullishCoalesce(this.styleIDMap.get(stylesheet), () => -1);
  }
  has(stylesheet) {
    return this.styleIDMap.has(stylesheet);
  }
  add(stylesheet, id2) {
    if (this.has(stylesheet))
      return this.getId(stylesheet);
    let newId;
    if (id2 === void 0) {
      newId = this.id++;
    } else
      newId = id2;
    this.styleIDMap.set(stylesheet, newId);
    this.idStyleMap.set(newId, stylesheet);
    return newId;
  }
  getStyle(id2) {
    return this.idStyleMap.get(id2) || null;
  }
  reset() {
    this.styleIDMap = /* @__PURE__ */ new WeakMap();
    this.idStyleMap = /* @__PURE__ */ new Map();
    this.id = 1;
  }
  generateId() {
    return this.id++;
  }
}
function getShadowHost(n2) {
  let shadowHost = null;
  if (_optionalChain$4([n2, "access", (_19) => _19.getRootNode, "optionalCall", (_20) => _20(), "optionalAccess", (_21) => _21.nodeType]) === Node.DOCUMENT_FRAGMENT_NODE && n2.getRootNode().host)
    shadowHost = n2.getRootNode().host;
  return shadowHost;
}
__name(getShadowHost, "getShadowHost");
function getRootShadowHost(n2) {
  let rootShadowHost = n2;
  let shadowHost;
  while (shadowHost = getShadowHost(rootShadowHost))
    rootShadowHost = shadowHost;
  return rootShadowHost;
}
__name(getRootShadowHost, "getRootShadowHost");
function shadowHostInDom(n2) {
  const doc2 = n2.ownerDocument;
  if (!doc2)
    return false;
  const shadowHost = getRootShadowHost(n2);
  return doc2.contains(shadowHost);
}
__name(shadowHostInDom, "shadowHostInDom");
function inDom(n2) {
  const doc2 = n2.ownerDocument;
  if (!doc2)
    return false;
  return doc2.contains(n2) || shadowHostInDom(n2);
}
__name(inDom, "inDom");
const cachedImplementations$2 = {};
function getImplementation$2(name2) {
  const cached = cachedImplementations$2[name2];
  if (cached) {
    return cached;
  }
  const document2 = window.document;
  let impl = window[name2];
  if (document2 && typeof document2.createElement === "function") {
    try {
      const sandbox = document2.createElement("iframe");
      sandbox.hidden = true;
      document2.head.appendChild(sandbox);
      const contentWindow = sandbox.contentWindow;
      if (contentWindow && contentWindow[name2]) {
        impl = contentWindow[name2];
      }
      document2.head.removeChild(sandbox);
    } catch (e2) {
    }
  }
  return cachedImplementations$2[name2] = impl.bind(window);
}
__name(getImplementation$2, "getImplementation$2");
function onRequestAnimationFrame$1(...rest) {
  return getImplementation$2("requestAnimationFrame")(...rest);
}
__name(onRequestAnimationFrame$1, "onRequestAnimationFrame$1");
function setTimeout$1$1(...rest) {
  return getImplementation$2("setTimeout")(...rest);
}
__name(setTimeout$1$1, "setTimeout$1$1");
function clearTimeout$1(...rest) {
  return getImplementation$2("clearTimeout")(...rest);
}
__name(clearTimeout$1, "clearTimeout$1");
var EventType$1 = /* @__PURE__ */ ((EventType2) => {
  EventType2[EventType2["DomContentLoaded"] = 0] = "DomContentLoaded";
  EventType2[EventType2["Load"] = 1] = "Load";
  EventType2[EventType2["FullSnapshot"] = 2] = "FullSnapshot";
  EventType2[EventType2["IncrementalSnapshot"] = 3] = "IncrementalSnapshot";
  EventType2[EventType2["Meta"] = 4] = "Meta";
  EventType2[EventType2["Custom"] = 5] = "Custom";
  EventType2[EventType2["Plugin"] = 6] = "Plugin";
  return EventType2;
})(EventType$1 || {});
var IncrementalSource = /* @__PURE__ */ ((IncrementalSource2) => {
  IncrementalSource2[IncrementalSource2["Mutation"] = 0] = "Mutation";
  IncrementalSource2[IncrementalSource2["MouseMove"] = 1] = "MouseMove";
  IncrementalSource2[IncrementalSource2["MouseInteraction"] = 2] = "MouseInteraction";
  IncrementalSource2[IncrementalSource2["Scroll"] = 3] = "Scroll";
  IncrementalSource2[IncrementalSource2["ViewportResize"] = 4] = "ViewportResize";
  IncrementalSource2[IncrementalSource2["Input"] = 5] = "Input";
  IncrementalSource2[IncrementalSource2["TouchMove"] = 6] = "TouchMove";
  IncrementalSource2[IncrementalSource2["MediaInteraction"] = 7] = "MediaInteraction";
  IncrementalSource2[IncrementalSource2["StyleSheetRule"] = 8] = "StyleSheetRule";
  IncrementalSource2[IncrementalSource2["CanvasMutation"] = 9] = "CanvasMutation";
  IncrementalSource2[IncrementalSource2["Font"] = 10] = "Font";
  IncrementalSource2[IncrementalSource2["Log"] = 11] = "Log";
  IncrementalSource2[IncrementalSource2["Drag"] = 12] = "Drag";
  IncrementalSource2[IncrementalSource2["StyleDeclaration"] = 13] = "StyleDeclaration";
  IncrementalSource2[IncrementalSource2["Selection"] = 14] = "Selection";
  IncrementalSource2[IncrementalSource2["AdoptedStyleSheet"] = 15] = "AdoptedStyleSheet";
  IncrementalSource2[IncrementalSource2["CustomElement"] = 16] = "CustomElement";
  return IncrementalSource2;
})(IncrementalSource || {});
var MouseInteractions = /* @__PURE__ */ ((MouseInteractions2) => {
  MouseInteractions2[MouseInteractions2["MouseUp"] = 0] = "MouseUp";
  MouseInteractions2[MouseInteractions2["MouseDown"] = 1] = "MouseDown";
  MouseInteractions2[MouseInteractions2["Click"] = 2] = "Click";
  MouseInteractions2[MouseInteractions2["ContextMenu"] = 3] = "ContextMenu";
  MouseInteractions2[MouseInteractions2["DblClick"] = 4] = "DblClick";
  MouseInteractions2[MouseInteractions2["Focus"] = 5] = "Focus";
  MouseInteractions2[MouseInteractions2["Blur"] = 6] = "Blur";
  MouseInteractions2[MouseInteractions2["TouchStart"] = 7] = "TouchStart";
  MouseInteractions2[MouseInteractions2["TouchMove_Departed"] = 8] = "TouchMove_Departed";
  MouseInteractions2[MouseInteractions2["TouchEnd"] = 9] = "TouchEnd";
  MouseInteractions2[MouseInteractions2["TouchCancel"] = 10] = "TouchCancel";
  return MouseInteractions2;
})(MouseInteractions || {});
var PointerTypes = /* @__PURE__ */ ((PointerTypes2) => {
  PointerTypes2[PointerTypes2["Mouse"] = 0] = "Mouse";
  PointerTypes2[PointerTypes2["Pen"] = 1] = "Pen";
  PointerTypes2[PointerTypes2["Touch"] = 2] = "Touch";
  return PointerTypes2;
})(PointerTypes || {});
var NodeType$1$1;
(function(NodeType3) {
  NodeType3[NodeType3["Document"] = 0] = "Document";
  NodeType3[NodeType3["DocumentType"] = 1] = "DocumentType";
  NodeType3[NodeType3["Element"] = 2] = "Element";
  NodeType3[NodeType3["Text"] = 3] = "Text";
  NodeType3[NodeType3["CDATA"] = 4] = "CDATA";
  NodeType3[NodeType3["Comment"] = 5] = "Comment";
})(NodeType$1$1 || (NodeType$1$1 = {}));
var NodeType$2$1;
(function(NodeType3) {
  NodeType3[NodeType3["PLACEHOLDER"] = 0] = "PLACEHOLDER";
  NodeType3[NodeType3["ELEMENT_NODE"] = 1] = "ELEMENT_NODE";
  NodeType3[NodeType3["ATTRIBUTE_NODE"] = 2] = "ATTRIBUTE_NODE";
  NodeType3[NodeType3["TEXT_NODE"] = 3] = "TEXT_NODE";
  NodeType3[NodeType3["CDATA_SECTION_NODE"] = 4] = "CDATA_SECTION_NODE";
  NodeType3[NodeType3["ENTITY_REFERENCE_NODE"] = 5] = "ENTITY_REFERENCE_NODE";
  NodeType3[NodeType3["ENTITY_NODE"] = 6] = "ENTITY_NODE";
  NodeType3[NodeType3["PROCESSING_INSTRUCTION_NODE"] = 7] = "PROCESSING_INSTRUCTION_NODE";
  NodeType3[NodeType3["COMMENT_NODE"] = 8] = "COMMENT_NODE";
  NodeType3[NodeType3["DOCUMENT_NODE"] = 9] = "DOCUMENT_NODE";
  NodeType3[NodeType3["DOCUMENT_TYPE_NODE"] = 10] = "DOCUMENT_TYPE_NODE";
  NodeType3[NodeType3["DOCUMENT_FRAGMENT_NODE"] = 11] = "DOCUMENT_FRAGMENT_NODE";
})(NodeType$2$1 || (NodeType$2$1 = {}));
function getIFrameContentDocument(iframe) {
  try {
    return iframe.contentDocument;
  } catch (e2) {
  }
}
__name(getIFrameContentDocument, "getIFrameContentDocument");
function getIFrameContentWindow(iframe) {
  try {
    return iframe.contentWindow;
  } catch (e2) {
  }
}
__name(getIFrameContentWindow, "getIFrameContentWindow");
function _optionalChain$3(ops2) {
  let lastAccessLHS = void 0;
  let value = ops2[0];
  let i2 = 1;
  while (i2 < ops2.length) {
    const op = ops2[i2];
    const fn = ops2[i2 + 1];
    i2 += 2;
    if ((op === "optionalAccess" || op === "optionalCall") && value == null) {
      return void 0;
    }
    if (op === "access" || op === "optionalAccess") {
      lastAccessLHS = value;
      value = fn(value);
    } else if (op === "call" || op === "optionalCall") {
      value = fn((...args) => value.call(lastAccessLHS, ...args));
      lastAccessLHS = void 0;
    }
  }
  return value;
}
__name(_optionalChain$3, "_optionalChain$3");
function isNodeInLinkedList(n2) {
  return "__ln" in n2;
}
__name(isNodeInLinkedList, "isNodeInLinkedList");
class DoubleLinkedList {
  static {
    __name(this, "DoubleLinkedList");
  }
  constructor() {
    this.length = 0;
    this.head = null;
    this.tail = null;
  }
  get(position) {
    if (position >= this.length) {
      throw new Error("Position outside of list range");
    }
    let current = this.head;
    for (let index2 = 0; index2 < position; index2++) {
      current = _optionalChain$3([current, "optionalAccess", (_2) => _2.next]) || null;
    }
    return current;
  }
  addNode(n2) {
    const node2 = {
      value: n2,
      previous: null,
      next: null
    };
    n2.__ln = node2;
    if (n2.previousSibling && isNodeInLinkedList(n2.previousSibling)) {
      const current = n2.previousSibling.__ln.next;
      node2.next = current;
      node2.previous = n2.previousSibling.__ln;
      n2.previousSibling.__ln.next = node2;
      if (current) {
        current.previous = node2;
      }
    } else if (n2.nextSibling && isNodeInLinkedList(n2.nextSibling) && n2.nextSibling.__ln.previous) {
      const current = n2.nextSibling.__ln.previous;
      node2.previous = current;
      node2.next = n2.nextSibling.__ln;
      n2.nextSibling.__ln.previous = node2;
      if (current) {
        current.next = node2;
      }
    } else {
      if (this.head) {
        this.head.previous = node2;
      }
      node2.next = this.head;
      this.head = node2;
    }
    if (node2.next === null) {
      this.tail = node2;
    }
    this.length++;
  }
  removeNode(n2) {
    const current = n2.__ln;
    if (!this.head) {
      return;
    }
    if (!current.previous) {
      this.head = current.next;
      if (this.head) {
        this.head.previous = null;
      } else {
        this.tail = null;
      }
    } else {
      current.previous.next = current.next;
      if (current.next) {
        current.next.previous = current.previous;
      } else {
        this.tail = current.previous;
      }
    }
    if (n2.__ln) {
      delete n2.__ln;
    }
    this.length--;
  }
}
const moveKey = /* @__PURE__ */ __name((id2, parentId) => `${id2}@${parentId}`, "moveKey");
class MutationBuffer {
  static {
    __name(this, "MutationBuffer");
  }
  constructor() {
    this.frozen = false;
    this.locked = false;
    this.texts = [];
    this.attributes = [];
    this.attributeMap = /* @__PURE__ */ new WeakMap();
    this.removes = [];
    this.mapRemoves = [];
    this.movedMap = {};
    this.addedSet = /* @__PURE__ */ new Set();
    this.movedSet = /* @__PURE__ */ new Set();
    this.droppedSet = /* @__PURE__ */ new Set();
    this.processMutations = (mutations) => {
      mutations.forEach(this.processMutation);
      this.emit();
    };
    this.emit = () => {
      if (this.frozen || this.locked) {
        return;
      }
      const adds = [];
      const addedIds = /* @__PURE__ */ new Set();
      const addList = new DoubleLinkedList();
      const getNextId = /* @__PURE__ */ __name((n2) => {
        let ns = n2;
        let nextId = IGNORED_NODE;
        while (nextId === IGNORED_NODE) {
          ns = ns && ns.nextSibling;
          nextId = ns && this.mirror.getId(ns);
        }
        return nextId;
      }, "getNextId");
      const pushAdd = /* @__PURE__ */ __name((n2) => {
        if (!n2.parentNode || !inDom(n2)) {
          return;
        }
        const parentId = isShadowRoot(n2.parentNode) ? this.mirror.getId(getShadowHost(n2)) : this.mirror.getId(n2.parentNode);
        const nextId = getNextId(n2);
        if (parentId === -1 || nextId === -1) {
          return addList.addNode(n2);
        }
        const sn2 = serializeNodeWithId(n2, {
          doc: this.doc,
          mirror: this.mirror,
          blockClass: this.blockClass,
          blockSelector: this.blockSelector,
          maskAllText: this.maskAllText,
          unblockSelector: this.unblockSelector,
          maskTextClass: this.maskTextClass,
          unmaskTextClass: this.unmaskTextClass,
          maskTextSelector: this.maskTextSelector,
          unmaskTextSelector: this.unmaskTextSelector,
          skipChild: true,
          newlyAddedElement: true,
          inlineStylesheet: this.inlineStylesheet,
          maskInputOptions: this.maskInputOptions,
          maskAttributeFn: this.maskAttributeFn,
          maskTextFn: this.maskTextFn,
          maskInputFn: this.maskInputFn,
          slimDOMOptions: this.slimDOMOptions,
          dataURLOptions: this.dataURLOptions,
          recordCanvas: this.recordCanvas,
          inlineImages: this.inlineImages,
          onSerialize: /* @__PURE__ */ __name((currentN) => {
            if (isSerializedIframe(currentN, this.mirror) && !isBlocked$1(currentN, this.blockClass, this.blockSelector, this.unblockSelector, false)) {
              this.iframeManager.addIframe(currentN);
            }
            if (isSerializedStylesheet(currentN, this.mirror)) {
              this.stylesheetManager.trackLinkElement(currentN);
            }
            if (hasShadowRoot(n2)) {
              this.shadowDomManager.addShadowRoot(n2.shadowRoot, this.doc);
            }
          }, "onSerialize"),
          onIframeLoad: /* @__PURE__ */ __name((iframe, childSn) => {
            if (isBlocked$1(iframe, this.blockClass, this.blockSelector, this.unblockSelector, false)) {
              return;
            }
            this.iframeManager.attachIframe(iframe, childSn);
            if (iframe.contentWindow) {
              this.canvasManager.addWindow(iframe.contentWindow);
            }
            this.shadowDomManager.observeAttachShadow(iframe);
          }, "onIframeLoad"),
          onStylesheetLoad: /* @__PURE__ */ __name((link2, childSn) => {
            this.stylesheetManager.attachLinkElement(link2, childSn);
          }, "onStylesheetLoad")
        });
        if (sn2) {
          adds.push({
            parentId,
            nextId,
            node: sn2
          });
          addedIds.add(sn2.id);
        }
      }, "pushAdd");
      while (this.mapRemoves.length) {
        this.mirror.removeNodeFromMap(this.mapRemoves.shift());
      }
      for (const n2 of this.movedSet) {
        if (isParentRemoved(this.removes, n2, this.mirror) && !this.movedSet.has(n2.parentNode)) {
          continue;
        }
        pushAdd(n2);
      }
      for (const n2 of this.addedSet) {
        if (!isAncestorInSet(this.droppedSet, n2) && !isParentRemoved(this.removes, n2, this.mirror)) {
          pushAdd(n2);
        } else if (isAncestorInSet(this.movedSet, n2)) {
          pushAdd(n2);
        } else {
          this.droppedSet.add(n2);
        }
      }
      let candidate = null;
      while (addList.length) {
        let node2 = null;
        if (candidate) {
          const parentId = this.mirror.getId(candidate.value.parentNode);
          const nextId = getNextId(candidate.value);
          if (parentId !== -1 && nextId !== -1) {
            node2 = candidate;
          }
        }
        if (!node2) {
          let tailNode = addList.tail;
          while (tailNode) {
            const _node = tailNode;
            tailNode = tailNode.previous;
            if (_node) {
              const parentId = this.mirror.getId(_node.value.parentNode);
              const nextId = getNextId(_node.value);
              if (nextId === -1)
                continue;
              else if (parentId !== -1) {
                node2 = _node;
                break;
              } else {
                const unhandledNode = _node.value;
                if (unhandledNode.parentNode && unhandledNode.parentNode.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
                  const shadowHost = unhandledNode.parentNode.host;
                  const parentId2 = this.mirror.getId(shadowHost);
                  if (parentId2 !== -1) {
                    node2 = _node;
                    break;
                  }
                }
              }
            }
          }
        }
        if (!node2) {
          while (addList.head) {
            addList.removeNode(addList.head.value);
          }
          break;
        }
        candidate = node2.previous;
        addList.removeNode(node2.value);
        pushAdd(node2.value);
      }
      const payload = {
        texts: this.texts.map((text2) => ({
          id: this.mirror.getId(text2.node),
          value: text2.value
        })).filter((text2) => !addedIds.has(text2.id)).filter((text2) => this.mirror.has(text2.id)),
        attributes: this.attributes.map((attribute2) => {
          const { attributes } = attribute2;
          if (typeof attributes.style === "string") {
            const diffAsStr = JSON.stringify(attribute2.styleDiff);
            const unchangedAsStr = JSON.stringify(attribute2._unchangedStyles);
            if (diffAsStr.length < attributes.style.length) {
              if ((diffAsStr + unchangedAsStr).split("var(").length === attributes.style.split("var(").length) {
                attributes.style = attribute2.styleDiff;
              }
            }
          }
          return {
            id: this.mirror.getId(attribute2.node),
            attributes
          };
        }).filter((attribute2) => !addedIds.has(attribute2.id)).filter((attribute2) => this.mirror.has(attribute2.id)),
        removes: this.removes,
        adds
      };
      if (!payload.texts.length && !payload.attributes.length && !payload.removes.length && !payload.adds.length) {
        return;
      }
      this.texts = [];
      this.attributes = [];
      this.attributeMap = /* @__PURE__ */ new WeakMap();
      this.removes = [];
      this.addedSet = /* @__PURE__ */ new Set();
      this.movedSet = /* @__PURE__ */ new Set();
      this.droppedSet = /* @__PURE__ */ new Set();
      this.movedMap = {};
      this.mutationCb(payload);
    };
    this.processMutation = (m2) => {
      if (isIgnored(m2.target, this.mirror)) {
        return;
      }
      switch (m2.type) {
        case "characterData": {
          const value = m2.target.textContent;
          if (!isBlocked$1(m2.target, this.blockClass, this.blockSelector, this.unblockSelector, false) && value !== m2.oldValue) {
            this.texts.push({
              value: needMaskingText(m2.target, this.maskTextClass, this.maskTextSelector, this.unmaskTextClass, this.unmaskTextSelector, this.maskAllText) && value ? this.maskTextFn ? this.maskTextFn(value, closestElementOfNode$1(m2.target)) : value.replace(/[\S]/g, "*") : value,
              node: m2.target
            });
          }
          break;
        }
        case "attributes": {
          const target = m2.target;
          let attributeName = m2.attributeName;
          let value = m2.target.getAttribute(attributeName);
          if (attributeName === "value") {
            const type = getInputType(target);
            const tagName = target.tagName;
            value = getInputValue(target, tagName, type);
            const isInputMasked = shouldMaskInput({
              maskInputOptions: this.maskInputOptions,
              tagName,
              type
            });
            const forceMask = needMaskingText(m2.target, this.maskTextClass, this.maskTextSelector, this.unmaskTextClass, this.unmaskTextSelector, isInputMasked);
            value = maskInputValue({
              isMasked: forceMask,
              element: target,
              value,
              maskInputFn: this.maskInputFn
            });
          }
          if (isBlocked$1(m2.target, this.blockClass, this.blockSelector, this.unblockSelector, false) || value === m2.oldValue) {
            return;
          }
          let item = this.attributeMap.get(m2.target);
          if (target.tagName === "IFRAME" && attributeName === "src" && !this.keepIframeSrcFn(value)) {
            const iframeDoc = getIFrameContentDocument(target);
            if (!iframeDoc) {
              attributeName = "rr_src";
            } else {
              return;
            }
          }
          if (!item) {
            item = {
              node: m2.target,
              attributes: {},
              styleDiff: {},
              _unchangedStyles: {}
            };
            this.attributes.push(item);
            this.attributeMap.set(m2.target, item);
          }
          if (attributeName === "type" && target.tagName === "INPUT" && (m2.oldValue || "").toLowerCase() === "password") {
            target.setAttribute("data-rr-is-password", "true");
          }
          if (!ignoreAttribute(target.tagName, attributeName)) {
            item.attributes[attributeName] = transformAttribute(this.doc, toLowerCase(target.tagName), toLowerCase(attributeName), value, target, this.maskAttributeFn);
            if (attributeName === "style") {
              if (!this.unattachedDoc) {
                try {
                  this.unattachedDoc = document.implementation.createHTMLDocument();
                } catch (e2) {
                  this.unattachedDoc = this.doc;
                }
              }
              const old = this.unattachedDoc.createElement("span");
              if (m2.oldValue) {
                old.setAttribute("style", m2.oldValue);
              }
              for (const pname of Array.from(target.style)) {
                const newValue2 = target.style.getPropertyValue(pname);
                const newPriority = target.style.getPropertyPriority(pname);
                if (newValue2 !== old.style.getPropertyValue(pname) || newPriority !== old.style.getPropertyPriority(pname)) {
                  if (newPriority === "") {
                    item.styleDiff[pname] = newValue2;
                  } else {
                    item.styleDiff[pname] = [newValue2, newPriority];
                  }
                } else {
                  item._unchangedStyles[pname] = [newValue2, newPriority];
                }
              }
              for (const pname of Array.from(old.style)) {
                if (target.style.getPropertyValue(pname) === "") {
                  item.styleDiff[pname] = false;
                }
              }
            }
          }
          break;
        }
        case "childList": {
          if (isBlocked$1(m2.target, this.blockClass, this.blockSelector, this.unblockSelector, true)) {
            return;
          }
          m2.addedNodes.forEach((n2) => this.genAdds(n2, m2.target));
          m2.removedNodes.forEach((n2) => {
            const nodeId = this.mirror.getId(n2);
            const parentId = isShadowRoot(m2.target) ? this.mirror.getId(m2.target.host) : this.mirror.getId(m2.target);
            if (isBlocked$1(m2.target, this.blockClass, this.blockSelector, this.unblockSelector, false) || isIgnored(n2, this.mirror) || !isSerialized(n2, this.mirror)) {
              return;
            }
            if (this.addedSet.has(n2)) {
              deepDelete(this.addedSet, n2);
              this.droppedSet.add(n2);
            } else if (this.addedSet.has(m2.target) && nodeId === -1) ;
            else if (isAncestorRemoved(m2.target, this.mirror)) ;
            else if (this.movedSet.has(n2) && this.movedMap[moveKey(nodeId, parentId)]) {
              deepDelete(this.movedSet, n2);
            } else {
              this.removes.push({
                parentId,
                id: nodeId,
                isShadow: isShadowRoot(m2.target) && isNativeShadowDom(m2.target) ? true : void 0
              });
            }
            this.mapRemoves.push(n2);
          });
          break;
        }
      }
    };
    this.genAdds = (n2, target) => {
      if (this.processedNodeManager.inOtherBuffer(n2, this))
        return;
      if (this.addedSet.has(n2) || this.movedSet.has(n2))
        return;
      if (this.mirror.hasNode(n2)) {
        if (isIgnored(n2, this.mirror)) {
          return;
        }
        this.movedSet.add(n2);
        let targetId = null;
        if (target && this.mirror.hasNode(target)) {
          targetId = this.mirror.getId(target);
        }
        if (targetId && targetId !== -1) {
          this.movedMap[moveKey(this.mirror.getId(n2), targetId)] = true;
        }
      } else {
        this.addedSet.add(n2);
        this.droppedSet.delete(n2);
      }
      if (!isBlocked$1(n2, this.blockClass, this.blockSelector, this.unblockSelector, false)) {
        n2.childNodes.forEach((childN) => this.genAdds(childN));
        if (hasShadowRoot(n2)) {
          n2.shadowRoot.childNodes.forEach((childN) => {
            this.processedNodeManager.add(childN, this);
            this.genAdds(childN, n2);
          });
        }
      }
    };
  }
  init(options2) {
    [
      "mutationCb",
      "blockClass",
      "blockSelector",
      "unblockSelector",
      "maskAllText",
      "maskTextClass",
      "unmaskTextClass",
      "maskTextSelector",
      "unmaskTextSelector",
      "inlineStylesheet",
      "maskInputOptions",
      "maskAttributeFn",
      "maskTextFn",
      "maskInputFn",
      "keepIframeSrcFn",
      "recordCanvas",
      "inlineImages",
      "slimDOMOptions",
      "dataURLOptions",
      "doc",
      "mirror",
      "iframeManager",
      "stylesheetManager",
      "shadowDomManager",
      "canvasManager",
      "processedNodeManager"
    ].forEach((key) => {
      this[key] = options2[key];
    });
  }
  freeze() {
    this.frozen = true;
    this.canvasManager.freeze();
  }
  unfreeze() {
    this.frozen = false;
    this.canvasManager.unfreeze();
    this.emit();
  }
  isFrozen() {
    return this.frozen;
  }
  lock() {
    this.locked = true;
    this.canvasManager.lock();
  }
  unlock() {
    this.locked = false;
    this.canvasManager.unlock();
    this.emit();
  }
  reset() {
    this.shadowDomManager.reset();
    this.canvasManager.reset();
  }
}
function deepDelete(addsSet, n2) {
  addsSet.delete(n2);
  n2.childNodes.forEach((childN) => deepDelete(addsSet, childN));
}
__name(deepDelete, "deepDelete");
function isParentRemoved(removes, n2, mirror2) {
  if (removes.length === 0)
    return false;
  return _isParentRemoved(removes, n2, mirror2);
}
__name(isParentRemoved, "isParentRemoved");
function _isParentRemoved(removes, n2, mirror2) {
  let node2 = n2.parentNode;
  while (node2) {
    const parentId = mirror2.getId(node2);
    if (removes.some((r2) => r2.id === parentId)) {
      return true;
    }
    node2 = node2.parentNode;
  }
  return false;
}
__name(_isParentRemoved, "_isParentRemoved");
function isAncestorInSet(set3, n2) {
  if (set3.size === 0)
    return false;
  return _isAncestorInSet(set3, n2);
}
__name(isAncestorInSet, "isAncestorInSet");
function _isAncestorInSet(set3, n2) {
  const { parentNode: parentNode2 } = n2;
  if (!parentNode2) {
    return false;
  }
  if (set3.has(parentNode2)) {
    return true;
  }
  return _isAncestorInSet(set3, parentNode2);
}
__name(_isAncestorInSet, "_isAncestorInSet");
let errorHandler$1;
function registerErrorHandler$1(handler5) {
  errorHandler$1 = handler5;
}
__name(registerErrorHandler$1, "registerErrorHandler$1");
function unregisterErrorHandler() {
  errorHandler$1 = void 0;
}
__name(unregisterErrorHandler, "unregisterErrorHandler");
const callbackWrapper$1 = /* @__PURE__ */ __name((cb) => {
  if (!errorHandler$1) {
    return cb;
  }
  const rrwebWrapped = /* @__PURE__ */ __name((...rest) => {
    try {
      return cb(...rest);
    } catch (error2) {
      if (errorHandler$1 && errorHandler$1(error2) === true) {
        return () => {
        };
      }
      throw error2;
    }
  }, "rrwebWrapped");
  return rrwebWrapped;
}, "callbackWrapper$1");
function _optionalChain$2(ops2) {
  let lastAccessLHS = void 0;
  let value = ops2[0];
  let i2 = 1;
  while (i2 < ops2.length) {
    const op = ops2[i2];
    const fn = ops2[i2 + 1];
    i2 += 2;
    if ((op === "optionalAccess" || op === "optionalCall") && value == null) {
      return void 0;
    }
    if (op === "access" || op === "optionalAccess") {
      lastAccessLHS = value;
      value = fn(value);
    } else if (op === "call" || op === "optionalCall") {
      value = fn((...args) => value.call(lastAccessLHS, ...args));
      lastAccessLHS = void 0;
    }
  }
  return value;
}
__name(_optionalChain$2, "_optionalChain$2");
const mutationBuffers = [];
function getEventTarget(event) {
  try {
    if ("composedPath" in event) {
      const path = event.composedPath();
      if (path.length) {
        return path[0];
      }
    } else if ("path" in event && event.path.length) {
      return event.path[0];
    }
  } catch (e2) {
  }
  return event && event.target;
}
__name(getEventTarget, "getEventTarget");
function initMutationObserver(options2, rootEl) {
  const mutationBuffer = new MutationBuffer();
  mutationBuffers.push(mutationBuffer);
  mutationBuffer.init(options2);
  let mutationObserverCtor = window.MutationObserver || window.__rrMutationObserver;
  const angularZoneSymbol = _optionalChain$2([window, "optionalAccess", (_2) => _2.Zone, "optionalAccess", (_2) => _2.__symbol__, "optionalCall", (_3) => _3("MutationObserver")]);
  if (angularZoneSymbol && window[angularZoneSymbol]) {
    mutationObserverCtor = window[angularZoneSymbol];
  }
  const observer = new mutationObserverCtor(callbackWrapper$1((mutations) => {
    if (options2.onMutation && options2.onMutation(mutations) === false) {
      return;
    }
    mutationBuffer.processMutations.bind(mutationBuffer)(mutations);
  }));
  observer.observe(rootEl, {
    attributes: true,
    attributeOldValue: true,
    characterData: true,
    characterDataOldValue: true,
    childList: true,
    subtree: true
  });
  return observer;
}
__name(initMutationObserver, "initMutationObserver");
function initMoveObserver({ mousemoveCb, sampling, doc: doc2, mirror: mirror2 }) {
  if (sampling.mousemove === false) {
    return () => {
    };
  }
  const threshold = typeof sampling.mousemove === "number" ? sampling.mousemove : 50;
  const callbackThreshold = typeof sampling.mousemoveCallback === "number" ? sampling.mousemoveCallback : 500;
  let positions = [];
  let timeBaseline;
  const wrappedCb = throttle$1(callbackWrapper$1((source) => {
    const totalOffset = Date.now() - timeBaseline;
    mousemoveCb(positions.map((p2) => {
      p2.timeOffset -= totalOffset;
      return p2;
    }), source);
    positions = [];
    timeBaseline = null;
  }), callbackThreshold);
  const updatePosition = callbackWrapper$1(throttle$1(callbackWrapper$1((evt) => {
    const target = getEventTarget(evt);
    const { clientX, clientY } = legacy_isTouchEvent(evt) ? evt.changedTouches[0] : evt;
    if (!timeBaseline) {
      timeBaseline = nowTimestamp();
    }
    positions.push({
      x: clientX,
      y: clientY,
      id: mirror2.getId(target),
      timeOffset: nowTimestamp() - timeBaseline
    });
    wrappedCb(typeof DragEvent !== "undefined" && evt instanceof DragEvent ? IncrementalSource.Drag : evt instanceof MouseEvent ? IncrementalSource.MouseMove : IncrementalSource.TouchMove);
  }), threshold, {
    trailing: false
  }));
  const handlers2 = [
    on$1("mousemove", updatePosition, doc2),
    on$1("touchmove", updatePosition, doc2),
    on$1("drag", updatePosition, doc2)
  ];
  return callbackWrapper$1(() => {
    handlers2.forEach((h2) => h2());
  });
}
__name(initMoveObserver, "initMoveObserver");
function initMouseInteractionObserver({ mouseInteractionCb, doc: doc2, mirror: mirror2, blockClass, blockSelector, unblockSelector, sampling }) {
  if (sampling.mouseInteraction === false) {
    return () => {
    };
  }
  const disableMap = sampling.mouseInteraction === true || sampling.mouseInteraction === void 0 ? {} : sampling.mouseInteraction;
  const handlers2 = [];
  let currentPointerType = null;
  const getHandler = /* @__PURE__ */ __name((eventKey) => {
    return (event) => {
      const target = getEventTarget(event);
      if (isBlocked$1(target, blockClass, blockSelector, unblockSelector, true)) {
        return;
      }
      let pointerType = null;
      let thisEventKey = eventKey;
      if ("pointerType" in event) {
        switch (event.pointerType) {
          case "mouse":
            pointerType = PointerTypes.Mouse;
            break;
          case "touch":
            pointerType = PointerTypes.Touch;
            break;
          case "pen":
            pointerType = PointerTypes.Pen;
            break;
        }
        if (pointerType === PointerTypes.Touch) {
          if (MouseInteractions[eventKey] === MouseInteractions.MouseDown) {
            thisEventKey = "TouchStart";
          } else if (MouseInteractions[eventKey] === MouseInteractions.MouseUp) {
            thisEventKey = "TouchEnd";
          }
        } else if (pointerType === PointerTypes.Pen) ;
      } else if (legacy_isTouchEvent(event)) {
        pointerType = PointerTypes.Touch;
      }
      if (pointerType !== null) {
        currentPointerType = pointerType;
        if (thisEventKey.startsWith("Touch") && pointerType === PointerTypes.Touch || thisEventKey.startsWith("Mouse") && pointerType === PointerTypes.Mouse) {
          pointerType = null;
        }
      } else if (MouseInteractions[eventKey] === MouseInteractions.Click) {
        pointerType = currentPointerType;
        currentPointerType = null;
      }
      const e2 = legacy_isTouchEvent(event) ? event.changedTouches[0] : event;
      if (!e2) {
        return;
      }
      const id2 = mirror2.getId(target);
      const { clientX, clientY } = e2;
      callbackWrapper$1(mouseInteractionCb)({
        type: MouseInteractions[thisEventKey],
        id: id2,
        x: clientX,
        y: clientY,
        ...pointerType !== null && { pointerType }
      });
    };
  }, "getHandler");
  Object.keys(MouseInteractions).filter((key) => Number.isNaN(Number(key)) && !key.endsWith("_Departed") && disableMap[key] !== false).forEach((eventKey) => {
    let eventName = toLowerCase(eventKey);
    const handler5 = getHandler(eventKey);
    if (window.PointerEvent) {
      switch (MouseInteractions[eventKey]) {
        case MouseInteractions.MouseDown:
        case MouseInteractions.MouseUp:
          eventName = eventName.replace("mouse", "pointer");
          break;
        case MouseInteractions.TouchStart:
        case MouseInteractions.TouchEnd:
          return;
      }
    }
    handlers2.push(on$1(eventName, handler5, doc2));
  });
  return callbackWrapper$1(() => {
    handlers2.forEach((h2) => h2());
  });
}
__name(initMouseInteractionObserver, "initMouseInteractionObserver");
function initScrollObserver({ scrollCb, doc: doc2, mirror: mirror2, blockClass, blockSelector, unblockSelector, sampling }) {
  const updatePosition = callbackWrapper$1(throttle$1(callbackWrapper$1((evt) => {
    const target = getEventTarget(evt);
    if (!target || isBlocked$1(target, blockClass, blockSelector, unblockSelector, true)) {
      return;
    }
    const id2 = mirror2.getId(target);
    if (target === doc2 && doc2.defaultView) {
      const scrollLeftTop = getWindowScroll(doc2.defaultView);
      scrollCb({
        id: id2,
        x: scrollLeftTop.left,
        y: scrollLeftTop.top
      });
    } else {
      scrollCb({
        id: id2,
        x: target.scrollLeft,
        y: target.scrollTop
      });
    }
  }), sampling.scroll || 100));
  return on$1("scroll", updatePosition, doc2);
}
__name(initScrollObserver, "initScrollObserver");
function initViewportResizeObserver({ viewportResizeCb }, { win }) {
  let lastH = -1;
  let lastW = -1;
  const updateDimension = callbackWrapper$1(throttle$1(callbackWrapper$1(() => {
    const height = getWindowHeight();
    const width2 = getWindowWidth();
    if (lastH !== height || lastW !== width2) {
      viewportResizeCb({
        width: Number(width2),
        height: Number(height)
      });
      lastH = height;
      lastW = width2;
    }
  }), 200));
  return on$1("resize", updateDimension, win);
}
__name(initViewportResizeObserver, "initViewportResizeObserver");
const INPUT_TAGS = ["INPUT", "TEXTAREA", "SELECT"];
const lastInputValueMap = /* @__PURE__ */ new WeakMap();
function initInputObserver({ inputCb, doc: doc2, mirror: mirror2, blockClass, blockSelector, unblockSelector, ignoreClass, ignoreSelector, maskInputOptions, maskInputFn, sampling, userTriggeredOnInput, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector }) {
  function eventHandler(event) {
    let target = getEventTarget(event);
    const userTriggered = event.isTrusted;
    const tagName = target && toUpperCase(target.tagName);
    if (tagName === "OPTION")
      target = target.parentElement;
    if (!target || !tagName || INPUT_TAGS.indexOf(tagName) < 0 || isBlocked$1(target, blockClass, blockSelector, unblockSelector, true)) {
      return;
    }
    const el = target;
    if (el.classList.contains(ignoreClass) || ignoreSelector && el.matches(ignoreSelector)) {
      return;
    }
    const type = getInputType(target);
    let text2 = getInputValue(el, tagName, type);
    let isChecked = false;
    const isInputMasked = shouldMaskInput({
      maskInputOptions,
      tagName,
      type
    });
    const forceMask = needMaskingText(target, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, isInputMasked);
    if (type === "radio" || type === "checkbox") {
      isChecked = target.checked;
    }
    text2 = maskInputValue({
      isMasked: forceMask,
      element: target,
      value: text2,
      maskInputFn
    });
    cbWithDedup(target, userTriggeredOnInput ? { text: text2, isChecked, userTriggered } : { text: text2, isChecked });
    const name2 = target.name;
    if (type === "radio" && name2 && isChecked) {
      doc2.querySelectorAll(`input[type="radio"][name="${name2}"]`).forEach((el2) => {
        if (el2 !== target) {
          const text3 = maskInputValue({
            isMasked: forceMask,
            element: el2,
            value: getInputValue(el2, tagName, type),
            maskInputFn
          });
          cbWithDedup(el2, userTriggeredOnInput ? { text: text3, isChecked: !isChecked, userTriggered: false } : { text: text3, isChecked: !isChecked });
        }
      });
    }
  }
  __name(eventHandler, "eventHandler");
  function cbWithDedup(target, v2) {
    const lastInputValue = lastInputValueMap.get(target);
    if (!lastInputValue || lastInputValue.text !== v2.text || lastInputValue.isChecked !== v2.isChecked) {
      lastInputValueMap.set(target, v2);
      const id2 = mirror2.getId(target);
      callbackWrapper$1(inputCb)({
        ...v2,
        id: id2
      });
    }
  }
  __name(cbWithDedup, "cbWithDedup");
  const events2 = sampling.input === "last" ? ["change"] : ["input", "change"];
  const handlers2 = events2.map((eventName) => on$1(eventName, callbackWrapper$1(eventHandler), doc2));
  const currentWindow = doc2.defaultView;
  if (!currentWindow) {
    return () => {
      handlers2.forEach((h2) => h2());
    };
  }
  const propertyDescriptor = currentWindow.Object.getOwnPropertyDescriptor(currentWindow.HTMLInputElement.prototype, "value");
  const hookProperties = [
    [currentWindow.HTMLInputElement.prototype, "value"],
    [currentWindow.HTMLInputElement.prototype, "checked"],
    [currentWindow.HTMLSelectElement.prototype, "value"],
    [currentWindow.HTMLTextAreaElement.prototype, "value"],
    [currentWindow.HTMLSelectElement.prototype, "selectedIndex"],
    [currentWindow.HTMLOptionElement.prototype, "selected"]
  ];
  if (propertyDescriptor && propertyDescriptor.set) {
    handlers2.push(...hookProperties.map((p2) => hookSetter$1(p2[0], p2[1], {
      set() {
        callbackWrapper$1(eventHandler)({
          target: this,
          isTrusted: false
        });
      }
    }, false, currentWindow)));
  }
  return callbackWrapper$1(() => {
    handlers2.forEach((h2) => h2());
  });
}
__name(initInputObserver, "initInputObserver");
function getNestedCSSRulePositions(rule) {
  const positions = [];
  function recurse(childRule, pos) {
    if (hasNestedCSSRule("CSSGroupingRule") && childRule.parentRule instanceof CSSGroupingRule || hasNestedCSSRule("CSSMediaRule") && childRule.parentRule instanceof CSSMediaRule || hasNestedCSSRule("CSSSupportsRule") && childRule.parentRule instanceof CSSSupportsRule || hasNestedCSSRule("CSSConditionRule") && childRule.parentRule instanceof CSSConditionRule) {
      const rules = Array.from(childRule.parentRule.cssRules);
      const index2 = rules.indexOf(childRule);
      pos.unshift(index2);
    } else if (childRule.parentStyleSheet) {
      const rules = Array.from(childRule.parentStyleSheet.cssRules);
      const index2 = rules.indexOf(childRule);
      pos.unshift(index2);
    }
    return pos;
  }
  __name(recurse, "recurse");
  return recurse(rule, positions);
}
__name(getNestedCSSRulePositions, "getNestedCSSRulePositions");
function getIdAndStyleId(sheet, mirror2, styleMirror) {
  let id2, styleId;
  if (!sheet)
    return {};
  if (sheet.ownerNode)
    id2 = mirror2.getId(sheet.ownerNode);
  else
    styleId = styleMirror.getId(sheet);
  return {
    styleId,
    id: id2
  };
}
__name(getIdAndStyleId, "getIdAndStyleId");
function initStyleSheetObserver({ styleSheetRuleCb, mirror: mirror2, stylesheetManager }, { win }) {
  if (!win.CSSStyleSheet || !win.CSSStyleSheet.prototype) {
    return () => {
    };
  }
  const insertRule = win.CSSStyleSheet.prototype.insertRule;
  win.CSSStyleSheet.prototype.insertRule = new Proxy(insertRule, {
    apply: callbackWrapper$1((target, thisArg, argumentsList) => {
      const [rule, index2] = argumentsList;
      const { id: id2, styleId } = getIdAndStyleId(thisArg, mirror2, stylesheetManager.styleMirror);
      if (id2 && id2 !== -1 || styleId && styleId !== -1) {
        styleSheetRuleCb({
          id: id2,
          styleId,
          adds: [{ rule, index: index2 }]
        });
      }
      return target.apply(thisArg, argumentsList);
    })
  });
  const deleteRule = win.CSSStyleSheet.prototype.deleteRule;
  win.CSSStyleSheet.prototype.deleteRule = new Proxy(deleteRule, {
    apply: callbackWrapper$1((target, thisArg, argumentsList) => {
      const [index2] = argumentsList;
      const { id: id2, styleId } = getIdAndStyleId(thisArg, mirror2, stylesheetManager.styleMirror);
      if (id2 && id2 !== -1 || styleId && styleId !== -1) {
        styleSheetRuleCb({
          id: id2,
          styleId,
          removes: [{ index: index2 }]
        });
      }
      return target.apply(thisArg, argumentsList);
    })
  });
  let replace2;
  if (win.CSSStyleSheet.prototype.replace) {
    replace2 = win.CSSStyleSheet.prototype.replace;
    win.CSSStyleSheet.prototype.replace = new Proxy(replace2, {
      apply: callbackWrapper$1((target, thisArg, argumentsList) => {
        const [text2] = argumentsList;
        const { id: id2, styleId } = getIdAndStyleId(thisArg, mirror2, stylesheetManager.styleMirror);
        if (id2 && id2 !== -1 || styleId && styleId !== -1) {
          styleSheetRuleCb({
            id: id2,
            styleId,
            replace: text2
          });
        }
        return target.apply(thisArg, argumentsList);
      })
    });
  }
  let replaceSync;
  if (win.CSSStyleSheet.prototype.replaceSync) {
    replaceSync = win.CSSStyleSheet.prototype.replaceSync;
    win.CSSStyleSheet.prototype.replaceSync = new Proxy(replaceSync, {
      apply: callbackWrapper$1((target, thisArg, argumentsList) => {
        const [text2] = argumentsList;
        const { id: id2, styleId } = getIdAndStyleId(thisArg, mirror2, stylesheetManager.styleMirror);
        if (id2 && id2 !== -1 || styleId && styleId !== -1) {
          styleSheetRuleCb({
            id: id2,
            styleId,
            replaceSync: text2
          });
        }
        return target.apply(thisArg, argumentsList);
      })
    });
  }
  const supportedNestedCSSRuleTypes = {};
  if (canMonkeyPatchNestedCSSRule("CSSGroupingRule")) {
    supportedNestedCSSRuleTypes.CSSGroupingRule = win.CSSGroupingRule;
  } else {
    if (canMonkeyPatchNestedCSSRule("CSSMediaRule")) {
      supportedNestedCSSRuleTypes.CSSMediaRule = win.CSSMediaRule;
    }
    if (canMonkeyPatchNestedCSSRule("CSSConditionRule")) {
      supportedNestedCSSRuleTypes.CSSConditionRule = win.CSSConditionRule;
    }
    if (canMonkeyPatchNestedCSSRule("CSSSupportsRule")) {
      supportedNestedCSSRuleTypes.CSSSupportsRule = win.CSSSupportsRule;
    }
  }
  const unmodifiedFunctions = {};
  Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => {
    unmodifiedFunctions[typeKey] = {
      insertRule: type.prototype.insertRule,
      deleteRule: type.prototype.deleteRule
    };
    type.prototype.insertRule = new Proxy(unmodifiedFunctions[typeKey].insertRule, {
      apply: callbackWrapper$1((target, thisArg, argumentsList) => {
        const [rule, index2] = argumentsList;
        const { id: id2, styleId } = getIdAndStyleId(thisArg.parentStyleSheet, mirror2, stylesheetManager.styleMirror);
        if (id2 && id2 !== -1 || styleId && styleId !== -1) {
          styleSheetRuleCb({
            id: id2,
            styleId,
            adds: [
              {
                rule,
                index: [
                  ...getNestedCSSRulePositions(thisArg),
                  index2 || 0
                ]
              }
            ]
          });
        }
        return target.apply(thisArg, argumentsList);
      })
    });
    type.prototype.deleteRule = new Proxy(unmodifiedFunctions[typeKey].deleteRule, {
      apply: callbackWrapper$1((target, thisArg, argumentsList) => {
        const [index2] = argumentsList;
        const { id: id2, styleId } = getIdAndStyleId(thisArg.parentStyleSheet, mirror2, stylesheetManager.styleMirror);
        if (id2 && id2 !== -1 || styleId && styleId !== -1) {
          styleSheetRuleCb({
            id: id2,
            styleId,
            removes: [
              { index: [...getNestedCSSRulePositions(thisArg), index2] }
            ]
          });
        }
        return target.apply(thisArg, argumentsList);
      })
    });
  });
  return callbackWrapper$1(() => {
    win.CSSStyleSheet.prototype.insertRule = insertRule;
    win.CSSStyleSheet.prototype.deleteRule = deleteRule;
    replace2 && (win.CSSStyleSheet.prototype.replace = replace2);
    replaceSync && (win.CSSStyleSheet.prototype.replaceSync = replaceSync);
    Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => {
      type.prototype.insertRule = unmodifiedFunctions[typeKey].insertRule;
      type.prototype.deleteRule = unmodifiedFunctions[typeKey].deleteRule;
    });
  });
}
__name(initStyleSheetObserver, "initStyleSheetObserver");
function initAdoptedStyleSheetObserver({ mirror: mirror2, stylesheetManager }, host) {
  let hostId = null;
  if (host.nodeName === "#document")
    hostId = mirror2.getId(host);
  else
    hostId = mirror2.getId(host.host);
  const patchTarget = host.nodeName === "#document" ? _optionalChain$2([host, "access", (_4) => _4.defaultView, "optionalAccess", (_5) => _5.Document]) : _optionalChain$2([host, "access", (_6) => _6.ownerDocument, "optionalAccess", (_7) => _7.defaultView, "optionalAccess", (_8) => _8.ShadowRoot]);
  const originalPropertyDescriptor = _optionalChain$2([patchTarget, "optionalAccess", (_9) => _9.prototype]) ? Object.getOwnPropertyDescriptor(_optionalChain$2([patchTarget, "optionalAccess", (_10) => _10.prototype]), "adoptedStyleSheets") : void 0;
  if (hostId === null || hostId === -1 || !patchTarget || !originalPropertyDescriptor)
    return () => {
    };
  Object.defineProperty(host, "adoptedStyleSheets", {
    configurable: originalPropertyDescriptor.configurable,
    enumerable: originalPropertyDescriptor.enumerable,
    get() {
      return _optionalChain$2([originalPropertyDescriptor, "access", (_11) => _11.get, "optionalAccess", (_12) => _12.call, "call", (_13) => _13(this)]);
    },
    set(sheets) {
      const result = _optionalChain$2([originalPropertyDescriptor, "access", (_14) => _14.set, "optionalAccess", (_15) => _15.call, "call", (_16) => _16(this, sheets)]);
      if (hostId !== null && hostId !== -1) {
        try {
          stylesheetManager.adoptStyleSheets(sheets, hostId);
        } catch (e2) {
        }
      }
      return result;
    }
  });
  return callbackWrapper$1(() => {
    Object.defineProperty(host, "adoptedStyleSheets", {
      configurable: originalPropertyDescriptor.configurable,
      enumerable: originalPropertyDescriptor.enumerable,
      get: originalPropertyDescriptor.get,
      set: originalPropertyDescriptor.set
    });
  });
}
__name(initAdoptedStyleSheetObserver, "initAdoptedStyleSheetObserver");
function initStyleDeclarationObserver({ styleDeclarationCb, mirror: mirror2, ignoreCSSAttributes, stylesheetManager }, { win }) {
  const setProperty2 = win.CSSStyleDeclaration.prototype.setProperty;
  win.CSSStyleDeclaration.prototype.setProperty = new Proxy(setProperty2, {
    apply: callbackWrapper$1((target, thisArg, argumentsList) => {
      const [property, value, priority] = argumentsList;
      if (ignoreCSSAttributes.has(property)) {
        return setProperty2.apply(thisArg, [property, value, priority]);
      }
      const { id: id2, styleId } = getIdAndStyleId(_optionalChain$2([thisArg, "access", (_17) => _17.parentRule, "optionalAccess", (_18) => _18.parentStyleSheet]), mirror2, stylesheetManager.styleMirror);
      if (id2 && id2 !== -1 || styleId && styleId !== -1) {
        styleDeclarationCb({
          id: id2,
          styleId,
          set: {
            property,
            value,
            priority
          },
          index: getNestedCSSRulePositions(thisArg.parentRule)
        });
      }
      return target.apply(thisArg, argumentsList);
    })
  });
  const removeProperty = win.CSSStyleDeclaration.prototype.removeProperty;
  win.CSSStyleDeclaration.prototype.removeProperty = new Proxy(removeProperty, {
    apply: callbackWrapper$1((target, thisArg, argumentsList) => {
      const [property] = argumentsList;
      if (ignoreCSSAttributes.has(property)) {
        return removeProperty.apply(thisArg, [property]);
      }
      const { id: id2, styleId } = getIdAndStyleId(_optionalChain$2([thisArg, "access", (_19) => _19.parentRule, "optionalAccess", (_20) => _20.parentStyleSheet]), mirror2, stylesheetManager.styleMirror);
      if (id2 && id2 !== -1 || styleId && styleId !== -1) {
        styleDeclarationCb({
          id: id2,
          styleId,
          remove: {
            property
          },
          index: getNestedCSSRulePositions(thisArg.parentRule)
        });
      }
      return target.apply(thisArg, argumentsList);
    })
  });
  return callbackWrapper$1(() => {
    win.CSSStyleDeclaration.prototype.setProperty = setProperty2;
    win.CSSStyleDeclaration.prototype.removeProperty = removeProperty;
  });
}
__name(initStyleDeclarationObserver, "initStyleDeclarationObserver");
function initMediaInteractionObserver({ mediaInteractionCb, blockClass, blockSelector, unblockSelector, mirror: mirror2, sampling, doc: doc2 }) {
  const handler5 = callbackWrapper$1((type) => throttle$1(callbackWrapper$1((event) => {
    const target = getEventTarget(event);
    if (!target || isBlocked$1(target, blockClass, blockSelector, unblockSelector, true)) {
      return;
    }
    const { currentTime, volume, muted, playbackRate } = target;
    mediaInteractionCb({
      type,
      id: mirror2.getId(target),
      currentTime,
      volume,
      muted,
      playbackRate
    });
  }), sampling.media || 500));
  const handlers2 = [
    on$1("play", handler5(0), doc2),
    on$1("pause", handler5(1), doc2),
    on$1("seeked", handler5(2), doc2),
    on$1("volumechange", handler5(3), doc2),
    on$1("ratechange", handler5(4), doc2)
  ];
  return callbackWrapper$1(() => {
    handlers2.forEach((h2) => h2());
  });
}
__name(initMediaInteractionObserver, "initMediaInteractionObserver");
function initFontObserver({ fontCb, doc: doc2 }) {
  const win = doc2.defaultView;
  if (!win) {
    return () => {
    };
  }
  const handlers2 = [];
  const fontMap = /* @__PURE__ */ new WeakMap();
  const originalFontFace = win.FontFace;
  win.FontFace = /* @__PURE__ */ __name(function FontFace(family, source, descriptors2) {
    const fontFace = new originalFontFace(family, source, descriptors2);
    fontMap.set(fontFace, {
      family,
      buffer: typeof source !== "string",
      descriptors: descriptors2,
      fontSource: typeof source === "string" ? source : JSON.stringify(Array.from(new Uint8Array(source)))
    });
    return fontFace;
  }, "FontFace");
  const restoreHandler = patch$2(doc2.fonts, "add", function(original) {
    return function(fontFace) {
      setTimeout$1$1(callbackWrapper$1(() => {
        const p2 = fontMap.get(fontFace);
        if (p2) {
          fontCb(p2);
          fontMap.delete(fontFace);
        }
      }), 0);
      return original.apply(this, [fontFace]);
    };
  });
  handlers2.push(() => {
    win.FontFace = originalFontFace;
  });
  handlers2.push(restoreHandler);
  return callbackWrapper$1(() => {
    handlers2.forEach((h2) => h2());
  });
}
__name(initFontObserver, "initFontObserver");
function initSelectionObserver(param) {
  const { doc: doc2, mirror: mirror2, blockClass, blockSelector, unblockSelector, selectionCb } = param;
  let collapsed = true;
  const updateSelection2 = callbackWrapper$1(() => {
    const selection = doc2.getSelection();
    if (!selection || collapsed && _optionalChain$2([selection, "optionalAccess", (_21) => _21.isCollapsed]))
      return;
    collapsed = selection.isCollapsed || false;
    const ranges = [];
    const count2 = selection.rangeCount || 0;
    for (let i2 = 0; i2 < count2; i2++) {
      const range = selection.getRangeAt(i2);
      const { startContainer, startOffset, endContainer, endOffset } = range;
      const blocked = isBlocked$1(startContainer, blockClass, blockSelector, unblockSelector, true) || isBlocked$1(endContainer, blockClass, blockSelector, unblockSelector, true);
      if (blocked)
        continue;
      ranges.push({
        start: mirror2.getId(startContainer),
        startOffset,
        end: mirror2.getId(endContainer),
        endOffset
      });
    }
    selectionCb({ ranges });
  });
  updateSelection2();
  return on$1("selectionchange", updateSelection2);
}
__name(initSelectionObserver, "initSelectionObserver");
function initCustomElementObserver({ doc: doc2, customElementCb }) {
  const win = doc2.defaultView;
  if (!win || !win.customElements)
    return () => {
    };
  const restoreHandler = patch$2(win.customElements, "define", function(original) {
    return function(name2, constructor, options2) {
      try {
        customElementCb({
          define: {
            name: name2
          }
        });
      } catch (e2) {
      }
      return original.apply(this, [name2, constructor, options2]);
    };
  });
  return restoreHandler;
}
__name(initCustomElementObserver, "initCustomElementObserver");
function initObservers(o2, _hooks = {}) {
  const currentWindow = o2.doc.defaultView;
  if (!currentWindow) {
    return () => {
    };
  }
  let mutationObserver;
  if (o2.recordDOM) {
    mutationObserver = initMutationObserver(o2, o2.doc);
  }
  const mousemoveHandler = initMoveObserver(o2);
  const mouseInteractionHandler = initMouseInteractionObserver(o2);
  const scrollHandler = initScrollObserver(o2);
  const viewportResizeHandler = initViewportResizeObserver(o2, {
    win: currentWindow
  });
  const inputHandler = initInputObserver(o2);
  const mediaInteractionHandler = initMediaInteractionObserver(o2);
  let styleSheetObserver = /* @__PURE__ */ __name(() => {
  }, "styleSheetObserver");
  let adoptedStyleSheetObserver = /* @__PURE__ */ __name(() => {
  }, "adoptedStyleSheetObserver");
  let styleDeclarationObserver = /* @__PURE__ */ __name(() => {
  }, "styleDeclarationObserver");
  let fontObserver = /* @__PURE__ */ __name(() => {
  }, "fontObserver");
  if (o2.recordDOM) {
    styleSheetObserver = initStyleSheetObserver(o2, { win: currentWindow });
    adoptedStyleSheetObserver = initAdoptedStyleSheetObserver(o2, o2.doc);
    styleDeclarationObserver = initStyleDeclarationObserver(o2, {
      win: currentWindow
    });
    if (o2.collectFonts) {
      fontObserver = initFontObserver(o2);
    }
  }
  const selectionObserver = initSelectionObserver(o2);
  const customElementObserver = initCustomElementObserver(o2);
  const pluginHandlers = [];
  for (const plugin of o2.plugins) {
    pluginHandlers.push(plugin.observer(plugin.callback, currentWindow, plugin.options));
  }
  return callbackWrapper$1(() => {
    mutationBuffers.forEach((b2) => b2.reset());
    _optionalChain$2([mutationObserver, "optionalAccess", (_22) => _22.disconnect, "call", (_23) => _23()]);
    mousemoveHandler();
    mouseInteractionHandler();
    scrollHandler();
    viewportResizeHandler();
    inputHandler();
    mediaInteractionHandler();
    styleSheetObserver();
    adoptedStyleSheetObserver();
    styleDeclarationObserver();
    fontObserver();
    selectionObserver();
    customElementObserver();
    pluginHandlers.forEach((h2) => h2());
  });
}
__name(initObservers, "initObservers");
function hasNestedCSSRule(prop2) {
  return typeof window[prop2] !== "undefined";
}
__name(hasNestedCSSRule, "hasNestedCSSRule");
function canMonkeyPatchNestedCSSRule(prop2) {
  return Boolean(typeof window[prop2] !== "undefined" && window[prop2].prototype && "insertRule" in window[prop2].prototype && "deleteRule" in window[prop2].prototype);
}
__name(canMonkeyPatchNestedCSSRule, "canMonkeyPatchNestedCSSRule");
class CrossOriginIframeMirror {
  static {
    __name(this, "CrossOriginIframeMirror");
  }
  constructor(generateIdFn) {
    this.generateIdFn = generateIdFn;
    this.iframeIdToRemoteIdMap = /* @__PURE__ */ new WeakMap();
    this.iframeRemoteIdToIdMap = /* @__PURE__ */ new WeakMap();
  }
  getId(iframe, remoteId, idToRemoteMap, remoteToIdMap) {
    const idToRemoteIdMap = idToRemoteMap || this.getIdToRemoteIdMap(iframe);
    const remoteIdToIdMap = remoteToIdMap || this.getRemoteIdToIdMap(iframe);
    let id2 = idToRemoteIdMap.get(remoteId);
    if (!id2) {
      id2 = this.generateIdFn();
      idToRemoteIdMap.set(remoteId, id2);
      remoteIdToIdMap.set(id2, remoteId);
    }
    return id2;
  }
  getIds(iframe, remoteId) {
    const idToRemoteIdMap = this.getIdToRemoteIdMap(iframe);
    const remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);
    return remoteId.map((id2) => this.getId(iframe, id2, idToRemoteIdMap, remoteIdToIdMap));
  }
  getRemoteId(iframe, id2, map3) {
    const remoteIdToIdMap = map3 || this.getRemoteIdToIdMap(iframe);
    if (typeof id2 !== "number")
      return id2;
    const remoteId = remoteIdToIdMap.get(id2);
    if (!remoteId)
      return -1;
    return remoteId;
  }
  getRemoteIds(iframe, ids) {
    const remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);
    return ids.map((id2) => this.getRemoteId(iframe, id2, remoteIdToIdMap));
  }
  reset(iframe) {
    if (!iframe) {
      this.iframeIdToRemoteIdMap = /* @__PURE__ */ new WeakMap();
      this.iframeRemoteIdToIdMap = /* @__PURE__ */ new WeakMap();
      return;
    }
    this.iframeIdToRemoteIdMap.delete(iframe);
    this.iframeRemoteIdToIdMap.delete(iframe);
  }
  getIdToRemoteIdMap(iframe) {
    let idToRemoteIdMap = this.iframeIdToRemoteIdMap.get(iframe);
    if (!idToRemoteIdMap) {
      idToRemoteIdMap = /* @__PURE__ */ new Map();
      this.iframeIdToRemoteIdMap.set(iframe, idToRemoteIdMap);
    }
    return idToRemoteIdMap;
  }
  getRemoteIdToIdMap(iframe) {
    let remoteIdToIdMap = this.iframeRemoteIdToIdMap.get(iframe);
    if (!remoteIdToIdMap) {
      remoteIdToIdMap = /* @__PURE__ */ new Map();
      this.iframeRemoteIdToIdMap.set(iframe, remoteIdToIdMap);
    }
    return remoteIdToIdMap;
  }
}
function _optionalChain$1(ops2) {
  let lastAccessLHS = void 0;
  let value = ops2[0];
  let i2 = 1;
  while (i2 < ops2.length) {
    const op = ops2[i2];
    const fn = ops2[i2 + 1];
    i2 += 2;
    if ((op === "optionalAccess" || op === "optionalCall") && value == null) {
      return void 0;
    }
    if (op === "access" || op === "optionalAccess") {
      lastAccessLHS = value;
      value = fn(value);
    } else if (op === "call" || op === "optionalCall") {
      value = fn((...args) => value.call(lastAccessLHS, ...args));
      lastAccessLHS = void 0;
    }
  }
  return value;
}
__name(_optionalChain$1, "_optionalChain$1");
class IframeManagerNoop {
  static {
    __name(this, "IframeManagerNoop");
  }
  constructor() {
    this.crossOriginIframeMirror = new CrossOriginIframeMirror(genId);
    this.crossOriginIframeRootIdMap = /* @__PURE__ */ new WeakMap();
  }
  addIframe() {
  }
  addLoadListener() {
  }
  attachIframe() {
  }
}
class IframeManager {
  static {
    __name(this, "IframeManager");
  }
  constructor(options2) {
    this.iframes = /* @__PURE__ */ new WeakMap();
    this.crossOriginIframeMap = /* @__PURE__ */ new WeakMap();
    this.crossOriginIframeMirror = new CrossOriginIframeMirror(genId);
    this.crossOriginIframeRootIdMap = /* @__PURE__ */ new WeakMap();
    this.mutationCb = options2.mutationCb;
    this.wrappedEmit = options2.wrappedEmit;
    this.stylesheetManager = options2.stylesheetManager;
    this.recordCrossOriginIframes = options2.recordCrossOriginIframes;
    this.crossOriginIframeStyleMirror = new CrossOriginIframeMirror(this.stylesheetManager.styleMirror.generateId.bind(this.stylesheetManager.styleMirror));
    this.mirror = options2.mirror;
    if (this.recordCrossOriginIframes) {
      window.addEventListener("message", this.handleMessage.bind(this));
    }
  }
  addIframe(iframeEl) {
    this.iframes.set(iframeEl, true);
    if (iframeEl.contentWindow)
      this.crossOriginIframeMap.set(iframeEl.contentWindow, iframeEl);
  }
  addLoadListener(cb) {
    this.loadListener = cb;
  }
  attachIframe(iframeEl, childSn) {
    this.mutationCb({
      adds: [
        {
          parentId: this.mirror.getId(iframeEl),
          nextId: null,
          node: childSn
        }
      ],
      removes: [],
      texts: [],
      attributes: [],
      isAttachIframe: true
    });
    _optionalChain$1([this, "access", (_2) => _2.loadListener, "optionalCall", (_2) => _2(iframeEl)]);
    const iframeDoc = getIFrameContentDocument(iframeEl);
    if (iframeDoc && iframeDoc.adoptedStyleSheets && iframeDoc.adoptedStyleSheets.length > 0)
      this.stylesheetManager.adoptStyleSheets(iframeDoc.adoptedStyleSheets, this.mirror.getId(iframeDoc));
  }
  handleMessage(message) {
    const crossOriginMessageEvent = message;
    if (crossOriginMessageEvent.data.type !== "rrweb" || crossOriginMessageEvent.origin !== crossOriginMessageEvent.data.origin)
      return;
    const iframeSourceWindow = message.source;
    if (!iframeSourceWindow)
      return;
    const iframeEl = this.crossOriginIframeMap.get(message.source);
    if (!iframeEl)
      return;
    const transformedEvent = this.transformCrossOriginEvent(iframeEl, crossOriginMessageEvent.data.event);
    if (transformedEvent)
      this.wrappedEmit(transformedEvent, crossOriginMessageEvent.data.isCheckout);
  }
  transformCrossOriginEvent(iframeEl, e2) {
    switch (e2.type) {
      case EventType$1.FullSnapshot: {
        this.crossOriginIframeMirror.reset(iframeEl);
        this.crossOriginIframeStyleMirror.reset(iframeEl);
        this.replaceIdOnNode(e2.data.node, iframeEl);
        const rootId = e2.data.node.id;
        this.crossOriginIframeRootIdMap.set(iframeEl, rootId);
        this.patchRootIdOnNode(e2.data.node, rootId);
        return {
          timestamp: e2.timestamp,
          type: EventType$1.IncrementalSnapshot,
          data: {
            source: IncrementalSource.Mutation,
            adds: [
              {
                parentId: this.mirror.getId(iframeEl),
                nextId: null,
                node: e2.data.node
              }
            ],
            removes: [],
            texts: [],
            attributes: [],
            isAttachIframe: true
          }
        };
      }
      case EventType$1.Meta:
      case EventType$1.Load:
      case EventType$1.DomContentLoaded: {
        return false;
      }
      case EventType$1.Plugin: {
        return e2;
      }
      case EventType$1.Custom: {
        this.replaceIds(e2.data.payload, iframeEl, ["id", "parentId", "previousId", "nextId"]);
        return e2;
      }
      case EventType$1.IncrementalSnapshot: {
        switch (e2.data.source) {
          case IncrementalSource.Mutation: {
            e2.data.adds.forEach((n2) => {
              this.replaceIds(n2, iframeEl, [
                "parentId",
                "nextId",
                "previousId"
              ]);
              this.replaceIdOnNode(n2.node, iframeEl);
              const rootId = this.crossOriginIframeRootIdMap.get(iframeEl);
              rootId && this.patchRootIdOnNode(n2.node, rootId);
            });
            e2.data.removes.forEach((n2) => {
              this.replaceIds(n2, iframeEl, ["parentId", "id"]);
            });
            e2.data.attributes.forEach((n2) => {
              this.replaceIds(n2, iframeEl, ["id"]);
            });
            e2.data.texts.forEach((n2) => {
              this.replaceIds(n2, iframeEl, ["id"]);
            });
            return e2;
          }
          case IncrementalSource.Drag:
          case IncrementalSource.TouchMove:
          case IncrementalSource.MouseMove: {
            e2.data.positions.forEach((p2) => {
              this.replaceIds(p2, iframeEl, ["id"]);
            });
            return e2;
          }
          case IncrementalSource.ViewportResize: {
            return false;
          }
          case IncrementalSource.MediaInteraction:
          case IncrementalSource.MouseInteraction:
          case IncrementalSource.Scroll:
          case IncrementalSource.CanvasMutation:
          case IncrementalSource.Input: {
            this.replaceIds(e2.data, iframeEl, ["id"]);
            return e2;
          }
          case IncrementalSource.StyleSheetRule:
          case IncrementalSource.StyleDeclaration: {
            this.replaceIds(e2.data, iframeEl, ["id"]);
            this.replaceStyleIds(e2.data, iframeEl, ["styleId"]);
            return e2;
          }
          case IncrementalSource.Font: {
            return e2;
          }
          case IncrementalSource.Selection: {
            e2.data.ranges.forEach((range) => {
              this.replaceIds(range, iframeEl, ["start", "end"]);
            });
            return e2;
          }
          case IncrementalSource.AdoptedStyleSheet: {
            this.replaceIds(e2.data, iframeEl, ["id"]);
            this.replaceStyleIds(e2.data, iframeEl, ["styleIds"]);
            _optionalChain$1([e2, "access", (_3) => _3.data, "access", (_4) => _4.styles, "optionalAccess", (_5) => _5.forEach, "call", (_6) => _6((style2) => {
              this.replaceStyleIds(style2, iframeEl, ["styleId"]);
            })]);
            return e2;
          }
        }
      }
    }
    return false;
  }
  replace(iframeMirror, obj, iframeEl, keys2) {
    for (const key of keys2) {
      if (!Array.isArray(obj[key]) && typeof obj[key] !== "number")
        continue;
      if (Array.isArray(obj[key])) {
        obj[key] = iframeMirror.getIds(iframeEl, obj[key]);
      } else {
        obj[key] = iframeMirror.getId(iframeEl, obj[key]);
      }
    }
    return obj;
  }
  replaceIds(obj, iframeEl, keys2) {
    return this.replace(this.crossOriginIframeMirror, obj, iframeEl, keys2);
  }
  replaceStyleIds(obj, iframeEl, keys2) {
    return this.replace(this.crossOriginIframeStyleMirror, obj, iframeEl, keys2);
  }
  replaceIdOnNode(node2, iframeEl) {
    this.replaceIds(node2, iframeEl, ["id", "rootId"]);
    if ("childNodes" in node2) {
      node2.childNodes.forEach((child2) => {
        this.replaceIdOnNode(child2, iframeEl);
      });
    }
  }
  patchRootIdOnNode(node2, rootId) {
    if (node2.type !== NodeType$3.Document && !node2.rootId)
      node2.rootId = rootId;
    if ("childNodes" in node2) {
      node2.childNodes.forEach((child2) => {
        this.patchRootIdOnNode(child2, rootId);
      });
    }
  }
}
class ShadowDomManagerNoop {
  static {
    __name(this, "ShadowDomManagerNoop");
  }
  init() {
  }
  addShadowRoot() {
  }
  observeAttachShadow() {
  }
  reset() {
  }
}
class ShadowDomManager {
  static {
    __name(this, "ShadowDomManager");
  }
  constructor(options2) {
    this.shadowDoms = /* @__PURE__ */ new WeakSet();
    this.restoreHandlers = [];
    this.mutationCb = options2.mutationCb;
    this.scrollCb = options2.scrollCb;
    this.bypassOptions = options2.bypassOptions;
    this.mirror = options2.mirror;
    this.init();
  }
  init() {
    this.reset();
    this.patchAttachShadow(Element, document);
  }
  addShadowRoot(shadowRoot, doc2) {
    if (!isNativeShadowDom(shadowRoot))
      return;
    if (this.shadowDoms.has(shadowRoot))
      return;
    this.shadowDoms.add(shadowRoot);
    this.bypassOptions.canvasManager.addShadowRoot(shadowRoot);
    const observer = initMutationObserver({
      ...this.bypassOptions,
      doc: doc2,
      mutationCb: this.mutationCb,
      mirror: this.mirror,
      shadowDomManager: this
    }, shadowRoot);
    this.restoreHandlers.push(() => observer.disconnect());
    this.restoreHandlers.push(initScrollObserver({
      ...this.bypassOptions,
      scrollCb: this.scrollCb,
      doc: shadowRoot,
      mirror: this.mirror
    }));
    setTimeout$1$1(() => {
      if (shadowRoot.adoptedStyleSheets && shadowRoot.adoptedStyleSheets.length > 0)
        this.bypassOptions.stylesheetManager.adoptStyleSheets(shadowRoot.adoptedStyleSheets, this.mirror.getId(shadowRoot.host));
      this.restoreHandlers.push(initAdoptedStyleSheetObserver({
        mirror: this.mirror,
        stylesheetManager: this.bypassOptions.stylesheetManager
      }, shadowRoot));
    }, 0);
  }
  observeAttachShadow(iframeElement) {
    const iframeDoc = getIFrameContentDocument(iframeElement);
    const iframeWindow = getIFrameContentWindow(iframeElement);
    if (!iframeDoc || !iframeWindow)
      return;
    this.patchAttachShadow(iframeWindow.Element, iframeDoc);
  }
  patchAttachShadow(element, doc2) {
    const manager2 = this;
    this.restoreHandlers.push(patch$2(element.prototype, "attachShadow", function(original) {
      return function(option) {
        const shadowRoot = original.call(this, option);
        if (this.shadowRoot && inDom(this))
          manager2.addShadowRoot(this.shadowRoot, doc2);
        return shadowRoot;
      };
    }));
  }
  reset() {
    this.restoreHandlers.forEach((handler5) => {
      try {
        handler5();
      } catch (e2) {
      }
    });
    this.restoreHandlers = [];
    this.shadowDoms = /* @__PURE__ */ new WeakSet();
    this.bypassOptions.canvasManager.resetShadowRoots();
  }
}
class CanvasManagerNoop {
  static {
    __name(this, "CanvasManagerNoop");
  }
  reset() {
  }
  freeze() {
  }
  unfreeze() {
  }
  lock() {
  }
  unlock() {
  }
  snapshot() {
  }
  addWindow() {
  }
  addShadowRoot() {
  }
  resetShadowRoots() {
  }
}
class StylesheetManager {
  static {
    __name(this, "StylesheetManager");
  }
  constructor(options2) {
    this.trackedLinkElements = /* @__PURE__ */ new WeakSet();
    this.styleMirror = new StyleSheetMirror();
    this.mutationCb = options2.mutationCb;
    this.adoptedStyleSheetCb = options2.adoptedStyleSheetCb;
  }
  attachLinkElement(linkEl, childSn) {
    if ("_cssText" in childSn.attributes)
      this.mutationCb({
        adds: [],
        removes: [],
        texts: [],
        attributes: [
          {
            id: childSn.id,
            attributes: childSn.attributes
          }
        ]
      });
    this.trackLinkElement(linkEl);
  }
  trackLinkElement(linkEl) {
    if (this.trackedLinkElements.has(linkEl))
      return;
    this.trackedLinkElements.add(linkEl);
    this.trackStylesheetInLinkElement(linkEl);
  }
  adoptStyleSheets(sheets, hostId) {
    if (sheets.length === 0)
      return;
    const adoptedStyleSheetData = {
      id: hostId,
      styleIds: []
    };
    const styles = [];
    for (const sheet of sheets) {
      let styleId;
      if (!this.styleMirror.has(sheet)) {
        styleId = this.styleMirror.add(sheet);
        styles.push({
          styleId,
          rules: Array.from(sheet.rules || CSSRule, (r2, index2) => ({
            rule: stringifyRule(r2),
            index: index2
          }))
        });
      } else
        styleId = this.styleMirror.getId(sheet);
      adoptedStyleSheetData.styleIds.push(styleId);
    }
    if (styles.length > 0)
      adoptedStyleSheetData.styles = styles;
    this.adoptedStyleSheetCb(adoptedStyleSheetData);
  }
  reset() {
    this.styleMirror.reset();
    this.trackedLinkElements = /* @__PURE__ */ new WeakSet();
  }
  trackStylesheetInLinkElement(linkEl) {
  }
}
class ProcessedNodeManager {
  static {
    __name(this, "ProcessedNodeManager");
  }
  constructor() {
    this.nodeMap = /* @__PURE__ */ new WeakMap();
    this.active = false;
  }
  inOtherBuffer(node2, thisBuffer) {
    const buffers = this.nodeMap.get(node2);
    return buffers && Array.from(buffers).some((buffer) => buffer !== thisBuffer);
  }
  add(node2, buffer) {
    if (!this.active) {
      this.active = true;
      onRequestAnimationFrame$1(() => {
        this.nodeMap = /* @__PURE__ */ new WeakMap();
        this.active = false;
      });
    }
    this.nodeMap.set(node2, (this.nodeMap.get(node2) || /* @__PURE__ */ new Set()).add(buffer));
  }
  destroy() {
  }
}
let wrappedEmit;
let _takeFullSnapshot;
try {
  if (Array.from([1], (x2) => x2 * 2)[0] !== 2) {
    const cleanFrame = document.createElement("iframe");
    document.body.appendChild(cleanFrame);
    Array.from = _optionalChain([cleanFrame, "access", (_2) => _2.contentWindow, "optionalAccess", (_2) => _2.Array, "access", (_3) => _3.from]) || Array.from;
    document.body.removeChild(cleanFrame);
  }
} catch (err) {
  console.debug("Unable to override Array.from", err);
}
const mirror = createMirror();
function record(options2 = {}) {
  const { emit, checkoutEveryNms, checkoutEveryNth, blockClass = "rr-block", blockSelector = null, unblockSelector = null, ignoreClass = "rr-ignore", ignoreSelector = null, maskAllText = false, maskTextClass = "rr-mask", unmaskTextClass = null, maskTextSelector = null, unmaskTextSelector = null, inlineStylesheet = true, maskAllInputs, maskInputOptions: _maskInputOptions, slimDOMOptions: _slimDOMOptions, maskAttributeFn, maskInputFn, maskTextFn, maxCanvasSize = null, packFn, sampling = {}, dataURLOptions = {}, mousemoveWait, recordDOM = true, recordCanvas = false, recordCrossOriginIframes = false, recordAfter = options2.recordAfter === "DOMContentLoaded" ? options2.recordAfter : "load", userTriggeredOnInput = false, collectFonts = false, inlineImages = false, plugins, keepIframeSrcFn = /* @__PURE__ */ __name(() => false, "keepIframeSrcFn"), ignoreCSSAttributes = /* @__PURE__ */ new Set([]), errorHandler: errorHandler2, onMutation, getCanvasManager } = options2;
  registerErrorHandler$1(errorHandler2);
  const inEmittingFrame = recordCrossOriginIframes ? window.parent === window : true;
  let passEmitsToParent = false;
  if (!inEmittingFrame) {
    try {
      if (window.parent.document) {
        passEmitsToParent = false;
      }
    } catch (e2) {
      passEmitsToParent = true;
    }
  }
  if (inEmittingFrame && !emit) {
    throw new Error("emit function is required");
  }
  if (!inEmittingFrame && !passEmitsToParent) {
    return () => {
    };
  }
  if (mousemoveWait !== void 0 && sampling.mousemove === void 0) {
    sampling.mousemove = mousemoveWait;
  }
  mirror.reset();
  const maskInputOptions = maskAllInputs === true ? {
    color: true,
    date: true,
    "datetime-local": true,
    email: true,
    month: true,
    number: true,
    range: true,
    search: true,
    tel: true,
    text: true,
    time: true,
    url: true,
    week: true,
    textarea: true,
    select: true,
    radio: true,
    checkbox: true
  } : _maskInputOptions !== void 0 ? _maskInputOptions : {};
  const slimDOMOptions = _slimDOMOptions === true || _slimDOMOptions === "all" ? {
    script: true,
    comment: true,
    headFavicon: true,
    headWhitespace: true,
    headMetaSocial: true,
    headMetaRobots: true,
    headMetaHttpEquiv: true,
    headMetaVerification: true,
    headMetaAuthorship: _slimDOMOptions === "all",
    headMetaDescKeywords: _slimDOMOptions === "all"
  } : _slimDOMOptions ? _slimDOMOptions : {};
  polyfill();
  let lastFullSnapshotEvent;
  let incrementalSnapshotCount = 0;
  const eventProcessor = /* @__PURE__ */ __name((e2) => {
    for (const plugin of plugins || []) {
      if (plugin.eventProcessor) {
        e2 = plugin.eventProcessor(e2);
      }
    }
    if (packFn && !passEmitsToParent) {
      e2 = packFn(e2);
    }
    return e2;
  }, "eventProcessor");
  wrappedEmit = /* @__PURE__ */ __name((r2, isCheckout) => {
    const e2 = r2;
    e2.timestamp = nowTimestamp();
    if (_optionalChain([mutationBuffers, "access", (_4) => _4[0], "optionalAccess", (_5) => _5.isFrozen, "call", (_6) => _6()]) && e2.type !== EventType$1.FullSnapshot && !(e2.type === EventType$1.IncrementalSnapshot && e2.data.source === IncrementalSource.Mutation)) {
      mutationBuffers.forEach((buf) => buf.unfreeze());
    }
    if (inEmittingFrame) {
      _optionalChain([emit, "optionalCall", (_7) => _7(eventProcessor(e2), isCheckout)]);
    } else if (passEmitsToParent) {
      const message = {
        type: "rrweb",
        event: eventProcessor(e2),
        origin: window.location.origin,
        isCheckout
      };
      window.parent.postMessage(message, "*");
    }
    if (e2.type === EventType$1.FullSnapshot) {
      lastFullSnapshotEvent = e2;
      incrementalSnapshotCount = 0;
    } else if (e2.type === EventType$1.IncrementalSnapshot) {
      if (e2.data.source === IncrementalSource.Mutation && e2.data.isAttachIframe) {
        return;
      }
      incrementalSnapshotCount++;
      const exceedCount = checkoutEveryNth && incrementalSnapshotCount >= checkoutEveryNth;
      const exceedTime = checkoutEveryNms && lastFullSnapshotEvent && e2.timestamp - lastFullSnapshotEvent.timestamp > checkoutEveryNms;
      if (exceedCount || exceedTime) {
        takeFullSnapshot2(true);
      }
    }
  }, "wrappedEmit");
  const wrappedMutationEmit = /* @__PURE__ */ __name((m2) => {
    wrappedEmit({
      type: EventType$1.IncrementalSnapshot,
      data: {
        source: IncrementalSource.Mutation,
        ...m2
      }
    });
  }, "wrappedMutationEmit");
  const wrappedScrollEmit = /* @__PURE__ */ __name((p2) => wrappedEmit({
    type: EventType$1.IncrementalSnapshot,
    data: {
      source: IncrementalSource.Scroll,
      ...p2
    }
  }), "wrappedScrollEmit");
  const wrappedCanvasMutationEmit = /* @__PURE__ */ __name((p2) => wrappedEmit({
    type: EventType$1.IncrementalSnapshot,
    data: {
      source: IncrementalSource.CanvasMutation,
      ...p2
    }
  }), "wrappedCanvasMutationEmit");
  const wrappedAdoptedStyleSheetEmit = /* @__PURE__ */ __name((a2) => wrappedEmit({
    type: EventType$1.IncrementalSnapshot,
    data: {
      source: IncrementalSource.AdoptedStyleSheet,
      ...a2
    }
  }), "wrappedAdoptedStyleSheetEmit");
  const stylesheetManager = new StylesheetManager({
    mutationCb: wrappedMutationEmit,
    adoptedStyleSheetCb: wrappedAdoptedStyleSheetEmit
  });
  const iframeManager = typeof __RRWEB_EXCLUDE_IFRAME__ === "boolean" && __RRWEB_EXCLUDE_IFRAME__ ? new IframeManagerNoop() : new IframeManager({
    mirror,
    mutationCb: wrappedMutationEmit,
    stylesheetManager,
    recordCrossOriginIframes,
    wrappedEmit
  });
  for (const plugin of plugins || []) {
    if (plugin.getMirror)
      plugin.getMirror({
        nodeMirror: mirror,
        crossOriginIframeMirror: iframeManager.crossOriginIframeMirror,
        crossOriginIframeStyleMirror: iframeManager.crossOriginIframeStyleMirror
      });
  }
  const processedNodeManager = new ProcessedNodeManager();
  const canvasManager = _getCanvasManager(getCanvasManager, {
    mirror,
    win: window,
    mutationCb: /* @__PURE__ */ __name((p2) => wrappedEmit({
      type: EventType$1.IncrementalSnapshot,
      data: {
        source: IncrementalSource.CanvasMutation,
        ...p2
      }
    }), "mutationCb"),
    recordCanvas,
    blockClass,
    blockSelector,
    unblockSelector,
    maxCanvasSize,
    sampling: sampling["canvas"],
    dataURLOptions,
    errorHandler: errorHandler2
  });
  const shadowDomManager = typeof __RRWEB_EXCLUDE_SHADOW_DOM__ === "boolean" && __RRWEB_EXCLUDE_SHADOW_DOM__ ? new ShadowDomManagerNoop() : new ShadowDomManager({
    mutationCb: wrappedMutationEmit,
    scrollCb: wrappedScrollEmit,
    bypassOptions: {
      onMutation,
      blockClass,
      blockSelector,
      unblockSelector,
      maskAllText,
      maskTextClass,
      unmaskTextClass,
      maskTextSelector,
      unmaskTextSelector,
      inlineStylesheet,
      maskInputOptions,
      dataURLOptions,
      maskAttributeFn,
      maskTextFn,
      maskInputFn,
      recordCanvas,
      inlineImages,
      sampling,
      slimDOMOptions,
      iframeManager,
      stylesheetManager,
      canvasManager,
      keepIframeSrcFn,
      processedNodeManager
    },
    mirror
  });
  const takeFullSnapshot2 = /* @__PURE__ */ __name((isCheckout = false) => {
    if (!recordDOM) {
      return;
    }
    wrappedEmit({
      type: EventType$1.Meta,
      data: {
        href: window.location.href,
        width: getWindowWidth(),
        height: getWindowHeight()
      }
    }, isCheckout);
    stylesheetManager.reset();
    shadowDomManager.init();
    mutationBuffers.forEach((buf) => buf.lock());
    const node2 = snapshot(document, {
      mirror,
      blockClass,
      blockSelector,
      unblockSelector,
      maskAllText,
      maskTextClass,
      unmaskTextClass,
      maskTextSelector,
      unmaskTextSelector,
      inlineStylesheet,
      maskAllInputs: maskInputOptions,
      maskAttributeFn,
      maskInputFn,
      maskTextFn,
      slimDOM: slimDOMOptions,
      dataURLOptions,
      recordCanvas,
      inlineImages,
      onSerialize: /* @__PURE__ */ __name((n2) => {
        if (isSerializedIframe(n2, mirror)) {
          iframeManager.addIframe(n2);
        }
        if (isSerializedStylesheet(n2, mirror)) {
          stylesheetManager.trackLinkElement(n2);
        }
        if (hasShadowRoot(n2)) {
          shadowDomManager.addShadowRoot(n2.shadowRoot, document);
        }
      }, "onSerialize"),
      onIframeLoad: /* @__PURE__ */ __name((iframe, childSn) => {
        iframeManager.attachIframe(iframe, childSn);
        if (iframe.contentWindow) {
          canvasManager.addWindow(iframe.contentWindow);
        }
        shadowDomManager.observeAttachShadow(iframe);
      }, "onIframeLoad"),
      onStylesheetLoad: /* @__PURE__ */ __name((linkEl, childSn) => {
        stylesheetManager.attachLinkElement(linkEl, childSn);
      }, "onStylesheetLoad"),
      keepIframeSrcFn
    });
    if (!node2) {
      return console.warn("Failed to snapshot the document");
    }
    wrappedEmit({
      type: EventType$1.FullSnapshot,
      data: {
        node: node2,
        initialOffset: getWindowScroll(window)
      }
    });
    mutationBuffers.forEach((buf) => buf.unlock());
    if (document.adoptedStyleSheets && document.adoptedStyleSheets.length > 0)
      stylesheetManager.adoptStyleSheets(document.adoptedStyleSheets, mirror.getId(document));
  }, "takeFullSnapshot");
  _takeFullSnapshot = takeFullSnapshot2;
  try {
    const handlers2 = [];
    const observe2 = /* @__PURE__ */ __name((doc2) => {
      return callbackWrapper$1(initObservers)({
        onMutation,
        mutationCb: wrappedMutationEmit,
        mousemoveCb: /* @__PURE__ */ __name((positions, source) => wrappedEmit({
          type: EventType$1.IncrementalSnapshot,
          data: {
            source,
            positions
          }
        }), "mousemoveCb"),
        mouseInteractionCb: /* @__PURE__ */ __name((d2) => wrappedEmit({
          type: EventType$1.IncrementalSnapshot,
          data: {
            source: IncrementalSource.MouseInteraction,
            ...d2
          }
        }), "mouseInteractionCb"),
        scrollCb: wrappedScrollEmit,
        viewportResizeCb: /* @__PURE__ */ __name((d2) => wrappedEmit({
          type: EventType$1.IncrementalSnapshot,
          data: {
            source: IncrementalSource.ViewportResize,
            ...d2
          }
        }), "viewportResizeCb"),
        inputCb: /* @__PURE__ */ __name((v2) => wrappedEmit({
          type: EventType$1.IncrementalSnapshot,
          data: {
            source: IncrementalSource.Input,
            ...v2
          }
        }), "inputCb"),
        mediaInteractionCb: /* @__PURE__ */ __name((p2) => wrappedEmit({
          type: EventType$1.IncrementalSnapshot,
          data: {
            source: IncrementalSource.MediaInteraction,
            ...p2
          }
        }), "mediaInteractionCb"),
        styleSheetRuleCb: /* @__PURE__ */ __name((r2) => wrappedEmit({
          type: EventType$1.IncrementalSnapshot,
          data: {
            source: IncrementalSource.StyleSheetRule,
            ...r2
          }
        }), "styleSheetRuleCb"),
        styleDeclarationCb: /* @__PURE__ */ __name((r2) => wrappedEmit({
          type: EventType$1.IncrementalSnapshot,
          data: {
            source: IncrementalSource.StyleDeclaration,
            ...r2
          }
        }), "styleDeclarationCb"),
        canvasMutationCb: wrappedCanvasMutationEmit,
        fontCb: /* @__PURE__ */ __name((p2) => wrappedEmit({
          type: EventType$1.IncrementalSnapshot,
          data: {
            source: IncrementalSource.Font,
            ...p2
          }
        }), "fontCb"),
        selectionCb: /* @__PURE__ */ __name((p2) => {
          wrappedEmit({
            type: EventType$1.IncrementalSnapshot,
            data: {
              source: IncrementalSource.Selection,
              ...p2
            }
          });
        }, "selectionCb"),
        customElementCb: /* @__PURE__ */ __name((c2) => {
          wrappedEmit({
            type: EventType$1.IncrementalSnapshot,
            data: {
              source: IncrementalSource.CustomElement,
              ...c2
            }
          });
        }, "customElementCb"),
        blockClass,
        ignoreClass,
        ignoreSelector,
        maskAllText,
        maskTextClass,
        unmaskTextClass,
        maskTextSelector,
        unmaskTextSelector,
        maskInputOptions,
        inlineStylesheet,
        sampling,
        recordDOM,
        recordCanvas,
        inlineImages,
        userTriggeredOnInput,
        collectFonts,
        doc: doc2,
        maskAttributeFn,
        maskInputFn,
        maskTextFn,
        keepIframeSrcFn,
        blockSelector,
        unblockSelector,
        slimDOMOptions,
        dataURLOptions,
        mirror,
        iframeManager,
        stylesheetManager,
        shadowDomManager,
        processedNodeManager,
        canvasManager,
        ignoreCSSAttributes,
        plugins: _optionalChain([
          plugins,
          "optionalAccess",
          (_8) => _8.filter,
          "call",
          (_9) => _9((p2) => p2.observer),
          "optionalAccess",
          (_10) => _10.map,
          "call",
          (_11) => _11((p2) => ({
            observer: p2.observer,
            options: p2.options,
            callback: /* @__PURE__ */ __name((payload) => wrappedEmit({
              type: EventType$1.Plugin,
              data: {
                plugin: p2.name,
                payload
              }
            }), "callback")
          }))
        ]) || []
      }, {});
    }, "observe");
    iframeManager.addLoadListener((iframeEl) => {
      try {
        handlers2.push(observe2(iframeEl.contentDocument));
      } catch (error2) {
        console.warn(error2);
      }
    });
    const init2 = /* @__PURE__ */ __name(() => {
      takeFullSnapshot2();
      handlers2.push(observe2(document));
    }, "init");
    if (document.readyState === "interactive" || document.readyState === "complete") {
      init2();
    } else {
      handlers2.push(on$1("DOMContentLoaded", () => {
        wrappedEmit({
          type: EventType$1.DomContentLoaded,
          data: {}
        });
        if (recordAfter === "DOMContentLoaded")
          init2();
      }));
      handlers2.push(on$1("load", () => {
        wrappedEmit({
          type: EventType$1.Load,
          data: {}
        });
        if (recordAfter === "load")
          init2();
      }, window));
    }
    return () => {
      handlers2.forEach((h2) => h2());
      processedNodeManager.destroy();
      _takeFullSnapshot = void 0;
      unregisterErrorHandler();
    };
  } catch (error2) {
    console.warn(error2);
  }
}
__name(record, "record");
function takeFullSnapshot(isCheckout) {
  if (!_takeFullSnapshot) {
    throw new Error("please take full snapshot after start recording");
  }
  _takeFullSnapshot(isCheckout);
}
__name(takeFullSnapshot, "takeFullSnapshot");
record.mirror = mirror;
record.takeFullSnapshot = takeFullSnapshot;
function _getCanvasManager(getCanvasManagerFn, options2) {
  try {
    return getCanvasManagerFn ? getCanvasManagerFn(options2) : new CanvasManagerNoop();
  } catch (e2) {
    console.warn("Unable to initialize CanvasManager");
    return new CanvasManagerNoop();
  }
}
__name(_getCanvasManager, "_getCanvasManager");
const ReplayEventTypeIncrementalSnapshot = 3;
const ReplayEventTypeCustom = 5;
function timestampToMs(timestamp2) {
  const isMs = timestamp2 > 9999999999;
  return isMs ? timestamp2 : timestamp2 * 1e3;
}
__name(timestampToMs, "timestampToMs");
function timestampToS(timestamp2) {
  const isMs = timestamp2 > 9999999999;
  return isMs ? timestamp2 / 1e3 : timestamp2;
}
__name(timestampToS, "timestampToS");
function addBreadcrumbEvent(replay, breadcrumb) {
  if (breadcrumb.category === "sentry.transaction") {
    return;
  }
  if (["ui.click", "ui.input"].includes(breadcrumb.category)) {
    replay.triggerUserActivity();
  } else {
    replay.checkAndHandleExpiredSession();
  }
  replay.addUpdate(() => {
    replay.throttledAddEvent({
      type: EventType$1.Custom,
      // TODO: We were converting from ms to seconds for breadcrumbs, spans,
      // but maybe we should just keep them as milliseconds
      timestamp: (breadcrumb.timestamp || 0) * 1e3,
      data: {
        tag: "breadcrumb",
        // normalize to max. 10 depth and 1_000 properties per object
        payload: normalize$2(breadcrumb, 10, 1e3)
      }
    });
    return breadcrumb.category === "console";
  });
}
__name(addBreadcrumbEvent, "addBreadcrumbEvent");
const INTERACTIVE_SELECTOR = "button,a";
function getClosestInteractive(element) {
  const closestInteractive = element.closest(INTERACTIVE_SELECTOR);
  return closestInteractive || element;
}
__name(getClosestInteractive, "getClosestInteractive");
function getClickTargetNode(event) {
  const target = getTargetNode(event);
  if (!target || !(target instanceof Element)) {
    return target;
  }
  return getClosestInteractive(target);
}
__name(getClickTargetNode, "getClickTargetNode");
function getTargetNode(event) {
  if (isEventWithTarget(event)) {
    return event.target;
  }
  return event;
}
__name(getTargetNode, "getTargetNode");
function isEventWithTarget(event) {
  return typeof event === "object" && !!event && "target" in event;
}
__name(isEventWithTarget, "isEventWithTarget");
let handlers$2;
function onWindowOpen(cb) {
  if (!handlers$2) {
    handlers$2 = [];
    monkeyPatchWindowOpen();
  }
  handlers$2.push(cb);
  return () => {
    const pos = handlers$2 ? handlers$2.indexOf(cb) : -1;
    if (pos > -1) {
      handlers$2.splice(pos, 1);
    }
  };
}
__name(onWindowOpen, "onWindowOpen");
function monkeyPatchWindowOpen() {
  fill(WINDOW$1, "open", function(originalWindowOpen) {
    return function(...args) {
      if (handlers$2) {
        try {
          handlers$2.forEach((handler5) => handler5());
        } catch (e2) {
        }
      }
      return originalWindowOpen.apply(WINDOW$1, args);
    };
  });
}
__name(monkeyPatchWindowOpen, "monkeyPatchWindowOpen");
const IncrementalMutationSources = /* @__PURE__ */ new Set([
  IncrementalSource.Mutation,
  IncrementalSource.StyleSheetRule,
  IncrementalSource.StyleDeclaration,
  IncrementalSource.AdoptedStyleSheet,
  IncrementalSource.CanvasMutation,
  IncrementalSource.Selection,
  IncrementalSource.MediaInteraction
]);
function handleClick$1(clickDetector, clickBreadcrumb, node2) {
  clickDetector.handleClick(clickBreadcrumb, node2);
}
__name(handleClick$1, "handleClick$1");
class ClickDetector {
  static {
    __name(this, "ClickDetector");
  }
  // protected for testing
  constructor(replay, slowClickConfig, _addBreadcrumbEvent = addBreadcrumbEvent) {
    this._lastMutation = 0;
    this._lastScroll = 0;
    this._clicks = [];
    this._timeout = slowClickConfig.timeout / 1e3;
    this._threshold = slowClickConfig.threshold / 1e3;
    this._scrollTimeout = slowClickConfig.scrollTimeout / 1e3;
    this._replay = replay;
    this._ignoreSelector = slowClickConfig.ignoreSelector;
    this._addBreadcrumbEvent = _addBreadcrumbEvent;
  }
  /** Register click detection handlers on mutation or scroll. */
  addListeners() {
    const cleanupWindowOpen = onWindowOpen(() => {
      this._lastMutation = nowInSeconds();
    });
    this._teardown = () => {
      cleanupWindowOpen();
      this._clicks = [];
      this._lastMutation = 0;
      this._lastScroll = 0;
    };
  }
  /** Clean up listeners. */
  removeListeners() {
    if (this._teardown) {
      this._teardown();
    }
    if (this._checkClickTimeout) {
      clearTimeout(this._checkClickTimeout);
    }
  }
  /** @inheritDoc */
  handleClick(breadcrumb, node2) {
    if (ignoreElement(node2, this._ignoreSelector) || !isClickBreadcrumb(breadcrumb)) {
      return;
    }
    const newClick = {
      timestamp: timestampToS(breadcrumb.timestamp),
      clickBreadcrumb: breadcrumb,
      // Set this to 0 so we know it originates from the click breadcrumb
      clickCount: 0,
      node: node2
    };
    if (this._clicks.some((click2) => click2.node === newClick.node && Math.abs(click2.timestamp - newClick.timestamp) < 1)) {
      return;
    }
    this._clicks.push(newClick);
    if (this._clicks.length === 1) {
      this._scheduleCheckClicks();
    }
  }
  /** @inheritDoc */
  registerMutation(timestamp2 = Date.now()) {
    this._lastMutation = timestampToS(timestamp2);
  }
  /** @inheritDoc */
  registerScroll(timestamp2 = Date.now()) {
    this._lastScroll = timestampToS(timestamp2);
  }
  /** @inheritDoc */
  registerClick(element) {
    const node2 = getClosestInteractive(element);
    this._handleMultiClick(node2);
  }
  /** Count multiple clicks on elements. */
  _handleMultiClick(node2) {
    this._getClicks(node2).forEach((click2) => {
      click2.clickCount++;
    });
  }
  /** Get all pending clicks for a given node. */
  _getClicks(node2) {
    return this._clicks.filter((click2) => click2.node === node2);
  }
  /** Check the clicks that happened. */
  _checkClicks() {
    const timedOutClicks = [];
    const now2 = nowInSeconds();
    this._clicks.forEach((click2) => {
      if (!click2.mutationAfter && this._lastMutation) {
        click2.mutationAfter = click2.timestamp <= this._lastMutation ? this._lastMutation - click2.timestamp : void 0;
      }
      if (!click2.scrollAfter && this._lastScroll) {
        click2.scrollAfter = click2.timestamp <= this._lastScroll ? this._lastScroll - click2.timestamp : void 0;
      }
      if (click2.timestamp + this._timeout <= now2) {
        timedOutClicks.push(click2);
      }
    });
    for (const click2 of timedOutClicks) {
      const pos = this._clicks.indexOf(click2);
      if (pos > -1) {
        this._generateBreadcrumbs(click2);
        this._clicks.splice(pos, 1);
      }
    }
    if (this._clicks.length) {
      this._scheduleCheckClicks();
    }
  }
  /** Generate matching breadcrumb(s) for the click. */
  _generateBreadcrumbs(click2) {
    const replay = this._replay;
    const hadScroll = click2.scrollAfter && click2.scrollAfter <= this._scrollTimeout;
    const hadMutation = click2.mutationAfter && click2.mutationAfter <= this._threshold;
    const isSlowClick = !hadScroll && !hadMutation;
    const { clickCount, clickBreadcrumb } = click2;
    if (isSlowClick) {
      const timeAfterClickMs = Math.min(click2.mutationAfter || this._timeout, this._timeout) * 1e3;
      const endReason = timeAfterClickMs < this._timeout * 1e3 ? "mutation" : "timeout";
      const breadcrumb = {
        type: "default",
        message: clickBreadcrumb.message,
        timestamp: clickBreadcrumb.timestamp,
        category: "ui.slowClickDetected",
        data: {
          ...clickBreadcrumb.data,
          url: WINDOW$1.location.href,
          route: replay.getCurrentRoute(),
          timeAfterClickMs,
          endReason,
          // If clickCount === 0, it means multiClick was not correctly captured here
          // - we still want to send 1 in this case
          clickCount: clickCount || 1
        }
      };
      this._addBreadcrumbEvent(replay, breadcrumb);
      return;
    }
    if (clickCount > 1) {
      const breadcrumb = {
        type: "default",
        message: clickBreadcrumb.message,
        timestamp: clickBreadcrumb.timestamp,
        category: "ui.multiClick",
        data: {
          ...clickBreadcrumb.data,
          url: WINDOW$1.location.href,
          route: replay.getCurrentRoute(),
          clickCount,
          metric: true
        }
      };
      this._addBreadcrumbEvent(replay, breadcrumb);
    }
  }
  /** Schedule to check current clicks. */
  _scheduleCheckClicks() {
    if (this._checkClickTimeout) {
      clearTimeout(this._checkClickTimeout);
    }
    this._checkClickTimeout = setTimeout$3(() => this._checkClicks(), 1e3);
  }
}
const SLOW_CLICK_TAGS = ["A", "BUTTON", "INPUT"];
function ignoreElement(node2, ignoreSelector) {
  if (!SLOW_CLICK_TAGS.includes(node2.tagName)) {
    return true;
  }
  if (node2.tagName === "INPUT" && !["submit", "button"].includes(node2.getAttribute("type") || "")) {
    return true;
  }
  if (node2.tagName === "A" && (node2.hasAttribute("download") || node2.hasAttribute("target") && node2.getAttribute("target") !== "_self")) {
    return true;
  }
  if (ignoreSelector && node2.matches(ignoreSelector)) {
    return true;
  }
  return false;
}
__name(ignoreElement, "ignoreElement");
function isClickBreadcrumb(breadcrumb) {
  return !!(breadcrumb.data && typeof breadcrumb.data.nodeId === "number" && breadcrumb.timestamp);
}
__name(isClickBreadcrumb, "isClickBreadcrumb");
function nowInSeconds() {
  return Date.now() / 1e3;
}
__name(nowInSeconds, "nowInSeconds");
function updateClickDetectorForRecordingEvent(clickDetector, event) {
  try {
    if (!isIncrementalEvent(event)) {
      return;
    }
    const { source } = event.data;
    if (IncrementalMutationSources.has(source)) {
      clickDetector.registerMutation(event.timestamp);
    }
    if (source === IncrementalSource.Scroll) {
      clickDetector.registerScroll(event.timestamp);
    }
    if (isIncrementalMouseInteraction(event)) {
      const { type, id: id2 } = event.data;
      const node2 = record.mirror.getNode(id2);
      if (node2 instanceof HTMLElement && type === MouseInteractions.Click) {
        clickDetector.registerClick(node2);
      }
    }
  } catch (e2) {
  }
}
__name(updateClickDetectorForRecordingEvent, "updateClickDetectorForRecordingEvent");
function isIncrementalEvent(event) {
  return event.type === ReplayEventTypeIncrementalSnapshot;
}
__name(isIncrementalEvent, "isIncrementalEvent");
function isIncrementalMouseInteraction(event) {
  return event.data.source === IncrementalSource.MouseInteraction;
}
__name(isIncrementalMouseInteraction, "isIncrementalMouseInteraction");
function createBreadcrumb(breadcrumb) {
  return {
    timestamp: Date.now() / 1e3,
    type: "default",
    ...breadcrumb
  };
}
__name(createBreadcrumb, "createBreadcrumb");
var NodeType$4;
(function(NodeType3) {
  NodeType3[NodeType3["Document"] = 0] = "Document";
  NodeType3[NodeType3["DocumentType"] = 1] = "DocumentType";
  NodeType3[NodeType3["Element"] = 2] = "Element";
  NodeType3[NodeType3["Text"] = 3] = "Text";
  NodeType3[NodeType3["CDATA"] = 4] = "CDATA";
  NodeType3[NodeType3["Comment"] = 5] = "Comment";
})(NodeType$4 || (NodeType$4 = {}));
const ATTRIBUTES_TO_RECORD = /* @__PURE__ */ new Set([
  "id",
  "class",
  "aria-label",
  "role",
  "name",
  "alt",
  "title",
  "data-test-id",
  "data-testid",
  "disabled",
  "aria-disabled",
  "data-sentry-component"
]);
function getAttributesToRecord(attributes) {
  const obj = {};
  if (!attributes["data-sentry-component"] && attributes["data-sentry-element"]) {
    attributes["data-sentry-component"] = attributes["data-sentry-element"];
  }
  for (const key in attributes) {
    if (ATTRIBUTES_TO_RECORD.has(key)) {
      let normalizedKey = key;
      if (key === "data-testid" || key === "data-test-id") {
        normalizedKey = "testId";
      }
      obj[normalizedKey] = attributes[key];
    }
  }
  return obj;
}
__name(getAttributesToRecord, "getAttributesToRecord");
const handleDomListener = /* @__PURE__ */ __name((replay) => {
  return (handlerData) => {
    if (!replay.isEnabled()) {
      return;
    }
    const result = handleDom(handlerData);
    if (!result) {
      return;
    }
    const isClick = handlerData.name === "click";
    const event = isClick ? handlerData.event : void 0;
    if (isClick && replay.clickDetector && event && event.target && !event.altKey && !event.metaKey && !event.ctrlKey && !event.shiftKey) {
      handleClick$1(
        replay.clickDetector,
        result,
        getClickTargetNode(handlerData.event)
      );
    }
    addBreadcrumbEvent(replay, result);
  };
}, "handleDomListener");
function getBaseDomBreadcrumb(target, message) {
  const nodeId = record.mirror.getId(target);
  const node2 = nodeId && record.mirror.getNode(nodeId);
  const meta = node2 && record.mirror.getMeta(node2);
  const element = meta && isElement$2(meta) ? meta : null;
  return {
    message,
    data: element ? {
      nodeId,
      node: {
        id: nodeId,
        tagName: element.tagName,
        textContent: Array.from(element.childNodes).map((node3) => node3.type === NodeType$4.Text && node3.textContent).filter(Boolean).map((text2) => text2.trim()).join(""),
        attributes: getAttributesToRecord(element.attributes)
      }
    } : {}
  };
}
__name(getBaseDomBreadcrumb, "getBaseDomBreadcrumb");
function handleDom(handlerData) {
  const { target, message } = getDomTarget(handlerData);
  return createBreadcrumb({
    category: `ui.${handlerData.name}`,
    ...getBaseDomBreadcrumb(target, message)
  });
}
__name(handleDom, "handleDom");
function getDomTarget(handlerData) {
  const isClick = handlerData.name === "click";
  let message;
  let target = null;
  try {
    target = isClick ? getClickTargetNode(handlerData.event) : getTargetNode(handlerData.event);
    message = htmlTreeAsString(target, { maxStringLength: 200 }) || "<unknown>";
  } catch (e2) {
    message = "<unknown>";
  }
  return { target, message };
}
__name(getDomTarget, "getDomTarget");
function isElement$2(node2) {
  return node2.type === NodeType$4.Element;
}
__name(isElement$2, "isElement$2");
function handleKeyboardEvent(replay, event) {
  if (!replay.isEnabled()) {
    return;
  }
  replay.updateUserActivity();
  const breadcrumb = getKeyboardBreadcrumb(event);
  if (!breadcrumb) {
    return;
  }
  addBreadcrumbEvent(replay, breadcrumb);
}
__name(handleKeyboardEvent, "handleKeyboardEvent");
function getKeyboardBreadcrumb(event) {
  const { metaKey, shiftKey, ctrlKey, altKey, key, target } = event;
  if (!target || isInputElement(target) || !key) {
    return null;
  }
  const hasModifierKey = metaKey || ctrlKey || altKey;
  const isCharacterKey = key.length === 1;
  if (!hasModifierKey && isCharacterKey) {
    return null;
  }
  const message = htmlTreeAsString(target, { maxStringLength: 200 }) || "<unknown>";
  const baseBreadcrumb = getBaseDomBreadcrumb(target, message);
  return createBreadcrumb({
    category: "ui.keyDown",
    message,
    data: {
      ...baseBreadcrumb.data,
      metaKey,
      shiftKey,
      ctrlKey,
      altKey,
      key
    }
  });
}
__name(getKeyboardBreadcrumb, "getKeyboardBreadcrumb");
function isInputElement(target) {
  return target.tagName === "INPUT" || target.tagName === "TEXTAREA" || target.isContentEditable;
}
__name(isInputElement, "isInputElement");
const ENTRY_TYPES = {
  // @ts-expect-error TODO: entry type does not fit the create* functions entry type
  resource: createResourceEntry,
  paint: createPaintEntry,
  // @ts-expect-error TODO: entry type does not fit the create* functions entry type
  navigation: createNavigationEntry
};
function webVitalHandler(getter, replay) {
  return ({ metric }) => void replay.replayPerformanceEntries.push(getter(metric));
}
__name(webVitalHandler, "webVitalHandler");
function createPerformanceEntries(entries) {
  return entries.map(createPerformanceEntry).filter(Boolean);
}
__name(createPerformanceEntries, "createPerformanceEntries");
function createPerformanceEntry(entry) {
  const entryType = ENTRY_TYPES[entry.entryType];
  if (!entryType) {
    return null;
  }
  return entryType(entry);
}
__name(createPerformanceEntry, "createPerformanceEntry");
function getAbsoluteTime$1(time) {
  return ((browserPerformanceTimeOrigin || WINDOW$1.performance.timeOrigin) + time) / 1e3;
}
__name(getAbsoluteTime$1, "getAbsoluteTime$1");
function createPaintEntry(entry) {
  const { duration, entryType, name: name2, startTime } = entry;
  const start2 = getAbsoluteTime$1(startTime);
  return {
    type: entryType,
    name: name2,
    start: start2,
    end: start2 + duration,
    data: void 0
  };
}
__name(createPaintEntry, "createPaintEntry");
function createNavigationEntry(entry) {
  const {
    entryType,
    name: name2,
    decodedBodySize,
    duration,
    domComplete,
    encodedBodySize,
    domContentLoadedEventStart,
    domContentLoadedEventEnd,
    domInteractive,
    loadEventStart,
    loadEventEnd,
    redirectCount,
    startTime,
    transferSize,
    type
  } = entry;
  if (duration === 0) {
    return null;
  }
  return {
    type: `${entryType}.${type}`,
    start: getAbsoluteTime$1(startTime),
    end: getAbsoluteTime$1(domComplete),
    name: name2,
    data: {
      size: transferSize,
      decodedBodySize,
      encodedBodySize,
      duration,
      domInteractive,
      domContentLoadedEventStart,
      domContentLoadedEventEnd,
      loadEventStart,
      loadEventEnd,
      domComplete,
      redirectCount
    }
  };
}
__name(createNavigationEntry, "createNavigationEntry");
function createResourceEntry(entry) {
  const {
    entryType,
    initiatorType,
    name: name2,
    responseEnd,
    startTime,
    decodedBodySize,
    encodedBodySize,
    responseStatus,
    transferSize
  } = entry;
  if (["fetch", "xmlhttprequest"].includes(initiatorType)) {
    return null;
  }
  return {
    type: `${entryType}.${initiatorType}`,
    start: getAbsoluteTime$1(startTime),
    end: getAbsoluteTime$1(responseEnd),
    name: name2,
    data: {
      size: transferSize,
      statusCode: responseStatus,
      decodedBodySize,
      encodedBodySize
    }
  };
}
__name(createResourceEntry, "createResourceEntry");
function getLargestContentfulPaint(metric) {
  const lastEntry = metric.entries[metric.entries.length - 1];
  const node2 = lastEntry && lastEntry.element ? [lastEntry.element] : void 0;
  return getWebVital(metric, "largest-contentful-paint", node2);
}
__name(getLargestContentfulPaint, "getLargestContentfulPaint");
function isLayoutShift(entry) {
  return entry.sources !== void 0;
}
__name(isLayoutShift, "isLayoutShift");
function getCumulativeLayoutShift(metric) {
  const layoutShifts = [];
  const nodes = [];
  for (const entry of metric.entries) {
    if (isLayoutShift(entry)) {
      const nodeIds = [];
      for (const source of entry.sources) {
        if (source.node) {
          nodes.push(source.node);
          const nodeId = record.mirror.getId(source.node);
          if (nodeId) {
            nodeIds.push(nodeId);
          }
        }
      }
      layoutShifts.push({ value: entry.value, nodeIds: nodeIds.length ? nodeIds : void 0 });
    }
  }
  return getWebVital(metric, "cumulative-layout-shift", nodes, layoutShifts);
}
__name(getCumulativeLayoutShift, "getCumulativeLayoutShift");
function getFirstInputDelay(metric) {
  const lastEntry = metric.entries[metric.entries.length - 1];
  const node2 = lastEntry && lastEntry.target ? [lastEntry.target] : void 0;
  return getWebVital(metric, "first-input-delay", node2);
}
__name(getFirstInputDelay, "getFirstInputDelay");
function getInteractionToNextPaint(metric) {
  const lastEntry = metric.entries[metric.entries.length - 1];
  const node2 = lastEntry && lastEntry.target ? [lastEntry.target] : void 0;
  return getWebVital(metric, "interaction-to-next-paint", node2);
}
__name(getInteractionToNextPaint, "getInteractionToNextPaint");
function getWebVital(metric, name2, nodes, attributions) {
  const value = metric.value;
  const rating = metric.rating;
  const end = getAbsoluteTime$1(value);
  return {
    type: "web-vital",
    name: name2,
    start: end,
    end,
    data: {
      value,
      size: value,
      rating,
      nodeIds: nodes ? nodes.map((node2) => record.mirror.getId(node2)) : void 0,
      attributions
    }
  };
}
__name(getWebVital, "getWebVital");
function setupPerformanceObserver(replay) {
  function addPerformanceEntry(entry) {
    if (!replay.performanceEntries.includes(entry)) {
      replay.performanceEntries.push(entry);
    }
  }
  __name(addPerformanceEntry, "addPerformanceEntry");
  function onEntries({ entries }) {
    entries.forEach(addPerformanceEntry);
  }
  __name(onEntries, "onEntries");
  const clearCallbacks = [];
  ["navigation", "paint", "resource"].forEach((type) => {
    clearCallbacks.push(addPerformanceInstrumentationHandler(type, onEntries));
  });
  clearCallbacks.push(
    addLcpInstrumentationHandler(webVitalHandler(getLargestContentfulPaint, replay)),
    addClsInstrumentationHandler(webVitalHandler(getCumulativeLayoutShift, replay)),
    addFidInstrumentationHandler(webVitalHandler(getFirstInputDelay, replay)),
    addInpInstrumentationHandler(webVitalHandler(getInteractionToNextPaint, replay))
  );
  return () => {
    clearCallbacks.forEach((clearCallback) => clearCallback());
  };
}
__name(setupPerformanceObserver, "setupPerformanceObserver");
const DEBUG_BUILD$2 = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__;
const r$3 = `var t=Uint8Array,n=Uint16Array,r=Int32Array,e=new t([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),i=new t([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),a=new t([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),s=function(t,e){for(var i=new n(31),a=0;a<31;++a)i[a]=e+=1<<t[a-1];var s=new r(i[30]);for(a=1;a<30;++a)for(var o=i[a];o<i[a+1];++o)s[o]=o-i[a]<<5|a;return{b:i,r:s}},o=s(e,2),f=o.b,h=o.r;f[28]=258,h[258]=28;for(var l=s(i,0).r,u=new n(32768),c=0;c<32768;++c){var v=(43690&c)>>1|(21845&c)<<1;v=(61680&(v=(52428&v)>>2|(13107&v)<<2))>>4|(3855&v)<<4,u[c]=((65280&v)>>8|(255&v)<<8)>>1}var d=function(t,r,e){for(var i=t.length,a=0,s=new n(r);a<i;++a)t[a]&&++s[t[a]-1];var o,f=new n(r);for(a=1;a<r;++a)f[a]=f[a-1]+s[a-1]<<1;if(e){o=new n(1<<r);var h=15-r;for(a=0;a<i;++a)if(t[a])for(var l=a<<4|t[a],c=r-t[a],v=f[t[a]-1]++<<c,d=v|(1<<c)-1;v<=d;++v)o[u[v]>>h]=l}else for(o=new n(i),a=0;a<i;++a)t[a]&&(o[a]=u[f[t[a]-1]++]>>15-t[a]);return o},g=new t(288);for(c=0;c<144;++c)g[c]=8;for(c=144;c<256;++c)g[c]=9;for(c=256;c<280;++c)g[c]=7;for(c=280;c<288;++c)g[c]=8;var w=new t(32);for(c=0;c<32;++c)w[c]=5;var p=d(g,9,0),y=d(w,5,0),m=function(t){return(t+7)/8|0},b=function(n,r,e){return(null==e||e>n.length)&&(e=n.length),new t(n.subarray(r,e))},M=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],E=function(t,n,r){var e=new Error(n||M[t]);if(e.code=t,Error.captureStackTrace&&Error.captureStackTrace(e,E),!r)throw e;return e},z=function(t,n,r){r<<=7&n;var e=n/8|0;t[e]|=r,t[e+1]|=r>>8},_=function(t,n,r){r<<=7&n;var e=n/8|0;t[e]|=r,t[e+1]|=r>>8,t[e+2]|=r>>16},x=function(r,e){for(var i=[],a=0;a<r.length;++a)r[a]&&i.push({s:a,f:r[a]});var s=i.length,o=i.slice();if(!s)return{t:F,l:0};if(1==s){var f=new t(i[0].s+1);return f[i[0].s]=1,{t:f,l:1}}i.sort((function(t,n){return t.f-n.f})),i.push({s:-1,f:25001});var h=i[0],l=i[1],u=0,c=1,v=2;for(i[0]={s:-1,f:h.f+l.f,l:h,r:l};c!=s-1;)h=i[i[u].f<i[v].f?u++:v++],l=i[u!=c&&i[u].f<i[v].f?u++:v++],i[c++]={s:-1,f:h.f+l.f,l:h,r:l};var d=o[0].s;for(a=1;a<s;++a)o[a].s>d&&(d=o[a].s);var g=new n(d+1),w=A(i[c-1],g,0);if(w>e){a=0;var p=0,y=w-e,m=1<<y;for(o.sort((function(t,n){return g[n.s]-g[t.s]||t.f-n.f}));a<s;++a){var b=o[a].s;if(!(g[b]>e))break;p+=m-(1<<w-g[b]),g[b]=e}for(p>>=y;p>0;){var M=o[a].s;g[M]<e?p-=1<<e-g[M]++-1:++a}for(;a>=0&&p;--a){var E=o[a].s;g[E]==e&&(--g[E],++p)}w=e}return{t:new t(g),l:w}},A=function(t,n,r){return-1==t.s?Math.max(A(t.l,n,r+1),A(t.r,n,r+1)):n[t.s]=r},D=function(t){for(var r=t.length;r&&!t[--r];);for(var e=new n(++r),i=0,a=t[0],s=1,o=function(t){e[i++]=t},f=1;f<=r;++f)if(t[f]==a&&f!=r)++s;else{if(!a&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(a),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(a);s=1,a=t[f]}return{c:e.subarray(0,i),n:r}},T=function(t,n){for(var r=0,e=0;e<n.length;++e)r+=t[e]*n[e];return r},k=function(t,n,r){var e=r.length,i=m(n+2);t[i]=255&e,t[i+1]=e>>8,t[i+2]=255^t[i],t[i+3]=255^t[i+1];for(var a=0;a<e;++a)t[i+a+4]=r[a];return 8*(i+4+e)},U=function(t,r,s,o,f,h,l,u,c,v,m){z(r,m++,s),++f[256];for(var b=x(f,15),M=b.t,E=b.l,A=x(h,15),U=A.t,C=A.l,F=D(M),I=F.c,S=F.n,L=D(U),O=L.c,j=L.n,q=new n(19),B=0;B<I.length;++B)++q[31&I[B]];for(B=0;B<O.length;++B)++q[31&O[B]];for(var G=x(q,7),H=G.t,J=G.l,K=19;K>4&&!H[a[K-1]];--K);var N,P,Q,R,V=v+5<<3,W=T(f,g)+T(h,w)+l,X=T(f,M)+T(h,U)+l+14+3*K+T(q,H)+2*q[16]+3*q[17]+7*q[18];if(c>=0&&V<=W&&V<=X)return k(r,m,t.subarray(c,c+v));if(z(r,m,1+(X<W)),m+=2,X<W){N=d(M,E,0),P=M,Q=d(U,C,0),R=U;var Y=d(H,J,0);z(r,m,S-257),z(r,m+5,j-1),z(r,m+10,K-4),m+=14;for(B=0;B<K;++B)z(r,m+3*B,H[a[B]]);m+=3*K;for(var Z=[I,O],$=0;$<2;++$){var tt=Z[$];for(B=0;B<tt.length;++B){var nt=31&tt[B];z(r,m,Y[nt]),m+=H[nt],nt>15&&(z(r,m,tt[B]>>5&127),m+=tt[B]>>12)}}}else N=p,P=g,Q=y,R=w;for(B=0;B<u;++B){var rt=o[B];if(rt>255){_(r,m,N[(nt=rt>>18&31)+257]),m+=P[nt+257],nt>7&&(z(r,m,rt>>23&31),m+=e[nt]);var et=31&rt;_(r,m,Q[et]),m+=R[et],et>3&&(_(r,m,rt>>5&8191),m+=i[et])}else _(r,m,N[rt]),m+=P[rt]}return _(r,m,N[256]),m+P[256]},C=new r([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),F=new t(0),I=function(){for(var t=new Int32Array(256),n=0;n<256;++n){for(var r=n,e=9;--e;)r=(1&r&&-306674912)^r>>>1;t[n]=r}return t}(),S=function(){var t=-1;return{p:function(n){for(var r=t,e=0;e<n.length;++e)r=I[255&r^n[e]]^r>>>8;t=r},d:function(){return~t}}},L=function(){var t=1,n=0;return{p:function(r){for(var e=t,i=n,a=0|r.length,s=0;s!=a;){for(var o=Math.min(s+2655,a);s<o;++s)i+=e+=r[s];e=(65535&e)+15*(e>>16),i=(65535&i)+15*(i>>16)}t=e,n=i},d:function(){return(255&(t%=65521))<<24|(65280&t)<<8|(255&(n%=65521))<<8|n>>8}}},O=function(a,s,o,f,u){if(!u&&(u={l:1},s.dictionary)){var c=s.dictionary.subarray(-32768),v=new t(c.length+a.length);v.set(c),v.set(a,c.length),a=v,u.w=c.length}return function(a,s,o,f,u,c){var v=c.z||a.length,d=new t(f+v+5*(1+Math.ceil(v/7e3))+u),g=d.subarray(f,d.length-u),w=c.l,p=7&(c.r||0);if(s){p&&(g[0]=c.r>>3);for(var y=C[s-1],M=y>>13,E=8191&y,z=(1<<o)-1,_=c.p||new n(32768),x=c.h||new n(z+1),A=Math.ceil(o/3),D=2*A,T=function(t){return(a[t]^a[t+1]<<A^a[t+2]<<D)&z},F=new r(25e3),I=new n(288),S=new n(32),L=0,O=0,j=c.i||0,q=0,B=c.w||0,G=0;j+2<v;++j){var H=T(j),J=32767&j,K=x[H];if(_[J]=K,x[H]=J,B<=j){var N=v-j;if((L>7e3||q>24576)&&(N>423||!w)){p=U(a,g,0,F,I,S,O,q,G,j-G,p),q=L=O=0,G=j;for(var P=0;P<286;++P)I[P]=0;for(P=0;P<30;++P)S[P]=0}var Q=2,R=0,V=E,W=J-K&32767;if(N>2&&H==T(j-W))for(var X=Math.min(M,N)-1,Y=Math.min(32767,j),Z=Math.min(258,N);W<=Y&&--V&&J!=K;){if(a[j+Q]==a[j+Q-W]){for(var $=0;$<Z&&a[j+$]==a[j+$-W];++$);if($>Q){if(Q=$,R=W,$>X)break;var tt=Math.min(W,$-2),nt=0;for(P=0;P<tt;++P){var rt=j-W+P&32767,et=rt-_[rt]&32767;et>nt&&(nt=et,K=rt)}}}W+=(J=K)-(K=_[J])&32767}if(R){F[q++]=268435456|h[Q]<<18|l[R];var it=31&h[Q],at=31&l[R];O+=e[it]+i[at],++I[257+it],++S[at],B=j+Q,++L}else F[q++]=a[j],++I[a[j]]}}for(j=Math.max(j,B);j<v;++j)F[q++]=a[j],++I[a[j]];p=U(a,g,w,F,I,S,O,q,G,j-G,p),w||(c.r=7&p|g[p/8|0]<<3,p-=7,c.h=x,c.p=_,c.i=j,c.w=B)}else{for(j=c.w||0;j<v+w;j+=65535){var st=j+65535;st>=v&&(g[p/8|0]=w,st=v),p=k(g,p+1,a.subarray(j,st))}c.i=v}return b(d,0,f+m(p)+u)}(a,null==s.level?6:s.level,null==s.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(a.length)))):12+s.mem,o,f,u)},j=function(t,n,r){for(;r;++n)t[n]=r,r>>>=8},q=function(t,n){var r=n.filename;if(t[0]=31,t[1]=139,t[2]=8,t[8]=n.level<2?4:9==n.level?2:0,t[9]=3,0!=n.mtime&&j(t,4,Math.floor(new Date(n.mtime||Date.now())/1e3)),r){t[3]=8;for(var e=0;e<=r.length;++e)t[e+10]=r.charCodeAt(e)}},B=function(t){return 10+(t.filename?t.filename.length+1:0)},G=function(){function n(n,r){if("function"==typeof n&&(r=n,n={}),this.ondata=r,this.o=n||{},this.s={l:0,i:32768,w:32768,z:32768},this.b=new t(98304),this.o.dictionary){var e=this.o.dictionary.subarray(-32768);this.b.set(e,32768-e.length),this.s.i=32768-e.length}}return n.prototype.p=function(t,n){this.ondata(O(t,this.o,0,0,this.s),n)},n.prototype.push=function(n,r){this.ondata||E(5),this.s.l&&E(4);var e=n.length+this.s.z;if(e>this.b.length){if(e>2*this.b.length-32768){var i=new t(-32768&e);i.set(this.b.subarray(0,this.s.z)),this.b=i}var a=this.b.length-this.s.z;a&&(this.b.set(n.subarray(0,a),this.s.z),this.s.z=this.b.length,this.p(this.b,!1)),this.b.set(this.b.subarray(-32768)),this.b.set(n.subarray(a),32768),this.s.z=n.length-a+32768,this.s.i=32766,this.s.w=32768}else this.b.set(n,this.s.z),this.s.z+=n.length;this.s.l=1&r,(this.s.z>this.s.w+8191||r)&&(this.p(this.b,r||!1),this.s.w=this.s.i,this.s.i-=2)},n}();var H=function(){function t(t,n){this.c=L(),this.v=1,G.call(this,t,n)}return t.prototype.push=function(t,n){this.c.p(t),G.prototype.push.call(this,t,n)},t.prototype.p=function(t,n){var r=O(t,this.o,this.v&&(this.o.dictionary?6:2),n&&4,this.s);this.v&&(function(t,n){var r=n.level,e=0==r?0:r<6?1:9==r?3:2;if(t[0]=120,t[1]=e<<6|(n.dictionary&&32),t[1]|=31-(t[0]<<8|t[1])%31,n.dictionary){var i=L();i.p(n.dictionary),j(t,2,i.d())}}(r,this.o),this.v=0),n&&j(r,r.length-4,this.c.d()),this.ondata(r,n)},t}(),J="undefined"!=typeof TextEncoder&&new TextEncoder,K="undefined"!=typeof TextDecoder&&new TextDecoder;try{K.decode(F,{stream:!0})}catch(t){}var N=function(){function t(t){this.ondata=t}return t.prototype.push=function(t,n){this.ondata||E(5),this.d&&E(4),this.ondata(P(t),this.d=n||!1)},t}();function P(n,r){if(J)return J.encode(n);for(var e=n.length,i=new t(n.length+(n.length>>1)),a=0,s=function(t){i[a++]=t},o=0;o<e;++o){if(a+5>i.length){var f=new t(a+8+(e-o<<1));f.set(i),i=f}var h=n.charCodeAt(o);h<128||r?s(h):h<2048?(s(192|h>>6),s(128|63&h)):h>55295&&h<57344?(s(240|(h=65536+(1047552&h)|1023&n.charCodeAt(++o))>>18),s(128|h>>12&63),s(128|h>>6&63),s(128|63&h)):(s(224|h>>12),s(128|h>>6&63),s(128|63&h))}return b(i,0,a)}function Q(t){return function(t,n){n||(n={});var r=S(),e=t.length;r.p(t);var i=O(t,n,B(n),8),a=i.length;return q(i,n),j(i,a-8,r.d()),j(i,a-4,e),i}(P(t))}const R=new class{constructor(){this._init()}clear(){this._init()}addEvent(t){if(!t)throw new Error("Adding invalid event");const n=this._hasEvents?",":"";this.stream.push(n+t),this._hasEvents=!0}finish(){this.stream.push("]",!0);const t=function(t){let n=0;for(const r of t)n+=r.length;const r=new Uint8Array(n);for(let n=0,e=0,i=t.length;n<i;n++){const i=t[n];r.set(i,e),e+=i.length}return r}(this._deflatedData);return this._init(),t}_init(){this._hasEvents=!1,this._deflatedData=[],this.deflate=new H,this.deflate.ondata=(t,n)=>{this._deflatedData.push(t)},this.stream=new N(((t,n)=>{this.deflate.push(t,n)})),this.stream.push("[")}},V={clear:()=>{R.clear()},addEvent:t=>R.addEvent(t),finish:()=>R.finish(),compress:t=>Q(t)};addEventListener("message",(function(t){const n=t.data.method,r=t.data.id,e=t.data.arg;if(n in V&&"function"==typeof V[n])try{const t=V[n](e);postMessage({id:r,method:n,success:!0,response:t})}catch(t){postMessage({id:r,method:n,success:!1,response:t.message}),console.error(t)}})),postMessage({id:void 0,method:"init",success:!0,response:void 0});`;
function e$1() {
  const e2 = new Blob([r$3]);
  return URL.createObjectURL(e2);
}
__name(e$1, "e$1");
const CONSOLE_LEVELS = ["info", "warn", "error", "log"];
const PREFIX$1 = "[Replay] ";
function _addBreadcrumb(message, level = "info") {
  addBreadcrumb(
    {
      category: "console",
      data: {
        logger: "replay"
      },
      level,
      message: `${PREFIX$1}${message}`
    },
    { level }
  );
}
__name(_addBreadcrumb, "_addBreadcrumb");
function makeReplayLogger() {
  let _capture = false;
  let _trace = false;
  const _logger = {
    exception: /* @__PURE__ */ __name(() => void 0, "exception"),
    infoTick: /* @__PURE__ */ __name(() => void 0, "infoTick"),
    setConfig: /* @__PURE__ */ __name((opts) => {
      _capture = opts.captureExceptions;
      _trace = opts.traceInternals;
    }, "setConfig")
  };
  if (DEBUG_BUILD$2) {
    CONSOLE_LEVELS.forEach((name2) => {
      _logger[name2] = (...args) => {
        logger$5[name2](PREFIX$1, ...args);
        if (_trace) {
          _addBreadcrumb(args.join(""), severityLevelFromString(name2));
        }
      };
    });
    _logger.exception = (error2, ...message) => {
      if (message.length && _logger.error) {
        _logger.error(...message);
      }
      logger$5.error(PREFIX$1, error2);
      if (_capture) {
        captureException(error2);
      } else if (_trace) {
        _addBreadcrumb(error2, "error");
      }
    };
    _logger.infoTick = (...args) => {
      logger$5.info(PREFIX$1, ...args);
      if (_trace) {
        setTimeout(() => _addBreadcrumb(args[0]), 0);
      }
    };
  } else {
    CONSOLE_LEVELS.forEach((name2) => {
      _logger[name2] = () => void 0;
    });
  }
  return _logger;
}
__name(makeReplayLogger, "makeReplayLogger");
const logger$4 = makeReplayLogger();
class EventBufferSizeExceededError extends Error {
  static {
    __name(this, "EventBufferSizeExceededError");
  }
  constructor() {
    super(`Event buffer exceeded maximum size of ${REPLAY_MAX_EVENT_BUFFER_SIZE}.`);
  }
}
class EventBufferArray {
  static {
    __name(this, "EventBufferArray");
  }
  /** All the events that are buffered to be sent. */
  /** @inheritdoc */
  /** @inheritdoc */
  constructor() {
    this.events = [];
    this._totalSize = 0;
    this.hasCheckout = false;
    this.waitForCheckout = false;
  }
  /** @inheritdoc */
  get hasEvents() {
    return this.events.length > 0;
  }
  /** @inheritdoc */
  get type() {
    return "sync";
  }
  /** @inheritdoc */
  destroy() {
    this.events = [];
  }
  /** @inheritdoc */
  async addEvent(event) {
    const eventSize = JSON.stringify(event).length;
    this._totalSize += eventSize;
    if (this._totalSize > REPLAY_MAX_EVENT_BUFFER_SIZE) {
      throw new EventBufferSizeExceededError();
    }
    this.events.push(event);
  }
  /** @inheritdoc */
  finish() {
    return new Promise((resolve2) => {
      const eventsRet = this.events;
      this.clear();
      resolve2(JSON.stringify(eventsRet));
    });
  }
  /** @inheritdoc */
  clear() {
    this.events = [];
    this._totalSize = 0;
    this.hasCheckout = false;
  }
  /** @inheritdoc */
  getEarliestTimestamp() {
    const timestamp2 = this.events.map((event) => event.timestamp).sort()[0];
    if (!timestamp2) {
      return null;
    }
    return timestampToMs(timestamp2);
  }
}
class WorkerHandler {
  static {
    __name(this, "WorkerHandler");
  }
  constructor(worker) {
    this._worker = worker;
    this._id = 0;
  }
  /**
   * Ensure the worker is ready (or not).
   * This will either resolve when the worker is ready, or reject if an error occurred.
   */
  ensureReady() {
    if (this._ensureReadyPromise) {
      return this._ensureReadyPromise;
    }
    this._ensureReadyPromise = new Promise((resolve2, reject) => {
      this._worker.addEventListener(
        "message",
        ({ data }) => {
          if (data.success) {
            resolve2();
          } else {
            reject();
          }
        },
        { once: true }
      );
      this._worker.addEventListener(
        "error",
        (error2) => {
          reject(error2);
        },
        { once: true }
      );
    });
    return this._ensureReadyPromise;
  }
  /**
   * Destroy the worker.
   */
  destroy() {
    DEBUG_BUILD$2 && logger$4.info("Destroying compression worker");
    this._worker.terminate();
  }
  /**
   * Post message to worker and wait for response before resolving promise.
   */
  postMessage(method, arg) {
    const id2 = this._getAndIncrementId();
    return new Promise((resolve2, reject) => {
      const listener = /* @__PURE__ */ __name(({ data }) => {
        const response = data;
        if (response.method !== method) {
          return;
        }
        if (response.id !== id2) {
          return;
        }
        this._worker.removeEventListener("message", listener);
        if (!response.success) {
          DEBUG_BUILD$2 && logger$4.error("Error in compression worker: ", response.response);
          reject(new Error("Error in compression worker"));
          return;
        }
        resolve2(response.response);
      }, "listener");
      this._worker.addEventListener("message", listener);
      this._worker.postMessage({ id: id2, method, arg });
    });
  }
  /** Get the current ID and increment it for the next call. */
  _getAndIncrementId() {
    return this._id++;
  }
}
class EventBufferCompressionWorker {
  static {
    __name(this, "EventBufferCompressionWorker");
  }
  /** @inheritdoc */
  /** @inheritdoc */
  constructor(worker) {
    this._worker = new WorkerHandler(worker);
    this._earliestTimestamp = null;
    this._totalSize = 0;
    this.hasCheckout = false;
    this.waitForCheckout = false;
  }
  /** @inheritdoc */
  get hasEvents() {
    return !!this._earliestTimestamp;
  }
  /** @inheritdoc */
  get type() {
    return "worker";
  }
  /**
   * Ensure the worker is ready (or not).
   * This will either resolve when the worker is ready, or reject if an error occurred.
   */
  ensureReady() {
    return this._worker.ensureReady();
  }
  /**
   * Destroy the event buffer.
   */
  destroy() {
    this._worker.destroy();
  }
  /**
   * Add an event to the event buffer.
   *
   * Returns true if event was successfully received and processed by worker.
   */
  addEvent(event) {
    const timestamp2 = timestampToMs(event.timestamp);
    if (!this._earliestTimestamp || timestamp2 < this._earliestTimestamp) {
      this._earliestTimestamp = timestamp2;
    }
    const data = JSON.stringify(event);
    this._totalSize += data.length;
    if (this._totalSize > REPLAY_MAX_EVENT_BUFFER_SIZE) {
      return Promise.reject(new EventBufferSizeExceededError());
    }
    return this._sendEventToWorker(data);
  }
  /**
   * Finish the event buffer and return the compressed data.
   */
  finish() {
    return this._finishRequest();
  }
  /** @inheritdoc */
  clear() {
    this._earliestTimestamp = null;
    this._totalSize = 0;
    this.hasCheckout = false;
    this._worker.postMessage("clear").then(null, (e2) => {
      DEBUG_BUILD$2 && logger$4.exception(e2, 'Sending "clear" message to worker failed', e2);
    });
  }
  /** @inheritdoc */
  getEarliestTimestamp() {
    return this._earliestTimestamp;
  }
  /**
   * Send the event to the worker.
   */
  _sendEventToWorker(data) {
    return this._worker.postMessage("addEvent", data);
  }
  /**
   * Finish the request and return the compressed data from the worker.
   */
  async _finishRequest() {
    const response = await this._worker.postMessage("finish");
    this._earliestTimestamp = null;
    this._totalSize = 0;
    return response;
  }
}
class EventBufferProxy {
  static {
    __name(this, "EventBufferProxy");
  }
  constructor(worker) {
    this._fallback = new EventBufferArray();
    this._compression = new EventBufferCompressionWorker(worker);
    this._used = this._fallback;
    this._ensureWorkerIsLoadedPromise = this._ensureWorkerIsLoaded();
  }
  /** @inheritdoc */
  get waitForCheckout() {
    return this._used.waitForCheckout;
  }
  /** @inheritdoc */
  get type() {
    return this._used.type;
  }
  /** @inheritDoc */
  get hasEvents() {
    return this._used.hasEvents;
  }
  /** @inheritdoc */
  get hasCheckout() {
    return this._used.hasCheckout;
  }
  /** @inheritdoc */
  set hasCheckout(value) {
    this._used.hasCheckout = value;
  }
  /** @inheritdoc */
  // eslint-disable-next-line @typescript-eslint/adjacent-overload-signatures
  set waitForCheckout(value) {
    this._used.waitForCheckout = value;
  }
  /** @inheritDoc */
  destroy() {
    this._fallback.destroy();
    this._compression.destroy();
  }
  /** @inheritdoc */
  clear() {
    return this._used.clear();
  }
  /** @inheritdoc */
  getEarliestTimestamp() {
    return this._used.getEarliestTimestamp();
  }
  /**
   * Add an event to the event buffer.
   *
   * Returns true if event was successfully added.
   */
  addEvent(event) {
    return this._used.addEvent(event);
  }
  /** @inheritDoc */
  async finish() {
    await this.ensureWorkerIsLoaded();
    return this._used.finish();
  }
  /** Ensure the worker has loaded. */
  ensureWorkerIsLoaded() {
    return this._ensureWorkerIsLoadedPromise;
  }
  /** Actually check if the worker has been loaded. */
  async _ensureWorkerIsLoaded() {
    try {
      await this._compression.ensureReady();
    } catch (error2) {
      DEBUG_BUILD$2 && logger$4.exception(error2, "Failed to load the compression worker, falling back to simple buffer");
      return;
    }
    await this._switchToCompressionWorker();
  }
  /** Switch the used buffer to the compression worker. */
  async _switchToCompressionWorker() {
    const { events: events2, hasCheckout, waitForCheckout } = this._fallback;
    const addEventPromises = [];
    for (const event of events2) {
      addEventPromises.push(this._compression.addEvent(event));
    }
    this._compression.hasCheckout = hasCheckout;
    this._compression.waitForCheckout = waitForCheckout;
    this._used = this._compression;
    try {
      await Promise.all(addEventPromises);
      this._fallback.clear();
    } catch (error2) {
      DEBUG_BUILD$2 && logger$4.exception(error2, "Failed to add events when switching buffers.");
    }
  }
}
function createEventBuffer({
  useCompression,
  workerUrl: customWorkerUrl
}) {
  if (useCompression && // eslint-disable-next-line no-restricted-globals
  window.Worker) {
    const worker = _loadWorker(customWorkerUrl);
    if (worker) {
      return worker;
    }
  }
  DEBUG_BUILD$2 && logger$4.info("Using simple buffer");
  return new EventBufferArray();
}
__name(createEventBuffer, "createEventBuffer");
function _loadWorker(customWorkerUrl) {
  try {
    const workerUrl = customWorkerUrl || _getWorkerUrl();
    if (!workerUrl) {
      return;
    }
    DEBUG_BUILD$2 && logger$4.info(`Using compression worker${customWorkerUrl ? ` from ${customWorkerUrl}` : ""}`);
    const worker = new Worker(workerUrl);
    return new EventBufferProxy(worker);
  } catch (error2) {
    DEBUG_BUILD$2 && logger$4.exception(error2, "Failed to create compression worker");
  }
}
__name(_loadWorker, "_loadWorker");
function _getWorkerUrl() {
  if (typeof __SENTRY_EXCLUDE_REPLAY_WORKER__ === "undefined" || !__SENTRY_EXCLUDE_REPLAY_WORKER__) {
    return e$1();
  }
  return "";
}
__name(_getWorkerUrl, "_getWorkerUrl");
function hasSessionStorage() {
  try {
    return "sessionStorage" in WINDOW$1 && !!WINDOW$1.sessionStorage;
  } catch (e2) {
    return false;
  }
}
__name(hasSessionStorage, "hasSessionStorage");
function clearSession(replay) {
  deleteSession();
  replay.session = void 0;
}
__name(clearSession, "clearSession");
function deleteSession() {
  if (!hasSessionStorage()) {
    return;
  }
  try {
    WINDOW$1.sessionStorage.removeItem(REPLAY_SESSION_KEY);
  } catch (e2) {
  }
}
__name(deleteSession, "deleteSession");
function isSampled(sampleRate) {
  if (sampleRate === void 0) {
    return false;
  }
  return Math.random() < sampleRate;
}
__name(isSampled, "isSampled");
function makeSession(session) {
  const now2 = Date.now();
  const id2 = session.id || uuid4();
  const started = session.started || now2;
  const lastActivity = session.lastActivity || now2;
  const segmentId = session.segmentId || 0;
  const sampled = session.sampled;
  const previousSessionId = session.previousSessionId;
  return {
    id: id2,
    started,
    lastActivity,
    segmentId,
    sampled,
    previousSessionId
  };
}
__name(makeSession, "makeSession");
function saveSession(session) {
  if (!hasSessionStorage()) {
    return;
  }
  try {
    WINDOW$1.sessionStorage.setItem(REPLAY_SESSION_KEY, JSON.stringify(session));
  } catch (e2) {
  }
}
__name(saveSession, "saveSession");
function getSessionSampleType(sessionSampleRate, allowBuffering) {
  return isSampled(sessionSampleRate) ? "session" : allowBuffering ? "buffer" : false;
}
__name(getSessionSampleType, "getSessionSampleType");
function createSession({ sessionSampleRate, allowBuffering, stickySession = false }, { previousSessionId } = {}) {
  const sampled = getSessionSampleType(sessionSampleRate, allowBuffering);
  const session = makeSession({
    sampled,
    previousSessionId
  });
  if (stickySession) {
    saveSession(session);
  }
  return session;
}
__name(createSession, "createSession");
function fetchSession() {
  if (!hasSessionStorage()) {
    return null;
  }
  try {
    const sessionStringFromStorage = WINDOW$1.sessionStorage.getItem(REPLAY_SESSION_KEY);
    if (!sessionStringFromStorage) {
      return null;
    }
    const sessionObj = JSON.parse(sessionStringFromStorage);
    DEBUG_BUILD$2 && logger$4.infoTick("Loading existing session");
    return makeSession(sessionObj);
  } catch (e2) {
    return null;
  }
}
__name(fetchSession, "fetchSession");
function isExpired(initialTime, expiry, targetTime = +/* @__PURE__ */ new Date()) {
  if (initialTime === null || expiry === void 0 || expiry < 0) {
    return true;
  }
  if (expiry === 0) {
    return false;
  }
  return initialTime + expiry <= targetTime;
}
__name(isExpired, "isExpired");
function isSessionExpired(session, {
  maxReplayDuration,
  sessionIdleExpire,
  targetTime = Date.now()
}) {
  return (
    // First, check that maximum session length has not been exceeded
    isExpired(session.started, maxReplayDuration, targetTime) || // check that the idle timeout has not been exceeded (i.e. user has
    // performed an action within the last `sessionIdleExpire` ms)
    isExpired(session.lastActivity, sessionIdleExpire, targetTime)
  );
}
__name(isSessionExpired, "isSessionExpired");
function shouldRefreshSession(session, { sessionIdleExpire, maxReplayDuration }) {
  if (!isSessionExpired(session, { sessionIdleExpire, maxReplayDuration })) {
    return false;
  }
  if (session.sampled === "buffer" && session.segmentId === 0) {
    return false;
  }
  return true;
}
__name(shouldRefreshSession, "shouldRefreshSession");
function loadOrCreateSession({
  sessionIdleExpire,
  maxReplayDuration,
  previousSessionId
}, sessionOptions) {
  const existingSession = sessionOptions.stickySession && fetchSession();
  if (!existingSession) {
    DEBUG_BUILD$2 && logger$4.infoTick("Creating new session");
    return createSession(sessionOptions, { previousSessionId });
  }
  if (!shouldRefreshSession(existingSession, { sessionIdleExpire, maxReplayDuration })) {
    return existingSession;
  }
  DEBUG_BUILD$2 && logger$4.infoTick("Session in sessionStorage is expired, creating new one...");
  return createSession(sessionOptions, { previousSessionId: existingSession.id });
}
__name(loadOrCreateSession, "loadOrCreateSession");
function isCustomEvent(event) {
  return event.type === EventType$1.Custom;
}
__name(isCustomEvent, "isCustomEvent");
function addEventSync(replay, event, isCheckout) {
  if (!shouldAddEvent(replay, event)) {
    return false;
  }
  _addEvent(replay, event, isCheckout);
  return true;
}
__name(addEventSync, "addEventSync");
function addEvent(replay, event, isCheckout) {
  if (!shouldAddEvent(replay, event)) {
    return Promise.resolve(null);
  }
  return _addEvent(replay, event, isCheckout);
}
__name(addEvent, "addEvent");
async function _addEvent(replay, event, isCheckout) {
  const { eventBuffer } = replay;
  if (!eventBuffer || eventBuffer.waitForCheckout && !isCheckout) {
    return null;
  }
  const isBufferMode = replay.recordingMode === "buffer";
  try {
    if (isCheckout && isBufferMode) {
      eventBuffer.clear();
    }
    if (isCheckout) {
      eventBuffer.hasCheckout = true;
      eventBuffer.waitForCheckout = false;
    }
    const replayOptions = replay.getOptions();
    const eventAfterPossibleCallback = maybeApplyCallback(event, replayOptions.beforeAddRecordingEvent);
    if (!eventAfterPossibleCallback) {
      return;
    }
    return await eventBuffer.addEvent(eventAfterPossibleCallback);
  } catch (error2) {
    const isExceeded = error2 && error2 instanceof EventBufferSizeExceededError;
    const reason = isExceeded ? "addEventSizeExceeded" : "addEvent";
    if (isExceeded && isBufferMode) {
      eventBuffer.clear();
      eventBuffer.waitForCheckout = true;
      return null;
    }
    replay.handleException(error2);
    await replay.stop({ reason });
    const client = getClient();
    if (client) {
      client.recordDroppedEvent("internal_sdk_error", "replay");
    }
  }
}
__name(_addEvent, "_addEvent");
function shouldAddEvent(replay, event) {
  if (!replay.eventBuffer || replay.isPaused() || !replay.isEnabled()) {
    return false;
  }
  const timestampInMs = timestampToMs(event.timestamp);
  if (timestampInMs + replay.timeouts.sessionIdlePause < Date.now()) {
    return false;
  }
  if (timestampInMs > replay.getContext().initialTimestamp + replay.getOptions().maxReplayDuration) {
    DEBUG_BUILD$2 && logger$4.infoTick(`Skipping event with timestamp ${timestampInMs} because it is after maxReplayDuration`);
    return false;
  }
  return true;
}
__name(shouldAddEvent, "shouldAddEvent");
function maybeApplyCallback(event, callback) {
  try {
    if (typeof callback === "function" && isCustomEvent(event)) {
      return callback(event);
    }
  } catch (error2) {
    DEBUG_BUILD$2 && logger$4.exception(error2, "An error occurred in the `beforeAddRecordingEvent` callback, skipping the event...");
    return null;
  }
  return event;
}
__name(maybeApplyCallback, "maybeApplyCallback");
function isErrorEvent(event) {
  return !event.type;
}
__name(isErrorEvent, "isErrorEvent");
function isTransactionEvent(event) {
  return event.type === "transaction";
}
__name(isTransactionEvent, "isTransactionEvent");
function isReplayEvent(event) {
  return event.type === "replay_event";
}
__name(isReplayEvent, "isReplayEvent");
function isFeedbackEvent(event) {
  return event.type === "feedback";
}
__name(isFeedbackEvent, "isFeedbackEvent");
function handleAfterSendEvent(replay) {
  return (event, sendResponse) => {
    if (!replay.isEnabled() || !isErrorEvent(event) && !isTransactionEvent(event)) {
      return;
    }
    const statusCode = sendResponse && sendResponse.statusCode;
    if (!statusCode || statusCode < 200 || statusCode >= 300) {
      return;
    }
    if (isTransactionEvent(event)) {
      handleTransactionEvent(replay, event);
      return;
    }
    handleErrorEvent(replay, event);
  };
}
__name(handleAfterSendEvent, "handleAfterSendEvent");
function handleTransactionEvent(replay, event) {
  const replayContext = replay.getContext();
  if (event.contexts && event.contexts.trace && event.contexts.trace.trace_id && replayContext.traceIds.size < 100) {
    replayContext.traceIds.add(event.contexts.trace.trace_id);
  }
}
__name(handleTransactionEvent, "handleTransactionEvent");
function handleErrorEvent(replay, event) {
  const replayContext = replay.getContext();
  if (event.event_id && replayContext.errorIds.size < 100) {
    replayContext.errorIds.add(event.event_id);
  }
  if (replay.recordingMode !== "buffer" || !event.tags || !event.tags.replayId) {
    return;
  }
  const { beforeErrorSampling } = replay.getOptions();
  if (typeof beforeErrorSampling === "function" && !beforeErrorSampling(event)) {
    return;
  }
  setTimeout$3(async () => {
    try {
      await replay.sendBufferedReplayOrFlush();
    } catch (err) {
      replay.handleException(err);
    }
  });
}
__name(handleErrorEvent, "handleErrorEvent");
function handleBeforeSendEvent(replay) {
  return (event) => {
    if (!replay.isEnabled() || !isErrorEvent(event)) {
      return;
    }
    handleHydrationError(replay, event);
  };
}
__name(handleBeforeSendEvent, "handleBeforeSendEvent");
function handleHydrationError(replay, event) {
  const exceptionValue = event.exception && event.exception.values && event.exception.values[0] && event.exception.values[0].value;
  if (typeof exceptionValue !== "string") {
    return;
  }
  if (
    // Only matches errors in production builds of react-dom
    // Example https://reactjs.org/docs/error-decoder.html?invariant=423
    // With newer React versions, the messages changed to a different website https://react.dev/errors/418
    exceptionValue.match(
      /(reactjs\.org\/docs\/error-decoder\.html\?invariant=|react\.dev\/errors\/)(418|419|422|423|425)/
    ) || // Development builds of react-dom
    // Error 1: Hydration failed because the initial UI does not match what was rendered on the server.
    // Error 2: Text content does not match server-rendered HTML. Warning: Text content did not match.
    exceptionValue.match(/(does not match server-rendered HTML|Hydration failed because)/i)
  ) {
    const breadcrumb = createBreadcrumb({
      category: "replay.hydrate-error",
      data: {
        url: getLocationHref()
      }
    });
    addBreadcrumbEvent(replay, breadcrumb);
  }
}
__name(handleHydrationError, "handleHydrationError");
function handleBreadcrumbs(replay) {
  const client = getClient();
  if (!client) {
    return;
  }
  client.on("beforeAddBreadcrumb", (breadcrumb) => beforeAddBreadcrumb(replay, breadcrumb));
}
__name(handleBreadcrumbs, "handleBreadcrumbs");
function beforeAddBreadcrumb(replay, breadcrumb) {
  if (!replay.isEnabled() || !isBreadcrumbWithCategory(breadcrumb)) {
    return;
  }
  const result = normalizeBreadcrumb(breadcrumb);
  if (result) {
    addBreadcrumbEvent(replay, result);
  }
}
__name(beforeAddBreadcrumb, "beforeAddBreadcrumb");
function normalizeBreadcrumb(breadcrumb) {
  if (!isBreadcrumbWithCategory(breadcrumb) || [
    // fetch & xhr are handled separately,in handleNetworkBreadcrumbs
    "fetch",
    "xhr",
    // These two are breadcrumbs for emitted sentry events, we don't care about them
    "sentry.event",
    "sentry.transaction"
  ].includes(breadcrumb.category) || // We capture UI breadcrumbs separately
  breadcrumb.category.startsWith("ui.")) {
    return null;
  }
  if (breadcrumb.category === "console") {
    return normalizeConsoleBreadcrumb(breadcrumb);
  }
  return createBreadcrumb(breadcrumb);
}
__name(normalizeBreadcrumb, "normalizeBreadcrumb");
function normalizeConsoleBreadcrumb(breadcrumb) {
  const args = breadcrumb.data && breadcrumb.data.arguments;
  if (!Array.isArray(args) || args.length === 0) {
    return createBreadcrumb(breadcrumb);
  }
  let isTruncated = false;
  const normalizedArgs = args.map((arg) => {
    if (!arg) {
      return arg;
    }
    if (typeof arg === "string") {
      if (arg.length > CONSOLE_ARG_MAX_SIZE) {
        isTruncated = true;
        return `${arg.slice(0, CONSOLE_ARG_MAX_SIZE)}…`;
      }
      return arg;
    }
    if (typeof arg === "object") {
      try {
        const normalizedArg = normalize$2(arg, 7);
        const stringified = JSON.stringify(normalizedArg);
        if (stringified.length > CONSOLE_ARG_MAX_SIZE) {
          isTruncated = true;
          return `${JSON.stringify(normalizedArg, null, 2).slice(0, CONSOLE_ARG_MAX_SIZE)}…`;
        }
        return normalizedArg;
      } catch (e2) {
      }
    }
    return arg;
  });
  return createBreadcrumb({
    ...breadcrumb,
    data: {
      ...breadcrumb.data,
      arguments: normalizedArgs,
      ...isTruncated ? { _meta: { warnings: ["CONSOLE_ARG_TRUNCATED"] } } : {}
    }
  });
}
__name(normalizeConsoleBreadcrumb, "normalizeConsoleBreadcrumb");
function isBreadcrumbWithCategory(breadcrumb) {
  return !!breadcrumb.category;
}
__name(isBreadcrumbWithCategory, "isBreadcrumbWithCategory");
function isRrwebError(event, hint) {
  if (event.type || !event.exception || !event.exception.values || !event.exception.values.length) {
    return false;
  }
  if (hint.originalException && hint.originalException.__rrweb__) {
    return true;
  }
  return false;
}
__name(isRrwebError, "isRrwebError");
function resetReplayIdOnDynamicSamplingContext() {
  const dsc = getCurrentScope().getPropagationContext().dsc;
  if (dsc) {
    delete dsc.replay_id;
  }
  const activeSpan = getActiveSpan();
  if (activeSpan) {
    const dsc2 = getDynamicSamplingContextFromSpan(activeSpan);
    delete dsc2.replay_id;
  }
}
__name(resetReplayIdOnDynamicSamplingContext, "resetReplayIdOnDynamicSamplingContext");
function addFeedbackBreadcrumb(replay, event) {
  replay.triggerUserActivity();
  replay.addUpdate(() => {
    if (!event.timestamp) {
      return true;
    }
    replay.throttledAddEvent({
      type: EventType$1.Custom,
      timestamp: event.timestamp * 1e3,
      data: {
        tag: "breadcrumb",
        payload: {
          timestamp: event.timestamp,
          type: "default",
          category: "sentry.feedback",
          data: {
            feedbackId: event.event_id
          }
        }
      }
    });
    return false;
  });
}
__name(addFeedbackBreadcrumb, "addFeedbackBreadcrumb");
function shouldSampleForBufferEvent(replay, event) {
  if (replay.recordingMode !== "buffer") {
    return false;
  }
  if (event.message === UNABLE_TO_SEND_REPLAY) {
    return false;
  }
  if (!event.exception || event.type) {
    return false;
  }
  return isSampled(replay.getOptions().errorSampleRate);
}
__name(shouldSampleForBufferEvent, "shouldSampleForBufferEvent");
function handleGlobalEventListener(replay) {
  return Object.assign(
    (event, hint) => {
      if (!replay.isEnabled() || replay.isPaused()) {
        return event;
      }
      if (isReplayEvent(event)) {
        delete event.breadcrumbs;
        return event;
      }
      if (!isErrorEvent(event) && !isTransactionEvent(event) && !isFeedbackEvent(event)) {
        return event;
      }
      const isSessionActive = replay.checkAndHandleExpiredSession();
      if (!isSessionActive) {
        resetReplayIdOnDynamicSamplingContext();
        return event;
      }
      if (isFeedbackEvent(event)) {
        replay.flush();
        event.contexts.feedback.replay_id = replay.getSessionId();
        addFeedbackBreadcrumb(replay, event);
        return event;
      }
      if (isRrwebError(event, hint) && !replay.getOptions()._experiments.captureExceptions) {
        DEBUG_BUILD$2 && logger$4.log("Ignoring error from rrweb internals", event);
        return null;
      }
      const isErrorEventSampled = shouldSampleForBufferEvent(replay, event);
      const shouldTagReplayId = isErrorEventSampled || replay.recordingMode === "session";
      if (shouldTagReplayId) {
        event.tags = { ...event.tags, replayId: replay.getSessionId() };
      }
      return event;
    },
    { id: "Replay" }
  );
}
__name(handleGlobalEventListener, "handleGlobalEventListener");
function createPerformanceSpans(replay, entries) {
  return entries.map(({ type, start: start2, end, name: name2, data }) => {
    const response = replay.throttledAddEvent({
      type: EventType$1.Custom,
      timestamp: start2,
      data: {
        tag: "performanceSpan",
        payload: {
          op: type,
          description: name2,
          startTimestamp: start2,
          endTimestamp: end,
          data
        }
      }
    });
    return typeof response === "string" ? Promise.resolve(null) : response;
  });
}
__name(createPerformanceSpans, "createPerformanceSpans");
function handleHistory(handlerData) {
  const { from: from2, to } = handlerData;
  const now2 = Date.now() / 1e3;
  return {
    type: "navigation.push",
    start: now2,
    end: now2,
    name: to,
    data: {
      previous: from2
    }
  };
}
__name(handleHistory, "handleHistory");
function handleHistorySpanListener(replay) {
  return (handlerData) => {
    if (!replay.isEnabled()) {
      return;
    }
    const result = handleHistory(handlerData);
    if (result === null) {
      return;
    }
    replay.getContext().urls.push(result.name);
    replay.triggerUserActivity();
    replay.addUpdate(() => {
      createPerformanceSpans(replay, [result]);
      return false;
    });
  };
}
__name(handleHistorySpanListener, "handleHistorySpanListener");
function shouldFilterRequest(replay, url) {
  if (DEBUG_BUILD$2 && replay.getOptions()._experiments.traceInternals) {
    return false;
  }
  return isSentryRequestUrl(url, getClient());
}
__name(shouldFilterRequest, "shouldFilterRequest");
function addNetworkBreadcrumb(replay, result) {
  if (!replay.isEnabled()) {
    return;
  }
  if (result === null) {
    return;
  }
  if (shouldFilterRequest(replay, result.name)) {
    return;
  }
  replay.addUpdate(() => {
    createPerformanceSpans(replay, [result]);
    return true;
  });
}
__name(addNetworkBreadcrumb, "addNetworkBreadcrumb");
function getBodySize(body) {
  if (!body) {
    return void 0;
  }
  const textEncoder = new TextEncoder();
  try {
    if (typeof body === "string") {
      return textEncoder.encode(body).length;
    }
    if (body instanceof URLSearchParams) {
      return textEncoder.encode(body.toString()).length;
    }
    if (body instanceof FormData) {
      const formDataStr = _serializeFormData(body);
      return textEncoder.encode(formDataStr).length;
    }
    if (body instanceof Blob) {
      return body.size;
    }
    if (body instanceof ArrayBuffer) {
      return body.byteLength;
    }
  } catch (e2) {
  }
  return void 0;
}
__name(getBodySize, "getBodySize");
function parseContentLengthHeader(header) {
  if (!header) {
    return void 0;
  }
  const size = parseInt(header, 10);
  return isNaN(size) ? void 0 : size;
}
__name(parseContentLengthHeader, "parseContentLengthHeader");
function getBodyString(body) {
  try {
    if (typeof body === "string") {
      return [body];
    }
    if (body instanceof URLSearchParams) {
      return [body.toString()];
    }
    if (body instanceof FormData) {
      return [_serializeFormData(body)];
    }
    if (!body) {
      return [void 0];
    }
  } catch (error2) {
    DEBUG_BUILD$2 && logger$4.exception(error2, "Failed to serialize body", body);
    return [void 0, "BODY_PARSE_ERROR"];
  }
  DEBUG_BUILD$2 && logger$4.info("Skipping network body because of body type", body);
  return [void 0, "UNPARSEABLE_BODY_TYPE"];
}
__name(getBodyString, "getBodyString");
function mergeWarning(info, warning) {
  if (!info) {
    return {
      headers: {},
      size: void 0,
      _meta: {
        warnings: [warning]
      }
    };
  }
  const newMeta = { ...info._meta };
  const existingWarnings = newMeta.warnings || [];
  newMeta.warnings = [...existingWarnings, warning];
  info._meta = newMeta;
  return info;
}
__name(mergeWarning, "mergeWarning");
function makeNetworkReplayBreadcrumb(type, data) {
  if (!data) {
    return null;
  }
  const { startTimestamp, endTimestamp, url, method, statusCode, request, response } = data;
  const result = {
    type,
    start: startTimestamp / 1e3,
    end: endTimestamp / 1e3,
    name: url,
    data: dropUndefinedKeys({
      method,
      statusCode,
      request,
      response
    })
  };
  return result;
}
__name(makeNetworkReplayBreadcrumb, "makeNetworkReplayBreadcrumb");
function buildSkippedNetworkRequestOrResponse(bodySize) {
  return {
    headers: {},
    size: bodySize,
    _meta: {
      warnings: ["URL_SKIPPED"]
    }
  };
}
__name(buildSkippedNetworkRequestOrResponse, "buildSkippedNetworkRequestOrResponse");
function buildNetworkRequestOrResponse(headers, bodySize, body) {
  if (!bodySize && Object.keys(headers).length === 0) {
    return void 0;
  }
  if (!bodySize) {
    return {
      headers
    };
  }
  if (!body) {
    return {
      headers,
      size: bodySize
    };
  }
  const info = {
    headers,
    size: bodySize
  };
  const { body: normalizedBody, warnings } = normalizeNetworkBody(body);
  info.body = normalizedBody;
  if (warnings && warnings.length > 0) {
    info._meta = {
      warnings
    };
  }
  return info;
}
__name(buildNetworkRequestOrResponse, "buildNetworkRequestOrResponse");
function getAllowedHeaders(headers, allowedHeaders) {
  return Object.entries(headers).reduce((filteredHeaders, [key, value]) => {
    const normalizedKey = key.toLowerCase();
    if (allowedHeaders.includes(normalizedKey) && headers[key]) {
      filteredHeaders[normalizedKey] = value;
    }
    return filteredHeaders;
  }, {});
}
__name(getAllowedHeaders, "getAllowedHeaders");
function _serializeFormData(formData) {
  return new URLSearchParams(formData).toString();
}
__name(_serializeFormData, "_serializeFormData");
function normalizeNetworkBody(body) {
  if (!body || typeof body !== "string") {
    return {
      body
    };
  }
  const exceedsSizeLimit = body.length > NETWORK_BODY_MAX_SIZE;
  const isProbablyJson = _strIsProbablyJson(body);
  if (exceedsSizeLimit) {
    const truncatedBody = body.slice(0, NETWORK_BODY_MAX_SIZE);
    if (isProbablyJson) {
      return {
        body: truncatedBody,
        warnings: ["MAYBE_JSON_TRUNCATED"]
      };
    }
    return {
      body: `${truncatedBody}…`,
      warnings: ["TEXT_TRUNCATED"]
    };
  }
  if (isProbablyJson) {
    try {
      const jsonBody = JSON.parse(body);
      return {
        body: jsonBody
      };
    } catch (e2) {
    }
  }
  return {
    body
  };
}
__name(normalizeNetworkBody, "normalizeNetworkBody");
function _strIsProbablyJson(str) {
  const first2 = str[0];
  const last = str[str.length - 1];
  return first2 === "[" && last === "]" || first2 === "{" && last === "}";
}
__name(_strIsProbablyJson, "_strIsProbablyJson");
function urlMatches(url, urls) {
  const fullUrl = getFullUrl(url);
  return stringMatchesSomePattern(fullUrl, urls);
}
__name(urlMatches, "urlMatches");
function getFullUrl(url, baseURI = WINDOW$1.document.baseURI) {
  if (url.startsWith("http://") || url.startsWith("https://") || url.startsWith(WINDOW$1.location.origin)) {
    return url;
  }
  const fixedUrl = new URL(url, baseURI);
  if (fixedUrl.origin !== new URL(baseURI).origin) {
    return url;
  }
  const fullUrl = fixedUrl.href;
  if (!url.endsWith("/") && fullUrl.endsWith("/")) {
    return fullUrl.slice(0, -1);
  }
  return fullUrl;
}
__name(getFullUrl, "getFullUrl");
async function captureFetchBreadcrumbToReplay(breadcrumb, hint, options2) {
  try {
    const data = await _prepareFetchData(breadcrumb, hint, options2);
    const result = makeNetworkReplayBreadcrumb("resource.fetch", data);
    addNetworkBreadcrumb(options2.replay, result);
  } catch (error2) {
    DEBUG_BUILD$2 && logger$4.exception(error2, "Failed to capture fetch breadcrumb");
  }
}
__name(captureFetchBreadcrumbToReplay, "captureFetchBreadcrumbToReplay");
function enrichFetchBreadcrumb(breadcrumb, hint) {
  const { input, response } = hint;
  const body = input ? _getFetchRequestArgBody(input) : void 0;
  const reqSize = getBodySize(body);
  const resSize = response ? parseContentLengthHeader(response.headers.get("content-length")) : void 0;
  if (reqSize !== void 0) {
    breadcrumb.data.request_body_size = reqSize;
  }
  if (resSize !== void 0) {
    breadcrumb.data.response_body_size = resSize;
  }
}
__name(enrichFetchBreadcrumb, "enrichFetchBreadcrumb");
async function _prepareFetchData(breadcrumb, hint, options2) {
  const now2 = Date.now();
  const { startTimestamp = now2, endTimestamp = now2 } = hint;
  const {
    url,
    method,
    status_code: statusCode = 0,
    request_body_size: requestBodySize,
    response_body_size: responseBodySize
  } = breadcrumb.data;
  const captureDetails = urlMatches(url, options2.networkDetailAllowUrls) && !urlMatches(url, options2.networkDetailDenyUrls);
  const request = captureDetails ? _getRequestInfo(options2, hint.input, requestBodySize) : buildSkippedNetworkRequestOrResponse(requestBodySize);
  const response = await _getResponseInfo(captureDetails, options2, hint.response, responseBodySize);
  return {
    startTimestamp,
    endTimestamp,
    url,
    method,
    statusCode,
    request,
    response
  };
}
__name(_prepareFetchData, "_prepareFetchData");
function _getRequestInfo({ networkCaptureBodies, networkRequestHeaders }, input, requestBodySize) {
  const headers = input ? getRequestHeaders(input, networkRequestHeaders) : {};
  if (!networkCaptureBodies) {
    return buildNetworkRequestOrResponse(headers, requestBodySize, void 0);
  }
  const requestBody = _getFetchRequestArgBody(input);
  const [bodyStr, warning] = getBodyString(requestBody);
  const data = buildNetworkRequestOrResponse(headers, requestBodySize, bodyStr);
  if (warning) {
    return mergeWarning(data, warning);
  }
  return data;
}
__name(_getRequestInfo, "_getRequestInfo");
async function _getResponseInfo(captureDetails, {
  networkCaptureBodies,
  networkResponseHeaders
}, response, responseBodySize) {
  if (!captureDetails && responseBodySize !== void 0) {
    return buildSkippedNetworkRequestOrResponse(responseBodySize);
  }
  const headers = response ? getAllHeaders(response.headers, networkResponseHeaders) : {};
  if (!response || !networkCaptureBodies && responseBodySize !== void 0) {
    return buildNetworkRequestOrResponse(headers, responseBodySize, void 0);
  }
  const [bodyText, warning] = await _parseFetchResponseBody(response);
  const result = getResponseData(bodyText, {
    networkCaptureBodies,
    responseBodySize,
    captureDetails,
    headers
  });
  if (warning) {
    return mergeWarning(result, warning);
  }
  return result;
}
__name(_getResponseInfo, "_getResponseInfo");
function getResponseData(bodyText, {
  networkCaptureBodies,
  responseBodySize,
  captureDetails,
  headers
}) {
  try {
    const size = bodyText && bodyText.length && responseBodySize === void 0 ? getBodySize(bodyText) : responseBodySize;
    if (!captureDetails) {
      return buildSkippedNetworkRequestOrResponse(size);
    }
    if (networkCaptureBodies) {
      return buildNetworkRequestOrResponse(headers, size, bodyText);
    }
    return buildNetworkRequestOrResponse(headers, size, void 0);
  } catch (error2) {
    DEBUG_BUILD$2 && logger$4.exception(error2, "Failed to serialize response body");
    return buildNetworkRequestOrResponse(headers, responseBodySize, void 0);
  }
}
__name(getResponseData, "getResponseData");
async function _parseFetchResponseBody(response) {
  const res = _tryCloneResponse(response);
  if (!res) {
    return [void 0, "BODY_PARSE_ERROR"];
  }
  try {
    const text2 = await _tryGetResponseText(res);
    return [text2];
  } catch (error2) {
    if (error2 instanceof Error && error2.message.indexOf("Timeout") > -1) {
      DEBUG_BUILD$2 && logger$4.warn("Parsing text body from response timed out");
      return [void 0, "BODY_PARSE_TIMEOUT"];
    }
    DEBUG_BUILD$2 && logger$4.exception(error2, "Failed to get text body from response");
    return [void 0, "BODY_PARSE_ERROR"];
  }
}
__name(_parseFetchResponseBody, "_parseFetchResponseBody");
function _getFetchRequestArgBody(fetchArgs = []) {
  if (fetchArgs.length !== 2 || typeof fetchArgs[1] !== "object") {
    return void 0;
  }
  return fetchArgs[1].body;
}
__name(_getFetchRequestArgBody, "_getFetchRequestArgBody");
function getAllHeaders(headers, allowedHeaders) {
  const allHeaders = {};
  allowedHeaders.forEach((header) => {
    if (headers.get(header)) {
      allHeaders[header] = headers.get(header);
    }
  });
  return allHeaders;
}
__name(getAllHeaders, "getAllHeaders");
function getRequestHeaders(fetchArgs, allowedHeaders) {
  if (fetchArgs.length === 1 && typeof fetchArgs[0] !== "string") {
    return getHeadersFromOptions(fetchArgs[0], allowedHeaders);
  }
  if (fetchArgs.length === 2) {
    return getHeadersFromOptions(fetchArgs[1], allowedHeaders);
  }
  return {};
}
__name(getRequestHeaders, "getRequestHeaders");
function getHeadersFromOptions(input, allowedHeaders) {
  if (!input) {
    return {};
  }
  const headers = input.headers;
  if (!headers) {
    return {};
  }
  if (headers instanceof Headers) {
    return getAllHeaders(headers, allowedHeaders);
  }
  if (Array.isArray(headers)) {
    return {};
  }
  return getAllowedHeaders(headers, allowedHeaders);
}
__name(getHeadersFromOptions, "getHeadersFromOptions");
function _tryCloneResponse(response) {
  try {
    return response.clone();
  } catch (error2) {
    DEBUG_BUILD$2 && logger$4.exception(error2, "Failed to clone response body");
  }
}
__name(_tryCloneResponse, "_tryCloneResponse");
function _tryGetResponseText(response) {
  return new Promise((resolve2, reject) => {
    const timeout = setTimeout$3(() => reject(new Error("Timeout while trying to read response body")), 500);
    _getResponseText(response).then(
      (txt) => resolve2(txt),
      (reason) => reject(reason)
    ).finally(() => clearTimeout(timeout));
  });
}
__name(_tryGetResponseText, "_tryGetResponseText");
async function _getResponseText(response) {
  return await response.text();
}
__name(_getResponseText, "_getResponseText");
async function captureXhrBreadcrumbToReplay(breadcrumb, hint, options2) {
  try {
    const data = _prepareXhrData(breadcrumb, hint, options2);
    const result = makeNetworkReplayBreadcrumb("resource.xhr", data);
    addNetworkBreadcrumb(options2.replay, result);
  } catch (error2) {
    DEBUG_BUILD$2 && logger$4.exception(error2, "Failed to capture xhr breadcrumb");
  }
}
__name(captureXhrBreadcrumbToReplay, "captureXhrBreadcrumbToReplay");
function enrichXhrBreadcrumb(breadcrumb, hint) {
  const { xhr, input } = hint;
  if (!xhr) {
    return;
  }
  const reqSize = getBodySize(input);
  const resSize = xhr.getResponseHeader("content-length") ? parseContentLengthHeader(xhr.getResponseHeader("content-length")) : _getBodySize(xhr.response, xhr.responseType);
  if (reqSize !== void 0) {
    breadcrumb.data.request_body_size = reqSize;
  }
  if (resSize !== void 0) {
    breadcrumb.data.response_body_size = resSize;
  }
}
__name(enrichXhrBreadcrumb, "enrichXhrBreadcrumb");
function _prepareXhrData(breadcrumb, hint, options2) {
  const now2 = Date.now();
  const { startTimestamp = now2, endTimestamp = now2, input, xhr } = hint;
  const {
    url,
    method,
    status_code: statusCode = 0,
    request_body_size: requestBodySize,
    response_body_size: responseBodySize
  } = breadcrumb.data;
  if (!url) {
    return null;
  }
  if (!xhr || !urlMatches(url, options2.networkDetailAllowUrls) || urlMatches(url, options2.networkDetailDenyUrls)) {
    const request2 = buildSkippedNetworkRequestOrResponse(requestBodySize);
    const response2 = buildSkippedNetworkRequestOrResponse(responseBodySize);
    return {
      startTimestamp,
      endTimestamp,
      url,
      method,
      statusCode,
      request: request2,
      response: response2
    };
  }
  const xhrInfo = xhr[SENTRY_XHR_DATA_KEY];
  const networkRequestHeaders = xhrInfo ? getAllowedHeaders(xhrInfo.request_headers, options2.networkRequestHeaders) : {};
  const networkResponseHeaders = getAllowedHeaders(getResponseHeaders(xhr), options2.networkResponseHeaders);
  const [requestBody, requestWarning] = options2.networkCaptureBodies ? getBodyString(input) : [void 0];
  const [responseBody, responseWarning] = options2.networkCaptureBodies ? _getXhrResponseBody(xhr) : [void 0];
  const request = buildNetworkRequestOrResponse(networkRequestHeaders, requestBodySize, requestBody);
  const response = buildNetworkRequestOrResponse(networkResponseHeaders, responseBodySize, responseBody);
  return {
    startTimestamp,
    endTimestamp,
    url,
    method,
    statusCode,
    request: requestWarning ? mergeWarning(request, requestWarning) : request,
    response: responseWarning ? mergeWarning(response, responseWarning) : response
  };
}
__name(_prepareXhrData, "_prepareXhrData");
function getResponseHeaders(xhr) {
  const headers = xhr.getAllResponseHeaders();
  if (!headers) {
    return {};
  }
  return headers.split("\r\n").reduce((acc, line) => {
    const [key, value] = line.split(": ");
    if (value) {
      acc[key.toLowerCase()] = value;
    }
    return acc;
  }, {});
}
__name(getResponseHeaders, "getResponseHeaders");
function _getXhrResponseBody(xhr) {
  const errors2 = [];
  try {
    return [xhr.responseText];
  } catch (e2) {
    errors2.push(e2);
  }
  try {
    return _parseXhrResponse(xhr.response, xhr.responseType);
  } catch (e2) {
    errors2.push(e2);
  }
  DEBUG_BUILD$2 && logger$4.warn("Failed to get xhr response body", ...errors2);
  return [void 0];
}
__name(_getXhrResponseBody, "_getXhrResponseBody");
function _parseXhrResponse(body, responseType) {
  try {
    if (typeof body === "string") {
      return [body];
    }
    if (body instanceof Document) {
      return [body.body.outerHTML];
    }
    if (responseType === "json" && body && typeof body === "object") {
      return [JSON.stringify(body)];
    }
    if (!body) {
      return [void 0];
    }
  } catch (error2) {
    DEBUG_BUILD$2 && logger$4.exception(error2, "Failed to serialize body", body);
    return [void 0, "BODY_PARSE_ERROR"];
  }
  DEBUG_BUILD$2 && logger$4.info("Skipping network body because of body type", body);
  return [void 0, "UNPARSEABLE_BODY_TYPE"];
}
__name(_parseXhrResponse, "_parseXhrResponse");
function _getBodySize(body, responseType) {
  try {
    const bodyStr = responseType === "json" && body && typeof body === "object" ? JSON.stringify(body) : body;
    return getBodySize(bodyStr);
  } catch (e2) {
    return void 0;
  }
}
__name(_getBodySize, "_getBodySize");
function handleNetworkBreadcrumbs(replay) {
  const client = getClient();
  try {
    const {
      networkDetailAllowUrls,
      networkDetailDenyUrls,
      networkCaptureBodies,
      networkRequestHeaders,
      networkResponseHeaders
    } = replay.getOptions();
    const options2 = {
      replay,
      networkDetailAllowUrls,
      networkDetailDenyUrls,
      networkCaptureBodies,
      networkRequestHeaders,
      networkResponseHeaders
    };
    if (client) {
      client.on("beforeAddBreadcrumb", (breadcrumb, hint) => beforeAddNetworkBreadcrumb(options2, breadcrumb, hint));
    }
  } catch (e2) {
  }
}
__name(handleNetworkBreadcrumbs, "handleNetworkBreadcrumbs");
function beforeAddNetworkBreadcrumb(options2, breadcrumb, hint) {
  if (!breadcrumb.data) {
    return;
  }
  try {
    if (_isXhrBreadcrumb(breadcrumb) && _isXhrHint(hint)) {
      enrichXhrBreadcrumb(breadcrumb, hint);
      captureXhrBreadcrumbToReplay(breadcrumb, hint, options2);
    }
    if (_isFetchBreadcrumb(breadcrumb) && _isFetchHint(hint)) {
      enrichFetchBreadcrumb(breadcrumb, hint);
      captureFetchBreadcrumbToReplay(breadcrumb, hint, options2);
    }
  } catch (e2) {
    DEBUG_BUILD$2 && logger$4.exception(e2, "Error when enriching network breadcrumb");
  }
}
__name(beforeAddNetworkBreadcrumb, "beforeAddNetworkBreadcrumb");
function _isXhrBreadcrumb(breadcrumb) {
  return breadcrumb.category === "xhr";
}
__name(_isXhrBreadcrumb, "_isXhrBreadcrumb");
function _isFetchBreadcrumb(breadcrumb) {
  return breadcrumb.category === "fetch";
}
__name(_isFetchBreadcrumb, "_isFetchBreadcrumb");
function _isXhrHint(hint) {
  return hint && hint.xhr;
}
__name(_isXhrHint, "_isXhrHint");
function _isFetchHint(hint) {
  return hint && hint.response;
}
__name(_isFetchHint, "_isFetchHint");
function addGlobalListeners(replay) {
  const client = getClient();
  addClickKeypressInstrumentationHandler(handleDomListener(replay));
  addHistoryInstrumentationHandler(handleHistorySpanListener(replay));
  handleBreadcrumbs(replay);
  handleNetworkBreadcrumbs(replay);
  const eventProcessor = handleGlobalEventListener(replay);
  addEventProcessor(eventProcessor);
  if (client) {
    client.on("beforeSendEvent", handleBeforeSendEvent(replay));
    client.on("afterSendEvent", handleAfterSendEvent(replay));
    client.on("createDsc", (dsc) => {
      const replayId = replay.getSessionId();
      if (replayId && replay.isEnabled() && replay.recordingMode === "session") {
        const isSessionActive = replay.checkAndHandleExpiredSession();
        if (isSessionActive) {
          dsc.replay_id = replayId;
        }
      }
    });
    client.on("spanStart", (span) => {
      replay.lastActiveSpan = span;
    });
    client.on("spanEnd", (span) => {
      replay.lastActiveSpan = span;
    });
    client.on("beforeSendFeedback", (feedbackEvent, options2) => {
      const replayId = replay.getSessionId();
      if (options2 && options2.includeReplay && replay.isEnabled() && replayId) {
        if (feedbackEvent.contexts && feedbackEvent.contexts.feedback) {
          feedbackEvent.contexts.feedback.replay_id = replayId;
        }
      }
    });
  }
}
__name(addGlobalListeners, "addGlobalListeners");
async function addMemoryEntry(replay) {
  try {
    return Promise.all(
      createPerformanceSpans(replay, [
        // @ts-expect-error memory doesn't exist on type Performance as the API is non-standard (we check that it exists above)
        createMemoryEntry(WINDOW$1.performance.memory)
      ])
    );
  } catch (error2) {
    return [];
  }
}
__name(addMemoryEntry, "addMemoryEntry");
function createMemoryEntry(memoryEntry) {
  const { jsHeapSizeLimit, totalJSHeapSize, usedJSHeapSize } = memoryEntry;
  const time = Date.now() / 1e3;
  return {
    type: "memory",
    name: "memory",
    start: time,
    end: time,
    data: {
      memory: {
        jsHeapSizeLimit,
        totalJSHeapSize,
        usedJSHeapSize
      }
    }
  };
}
__name(createMemoryEntry, "createMemoryEntry");
function debounce(func, wait, options2) {
  let callbackReturnValue;
  let timerId;
  let maxTimerId;
  const maxWait = options2 && options2.maxWait ? Math.max(options2.maxWait, wait) : 0;
  function invokeFunc() {
    cancelTimers();
    callbackReturnValue = func();
    return callbackReturnValue;
  }
  __name(invokeFunc, "invokeFunc");
  function cancelTimers() {
    timerId !== void 0 && clearTimeout(timerId);
    maxTimerId !== void 0 && clearTimeout(maxTimerId);
    timerId = maxTimerId = void 0;
  }
  __name(cancelTimers, "cancelTimers");
  function flush2() {
    if (timerId !== void 0 || maxTimerId !== void 0) {
      return invokeFunc();
    }
    return callbackReturnValue;
  }
  __name(flush2, "flush");
  function debounced() {
    if (timerId) {
      clearTimeout(timerId);
    }
    timerId = setTimeout$3(invokeFunc, wait);
    if (maxWait && maxTimerId === void 0) {
      maxTimerId = setTimeout$3(invokeFunc, maxWait);
    }
    return callbackReturnValue;
  }
  __name(debounced, "debounced");
  debounced.cancel = cancelTimers;
  debounced.flush = flush2;
  return debounced;
}
__name(debounce, "debounce");
function getHandleRecordingEmit(replay) {
  let hadFirstEvent = false;
  return (event, _isCheckout) => {
    if (!replay.checkAndHandleExpiredSession()) {
      DEBUG_BUILD$2 && logger$4.warn("Received replay event after session expired.");
      return;
    }
    const isCheckout = _isCheckout || !hadFirstEvent;
    hadFirstEvent = true;
    if (replay.clickDetector) {
      updateClickDetectorForRecordingEvent(replay.clickDetector, event);
    }
    replay.addUpdate(() => {
      if (replay.recordingMode === "buffer" && isCheckout) {
        replay.setInitialState();
      }
      if (!addEventSync(replay, event, isCheckout)) {
        return true;
      }
      if (!isCheckout) {
        return false;
      }
      const session = replay.session;
      addSettingsEvent(replay, isCheckout);
      if (replay.recordingMode === "buffer" && session && replay.eventBuffer) {
        const earliestEvent = replay.eventBuffer.getEarliestTimestamp();
        if (earliestEvent) {
          DEBUG_BUILD$2 && logger$4.info(`Updating session start time to earliest event in buffer to ${new Date(earliestEvent)}`);
          session.started = earliestEvent;
          if (replay.getOptions().stickySession) {
            saveSession(session);
          }
        }
      }
      if (session && session.previousSessionId) {
        return true;
      }
      if (replay.recordingMode === "session") {
        void replay.flush();
      }
      return true;
    });
  };
}
__name(getHandleRecordingEmit, "getHandleRecordingEmit");
function createOptionsEvent(replay) {
  const options2 = replay.getOptions();
  return {
    type: EventType$1.Custom,
    timestamp: Date.now(),
    data: {
      tag: "options",
      payload: {
        shouldRecordCanvas: replay.isRecordingCanvas(),
        sessionSampleRate: options2.sessionSampleRate,
        errorSampleRate: options2.errorSampleRate,
        useCompressionOption: options2.useCompression,
        blockAllMedia: options2.blockAllMedia,
        maskAllText: options2.maskAllText,
        maskAllInputs: options2.maskAllInputs,
        useCompression: replay.eventBuffer ? replay.eventBuffer.type === "worker" : false,
        networkDetailHasUrls: options2.networkDetailAllowUrls.length > 0,
        networkCaptureBodies: options2.networkCaptureBodies,
        networkRequestHasHeaders: options2.networkRequestHeaders.length > 0,
        networkResponseHasHeaders: options2.networkResponseHeaders.length > 0
      }
    }
  };
}
__name(createOptionsEvent, "createOptionsEvent");
function addSettingsEvent(replay, isCheckout) {
  if (!isCheckout || !replay.session || replay.session.segmentId !== 0) {
    return;
  }
  addEventSync(replay, createOptionsEvent(replay), false);
}
__name(addSettingsEvent, "addSettingsEvent");
function createReplayEnvelope(replayEvent, recordingData, dsn, tunnel) {
  return createEnvelope(
    createEventEnvelopeHeaders(replayEvent, getSdkMetadataForEnvelopeHeader(replayEvent), tunnel, dsn),
    [
      [{ type: "replay_event" }, replayEvent],
      [
        {
          type: "replay_recording",
          // If string then we need to encode to UTF8, otherwise will have
          // wrong size. TextEncoder has similar browser support to
          // MutationObserver, although it does not accept IE11.
          length: typeof recordingData === "string" ? new TextEncoder().encode(recordingData).length : recordingData.length
        },
        recordingData
      ]
    ]
  );
}
__name(createReplayEnvelope, "createReplayEnvelope");
function prepareRecordingData({
  recordingData,
  headers
}) {
  let payloadWithSequence;
  const replayHeaders = `${JSON.stringify(headers)}
`;
  if (typeof recordingData === "string") {
    payloadWithSequence = `${replayHeaders}${recordingData}`;
  } else {
    const enc = new TextEncoder();
    const sequence = enc.encode(replayHeaders);
    payloadWithSequence = new Uint8Array(sequence.length + recordingData.length);
    payloadWithSequence.set(sequence);
    payloadWithSequence.set(recordingData, sequence.length);
  }
  return payloadWithSequence;
}
__name(prepareRecordingData, "prepareRecordingData");
async function prepareReplayEvent({
  client,
  scope,
  replayId: event_id,
  event
}) {
  const integrations = typeof client._integrations === "object" && client._integrations !== null && !Array.isArray(client._integrations) ? Object.keys(client._integrations) : void 0;
  const eventHint = { event_id, integrations };
  client.emit("preprocessEvent", event, eventHint);
  const preparedEvent = await prepareEvent(
    client.getOptions(),
    event,
    eventHint,
    scope,
    client,
    getIsolationScope()
  );
  if (!preparedEvent) {
    return null;
  }
  preparedEvent.platform = preparedEvent.platform || "javascript";
  const metadata = client.getSdkMetadata();
  const { name: name2, version: version2 } = metadata && metadata.sdk || {};
  preparedEvent.sdk = {
    ...preparedEvent.sdk,
    name: name2 || "sentry.javascript.unknown",
    version: version2 || "0.0.0"
  };
  return preparedEvent;
}
__name(prepareReplayEvent, "prepareReplayEvent");
async function sendReplayRequest({
  recordingData,
  replayId,
  segmentId: segment_id,
  eventContext,
  timestamp: timestamp2,
  session
}) {
  const preparedRecordingData = prepareRecordingData({
    recordingData,
    headers: {
      segment_id
    }
  });
  const { urls, errorIds, traceIds, initialTimestamp } = eventContext;
  const client = getClient();
  const scope = getCurrentScope();
  const transport = client && client.getTransport();
  const dsn = client && client.getDsn();
  if (!client || !transport || !dsn || !session.sampled) {
    return resolvedSyncPromise({});
  }
  const baseEvent = {
    type: REPLAY_EVENT_NAME,
    replay_start_timestamp: initialTimestamp / 1e3,
    timestamp: timestamp2 / 1e3,
    error_ids: errorIds,
    trace_ids: traceIds,
    urls,
    replay_id: replayId,
    segment_id,
    replay_type: session.sampled
  };
  const replayEvent = await prepareReplayEvent({ scope, client, replayId, event: baseEvent });
  if (!replayEvent) {
    client.recordDroppedEvent("event_processor", "replay", baseEvent);
    DEBUG_BUILD$2 && logger$4.info("An event processor returned `null`, will not send event.");
    return resolvedSyncPromise({});
  }
  delete replayEvent.sdkProcessingMetadata;
  const envelope = createReplayEnvelope(replayEvent, preparedRecordingData, dsn, client.getOptions().tunnel);
  let response;
  try {
    response = await transport.send(envelope);
  } catch (err) {
    const error2 = new Error(UNABLE_TO_SEND_REPLAY);
    try {
      error2.cause = err;
    } catch (e2) {
    }
    throw error2;
  }
  if (typeof response.statusCode === "number" && (response.statusCode < 200 || response.statusCode >= 300)) {
    throw new TransportStatusCodeError(response.statusCode);
  }
  const rateLimits = updateRateLimits({}, response);
  if (isRateLimited(rateLimits, "replay")) {
    throw new RateLimitError(rateLimits);
  }
  return response;
}
__name(sendReplayRequest, "sendReplayRequest");
class TransportStatusCodeError extends Error {
  static {
    __name(this, "TransportStatusCodeError");
  }
  constructor(statusCode) {
    super(`Transport returned status code ${statusCode}`);
  }
}
class RateLimitError extends Error {
  static {
    __name(this, "RateLimitError");
  }
  constructor(rateLimits) {
    super("Rate limit hit");
    this.rateLimits = rateLimits;
  }
}
async function sendReplay(replayData, retryConfig = {
  count: 0,
  interval: RETRY_BASE_INTERVAL
}) {
  const { recordingData, onError } = replayData;
  if (!recordingData.length) {
    return;
  }
  try {
    await sendReplayRequest(replayData);
    return true;
  } catch (err) {
    if (err instanceof TransportStatusCodeError || err instanceof RateLimitError) {
      throw err;
    }
    setContext("Replays", {
      _retryCount: retryConfig.count
    });
    if (onError) {
      onError(err);
    }
    if (retryConfig.count >= RETRY_MAX_COUNT) {
      const error2 = new Error(`${UNABLE_TO_SEND_REPLAY} - max retries exceeded`);
      try {
        error2.cause = err;
      } catch (e2) {
      }
      throw error2;
    }
    retryConfig.interval *= ++retryConfig.count;
    return new Promise((resolve2, reject) => {
      setTimeout$3(async () => {
        try {
          await sendReplay(replayData, retryConfig);
          resolve2(true);
        } catch (err2) {
          reject(err2);
        }
      }, retryConfig.interval);
    });
  }
}
__name(sendReplay, "sendReplay");
const THROTTLED = "__THROTTLED";
const SKIPPED = "__SKIPPED";
function throttle$2(fn, maxCount, durationSeconds) {
  const counter = /* @__PURE__ */ new Map();
  const _cleanup = /* @__PURE__ */ __name((now2) => {
    const threshold = now2 - durationSeconds;
    counter.forEach((_value, key) => {
      if (key < threshold) {
        counter.delete(key);
      }
    });
  }, "_cleanup");
  const _getTotalCount = /* @__PURE__ */ __name(() => {
    return [...counter.values()].reduce((a2, b2) => a2 + b2, 0);
  }, "_getTotalCount");
  let isThrottled = false;
  return (...rest) => {
    const now2 = Math.floor(Date.now() / 1e3);
    _cleanup(now2);
    if (_getTotalCount() >= maxCount) {
      const wasThrottled = isThrottled;
      isThrottled = true;
      return wasThrottled ? SKIPPED : THROTTLED;
    }
    isThrottled = false;
    const count2 = counter.get(now2) || 0;
    counter.set(now2, count2 + 1);
    return fn(...rest);
  };
}
__name(throttle$2, "throttle$2");
class ReplayContainer {
  static {
    __name(this, "ReplayContainer");
  }
  /**
   * Recording can happen in one of two modes:
   *   - session: Record the whole session, sending it continuously
   *   - buffer: Always keep the last 60s of recording, requires:
   *     - having replaysOnErrorSampleRate > 0 to capture replay when an error occurs
   *     - or calling `flush()` to send the replay
   */
  /**
   * The current or last active span.
   * This is only available when performance is enabled.
   */
  /**
   * These are here so we can overwrite them in tests etc.
   * @hidden
   */
  /** The replay has to be manually started, because no sample rate (neither session or error) was provided. */
  /**
   * Options to pass to `rrweb.record()`
   */
  /**
   * Timestamp of the last user activity. This lives across sessions.
   */
  /**
   * Is the integration currently active?
   */
  /**
   * Paused is a state where:
   * - DOM Recording is not listening at all
   * - Nothing will be added to event buffer (e.g. core SDK events)
   */
  /**
   * Have we attached listeners to the core SDK?
   * Note we have to track this as there is no way to remove instrumentation handlers.
   */
  /**
   * Function to stop recording
   */
  /**
   * Internal use for canvas recording options
   */
  constructor({
    options: options2,
    recordingOptions
  }) {
    ReplayContainer.prototype.__init.call(this);
    ReplayContainer.prototype.__init2.call(this);
    ReplayContainer.prototype.__init3.call(this);
    ReplayContainer.prototype.__init4.call(this);
    ReplayContainer.prototype.__init5.call(this);
    ReplayContainer.prototype.__init6.call(this);
    this.eventBuffer = null;
    this.performanceEntries = [];
    this.replayPerformanceEntries = [];
    this.recordingMode = "session";
    this.timeouts = {
      sessionIdlePause: SESSION_IDLE_PAUSE_DURATION,
      sessionIdleExpire: SESSION_IDLE_EXPIRE_DURATION
    };
    this._lastActivity = Date.now();
    this._isEnabled = false;
    this._isPaused = false;
    this._requiresManualStart = false;
    this._hasInitializedCoreListeners = false;
    this._context = {
      errorIds: /* @__PURE__ */ new Set(),
      traceIds: /* @__PURE__ */ new Set(),
      urls: [],
      initialTimestamp: Date.now(),
      initialUrl: ""
    };
    this._recordingOptions = recordingOptions;
    this._options = options2;
    this._debouncedFlush = debounce(() => this._flush(), this._options.flushMinDelay, {
      maxWait: this._options.flushMaxDelay
    });
    this._throttledAddEvent = throttle$2(
      (event, isCheckout) => addEvent(this, event, isCheckout),
      // Max 300 events...
      300,
      // ... per 5s
      5
    );
    const { slowClickTimeout, slowClickIgnoreSelectors } = this.getOptions();
    const slowClickConfig = slowClickTimeout ? {
      threshold: Math.min(SLOW_CLICK_THRESHOLD, slowClickTimeout),
      timeout: slowClickTimeout,
      scrollTimeout: SLOW_CLICK_SCROLL_TIMEOUT,
      ignoreSelector: slowClickIgnoreSelectors ? slowClickIgnoreSelectors.join(",") : ""
    } : void 0;
    if (slowClickConfig) {
      this.clickDetector = new ClickDetector(this, slowClickConfig);
    }
    if (DEBUG_BUILD$2) {
      const experiments = options2._experiments;
      logger$4.setConfig({
        captureExceptions: !!experiments.captureExceptions,
        traceInternals: !!experiments.traceInternals
      });
    }
  }
  /** Get the event context. */
  getContext() {
    return this._context;
  }
  /** If recording is currently enabled. */
  isEnabled() {
    return this._isEnabled;
  }
  /** If recording is currently paused. */
  isPaused() {
    return this._isPaused;
  }
  /**
   * Determine if canvas recording is enabled
   */
  isRecordingCanvas() {
    return Boolean(this._canvas);
  }
  /** Get the replay integration options. */
  getOptions() {
    return this._options;
  }
  /** A wrapper to conditionally capture exceptions. */
  handleException(error2) {
    DEBUG_BUILD$2 && logger$4.exception(error2);
    if (this._options.onError) {
      this._options.onError(error2);
    }
  }
  /**
   * Initializes the plugin based on sampling configuration. Should not be
   * called outside of constructor.
   */
  initializeSampling(previousSessionId) {
    const { errorSampleRate, sessionSampleRate } = this._options;
    const requiresManualStart = errorSampleRate <= 0 && sessionSampleRate <= 0;
    this._requiresManualStart = requiresManualStart;
    if (requiresManualStart) {
      return;
    }
    this._initializeSessionForSampling(previousSessionId);
    if (!this.session) {
      DEBUG_BUILD$2 && logger$4.exception(new Error("Unable to initialize and create session"));
      return;
    }
    if (this.session.sampled === false) {
      return;
    }
    this.recordingMode = this.session.sampled === "buffer" && this.session.segmentId === 0 ? "buffer" : "session";
    DEBUG_BUILD$2 && logger$4.infoTick(`Starting replay in ${this.recordingMode} mode`);
    this._initializeRecording();
  }
  /**
   * Start a replay regardless of sampling rate. Calling this will always
   * create a new session. Will log a message if replay is already in progress.
   *
   * Creates or loads a session, attaches listeners to varying events (DOM,
   * _performanceObserver, Recording, Sentry SDK, etc)
   */
  start() {
    if (this._isEnabled && this.recordingMode === "session") {
      DEBUG_BUILD$2 && logger$4.info("Recording is already in progress");
      return;
    }
    if (this._isEnabled && this.recordingMode === "buffer") {
      DEBUG_BUILD$2 && logger$4.info("Buffering is in progress, call `flush()` to save the replay");
      return;
    }
    DEBUG_BUILD$2 && logger$4.infoTick("Starting replay in session mode");
    this._updateUserActivity();
    const session = loadOrCreateSession(
      {
        maxReplayDuration: this._options.maxReplayDuration,
        sessionIdleExpire: this.timeouts.sessionIdleExpire
      },
      {
        stickySession: this._options.stickySession,
        // This is intentional: create a new session-based replay when calling `start()`
        sessionSampleRate: 1,
        allowBuffering: false
      }
    );
    this.session = session;
    this._initializeRecording();
  }
  /**
   * Start replay buffering. Buffers until `flush()` is called or, if
   * `replaysOnErrorSampleRate` > 0, an error occurs.
   */
  startBuffering() {
    if (this._isEnabled) {
      DEBUG_BUILD$2 && logger$4.info("Buffering is in progress, call `flush()` to save the replay");
      return;
    }
    DEBUG_BUILD$2 && logger$4.infoTick("Starting replay in buffer mode");
    const session = loadOrCreateSession(
      {
        sessionIdleExpire: this.timeouts.sessionIdleExpire,
        maxReplayDuration: this._options.maxReplayDuration
      },
      {
        stickySession: this._options.stickySession,
        sessionSampleRate: 0,
        allowBuffering: true
      }
    );
    this.session = session;
    this.recordingMode = "buffer";
    this._initializeRecording();
  }
  /**
   * Start recording.
   *
   * Note that this will cause a new DOM checkout
   */
  startRecording() {
    try {
      const canvasOptions = this._canvas;
      this._stopRecording = record({
        ...this._recordingOptions,
        // When running in error sampling mode, we need to overwrite `checkoutEveryNms`
        // Without this, it would record forever, until an error happens, which we don't want
        // instead, we'll always keep the last 60 seconds of replay before an error happened
        ...this.recordingMode === "buffer" ? { checkoutEveryNms: BUFFER_CHECKOUT_TIME } : (
          // Otherwise, use experimental option w/ min checkout time of 6 minutes
          // This is to improve playback seeking as there could potentially be
          // less mutations to process in the worse cases.
          //
          // checkout by "N" events is probably ideal, but means we have less
          // control about the number of checkouts we make (which generally
          // increases replay size)
          this._options._experiments.continuousCheckout && {
            // Minimum checkout time is 6 minutes
            checkoutEveryNms: Math.max(36e4, this._options._experiments.continuousCheckout)
          }
        ),
        emit: getHandleRecordingEmit(this),
        onMutation: this._onMutationHandler,
        ...canvasOptions ? {
          recordCanvas: canvasOptions.recordCanvas,
          getCanvasManager: canvasOptions.getCanvasManager,
          sampling: canvasOptions.sampling,
          dataURLOptions: canvasOptions.dataURLOptions
        } : {}
      });
    } catch (err) {
      this.handleException(err);
    }
  }
  /**
   * Stops the recording, if it was running.
   *
   * Returns true if it was previously stopped, or is now stopped,
   * otherwise false.
   */
  stopRecording() {
    try {
      if (this._stopRecording) {
        this._stopRecording();
        this._stopRecording = void 0;
      }
      return true;
    } catch (err) {
      this.handleException(err);
      return false;
    }
  }
  /**
   * Currently, this needs to be manually called (e.g. for tests). Sentry SDK
   * does not support a teardown
   */
  async stop({ forceFlush = false, reason } = {}) {
    if (!this._isEnabled) {
      return;
    }
    this._isEnabled = false;
    try {
      DEBUG_BUILD$2 && logger$4.info(`Stopping Replay${reason ? ` triggered by ${reason}` : ""}`);
      resetReplayIdOnDynamicSamplingContext();
      this._removeListeners();
      this.stopRecording();
      this._debouncedFlush.cancel();
      if (forceFlush) {
        await this._flush({ force: true });
      }
      this.eventBuffer && this.eventBuffer.destroy();
      this.eventBuffer = null;
      clearSession(this);
    } catch (err) {
      this.handleException(err);
    }
  }
  /**
   * Pause some replay functionality. See comments for `_isPaused`.
   * This differs from stop as this only stops DOM recording, it is
   * not as thorough of a shutdown as `stop()`.
   */
  pause() {
    if (this._isPaused) {
      return;
    }
    this._isPaused = true;
    this.stopRecording();
    DEBUG_BUILD$2 && logger$4.info("Pausing replay");
  }
  /**
   * Resumes recording, see notes for `pause().
   *
   * Note that calling `startRecording()` here will cause a
   * new DOM checkout.`
   */
  resume() {
    if (!this._isPaused || !this._checkSession()) {
      return;
    }
    this._isPaused = false;
    this.startRecording();
    DEBUG_BUILD$2 && logger$4.info("Resuming replay");
  }
  /**
   * If not in "session" recording mode, flush event buffer which will create a new replay.
   * Unless `continueRecording` is false, the replay will continue to record and
   * behave as a "session"-based replay.
   *
   * Otherwise, queue up a flush.
   */
  async sendBufferedReplayOrFlush({ continueRecording = true } = {}) {
    if (this.recordingMode === "session") {
      return this.flushImmediate();
    }
    const activityTime = Date.now();
    DEBUG_BUILD$2 && logger$4.info("Converting buffer to session");
    await this.flushImmediate();
    const hasStoppedRecording = this.stopRecording();
    if (!continueRecording || !hasStoppedRecording) {
      return;
    }
    if (this.recordingMode === "session") {
      return;
    }
    this.recordingMode = "session";
    if (this.session) {
      this._updateUserActivity(activityTime);
      this._updateSessionActivity(activityTime);
      this._maybeSaveSession();
    }
    this.startRecording();
  }
  /**
   * We want to batch uploads of replay events. Save events only if
   * `<flushMinDelay>` milliseconds have elapsed since the last event
   * *OR* if `<flushMaxDelay>` milliseconds have elapsed.
   *
   * Accepts a callback to perform side-effects and returns true to stop batch
   * processing and hand back control to caller.
   */
  addUpdate(cb) {
    const cbResult = cb();
    if (this.recordingMode === "buffer") {
      return;
    }
    if (cbResult === true) {
      return;
    }
    this._debouncedFlush();
  }
  /**
   * Updates the user activity timestamp and resumes recording. This should be
   * called in an event handler for a user action that we consider as the user
   * being "active" (e.g. a mouse click).
   */
  triggerUserActivity() {
    this._updateUserActivity();
    if (!this._stopRecording) {
      if (!this._checkSession()) {
        return;
      }
      this.resume();
      return;
    }
    this.checkAndHandleExpiredSession();
    this._updateSessionActivity();
  }
  /**
   * Updates the user activity timestamp *without* resuming
   * recording. Some user events (e.g. keydown) can be create
   * low-value replays that only contain the keypress as a
   * breadcrumb. Instead this would require other events to
   * create a new replay after a session has expired.
   */
  updateUserActivity() {
    this._updateUserActivity();
    this._updateSessionActivity();
  }
  /**
   * Only flush if `this.recordingMode === 'session'`
   */
  conditionalFlush() {
    if (this.recordingMode === "buffer") {
      return Promise.resolve();
    }
    return this.flushImmediate();
  }
  /**
   * Flush using debounce flush
   */
  flush() {
    return this._debouncedFlush();
  }
  /**
   * Always flush via `_debouncedFlush` so that we do not have flushes triggered
   * from calling both `flush` and `_debouncedFlush`. Otherwise, there could be
   * cases of multiple flushes happening closely together.
   */
  flushImmediate() {
    this._debouncedFlush();
    return this._debouncedFlush.flush();
  }
  /**
   * Cancels queued up flushes.
   */
  cancelFlush() {
    this._debouncedFlush.cancel();
  }
  /** Get the current session (=replay) ID */
  getSessionId() {
    return this.session && this.session.id;
  }
  /**
   * Checks if recording should be stopped due to user inactivity. Otherwise
   * check if session is expired and create a new session if so. Triggers a new
   * full snapshot on new session.
   *
   * Returns true if session is not expired, false otherwise.
   * @hidden
   */
  checkAndHandleExpiredSession() {
    if (this._lastActivity && isExpired(this._lastActivity, this.timeouts.sessionIdlePause) && this.session && this.session.sampled === "session") {
      this.pause();
      return;
    }
    if (!this._checkSession()) {
      return false;
    }
    return true;
  }
  /**
   * Capture some initial state that can change throughout the lifespan of the
   * replay. This is required because otherwise they would be captured at the
   * first flush.
   */
  setInitialState() {
    const urlPath = `${WINDOW$1.location.pathname}${WINDOW$1.location.hash}${WINDOW$1.location.search}`;
    const url = `${WINDOW$1.location.origin}${urlPath}`;
    this.performanceEntries = [];
    this.replayPerformanceEntries = [];
    this._clearContext();
    this._context.initialUrl = url;
    this._context.initialTimestamp = Date.now();
    this._context.urls.push(url);
  }
  /**
   * Add a breadcrumb event, that may be throttled.
   * If it was throttled, we add a custom breadcrumb to indicate that.
   */
  throttledAddEvent(event, isCheckout) {
    const res = this._throttledAddEvent(event, isCheckout);
    if (res === THROTTLED) {
      const breadcrumb = createBreadcrumb({
        category: "replay.throttled"
      });
      this.addUpdate(() => {
        return !addEventSync(this, {
          type: ReplayEventTypeCustom,
          timestamp: breadcrumb.timestamp || 0,
          data: {
            tag: "breadcrumb",
            payload: breadcrumb,
            metric: true
          }
        });
      });
    }
    return res;
  }
  /**
   * This will get the parametrized route name of the current page.
   * This is only available if performance is enabled, and if an instrumented router is used.
   */
  getCurrentRoute() {
    const lastActiveSpan = this.lastActiveSpan || getActiveSpan();
    const lastRootSpan = lastActiveSpan && getRootSpan(lastActiveSpan);
    const attributes = lastRootSpan && spanToJSON(lastRootSpan).data || {};
    const source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];
    if (!lastRootSpan || !source || !["route", "custom"].includes(source)) {
      return void 0;
    }
    return spanToJSON(lastRootSpan).description;
  }
  /**
   * Initialize and start all listeners to varying events (DOM,
   * Performance Observer, Recording, Sentry SDK, etc)
   */
  _initializeRecording() {
    this.setInitialState();
    this._updateSessionActivity();
    this.eventBuffer = createEventBuffer({
      useCompression: this._options.useCompression,
      workerUrl: this._options.workerUrl
    });
    this._removeListeners();
    this._addListeners();
    this._isEnabled = true;
    this._isPaused = false;
    this.startRecording();
  }
  /**
   * Loads (or refreshes) the current session.
   */
  _initializeSessionForSampling(previousSessionId) {
    const allowBuffering = this._options.errorSampleRate > 0;
    const session = loadOrCreateSession(
      {
        sessionIdleExpire: this.timeouts.sessionIdleExpire,
        maxReplayDuration: this._options.maxReplayDuration,
        previousSessionId
      },
      {
        stickySession: this._options.stickySession,
        sessionSampleRate: this._options.sessionSampleRate,
        allowBuffering
      }
    );
    this.session = session;
  }
  /**
   * Checks and potentially refreshes the current session.
   * Returns false if session is not recorded.
   */
  _checkSession() {
    if (!this.session) {
      return false;
    }
    const currentSession = this.session;
    if (shouldRefreshSession(currentSession, {
      sessionIdleExpire: this.timeouts.sessionIdleExpire,
      maxReplayDuration: this._options.maxReplayDuration
    })) {
      this._refreshSession(currentSession);
      return false;
    }
    return true;
  }
  /**
   * Refresh a session with a new one.
   * This stops the current session (without forcing a flush, as that would never work since we are expired),
   * and then does a new sampling based on the refreshed session.
   */
  async _refreshSession(session) {
    if (!this._isEnabled) {
      return;
    }
    await this.stop({ reason: "refresh session" });
    this.initializeSampling(session.id);
  }
  /**
   * Adds listeners to record events for the replay
   */
  _addListeners() {
    try {
      WINDOW$1.document.addEventListener("visibilitychange", this._handleVisibilityChange);
      WINDOW$1.addEventListener("blur", this._handleWindowBlur);
      WINDOW$1.addEventListener("focus", this._handleWindowFocus);
      WINDOW$1.addEventListener("keydown", this._handleKeyboardEvent);
      if (this.clickDetector) {
        this.clickDetector.addListeners();
      }
      if (!this._hasInitializedCoreListeners) {
        addGlobalListeners(this);
        this._hasInitializedCoreListeners = true;
      }
    } catch (err) {
      this.handleException(err);
    }
    this._performanceCleanupCallback = setupPerformanceObserver(this);
  }
  /**
   * Cleans up listeners that were created in `_addListeners`
   */
  _removeListeners() {
    try {
      WINDOW$1.document.removeEventListener("visibilitychange", this._handleVisibilityChange);
      WINDOW$1.removeEventListener("blur", this._handleWindowBlur);
      WINDOW$1.removeEventListener("focus", this._handleWindowFocus);
      WINDOW$1.removeEventListener("keydown", this._handleKeyboardEvent);
      if (this.clickDetector) {
        this.clickDetector.removeListeners();
      }
      if (this._performanceCleanupCallback) {
        this._performanceCleanupCallback();
      }
    } catch (err) {
      this.handleException(err);
    }
  }
  /**
   * Handle when visibility of the page content changes. Opening a new tab will
   * cause the state to change to hidden because of content of current page will
   * be hidden. Likewise, moving a different window to cover the contents of the
   * page will also trigger a change to a hidden state.
   */
  __init() {
    this._handleVisibilityChange = () => {
      if (WINDOW$1.document.visibilityState === "visible") {
        this._doChangeToForegroundTasks();
      } else {
        this._doChangeToBackgroundTasks();
      }
    };
  }
  /**
   * Handle when page is blurred
   */
  __init2() {
    this._handleWindowBlur = () => {
      const breadcrumb = createBreadcrumb({
        category: "ui.blur"
      });
      this._doChangeToBackgroundTasks(breadcrumb);
    };
  }
  /**
   * Handle when page is focused
   */
  __init3() {
    this._handleWindowFocus = () => {
      const breadcrumb = createBreadcrumb({
        category: "ui.focus"
      });
      this._doChangeToForegroundTasks(breadcrumb);
    };
  }
  /** Ensure page remains active when a key is pressed. */
  __init4() {
    this._handleKeyboardEvent = (event) => {
      handleKeyboardEvent(this, event);
    };
  }
  /**
   * Tasks to run when we consider a page to be hidden (via blurring and/or visibility)
   */
  _doChangeToBackgroundTasks(breadcrumb) {
    if (!this.session) {
      return;
    }
    const expired = isSessionExpired(this.session, {
      maxReplayDuration: this._options.maxReplayDuration,
      sessionIdleExpire: this.timeouts.sessionIdleExpire
    });
    if (expired) {
      return;
    }
    if (breadcrumb) {
      this._createCustomBreadcrumb(breadcrumb);
    }
    void this.conditionalFlush();
  }
  /**
   * Tasks to run when we consider a page to be visible (via focus and/or visibility)
   */
  _doChangeToForegroundTasks(breadcrumb) {
    if (!this.session) {
      return;
    }
    const isSessionActive = this.checkAndHandleExpiredSession();
    if (!isSessionActive) {
      DEBUG_BUILD$2 && logger$4.info("Document has become active, but session has expired");
      return;
    }
    if (breadcrumb) {
      this._createCustomBreadcrumb(breadcrumb);
    }
  }
  /**
   * Update user activity (across session lifespans)
   */
  _updateUserActivity(_lastActivity = Date.now()) {
    this._lastActivity = _lastActivity;
  }
  /**
   * Updates the session's last activity timestamp
   */
  _updateSessionActivity(_lastActivity = Date.now()) {
    if (this.session) {
      this.session.lastActivity = _lastActivity;
      this._maybeSaveSession();
    }
  }
  /**
   * Helper to create (and buffer) a replay breadcrumb from a core SDK breadcrumb
   */
  _createCustomBreadcrumb(breadcrumb) {
    this.addUpdate(() => {
      this.throttledAddEvent({
        type: EventType$1.Custom,
        timestamp: breadcrumb.timestamp || 0,
        data: {
          tag: "breadcrumb",
          payload: breadcrumb
        }
      });
    });
  }
  /**
   * Observed performance events are added to `this.performanceEntries`. These
   * are included in the replay event before it is finished and sent to Sentry.
   */
  _addPerformanceEntries() {
    let performanceEntries = createPerformanceEntries(this.performanceEntries).concat(this.replayPerformanceEntries);
    this.performanceEntries = [];
    this.replayPerformanceEntries = [];
    if (this._requiresManualStart) {
      const initialTimestampInSeconds = this._context.initialTimestamp / 1e3;
      performanceEntries = performanceEntries.filter((entry) => entry.start >= initialTimestampInSeconds);
    }
    return Promise.all(createPerformanceSpans(this, performanceEntries));
  }
  /**
   * Clear _context
   */
  _clearContext() {
    this._context.errorIds.clear();
    this._context.traceIds.clear();
    this._context.urls = [];
  }
  /** Update the initial timestamp based on the buffer content. */
  _updateInitialTimestampFromEventBuffer() {
    const { session, eventBuffer } = this;
    if (!session || !eventBuffer || this._requiresManualStart) {
      return;
    }
    if (session.segmentId) {
      return;
    }
    const earliestEvent = eventBuffer.getEarliestTimestamp();
    if (earliestEvent && earliestEvent < this._context.initialTimestamp) {
      this._context.initialTimestamp = earliestEvent;
    }
  }
  /**
   * Return and clear _context
   */
  _popEventContext() {
    const _context = {
      initialTimestamp: this._context.initialTimestamp,
      initialUrl: this._context.initialUrl,
      errorIds: Array.from(this._context.errorIds),
      traceIds: Array.from(this._context.traceIds),
      urls: this._context.urls
    };
    this._clearContext();
    return _context;
  }
  /**
   * Flushes replay event buffer to Sentry.
   *
   * Performance events are only added right before flushing - this is
   * due to the buffered performance observer events.
   *
   * Should never be called directly, only by `flush`
   */
  async _runFlush() {
    const replayId = this.getSessionId();
    if (!this.session || !this.eventBuffer || !replayId) {
      DEBUG_BUILD$2 && logger$4.error("No session or eventBuffer found to flush.");
      return;
    }
    await this._addPerformanceEntries();
    if (!this.eventBuffer || !this.eventBuffer.hasEvents) {
      return;
    }
    await addMemoryEntry(this);
    if (!this.eventBuffer) {
      return;
    }
    if (replayId !== this.getSessionId()) {
      return;
    }
    try {
      this._updateInitialTimestampFromEventBuffer();
      const timestamp2 = Date.now();
      if (timestamp2 - this._context.initialTimestamp > this._options.maxReplayDuration + 3e4) {
        throw new Error("Session is too long, not sending replay");
      }
      const eventContext = this._popEventContext();
      const segmentId = this.session.segmentId++;
      this._maybeSaveSession();
      const recordingData = await this.eventBuffer.finish();
      await sendReplay({
        replayId,
        recordingData,
        segmentId,
        eventContext,
        session: this.session,
        timestamp: timestamp2,
        onError: /* @__PURE__ */ __name((err) => this.handleException(err), "onError")
      });
    } catch (err) {
      this.handleException(err);
      this.stop({ reason: "sendReplay" });
      const client = getClient();
      if (client) {
        const dropReason = err instanceof RateLimitError ? "ratelimit_backoff" : "send_error";
        client.recordDroppedEvent(dropReason, "replay");
      }
    }
  }
  /**
   * Flush recording data to Sentry. Creates a lock so that only a single flush
   * can be active at a time. Do not call this directly.
   */
  __init5() {
    this._flush = async ({
      force = false
    } = {}) => {
      if (!this._isEnabled && !force) {
        return;
      }
      if (!this.checkAndHandleExpiredSession()) {
        DEBUG_BUILD$2 && logger$4.error("Attempting to finish replay event after session expired.");
        return;
      }
      if (!this.session) {
        return;
      }
      const start2 = this.session.started;
      const now2 = Date.now();
      const duration = now2 - start2;
      this._debouncedFlush.cancel();
      const tooShort = duration < this._options.minReplayDuration;
      const tooLong = duration > this._options.maxReplayDuration + 5e3;
      if (tooShort || tooLong) {
        DEBUG_BUILD$2 && logger$4.info(
          `Session duration (${Math.floor(duration / 1e3)}s) is too ${tooShort ? "short" : "long"}, not sending replay.`
        );
        if (tooShort) {
          this._debouncedFlush();
        }
        return;
      }
      const eventBuffer = this.eventBuffer;
      if (eventBuffer && this.session.segmentId === 0 && !eventBuffer.hasCheckout) {
        DEBUG_BUILD$2 && logger$4.info("Flushing initial segment without checkout.");
      }
      const _flushInProgress = !!this._flushLock;
      if (!this._flushLock) {
        this._flushLock = this._runFlush();
      }
      try {
        await this._flushLock;
      } catch (err) {
        this.handleException(err);
      } finally {
        this._flushLock = void 0;
        if (_flushInProgress) {
          this._debouncedFlush();
        }
      }
    };
  }
  /** Save the session, if it is sticky */
  _maybeSaveSession() {
    if (this.session && this._options.stickySession) {
      saveSession(this.session);
    }
  }
  /** Handler for rrweb.record.onMutation */
  __init6() {
    this._onMutationHandler = (mutations) => {
      const count2 = mutations.length;
      const mutationLimit = this._options.mutationLimit;
      const mutationBreadcrumbLimit = this._options.mutationBreadcrumbLimit;
      const overMutationLimit = mutationLimit && count2 > mutationLimit;
      if (count2 > mutationBreadcrumbLimit || overMutationLimit) {
        const breadcrumb = createBreadcrumb({
          category: "replay.mutations",
          data: {
            count: count2,
            limit: overMutationLimit
          }
        });
        this._createCustomBreadcrumb(breadcrumb);
      }
      if (overMutationLimit) {
        this.stop({ reason: "mutationLimit", forceFlush: this.recordingMode === "session" });
        return false;
      }
      return true;
    };
  }
}
function getOption(selectors, defaultSelectors) {
  return [
    ...selectors,
    // sentry defaults
    ...defaultSelectors
  ].join(",");
}
__name(getOption, "getOption");
function getPrivacyOptions({ mask, unmask, block: block2, unblock, ignore }) {
  const defaultBlockedElements = ["base", "iframe[srcdoc]:not([src])"];
  const maskSelector = getOption(mask, [".sentry-mask", "[data-sentry-mask]"]);
  const unmaskSelector = getOption(unmask, []);
  const options2 = {
    // We are making the decision to make text and input selectors the same
    maskTextSelector: maskSelector,
    unmaskTextSelector: unmaskSelector,
    blockSelector: getOption(block2, [".sentry-block", "[data-sentry-block]", ...defaultBlockedElements]),
    unblockSelector: getOption(unblock, []),
    ignoreSelector: getOption(ignore, [".sentry-ignore", "[data-sentry-ignore]", 'input[type="file"]'])
  };
  return options2;
}
__name(getPrivacyOptions, "getPrivacyOptions");
function maskAttribute({
  el,
  key,
  maskAttributes,
  maskAllText,
  privacyOptions,
  value
}) {
  if (!maskAllText) {
    return value;
  }
  if (privacyOptions.unmaskTextSelector && el.matches(privacyOptions.unmaskTextSelector)) {
    return value;
  }
  if (maskAttributes.includes(key) || // Need to mask `value` attribute for `<input>` if it's a button-like
  // type
  key === "value" && el.tagName === "INPUT" && ["submit", "button"].includes(el.getAttribute("type") || "")) {
    return value.replace(/[\S]/g, "*");
  }
  return value;
}
__name(maskAttribute, "maskAttribute");
const MEDIA_SELECTORS = 'img,image,svg,video,object,picture,embed,map,audio,link[rel="icon"],link[rel="apple-touch-icon"]';
const DEFAULT_NETWORK_HEADERS = ["content-length", "content-type", "accept"];
let _initialized = false;
const replayIntegration = /* @__PURE__ */ __name((options2) => {
  return new Replay(options2);
}, "replayIntegration");
class Replay {
  static {
    __name(this, "Replay");
  }
  /**
   * @inheritDoc
   */
  static __initStatic() {
    this.id = "Replay";
  }
  /**
   * @inheritDoc
   */
  /**
   * Options to pass to `rrweb.record()`
   */
  /**
   * Initial options passed to the replay integration, merged with default values.
   * Note: `sessionSampleRate` and `errorSampleRate` are not required here, as they
   * can only be finally set when setupOnce() is called.
   *
   * @private
   */
  constructor({
    flushMinDelay = DEFAULT_FLUSH_MIN_DELAY,
    flushMaxDelay = DEFAULT_FLUSH_MAX_DELAY,
    minReplayDuration = MIN_REPLAY_DURATION,
    maxReplayDuration = MAX_REPLAY_DURATION,
    stickySession = true,
    useCompression = true,
    workerUrl,
    _experiments = {},
    maskAllText = true,
    maskAllInputs = true,
    blockAllMedia = true,
    mutationBreadcrumbLimit = 750,
    mutationLimit = 1e4,
    slowClickTimeout = 7e3,
    slowClickIgnoreSelectors = [],
    networkDetailAllowUrls = [],
    networkDetailDenyUrls = [],
    networkCaptureBodies = true,
    networkRequestHeaders = [],
    networkResponseHeaders = [],
    mask = [],
    maskAttributes = ["title", "placeholder"],
    unmask = [],
    block: block2 = [],
    unblock = [],
    ignore = [],
    maskFn,
    beforeAddRecordingEvent,
    beforeErrorSampling,
    onError
  } = {}) {
    this.name = Replay.id;
    const privacyOptions = getPrivacyOptions({
      mask,
      unmask,
      block: block2,
      unblock,
      ignore
    });
    this._recordingOptions = {
      maskAllInputs,
      maskAllText,
      maskInputOptions: { password: true },
      maskTextFn: maskFn,
      maskInputFn: maskFn,
      maskAttributeFn: /* @__PURE__ */ __name((key, value, el) => maskAttribute({
        maskAttributes,
        maskAllText,
        privacyOptions,
        key,
        value,
        el
      }), "maskAttributeFn"),
      ...privacyOptions,
      // Our defaults
      slimDOMOptions: "all",
      inlineStylesheet: true,
      // Disable inline images as it will increase segment/replay size
      inlineImages: false,
      // collect fonts, but be aware that `sentry.io` needs to be an allowed
      // origin for playback
      collectFonts: true,
      errorHandler: /* @__PURE__ */ __name((err) => {
        try {
          err.__rrweb__ = true;
        } catch (error2) {
        }
      }, "errorHandler")
    };
    this._initialOptions = {
      flushMinDelay,
      flushMaxDelay,
      minReplayDuration: Math.min(minReplayDuration, MIN_REPLAY_DURATION_LIMIT),
      maxReplayDuration: Math.min(maxReplayDuration, MAX_REPLAY_DURATION),
      stickySession,
      useCompression,
      workerUrl,
      blockAllMedia,
      maskAllInputs,
      maskAllText,
      mutationBreadcrumbLimit,
      mutationLimit,
      slowClickTimeout,
      slowClickIgnoreSelectors,
      networkDetailAllowUrls,
      networkDetailDenyUrls,
      networkCaptureBodies,
      networkRequestHeaders: _getMergedNetworkHeaders(networkRequestHeaders),
      networkResponseHeaders: _getMergedNetworkHeaders(networkResponseHeaders),
      beforeAddRecordingEvent,
      beforeErrorSampling,
      onError,
      _experiments
    };
    if (this._initialOptions.blockAllMedia) {
      this._recordingOptions.blockSelector = !this._recordingOptions.blockSelector ? MEDIA_SELECTORS : `${this._recordingOptions.blockSelector},${MEDIA_SELECTORS}`;
    }
    if (this._isInitialized && isBrowser$2()) {
      throw new Error("Multiple Sentry Session Replay instances are not supported");
    }
    this._isInitialized = true;
  }
  /** If replay has already been initialized */
  get _isInitialized() {
    return _initialized;
  }
  /** Update _isInitialized */
  set _isInitialized(value) {
    _initialized = value;
  }
  /**
   * Setup and initialize replay container
   */
  afterAllSetup(client) {
    if (!isBrowser$2() || this._replay) {
      return;
    }
    this._setup(client);
    this._initialize(client);
  }
  /**
   * Start a replay regardless of sampling rate. Calling this will always
   * create a new session. Will log a message if replay is already in progress.
   *
   * Creates or loads a session, attaches listeners to varying events (DOM,
   * PerformanceObserver, Recording, Sentry SDK, etc)
   */
  start() {
    if (!this._replay) {
      return;
    }
    this._replay.start();
  }
  /**
   * Start replay buffering. Buffers until `flush()` is called or, if
   * `replaysOnErrorSampleRate` > 0, until an error occurs.
   */
  startBuffering() {
    if (!this._replay) {
      return;
    }
    this._replay.startBuffering();
  }
  /**
   * Currently, this needs to be manually called (e.g. for tests). Sentry SDK
   * does not support a teardown
   */
  stop() {
    if (!this._replay) {
      return Promise.resolve();
    }
    return this._replay.stop({ forceFlush: this._replay.recordingMode === "session" });
  }
  /**
   * If not in "session" recording mode, flush event buffer which will create a new replay.
   * If replay is not enabled, a new session replay is started.
   * Unless `continueRecording` is false, the replay will continue to record and
   * behave as a "session"-based replay.
   *
   * Otherwise, queue up a flush.
   */
  flush(options2) {
    if (!this._replay) {
      return Promise.resolve();
    }
    if (!this._replay.isEnabled()) {
      this._replay.start();
      return Promise.resolve();
    }
    return this._replay.sendBufferedReplayOrFlush(options2);
  }
  /**
   * Get the current session ID.
   */
  getReplayId() {
    if (!this._replay || !this._replay.isEnabled()) {
      return;
    }
    return this._replay.getSessionId();
  }
  /**
   * Get the current recording mode. This can be either `session` or `buffer`.
   *
   * `session`: Recording the whole session, sending it continuously
   * `buffer`: Always keeping the last 60s of recording, requires:
   *   - having replaysOnErrorSampleRate > 0 to capture replay when an error occurs
   *   - or calling `flush()` to send the replay
   */
  getRecordingMode() {
    if (!this._replay || !this._replay.isEnabled()) {
      return;
    }
    return this._replay.recordingMode;
  }
  /**
   * Initializes replay.
   */
  _initialize(client) {
    if (!this._replay) {
      return;
    }
    this._maybeLoadFromReplayCanvasIntegration(client);
    this._replay.initializeSampling();
  }
  /** Setup the integration. */
  _setup(client) {
    const finalOptions = loadReplayOptionsFromClient(this._initialOptions, client);
    this._replay = new ReplayContainer({
      options: finalOptions,
      recordingOptions: this._recordingOptions
    });
  }
  /** Get canvas options from ReplayCanvas integration, if it is also added. */
  _maybeLoadFromReplayCanvasIntegration(client) {
    try {
      const canvasIntegration = client.getIntegrationByName("ReplayCanvas");
      if (!canvasIntegration) {
        return;
      }
      this._replay["_canvas"] = canvasIntegration.getOptions();
    } catch (e2) {
    }
  }
}
Replay.__initStatic();
function loadReplayOptionsFromClient(initialOptions, client) {
  const opt = client.getOptions();
  const finalOptions = {
    sessionSampleRate: 0,
    errorSampleRate: 0,
    ...dropUndefinedKeys(initialOptions)
  };
  const replaysSessionSampleRate = parseSampleRate(opt.replaysSessionSampleRate);
  const replaysOnErrorSampleRate = parseSampleRate(opt.replaysOnErrorSampleRate);
  if (replaysSessionSampleRate == null && replaysOnErrorSampleRate == null) {
    consoleSandbox(() => {
      console.warn(
        "Replay is disabled because neither `replaysSessionSampleRate` nor `replaysOnErrorSampleRate` are set."
      );
    });
  }
  if (replaysSessionSampleRate != null) {
    finalOptions.sessionSampleRate = replaysSessionSampleRate;
  }
  if (replaysOnErrorSampleRate != null) {
    finalOptions.errorSampleRate = replaysOnErrorSampleRate;
  }
  return finalOptions;
}
__name(loadReplayOptionsFromClient, "loadReplayOptionsFromClient");
function _getMergedNetworkHeaders(headers) {
  return [...DEFAULT_NETWORK_HEADERS, ...headers.map((header) => header.toLowerCase())];
}
__name(_getMergedNetworkHeaders, "_getMergedNetworkHeaders");
function getReplay() {
  const client = getClient();
  return client && client.getIntegrationByName("Replay");
}
__name(getReplay, "getReplay");
var NodeType$2;
(function(NodeType3) {
  NodeType3[NodeType3["Document"] = 0] = "Document";
  NodeType3[NodeType3["DocumentType"] = 1] = "DocumentType";
  NodeType3[NodeType3["Element"] = 2] = "Element";
  NodeType3[NodeType3["Text"] = 3] = "Text";
  NodeType3[NodeType3["CDATA"] = 4] = "CDATA";
  NodeType3[NodeType3["Comment"] = 5] = "Comment";
})(NodeType$2 || (NodeType$2 = {}));
function elementClassMatchesRegex(el, regex2) {
  for (let eIndex = el.classList.length; eIndex--; ) {
    const className = el.classList[eIndex];
    if (regex2.test(className)) {
      return true;
    }
  }
  return false;
}
__name(elementClassMatchesRegex, "elementClassMatchesRegex");
function distanceToMatch(node2, matchPredicate, limit2 = Infinity, distance2 = 0) {
  if (!node2)
    return -1;
  if (node2.nodeType !== node2.ELEMENT_NODE)
    return -1;
  if (distance2 > limit2)
    return -1;
  if (matchPredicate(node2))
    return distance2;
  return distanceToMatch(node2.parentNode, matchPredicate, limit2, distance2 + 1);
}
__name(distanceToMatch, "distanceToMatch");
function createMatchPredicate(className, selector) {
  return (node2) => {
    const el = node2;
    if (el === null)
      return false;
    try {
      if (className) {
        if (typeof className === "string") {
          if (el.matches(`.${className}`))
            return true;
        } else if (elementClassMatchesRegex(el, className)) {
          return true;
        }
      }
      if (selector && el.matches(selector))
        return true;
      return false;
    } catch (e2) {
      return false;
    }
  };
}
__name(createMatchPredicate, "createMatchPredicate");
const DEPARTED_MIRROR_ACCESS_WARNING = "Please stop import mirror directly. Instead of that,\r\nnow you can use replayer.getMirror() to access the mirror instance of a replayer,\r\nor you can use record.mirror to access the mirror instance during recording.";
let _mirror = {
  map: {},
  getId() {
    console.error(DEPARTED_MIRROR_ACCESS_WARNING);
    return -1;
  },
  getNode() {
    console.error(DEPARTED_MIRROR_ACCESS_WARNING);
    return null;
  },
  removeNodeFromMap() {
    console.error(DEPARTED_MIRROR_ACCESS_WARNING);
  },
  has() {
    console.error(DEPARTED_MIRROR_ACCESS_WARNING);
    return false;
  },
  reset() {
    console.error(DEPARTED_MIRROR_ACCESS_WARNING);
  }
};
if (typeof window !== "undefined" && window.Proxy && window.Reflect) {
  _mirror = new Proxy(_mirror, {
    get(target, prop2, receiver) {
      if (prop2 === "map") {
        console.error(DEPARTED_MIRROR_ACCESS_WARNING);
      }
      return Reflect.get(target, prop2, receiver);
    }
  });
}
function hookSetter(target, key, d2, isRevoked, win = window) {
  const original = win.Object.getOwnPropertyDescriptor(target, key);
  win.Object.defineProperty(target, key, isRevoked ? d2 : {
    set(value) {
      setTimeout$1(() => {
        d2.set.call(this, value);
      }, 0);
      if (original && original.set) {
        original.set.call(this, value);
      }
    }
  });
  return () => hookSetter(target, key, original || {}, true);
}
__name(hookSetter, "hookSetter");
function patch$1(source, name2, replacement) {
  try {
    if (!(name2 in source)) {
      return () => {
      };
    }
    const original = source[name2];
    const wrapped = replacement(original);
    if (typeof wrapped === "function") {
      wrapped.prototype = wrapped.prototype || {};
      Object.defineProperties(wrapped, {
        __rrweb_original__: {
          enumerable: false,
          value: original
        }
      });
    }
    source[name2] = wrapped;
    return () => {
      source[name2] = original;
    };
  } catch (e2) {
    return () => {
    };
  }
}
__name(patch$1, "patch$1");
if (!/[1-9][0-9]{12}/.test(Date.now().toString())) ;
function closestElementOfNode(node2) {
  if (!node2) {
    return null;
  }
  const el = node2.nodeType === node2.ELEMENT_NODE ? node2 : node2.parentElement;
  return el;
}
__name(closestElementOfNode, "closestElementOfNode");
function isBlocked(node2, blockClass, blockSelector, unblockSelector, checkAncestors) {
  if (!node2) {
    return false;
  }
  const el = closestElementOfNode(node2);
  if (!el) {
    return false;
  }
  const blockedPredicate = createMatchPredicate(blockClass, blockSelector);
  const blockDistance = distanceToMatch(el, blockedPredicate);
  let unblockDistance = -1;
  if (blockDistance < 0) {
    return false;
  }
  if (unblockSelector) {
    unblockDistance = distanceToMatch(el, createMatchPredicate(null, unblockSelector));
  }
  if (blockDistance > -1 && unblockDistance < 0) {
    return true;
  }
  return blockDistance < unblockDistance;
}
__name(isBlocked, "isBlocked");
const cachedImplementations = {};
function getImplementation(name2) {
  const cached = cachedImplementations[name2];
  if (cached) {
    return cached;
  }
  const document2 = window.document;
  let impl = window[name2];
  if (document2 && typeof document2.createElement === "function") {
    try {
      const sandbox = document2.createElement("iframe");
      sandbox.hidden = true;
      document2.head.appendChild(sandbox);
      const contentWindow = sandbox.contentWindow;
      if (contentWindow && contentWindow[name2]) {
        impl = contentWindow[name2];
      }
      document2.head.removeChild(sandbox);
    } catch (e2) {
    }
  }
  return cachedImplementations[name2] = impl.bind(window);
}
__name(getImplementation, "getImplementation");
function onRequestAnimationFrame(...rest) {
  return getImplementation("requestAnimationFrame")(...rest);
}
__name(onRequestAnimationFrame, "onRequestAnimationFrame");
function setTimeout$1(...rest) {
  return getImplementation("setTimeout")(...rest);
}
__name(setTimeout$1, "setTimeout$1");
var CanvasContext = /* @__PURE__ */ ((CanvasContext2) => {
  CanvasContext2[CanvasContext2["2D"] = 0] = "2D";
  CanvasContext2[CanvasContext2["WebGL"] = 1] = "WebGL";
  CanvasContext2[CanvasContext2["WebGL2"] = 2] = "WebGL2";
  return CanvasContext2;
})(CanvasContext || {});
let errorHandler;
function registerErrorHandler(handler5) {
  errorHandler = handler5;
}
__name(registerErrorHandler, "registerErrorHandler");
const callbackWrapper = /* @__PURE__ */ __name((cb) => {
  if (!errorHandler) {
    return cb;
  }
  const rrwebWrapped = /* @__PURE__ */ __name((...rest) => {
    try {
      return cb(...rest);
    } catch (error2) {
      if (errorHandler && errorHandler(error2) === true) {
        return () => {
        };
      }
      throw error2;
    }
  }, "rrwebWrapped");
  return rrwebWrapped;
}, "callbackWrapper");
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var lookup = typeof Uint8Array === "undefined" ? [] : new Uint8Array(256);
for (var i$3 = 0; i$3 < chars.length; i$3++) {
  lookup[chars.charCodeAt(i$3)] = i$3;
}
var encode$5 = /* @__PURE__ */ __name(function(arraybuffer) {
  var bytes = new Uint8Array(arraybuffer), i2, len = bytes.length, base642 = "";
  for (i2 = 0; i2 < len; i2 += 3) {
    base642 += chars[bytes[i2] >> 2];
    base642 += chars[(bytes[i2] & 3) << 4 | bytes[i2 + 1] >> 4];
    base642 += chars[(bytes[i2 + 1] & 15) << 2 | bytes[i2 + 2] >> 6];
    base642 += chars[bytes[i2 + 2] & 63];
  }
  if (len % 3 === 2) {
    base642 = base642.substring(0, base642.length - 1) + "=";
  } else if (len % 3 === 1) {
    base642 = base642.substring(0, base642.length - 2) + "==";
  }
  return base642;
}, "encode$5");
const canvasVarMap = /* @__PURE__ */ new Map();
function variableListFor(ctx, ctor) {
  let contextMap = canvasVarMap.get(ctx);
  if (!contextMap) {
    contextMap = /* @__PURE__ */ new Map();
    canvasVarMap.set(ctx, contextMap);
  }
  if (!contextMap.has(ctor)) {
    contextMap.set(ctor, []);
  }
  return contextMap.get(ctor);
}
__name(variableListFor, "variableListFor");
const saveWebGLVar = /* @__PURE__ */ __name((value, win, ctx) => {
  if (!value || !(isInstanceOfWebGLObject(value, win) || typeof value === "object"))
    return;
  const name2 = value.constructor.name;
  const list2 = variableListFor(ctx, name2);
  let index2 = list2.indexOf(value);
  if (index2 === -1) {
    index2 = list2.length;
    list2.push(value);
  }
  return index2;
}, "saveWebGLVar");
function serializeArg(value, win, ctx) {
  if (value instanceof Array) {
    return value.map((arg) => serializeArg(arg, win, ctx));
  } else if (value === null) {
    return value;
  } else if (value instanceof Float32Array || value instanceof Float64Array || value instanceof Int32Array || value instanceof Uint32Array || value instanceof Uint8Array || value instanceof Uint16Array || value instanceof Int16Array || value instanceof Int8Array || value instanceof Uint8ClampedArray) {
    const name2 = value.constructor.name;
    return {
      rr_type: name2,
      args: [Object.values(value)]
    };
  } else if (value instanceof ArrayBuffer) {
    const name2 = value.constructor.name;
    const base642 = encode$5(value);
    return {
      rr_type: name2,
      base64: base642
    };
  } else if (value instanceof DataView) {
    const name2 = value.constructor.name;
    return {
      rr_type: name2,
      args: [
        serializeArg(value.buffer, win, ctx),
        value.byteOffset,
        value.byteLength
      ]
    };
  } else if (value instanceof HTMLImageElement) {
    const name2 = value.constructor.name;
    const { src } = value;
    return {
      rr_type: name2,
      src
    };
  } else if (value instanceof HTMLCanvasElement) {
    const name2 = "HTMLImageElement";
    const src = value.toDataURL();
    return {
      rr_type: name2,
      src
    };
  } else if (value instanceof ImageData) {
    const name2 = value.constructor.name;
    return {
      rr_type: name2,
      args: [serializeArg(value.data, win, ctx), value.width, value.height]
    };
  } else if (isInstanceOfWebGLObject(value, win) || typeof value === "object") {
    const name2 = value.constructor.name;
    const index2 = saveWebGLVar(value, win, ctx);
    return {
      rr_type: name2,
      index: index2
    };
  }
  return value;
}
__name(serializeArg, "serializeArg");
const serializeArgs = /* @__PURE__ */ __name((args, win, ctx) => {
  return args.map((arg) => serializeArg(arg, win, ctx));
}, "serializeArgs");
const isInstanceOfWebGLObject = /* @__PURE__ */ __name((value, win) => {
  const webGLConstructorNames = [
    "WebGLActiveInfo",
    "WebGLBuffer",
    "WebGLFramebuffer",
    "WebGLProgram",
    "WebGLRenderbuffer",
    "WebGLShader",
    "WebGLShaderPrecisionFormat",
    "WebGLTexture",
    "WebGLUniformLocation",
    "WebGLVertexArrayObject",
    "WebGLVertexArrayObjectOES"
  ];
  const supportedWebGLConstructorNames = webGLConstructorNames.filter((name2) => typeof win[name2] === "function");
  return Boolean(supportedWebGLConstructorNames.find((name2) => value instanceof win[name2]));
}, "isInstanceOfWebGLObject");
function initCanvas2DMutationObserver(cb, win, blockClass, blockSelector, unblockSelector) {
  const handlers2 = [];
  const props2D = Object.getOwnPropertyNames(win.CanvasRenderingContext2D.prototype);
  for (const prop2 of props2D) {
    try {
      if (typeof win.CanvasRenderingContext2D.prototype[prop2] !== "function") {
        continue;
      }
      const restoreHandler = patch$1(win.CanvasRenderingContext2D.prototype, prop2, function(original) {
        return function(...args) {
          if (!isBlocked(this.canvas, blockClass, blockSelector, unblockSelector, true)) {
            setTimeout$1(() => {
              const recordArgs = serializeArgs(args, win, this);
              cb(this.canvas, {
                type: CanvasContext["2D"],
                property: prop2,
                args: recordArgs
              });
            }, 0);
          }
          return original.apply(this, args);
        };
      });
      handlers2.push(restoreHandler);
    } catch (e2) {
      const hookHandler = hookSetter(win.CanvasRenderingContext2D.prototype, prop2, {
        set(v2) {
          cb(this.canvas, {
            type: CanvasContext["2D"],
            property: prop2,
            args: [v2],
            setter: true
          });
        }
      });
      handlers2.push(hookHandler);
    }
  }
  return () => {
    handlers2.forEach((h2) => h2());
  };
}
__name(initCanvas2DMutationObserver, "initCanvas2DMutationObserver");
function getNormalizedContextName(contextType) {
  return contextType === "experimental-webgl" ? "webgl" : contextType;
}
__name(getNormalizedContextName, "getNormalizedContextName");
function initCanvasContextObserver(win, blockClass, blockSelector, unblockSelector, setPreserveDrawingBufferToTrue) {
  const handlers2 = [];
  try {
    const restoreHandler = patch$1(win.HTMLCanvasElement.prototype, "getContext", function(original) {
      return function(contextType, ...args) {
        if (!isBlocked(this, blockClass, blockSelector, unblockSelector, true)) {
          const ctxName = getNormalizedContextName(contextType);
          if (!("__context" in this))
            this.__context = ctxName;
          if (setPreserveDrawingBufferToTrue && ["webgl", "webgl2"].includes(ctxName)) {
            if (args[0] && typeof args[0] === "object") {
              const contextAttributes = args[0];
              if (!contextAttributes.preserveDrawingBuffer) {
                contextAttributes.preserveDrawingBuffer = true;
              }
            } else {
              args.splice(0, 1, {
                preserveDrawingBuffer: true
              });
            }
          }
        }
        return original.apply(this, [contextType, ...args]);
      };
    });
    handlers2.push(restoreHandler);
  } catch (e2) {
    console.error("failed to patch HTMLCanvasElement.prototype.getContext");
  }
  return () => {
    handlers2.forEach((h2) => h2());
  };
}
__name(initCanvasContextObserver, "initCanvasContextObserver");
function patchGLPrototype(prototype2, type, cb, blockClass, blockSelector, unblockSelector, mirror2, win) {
  const handlers2 = [];
  const props = Object.getOwnPropertyNames(prototype2);
  for (const prop2 of props) {
    if ([
      "isContextLost",
      "canvas",
      "drawingBufferWidth",
      "drawingBufferHeight"
    ].includes(prop2)) {
      continue;
    }
    try {
      if (typeof prototype2[prop2] !== "function") {
        continue;
      }
      const restoreHandler = patch$1(prototype2, prop2, function(original) {
        return function(...args) {
          const result = original.apply(this, args);
          saveWebGLVar(result, win, this);
          if ("tagName" in this.canvas && !isBlocked(this.canvas, blockClass, blockSelector, unblockSelector, true)) {
            const recordArgs = serializeArgs(args, win, this);
            const mutation = {
              type,
              property: prop2,
              args: recordArgs
            };
            cb(this.canvas, mutation);
          }
          return result;
        };
      });
      handlers2.push(restoreHandler);
    } catch (e2) {
      const hookHandler = hookSetter(prototype2, prop2, {
        set(v2) {
          cb(this.canvas, {
            type,
            property: prop2,
            args: [v2],
            setter: true
          });
        }
      });
      handlers2.push(hookHandler);
    }
  }
  return handlers2;
}
__name(patchGLPrototype, "patchGLPrototype");
function initCanvasWebGLMutationObserver(cb, win, blockClass, blockSelector, unblockSelector, mirror2) {
  const handlers2 = [];
  handlers2.push(...patchGLPrototype(win.WebGLRenderingContext.prototype, CanvasContext.WebGL, cb, blockClass, blockSelector, unblockSelector, mirror2, win));
  if (typeof win.WebGL2RenderingContext !== "undefined") {
    handlers2.push(...patchGLPrototype(win.WebGL2RenderingContext.prototype, CanvasContext.WebGL2, cb, blockClass, blockSelector, unblockSelector, mirror2, win));
  }
  return () => {
    handlers2.forEach((h2) => h2());
  };
}
__name(initCanvasWebGLMutationObserver, "initCanvasWebGLMutationObserver");
var r$2 = `for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t="undefined"==typeof Uint8Array?[]:new Uint8Array(256),a=0;a<64;a++)t[e.charCodeAt(a)]=a;var n=function(t){var a,n=new Uint8Array(t),r=n.length,s="";for(a=0;a<r;a+=3)s+=e[n[a]>>2],s+=e[(3&n[a])<<4|n[a+1]>>4],s+=e[(15&n[a+1])<<2|n[a+2]>>6],s+=e[63&n[a+2]];return r%3==2?s=s.substring(0,s.length-1)+"=":r%3==1&&(s=s.substring(0,s.length-2)+"=="),s};const r=new Map,s=new Map;const i=self;i.onmessage=async function(e){if(!("OffscreenCanvas"in globalThis))return i.postMessage({id:e.data.id});{const{id:t,bitmap:a,width:o,height:f,maxCanvasSize:c,dataURLOptions:g}=e.data,u=async function(e,t,a){const r=e+"-"+t;if("OffscreenCanvas"in globalThis){if(s.has(r))return s.get(r);const i=new OffscreenCanvas(e,t);i.getContext("2d");const o=await i.convertToBlob(a),f=await o.arrayBuffer(),c=n(f);return s.set(r,c),c}return""}(o,f,g),[h,d]=function(e,t,a){if(!a)return[e,t];const[n,r]=a;if(e<=n&&t<=r)return[e,t];let s=e,i=t;return s>n&&(i=Math.floor(n*t/e),s=n),i>r&&(s=Math.floor(r*e/t),i=r),[s,i]}(o,f,c),l=new OffscreenCanvas(h,d),w=l.getContext("bitmaprenderer"),p=h===o&&d===f?a:await createImageBitmap(a,{resizeWidth:h,resizeHeight:d,resizeQuality:"low"});w.transferFromImageBitmap(p),a.close();const y=await l.convertToBlob(g),v=y.type,b=await y.arrayBuffer(),m=n(b);if(p.close(),!r.has(t)&&await u===m)return r.set(t,m),i.postMessage({id:t});if(r.get(t)===m)return i.postMessage({id:t});i.postMessage({id:t,type:v,base64:m,width:o,height:f}),r.set(t,m)}};`;
function t$2() {
  const t2 = new Blob([r$2]);
  return URL.createObjectURL(t2);
}
__name(t$2, "t$2");
class CanvasManager {
  static {
    __name(this, "CanvasManager");
  }
  reset() {
    this.pendingCanvasMutations.clear();
    this.restoreHandlers.forEach((handler5) => {
      try {
        handler5();
      } catch (e2) {
      }
    });
    this.restoreHandlers = [];
    this.windowsSet = /* @__PURE__ */ new WeakSet();
    this.windows = [];
    this.shadowDoms = /* @__PURE__ */ new Set();
    _optionalChain([this, "access", (_2) => _2.worker, "optionalAccess", (_2) => _2.terminate, "call", (_3) => _3()]);
    this.worker = null;
    this.snapshotInProgressMap = /* @__PURE__ */ new Map();
  }
  freeze() {
    this.frozen = true;
  }
  unfreeze() {
    this.frozen = false;
  }
  lock() {
    this.locked = true;
  }
  unlock() {
    this.locked = false;
  }
  constructor(options2) {
    this.pendingCanvasMutations = /* @__PURE__ */ new Map();
    this.rafStamps = { latestId: 0, invokeId: null };
    this.shadowDoms = /* @__PURE__ */ new Set();
    this.windowsSet = /* @__PURE__ */ new WeakSet();
    this.windows = [];
    this.restoreHandlers = [];
    this.frozen = false;
    this.locked = false;
    this.snapshotInProgressMap = /* @__PURE__ */ new Map();
    this.worker = null;
    this.processMutation = (target, mutation) => {
      const newFrame = this.rafStamps.invokeId && this.rafStamps.latestId !== this.rafStamps.invokeId;
      if (newFrame || !this.rafStamps.invokeId)
        this.rafStamps.invokeId = this.rafStamps.latestId;
      if (!this.pendingCanvasMutations.has(target)) {
        this.pendingCanvasMutations.set(target, []);
      }
      this.pendingCanvasMutations.get(target).push(mutation);
    };
    const { sampling = "all", win, blockClass, blockSelector, unblockSelector, maxCanvasSize, recordCanvas, dataURLOptions, errorHandler: errorHandler2 } = options2;
    this.mutationCb = options2.mutationCb;
    this.mirror = options2.mirror;
    this.options = options2;
    if (errorHandler2) {
      registerErrorHandler(errorHandler2);
    }
    if (recordCanvas && typeof sampling === "number" || options2.enableManualSnapshot) {
      this.worker = this.initFPSWorker();
    }
    this.addWindow(win);
    if (options2.enableManualSnapshot) {
      return;
    }
    callbackWrapper(() => {
      if (recordCanvas && sampling === "all") {
        this.startRAFTimestamping();
        this.startPendingCanvasMutationFlusher();
      }
      if (recordCanvas && typeof sampling === "number") {
        this.initCanvasFPSObserver(sampling, blockClass, blockSelector, unblockSelector, maxCanvasSize, {
          dataURLOptions
        });
      }
    })();
  }
  addWindow(win) {
    const { sampling = "all", blockClass, blockSelector, unblockSelector, recordCanvas, enableManualSnapshot } = this.options;
    if (this.windowsSet.has(win))
      return;
    if (enableManualSnapshot) {
      this.windowsSet.add(win);
      this.windows.push(new WeakRef(win));
      return;
    }
    callbackWrapper(() => {
      if (recordCanvas && sampling === "all") {
        this.initCanvasMutationObserver(win, blockClass, blockSelector, unblockSelector);
      }
      if (recordCanvas && typeof sampling === "number") {
        const canvasContextReset = initCanvasContextObserver(win, blockClass, blockSelector, unblockSelector, true);
        this.restoreHandlers.push(() => {
          canvasContextReset();
        });
      }
    })();
    this.windowsSet.add(win);
    this.windows.push(new WeakRef(win));
  }
  addShadowRoot(shadowRoot) {
    this.shadowDoms.add(new WeakRef(shadowRoot));
  }
  resetShadowRoots() {
    this.shadowDoms = /* @__PURE__ */ new Set();
  }
  initFPSWorker() {
    const worker = new Worker(t$2());
    worker.onmessage = (e2) => {
      const data = e2.data;
      const { id: id2 } = data;
      this.snapshotInProgressMap.set(id2, false);
      if (!("base64" in data))
        return;
      const { base64: base642, type, width: width2, height } = data;
      this.mutationCb({
        id: id2,
        type: CanvasContext["2D"],
        commands: [
          {
            property: "clearRect",
            args: [0, 0, width2, height]
          },
          {
            property: "drawImage",
            args: [
              {
                rr_type: "ImageBitmap",
                args: [
                  {
                    rr_type: "Blob",
                    data: [{ rr_type: "ArrayBuffer", base64: base642 }],
                    type
                  }
                ]
              },
              0,
              0,
              width2,
              height
            ]
          }
        ]
      });
    };
    return worker;
  }
  initCanvasFPSObserver(fps, blockClass, blockSelector, unblockSelector, maxCanvasSize, options2) {
    const rafId = this.takeSnapshot(false, fps, blockClass, blockSelector, unblockSelector, maxCanvasSize, options2.dataURLOptions);
    this.restoreHandlers.push(() => {
      cancelAnimationFrame(rafId);
    });
  }
  initCanvasMutationObserver(win, blockClass, blockSelector, unblockSelector) {
    const canvasContextReset = initCanvasContextObserver(win, blockClass, blockSelector, unblockSelector, false);
    const canvas2DReset = initCanvas2DMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector, unblockSelector);
    const canvasWebGL1and2Reset = initCanvasWebGLMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector, unblockSelector, this.mirror);
    this.restoreHandlers.push(() => {
      canvasContextReset();
      canvas2DReset();
      canvasWebGL1and2Reset();
    });
  }
  snapshot(canvasElement) {
    const { options: options2 } = this;
    const rafId = this.takeSnapshot(true, options2.sampling === "all" ? 2 : options2.sampling || 2, options2.blockClass, options2.blockSelector, options2.unblockSelector, options2.maxCanvasSize, options2.dataURLOptions, canvasElement);
    this.restoreHandlers.push(() => {
      cancelAnimationFrame(rafId);
    });
  }
  takeSnapshot(isManualSnapshot, fps, blockClass, blockSelector, unblockSelector, maxCanvasSize, dataURLOptions, canvasElement) {
    const timeBetweenSnapshots = 1e3 / fps;
    let lastSnapshotTime = 0;
    let rafId;
    const getCanvas = /* @__PURE__ */ __name((canvasElement2) => {
      if (canvasElement2) {
        return [canvasElement2];
      }
      const matchedCanvas = [];
      const searchCanvas = /* @__PURE__ */ __name((root2) => {
        root2.querySelectorAll("canvas").forEach((canvas2) => {
          if (!isBlocked(canvas2, blockClass, blockSelector, unblockSelector)) {
            matchedCanvas.push(canvas2);
          }
        });
      }, "searchCanvas");
      for (const item of this.windows) {
        const window2 = item.deref();
        if (window2) {
          searchCanvas(window2.document);
        }
      }
      for (const item of this.shadowDoms) {
        const shadowRoot = item.deref();
        if (shadowRoot) {
          searchCanvas(shadowRoot);
        }
      }
      return matchedCanvas;
    }, "getCanvas");
    const takeCanvasSnapshots = /* @__PURE__ */ __name((timestamp2) => {
      if (!this.windows.length) {
        return;
      }
      if (lastSnapshotTime && timestamp2 - lastSnapshotTime < timeBetweenSnapshots) {
        rafId = onRequestAnimationFrame(takeCanvasSnapshots);
        return;
      }
      lastSnapshotTime = timestamp2;
      getCanvas(canvasElement).forEach((canvas2) => {
        if (!this.mirror.hasNode(canvas2)) {
          return;
        }
        const id2 = this.mirror.getId(canvas2);
        if (this.snapshotInProgressMap.get(id2))
          return;
        if (!canvas2.width || !canvas2.height)
          return;
        this.snapshotInProgressMap.set(id2, true);
        if (!isManualSnapshot && ["webgl", "webgl2"].includes(canvas2.__context)) {
          const context = canvas2.getContext(canvas2.__context);
          if (_optionalChain([context, "optionalAccess", (_4) => _4.getContextAttributes, "call", (_5) => _5(), "optionalAccess", (_6) => _6.preserveDrawingBuffer]) === false) {
            context.clear(context.COLOR_BUFFER_BIT);
          }
        }
        createImageBitmap(canvas2).then((bitmap) => {
          _optionalChain([this, "access", (_7) => _7.worker, "optionalAccess", (_8) => _8.postMessage, "call", (_9) => _9({
            id: id2,
            bitmap,
            width: canvas2.width,
            height: canvas2.height,
            dataURLOptions,
            maxCanvasSize
          }, [bitmap])]);
        }).catch((error2) => {
          callbackWrapper(() => {
            throw error2;
          })();
        });
      });
      if (!isManualSnapshot) {
        rafId = onRequestAnimationFrame(takeCanvasSnapshots);
      }
    }, "takeCanvasSnapshots");
    rafId = onRequestAnimationFrame(takeCanvasSnapshots);
    return rafId;
  }
  startPendingCanvasMutationFlusher() {
    onRequestAnimationFrame(() => this.flushPendingCanvasMutations());
  }
  startRAFTimestamping() {
    const setLatestRAFTimestamp = /* @__PURE__ */ __name((timestamp2) => {
      this.rafStamps.latestId = timestamp2;
      onRequestAnimationFrame(setLatestRAFTimestamp);
    }, "setLatestRAFTimestamp");
    onRequestAnimationFrame(setLatestRAFTimestamp);
  }
  flushPendingCanvasMutations() {
    this.pendingCanvasMutations.forEach((values, canvas2) => {
      const id2 = this.mirror.getId(canvas2);
      this.flushPendingCanvasMutationFor(canvas2, id2);
    });
    onRequestAnimationFrame(() => this.flushPendingCanvasMutations());
  }
  flushPendingCanvasMutationFor(canvas2, id2) {
    if (this.frozen || this.locked) {
      return;
    }
    const valuesWithType = this.pendingCanvasMutations.get(canvas2);
    if (!valuesWithType || id2 === -1)
      return;
    const values = valuesWithType.map((value) => {
      const { type: type2, ...rest } = value;
      return rest;
    });
    const { type } = valuesWithType[0];
    this.mutationCb({ id: id2, type, commands: values });
    this.pendingCanvasMutations.delete(canvas2);
  }
}
const CANVAS_QUALITY = {
  low: {
    sampling: {
      canvas: 1
    },
    dataURLOptions: {
      type: "image/webp",
      quality: 0.25
    }
  },
  medium: {
    sampling: {
      canvas: 2
    },
    dataURLOptions: {
      type: "image/webp",
      quality: 0.4
    }
  },
  high: {
    sampling: {
      canvas: 4
    },
    dataURLOptions: {
      type: "image/webp",
      quality: 0.5
    }
  }
};
const INTEGRATION_NAME$3 = "ReplayCanvas";
const DEFAULT_MAX_CANVAS_SIZE = 1280;
const _replayCanvasIntegration = /* @__PURE__ */ __name((options2 = {}) => {
  const [maxCanvasWidth, maxCanvasHeight] = options2.maxCanvasSize || [];
  const _canvasOptions = {
    quality: options2.quality || "medium",
    enableManualSnapshot: options2.enableManualSnapshot,
    maxCanvasSize: [
      maxCanvasWidth ? Math.min(maxCanvasWidth, DEFAULT_MAX_CANVAS_SIZE) : DEFAULT_MAX_CANVAS_SIZE,
      maxCanvasHeight ? Math.min(maxCanvasHeight, DEFAULT_MAX_CANVAS_SIZE) : DEFAULT_MAX_CANVAS_SIZE
    ]
  };
  let canvasManagerResolve;
  const _canvasManager = new Promise((resolve2) => canvasManagerResolve = resolve2);
  return {
    name: INTEGRATION_NAME$3,
    getOptions() {
      const { quality, enableManualSnapshot, maxCanvasSize } = _canvasOptions;
      return {
        enableManualSnapshot,
        recordCanvas: true,
        getCanvasManager: /* @__PURE__ */ __name((getCanvasManagerOptions) => {
          const manager2 = new CanvasManager({
            ...getCanvasManagerOptions,
            enableManualSnapshot,
            maxCanvasSize,
            errorHandler: /* @__PURE__ */ __name((err) => {
              try {
                if (typeof err === "object") {
                  err.__rrweb__ = true;
                }
              } catch (error2) {
              }
            }, "errorHandler")
          });
          canvasManagerResolve(manager2);
          return manager2;
        }, "getCanvasManager"),
        ...CANVAS_QUALITY[quality || "medium"] || CANVAS_QUALITY.medium
      };
    },
    async snapshot(canvasElement) {
      const canvasManager = await _canvasManager;
      canvasManager.snapshot(canvasElement);
    }
  };
}, "_replayCanvasIntegration");
const replayCanvasIntegration = defineIntegration(
  _replayCanvasIntegration
);
const WINDOW = GLOBAL_OBJ;
const DOCUMENT = WINDOW.document;
const NAVIGATOR = WINDOW.navigator;
const TRIGGER_LABEL = "Report a Bug";
const CANCEL_BUTTON_LABEL = "Cancel";
const SUBMIT_BUTTON_LABEL = "Send Bug Report";
const CONFIRM_BUTTON_LABEL = "Confirm";
const FORM_TITLE = "Report a Bug";
const EMAIL_PLACEHOLDER = "your.email@example.org";
const EMAIL_LABEL = "Email";
const MESSAGE_PLACEHOLDER = "What's the bug? What did you expect?";
const MESSAGE_LABEL = "Description";
const NAME_PLACEHOLDER = "Your Name";
const NAME_LABEL = "Name";
const SUCCESS_MESSAGE_TEXT = "Thank you for your report!";
const IS_REQUIRED_LABEL = "(required)";
const ADD_SCREENSHOT_LABEL = "Add a screenshot";
const REMOVE_SCREENSHOT_LABEL = "Remove screenshot";
const FEEDBACK_WIDGET_SOURCE = "widget";
const FEEDBACK_API_SOURCE = "api";
const SUCCESS_MESSAGE_TIMEOUT = 5e3;
const sendFeedback = /* @__PURE__ */ __name((params, hint = { includeReplay: true }) => {
  if (!params.message) {
    throw new Error("Unable to submit feedback with empty message");
  }
  const client = getClient();
  if (!client) {
    throw new Error("No client setup, cannot send feedback.");
  }
  if (params.tags && Object.keys(params.tags).length) {
    getCurrentScope().setTags(params.tags);
  }
  const eventId = captureFeedback(
    {
      source: FEEDBACK_API_SOURCE,
      url: getLocationHref(),
      ...params
    },
    hint
  );
  return new Promise((resolve2, reject) => {
    const timeout = setTimeout(() => reject("Unable to determine if Feedback was correctly sent."), 5e3);
    const cleanup = client.on("afterSendEvent", (event, response) => {
      if (event.event_id !== eventId) {
        return;
      }
      clearTimeout(timeout);
      cleanup();
      if (response && typeof response.statusCode === "number" && response.statusCode >= 200 && response.statusCode < 300) {
        return resolve2(eventId);
      }
      if (response && typeof response.statusCode === "number" && response.statusCode === 0) {
        return reject(
          "Unable to send Feedback. This is because of network issues, or because you are using an ad-blocker."
        );
      }
      if (response && typeof response.statusCode === "number" && response.statusCode === 403) {
        return reject(
          "Unable to send Feedback. This could be because this domain is not in your list of allowed domains."
        );
      }
      return reject(
        "Unable to send Feedback. This could be because of network issues, or because you are using an ad-blocker"
      );
    });
  });
}, "sendFeedback");
const DEBUG_BUILD$1 = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__;
function isScreenshotSupported() {
  if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(NAVIGATOR.userAgent)) {
    return false;
  }
  if (/Macintosh/i.test(NAVIGATOR.userAgent) && NAVIGATOR.maxTouchPoints && NAVIGATOR.maxTouchPoints > 1) {
    return false;
  }
  if (!isSecureContext) {
    return false;
  }
  return true;
}
__name(isScreenshotSupported, "isScreenshotSupported");
function mergeOptions$1(defaultOptions2, optionOverrides) {
  return {
    ...defaultOptions2,
    ...optionOverrides,
    tags: {
      ...defaultOptions2.tags,
      ...optionOverrides.tags
    },
    onFormOpen: /* @__PURE__ */ __name(() => {
      optionOverrides.onFormOpen && optionOverrides.onFormOpen();
      defaultOptions2.onFormOpen && defaultOptions2.onFormOpen();
    }, "onFormOpen"),
    onFormClose: /* @__PURE__ */ __name(() => {
      optionOverrides.onFormClose && optionOverrides.onFormClose();
      defaultOptions2.onFormClose && defaultOptions2.onFormClose();
    }, "onFormClose"),
    onSubmitSuccess: /* @__PURE__ */ __name((data) => {
      optionOverrides.onSubmitSuccess && optionOverrides.onSubmitSuccess(data);
      defaultOptions2.onSubmitSuccess && defaultOptions2.onSubmitSuccess(data);
    }, "onSubmitSuccess"),
    onSubmitError: /* @__PURE__ */ __name((error2) => {
      optionOverrides.onSubmitError && optionOverrides.onSubmitError(error2);
      defaultOptions2.onSubmitError && defaultOptions2.onSubmitError(error2);
    }, "onSubmitError"),
    onFormSubmitted: /* @__PURE__ */ __name(() => {
      optionOverrides.onFormSubmitted && optionOverrides.onFormSubmitted();
      defaultOptions2.onFormSubmitted && defaultOptions2.onFormSubmitted();
    }, "onFormSubmitted"),
    themeDark: {
      ...defaultOptions2.themeDark,
      ...optionOverrides.themeDark
    },
    themeLight: {
      ...defaultOptions2.themeLight,
      ...optionOverrides.themeLight
    }
  };
}
__name(mergeOptions$1, "mergeOptions$1");
function createActorStyles(styleNonce) {
  const style2 = DOCUMENT.createElement("style");
  style2.textContent = `
.widget__actor {
  position: fixed;
  z-index: var(--z-index);
  margin: var(--page-margin);
  inset: var(--actor-inset);

  display: flex;
  align-items: center;
  gap: 8px;
  padding: 16px;

  font-family: inherit;
  font-size: var(--font-size);
  font-weight: 600;
  line-height: 1.14em;
  text-decoration: none;

  background: var(--actor-background, var(--background));
  border-radius: var(--actor-border-radius, 1.7em/50%);
  border: var(--actor-border, var(--border));
  box-shadow: var(--actor-box-shadow, var(--box-shadow));
  color: var(--actor-color, var(--foreground));
  fill: var(--actor-color, var(--foreground));
  cursor: pointer;
  opacity: 1;
  transition: transform 0.2s ease-in-out;
  transform: translate(0, 0) scale(1);
}
.widget__actor[aria-hidden="true"] {
  opacity: 0;
  pointer-events: none;
  visibility: hidden;
  transform: translate(0, 16px) scale(0.98);
}

.widget__actor:hover {
  background: var(--actor-hover-background, var(--background));
  filter: var(--interactive-filter);
}

.widget__actor svg {
  width: 1.14em;
  height: 1.14em;
}

@media (max-width: 600px) {
  .widget__actor span {
    display: none;
  }
}
`;
  if (styleNonce) {
    style2.setAttribute("nonce", styleNonce);
  }
  return style2;
}
__name(createActorStyles, "createActorStyles");
function setAttributesNS(el, attributes) {
  Object.entries(attributes).forEach(([key, val]) => {
    el.setAttributeNS(null, key, val);
  });
  return el;
}
__name(setAttributesNS, "setAttributesNS");
const SIZE = 20;
const XMLNS$2 = "http://www.w3.org/2000/svg";
function FeedbackIcon() {
  const createElementNS = /* @__PURE__ */ __name((tagName) => WINDOW.document.createElementNS(XMLNS$2, tagName), "createElementNS");
  const svg = setAttributesNS(createElementNS("svg"), {
    width: `${SIZE}`,
    height: `${SIZE}`,
    viewBox: `0 0 ${SIZE} ${SIZE}`,
    fill: "var(--actor-color, var(--foreground))"
  });
  const g2 = setAttributesNS(createElementNS("g"), {
    clipPath: "url(#clip0_57_80)"
  });
  const path = setAttributesNS(createElementNS("path"), {
    ["fill-rule"]: "evenodd",
    ["clip-rule"]: "evenodd",
    d: "M15.6622 15H12.3997C12.2129 14.9959 12.031 14.9396 11.8747 14.8375L8.04965 12.2H7.49956V19.1C7.4875 19.3348 7.3888 19.5568 7.22256 19.723C7.05632 19.8892 6.83435 19.9879 6.59956 20H2.04956C1.80193 19.9968 1.56535 19.8969 1.39023 19.7218C1.21511 19.5467 1.1153 19.3101 1.11206 19.0625V12.2H0.949652C0.824431 12.2017 0.700142 12.1783 0.584123 12.1311C0.468104 12.084 0.362708 12.014 0.274155 11.9255C0.185602 11.8369 0.115689 11.7315 0.0685419 11.6155C0.0213952 11.4995 -0.00202913 11.3752 -0.00034808 11.25V3.75C-0.00900498 3.62067 0.0092504 3.49095 0.0532651 3.36904C0.0972798 3.24712 0.166097 3.13566 0.255372 3.04168C0.344646 2.94771 0.452437 2.87327 0.571937 2.82307C0.691437 2.77286 0.82005 2.74798 0.949652 2.75H8.04965L11.8747 0.1625C12.031 0.0603649 12.2129 0.00407221 12.3997 0H15.6622C15.9098 0.00323746 16.1464 0.103049 16.3215 0.278167C16.4966 0.453286 16.5964 0.689866 16.5997 0.9375V3.25269C17.3969 3.42959 18.1345 3.83026 18.7211 4.41679C19.5322 5.22788 19.9878 6.32796 19.9878 7.47502C19.9878 8.62209 19.5322 9.72217 18.7211 10.5333C18.1345 11.1198 17.3969 11.5205 16.5997 11.6974V14.0125C16.6047 14.1393 16.5842 14.2659 16.5395 14.3847C16.4948 14.5035 16.4268 14.6121 16.3394 14.7042C16.252 14.7962 16.147 14.8698 16.0307 14.9206C15.9144 14.9714 15.7891 14.9984 15.6622 15ZM1.89695 10.325H1.88715V4.625H8.33715C8.52423 4.62301 8.70666 4.56654 8.86215 4.4625L12.6872 1.875H14.7247V13.125H12.6872L8.86215 10.4875C8.70666 10.3835 8.52423 10.327 8.33715 10.325H2.20217C2.15205 10.3167 2.10102 10.3125 2.04956 10.3125C1.9981 10.3125 1.94708 10.3167 1.89695 10.325ZM2.98706 12.2V18.1625H5.66206V12.2H2.98706ZM16.5997 9.93612V5.01393C16.6536 5.02355 16.7072 5.03495 16.7605 5.04814C17.1202 5.13709 17.4556 5.30487 17.7425 5.53934C18.0293 5.77381 18.2605 6.06912 18.4192 6.40389C18.578 6.73866 18.6603 7.10452 18.6603 7.47502C18.6603 7.84552 18.578 8.21139 18.4192 8.54616C18.2605 8.88093 18.0293 9.17624 17.7425 9.41071C17.4556 9.64518 17.1202 9.81296 16.7605 9.90191C16.7072 9.91509 16.6536 9.9265 16.5997 9.93612Z"
  });
  svg.appendChild(g2).appendChild(path);
  const speakerDefs = createElementNS("defs");
  const speakerClipPathDef = setAttributesNS(createElementNS("clipPath"), {
    id: "clip0_57_80"
  });
  const speakerRect = setAttributesNS(createElementNS("rect"), {
    width: `${SIZE}`,
    height: `${SIZE}`,
    fill: "white"
  });
  speakerClipPathDef.appendChild(speakerRect);
  speakerDefs.appendChild(speakerClipPathDef);
  svg.appendChild(speakerDefs).appendChild(speakerClipPathDef).appendChild(speakerRect);
  return svg;
}
__name(FeedbackIcon, "FeedbackIcon");
function Actor({ triggerLabel, triggerAriaLabel, shadow, styleNonce }) {
  const el = DOCUMENT.createElement("button");
  el.type = "button";
  el.className = "widget__actor";
  el.ariaHidden = "false";
  el.ariaLabel = triggerAriaLabel || triggerLabel || TRIGGER_LABEL;
  el.appendChild(FeedbackIcon());
  if (triggerLabel) {
    const label = DOCUMENT.createElement("span");
    label.appendChild(DOCUMENT.createTextNode(triggerLabel));
    el.appendChild(label);
  }
  const style2 = createActorStyles(styleNonce);
  return {
    el,
    appendToDom() {
      shadow.appendChild(style2);
      shadow.appendChild(el);
    },
    removeFromDom() {
      shadow.removeChild(el);
      shadow.removeChild(style2);
    },
    show() {
      el.ariaHidden = "false";
    },
    hide() {
      el.ariaHidden = "true";
    }
  };
}
__name(Actor, "Actor");
const PURPLE = "rgba(88, 74, 192, 1)";
const DEFAULT_LIGHT = {
  foreground: "#2b2233",
  background: "#ffffff",
  accentForeground: "white",
  accentBackground: PURPLE,
  successColor: "#268d75",
  errorColor: "#df3338",
  border: "1.5px solid rgba(41, 35, 47, 0.13)",
  boxShadow: "0px 4px 24px 0px rgba(43, 34, 51, 0.12)",
  outline: "1px auto var(--accent-background)",
  interactiveFilter: "brightness(95%)"
};
const DEFAULT_DARK = {
  foreground: "#ebe6ef",
  background: "#29232f",
  accentForeground: "white",
  accentBackground: PURPLE,
  successColor: "#2da98c",
  errorColor: "#f55459",
  border: "1.5px solid rgba(235, 230, 239, 0.15)",
  boxShadow: "0px 4px 24px 0px rgba(43, 34, 51, 0.12)",
  outline: "1px auto var(--accent-background)",
  interactiveFilter: "brightness(150%)"
};
function getThemedCssVariables(theme3) {
  return `
  --foreground: ${theme3.foreground};
  --background: ${theme3.background};
  --accent-foreground: ${theme3.accentForeground};
  --accent-background: ${theme3.accentBackground};
  --success-color: ${theme3.successColor};
  --error-color: ${theme3.errorColor};
  --border: ${theme3.border};
  --box-shadow: ${theme3.boxShadow};
  --outline: ${theme3.outline};
  --interactive-filter: ${theme3.interactiveFilter};
  `;
}
__name(getThemedCssVariables, "getThemedCssVariables");
function createMainStyles({
  colorScheme,
  themeDark,
  themeLight,
  styleNonce
}) {
  const style2 = DOCUMENT.createElement("style");
  style2.textContent = `
:host {
  --font-family: system-ui, 'Helvetica Neue', Arial, sans-serif;
  --font-size: 14px;
  --z-index: 100000;

  --page-margin: 16px;
  --inset: auto 0 0 auto;
  --actor-inset: var(--inset);

  font-family: var(--font-family);
  font-size: var(--font-size);

  ${colorScheme !== "system" ? "color-scheme: only light;" : ""}

  ${getThemedCssVariables(
    colorScheme === "dark" ? { ...DEFAULT_DARK, ...themeDark } : { ...DEFAULT_LIGHT, ...themeLight }
  )}
}

${colorScheme === "system" ? `
@media (prefers-color-scheme: dark) {
  :host {
    ${getThemedCssVariables({ ...DEFAULT_DARK, ...themeDark })}
  }
}` : ""}
}
`;
  if (styleNonce) {
    style2.setAttribute("nonce", styleNonce);
  }
  return style2;
}
__name(createMainStyles, "createMainStyles");
const buildFeedbackIntegration = /* @__PURE__ */ __name(({
  lazyLoadIntegration: lazyLoadIntegration2,
  getModalIntegration,
  getScreenshotIntegration
}) => {
  const feedbackIntegration = /* @__PURE__ */ __name(({
    // FeedbackGeneralConfiguration
    id: id2 = "sentry-feedback",
    autoInject = true,
    showBranding = true,
    isEmailRequired = false,
    isNameRequired = false,
    showEmail = true,
    showName = true,
    enableScreenshot = true,
    useSentryUser = {
      email: "email",
      name: "username"
    },
    tags,
    styleNonce,
    scriptNonce,
    // FeedbackThemeConfiguration
    colorScheme = "system",
    themeLight = {},
    themeDark = {},
    // FeedbackTextConfiguration
    addScreenshotButtonLabel = ADD_SCREENSHOT_LABEL,
    cancelButtonLabel = CANCEL_BUTTON_LABEL,
    confirmButtonLabel = CONFIRM_BUTTON_LABEL,
    emailLabel = EMAIL_LABEL,
    emailPlaceholder = EMAIL_PLACEHOLDER,
    formTitle = FORM_TITLE,
    isRequiredLabel = IS_REQUIRED_LABEL,
    messageLabel = MESSAGE_LABEL,
    messagePlaceholder = MESSAGE_PLACEHOLDER,
    nameLabel = NAME_LABEL,
    namePlaceholder = NAME_PLACEHOLDER,
    removeScreenshotButtonLabel = REMOVE_SCREENSHOT_LABEL,
    submitButtonLabel = SUBMIT_BUTTON_LABEL,
    successMessageText = SUCCESS_MESSAGE_TEXT,
    triggerLabel = TRIGGER_LABEL,
    triggerAriaLabel = "",
    // FeedbackCallbacks
    onFormOpen,
    onFormClose,
    onSubmitSuccess,
    onSubmitError,
    onFormSubmitted
  } = {}) => {
    const _options = {
      id: id2,
      autoInject,
      showBranding,
      isEmailRequired,
      isNameRequired,
      showEmail,
      showName,
      enableScreenshot,
      useSentryUser,
      tags,
      styleNonce,
      scriptNonce,
      colorScheme,
      themeDark,
      themeLight,
      triggerLabel,
      triggerAriaLabel,
      cancelButtonLabel,
      submitButtonLabel,
      confirmButtonLabel,
      formTitle,
      emailLabel,
      emailPlaceholder,
      messageLabel,
      messagePlaceholder,
      nameLabel,
      namePlaceholder,
      successMessageText,
      isRequiredLabel,
      addScreenshotButtonLabel,
      removeScreenshotButtonLabel,
      onFormClose,
      onFormOpen,
      onSubmitError,
      onSubmitSuccess,
      onFormSubmitted
    };
    let _shadow = null;
    let _subscriptions = [];
    const _createShadow = /* @__PURE__ */ __name((options2) => {
      if (!_shadow) {
        const host = DOCUMENT.createElement("div");
        host.id = String(options2.id);
        DOCUMENT.body.appendChild(host);
        _shadow = host.attachShadow({ mode: "open" });
        _shadow.appendChild(createMainStyles(options2));
      }
      return _shadow;
    }, "_createShadow");
    const _loadAndRenderDialog = /* @__PURE__ */ __name(async (options2) => {
      const screenshotRequired = options2.enableScreenshot && isScreenshotSupported();
      let modalIntegration;
      let screenshotIntegration;
      try {
        const modalIntegrationFn = getModalIntegration ? getModalIntegration() : await lazyLoadIntegration2("feedbackModalIntegration", scriptNonce);
        modalIntegration = modalIntegrationFn();
        addIntegration(modalIntegration);
      } catch (e2) {
        DEBUG_BUILD$1 && logger$5.error(
          "[Feedback] Error when trying to load feedback integrations. Try using `feedbackSyncIntegration` in your `Sentry.init`."
        );
        throw new Error("[Feedback] Missing feedback modal integration!");
      }
      try {
        const screenshotIntegrationFn = screenshotRequired ? getScreenshotIntegration ? getScreenshotIntegration() : await lazyLoadIntegration2("feedbackScreenshotIntegration", scriptNonce) : void 0;
        if (screenshotIntegrationFn) {
          screenshotIntegration = screenshotIntegrationFn();
          addIntegration(screenshotIntegration);
        }
      } catch (e2) {
        DEBUG_BUILD$1 && logger$5.error("[Feedback] Missing feedback screenshot integration. Proceeding without screenshots.");
      }
      const dialog = modalIntegration.createDialog({
        options: {
          ...options2,
          onFormClose: /* @__PURE__ */ __name(() => {
            dialog && dialog.close();
            options2.onFormClose && options2.onFormClose();
          }, "onFormClose"),
          onFormSubmitted: /* @__PURE__ */ __name(() => {
            dialog && dialog.close();
            options2.onFormSubmitted && options2.onFormSubmitted();
          }, "onFormSubmitted")
        },
        screenshotIntegration,
        sendFeedback,
        shadow: _createShadow(options2)
      });
      return dialog;
    }, "_loadAndRenderDialog");
    const _attachTo = /* @__PURE__ */ __name((el, optionOverrides = {}) => {
      const mergedOptions = mergeOptions$1(_options, optionOverrides);
      const targetEl = typeof el === "string" ? DOCUMENT.querySelector(el) : typeof el.addEventListener === "function" ? el : null;
      if (!targetEl) {
        DEBUG_BUILD$1 && logger$5.error("[Feedback] Unable to attach to target element");
        throw new Error("Unable to attach to target element");
      }
      let dialog = null;
      const handleClick2 = /* @__PURE__ */ __name(async () => {
        if (!dialog) {
          dialog = await _loadAndRenderDialog({
            ...mergedOptions,
            onFormSubmitted: /* @__PURE__ */ __name(() => {
              dialog && dialog.removeFromDom();
              mergedOptions.onFormSubmitted && mergedOptions.onFormSubmitted();
            }, "onFormSubmitted")
          });
        }
        dialog.appendToDom();
        dialog.open();
      }, "handleClick");
      targetEl.addEventListener("click", handleClick2);
      const unsubscribe = /* @__PURE__ */ __name(() => {
        _subscriptions = _subscriptions.filter((sub) => sub !== unsubscribe);
        dialog && dialog.removeFromDom();
        dialog = null;
        targetEl.removeEventListener("click", handleClick2);
      }, "unsubscribe");
      _subscriptions.push(unsubscribe);
      return unsubscribe;
    }, "_attachTo");
    const _createActor = /* @__PURE__ */ __name((optionOverrides = {}) => {
      const mergedOptions = mergeOptions$1(_options, optionOverrides);
      const shadow = _createShadow(mergedOptions);
      const actor = Actor({
        triggerLabel: mergedOptions.triggerLabel,
        triggerAriaLabel: mergedOptions.triggerAriaLabel,
        shadow,
        styleNonce
      });
      _attachTo(actor.el, {
        ...mergedOptions,
        onFormOpen() {
          actor.hide();
        },
        onFormClose() {
          actor.show();
        },
        onFormSubmitted() {
          actor.show();
        }
      });
      return actor;
    }, "_createActor");
    return {
      name: "Feedback",
      setupOnce() {
        if (!isBrowser$2() || !_options.autoInject) {
          return;
        }
        if (DOCUMENT.readyState === "loading") {
          DOCUMENT.addEventListener("DOMContentLoaded", () => _createActor().appendToDom());
        } else {
          _createActor().appendToDom();
        }
      },
      /**
       * Adds click listener to the element to open a feedback dialog
       *
       * The returned function can be used to remove the click listener
       */
      attachTo: _attachTo,
      /**
       * Creates a new widget which is composed of a Button which triggers a Dialog.
       * Accepts partial options to override any options passed to constructor.
       */
      createWidget(optionOverrides = {}) {
        const actor = _createActor(mergeOptions$1(_options, optionOverrides));
        actor.appendToDom();
        return actor;
      },
      /**
       * Creates a new Form which you can
       * Accepts partial options to override any options passed to constructor.
       */
      async createForm(optionOverrides = {}) {
        return _loadAndRenderDialog(mergeOptions$1(_options, optionOverrides));
      },
      /**
       * Removes the Feedback integration (including host, shadow DOM, and all widgets)
       */
      remove() {
        if (_shadow) {
          _shadow.parentElement && _shadow.parentElement.remove();
          _shadow = null;
        }
        _subscriptions.forEach((sub) => sub());
        _subscriptions = [];
      }
    };
  }, "feedbackIntegration");
  return feedbackIntegration;
}, "buildFeedbackIntegration");
function getFeedback() {
  const client = getClient();
  return client && client.getIntegrationByName("Feedback");
}
__name(getFeedback, "getFeedback");
var n, l$1, u$1, i$1, o$1, r$1, f$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;
}
__name(v$1, "v$1");
function p$1(n2) {
  var l2 = n2.parentNode;
  l2 && l2.removeChild(n2);
}
__name(p$1, "p$1");
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);
}
__name(y$1, "y$1");
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, constructor: void 0, __v: null == r2 ? ++u$1 : r2, __i: -1, __u: 0 };
  return null == r2 && null != l$1.vnode && l$1.vnode(f2), f2;
}
__name(d$1, "d$1");
function g$1$1(n2) {
  return n2.children;
}
__name(g$1$1, "g$1$1");
function b$1(n2, l2) {
  this.props = n2, this.context = l2;
}
__name(b$1, "b$1");
function m$1(n2, l2) {
  if (null == l2) return n2.__ ? m$1(n2.__, n2.__i + 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 ? m$1(n2) : null;
}
__name(m$1, "m$1");
function w$1(n2, u2, t2) {
  var i2, o2 = n2.__v, r2 = o2.__e, f2 = n2.__P;
  if (f2) return (i2 = v$1({}, o2)).__v = o2.__v + 1, l$1.vnode && l$1.vnode(i2), M$1(f2, i2, o2, n2.__n, void 0 !== f2.ownerSVGElement, 32 & o2.__u ? [r2] : null, u2, null == r2 ? m$1(o2) : r2, !!(32 & o2.__u), t2), i2.__.__k[i2.__i] = i2, i2.__d = void 0, i2.__e != r2 && k$1(i2), i2;
}
__name(w$1, "w$1");
function k$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 k$1(n2);
  }
}
__name(k$1, "k$1");
function x$1(n2) {
  (!n2.__d && (n2.__d = true) && i$1.push(n2) && !C$1.__r++ || o$1 !== l$1.debounceRendering) && ((o$1 = l$1.debounceRendering) || r$1)(C$1);
}
__name(x$1, "x$1");
function C$1() {
  var n2, u2, t2, o2 = [], r2 = [];
  for (i$1.sort(f$1); n2 = i$1.shift(); ) n2.__d && (t2 = i$1.length, u2 = w$1(n2, o2, r2) || u2, 0 === t2 || i$1.length > t2 ? (j$1(o2, u2, r2), r2.length = o2.length = 0, u2 = void 0, i$1.sort(f$1)) : u2 && l$1.__c && l$1.__c(u2, s$1));
  u2 && j$1(o2, u2, r2), C$1.__r = 0;
}
__name(C$1, "C$1");
function P$1(n2, l2, u2, t2, i2, o2, r2, f2, e2, a2, h2) {
  var v2, p2, y2, d2, _2, g2 = t2 && t2.__k || s$1, b2 = l2.length;
  for (u2.__d = e2, S$1(u2, l2, g2), e2 = u2.__d, v2 = 0; v2 < b2; v2++) null != (y2 = u2.__k[v2]) && "boolean" != typeof y2 && "function" != typeof y2 && (p2 = -1 === y2.__i ? c$1 : g2[y2.__i] || c$1, y2.__i = v2, M$1(n2, y2, p2, i2, o2, r2, f2, e2, a2, h2), d2 = y2.__e, y2.ref && p2.ref != y2.ref && (p2.ref && N$1(p2.ref, null, y2), h2.push(y2.ref, y2.__c || d2, y2)), null == _2 && null != d2 && (_2 = d2), 65536 & y2.__u || p2.__k === y2.__k ? e2 = $$1(y2, e2, n2) : "function" == typeof y2.type && void 0 !== y2.__d ? e2 = y2.__d : d2 && (e2 = d2.nextSibling), y2.__d = void 0, y2.__u &= -196609);
  u2.__d = e2, u2.__e = _2;
}
__name(P$1, "P$1");
function S$1(n2, l2, u2) {
  var t2, i2, o2, r2, f2, e2 = l2.length, c2 = u2.length, s2 = c2, a2 = 0;
  for (n2.__k = [], t2 = 0; t2 < e2; t2++) null != (i2 = n2.__k[t2] = null == (i2 = l2[t2]) || "boolean" == typeof i2 || "function" == typeof i2 ? null : "string" == typeof i2 || "number" == typeof i2 || "bigint" == typeof i2 || i2.constructor == String ? d$1(null, i2, null, null, i2) : h$1(i2) ? d$1(g$1$1, { children: i2 }, null, null, null) : void 0 === i2.constructor && i2.__b > 0 ? d$1(i2.type, i2.props, i2.key, i2.ref ? i2.ref : null, i2.__v) : i2) ? (i2.__ = n2, i2.__b = n2.__b + 1, f2 = I(i2, u2, r2 = t2 + a2, s2), i2.__i = f2, o2 = null, -1 !== f2 && (s2--, (o2 = u2[f2]) && (o2.__u |= 131072)), null == o2 || null === o2.__v ? (-1 == f2 && a2--, "function" != typeof i2.type && (i2.__u |= 65536)) : f2 !== r2 && (f2 === r2 + 1 ? a2++ : f2 > r2 ? s2 > e2 - r2 ? a2 += f2 - r2 : a2-- : a2 = f2 < r2 && f2 == r2 - 1 ? f2 - r2 : 0, f2 !== t2 + a2 && (i2.__u |= 65536))) : (o2 = u2[t2]) && null == o2.key && o2.__e && (o2.__e == n2.__d && (n2.__d = m$1(o2)), O$1(o2, o2, false), u2[t2] = null, s2--);
  if (s2) for (t2 = 0; t2 < c2; t2++) null != (o2 = u2[t2]) && 0 == (131072 & o2.__u) && (o2.__e == n2.__d && (n2.__d = m$1(o2)), O$1(o2, o2));
}
__name(S$1, "S$1");
function $$1(n2, l2, u2) {
  var t2, i2;
  if ("function" == typeof n2.type) {
    for (t2 = n2.__k, i2 = 0; t2 && i2 < t2.length; i2++) t2[i2] && (t2[i2].__ = n2, l2 = $$1(t2[i2], l2, u2));
    return l2;
  }
  n2.__e != l2 && (u2.insertBefore(n2.__e, l2 || null), l2 = n2.__e);
  do {
    l2 = l2 && l2.nextSibling;
  } while (null != l2 && 8 === l2.nodeType);
  return l2;
}
__name($$1, "$$1");
function I(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 && 0 == (131072 & e2.__u) ? 1 : 0)) for (; r2 >= 0 || f2 < l2.length; ) {
    if (r2 >= 0) {
      if ((e2 = l2[r2]) && 0 == (131072 & e2.__u) && i2 == e2.key && o2 === e2.type) return r2;
      r2--;
    }
    if (f2 < l2.length) {
      if ((e2 = l2[f2]) && 0 == (131072 & e2.__u) && i2 == e2.key && o2 === e2.type) return f2;
      f2++;
    }
  }
  return -1;
}
__name(I, "I");
function T$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";
}
__name(T$1, "T$1");
function A$1(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 || T$1(n2.style, l2, "");
    if (u2) for (l2 in u2) t2 && u2[l2] === t2[l2] || T$1(n2.style, l2, u2[l2]);
  }
  else if ("o" === l2[0] && "n" === l2[1]) o2 = l2 !== (l2 = l2.replace(/(PointerCapture)$|Capture$/i, "$1")), l2 = l2.toLowerCase() in n2 ? l2.toLowerCase().slice(2) : l2.slice(2), n2.l || (n2.l = {}), n2.l[l2 + o2] = u2, u2 ? t2 ? u2.u = t2.u : (u2.u = Date.now(), n2.addEventListener(l2, o2 ? L$1 : D$1, o2)) : n2.removeEventListener(l2, o2 ? L$1 : D$1, o2);
  else {
    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 && "role" !== 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));
  }
}
__name(A$1, "A$1");
function D$1(n2) {
  if (this.l) {
    var u2 = this.l[n2.type + false];
    if (n2.t) {
      if (n2.t <= u2.u) return;
    } else n2.t = Date.now();
    return u2(l$1.event ? l$1.event(n2) : n2);
  }
}
__name(D$1, "D$1");
function L$1(n2) {
  if (this.l) return this.l[n2.type + true](l$1.event ? l$1.event(n2) : n2);
}
__name(L$1, "L$1");
function M$1(n2, u2, t2, i2, o2, r2, f2, e2, c2, s2) {
  var a2, p2, y2, d2, _2, m2, w2, k2, x2, C2, S2, $2, H2, I2, T2, A2 = u2.type;
  if (void 0 !== u2.constructor) return null;
  128 & t2.__u && (c2 = !!(32 & t2.__u), r2 = [e2 = u2.__e = t2.__e]), (a2 = l$1.__b) && a2(u2);
  n: if ("function" == typeof A2) try {
    if (k2 = u2.props, x2 = (a2 = A2.contextType) && i2[a2.__c], C2 = a2 ? x2 ? x2.props.value : a2.__ : i2, t2.__c ? w2 = (p2 = u2.__c = t2.__c).__ = p2.__E : ("prototype" in A2 && A2.prototype.render ? u2.__c = p2 = new A2(k2, C2) : (u2.__c = p2 = new b$1(k2, C2), p2.constructor = A2, p2.render = q$1), x2 && x2.sub(p2), p2.props = k2, 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 != A2.getDerivedStateFromProps && (p2.__s == p2.state && (p2.__s = v$1({}, p2.__s)), v$1(p2.__s, A2.getDerivedStateFromProps(k2, p2.__s))), d2 = p2.props, _2 = p2.state, p2.__v = u2, y2) null == A2.getDerivedStateFromProps && null != p2.componentWillMount && p2.componentWillMount(), null != p2.componentDidMount && p2.__h.push(p2.componentDidMount);
    else {
      if (null == A2.getDerivedStateFromProps && k2 !== d2 && null != p2.componentWillReceiveProps && p2.componentWillReceiveProps(k2, C2), !p2.__e && (null != p2.shouldComponentUpdate && false === p2.shouldComponentUpdate(k2, p2.__s, C2) || u2.__v === t2.__v)) {
        for (u2.__v !== t2.__v && (p2.props = k2, 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(k2, p2.__s, C2), null != p2.componentDidUpdate && p2.__h.push(function() {
        p2.componentDidUpdate(d2, _2, m2);
      });
    }
    if (p2.context = C2, p2.props = k2, p2.__P = n2, p2.__e = false, $2 = l$1.__r, H2 = 0, "prototype" in A2 && A2.prototype.render) {
      for (p2.state = p2.__s, p2.__d = false, $2 && $2(u2), a2 = p2.render(p2.props, p2.state, p2.context), I2 = 0; I2 < p2._sb.length; I2++) p2.__h.push(p2._sb[I2]);
      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 && ++H2 < 25);
    p2.state = p2.__s, null != p2.getChildContext && (i2 = v$1(v$1({}, i2), p2.getChildContext())), y2 || null == p2.getSnapshotBeforeUpdate || (m2 = p2.getSnapshotBeforeUpdate(d2, _2)), P$1(n2, h$1(T2 = null != a2 && a2.type === g$1$1 && null == a2.key ? a2.props.children : a2) ? T2 : [T2], u2, t2, i2, o2, r2, f2, e2, c2, s2), p2.base = u2.__e, u2.__u &= -161, p2.__h.length && f2.push(p2), w2 && (p2.__E = p2.__ = null);
  } catch (n3) {
    u2.__v = null, c2 || null != r2 ? (u2.__e = e2, u2.__u |= c2 ? 160 : 32, r2[r2.indexOf(e2)] = null) : (u2.__e = t2.__e, u2.__k = t2.__k), l$1.__e(n3, u2, t2);
  }
  else null == r2 && u2.__v === t2.__v ? (u2.__k = t2.__k, u2.__e = t2.__e) : u2.__e = z$1$1(t2.__e, u2, t2, i2, o2, r2, f2, c2, s2);
  (a2 = l$1.diffed) && a2(u2);
}
__name(M$1, "M$1");
function j$1(n2, u2, t2) {
  for (var i2 = 0; i2 < t2.length; i2++) N$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);
    }
  });
}
__name(j$1, "j$1");
function z$1$1(l2, u2, t2, i2, o2, r2, f2, e2, s2) {
  var a2, v2, y2, d2, _2, g2, b2, w2 = t2.props, k2 = u2.props, x2 = u2.type;
  if ("svg" === x2 && (o2 = true), null != r2) {
    for (a2 = 0; a2 < r2.length; a2++) if ((_2 = r2[a2]) && "setAttribute" in _2 == !!x2 && (x2 ? _2.localName === x2 : 3 === _2.nodeType)) {
      l2 = _2, r2[a2] = null;
      break;
    }
  }
  if (null == l2) {
    if (null === x2) return document.createTextNode(k2);
    l2 = o2 ? document.createElementNS("http://www.w3.org/2000/svg", x2) : document.createElement(x2, k2.is && k2), r2 = null, e2 = false;
  }
  if (null === x2) w2 === k2 || e2 && l2.data === k2 || (l2.data = k2);
  else {
    if (r2 = r2 && n.call(l2.childNodes), w2 = t2.props || c$1, !e2 && null != r2) for (w2 = {}, a2 = 0; a2 < l2.attributes.length; a2++) w2[(_2 = l2.attributes[a2]).name] = _2.value;
    for (a2 in w2) _2 = w2[a2], "children" == a2 || ("dangerouslySetInnerHTML" == a2 ? y2 = _2 : "key" === a2 || a2 in k2 || A$1(l2, a2, null, _2, o2));
    for (a2 in k2) _2 = k2[a2], "children" == a2 ? d2 = _2 : "dangerouslySetInnerHTML" == a2 ? v2 = _2 : "value" == a2 ? g2 = _2 : "checked" == a2 ? b2 = _2 : "key" === a2 || e2 && "function" != typeof _2 || w2[a2] === _2 || A$1(l2, a2, _2, w2[a2], o2);
    if (v2) e2 || y2 && (v2.__html === y2.__html || v2.__html === l2.innerHTML) || (l2.innerHTML = v2.__html), u2.__k = [];
    else if (y2 && (l2.innerHTML = ""), P$1(l2, h$1(d2) ? d2 : [d2], u2, t2, i2, o2 && "foreignObject" !== x2, r2, f2, r2 ? r2[0] : t2.__k && m$1(t2, 0), e2, s2), null != r2) for (a2 = r2.length; a2--; ) null != r2[a2] && p$1(r2[a2]);
    e2 || (a2 = "value", void 0 !== g2 && (g2 !== l2[a2] || "progress" === x2 && !g2 || "option" === x2 && g2 !== w2[a2]) && A$1(l2, a2, g2, w2[a2], false), a2 = "checked", void 0 !== b2 && b2 !== l2[a2] && A$1(l2, a2, b2, w2[a2], false));
  }
  return l2;
}
__name(z$1$1, "z$1$1");
function N$1(n2, u2, t2) {
  try {
    "function" == typeof n2 ? n2(u2) : n2.current = u2;
  } catch (n3) {
    l$1.__e(n3, t2);
  }
}
__name(N$1, "N$1");
function O$1(n2, u2, t2) {
  var i2, o2;
  if (l$1.unmount && l$1.unmount(n2), (i2 = n2.ref) && (i2.current && i2.current !== n2.__e || N$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] && O$1(i2[o2], u2, t2 || "function" != typeof n2.type);
  t2 || null == n2.__e || p$1(n2.__e), n2.__ = n2.__e = n2.__d = void 0;
}
__name(O$1, "O$1");
function q$1(n2, l2, u2) {
  return this.constructor(n2, u2);
}
__name(q$1, "q$1");
function B$1(u2, t2, i2) {
  var o2, r2, f2, e2;
  l$1.__ && l$1.__(u2, t2), r2 = (o2 = "function" == typeof i2) ? null : t2.__k, f2 = [], e2 = [], M$1(t2, u2 = (!o2 && i2 || t2).__k = y$1(g$1$1, 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), u2.__d = void 0, j$1(f2, u2, e2);
}
__name(B$1, "B$1");
n = s$1.slice, l$1 = { __e: /* @__PURE__ */ __name(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;
}, "__e") }, 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), x$1(this));
}, b$1.prototype.forceUpdate = function(n2) {
  this.__v && (this.__e = true, n2 && this.__h.push(n2), x$1(this));
}, b$1.prototype.render = g$1$1, i$1 = [], r$1 = "function" == typeof Promise ? Promise.prototype.then.bind(Promise.resolve()) : setTimeout, f$1 = /* @__PURE__ */ __name(function(n2, l2) {
  return n2.__v.__b - l2.__v.__b;
}, "f$1"), C$1.__r = 0;
var t$1, r, u, i$2, o = 0, f = [], c = [], e = l$1, a = e.__b, v$2 = e.__r, l = e.diffed, m$2 = e.__c, s = e.unmount, d = e.__;
function h(n2, t2) {
  e.__h && e.__h(r, n2, o || t2), o = 0;
  var u2 = r.__H || (r.__H = { __: [], __h: [] });
  return n2 >= u2.__.length && u2.__.push({ __V: c }), u2.__[n2];
}
__name(h, "h");
function p(n2) {
  return o = 1, y(D$2, n2);
}
__name(p, "p");
function y(n2, u2, i2) {
  var o2 = h(t$1++, 2);
  if (o2.t = n2, !o2.__c && (o2.__ = [i2 ? i2(u2) : D$2(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 = /* @__PURE__ */ __name(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));
    }, "f");
    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.__;
}
__name(y, "y");
function _$1(n2, u2) {
  var i2 = h(t$1++, 3);
  !e.__s && C$2(i2.__H, u2) && (i2.__ = n2, i2.i = u2, r.__H.__h.push(i2));
}
__name(_$1, "_$1");
function A(n2, u2) {
  var i2 = h(t$1++, 4);
  !e.__s && C$2(i2.__H, u2) && (i2.__ = n2, i2.i = u2, r.__h.push(i2));
}
__name(A, "A");
function F$1(n2) {
  return o = 5, q$2(function() {
    return { current: n2 };
  }, []);
}
__name(F$1, "F$1");
function T(n2, t2, r2) {
  o = 6, A(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));
}
__name(T, "T");
function q$2(n2, r2) {
  var u2 = h(t$1++, 7);
  return C$2(u2.__H, r2) ? (u2.__V = n2(), u2.i = r2, u2.__h = n2, u2.__V) : u2.__;
}
__name(q$2, "q$2");
function x$2(n2, t2) {
  return o = 8, q$2(function() {
    return n2;
  }, t2);
}
__name(x$2, "x$2");
function P$2(n2) {
  var u2 = r.context[n2.__c], i2 = h(t$1++, 9);
  return i2.c = n2, u2 ? (null == i2.__ && (i2.__ = true, u2.sub(r)), u2.props.value) : n2.__;
}
__name(P$2, "P$2");
function V(n2, t2) {
  e.useDebugValue && e.useDebugValue(t2 ? t2(n2) : n2);
}
__name(V, "V");
function b$2(n2) {
  var u2 = h(t$1++, 10), i2 = p();
  return u2.__ = n2, r.componentDidCatch || (r.componentDidCatch = function(n3, t2) {
    u2.__ && u2.__(n3, t2), i2[1](n3);
  }), [i2[0], function() {
    i2[1](void 0);
  }];
}
__name(b$2, "b$2");
function g$7() {
  var n2 = h(t$1++, 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.__;
}
__name(g$7, "g$7");
function j$2() {
  for (var n2; n2 = f.shift(); ) if (n2.__P && n2.__H) try {
    n2.__H.__h.forEach(z$2), n2.__H.__h.forEach(B$2), n2.__H.__h = [];
  } catch (t2) {
    n2.__H.__h = [], e.__e(t2, n2.__v);
  }
}
__name(j$2, "j$2");
e.__b = function(n2) {
  r = null, a && a(n2);
}, e.__ = function(n2, t2) {
  t2.__k && t2.__k.__m && (n2.__m = t2.__k.__m), d && d(n2, t2);
}, e.__r = function(n2) {
  v$2 && v$2(n2), t$1 = 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(z$2), i2.__h.forEach(B$2), i2.__h = [], t$1 = 0)), u = r;
}, e.diffed = function(n2) {
  l && l(n2);
  var t2 = n2.__c;
  t2 && t2.__H && (t2.__H.__h.length && (1 !== f.push(t2) && i$2 === e.requestAnimationFrame || ((i$2 = e.requestAnimationFrame) || w)(j$2)), t2.__H.__.forEach(function(n3) {
    n3.i && (n3.__H = n3.i), n3.__V !== c && (n3.__ = n3.__V), n3.i = void 0, n3.__V = c;
  })), u = r = null;
}, e.__c = function(n2, t2) {
  t2.some(function(n3) {
    try {
      n3.__h.forEach(z$2), n3.__h = n3.__h.filter(function(n4) {
        return !n4.__ || B$2(n4);
      });
    } catch (r2) {
      t2.some(function(n4) {
        n4.__h && (n4.__h = []);
      }), t2 = [], e.__e(r2, n3.__v);
    }
  }), m$2 && m$2(n2, t2);
}, e.unmount = function(n2) {
  s && s(n2);
  var t2, r2 = n2.__c;
  r2 && r2.__H && (r2.__H.__.forEach(function(n3) {
    try {
      z$2(n3);
    } catch (n4) {
      t2 = n4;
    }
  }), r2.__H = void 0, t2 && e.__e(t2, r2.__v));
};
var k$2 = "function" == typeof requestAnimationFrame;
function w(n2) {
  var t2, r2 = /* @__PURE__ */ __name(function() {
    clearTimeout(u2), k$2 && cancelAnimationFrame(t2), setTimeout(n2);
  }, "r"), u2 = setTimeout(r2, 100);
  k$2 && (t2 = requestAnimationFrame(r2));
}
__name(w, "w");
function z$2(n2) {
  var t2 = r, u2 = n2.__c;
  "function" == typeof u2 && (n2.__c = void 0, u2()), r = t2;
}
__name(z$2, "z$2");
function B$2(n2) {
  var t2 = r;
  n2.__c = n2.__(), r = t2;
}
__name(B$2, "B$2");
function C$2(n2, t2) {
  return !n2 || n2.length !== t2.length || t2.some(function(t3, r2) {
    return t3 !== n2[r2];
  });
}
__name(C$2, "C$2");
function D$2(n2, t2) {
  return "function" == typeof t2 ? t2(n2) : t2;
}
__name(D$2, "D$2");
const hooks = {
  __proto__: null,
  useCallback: x$2,
  useContext: P$2,
  useDebugValue: V,
  useEffect: _$1,
  useErrorBoundary: b$2,
  useId: g$7,
  useImperativeHandle: T,
  useLayoutEffect: A,
  useMemo: q$2,
  useReducer: y,
  useRef: F$1,
  useState: p
};
const XMLNS$1 = "http://www.w3.org/2000/svg";
function SentryLogo() {
  const createElementNS = /* @__PURE__ */ __name((tagName) => DOCUMENT.createElementNS(XMLNS$1, tagName), "createElementNS");
  const svg = setAttributesNS(createElementNS("svg"), {
    width: "32",
    height: "30",
    viewBox: "0 0 72 66",
    fill: "inherit"
  });
  const path = setAttributesNS(createElementNS("path"), {
    transform: "translate(11, 11)",
    d: "M29,2.26a4.67,4.67,0,0,0-8,0L14.42,13.53A32.21,32.21,0,0,1,32.17,40.19H27.55A27.68,27.68,0,0,0,12.09,17.47L6,28a15.92,15.92,0,0,1,9.23,12.17H4.62A.76.76,0,0,1,4,39.06l2.94-5a10.74,10.74,0,0,0-3.36-1.9l-2.91,5a4.54,4.54,0,0,0,1.69,6.24A4.66,4.66,0,0,0,4.62,44H19.15a19.4,19.4,0,0,0-8-17.31l2.31-4A23.87,23.87,0,0,1,23.76,44H36.07a35.88,35.88,0,0,0-16.41-31.8l4.67-8a.77.77,0,0,1,1.05-.27c.53.29,20.29,34.77,20.66,35.17a.76.76,0,0,1-.68,1.13H40.6q.09,1.91,0,3.81h4.78A4.59,4.59,0,0,0,50,39.43a4.49,4.49,0,0,0-.62-2.28Z"
  });
  svg.appendChild(path);
  return svg;
}
__name(SentryLogo, "SentryLogo");
function DialogHeader({ options: options2 }) {
  const logoHtml = q$2(() => ({ __html: SentryLogo().outerHTML }), []);
  return y$1(
    "h2",
    { class: "dialog__header" },
    y$1("span", { class: "dialog__title" }, options2.formTitle),
    options2.showBranding ? y$1(
      "a",
      {
        class: "brand-link",
        target: "_blank",
        href: "https://sentry.io/welcome/",
        title: "Powered by Sentry",
        rel: "noopener noreferrer",
        dangerouslySetInnerHTML: logoHtml
      }
    ) : null
  );
}
__name(DialogHeader, "DialogHeader");
function getMissingFields(feedback, props) {
  const emptyFields = [];
  if (props.isNameRequired && !feedback.name) {
    emptyFields.push(props.nameLabel);
  }
  if (props.isEmailRequired && !feedback.email) {
    emptyFields.push(props.emailLabel);
  }
  if (!feedback.message) {
    emptyFields.push(props.messageLabel);
  }
  return emptyFields;
}
__name(getMissingFields, "getMissingFields");
function retrieveStringValue(formData, key) {
  const value = formData.get(key);
  if (typeof value === "string") {
    return value.trim();
  }
  return "";
}
__name(retrieveStringValue, "retrieveStringValue");
function Form({
  options: options2,
  defaultEmail,
  defaultName,
  onFormClose,
  onSubmit,
  onSubmitSuccess,
  onSubmitError,
  showEmail,
  showName,
  screenshotInput
}) {
  const {
    tags,
    addScreenshotButtonLabel,
    removeScreenshotButtonLabel,
    cancelButtonLabel,
    emailLabel,
    emailPlaceholder,
    isEmailRequired,
    isNameRequired,
    messageLabel,
    messagePlaceholder,
    nameLabel,
    namePlaceholder,
    submitButtonLabel,
    isRequiredLabel
  } = options2;
  const [error2, setError] = p(null);
  const [showScreenshotInput, setShowScreenshotInput] = p(false);
  const ScreenshotInputComponent = screenshotInput && screenshotInput.input;
  const [screenshotError, setScreenshotError] = p(null);
  const onScreenshotError = x$2((error3) => {
    setScreenshotError(error3);
    setShowScreenshotInput(false);
  }, []);
  const hasAllRequiredFields = x$2(
    (data) => {
      const missingFields = getMissingFields(data, {
        emailLabel,
        isEmailRequired,
        isNameRequired,
        messageLabel,
        nameLabel
      });
      if (missingFields.length > 0) {
        setError(`Please enter in the following required fields: ${missingFields.join(", ")}`);
      } else {
        setError(null);
      }
      return missingFields.length === 0;
    },
    [emailLabel, isEmailRequired, isNameRequired, messageLabel, nameLabel]
  );
  const handleSubmit = x$2(
    async (e2) => {
      try {
        e2.preventDefault();
        if (!(e2.target instanceof HTMLFormElement)) {
          return;
        }
        const formData = new FormData(e2.target);
        const attachment = await (screenshotInput && showScreenshotInput ? screenshotInput.value() : void 0);
        const data = {
          name: retrieveStringValue(formData, "name"),
          email: retrieveStringValue(formData, "email"),
          message: retrieveStringValue(formData, "message"),
          attachments: attachment ? [attachment] : void 0
        };
        if (!hasAllRequiredFields(data)) {
          return;
        }
        try {
          await onSubmit(
            {
              name: data.name,
              email: data.email,
              message: data.message,
              source: FEEDBACK_WIDGET_SOURCE,
              tags
            },
            { attachments: data.attachments }
          );
          onSubmitSuccess(data);
        } catch (error3) {
          DEBUG_BUILD$1 && logger$5.error(error3);
          setError(error3);
          onSubmitError(error3);
        }
      } catch (e22) {
      }
    },
    [screenshotInput && showScreenshotInput, onSubmitSuccess, onSubmitError]
  );
  return y$1(
    "form",
    { class: "form", onSubmit: handleSubmit },
    ScreenshotInputComponent && showScreenshotInput ? y$1(ScreenshotInputComponent, { onError: onScreenshotError }) : null,
    y$1(
      "div",
      { class: "form__right", "data-sentry-feedback": true },
      y$1(
        "div",
        { class: "form__top" },
        error2 ? y$1("div", { class: "form__error-container" }, error2) : null,
        showName ? y$1(
          "label",
          { for: "name", class: "form__label" },
          y$1(LabelText, { label: nameLabel, isRequiredLabel, isRequired: isNameRequired }),
          y$1(
            "input",
            {
              class: "form__input",
              defaultValue: defaultName,
              id: "name",
              name: "name",
              placeholder: namePlaceholder,
              required: isNameRequired,
              type: "text"
            }
          )
        ) : y$1("input", { "aria-hidden": true, value: defaultName, name: "name", type: "hidden" }),
        showEmail ? y$1(
          "label",
          { for: "email", class: "form__label" },
          y$1(LabelText, { label: emailLabel, isRequiredLabel, isRequired: isEmailRequired }),
          y$1(
            "input",
            {
              class: "form__input",
              defaultValue: defaultEmail,
              id: "email",
              name: "email",
              placeholder: emailPlaceholder,
              required: isEmailRequired,
              type: "email"
            }
          )
        ) : y$1("input", { "aria-hidden": true, value: defaultEmail, name: "email", type: "hidden" }),
        y$1(
          "label",
          { for: "message", class: "form__label" },
          y$1(LabelText, { label: messageLabel, isRequiredLabel, isRequired: true }),
          y$1(
            "textarea",
            {
              autoFocus: true,
              class: "form__input form__input--textarea",
              id: "message",
              name: "message",
              placeholder: messagePlaceholder,
              required: true,
              rows: 5
            }
          )
        ),
        ScreenshotInputComponent ? y$1(
          "label",
          { for: "screenshot", class: "form__label" },
          y$1(
            "button",
            {
              class: "btn btn--default",
              type: "button",
              onClick: /* @__PURE__ */ __name(() => {
                setScreenshotError(null);
                setShowScreenshotInput((prev) => !prev);
              }, "onClick")
            },
            showScreenshotInput ? removeScreenshotButtonLabel : addScreenshotButtonLabel
          ),
          screenshotError ? y$1("div", { class: "form__error-container" }, screenshotError.message) : null
        ) : null
      ),
      y$1(
        "div",
        { class: "btn-group" },
        y$1(
          "button",
          { class: "btn btn--primary", type: "submit" },
          submitButtonLabel
        ),
        y$1(
          "button",
          { class: "btn btn--default", type: "button", onClick: onFormClose },
          cancelButtonLabel
        )
      )
    )
  );
}
__name(Form, "Form");
function LabelText({
  label,
  isRequired,
  isRequiredLabel
}) {
  return y$1(
    "span",
    { class: "form__label__text" },
    label,
    isRequired && y$1("span", { class: "form__label__text--required" }, isRequiredLabel)
  );
}
__name(LabelText, "LabelText");
const WIDTH = 16;
const HEIGHT = 17;
const XMLNS = "http://www.w3.org/2000/svg";
function SuccessIcon() {
  const createElementNS = /* @__PURE__ */ __name((tagName) => WINDOW.document.createElementNS(XMLNS, tagName), "createElementNS");
  const svg = setAttributesNS(createElementNS("svg"), {
    width: `${WIDTH}`,
    height: `${HEIGHT}`,
    viewBox: `0 0 ${WIDTH} ${HEIGHT}`,
    fill: "inherit"
  });
  const g2 = setAttributesNS(createElementNS("g"), {
    clipPath: "url(#clip0_57_156)"
  });
  const path2 = setAttributesNS(createElementNS("path"), {
    ["fill-rule"]: "evenodd",
    ["clip-rule"]: "evenodd",
    d: "M3.55544 15.1518C4.87103 16.0308 6.41775 16.5 8 16.5C10.1217 16.5 12.1566 15.6571 13.6569 14.1569C15.1571 12.6566 16 10.6217 16 8.5C16 6.91775 15.5308 5.37103 14.6518 4.05544C13.7727 2.73985 12.5233 1.71447 11.0615 1.10897C9.59966 0.503466 7.99113 0.34504 6.43928 0.653721C4.88743 0.962403 3.46197 1.72433 2.34315 2.84315C1.22433 3.96197 0.462403 5.38743 0.153721 6.93928C-0.15496 8.49113 0.00346625 10.0997 0.608967 11.5615C1.21447 13.0233 2.23985 14.2727 3.55544 15.1518ZM4.40546 3.1204C5.46945 2.40946 6.72036 2.03 8 2.03C9.71595 2.03 11.3616 2.71166 12.575 3.92502C13.7883 5.13838 14.47 6.78405 14.47 8.5C14.47 9.77965 14.0905 11.0306 13.3796 12.0945C12.6687 13.1585 11.6582 13.9878 10.476 14.4775C9.29373 14.9672 7.99283 15.0953 6.73777 14.8457C5.48271 14.596 4.32987 13.9798 3.42502 13.075C2.52018 12.1701 1.90397 11.0173 1.65432 9.76224C1.40468 8.50718 1.5328 7.20628 2.0225 6.02404C2.5122 4.8418 3.34148 3.83133 4.40546 3.1204Z"
  });
  const path = setAttributesNS(createElementNS("path"), {
    d: "M6.68775 12.4297C6.78586 12.4745 6.89218 12.4984 7 12.5C7.11275 12.4955 7.22315 12.4664 7.32337 12.4145C7.4236 12.3627 7.51121 12.2894 7.58 12.2L12 5.63999C12.0848 5.47724 12.1071 5.28902 12.0625 5.11098C12.0178 4.93294 11.9095 4.77744 11.7579 4.67392C11.6064 4.57041 11.4221 4.52608 11.24 4.54931C11.0579 4.57254 10.8907 4.66173 10.77 4.79999L6.88 10.57L5.13 8.56999C5.06508 8.49566 4.98613 8.43488 4.89768 8.39111C4.80922 8.34735 4.713 8.32148 4.61453 8.31498C4.51605 8.30847 4.41727 8.32147 4.32382 8.35322C4.23038 8.38497 4.14413 8.43484 4.07 8.49999C3.92511 8.63217 3.83692 8.81523 3.82387 9.01092C3.81083 9.2066 3.87393 9.39976 4 9.54999L6.43 12.24C6.50187 12.3204 6.58964 12.385 6.68775 12.4297Z"
  });
  svg.appendChild(g2).append(path, path2);
  const speakerDefs = createElementNS("defs");
  const speakerClipPathDef = setAttributesNS(createElementNS("clipPath"), {
    id: "clip0_57_156"
  });
  const speakerRect = setAttributesNS(createElementNS("rect"), {
    width: `${WIDTH}`,
    height: `${WIDTH}`,
    fill: "white",
    transform: "translate(0 0.5)"
  });
  speakerClipPathDef.appendChild(speakerRect);
  speakerDefs.appendChild(speakerClipPathDef);
  svg.appendChild(speakerDefs).appendChild(speakerClipPathDef).appendChild(speakerRect);
  return svg;
}
__name(SuccessIcon, "SuccessIcon");
function Dialog({ open: open2, onFormSubmitted, ...props }) {
  const options2 = props.options;
  const successIconHtml = q$2(() => ({ __html: SuccessIcon().outerHTML }), []);
  const [timeoutId, setTimeoutId] = p(null);
  const handleOnSuccessClick = x$2(() => {
    if (timeoutId) {
      clearTimeout(timeoutId);
      setTimeoutId(null);
    }
    onFormSubmitted();
  }, [timeoutId]);
  const onSubmitSuccess = x$2(
    (data) => {
      props.onSubmitSuccess(data);
      setTimeoutId(
        setTimeout(() => {
          onFormSubmitted();
          setTimeoutId(null);
        }, SUCCESS_MESSAGE_TIMEOUT)
      );
    },
    [onFormSubmitted]
  );
  return y$1(
    g$1$1,
    null,
    timeoutId ? y$1(
      "div",
      { class: "success__position", onClick: handleOnSuccessClick },
      y$1(
        "div",
        { class: "success__content" },
        options2.successMessageText,
        y$1("span", { class: "success__icon", dangerouslySetInnerHTML: successIconHtml })
      )
    ) : y$1(
      "dialog",
      { class: "dialog", onClick: options2.onFormClose, open: open2 },
      y$1(
        "div",
        { class: "dialog__position" },
        y$1(
          "div",
          {
            class: "dialog__content",
            onClick: /* @__PURE__ */ __name((e2) => {
              e2.stopPropagation();
            }, "onClick")
          },
          y$1(DialogHeader, { options: options2 }),
          y$1(Form, { ...props, onSubmitSuccess })
        )
      )
    )
  );
}
__name(Dialog, "Dialog");
const DIALOG = `
.dialog {
  position: fixed;
  z-index: var(--z-index);
  margin: 0;
  inset: 0;

  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
  height: 100vh;
  width: 100vw;

  color: var(--dialog-color, var(--foreground));
  fill: var(--dialog-color, var(--foreground));
  line-height: 1.75em;

  background-color: rgba(0, 0, 0, 0.05);
  border: none;
  inset: 0;
  opacity: 1;
  transition: opacity 0.2s ease-in-out;
}

.dialog__position {
  position: fixed;
  z-index: var(--z-index);
  inset: var(--dialog-inset);
  padding: var(--page-margin);
  display: flex;
  max-height: calc(100vh - (2 * var(--page-margin)));
}
@media (max-width: 600px) {
  .dialog__position {
    inset: var(--page-margin);
    padding: 0;
  }
}

.dialog__position:has(.editor) {
  inset: var(--page-margin);
  padding: 0;
}

.dialog:not([open]) {
  opacity: 0;
  pointer-events: none;
  visibility: hidden;
}
.dialog:not([open]) .dialog__content {
  transform: translate(0, -16px) scale(0.98);
}

.dialog__content {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: var(--dialog-padding, 24px);
  max-width: 100%;
  width: 100%;
  max-height: 100%;
  overflow: auto;

  background: var(--dialog-background, var(--background));
  border-radius: var(--dialog-border-radius, 20px);
  border: var(--dialog-border, var(--border));
  box-shadow: var(--dialog-box-shadow, var(--box-shadow));
  transform: translate(0, 0) scale(1);
  transition: transform 0.2s ease-in-out;
}

`;
const DIALOG_HEADER = `
.dialog__header {
  display: flex;
  gap: 4px;
  justify-content: space-between;
  font-weight: var(--dialog-header-weight, 600);
  margin: 0;
}
.dialog__title {
  align-self: center;
  width: var(--form-width, 272px);
}

@media (max-width: 600px) {
  .dialog__title {
    width: auto;
  }
}

.dialog__position:has(.editor) .dialog__title {
  width: auto;
}


.brand-link {
  display: inline-flex;
}
.brand-link:focus-visible {
  outline: var(--outline);
}
`;
const FORM = `
.form {
  display: flex;
  overflow: auto;
  flex-direction: row;
  gap: 16px;
  flex: 1 0;
}

.form__right {
  flex: 0 0 auto;
  display: flex;
  overflow: auto;
  flex-direction: column;
  justify-content: space-between;
  gap: 20px;
  width: var(--form-width, 100%);
}

.dialog__position:has(.editor) .form__right {
  width: var(--form-width, 272px);
}

.form__top {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form__error-container {
  color: var(--error-color);
  fill: var(--error-color);
}

.form__label {
  display: flex;
  flex-direction: column;
  gap: 4px;
  margin: 0px;
}

.form__label__text {
  display: flex;
  gap: 4px;
  align-items: center;
}

.form__label__text--required {
  font-size: 0.85em;
}

.form__input {
  font-family: inherit;
  line-height: inherit;
  background: transparent;
  box-sizing: border-box;
  border: var(--input-border, var(--border));
  border-radius: var(--input-border-radius, 6px);
  color: var(--input-color, inherit);
  fill: var(--input-color, inherit);
  font-size: var(--input-font-size, inherit);
  font-weight: var(--input-font-weight, 500);
  padding: 6px 12px;
}

.form__input::placeholder {
  opacity: 0.65;
  color: var(--input-placeholder-color, inherit);
  filter: var(--interactive-filter);
}

.form__input:focus-visible {
  outline: var(--input-focus-outline, var(--outline));
}

.form__input--textarea {
  font-family: inherit;
  resize: vertical;
}

.error {
  color: var(--error-color);
  fill: var(--error-color);
}
`;
const BUTTON = `
.btn-group {
  display: grid;
  gap: 8px;
}

.btn {
  line-height: inherit;
  border: var(--button-border, var(--border));
  border-radius: var(--button-border-radius, 6px);
  cursor: pointer;
  font-family: inherit;
  font-size: var(--button-font-size, inherit);
  font-weight: var(--button-font-weight, 600);
  padding: var(--button-padding, 6px 16px);
}
.btn[disabled] {
  opacity: 0.6;
  pointer-events: none;
}

.btn--primary {
  color: var(--button-primary-color, var(--accent-foreground));
  fill: var(--button-primary-color, var(--accent-foreground));
  background: var(--button-primary-background, var(--accent-background));
  border: var(--button-primary-border, var(--border));
  border-radius: var(--button-primary-border-radius, 6px);
  font-weight: var(--button-primary-font-weight, 500);
}
.btn--primary:hover {
  color: var(--button-primary-hover-color, var(--accent-foreground));
  fill: var(--button-primary-hover-color, var(--accent-foreground));
  background: var(--button-primary-hover-background, var(--accent-background));
  filter: var(--interactive-filter);
}
.btn--primary:focus-visible {
  background: var(--button-primary-hover-background, var(--accent-background));
  filter: var(--interactive-filter);
  outline: var(--button-primary-focus-outline, var(--outline));
}

.btn--default {
  color: var(--button-color, var(--foreground));
  fill: var(--button-color, var(--foreground));
  background: var(--button-background, var(--background));
  border: var(--button-border, var(--border));
  border-radius: var(--button-border-radius, 6px);
  font-weight: var(--button-font-weight, 500);
}
.btn--default:hover {
  color: var(--button-color, var(--foreground));
  fill: var(--button-color, var(--foreground));
  background: var(--button-hover-background, var(--background));
  filter: var(--interactive-filter);
}
.btn--default:focus-visible {
  background: var(--button-hover-background, var(--background));
  filter: var(--interactive-filter);
  outline: var(--button-focus-outline, var(--outline));
}
`;
const SUCCESS = `
.success__position {
  position: fixed;
  inset: var(--dialog-inset);
  padding: var(--page-margin);
  z-index: var(--z-index);
}
.success__content {
  background: var(--success-background, var(--background));
  border: var(--success-border, var(--border));
  border-radius: var(--success-border-radius, 1.7em/50%);
  box-shadow: var(--success-box-shadow, var(--box-shadow));
  font-weight: var(--success-font-weight, 600);
  color: var(--success-color);
  fill: var(--success-color);
  padding: 12px 24px;
  line-height: 1.75em;

  display: grid;
  align-items: center;
  grid-auto-flow: column;
  gap: 6px;
  cursor: default;
}

.success__icon {
  display: flex;
}
`;
function createDialogStyles(styleNonce) {
  const style2 = DOCUMENT.createElement("style");
  style2.textContent = `
:host {
  --dialog-inset: var(--inset);
}

${DIALOG}
${DIALOG_HEADER}
${FORM}
${BUTTON}
${SUCCESS}
`;
  if (styleNonce) {
    style2.setAttribute("nonce", styleNonce);
  }
  return style2;
}
__name(createDialogStyles, "createDialogStyles");
function getUser() {
  const currentUser = getCurrentScope().getUser();
  const isolationUser = getIsolationScope().getUser();
  const globalUser = getGlobalScope$1().getUser();
  if (currentUser && Object.keys(currentUser).length) {
    return currentUser;
  }
  if (isolationUser && Object.keys(isolationUser).length) {
    return isolationUser;
  }
  return globalUser;
}
__name(getUser, "getUser");
const feedbackModalIntegration = /* @__PURE__ */ __name(() => {
  return {
    name: "FeedbackModal",
    // eslint-disable-next-line @typescript-eslint/no-empty-function
    setupOnce() {
    },
    createDialog: /* @__PURE__ */ __name(({ options: options2, screenshotIntegration, sendFeedback: sendFeedback2, shadow }) => {
      const shadowRoot = shadow;
      const userKey = options2.useSentryUser;
      const user = getUser();
      const el = DOCUMENT.createElement("div");
      const style2 = createDialogStyles(options2.styleNonce);
      let originalOverflow = "";
      const dialog = {
        get el() {
          return el;
        },
        appendToDom() {
          if (!shadowRoot.contains(style2) && !shadowRoot.contains(el)) {
            shadowRoot.appendChild(style2);
            shadowRoot.appendChild(el);
          }
        },
        removeFromDom() {
          shadowRoot.removeChild(el);
          shadowRoot.removeChild(style2);
          DOCUMENT.body.style.overflow = originalOverflow;
        },
        open() {
          renderContent(true);
          options2.onFormOpen && options2.onFormOpen();
          originalOverflow = DOCUMENT.body.style.overflow;
          DOCUMENT.body.style.overflow = "hidden";
        },
        close() {
          renderContent(false);
          DOCUMENT.body.style.overflow = originalOverflow;
        }
      };
      const screenshotInput = screenshotIntegration && screenshotIntegration.createInput({ h: y$1, hooks, dialog, options: options2 });
      const renderContent = /* @__PURE__ */ __name((open2) => {
        B$1(
          y$1(
            Dialog,
            {
              options: options2,
              screenshotInput,
              showName: options2.showName || options2.isNameRequired,
              showEmail: options2.showEmail || options2.isEmailRequired,
              defaultName: userKey && user && user[userKey.name] || "",
              defaultEmail: userKey && user && user[userKey.email] || "",
              onFormClose: /* @__PURE__ */ __name(() => {
                renderContent(false);
                options2.onFormClose && options2.onFormClose();
              }, "onFormClose"),
              onSubmit: sendFeedback2,
              onSubmitSuccess: /* @__PURE__ */ __name((data) => {
                renderContent(false);
                options2.onSubmitSuccess && options2.onSubmitSuccess(data);
              }, "onSubmitSuccess"),
              onSubmitError: /* @__PURE__ */ __name((error2) => {
                options2.onSubmitError && options2.onSubmitError(error2);
              }, "onSubmitError"),
              onFormSubmitted: /* @__PURE__ */ __name(() => {
                options2.onFormSubmitted && options2.onFormSubmitted();
              }, "onFormSubmitted"),
              open: open2
            }
          ),
          el
        );
      }, "renderContent");
      return dialog;
    }, "createDialog")
  };
}, "feedbackModalIntegration");
function CropCornerFactory({
  h: h2
  // eslint-disable-line @typescript-eslint/no-unused-vars
}) {
  return /* @__PURE__ */ __name(function CropCorner({
    top,
    left,
    corner,
    onGrabButton
  }) {
    return h2(
      "button",
      {
        class: `editor__crop-corner editor__crop-corner--${corner} `,
        style: {
          top,
          left
        },
        onMouseDown: /* @__PURE__ */ __name((e2) => {
          e2.preventDefault();
          onGrabButton(e2, corner);
        }, "onMouseDown"),
        onClick: /* @__PURE__ */ __name((e2) => {
          e2.preventDefault();
        }, "onClick")
      }
    );
  }, "CropCorner");
}
__name(CropCornerFactory, "CropCornerFactory");
function createScreenshotInputStyles(styleNonce) {
  const style2 = DOCUMENT.createElement("style");
  const surface200 = "#1A141F";
  const gray100 = "#302735";
  style2.textContent = `
.editor {
  padding: 10px;
  padding-top: 65px;
  padding-bottom: 65px;
  flex-grow: 1;

  background-color: ${surface200};
  background-image: repeating-linear-gradient(
      -145deg,
      transparent,
      transparent 8px,
      ${surface200} 8px,
      ${surface200} 11px
    ),
    repeating-linear-gradient(
      -45deg,
      transparent,
      transparent 15px,
      ${gray100} 15px,
      ${gray100} 16px
    );
}

.editor__canvas-container {
  width: 100%;
  height: 100%;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

.editor__canvas-container canvas {
  object-fit: contain;
  position: relative;
}

.editor__crop-btn-group {
  padding: 8px;
  gap: 8px;
  border-radius: var(--menu-border-radius, 6px);
  background: var(--button-primary-background, var(--background));
  width: 175px;
  position: absolute;
}

.editor__crop-corner {
  width: 30px;
  height: 30px;
  position: absolute;
  background: none;
  border: 3px solid #ffffff;
}

.editor__crop-corner--top-left {
  cursor: nwse-resize;
  border-right: none;
  border-bottom: none;
}
.editor__crop-corner--top-right {
  cursor: nesw-resize;
  border-left: none;
  border-bottom: none;
}
.editor__crop-corner--bottom-left {
  cursor: nesw-resize;
  border-right: none;
  border-top: none;
}
.editor__crop-corner--bottom-right {
  cursor: nwse-resize;
  border-left: none;
  border-top: none;
}
`;
  if (styleNonce) {
    style2.setAttribute("nonce", styleNonce);
  }
  return style2;
}
__name(createScreenshotInputStyles, "createScreenshotInputStyles");
function useTakeScreenshotFactory({ hooks: hooks2 }) {
  return /* @__PURE__ */ __name(function useTakeScreenshot({ onBeforeScreenshot, onScreenshot, onAfterScreenshot, onError }) {
    hooks2.useEffect(() => {
      const takeScreenshot = /* @__PURE__ */ __name(async () => {
        onBeforeScreenshot();
        const stream = await NAVIGATOR.mediaDevices.getDisplayMedia({
          video: {
            width: WINDOW.innerWidth * WINDOW.devicePixelRatio,
            height: WINDOW.innerHeight * WINDOW.devicePixelRatio
          },
          audio: false,
          // @ts-expect-error experimental flags: https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getDisplayMedia#prefercurrenttab
          monitorTypeSurfaces: "exclude",
          preferCurrentTab: true,
          selfBrowserSurface: "include",
          surfaceSwitching: "exclude"
        });
        const video = DOCUMENT.createElement("video");
        await new Promise((resolve2, reject) => {
          video.srcObject = stream;
          video.onloadedmetadata = () => {
            onScreenshot(video);
            stream.getTracks().forEach((track) => track.stop());
            resolve2();
          };
          video.play().catch(reject);
        });
        onAfterScreenshot();
      }, "takeScreenshot");
      takeScreenshot().catch(onError);
    }, []);
  }, "useTakeScreenshot");
}
__name(useTakeScreenshotFactory, "useTakeScreenshotFactory");
const CROP_BUTTON_SIZE = 30;
const CROP_BUTTON_BORDER = 3;
const CROP_BUTTON_OFFSET = CROP_BUTTON_SIZE + CROP_BUTTON_BORDER;
const DPI = WINDOW.devicePixelRatio;
const constructRect = /* @__PURE__ */ __name((box) => {
  return {
    x: Math.min(box.startX, box.endX),
    y: Math.min(box.startY, box.endY),
    width: Math.abs(box.startX - box.endX),
    height: Math.abs(box.startY - box.endY)
  };
}, "constructRect");
const getContainedSize = /* @__PURE__ */ __name((img) => {
  const imgClientHeight = img.clientHeight;
  const imgClientWidth = img.clientWidth;
  const ratio = img.width / img.height;
  let width2 = imgClientHeight * ratio;
  let height = imgClientHeight;
  if (width2 > imgClientWidth) {
    width2 = imgClientWidth;
    height = imgClientWidth / ratio;
  }
  const x2 = (imgClientWidth - width2) / 2;
  const y2 = (imgClientHeight - height) / 2;
  return { startX: x2, startY: y2, endX: width2 + x2, endY: height + y2 };
}, "getContainedSize");
function ScreenshotEditorFactory({
  h: h2,
  hooks: hooks2,
  imageBuffer,
  dialog,
  options: options2
}) {
  const useTakeScreenshot = useTakeScreenshotFactory({ hooks: hooks2 });
  return /* @__PURE__ */ __name(function ScreenshotEditor({ onError }) {
    const styles = hooks2.useMemo(() => ({ __html: createScreenshotInputStyles(options2.styleNonce).innerText }), []);
    const CropCorner = CropCornerFactory({ h: h2 });
    const canvasContainerRef = hooks2.useRef(null);
    const cropContainerRef = hooks2.useRef(null);
    const croppingRef = hooks2.useRef(null);
    const [croppingRect, setCroppingRect] = hooks2.useState({ startX: 0, startY: 0, endX: 0, endY: 0 });
    const [confirmCrop, setConfirmCrop] = hooks2.useState(false);
    const [isResizing, setIsResizing] = hooks2.useState(false);
    hooks2.useEffect(() => {
      WINDOW.addEventListener("resize", resizeCropper, false);
    }, []);
    function resizeCropper() {
      const cropper = croppingRef.current;
      const imageDimensions = constructRect(getContainedSize(imageBuffer));
      if (cropper) {
        cropper.width = imageDimensions.width * DPI;
        cropper.height = imageDimensions.height * DPI;
        cropper.style.width = `${imageDimensions.width}px`;
        cropper.style.height = `${imageDimensions.height}px`;
        const ctx = cropper.getContext("2d");
        if (ctx) {
          ctx.scale(DPI, DPI);
        }
      }
      const cropButton = cropContainerRef.current;
      if (cropButton) {
        cropButton.style.width = `${imageDimensions.width}px`;
        cropButton.style.height = `${imageDimensions.height}px`;
      }
      setCroppingRect({ startX: 0, startY: 0, endX: imageDimensions.width, endY: imageDimensions.height });
    }
    __name(resizeCropper, "resizeCropper");
    hooks2.useEffect(() => {
      const cropper = croppingRef.current;
      if (!cropper) {
        return;
      }
      const ctx = cropper.getContext("2d");
      if (!ctx) {
        return;
      }
      const imageDimensions = constructRect(getContainedSize(imageBuffer));
      const croppingBox = constructRect(croppingRect);
      ctx.clearRect(0, 0, imageDimensions.width, imageDimensions.height);
      ctx.fillStyle = "rgba(0, 0, 0, 0.5)";
      ctx.fillRect(0, 0, imageDimensions.width, imageDimensions.height);
      ctx.clearRect(croppingBox.x, croppingBox.y, croppingBox.width, croppingBox.height);
      ctx.strokeStyle = "#ffffff";
      ctx.lineWidth = 3;
      ctx.strokeRect(croppingBox.x + 1, croppingBox.y + 1, croppingBox.width - 2, croppingBox.height - 2);
      ctx.strokeStyle = "#000000";
      ctx.lineWidth = 1;
      ctx.strokeRect(croppingBox.x + 3, croppingBox.y + 3, croppingBox.width - 6, croppingBox.height - 6);
    }, [croppingRect]);
    function onGrabButton(e2, corner) {
      setConfirmCrop(false);
      setIsResizing(true);
      const handleMouseMove2 = makeHandleMouseMove(corner);
      const handleMouseUp = /* @__PURE__ */ __name(() => {
        DOCUMENT.removeEventListener("mousemove", handleMouseMove2);
        DOCUMENT.removeEventListener("mouseup", handleMouseUp);
        setConfirmCrop(true);
        setIsResizing(false);
      }, "handleMouseUp");
      DOCUMENT.addEventListener("mouseup", handleMouseUp);
      DOCUMENT.addEventListener("mousemove", handleMouseMove2);
    }
    __name(onGrabButton, "onGrabButton");
    const makeHandleMouseMove = hooks2.useCallback((corner) => {
      return function(e2) {
        if (!croppingRef.current) {
          return;
        }
        const cropCanvas = croppingRef.current;
        const cropBoundingRect = cropCanvas.getBoundingClientRect();
        const mouseX = e2.clientX - cropBoundingRect.x;
        const mouseY = e2.clientY - cropBoundingRect.y;
        switch (corner) {
          case "top-left":
            setCroppingRect((prev) => ({
              ...prev,
              startX: Math.min(Math.max(0, mouseX), prev.endX - CROP_BUTTON_OFFSET),
              startY: Math.min(Math.max(0, mouseY), prev.endY - CROP_BUTTON_OFFSET)
            }));
            break;
          case "top-right":
            setCroppingRect((prev) => ({
              ...prev,
              endX: Math.max(Math.min(mouseX, cropCanvas.width / DPI), prev.startX + CROP_BUTTON_OFFSET),
              startY: Math.min(Math.max(0, mouseY), prev.endY - CROP_BUTTON_OFFSET)
            }));
            break;
          case "bottom-left":
            setCroppingRect((prev) => ({
              ...prev,
              startX: Math.min(Math.max(0, mouseX), prev.endX - CROP_BUTTON_OFFSET),
              endY: Math.max(Math.min(mouseY, cropCanvas.height / DPI), prev.startY + CROP_BUTTON_OFFSET)
            }));
            break;
          case "bottom-right":
            setCroppingRect((prev) => ({
              ...prev,
              endX: Math.max(Math.min(mouseX, cropCanvas.width / DPI), prev.startX + CROP_BUTTON_OFFSET),
              endY: Math.max(Math.min(mouseY, cropCanvas.height / DPI), prev.startY + CROP_BUTTON_OFFSET)
            }));
            break;
        }
      };
    }, []);
    const initialPositionRef = hooks2.useRef({ initialX: 0, initialY: 0 });
    function onDragStart(e2) {
      if (isResizing) return;
      initialPositionRef.current = { initialX: e2.clientX, initialY: e2.clientY };
      const handleMouseMove2 = /* @__PURE__ */ __name((moveEvent) => {
        const cropCanvas = croppingRef.current;
        if (!cropCanvas) return;
        const deltaX = moveEvent.clientX - initialPositionRef.current.initialX;
        const deltaY = moveEvent.clientY - initialPositionRef.current.initialY;
        setCroppingRect((prev) => {
          const newStartX = Math.max(
            0,
            Math.min(prev.startX + deltaX, cropCanvas.width / DPI - (prev.endX - prev.startX))
          );
          const newStartY = Math.max(
            0,
            Math.min(prev.startY + deltaY, cropCanvas.height / DPI - (prev.endY - prev.startY))
          );
          const newEndX = newStartX + (prev.endX - prev.startX);
          const newEndY = newStartY + (prev.endY - prev.startY);
          initialPositionRef.current.initialX = moveEvent.clientX;
          initialPositionRef.current.initialY = moveEvent.clientY;
          return {
            startX: newStartX,
            startY: newStartY,
            endX: newEndX,
            endY: newEndY
          };
        });
      }, "handleMouseMove");
      const handleMouseUp = /* @__PURE__ */ __name(() => {
        DOCUMENT.removeEventListener("mousemove", handleMouseMove2);
        DOCUMENT.removeEventListener("mouseup", handleMouseUp);
      }, "handleMouseUp");
      DOCUMENT.addEventListener("mousemove", handleMouseMove2);
      DOCUMENT.addEventListener("mouseup", handleMouseUp);
    }
    __name(onDragStart, "onDragStart");
    function submit() {
      const cutoutCanvas = DOCUMENT.createElement("canvas");
      const imageBox = constructRect(getContainedSize(imageBuffer));
      const croppingBox = constructRect(croppingRect);
      cutoutCanvas.width = croppingBox.width * DPI;
      cutoutCanvas.height = croppingBox.height * DPI;
      const cutoutCtx = cutoutCanvas.getContext("2d");
      if (cutoutCtx && imageBuffer) {
        cutoutCtx.drawImage(
          imageBuffer,
          croppingBox.x / imageBox.width * imageBuffer.width,
          croppingBox.y / imageBox.height * imageBuffer.height,
          croppingBox.width / imageBox.width * imageBuffer.width,
          croppingBox.height / imageBox.height * imageBuffer.height,
          0,
          0,
          cutoutCanvas.width,
          cutoutCanvas.height
        );
      }
      const ctx = imageBuffer.getContext("2d");
      if (ctx) {
        ctx.clearRect(0, 0, imageBuffer.width, imageBuffer.height);
        imageBuffer.width = cutoutCanvas.width;
        imageBuffer.height = cutoutCanvas.height;
        imageBuffer.style.width = `${croppingBox.width}px`;
        imageBuffer.style.height = `${croppingBox.height}px`;
        ctx.drawImage(cutoutCanvas, 0, 0);
        resizeCropper();
      }
    }
    __name(submit, "submit");
    useTakeScreenshot({
      onBeforeScreenshot: hooks2.useCallback(() => {
        dialog.el.style.display = "none";
      }, []),
      onScreenshot: hooks2.useCallback(
        (imageSource) => {
          const context = imageBuffer.getContext("2d");
          if (!context) {
            throw new Error("Could not get canvas context");
          }
          imageBuffer.width = imageSource.videoWidth;
          imageBuffer.height = imageSource.videoHeight;
          imageBuffer.style.width = "100%";
          imageBuffer.style.height = "100%";
          context.drawImage(imageSource, 0, 0);
        },
        [imageBuffer]
      ),
      onAfterScreenshot: hooks2.useCallback(() => {
        dialog.el.style.display = "block";
        const container = canvasContainerRef.current;
        container && container.appendChild(imageBuffer);
        resizeCropper();
      }, []),
      onError: hooks2.useCallback((error2) => {
        dialog.el.style.display = "block";
        onError(error2);
      }, [])
    });
    return h2(
      "div",
      { class: "editor" },
      h2("style", { nonce: options2.styleNonce, dangerouslySetInnerHTML: styles }),
      h2(
        "div",
        { class: "editor__canvas-container", ref: canvasContainerRef },
        h2(
          "div",
          { class: "editor__crop-container", style: { position: "absolute", zIndex: 1 }, ref: cropContainerRef },
          h2(
            "canvas",
            {
              onMouseDown: onDragStart,
              style: { position: "absolute", cursor: confirmCrop ? "move" : "auto" },
              ref: croppingRef
            }
          ),
          h2(
            CropCorner,
            {
              left: croppingRect.startX - CROP_BUTTON_BORDER,
              top: croppingRect.startY - CROP_BUTTON_BORDER,
              onGrabButton,
              corner: "top-left"
            }
          ),
          h2(
            CropCorner,
            {
              left: croppingRect.endX - CROP_BUTTON_SIZE + CROP_BUTTON_BORDER,
              top: croppingRect.startY - CROP_BUTTON_BORDER,
              onGrabButton,
              corner: "top-right"
            }
          ),
          h2(
            CropCorner,
            {
              left: croppingRect.startX - CROP_BUTTON_BORDER,
              top: croppingRect.endY - CROP_BUTTON_SIZE + CROP_BUTTON_BORDER,
              onGrabButton,
              corner: "bottom-left"
            }
          ),
          h2(
            CropCorner,
            {
              left: croppingRect.endX - CROP_BUTTON_SIZE + CROP_BUTTON_BORDER,
              top: croppingRect.endY - CROP_BUTTON_SIZE + CROP_BUTTON_BORDER,
              onGrabButton,
              corner: "bottom-right"
            }
          ),
          h2(
            "div",
            {
              style: {
                left: Math.max(0, croppingRect.endX - 191),
                top: Math.max(0, croppingRect.endY + 8),
                display: confirmCrop ? "flex" : "none"
              },
              class: "editor__crop-btn-group"
            },
            h2(
              "button",
              {
                onClick: /* @__PURE__ */ __name((e2) => {
                  e2.preventDefault();
                  if (croppingRef.current) {
                    setCroppingRect({
                      startX: 0,
                      startY: 0,
                      endX: croppingRef.current.width / DPI,
                      endY: croppingRef.current.height / DPI
                    });
                  }
                  setConfirmCrop(false);
                }, "onClick"),
                class: "btn btn--default"
              },
              options2.cancelButtonLabel
            ),
            h2(
              "button",
              {
                onClick: /* @__PURE__ */ __name((e2) => {
                  e2.preventDefault();
                  submit();
                  setConfirmCrop(false);
                }, "onClick"),
                class: "btn btn--primary"
              },
              options2.confirmButtonLabel
            )
          )
        )
      )
    );
  }, "ScreenshotEditor");
}
__name(ScreenshotEditorFactory, "ScreenshotEditorFactory");
const feedbackScreenshotIntegration = /* @__PURE__ */ __name(() => {
  return {
    name: "FeedbackScreenshot",
    // eslint-disable-next-line @typescript-eslint/no-empty-function
    setupOnce() {
    },
    createInput: /* @__PURE__ */ __name(({ h: h2, hooks: hooks2, dialog, options: options2 }) => {
      const imageBuffer = DOCUMENT.createElement("canvas");
      return {
        input: ScreenshotEditorFactory({
          h: h2,
          hooks: hooks2,
          imageBuffer,
          dialog,
          options: options2
        }),
        // eslint-disable-line @typescript-eslint/no-explicit-any
        value: /* @__PURE__ */ __name(async () => {
          const blob = await new Promise((resolve2) => {
            imageBuffer.toBlob(resolve2, "image/png");
          });
          if (blob) {
            const data = new Uint8Array(await blob.arrayBuffer());
            const attachment = {
              data,
              filename: "screenshot.png",
              contentType: "application/png"
              // attachmentType?: string;
            };
            return attachment;
          }
          return void 0;
        }, "value")
      };
    }, "createInput")
  };
}, "feedbackScreenshotIntegration");
const feedbackAsyncIntegration = buildFeedbackIntegration({
  lazyLoadIntegration
});
const feedbackSyncIntegration = buildFeedbackIntegration({
  getModalIntegration: /* @__PURE__ */ __name(() => feedbackModalIntegration, "getModalIntegration"),
  getScreenshotIntegration: /* @__PURE__ */ __name(() => feedbackScreenshotIntegration, "getScreenshotIntegration")
});
function increment$2(name2, value = 1, data) {
  metrics$1.increment(BrowserMetricsAggregator, name2, value, data);
}
__name(increment$2, "increment$2");
function distribution(name2, value, data) {
  metrics$1.distribution(BrowserMetricsAggregator, name2, value, data);
}
__name(distribution, "distribution");
function set$3(name2, value, data) {
  metrics$1.set(BrowserMetricsAggregator, name2, value, data);
}
__name(set$3, "set$3");
function gauge(name2, value, data) {
  metrics$1.gauge(BrowserMetricsAggregator, name2, value, data);
}
__name(gauge, "gauge");
function timing(name2, value, unit = "second", data) {
  return metrics$1.timing(BrowserMetricsAggregator, name2, value, unit, data);
}
__name(timing, "timing");
const metrics = {
  increment: increment$2,
  distribution,
  set: set$3,
  gauge,
  timing
};
const responseToSpanId = /* @__PURE__ */ new WeakMap();
const spanIdToEndTimestamp = /* @__PURE__ */ new Map();
const defaultRequestInstrumentationOptions = {
  traceFetch: true,
  traceXHR: true,
  enableHTTPTimings: true,
  trackFetchStreamPerformance: false
};
function instrumentOutgoingRequests(client, _options) {
  const {
    traceFetch,
    traceXHR,
    trackFetchStreamPerformance,
    shouldCreateSpanForRequest,
    enableHTTPTimings,
    tracePropagationTargets
  } = {
    traceFetch: defaultRequestInstrumentationOptions.traceFetch,
    traceXHR: defaultRequestInstrumentationOptions.traceXHR,
    trackFetchStreamPerformance: defaultRequestInstrumentationOptions.trackFetchStreamPerformance,
    ..._options
  };
  const shouldCreateSpan = typeof shouldCreateSpanForRequest === "function" ? shouldCreateSpanForRequest : (_2) => true;
  const shouldAttachHeadersWithTargets = /* @__PURE__ */ __name((url) => shouldAttachHeaders(url, tracePropagationTargets), "shouldAttachHeadersWithTargets");
  const spans = {};
  if (traceFetch) {
    client.addEventProcessor((event) => {
      if (event.type === "transaction" && event.spans) {
        event.spans.forEach((span) => {
          if (span.op === "http.client") {
            const updatedTimestamp = spanIdToEndTimestamp.get(span.span_id);
            if (updatedTimestamp) {
              span.timestamp = updatedTimestamp / 1e3;
              spanIdToEndTimestamp.delete(span.span_id);
            }
          }
        });
      }
      return event;
    });
    if (trackFetchStreamPerformance) {
      addFetchEndInstrumentationHandler((handlerData) => {
        if (handlerData.response) {
          const span = responseToSpanId.get(handlerData.response);
          if (span && handlerData.endTimestamp) {
            spanIdToEndTimestamp.set(span, handlerData.endTimestamp);
          }
        }
      });
    }
    addFetchInstrumentationHandler((handlerData) => {
      const createdSpan = instrumentFetchRequest(handlerData, shouldCreateSpan, shouldAttachHeadersWithTargets, spans);
      if (handlerData.response && handlerData.fetchData.__span) {
        responseToSpanId.set(handlerData.response, handlerData.fetchData.__span);
      }
      if (createdSpan) {
        const fullUrl = getFullURL(handlerData.fetchData.url);
        const host = fullUrl ? parseUrl$1(fullUrl).host : void 0;
        createdSpan.setAttributes({
          "http.url": fullUrl,
          "server.address": host
        });
      }
      if (enableHTTPTimings && createdSpan) {
        addHTTPTimings(createdSpan);
      }
    });
  }
  if (traceXHR) {
    addXhrInstrumentationHandler((handlerData) => {
      const createdSpan = xhrCallback(handlerData, shouldCreateSpan, shouldAttachHeadersWithTargets, spans);
      if (enableHTTPTimings && createdSpan) {
        addHTTPTimings(createdSpan);
      }
    });
  }
}
__name(instrumentOutgoingRequests, "instrumentOutgoingRequests");
function isPerformanceResourceTiming(entry) {
  return entry.entryType === "resource" && "initiatorType" in entry && typeof entry.nextHopProtocol === "string" && (entry.initiatorType === "fetch" || entry.initiatorType === "xmlhttprequest");
}
__name(isPerformanceResourceTiming, "isPerformanceResourceTiming");
function addHTTPTimings(span) {
  const { url } = spanToJSON(span).data || {};
  if (!url || typeof url !== "string") {
    return;
  }
  const cleanup = addPerformanceInstrumentationHandler("resource", ({ entries }) => {
    entries.forEach((entry) => {
      if (isPerformanceResourceTiming(entry) && entry.name.endsWith(url)) {
        const spanData = resourceTimingEntryToSpanData(entry);
        spanData.forEach((data) => span.setAttribute(...data));
        setTimeout(cleanup);
      }
    });
  });
}
__name(addHTTPTimings, "addHTTPTimings");
function extractNetworkProtocol(nextHopProtocol) {
  let name2 = "unknown";
  let version2 = "unknown";
  let _name = "";
  for (const char of nextHopProtocol) {
    if (char === "/") {
      [name2, version2] = nextHopProtocol.split("/");
      break;
    }
    if (!isNaN(Number(char))) {
      name2 = _name === "h" ? "http" : _name;
      version2 = nextHopProtocol.split(_name)[1];
      break;
    }
    _name += char;
  }
  if (_name === nextHopProtocol) {
    name2 = _name;
  }
  return { name: name2, version: version2 };
}
__name(extractNetworkProtocol, "extractNetworkProtocol");
function getAbsoluteTime(time = 0) {
  return ((browserPerformanceTimeOrigin || performance.timeOrigin) + time) / 1e3;
}
__name(getAbsoluteTime, "getAbsoluteTime");
function resourceTimingEntryToSpanData(resourceTiming) {
  const { name: name2, version: version2 } = extractNetworkProtocol(resourceTiming.nextHopProtocol);
  const timingSpanData = [];
  timingSpanData.push(["network.protocol.version", version2], ["network.protocol.name", name2]);
  if (!browserPerformanceTimeOrigin) {
    return timingSpanData;
  }
  return [
    ...timingSpanData,
    ["http.request.redirect_start", getAbsoluteTime(resourceTiming.redirectStart)],
    ["http.request.fetch_start", getAbsoluteTime(resourceTiming.fetchStart)],
    ["http.request.domain_lookup_start", getAbsoluteTime(resourceTiming.domainLookupStart)],
    ["http.request.domain_lookup_end", getAbsoluteTime(resourceTiming.domainLookupEnd)],
    ["http.request.connect_start", getAbsoluteTime(resourceTiming.connectStart)],
    ["http.request.secure_connection_start", getAbsoluteTime(resourceTiming.secureConnectionStart)],
    ["http.request.connection_end", getAbsoluteTime(resourceTiming.connectEnd)],
    ["http.request.request_start", getAbsoluteTime(resourceTiming.requestStart)],
    ["http.request.response_start", getAbsoluteTime(resourceTiming.responseStart)],
    ["http.request.response_end", getAbsoluteTime(resourceTiming.responseEnd)]
  ];
}
__name(resourceTimingEntryToSpanData, "resourceTimingEntryToSpanData");
function shouldAttachHeaders(targetUrl, tracePropagationTargets) {
  const href = WINDOW$5.location && WINDOW$5.location.href;
  if (!href) {
    const isRelativeSameOriginRequest = !!targetUrl.match(/^\/(?!\/)/);
    if (!tracePropagationTargets) {
      return isRelativeSameOriginRequest;
    } else {
      return stringMatchesSomePattern(targetUrl, tracePropagationTargets);
    }
  } else {
    let resolvedUrl;
    let currentOrigin;
    try {
      resolvedUrl = new URL(targetUrl, href);
      currentOrigin = new URL(href).origin;
    } catch (e2) {
      return false;
    }
    const isSameOriginRequest = resolvedUrl.origin === currentOrigin;
    if (!tracePropagationTargets) {
      return isSameOriginRequest;
    } else {
      return stringMatchesSomePattern(resolvedUrl.toString(), tracePropagationTargets) || isSameOriginRequest && stringMatchesSomePattern(resolvedUrl.pathname, tracePropagationTargets);
    }
  }
}
__name(shouldAttachHeaders, "shouldAttachHeaders");
function xhrCallback(handlerData, shouldCreateSpan, shouldAttachHeaders2, spans) {
  const xhr = handlerData.xhr;
  const sentryXhrData = xhr && xhr[SENTRY_XHR_DATA_KEY];
  if (!xhr || xhr.__sentry_own_request__ || !sentryXhrData) {
    return void 0;
  }
  const shouldCreateSpanResult = hasTracingEnabled() && shouldCreateSpan(sentryXhrData.url);
  if (handlerData.endTimestamp && shouldCreateSpanResult) {
    const spanId = xhr.__sentry_xhr_span_id__;
    if (!spanId) return;
    const span2 = spans[spanId];
    if (span2 && sentryXhrData.status_code !== void 0) {
      setHttpStatus(span2, sentryXhrData.status_code);
      span2.end();
      delete spans[spanId];
    }
    return void 0;
  }
  const fullUrl = getFullURL(sentryXhrData.url);
  const host = fullUrl ? parseUrl$1(fullUrl).host : void 0;
  const hasParent = !!getActiveSpan();
  const span = shouldCreateSpanResult && hasParent ? startInactiveSpan({
    name: `${sentryXhrData.method} ${sentryXhrData.url}`,
    attributes: {
      type: "xhr",
      "http.method": sentryXhrData.method,
      "http.url": fullUrl,
      url: sentryXhrData.url,
      "server.address": host,
      [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.http.browser",
      [SEMANTIC_ATTRIBUTE_SENTRY_OP]: "http.client"
    }
  }) : new SentryNonRecordingSpan();
  xhr.__sentry_xhr_span_id__ = span.spanContext().spanId;
  spans[xhr.__sentry_xhr_span_id__] = span;
  if (shouldAttachHeaders2(sentryXhrData.url)) {
    addTracingHeadersToXhrRequest(
      xhr,
      // If performance is disabled (TWP) or there's no active root span (pageload/navigation/interaction),
      // we do not want to use the span as base for the trace headers,
      // which means that the headers will be generated from the scope and the sampling decision is deferred
      hasTracingEnabled() && hasParent ? span : void 0
    );
  }
  return span;
}
__name(xhrCallback, "xhrCallback");
function addTracingHeadersToXhrRequest(xhr, span) {
  const { "sentry-trace": sentryTrace, baggage } = getTraceData({ span });
  if (sentryTrace) {
    setHeaderOnXhr(xhr, sentryTrace, baggage);
  }
}
__name(addTracingHeadersToXhrRequest, "addTracingHeadersToXhrRequest");
function setHeaderOnXhr(xhr, sentryTraceHeader, sentryBaggageHeader) {
  try {
    xhr.setRequestHeader("sentry-trace", sentryTraceHeader);
    if (sentryBaggageHeader) {
      xhr.setRequestHeader("baggage", sentryBaggageHeader);
    }
  } catch (_2) {
  }
}
__name(setHeaderOnXhr, "setHeaderOnXhr");
function getFullURL(url) {
  try {
    const parsed = new URL(url, WINDOW$5.location.origin);
    return parsed.href;
  } catch (e2) {
    return void 0;
  }
}
__name(getFullURL, "getFullURL");
function registerBackgroundTabDetection() {
  if (WINDOW$5 && WINDOW$5.document) {
    WINDOW$5.document.addEventListener("visibilitychange", () => {
      const activeSpan = getActiveSpan();
      if (!activeSpan) {
        return;
      }
      const rootSpan = getRootSpan(activeSpan);
      if (WINDOW$5.document.hidden && rootSpan) {
        const cancelledStatus = "cancelled";
        const { op, status } = spanToJSON(rootSpan);
        if (DEBUG_BUILD$4) {
          logger$5.log(`[Tracing] Transaction: ${cancelledStatus} -> since tab moved to the background, op: ${op}`);
        }
        if (!status) {
          rootSpan.setStatus({ code: SPAN_STATUS_ERROR, message: cancelledStatus });
        }
        rootSpan.setAttribute("sentry.cancellation_reason", "document.hidden");
        rootSpan.end();
      }
    });
  } else {
    DEBUG_BUILD$4 && logger$5.warn("[Tracing] Could not set up background tab detection due to lack of global document");
  }
}
__name(registerBackgroundTabDetection, "registerBackgroundTabDetection");
const BROWSER_TRACING_INTEGRATION_ID = "BrowserTracing";
const DEFAULT_BROWSER_TRACING_OPTIONS = {
  ...TRACING_DEFAULTS,
  instrumentNavigation: true,
  instrumentPageLoad: true,
  markBackgroundSpan: true,
  enableLongTask: true,
  enableLongAnimationFrame: true,
  enableInp: true,
  _experiments: {},
  ...defaultRequestInstrumentationOptions
};
const browserTracingIntegration$1 = /* @__PURE__ */ __name((_options = {}) => {
  registerSpanErrorInstrumentation();
  const {
    enableInp,
    enableLongTask,
    enableLongAnimationFrame,
    _experiments: { enableInteractions, enableStandaloneClsSpans },
    beforeStartSpan,
    idleTimeout,
    finalTimeout,
    childSpanTimeout,
    markBackgroundSpan,
    traceFetch,
    traceXHR,
    trackFetchStreamPerformance,
    shouldCreateSpanForRequest,
    enableHTTPTimings,
    instrumentPageLoad,
    instrumentNavigation
  } = {
    ...DEFAULT_BROWSER_TRACING_OPTIONS,
    ..._options
  };
  const _collectWebVitals = startTrackingWebVitals({ recordClsStandaloneSpans: enableStandaloneClsSpans || false });
  if (enableInp) {
    startTrackingINP();
  }
  if (enableLongAnimationFrame && GLOBAL_OBJ.PerformanceObserver && PerformanceObserver.supportedEntryTypes && PerformanceObserver.supportedEntryTypes.includes("long-animation-frame")) {
    startTrackingLongAnimationFrames();
  } else if (enableLongTask) {
    startTrackingLongTasks();
  }
  if (enableInteractions) {
    startTrackingInteractions();
  }
  const latestRoute = {
    name: void 0,
    source: void 0
  };
  function _createRouteSpan(client, startSpanOptions) {
    const isPageloadTransaction = startSpanOptions.op === "pageload";
    const finalStartSpanOptions = beforeStartSpan ? beforeStartSpan(startSpanOptions) : startSpanOptions;
    const attributes = finalStartSpanOptions.attributes || {};
    if (startSpanOptions.name !== finalStartSpanOptions.name) {
      attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] = "custom";
      finalStartSpanOptions.attributes = attributes;
    }
    latestRoute.name = finalStartSpanOptions.name;
    latestRoute.source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];
    const idleSpan = startIdleSpan(finalStartSpanOptions, {
      idleTimeout,
      finalTimeout,
      childSpanTimeout,
      // should wait for finish signal if it's a pageload transaction
      disableAutoFinish: isPageloadTransaction,
      beforeSpanEnd: /* @__PURE__ */ __name((span) => {
        _collectWebVitals();
        addPerformanceEntries(span, { recordClsOnPageloadSpan: !enableStandaloneClsSpans });
      }, "beforeSpanEnd")
    });
    function emitFinish() {
      if (["interactive", "complete"].includes(WINDOW$5.document.readyState)) {
        client.emit("idleSpanEnableAutoFinish", idleSpan);
      }
    }
    __name(emitFinish, "emitFinish");
    if (isPageloadTransaction && WINDOW$5.document) {
      WINDOW$5.document.addEventListener("readystatechange", () => {
        emitFinish();
      });
      emitFinish();
    }
    return idleSpan;
  }
  __name(_createRouteSpan, "_createRouteSpan");
  return {
    name: BROWSER_TRACING_INTEGRATION_ID,
    afterAllSetup(client) {
      let activeSpan;
      let startingUrl = WINDOW$5.location && WINDOW$5.location.href;
      function maybeEndActiveSpan() {
        if (activeSpan && !spanToJSON(activeSpan).timestamp) {
          DEBUG_BUILD$4 && logger$5.log(`[Tracing] Finishing current active span with op: ${spanToJSON(activeSpan).op}`);
          activeSpan.end();
        }
      }
      __name(maybeEndActiveSpan, "maybeEndActiveSpan");
      client.on("startNavigationSpan", (startSpanOptions) => {
        if (getClient() !== client) {
          return;
        }
        maybeEndActiveSpan();
        activeSpan = _createRouteSpan(client, {
          op: "navigation",
          ...startSpanOptions
        });
      });
      client.on("startPageLoadSpan", (startSpanOptions, traceOptions = {}) => {
        if (getClient() !== client) {
          return;
        }
        maybeEndActiveSpan();
        const sentryTrace = traceOptions.sentryTrace || getMetaContent("sentry-trace");
        const baggage = traceOptions.baggage || getMetaContent("baggage");
        const propagationContext = propagationContextFromHeaders(sentryTrace, baggage);
        getCurrentScope().setPropagationContext(propagationContext);
        activeSpan = _createRouteSpan(client, {
          op: "pageload",
          ...startSpanOptions
        });
      });
      client.on("spanEnd", (span) => {
        const op = spanToJSON(span).op;
        if (span !== getRootSpan(span) || op !== "navigation" && op !== "pageload") {
          return;
        }
        const scope = getCurrentScope();
        const oldPropagationContext = scope.getPropagationContext();
        scope.setPropagationContext({
          ...oldPropagationContext,
          sampled: oldPropagationContext.sampled !== void 0 ? oldPropagationContext.sampled : spanIsSampled(span),
          dsc: oldPropagationContext.dsc || getDynamicSamplingContextFromSpan(span)
        });
      });
      if (WINDOW$5.location) {
        if (instrumentPageLoad) {
          startBrowserTracingPageLoadSpan(client, {
            name: WINDOW$5.location.pathname,
            // pageload should always start at timeOrigin (and needs to be in s, not ms)
            startTime: browserPerformanceTimeOrigin ? browserPerformanceTimeOrigin / 1e3 : void 0,
            attributes: {
              [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: "url",
              [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.pageload.browser"
            }
          });
        }
        if (instrumentNavigation) {
          addHistoryInstrumentationHandler(({ to, from: from2 }) => {
            if (from2 === void 0 && startingUrl && startingUrl.indexOf(to) !== -1) {
              startingUrl = void 0;
              return;
            }
            if (from2 !== to) {
              startingUrl = void 0;
              startBrowserTracingNavigationSpan(client, {
                name: WINDOW$5.location.pathname,
                attributes: {
                  [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: "url",
                  [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.navigation.browser"
                }
              });
            }
          });
        }
      }
      if (markBackgroundSpan) {
        registerBackgroundTabDetection();
      }
      if (enableInteractions) {
        registerInteractionListener(idleTimeout, finalTimeout, childSpanTimeout, latestRoute);
      }
      if (enableInp) {
        registerInpInteractionListener();
      }
      instrumentOutgoingRequests(client, {
        traceFetch,
        traceXHR,
        trackFetchStreamPerformance,
        tracePropagationTargets: client.getOptions().tracePropagationTargets,
        shouldCreateSpanForRequest,
        enableHTTPTimings
      });
    }
  };
}, "browserTracingIntegration$1");
function startBrowserTracingPageLoadSpan(client, spanOptions, traceOptions) {
  client.emit("startPageLoadSpan", spanOptions, traceOptions);
  getCurrentScope().setTransactionName(spanOptions.name);
  const span = getActiveSpan();
  const op = span && spanToJSON(span).op;
  return op === "pageload" ? span : void 0;
}
__name(startBrowserTracingPageLoadSpan, "startBrowserTracingPageLoadSpan");
function startBrowserTracingNavigationSpan(client, spanOptions) {
  getIsolationScope().setPropagationContext({ traceId: generateTraceId() });
  getCurrentScope().setPropagationContext({ traceId: generateTraceId() });
  client.emit("startNavigationSpan", spanOptions);
  getCurrentScope().setTransactionName(spanOptions.name);
  const span = getActiveSpan();
  const op = span && spanToJSON(span).op;
  return op === "navigation" ? span : void 0;
}
__name(startBrowserTracingNavigationSpan, "startBrowserTracingNavigationSpan");
function getMetaContent(metaName) {
  const metaTag = getDomElement(`meta[name=${metaName}]`);
  return metaTag ? metaTag.getAttribute("content") : void 0;
}
__name(getMetaContent, "getMetaContent");
function registerInteractionListener(idleTimeout, finalTimeout, childSpanTimeout, latestRoute) {
  let inflightInteractionSpan;
  const registerInteractionTransaction = /* @__PURE__ */ __name(() => {
    const op = "ui.action.click";
    const activeSpan = getActiveSpan();
    const rootSpan = activeSpan && getRootSpan(activeSpan);
    if (rootSpan) {
      const currentRootSpanOp = spanToJSON(rootSpan).op;
      if (["navigation", "pageload"].includes(currentRootSpanOp)) {
        DEBUG_BUILD$4 && logger$5.warn(`[Tracing] Did not create ${op} span because a pageload or navigation span is in progress.`);
        return void 0;
      }
    }
    if (inflightInteractionSpan) {
      inflightInteractionSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON, "interactionInterrupted");
      inflightInteractionSpan.end();
      inflightInteractionSpan = void 0;
    }
    if (!latestRoute.name) {
      DEBUG_BUILD$4 && logger$5.warn(`[Tracing] Did not create ${op} transaction because _latestRouteName is missing.`);
      return void 0;
    }
    inflightInteractionSpan = startIdleSpan(
      {
        name: latestRoute.name,
        op,
        attributes: {
          [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: latestRoute.source || "url"
        }
      },
      {
        idleTimeout,
        finalTimeout,
        childSpanTimeout
      }
    );
  }, "registerInteractionTransaction");
  if (WINDOW$5.document) {
    addEventListener("click", registerInteractionTransaction, { once: false, capture: true });
  }
}
__name(registerInteractionListener, "registerInteractionListener");
function promisifyRequest$1(request) {
  return new Promise((resolve2, reject) => {
    request.oncomplete = request.onsuccess = () => resolve2(request.result);
    request.onabort = request.onerror = () => reject(request.error);
  });
}
__name(promisifyRequest$1, "promisifyRequest$1");
function createStore(dbName, storeName) {
  const request = indexedDB.open(dbName);
  request.onupgradeneeded = () => request.result.createObjectStore(storeName);
  const dbp = promisifyRequest$1(request);
  return (callback) => dbp.then((db) => callback(db.transaction(storeName, "readwrite").objectStore(storeName)));
}
__name(createStore, "createStore");
function keys$7(store) {
  return promisifyRequest$1(store.getAllKeys());
}
__name(keys$7, "keys$7");
function push$1(store, value, maxQueueSize) {
  return store((store2) => {
    return keys$7(store2).then((keys2) => {
      if (keys2.length >= maxQueueSize) {
        return;
      }
      store2.put(value, Math.max(...keys2, 0) + 1);
      return promisifyRequest$1(store2.transaction);
    });
  });
}
__name(push$1, "push$1");
function unshift(store, value, maxQueueSize) {
  return store((store2) => {
    return keys$7(store2).then((keys2) => {
      if (keys2.length >= maxQueueSize) {
        return;
      }
      store2.put(value, Math.min(...keys2, 0) - 1);
      return promisifyRequest$1(store2.transaction);
    });
  });
}
__name(unshift, "unshift");
function shift$1(store) {
  return store((store2) => {
    return keys$7(store2).then((keys2) => {
      const firstKey = keys2[0];
      if (firstKey == null) {
        return void 0;
      }
      return promisifyRequest$1(store2.get(firstKey)).then((value) => {
        store2.delete(firstKey);
        return promisifyRequest$1(store2.transaction).then(() => value);
      });
    });
  });
}
__name(shift$1, "shift$1");
function createIndexedDbStore(options2) {
  let store;
  function getStore() {
    if (store == void 0) {
      store = createStore(options2.dbName || "sentry-offline", options2.storeName || "queue");
    }
    return store;
  }
  __name(getStore, "getStore");
  return {
    push: /* @__PURE__ */ __name(async (env) => {
      try {
        const serialized = await serializeEnvelope(env);
        await push$1(getStore(), serialized, options2.maxQueueSize || 30);
      } catch (_2) {
      }
    }, "push"),
    unshift: /* @__PURE__ */ __name(async (env) => {
      try {
        const serialized = await serializeEnvelope(env);
        await unshift(getStore(), serialized, options2.maxQueueSize || 30);
      } catch (_2) {
      }
    }, "unshift"),
    shift: /* @__PURE__ */ __name(async () => {
      try {
        const deserialized = await shift$1(getStore());
        if (deserialized) {
          return parseEnvelope(deserialized);
        }
      } catch (_2) {
      }
      return void 0;
    }, "shift")
  };
}
__name(createIndexedDbStore, "createIndexedDbStore");
function makeIndexedDbOfflineTransport(createTransport2) {
  return (options2) => createTransport2({ ...options2, createStore: createIndexedDbStore });
}
__name(makeIndexedDbOfflineTransport, "makeIndexedDbOfflineTransport");
function makeBrowserOfflineTransport(createTransport2 = makeFetchTransport) {
  return makeIndexedDbOfflineTransport(makeOfflineTransport(createTransport2));
}
__name(makeBrowserOfflineTransport, "makeBrowserOfflineTransport");
const MS_TO_NS = 1e6;
const THREAD_ID_STRING = String(0);
const THREAD_NAME = "main";
let OS_PLATFORM = "";
let OS_PLATFORM_VERSION = "";
let OS_ARCH = "";
let OS_BROWSER = WINDOW$5.navigator && WINDOW$5.navigator.userAgent || "";
let OS_MODEL = "";
const OS_LOCALE = WINDOW$5.navigator && WINDOW$5.navigator.language || WINDOW$5.navigator && WINDOW$5.navigator.languages && WINDOW$5.navigator.languages[0] || "";
function isUserAgentData(data) {
  return typeof data === "object" && data !== null && "getHighEntropyValues" in data;
}
__name(isUserAgentData, "isUserAgentData");
const userAgentData = WINDOW$5.navigator && WINDOW$5.navigator.userAgentData;
if (isUserAgentData(userAgentData)) {
  userAgentData.getHighEntropyValues(["architecture", "model", "platform", "platformVersion", "fullVersionList"]).then((ua) => {
    OS_PLATFORM = ua.platform || "";
    OS_ARCH = ua.architecture || "";
    OS_MODEL = ua.model || "";
    OS_PLATFORM_VERSION = ua.platformVersion || "";
    if (ua.fullVersionList && ua.fullVersionList.length > 0) {
      const firstUa = ua.fullVersionList[ua.fullVersionList.length - 1];
      OS_BROWSER = `${firstUa.brand} ${firstUa.version}`;
    }
  }).catch((e2) => void 0);
}
function isProcessedJSSelfProfile(profile) {
  return !("thread_metadata" in profile);
}
__name(isProcessedJSSelfProfile, "isProcessedJSSelfProfile");
function enrichWithThreadInformation(profile) {
  if (!isProcessedJSSelfProfile(profile)) {
    return profile;
  }
  return convertJSSelfProfileToSampledFormat(profile);
}
__name(enrichWithThreadInformation, "enrichWithThreadInformation");
function getTraceId(event) {
  const traceId = event && event.contexts && event.contexts["trace"] && event.contexts["trace"]["trace_id"];
  if (typeof traceId === "string" && traceId.length !== 32) {
    if (DEBUG_BUILD$4) {
      logger$5.log(`[Profiling] Invalid traceId: ${traceId} on profiled event`);
    }
  }
  if (typeof traceId !== "string") {
    return "";
  }
  return traceId;
}
__name(getTraceId, "getTraceId");
function createProfilePayload(profile_id, start_timestamp, processed_profile, event) {
  if (event.type !== "transaction") {
    throw new TypeError("Profiling events may only be attached to transactions, this should never occur.");
  }
  if (processed_profile === void 0 || processed_profile === null) {
    throw new TypeError(
      `Cannot construct profiling event envelope without a valid profile. Got ${processed_profile} instead.`
    );
  }
  const traceId = getTraceId(event);
  const enrichedThreadProfile = enrichWithThreadInformation(processed_profile);
  const transactionStartMs = start_timestamp ? start_timestamp : typeof event.start_timestamp === "number" ? event.start_timestamp * 1e3 : timestampInSeconds() * 1e3;
  const transactionEndMs = typeof event.timestamp === "number" ? event.timestamp * 1e3 : timestampInSeconds() * 1e3;
  const profile = {
    event_id: profile_id,
    timestamp: new Date(transactionStartMs).toISOString(),
    platform: "javascript",
    version: "1",
    release: event.release || "",
    environment: event.environment || DEFAULT_ENVIRONMENT,
    runtime: {
      name: "javascript",
      version: WINDOW$5.navigator.userAgent
    },
    os: {
      name: OS_PLATFORM,
      version: OS_PLATFORM_VERSION,
      build_number: OS_BROWSER
    },
    device: {
      locale: OS_LOCALE,
      model: OS_MODEL,
      manufacturer: OS_BROWSER,
      architecture: OS_ARCH,
      is_emulator: false
    },
    debug_meta: {
      images: applyDebugMetadata(processed_profile.resources)
    },
    profile: enrichedThreadProfile,
    transactions: [
      {
        name: event.transaction || "",
        id: event.event_id || uuid4(),
        trace_id: traceId,
        active_thread_id: THREAD_ID_STRING,
        relative_start_ns: "0",
        relative_end_ns: ((transactionEndMs - transactionStartMs) * 1e6).toFixed(0)
      }
    ]
  };
  return profile;
}
__name(createProfilePayload, "createProfilePayload");
function isAutomatedPageLoadSpan(span) {
  return spanToJSON(span).op === "pageload";
}
__name(isAutomatedPageLoadSpan, "isAutomatedPageLoadSpan");
function convertJSSelfProfileToSampledFormat(input) {
  let EMPTY_STACK_ID = void 0;
  let STACK_ID = 0;
  const profile = {
    samples: [],
    stacks: [],
    frames: [],
    thread_metadata: {
      [THREAD_ID_STRING]: { name: THREAD_NAME }
    }
  };
  const firstSample = input.samples[0];
  if (!firstSample) {
    return profile;
  }
  const start2 = firstSample.timestamp;
  const origin2 = typeof performance.timeOrigin === "number" ? performance.timeOrigin : browserPerformanceTimeOrigin || 0;
  const adjustForOriginChange = origin2 - (browserPerformanceTimeOrigin || origin2);
  input.samples.forEach((jsSample, i2) => {
    if (jsSample.stackId === void 0) {
      if (EMPTY_STACK_ID === void 0) {
        EMPTY_STACK_ID = STACK_ID;
        profile.stacks[EMPTY_STACK_ID] = [];
        STACK_ID++;
      }
      profile["samples"][i2] = {
        // convert ms timestamp to ns
        elapsed_since_start_ns: ((jsSample.timestamp + adjustForOriginChange - start2) * MS_TO_NS).toFixed(0),
        stack_id: EMPTY_STACK_ID,
        thread_id: THREAD_ID_STRING
      };
      return;
    }
    let stackTop = input.stacks[jsSample.stackId];
    const stack = [];
    while (stackTop) {
      stack.push(stackTop.frameId);
      const frame = input.frames[stackTop.frameId];
      if (frame && profile.frames[stackTop.frameId] === void 0) {
        profile.frames[stackTop.frameId] = {
          function: frame.name,
          abs_path: typeof frame.resourceId === "number" ? input.resources[frame.resourceId] : void 0,
          lineno: frame.line,
          colno: frame.column
        };
      }
      stackTop = stackTop.parentId === void 0 ? void 0 : input.stacks[stackTop.parentId];
    }
    const sample = {
      // convert ms timestamp to ns
      elapsed_since_start_ns: ((jsSample.timestamp + adjustForOriginChange - start2) * MS_TO_NS).toFixed(0),
      stack_id: STACK_ID,
      thread_id: THREAD_ID_STRING
    };
    profile["stacks"][STACK_ID] = stack;
    profile["samples"][i2] = sample;
    STACK_ID++;
  });
  return profile;
}
__name(convertJSSelfProfileToSampledFormat, "convertJSSelfProfileToSampledFormat");
function addProfilesToEnvelope(envelope, profiles) {
  if (!profiles.length) {
    return envelope;
  }
  for (const profile of profiles) {
    envelope[1].push([{ type: "profile" }, profile]);
  }
  return envelope;
}
__name(addProfilesToEnvelope, "addProfilesToEnvelope");
function findProfiledTransactionsFromEnvelope(envelope) {
  const events2 = [];
  forEachEnvelopeItem(envelope, (item, type) => {
    if (type !== "transaction") {
      return;
    }
    for (let j2 = 1; j2 < item.length; j2++) {
      const event = item[j2];
      if (event && event.contexts && event.contexts["profile"] && event.contexts["profile"]["profile_id"]) {
        events2.push(item[j2]);
      }
    }
  });
  return events2;
}
__name(findProfiledTransactionsFromEnvelope, "findProfiledTransactionsFromEnvelope");
function applyDebugMetadata(resource_paths) {
  const client = getClient();
  const options2 = client && client.getOptions();
  const stackParser = options2 && options2.stackParser;
  if (!stackParser) {
    return [];
  }
  return getDebugImagesForResources(stackParser, resource_paths);
}
__name(applyDebugMetadata, "applyDebugMetadata");
function isValidSampleRate(rate) {
  if (typeof rate !== "number" && typeof rate !== "boolean" || typeof rate === "number" && isNaN(rate)) {
    DEBUG_BUILD$4 && logger$5.warn(
      `[Profiling] Invalid sample rate. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(
        rate
      )} of type ${JSON.stringify(typeof rate)}.`
    );
    return false;
  }
  if (rate === true || rate === false) {
    return true;
  }
  if (rate < 0 || rate > 1) {
    DEBUG_BUILD$4 && logger$5.warn(`[Profiling] Invalid sample rate. Sample rate must be between 0 and 1. Got ${rate}.`);
    return false;
  }
  return true;
}
__name(isValidSampleRate, "isValidSampleRate");
function isValidProfile(profile) {
  if (profile.samples.length < 2) {
    if (DEBUG_BUILD$4) {
      logger$5.log("[Profiling] Discarding profile because it contains less than 2 samples");
    }
    return false;
  }
  if (!profile.frames.length) {
    if (DEBUG_BUILD$4) {
      logger$5.log("[Profiling] Discarding profile because it contains no frames");
    }
    return false;
  }
  return true;
}
__name(isValidProfile, "isValidProfile");
let PROFILING_CONSTRUCTOR_FAILED = false;
const MAX_PROFILE_DURATION_MS = 3e4;
function isJSProfilerSupported(maybeProfiler) {
  return typeof maybeProfiler === "function";
}
__name(isJSProfilerSupported, "isJSProfilerSupported");
function startJSSelfProfile() {
  const JSProfilerConstructor = WINDOW$5.Profiler;
  if (!isJSProfilerSupported(JSProfilerConstructor)) {
    if (DEBUG_BUILD$4) {
      logger$5.log(
        "[Profiling] Profiling is not supported by this browser, Profiler interface missing on window object."
      );
    }
    return;
  }
  const samplingIntervalMS = 10;
  const maxSamples = Math.floor(MAX_PROFILE_DURATION_MS / samplingIntervalMS);
  try {
    return new JSProfilerConstructor({ sampleInterval: samplingIntervalMS, maxBufferSize: maxSamples });
  } catch (e2) {
    if (DEBUG_BUILD$4) {
      logger$5.log(
        "[Profiling] Failed to initialize the Profiling constructor, this is likely due to a missing 'Document-Policy': 'js-profiling' header."
      );
      logger$5.log("[Profiling] Disabling profiling for current user session.");
    }
    PROFILING_CONSTRUCTOR_FAILED = true;
  }
  return;
}
__name(startJSSelfProfile, "startJSSelfProfile");
function shouldProfileSpan(span) {
  if (PROFILING_CONSTRUCTOR_FAILED) {
    if (DEBUG_BUILD$4) {
      logger$5.log("[Profiling] Profiling has been disabled for the duration of the current user session.");
    }
    return false;
  }
  if (!span.isRecording()) {
    if (DEBUG_BUILD$4) {
      logger$5.log("[Profiling] Discarding profile because transaction was not sampled.");
    }
    return false;
  }
  const client = getClient();
  const options2 = client && client.getOptions();
  if (!options2) {
    DEBUG_BUILD$4 && logger$5.log("[Profiling] Profiling disabled, no options found.");
    return false;
  }
  const profilesSampleRate = options2.profilesSampleRate;
  if (!isValidSampleRate(profilesSampleRate)) {
    DEBUG_BUILD$4 && logger$5.warn("[Profiling] Discarding profile because of invalid sample rate.");
    return false;
  }
  if (!profilesSampleRate) {
    DEBUG_BUILD$4 && logger$5.log(
      "[Profiling] Discarding profile because a negative sampling decision was inherited or profileSampleRate is set to 0"
    );
    return false;
  }
  const sampled = profilesSampleRate === true ? true : Math.random() < profilesSampleRate;
  if (!sampled) {
    DEBUG_BUILD$4 && logger$5.log(
      `[Profiling] Discarding profile because it's not included in the random sample (sampling rate = ${Number(
        profilesSampleRate
      )})`
    );
    return false;
  }
  return true;
}
__name(shouldProfileSpan, "shouldProfileSpan");
function createProfilingEvent(profile_id, start_timestamp, profile, event) {
  if (!isValidProfile(profile)) {
    return null;
  }
  return createProfilePayload(profile_id, start_timestamp, profile, event);
}
__name(createProfilingEvent, "createProfilingEvent");
const PROFILE_MAP = /* @__PURE__ */ new Map();
function getActiveProfilesCount() {
  return PROFILE_MAP.size;
}
__name(getActiveProfilesCount, "getActiveProfilesCount");
function takeProfileFromGlobalCache(profile_id) {
  const profile = PROFILE_MAP.get(profile_id);
  if (profile) {
    PROFILE_MAP.delete(profile_id);
  }
  return profile;
}
__name(takeProfileFromGlobalCache, "takeProfileFromGlobalCache");
function addProfileToGlobalCache(profile_id, profile) {
  PROFILE_MAP.set(profile_id, profile);
  if (PROFILE_MAP.size > 30) {
    const last = PROFILE_MAP.keys().next().value;
    PROFILE_MAP.delete(last);
  }
}
__name(addProfileToGlobalCache, "addProfileToGlobalCache");
function startProfileForSpan(span) {
  let startTimestamp;
  if (isAutomatedPageLoadSpan(span)) {
    startTimestamp = timestampInSeconds() * 1e3;
  }
  const profiler2 = startJSSelfProfile();
  if (!profiler2) {
    return;
  }
  if (DEBUG_BUILD$4) {
    logger$5.log(`[Profiling] started profiling span: ${spanToJSON(span).description}`);
  }
  const profileId = uuid4();
  getCurrentScope().setContext("profile", {
    profile_id: profileId,
    start_timestamp: startTimestamp
  });
  async function onProfileHandler() {
    if (!span) {
      return;
    }
    if (!profiler2) {
      return;
    }
    return profiler2.stop().then((profile) => {
      if (maxDurationTimeoutID) {
        WINDOW$5.clearTimeout(maxDurationTimeoutID);
        maxDurationTimeoutID = void 0;
      }
      if (DEBUG_BUILD$4) {
        logger$5.log(`[Profiling] stopped profiling of span: ${spanToJSON(span).description}`);
      }
      if (!profile) {
        if (DEBUG_BUILD$4) {
          logger$5.log(
            `[Profiling] profiler returned null profile for: ${spanToJSON(span).description}`,
            "this may indicate an overlapping span or a call to stopProfiling with a profile title that was never started"
          );
        }
        return;
      }
      addProfileToGlobalCache(profileId, profile);
    }).catch((error2) => {
      if (DEBUG_BUILD$4) {
        logger$5.log("[Profiling] error while stopping profiler:", error2);
      }
    });
  }
  __name(onProfileHandler, "onProfileHandler");
  let maxDurationTimeoutID = WINDOW$5.setTimeout(() => {
    if (DEBUG_BUILD$4) {
      logger$5.log("[Profiling] max profile duration elapsed, stopping profiling for:", spanToJSON(span).description);
    }
    onProfileHandler();
  }, MAX_PROFILE_DURATION_MS);
  const originalEnd = span.end.bind(span);
  function profilingWrappedSpanEnd() {
    if (!span) {
      return originalEnd();
    }
    void onProfileHandler().then(
      () => {
        originalEnd();
      },
      () => {
        originalEnd();
      }
    );
    return span;
  }
  __name(profilingWrappedSpanEnd, "profilingWrappedSpanEnd");
  span.end = profilingWrappedSpanEnd;
}
__name(startProfileForSpan, "startProfileForSpan");
const INTEGRATION_NAME$2 = "BrowserProfiling";
const _browserProfilingIntegration = /* @__PURE__ */ __name(() => {
  return {
    name: INTEGRATION_NAME$2,
    setup(client) {
      const activeSpan = getActiveSpan();
      const rootSpan = activeSpan && getRootSpan(activeSpan);
      if (rootSpan && isAutomatedPageLoadSpan(rootSpan)) {
        if (shouldProfileSpan(rootSpan)) {
          startProfileForSpan(rootSpan);
        }
      }
      client.on("spanStart", (span) => {
        if (span === getRootSpan(span) && shouldProfileSpan(span)) {
          startProfileForSpan(span);
        }
      });
      client.on("beforeEnvelope", (envelope) => {
        if (!getActiveProfilesCount()) {
          return;
        }
        const profiledTransactionEvents = findProfiledTransactionsFromEnvelope(envelope);
        if (!profiledTransactionEvents.length) {
          return;
        }
        const profilesToAddToEnvelope = [];
        for (const profiledTransaction of profiledTransactionEvents) {
          const context = profiledTransaction && profiledTransaction.contexts;
          const profile_id = context && context["profile"] && context["profile"]["profile_id"];
          const start_timestamp = context && context["profile"] && context["profile"]["start_timestamp"];
          if (typeof profile_id !== "string") {
            DEBUG_BUILD$4 && logger$5.log("[Profiling] cannot find profile for a span without a profile context");
            continue;
          }
          if (!profile_id) {
            DEBUG_BUILD$4 && logger$5.log("[Profiling] cannot find profile for a span without a profile context");
            continue;
          }
          if (context && context["profile"]) {
            delete context.profile;
          }
          const profile = takeProfileFromGlobalCache(profile_id);
          if (!profile) {
            DEBUG_BUILD$4 && logger$5.log(`[Profiling] Could not retrieve profile for span: ${profile_id}`);
            continue;
          }
          const profileEvent = createProfilingEvent(
            profile_id,
            start_timestamp,
            profile,
            profiledTransaction
          );
          if (profileEvent) {
            profilesToAddToEnvelope.push(profileEvent);
          }
        }
        addProfilesToEnvelope(envelope, profilesToAddToEnvelope);
      });
    }
  };
}, "_browserProfilingIntegration");
const browserProfilingIntegration = defineIntegration(_browserProfilingIntegration);
const INTEGRATION_NAME$1 = "SpotlightBrowser";
const _spotlightIntegration = /* @__PURE__ */ __name((options2 = {}) => {
  const sidecarUrl = options2.sidecarUrl || "http://localhost:8969/stream";
  return {
    name: INTEGRATION_NAME$1,
    setup: /* @__PURE__ */ __name(() => {
      DEBUG_BUILD$4 && logger$5.log("Using Sidecar URL", sidecarUrl);
    }, "setup"),
    // We don't want to send interaction transactions/root spans created from
    // clicks within Spotlight to Sentry. Neither do we want them to be sent to
    // spotlight.
    processEvent: /* @__PURE__ */ __name((event) => isSpotlightInteraction(event) ? null : event, "processEvent"),
    afterAllSetup: /* @__PURE__ */ __name((client) => {
      setupSidecarForwarding(client, sidecarUrl);
    }, "afterAllSetup")
  };
}, "_spotlightIntegration");
function setupSidecarForwarding(client, sidecarUrl) {
  const makeFetch = getNativeImplementation("fetch");
  let failCount = 0;
  client.on("beforeEnvelope", (envelope) => {
    if (failCount > 3) {
      logger$5.warn("[Spotlight] Disabled Sentry -> Spotlight integration due to too many failed requests:", failCount);
      return;
    }
    makeFetch(sidecarUrl, {
      method: "POST",
      body: serializeEnvelope(envelope),
      headers: {
        "Content-Type": "application/x-sentry-envelope"
      },
      mode: "cors"
    }).then(
      (res) => {
        if (res.status >= 200 && res.status < 400) {
          failCount = 0;
        }
      },
      (err) => {
        failCount++;
        logger$5.error(
          "Sentry SDK can't connect to Sidecar is it running? See: https://spotlightjs.com/sidecar/npx/",
          err
        );
      }
    );
  });
}
__name(setupSidecarForwarding, "setupSidecarForwarding");
const spotlightBrowserIntegration = defineIntegration(_spotlightIntegration);
function isSpotlightInteraction(event) {
  return Boolean(
    event.type === "transaction" && event.spans && event.contexts && event.contexts.trace && event.contexts.trace.op === "ui.action.click" && event.spans.some(({ description }) => description && description.includes("#sentry-spotlight"))
  );
}
__name(isSpotlightInteraction, "isSpotlightInteraction");
const FLAG_BUFFER_SIZE = 100;
function copyFlagsFromScopeToEvent(event) {
  const scope = getCurrentScope();
  const flagContext = scope.getScopeData().contexts.flags;
  const flagBuffer = flagContext ? flagContext.values : [];
  if (!flagBuffer.length) {
    return event;
  }
  if (event.contexts === void 0) {
    event.contexts = {};
  }
  event.contexts.flags = { values: [...flagBuffer] };
  return event;
}
__name(copyFlagsFromScopeToEvent, "copyFlagsFromScopeToEvent");
function insertFlagToScope(name2, value, maxSize = FLAG_BUFFER_SIZE) {
  const scopeContexts = getCurrentScope().getScopeData().contexts;
  if (!scopeContexts.flags) {
    scopeContexts.flags = { values: [] };
  }
  const flags = scopeContexts.flags.values;
  insertToFlagBuffer(flags, name2, value, maxSize);
}
__name(insertFlagToScope, "insertFlagToScope");
function insertToFlagBuffer(flags, name2, value, maxSize) {
  if (typeof value !== "boolean") {
    return;
  }
  if (flags.length > maxSize) {
    DEBUG_BUILD$4 && logger$5.error(`[Feature Flags] insertToFlagBuffer called on a buffer larger than maxSize=${maxSize}`);
    return;
  }
  const index2 = flags.findIndex((f2) => f2.flag === name2);
  if (index2 !== -1) {
    flags.splice(index2, 1);
  }
  if (flags.length === maxSize) {
    flags.shift();
  }
  flags.push({
    flag: name2,
    result: value
  });
}
__name(insertToFlagBuffer, "insertToFlagBuffer");
const featureFlagsIntegration = defineIntegration(() => {
  return {
    name: "FeatureFlags",
    processEvent(event, _hint, _client) {
      return copyFlagsFromScopeToEvent(event);
    },
    addFeatureFlag(name2, value) {
      insertFlagToScope(name2, value);
    }
  };
});
const launchDarklyIntegration = defineIntegration(() => {
  return {
    name: "LaunchDarkly",
    processEvent(event, _hint, _client) {
      return copyFlagsFromScopeToEvent(event);
    }
  };
});
function buildLaunchDarklyFlagUsedHandler() {
  return {
    name: "sentry-flag-auditor",
    type: "flag-used",
    synchronous: true,
    /**
     * Handle a flag evaluation by storing its name and value on the current scope.
     */
    method: /* @__PURE__ */ __name((flagKey, flagDetail, _context) => {
      insertFlagToScope(flagKey, flagDetail.value);
    }, "method")
  };
}
__name(buildLaunchDarklyFlagUsedHandler, "buildLaunchDarklyFlagUsedHandler");
const openFeatureIntegration = defineIntegration(() => {
  return {
    name: "OpenFeature",
    processEvent(event, _hint, _client) {
      return copyFlagsFromScopeToEvent(event);
    }
  };
});
class OpenFeatureIntegrationHook {
  static {
    __name(this, "OpenFeatureIntegrationHook");
  }
  /**
   * Successful evaluation result.
   */
  after(_hookContext, evaluationDetails) {
    insertFlagToScope(evaluationDetails.flagKey, evaluationDetails.value);
  }
  /**
   * On error evaluation result.
   */
  error(hookContext, _error, _hookHints) {
    insertFlagToScope(hookContext.flagKey, hookContext.defaultValue);
  }
}
const DEFAULT_HOOKS = ["activate", "mount", "update"];
const DEBUG_BUILD = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__;
const classifyRE = /(?:^|[-_])(\w)/g;
const classify = /* @__PURE__ */ __name((str) => str.replace(classifyRE, (c2) => c2.toUpperCase()).replace(/[-_]/g, ""), "classify");
const ROOT_COMPONENT_NAME = "<Root>";
const ANONYMOUS_COMPONENT_NAME = "<Anonymous>";
const repeat = /* @__PURE__ */ __name((str, n2) => {
  return str.repeat(n2);
}, "repeat");
const formatComponentName = /* @__PURE__ */ __name((vm, includeFile) => {
  if (!vm) {
    return ANONYMOUS_COMPONENT_NAME;
  }
  if (vm.$root === vm) {
    return ROOT_COMPONENT_NAME;
  }
  if (!vm.$options) {
    return ANONYMOUS_COMPONENT_NAME;
  }
  const options2 = vm.$options;
  let name2 = options2.name || options2._componentTag || options2.__name;
  const file = options2.__file;
  if (!name2 && file) {
    const match2 = file.match(/([^/\\]+)\.vue$/);
    if (match2) {
      name2 = match2[1];
    }
  }
  return (name2 ? `<${classify(name2)}>` : ANONYMOUS_COMPONENT_NAME) + (file && includeFile !== false ? ` at ${file}` : "");
}, "formatComponentName");
const generateComponentTrace = /* @__PURE__ */ __name((vm) => {
  if (vm && (vm._isVue || vm.__isVue) && vm.$parent) {
    const tree = [];
    let currentRecursiveSequence = 0;
    while (vm) {
      if (tree.length > 0) {
        const last = tree[tree.length - 1];
        if (last.constructor === vm.constructor) {
          currentRecursiveSequence++;
          vm = vm.$parent;
          continue;
        } else if (currentRecursiveSequence > 0) {
          tree[tree.length - 1] = [last, currentRecursiveSequence];
          currentRecursiveSequence = 0;
        }
      }
      tree.push(vm);
      vm = vm.$parent;
    }
    const formattedTree = tree.map(
      (vm2, i2) => `${(i2 === 0 ? "---> " : repeat(" ", 5 + i2 * 2)) + (Array.isArray(vm2) ? `${formatComponentName(vm2[0])}... (${vm2[1]} recursive calls)` : formatComponentName(vm2))}`
    ).join("\n");
    return `

found in

${formattedTree}`;
  }
  return `

(found in ${formatComponentName(vm)})`;
}, "generateComponentTrace");
const attachErrorHandler = /* @__PURE__ */ __name((app2, options2) => {
  const { errorHandler: originalErrorHandler, warnHandler, silent } = app2.config;
  app2.config.errorHandler = (error2, vm, lifecycleHook) => {
    const componentName = formatComponentName(vm, false);
    const trace = vm ? generateComponentTrace(vm) : "";
    const metadata = {
      componentName,
      lifecycleHook,
      trace
    };
    if (options2.attachProps && vm) {
      if (vm.$options && vm.$options.propsData) {
        metadata.propsData = vm.$options.propsData;
      } else if (vm.$props) {
        metadata.propsData = vm.$props;
      }
    }
    setTimeout(() => {
      captureException(error2, {
        captureContext: { contexts: { vue: metadata } },
        mechanism: { handled: false }
      });
    });
    if (typeof originalErrorHandler === "function" && app2.config.errorHandler) {
      originalErrorHandler.call(app2, error2, vm, lifecycleHook);
    }
    if (options2.logErrors) {
      const hasConsole = typeof console !== "undefined";
      const message = `Error in ${lifecycleHook}: "${error2 && error2.toString()}"`;
      if (warnHandler) {
        warnHandler.call(null, message, vm, trace);
      } else if (hasConsole && !silent) {
        consoleSandbox(() => {
          console.error(`[Vue warn]: ${message}${trace}`);
        });
      }
    }
  };
}, "attachErrorHandler");
const VUE_OP = "ui.vue";
const HOOKS = {
  activate: ["activated", "deactivated"],
  create: ["beforeCreate", "created"],
  // Vue 3
  unmount: ["beforeUnmount", "unmounted"],
  // Vue 2
  destroy: ["beforeDestroy", "destroyed"],
  mount: ["beforeMount", "mounted"],
  update: ["beforeUpdate", "updated"]
};
function finishRootSpan(vm, timestamp2, timeout) {
  if (vm.$_sentryRootSpanTimer) {
    clearTimeout(vm.$_sentryRootSpanTimer);
  }
  vm.$_sentryRootSpanTimer = setTimeout(() => {
    if (vm.$root && vm.$root.$_sentryRootSpan) {
      vm.$root.$_sentryRootSpan.end(timestamp2);
      vm.$root.$_sentryRootSpan = void 0;
    }
  }, timeout);
}
__name(finishRootSpan, "finishRootSpan");
function findTrackComponent(trackComponents, formattedName) {
  function extractComponentName(name2) {
    return name2.replace(/^<([^\s]*)>(?: at [^\s]*)?$/, "$1");
  }
  __name(extractComponentName, "extractComponentName");
  const isMatched = trackComponents.some((compo) => {
    return extractComponentName(formattedName) === extractComponentName(compo);
  });
  return isMatched;
}
__name(findTrackComponent, "findTrackComponent");
const createTracingMixins = /* @__PURE__ */ __name((options2) => {
  const hooks2 = (options2.hooks || []).concat(DEFAULT_HOOKS).filter((value, index2, self2) => self2.indexOf(value) === index2);
  const mixins = {};
  for (const operation of hooks2) {
    const internalHooks = HOOKS[operation];
    if (!internalHooks) {
      DEBUG_BUILD && logger$5.warn(`Unknown hook: ${operation}`);
      continue;
    }
    for (const internalHook of internalHooks) {
      mixins[internalHook] = function() {
        const isRoot = this.$root === this;
        if (isRoot) {
          this.$_sentryRootSpan = this.$_sentryRootSpan || startInactiveSpan({
            name: "Application Render",
            op: `${VUE_OP}.render`,
            attributes: {
              [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.ui.vue"
            },
            onlyIfParent: true
          });
        }
        const name2 = formatComponentName(this, false);
        const shouldTrack = Array.isArray(options2.trackComponents) ? findTrackComponent(options2.trackComponents, name2) : options2.trackComponents;
        if (!isRoot && !shouldTrack) {
          return;
        }
        this.$_sentrySpans = this.$_sentrySpans || {};
        if (internalHook == internalHooks[0]) {
          const activeSpan = this.$root && this.$root.$_sentryRootSpan || getActiveSpan();
          if (activeSpan) {
            const oldSpan = this.$_sentrySpans[operation];
            if (oldSpan) {
              oldSpan.end();
            }
            this.$_sentrySpans[operation] = startInactiveSpan({
              name: `Vue ${name2}`,
              op: `${VUE_OP}.${operation}`,
              attributes: {
                [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.ui.vue"
              },
              // UI spans should only be created if there is an active root span (transaction)
              onlyIfParent: true
            });
          }
        } else {
          const span = this.$_sentrySpans[operation];
          if (!span) return;
          span.end();
          finishRootSpan(this, timestampInSeconds(), options2.timeout);
        }
      };
    }
  }
  return mixins;
}, "createTracingMixins");
const globalWithVue = GLOBAL_OBJ;
const DEFAULT_CONFIG = {
  Vue: globalWithVue.Vue,
  attachProps: true,
  logErrors: true,
  attachErrorHandler: true,
  hooks: DEFAULT_HOOKS,
  timeout: 2e3,
  trackComponents: false
};
const INTEGRATION_NAME = "Vue";
const vueIntegration = defineIntegration((integrationOptions = {}) => {
  return {
    name: INTEGRATION_NAME,
    setup(client) {
      const options2 = { ...DEFAULT_CONFIG, ...client.getOptions(), ...integrationOptions };
      if (!options2.Vue && !options2.app) {
        consoleSandbox(() => {
          console.warn(
            "[@sentry/vue]: Misconfigured SDK. Vue specific errors will not be captured. Update your `Sentry.init` call with an appropriate config option: `app` (Application Instance - Vue 3) or `Vue` (Vue Constructor - Vue 2)."
          );
        });
        return;
      }
      if (options2.app) {
        const apps = Array.isArray(options2.app) ? options2.app : [options2.app];
        apps.forEach((app2) => vueInit(app2, options2));
      } else if (options2.Vue) {
        vueInit(options2.Vue, options2);
      }
    }
  };
});
const vueInit = /* @__PURE__ */ __name((app2, options2) => {
  if (DEBUG_BUILD) {
    const appWithInstance = app2;
    const isMounted = appWithInstance._instance && appWithInstance._instance.isMounted;
    if (isMounted === true) {
      consoleSandbox(() => {
        console.warn(
          "[@sentry/vue]: Misconfigured SDK. Vue app is already mounted. Make sure to call `app.mount()` after `Sentry.init()`."
        );
      });
    }
  }
  if (options2.attachErrorHandler) {
    attachErrorHandler(app2, options2);
  }
  if (hasTracingEnabled(options2)) {
    app2.mixin(
      createTracingMixins({
        ...options2,
        // eslint-disable-next-line deprecation/deprecation
        ...options2.tracingOptions
      })
    );
  }
}, "vueInit");
function init$3(config2 = {}) {
  const options2 = {
    _metadata: {
      sdk: {
        name: "sentry.javascript.vue",
        packages: [
          {
            name: "npm:@sentry/vue",
            version: SDK_VERSION$2
          }
        ],
        version: SDK_VERSION$2
      }
    },
    defaultIntegrations: [...getDefaultIntegrations(config2), vueIntegration()],
    ...config2
  };
  return init$4(options2);
}
__name(init$3, "init$3");
function instrumentVueRouter(router2, options2, startNavigationSpanFn) {
  let isFirstPageLoad = true;
  router2.onError((error2) => captureException(error2, { mechanism: { handled: false } }));
  router2.beforeEach((to, from2, next) => {
    const isPageLoadNavigation = from2.name == null && from2.matched.length === 0 || from2.name === void 0 && isFirstPageLoad;
    if (isFirstPageLoad) {
      isFirstPageLoad = false;
    }
    const attributes = {
      [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.navigation.vue"
    };
    for (const key of Object.keys(to.params)) {
      attributes[`params.${key}`] = to.params[key];
    }
    for (const key of Object.keys(to.query)) {
      const value = to.query[key];
      if (value) {
        attributes[`query.${key}`] = value;
      }
    }
    let spanName = to.path;
    let transactionSource = "url";
    if (to.name && options2.routeLabel !== "path") {
      spanName = to.name.toString();
      transactionSource = "custom";
    } else if (to.matched.length > 0) {
      const lastIndex = to.matched.length - 1;
      spanName = to.matched[lastIndex].path;
      transactionSource = "route";
    }
    getCurrentScope().setTransactionName(spanName);
    if (options2.instrumentPageLoad && isPageLoadNavigation) {
      const activeRootSpan = getActiveRootSpan();
      if (activeRootSpan) {
        const existingAttributes = spanToJSON(activeRootSpan).data || {};
        if (existingAttributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] !== "custom") {
          activeRootSpan.updateName(spanName);
          activeRootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, transactionSource);
        }
        activeRootSpan.setAttributes({
          ...attributes,
          [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.pageload.vue"
        });
      }
    }
    if (options2.instrumentNavigation && !isPageLoadNavigation) {
      attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] = transactionSource;
      attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN] = "auto.navigation.vue";
      startNavigationSpanFn({
        name: spanName,
        op: "navigation",
        attributes
      });
    }
    if (next) {
      next();
    }
  });
}
__name(instrumentVueRouter, "instrumentVueRouter");
function getActiveRootSpan() {
  const span = getActiveSpan();
  const rootSpan = span && getRootSpan(span);
  if (!rootSpan) {
    return void 0;
  }
  const op = spanToJSON(rootSpan).op;
  return op === "navigation" || op === "pageload" ? rootSpan : void 0;
}
__name(getActiveRootSpan, "getActiveRootSpan");
function browserTracingIntegration(options2 = {}) {
  if (!options2.router) {
    return browserTracingIntegration$1(options2);
  }
  const integration = browserTracingIntegration$1({
    ...options2,
    instrumentNavigation: false
  });
  const { router: router2, instrumentNavigation = true, instrumentPageLoad = true, routeLabel = "name" } = options2;
  return {
    ...integration,
    afterAllSetup(client) {
      integration.afterAllSetup(client);
      const startNavigationSpan = /* @__PURE__ */ __name((options3) => {
        startBrowserTracingNavigationSpan(client, options3);
      }, "startNavigationSpan");
      instrumentVueRouter(router2, { routeLabel, instrumentNavigation, instrumentPageLoad }, startNavigationSpan);
    }
  };
}
__name(browserTracingIntegration, "browserTracingIntegration");
const createSentryPiniaPlugin = /* @__PURE__ */ __name((options2 = {
  attachPiniaState: true,
  addBreadcrumbs: true,
  actionTransformer: /* @__PURE__ */ __name((action) => action, "actionTransformer"),
  stateTransformer: /* @__PURE__ */ __name((state) => state, "stateTransformer")
}) => {
  const plugin = /* @__PURE__ */ __name(({ store }) => {
    options2.attachPiniaState !== false && getGlobalScope$1().addEventProcessor((event, hint) => {
      try {
        const timestamp2 = (/* @__PURE__ */ new Date()).toTimeString().split(" ")[0];
        const filename = `pinia_state_${store.$id}_${timestamp2}.json`;
        hint.attachments = [
          ...hint.attachments || [],
          {
            filename,
            data: JSON.stringify(store.$state)
          }
        ];
      } catch (_2) {
      }
      return event;
    });
    store.$onAction((context) => {
      context.after(() => {
        const transformedActionName = options2.actionTransformer ? options2.actionTransformer(context.name) : context.name;
        if (typeof transformedActionName !== "undefined" && transformedActionName !== null && options2.addBreadcrumbs !== false) {
          addBreadcrumb({
            category: "action",
            message: transformedActionName,
            level: "info"
          });
        }
        const transformedState = options2.stateTransformer ? options2.stateTransformer(store.$state) : store.$state;
        const scope = getCurrentScope();
        const currentState = scope.getScopeData().contexts.state;
        if (typeof transformedState !== "undefined" && transformedState !== null) {
          const client = getClient();
          const options3 = client && client.getOptions();
          const normalizationDepth = options3 && options3.normalizeDepth || 3;
          const piniaStateContext = { type: "pinia", value: transformedState };
          const newState = {
            ...currentState || {},
            state: piniaStateContext
          };
          addNonEnumerableProperty(
            newState,
            "__sentry_override_normalization_depth__",
            3 + // 3 layers for `state.value.transformedState
            normalizationDepth
            // rest for the actual state
          );
          scope.setContext("state", newState);
        } else {
          scope.setContext("state", {
            ...currentState || {},
            state: { type: "pinia", value: "undefined" }
          });
        }
      });
    });
  }, "plugin");
  return plugin;
}, "createSentryPiniaPlugin");
const getDefaultsFromPostinstall = /* @__PURE__ */ __name(() => void 0, "getDefaultsFromPostinstall");
var define_process_env_default$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 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$1 = /* @__PURE__ */ __name(function(assertion, message) {
  if (!assertion) {
    throw assertionError(message);
  }
}, "assert$1");
const assertionError = /* @__PURE__ */ __name(function(message) {
  return new Error("Firebase Database (" + CONSTANTS.SDK_VERSION + ") INTERNAL ASSERT FAILED: " + message);
}, "assertionError");
/**
 * @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 = /* @__PURE__ */ __name(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;
}, "stringToByteArray$1");
const byteArrayToString$1 = /* @__PURE__ */ __name(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("");
}, "byteArrayToString$1");
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$1(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 {
  static {
    __name(this, "DecodeBase64StringError");
  }
  constructor() {
    super(...arguments);
    this.name = "DecodeBase64StringError";
  }
}
const base64Encode = /* @__PURE__ */ __name(function(str) {
  const utf8Bytes = stringToByteArray$1(str);
  return base64.encodeByteArray(utf8Bytes, true);
}, "base64Encode");
const base64urlEncodeWithoutPadding = /* @__PURE__ */ __name(function(str) {
  return base64Encode(str).replace(/\./g, "");
}, "base64urlEncodeWithoutPadding");
const base64Decode = /* @__PURE__ */ __name(function(str) {
  try {
    return base64.decodeString(str, true);
  } catch (e2) {
    console.error("base64Decode failed: ", e2);
  }
  return null;
}, "base64Decode");
/**
 * @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);
}
__name(deepCopy, "deepCopy");
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 prop2 in source) {
    if (!source.hasOwnProperty(prop2) || !isValidKey$1(prop2)) {
      continue;
    }
    target[prop2] = deepExtend(target[prop2], source[prop2]);
  }
  return target;
}
__name(deepExtend, "deepExtend");
function isValidKey$1(key) {
  return key !== "__proto__";
}
__name(isValidKey$1, "isValidKey$1");
/**
 * @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.");
}
__name(getGlobal, "getGlobal");
/**
 * @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 = /* @__PURE__ */ __name(() => getGlobal().__FIREBASE_DEFAULTS__, "getDefaultsFromGlobal");
const getDefaultsFromEnvVariable = /* @__PURE__ */ __name(() => {
  if (typeof process === "undefined" || typeof define_process_env_default$1 === "undefined") {
    return;
  }
  const defaultsJsonString = define_process_env_default$1.__FIREBASE_DEFAULTS__;
  if (defaultsJsonString) {
    return JSON.parse(defaultsJsonString);
  }
}, "getDefaultsFromEnvVariable");
const getDefaultsFromCookie = /* @__PURE__ */ __name(() => {
  if (typeof document === "undefined") {
    return;
  }
  let match2;
  try {
    match2 = document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/);
  } catch (e2) {
    return;
  }
  const decoded = match2 && base64Decode(match2[1]);
  return decoded && JSON.parse(decoded);
}, "getDefaultsFromCookie");
const getDefaults = /* @__PURE__ */ __name(() => {
  try {
    return getDefaultsFromPostinstall() || getDefaultsFromGlobal() || getDefaultsFromEnvVariable() || getDefaultsFromCookie();
  } catch (e2) {
    console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e2}`);
    return;
  }
}, "getDefaults");
const getDefaultEmulatorHost = /* @__PURE__ */ __name((productName) => {
  var _a2, _b;
  return (_b = (_a2 = getDefaults()) === null || _a2 === void 0 ? void 0 : _a2.emulatorHosts) === null || _b === void 0 ? void 0 : _b[productName];
}, "getDefaultEmulatorHost");
const getDefaultEmulatorHostnameAndPort = /* @__PURE__ */ __name((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];
  }
}, "getDefaultEmulatorHostnameAndPort");
const getDefaultAppConfig = /* @__PURE__ */ __name(() => {
  var _a2;
  return (_a2 = getDefaults()) === null || _a2 === void 0 ? void 0 : _a2.config;
}, "getDefaultAppConfig");
const getExperimentalSetting = /* @__PURE__ */ __name((name2) => {
  var _a2;
  return (_a2 = getDefaults()) === null || _a2 === void 0 ? void 0 : _a2[`_${name2}`];
}, "getExperimentalSetting");
/**
 * @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 {
  static {
    __name(this, "Deferred");
  }
  constructor() {
    this.reject = () => {
    };
    this.resolve = () => {
    };
    this.promise = new Promise((resolve2, reject) => {
      this.resolve = resolve2;
      this.reject = reject;
    });
  }
  /**
   * Our API internals are not promisified 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(".");
}
__name(createMockUserToken, "createMockUserToken");
/**
 * @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 "";
  }
}
__name(getUA, "getUA");
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());
}
__name(isMobileCordova, "isMobileCordova");
function isNode() {
  var _a2;
  const forceEnvironment = (_a2 = getDefaults()) === null || _a2 === void 0 ? void 0 : _a2.forceEnvironment;
  if (forceEnvironment === "node") {
    return true;
  } else if (forceEnvironment === "browser") {
    return false;
  }
  try {
    return Object.prototype.toString.call(global.process) === "[object process]";
  } catch (e2) {
    return false;
  }
}
__name(isNode, "isNode");
function isBrowser$1() {
  return typeof window !== "undefined" || isWebWorker();
}
__name(isBrowser$1, "isBrowser$1");
function isWebWorker() {
  return typeof WorkerGlobalScope !== "undefined" && typeof self !== "undefined" && self instanceof WorkerGlobalScope;
}
__name(isWebWorker, "isWebWorker");
function isCloudflareWorker() {
  return typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers";
}
__name(isCloudflareWorker, "isCloudflareWorker");
function isBrowserExtension() {
  const runtime = typeof chrome === "object" ? chrome.runtime : typeof browser === "object" ? browser.runtime : void 0;
  return typeof runtime === "object" && runtime.id !== void 0;
}
__name(isBrowserExtension, "isBrowserExtension");
function isReactNative() {
  return typeof navigator === "object" && navigator["product"] === "ReactNative";
}
__name(isReactNative, "isReactNative");
function isElectron$1() {
  return getUA().indexOf("Electron/") >= 0;
}
__name(isElectron$1, "isElectron$1");
function isIE() {
  const ua = getUA();
  return ua.indexOf("MSIE ") >= 0 || ua.indexOf("Trident/") >= 0;
}
__name(isIE, "isIE");
function isUWP() {
  return getUA().indexOf("MSAppHost/") >= 0;
}
__name(isUWP, "isUWP");
function isNodeSdk() {
  return CONSTANTS.NODE_CLIENT === true || CONSTANTS.NODE_ADMIN === true;
}
__name(isNodeSdk, "isNodeSdk");
function isSafari$1() {
  return !isNode() && !!navigator.userAgent && navigator.userAgent.includes("Safari") && !navigator.userAgent.includes("Chrome");
}
__name(isSafari$1, "isSafari$1");
function isIndexedDBAvailable() {
  try {
    return typeof indexedDB === "object";
  } catch (e2) {
    return false;
  }
}
__name(isIndexedDBAvailable, "isIndexedDBAvailable");
function validateIndexedDBOpenable() {
  return new Promise((resolve2, 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);
        }
        resolve2(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);
    }
  });
}
__name(validateIndexedDBOpenable, "validateIndexedDBOpenable");
function areCookiesEnabled() {
  if (typeof navigator === "undefined" || !navigator.cookieEnabled) {
    return false;
  }
  return true;
}
__name(areCookiesEnabled, "areCookiesEnabled");
/**
 * @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 {
  static {
    __name(this, "FirebaseError");
  }
  constructor(code2, message, customData) {
    super(message);
    this.code = code2;
    this.customData = customData;
    this.name = ERROR_NAME;
    Object.setPrototypeOf(this, FirebaseError.prototype);
    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, ErrorFactory.prototype.create);
    }
  }
}
class ErrorFactory {
  static {
    __name(this, "ErrorFactory");
  }
  constructor(service, serviceName, errors2) {
    this.service = service;
    this.serviceName = serviceName;
    this.errors = errors2;
  }
  create(code2, ...data) {
    const customData = data[0] || {};
    const fullCode = `${this.service}/${code2}`;
    const template = this.errors[code2];
    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}?>`;
  });
}
__name(replaceTemplate, "replaceTemplate");
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);
}
__name(jsonEval, "jsonEval");
function stringify$2(data) {
  return JSON.stringify(data);
}
__name(stringify$2, "stringify$2");
/**
 * @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$4 = /* @__PURE__ */ __name(function(token) {
  let header = {}, claims = {}, data = {}, signature = "";
  try {
    const parts2 = token.split(".");
    header = jsonEval(base64Decode(parts2[0]) || "");
    claims = jsonEval(base64Decode(parts2[1]) || "");
    signature = parts2[2];
    data = claims["d"] || {};
    delete claims["d"];
  } catch (e2) {
  }
  return {
    header,
    claims,
    data,
    signature
  };
}, "decode$4");
const isValidTimestamp = /* @__PURE__ */ __name(function(token) {
  const claims = decode$4(token).claims;
  const now2 = Math.floor((/* @__PURE__ */ new Date()).getTime() / 1e3);
  let validSince = 0, validUntil = 0;
  if (typeof claims === "object") {
    if (claims.hasOwnProperty("nbf")) {
      validSince = claims["nbf"];
    } else if (claims.hasOwnProperty("iat")) {
      validSince = claims["iat"];
    }
    if (claims.hasOwnProperty("exp")) {
      validUntil = claims["exp"];
    } else {
      validUntil = validSince + 86400;
    }
  }
  return !!now2 && !!validSince && !!validUntil && now2 >= validSince && now2 <= validUntil;
}, "isValidTimestamp");
const issuedAtTime = /* @__PURE__ */ __name(function(token) {
  const claims = decode$4(token).claims;
  if (typeof claims === "object" && claims.hasOwnProperty("iat")) {
    return claims["iat"];
  }
  return null;
}, "issuedAtTime");
const isValidFormat = /* @__PURE__ */ __name(function(token) {
  const decoded = decode$4(token), claims = decoded.claims;
  return !!claims && typeof claims === "object" && claims.hasOwnProperty("iat");
}, "isValidFormat");
const isAdmin = /* @__PURE__ */ __name(function(token) {
  const claims = decode$4(token).claims;
  return typeof claims === "object" && claims["admin"] === true;
}, "isAdmin");
/**
 * @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$2(obj, key) {
  return Object.prototype.hasOwnProperty.call(obj, key);
}
__name(contains$2, "contains$2");
function safeGet(obj, key) {
  if (Object.prototype.hasOwnProperty.call(obj, key)) {
    return obj[key];
  } else {
    return void 0;
  }
}
__name(safeGet, "safeGet");
function isEmpty$4(obj) {
  for (const key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      return false;
    }
  }
  return true;
}
__name(isEmpty$4, "isEmpty$4");
function map$1(obj, fn, contextObj) {
  const res = {};
  for (const key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      res[key] = fn.call(contextObj, obj[key], key, obj);
    }
  }
  return res;
}
__name(map$1, "map$1");
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$e(aProp) && isObject$e(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;
}
__name(deepEqual, "deepEqual");
function isObject$e(thing) {
  return thing !== null && typeof thing === "object";
}
__name(isObject$e, "isObject$e");
/**
 * @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 promiseWithTimeout(promise, timeInMS = 2e3) {
  const deferredPromise = new Deferred();
  setTimeout(() => deferredPromise.reject("timeout!"), timeInMS);
  promise.then(deferredPromise.resolve, deferredPromise.reject);
  return deferredPromise.promise;
}
__name(promiseWithTimeout, "promiseWithTimeout");
/**
 * @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("&") : "";
}
__name(querystring, "querystring");
function querystringDecode(querystring2) {
  const obj = {};
  const tokens = querystring2.replace(/^\?/, "").split("&");
  tokens.forEach((token) => {
    if (token) {
      const [key, value] = token.split("=");
      obj[decodeURIComponent(key)] = decodeURIComponent(value);
    }
  });
  return obj;
}
__name(querystringDecode, "querystringDecode");
function extractQuerystring(url) {
  const queryStart = url.indexOf("?");
  if (!queryStart) {
    return "";
  }
  const fragmentStart = url.indexOf("#", queryStart);
  return url.substring(queryStart, fragmentStart > 0 ? fragmentStart : void 0);
}
__name(extractQuerystring, "extractQuerystring");
/**
 * @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 {
  static {
    __name(this, "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 createSubscribe(executor, onNoObservers) {
  const proxy = new ObserverProxy(executor, onNoObservers);
  return proxy.subscribe.bind(proxy);
}
__name(createSubscribe, "createSubscribe");
class ObserverProxy {
  static {
    __name(this, "ObserverProxy");
  }
  /**
   * @param executor Function which can make calls to a single Observer
   *     as a proxy.
   * @param onNoObservers Callback when count of Observers goes to zero.
   */
  constructor(executor, onNoObservers) {
    this.observers = [];
    this.unsubscribes = [];
    this.observerCount = 0;
    this.task = Promise.resolve();
    this.finalized = false;
    this.onNoObservers = onNoObservers;
    this.task.then(() => {
      executor(this);
    }).catch((e2) => {
      this.error(e2);
    });
  }
  next(value) {
    this.forEachObserver((observer) => {
      observer.next(value);
    });
  }
  error(error2) {
    this.forEachObserver((observer) => {
      observer.error(error2);
    });
    this.close(error2);
  }
  complete() {
    this.forEachObserver((observer) => {
      observer.complete();
    });
    this.close();
  }
  /**
   * Subscribe function that can be used to add an Observer to the fan-out list.
   *
   * - We require that no event is sent to a subscriber synchronously to their
   *   call to subscribe().
   */
  subscribe(nextOrObserver, error2, complete) {
    let observer;
    if (nextOrObserver === void 0 && error2 === void 0 && complete === void 0) {
      throw new Error("Missing Observer.");
    }
    if (implementsAnyMethods(nextOrObserver, [
      "next",
      "error",
      "complete"
    ])) {
      observer = nextOrObserver;
    } else {
      observer = {
        next: nextOrObserver,
        error: error2,
        complete
      };
    }
    if (observer.next === void 0) {
      observer.next = noop$6;
    }
    if (observer.error === void 0) {
      observer.error = noop$6;
    }
    if (observer.complete === void 0) {
      observer.complete = noop$6;
    }
    const unsub = this.unsubscribeOne.bind(this, this.observers.length);
    if (this.finalized) {
      this.task.then(() => {
        try {
          if (this.finalError) {
            observer.error(this.finalError);
          } else {
            observer.complete();
          }
        } catch (e2) {
        }
        return;
      });
    }
    this.observers.push(observer);
    return unsub;
  }
  // Unsubscribe is synchronous - we guarantee that no events are sent to
  // any unsubscribed Observer.
  unsubscribeOne(i2) {
    if (this.observers === void 0 || this.observers[i2] === void 0) {
      return;
    }
    delete this.observers[i2];
    this.observerCount -= 1;
    if (this.observerCount === 0 && this.onNoObservers !== void 0) {
      this.onNoObservers(this);
    }
  }
  forEachObserver(fn) {
    if (this.finalized) {
      return;
    }
    for (let i2 = 0; i2 < this.observers.length; i2++) {
      this.sendOne(i2, fn);
    }
  }
  // Call the Observer via one of it's callback function. We are careful to
  // confirm that the observe has not been unsubscribed since this asynchronous
  // function had been queued.
  sendOne(i2, fn) {
    this.task.then(() => {
      if (this.observers !== void 0 && this.observers[i2] !== void 0) {
        try {
          fn(this.observers[i2]);
        } catch (e2) {
          if (typeof console !== "undefined" && console.error) {
            console.error(e2);
          }
        }
      }
    });
  }
  close(err) {
    if (this.finalized) {
      return;
    }
    this.finalized = true;
    if (err !== void 0) {
      this.finalError = err;
    }
    this.task.then(() => {
      this.observers = void 0;
      this.onNoObservers = void 0;
    });
  }
}
function async$1(fn, onError) {
  return (...args) => {
    Promise.resolve(true).then(() => {
      fn(...args);
    }).catch((error2) => {
      if (onError) {
        onError(error2);
      }
    });
  };
}
__name(async$1, "async$1");
function implementsAnyMethods(obj, methods) {
  if (typeof obj !== "object" || obj === null) {
    return false;
  }
  for (const method of methods) {
    if (method in obj && typeof obj[method] === "function") {
      return true;
    }
  }
  return false;
}
__name(implementsAnyMethods, "implementsAnyMethods");
function noop$6() {
}
__name(noop$6, "noop$6");
/**
 * @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 validateArgCount = /* @__PURE__ */ __name(function(fnName, minCount, maxCount, argCount) {
  let argError;
  if (argCount < minCount) {
    argError = "at least " + minCount;
  } else if (argCount > maxCount) {
    argError = maxCount === 0 ? "none" : "no more than " + maxCount;
  }
  if (argError) {
    const error2 = fnName + " failed: Was called with " + argCount + (argCount === 1 ? " argument." : " arguments.") + " Expects " + argError + ".";
    throw new Error(error2);
  }
}, "validateArgCount");
function errorPrefix(fnName, argName) {
  return `${fnName} failed: ${argName} argument `;
}
__name(errorPrefix, "errorPrefix");
function validateNamespace(fnName, namespace, optional) {
  if (optional && !namespace) {
    return;
  }
  if (typeof namespace !== "string") {
    throw new Error(errorPrefix(fnName, "namespace") + "must be a valid firebase namespace.");
  }
}
__name(validateNamespace, "validateNamespace");
function validateCallback(fnName, argumentName, callback, optional) {
  if (optional && !callback) {
    return;
  }
  if (typeof callback !== "function") {
    throw new Error(errorPrefix(fnName, argumentName) + "must be a valid function.");
  }
}
__name(validateCallback, "validateCallback");
function validateContextObject(fnName, argumentName, context, optional) {
  if (optional && !context) {
    return;
  }
  if (typeof context !== "object" || context === null) {
    throw new Error(errorPrefix(fnName, argumentName) + "must be a valid context object.");
  }
}
__name(validateContextObject, "validateContextObject");
/**
 * @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 = /* @__PURE__ */ __name(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$1(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;
}, "stringToByteArray");
const stringLength = /* @__PURE__ */ __name(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;
}, "stringLength");
/**
 * @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_INTERVAL_MILLIS = 1e3;
const DEFAULT_BACKOFF_FACTOR = 2;
const MAX_VALUE_MILLIS = 4 * 60 * 60 * 1e3;
const RANDOM_FACTOR = 0.5;
function calculateBackoffMillis(backoffCount, intervalMillis = DEFAULT_INTERVAL_MILLIS, backoffFactor = DEFAULT_BACKOFF_FACTOR) {
  const currBaseValue = intervalMillis * Math.pow(backoffFactor, backoffCount);
  const randomWait = Math.round(
    // A fraction of the backoff value to add/subtract.
    // Deviation: changes multiplication order to improve readability.
    RANDOM_FACTOR * currBaseValue * // A random float (rounded to int by Math.round above) in the range [-1, 1]. Determines
    // if we add or subtract.
    (Math.random() - 0.5) * 2
  );
  return Math.min(MAX_VALUE_MILLIS, currBaseValue + randomWait);
}
__name(calculateBackoffMillis, "calculateBackoffMillis");
/**
 * @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.
 */
function ordinal(i2) {
  if (!Number.isFinite(i2)) {
    return `${i2}`;
  }
  return i2 + indicator(i2);
}
__name(ordinal, "ordinal");
function indicator(i2) {
  i2 = Math.abs(i2);
  const cent = i2 % 100;
  if (cent >= 10 && cent <= 20) {
    return "th";
  }
  const dec = i2 % 10;
  if (dec === 1) {
    return "st";
  }
  if (dec === 2) {
    return "nd";
  }
  if (dec === 3) {
    return "rd";
  }
  return "th";
}
__name(indicator, "indicator");
/**
 * @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;
  }
}
__name(getModularInstance, "getModularInstance");
class Component {
  static {
    __name(this, "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 {
  static {
    __name(this, "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 multiple 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 instance = this.getOrInitializeService({
            instanceIdentifier: normalizedIdentifier
          });
          if (instance) {
            deferred.resolve(instance);
          }
        } catch (e2) {
        }
      }
    }
    return this.instancesDeferred.get(normalizedIdentifier).promise;
  }
  getImmediate(options2) {
    var _a2;
    const normalizedIdentifier = this.normalizeInstanceIdentifier(options2 === null || options2 === void 0 ? void 0 : options2.identifier);
    const optional = (_a2 = options2 === null || options2 === void 0 ? void 0 : options2.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 instance = this.getOrInitializeService({
          instanceIdentifier: normalizedIdentifier
        });
        instanceDeferred.resolve(instance);
      } 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: options2 = {} } = 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 instance = this.getOrInitializeService({
      instanceIdentifier: normalizedIdentifier,
      options: options2
    });
    for (const [instanceIdentifier, instanceDeferred] of this.instancesDeferred.entries()) {
      const normalizedDeferredIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier);
      if (normalizedIdentifier === normalizedDeferredIdentifier) {
        instanceDeferred.resolve(instance);
      }
    }
    return instance;
  }
  /**
   *
   * @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(instance, identifier) {
    const callbacks = this.onInitCallbacks.get(identifier);
    if (!callbacks) {
      return;
    }
    for (const callback of callbacks) {
      try {
        callback(instance, identifier);
      } catch (_a2) {
      }
    }
  }
  getOrInitializeService({ instanceIdentifier, options: options2 = {} }) {
    let instance = this.instances.get(instanceIdentifier);
    if (!instance && this.component) {
      instance = this.component.instanceFactory(this.container, {
        instanceIdentifier: normalizeIdentifierForFactory(instanceIdentifier),
        options: options2
      });
      this.instances.set(instanceIdentifier, instance);
      this.instancesOptions.set(instanceIdentifier, options2);
      this.invokeOnInitCallbacks(instance, instanceIdentifier);
      if (this.component.onInstanceCreated) {
        try {
          this.component.onInstanceCreated(this.container, instanceIdentifier, instance);
        } catch (_a2) {
        }
      }
    }
    return instance || 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;
}
__name(normalizeIdentifierForFactory, "normalizeIdentifierForFactory");
function isComponentEager(component) {
  return component.instantiationMode === "EAGER";
}
__name(isComponentEager, "isComponentEager");
/**
 * @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 {
  static {
    __name(this, "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.
 */
const instances = [];
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 = /* @__PURE__ */ __name((instance, logType, ...args) => {
  if (logType < instance.logLevel) {
    return;
  }
  const now2 = (/* @__PURE__ */ new Date()).toISOString();
  const method = ConsoleMethod[logType];
  if (method) {
    console[method](`[${now2}]  ${instance.name}:`, ...args);
  } else {
    throw new Error(`Attempted to log a message with an invalid logType (value: ${logType})`);
  }
}, "defaultLogHandler");
class Logger {
  static {
    __name(this, "Logger");
  }
  /**
   * 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;
    instances.push(this);
  }
  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);
  }
}
function setLogLevel$2(level) {
  instances.forEach((inst) => {
    inst.setLogLevel(level);
  });
}
__name(setLogLevel$2, "setLogLevel$2");
function setUserLogHandler(logCallback, options2) {
  for (const instance of instances) {
    let customLogLevel = null;
    if (options2 && options2.level) {
      customLogLevel = levelStringToEnum[options2.level];
    }
    if (logCallback === null) {
      instance.userLogHandler = null;
    } else {
      instance.userLogHandler = (instance2, level, ...args) => {
        const message = args.map((arg) => {
          if (arg == null) {
            return null;
          } else if (typeof arg === "string") {
            return arg;
          } else if (typeof arg === "number" || typeof arg === "boolean") {
            return arg.toString();
          } else if (arg instanceof Error) {
            return arg.message;
          } else {
            try {
              return JSON.stringify(arg);
            } catch (ignored) {
              return null;
            }
          }
        }).filter((arg) => arg).join(" ");
        if (level >= (customLogLevel !== null && customLogLevel !== void 0 ? customLogLevel : instance2.logLevel)) {
          logCallback({
            level: LogLevel[level].toLowerCase(),
            message,
            args,
            type: instance2.name
          });
        }
      };
    }
  }
}
__name(setUserLogHandler, "setUserLogHandler");
const instanceOfAny = /* @__PURE__ */ __name((object, constructors) => constructors.some((c2) => object instanceof c2), "instanceOfAny");
let idbProxyableTypes;
let cursorAdvanceMethods;
function getIdbProxyableTypes() {
  return idbProxyableTypes || (idbProxyableTypes = [
    IDBDatabase,
    IDBObjectStore,
    IDBIndex,
    IDBCursor,
    IDBTransaction
  ]);
}
__name(getIdbProxyableTypes, "getIdbProxyableTypes");
function getCursorAdvanceMethods() {
  return cursorAdvanceMethods || (cursorAdvanceMethods = [
    IDBCursor.prototype.advance,
    IDBCursor.prototype.continue,
    IDBCursor.prototype.continuePrimaryKey
  ]);
}
__name(getCursorAdvanceMethods, "getCursorAdvanceMethods");
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((resolve2, reject) => {
    const unlisten = /* @__PURE__ */ __name(() => {
      request.removeEventListener("success", success);
      request.removeEventListener("error", error2);
    }, "unlisten");
    const success = /* @__PURE__ */ __name(() => {
      resolve2(wrap$1(request.result));
      unlisten();
    }, "success");
    const error2 = /* @__PURE__ */ __name(() => {
      reject(request.error);
      unlisten();
    }, "error");
    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;
}
__name(promisifyRequest, "promisifyRequest");
function cacheDonePromiseForTransaction(tx) {
  if (transactionDoneMap.has(tx))
    return;
  const done = new Promise((resolve2, reject) => {
    const unlisten = /* @__PURE__ */ __name(() => {
      tx.removeEventListener("complete", complete);
      tx.removeEventListener("error", error2);
      tx.removeEventListener("abort", error2);
    }, "unlisten");
    const complete = /* @__PURE__ */ __name(() => {
      resolve2();
      unlisten();
    }, "complete");
    const error2 = /* @__PURE__ */ __name(() => {
      reject(tx.error || new DOMException("AbortError", "AbortError"));
      unlisten();
    }, "error");
    tx.addEventListener("complete", complete);
    tx.addEventListener("error", error2);
    tx.addEventListener("abort", error2);
  });
  transactionDoneMap.set(tx, done);
}
__name(cacheDonePromiseForTransaction, "cacheDonePromiseForTransaction");
let idbProxyTraps = {
  get(target, prop2, receiver) {
    if (target instanceof IDBTransaction) {
      if (prop2 === "done")
        return transactionDoneMap.get(target);
      if (prop2 === "objectStoreNames") {
        return target.objectStoreNames || transactionStoreNamesMap.get(target);
      }
      if (prop2 === "store") {
        return receiver.objectStoreNames[1] ? void 0 : receiver.objectStore(receiver.objectStoreNames[0]);
      }
    }
    return wrap$1(target[prop2]);
  },
  set(target, prop2, value) {
    target[prop2] = value;
    return true;
  },
  has(target, prop2) {
    if (target instanceof IDBTransaction && (prop2 === "done" || prop2 === "store")) {
      return true;
    }
    return prop2 in target;
  }
};
function replaceTraps(callback) {
  idbProxyTraps = callback(idbProxyTraps);
}
__name(replaceTraps, "replaceTraps");
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$1(tx);
    };
  }
  if (getCursorAdvanceMethods().includes(func)) {
    return function(...args) {
      func.apply(unwrap(this), args);
      return wrap$1(cursorRequestMap.get(this));
    };
  }
  return function(...args) {
    return wrap$1(func.apply(unwrap(this), args));
  };
}
__name(wrapFunction, "wrapFunction");
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;
}
__name(transformCachableValue, "transformCachableValue");
function wrap$1(value) {
  if (value instanceof IDBRequest)
    return promisifyRequest(value);
  if (transformCache.has(value))
    return transformCache.get(value);
  const newValue2 = transformCachableValue(value);
  if (newValue2 !== value) {
    transformCache.set(value, newValue2);
    reverseTransformCache.set(newValue2, value);
  }
  return newValue2;
}
__name(wrap$1, "wrap$1");
const unwrap = /* @__PURE__ */ __name((value) => reverseTransformCache.get(value), "unwrap");
function openDB(name2, version2, { blocked, upgrade, blocking, terminated } = {}) {
  const request = indexedDB.open(name2, version2);
  const openPromise = wrap$1(request);
  if (upgrade) {
    request.addEventListener("upgradeneeded", (event) => {
      upgrade(wrap$1(request.result), event.oldVersion, event.newVersion, wrap$1(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;
}
__name(openDB, "openDB");
function deleteDB(name2, { blocked } = {}) {
  const request = indexedDB.deleteDatabase(name2);
  if (blocked) {
    request.addEventListener("blocked", (event) => blocked(
      // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405
      event.oldVersion,
      event
    ));
  }
  return wrap$1(request).then(() => void 0);
}
__name(deleteDB, "deleteDB");
const readMethods = ["get", "getKey", "getAll", "getAllKeys", "count"];
const writeMethods = ["put", "add", "delete", "clear"];
const cachedMethods = /* @__PURE__ */ new Map();
function getMethod(target, prop2) {
  if (!(target instanceof IDBDatabase && !(prop2 in target) && typeof prop2 === "string")) {
    return;
  }
  if (cachedMethods.get(prop2))
    return cachedMethods.get(prop2);
  const targetFuncName = prop2.replace(/FromIndex$/, "");
  const useIndex = prop2 !== 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 = /* @__PURE__ */ __name(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];
  }, "method");
  cachedMethods.set(prop2, method);
  return method;
}
__name(getMethod, "getMethod");
replaceTraps((oldTraps) => ({
  ...oldTraps,
  get: /* @__PURE__ */ __name((target, prop2, receiver) => getMethod(target, prop2) || oldTraps.get(target, prop2, receiver), "get"),
  has: /* @__PURE__ */ __name((target, prop2) => !!getMethod(target, prop2) || oldTraps.has(target, prop2), "has")
}));
/**
 * @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 {
  static {
    __name(this, "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";
}
__name(isVersionServiceProvider, "isVersionServiceProvider");
const name$q = "@firebase/app";
const version$1$1 = "0.11.4";
/**
 * @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$3 = new Logger("@firebase/app");
const name$p = "@firebase/app-compat";
const name$o = "@firebase/analytics-compat";
const name$n = "@firebase/analytics";
const name$m = "@firebase/app-check-compat";
const name$l = "@firebase/app-check";
const name$k = "@firebase/auth";
const name$j = "@firebase/auth-compat";
const name$i = "@firebase/database";
const name$h = "@firebase/data-connect";
const name$g = "@firebase/database-compat";
const name$f = "@firebase/functions";
const name$e = "@firebase/functions-compat";
const name$d = "@firebase/installations";
const name$c = "@firebase/installations-compat";
const name$b = "@firebase/messaging";
const name$a$1 = "@firebase/messaging-compat";
const name$9$1 = "@firebase/performance";
const name$8$1 = "@firebase/performance-compat";
const name$7$1 = "@firebase/remote-config";
const name$6$1 = "@firebase/remote-config-compat";
const name$5$1 = "@firebase/storage";
const name$4$1 = "@firebase/storage-compat";
const name$3$1 = "@firebase/firestore";
const name$2$1 = "@firebase/vertexai";
const name$1$1 = "@firebase/firestore-compat";
const name$r = "firebase";
const version$5 = "11.6.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$q]: "fire-core",
  [name$p]: "fire-core-compat",
  [name$n]: "fire-analytics",
  [name$o]: "fire-analytics-compat",
  [name$l]: "fire-app-check",
  [name$m]: "fire-app-check-compat",
  [name$k]: "fire-auth",
  [name$j]: "fire-auth-compat",
  [name$i]: "fire-rtdb",
  [name$h]: "fire-data-connect",
  [name$g]: "fire-rtdb-compat",
  [name$f]: "fire-fn",
  [name$e]: "fire-fn-compat",
  [name$d]: "fire-iid",
  [name$c]: "fire-iid-compat",
  [name$b]: "fire-fcm",
  [name$a$1]: "fire-fcm-compat",
  [name$9$1]: "fire-perf",
  [name$8$1]: "fire-perf-compat",
  [name$7$1]: "fire-rc",
  [name$6$1]: "fire-rc-compat",
  [name$5$1]: "fire-gcs",
  [name$4$1]: "fire-gcs-compat",
  [name$3$1]: "fire-fst",
  [name$1$1]: "fire-fst-compat",
  [name$2$1]: "fire-vertex",
  "fire-js": "fire-js",
  // Platform identifier for JS SDK.
  [name$r]: "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 _serverApps = /* @__PURE__ */ new Map();
const _components = /* @__PURE__ */ new Map();
function _addComponent(app2, component) {
  try {
    app2.container.addComponent(component);
  } catch (e2) {
    logger$3.debug(`Component ${component.name} failed to register with FirebaseApp ${app2.name}`, e2);
  }
}
__name(_addComponent, "_addComponent");
function _addOrOverwriteComponent(app2, component) {
  app2.container.addOrOverwriteComponent(component);
}
__name(_addOrOverwriteComponent, "_addOrOverwriteComponent");
function _registerComponent(component) {
  const componentName = component.name;
  if (_components.has(componentName)) {
    logger$3.debug(`There were multiple attempts to register component ${componentName}.`);
    return false;
  }
  _components.set(componentName, component);
  for (const app2 of _apps.values()) {
    _addComponent(app2, component);
  }
  for (const serverApp of _serverApps.values()) {
    _addComponent(serverApp, component);
  }
  return true;
}
__name(_registerComponent, "_registerComponent");
function _getProvider(app2, name2) {
  const heartbeatController = app2.container.getProvider("heartbeat").getImmediate({ optional: true });
  if (heartbeatController) {
    void heartbeatController.triggerHeartbeat();
  }
  return app2.container.getProvider(name2);
}
__name(_getProvider, "_getProvider");
function _removeServiceInstance(app2, name2, instanceIdentifier = DEFAULT_ENTRY_NAME) {
  _getProvider(app2, name2).clearInstance(instanceIdentifier);
}
__name(_removeServiceInstance, "_removeServiceInstance");
function _isFirebaseApp(obj) {
  return obj.options !== void 0;
}
__name(_isFirebaseApp, "_isFirebaseApp");
function _isFirebaseServerApp(obj) {
  if (obj === null || obj === void 0) {
    return false;
  }
  return obj.settings !== void 0;
}
__name(_isFirebaseServerApp, "_isFirebaseServerApp");
function _clearComponents() {
  _components.clear();
}
__name(_clearComponents, "_clearComponents");
/**
 * @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$1 = {
  [
    "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",
  [
    "server-app-deleted"
    /* AppError.SERVER_APP_DELETED */
  ]: "Firebase Server App has been 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}.",
  [
    "finalization-registry-not-supported"
    /* AppError.FINALIZATION_REGISTRY_NOT_SUPPORTED */
  ]: "FirebaseServerApp deleteOnDeref field defined but the JS runtime does not support FinalizationRegistry.",
  [
    "invalid-server-app-environment"
    /* AppError.INVALID_SERVER_APP_ENVIRONMENT */
  ]: "FirebaseServerApp is not for use in browser environments."
};
const ERROR_FACTORY$1 = new ErrorFactory("app", "Firebase", ERRORS$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.
 */
class FirebaseAppImpl {
  static {
    __name(this, "FirebaseAppImpl");
  }
  constructor(options2, config2, container) {
    this._isDeleted = false;
    this._options = Object.assign({}, options2);
    this._config = Object.assign({}, config2);
    this._name = config2.name;
    this._automaticDataCollectionEnabled = config2.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$1.create("app-deleted", { appName: this._name });
    }
  }
}
/**
 * @license
 * Copyright 2023 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 validateTokenTTL(base64Token, tokenName) {
  const secondPart = base64Decode(base64Token.split(".")[1]);
  if (secondPart === null) {
    console.error(`FirebaseServerApp ${tokenName} is invalid: second part could not be parsed.`);
    return;
  }
  const expClaim = JSON.parse(secondPart).exp;
  if (expClaim === void 0) {
    console.error(`FirebaseServerApp ${tokenName} is invalid: expiration claim could not be parsed`);
    return;
  }
  const exp = JSON.parse(secondPart).exp * 1e3;
  const now2 = (/* @__PURE__ */ new Date()).getTime();
  const diff2 = exp - now2;
  if (diff2 <= 0) {
    console.error(`FirebaseServerApp ${tokenName} is invalid: the token has expired.`);
  }
}
__name(validateTokenTTL, "validateTokenTTL");
class FirebaseServerAppImpl extends FirebaseAppImpl {
  static {
    __name(this, "FirebaseServerAppImpl");
  }
  constructor(options2, serverConfig2, name2, container) {
    const automaticDataCollectionEnabled = serverConfig2.automaticDataCollectionEnabled !== void 0 ? serverConfig2.automaticDataCollectionEnabled : false;
    const config2 = {
      name: name2,
      automaticDataCollectionEnabled
    };
    if (options2.apiKey !== void 0) {
      super(options2, config2, container);
    } else {
      const appImpl = options2;
      super(appImpl.options, config2, container);
    }
    this._serverConfig = Object.assign({ automaticDataCollectionEnabled }, serverConfig2);
    if (this._serverConfig.authIdToken) {
      validateTokenTTL(this._serverConfig.authIdToken, "authIdToken");
    }
    if (this._serverConfig.appCheckToken) {
      validateTokenTTL(this._serverConfig.appCheckToken, "appCheckToken");
    }
    this._finalizationRegistry = null;
    if (typeof FinalizationRegistry !== "undefined") {
      this._finalizationRegistry = new FinalizationRegistry(() => {
        this.automaticCleanup();
      });
    }
    this._refCount = 0;
    this.incRefCount(this._serverConfig.releaseOnDeref);
    this._serverConfig.releaseOnDeref = void 0;
    serverConfig2.releaseOnDeref = void 0;
    registerVersion(name$q, version$1$1, "serverapp");
  }
  toJSON() {
    return void 0;
  }
  get refCount() {
    return this._refCount;
  }
  // Increment the reference count of this server app. If an object is provided, register it
  // with the finalization registry.
  incRefCount(obj) {
    if (this.isDeleted) {
      return;
    }
    this._refCount++;
    if (obj !== void 0 && this._finalizationRegistry !== null) {
      this._finalizationRegistry.register(obj, this);
    }
  }
  // Decrement the reference count.
  decRefCount() {
    if (this.isDeleted) {
      return 0;
    }
    return --this._refCount;
  }
  // Invoked by the FinalizationRegistry callback to note that this app should go through its
  // reference counts and delete itself if no reference count remain. The coordinating logic that
  // handles this is in deleteApp(...).
  automaticCleanup() {
    void deleteApp(this);
  }
  get settings() {
    this.checkDestroyed();
    return this._serverConfig;
  }
  /**
   * 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$1.create(
        "server-app-deleted"
        /* AppError.SERVER_APP_DELETED */
      );
    }
  }
}
/**
 * @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$5;
function initializeApp(_options, rawConfig = {}) {
  let options2 = _options;
  if (typeof rawConfig !== "object") {
    const name3 = rawConfig;
    rawConfig = { name: name3 };
  }
  const config2 = Object.assign({ name: DEFAULT_ENTRY_NAME, automaticDataCollectionEnabled: false }, rawConfig);
  const name2 = config2.name;
  if (typeof name2 !== "string" || !name2) {
    throw ERROR_FACTORY$1.create("bad-app-name", {
      appName: String(name2)
    });
  }
  options2 || (options2 = getDefaultAppConfig());
  if (!options2) {
    throw ERROR_FACTORY$1.create(
      "no-options"
      /* AppError.NO_OPTIONS */
    );
  }
  const existingApp = _apps.get(name2);
  if (existingApp) {
    if (deepEqual(options2, existingApp.options) && deepEqual(config2, existingApp.config)) {
      return existingApp;
    } else {
      throw ERROR_FACTORY$1.create("duplicate-app", { appName: name2 });
    }
  }
  const container = new ComponentContainer(name2);
  for (const component of _components.values()) {
    container.addComponent(component);
  }
  const newApp = new FirebaseAppImpl(options2, config2, container);
  _apps.set(name2, newApp);
  return newApp;
}
__name(initializeApp, "initializeApp");
function initializeServerApp(_options, _serverAppConfig) {
  if (isBrowser$1() && !isWebWorker()) {
    throw ERROR_FACTORY$1.create(
      "invalid-server-app-environment"
      /* AppError.INVALID_SERVER_APP_ENVIRONMENT */
    );
  }
  if (_serverAppConfig.automaticDataCollectionEnabled === void 0) {
    _serverAppConfig.automaticDataCollectionEnabled = false;
  }
  let appOptions;
  if (_isFirebaseApp(_options)) {
    appOptions = _options.options;
  } else {
    appOptions = _options;
  }
  const nameObj = Object.assign(Object.assign({}, _serverAppConfig), appOptions);
  if (nameObj.releaseOnDeref !== void 0) {
    delete nameObj.releaseOnDeref;
  }
  const hashCode = /* @__PURE__ */ __name((s2) => {
    return [...s2].reduce((hash, c2) => Math.imul(31, hash) + c2.charCodeAt(0) | 0, 0);
  }, "hashCode");
  if (_serverAppConfig.releaseOnDeref !== void 0) {
    if (typeof FinalizationRegistry === "undefined") {
      throw ERROR_FACTORY$1.create("finalization-registry-not-supported", {});
    }
  }
  const nameString = "" + hashCode(JSON.stringify(nameObj));
  const existingApp = _serverApps.get(nameString);
  if (existingApp) {
    existingApp.incRefCount(_serverAppConfig.releaseOnDeref);
    return existingApp;
  }
  const container = new ComponentContainer(nameString);
  for (const component of _components.values()) {
    container.addComponent(component);
  }
  const newApp = new FirebaseServerAppImpl(appOptions, _serverAppConfig, nameString, container);
  _serverApps.set(nameString, newApp);
  return newApp;
}
__name(initializeServerApp, "initializeServerApp");
function getApp(name2 = DEFAULT_ENTRY_NAME) {
  const app2 = _apps.get(name2);
  if (!app2 && name2 === DEFAULT_ENTRY_NAME && getDefaultAppConfig()) {
    return initializeApp();
  }
  if (!app2) {
    throw ERROR_FACTORY$1.create("no-app", { appName: name2 });
  }
  return app2;
}
__name(getApp, "getApp");
function getApps() {
  return Array.from(_apps.values());
}
__name(getApps, "getApps");
async function deleteApp(app2) {
  let cleanupProviders = false;
  const name2 = app2.name;
  if (_apps.has(name2)) {
    cleanupProviders = true;
    _apps.delete(name2);
  } else if (_serverApps.has(name2)) {
    const firebaseServerApp = app2;
    if (firebaseServerApp.decRefCount() <= 0) {
      _serverApps.delete(name2);
      cleanupProviders = true;
    }
  }
  if (cleanupProviders) {
    await Promise.all(app2.container.getProviders().map((provider) => provider.delete()));
    app2.isDeleted = true;
  }
}
__name(deleteApp, "deleteApp");
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$3.warn(warning.join(" "));
    return;
  }
  _registerComponent(new Component(
    `${library}-version`,
    () => ({ library, version: version2 }),
    "VERSION"
    /* ComponentType.VERSION */
  ));
}
__name(registerVersion, "registerVersion");
function onLog(logCallback, options2) {
  if (logCallback !== null && typeof logCallback !== "function") {
    throw ERROR_FACTORY$1.create(
      "invalid-log-argument"
      /* AppError.INVALID_LOG_ARGUMENT */
    );
  }
  setUserLogHandler(logCallback, options2);
}
__name(onLog, "onLog");
function setLogLevel$1(logLevel) {
  setLogLevel$2(logLevel);
}
__name(setLogLevel$1, "setLogLevel$1");
/**
 * @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$2 = "firebase-heartbeat-database";
const DB_VERSION$2 = 1;
const STORE_NAME$1 = "firebase-heartbeat-store";
let dbPromise$1 = null;
function getDbPromise() {
  if (!dbPromise$1) {
    dbPromise$1 = openDB(DB_NAME$2, DB_VERSION$2, {
      upgrade: /* @__PURE__ */ __name((db, oldVersion) => {
        switch (oldVersion) {
          case 0:
            try {
              db.createObjectStore(STORE_NAME$1);
            } catch (e2) {
              console.warn(e2);
            }
        }
      }, "upgrade")
    }).catch((e2) => {
      throw ERROR_FACTORY$1.create("idb-open", {
        originalErrorMessage: e2.message
      });
    });
  }
  return dbPromise$1;
}
__name(getDbPromise, "getDbPromise");
async function readHeartbeatsFromIndexedDB(app2) {
  try {
    const db = await getDbPromise();
    const tx = db.transaction(STORE_NAME$1);
    const result = await tx.objectStore(STORE_NAME$1).get(computeKey$1(app2));
    await tx.done;
    return result;
  } catch (e2) {
    if (e2 instanceof FirebaseError) {
      logger$3.warn(e2.message);
    } else {
      const idbGetError = ERROR_FACTORY$1.create("idb-get", {
        originalErrorMessage: e2 === null || e2 === void 0 ? void 0 : e2.message
      });
      logger$3.warn(idbGetError.message);
    }
  }
}
__name(readHeartbeatsFromIndexedDB, "readHeartbeatsFromIndexedDB");
async function writeHeartbeatsToIndexedDB(app2, heartbeatObject) {
  try {
    const db = await getDbPromise();
    const tx = db.transaction(STORE_NAME$1, "readwrite");
    const objectStore = tx.objectStore(STORE_NAME$1);
    await objectStore.put(heartbeatObject, computeKey$1(app2));
    await tx.done;
  } catch (e2) {
    if (e2 instanceof FirebaseError) {
      logger$3.warn(e2.message);
    } else {
      const idbGetError = ERROR_FACTORY$1.create("idb-set", {
        originalErrorMessage: e2 === null || e2 === void 0 ? void 0 : e2.message
      });
      logger$3.warn(idbGetError.message);
    }
  }
}
__name(writeHeartbeatsToIndexedDB, "writeHeartbeatsToIndexedDB");
function computeKey$1(app2) {
  return `${app2.name}!${app2.options.appId}`;
}
__name(computeKey$1, "computeKey$1");
/**
 * @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 MAX_NUM_STORED_HEARTBEATS = 30;
class HeartbeatServiceImpl {
  static {
    __name(this, "HeartbeatServiceImpl");
  }
  constructor(container) {
    this.container = container;
    this._heartbeatsCache = null;
    const app2 = this.container.getProvider("app").getImmediate();
    this._storage = new HeartbeatStorageImpl(app2);
    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() {
    var _a2, _b;
    try {
      const platformLogger = this.container.getProvider("platform-logger").getImmediate();
      const agent2 = platformLogger.getPlatformInfoString();
      const date = getUTCDateString();
      if (((_a2 = this._heartbeatsCache) === null || _a2 === void 0 ? void 0 : _a2.heartbeats) == null) {
        this._heartbeatsCache = await this._heartbeatsCachePromise;
        if (((_b = this._heartbeatsCache) === null || _b === void 0 ? void 0 : _b.heartbeats) == null) {
          return;
        }
      }
      if (this._heartbeatsCache.lastSentHeartbeatDate === date || this._heartbeatsCache.heartbeats.some((singleDateHeartbeat) => singleDateHeartbeat.date === date)) {
        return;
      } else {
        this._heartbeatsCache.heartbeats.push({ date, agent: agent2 });
        if (this._heartbeatsCache.heartbeats.length > MAX_NUM_STORED_HEARTBEATS) {
          const earliestHeartbeatIdx = getEarliestHeartbeatIdx(this._heartbeatsCache.heartbeats);
          this._heartbeatsCache.heartbeats.splice(earliestHeartbeatIdx, 1);
        }
      }
      return this._storage.overwrite(this._heartbeatsCache);
    } catch (e2) {
      logger$3.warn(e2);
    }
  }
  /**
   * 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() {
    var _a2;
    try {
      if (this._heartbeatsCache === null) {
        await this._heartbeatsCachePromise;
      }
      if (((_a2 = this._heartbeatsCache) === null || _a2 === void 0 ? void 0 : _a2.heartbeats) == 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;
    } catch (e2) {
      logger$3.warn(e2);
      return "";
    }
  }
}
function getUTCDateString() {
  const today = /* @__PURE__ */ new Date();
  return today.toISOString().substring(0, 10);
}
__name(getUTCDateString, "getUTCDateString");
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
  };
}
__name(extractHeartbeatsForHeader, "extractHeartbeatsForHeader");
class HeartbeatStorageImpl {
  static {
    __name(this, "HeartbeatStorageImpl");
  }
  constructor(app2) {
    this.app = app2;
    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);
      if (idbHeartbeatObject === null || idbHeartbeatObject === void 0 ? void 0 : idbHeartbeatObject.heartbeats) {
        return idbHeartbeatObject;
      } else {
        return { 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;
}
__name(countBytes, "countBytes");
function getEarliestHeartbeatIdx(heartbeats) {
  if (heartbeats.length === 0) {
    return -1;
  }
  let earliestHeartbeatIdx = 0;
  let earliestHeartbeatDate = heartbeats[0].date;
  for (let i2 = 1; i2 < heartbeats.length; i2++) {
    if (heartbeats[i2].date < earliestHeartbeatDate) {
      earliestHeartbeatDate = heartbeats[i2].date;
      earliestHeartbeatIdx = i2;
    }
  }
  return earliestHeartbeatIdx;
}
__name(getEarliestHeartbeatIdx, "getEarliestHeartbeatIdx");
/**
 * @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$q, version$1$1, variant);
  registerVersion(name$q, version$1$1, "esm2017");
  registerVersion("fire-js", "");
}
__name(registerCoreComponents, "registerCoreComponents");
registerCoreComponents("");
var name$a = "firebase";
var version$4 = "11.6.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$a, version$4, "app");
var isVue2 = false;
var isVue3 = true;
var Vue2 = void 0;
function install$7() {
}
__name(install$7, "install$7");
function set$2(target, key, val) {
  if (Array.isArray(target)) {
    target.length = Math.max(target.length, key);
    target.splice(key, 1, val);
    return val;
  }
  target[key] = val;
  return val;
}
__name(set$2, "set$2");
function del$1(target, key) {
  if (Array.isArray(target)) {
    target.splice(key, 1);
    return;
  }
  delete target[key];
}
__name(del$1, "del$1");
/*!
 * pinia v2.2.2
 * (c) 2024 Eduardo San Martin Morote
 * @license MIT
 */
let activePinia;
const setActivePinia = /* @__PURE__ */ __name((pinia2) => activePinia = pinia2, "setActivePinia");
const getActivePinia = /* @__PURE__ */ __name(() => hasInjectionContext() && inject(piniaSymbol) || activePinia, "getActivePinia");
const piniaSymbol = false ? Symbol("pinia") : (
  /* istanbul ignore next */
  Symbol()
);
function isPlainObject$2(o2) {
  return o2 && typeof o2 === "object" && Object.prototype.toString.call(o2) === "[object Object]" && typeof o2.toJSON !== "function";
}
__name(isPlainObject$2, "isPlainObject$2");
var MutationType;
(function(MutationType2) {
  MutationType2["direct"] = "direct";
  MutationType2["patchObject"] = "patch object";
  MutationType2["patchFunction"] = "patch function";
})(MutationType || (MutationType = {}));
const IS_CLIENT = typeof window !== "undefined";
const _global$2 = /* @__PURE__ */ (() => typeof window === "object" && window.window === window ? window : typeof self === "object" && self.self === self ? self : typeof global === "object" && global.global === global ? global : typeof globalThis === "object" ? globalThis : { HTMLElement: null })();
function bom(blob, { autoBom = false } = {}) {
  if (autoBom && /^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) {
    return new Blob([String.fromCharCode(65279), blob], { type: blob.type });
  }
  return blob;
}
__name(bom, "bom");
function download(url, name2, opts) {
  const xhr = new XMLHttpRequest();
  xhr.open("GET", url);
  xhr.responseType = "blob";
  xhr.onload = function() {
    saveAs$1(xhr.response, name2, opts);
  };
  xhr.onerror = function() {
    console.error("could not download file");
  };
  xhr.send();
}
__name(download, "download");
function corsEnabled(url) {
  const xhr = new XMLHttpRequest();
  xhr.open("HEAD", url, false);
  try {
    xhr.send();
  } catch (e2) {
  }
  return xhr.status >= 200 && xhr.status <= 299;
}
__name(corsEnabled, "corsEnabled");
function click(node2) {
  try {
    node2.dispatchEvent(new MouseEvent("click"));
  } catch (e2) {
    const evt = document.createEvent("MouseEvents");
    evt.initMouseEvent("click", true, true, window, 0, 0, 0, 80, 20, false, false, false, false, 0, null);
    node2.dispatchEvent(evt);
  }
}
__name(click, "click");
const _navigator$1 = typeof navigator === "object" ? navigator : { userAgent: "" };
const isMacOSWebView = /* @__PURE__ */ (() => /Macintosh/.test(_navigator$1.userAgent) && /AppleWebKit/.test(_navigator$1.userAgent) && !/Safari/.test(_navigator$1.userAgent))();
const saveAs$1 = !IS_CLIENT ? () => {
} : (
  // Use download attribute first if possible (#193 Lumia mobile) unless this is a macOS WebView or mini program
  typeof HTMLAnchorElement !== "undefined" && "download" in HTMLAnchorElement.prototype && !isMacOSWebView ? downloadSaveAs : (
    // Use msSaveOrOpenBlob as a second approach
    "msSaveOrOpenBlob" in _navigator$1 ? msSaveAs : (
      // Fallback to using FileReader and a popup
      fileSaverSaveAs
    )
  )
);
function downloadSaveAs(blob, name2 = "download", opts) {
  const a2 = document.createElement("a");
  a2.download = name2;
  a2.rel = "noopener";
  if (typeof blob === "string") {
    a2.href = blob;
    if (a2.origin !== location.origin) {
      if (corsEnabled(a2.href)) {
        download(blob, name2, opts);
      } else {
        a2.target = "_blank";
        click(a2);
      }
    } else {
      click(a2);
    }
  } else {
    a2.href = URL.createObjectURL(blob);
    setTimeout(function() {
      URL.revokeObjectURL(a2.href);
    }, 4e4);
    setTimeout(function() {
      click(a2);
    }, 0);
  }
}
__name(downloadSaveAs, "downloadSaveAs");
function msSaveAs(blob, name2 = "download", opts) {
  if (typeof blob === "string") {
    if (corsEnabled(blob)) {
      download(blob, name2, opts);
    } else {
      const a2 = document.createElement("a");
      a2.href = blob;
      a2.target = "_blank";
      setTimeout(function() {
        click(a2);
      });
    }
  } else {
    navigator.msSaveOrOpenBlob(bom(blob, opts), name2);
  }
}
__name(msSaveAs, "msSaveAs");
function fileSaverSaveAs(blob, name2, opts, popup) {
  popup = popup || open("", "_blank");
  if (popup) {
    popup.document.title = popup.document.body.innerText = "downloading...";
  }
  if (typeof blob === "string")
    return download(blob, name2, opts);
  const force = blob.type === "application/octet-stream";
  const isSafari3 = /constructor/i.test(String(_global$2.HTMLElement)) || "safari" in _global$2;
  const isChromeIOS = /CriOS\/[\d]+/.test(navigator.userAgent);
  if ((isChromeIOS || force && isSafari3 || isMacOSWebView) && typeof FileReader !== "undefined") {
    const reader = new FileReader();
    reader.onloadend = function() {
      let url = reader.result;
      if (typeof url !== "string") {
        popup = null;
        throw new Error("Wrong reader.result type");
      }
      url = isChromeIOS ? url : url.replace(/^data:[^;]*;/, "data:attachment/file;");
      if (popup) {
        popup.location.href = url;
      } else {
        location.assign(url);
      }
      popup = null;
    };
    reader.readAsDataURL(blob);
  } else {
    const url = URL.createObjectURL(blob);
    if (popup)
      popup.location.assign(url);
    else
      location.href = url;
    popup = null;
    setTimeout(function() {
      URL.revokeObjectURL(url);
    }, 4e4);
  }
}
__name(fileSaverSaveAs, "fileSaverSaveAs");
function toastMessage(message, type) {
  const piniaMessage = "🍍 " + message;
  if (typeof __VUE_DEVTOOLS_TOAST__ === "function") {
    __VUE_DEVTOOLS_TOAST__(piniaMessage, type);
  } else if (type === "error") {
    console.error(piniaMessage);
  } else if (type === "warn") {
    console.warn(piniaMessage);
  } else {
    console.log(piniaMessage);
  }
}
__name(toastMessage, "toastMessage");
function isPinia(o2) {
  return "_a" in o2 && "install" in o2;
}
__name(isPinia, "isPinia");
function checkClipboardAccess() {
  if (!("clipboard" in navigator)) {
    toastMessage(`Your browser doesn't support the Clipboard API`, "error");
    return true;
  }
}
__name(checkClipboardAccess, "checkClipboardAccess");
function checkNotFocusedError(error2) {
  if (error2 instanceof Error && error2.message.toLowerCase().includes("document is not focused")) {
    toastMessage('You need to activate the "Emulate a focused page" setting in the "Rendering" panel of devtools.', "warn");
    return true;
  }
  return false;
}
__name(checkNotFocusedError, "checkNotFocusedError");
async function actionGlobalCopyState(pinia2) {
  if (checkClipboardAccess())
    return;
  try {
    await navigator.clipboard.writeText(JSON.stringify(pinia2.state.value));
    toastMessage("Global state copied to clipboard.");
  } catch (error2) {
    if (checkNotFocusedError(error2))
      return;
    toastMessage(`Failed to serialize the state. Check the console for more details.`, "error");
    console.error(error2);
  }
}
__name(actionGlobalCopyState, "actionGlobalCopyState");
async function actionGlobalPasteState(pinia2) {
  if (checkClipboardAccess())
    return;
  try {
    loadStoresState(pinia2, JSON.parse(await navigator.clipboard.readText()));
    toastMessage("Global state pasted from clipboard.");
  } catch (error2) {
    if (checkNotFocusedError(error2))
      return;
    toastMessage(`Failed to deserialize the state from clipboard. Check the console for more details.`, "error");
    console.error(error2);
  }
}
__name(actionGlobalPasteState, "actionGlobalPasteState");
async function actionGlobalSaveState(pinia2) {
  try {
    saveAs$1(new Blob([JSON.stringify(pinia2.state.value)], {
      type: "text/plain;charset=utf-8"
    }), "pinia-state.json");
  } catch (error2) {
    toastMessage(`Failed to export the state as JSON. Check the console for more details.`, "error");
    console.error(error2);
  }
}
__name(actionGlobalSaveState, "actionGlobalSaveState");
let fileInput;
function getFileOpener() {
  if (!fileInput) {
    fileInput = document.createElement("input");
    fileInput.type = "file";
    fileInput.accept = ".json";
  }
  function openFile() {
    return new Promise((resolve2, reject) => {
      fileInput.onchange = async () => {
        const files = fileInput.files;
        if (!files)
          return resolve2(null);
        const file = files.item(0);
        if (!file)
          return resolve2(null);
        return resolve2({ text: await file.text(), file });
      };
      fileInput.oncancel = () => resolve2(null);
      fileInput.onerror = reject;
      fileInput.click();
    });
  }
  __name(openFile, "openFile");
  return openFile;
}
__name(getFileOpener, "getFileOpener");
async function actionGlobalOpenStateFile(pinia2) {
  try {
    const open2 = getFileOpener();
    const result = await open2();
    if (!result)
      return;
    const { text: text2, file } = result;
    loadStoresState(pinia2, JSON.parse(text2));
    toastMessage(`Global state imported from "${file.name}".`);
  } catch (error2) {
    toastMessage(`Failed to import the state from JSON. Check the console for more details.`, "error");
    console.error(error2);
  }
}
__name(actionGlobalOpenStateFile, "actionGlobalOpenStateFile");
function loadStoresState(pinia2, state) {
  for (const key in state) {
    const storeState = pinia2.state.value[key];
    if (storeState) {
      Object.assign(storeState, state[key]);
    } else {
      pinia2.state.value[key] = state[key];
    }
  }
}
__name(loadStoresState, "loadStoresState");
function formatDisplay$1(display) {
  return {
    _custom: {
      display
    }
  };
}
__name(formatDisplay$1, "formatDisplay$1");
const PINIA_ROOT_LABEL = "🍍 Pinia (root)";
const PINIA_ROOT_ID = "_root";
function formatStoreForInspectorTree(store) {
  return isPinia(store) ? {
    id: PINIA_ROOT_ID,
    label: PINIA_ROOT_LABEL
  } : {
    id: store.$id,
    label: store.$id
  };
}
__name(formatStoreForInspectorTree, "formatStoreForInspectorTree");
function formatStoreForInspectorState(store) {
  if (isPinia(store)) {
    const storeNames = Array.from(store._s.keys());
    const storeMap = store._s;
    const state2 = {
      state: storeNames.map((storeId) => ({
        editable: true,
        key: storeId,
        value: store.state.value[storeId]
      })),
      getters: storeNames.filter((id2) => storeMap.get(id2)._getters).map((id2) => {
        const store2 = storeMap.get(id2);
        return {
          editable: false,
          key: id2,
          value: store2._getters.reduce((getters, key) => {
            getters[key] = store2[key];
            return getters;
          }, {})
        };
      })
    };
    return state2;
  }
  const state = {
    state: Object.keys(store.$state).map((key) => ({
      editable: true,
      key,
      value: store.$state[key]
    }))
  };
  if (store._getters && store._getters.length) {
    state.getters = store._getters.map((getterName) => ({
      editable: false,
      key: getterName,
      value: store[getterName]
    }));
  }
  if (store._customProperties.size) {
    state.customProperties = Array.from(store._customProperties).map((key) => ({
      editable: true,
      key,
      value: store[key]
    }));
  }
  return state;
}
__name(formatStoreForInspectorState, "formatStoreForInspectorState");
function formatEventData(events2) {
  if (!events2)
    return {};
  if (Array.isArray(events2)) {
    return events2.reduce((data, event) => {
      data.keys.push(event.key);
      data.operations.push(event.type);
      data.oldValue[event.key] = event.oldValue;
      data.newValue[event.key] = event.newValue;
      return data;
    }, {
      oldValue: {},
      keys: [],
      operations: [],
      newValue: {}
    });
  } else {
    return {
      operation: formatDisplay$1(events2.type),
      key: formatDisplay$1(events2.key),
      oldValue: events2.oldValue,
      newValue: events2.newValue
    };
  }
}
__name(formatEventData, "formatEventData");
function formatMutationType(type) {
  switch (type) {
    case MutationType.direct:
      return "mutation";
    case MutationType.patchFunction:
      return "$patch";
    case MutationType.patchObject:
      return "$patch";
    default:
      return "unknown";
  }
}
__name(formatMutationType, "formatMutationType");
let isTimelineActive = true;
const componentStateTypes = [];
const MUTATIONS_LAYER_ID = "pinia:mutations";
const INSPECTOR_ID = "pinia";
const { assign: assign$1$1 } = Object;
const getStoreType = /* @__PURE__ */ __name((id2) => "🍍 " + id2, "getStoreType");
function registerPiniaDevtools(app2, pinia2) {
  setupDevtoolsPlugin({
    id: "dev.esm.pinia",
    label: "Pinia 🍍",
    logo: "https://pinia.vuejs.org/logo.svg",
    packageName: "pinia",
    homepage: "https://pinia.vuejs.org",
    componentStateTypes,
    app: app2
  }, (api2) => {
    if (typeof api2.now !== "function") {
      toastMessage("You seem to be using an outdated version of Vue Devtools. Are you still using the Beta release instead of the stable one? You can find the links at https://devtools.vuejs.org/guide/installation.html.");
    }
    api2.addTimelineLayer({
      id: MUTATIONS_LAYER_ID,
      label: `Pinia 🍍`,
      color: 15064968
    });
    api2.addInspector({
      id: INSPECTOR_ID,
      label: "Pinia 🍍",
      icon: "storage",
      treeFilterPlaceholder: "Search stores",
      actions: [
        {
          icon: "content_copy",
          action: /* @__PURE__ */ __name(() => {
            actionGlobalCopyState(pinia2);
          }, "action"),
          tooltip: "Serialize and copy the state"
        },
        {
          icon: "content_paste",
          action: /* @__PURE__ */ __name(async () => {
            await actionGlobalPasteState(pinia2);
            api2.sendInspectorTree(INSPECTOR_ID);
            api2.sendInspectorState(INSPECTOR_ID);
          }, "action"),
          tooltip: "Replace the state with the content of your clipboard"
        },
        {
          icon: "save",
          action: /* @__PURE__ */ __name(() => {
            actionGlobalSaveState(pinia2);
          }, "action"),
          tooltip: "Save the state as a JSON file"
        },
        {
          icon: "folder_open",
          action: /* @__PURE__ */ __name(async () => {
            await actionGlobalOpenStateFile(pinia2);
            api2.sendInspectorTree(INSPECTOR_ID);
            api2.sendInspectorState(INSPECTOR_ID);
          }, "action"),
          tooltip: "Import the state from a JSON file"
        }
      ],
      nodeActions: [
        {
          icon: "restore",
          tooltip: 'Reset the state (with "$reset")',
          action: /* @__PURE__ */ __name((nodeId) => {
            const store = pinia2._s.get(nodeId);
            if (!store) {
              toastMessage(`Cannot reset "${nodeId}" store because it wasn't found.`, "warn");
            } else if (typeof store.$reset !== "function") {
              toastMessage(`Cannot reset "${nodeId}" store because it doesn't have a "$reset" method implemented.`, "warn");
            } else {
              store.$reset();
              toastMessage(`Store "${nodeId}" reset.`);
            }
          }, "action")
        }
      ]
    });
    api2.on.inspectComponent((payload, ctx) => {
      const proxy = payload.componentInstance && payload.componentInstance.proxy;
      if (proxy && proxy._pStores) {
        const piniaStores = payload.componentInstance.proxy._pStores;
        Object.values(piniaStores).forEach((store) => {
          payload.instanceData.state.push({
            type: getStoreType(store.$id),
            key: "state",
            editable: true,
            value: store._isOptionsAPI ? {
              _custom: {
                value: toRaw(store.$state),
                actions: [
                  {
                    icon: "restore",
                    tooltip: "Reset the state of this store",
                    action: /* @__PURE__ */ __name(() => store.$reset(), "action")
                  }
                ]
              }
            } : (
              // NOTE: workaround to unwrap transferred refs
              Object.keys(store.$state).reduce((state, key) => {
                state[key] = store.$state[key];
                return state;
              }, {})
            )
          });
          if (store._getters && store._getters.length) {
            payload.instanceData.state.push({
              type: getStoreType(store.$id),
              key: "getters",
              editable: false,
              value: store._getters.reduce((getters, key) => {
                try {
                  getters[key] = store[key];
                } catch (error2) {
                  getters[key] = error2;
                }
                return getters;
              }, {})
            });
          }
        });
      }
    });
    api2.on.getInspectorTree((payload) => {
      if (payload.app === app2 && payload.inspectorId === INSPECTOR_ID) {
        let stores = [pinia2];
        stores = stores.concat(Array.from(pinia2._s.values()));
        payload.rootNodes = (payload.filter ? stores.filter((store) => "$id" in store ? store.$id.toLowerCase().includes(payload.filter.toLowerCase()) : PINIA_ROOT_LABEL.toLowerCase().includes(payload.filter.toLowerCase())) : stores).map(formatStoreForInspectorTree);
      }
    });
    globalThis.$pinia = pinia2;
    api2.on.getInspectorState((payload) => {
      if (payload.app === app2 && payload.inspectorId === INSPECTOR_ID) {
        const inspectedStore = payload.nodeId === PINIA_ROOT_ID ? pinia2 : pinia2._s.get(payload.nodeId);
        if (!inspectedStore) {
          return;
        }
        if (inspectedStore) {
          if (payload.nodeId !== PINIA_ROOT_ID)
            globalThis.$store = toRaw(inspectedStore);
          payload.state = formatStoreForInspectorState(inspectedStore);
        }
      }
    });
    api2.on.editInspectorState((payload, ctx) => {
      if (payload.app === app2 && payload.inspectorId === INSPECTOR_ID) {
        const inspectedStore = payload.nodeId === PINIA_ROOT_ID ? pinia2 : pinia2._s.get(payload.nodeId);
        if (!inspectedStore) {
          return toastMessage(`store "${payload.nodeId}" not found`, "error");
        }
        const { path } = payload;
        if (!isPinia(inspectedStore)) {
          if (path.length !== 1 || !inspectedStore._customProperties.has(path[0]) || path[0] in inspectedStore.$state) {
            path.unshift("$state");
          }
        } else {
          path.unshift("state");
        }
        isTimelineActive = false;
        payload.set(inspectedStore, path, payload.state.value);
        isTimelineActive = true;
      }
    });
    api2.on.editComponentState((payload) => {
      if (payload.type.startsWith("🍍")) {
        const storeId = payload.type.replace(/^🍍\s*/, "");
        const store = pinia2._s.get(storeId);
        if (!store) {
          return toastMessage(`store "${storeId}" not found`, "error");
        }
        const { path } = payload;
        if (path[0] !== "state") {
          return toastMessage(`Invalid path for store "${storeId}":
${path}
Only state can be modified.`);
        }
        path[0] = "$state";
        isTimelineActive = false;
        payload.set(store, path, payload.state.value);
        isTimelineActive = true;
      }
    });
  });
}
__name(registerPiniaDevtools, "registerPiniaDevtools");
function addStoreToDevtools(app2, store) {
  if (!componentStateTypes.includes(getStoreType(store.$id))) {
    componentStateTypes.push(getStoreType(store.$id));
  }
  setupDevtoolsPlugin({
    id: "dev.esm.pinia",
    label: "Pinia 🍍",
    logo: "https://pinia.vuejs.org/logo.svg",
    packageName: "pinia",
    homepage: "https://pinia.vuejs.org",
    componentStateTypes,
    app: app2,
    settings: {
      logStoreChanges: {
        label: "Notify about new/deleted stores",
        type: "boolean",
        defaultValue: true
      }
      // useEmojis: {
      //   label: 'Use emojis in messages ⚡️',
      //   type: 'boolean',
      //   defaultValue: true,
      // },
    }
  }, (api2) => {
    const now2 = typeof api2.now === "function" ? api2.now.bind(api2) : Date.now;
    store.$onAction(({ after, onError, name: name2, args }) => {
      const groupId = runningActionId++;
      api2.addTimelineEvent({
        layerId: MUTATIONS_LAYER_ID,
        event: {
          time: now2(),
          title: "🛫 " + name2,
          subtitle: "start",
          data: {
            store: formatDisplay$1(store.$id),
            action: formatDisplay$1(name2),
            args
          },
          groupId
        }
      });
      after((result) => {
        activeAction = void 0;
        api2.addTimelineEvent({
          layerId: MUTATIONS_LAYER_ID,
          event: {
            time: now2(),
            title: "🛬 " + name2,
            subtitle: "end",
            data: {
              store: formatDisplay$1(store.$id),
              action: formatDisplay$1(name2),
              args,
              result
            },
            groupId
          }
        });
      });
      onError((error2) => {
        activeAction = void 0;
        api2.addTimelineEvent({
          layerId: MUTATIONS_LAYER_ID,
          event: {
            time: now2(),
            logType: "error",
            title: "💥 " + name2,
            subtitle: "end",
            data: {
              store: formatDisplay$1(store.$id),
              action: formatDisplay$1(name2),
              args,
              error: error2
            },
            groupId
          }
        });
      });
    }, true);
    store._customProperties.forEach((name2) => {
      watch(() => unref(store[name2]), (newValue2, oldValue) => {
        api2.notifyComponentUpdate();
        api2.sendInspectorState(INSPECTOR_ID);
        if (isTimelineActive) {
          api2.addTimelineEvent({
            layerId: MUTATIONS_LAYER_ID,
            event: {
              time: now2(),
              title: "Change",
              subtitle: name2,
              data: {
                newValue: newValue2,
                oldValue
              },
              groupId: activeAction
            }
          });
        }
      }, { deep: true });
    });
    store.$subscribe(({ events: events2, type }, state) => {
      api2.notifyComponentUpdate();
      api2.sendInspectorState(INSPECTOR_ID);
      if (!isTimelineActive)
        return;
      const eventData = {
        time: now2(),
        title: formatMutationType(type),
        data: assign$1$1({ store: formatDisplay$1(store.$id) }, formatEventData(events2)),
        groupId: activeAction
      };
      if (type === MutationType.patchFunction) {
        eventData.subtitle = "⤵️";
      } else if (type === MutationType.patchObject) {
        eventData.subtitle = "🧩";
      } else if (events2 && !Array.isArray(events2)) {
        eventData.subtitle = events2.type;
      }
      if (events2) {
        eventData.data["rawEvent(s)"] = {
          _custom: {
            display: "DebuggerEvent",
            type: "object",
            tooltip: "raw DebuggerEvent[]",
            value: events2
          }
        };
      }
      api2.addTimelineEvent({
        layerId: MUTATIONS_LAYER_ID,
        event: eventData
      });
    }, { detached: true, flush: "sync" });
    const hotUpdate = store._hotUpdate;
    store._hotUpdate = markRaw((newStore) => {
      hotUpdate(newStore);
      api2.addTimelineEvent({
        layerId: MUTATIONS_LAYER_ID,
        event: {
          time: now2(),
          title: "🔥 " + store.$id,
          subtitle: "HMR update",
          data: {
            store: formatDisplay$1(store.$id),
            info: formatDisplay$1(`HMR update`)
          }
        }
      });
      api2.notifyComponentUpdate();
      api2.sendInspectorTree(INSPECTOR_ID);
      api2.sendInspectorState(INSPECTOR_ID);
    });
    const { $dispose } = store;
    store.$dispose = () => {
      $dispose();
      api2.notifyComponentUpdate();
      api2.sendInspectorTree(INSPECTOR_ID);
      api2.sendInspectorState(INSPECTOR_ID);
      api2.getSettings().logStoreChanges && toastMessage(`Disposed "${store.$id}" store 🗑`);
    };
    api2.notifyComponentUpdate();
    api2.sendInspectorTree(INSPECTOR_ID);
    api2.sendInspectorState(INSPECTOR_ID);
    api2.getSettings().logStoreChanges && toastMessage(`"${store.$id}" store installed 🆕`);
  });
}
__name(addStoreToDevtools, "addStoreToDevtools");
let runningActionId = 0;
let activeAction;
function patchActionForGrouping(store, actionNames, wrapWithProxy) {
  const actions = actionNames.reduce((storeActions, actionName) => {
    storeActions[actionName] = toRaw(store)[actionName];
    return storeActions;
  }, {});
  for (const actionName in actions) {
    store[actionName] = function() {
      const _actionId = runningActionId;
      const trackedStore = wrapWithProxy ? new Proxy(store, {
        get(...args) {
          activeAction = _actionId;
          return Reflect.get(...args);
        },
        set(...args) {
          activeAction = _actionId;
          return Reflect.set(...args);
        }
      }) : store;
      activeAction = _actionId;
      const retValue = actions[actionName].apply(trackedStore, arguments);
      activeAction = void 0;
      return retValue;
    };
  }
}
__name(patchActionForGrouping, "patchActionForGrouping");
function devtoolsPlugin({ app: app2, store, options: options2 }) {
  if (store.$id.startsWith("__hot:")) {
    return;
  }
  store._isOptionsAPI = !!options2.state;
  if (!store._p._testing) {
    patchActionForGrouping(store, Object.keys(options2.actions), store._isOptionsAPI);
    const originalHotUpdate = store._hotUpdate;
    toRaw(store)._hotUpdate = function(newStore) {
      originalHotUpdate.apply(this, arguments);
      patchActionForGrouping(store, Object.keys(newStore._hmrPayload.actions), !!store._isOptionsAPI);
    };
  }
  addStoreToDevtools(
    app2,
    // FIXME: is there a way to allow the assignment from Store<Id, S, G, A> to StoreGeneric?
    store
  );
}
__name(devtoolsPlugin, "devtoolsPlugin");
function createPinia() {
  const scope = effectScope(true);
  const state = scope.run(() => ref$3({}));
  let _p = [];
  let toBeInstalled = [];
  const pinia2 = markRaw({
    install(app2) {
      setActivePinia(pinia2);
      if (!isVue2) {
        pinia2._a = app2;
        app2.provide(piniaSymbol, pinia2);
        app2.config.globalProperties.$pinia = pinia2;
        if (false) {
          registerPiniaDevtools(app2, pinia2);
        }
        toBeInstalled.forEach((plugin) => _p.push(plugin));
        toBeInstalled = [];
      }
    },
    use(plugin) {
      if (!this._a && !isVue2) {
        toBeInstalled.push(plugin);
      } else {
        _p.push(plugin);
      }
      return this;
    },
    _p,
    // it's actually undefined here
    // @ts-expect-error
    _a: null,
    _e: scope,
    _s: /* @__PURE__ */ new Map(),
    state
  });
  if (false) {
    pinia2.use(devtoolsPlugin);
  }
  return pinia2;
}
__name(createPinia, "createPinia");
function disposePinia(pinia2) {
  pinia2._e.stop();
  pinia2._s.clear();
  pinia2._p.splice(0);
  pinia2.state.value = {};
  pinia2._a = null;
}
__name(disposePinia, "disposePinia");
const isUseStore = /* @__PURE__ */ __name((fn) => {
  return typeof fn === "function" && typeof fn.$id === "string";
}, "isUseStore");
function patchObject(newState, oldState) {
  for (const key in oldState) {
    const subPatch = oldState[key];
    if (!(key in newState)) {
      continue;
    }
    const targetValue = newState[key];
    if (isPlainObject$2(targetValue) && isPlainObject$2(subPatch) && !isRef(subPatch) && !isReactive(subPatch)) {
      newState[key] = patchObject(targetValue, subPatch);
    } else {
      if (isVue2) {
        set$2(newState, key, subPatch);
      } else {
        newState[key] = subPatch;
      }
    }
  }
  return newState;
}
__name(patchObject, "patchObject");
function acceptHMRUpdate(initialUseStore, hot) {
  if (true) {
    return () => {
    };
  }
  return (newModule) => {
    const pinia2 = hot.data.pinia || initialUseStore._pinia;
    if (!pinia2) {
      return;
    }
    hot.data.pinia = pinia2;
    for (const exportName in newModule) {
      const useStore = newModule[exportName];
      if (isUseStore(useStore) && pinia2._s.has(useStore.$id)) {
        const id2 = useStore.$id;
        if (id2 !== initialUseStore.$id) {
          console.warn(`The id of the store changed from "${initialUseStore.$id}" to "${id2}". Reloading.`);
          return hot.invalidate();
        }
        const existingStore = pinia2._s.get(id2);
        if (!existingStore) {
          console.log(`[Pinia]: skipping hmr because store doesn't exist yet`);
          return;
        }
        useStore(pinia2, existingStore);
      }
    }
  };
}
__name(acceptHMRUpdate, "acceptHMRUpdate");
const noop$5 = /* @__PURE__ */ __name(() => {
}, "noop$5");
function addSubscription(subscriptions, callback, detached, onCleanup = noop$5) {
  subscriptions.push(callback);
  const removeSubscription = /* @__PURE__ */ __name(() => {
    const idx = subscriptions.indexOf(callback);
    if (idx > -1) {
      subscriptions.splice(idx, 1);
      onCleanup();
    }
  }, "removeSubscription");
  if (!detached && getCurrentScope$1()) {
    onScopeDispose(removeSubscription);
  }
  return removeSubscription;
}
__name(addSubscription, "addSubscription");
function triggerSubscriptions(subscriptions, ...args) {
  subscriptions.slice().forEach((callback) => {
    callback(...args);
  });
}
__name(triggerSubscriptions, "triggerSubscriptions");
const fallbackRunWithContext = /* @__PURE__ */ __name((fn) => fn(), "fallbackRunWithContext");
const ACTION_MARKER = Symbol();
const ACTION_NAME = Symbol();
function mergeReactiveObjects(target, patchToApply) {
  if (target instanceof Map && patchToApply instanceof Map) {
    patchToApply.forEach((value, key) => target.set(key, value));
  } else if (target instanceof Set && patchToApply instanceof Set) {
    patchToApply.forEach(target.add, target);
  }
  for (const key in patchToApply) {
    if (!patchToApply.hasOwnProperty(key))
      continue;
    const subPatch = patchToApply[key];
    const targetValue = target[key];
    if (isPlainObject$2(targetValue) && isPlainObject$2(subPatch) && target.hasOwnProperty(key) && !isRef(subPatch) && !isReactive(subPatch)) {
      target[key] = mergeReactiveObjects(targetValue, subPatch);
    } else {
      target[key] = subPatch;
    }
  }
  return target;
}
__name(mergeReactiveObjects, "mergeReactiveObjects");
const skipHydrateSymbol = false ? Symbol("pinia:skipHydration") : (
  /* istanbul ignore next */
  Symbol()
);
const skipHydrateMap = /* @__PURE__ */ new WeakMap();
function skipHydrate(obj) {
  return isVue2 ? (
    // in @vue/composition-api, the refs are sealed so defineProperty doesn't work...
    /* istanbul ignore next */
    skipHydrateMap.set(obj, 1) && obj
  ) : Object.defineProperty(obj, skipHydrateSymbol, {});
}
__name(skipHydrate, "skipHydrate");
function shouldHydrate(obj) {
  return isVue2 ? (
    /* istanbul ignore next */
    !skipHydrateMap.has(obj)
  ) : !isPlainObject$2(obj) || !obj.hasOwnProperty(skipHydrateSymbol);
}
__name(shouldHydrate, "shouldHydrate");
const { assign: assign$4 } = Object;
function isComputed(o2) {
  return !!(isRef(o2) && o2.effect);
}
__name(isComputed, "isComputed");
function createOptionsStore(id2, options2, pinia2, hot) {
  const { state, actions, getters } = options2;
  const initialState = pinia2.state.value[id2];
  let store;
  function setup2() {
    if (!initialState && true) {
      if (isVue2) {
        set$2(pinia2.state.value, id2, state ? state() : {});
      } else {
        pinia2.state.value[id2] = state ? state() : {};
      }
    }
    const localState = false ? (
      // use ref() to unwrap refs inside state TODO: check if this is still necessary
      toRefs$1(ref$3(state ? state() : {}).value)
    ) : toRefs$1(pinia2.state.value[id2]);
    return assign$4(localState, actions, Object.keys(getters || {}).reduce((computedGetters, name2) => {
      if (false) {
        console.warn(`[🍍]: A getter cannot have the same name as another state property. Rename one of them. Found with "${name2}" in store "${id2}".`);
      }
      computedGetters[name2] = markRaw(computed(() => {
        setActivePinia(pinia2);
        const store2 = pinia2._s.get(id2);
        if (isVue2 && !store2._r)
          return;
        return getters[name2].call(store2, store2);
      }));
      return computedGetters;
    }, {}));
  }
  __name(setup2, "setup");
  store = createSetupStore(id2, setup2, options2, pinia2, hot, true);
  return store;
}
__name(createOptionsStore, "createOptionsStore");
function createSetupStore($id, setup2, options2 = {}, pinia2, hot, isOptionsStore) {
  let scope;
  const optionsForPlugin = assign$4({ actions: {} }, options2);
  if (false) {
    throw new Error("Pinia destroyed");
  }
  const $subscribeOptions = { deep: true };
  if (false) {
    $subscribeOptions.onTrigger = (event) => {
      if (isListening) {
        debuggerEvents = event;
      } else if (isListening == false && !store._hotUpdating) {
        if (Array.isArray(debuggerEvents)) {
          debuggerEvents.push(event);
        } else {
          console.error("🍍 debuggerEvents should be an array. This is most likely an internal Pinia bug.");
        }
      }
    };
  }
  let isListening;
  let isSyncListening;
  let subscriptions = [];
  let actionSubscriptions = [];
  let debuggerEvents;
  const initialState = pinia2.state.value[$id];
  if (!isOptionsStore && !initialState && true) {
    if (isVue2) {
      set$2(pinia2.state.value, $id, {});
    } else {
      pinia2.state.value[$id] = {};
    }
  }
  const hotState = ref$3({});
  let activeListener;
  function $patch(partialStateOrMutator) {
    let subscriptionMutation;
    isListening = isSyncListening = false;
    if (false) {
      debuggerEvents = [];
    }
    if (typeof partialStateOrMutator === "function") {
      partialStateOrMutator(pinia2.state.value[$id]);
      subscriptionMutation = {
        type: MutationType.patchFunction,
        storeId: $id,
        events: debuggerEvents
      };
    } else {
      mergeReactiveObjects(pinia2.state.value[$id], partialStateOrMutator);
      subscriptionMutation = {
        type: MutationType.patchObject,
        payload: partialStateOrMutator,
        storeId: $id,
        events: debuggerEvents
      };
    }
    const myListenerId = activeListener = Symbol();
    nextTick().then(() => {
      if (activeListener === myListenerId) {
        isListening = true;
      }
    });
    isSyncListening = true;
    triggerSubscriptions(subscriptions, subscriptionMutation, pinia2.state.value[$id]);
  }
  __name($patch, "$patch");
  const $reset = isOptionsStore ? /* @__PURE__ */ __name(function $reset2() {
    const { state } = options2;
    const newState = state ? state() : {};
    this.$patch(($state) => {
      assign$4($state, newState);
    });
  }, "$reset2") : (
    /* istanbul ignore next */
    false ? () => {
      throw new Error(`🍍: Store "${$id}" is built using the setup syntax and does not implement $reset().`);
    } : noop$5
  );
  function $dispose() {
    scope.stop();
    subscriptions = [];
    actionSubscriptions = [];
    pinia2._s.delete($id);
  }
  __name($dispose, "$dispose");
  const action = /* @__PURE__ */ __name((fn, name2 = "") => {
    if (ACTION_MARKER in fn) {
      fn[ACTION_NAME] = name2;
      return fn;
    }
    const wrappedAction = /* @__PURE__ */ __name(function() {
      setActivePinia(pinia2);
      const args = Array.from(arguments);
      const afterCallbackList = [];
      const onErrorCallbackList = [];
      function after(callback) {
        afterCallbackList.push(callback);
      }
      __name(after, "after");
      function onError(callback) {
        onErrorCallbackList.push(callback);
      }
      __name(onError, "onError");
      triggerSubscriptions(actionSubscriptions, {
        args,
        name: wrappedAction[ACTION_NAME],
        store,
        after,
        onError
      });
      let ret;
      try {
        ret = fn.apply(this && this.$id === $id ? this : store, args);
      } catch (error2) {
        triggerSubscriptions(onErrorCallbackList, error2);
        throw error2;
      }
      if (ret instanceof Promise) {
        return ret.then((value) => {
          triggerSubscriptions(afterCallbackList, value);
          return value;
        }).catch((error2) => {
          triggerSubscriptions(onErrorCallbackList, error2);
          return Promise.reject(error2);
        });
      }
      triggerSubscriptions(afterCallbackList, ret);
      return ret;
    }, "wrappedAction");
    wrappedAction[ACTION_MARKER] = true;
    wrappedAction[ACTION_NAME] = name2;
    return wrappedAction;
  }, "action");
  const _hmrPayload = /* @__PURE__ */ markRaw({
    actions: {},
    getters: {},
    state: [],
    hotState
  });
  const partialStore = {
    _p: pinia2,
    // _s: scope,
    $id,
    $onAction: addSubscription.bind(null, actionSubscriptions),
    $patch,
    $reset,
    $subscribe(callback, options22 = {}) {
      const removeSubscription = addSubscription(subscriptions, callback, options22.detached, () => stopWatcher());
      const stopWatcher = scope.run(() => watch(() => pinia2.state.value[$id], (state) => {
        if (options22.flush === "sync" ? isSyncListening : isListening) {
          callback({
            storeId: $id,
            type: MutationType.direct,
            events: debuggerEvents
          }, state);
        }
      }, assign$4({}, $subscribeOptions, options22)));
      return removeSubscription;
    },
    $dispose
  };
  if (isVue2) {
    partialStore._r = false;
  }
  const store = reactive(false ? assign$4(
    {
      _hmrPayload,
      _customProperties: markRaw(/* @__PURE__ */ new Set())
      // devtools custom properties
    },
    partialStore
    // must be added later
    // setupStore
  ) : partialStore);
  pinia2._s.set($id, store);
  const runWithContext = pinia2._a && pinia2._a.runWithContext || fallbackRunWithContext;
  const setupStore = runWithContext(() => pinia2._e.run(() => (scope = effectScope()).run(() => setup2({ action }))));
  for (const key in setupStore) {
    const prop2 = setupStore[key];
    if (isRef(prop2) && !isComputed(prop2) || isReactive(prop2)) {
      if (false) {
        set$2(hotState.value, key, toRef$1(setupStore, key));
      } else if (!isOptionsStore) {
        if (initialState && shouldHydrate(prop2)) {
          if (isRef(prop2)) {
            prop2.value = initialState[key];
          } else {
            mergeReactiveObjects(prop2, initialState[key]);
          }
        }
        if (isVue2) {
          set$2(pinia2.state.value[$id], key, prop2);
        } else {
          pinia2.state.value[$id][key] = prop2;
        }
      }
      if (false) {
        _hmrPayload.state.push(key);
      }
    } else if (typeof prop2 === "function") {
      const actionValue = false ? prop2 : action(prop2, key);
      if (isVue2) {
        set$2(setupStore, key, actionValue);
      } else {
        setupStore[key] = actionValue;
      }
      if (false) {
        _hmrPayload.actions[key] = prop2;
      }
      optionsForPlugin.actions[key] = prop2;
    } else if (false) {
      if (isComputed(prop2)) {
        _hmrPayload.getters[key] = isOptionsStore ? (
          // @ts-expect-error
          options2.getters[key]
        ) : prop2;
        if (IS_CLIENT) {
          const getters = setupStore._getters || // @ts-expect-error: same
          (setupStore._getters = markRaw([]));
          getters.push(key);
        }
      }
    }
  }
  if (isVue2) {
    Object.keys(setupStore).forEach((key) => {
      set$2(store, key, setupStore[key]);
    });
  } else {
    assign$4(store, setupStore);
    assign$4(toRaw(store), setupStore);
  }
  Object.defineProperty(store, "$state", {
    get: /* @__PURE__ */ __name(() => false ? hotState.value : pinia2.state.value[$id], "get"),
    set: /* @__PURE__ */ __name((state) => {
      if (false) {
        throw new Error("cannot set hotState");
      }
      $patch(($state) => {
        assign$4($state, state);
      });
    }, "set")
  });
  if (false) {
    store._hotUpdate = markRaw((newStore) => {
      store._hotUpdating = true;
      newStore._hmrPayload.state.forEach((stateKey) => {
        if (stateKey in store.$state) {
          const newStateTarget = newStore.$state[stateKey];
          const oldStateSource = store.$state[stateKey];
          if (typeof newStateTarget === "object" && isPlainObject$2(newStateTarget) && isPlainObject$2(oldStateSource)) {
            patchObject(newStateTarget, oldStateSource);
          } else {
            newStore.$state[stateKey] = oldStateSource;
          }
        }
        set$2(store, stateKey, toRef$1(newStore.$state, stateKey));
      });
      Object.keys(store.$state).forEach((stateKey) => {
        if (!(stateKey in newStore.$state)) {
          del$1(store, stateKey);
        }
      });
      isListening = false;
      isSyncListening = false;
      pinia2.state.value[$id] = toRef$1(newStore._hmrPayload, "hotState");
      isSyncListening = true;
      nextTick().then(() => {
        isListening = true;
      });
      for (const actionName in newStore._hmrPayload.actions) {
        const actionFn = newStore[actionName];
        set$2(store, actionName, action(actionFn, actionName));
      }
      for (const getterName in newStore._hmrPayload.getters) {
        const getter = newStore._hmrPayload.getters[getterName];
        const getterValue = isOptionsStore ? (
          // special handling of options api
          computed(() => {
            setActivePinia(pinia2);
            return getter.call(store, store);
          })
        ) : getter;
        set$2(store, getterName, getterValue);
      }
      Object.keys(store._hmrPayload.getters).forEach((key) => {
        if (!(key in newStore._hmrPayload.getters)) {
          del$1(store, key);
        }
      });
      Object.keys(store._hmrPayload.actions).forEach((key) => {
        if (!(key in newStore._hmrPayload.actions)) {
          del$1(store, key);
        }
      });
      store._hmrPayload = newStore._hmrPayload;
      store._getters = newStore._getters;
      store._hotUpdating = false;
    });
  }
  if (false) {
    const nonEnumerable = {
      writable: true,
      configurable: true,
      // avoid warning on devtools trying to display this property
      enumerable: false
    };
    ["_p", "_hmrPayload", "_getters", "_customProperties"].forEach((p2) => {
      Object.defineProperty(store, p2, assign$4({ value: store[p2] }, nonEnumerable));
    });
  }
  if (isVue2) {
    store._r = true;
  }
  pinia2._p.forEach((extender) => {
    if (false) {
      const extensions = scope.run(() => extender({
        store,
        app: pinia2._a,
        pinia: pinia2,
        options: optionsForPlugin
      }));
      Object.keys(extensions || {}).forEach((key) => store._customProperties.add(key));
      assign$4(store, extensions);
    } else {
      assign$4(store, scope.run(() => extender({
        store,
        app: pinia2._a,
        pinia: pinia2,
        options: optionsForPlugin
      })));
    }
  });
  if (false) {
    console.warn(`[🍍]: The "state" must be a plain object. It cannot be
	state: () => new MyClass()
Found in store "${store.$id}".`);
  }
  if (initialState && isOptionsStore && options2.hydrate) {
    options2.hydrate(store.$state, initialState);
  }
  isListening = true;
  isSyncListening = true;
  return store;
}
__name(createSetupStore, "createSetupStore");
// @__NO_SIDE_EFFECTS__
function defineStore(idOrOptions, setup2, setupOptions) {
  let id2;
  let options2;
  const isSetupStore = typeof setup2 === "function";
  if (typeof idOrOptions === "string") {
    id2 = idOrOptions;
    options2 = isSetupStore ? setupOptions : setup2;
  } else {
    options2 = idOrOptions;
    id2 = idOrOptions.id;
    if (false) {
      throw new Error(`[🍍]: "defineStore()" must be passed a store id as its first argument.`);
    }
  }
  function useStore(pinia2, hot) {
    const hasContext = hasInjectionContext();
    pinia2 = // in test mode, ignore the argument provided as we can always retrieve a
    // pinia instance with getActivePinia()
    (false ? null : pinia2) || (hasContext ? inject(piniaSymbol, null) : null);
    if (pinia2)
      setActivePinia(pinia2);
    if (false) {
      throw new Error(`[🍍]: "getActivePinia()" was called but there was no active Pinia. Are you trying to use a store before calling "app.use(pinia)"?
See https://pinia.vuejs.org/core-concepts/outside-component-usage.html for help.
This will fail in production.`);
    }
    pinia2 = activePinia;
    if (!pinia2._s.has(id2)) {
      if (isSetupStore) {
        createSetupStore(id2, setup2, options2, pinia2);
      } else {
        createOptionsStore(id2, options2, pinia2);
      }
      if (false) {
        useStore._pinia = pinia2;
      }
    }
    const store = pinia2._s.get(id2);
    if (false) {
      const hotId = "__hot:" + id2;
      const newStore = isSetupStore ? createSetupStore(hotId, setup2, options2, pinia2, true) : createOptionsStore(hotId, assign$4({}, options2), pinia2, true);
      hot._hotUpdate(newStore);
      delete pinia2.state.value[hotId];
      pinia2._s.delete(hotId);
    }
    if (false) {
      const currentInstance = getCurrentInstance();
      if (currentInstance && currentInstance.proxy && // avoid adding stores that are just built for hot module replacement
      !hot) {
        const vm = currentInstance.proxy;
        const cache = "_pStores" in vm ? vm._pStores : vm._pStores = {};
        cache[id2] = store;
      }
    }
    return store;
  }
  __name(useStore, "useStore");
  useStore.$id = id2;
  return useStore;
}
__name(defineStore, "defineStore");
let mapStoreSuffix = "Store";
function setMapStoreSuffix(suffix) {
  mapStoreSuffix = suffix;
}
__name(setMapStoreSuffix, "setMapStoreSuffix");
function mapStores(...stores) {
  if (false) {
    console.warn(`[🍍]: Directly pass all stores to "mapStores()" without putting them in an array:
Replace
	mapStores([useAuthStore, useCartStore])
with
	mapStores(useAuthStore, useCartStore)
This will fail in production if not fixed.`);
    stores = stores[0];
  }
  return stores.reduce((reduced, useStore) => {
    reduced[useStore.$id + mapStoreSuffix] = function() {
      return useStore(this.$pinia);
    };
    return reduced;
  }, {});
}
__name(mapStores, "mapStores");
function mapState(useStore, keysOrMapper) {
  return Array.isArray(keysOrMapper) ? keysOrMapper.reduce((reduced, key) => {
    reduced[key] = function() {
      return useStore(this.$pinia)[key];
    };
    return reduced;
  }, {}) : Object.keys(keysOrMapper).reduce((reduced, key) => {
    reduced[key] = function() {
      const store = useStore(this.$pinia);
      const storeKey = keysOrMapper[key];
      return typeof storeKey === "function" ? storeKey.call(this, store) : store[storeKey];
    };
    return reduced;
  }, {});
}
__name(mapState, "mapState");
const mapGetters = mapState;
function mapActions(useStore, keysOrMapper) {
  return Array.isArray(keysOrMapper) ? keysOrMapper.reduce((reduced, key) => {
    reduced[key] = function(...args) {
      return useStore(this.$pinia)[key](...args);
    };
    return reduced;
  }, {}) : Object.keys(keysOrMapper).reduce((reduced, key) => {
    reduced[key] = function(...args) {
      return useStore(this.$pinia)[keysOrMapper[key]](...args);
    };
    return reduced;
  }, {});
}
__name(mapActions, "mapActions");
function mapWritableState(useStore, keysOrMapper) {
  return Array.isArray(keysOrMapper) ? keysOrMapper.reduce((reduced, key) => {
    reduced[key] = {
      get() {
        return useStore(this.$pinia)[key];
      },
      set(value) {
        return useStore(this.$pinia)[key] = value;
      }
    };
    return reduced;
  }, {}) : Object.keys(keysOrMapper).reduce((reduced, key) => {
    reduced[key] = {
      get() {
        return useStore(this.$pinia)[keysOrMapper[key]];
      },
      set(value) {
        return useStore(this.$pinia)[keysOrMapper[key]] = value;
      }
    };
    return reduced;
  }, {});
}
__name(mapWritableState, "mapWritableState");
function storeToRefs(store) {
  if (isVue2) {
    return toRefs$1(store);
  } else {
    store = toRaw(store);
    const refs = {};
    for (const key in store) {
      const value = store[key];
      if (isRef(value) || isReactive(value)) {
        refs[key] = // ---
        toRef$1(store, key);
      }
    }
    return refs;
  }
}
__name(storeToRefs, "storeToRefs");
const PiniaVuePlugin = /* @__PURE__ */ __name(function(_Vue) {
  _Vue.mixin({
    beforeCreate() {
      const options2 = this.$options;
      if (options2.pinia) {
        const pinia2 = options2.pinia;
        if (!this._provided) {
          const provideCache = {};
          Object.defineProperty(this, "_provided", {
            get: /* @__PURE__ */ __name(() => provideCache, "get"),
            set: /* @__PURE__ */ __name((v2) => Object.assign(provideCache, v2), "set")
          });
        }
        this._provided[piniaSymbol] = pinia2;
        if (!this.$pinia) {
          this.$pinia = pinia2;
        }
        pinia2._a = this;
        if (IS_CLIENT) {
          setActivePinia(pinia2);
        }
        if (false) {
          registerPiniaDevtools(pinia2._a, pinia2);
        }
      } else if (!this.$pinia && options2.parent && options2.parent.$pinia) {
        this.$pinia = options2.parent.$pinia;
      }
    },
    destroyed() {
      delete this._pStores;
    }
  });
}, "PiniaVuePlugin");
var extendStatics = /* @__PURE__ */ __name(function(d2, b2) {
  extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d3, b3) {
    d3.__proto__ = b3;
  } || function(d3, b3) {
    for (var p2 in b3) if (Object.prototype.hasOwnProperty.call(b3, p2)) d3[p2] = b3[p2];
  };
  return extendStatics(d2, b2);
}, "extendStatics");
function __extends(d2, b2) {
  if (typeof b2 !== "function" && b2 !== null)
    throw new TypeError("Class extends value " + String(b2) + " is not a constructor or null");
  extendStatics(d2, b2);
  function __() {
    this.constructor = d2;
  }
  __name(__, "__");
  d2.prototype = b2 === null ? Object.create(b2) : (__.prototype = b2.prototype, new __());
}
__name(__extends, "__extends");
var __assign$1 = /* @__PURE__ */ __name(function() {
  __assign$1 = Object.assign || /* @__PURE__ */ __name(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;
  }, "__assign");
  return __assign$1.apply(this, arguments);
}, "__assign$1");
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;
}
__name(__rest, "__rest");
function __decorate(decorators, target, key, desc) {
  var c2 = arguments.length, r2 = c2 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d2;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r2 = Reflect.decorate(decorators, target, key, desc);
  else for (var i2 = decorators.length - 1; i2 >= 0; i2--) if (d2 = decorators[i2]) r2 = (c2 < 3 ? d2(r2) : c2 > 3 ? d2(target, key, r2) : d2(target, key)) || r2;
  return c2 > 3 && r2 && Object.defineProperty(target, key, r2), r2;
}
__name(__decorate, "__decorate");
function __param(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
}
__name(__param, "__param");
function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
  function accept(f2) {
    if (f2 !== void 0 && typeof f2 !== "function") throw new TypeError("Function expected");
    return f2;
  }
  __name(accept, "accept");
  var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
  var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
  var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
  var _2, done = false;
  for (var i2 = decorators.length - 1; i2 >= 0; i2--) {
    var context = {};
    for (var p2 in contextIn) context[p2] = p2 === "access" ? {} : contextIn[p2];
    for (var p2 in contextIn.access) context.access[p2] = contextIn.access[p2];
    context.addInitializer = function(f2) {
      if (done) throw new TypeError("Cannot add initializers after decoration has completed");
      extraInitializers.push(accept(f2 || null));
    };
    var result = (0, decorators[i2])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
    if (kind === "accessor") {
      if (result === void 0) continue;
      if (result === null || typeof result !== "object") throw new TypeError("Object expected");
      if (_2 = accept(result.get)) descriptor.get = _2;
      if (_2 = accept(result.set)) descriptor.set = _2;
      if (_2 = accept(result.init)) initializers.unshift(_2);
    } else if (_2 = accept(result)) {
      if (kind === "field") initializers.unshift(_2);
      else descriptor[key] = _2;
    }
  }
  if (target) Object.defineProperty(target, contextIn.name, descriptor);
  done = true;
}
__name(__esDecorate, "__esDecorate");
;
function __runInitializers(thisArg, initializers, value) {
  var useValue = arguments.length > 2;
  for (var i2 = 0; i2 < initializers.length; i2++) {
    value = useValue ? initializers[i2].call(thisArg, value) : initializers[i2].call(thisArg);
  }
  return useValue ? value : void 0;
}
__name(__runInitializers, "__runInitializers");
;
function __propKey(x2) {
  return typeof x2 === "symbol" ? x2 : "".concat(x2);
}
__name(__propKey, "__propKey");
;
function __setFunctionName(f2, name2, prefix) {
  if (typeof name2 === "symbol") name2 = name2.description ? "[".concat(name2.description, "]") : "";
  return Object.defineProperty(f2, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name2) : name2 });
}
__name(__setFunctionName, "__setFunctionName");
;
function __metadata(metadataKey, metadataValue) {
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}
__name(__metadata, "__metadata");
function __awaiter(thisArg, _arguments, P2, generator) {
  function adopt(value) {
    return value instanceof P2 ? value : new P2(function(resolve2) {
      resolve2(value);
    });
  }
  __name(adopt, "adopt");
  return new (P2 || (P2 = Promise))(function(resolve2, reject) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e2) {
        reject(e2);
      }
    }
    __name(fulfilled, "fulfilled");
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e2) {
        reject(e2);
      }
    }
    __name(rejected, "rejected");
    function step(result) {
      result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    __name(step, "step");
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
}
__name(__awaiter, "__awaiter");
function __generator(thisArg, body) {
  var _2 = { label: 0, sent: /* @__PURE__ */ __name(function() {
    if (t2[0] & 1) throw t2[1];
    return t2[1];
  }, "sent"), trys: [], ops: [] }, f2, y2, t2, g2 = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
  return g2.next = verb(0), g2["throw"] = verb(1), g2["return"] = verb(2), typeof Symbol === "function" && (g2[Symbol.iterator] = function() {
    return this;
  }), g2;
  function verb(n2) {
    return function(v2) {
      return step([n2, v2]);
    };
  }
  __name(verb, "verb");
  function step(op) {
    if (f2) throw new TypeError("Generator is already executing.");
    while (g2 && (g2 = 0, op[0] && (_2 = 0)), _2) try {
      if (f2 = 1, y2 && (t2 = op[0] & 2 ? y2["return"] : op[0] ? y2["throw"] || ((t2 = y2["return"]) && t2.call(y2), 0) : y2.next) && !(t2 = t2.call(y2, op[1])).done) return t2;
      if (y2 = 0, t2) op = [op[0] & 2, t2.value];
      switch (op[0]) {
        case 0:
        case 1:
          t2 = op;
          break;
        case 4:
          _2.label++;
          return { value: op[1], done: false };
        case 5:
          _2.label++;
          y2 = op[1];
          op = [0];
          continue;
        case 7:
          op = _2.ops.pop();
          _2.trys.pop();
          continue;
        default:
          if (!(t2 = _2.trys, t2 = t2.length > 0 && t2[t2.length - 1]) && (op[0] === 6 || op[0] === 2)) {
            _2 = 0;
            continue;
          }
          if (op[0] === 3 && (!t2 || op[1] > t2[0] && op[1] < t2[3])) {
            _2.label = op[1];
            break;
          }
          if (op[0] === 6 && _2.label < t2[1]) {
            _2.label = t2[1];
            t2 = op;
            break;
          }
          if (t2 && _2.label < t2[2]) {
            _2.label = t2[2];
            _2.ops.push(op);
            break;
          }
          if (t2[2]) _2.ops.pop();
          _2.trys.pop();
          continue;
      }
      op = body.call(thisArg, _2);
    } catch (e2) {
      op = [6, e2];
      y2 = 0;
    } finally {
      f2 = t2 = 0;
    }
    if (op[0] & 5) throw op[1];
    return { value: op[0] ? op[1] : void 0, done: true };
  }
  __name(step, "step");
}
__name(__generator, "__generator");
var __createBinding = Object.create ? function(o2, m2, k2, k22) {
  if (k22 === void 0) k22 = k2;
  var desc = Object.getOwnPropertyDescriptor(m2, k2);
  if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) {
    desc = { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return m2[k2];
    }, "get") };
  }
  Object.defineProperty(o2, k22, desc);
} : function(o2, m2, k2, k22) {
  if (k22 === void 0) k22 = k2;
  o2[k22] = m2[k2];
};
function __exportStar(m2, o2) {
  for (var p2 in m2) if (p2 !== "default" && !Object.prototype.hasOwnProperty.call(o2, p2)) __createBinding(o2, m2, p2);
}
__name(__exportStar, "__exportStar");
function __values(o2) {
  var s2 = typeof Symbol === "function" && Symbol.iterator, m2 = s2 && o2[s2], i2 = 0;
  if (m2) return m2.call(o2);
  if (o2 && typeof o2.length === "number") return {
    next: /* @__PURE__ */ __name(function() {
      if (o2 && i2 >= o2.length) o2 = void 0;
      return { value: o2 && o2[i2++], done: !o2 };
    }, "next")
  };
  throw new TypeError(s2 ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
__name(__values, "__values");
function __read(o2, n2) {
  var m2 = typeof Symbol === "function" && o2[Symbol.iterator];
  if (!m2) return o2;
  var i2 = m2.call(o2), r2, ar = [], e2;
  try {
    while ((n2 === void 0 || n2-- > 0) && !(r2 = i2.next()).done) ar.push(r2.value);
  } catch (error2) {
    e2 = { error: error2 };
  } finally {
    try {
      if (r2 && !r2.done && (m2 = i2["return"])) m2.call(i2);
    } finally {
      if (e2) throw e2.error;
    }
  }
  return ar;
}
__name(__read, "__read");
function __spread() {
  for (var ar = [], i2 = 0; i2 < arguments.length; i2++)
    ar = ar.concat(__read(arguments[i2]));
  return ar;
}
__name(__spread, "__spread");
function __spreadArrays() {
  for (var s2 = 0, i2 = 0, il = arguments.length; i2 < il; i2++) s2 += arguments[i2].length;
  for (var r2 = Array(s2), k2 = 0, i2 = 0; i2 < il; i2++)
    for (var a2 = arguments[i2], j2 = 0, jl = a2.length; j2 < jl; j2++, k2++)
      r2[k2] = a2[j2];
  return r2;
}
__name(__spreadArrays, "__spreadArrays");
function __spreadArray(to, from2, pack) {
  if (pack || arguments.length === 2) for (var i2 = 0, l2 = from2.length, ar; i2 < l2; i2++) {
    if (ar || !(i2 in from2)) {
      if (!ar) ar = Array.prototype.slice.call(from2, 0, i2);
      ar[i2] = from2[i2];
    }
  }
  return to.concat(ar || Array.prototype.slice.call(from2));
}
__name(__spreadArray, "__spreadArray");
function __await(v2) {
  return this instanceof __await ? (this.v = v2, this) : new __await(v2);
}
__name(__await, "__await");
function __asyncGenerator(thisArg, _arguments, generator) {
  if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
  var g2 = generator.apply(thisArg, _arguments || []), i2, q2 = [];
  return i2 = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i2[Symbol.asyncIterator] = function() {
    return this;
  }, i2;
  function awaitReturn(f2) {
    return function(v2) {
      return Promise.resolve(v2).then(f2, reject);
    };
  }
  __name(awaitReturn, "awaitReturn");
  function verb(n2, f2) {
    if (g2[n2]) {
      i2[n2] = function(v2) {
        return new Promise(function(a2, b2) {
          q2.push([n2, v2, a2, b2]) > 1 || resume(n2, v2);
        });
      };
      if (f2) i2[n2] = f2(i2[n2]);
    }
  }
  __name(verb, "verb");
  function resume(n2, v2) {
    try {
      step(g2[n2](v2));
    } catch (e2) {
      settle2(q2[0][3], e2);
    }
  }
  __name(resume, "resume");
  function step(r2) {
    r2.value instanceof __await ? Promise.resolve(r2.value.v).then(fulfill, reject) : settle2(q2[0][2], r2);
  }
  __name(step, "step");
  function fulfill(value) {
    resume("next", value);
  }
  __name(fulfill, "fulfill");
  function reject(value) {
    resume("throw", value);
  }
  __name(reject, "reject");
  function settle2(f2, v2) {
    if (f2(v2), q2.shift(), q2.length) resume(q2[0][0], q2[0][1]);
  }
  __name(settle2, "settle");
}
__name(__asyncGenerator, "__asyncGenerator");
function __asyncDelegator(o2) {
  var i2, p2;
  return i2 = {}, verb("next"), verb("throw", function(e2) {
    throw e2;
  }), verb("return"), i2[Symbol.iterator] = function() {
    return this;
  }, i2;
  function verb(n2, f2) {
    i2[n2] = o2[n2] ? function(v2) {
      return (p2 = !p2) ? { value: __await(o2[n2](v2)), done: false } : f2 ? f2(v2) : v2;
    } : f2;
  }
  __name(verb, "verb");
}
__name(__asyncDelegator, "__asyncDelegator");
function __asyncValues(o2) {
  if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
  var m2 = o2[Symbol.asyncIterator], i2;
  return m2 ? m2.call(o2) : (o2 = typeof __values === "function" ? __values(o2) : o2[Symbol.iterator](), i2 = {}, verb("next"), verb("throw"), verb("return"), i2[Symbol.asyncIterator] = function() {
    return this;
  }, i2);
  function verb(n2) {
    i2[n2] = o2[n2] && function(v2) {
      return new Promise(function(resolve2, reject) {
        v2 = o2[n2](v2), settle2(resolve2, reject, v2.done, v2.value);
      });
    };
  }
  __name(verb, "verb");
  function settle2(resolve2, reject, d2, v2) {
    Promise.resolve(v2).then(function(v3) {
      resolve2({ value: v3, done: d2 });
    }, reject);
  }
  __name(settle2, "settle");
}
__name(__asyncValues, "__asyncValues");
function __makeTemplateObject(cooked, raw) {
  if (Object.defineProperty) {
    Object.defineProperty(cooked, "raw", { value: raw });
  } else {
    cooked.raw = raw;
  }
  return cooked;
}
__name(__makeTemplateObject, "__makeTemplateObject");
;
var __setModuleDefault = Object.create ? function(o2, v2) {
  Object.defineProperty(o2, "default", { enumerable: true, value: v2 });
} : function(o2, v2) {
  o2["default"] = v2;
};
var ownKeys$9 = /* @__PURE__ */ __name(function(o2) {
  ownKeys$9 = Object.getOwnPropertyNames || function(o3) {
    var ar = [];
    for (var k2 in o3) if (Object.prototype.hasOwnProperty.call(o3, k2)) ar[ar.length] = k2;
    return ar;
  };
  return ownKeys$9(o2);
}, "ownKeys$9");
function __importStar(mod) {
  if (mod && mod.__esModule) return mod;
  var result = {};
  if (mod != null) {
    for (var k2 = ownKeys$9(mod), i2 = 0; i2 < k2.length; i2++) if (k2[i2] !== "default") __createBinding(result, mod, k2[i2]);
  }
  __setModuleDefault(result, mod);
  return result;
}
__name(__importStar, "__importStar");
function __importDefault(mod) {
  return mod && mod.__esModule ? mod : { default: mod };
}
__name(__importDefault, "__importDefault");
function __classPrivateFieldGet$1(receiver, state, kind, f2) {
  if (kind === "a" && !f2) throw new TypeError("Private accessor was defined without a getter");
  if (typeof state === "function" ? receiver !== state || !f2 : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return kind === "m" ? f2 : kind === "a" ? f2.call(receiver) : f2 ? f2.value : state.get(receiver);
}
__name(__classPrivateFieldGet$1, "__classPrivateFieldGet$1");
function __classPrivateFieldSet$1(receiver, state, value, kind, f2) {
  if (kind === "m") throw new TypeError("Private method is not writable");
  if (kind === "a" && !f2) throw new TypeError("Private accessor was defined without a setter");
  if (typeof state === "function" ? receiver !== state || !f2 : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
  return kind === "a" ? f2.call(receiver, value) : f2 ? f2.value = value : state.set(receiver, value), value;
}
__name(__classPrivateFieldSet$1, "__classPrivateFieldSet$1");
function __classPrivateFieldIn(state, receiver) {
  if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function") throw new TypeError("Cannot use 'in' operator on non-object");
  return typeof state === "function" ? receiver === state : state.has(receiver);
}
__name(__classPrivateFieldIn, "__classPrivateFieldIn");
function __addDisposableResource(env, value, async2) {
  if (value !== null && value !== void 0) {
    if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
    var dispose, inner;
    if (async2) {
      if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
      dispose = value[Symbol.asyncDispose];
    }
    if (dispose === void 0) {
      if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
      dispose = value[Symbol.dispose];
      if (async2) inner = dispose;
    }
    if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
    if (inner) dispose = /* @__PURE__ */ __name(function() {
      try {
        inner.call(this);
      } catch (e2) {
        return Promise.reject(e2);
      }
    }, "dispose");
    env.stack.push({ value, dispose, async: async2 });
  } else if (async2) {
    env.stack.push({ async: true });
  }
  return value;
}
__name(__addDisposableResource, "__addDisposableResource");
var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error2, suppressed, message) {
  var e2 = new Error(message);
  return e2.name = "SuppressedError", e2.error = error2, e2.suppressed = suppressed, e2;
};
function __disposeResources(env) {
  function fail2(e2) {
    env.error = env.hasError ? new _SuppressedError(e2, env.error, "An error was suppressed during disposal.") : e2;
    env.hasError = true;
  }
  __name(fail2, "fail");
  var r2, s2 = 0;
  function next() {
    while (r2 = env.stack.pop()) {
      try {
        if (!r2.async && s2 === 1) return s2 = 0, env.stack.push(r2), Promise.resolve().then(next);
        if (r2.dispose) {
          var result = r2.dispose.call(r2.value);
          if (r2.async) return s2 |= 2, Promise.resolve(result).then(next, function(e2) {
            fail2(e2);
            return next();
          });
        } else s2 |= 1;
      } catch (e2) {
        fail2(e2);
      }
    }
    if (s2 === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
    if (env.hasError) throw env.error;
  }
  __name(next, "next");
  return next();
}
__name(__disposeResources, "__disposeResources");
function __rewriteRelativeImportExtension(path, preserveJsx) {
  if (typeof path === "string" && /^\.\.?\//.test(path)) {
    return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function(m2, tsx, d2, ext, cm) {
      return tsx ? preserveJsx ? ".jsx" : ".js" : d2 && (!ext || !cm) ? m2 : d2 + ext + "." + cm.toLowerCase() + "js";
    });
  }
  return path;
}
__name(__rewriteRelativeImportExtension, "__rewriteRelativeImportExtension");
const tslib_es6 = {
  __extends,
  __assign: __assign$1,
  __rest,
  __decorate,
  __param,
  __esDecorate,
  __runInitializers,
  __propKey,
  __setFunctionName,
  __metadata,
  __awaiter,
  __generator,
  __createBinding,
  __exportStar,
  __values,
  __read,
  __spread,
  __spreadArrays,
  __spreadArray,
  __await,
  __asyncGenerator,
  __asyncDelegator,
  __asyncValues,
  __makeTemplateObject,
  __importStar,
  __importDefault,
  __classPrivateFieldGet: __classPrivateFieldGet$1,
  __classPrivateFieldSet: __classPrivateFieldSet$1,
  __classPrivateFieldIn,
  __addDisposableResource,
  __disposeResources,
  __rewriteRelativeImportExtension
};
/**
 * @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 FactorId = {
  /** Phone as second factor */
  PHONE: "phone",
  TOTP: "totp"
};
const ProviderId = {
  /** Facebook provider ID */
  FACEBOOK: "facebook.com",
  /** GitHub provider ID */
  GITHUB: "github.com",
  /** Google provider ID */
  GOOGLE: "google.com",
  /** Password provider */
  PASSWORD: "password",
  /** Phone provider */
  PHONE: "phone",
  /** Twitter provider ID */
  TWITTER: "twitter.com"
};
const SignInMethod = {
  /** Email link sign in method */
  EMAIL_LINK: "emailLink",
  /** Email/password sign in method */
  EMAIL_PASSWORD: "password",
  /** Facebook sign in method */
  FACEBOOK: "facebook.com",
  /** GitHub sign in method */
  GITHUB: "github.com",
  /** Google sign in method */
  GOOGLE: "google.com",
  /** Phone sign in method */
  PHONE: "phone",
  /** Twitter sign in method */
  TWITTER: "twitter.com"
};
const OperationType$1 = {
  /** Operation involving linking an additional provider to an already signed-in user. */
  LINK: "link",
  /** Operation involving using a provider to reauthenticate an already signed-in user. */
  REAUTHENTICATE: "reauthenticate",
  /** Operation involving signing in a user. */
  SIGN_IN: "signIn"
};
const ActionCodeOperation = {
  /** The email link sign-in action. */
  EMAIL_SIGNIN: "EMAIL_SIGNIN",
  /** The password reset action. */
  PASSWORD_RESET: "PASSWORD_RESET",
  /** The email revocation action. */
  RECOVER_EMAIL: "RECOVER_EMAIL",
  /** The revert second factor addition email action. */
  REVERT_SECOND_FACTOR_ADDITION: "REVERT_SECOND_FACTOR_ADDITION",
  /** The revert second factor addition email action. */
  VERIFY_AND_CHANGE_EMAIL: "VERIFY_AND_CHANGE_EMAIL",
  /** The email verification action. */
  VERIFY_EMAIL: "VERIFY_EMAIL"
};
/**
 * @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.
 */
function _debugErrorMap() {
  return {
    [
      "admin-restricted-operation"
      /* AuthErrorCode.ADMIN_ONLY_OPERATION */
    ]: "This operation is restricted to administrators only.",
    [
      "argument-error"
      /* AuthErrorCode.ARGUMENT_ERROR */
    ]: "",
    [
      "app-not-authorized"
      /* AuthErrorCode.APP_NOT_AUTHORIZED */
    ]: "This app, identified by the domain where it's hosted, is not authorized to use Firebase Authentication with the provided API key. Review your key configuration in the Google API console.",
    [
      "app-not-installed"
      /* AuthErrorCode.APP_NOT_INSTALLED */
    ]: "The requested mobile application corresponding to the identifier (Android package name or iOS bundle ID) provided is not installed on this device.",
    [
      "captcha-check-failed"
      /* AuthErrorCode.CAPTCHA_CHECK_FAILED */
    ]: "The reCAPTCHA response token provided is either invalid, expired, already used or the domain associated with it does not match the list of whitelisted domains.",
    [
      "code-expired"
      /* AuthErrorCode.CODE_EXPIRED */
    ]: "The SMS code has expired. Please re-send the verification code to try again.",
    [
      "cordova-not-ready"
      /* AuthErrorCode.CORDOVA_NOT_READY */
    ]: "Cordova framework is not ready.",
    [
      "cors-unsupported"
      /* AuthErrorCode.CORS_UNSUPPORTED */
    ]: "This browser is not supported.",
    [
      "credential-already-in-use"
      /* AuthErrorCode.CREDENTIAL_ALREADY_IN_USE */
    ]: "This credential is already associated with a different user account.",
    [
      "custom-token-mismatch"
      /* AuthErrorCode.CREDENTIAL_MISMATCH */
    ]: "The custom token corresponds to a different audience.",
    [
      "requires-recent-login"
      /* AuthErrorCode.CREDENTIAL_TOO_OLD_LOGIN_AGAIN */
    ]: "This operation is sensitive and requires recent authentication. Log in again before retrying this request.",
    [
      "dependent-sdk-initialized-before-auth"
      /* AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH */
    ]: "Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK.",
    [
      "dynamic-link-not-activated"
      /* AuthErrorCode.DYNAMIC_LINK_NOT_ACTIVATED */
    ]: "Please activate Dynamic Links in the Firebase Console and agree to the terms and conditions.",
    [
      "email-change-needs-verification"
      /* AuthErrorCode.EMAIL_CHANGE_NEEDS_VERIFICATION */
    ]: "Multi-factor users must always have a verified email.",
    [
      "email-already-in-use"
      /* AuthErrorCode.EMAIL_EXISTS */
    ]: "The email address is already in use by another account.",
    [
      "emulator-config-failed"
      /* AuthErrorCode.EMULATOR_CONFIG_FAILED */
    ]: 'Auth instance has already been used to make a network call. Auth can no longer be configured to use the emulator. Try calling "connectAuthEmulator()" sooner.',
    [
      "expired-action-code"
      /* AuthErrorCode.EXPIRED_OOB_CODE */
    ]: "The action code has expired.",
    [
      "cancelled-popup-request"
      /* AuthErrorCode.EXPIRED_POPUP_REQUEST */
    ]: "This operation has been cancelled due to another conflicting popup being opened.",
    [
      "internal-error"
      /* AuthErrorCode.INTERNAL_ERROR */
    ]: "An internal AuthError has occurred.",
    [
      "invalid-app-credential"
      /* AuthErrorCode.INVALID_APP_CREDENTIAL */
    ]: "The phone verification request contains an invalid application verifier. The reCAPTCHA token response is either invalid or expired.",
    [
      "invalid-app-id"
      /* AuthErrorCode.INVALID_APP_ID */
    ]: "The mobile app identifier is not registered for the current project.",
    [
      "invalid-user-token"
      /* AuthErrorCode.INVALID_AUTH */
    ]: "This user's credential isn't valid for this project. This can happen if the user's token has been tampered with, or if the user isn't for the project associated with this API key.",
    [
      "invalid-auth-event"
      /* AuthErrorCode.INVALID_AUTH_EVENT */
    ]: "An internal AuthError has occurred.",
    [
      "invalid-verification-code"
      /* AuthErrorCode.INVALID_CODE */
    ]: "The SMS verification code used to create the phone auth credential is invalid. Please resend the verification code sms and be sure to use the verification code provided by the user.",
    [
      "invalid-continue-uri"
      /* AuthErrorCode.INVALID_CONTINUE_URI */
    ]: "The continue URL provided in the request is invalid.",
    [
      "invalid-cordova-configuration"
      /* AuthErrorCode.INVALID_CORDOVA_CONFIGURATION */
    ]: "The following Cordova plugins must be installed to enable OAuth sign-in: cordova-plugin-buildinfo, cordova-universal-links-plugin, cordova-plugin-browsertab, cordova-plugin-inappbrowser and cordova-plugin-customurlscheme.",
    [
      "invalid-custom-token"
      /* AuthErrorCode.INVALID_CUSTOM_TOKEN */
    ]: "The custom token format is incorrect. Please check the documentation.",
    [
      "invalid-dynamic-link-domain"
      /* AuthErrorCode.INVALID_DYNAMIC_LINK_DOMAIN */
    ]: "The provided dynamic link domain is not configured or authorized for the current project.",
    [
      "invalid-email"
      /* AuthErrorCode.INVALID_EMAIL */
    ]: "The email address is badly formatted.",
    [
      "invalid-emulator-scheme"
      /* AuthErrorCode.INVALID_EMULATOR_SCHEME */
    ]: "Emulator URL must start with a valid scheme (http:// or https://).",
    [
      "invalid-api-key"
      /* AuthErrorCode.INVALID_API_KEY */
    ]: "Your API key is invalid, please check you have copied it correctly.",
    [
      "invalid-cert-hash"
      /* AuthErrorCode.INVALID_CERT_HASH */
    ]: "The SHA-1 certificate hash provided is invalid.",
    [
      "invalid-credential"
      /* AuthErrorCode.INVALID_CREDENTIAL */
    ]: "The supplied auth credential is incorrect, malformed or has expired.",
    [
      "invalid-message-payload"
      /* AuthErrorCode.INVALID_MESSAGE_PAYLOAD */
    ]: "The email template corresponding to this action contains invalid characters in its message. Please fix by going to the Auth email templates section in the Firebase Console.",
    [
      "invalid-multi-factor-session"
      /* AuthErrorCode.INVALID_MFA_SESSION */
    ]: "The request does not contain a valid proof of first factor successful sign-in.",
    [
      "invalid-oauth-provider"
      /* AuthErrorCode.INVALID_OAUTH_PROVIDER */
    ]: "EmailAuthProvider is not supported for this operation. This operation only supports OAuth providers.",
    [
      "invalid-oauth-client-id"
      /* AuthErrorCode.INVALID_OAUTH_CLIENT_ID */
    ]: "The OAuth client ID provided is either invalid or does not match the specified API key.",
    [
      "unauthorized-domain"
      /* AuthErrorCode.INVALID_ORIGIN */
    ]: "This domain is not authorized for OAuth operations for your Firebase project. Edit the list of authorized domains from the Firebase console.",
    [
      "invalid-action-code"
      /* AuthErrorCode.INVALID_OOB_CODE */
    ]: "The action code is invalid. This can happen if the code is malformed, expired, or has already been used.",
    [
      "wrong-password"
      /* AuthErrorCode.INVALID_PASSWORD */
    ]: "The password is invalid or the user does not have a password.",
    [
      "invalid-persistence-type"
      /* AuthErrorCode.INVALID_PERSISTENCE */
    ]: "The specified persistence type is invalid. It can only be local, session or none.",
    [
      "invalid-phone-number"
      /* AuthErrorCode.INVALID_PHONE_NUMBER */
    ]: "The format of the phone number provided is incorrect. Please enter the phone number in a format that can be parsed into E.164 format. E.164 phone numbers are written in the format [+][country code][subscriber number including area code].",
    [
      "invalid-provider-id"
      /* AuthErrorCode.INVALID_PROVIDER_ID */
    ]: "The specified provider ID is invalid.",
    [
      "invalid-recipient-email"
      /* AuthErrorCode.INVALID_RECIPIENT_EMAIL */
    ]: "The email corresponding to this action failed to send as the provided recipient email address is invalid.",
    [
      "invalid-sender"
      /* AuthErrorCode.INVALID_SENDER */
    ]: "The email template corresponding to this action contains an invalid sender email or name. Please fix by going to the Auth email templates section in the Firebase Console.",
    [
      "invalid-verification-id"
      /* AuthErrorCode.INVALID_SESSION_INFO */
    ]: "The verification ID used to create the phone auth credential is invalid.",
    [
      "invalid-tenant-id"
      /* AuthErrorCode.INVALID_TENANT_ID */
    ]: "The Auth instance's tenant ID is invalid.",
    [
      "login-blocked"
      /* AuthErrorCode.LOGIN_BLOCKED */
    ]: "Login blocked by user-provided method: {$originalMessage}",
    [
      "missing-android-pkg-name"
      /* AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME */
    ]: "An Android Package Name must be provided if the Android App is required to be installed.",
    [
      "auth-domain-config-required"
      /* AuthErrorCode.MISSING_AUTH_DOMAIN */
    ]: "Be sure to include authDomain when calling firebase.initializeApp(), by following the instructions in the Firebase console.",
    [
      "missing-app-credential"
      /* AuthErrorCode.MISSING_APP_CREDENTIAL */
    ]: "The phone verification request is missing an application verifier assertion. A reCAPTCHA response token needs to be provided.",
    [
      "missing-verification-code"
      /* AuthErrorCode.MISSING_CODE */
    ]: "The phone auth credential was created with an empty SMS verification code.",
    [
      "missing-continue-uri"
      /* AuthErrorCode.MISSING_CONTINUE_URI */
    ]: "A continue URL must be provided in the request.",
    [
      "missing-iframe-start"
      /* AuthErrorCode.MISSING_IFRAME_START */
    ]: "An internal AuthError has occurred.",
    [
      "missing-ios-bundle-id"
      /* AuthErrorCode.MISSING_IOS_BUNDLE_ID */
    ]: "An iOS Bundle ID must be provided if an App Store ID is provided.",
    [
      "missing-or-invalid-nonce"
      /* AuthErrorCode.MISSING_OR_INVALID_NONCE */
    ]: "The request does not contain a valid nonce. This can occur if the SHA-256 hash of the provided raw nonce does not match the hashed nonce in the ID token payload.",
    [
      "missing-password"
      /* AuthErrorCode.MISSING_PASSWORD */
    ]: "A non-empty password must be provided",
    [
      "missing-multi-factor-info"
      /* AuthErrorCode.MISSING_MFA_INFO */
    ]: "No second factor identifier is provided.",
    [
      "missing-multi-factor-session"
      /* AuthErrorCode.MISSING_MFA_SESSION */
    ]: "The request is missing proof of first factor successful sign-in.",
    [
      "missing-phone-number"
      /* AuthErrorCode.MISSING_PHONE_NUMBER */
    ]: "To send verification codes, provide a phone number for the recipient.",
    [
      "missing-verification-id"
      /* AuthErrorCode.MISSING_SESSION_INFO */
    ]: "The phone auth credential was created with an empty verification ID.",
    [
      "app-deleted"
      /* AuthErrorCode.MODULE_DESTROYED */
    ]: "This instance of FirebaseApp has been deleted.",
    [
      "multi-factor-info-not-found"
      /* AuthErrorCode.MFA_INFO_NOT_FOUND */
    ]: "The user does not have a second factor matching the identifier provided.",
    [
      "multi-factor-auth-required"
      /* AuthErrorCode.MFA_REQUIRED */
    ]: "Proof of ownership of a second factor is required to complete sign-in.",
    [
      "account-exists-with-different-credential"
      /* AuthErrorCode.NEED_CONFIRMATION */
    ]: "An account already exists with the same email address but different sign-in credentials. Sign in using a provider associated with this email address.",
    [
      "network-request-failed"
      /* AuthErrorCode.NETWORK_REQUEST_FAILED */
    ]: "A network AuthError (such as timeout, interrupted connection or unreachable host) has occurred.",
    [
      "no-auth-event"
      /* AuthErrorCode.NO_AUTH_EVENT */
    ]: "An internal AuthError has occurred.",
    [
      "no-such-provider"
      /* AuthErrorCode.NO_SUCH_PROVIDER */
    ]: "User was not linked to an account with the given provider.",
    [
      "null-user"
      /* AuthErrorCode.NULL_USER */
    ]: "A null user object was provided as the argument for an operation which requires a non-null user object.",
    [
      "operation-not-allowed"
      /* AuthErrorCode.OPERATION_NOT_ALLOWED */
    ]: "The given sign-in provider is disabled for this Firebase project. Enable it in the Firebase console, under the sign-in method tab of the Auth section.",
    [
      "operation-not-supported-in-this-environment"
      /* AuthErrorCode.OPERATION_NOT_SUPPORTED */
    ]: 'This operation is not supported in the environment this application is running on. "location.protocol" must be http, https or chrome-extension and web storage must be enabled.',
    [
      "popup-blocked"
      /* AuthErrorCode.POPUP_BLOCKED */
    ]: "Unable to establish a connection with the popup. It may have been blocked by the browser.",
    [
      "popup-closed-by-user"
      /* AuthErrorCode.POPUP_CLOSED_BY_USER */
    ]: "The popup has been closed by the user before finalizing the operation.",
    [
      "provider-already-linked"
      /* AuthErrorCode.PROVIDER_ALREADY_LINKED */
    ]: "User can only be linked to one identity for the given provider.",
    [
      "quota-exceeded"
      /* AuthErrorCode.QUOTA_EXCEEDED */
    ]: "The project's quota for this operation has been exceeded.",
    [
      "redirect-cancelled-by-user"
      /* AuthErrorCode.REDIRECT_CANCELLED_BY_USER */
    ]: "The redirect operation has been cancelled by the user before finalizing.",
    [
      "redirect-operation-pending"
      /* AuthErrorCode.REDIRECT_OPERATION_PENDING */
    ]: "A redirect sign-in operation is already pending.",
    [
      "rejected-credential"
      /* AuthErrorCode.REJECTED_CREDENTIAL */
    ]: "The request contains malformed or mismatching credentials.",
    [
      "second-factor-already-in-use"
      /* AuthErrorCode.SECOND_FACTOR_ALREADY_ENROLLED */
    ]: "The second factor is already enrolled on this account.",
    [
      "maximum-second-factor-count-exceeded"
      /* AuthErrorCode.SECOND_FACTOR_LIMIT_EXCEEDED */
    ]: "The maximum allowed number of second factors on a user has been exceeded.",
    [
      "tenant-id-mismatch"
      /* AuthErrorCode.TENANT_ID_MISMATCH */
    ]: "The provided tenant ID does not match the Auth instance's tenant ID",
    [
      "timeout"
      /* AuthErrorCode.TIMEOUT */
    ]: "The operation has timed out.",
    [
      "user-token-expired"
      /* AuthErrorCode.TOKEN_EXPIRED */
    ]: "The user's credential is no longer valid. The user must sign in again.",
    [
      "too-many-requests"
      /* AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER */
    ]: "We have blocked all requests from this device due to unusual activity. Try again later.",
    [
      "unauthorized-continue-uri"
      /* AuthErrorCode.UNAUTHORIZED_DOMAIN */
    ]: "The domain of the continue URL is not whitelisted.  Please whitelist the domain in the Firebase console.",
    [
      "unsupported-first-factor"
      /* AuthErrorCode.UNSUPPORTED_FIRST_FACTOR */
    ]: "Enrolling a second factor or signing in with a multi-factor account requires sign-in with a supported first factor.",
    [
      "unsupported-persistence-type"
      /* AuthErrorCode.UNSUPPORTED_PERSISTENCE */
    ]: "The current environment does not support the specified persistence type.",
    [
      "unsupported-tenant-operation"
      /* AuthErrorCode.UNSUPPORTED_TENANT_OPERATION */
    ]: "This operation is not supported in a multi-tenant context.",
    [
      "unverified-email"
      /* AuthErrorCode.UNVERIFIED_EMAIL */
    ]: "The operation requires a verified email.",
    [
      "user-cancelled"
      /* AuthErrorCode.USER_CANCELLED */
    ]: "The user did not grant your application the permissions it requested.",
    [
      "user-not-found"
      /* AuthErrorCode.USER_DELETED */
    ]: "There is no user record corresponding to this identifier. The user may have been deleted.",
    [
      "user-disabled"
      /* AuthErrorCode.USER_DISABLED */
    ]: "The user account has been disabled by an administrator.",
    [
      "user-mismatch"
      /* AuthErrorCode.USER_MISMATCH */
    ]: "The supplied credentials do not correspond to the previously signed in user.",
    [
      "user-signed-out"
      /* AuthErrorCode.USER_SIGNED_OUT */
    ]: "",
    [
      "weak-password"
      /* AuthErrorCode.WEAK_PASSWORD */
    ]: "The password must be 6 characters long or more.",
    [
      "web-storage-unsupported"
      /* AuthErrorCode.WEB_STORAGE_UNSUPPORTED */
    ]: "This browser is not supported or 3rd party cookies and data may be disabled.",
    [
      "already-initialized"
      /* AuthErrorCode.ALREADY_INITIALIZED */
    ]: "initializeAuth() has already been called with different options. To avoid this error, call initializeAuth() with the same options as when it was originally called, or call getAuth() to return the already initialized instance.",
    [
      "missing-recaptcha-token"
      /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */
    ]: "The reCAPTCHA token is missing when sending request to the backend.",
    [
      "invalid-recaptcha-token"
      /* AuthErrorCode.INVALID_RECAPTCHA_TOKEN */
    ]: "The reCAPTCHA token is invalid when sending request to the backend.",
    [
      "invalid-recaptcha-action"
      /* AuthErrorCode.INVALID_RECAPTCHA_ACTION */
    ]: "The reCAPTCHA action is invalid when sending request to the backend.",
    [
      "recaptcha-not-enabled"
      /* AuthErrorCode.RECAPTCHA_NOT_ENABLED */
    ]: "reCAPTCHA Enterprise integration is not enabled for this project.",
    [
      "missing-client-type"
      /* AuthErrorCode.MISSING_CLIENT_TYPE */
    ]: "The reCAPTCHA client type is missing when sending request to the backend.",
    [
      "missing-recaptcha-version"
      /* AuthErrorCode.MISSING_RECAPTCHA_VERSION */
    ]: "The reCAPTCHA version is missing when sending request to the backend.",
    [
      "invalid-req-type"
      /* AuthErrorCode.INVALID_REQ_TYPE */
    ]: "Invalid request parameters.",
    [
      "invalid-recaptcha-version"
      /* AuthErrorCode.INVALID_RECAPTCHA_VERSION */
    ]: "The reCAPTCHA version is invalid when sending request to the backend.",
    [
      "unsupported-password-policy-schema-version"
      /* AuthErrorCode.UNSUPPORTED_PASSWORD_POLICY_SCHEMA_VERSION */
    ]: "The password policy received from the backend uses a schema version that is not supported by this version of the Firebase SDK.",
    [
      "password-does-not-meet-requirements"
      /* AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS */
    ]: "The password does not meet the requirements.",
    [
      "invalid-hosting-link-domain"
      /* AuthErrorCode.INVALID_HOSTING_LINK_DOMAIN */
    ]: "The provided Hosting link domain is not configured in Firebase Hosting or is not owned by the current project. This cannot be a default Hosting domain (`web.app` or `firebaseapp.com`)."
  };
}
__name(_debugErrorMap, "_debugErrorMap");
function _prodErrorMap() {
  return {
    [
      "dependent-sdk-initialized-before-auth"
      /* AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH */
    ]: "Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK."
  };
}
__name(_prodErrorMap, "_prodErrorMap");
const debugErrorMap = _debugErrorMap;
const prodErrorMap = _prodErrorMap;
const _DEFAULT_AUTH_ERROR_FACTORY = new ErrorFactory("auth", "Firebase", _prodErrorMap());
const AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY = {
  ADMIN_ONLY_OPERATION: "auth/admin-restricted-operation",
  ARGUMENT_ERROR: "auth/argument-error",
  APP_NOT_AUTHORIZED: "auth/app-not-authorized",
  APP_NOT_INSTALLED: "auth/app-not-installed",
  CAPTCHA_CHECK_FAILED: "auth/captcha-check-failed",
  CODE_EXPIRED: "auth/code-expired",
  CORDOVA_NOT_READY: "auth/cordova-not-ready",
  CORS_UNSUPPORTED: "auth/cors-unsupported",
  CREDENTIAL_ALREADY_IN_USE: "auth/credential-already-in-use",
  CREDENTIAL_MISMATCH: "auth/custom-token-mismatch",
  CREDENTIAL_TOO_OLD_LOGIN_AGAIN: "auth/requires-recent-login",
  DEPENDENT_SDK_INIT_BEFORE_AUTH: "auth/dependent-sdk-initialized-before-auth",
  DYNAMIC_LINK_NOT_ACTIVATED: "auth/dynamic-link-not-activated",
  EMAIL_CHANGE_NEEDS_VERIFICATION: "auth/email-change-needs-verification",
  EMAIL_EXISTS: "auth/email-already-in-use",
  EMULATOR_CONFIG_FAILED: "auth/emulator-config-failed",
  EXPIRED_OOB_CODE: "auth/expired-action-code",
  EXPIRED_POPUP_REQUEST: "auth/cancelled-popup-request",
  INTERNAL_ERROR: "auth/internal-error",
  INVALID_API_KEY: "auth/invalid-api-key",
  INVALID_APP_CREDENTIAL: "auth/invalid-app-credential",
  INVALID_APP_ID: "auth/invalid-app-id",
  INVALID_AUTH: "auth/invalid-user-token",
  INVALID_AUTH_EVENT: "auth/invalid-auth-event",
  INVALID_CERT_HASH: "auth/invalid-cert-hash",
  INVALID_CODE: "auth/invalid-verification-code",
  INVALID_CONTINUE_URI: "auth/invalid-continue-uri",
  INVALID_CORDOVA_CONFIGURATION: "auth/invalid-cordova-configuration",
  INVALID_CUSTOM_TOKEN: "auth/invalid-custom-token",
  INVALID_DYNAMIC_LINK_DOMAIN: "auth/invalid-dynamic-link-domain",
  INVALID_EMAIL: "auth/invalid-email",
  INVALID_EMULATOR_SCHEME: "auth/invalid-emulator-scheme",
  INVALID_IDP_RESPONSE: "auth/invalid-credential",
  INVALID_LOGIN_CREDENTIALS: "auth/invalid-credential",
  INVALID_MESSAGE_PAYLOAD: "auth/invalid-message-payload",
  INVALID_MFA_SESSION: "auth/invalid-multi-factor-session",
  INVALID_OAUTH_CLIENT_ID: "auth/invalid-oauth-client-id",
  INVALID_OAUTH_PROVIDER: "auth/invalid-oauth-provider",
  INVALID_OOB_CODE: "auth/invalid-action-code",
  INVALID_ORIGIN: "auth/unauthorized-domain",
  INVALID_PASSWORD: "auth/wrong-password",
  INVALID_PERSISTENCE: "auth/invalid-persistence-type",
  INVALID_PHONE_NUMBER: "auth/invalid-phone-number",
  INVALID_PROVIDER_ID: "auth/invalid-provider-id",
  INVALID_RECIPIENT_EMAIL: "auth/invalid-recipient-email",
  INVALID_SENDER: "auth/invalid-sender",
  INVALID_SESSION_INFO: "auth/invalid-verification-id",
  INVALID_TENANT_ID: "auth/invalid-tenant-id",
  MFA_INFO_NOT_FOUND: "auth/multi-factor-info-not-found",
  MFA_REQUIRED: "auth/multi-factor-auth-required",
  MISSING_ANDROID_PACKAGE_NAME: "auth/missing-android-pkg-name",
  MISSING_APP_CREDENTIAL: "auth/missing-app-credential",
  MISSING_AUTH_DOMAIN: "auth/auth-domain-config-required",
  MISSING_CODE: "auth/missing-verification-code",
  MISSING_CONTINUE_URI: "auth/missing-continue-uri",
  MISSING_IFRAME_START: "auth/missing-iframe-start",
  MISSING_IOS_BUNDLE_ID: "auth/missing-ios-bundle-id",
  MISSING_OR_INVALID_NONCE: "auth/missing-or-invalid-nonce",
  MISSING_MFA_INFO: "auth/missing-multi-factor-info",
  MISSING_MFA_SESSION: "auth/missing-multi-factor-session",
  MISSING_PHONE_NUMBER: "auth/missing-phone-number",
  MISSING_SESSION_INFO: "auth/missing-verification-id",
  MODULE_DESTROYED: "auth/app-deleted",
  NEED_CONFIRMATION: "auth/account-exists-with-different-credential",
  NETWORK_REQUEST_FAILED: "auth/network-request-failed",
  NULL_USER: "auth/null-user",
  NO_AUTH_EVENT: "auth/no-auth-event",
  NO_SUCH_PROVIDER: "auth/no-such-provider",
  OPERATION_NOT_ALLOWED: "auth/operation-not-allowed",
  OPERATION_NOT_SUPPORTED: "auth/operation-not-supported-in-this-environment",
  POPUP_BLOCKED: "auth/popup-blocked",
  POPUP_CLOSED_BY_USER: "auth/popup-closed-by-user",
  PROVIDER_ALREADY_LINKED: "auth/provider-already-linked",
  QUOTA_EXCEEDED: "auth/quota-exceeded",
  REDIRECT_CANCELLED_BY_USER: "auth/redirect-cancelled-by-user",
  REDIRECT_OPERATION_PENDING: "auth/redirect-operation-pending",
  REJECTED_CREDENTIAL: "auth/rejected-credential",
  SECOND_FACTOR_ALREADY_ENROLLED: "auth/second-factor-already-in-use",
  SECOND_FACTOR_LIMIT_EXCEEDED: "auth/maximum-second-factor-count-exceeded",
  TENANT_ID_MISMATCH: "auth/tenant-id-mismatch",
  TIMEOUT: "auth/timeout",
  TOKEN_EXPIRED: "auth/user-token-expired",
  TOO_MANY_ATTEMPTS_TRY_LATER: "auth/too-many-requests",
  UNAUTHORIZED_DOMAIN: "auth/unauthorized-continue-uri",
  UNSUPPORTED_FIRST_FACTOR: "auth/unsupported-first-factor",
  UNSUPPORTED_PERSISTENCE: "auth/unsupported-persistence-type",
  UNSUPPORTED_TENANT_OPERATION: "auth/unsupported-tenant-operation",
  UNVERIFIED_EMAIL: "auth/unverified-email",
  USER_CANCELLED: "auth/user-cancelled",
  USER_DELETED: "auth/user-not-found",
  USER_DISABLED: "auth/user-disabled",
  USER_MISMATCH: "auth/user-mismatch",
  USER_SIGNED_OUT: "auth/user-signed-out",
  WEAK_PASSWORD: "auth/weak-password",
  WEB_STORAGE_UNSUPPORTED: "auth/web-storage-unsupported",
  ALREADY_INITIALIZED: "auth/already-initialized",
  RECAPTCHA_NOT_ENABLED: "auth/recaptcha-not-enabled",
  MISSING_RECAPTCHA_TOKEN: "auth/missing-recaptcha-token",
  INVALID_RECAPTCHA_TOKEN: "auth/invalid-recaptcha-token",
  INVALID_RECAPTCHA_ACTION: "auth/invalid-recaptcha-action",
  MISSING_CLIENT_TYPE: "auth/missing-client-type",
  MISSING_RECAPTCHA_VERSION: "auth/missing-recaptcha-version",
  INVALID_RECAPTCHA_VERSION: "auth/invalid-recaptcha-version",
  INVALID_REQ_TYPE: "auth/invalid-req-type",
  INVALID_HOSTING_LINK_DOMAIN: "auth/invalid-hosting-link-domain"
};
/**
 * @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 logClient$1 = new Logger("@firebase/auth");
function _logWarn(msg, ...args) {
  if (logClient$1.logLevel <= LogLevel.WARN) {
    logClient$1.warn(`Auth (${SDK_VERSION$1}): ${msg}`, ...args);
  }
}
__name(_logWarn, "_logWarn");
function _logError(msg, ...args) {
  if (logClient$1.logLevel <= LogLevel.ERROR) {
    logClient$1.error(`Auth (${SDK_VERSION$1}): ${msg}`, ...args);
  }
}
__name(_logError, "_logError");
/**
 * @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.
 */
function _fail(authOrCode, ...rest) {
  throw createErrorInternal(authOrCode, ...rest);
}
__name(_fail, "_fail");
function _createError(authOrCode, ...rest) {
  return createErrorInternal(authOrCode, ...rest);
}
__name(_createError, "_createError");
function _errorWithCustomMessage(auth2, code2, message) {
  const errorMap2 = Object.assign(Object.assign({}, prodErrorMap()), { [code2]: message });
  const factory2 = new ErrorFactory("auth", "Firebase", errorMap2);
  return factory2.create(code2, {
    appName: auth2.name
  });
}
__name(_errorWithCustomMessage, "_errorWithCustomMessage");
function _serverAppCurrentUserOperationNotSupportedError(auth2) {
  return _errorWithCustomMessage(auth2, "operation-not-supported-in-this-environment", "Operations that alter the current user are not supported in conjunction with FirebaseServerApp");
}
__name(_serverAppCurrentUserOperationNotSupportedError, "_serverAppCurrentUserOperationNotSupportedError");
function _assertInstanceOf(auth2, object, instance) {
  const constructorInstance = instance;
  if (!(object instanceof constructorInstance)) {
    if (constructorInstance.name !== object.constructor.name) {
      _fail(
        auth2,
        "argument-error"
        /* AuthErrorCode.ARGUMENT_ERROR */
      );
    }
    throw _errorWithCustomMessage(auth2, "argument-error", `Type of ${object.constructor.name} does not match expected instance.Did you pass a reference from a different Auth SDK?`);
  }
}
__name(_assertInstanceOf, "_assertInstanceOf");
function createErrorInternal(authOrCode, ...rest) {
  if (typeof authOrCode !== "string") {
    const code2 = rest[0];
    const fullParams = [...rest.slice(1)];
    if (fullParams[0]) {
      fullParams[0].appName = authOrCode.name;
    }
    return authOrCode._errorFactory.create(code2, ...fullParams);
  }
  return _DEFAULT_AUTH_ERROR_FACTORY.create(authOrCode, ...rest);
}
__name(createErrorInternal, "createErrorInternal");
function _assert(assertion, authOrCode, ...rest) {
  if (!assertion) {
    throw createErrorInternal(authOrCode, ...rest);
  }
}
__name(_assert, "_assert");
function debugFail(failure) {
  const message = `INTERNAL ASSERTION FAILED: ` + failure;
  _logError(message);
  throw new Error(message);
}
__name(debugFail, "debugFail");
function debugAssert(assertion, message) {
  if (!assertion) {
    debugFail(message);
  }
}
__name(debugAssert, "debugAssert");
/**
 * @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.
 */
function _getCurrentUrl() {
  var _a2;
  return typeof self !== "undefined" && ((_a2 = self.location) === null || _a2 === void 0 ? void 0 : _a2.href) || "";
}
__name(_getCurrentUrl, "_getCurrentUrl");
function _isHttpOrHttps() {
  return _getCurrentScheme() === "http:" || _getCurrentScheme() === "https:";
}
__name(_isHttpOrHttps, "_isHttpOrHttps");
function _getCurrentScheme() {
  var _a2;
  return typeof self !== "undefined" && ((_a2 = self.location) === null || _a2 === void 0 ? void 0 : _a2.protocol) || null;
}
__name(_getCurrentScheme, "_getCurrentScheme");
/**
 * @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.
 */
function _isOnline() {
  if (typeof navigator !== "undefined" && navigator && "onLine" in navigator && typeof navigator.onLine === "boolean" && // Apply only for traditional web apps and Chrome extensions.
  // This is especially true for Cordova apps which have unreliable
  // navigator.onLine behavior unless cordova-plugin-network-information is
  // installed which overwrites the native navigator.onLine value and
  // defines navigator.connection.
  (_isHttpOrHttps() || isBrowserExtension() || "connection" in navigator)) {
    return navigator.onLine;
  }
  return true;
}
__name(_isOnline, "_isOnline");
function _getUserLanguage() {
  if (typeof navigator === "undefined") {
    return null;
  }
  const navigatorLanguage = navigator;
  return (
    // Most reliable, but only supported in Chrome/Firefox.
    navigatorLanguage.languages && navigatorLanguage.languages[0] || // Supported in most browsers, but returns the language of the browser
    // UI, not the language set in browser settings.
    navigatorLanguage.language || // Couldn't determine language.
    null
  );
}
__name(_getUserLanguage, "_getUserLanguage");
/**
 * @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 Delay {
  static {
    __name(this, "Delay");
  }
  constructor(shortDelay, longDelay) {
    this.shortDelay = shortDelay;
    this.longDelay = longDelay;
    debugAssert(longDelay > shortDelay, "Short delay should be less than long delay!");
    this.isMobile = isMobileCordova() || isReactNative();
  }
  get() {
    if (!_isOnline()) {
      return Math.min(5e3, this.shortDelay);
    }
    return this.isMobile ? this.longDelay : this.shortDelay;
  }
}
/**
 * @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.
 */
function _emulatorUrl(config2, path) {
  debugAssert(config2.emulator, "Emulator should always be set here");
  const { url } = config2.emulator;
  if (!path) {
    return url;
  }
  return `${url}${path.startsWith("/") ? path.slice(1) : path}`;
}
__name(_emulatorUrl, "_emulatorUrl");
/**
 * @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 FetchProvider {
  static {
    __name(this, "FetchProvider");
  }
  static initialize(fetchImpl, headersImpl, responseImpl) {
    this.fetchImpl = fetchImpl;
    if (headersImpl) {
      this.headersImpl = headersImpl;
    }
    if (responseImpl) {
      this.responseImpl = responseImpl;
    }
  }
  static fetch() {
    if (this.fetchImpl) {
      return this.fetchImpl;
    }
    if (typeof self !== "undefined" && "fetch" in self) {
      return self.fetch;
    }
    if (typeof globalThis !== "undefined" && globalThis.fetch) {
      return globalThis.fetch;
    }
    if (typeof fetch !== "undefined") {
      return fetch;
    }
    debugFail("Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill");
  }
  static headers() {
    if (this.headersImpl) {
      return this.headersImpl;
    }
    if (typeof self !== "undefined" && "Headers" in self) {
      return self.Headers;
    }
    if (typeof globalThis !== "undefined" && globalThis.Headers) {
      return globalThis.Headers;
    }
    if (typeof Headers !== "undefined") {
      return Headers;
    }
    debugFail("Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill");
  }
  static response() {
    if (this.responseImpl) {
      return this.responseImpl;
    }
    if (typeof self !== "undefined" && "Response" in self) {
      return self.Response;
    }
    if (typeof globalThis !== "undefined" && globalThis.Response) {
      return globalThis.Response;
    }
    if (typeof Response !== "undefined") {
      return Response;
    }
    debugFail("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill");
  }
}
/**
 * @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 SERVER_ERROR_MAP = {
  // Custom token errors.
  [
    "CREDENTIAL_MISMATCH"
    /* ServerError.CREDENTIAL_MISMATCH */
  ]: "custom-token-mismatch",
  // This can only happen if the SDK sends a bad request.
  [
    "MISSING_CUSTOM_TOKEN"
    /* ServerError.MISSING_CUSTOM_TOKEN */
  ]: "internal-error",
  // Create Auth URI errors.
  [
    "INVALID_IDENTIFIER"
    /* ServerError.INVALID_IDENTIFIER */
  ]: "invalid-email",
  // This can only happen if the SDK sends a bad request.
  [
    "MISSING_CONTINUE_URI"
    /* ServerError.MISSING_CONTINUE_URI */
  ]: "internal-error",
  // Sign in with email and password errors (some apply to sign up too).
  [
    "INVALID_PASSWORD"
    /* ServerError.INVALID_PASSWORD */
  ]: "wrong-password",
  // This can only happen if the SDK sends a bad request.
  [
    "MISSING_PASSWORD"
    /* ServerError.MISSING_PASSWORD */
  ]: "missing-password",
  // Thrown if Email Enumeration Protection is enabled in the project and the email or password is
  // invalid.
  [
    "INVALID_LOGIN_CREDENTIALS"
    /* ServerError.INVALID_LOGIN_CREDENTIALS */
  ]: "invalid-credential",
  // Sign up with email and password errors.
  [
    "EMAIL_EXISTS"
    /* ServerError.EMAIL_EXISTS */
  ]: "email-already-in-use",
  [
    "PASSWORD_LOGIN_DISABLED"
    /* ServerError.PASSWORD_LOGIN_DISABLED */
  ]: "operation-not-allowed",
  // Verify assertion for sign in with credential errors:
  [
    "INVALID_IDP_RESPONSE"
    /* ServerError.INVALID_IDP_RESPONSE */
  ]: "invalid-credential",
  [
    "INVALID_PENDING_TOKEN"
    /* ServerError.INVALID_PENDING_TOKEN */
  ]: "invalid-credential",
  [
    "FEDERATED_USER_ID_ALREADY_LINKED"
    /* ServerError.FEDERATED_USER_ID_ALREADY_LINKED */
  ]: "credential-already-in-use",
  // This can only happen if the SDK sends a bad request.
  [
    "MISSING_REQ_TYPE"
    /* ServerError.MISSING_REQ_TYPE */
  ]: "internal-error",
  // Send Password reset email errors:
  [
    "EMAIL_NOT_FOUND"
    /* ServerError.EMAIL_NOT_FOUND */
  ]: "user-not-found",
  [
    "RESET_PASSWORD_EXCEED_LIMIT"
    /* ServerError.RESET_PASSWORD_EXCEED_LIMIT */
  ]: "too-many-requests",
  [
    "EXPIRED_OOB_CODE"
    /* ServerError.EXPIRED_OOB_CODE */
  ]: "expired-action-code",
  [
    "INVALID_OOB_CODE"
    /* ServerError.INVALID_OOB_CODE */
  ]: "invalid-action-code",
  // This can only happen if the SDK sends a bad request.
  [
    "MISSING_OOB_CODE"
    /* ServerError.MISSING_OOB_CODE */
  ]: "internal-error",
  // Operations that require ID token in request:
  [
    "CREDENTIAL_TOO_OLD_LOGIN_AGAIN"
    /* ServerError.CREDENTIAL_TOO_OLD_LOGIN_AGAIN */
  ]: "requires-recent-login",
  [
    "INVALID_ID_TOKEN"
    /* ServerError.INVALID_ID_TOKEN */
  ]: "invalid-user-token",
  [
    "TOKEN_EXPIRED"
    /* ServerError.TOKEN_EXPIRED */
  ]: "user-token-expired",
  [
    "USER_NOT_FOUND"
    /* ServerError.USER_NOT_FOUND */
  ]: "user-token-expired",
  // Other errors.
  [
    "TOO_MANY_ATTEMPTS_TRY_LATER"
    /* ServerError.TOO_MANY_ATTEMPTS_TRY_LATER */
  ]: "too-many-requests",
  [
    "PASSWORD_DOES_NOT_MEET_REQUIREMENTS"
    /* ServerError.PASSWORD_DOES_NOT_MEET_REQUIREMENTS */
  ]: "password-does-not-meet-requirements",
  // Phone Auth related errors.
  [
    "INVALID_CODE"
    /* ServerError.INVALID_CODE */
  ]: "invalid-verification-code",
  [
    "INVALID_SESSION_INFO"
    /* ServerError.INVALID_SESSION_INFO */
  ]: "invalid-verification-id",
  [
    "INVALID_TEMPORARY_PROOF"
    /* ServerError.INVALID_TEMPORARY_PROOF */
  ]: "invalid-credential",
  [
    "MISSING_SESSION_INFO"
    /* ServerError.MISSING_SESSION_INFO */
  ]: "missing-verification-id",
  [
    "SESSION_EXPIRED"
    /* ServerError.SESSION_EXPIRED */
  ]: "code-expired",
  // Other action code errors when additional settings passed.
  // MISSING_CONTINUE_URI is getting mapped to INTERNAL_ERROR above.
  // This is OK as this error will be caught by client side validation.
  [
    "MISSING_ANDROID_PACKAGE_NAME"
    /* ServerError.MISSING_ANDROID_PACKAGE_NAME */
  ]: "missing-android-pkg-name",
  [
    "UNAUTHORIZED_DOMAIN"
    /* ServerError.UNAUTHORIZED_DOMAIN */
  ]: "unauthorized-continue-uri",
  // getProjectConfig errors when clientId is passed.
  [
    "INVALID_OAUTH_CLIENT_ID"
    /* ServerError.INVALID_OAUTH_CLIENT_ID */
  ]: "invalid-oauth-client-id",
  // User actions (sign-up or deletion) disabled errors.
  [
    "ADMIN_ONLY_OPERATION"
    /* ServerError.ADMIN_ONLY_OPERATION */
  ]: "admin-restricted-operation",
  // Multi factor related errors.
  [
    "INVALID_MFA_PENDING_CREDENTIAL"
    /* ServerError.INVALID_MFA_PENDING_CREDENTIAL */
  ]: "invalid-multi-factor-session",
  [
    "MFA_ENROLLMENT_NOT_FOUND"
    /* ServerError.MFA_ENROLLMENT_NOT_FOUND */
  ]: "multi-factor-info-not-found",
  [
    "MISSING_MFA_ENROLLMENT_ID"
    /* ServerError.MISSING_MFA_ENROLLMENT_ID */
  ]: "missing-multi-factor-info",
  [
    "MISSING_MFA_PENDING_CREDENTIAL"
    /* ServerError.MISSING_MFA_PENDING_CREDENTIAL */
  ]: "missing-multi-factor-session",
  [
    "SECOND_FACTOR_EXISTS"
    /* ServerError.SECOND_FACTOR_EXISTS */
  ]: "second-factor-already-in-use",
  [
    "SECOND_FACTOR_LIMIT_EXCEEDED"
    /* ServerError.SECOND_FACTOR_LIMIT_EXCEEDED */
  ]: "maximum-second-factor-count-exceeded",
  // Blocking functions related errors.
  [
    "BLOCKING_FUNCTION_ERROR_RESPONSE"
    /* ServerError.BLOCKING_FUNCTION_ERROR_RESPONSE */
  ]: "internal-error",
  // Recaptcha related errors.
  [
    "RECAPTCHA_NOT_ENABLED"
    /* ServerError.RECAPTCHA_NOT_ENABLED */
  ]: "recaptcha-not-enabled",
  [
    "MISSING_RECAPTCHA_TOKEN"
    /* ServerError.MISSING_RECAPTCHA_TOKEN */
  ]: "missing-recaptcha-token",
  [
    "INVALID_RECAPTCHA_TOKEN"
    /* ServerError.INVALID_RECAPTCHA_TOKEN */
  ]: "invalid-recaptcha-token",
  [
    "INVALID_RECAPTCHA_ACTION"
    /* ServerError.INVALID_RECAPTCHA_ACTION */
  ]: "invalid-recaptcha-action",
  [
    "MISSING_CLIENT_TYPE"
    /* ServerError.MISSING_CLIENT_TYPE */
  ]: "missing-client-type",
  [
    "MISSING_RECAPTCHA_VERSION"
    /* ServerError.MISSING_RECAPTCHA_VERSION */
  ]: "missing-recaptcha-version",
  [
    "INVALID_RECAPTCHA_VERSION"
    /* ServerError.INVALID_RECAPTCHA_VERSION */
  ]: "invalid-recaptcha-version",
  [
    "INVALID_REQ_TYPE"
    /* ServerError.INVALID_REQ_TYPE */
  ]: "invalid-req-type"
  /* AuthErrorCode.INVALID_REQ_TYPE */
};
/**
 * @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 CookieAuthProxiedEndpoints = [
  "/v1/accounts:signInWithCustomToken",
  "/v1/accounts:signInWithEmailLink",
  "/v1/accounts:signInWithIdp",
  "/v1/accounts:signInWithPassword",
  "/v1/accounts:signInWithPhoneNumber",
  "/v1/token"
  /* Endpoint.TOKEN */
];
const DEFAULT_API_TIMEOUT_MS = new Delay(3e4, 6e4);
function _addTidIfNecessary(auth2, request) {
  if (auth2.tenantId && !request.tenantId) {
    return Object.assign(Object.assign({}, request), { tenantId: auth2.tenantId });
  }
  return request;
}
__name(_addTidIfNecessary, "_addTidIfNecessary");
async function _performApiRequest(auth2, method, path, request, customErrorMap = {}) {
  return _performFetchWithErrorHandling(auth2, customErrorMap, async () => {
    let body = {};
    let params = {};
    if (request) {
      if (method === "GET") {
        params = request;
      } else {
        body = {
          body: JSON.stringify(request)
        };
      }
    }
    const query2 = querystring(Object.assign({ key: auth2.config.apiKey }, params)).slice(1);
    const headers = await auth2._getAdditionalHeaders();
    headers[
      "Content-Type"
      /* HttpHeader.CONTENT_TYPE */
    ] = "application/json";
    if (auth2.languageCode) {
      headers[
        "X-Firebase-Locale"
        /* HttpHeader.X_FIREBASE_LOCALE */
      ] = auth2.languageCode;
    }
    const fetchArgs = Object.assign({
      method,
      headers
    }, body);
    if (!isCloudflareWorker()) {
      fetchArgs.referrerPolicy = "no-referrer";
    }
    return FetchProvider.fetch()(await _getFinalTarget(auth2, auth2.config.apiHost, path, query2), fetchArgs);
  });
}
__name(_performApiRequest, "_performApiRequest");
async function _performFetchWithErrorHandling(auth2, customErrorMap, fetchFn) {
  auth2._canInitEmulator = false;
  const errorMap2 = Object.assign(Object.assign({}, SERVER_ERROR_MAP), customErrorMap);
  try {
    const networkTimeout = new NetworkTimeout(auth2);
    const response = await Promise.race([
      fetchFn(),
      networkTimeout.promise
    ]);
    networkTimeout.clearNetworkTimeout();
    const json = await response.json();
    if ("needConfirmation" in json) {
      throw _makeTaggedError(auth2, "account-exists-with-different-credential", json);
    }
    if (response.ok && !("errorMessage" in json)) {
      return json;
    } else {
      const errorMessage = response.ok ? json.errorMessage : json.error.message;
      const [serverErrorCode, serverErrorMessage] = errorMessage.split(" : ");
      if (serverErrorCode === "FEDERATED_USER_ID_ALREADY_LINKED") {
        throw _makeTaggedError(auth2, "credential-already-in-use", json);
      } else if (serverErrorCode === "EMAIL_EXISTS") {
        throw _makeTaggedError(auth2, "email-already-in-use", json);
      } else if (serverErrorCode === "USER_DISABLED") {
        throw _makeTaggedError(auth2, "user-disabled", json);
      }
      const authError = errorMap2[serverErrorCode] || serverErrorCode.toLowerCase().replace(/[_\s]+/g, "-");
      if (serverErrorMessage) {
        throw _errorWithCustomMessage(auth2, authError, serverErrorMessage);
      } else {
        _fail(auth2, authError);
      }
    }
  } catch (e2) {
    if (e2 instanceof FirebaseError) {
      throw e2;
    }
    _fail(auth2, "network-request-failed", { "message": String(e2) });
  }
}
__name(_performFetchWithErrorHandling, "_performFetchWithErrorHandling");
async function _performSignInRequest(auth2, method, path, request, customErrorMap = {}) {
  const serverResponse = await _performApiRequest(auth2, method, path, request, customErrorMap);
  if ("mfaPendingCredential" in serverResponse) {
    _fail(auth2, "multi-factor-auth-required", {
      _serverResponse: serverResponse
    });
  }
  return serverResponse;
}
__name(_performSignInRequest, "_performSignInRequest");
async function _getFinalTarget(auth2, host, path, query2) {
  const base2 = `${host}${path}?${query2}`;
  const authInternal = auth2;
  const finalTarget = authInternal.config.emulator ? _emulatorUrl(auth2.config, base2) : `${auth2.config.apiScheme}://${base2}`;
  if (CookieAuthProxiedEndpoints.includes(path)) {
    await authInternal._persistenceManagerAvailable;
    if (authInternal._getPersistenceType() === "COOKIE") {
      const cookiePersistence = authInternal._getPersistence();
      return cookiePersistence._getFinalTarget(finalTarget).toString();
    }
  }
  return finalTarget;
}
__name(_getFinalTarget, "_getFinalTarget");
function _parseEnforcementState(enforcementStateStr) {
  switch (enforcementStateStr) {
    case "ENFORCE":
      return "ENFORCE";
    case "AUDIT":
      return "AUDIT";
    case "OFF":
      return "OFF";
    default:
      return "ENFORCEMENT_STATE_UNSPECIFIED";
  }
}
__name(_parseEnforcementState, "_parseEnforcementState");
class NetworkTimeout {
  static {
    __name(this, "NetworkTimeout");
  }
  clearNetworkTimeout() {
    clearTimeout(this.timer);
  }
  constructor(auth2) {
    this.auth = auth2;
    this.timer = null;
    this.promise = new Promise((_2, reject) => {
      this.timer = setTimeout(() => {
        return reject(_createError(
          this.auth,
          "network-request-failed"
          /* AuthErrorCode.NETWORK_REQUEST_FAILED */
        ));
      }, DEFAULT_API_TIMEOUT_MS.get());
    });
  }
}
function _makeTaggedError(auth2, code2, response) {
  const errorParams = {
    appName: auth2.name
  };
  if (response.email) {
    errorParams.email = response.email;
  }
  if (response.phoneNumber) {
    errorParams.phoneNumber = response.phoneNumber;
  }
  const error2 = _createError(auth2, code2, errorParams);
  error2.customData._tokenResponse = response;
  return error2;
}
__name(_makeTaggedError, "_makeTaggedError");
/**
 * @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.
 */
function isV2(grecaptcha) {
  return grecaptcha !== void 0 && grecaptcha.getResponse !== void 0;
}
__name(isV2, "isV2");
function isEnterprise(grecaptcha) {
  return grecaptcha !== void 0 && grecaptcha.enterprise !== void 0;
}
__name(isEnterprise, "isEnterprise");
class RecaptchaConfig {
  static {
    __name(this, "RecaptchaConfig");
  }
  constructor(response) {
    this.siteKey = "";
    this.recaptchaEnforcementState = [];
    if (response.recaptchaKey === void 0) {
      throw new Error("recaptchaKey undefined");
    }
    this.siteKey = response.recaptchaKey.split("/")[3];
    this.recaptchaEnforcementState = response.recaptchaEnforcementState;
  }
  /**
   * Returns the reCAPTCHA Enterprise enforcement state for the given provider.
   *
   * @param providerStr - The provider whose enforcement state is to be returned.
   * @returns The reCAPTCHA Enterprise enforcement state for the given provider.
   */
  getProviderEnforcementState(providerStr) {
    if (!this.recaptchaEnforcementState || this.recaptchaEnforcementState.length === 0) {
      return null;
    }
    for (const recaptchaEnforcementState of this.recaptchaEnforcementState) {
      if (recaptchaEnforcementState.provider && recaptchaEnforcementState.provider === providerStr) {
        return _parseEnforcementState(recaptchaEnforcementState.enforcementState);
      }
    }
    return null;
  }
  /**
   * Returns true if the reCAPTCHA Enterprise enforcement state for the provider is set to ENFORCE or AUDIT.
   *
   * @param providerStr - The provider whose enablement state is to be returned.
   * @returns Whether or not reCAPTCHA Enterprise protection is enabled for the given provider.
   */
  isProviderEnabled(providerStr) {
    return this.getProviderEnforcementState(providerStr) === "ENFORCE" || this.getProviderEnforcementState(providerStr) === "AUDIT";
  }
  /**
   * Returns true if reCAPTCHA Enterprise protection is enabled in at least one provider, otherwise
   * returns false.
   *
   * @returns Whether or not reCAPTCHA Enterprise protection is enabled for at least one provider.
   */
  isAnyProviderEnabled() {
    return this.isProviderEnabled(
      "EMAIL_PASSWORD_PROVIDER"
      /* RecaptchaAuthProvider.EMAIL_PASSWORD_PROVIDER */
    ) || this.isProviderEnabled(
      "PHONE_PROVIDER"
      /* RecaptchaAuthProvider.PHONE_PROVIDER */
    );
  }
}
/**
 * @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.
 */
async function getRecaptchaParams(auth2) {
  return (await _performApiRequest(
    auth2,
    "GET",
    "/v1/recaptchaParams"
    /* Endpoint.GET_RECAPTCHA_PARAM */
  )).recaptchaSiteKey || "";
}
__name(getRecaptchaParams, "getRecaptchaParams");
async function getRecaptchaConfig(auth2, request) {
  return _performApiRequest(auth2, "GET", "/v2/recaptchaConfig", _addTidIfNecessary(auth2, request));
}
__name(getRecaptchaConfig, "getRecaptchaConfig");
/**
 * @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.
 */
async function deleteAccount(auth2, request) {
  return _performApiRequest(auth2, "POST", "/v1/accounts:delete", request);
}
__name(deleteAccount, "deleteAccount");
async function deleteLinkedAccounts(auth2, request) {
  return _performApiRequest(auth2, "POST", "/v1/accounts:update", request);
}
__name(deleteLinkedAccounts, "deleteLinkedAccounts");
async function getAccountInfo(auth2, request) {
  return _performApiRequest(auth2, "POST", "/v1/accounts:lookup", request);
}
__name(getAccountInfo, "getAccountInfo");
/**
 * @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.
 */
function utcTimestampToDateString(utcTimestamp) {
  if (!utcTimestamp) {
    return void 0;
  }
  try {
    const date = new Date(Number(utcTimestamp));
    if (!isNaN(date.getTime())) {
      return date.toUTCString();
    }
  } catch (e2) {
  }
  return void 0;
}
__name(utcTimestampToDateString, "utcTimestampToDateString");
/**
 * @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.
 */
function getIdToken(user, forceRefresh = false) {
  return getModularInstance(user).getIdToken(forceRefresh);
}
__name(getIdToken, "getIdToken");
async function getIdTokenResult(user, forceRefresh = false) {
  const userInternal = getModularInstance(user);
  const token = await userInternal.getIdToken(forceRefresh);
  const claims = _parseToken(token);
  _assert(
    claims && claims.exp && claims.auth_time && claims.iat,
    userInternal.auth,
    "internal-error"
    /* AuthErrorCode.INTERNAL_ERROR */
  );
  const firebase = typeof claims.firebase === "object" ? claims.firebase : void 0;
  const signInProvider = firebase === null || firebase === void 0 ? void 0 : firebase["sign_in_provider"];
  return {
    claims,
    token,
    authTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.auth_time)),
    issuedAtTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.iat)),
    expirationTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.exp)),
    signInProvider: signInProvider || null,
    signInSecondFactor: (firebase === null || firebase === void 0 ? void 0 : firebase["sign_in_second_factor"]) || null
  };
}
__name(getIdTokenResult, "getIdTokenResult");
function secondsStringToMilliseconds(seconds) {
  return Number(seconds) * 1e3;
}
__name(secondsStringToMilliseconds, "secondsStringToMilliseconds");
function _parseToken(token) {
  const [algorithm, payload, signature] = token.split(".");
  if (algorithm === void 0 || payload === void 0 || signature === void 0) {
    _logError("JWT malformed, contained fewer than 3 sections");
    return null;
  }
  try {
    const decoded = base64Decode(payload);
    if (!decoded) {
      _logError("Failed to decode base64 JWT payload");
      return null;
    }
    return JSON.parse(decoded);
  } catch (e2) {
    _logError("Caught error parsing JWT payload as JSON", e2 === null || e2 === void 0 ? void 0 : e2.toString());
    return null;
  }
}
__name(_parseToken, "_parseToken");
function _tokenExpiresIn(token) {
  const parsedToken = _parseToken(token);
  _assert(
    parsedToken,
    "internal-error"
    /* AuthErrorCode.INTERNAL_ERROR */
  );
  _assert(
    typeof parsedToken.exp !== "undefined",
    "internal-error"
    /* AuthErrorCode.INTERNAL_ERROR */
  );
  _assert(
    typeof parsedToken.iat !== "undefined",
    "internal-error"
    /* AuthErrorCode.INTERNAL_ERROR */
  );
  return Number(parsedToken.exp) - Number(parsedToken.iat);
}
__name(_tokenExpiresIn, "_tokenExpiresIn");
/**
 * @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.
 */
async function _logoutIfInvalidated(user, promise, bypassAuthState = false) {
  if (bypassAuthState) {
    return promise;
  }
  try {
    return await promise;
  } catch (e2) {
    if (e2 instanceof FirebaseError && isUserInvalidated(e2)) {
      if (user.auth.currentUser === user) {
        await user.auth.signOut();
      }
    }
    throw e2;
  }
}
__name(_logoutIfInvalidated, "_logoutIfInvalidated");
function isUserInvalidated({ code: code2 }) {
  return code2 === `auth/${"user-disabled"}` || code2 === `auth/${"user-token-expired"}`;
}
__name(isUserInvalidated, "isUserInvalidated");
/**
 * @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 ProactiveRefresh {
  static {
    __name(this, "ProactiveRefresh");
  }
  constructor(user) {
    this.user = user;
    this.isRunning = false;
    this.timerId = null;
    this.errorBackoff = 3e4;
  }
  _start() {
    if (this.isRunning) {
      return;
    }
    this.isRunning = true;
    this.schedule();
  }
  _stop() {
    if (!this.isRunning) {
      return;
    }
    this.isRunning = false;
    if (this.timerId !== null) {
      clearTimeout(this.timerId);
    }
  }
  getInterval(wasError) {
    var _a2;
    if (wasError) {
      const interval = this.errorBackoff;
      this.errorBackoff = Math.min(
        this.errorBackoff * 2,
        96e4
        /* Duration.RETRY_BACKOFF_MAX */
      );
      return interval;
    } else {
      this.errorBackoff = 3e4;
      const expTime = (_a2 = this.user.stsTokenManager.expirationTime) !== null && _a2 !== void 0 ? _a2 : 0;
      const interval = expTime - Date.now() - 3e5;
      return Math.max(0, interval);
    }
  }
  schedule(wasError = false) {
    if (!this.isRunning) {
      return;
    }
    const interval = this.getInterval(wasError);
    this.timerId = setTimeout(async () => {
      await this.iteration();
    }, interval);
  }
  async iteration() {
    try {
      await this.user.getIdToken(true);
    } catch (e2) {
      if ((e2 === null || e2 === void 0 ? void 0 : e2.code) === `auth/${"network-request-failed"}`) {
        this.schedule(
          /* wasError */
          true
        );
      }
      return;
    }
    this.schedule();
  }
}
/**
 * @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 UserMetadata {
  static {
    __name(this, "UserMetadata");
  }
  constructor(createdAt, lastLoginAt) {
    this.createdAt = createdAt;
    this.lastLoginAt = lastLoginAt;
    this._initializeTime();
  }
  _initializeTime() {
    this.lastSignInTime = utcTimestampToDateString(this.lastLoginAt);
    this.creationTime = utcTimestampToDateString(this.createdAt);
  }
  _copy(metadata) {
    this.createdAt = metadata.createdAt;
    this.lastLoginAt = metadata.lastLoginAt;
    this._initializeTime();
  }
  toJSON() {
    return {
      createdAt: this.createdAt,
      lastLoginAt: this.lastLoginAt
    };
  }
}
/**
 * @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.
 */
async function _reloadWithoutSaving(user) {
  var _a2;
  const auth2 = user.auth;
  const idToken = await user.getIdToken();
  const response = await _logoutIfInvalidated(user, getAccountInfo(auth2, { idToken }));
  _assert(
    response === null || response === void 0 ? void 0 : response.users.length,
    auth2,
    "internal-error"
    /* AuthErrorCode.INTERNAL_ERROR */
  );
  const coreAccount = response.users[0];
  user._notifyReloadListener(coreAccount);
  const newProviderData = ((_a2 = coreAccount.providerUserInfo) === null || _a2 === void 0 ? void 0 : _a2.length) ? extractProviderData(coreAccount.providerUserInfo) : [];
  const providerData = mergeProviderData(user.providerData, newProviderData);
  const oldIsAnonymous = user.isAnonymous;
  const newIsAnonymous = !(user.email && coreAccount.passwordHash) && !(providerData === null || providerData === void 0 ? void 0 : providerData.length);
  const isAnonymous = !oldIsAnonymous ? false : newIsAnonymous;
  const updates = {
    uid: coreAccount.localId,
    displayName: coreAccount.displayName || null,
    photoURL: coreAccount.photoUrl || null,
    email: coreAccount.email || null,
    emailVerified: coreAccount.emailVerified || false,
    phoneNumber: coreAccount.phoneNumber || null,
    tenantId: coreAccount.tenantId || null,
    providerData,
    metadata: new UserMetadata(coreAccount.createdAt, coreAccount.lastLoginAt),
    isAnonymous
  };
  Object.assign(user, updates);
}
__name(_reloadWithoutSaving, "_reloadWithoutSaving");
async function reload(user) {
  const userInternal = getModularInstance(user);
  await _reloadWithoutSaving(userInternal);
  await userInternal.auth._persistUserIfCurrent(userInternal);
  userInternal.auth._notifyListenersIfCurrent(userInternal);
}
__name(reload, "reload");
function mergeProviderData(original, newData) {
  const deduped = original.filter((o2) => !newData.some((n2) => n2.providerId === o2.providerId));
  return [...deduped, ...newData];
}
__name(mergeProviderData, "mergeProviderData");
function extractProviderData(providers) {
  return providers.map((_a2) => {
    var { providerId } = _a2, provider = __rest(_a2, ["providerId"]);
    return {
      providerId,
      uid: provider.rawId || "",
      displayName: provider.displayName || null,
      email: provider.email || null,
      phoneNumber: provider.phoneNumber || null,
      photoURL: provider.photoUrl || null
    };
  });
}
__name(extractProviderData, "extractProviderData");
/**
 * @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.
 */
async function requestStsToken(auth2, refreshToken) {
  const response = await _performFetchWithErrorHandling(auth2, {}, async () => {
    const body = querystring({
      "grant_type": "refresh_token",
      "refresh_token": refreshToken
    }).slice(1);
    const { tokenApiHost, apiKey } = auth2.config;
    const url = await _getFinalTarget(auth2, tokenApiHost, "/v1/token", `key=${apiKey}`);
    const headers = await auth2._getAdditionalHeaders();
    headers[
      "Content-Type"
      /* HttpHeader.CONTENT_TYPE */
    ] = "application/x-www-form-urlencoded";
    return FetchProvider.fetch()(url, {
      method: "POST",
      headers,
      body
    });
  });
  return {
    accessToken: response.access_token,
    expiresIn: response.expires_in,
    refreshToken: response.refresh_token
  };
}
__name(requestStsToken, "requestStsToken");
async function revokeToken(auth2, request) {
  return _performApiRequest(auth2, "POST", "/v2/accounts:revokeToken", _addTidIfNecessary(auth2, request));
}
__name(revokeToken, "revokeToken");
/**
 * @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 StsTokenManager {
  static {
    __name(this, "StsTokenManager");
  }
  constructor() {
    this.refreshToken = null;
    this.accessToken = null;
    this.expirationTime = null;
  }
  get isExpired() {
    return !this.expirationTime || Date.now() > this.expirationTime - 3e4;
  }
  updateFromServerResponse(response) {
    _assert(
      response.idToken,
      "internal-error"
      /* AuthErrorCode.INTERNAL_ERROR */
    );
    _assert(
      typeof response.idToken !== "undefined",
      "internal-error"
      /* AuthErrorCode.INTERNAL_ERROR */
    );
    _assert(
      typeof response.refreshToken !== "undefined",
      "internal-error"
      /* AuthErrorCode.INTERNAL_ERROR */
    );
    const expiresIn = "expiresIn" in response && typeof response.expiresIn !== "undefined" ? Number(response.expiresIn) : _tokenExpiresIn(response.idToken);
    this.updateTokensAndExpiration(response.idToken, response.refreshToken, expiresIn);
  }
  updateFromIdToken(idToken) {
    _assert(
      idToken.length !== 0,
      "internal-error"
      /* AuthErrorCode.INTERNAL_ERROR */
    );
    const expiresIn = _tokenExpiresIn(idToken);
    this.updateTokensAndExpiration(idToken, null, expiresIn);
  }
  async getToken(auth2, forceRefresh = false) {
    if (!forceRefresh && this.accessToken && !this.isExpired) {
      return this.accessToken;
    }
    _assert(
      this.refreshToken,
      auth2,
      "user-token-expired"
      /* AuthErrorCode.TOKEN_EXPIRED */
    );
    if (this.refreshToken) {
      await this.refresh(auth2, this.refreshToken);
      return this.accessToken;
    }
    return null;
  }
  clearRefreshToken() {
    this.refreshToken = null;
  }
  async refresh(auth2, oldToken) {
    const { accessToken, refreshToken, expiresIn } = await requestStsToken(auth2, oldToken);
    this.updateTokensAndExpiration(accessToken, refreshToken, Number(expiresIn));
  }
  updateTokensAndExpiration(accessToken, refreshToken, expiresInSec) {
    this.refreshToken = refreshToken || null;
    this.accessToken = accessToken || null;
    this.expirationTime = Date.now() + expiresInSec * 1e3;
  }
  static fromJSON(appName, object) {
    const { refreshToken, accessToken, expirationTime } = object;
    const manager2 = new StsTokenManager();
    if (refreshToken) {
      _assert(typeof refreshToken === "string", "internal-error", {
        appName
      });
      manager2.refreshToken = refreshToken;
    }
    if (accessToken) {
      _assert(typeof accessToken === "string", "internal-error", {
        appName
      });
      manager2.accessToken = accessToken;
    }
    if (expirationTime) {
      _assert(typeof expirationTime === "number", "internal-error", {
        appName
      });
      manager2.expirationTime = expirationTime;
    }
    return manager2;
  }
  toJSON() {
    return {
      refreshToken: this.refreshToken,
      accessToken: this.accessToken,
      expirationTime: this.expirationTime
    };
  }
  _assign(stsTokenManager) {
    this.accessToken = stsTokenManager.accessToken;
    this.refreshToken = stsTokenManager.refreshToken;
    this.expirationTime = stsTokenManager.expirationTime;
  }
  _clone() {
    return Object.assign(new StsTokenManager(), this.toJSON());
  }
  _performRefresh() {
    return debugFail("not implemented");
  }
}
/**
 * @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.
 */
function assertStringOrUndefined(assertion, appName) {
  _assert(typeof assertion === "string" || typeof assertion === "undefined", "internal-error", { appName });
}
__name(assertStringOrUndefined, "assertStringOrUndefined");
class UserImpl {
  static {
    __name(this, "UserImpl");
  }
  constructor(_a2) {
    var { uid, auth: auth2, stsTokenManager } = _a2, opt = __rest(_a2, ["uid", "auth", "stsTokenManager"]);
    this.providerId = "firebase";
    this.proactiveRefresh = new ProactiveRefresh(this);
    this.reloadUserInfo = null;
    this.reloadListener = null;
    this.uid = uid;
    this.auth = auth2;
    this.stsTokenManager = stsTokenManager;
    this.accessToken = stsTokenManager.accessToken;
    this.displayName = opt.displayName || null;
    this.email = opt.email || null;
    this.emailVerified = opt.emailVerified || false;
    this.phoneNumber = opt.phoneNumber || null;
    this.photoURL = opt.photoURL || null;
    this.isAnonymous = opt.isAnonymous || false;
    this.tenantId = opt.tenantId || null;
    this.providerData = opt.providerData ? [...opt.providerData] : [];
    this.metadata = new UserMetadata(opt.createdAt || void 0, opt.lastLoginAt || void 0);
  }
  async getIdToken(forceRefresh) {
    const accessToken = await _logoutIfInvalidated(this, this.stsTokenManager.getToken(this.auth, forceRefresh));
    _assert(
      accessToken,
      this.auth,
      "internal-error"
      /* AuthErrorCode.INTERNAL_ERROR */
    );
    if (this.accessToken !== accessToken) {
      this.accessToken = accessToken;
      await this.auth._persistUserIfCurrent(this);
      this.auth._notifyListenersIfCurrent(this);
    }
    return accessToken;
  }
  getIdTokenResult(forceRefresh) {
    return getIdTokenResult(this, forceRefresh);
  }
  reload() {
    return reload(this);
  }
  _assign(user) {
    if (this === user) {
      return;
    }
    _assert(
      this.uid === user.uid,
      this.auth,
      "internal-error"
      /* AuthErrorCode.INTERNAL_ERROR */
    );
    this.displayName = user.displayName;
    this.photoURL = user.photoURL;
    this.email = user.email;
    this.emailVerified = user.emailVerified;
    this.phoneNumber = user.phoneNumber;
    this.isAnonymous = user.isAnonymous;
    this.tenantId = user.tenantId;
    this.providerData = user.providerData.map((userInfo) => Object.assign({}, userInfo));
    this.metadata._copy(user.metadata);
    this.stsTokenManager._assign(user.stsTokenManager);
  }
  _clone(auth2) {
    const newUser = new UserImpl(Object.assign(Object.assign({}, this), { auth: auth2, stsTokenManager: this.stsTokenManager._clone() }));
    newUser.metadata._copy(this.metadata);
    return newUser;
  }
  _onReload(callback) {
    _assert(
      !this.reloadListener,
      this.auth,
      "internal-error"
      /* AuthErrorCode.INTERNAL_ERROR */
    );
    this.reloadListener = callback;
    if (this.reloadUserInfo) {
      this._notifyReloadListener(this.reloadUserInfo);
      this.reloadUserInfo = null;
    }
  }
  _notifyReloadListener(userInfo) {
    if (this.reloadListener) {
      this.reloadListener(userInfo);
    } else {
      this.reloadUserInfo = userInfo;
    }
  }
  _startProactiveRefresh() {
    this.proactiveRefresh._start();
  }
  _stopProactiveRefresh() {
    this.proactiveRefresh._stop();
  }
  async _updateTokensIfNecessary(response, reload2 = false) {
    let tokensRefreshed = false;
    if (response.idToken && response.idToken !== this.stsTokenManager.accessToken) {
      this.stsTokenManager.updateFromServerResponse(response);
      tokensRefreshed = true;
    }
    if (reload2) {
      await _reloadWithoutSaving(this);
    }
    await this.auth._persistUserIfCurrent(this);
    if (tokensRefreshed) {
      this.auth._notifyListenersIfCurrent(this);
    }
  }
  async delete() {
    if (_isFirebaseServerApp(this.auth.app)) {
      return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this.auth));
    }
    const idToken = await this.getIdToken();
    await _logoutIfInvalidated(this, deleteAccount(this.auth, { idToken }));
    this.stsTokenManager.clearRefreshToken();
    return this.auth.signOut();
  }
  toJSON() {
    return Object.assign(Object.assign({
      uid: this.uid,
      email: this.email || void 0,
      emailVerified: this.emailVerified,
      displayName: this.displayName || void 0,
      isAnonymous: this.isAnonymous,
      photoURL: this.photoURL || void 0,
      phoneNumber: this.phoneNumber || void 0,
      tenantId: this.tenantId || void 0,
      providerData: this.providerData.map((userInfo) => Object.assign({}, userInfo)),
      stsTokenManager: this.stsTokenManager.toJSON(),
      // Redirect event ID must be maintained in case there is a pending
      // redirect event.
      _redirectEventId: this._redirectEventId
    }, this.metadata.toJSON()), {
      // Required for compatibility with the legacy SDK (go/firebase-auth-sdk-persistence-parsing):
      apiKey: this.auth.config.apiKey,
      appName: this.auth.name
    });
  }
  get refreshToken() {
    return this.stsTokenManager.refreshToken || "";
  }
  static _fromJSON(auth2, object) {
    var _a2, _b, _c, _d, _e2, _f, _g, _h;
    const displayName = (_a2 = object.displayName) !== null && _a2 !== void 0 ? _a2 : void 0;
    const email = (_b = object.email) !== null && _b !== void 0 ? _b : void 0;
    const phoneNumber = (_c = object.phoneNumber) !== null && _c !== void 0 ? _c : void 0;
    const photoURL = (_d = object.photoURL) !== null && _d !== void 0 ? _d : void 0;
    const tenantId = (_e2 = object.tenantId) !== null && _e2 !== void 0 ? _e2 : void 0;
    const _redirectEventId = (_f = object._redirectEventId) !== null && _f !== void 0 ? _f : void 0;
    const createdAt = (_g = object.createdAt) !== null && _g !== void 0 ? _g : void 0;
    const lastLoginAt = (_h = object.lastLoginAt) !== null && _h !== void 0 ? _h : void 0;
    const { uid, emailVerified, isAnonymous, providerData, stsTokenManager: plainObjectTokenManager } = object;
    _assert(
      uid && plainObjectTokenManager,
      auth2,
      "internal-error"
      /* AuthErrorCode.INTERNAL_ERROR */
    );
    const stsTokenManager = StsTokenManager.fromJSON(this.name, plainObjectTokenManager);
    _assert(
      typeof uid === "string",
      auth2,
      "internal-error"
      /* AuthErrorCode.INTERNAL_ERROR */
    );
    assertStringOrUndefined(displayName, auth2.name);
    assertStringOrUndefined(email, auth2.name);
    _assert(
      typeof emailVerified === "boolean",
      auth2,
      "internal-error"
      /* AuthErrorCode.INTERNAL_ERROR */
    );
    _assert(
      typeof isAnonymous === "boolean",
      auth2,
      "internal-error"
      /* AuthErrorCode.INTERNAL_ERROR */
    );
    assertStringOrUndefined(phoneNumber, auth2.name);
    assertStringOrUndefined(photoURL, auth2.name);
    assertStringOrUndefined(tenantId, auth2.name);
    assertStringOrUndefined(_redirectEventId, auth2.name);
    assertStringOrUndefined(createdAt, auth2.name);
    assertStringOrUndefined(lastLoginAt, auth2.name);
    const user = new UserImpl({
      uid,
      auth: auth2,
      email,
      emailVerified,
      displayName,
      isAnonymous,
      photoURL,
      phoneNumber,
      tenantId,
      stsTokenManager,
      createdAt,
      lastLoginAt
    });
    if (providerData && Array.isArray(providerData)) {
      user.providerData = providerData.map((userInfo) => Object.assign({}, userInfo));
    }
    if (_redirectEventId) {
      user._redirectEventId = _redirectEventId;
    }
    return user;
  }
  /**
   * Initialize a User from an idToken server response
   * @param auth
   * @param idTokenResponse
   */
  static async _fromIdTokenResponse(auth2, idTokenResponse, isAnonymous = false) {
    const stsTokenManager = new StsTokenManager();
    stsTokenManager.updateFromServerResponse(idTokenResponse);
    const user = new UserImpl({
      uid: idTokenResponse.localId,
      auth: auth2,
      stsTokenManager,
      isAnonymous
    });
    await _reloadWithoutSaving(user);
    return user;
  }
  /**
   * Initialize a User from an idToken server response
   * @param auth
   * @param idTokenResponse
   */
  static async _fromGetAccountInfoResponse(auth2, response, idToken) {
    const coreAccount = response.users[0];
    _assert(
      coreAccount.localId !== void 0,
      "internal-error"
      /* AuthErrorCode.INTERNAL_ERROR */
    );
    const providerData = coreAccount.providerUserInfo !== void 0 ? extractProviderData(coreAccount.providerUserInfo) : [];
    const isAnonymous = !(coreAccount.email && coreAccount.passwordHash) && !(providerData === null || providerData === void 0 ? void 0 : providerData.length);
    const stsTokenManager = new StsTokenManager();
    stsTokenManager.updateFromIdToken(idToken);
    const user = new UserImpl({
      uid: coreAccount.localId,
      auth: auth2,
      stsTokenManager,
      isAnonymous
    });
    const updates = {
      uid: coreAccount.localId,
      displayName: coreAccount.displayName || null,
      photoURL: coreAccount.photoUrl || null,
      email: coreAccount.email || null,
      emailVerified: coreAccount.emailVerified || false,
      phoneNumber: coreAccount.phoneNumber || null,
      tenantId: coreAccount.tenantId || null,
      providerData,
      metadata: new UserMetadata(coreAccount.createdAt, coreAccount.lastLoginAt),
      isAnonymous: !(coreAccount.email && coreAccount.passwordHash) && !(providerData === null || providerData === void 0 ? void 0 : providerData.length)
    };
    Object.assign(user, updates);
    return user;
  }
}
/**
 * @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 instanceCache = /* @__PURE__ */ new Map();
function _getInstance(cls) {
  debugAssert(cls instanceof Function, "Expected a class definition");
  let instance = instanceCache.get(cls);
  if (instance) {
    debugAssert(instance instanceof cls, "Instance stored in cache mismatched with class");
    return instance;
  }
  instance = new cls();
  instanceCache.set(cls, instance);
  return instance;
}
__name(_getInstance, "_getInstance");
/**
 * @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 InMemoryPersistence {
  static {
    __name(this, "InMemoryPersistence");
  }
  constructor() {
    this.type = "NONE";
    this.storage = {};
  }
  async _isAvailable() {
    return true;
  }
  async _set(key, value) {
    this.storage[key] = value;
  }
  async _get(key) {
    const value = this.storage[key];
    return value === void 0 ? null : value;
  }
  async _remove(key) {
    delete this.storage[key];
  }
  _addListener(_key, _listener) {
    return;
  }
  _removeListener(_key, _listener) {
    return;
  }
}
InMemoryPersistence.type = "NONE";
const inMemoryPersistence = InMemoryPersistence;
/**
 * @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 _persistenceKeyName(key, apiKey, appName) {
  return `${"firebase"}:${key}:${apiKey}:${appName}`;
}
__name(_persistenceKeyName, "_persistenceKeyName");
class PersistenceUserManager {
  static {
    __name(this, "PersistenceUserManager");
  }
  constructor(persistence, auth2, userKey) {
    this.persistence = persistence;
    this.auth = auth2;
    this.userKey = userKey;
    const { config: config2, name: name2 } = this.auth;
    this.fullUserKey = _persistenceKeyName(this.userKey, config2.apiKey, name2);
    this.fullPersistenceKey = _persistenceKeyName("persistence", config2.apiKey, name2);
    this.boundEventHandler = auth2._onStorageEvent.bind(auth2);
    this.persistence._addListener(this.fullUserKey, this.boundEventHandler);
  }
  setCurrentUser(user) {
    return this.persistence._set(this.fullUserKey, user.toJSON());
  }
  async getCurrentUser() {
    const blob = await this.persistence._get(this.fullUserKey);
    if (!blob) {
      return null;
    }
    if (typeof blob === "string") {
      const response = await getAccountInfo(this.auth, { idToken: blob }).catch(() => void 0);
      if (!response) {
        return null;
      }
      return UserImpl._fromGetAccountInfoResponse(this.auth, response, blob);
    }
    return UserImpl._fromJSON(this.auth, blob);
  }
  removeCurrentUser() {
    return this.persistence._remove(this.fullUserKey);
  }
  savePersistenceForRedirect() {
    return this.persistence._set(this.fullPersistenceKey, this.persistence.type);
  }
  async setPersistence(newPersistence) {
    if (this.persistence === newPersistence) {
      return;
    }
    const currentUser = await this.getCurrentUser();
    await this.removeCurrentUser();
    this.persistence = newPersistence;
    if (currentUser) {
      return this.setCurrentUser(currentUser);
    }
  }
  delete() {
    this.persistence._removeListener(this.fullUserKey, this.boundEventHandler);
  }
  static async create(auth2, persistenceHierarchy, userKey = "authUser") {
    if (!persistenceHierarchy.length) {
      return new PersistenceUserManager(_getInstance(inMemoryPersistence), auth2, userKey);
    }
    const availablePersistences = (await Promise.all(persistenceHierarchy.map(async (persistence) => {
      if (await persistence._isAvailable()) {
        return persistence;
      }
      return void 0;
    }))).filter((persistence) => persistence);
    let selectedPersistence = availablePersistences[0] || _getInstance(inMemoryPersistence);
    const key = _persistenceKeyName(userKey, auth2.config.apiKey, auth2.name);
    let userToMigrate = null;
    for (const persistence of persistenceHierarchy) {
      try {
        const blob = await persistence._get(key);
        if (blob) {
          let user;
          if (typeof blob === "string") {
            const response = await getAccountInfo(auth2, {
              idToken: blob
            }).catch(() => void 0);
            if (!response) {
              break;
            }
            user = await UserImpl._fromGetAccountInfoResponse(auth2, response, blob);
          } else {
            user = UserImpl._fromJSON(auth2, blob);
          }
          if (persistence !== selectedPersistence) {
            userToMigrate = user;
          }
          selectedPersistence = persistence;
          break;
        }
      } catch (_a2) {
      }
    }
    const migrationHierarchy = availablePersistences.filter((p2) => p2._shouldAllowMigration);
    if (!selectedPersistence._shouldAllowMigration || !migrationHierarchy.length) {
      return new PersistenceUserManager(selectedPersistence, auth2, userKey);
    }
    selectedPersistence = migrationHierarchy[0];
    if (userToMigrate) {
      await selectedPersistence._set(key, userToMigrate.toJSON());
    }
    await Promise.all(persistenceHierarchy.map(async (persistence) => {
      if (persistence !== selectedPersistence) {
        try {
          await persistence._remove(key);
        } catch (_a2) {
        }
      }
    }));
    return new PersistenceUserManager(selectedPersistence, auth2, userKey);
  }
}
/**
 * @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.
 */
function _getBrowserName(userAgent) {
  const ua = userAgent.toLowerCase();
  if (ua.includes("opera/") || ua.includes("opr/") || ua.includes("opios/")) {
    return "Opera";
  } else if (_isIEMobile(ua)) {
    return "IEMobile";
  } else if (ua.includes("msie") || ua.includes("trident/")) {
    return "IE";
  } else if (ua.includes("edge/")) {
    return "Edge";
  } else if (_isFirefox(ua)) {
    return "Firefox";
  } else if (ua.includes("silk/")) {
    return "Silk";
  } else if (_isBlackBerry(ua)) {
    return "Blackberry";
  } else if (_isWebOS(ua)) {
    return "Webos";
  } else if (_isSafari(ua)) {
    return "Safari";
  } else if ((ua.includes("chrome/") || _isChromeIOS(ua)) && !ua.includes("edge/")) {
    return "Chrome";
  } else if (_isAndroid(ua)) {
    return "Android";
  } else {
    const re2 = /([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/;
    const matches2 = userAgent.match(re2);
    if ((matches2 === null || matches2 === void 0 ? void 0 : matches2.length) === 2) {
      return matches2[1];
    }
  }
  return "Other";
}
__name(_getBrowserName, "_getBrowserName");
function _isFirefox(ua = getUA()) {
  return /firefox\//i.test(ua);
}
__name(_isFirefox, "_isFirefox");
function _isSafari(userAgent = getUA()) {
  const ua = userAgent.toLowerCase();
  return ua.includes("safari/") && !ua.includes("chrome/") && !ua.includes("crios/") && !ua.includes("android");
}
__name(_isSafari, "_isSafari");
function _isChromeIOS(ua = getUA()) {
  return /crios\//i.test(ua);
}
__name(_isChromeIOS, "_isChromeIOS");
function _isIEMobile(ua = getUA()) {
  return /iemobile/i.test(ua);
}
__name(_isIEMobile, "_isIEMobile");
function _isAndroid(ua = getUA()) {
  return /android/i.test(ua);
}
__name(_isAndroid, "_isAndroid");
function _isBlackBerry(ua = getUA()) {
  return /blackberry/i.test(ua);
}
__name(_isBlackBerry, "_isBlackBerry");
function _isWebOS(ua = getUA()) {
  return /webos/i.test(ua);
}
__name(_isWebOS, "_isWebOS");
function _isIOS(ua = getUA()) {
  return /iphone|ipad|ipod/i.test(ua) || /macintosh/i.test(ua) && /mobile/i.test(ua);
}
__name(_isIOS, "_isIOS");
function _isIOS7Or8(ua = getUA()) {
  return /(iPad|iPhone|iPod).*OS 7_\d/i.test(ua) || /(iPad|iPhone|iPod).*OS 8_\d/i.test(ua);
}
__name(_isIOS7Or8, "_isIOS7Or8");
function _isIOSStandalone(ua = getUA()) {
  var _a2;
  return _isIOS(ua) && !!((_a2 = window.navigator) === null || _a2 === void 0 ? void 0 : _a2.standalone);
}
__name(_isIOSStandalone, "_isIOSStandalone");
function _isIE10() {
  return isIE() && document.documentMode === 10;
}
__name(_isIE10, "_isIE10");
function _isMobileBrowser(ua = getUA()) {
  return _isIOS(ua) || _isAndroid(ua) || _isWebOS(ua) || _isBlackBerry(ua) || /windows phone/i.test(ua) || _isIEMobile(ua);
}
__name(_isMobileBrowser, "_isMobileBrowser");
/**
 * @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.
 */
function _getClientVersion(clientPlatform, frameworks = []) {
  let reportedPlatform;
  switch (clientPlatform) {
    case "Browser":
      reportedPlatform = _getBrowserName(getUA());
      break;
    case "Worker":
      reportedPlatform = `${_getBrowserName(getUA())}-${clientPlatform}`;
      break;
    default:
      reportedPlatform = clientPlatform;
  }
  const reportedFrameworks = frameworks.length ? frameworks.join(",") : "FirebaseCore-web";
  return `${reportedPlatform}/${"JsCore"}/${SDK_VERSION$1}/${reportedFrameworks}`;
}
__name(_getClientVersion, "_getClientVersion");
/**
 * @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.
 */
class AuthMiddlewareQueue {
  static {
    __name(this, "AuthMiddlewareQueue");
  }
  constructor(auth2) {
    this.auth = auth2;
    this.queue = [];
  }
  pushCallback(callback, onAbort) {
    const wrappedCallback = /* @__PURE__ */ __name((user) => new Promise((resolve2, reject) => {
      try {
        const result = callback(user);
        resolve2(result);
      } catch (e2) {
        reject(e2);
      }
    }), "wrappedCallback");
    wrappedCallback.onAbort = onAbort;
    this.queue.push(wrappedCallback);
    const index2 = this.queue.length - 1;
    return () => {
      this.queue[index2] = () => Promise.resolve();
    };
  }
  async runMiddleware(nextUser) {
    if (this.auth.currentUser === nextUser) {
      return;
    }
    const onAbortStack = [];
    try {
      for (const beforeStateCallback of this.queue) {
        await beforeStateCallback(nextUser);
        if (beforeStateCallback.onAbort) {
          onAbortStack.push(beforeStateCallback.onAbort);
        }
      }
    } catch (e2) {
      onAbortStack.reverse();
      for (const onAbort of onAbortStack) {
        try {
          onAbort();
        } catch (_2) {
        }
      }
      throw this.auth._errorFactory.create("login-blocked", {
        originalMessage: e2 === null || e2 === void 0 ? void 0 : e2.message
      });
    }
  }
}
/**
 * @license
 * Copyright 2023 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.
 */
async function _getPasswordPolicy(auth2, request = {}) {
  return _performApiRequest(auth2, "GET", "/v2/passwordPolicy", _addTidIfNecessary(auth2, request));
}
__name(_getPasswordPolicy, "_getPasswordPolicy");
/**
 * @license
 * Copyright 2023 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 MINIMUM_MIN_PASSWORD_LENGTH = 6;
class PasswordPolicyImpl {
  static {
    __name(this, "PasswordPolicyImpl");
  }
  constructor(response) {
    var _a2, _b, _c, _d;
    const responseOptions = response.customStrengthOptions;
    this.customStrengthOptions = {};
    this.customStrengthOptions.minPasswordLength = (_a2 = responseOptions.minPasswordLength) !== null && _a2 !== void 0 ? _a2 : MINIMUM_MIN_PASSWORD_LENGTH;
    if (responseOptions.maxPasswordLength) {
      this.customStrengthOptions.maxPasswordLength = responseOptions.maxPasswordLength;
    }
    if (responseOptions.containsLowercaseCharacter !== void 0) {
      this.customStrengthOptions.containsLowercaseLetter = responseOptions.containsLowercaseCharacter;
    }
    if (responseOptions.containsUppercaseCharacter !== void 0) {
      this.customStrengthOptions.containsUppercaseLetter = responseOptions.containsUppercaseCharacter;
    }
    if (responseOptions.containsNumericCharacter !== void 0) {
      this.customStrengthOptions.containsNumericCharacter = responseOptions.containsNumericCharacter;
    }
    if (responseOptions.containsNonAlphanumericCharacter !== void 0) {
      this.customStrengthOptions.containsNonAlphanumericCharacter = responseOptions.containsNonAlphanumericCharacter;
    }
    this.enforcementState = response.enforcementState;
    if (this.enforcementState === "ENFORCEMENT_STATE_UNSPECIFIED") {
      this.enforcementState = "OFF";
    }
    this.allowedNonAlphanumericCharacters = (_c = (_b = response.allowedNonAlphanumericCharacters) === null || _b === void 0 ? void 0 : _b.join("")) !== null && _c !== void 0 ? _c : "";
    this.forceUpgradeOnSignin = (_d = response.forceUpgradeOnSignin) !== null && _d !== void 0 ? _d : false;
    this.schemaVersion = response.schemaVersion;
  }
  validatePassword(password) {
    var _a2, _b, _c, _d, _e2, _f;
    const status = {
      isValid: true,
      passwordPolicy: this
    };
    this.validatePasswordLengthOptions(password, status);
    this.validatePasswordCharacterOptions(password, status);
    status.isValid && (status.isValid = (_a2 = status.meetsMinPasswordLength) !== null && _a2 !== void 0 ? _a2 : true);
    status.isValid && (status.isValid = (_b = status.meetsMaxPasswordLength) !== null && _b !== void 0 ? _b : true);
    status.isValid && (status.isValid = (_c = status.containsLowercaseLetter) !== null && _c !== void 0 ? _c : true);
    status.isValid && (status.isValid = (_d = status.containsUppercaseLetter) !== null && _d !== void 0 ? _d : true);
    status.isValid && (status.isValid = (_e2 = status.containsNumericCharacter) !== null && _e2 !== void 0 ? _e2 : true);
    status.isValid && (status.isValid = (_f = status.containsNonAlphanumericCharacter) !== null && _f !== void 0 ? _f : true);
    return status;
  }
  /**
   * Validates that the password meets the length options for the policy.
   *
   * @param password Password to validate.
   * @param status Validation status.
   */
  validatePasswordLengthOptions(password, status) {
    const minPasswordLength = this.customStrengthOptions.minPasswordLength;
    const maxPasswordLength = this.customStrengthOptions.maxPasswordLength;
    if (minPasswordLength) {
      status.meetsMinPasswordLength = password.length >= minPasswordLength;
    }
    if (maxPasswordLength) {
      status.meetsMaxPasswordLength = password.length <= maxPasswordLength;
    }
  }
  /**
   * Validates that the password meets the character options for the policy.
   *
   * @param password Password to validate.
   * @param status Validation status.
   */
  validatePasswordCharacterOptions(password, status) {
    this.updatePasswordCharacterOptionsStatuses(
      status,
      /* containsLowercaseCharacter= */
      false,
      /* containsUppercaseCharacter= */
      false,
      /* containsNumericCharacter= */
      false,
      /* containsNonAlphanumericCharacter= */
      false
    );
    let passwordChar;
    for (let i2 = 0; i2 < password.length; i2++) {
      passwordChar = password.charAt(i2);
      this.updatePasswordCharacterOptionsStatuses(
        status,
        /* containsLowercaseCharacter= */
        passwordChar >= "a" && passwordChar <= "z",
        /* containsUppercaseCharacter= */
        passwordChar >= "A" && passwordChar <= "Z",
        /* containsNumericCharacter= */
        passwordChar >= "0" && passwordChar <= "9",
        /* containsNonAlphanumericCharacter= */
        this.allowedNonAlphanumericCharacters.includes(passwordChar)
      );
    }
  }
  /**
   * Updates the running validation status with the statuses for the character options.
   * Expected to be called each time a character is processed to update each option status
   * based on the current character.
   *
   * @param status Validation status.
   * @param containsLowercaseCharacter Whether the character is a lowercase letter.
   * @param containsUppercaseCharacter Whether the character is an uppercase letter.
   * @param containsNumericCharacter Whether the character is a numeric character.
   * @param containsNonAlphanumericCharacter Whether the character is a non-alphanumeric character.
   */
  updatePasswordCharacterOptionsStatuses(status, containsLowercaseCharacter, containsUppercaseCharacter, containsNumericCharacter, containsNonAlphanumericCharacter) {
    if (this.customStrengthOptions.containsLowercaseLetter) {
      status.containsLowercaseLetter || (status.containsLowercaseLetter = containsLowercaseCharacter);
    }
    if (this.customStrengthOptions.containsUppercaseLetter) {
      status.containsUppercaseLetter || (status.containsUppercaseLetter = containsUppercaseCharacter);
    }
    if (this.customStrengthOptions.containsNumericCharacter) {
      status.containsNumericCharacter || (status.containsNumericCharacter = containsNumericCharacter);
    }
    if (this.customStrengthOptions.containsNonAlphanumericCharacter) {
      status.containsNonAlphanumericCharacter || (status.containsNonAlphanumericCharacter = containsNonAlphanumericCharacter);
    }
  }
}
/**
 * @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 AuthImpl {
  static {
    __name(this, "AuthImpl");
  }
  constructor(app2, heartbeatServiceProvider, appCheckServiceProvider, config2) {
    this.app = app2;
    this.heartbeatServiceProvider = heartbeatServiceProvider;
    this.appCheckServiceProvider = appCheckServiceProvider;
    this.config = config2;
    this.currentUser = null;
    this.emulatorConfig = null;
    this.operations = Promise.resolve();
    this.authStateSubscription = new Subscription(this);
    this.idTokenSubscription = new Subscription(this);
    this.beforeStateQueue = new AuthMiddlewareQueue(this);
    this.redirectUser = null;
    this.isProactiveRefreshEnabled = false;
    this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION = 1;
    this._canInitEmulator = true;
    this._isInitialized = false;
    this._deleted = false;
    this._initializationPromise = null;
    this._popupRedirectResolver = null;
    this._errorFactory = _DEFAULT_AUTH_ERROR_FACTORY;
    this._agentRecaptchaConfig = null;
    this._tenantRecaptchaConfigs = {};
    this._projectPasswordPolicy = null;
    this._tenantPasswordPolicies = {};
    this._resolvePersistenceManagerAvailable = void 0;
    this.lastNotifiedUid = void 0;
    this.languageCode = null;
    this.tenantId = null;
    this.settings = { appVerificationDisabledForTesting: false };
    this.frameworks = [];
    this.name = app2.name;
    this.clientVersion = config2.sdkClientVersion;
    this._persistenceManagerAvailable = new Promise((resolve2) => this._resolvePersistenceManagerAvailable = resolve2);
  }
  _initializeWithPersistence(persistenceHierarchy, popupRedirectResolver) {
    if (popupRedirectResolver) {
      this._popupRedirectResolver = _getInstance(popupRedirectResolver);
    }
    this._initializationPromise = this.queue(async () => {
      var _a2, _b, _c;
      if (this._deleted) {
        return;
      }
      this.persistenceManager = await PersistenceUserManager.create(this, persistenceHierarchy);
      (_a2 = this._resolvePersistenceManagerAvailable) === null || _a2 === void 0 ? void 0 : _a2.call(this);
      if (this._deleted) {
        return;
      }
      if ((_b = this._popupRedirectResolver) === null || _b === void 0 ? void 0 : _b._shouldInitProactively) {
        try {
          await this._popupRedirectResolver._initialize(this);
        } catch (e2) {
        }
      }
      await this.initializeCurrentUser(popupRedirectResolver);
      this.lastNotifiedUid = ((_c = this.currentUser) === null || _c === void 0 ? void 0 : _c.uid) || null;
      if (this._deleted) {
        return;
      }
      this._isInitialized = true;
    });
    return this._initializationPromise;
  }
  /**
   * If the persistence is changed in another window, the user manager will let us know
   */
  async _onStorageEvent() {
    if (this._deleted) {
      return;
    }
    const user = await this.assertedPersistence.getCurrentUser();
    if (!this.currentUser && !user) {
      return;
    }
    if (this.currentUser && user && this.currentUser.uid === user.uid) {
      this._currentUser._assign(user);
      await this.currentUser.getIdToken();
      return;
    }
    await this._updateCurrentUser(
      user,
      /* skipBeforeStateCallbacks */
      true
    );
  }
  async initializeCurrentUserFromIdToken(idToken) {
    try {
      const response = await getAccountInfo(this, { idToken });
      const user = await UserImpl._fromGetAccountInfoResponse(this, response, idToken);
      await this.directlySetCurrentUser(user);
    } catch (err) {
      console.warn("FirebaseServerApp could not login user with provided authIdToken: ", err);
      await this.directlySetCurrentUser(null);
    }
  }
  async initializeCurrentUser(popupRedirectResolver) {
    var _a2;
    if (_isFirebaseServerApp(this.app)) {
      const idToken = this.app.settings.authIdToken;
      if (idToken) {
        return new Promise((resolve2) => {
          setTimeout(() => this.initializeCurrentUserFromIdToken(idToken).then(resolve2, resolve2));
        });
      } else {
        return this.directlySetCurrentUser(null);
      }
    }
    const previouslyStoredUser = await this.assertedPersistence.getCurrentUser();
    let futureCurrentUser = previouslyStoredUser;
    let needsTocheckMiddleware = false;
    if (popupRedirectResolver && this.config.authDomain) {
      await this.getOrInitRedirectPersistenceManager();
      const redirectUserEventId = (_a2 = this.redirectUser) === null || _a2 === void 0 ? void 0 : _a2._redirectEventId;
      const storedUserEventId = futureCurrentUser === null || futureCurrentUser === void 0 ? void 0 : futureCurrentUser._redirectEventId;
      const result = await this.tryRedirectSignIn(popupRedirectResolver);
      if ((!redirectUserEventId || redirectUserEventId === storedUserEventId) && (result === null || result === void 0 ? void 0 : result.user)) {
        futureCurrentUser = result.user;
        needsTocheckMiddleware = true;
      }
    }
    if (!futureCurrentUser) {
      return this.directlySetCurrentUser(null);
    }
    if (!futureCurrentUser._redirectEventId) {
      if (needsTocheckMiddleware) {
        try {
          await this.beforeStateQueue.runMiddleware(futureCurrentUser);
        } catch (e2) {
          futureCurrentUser = previouslyStoredUser;
          this._popupRedirectResolver._overrideRedirectResult(this, () => Promise.reject(e2));
        }
      }
      if (futureCurrentUser) {
        return this.reloadAndSetCurrentUserOrClear(futureCurrentUser);
      } else {
        return this.directlySetCurrentUser(null);
      }
    }
    _assert(
      this._popupRedirectResolver,
      this,
      "argument-error"
      /* AuthErrorCode.ARGUMENT_ERROR */
    );
    await this.getOrInitRedirectPersistenceManager();
    if (this.redirectUser && this.redirectUser._redirectEventId === futureCurrentUser._redirectEventId) {
      return this.directlySetCurrentUser(futureCurrentUser);
    }
    return this.reloadAndSetCurrentUserOrClear(futureCurrentUser);
  }
  async tryRedirectSignIn(redirectResolver) {
    let result = null;
    try {
      result = await this._popupRedirectResolver._completeRedirectFn(this, redirectResolver, true);
    } catch (e2) {
      await this._setRedirectUser(null);
    }
    return result;
  }
  async reloadAndSetCurrentUserOrClear(user) {
    try {
      await _reloadWithoutSaving(user);
    } catch (e2) {
      if ((e2 === null || e2 === void 0 ? void 0 : e2.code) !== `auth/${"network-request-failed"}`) {
        return this.directlySetCurrentUser(null);
      }
    }
    return this.directlySetCurrentUser(user);
  }
  useDeviceLanguage() {
    this.languageCode = _getUserLanguage();
  }
  async _delete() {
    this._deleted = true;
  }
  async updateCurrentUser(userExtern) {
    if (_isFirebaseServerApp(this.app)) {
      return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this));
    }
    const user = userExtern ? getModularInstance(userExtern) : null;
    if (user) {
      _assert(
        user.auth.config.apiKey === this.config.apiKey,
        this,
        "invalid-user-token"
        /* AuthErrorCode.INVALID_AUTH */
      );
    }
    return this._updateCurrentUser(user && user._clone(this));
  }
  async _updateCurrentUser(user, skipBeforeStateCallbacks = false) {
    if (this._deleted) {
      return;
    }
    if (user) {
      _assert(
        this.tenantId === user.tenantId,
        this,
        "tenant-id-mismatch"
        /* AuthErrorCode.TENANT_ID_MISMATCH */
      );
    }
    if (!skipBeforeStateCallbacks) {
      await this.beforeStateQueue.runMiddleware(user);
    }
    return this.queue(async () => {
      await this.directlySetCurrentUser(user);
      this.notifyAuthListeners();
    });
  }
  async signOut() {
    if (_isFirebaseServerApp(this.app)) {
      return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this));
    }
    await this.beforeStateQueue.runMiddleware(null);
    if (this.redirectPersistenceManager || this._popupRedirectResolver) {
      await this._setRedirectUser(null);
    }
    return this._updateCurrentUser(
      null,
      /* skipBeforeStateCallbacks */
      true
    );
  }
  setPersistence(persistence) {
    if (_isFirebaseServerApp(this.app)) {
      return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this));
    }
    return this.queue(async () => {
      await this.assertedPersistence.setPersistence(_getInstance(persistence));
    });
  }
  _getRecaptchaConfig() {
    if (this.tenantId == null) {
      return this._agentRecaptchaConfig;
    } else {
      return this._tenantRecaptchaConfigs[this.tenantId];
    }
  }
  async validatePassword(password) {
    if (!this._getPasswordPolicyInternal()) {
      await this._updatePasswordPolicy();
    }
    const passwordPolicy = this._getPasswordPolicyInternal();
    if (passwordPolicy.schemaVersion !== this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION) {
      return Promise.reject(this._errorFactory.create("unsupported-password-policy-schema-version", {}));
    }
    return passwordPolicy.validatePassword(password);
  }
  _getPasswordPolicyInternal() {
    if (this.tenantId === null) {
      return this._projectPasswordPolicy;
    } else {
      return this._tenantPasswordPolicies[this.tenantId];
    }
  }
  async _updatePasswordPolicy() {
    const response = await _getPasswordPolicy(this);
    const passwordPolicy = new PasswordPolicyImpl(response);
    if (this.tenantId === null) {
      this._projectPasswordPolicy = passwordPolicy;
    } else {
      this._tenantPasswordPolicies[this.tenantId] = passwordPolicy;
    }
  }
  _getPersistenceType() {
    return this.assertedPersistence.persistence.type;
  }
  _getPersistence() {
    return this.assertedPersistence.persistence;
  }
  _updateErrorMap(errorMap2) {
    this._errorFactory = new ErrorFactory("auth", "Firebase", errorMap2());
  }
  onAuthStateChanged(nextOrObserver, error2, completed) {
    return this.registerStateListener(this.authStateSubscription, nextOrObserver, error2, completed);
  }
  beforeAuthStateChanged(callback, onAbort) {
    return this.beforeStateQueue.pushCallback(callback, onAbort);
  }
  onIdTokenChanged(nextOrObserver, error2, completed) {
    return this.registerStateListener(this.idTokenSubscription, nextOrObserver, error2, completed);
  }
  authStateReady() {
    return new Promise((resolve2, reject) => {
      if (this.currentUser) {
        resolve2();
      } else {
        const unsubscribe = this.onAuthStateChanged(() => {
          unsubscribe();
          resolve2();
        }, reject);
      }
    });
  }
  /**
   * Revokes the given access token. Currently only supports Apple OAuth access tokens.
   */
  async revokeAccessToken(token) {
    if (this.currentUser) {
      const idToken = await this.currentUser.getIdToken();
      const request = {
        providerId: "apple.com",
        tokenType: "ACCESS_TOKEN",
        token,
        idToken
      };
      if (this.tenantId != null) {
        request.tenantId = this.tenantId;
      }
      await revokeToken(this, request);
    }
  }
  toJSON() {
    var _a2;
    return {
      apiKey: this.config.apiKey,
      authDomain: this.config.authDomain,
      appName: this.name,
      currentUser: (_a2 = this._currentUser) === null || _a2 === void 0 ? void 0 : _a2.toJSON()
    };
  }
  async _setRedirectUser(user, popupRedirectResolver) {
    const redirectManager = await this.getOrInitRedirectPersistenceManager(popupRedirectResolver);
    return user === null ? redirectManager.removeCurrentUser() : redirectManager.setCurrentUser(user);
  }
  async getOrInitRedirectPersistenceManager(popupRedirectResolver) {
    if (!this.redirectPersistenceManager) {
      const resolver = popupRedirectResolver && _getInstance(popupRedirectResolver) || this._popupRedirectResolver;
      _assert(
        resolver,
        this,
        "argument-error"
        /* AuthErrorCode.ARGUMENT_ERROR */
      );
      this.redirectPersistenceManager = await PersistenceUserManager.create(
        this,
        [_getInstance(resolver._redirectPersistence)],
        "redirectUser"
        /* KeyName.REDIRECT_USER */
      );
      this.redirectUser = await this.redirectPersistenceManager.getCurrentUser();
    }
    return this.redirectPersistenceManager;
  }
  async _redirectUserForId(id2) {
    var _a2, _b;
    if (this._isInitialized) {
      await this.queue(async () => {
      });
    }
    if (((_a2 = this._currentUser) === null || _a2 === void 0 ? void 0 : _a2._redirectEventId) === id2) {
      return this._currentUser;
    }
    if (((_b = this.redirectUser) === null || _b === void 0 ? void 0 : _b._redirectEventId) === id2) {
      return this.redirectUser;
    }
    return null;
  }
  async _persistUserIfCurrent(user) {
    if (user === this.currentUser) {
      return this.queue(async () => this.directlySetCurrentUser(user));
    }
  }
  /** Notifies listeners only if the user is current */
  _notifyListenersIfCurrent(user) {
    if (user === this.currentUser) {
      this.notifyAuthListeners();
    }
  }
  _key() {
    return `${this.config.authDomain}:${this.config.apiKey}:${this.name}`;
  }
  _startProactiveRefresh() {
    this.isProactiveRefreshEnabled = true;
    if (this.currentUser) {
      this._currentUser._startProactiveRefresh();
    }
  }
  _stopProactiveRefresh() {
    this.isProactiveRefreshEnabled = false;
    if (this.currentUser) {
      this._currentUser._stopProactiveRefresh();
    }
  }
  /** Returns the current user cast as the internal type */
  get _currentUser() {
    return this.currentUser;
  }
  notifyAuthListeners() {
    var _a2, _b;
    if (!this._isInitialized) {
      return;
    }
    this.idTokenSubscription.next(this.currentUser);
    const currentUid = (_b = (_a2 = this.currentUser) === null || _a2 === void 0 ? void 0 : _a2.uid) !== null && _b !== void 0 ? _b : null;
    if (this.lastNotifiedUid !== currentUid) {
      this.lastNotifiedUid = currentUid;
      this.authStateSubscription.next(this.currentUser);
    }
  }
  registerStateListener(subscription, nextOrObserver, error2, completed) {
    if (this._deleted) {
      return () => {
      };
    }
    const cb = typeof nextOrObserver === "function" ? nextOrObserver : nextOrObserver.next.bind(nextOrObserver);
    let isUnsubscribed = false;
    const promise = this._isInitialized ? Promise.resolve() : this._initializationPromise;
    _assert(
      promise,
      this,
      "internal-error"
      /* AuthErrorCode.INTERNAL_ERROR */
    );
    promise.then(() => {
      if (isUnsubscribed) {
        return;
      }
      cb(this.currentUser);
    });
    if (typeof nextOrObserver === "function") {
      const unsubscribe = subscription.addObserver(nextOrObserver, error2, completed);
      return () => {
        isUnsubscribed = true;
        unsubscribe();
      };
    } else {
      const unsubscribe = subscription.addObserver(nextOrObserver);
      return () => {
        isUnsubscribed = true;
        unsubscribe();
      };
    }
  }
  /**
   * Unprotected (from race conditions) method to set the current user. This
   * should only be called from within a queued callback. This is necessary
   * because the queue shouldn't rely on another queued callback.
   */
  async directlySetCurrentUser(user) {
    if (this.currentUser && this.currentUser !== user) {
      this._currentUser._stopProactiveRefresh();
    }
    if (user && this.isProactiveRefreshEnabled) {
      user._startProactiveRefresh();
    }
    this.currentUser = user;
    if (user) {
      await this.assertedPersistence.setCurrentUser(user);
    } else {
      await this.assertedPersistence.removeCurrentUser();
    }
  }
  queue(action) {
    this.operations = this.operations.then(action, action);
    return this.operations;
  }
  get assertedPersistence() {
    _assert(
      this.persistenceManager,
      this,
      "internal-error"
      /* AuthErrorCode.INTERNAL_ERROR */
    );
    return this.persistenceManager;
  }
  _logFramework(framework) {
    if (!framework || this.frameworks.includes(framework)) {
      return;
    }
    this.frameworks.push(framework);
    this.frameworks.sort();
    this.clientVersion = _getClientVersion(this.config.clientPlatform, this._getFrameworks());
  }
  _getFrameworks() {
    return this.frameworks;
  }
  async _getAdditionalHeaders() {
    var _a2;
    const headers = {
      [
        "X-Client-Version"
        /* HttpHeader.X_CLIENT_VERSION */
      ]: this.clientVersion
    };
    if (this.app.options.appId) {
      headers[
        "X-Firebase-gmpid"
        /* HttpHeader.X_FIREBASE_GMPID */
      ] = this.app.options.appId;
    }
    const heartbeatsHeader = await ((_a2 = this.heartbeatServiceProvider.getImmediate({
      optional: true
    })) === null || _a2 === void 0 ? void 0 : _a2.getHeartbeatsHeader());
    if (heartbeatsHeader) {
      headers[
        "X-Firebase-Client"
        /* HttpHeader.X_FIREBASE_CLIENT */
      ] = heartbeatsHeader;
    }
    const appCheckToken = await this._getAppCheckToken();
    if (appCheckToken) {
      headers[
        "X-Firebase-AppCheck"
        /* HttpHeader.X_FIREBASE_APP_CHECK */
      ] = appCheckToken;
    }
    return headers;
  }
  async _getAppCheckToken() {
    var _a2;
    if (_isFirebaseServerApp(this.app) && this.app.settings.appCheckToken) {
      return this.app.settings.appCheckToken;
    }
    const appCheckTokenResult = await ((_a2 = this.appCheckServiceProvider.getImmediate({ optional: true })) === null || _a2 === void 0 ? void 0 : _a2.getToken());
    if (appCheckTokenResult === null || appCheckTokenResult === void 0 ? void 0 : appCheckTokenResult.error) {
      _logWarn(`Error while retrieving App Check token: ${appCheckTokenResult.error}`);
    }
    return appCheckTokenResult === null || appCheckTokenResult === void 0 ? void 0 : appCheckTokenResult.token;
  }
}
function _castAuth(auth2) {
  return getModularInstance(auth2);
}
__name(_castAuth, "_castAuth");
class Subscription {
  static {
    __name(this, "Subscription");
  }
  constructor(auth2) {
    this.auth = auth2;
    this.observer = null;
    this.addObserver = createSubscribe((observer) => this.observer = observer);
  }
  get next() {
    _assert(
      this.observer,
      this.auth,
      "internal-error"
      /* AuthErrorCode.INTERNAL_ERROR */
    );
    return this.observer.next.bind(this.observer);
  }
}
/**
 * @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.
 */
let externalJSProvider = {
  async loadJS() {
    throw new Error("Unable to load external scripts");
  },
  recaptchaV2Script: "",
  recaptchaEnterpriseScript: "",
  gapiScript: ""
};
function _setExternalJSProvider(p2) {
  externalJSProvider = p2;
}
__name(_setExternalJSProvider, "_setExternalJSProvider");
function _loadJS(url) {
  return externalJSProvider.loadJS(url);
}
__name(_loadJS, "_loadJS");
function _recaptchaV2ScriptUrl() {
  return externalJSProvider.recaptchaV2Script;
}
__name(_recaptchaV2ScriptUrl, "_recaptchaV2ScriptUrl");
function _recaptchaEnterpriseScriptUrl() {
  return externalJSProvider.recaptchaEnterpriseScript;
}
__name(_recaptchaEnterpriseScriptUrl, "_recaptchaEnterpriseScriptUrl");
function _gapiScriptUrl() {
  return externalJSProvider.gapiScript;
}
__name(_gapiScriptUrl, "_gapiScriptUrl");
function _generateCallbackName(prefix) {
  return `__${prefix}${Math.floor(Math.random() * 1e6)}`;
}
__name(_generateCallbackName, "_generateCallbackName");
/**
 * @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 _SOLVE_TIME_MS = 500;
const _EXPIRATION_TIME_MS = 6e4;
const _WIDGET_ID_START = 1e12;
class MockReCaptcha {
  static {
    __name(this, "MockReCaptcha");
  }
  constructor(auth2) {
    this.auth = auth2;
    this.counter = _WIDGET_ID_START;
    this._widgets = /* @__PURE__ */ new Map();
  }
  render(container, parameters) {
    const id2 = this.counter;
    this._widgets.set(id2, new MockWidget(container, this.auth.name, parameters || {}));
    this.counter++;
    return id2;
  }
  reset(optWidgetId) {
    var _a2;
    const id2 = optWidgetId || _WIDGET_ID_START;
    void ((_a2 = this._widgets.get(id2)) === null || _a2 === void 0 ? void 0 : _a2.delete());
    this._widgets.delete(id2);
  }
  getResponse(optWidgetId) {
    var _a2;
    const id2 = optWidgetId || _WIDGET_ID_START;
    return ((_a2 = this._widgets.get(id2)) === null || _a2 === void 0 ? void 0 : _a2.getResponse()) || "";
  }
  async execute(optWidgetId) {
    var _a2;
    const id2 = optWidgetId || _WIDGET_ID_START;
    void ((_a2 = this._widgets.get(id2)) === null || _a2 === void 0 ? void 0 : _a2.execute());
    return "";
  }
}
class MockGreCAPTCHATopLevel {
  static {
    __name(this, "MockGreCAPTCHATopLevel");
  }
  constructor() {
    this.enterprise = new MockGreCAPTCHA();
  }
  ready(callback) {
    callback();
  }
  execute(_siteKey, _options) {
    return Promise.resolve("token");
  }
  render(_container, _parameters) {
    return "";
  }
}
class MockGreCAPTCHA {
  static {
    __name(this, "MockGreCAPTCHA");
  }
  ready(callback) {
    callback();
  }
  execute(_siteKey, _options) {
    return Promise.resolve("token");
  }
  render(_container, _parameters) {
    return "";
  }
}
class MockWidget {
  static {
    __name(this, "MockWidget");
  }
  constructor(containerOrId, appName, params) {
    this.params = params;
    this.timerId = null;
    this.deleted = false;
    this.responseToken = null;
    this.clickHandler = () => {
      this.execute();
    };
    const container = typeof containerOrId === "string" ? document.getElementById(containerOrId) : containerOrId;
    _assert(container, "argument-error", { appName });
    this.container = container;
    this.isVisible = this.params.size !== "invisible";
    if (this.isVisible) {
      this.execute();
    } else {
      this.container.addEventListener("click", this.clickHandler);
    }
  }
  getResponse() {
    this.checkIfDeleted();
    return this.responseToken;
  }
  delete() {
    this.checkIfDeleted();
    this.deleted = true;
    if (this.timerId) {
      clearTimeout(this.timerId);
      this.timerId = null;
    }
    this.container.removeEventListener("click", this.clickHandler);
  }
  execute() {
    this.checkIfDeleted();
    if (this.timerId) {
      return;
    }
    this.timerId = window.setTimeout(() => {
      this.responseToken = generateRandomAlphaNumericString(50);
      const { callback, "expired-callback": expiredCallback } = this.params;
      if (callback) {
        try {
          callback(this.responseToken);
        } catch (e2) {
        }
      }
      this.timerId = window.setTimeout(() => {
        this.timerId = null;
        this.responseToken = null;
        if (expiredCallback) {
          try {
            expiredCallback();
          } catch (e2) {
          }
        }
        if (this.isVisible) {
          this.execute();
        }
      }, _EXPIRATION_TIME_MS);
    }, _SOLVE_TIME_MS);
  }
  checkIfDeleted() {
    if (this.deleted) {
      throw new Error("reCAPTCHA mock was already deleted!");
    }
  }
}
function generateRandomAlphaNumericString(len) {
  const chars2 = [];
  const allowedChars = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  for (let i2 = 0; i2 < len; i2++) {
    chars2.push(allowedChars.charAt(Math.floor(Math.random() * allowedChars.length)));
  }
  return chars2.join("");
}
__name(generateRandomAlphaNumericString, "generateRandomAlphaNumericString");
const RECAPTCHA_ENTERPRISE_VERIFIER_TYPE = "recaptcha-enterprise";
const FAKE_TOKEN = "NO_RECAPTCHA";
class RecaptchaEnterpriseVerifier {
  static {
    __name(this, "RecaptchaEnterpriseVerifier");
  }
  /**
   *
   * @param authExtern - The corresponding Firebase {@link Auth} instance.
   *
   */
  constructor(authExtern) {
    this.type = RECAPTCHA_ENTERPRISE_VERIFIER_TYPE;
    this.auth = _castAuth(authExtern);
  }
  /**
   * Executes the verification process.
   *
   * @returns A Promise for a token that can be used to assert the validity of a request.
   */
  async verify(action = "verify", forceRefresh = false) {
    async function retrieveSiteKey(auth2) {
      if (!forceRefresh) {
        if (auth2.tenantId == null && auth2._agentRecaptchaConfig != null) {
          return auth2._agentRecaptchaConfig.siteKey;
        }
        if (auth2.tenantId != null && auth2._tenantRecaptchaConfigs[auth2.tenantId] !== void 0) {
          return auth2._tenantRecaptchaConfigs[auth2.tenantId].siteKey;
        }
      }
      return new Promise(async (resolve2, reject) => {
        getRecaptchaConfig(auth2, {
          clientType: "CLIENT_TYPE_WEB",
          version: "RECAPTCHA_ENTERPRISE"
          /* RecaptchaVersion.ENTERPRISE */
        }).then((response) => {
          if (response.recaptchaKey === void 0) {
            reject(new Error("recaptcha Enterprise site key undefined"));
          } else {
            const config2 = new RecaptchaConfig(response);
            if (auth2.tenantId == null) {
              auth2._agentRecaptchaConfig = config2;
            } else {
              auth2._tenantRecaptchaConfigs[auth2.tenantId] = config2;
            }
            return resolve2(config2.siteKey);
          }
        }).catch((error2) => {
          reject(error2);
        });
      });
    }
    __name(retrieveSiteKey, "retrieveSiteKey");
    function retrieveRecaptchaToken(siteKey, resolve2, reject) {
      const grecaptcha = window.grecaptcha;
      if (isEnterprise(grecaptcha)) {
        grecaptcha.enterprise.ready(() => {
          grecaptcha.enterprise.execute(siteKey, { action }).then((token) => {
            resolve2(token);
          }).catch(() => {
            resolve2(FAKE_TOKEN);
          });
        });
      } else {
        reject(Error("No reCAPTCHA enterprise script loaded."));
      }
    }
    __name(retrieveRecaptchaToken, "retrieveRecaptchaToken");
    if (this.auth.settings.appVerificationDisabledForTesting) {
      const mockRecaptcha = new MockGreCAPTCHATopLevel();
      return mockRecaptcha.execute("siteKey", { action: "verify" });
    }
    return new Promise((resolve2, reject) => {
      retrieveSiteKey(this.auth).then((siteKey) => {
        if (!forceRefresh && isEnterprise(window.grecaptcha)) {
          retrieveRecaptchaToken(siteKey, resolve2, reject);
        } else {
          if (typeof window === "undefined") {
            reject(new Error("RecaptchaVerifier is only supported in browser"));
            return;
          }
          let url = _recaptchaEnterpriseScriptUrl();
          if (url.length !== 0) {
            url += siteKey;
          }
          _loadJS(url).then(() => {
            retrieveRecaptchaToken(siteKey, resolve2, reject);
          }).catch((error2) => {
            reject(error2);
          });
        }
      }).catch((error2) => {
        reject(error2);
      });
    });
  }
}
async function injectRecaptchaFields(auth2, request, action, isCaptchaResp = false, isFakeToken = false) {
  const verifier = new RecaptchaEnterpriseVerifier(auth2);
  let captchaResponse;
  if (isFakeToken) {
    captchaResponse = FAKE_TOKEN;
  } else {
    try {
      captchaResponse = await verifier.verify(action);
    } catch (error2) {
      captchaResponse = await verifier.verify(action, true);
    }
  }
  const newRequest = Object.assign({}, request);
  if (action === "mfaSmsEnrollment" || action === "mfaSmsSignIn") {
    if ("phoneEnrollmentInfo" in newRequest) {
      const phoneNumber = newRequest.phoneEnrollmentInfo.phoneNumber;
      const recaptchaToken = newRequest.phoneEnrollmentInfo.recaptchaToken;
      Object.assign(newRequest, {
        "phoneEnrollmentInfo": {
          phoneNumber,
          recaptchaToken,
          captchaResponse,
          "clientType": "CLIENT_TYPE_WEB",
          "recaptchaVersion": "RECAPTCHA_ENTERPRISE"
          /* RecaptchaVersion.ENTERPRISE */
        }
      });
    } else if ("phoneSignInInfo" in newRequest) {
      const recaptchaToken = newRequest.phoneSignInInfo.recaptchaToken;
      Object.assign(newRequest, {
        "phoneSignInInfo": {
          recaptchaToken,
          captchaResponse,
          "clientType": "CLIENT_TYPE_WEB",
          "recaptchaVersion": "RECAPTCHA_ENTERPRISE"
          /* RecaptchaVersion.ENTERPRISE */
        }
      });
    }
    return newRequest;
  }
  if (!isCaptchaResp) {
    Object.assign(newRequest, { captchaResponse });
  } else {
    Object.assign(newRequest, { "captchaResp": captchaResponse });
  }
  Object.assign(newRequest, {
    "clientType": "CLIENT_TYPE_WEB"
    /* RecaptchaClientType.WEB */
  });
  Object.assign(newRequest, {
    "recaptchaVersion": "RECAPTCHA_ENTERPRISE"
    /* RecaptchaVersion.ENTERPRISE */
  });
  return newRequest;
}
__name(injectRecaptchaFields, "injectRecaptchaFields");
async function handleRecaptchaFlow(authInstance, request, actionName, actionMethod, recaptchaAuthProvider) {
  var _a2, _b;
  if (recaptchaAuthProvider === "EMAIL_PASSWORD_PROVIDER") {
    if ((_a2 = authInstance._getRecaptchaConfig()) === null || _a2 === void 0 ? void 0 : _a2.isProviderEnabled(
      "EMAIL_PASSWORD_PROVIDER"
      /* RecaptchaAuthProvider.EMAIL_PASSWORD_PROVIDER */
    )) {
      const requestWithRecaptcha = await injectRecaptchaFields(
        authInstance,
        request,
        actionName,
        actionName === "getOobCode"
        /* RecaptchaActionName.GET_OOB_CODE */
      );
      return actionMethod(authInstance, requestWithRecaptcha);
    } else {
      return actionMethod(authInstance, request).catch(async (error2) => {
        if (error2.code === `auth/${"missing-recaptcha-token"}`) {
          console.log(`${actionName} is protected by reCAPTCHA Enterprise for this project. Automatically triggering the reCAPTCHA flow and restarting the flow.`);
          const requestWithRecaptcha = await injectRecaptchaFields(
            authInstance,
            request,
            actionName,
            actionName === "getOobCode"
            /* RecaptchaActionName.GET_OOB_CODE */
          );
          return actionMethod(authInstance, requestWithRecaptcha);
        } else {
          return Promise.reject(error2);
        }
      });
    }
  } else if (recaptchaAuthProvider === "PHONE_PROVIDER") {
    if ((_b = authInstance._getRecaptchaConfig()) === null || _b === void 0 ? void 0 : _b.isProviderEnabled(
      "PHONE_PROVIDER"
      /* RecaptchaAuthProvider.PHONE_PROVIDER */
    )) {
      const requestWithRecaptcha = await injectRecaptchaFields(authInstance, request, actionName);
      return actionMethod(authInstance, requestWithRecaptcha).catch(async (error2) => {
        var _a3;
        if (((_a3 = authInstance._getRecaptchaConfig()) === null || _a3 === void 0 ? void 0 : _a3.getProviderEnforcementState(
          "PHONE_PROVIDER"
          /* RecaptchaAuthProvider.PHONE_PROVIDER */
        )) === "AUDIT") {
          if (error2.code === `auth/${"missing-recaptcha-token"}` || error2.code === `auth/${"invalid-app-credential"}`) {
            console.log(`Failed to verify with reCAPTCHA Enterprise. Automatically triggering the reCAPTCHA v2 flow to complete the ${actionName} flow.`);
            const requestWithRecaptchaFields = await injectRecaptchaFields(
              authInstance,
              request,
              actionName,
              false,
              // isCaptchaResp
              true
              // isFakeToken
            );
            return actionMethod(authInstance, requestWithRecaptchaFields);
          }
        }
        return Promise.reject(error2);
      });
    } else {
      const requestWithRecaptchaFields = await injectRecaptchaFields(
        authInstance,
        request,
        actionName,
        false,
        // isCaptchaResp
        true
        // isFakeToken
      );
      return actionMethod(authInstance, requestWithRecaptchaFields);
    }
  } else {
    return Promise.reject(recaptchaAuthProvider + " provider is not supported.");
  }
}
__name(handleRecaptchaFlow, "handleRecaptchaFlow");
async function _initializeRecaptchaConfig(auth2) {
  const authInternal = _castAuth(auth2);
  const response = await getRecaptchaConfig(authInternal, {
    clientType: "CLIENT_TYPE_WEB",
    version: "RECAPTCHA_ENTERPRISE"
    /* RecaptchaVersion.ENTERPRISE */
  });
  const config2 = new RecaptchaConfig(response);
  if (authInternal.tenantId == null) {
    authInternal._agentRecaptchaConfig = config2;
  } else {
    authInternal._tenantRecaptchaConfigs[authInternal.tenantId] = config2;
  }
  if (config2.isAnyProviderEnabled()) {
    const verifier = new RecaptchaEnterpriseVerifier(authInternal);
    void verifier.verify();
  }
}
__name(_initializeRecaptchaConfig, "_initializeRecaptchaConfig");
/**
 * @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.
 */
function initializeAuth(app2, deps) {
  const provider = _getProvider(app2, "auth");
  if (provider.isInitialized()) {
    const auth3 = provider.getImmediate();
    const initialOptions = provider.getOptions();
    if (deepEqual(initialOptions, deps !== null && deps !== void 0 ? deps : {})) {
      return auth3;
    } else {
      _fail(
        auth3,
        "already-initialized"
        /* AuthErrorCode.ALREADY_INITIALIZED */
      );
    }
  }
  const auth2 = provider.initialize({ options: deps });
  return auth2;
}
__name(initializeAuth, "initializeAuth");
function _initializeAuthInstance(auth2, deps) {
  const persistence = (deps === null || deps === void 0 ? void 0 : deps.persistence) || [];
  const hierarchy = (Array.isArray(persistence) ? persistence : [persistence]).map(_getInstance);
  if (deps === null || deps === void 0 ? void 0 : deps.errorMap) {
    auth2._updateErrorMap(deps.errorMap);
  }
  auth2._initializeWithPersistence(hierarchy, deps === null || deps === void 0 ? void 0 : deps.popupRedirectResolver);
}
__name(_initializeAuthInstance, "_initializeAuthInstance");
function connectAuthEmulator(auth2, url, options2) {
  const authInternal = _castAuth(auth2);
  _assert(
    /^https?:\/\//.test(url),
    authInternal,
    "invalid-emulator-scheme"
    /* AuthErrorCode.INVALID_EMULATOR_SCHEME */
  );
  const disableWarnings = !!(options2 === null || options2 === void 0 ? void 0 : options2.disableWarnings);
  const protocol = extractProtocol(url);
  const { host, port } = extractHostAndPort(url);
  const portStr = port === null ? "" : `:${port}`;
  const emulator = { url: `${protocol}//${host}${portStr}/` };
  const emulatorConfig = Object.freeze({
    host,
    port,
    protocol: protocol.replace(":", ""),
    options: Object.freeze({ disableWarnings })
  });
  if (!authInternal._canInitEmulator) {
    _assert(
      authInternal.config.emulator && authInternal.emulatorConfig,
      authInternal,
      "emulator-config-failed"
      /* AuthErrorCode.EMULATOR_CONFIG_FAILED */
    );
    _assert(
      deepEqual(emulator, authInternal.config.emulator) && deepEqual(emulatorConfig, authInternal.emulatorConfig),
      authInternal,
      "emulator-config-failed"
      /* AuthErrorCode.EMULATOR_CONFIG_FAILED */
    );
    return;
  }
  authInternal.config.emulator = emulator;
  authInternal.emulatorConfig = emulatorConfig;
  authInternal.settings.appVerificationDisabledForTesting = true;
  if (!disableWarnings) {
    emitEmulatorWarning();
  }
}
__name(connectAuthEmulator, "connectAuthEmulator");
function extractProtocol(url) {
  const protocolEnd = url.indexOf(":");
  return protocolEnd < 0 ? "" : url.substr(0, protocolEnd + 1);
}
__name(extractProtocol, "extractProtocol");
function extractHostAndPort(url) {
  const protocol = extractProtocol(url);
  const authority = /(\/\/)?([^?#/]+)/.exec(url.substr(protocol.length));
  if (!authority) {
    return { host: "", port: null };
  }
  const hostAndPort = authority[2].split("@").pop() || "";
  const bracketedIPv6 = /^(\[[^\]]+\])(:|$)/.exec(hostAndPort);
  if (bracketedIPv6) {
    const host = bracketedIPv6[1];
    return { host, port: parsePort(hostAndPort.substr(host.length + 1)) };
  } else {
    const [host, port] = hostAndPort.split(":");
    return { host, port: parsePort(port) };
  }
}
__name(extractHostAndPort, "extractHostAndPort");
function parsePort(portStr) {
  if (!portStr) {
    return null;
  }
  const port = Number(portStr);
  if (isNaN(port)) {
    return null;
  }
  return port;
}
__name(parsePort, "parsePort");
function emitEmulatorWarning() {
  function attachBanner() {
    const el = document.createElement("p");
    const sty = el.style;
    el.innerText = "Running in emulator mode. Do not use with production credentials.";
    sty.position = "fixed";
    sty.width = "100%";
    sty.backgroundColor = "#ffffff";
    sty.border = ".1em solid #000000";
    sty.color = "#b50000";
    sty.bottom = "0px";
    sty.left = "0px";
    sty.margin = "0px";
    sty.zIndex = "10000";
    sty.textAlign = "center";
    el.classList.add("firebase-emulator-warning");
    document.body.appendChild(el);
  }
  __name(attachBanner, "attachBanner");
  if (typeof console !== "undefined" && typeof console.info === "function") {
    console.info("WARNING: You are using the Auth Emulator, which is intended for local testing only.  Do not use with production credentials.");
  }
  if (typeof window !== "undefined" && typeof document !== "undefined") {
    if (document.readyState === "loading") {
      window.addEventListener("DOMContentLoaded", attachBanner);
    } else {
      attachBanner();
    }
  }
}
__name(emitEmulatorWarning, "emitEmulatorWarning");
/**
 * @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 AuthCredential {
  static {
    __name(this, "AuthCredential");
  }
  /** @internal */
  constructor(providerId, signInMethod) {
    this.providerId = providerId;
    this.signInMethod = signInMethod;
  }
  /**
   * Returns a JSON-serializable representation of this object.
   *
   * @returns a JSON-serializable representation of this object.
   */
  toJSON() {
    return debugFail("not implemented");
  }
  /** @internal */
  _getIdTokenResponse(_auth) {
    return debugFail("not implemented");
  }
  /** @internal */
  _linkToIdToken(_auth, _idToken) {
    return debugFail("not implemented");
  }
  /** @internal */
  _getReauthenticationResolver(_auth) {
    return debugFail("not implemented");
  }
}
/**
 * @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.
 */
async function resetPassword(auth2, request) {
  return _performApiRequest(auth2, "POST", "/v1/accounts:resetPassword", _addTidIfNecessary(auth2, request));
}
__name(resetPassword, "resetPassword");
async function updateEmailPassword(auth2, request) {
  return _performApiRequest(auth2, "POST", "/v1/accounts:update", request);
}
__name(updateEmailPassword, "updateEmailPassword");
async function linkEmailPassword(auth2, request) {
  return _performApiRequest(auth2, "POST", "/v1/accounts:signUp", request);
}
__name(linkEmailPassword, "linkEmailPassword");
async function applyActionCode$1(auth2, request) {
  return _performApiRequest(auth2, "POST", "/v1/accounts:update", _addTidIfNecessary(auth2, request));
}
__name(applyActionCode$1, "applyActionCode$1");
/**
 * @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.
 */
async function signInWithPassword(auth2, request) {
  return _performSignInRequest(auth2, "POST", "/v1/accounts:signInWithPassword", _addTidIfNecessary(auth2, request));
}
__name(signInWithPassword, "signInWithPassword");
async function sendOobCode(auth2, request) {
  return _performApiRequest(auth2, "POST", "/v1/accounts:sendOobCode", _addTidIfNecessary(auth2, request));
}
__name(sendOobCode, "sendOobCode");
async function sendEmailVerification$1(auth2, request) {
  return sendOobCode(auth2, request);
}
__name(sendEmailVerification$1, "sendEmailVerification$1");
async function sendPasswordResetEmail$1(auth2, request) {
  return sendOobCode(auth2, request);
}
__name(sendPasswordResetEmail$1, "sendPasswordResetEmail$1");
async function sendSignInLinkToEmail$1(auth2, request) {
  return sendOobCode(auth2, request);
}
__name(sendSignInLinkToEmail$1, "sendSignInLinkToEmail$1");
async function verifyAndChangeEmail(auth2, request) {
  return sendOobCode(auth2, request);
}
__name(verifyAndChangeEmail, "verifyAndChangeEmail");
/**
 * @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.
 */
async function signInWithEmailLink$1(auth2, request) {
  return _performSignInRequest(auth2, "POST", "/v1/accounts:signInWithEmailLink", _addTidIfNecessary(auth2, request));
}
__name(signInWithEmailLink$1, "signInWithEmailLink$1");
async function signInWithEmailLinkForLinking(auth2, request) {
  return _performSignInRequest(auth2, "POST", "/v1/accounts:signInWithEmailLink", _addTidIfNecessary(auth2, request));
}
__name(signInWithEmailLinkForLinking, "signInWithEmailLinkForLinking");
/**
 * @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 EmailAuthCredential extends AuthCredential {
  static {
    __name(this, "EmailAuthCredential");
  }
  /** @internal */
  constructor(_email, _password, signInMethod, _tenantId = null) {
    super("password", signInMethod);
    this._email = _email;
    this._password = _password;
    this._tenantId = _tenantId;
  }
  /** @internal */
  static _fromEmailAndPassword(email, password) {
    return new EmailAuthCredential(
      email,
      password,
      "password"
      /* SignInMethod.EMAIL_PASSWORD */
    );
  }
  /** @internal */
  static _fromEmailAndCode(email, oobCode, tenantId = null) {
    return new EmailAuthCredential(email, oobCode, "emailLink", tenantId);
  }
  /** {@inheritdoc AuthCredential.toJSON} */
  toJSON() {
    return {
      email: this._email,
      password: this._password,
      signInMethod: this.signInMethod,
      tenantId: this._tenantId
    };
  }
  /**
   * Static method to deserialize a JSON representation of an object into an {@link  AuthCredential}.
   *
   * @param json - Either `object` or the stringified representation of the object. When string is
   * provided, `JSON.parse` would be called first.
   *
   * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.
   */
  static fromJSON(json) {
    const obj = typeof json === "string" ? JSON.parse(json) : json;
    if ((obj === null || obj === void 0 ? void 0 : obj.email) && (obj === null || obj === void 0 ? void 0 : obj.password)) {
      if (obj.signInMethod === "password") {
        return this._fromEmailAndPassword(obj.email, obj.password);
      } else if (obj.signInMethod === "emailLink") {
        return this._fromEmailAndCode(obj.email, obj.password, obj.tenantId);
      }
    }
    return null;
  }
  /** @internal */
  async _getIdTokenResponse(auth2) {
    switch (this.signInMethod) {
      case "password":
        const request = {
          returnSecureToken: true,
          email: this._email,
          password: this._password,
          clientType: "CLIENT_TYPE_WEB"
          /* RecaptchaClientType.WEB */
        };
        return handleRecaptchaFlow(
          auth2,
          request,
          "signInWithPassword",
          signInWithPassword,
          "EMAIL_PASSWORD_PROVIDER"
          /* RecaptchaAuthProvider.EMAIL_PASSWORD_PROVIDER */
        );
      case "emailLink":
        return signInWithEmailLink$1(auth2, {
          email: this._email,
          oobCode: this._password
        });
      default:
        _fail(
          auth2,
          "internal-error"
          /* AuthErrorCode.INTERNAL_ERROR */
        );
    }
  }
  /** @internal */
  async _linkToIdToken(auth2, idToken) {
    switch (this.signInMethod) {
      case "password":
        const request = {
          idToken,
          returnSecureToken: true,
          email: this._email,
          password: this._password,
          clientType: "CLIENT_TYPE_WEB"
          /* RecaptchaClientType.WEB */
        };
        return handleRecaptchaFlow(
          auth2,
          request,
          "signUpPassword",
          linkEmailPassword,
          "EMAIL_PASSWORD_PROVIDER"
          /* RecaptchaAuthProvider.EMAIL_PASSWORD_PROVIDER */
        );
      case "emailLink":
        return signInWithEmailLinkForLinking(auth2, {
          idToken,
          email: this._email,
          oobCode: this._password
        });
      default:
        _fail(
          auth2,
          "internal-error"
          /* AuthErrorCode.INTERNAL_ERROR */
        );
    }
  }
  /** @internal */
  _getReauthenticationResolver(auth2) {
    return this._getIdTokenResponse(auth2);
  }
}
/**
 * @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.
 */
async function signInWithIdp(auth2, request) {
  return _performSignInRequest(auth2, "POST", "/v1/accounts:signInWithIdp", _addTidIfNecessary(auth2, request));
}
__name(signInWithIdp, "signInWithIdp");
/**
 * @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 IDP_REQUEST_URI$1 = "http://localhost";
class OAuthCredential extends AuthCredential {
  static {
    __name(this, "OAuthCredential");
  }
  constructor() {
    super(...arguments);
    this.pendingToken = null;
  }
  /** @internal */
  static _fromParams(params) {
    const cred = new OAuthCredential(params.providerId, params.signInMethod);
    if (params.idToken || params.accessToken) {
      if (params.idToken) {
        cred.idToken = params.idToken;
      }
      if (params.accessToken) {
        cred.accessToken = params.accessToken;
      }
      if (params.nonce && !params.pendingToken) {
        cred.nonce = params.nonce;
      }
      if (params.pendingToken) {
        cred.pendingToken = params.pendingToken;
      }
    } else if (params.oauthToken && params.oauthTokenSecret) {
      cred.accessToken = params.oauthToken;
      cred.secret = params.oauthTokenSecret;
    } else {
      _fail(
        "argument-error"
        /* AuthErrorCode.ARGUMENT_ERROR */
      );
    }
    return cred;
  }
  /** {@inheritdoc AuthCredential.toJSON}  */
  toJSON() {
    return {
      idToken: this.idToken,
      accessToken: this.accessToken,
      secret: this.secret,
      nonce: this.nonce,
      pendingToken: this.pendingToken,
      providerId: this.providerId,
      signInMethod: this.signInMethod
    };
  }
  /**
   * Static method to deserialize a JSON representation of an object into an
   * {@link  AuthCredential}.
   *
   * @param json - Input can be either Object or the stringified representation of the object.
   * When string is provided, JSON.parse would be called first.
   *
   * @returns If the JSON input does not represent an {@link  AuthCredential}, null is returned.
   */
  static fromJSON(json) {
    const obj = typeof json === "string" ? JSON.parse(json) : json;
    const { providerId, signInMethod } = obj, rest = __rest(obj, ["providerId", "signInMethod"]);
    if (!providerId || !signInMethod) {
      return null;
    }
    const cred = new OAuthCredential(providerId, signInMethod);
    cred.idToken = rest.idToken || void 0;
    cred.accessToken = rest.accessToken || void 0;
    cred.secret = rest.secret;
    cred.nonce = rest.nonce;
    cred.pendingToken = rest.pendingToken || null;
    return cred;
  }
  /** @internal */
  _getIdTokenResponse(auth2) {
    const request = this.buildRequest();
    return signInWithIdp(auth2, request);
  }
  /** @internal */
  _linkToIdToken(auth2, idToken) {
    const request = this.buildRequest();
    request.idToken = idToken;
    return signInWithIdp(auth2, request);
  }
  /** @internal */
  _getReauthenticationResolver(auth2) {
    const request = this.buildRequest();
    request.autoCreate = false;
    return signInWithIdp(auth2, request);
  }
  buildRequest() {
    const request = {
      requestUri: IDP_REQUEST_URI$1,
      returnSecureToken: true
    };
    if (this.pendingToken) {
      request.pendingToken = this.pendingToken;
    } else {
      const postBody = {};
      if (this.idToken) {
        postBody["id_token"] = this.idToken;
      }
      if (this.accessToken) {
        postBody["access_token"] = this.accessToken;
      }
      if (this.secret) {
        postBody["oauth_token_secret"] = this.secret;
      }
      postBody["providerId"] = this.providerId;
      if (this.nonce && !this.pendingToken) {
        postBody["nonce"] = this.nonce;
      }
      request.postBody = querystring(postBody);
    }
    return request;
  }
}
/**
 * @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.
 */
async function sendPhoneVerificationCode(auth2, request) {
  return _performApiRequest(auth2, "POST", "/v1/accounts:sendVerificationCode", _addTidIfNecessary(auth2, request));
}
__name(sendPhoneVerificationCode, "sendPhoneVerificationCode");
async function signInWithPhoneNumber$1(auth2, request) {
  return _performSignInRequest(auth2, "POST", "/v1/accounts:signInWithPhoneNumber", _addTidIfNecessary(auth2, request));
}
__name(signInWithPhoneNumber$1, "signInWithPhoneNumber$1");
async function linkWithPhoneNumber$1(auth2, request) {
  const response = await _performSignInRequest(auth2, "POST", "/v1/accounts:signInWithPhoneNumber", _addTidIfNecessary(auth2, request));
  if (response.temporaryProof) {
    throw _makeTaggedError(auth2, "account-exists-with-different-credential", response);
  }
  return response;
}
__name(linkWithPhoneNumber$1, "linkWithPhoneNumber$1");
const VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_ = {
  [
    "USER_NOT_FOUND"
    /* ServerError.USER_NOT_FOUND */
  ]: "user-not-found"
  /* AuthErrorCode.USER_DELETED */
};
async function verifyPhoneNumberForExisting(auth2, request) {
  const apiRequest = Object.assign(Object.assign({}, request), { operation: "REAUTH" });
  return _performSignInRequest(auth2, "POST", "/v1/accounts:signInWithPhoneNumber", _addTidIfNecessary(auth2, apiRequest), VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_);
}
__name(verifyPhoneNumberForExisting, "verifyPhoneNumberForExisting");
/**
 * @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 PhoneAuthCredential extends AuthCredential {
  static {
    __name(this, "PhoneAuthCredential");
  }
  constructor(params) {
    super(
      "phone",
      "phone"
      /* SignInMethod.PHONE */
    );
    this.params = params;
  }
  /** @internal */
  static _fromVerification(verificationId, verificationCode) {
    return new PhoneAuthCredential({ verificationId, verificationCode });
  }
  /** @internal */
  static _fromTokenResponse(phoneNumber, temporaryProof) {
    return new PhoneAuthCredential({ phoneNumber, temporaryProof });
  }
  /** @internal */
  _getIdTokenResponse(auth2) {
    return signInWithPhoneNumber$1(auth2, this._makeVerificationRequest());
  }
  /** @internal */
  _linkToIdToken(auth2, idToken) {
    return linkWithPhoneNumber$1(auth2, Object.assign({ idToken }, this._makeVerificationRequest()));
  }
  /** @internal */
  _getReauthenticationResolver(auth2) {
    return verifyPhoneNumberForExisting(auth2, this._makeVerificationRequest());
  }
  /** @internal */
  _makeVerificationRequest() {
    const { temporaryProof, phoneNumber, verificationId, verificationCode } = this.params;
    if (temporaryProof && phoneNumber) {
      return { temporaryProof, phoneNumber };
    }
    return {
      sessionInfo: verificationId,
      code: verificationCode
    };
  }
  /** {@inheritdoc AuthCredential.toJSON} */
  toJSON() {
    const obj = {
      providerId: this.providerId
    };
    if (this.params.phoneNumber) {
      obj.phoneNumber = this.params.phoneNumber;
    }
    if (this.params.temporaryProof) {
      obj.temporaryProof = this.params.temporaryProof;
    }
    if (this.params.verificationCode) {
      obj.verificationCode = this.params.verificationCode;
    }
    if (this.params.verificationId) {
      obj.verificationId = this.params.verificationId;
    }
    return obj;
  }
  /** Generates a phone credential based on a plain object or a JSON string. */
  static fromJSON(json) {
    if (typeof json === "string") {
      json = JSON.parse(json);
    }
    const { verificationId, verificationCode, phoneNumber, temporaryProof } = json;
    if (!verificationCode && !verificationId && !phoneNumber && !temporaryProof) {
      return null;
    }
    return new PhoneAuthCredential({
      verificationId,
      verificationCode,
      phoneNumber,
      temporaryProof
    });
  }
}
/**
 * @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.
 */
function parseMode(mode) {
  switch (mode) {
    case "recoverEmail":
      return "RECOVER_EMAIL";
    case "resetPassword":
      return "PASSWORD_RESET";
    case "signIn":
      return "EMAIL_SIGNIN";
    case "verifyEmail":
      return "VERIFY_EMAIL";
    case "verifyAndChangeEmail":
      return "VERIFY_AND_CHANGE_EMAIL";
    case "revertSecondFactorAddition":
      return "REVERT_SECOND_FACTOR_ADDITION";
    default:
      return null;
  }
}
__name(parseMode, "parseMode");
function parseDeepLink(url) {
  const link2 = querystringDecode(extractQuerystring(url))["link"];
  const doubleDeepLink = link2 ? querystringDecode(extractQuerystring(link2))["deep_link_id"] : null;
  const iOSDeepLink = querystringDecode(extractQuerystring(url))["deep_link_id"];
  const iOSDoubleDeepLink = iOSDeepLink ? querystringDecode(extractQuerystring(iOSDeepLink))["link"] : null;
  return iOSDoubleDeepLink || iOSDeepLink || doubleDeepLink || link2 || url;
}
__name(parseDeepLink, "parseDeepLink");
class ActionCodeURL {
  static {
    __name(this, "ActionCodeURL");
  }
  /**
   * @param actionLink - The link from which to extract the URL.
   * @returns The {@link ActionCodeURL} object, or null if the link is invalid.
   *
   * @internal
   */
  constructor(actionLink) {
    var _a2, _b, _c, _d, _e2, _f;
    const searchParams = querystringDecode(extractQuerystring(actionLink));
    const apiKey = (_a2 = searchParams[
      "apiKey"
      /* QueryField.API_KEY */
    ]) !== null && _a2 !== void 0 ? _a2 : null;
    const code2 = (_b = searchParams[
      "oobCode"
      /* QueryField.CODE */
    ]) !== null && _b !== void 0 ? _b : null;
    const operation = parseMode((_c = searchParams[
      "mode"
      /* QueryField.MODE */
    ]) !== null && _c !== void 0 ? _c : null);
    _assert(
      apiKey && code2 && operation,
      "argument-error"
      /* AuthErrorCode.ARGUMENT_ERROR */
    );
    this.apiKey = apiKey;
    this.operation = operation;
    this.code = code2;
    this.continueUrl = (_d = searchParams[
      "continueUrl"
      /* QueryField.CONTINUE_URL */
    ]) !== null && _d !== void 0 ? _d : null;
    this.languageCode = (_e2 = searchParams[
      "languageCode"
      /* QueryField.LANGUAGE_CODE */
    ]) !== null && _e2 !== void 0 ? _e2 : null;
    this.tenantId = (_f = searchParams[
      "tenantId"
      /* QueryField.TENANT_ID */
    ]) !== null && _f !== void 0 ? _f : null;
  }
  /**
   * Parses the email action link string and returns an {@link ActionCodeURL} if the link is valid,
   * otherwise returns null.
   *
   * @param link  - The email action link string.
   * @returns The {@link ActionCodeURL} object, or null if the link is invalid.
   *
   * @public
   */
  static parseLink(link2) {
    const actionLink = parseDeepLink(link2);
    try {
      return new ActionCodeURL(actionLink);
    } catch (_a2) {
      return null;
    }
  }
}
function parseActionCodeURL(link2) {
  return ActionCodeURL.parseLink(link2);
}
__name(parseActionCodeURL, "parseActionCodeURL");
/**
 * @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 EmailAuthProvider {
  static {
    __name(this, "EmailAuthProvider");
  }
  constructor() {
    this.providerId = EmailAuthProvider.PROVIDER_ID;
  }
  /**
   * Initialize an {@link AuthCredential} using an email and password.
   *
   * @example
   * ```javascript
   * const authCredential = EmailAuthProvider.credential(email, password);
   * const userCredential = await signInWithCredential(auth, authCredential);
   * ```
   *
   * @example
   * ```javascript
   * const userCredential = await signInWithEmailAndPassword(auth, email, password);
   * ```
   *
   * @param email - Email address.
   * @param password - User account password.
   * @returns The auth provider credential.
   */
  static credential(email, password) {
    return EmailAuthCredential._fromEmailAndPassword(email, password);
  }
  /**
   * Initialize an {@link AuthCredential} using an email and an email link after a sign in with
   * email link operation.
   *
   * @example
   * ```javascript
   * const authCredential = EmailAuthProvider.credentialWithLink(auth, email, emailLink);
   * const userCredential = await signInWithCredential(auth, authCredential);
   * ```
   *
   * @example
   * ```javascript
   * await sendSignInLinkToEmail(auth, email);
   * // Obtain emailLink from user.
   * const userCredential = await signInWithEmailLink(auth, email, emailLink);
   * ```
   *
   * @param auth - The {@link Auth} instance used to verify the link.
   * @param email - Email address.
   * @param emailLink - Sign-in email link.
   * @returns - The auth provider credential.
   */
  static credentialWithLink(email, emailLink) {
    const actionCodeUrl = ActionCodeURL.parseLink(emailLink);
    _assert(
      actionCodeUrl,
      "argument-error"
      /* AuthErrorCode.ARGUMENT_ERROR */
    );
    return EmailAuthCredential._fromEmailAndCode(email, actionCodeUrl.code, actionCodeUrl.tenantId);
  }
}
EmailAuthProvider.PROVIDER_ID = "password";
EmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD = "password";
EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD = "emailLink";
/**
 * @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 FederatedAuthProvider {
  static {
    __name(this, "FederatedAuthProvider");
  }
  /**
   * Constructor for generic OAuth providers.
   *
   * @param providerId - Provider for which credentials should be generated.
   */
  constructor(providerId) {
    this.providerId = providerId;
    this.defaultLanguageCode = null;
    this.customParameters = {};
  }
  /**
   * Set the language gode.
   *
   * @param languageCode - language code
   */
  setDefaultLanguage(languageCode) {
    this.defaultLanguageCode = languageCode;
  }
  /**
   * Sets the OAuth custom parameters to pass in an OAuth request for popup and redirect sign-in
   * operations.
   *
   * @remarks
   * For a detailed list, check the reserved required OAuth 2.0 parameters such as `client_id`,
   * `redirect_uri`, `scope`, `response_type`, and `state` are not allowed and will be ignored.
   *
   * @param customOAuthParameters - The custom OAuth parameters to pass in the OAuth request.
   */
  setCustomParameters(customOAuthParameters) {
    this.customParameters = customOAuthParameters;
    return this;
  }
  /**
   * Retrieve the current list of {@link CustomParameters}.
   */
  getCustomParameters() {
    return this.customParameters;
  }
}
/**
 * @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 BaseOAuthProvider extends FederatedAuthProvider {
  static {
    __name(this, "BaseOAuthProvider");
  }
  constructor() {
    super(...arguments);
    this.scopes = [];
  }
  /**
   * Add an OAuth scope to the credential.
   *
   * @param scope - Provider OAuth scope to add.
   */
  addScope(scope) {
    if (!this.scopes.includes(scope)) {
      this.scopes.push(scope);
    }
    return this;
  }
  /**
   * Retrieve the current list of OAuth scopes.
   */
  getScopes() {
    return [...this.scopes];
  }
}
class OAuthProvider extends BaseOAuthProvider {
  static {
    __name(this, "OAuthProvider");
  }
  /**
   * Creates an {@link OAuthCredential} from a JSON string or a plain object.
   * @param json - A plain object or a JSON string
   */
  static credentialFromJSON(json) {
    const obj = typeof json === "string" ? JSON.parse(json) : json;
    _assert(
      "providerId" in obj && "signInMethod" in obj,
      "argument-error"
      /* AuthErrorCode.ARGUMENT_ERROR */
    );
    return OAuthCredential._fromParams(obj);
  }
  /**
   * Creates a {@link OAuthCredential} from a generic OAuth provider's access token or ID token.
   *
   * @remarks
   * The raw nonce is required when an ID token with a nonce field is provided. The SHA-256 hash of
   * the raw nonce must match the nonce field in the ID token.
   *
   * @example
   * ```javascript
   * // `googleUser` from the onsuccess Google Sign In callback.
   * // Initialize a generate OAuth provider with a `google.com` providerId.
   * const provider = new OAuthProvider('google.com');
   * const credential = provider.credential({
   *   idToken: googleUser.getAuthResponse().id_token,
   * });
   * const result = await signInWithCredential(credential);
   * ```
   *
   * @param params - Either the options object containing the ID token, access token and raw nonce
   * or the ID token string.
   */
  credential(params) {
    return this._credential(Object.assign(Object.assign({}, params), { nonce: params.rawNonce }));
  }
  /** An internal credential method that accepts more permissive options */
  _credential(params) {
    _assert(
      params.idToken || params.accessToken,
      "argument-error"
      /* AuthErrorCode.ARGUMENT_ERROR */
    );
    return OAuthCredential._fromParams(Object.assign(Object.assign({}, params), { providerId: this.providerId, signInMethod: this.providerId }));
  }
  /**
   * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
   *
   * @param userCredential - The user credential.
   */
  static credentialFromResult(userCredential) {
    return OAuthProvider.oauthCredentialFromTaggedObject(userCredential);
  }
  /**
   * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
   * thrown during a sign-in, link, or reauthenticate operation.
   *
   * @param userCredential - The user credential.
   */
  static credentialFromError(error2) {
    return OAuthProvider.oauthCredentialFromTaggedObject(error2.customData || {});
  }
  static oauthCredentialFromTaggedObject({ _tokenResponse: tokenResponse }) {
    if (!tokenResponse) {
      return null;
    }
    const { oauthIdToken, oauthAccessToken, oauthTokenSecret, pendingToken, nonce, providerId } = tokenResponse;
    if (!oauthAccessToken && !oauthTokenSecret && !oauthIdToken && !pendingToken) {
      return null;
    }
    if (!providerId) {
      return null;
    }
    try {
      return new OAuthProvider(providerId)._credential({
        idToken: oauthIdToken,
        accessToken: oauthAccessToken,
        nonce,
        pendingToken
      });
    } catch (e2) {
      return null;
    }
  }
}
/**
 * @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 FacebookAuthProvider extends BaseOAuthProvider {
  static {
    __name(this, "FacebookAuthProvider");
  }
  constructor() {
    super(
      "facebook.com"
      /* ProviderId.FACEBOOK */
    );
  }
  /**
   * Creates a credential for Facebook.
   *
   * @example
   * ```javascript
   * // `event` from the Facebook auth.authResponseChange callback.
   * const credential = FacebookAuthProvider.credential(event.authResponse.accessToken);
   * const result = await signInWithCredential(credential);
   * ```
   *
   * @param accessToken - Facebook access token.
   */
  static credential(accessToken) {
    return OAuthCredential._fromParams({
      providerId: FacebookAuthProvider.PROVIDER_ID,
      signInMethod: FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD,
      accessToken
    });
  }
  /**
   * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
   *
   * @param userCredential - The user credential.
   */
  static credentialFromResult(userCredential) {
    return FacebookAuthProvider.credentialFromTaggedObject(userCredential);
  }
  /**
   * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
   * thrown during a sign-in, link, or reauthenticate operation.
   *
   * @param userCredential - The user credential.
   */
  static credentialFromError(error2) {
    return FacebookAuthProvider.credentialFromTaggedObject(error2.customData || {});
  }
  static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {
    if (!tokenResponse || !("oauthAccessToken" in tokenResponse)) {
      return null;
    }
    if (!tokenResponse.oauthAccessToken) {
      return null;
    }
    try {
      return FacebookAuthProvider.credential(tokenResponse.oauthAccessToken);
    } catch (_a2) {
      return null;
    }
  }
}
FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD = "facebook.com";
FacebookAuthProvider.PROVIDER_ID = "facebook.com";
/**
 * @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 GoogleAuthProvider extends BaseOAuthProvider {
  static {
    __name(this, "GoogleAuthProvider");
  }
  constructor() {
    super(
      "google.com"
      /* ProviderId.GOOGLE */
    );
    this.addScope("profile");
  }
  /**
   * Creates a credential for Google. At least one of ID token and access token is required.
   *
   * @example
   * ```javascript
   * // \`googleUser\` from the onsuccess Google Sign In callback.
   * const credential = GoogleAuthProvider.credential(googleUser.getAuthResponse().id_token);
   * const result = await signInWithCredential(credential);
   * ```
   *
   * @param idToken - Google ID token.
   * @param accessToken - Google access token.
   */
  static credential(idToken, accessToken) {
    return OAuthCredential._fromParams({
      providerId: GoogleAuthProvider.PROVIDER_ID,
      signInMethod: GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD,
      idToken,
      accessToken
    });
  }
  /**
   * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
   *
   * @param userCredential - The user credential.
   */
  static credentialFromResult(userCredential) {
    return GoogleAuthProvider.credentialFromTaggedObject(userCredential);
  }
  /**
   * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
   * thrown during a sign-in, link, or reauthenticate operation.
   *
   * @param userCredential - The user credential.
   */
  static credentialFromError(error2) {
    return GoogleAuthProvider.credentialFromTaggedObject(error2.customData || {});
  }
  static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {
    if (!tokenResponse) {
      return null;
    }
    const { oauthIdToken, oauthAccessToken } = tokenResponse;
    if (!oauthIdToken && !oauthAccessToken) {
      return null;
    }
    try {
      return GoogleAuthProvider.credential(oauthIdToken, oauthAccessToken);
    } catch (_a2) {
      return null;
    }
  }
}
GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD = "google.com";
GoogleAuthProvider.PROVIDER_ID = "google.com";
/**
 * @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 GithubAuthProvider extends BaseOAuthProvider {
  static {
    __name(this, "GithubAuthProvider");
  }
  constructor() {
    super(
      "github.com"
      /* ProviderId.GITHUB */
    );
  }
  /**
   * Creates a credential for GitHub.
   *
   * @param accessToken - GitHub access token.
   */
  static credential(accessToken) {
    return OAuthCredential._fromParams({
      providerId: GithubAuthProvider.PROVIDER_ID,
      signInMethod: GithubAuthProvider.GITHUB_SIGN_IN_METHOD,
      accessToken
    });
  }
  /**
   * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
   *
   * @param userCredential - The user credential.
   */
  static credentialFromResult(userCredential) {
    return GithubAuthProvider.credentialFromTaggedObject(userCredential);
  }
  /**
   * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
   * thrown during a sign-in, link, or reauthenticate operation.
   *
   * @param userCredential - The user credential.
   */
  static credentialFromError(error2) {
    return GithubAuthProvider.credentialFromTaggedObject(error2.customData || {});
  }
  static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {
    if (!tokenResponse || !("oauthAccessToken" in tokenResponse)) {
      return null;
    }
    if (!tokenResponse.oauthAccessToken) {
      return null;
    }
    try {
      return GithubAuthProvider.credential(tokenResponse.oauthAccessToken);
    } catch (_a2) {
      return null;
    }
  }
}
GithubAuthProvider.GITHUB_SIGN_IN_METHOD = "github.com";
GithubAuthProvider.PROVIDER_ID = "github.com";
/**
 * @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 IDP_REQUEST_URI = "http://localhost";
class SAMLAuthCredential extends AuthCredential {
  static {
    __name(this, "SAMLAuthCredential");
  }
  /** @internal */
  constructor(providerId, pendingToken) {
    super(providerId, providerId);
    this.pendingToken = pendingToken;
  }
  /** @internal */
  _getIdTokenResponse(auth2) {
    const request = this.buildRequest();
    return signInWithIdp(auth2, request);
  }
  /** @internal */
  _linkToIdToken(auth2, idToken) {
    const request = this.buildRequest();
    request.idToken = idToken;
    return signInWithIdp(auth2, request);
  }
  /** @internal */
  _getReauthenticationResolver(auth2) {
    const request = this.buildRequest();
    request.autoCreate = false;
    return signInWithIdp(auth2, request);
  }
  /** {@inheritdoc AuthCredential.toJSON}  */
  toJSON() {
    return {
      signInMethod: this.signInMethod,
      providerId: this.providerId,
      pendingToken: this.pendingToken
    };
  }
  /**
   * Static method to deserialize a JSON representation of an object into an
   * {@link  AuthCredential}.
   *
   * @param json - Input can be either Object or the stringified representation of the object.
   * When string is provided, JSON.parse would be called first.
   *
   * @returns If the JSON input does not represent an {@link  AuthCredential}, null is returned.
   */
  static fromJSON(json) {
    const obj = typeof json === "string" ? JSON.parse(json) : json;
    const { providerId, signInMethod, pendingToken } = obj;
    if (!providerId || !signInMethod || !pendingToken || providerId !== signInMethod) {
      return null;
    }
    return new SAMLAuthCredential(providerId, pendingToken);
  }
  /**
   * Helper static method to avoid exposing the constructor to end users.
   *
   * @internal
   */
  static _create(providerId, pendingToken) {
    return new SAMLAuthCredential(providerId, pendingToken);
  }
  buildRequest() {
    return {
      requestUri: IDP_REQUEST_URI,
      returnSecureToken: true,
      pendingToken: this.pendingToken
    };
  }
}
/**
 * @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 SAML_PROVIDER_PREFIX = "saml.";
class SAMLAuthProvider extends FederatedAuthProvider {
  static {
    __name(this, "SAMLAuthProvider");
  }
  /**
   * Constructor. The providerId must start with "saml."
   * @param providerId - SAML provider ID.
   */
  constructor(providerId) {
    _assert(
      providerId.startsWith(SAML_PROVIDER_PREFIX),
      "argument-error"
      /* AuthErrorCode.ARGUMENT_ERROR */
    );
    super(providerId);
  }
  /**
   * Generates an {@link AuthCredential} from a {@link UserCredential} after a
   * successful SAML flow completes.
   *
   * @remarks
   *
   * For example, to get an {@link AuthCredential}, you could write the
   * following code:
   *
   * ```js
   * const userCredential = await signInWithPopup(auth, samlProvider);
   * const credential = SAMLAuthProvider.credentialFromResult(userCredential);
   * ```
   *
   * @param userCredential - The user credential.
   */
  static credentialFromResult(userCredential) {
    return SAMLAuthProvider.samlCredentialFromTaggedObject(userCredential);
  }
  /**
   * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
   * thrown during a sign-in, link, or reauthenticate operation.
   *
   * @param userCredential - The user credential.
   */
  static credentialFromError(error2) {
    return SAMLAuthProvider.samlCredentialFromTaggedObject(error2.customData || {});
  }
  /**
   * Creates an {@link AuthCredential} from a JSON string or a plain object.
   * @param json - A plain object or a JSON string
   */
  static credentialFromJSON(json) {
    const credential = SAMLAuthCredential.fromJSON(json);
    _assert(
      credential,
      "argument-error"
      /* AuthErrorCode.ARGUMENT_ERROR */
    );
    return credential;
  }
  static samlCredentialFromTaggedObject({ _tokenResponse: tokenResponse }) {
    if (!tokenResponse) {
      return null;
    }
    const { pendingToken, providerId } = tokenResponse;
    if (!pendingToken || !providerId) {
      return null;
    }
    try {
      return SAMLAuthCredential._create(providerId, pendingToken);
    } catch (e2) {
      return null;
    }
  }
}
/**
 * @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 TwitterAuthProvider extends BaseOAuthProvider {
  static {
    __name(this, "TwitterAuthProvider");
  }
  constructor() {
    super(
      "twitter.com"
      /* ProviderId.TWITTER */
    );
  }
  /**
   * Creates a credential for Twitter.
   *
   * @param token - Twitter access token.
   * @param secret - Twitter secret.
   */
  static credential(token, secret) {
    return OAuthCredential._fromParams({
      providerId: TwitterAuthProvider.PROVIDER_ID,
      signInMethod: TwitterAuthProvider.TWITTER_SIGN_IN_METHOD,
      oauthToken: token,
      oauthTokenSecret: secret
    });
  }
  /**
   * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
   *
   * @param userCredential - The user credential.
   */
  static credentialFromResult(userCredential) {
    return TwitterAuthProvider.credentialFromTaggedObject(userCredential);
  }
  /**
   * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
   * thrown during a sign-in, link, or reauthenticate operation.
   *
   * @param userCredential - The user credential.
   */
  static credentialFromError(error2) {
    return TwitterAuthProvider.credentialFromTaggedObject(error2.customData || {});
  }
  static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {
    if (!tokenResponse) {
      return null;
    }
    const { oauthAccessToken, oauthTokenSecret } = tokenResponse;
    if (!oauthAccessToken || !oauthTokenSecret) {
      return null;
    }
    try {
      return TwitterAuthProvider.credential(oauthAccessToken, oauthTokenSecret);
    } catch (_a2) {
      return null;
    }
  }
}
TwitterAuthProvider.TWITTER_SIGN_IN_METHOD = "twitter.com";
TwitterAuthProvider.PROVIDER_ID = "twitter.com";
/**
 * @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.
 */
async function signUp(auth2, request) {
  return _performSignInRequest(auth2, "POST", "/v1/accounts:signUp", _addTidIfNecessary(auth2, request));
}
__name(signUp, "signUp");
/**
 * @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 UserCredentialImpl {
  static {
    __name(this, "UserCredentialImpl");
  }
  constructor(params) {
    this.user = params.user;
    this.providerId = params.providerId;
    this._tokenResponse = params._tokenResponse;
    this.operationType = params.operationType;
  }
  static async _fromIdTokenResponse(auth2, operationType, idTokenResponse, isAnonymous = false) {
    const user = await UserImpl._fromIdTokenResponse(auth2, idTokenResponse, isAnonymous);
    const providerId = providerIdForResponse(idTokenResponse);
    const userCred = new UserCredentialImpl({
      user,
      providerId,
      _tokenResponse: idTokenResponse,
      operationType
    });
    return userCred;
  }
  static async _forOperation(user, operationType, response) {
    await user._updateTokensIfNecessary(
      response,
      /* reload */
      true
    );
    const providerId = providerIdForResponse(response);
    return new UserCredentialImpl({
      user,
      providerId,
      _tokenResponse: response,
      operationType
    });
  }
}
function providerIdForResponse(response) {
  if (response.providerId) {
    return response.providerId;
  }
  if ("phoneNumber" in response) {
    return "phone";
  }
  return null;
}
__name(providerIdForResponse, "providerIdForResponse");
/**
 * @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.
 */
async function signInAnonymously(auth2) {
  var _a2;
  if (_isFirebaseServerApp(auth2.app)) {
    return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth2));
  }
  const authInternal = _castAuth(auth2);
  await authInternal._initializationPromise;
  if ((_a2 = authInternal.currentUser) === null || _a2 === void 0 ? void 0 : _a2.isAnonymous) {
    return new UserCredentialImpl({
      user: authInternal.currentUser,
      providerId: null,
      operationType: "signIn"
      /* OperationType.SIGN_IN */
    });
  }
  const response = await signUp(authInternal, {
    returnSecureToken: true
  });
  const userCredential = await UserCredentialImpl._fromIdTokenResponse(authInternal, "signIn", response, true);
  await authInternal._updateCurrentUser(userCredential.user);
  return userCredential;
}
__name(signInAnonymously, "signInAnonymously");
/**
 * @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 MultiFactorError extends FirebaseError {
  static {
    __name(this, "MultiFactorError");
  }
  constructor(auth2, error2, operationType, user) {
    var _a2;
    super(error2.code, error2.message);
    this.operationType = operationType;
    this.user = user;
    Object.setPrototypeOf(this, MultiFactorError.prototype);
    this.customData = {
      appName: auth2.name,
      tenantId: (_a2 = auth2.tenantId) !== null && _a2 !== void 0 ? _a2 : void 0,
      _serverResponse: error2.customData._serverResponse,
      operationType
    };
  }
  static _fromErrorAndOperation(auth2, error2, operationType, user) {
    return new MultiFactorError(auth2, error2, operationType, user);
  }
}
function _processCredentialSavingMfaContextIfNecessary(auth2, operationType, credential, user) {
  const idTokenProvider = operationType === "reauthenticate" ? credential._getReauthenticationResolver(auth2) : credential._getIdTokenResponse(auth2);
  return idTokenProvider.catch((error2) => {
    if (error2.code === `auth/${"multi-factor-auth-required"}`) {
      throw MultiFactorError._fromErrorAndOperation(auth2, error2, operationType, user);
    }
    throw error2;
  });
}
__name(_processCredentialSavingMfaContextIfNecessary, "_processCredentialSavingMfaContextIfNecessary");
/**
 * @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.
 */
function providerDataAsNames(providerData) {
  return new Set(providerData.map(({ providerId }) => providerId).filter((pid) => !!pid));
}
__name(providerDataAsNames, "providerDataAsNames");
/**
 * @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.
 */
async function unlink(user, providerId) {
  const userInternal = getModularInstance(user);
  await _assertLinkedStatus(true, userInternal, providerId);
  const { providerUserInfo } = await deleteLinkedAccounts(userInternal.auth, {
    idToken: await userInternal.getIdToken(),
    deleteProvider: [providerId]
  });
  const providersLeft = providerDataAsNames(providerUserInfo || []);
  userInternal.providerData = userInternal.providerData.filter((pd) => providersLeft.has(pd.providerId));
  if (!providersLeft.has(
    "phone"
    /* ProviderId.PHONE */
  )) {
    userInternal.phoneNumber = null;
  }
  await userInternal.auth._persistUserIfCurrent(userInternal);
  return userInternal;
}
__name(unlink, "unlink");
async function _link$1(user, credential, bypassAuthState = false) {
  const response = await _logoutIfInvalidated(user, credential._linkToIdToken(user.auth, await user.getIdToken()), bypassAuthState);
  return UserCredentialImpl._forOperation(user, "link", response);
}
__name(_link$1, "_link$1");
async function _assertLinkedStatus(expected, user, provider) {
  await _reloadWithoutSaving(user);
  const providerIds = providerDataAsNames(user.providerData);
  const code2 = expected === false ? "provider-already-linked" : "no-such-provider";
  _assert(providerIds.has(provider) === expected, user.auth, code2);
}
__name(_assertLinkedStatus, "_assertLinkedStatus");
/**
 * @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.
 */
async function _reauthenticate(user, credential, bypassAuthState = false) {
  const { auth: auth2 } = user;
  if (_isFirebaseServerApp(auth2.app)) {
    return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth2));
  }
  const operationType = "reauthenticate";
  try {
    const response = await _logoutIfInvalidated(user, _processCredentialSavingMfaContextIfNecessary(auth2, operationType, credential, user), bypassAuthState);
    _assert(
      response.idToken,
      auth2,
      "internal-error"
      /* AuthErrorCode.INTERNAL_ERROR */
    );
    const parsed = _parseToken(response.idToken);
    _assert(
      parsed,
      auth2,
      "internal-error"
      /* AuthErrorCode.INTERNAL_ERROR */
    );
    const { sub: localId } = parsed;
    _assert(
      user.uid === localId,
      auth2,
      "user-mismatch"
      /* AuthErrorCode.USER_MISMATCH */
    );
    return UserCredentialImpl._forOperation(user, operationType, response);
  } catch (e2) {
    if ((e2 === null || e2 === void 0 ? void 0 : e2.code) === `auth/${"user-not-found"}`) {
      _fail(
        auth2,
        "user-mismatch"
        /* AuthErrorCode.USER_MISMATCH */
      );
    }
    throw e2;
  }
}
__name(_reauthenticate, "_reauthenticate");
/**
 * @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.
 */
async function _signInWithCredential(auth2, credential, bypassAuthState = false) {
  if (_isFirebaseServerApp(auth2.app)) {
    return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth2));
  }
  const operationType = "signIn";
  const response = await _processCredentialSavingMfaContextIfNecessary(auth2, operationType, credential);
  const userCredential = await UserCredentialImpl._fromIdTokenResponse(auth2, operationType, response);
  if (!bypassAuthState) {
    await auth2._updateCurrentUser(userCredential.user);
  }
  return userCredential;
}
__name(_signInWithCredential, "_signInWithCredential");
async function signInWithCredential(auth2, credential) {
  return _signInWithCredential(_castAuth(auth2), credential);
}
__name(signInWithCredential, "signInWithCredential");
async function linkWithCredential(user, credential) {
  const userInternal = getModularInstance(user);
  await _assertLinkedStatus(false, userInternal, credential.providerId);
  return _link$1(userInternal, credential);
}
__name(linkWithCredential, "linkWithCredential");
async function reauthenticateWithCredential(user, credential) {
  return _reauthenticate(getModularInstance(user), credential);
}
__name(reauthenticateWithCredential, "reauthenticateWithCredential");
/**
 * @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.
 */
async function signInWithCustomToken$1(auth2, request) {
  return _performSignInRequest(auth2, "POST", "/v1/accounts:signInWithCustomToken", _addTidIfNecessary(auth2, request));
}
__name(signInWithCustomToken$1, "signInWithCustomToken$1");
/**
 * @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.
 */
async function signInWithCustomToken(auth2, customToken) {
  if (_isFirebaseServerApp(auth2.app)) {
    return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth2));
  }
  const authInternal = _castAuth(auth2);
  const response = await signInWithCustomToken$1(authInternal, {
    token: customToken,
    returnSecureToken: true
  });
  const cred = await UserCredentialImpl._fromIdTokenResponse(authInternal, "signIn", response);
  await authInternal._updateCurrentUser(cred.user);
  return cred;
}
__name(signInWithCustomToken, "signInWithCustomToken");
/**
 * @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 MultiFactorInfoImpl {
  static {
    __name(this, "MultiFactorInfoImpl");
  }
  constructor(factorId, response) {
    this.factorId = factorId;
    this.uid = response.mfaEnrollmentId;
    this.enrollmentTime = new Date(response.enrolledAt).toUTCString();
    this.displayName = response.displayName;
  }
  static _fromServerResponse(auth2, enrollment) {
    if ("phoneInfo" in enrollment) {
      return PhoneMultiFactorInfoImpl._fromServerResponse(auth2, enrollment);
    } else if ("totpInfo" in enrollment) {
      return TotpMultiFactorInfoImpl._fromServerResponse(auth2, enrollment);
    }
    return _fail(
      auth2,
      "internal-error"
      /* AuthErrorCode.INTERNAL_ERROR */
    );
  }
}
class PhoneMultiFactorInfoImpl extends MultiFactorInfoImpl {
  static {
    __name(this, "PhoneMultiFactorInfoImpl");
  }
  constructor(response) {
    super("phone", response);
    this.phoneNumber = response.phoneInfo;
  }
  static _fromServerResponse(_auth, enrollment) {
    return new PhoneMultiFactorInfoImpl(enrollment);
  }
}
class TotpMultiFactorInfoImpl extends MultiFactorInfoImpl {
  static {
    __name(this, "TotpMultiFactorInfoImpl");
  }
  constructor(response) {
    super("totp", response);
  }
  static _fromServerResponse(_auth, enrollment) {
    return new TotpMultiFactorInfoImpl(enrollment);
  }
}
/**
 * @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.
 */
function _setActionCodeSettingsOnRequest(auth2, request, actionCodeSettings) {
  var _a2;
  _assert(
    ((_a2 = actionCodeSettings.url) === null || _a2 === void 0 ? void 0 : _a2.length) > 0,
    auth2,
    "invalid-continue-uri"
    /* AuthErrorCode.INVALID_CONTINUE_URI */
  );
  _assert(
    typeof actionCodeSettings.dynamicLinkDomain === "undefined" || actionCodeSettings.dynamicLinkDomain.length > 0,
    auth2,
    "invalid-dynamic-link-domain"
    /* AuthErrorCode.INVALID_DYNAMIC_LINK_DOMAIN */
  );
  _assert(
    typeof actionCodeSettings.linkDomain === "undefined" || actionCodeSettings.linkDomain.length > 0,
    auth2,
    "invalid-hosting-link-domain"
    /* AuthErrorCode.INVALID_HOSTING_LINK_DOMAIN */
  );
  request.continueUrl = actionCodeSettings.url;
  request.dynamicLinkDomain = actionCodeSettings.dynamicLinkDomain;
  request.linkDomain = actionCodeSettings.linkDomain;
  request.canHandleCodeInApp = actionCodeSettings.handleCodeInApp;
  if (actionCodeSettings.iOS) {
    _assert(
      actionCodeSettings.iOS.bundleId.length > 0,
      auth2,
      "missing-ios-bundle-id"
      /* AuthErrorCode.MISSING_IOS_BUNDLE_ID */
    );
    request.iOSBundleId = actionCodeSettings.iOS.bundleId;
  }
  if (actionCodeSettings.android) {
    _assert(
      actionCodeSettings.android.packageName.length > 0,
      auth2,
      "missing-android-pkg-name"
      /* AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME */
    );
    request.androidInstallApp = actionCodeSettings.android.installApp;
    request.androidMinimumVersionCode = actionCodeSettings.android.minimumVersion;
    request.androidPackageName = actionCodeSettings.android.packageName;
  }
}
__name(_setActionCodeSettingsOnRequest, "_setActionCodeSettingsOnRequest");
/**
 * @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.
 */
async function recachePasswordPolicy(auth2) {
  const authInternal = _castAuth(auth2);
  if (authInternal._getPasswordPolicyInternal()) {
    await authInternal._updatePasswordPolicy();
  }
}
__name(recachePasswordPolicy, "recachePasswordPolicy");
async function sendPasswordResetEmail(auth2, email, actionCodeSettings) {
  const authInternal = _castAuth(auth2);
  const request = {
    requestType: "PASSWORD_RESET",
    email,
    clientType: "CLIENT_TYPE_WEB"
    /* RecaptchaClientType.WEB */
  };
  if (actionCodeSettings) {
    _setActionCodeSettingsOnRequest(authInternal, request, actionCodeSettings);
  }
  await handleRecaptchaFlow(
    authInternal,
    request,
    "getOobCode",
    sendPasswordResetEmail$1,
    "EMAIL_PASSWORD_PROVIDER"
    /* RecaptchaAuthProvider.EMAIL_PASSWORD_PROVIDER */
  );
}
__name(sendPasswordResetEmail, "sendPasswordResetEmail");
async function confirmPasswordReset(auth2, oobCode, newPassword) {
  await resetPassword(getModularInstance(auth2), {
    oobCode,
    newPassword
  }).catch(async (error2) => {
    if (error2.code === `auth/${"password-does-not-meet-requirements"}`) {
      void recachePasswordPolicy(auth2);
    }
    throw error2;
  });
}
__name(confirmPasswordReset, "confirmPasswordReset");
async function applyActionCode(auth2, oobCode) {
  await applyActionCode$1(getModularInstance(auth2), { oobCode });
}
__name(applyActionCode, "applyActionCode");
async function checkActionCode(auth2, oobCode) {
  const authModular = getModularInstance(auth2);
  const response = await resetPassword(authModular, { oobCode });
  const operation = response.requestType;
  _assert(
    operation,
    authModular,
    "internal-error"
    /* AuthErrorCode.INTERNAL_ERROR */
  );
  switch (operation) {
    case "EMAIL_SIGNIN":
      break;
    case "VERIFY_AND_CHANGE_EMAIL":
      _assert(
        response.newEmail,
        authModular,
        "internal-error"
        /* AuthErrorCode.INTERNAL_ERROR */
      );
      break;
    case "REVERT_SECOND_FACTOR_ADDITION":
      _assert(
        response.mfaInfo,
        authModular,
        "internal-error"
        /* AuthErrorCode.INTERNAL_ERROR */
      );
    default:
      _assert(
        response.email,
        authModular,
        "internal-error"
        /* AuthErrorCode.INTERNAL_ERROR */
      );
  }
  let multiFactorInfo = null;
  if (response.mfaInfo) {
    multiFactorInfo = MultiFactorInfoImpl._fromServerResponse(_castAuth(authModular), response.mfaInfo);
  }
  return {
    data: {
      email: (response.requestType === "VERIFY_AND_CHANGE_EMAIL" ? response.newEmail : response.email) || null,
      previousEmail: (response.requestType === "VERIFY_AND_CHANGE_EMAIL" ? response.email : response.newEmail) || null,
      multiFactorInfo
    },
    operation
  };
}
__name(checkActionCode, "checkActionCode");
async function verifyPasswordResetCode(auth2, code2) {
  const { data } = await checkActionCode(getModularInstance(auth2), code2);
  return data.email;
}
__name(verifyPasswordResetCode, "verifyPasswordResetCode");
async function createUserWithEmailAndPassword(auth2, email, password) {
  if (_isFirebaseServerApp(auth2.app)) {
    return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth2));
  }
  const authInternal = _castAuth(auth2);
  const request = {
    returnSecureToken: true,
    email,
    password,
    clientType: "CLIENT_TYPE_WEB"
    /* RecaptchaClientType.WEB */
  };
  const signUpResponse = handleRecaptchaFlow(
    authInternal,
    request,
    "signUpPassword",
    signUp,
    "EMAIL_PASSWORD_PROVIDER"
    /* RecaptchaAuthProvider.EMAIL_PASSWORD_PROVIDER */
  );
  const response = await signUpResponse.catch((error2) => {
    if (error2.code === `auth/${"password-does-not-meet-requirements"}`) {
      void recachePasswordPolicy(auth2);
    }
    throw error2;
  });
  const userCredential = await UserCredentialImpl._fromIdTokenResponse(authInternal, "signIn", response);
  await authInternal._updateCurrentUser(userCredential.user);
  return userCredential;
}
__name(createUserWithEmailAndPassword, "createUserWithEmailAndPassword");
function signInWithEmailAndPassword(auth2, email, password) {
  if (_isFirebaseServerApp(auth2.app)) {
    return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth2));
  }
  return signInWithCredential(getModularInstance(auth2), EmailAuthProvider.credential(email, password)).catch(async (error2) => {
    if (error2.code === `auth/${"password-does-not-meet-requirements"}`) {
      void recachePasswordPolicy(auth2);
    }
    throw error2;
  });
}
__name(signInWithEmailAndPassword, "signInWithEmailAndPassword");
/**
 * @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.
 */
async function sendSignInLinkToEmail(auth2, email, actionCodeSettings) {
  const authInternal = _castAuth(auth2);
  const request = {
    requestType: "EMAIL_SIGNIN",
    email,
    clientType: "CLIENT_TYPE_WEB"
    /* RecaptchaClientType.WEB */
  };
  function setActionCodeSettings(request2, actionCodeSettings2) {
    _assert(
      actionCodeSettings2.handleCodeInApp,
      authInternal,
      "argument-error"
      /* AuthErrorCode.ARGUMENT_ERROR */
    );
    if (actionCodeSettings2) {
      _setActionCodeSettingsOnRequest(authInternal, request2, actionCodeSettings2);
    }
  }
  __name(setActionCodeSettings, "setActionCodeSettings");
  setActionCodeSettings(request, actionCodeSettings);
  await handleRecaptchaFlow(
    authInternal,
    request,
    "getOobCode",
    sendSignInLinkToEmail$1,
    "EMAIL_PASSWORD_PROVIDER"
    /* RecaptchaAuthProvider.EMAIL_PASSWORD_PROVIDER */
  );
}
__name(sendSignInLinkToEmail, "sendSignInLinkToEmail");
function isSignInWithEmailLink(auth2, emailLink) {
  const actionCodeUrl = ActionCodeURL.parseLink(emailLink);
  return (actionCodeUrl === null || actionCodeUrl === void 0 ? void 0 : actionCodeUrl.operation) === "EMAIL_SIGNIN";
}
__name(isSignInWithEmailLink, "isSignInWithEmailLink");
async function signInWithEmailLink(auth2, email, emailLink) {
  if (_isFirebaseServerApp(auth2.app)) {
    return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth2));
  }
  const authModular = getModularInstance(auth2);
  const credential = EmailAuthProvider.credentialWithLink(email, emailLink || _getCurrentUrl());
  _assert(
    credential._tenantId === (authModular.tenantId || null),
    authModular,
    "tenant-id-mismatch"
    /* AuthErrorCode.TENANT_ID_MISMATCH */
  );
  return signInWithCredential(authModular, credential);
}
__name(signInWithEmailLink, "signInWithEmailLink");
/**
 * @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.
 */
async function createAuthUri(auth2, request) {
  return _performApiRequest(auth2, "POST", "/v1/accounts:createAuthUri", _addTidIfNecessary(auth2, request));
}
__name(createAuthUri, "createAuthUri");
/**
 * @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.
 */
async function fetchSignInMethodsForEmail(auth2, email) {
  const continueUri = _isHttpOrHttps() ? _getCurrentUrl() : "http://localhost";
  const request = {
    identifier: email,
    continueUri
  };
  const { signinMethods } = await createAuthUri(getModularInstance(auth2), request);
  return signinMethods || [];
}
__name(fetchSignInMethodsForEmail, "fetchSignInMethodsForEmail");
async function sendEmailVerification(user, actionCodeSettings) {
  const userInternal = getModularInstance(user);
  const idToken = await user.getIdToken();
  const request = {
    requestType: "VERIFY_EMAIL",
    idToken
  };
  if (actionCodeSettings) {
    _setActionCodeSettingsOnRequest(userInternal.auth, request, actionCodeSettings);
  }
  const { email } = await sendEmailVerification$1(userInternal.auth, request);
  if (email !== user.email) {
    await user.reload();
  }
}
__name(sendEmailVerification, "sendEmailVerification");
async function verifyBeforeUpdateEmail(user, newEmail, actionCodeSettings) {
  const userInternal = getModularInstance(user);
  const idToken = await user.getIdToken();
  const request = {
    requestType: "VERIFY_AND_CHANGE_EMAIL",
    idToken,
    newEmail
  };
  if (actionCodeSettings) {
    _setActionCodeSettingsOnRequest(userInternal.auth, request, actionCodeSettings);
  }
  const { email } = await verifyAndChangeEmail(userInternal.auth, request);
  if (email !== user.email) {
    await user.reload();
  }
}
__name(verifyBeforeUpdateEmail, "verifyBeforeUpdateEmail");
/**
 * @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.
 */
async function updateProfile$1(auth2, request) {
  return _performApiRequest(auth2, "POST", "/v1/accounts:update", request);
}
__name(updateProfile$1, "updateProfile$1");
/**
 * @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.
 */
async function updateProfile(user, { displayName, photoURL: photoUrl }) {
  if (displayName === void 0 && photoUrl === void 0) {
    return;
  }
  const userInternal = getModularInstance(user);
  const idToken = await userInternal.getIdToken();
  const profileRequest = {
    idToken,
    displayName,
    photoUrl,
    returnSecureToken: true
  };
  const response = await _logoutIfInvalidated(userInternal, updateProfile$1(userInternal.auth, profileRequest));
  userInternal.displayName = response.displayName || null;
  userInternal.photoURL = response.photoUrl || null;
  const passwordProvider = userInternal.providerData.find(
    ({ providerId }) => providerId === "password"
    /* ProviderId.PASSWORD */
  );
  if (passwordProvider) {
    passwordProvider.displayName = userInternal.displayName;
    passwordProvider.photoURL = userInternal.photoURL;
  }
  await userInternal._updateTokensIfNecessary(response);
}
__name(updateProfile, "updateProfile");
function updateEmail(user, newEmail) {
  const userInternal = getModularInstance(user);
  if (_isFirebaseServerApp(userInternal.auth.app)) {
    return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(userInternal.auth));
  }
  return updateEmailOrPassword(userInternal, newEmail, null);
}
__name(updateEmail, "updateEmail");
function updatePassword(user, newPassword) {
  return updateEmailOrPassword(getModularInstance(user), null, newPassword);
}
__name(updatePassword, "updatePassword");
async function updateEmailOrPassword(user, email, password) {
  const { auth: auth2 } = user;
  const idToken = await user.getIdToken();
  const request = {
    idToken,
    returnSecureToken: true
  };
  if (email) {
    request.email = email;
  }
  if (password) {
    request.password = password;
  }
  const response = await _logoutIfInvalidated(user, updateEmailPassword(auth2, request));
  await user._updateTokensIfNecessary(
    response,
    /* reload */
    true
  );
}
__name(updateEmailOrPassword, "updateEmailOrPassword");
/**
 * @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 _fromIdTokenResponse(idTokenResponse) {
  var _a2, _b;
  if (!idTokenResponse) {
    return null;
  }
  const { providerId } = idTokenResponse;
  const profile = idTokenResponse.rawUserInfo ? JSON.parse(idTokenResponse.rawUserInfo) : {};
  const isNewUser = idTokenResponse.isNewUser || idTokenResponse.kind === "identitytoolkit#SignupNewUserResponse";
  if (!providerId && (idTokenResponse === null || idTokenResponse === void 0 ? void 0 : idTokenResponse.idToken)) {
    const signInProvider = (_b = (_a2 = _parseToken(idTokenResponse.idToken)) === null || _a2 === void 0 ? void 0 : _a2.firebase) === null || _b === void 0 ? void 0 : _b["sign_in_provider"];
    if (signInProvider) {
      const filteredProviderId = signInProvider !== "anonymous" && signInProvider !== "custom" ? signInProvider : null;
      return new GenericAdditionalUserInfo(isNewUser, filteredProviderId);
    }
  }
  if (!providerId) {
    return null;
  }
  switch (providerId) {
    case "facebook.com":
      return new FacebookAdditionalUserInfo(isNewUser, profile);
    case "github.com":
      return new GithubAdditionalUserInfo(isNewUser, profile);
    case "google.com":
      return new GoogleAdditionalUserInfo(isNewUser, profile);
    case "twitter.com":
      return new TwitterAdditionalUserInfo(isNewUser, profile, idTokenResponse.screenName || null);
    case "custom":
    case "anonymous":
      return new GenericAdditionalUserInfo(isNewUser, null);
    default:
      return new GenericAdditionalUserInfo(isNewUser, providerId, profile);
  }
}
__name(_fromIdTokenResponse, "_fromIdTokenResponse");
class GenericAdditionalUserInfo {
  static {
    __name(this, "GenericAdditionalUserInfo");
  }
  constructor(isNewUser, providerId, profile = {}) {
    this.isNewUser = isNewUser;
    this.providerId = providerId;
    this.profile = profile;
  }
}
class FederatedAdditionalUserInfoWithUsername extends GenericAdditionalUserInfo {
  static {
    __name(this, "FederatedAdditionalUserInfoWithUsername");
  }
  constructor(isNewUser, providerId, profile, username) {
    super(isNewUser, providerId, profile);
    this.username = username;
  }
}
class FacebookAdditionalUserInfo extends GenericAdditionalUserInfo {
  static {
    __name(this, "FacebookAdditionalUserInfo");
  }
  constructor(isNewUser, profile) {
    super(isNewUser, "facebook.com", profile);
  }
}
class GithubAdditionalUserInfo extends FederatedAdditionalUserInfoWithUsername {
  static {
    __name(this, "GithubAdditionalUserInfo");
  }
  constructor(isNewUser, profile) {
    super(isNewUser, "github.com", profile, typeof (profile === null || profile === void 0 ? void 0 : profile.login) === "string" ? profile === null || profile === void 0 ? void 0 : profile.login : null);
  }
}
class GoogleAdditionalUserInfo extends GenericAdditionalUserInfo {
  static {
    __name(this, "GoogleAdditionalUserInfo");
  }
  constructor(isNewUser, profile) {
    super(isNewUser, "google.com", profile);
  }
}
class TwitterAdditionalUserInfo extends FederatedAdditionalUserInfoWithUsername {
  static {
    __name(this, "TwitterAdditionalUserInfo");
  }
  constructor(isNewUser, profile, screenName) {
    super(isNewUser, "twitter.com", profile, screenName);
  }
}
function getAdditionalUserInfo(userCredential) {
  const { user, _tokenResponse } = userCredential;
  if (user.isAnonymous && !_tokenResponse) {
    return {
      providerId: null,
      isNewUser: false,
      profile: null
    };
  }
  return _fromIdTokenResponse(_tokenResponse);
}
__name(getAdditionalUserInfo, "getAdditionalUserInfo");
/**
 * @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.
 */
function setPersistence(auth2, persistence) {
  return getModularInstance(auth2).setPersistence(persistence);
}
__name(setPersistence, "setPersistence");
function initializeRecaptchaConfig(auth2) {
  return _initializeRecaptchaConfig(auth2);
}
__name(initializeRecaptchaConfig, "initializeRecaptchaConfig");
async function validatePassword(auth2, password) {
  const authInternal = _castAuth(auth2);
  return authInternal.validatePassword(password);
}
__name(validatePassword, "validatePassword");
function onIdTokenChanged(auth2, nextOrObserver, error2, completed) {
  return getModularInstance(auth2).onIdTokenChanged(nextOrObserver, error2, completed);
}
__name(onIdTokenChanged, "onIdTokenChanged");
function beforeAuthStateChanged(auth2, callback, onAbort) {
  return getModularInstance(auth2).beforeAuthStateChanged(callback, onAbort);
}
__name(beforeAuthStateChanged, "beforeAuthStateChanged");
function onAuthStateChanged(auth2, nextOrObserver, error2, completed) {
  return getModularInstance(auth2).onAuthStateChanged(nextOrObserver, error2, completed);
}
__name(onAuthStateChanged, "onAuthStateChanged");
function useDeviceLanguage(auth2) {
  getModularInstance(auth2).useDeviceLanguage();
}
__name(useDeviceLanguage, "useDeviceLanguage");
function updateCurrentUser(auth2, user) {
  return getModularInstance(auth2).updateCurrentUser(user);
}
__name(updateCurrentUser, "updateCurrentUser");
function signOut(auth2) {
  return getModularInstance(auth2).signOut();
}
__name(signOut, "signOut");
function revokeAccessToken(auth2, token) {
  const authInternal = _castAuth(auth2);
  return authInternal.revokeAccessToken(token);
}
__name(revokeAccessToken, "revokeAccessToken");
async function deleteUser(user) {
  return getModularInstance(user).delete();
}
__name(deleteUser, "deleteUser");
/**
 * @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 MultiFactorSessionImpl {
  static {
    __name(this, "MultiFactorSessionImpl");
  }
  constructor(type, credential, user) {
    this.type = type;
    this.credential = credential;
    this.user = user;
  }
  static _fromIdtoken(idToken, user) {
    return new MultiFactorSessionImpl("enroll", idToken, user);
  }
  static _fromMfaPendingCredential(mfaPendingCredential) {
    return new MultiFactorSessionImpl("signin", mfaPendingCredential);
  }
  toJSON() {
    const key = this.type === "enroll" ? "idToken" : "pendingCredential";
    return {
      multiFactorSession: {
        [key]: this.credential
      }
    };
  }
  static fromJSON(obj) {
    var _a2, _b;
    if (obj === null || obj === void 0 ? void 0 : obj.multiFactorSession) {
      if ((_a2 = obj.multiFactorSession) === null || _a2 === void 0 ? void 0 : _a2.pendingCredential) {
        return MultiFactorSessionImpl._fromMfaPendingCredential(obj.multiFactorSession.pendingCredential);
      } else if ((_b = obj.multiFactorSession) === null || _b === void 0 ? void 0 : _b.idToken) {
        return MultiFactorSessionImpl._fromIdtoken(obj.multiFactorSession.idToken);
      }
    }
    return null;
  }
}
/**
 * @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 MultiFactorResolverImpl {
  static {
    __name(this, "MultiFactorResolverImpl");
  }
  constructor(session, hints, signInResolver) {
    this.session = session;
    this.hints = hints;
    this.signInResolver = signInResolver;
  }
  /** @internal */
  static _fromError(authExtern, error2) {
    const auth2 = _castAuth(authExtern);
    const serverResponse = error2.customData._serverResponse;
    const hints = (serverResponse.mfaInfo || []).map((enrollment) => MultiFactorInfoImpl._fromServerResponse(auth2, enrollment));
    _assert(
      serverResponse.mfaPendingCredential,
      auth2,
      "internal-error"
      /* AuthErrorCode.INTERNAL_ERROR */
    );
    const session = MultiFactorSessionImpl._fromMfaPendingCredential(serverResponse.mfaPendingCredential);
    return new MultiFactorResolverImpl(session, hints, async (assertion) => {
      const mfaResponse = await assertion._process(auth2, session);
      delete serverResponse.mfaInfo;
      delete serverResponse.mfaPendingCredential;
      const idTokenResponse = Object.assign(Object.assign({}, serverResponse), { idToken: mfaResponse.idToken, refreshToken: mfaResponse.refreshToken });
      switch (error2.operationType) {
        case "signIn":
          const userCredential = await UserCredentialImpl._fromIdTokenResponse(auth2, error2.operationType, idTokenResponse);
          await auth2._updateCurrentUser(userCredential.user);
          return userCredential;
        case "reauthenticate":
          _assert(
            error2.user,
            auth2,
            "internal-error"
            /* AuthErrorCode.INTERNAL_ERROR */
          );
          return UserCredentialImpl._forOperation(error2.user, error2.operationType, idTokenResponse);
        default:
          _fail(
            auth2,
            "internal-error"
            /* AuthErrorCode.INTERNAL_ERROR */
          );
      }
    });
  }
  async resolveSignIn(assertionExtern) {
    const assertion = assertionExtern;
    return this.signInResolver(assertion);
  }
}
function getMultiFactorResolver(auth2, error2) {
  var _a2;
  const authModular = getModularInstance(auth2);
  const errorInternal = error2;
  _assert(
    error2.customData.operationType,
    authModular,
    "argument-error"
    /* AuthErrorCode.ARGUMENT_ERROR */
  );
  _assert(
    (_a2 = errorInternal.customData._serverResponse) === null || _a2 === void 0 ? void 0 : _a2.mfaPendingCredential,
    authModular,
    "argument-error"
    /* AuthErrorCode.ARGUMENT_ERROR */
  );
  return MultiFactorResolverImpl._fromError(authModular, errorInternal);
}
__name(getMultiFactorResolver, "getMultiFactorResolver");
/**
 * @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.
 */
function startEnrollPhoneMfa(auth2, request) {
  return _performApiRequest(auth2, "POST", "/v2/accounts/mfaEnrollment:start", _addTidIfNecessary(auth2, request));
}
__name(startEnrollPhoneMfa, "startEnrollPhoneMfa");
function finalizeEnrollPhoneMfa(auth2, request) {
  return _performApiRequest(auth2, "POST", "/v2/accounts/mfaEnrollment:finalize", _addTidIfNecessary(auth2, request));
}
__name(finalizeEnrollPhoneMfa, "finalizeEnrollPhoneMfa");
function startEnrollTotpMfa(auth2, request) {
  return _performApiRequest(auth2, "POST", "/v2/accounts/mfaEnrollment:start", _addTidIfNecessary(auth2, request));
}
__name(startEnrollTotpMfa, "startEnrollTotpMfa");
function finalizeEnrollTotpMfa(auth2, request) {
  return _performApiRequest(auth2, "POST", "/v2/accounts/mfaEnrollment:finalize", _addTidIfNecessary(auth2, request));
}
__name(finalizeEnrollTotpMfa, "finalizeEnrollTotpMfa");
function withdrawMfa(auth2, request) {
  return _performApiRequest(auth2, "POST", "/v2/accounts/mfaEnrollment:withdraw", _addTidIfNecessary(auth2, request));
}
__name(withdrawMfa, "withdrawMfa");
class MultiFactorUserImpl {
  static {
    __name(this, "MultiFactorUserImpl");
  }
  constructor(user) {
    this.user = user;
    this.enrolledFactors = [];
    user._onReload((userInfo) => {
      if (userInfo.mfaInfo) {
        this.enrolledFactors = userInfo.mfaInfo.map((enrollment) => MultiFactorInfoImpl._fromServerResponse(user.auth, enrollment));
      }
    });
  }
  static _fromUser(user) {
    return new MultiFactorUserImpl(user);
  }
  async getSession() {
    return MultiFactorSessionImpl._fromIdtoken(await this.user.getIdToken(), this.user);
  }
  async enroll(assertionExtern, displayName) {
    const assertion = assertionExtern;
    const session = await this.getSession();
    const finalizeMfaResponse = await _logoutIfInvalidated(this.user, assertion._process(this.user.auth, session, displayName));
    await this.user._updateTokensIfNecessary(finalizeMfaResponse);
    return this.user.reload();
  }
  async unenroll(infoOrUid) {
    const mfaEnrollmentId = typeof infoOrUid === "string" ? infoOrUid : infoOrUid.uid;
    const idToken = await this.user.getIdToken();
    try {
      const idTokenResponse = await _logoutIfInvalidated(this.user, withdrawMfa(this.user.auth, {
        idToken,
        mfaEnrollmentId
      }));
      this.enrolledFactors = this.enrolledFactors.filter(({ uid }) => uid !== mfaEnrollmentId);
      await this.user._updateTokensIfNecessary(idTokenResponse);
      await this.user.reload();
    } catch (e2) {
      throw e2;
    }
  }
}
const multiFactorUserCache = /* @__PURE__ */ new WeakMap();
function multiFactor(user) {
  const userModular = getModularInstance(user);
  if (!multiFactorUserCache.has(userModular)) {
    multiFactorUserCache.set(userModular, MultiFactorUserImpl._fromUser(userModular));
  }
  return multiFactorUserCache.get(userModular);
}
__name(multiFactor, "multiFactor");
const STORAGE_AVAILABLE_KEY = "__sak";
/**
 * @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 BrowserPersistenceClass {
  static {
    __name(this, "BrowserPersistenceClass");
  }
  constructor(storageRetriever, type) {
    this.storageRetriever = storageRetriever;
    this.type = type;
  }
  _isAvailable() {
    try {
      if (!this.storage) {
        return Promise.resolve(false);
      }
      this.storage.setItem(STORAGE_AVAILABLE_KEY, "1");
      this.storage.removeItem(STORAGE_AVAILABLE_KEY);
      return Promise.resolve(true);
    } catch (_a2) {
      return Promise.resolve(false);
    }
  }
  _set(key, value) {
    this.storage.setItem(key, JSON.stringify(value));
    return Promise.resolve();
  }
  _get(key) {
    const json = this.storage.getItem(key);
    return Promise.resolve(json ? JSON.parse(json) : null);
  }
  _remove(key) {
    this.storage.removeItem(key);
    return Promise.resolve();
  }
  get storage() {
    return this.storageRetriever();
  }
}
/**
 * @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 _POLLING_INTERVAL_MS$1 = 1e3;
const IE10_LOCAL_STORAGE_SYNC_DELAY = 10;
class BrowserLocalPersistence extends BrowserPersistenceClass {
  static {
    __name(this, "BrowserLocalPersistence");
  }
  constructor() {
    super(
      () => window.localStorage,
      "LOCAL"
      /* PersistenceType.LOCAL */
    );
    this.boundEventHandler = (event, poll) => this.onStorageEvent(event, poll);
    this.listeners = {};
    this.localCache = {};
    this.pollTimer = null;
    this.fallbackToPolling = _isMobileBrowser();
    this._shouldAllowMigration = true;
  }
  forAllChangedKeys(cb) {
    for (const key of Object.keys(this.listeners)) {
      const newValue2 = this.storage.getItem(key);
      const oldValue = this.localCache[key];
      if (newValue2 !== oldValue) {
        cb(key, oldValue, newValue2);
      }
    }
  }
  onStorageEvent(event, poll = false) {
    if (!event.key) {
      this.forAllChangedKeys((key2, _oldValue, newValue2) => {
        this.notifyListeners(key2, newValue2);
      });
      return;
    }
    const key = event.key;
    if (poll) {
      this.detachListener();
    } else {
      this.stopPolling();
    }
    const triggerListeners = /* @__PURE__ */ __name(() => {
      const storedValue2 = this.storage.getItem(key);
      if (!poll && this.localCache[key] === storedValue2) {
        return;
      }
      this.notifyListeners(key, storedValue2);
    }, "triggerListeners");
    const storedValue = this.storage.getItem(key);
    if (_isIE10() && storedValue !== event.newValue && event.newValue !== event.oldValue) {
      setTimeout(triggerListeners, IE10_LOCAL_STORAGE_SYNC_DELAY);
    } else {
      triggerListeners();
    }
  }
  notifyListeners(key, value) {
    this.localCache[key] = value;
    const listeners = this.listeners[key];
    if (listeners) {
      for (const listener of Array.from(listeners)) {
        listener(value ? JSON.parse(value) : value);
      }
    }
  }
  startPolling() {
    this.stopPolling();
    this.pollTimer = setInterval(() => {
      this.forAllChangedKeys((key, oldValue, newValue2) => {
        this.onStorageEvent(
          new StorageEvent("storage", {
            key,
            oldValue,
            newValue: newValue2
          }),
          /* poll */
          true
        );
      });
    }, _POLLING_INTERVAL_MS$1);
  }
  stopPolling() {
    if (this.pollTimer) {
      clearInterval(this.pollTimer);
      this.pollTimer = null;
    }
  }
  attachListener() {
    window.addEventListener("storage", this.boundEventHandler);
  }
  detachListener() {
    window.removeEventListener("storage", this.boundEventHandler);
  }
  _addListener(key, listener) {
    if (Object.keys(this.listeners).length === 0) {
      if (this.fallbackToPolling) {
        this.startPolling();
      } else {
        this.attachListener();
      }
    }
    if (!this.listeners[key]) {
      this.listeners[key] = /* @__PURE__ */ new Set();
      this.localCache[key] = this.storage.getItem(key);
    }
    this.listeners[key].add(listener);
  }
  _removeListener(key, listener) {
    if (this.listeners[key]) {
      this.listeners[key].delete(listener);
      if (this.listeners[key].size === 0) {
        delete this.listeners[key];
      }
    }
    if (Object.keys(this.listeners).length === 0) {
      this.detachListener();
      this.stopPolling();
    }
  }
  // Update local cache on base operations:
  async _set(key, value) {
    await super._set(key, value);
    this.localCache[key] = JSON.stringify(value);
  }
  async _get(key) {
    const value = await super._get(key);
    this.localCache[key] = JSON.stringify(value);
    return value;
  }
  async _remove(key) {
    await super._remove(key);
    delete this.localCache[key];
  }
}
BrowserLocalPersistence.type = "LOCAL";
const browserLocalPersistence = BrowserLocalPersistence;
/**
 * @license
 * Copyright 2025 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 POLLING_INTERVAL_MS = 1e3;
function getDocumentCookie(name2) {
  var _a2, _b;
  const escapedName = name2.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&");
  const matcher = RegExp(`${escapedName}=([^;]+)`);
  return (_b = (_a2 = document.cookie.match(matcher)) === null || _a2 === void 0 ? void 0 : _a2[1]) !== null && _b !== void 0 ? _b : null;
}
__name(getDocumentCookie, "getDocumentCookie");
function getCookieName(key) {
  const isDevMode = window.location.protocol === "http:";
  return `${isDevMode ? "__dev_" : "__HOST-"}FIREBASE_${key.split(":")[3]}`;
}
__name(getCookieName, "getCookieName");
class CookiePersistence {
  static {
    __name(this, "CookiePersistence");
  }
  constructor() {
    this.type = "COOKIE";
    this.listenerUnsubscribes = /* @__PURE__ */ new Map();
  }
  // used to get the URL to the backend to proxy to
  _getFinalTarget(originalUrl) {
    if (typeof window === void 0) {
      return originalUrl;
    }
    const url = new URL(`${window.location.origin}/__cookies__`);
    url.searchParams.set("finalTarget", originalUrl);
    return url;
  }
  // To be a usable persistence method in a chain browserCookiePersistence ensures that
  // prerequisites have been met, namely that we're in a secureContext, navigator and document are
  // available and cookies are enabled. Not all UAs support these method, so fallback accordingly.
  async _isAvailable() {
    var _a2;
    if (typeof isSecureContext === "boolean" && !isSecureContext) {
      return false;
    }
    if (typeof navigator === "undefined" || typeof document === "undefined") {
      return false;
    }
    return (_a2 = navigator.cookieEnabled) !== null && _a2 !== void 0 ? _a2 : true;
  }
  // Set should be a noop as we expect middleware to handle this
  async _set(_key, _value) {
    return;
  }
  // Attempt to get the cookie from cookieStore, fallback to document.cookie
  async _get(key) {
    if (!this._isAvailable()) {
      return null;
    }
    const name2 = getCookieName(key);
    if (window.cookieStore) {
      const cookie = await window.cookieStore.get(name2);
      return cookie === null || cookie === void 0 ? void 0 : cookie.value;
    }
    return getDocumentCookie(name2);
  }
  // Log out by overriding the idToken with a sentinel value of ""
  async _remove(key) {
    if (!this._isAvailable()) {
      return;
    }
    const existingValue = await this._get(key);
    if (!existingValue) {
      return;
    }
    const name2 = getCookieName(key);
    document.cookie = `${name2}=;Max-Age=34560000;Partitioned;Secure;SameSite=Strict;Path=/;Priority=High`;
    await fetch(`/__cookies__`, { method: "DELETE" }).catch(() => void 0);
  }
  // Listen for cookie changes, both cookieStore and fallback to polling document.cookie
  _addListener(key, listener) {
    if (!this._isAvailable()) {
      return;
    }
    const name2 = getCookieName(key);
    if (window.cookieStore) {
      const cb = /* @__PURE__ */ __name((event) => {
        const changedCookie = event.changed.find((change) => change.name === name2);
        if (changedCookie) {
          listener(changedCookie.value);
        }
        const deletedCookie = event.deleted.find((change) => change.name === name2);
        if (deletedCookie) {
          listener(null);
        }
      }, "cb");
      const unsubscribe2 = /* @__PURE__ */ __name(() => window.cookieStore.removeEventListener("change", cb), "unsubscribe");
      this.listenerUnsubscribes.set(listener, unsubscribe2);
      return window.cookieStore.addEventListener("change", cb);
    }
    let lastValue = getDocumentCookie(name2);
    const interval = setInterval(() => {
      const currentValue = getDocumentCookie(name2);
      if (currentValue !== lastValue) {
        listener(currentValue);
        lastValue = currentValue;
      }
    }, POLLING_INTERVAL_MS);
    const unsubscribe = /* @__PURE__ */ __name(() => clearInterval(interval), "unsubscribe");
    this.listenerUnsubscribes.set(listener, unsubscribe);
  }
  _removeListener(_key, listener) {
    const unsubscribe = this.listenerUnsubscribes.get(listener);
    if (!unsubscribe) {
      return;
    }
    unsubscribe();
    this.listenerUnsubscribes.delete(listener);
  }
}
CookiePersistence.type = "COOKIE";
const browserCookiePersistence = CookiePersistence;
/**
 * @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 BrowserSessionPersistence extends BrowserPersistenceClass {
  static {
    __name(this, "BrowserSessionPersistence");
  }
  constructor() {
    super(
      () => window.sessionStorage,
      "SESSION"
      /* PersistenceType.SESSION */
    );
  }
  _addListener(_key, _listener) {
    return;
  }
  _removeListener(_key, _listener) {
    return;
  }
}
BrowserSessionPersistence.type = "SESSION";
const browserSessionPersistence = BrowserSessionPersistence;
/**
 * @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 _allSettled(promises) {
  return Promise.all(promises.map(async (promise) => {
    try {
      const value = await promise;
      return {
        fulfilled: true,
        value
      };
    } catch (reason) {
      return {
        fulfilled: false,
        reason
      };
    }
  }));
}
__name(_allSettled, "_allSettled");
/**
 * @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 Receiver {
  static {
    __name(this, "Receiver");
  }
  constructor(eventTarget) {
    this.eventTarget = eventTarget;
    this.handlersMap = {};
    this.boundEventHandler = this.handleEvent.bind(this);
  }
  /**
   * Obtain an instance of a Receiver for a given event target, if none exists it will be created.
   *
   * @param eventTarget - An event target (such as window or self) through which the underlying
   * messages will be received.
   */
  static _getInstance(eventTarget) {
    const existingInstance = this.receivers.find((receiver) => receiver.isListeningto(eventTarget));
    if (existingInstance) {
      return existingInstance;
    }
    const newInstance = new Receiver(eventTarget);
    this.receivers.push(newInstance);
    return newInstance;
  }
  isListeningto(eventTarget) {
    return this.eventTarget === eventTarget;
  }
  /**
   * Fans out a MessageEvent to the appropriate listeners.
   *
   * @remarks
   * Sends an {@link Status.ACK} upon receipt and a {@link Status.DONE} once all handlers have
   * finished processing.
   *
   * @param event - The MessageEvent.
   *
   */
  async handleEvent(event) {
    const messageEvent = event;
    const { eventId, eventType, data } = messageEvent.data;
    const handlers2 = this.handlersMap[eventType];
    if (!(handlers2 === null || handlers2 === void 0 ? void 0 : handlers2.size)) {
      return;
    }
    messageEvent.ports[0].postMessage({
      status: "ack",
      eventId,
      eventType
    });
    const promises = Array.from(handlers2).map(async (handler5) => handler5(messageEvent.origin, data));
    const response = await _allSettled(promises);
    messageEvent.ports[0].postMessage({
      status: "done",
      eventId,
      eventType,
      response
    });
  }
  /**
   * Subscribe an event handler for a particular event.
   *
   * @param eventType - Event name to subscribe to.
   * @param eventHandler - The event handler which should receive the events.
   *
   */
  _subscribe(eventType, eventHandler) {
    if (Object.keys(this.handlersMap).length === 0) {
      this.eventTarget.addEventListener("message", this.boundEventHandler);
    }
    if (!this.handlersMap[eventType]) {
      this.handlersMap[eventType] = /* @__PURE__ */ new Set();
    }
    this.handlersMap[eventType].add(eventHandler);
  }
  /**
   * Unsubscribe an event handler from a particular event.
   *
   * @param eventType - Event name to unsubscribe from.
   * @param eventHandler - Optional event handler, if none provided, unsubscribe all handlers on this event.
   *
   */
  _unsubscribe(eventType, eventHandler) {
    if (this.handlersMap[eventType] && eventHandler) {
      this.handlersMap[eventType].delete(eventHandler);
    }
    if (!eventHandler || this.handlersMap[eventType].size === 0) {
      delete this.handlersMap[eventType];
    }
    if (Object.keys(this.handlersMap).length === 0) {
      this.eventTarget.removeEventListener("message", this.boundEventHandler);
    }
  }
}
Receiver.receivers = [];
/**
 * @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.
 */
function _generateEventId(prefix = "", digits = 10) {
  let random = "";
  for (let i2 = 0; i2 < digits; i2++) {
    random += Math.floor(Math.random() * 10);
  }
  return prefix + random;
}
__name(_generateEventId, "_generateEventId");
/**
 * @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 Sender {
  static {
    __name(this, "Sender");
  }
  constructor(target) {
    this.target = target;
    this.handlers = /* @__PURE__ */ new Set();
  }
  /**
   * Unsubscribe the handler and remove it from our tracking Set.
   *
   * @param handler - The handler to unsubscribe.
   */
  removeMessageHandler(handler5) {
    if (handler5.messageChannel) {
      handler5.messageChannel.port1.removeEventListener("message", handler5.onMessage);
      handler5.messageChannel.port1.close();
    }
    this.handlers.delete(handler5);
  }
  /**
   * Send a message to the Receiver located at {@link target}.
   *
   * @remarks
   * We'll first wait a bit for an ACK , if we get one we will wait significantly longer until the
   * receiver has had a chance to fully process the event.
   *
   * @param eventType - Type of event to send.
   * @param data - The payload of the event.
   * @param timeout - Timeout for waiting on an ACK from the receiver.
   *
   * @returns An array of settled promises from all the handlers that were listening on the receiver.
   */
  async _send(eventType, data, timeout = 50) {
    const messageChannel = typeof MessageChannel !== "undefined" ? new MessageChannel() : null;
    if (!messageChannel) {
      throw new Error(
        "connection_unavailable"
        /* _MessageError.CONNECTION_UNAVAILABLE */
      );
    }
    let completionTimer;
    let handler5;
    return new Promise((resolve2, reject) => {
      const eventId = _generateEventId("", 20);
      messageChannel.port1.start();
      const ackTimer = setTimeout(() => {
        reject(new Error(
          "unsupported_event"
          /* _MessageError.UNSUPPORTED_EVENT */
        ));
      }, timeout);
      handler5 = {
        messageChannel,
        onMessage(event) {
          const messageEvent = event;
          if (messageEvent.data.eventId !== eventId) {
            return;
          }
          switch (messageEvent.data.status) {
            case "ack":
              clearTimeout(ackTimer);
              completionTimer = setTimeout(
                () => {
                  reject(new Error(
                    "timeout"
                    /* _MessageError.TIMEOUT */
                  ));
                },
                3e3
                /* _TimeoutDuration.COMPLETION */
              );
              break;
            case "done":
              clearTimeout(completionTimer);
              resolve2(messageEvent.data.response);
              break;
            default:
              clearTimeout(ackTimer);
              clearTimeout(completionTimer);
              reject(new Error(
                "invalid_response"
                /* _MessageError.INVALID_RESPONSE */
              ));
              break;
          }
        }
      };
      this.handlers.add(handler5);
      messageChannel.port1.addEventListener("message", handler5.onMessage);
      this.target.postMessage({
        eventType,
        eventId,
        data
      }, [messageChannel.port2]);
    }).finally(() => {
      if (handler5) {
        this.removeMessageHandler(handler5);
      }
    });
  }
}
/**
 * @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.
 */
function _window() {
  return window;
}
__name(_window, "_window");
function _setWindowLocation(url) {
  _window().location.href = url;
}
__name(_setWindowLocation, "_setWindowLocation");
/**
 * @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.
 */
function _isWorker() {
  return typeof _window()["WorkerGlobalScope"] !== "undefined" && typeof _window()["importScripts"] === "function";
}
__name(_isWorker, "_isWorker");
async function _getActiveServiceWorker() {
  if (!(navigator === null || navigator === void 0 ? void 0 : navigator.serviceWorker)) {
    return null;
  }
  try {
    const registration = await navigator.serviceWorker.ready;
    return registration.active;
  } catch (_a2) {
    return null;
  }
}
__name(_getActiveServiceWorker, "_getActiveServiceWorker");
function _getServiceWorkerController() {
  var _a2;
  return ((_a2 = navigator === null || navigator === void 0 ? void 0 : navigator.serviceWorker) === null || _a2 === void 0 ? void 0 : _a2.controller) || null;
}
__name(_getServiceWorkerController, "_getServiceWorkerController");
function _getWorkerGlobalScope() {
  return _isWorker() ? self : null;
}
__name(_getWorkerGlobalScope, "_getWorkerGlobalScope");
/**
 * @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 DB_NAME$1 = "firebaseLocalStorageDb";
const DB_VERSION$1 = 1;
const DB_OBJECTSTORE_NAME = "firebaseLocalStorage";
const DB_DATA_KEYPATH = "fbase_key";
class DBPromise {
  static {
    __name(this, "DBPromise");
  }
  constructor(request) {
    this.request = request;
  }
  toPromise() {
    return new Promise((resolve2, reject) => {
      this.request.addEventListener("success", () => {
        resolve2(this.request.result);
      });
      this.request.addEventListener("error", () => {
        reject(this.request.error);
      });
    });
  }
}
function getObjectStore(db, isReadWrite) {
  return db.transaction([DB_OBJECTSTORE_NAME], isReadWrite ? "readwrite" : "readonly").objectStore(DB_OBJECTSTORE_NAME);
}
__name(getObjectStore, "getObjectStore");
function _deleteDatabase() {
  const request = indexedDB.deleteDatabase(DB_NAME$1);
  return new DBPromise(request).toPromise();
}
__name(_deleteDatabase, "_deleteDatabase");
function _openDatabase() {
  const request = indexedDB.open(DB_NAME$1, DB_VERSION$1);
  return new Promise((resolve2, reject) => {
    request.addEventListener("error", () => {
      reject(request.error);
    });
    request.addEventListener("upgradeneeded", () => {
      const db = request.result;
      try {
        db.createObjectStore(DB_OBJECTSTORE_NAME, { keyPath: DB_DATA_KEYPATH });
      } catch (e2) {
        reject(e2);
      }
    });
    request.addEventListener("success", async () => {
      const db = request.result;
      if (!db.objectStoreNames.contains(DB_OBJECTSTORE_NAME)) {
        db.close();
        await _deleteDatabase();
        resolve2(await _openDatabase());
      } else {
        resolve2(db);
      }
    });
  });
}
__name(_openDatabase, "_openDatabase");
async function _putObject(db, key, value) {
  const request = getObjectStore(db, true).put({
    [DB_DATA_KEYPATH]: key,
    value
  });
  return new DBPromise(request).toPromise();
}
__name(_putObject, "_putObject");
async function getObject(db, key) {
  const request = getObjectStore(db, false).get(key);
  const data = await new DBPromise(request).toPromise();
  return data === void 0 ? null : data.value;
}
__name(getObject, "getObject");
function _deleteObject(db, key) {
  const request = getObjectStore(db, true).delete(key);
  return new DBPromise(request).toPromise();
}
__name(_deleteObject, "_deleteObject");
const _POLLING_INTERVAL_MS = 800;
const _TRANSACTION_RETRY_COUNT = 3;
class IndexedDBLocalPersistence {
  static {
    __name(this, "IndexedDBLocalPersistence");
  }
  constructor() {
    this.type = "LOCAL";
    this._shouldAllowMigration = true;
    this.listeners = {};
    this.localCache = {};
    this.pollTimer = null;
    this.pendingWrites = 0;
    this.receiver = null;
    this.sender = null;
    this.serviceWorkerReceiverAvailable = false;
    this.activeServiceWorker = null;
    this._workerInitializationPromise = this.initializeServiceWorkerMessaging().then(() => {
    }, () => {
    });
  }
  async _openDb() {
    if (this.db) {
      return this.db;
    }
    this.db = await _openDatabase();
    return this.db;
  }
  async _withRetries(op) {
    let numAttempts = 0;
    while (true) {
      try {
        const db = await this._openDb();
        return await op(db);
      } catch (e2) {
        if (numAttempts++ > _TRANSACTION_RETRY_COUNT) {
          throw e2;
        }
        if (this.db) {
          this.db.close();
          this.db = void 0;
        }
      }
    }
  }
  /**
   * IndexedDB events do not propagate from the main window to the worker context.  We rely on a
   * postMessage interface to send these events to the worker ourselves.
   */
  async initializeServiceWorkerMessaging() {
    return _isWorker() ? this.initializeReceiver() : this.initializeSender();
  }
  /**
   * As the worker we should listen to events from the main window.
   */
  async initializeReceiver() {
    this.receiver = Receiver._getInstance(_getWorkerGlobalScope());
    this.receiver._subscribe("keyChanged", async (_origin, data) => {
      const keys2 = await this._poll();
      return {
        keyProcessed: keys2.includes(data.key)
      };
    });
    this.receiver._subscribe("ping", async (_origin, _data) => {
      return [
        "keyChanged"
        /* _EventType.KEY_CHANGED */
      ];
    });
  }
  /**
   * As the main window, we should let the worker know when keys change (set and remove).
   *
   * @remarks
   * {@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/ready | ServiceWorkerContainer.ready}
   * may not resolve.
   */
  async initializeSender() {
    var _a2, _b;
    this.activeServiceWorker = await _getActiveServiceWorker();
    if (!this.activeServiceWorker) {
      return;
    }
    this.sender = new Sender(this.activeServiceWorker);
    const results = await this.sender._send(
      "ping",
      {},
      800
      /* _TimeoutDuration.LONG_ACK */
    );
    if (!results) {
      return;
    }
    if (((_a2 = results[0]) === null || _a2 === void 0 ? void 0 : _a2.fulfilled) && ((_b = results[0]) === null || _b === void 0 ? void 0 : _b.value.includes(
      "keyChanged"
      /* _EventType.KEY_CHANGED */
    ))) {
      this.serviceWorkerReceiverAvailable = true;
    }
  }
  /**
   * Let the worker know about a changed key, the exact key doesn't technically matter since the
   * worker will just trigger a full sync anyway.
   *
   * @remarks
   * For now, we only support one service worker per page.
   *
   * @param key - Storage key which changed.
   */
  async notifyServiceWorker(key) {
    if (!this.sender || !this.activeServiceWorker || _getServiceWorkerController() !== this.activeServiceWorker) {
      return;
    }
    try {
      await this.sender._send(
        "keyChanged",
        { key },
        // Use long timeout if receiver has previously responded to a ping from us.
        this.serviceWorkerReceiverAvailable ? 800 : 50
        /* _TimeoutDuration.ACK */
      );
    } catch (_a2) {
    }
  }
  async _isAvailable() {
    try {
      if (!indexedDB) {
        return false;
      }
      const db = await _openDatabase();
      await _putObject(db, STORAGE_AVAILABLE_KEY, "1");
      await _deleteObject(db, STORAGE_AVAILABLE_KEY);
      return true;
    } catch (_a2) {
    }
    return false;
  }
  async _withPendingWrite(write2) {
    this.pendingWrites++;
    try {
      await write2();
    } finally {
      this.pendingWrites--;
    }
  }
  async _set(key, value) {
    return this._withPendingWrite(async () => {
      await this._withRetries((db) => _putObject(db, key, value));
      this.localCache[key] = value;
      return this.notifyServiceWorker(key);
    });
  }
  async _get(key) {
    const obj = await this._withRetries((db) => getObject(db, key));
    this.localCache[key] = obj;
    return obj;
  }
  async _remove(key) {
    return this._withPendingWrite(async () => {
      await this._withRetries((db) => _deleteObject(db, key));
      delete this.localCache[key];
      return this.notifyServiceWorker(key);
    });
  }
  async _poll() {
    const result = await this._withRetries((db) => {
      const getAllRequest = getObjectStore(db, false).getAll();
      return new DBPromise(getAllRequest).toPromise();
    });
    if (!result) {
      return [];
    }
    if (this.pendingWrites !== 0) {
      return [];
    }
    const keys2 = [];
    const keysInResult = /* @__PURE__ */ new Set();
    if (result.length !== 0) {
      for (const { fbase_key: key, value } of result) {
        keysInResult.add(key);
        if (JSON.stringify(this.localCache[key]) !== JSON.stringify(value)) {
          this.notifyListeners(key, value);
          keys2.push(key);
        }
      }
    }
    for (const localKey of Object.keys(this.localCache)) {
      if (this.localCache[localKey] && !keysInResult.has(localKey)) {
        this.notifyListeners(localKey, null);
        keys2.push(localKey);
      }
    }
    return keys2;
  }
  notifyListeners(key, newValue2) {
    this.localCache[key] = newValue2;
    const listeners = this.listeners[key];
    if (listeners) {
      for (const listener of Array.from(listeners)) {
        listener(newValue2);
      }
    }
  }
  startPolling() {
    this.stopPolling();
    this.pollTimer = setInterval(async () => this._poll(), _POLLING_INTERVAL_MS);
  }
  stopPolling() {
    if (this.pollTimer) {
      clearInterval(this.pollTimer);
      this.pollTimer = null;
    }
  }
  _addListener(key, listener) {
    if (Object.keys(this.listeners).length === 0) {
      this.startPolling();
    }
    if (!this.listeners[key]) {
      this.listeners[key] = /* @__PURE__ */ new Set();
      void this._get(key);
    }
    this.listeners[key].add(listener);
  }
  _removeListener(key, listener) {
    if (this.listeners[key]) {
      this.listeners[key].delete(listener);
      if (this.listeners[key].size === 0) {
        delete this.listeners[key];
      }
    }
    if (Object.keys(this.listeners).length === 0) {
      this.stopPolling();
    }
  }
}
IndexedDBLocalPersistence.type = "LOCAL";
const indexedDBLocalPersistence = IndexedDBLocalPersistence;
/**
 * @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.
 */
function startSignInPhoneMfa(auth2, request) {
  return _performApiRequest(auth2, "POST", "/v2/accounts/mfaSignIn:start", _addTidIfNecessary(auth2, request));
}
__name(startSignInPhoneMfa, "startSignInPhoneMfa");
function finalizeSignInPhoneMfa(auth2, request) {
  return _performApiRequest(auth2, "POST", "/v2/accounts/mfaSignIn:finalize", _addTidIfNecessary(auth2, request));
}
__name(finalizeSignInPhoneMfa, "finalizeSignInPhoneMfa");
function finalizeSignInTotpMfa(auth2, request) {
  return _performApiRequest(auth2, "POST", "/v2/accounts/mfaSignIn:finalize", _addTidIfNecessary(auth2, request));
}
__name(finalizeSignInTotpMfa, "finalizeSignInTotpMfa");
/**
 * @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 _JSLOAD_CALLBACK = _generateCallbackName("rcb");
const NETWORK_TIMEOUT_DELAY = new Delay(3e4, 6e4);
class ReCaptchaLoaderImpl {
  static {
    __name(this, "ReCaptchaLoaderImpl");
  }
  constructor() {
    var _a2;
    this.hostLanguage = "";
    this.counter = 0;
    this.librarySeparatelyLoaded = !!((_a2 = _window().grecaptcha) === null || _a2 === void 0 ? void 0 : _a2.render);
  }
  load(auth2, hl = "") {
    _assert(
      isHostLanguageValid(hl),
      auth2,
      "argument-error"
      /* AuthErrorCode.ARGUMENT_ERROR */
    );
    if (this.shouldResolveImmediately(hl) && isV2(_window().grecaptcha)) {
      return Promise.resolve(_window().grecaptcha);
    }
    return new Promise((resolve2, reject) => {
      const networkTimeout = _window().setTimeout(() => {
        reject(_createError(
          auth2,
          "network-request-failed"
          /* AuthErrorCode.NETWORK_REQUEST_FAILED */
        ));
      }, NETWORK_TIMEOUT_DELAY.get());
      _window()[_JSLOAD_CALLBACK] = () => {
        _window().clearTimeout(networkTimeout);
        delete _window()[_JSLOAD_CALLBACK];
        const recaptcha = _window().grecaptcha;
        if (!recaptcha || !isV2(recaptcha)) {
          reject(_createError(
            auth2,
            "internal-error"
            /* AuthErrorCode.INTERNAL_ERROR */
          ));
          return;
        }
        const render2 = recaptcha.render;
        recaptcha.render = (container, params) => {
          const widgetId = render2(container, params);
          this.counter++;
          return widgetId;
        };
        this.hostLanguage = hl;
        resolve2(recaptcha);
      };
      const url = `${_recaptchaV2ScriptUrl()}?${querystring({
        onload: _JSLOAD_CALLBACK,
        render: "explicit",
        hl
      })}`;
      _loadJS(url).catch(() => {
        clearTimeout(networkTimeout);
        reject(_createError(
          auth2,
          "internal-error"
          /* AuthErrorCode.INTERNAL_ERROR */
        ));
      });
    });
  }
  clearedOneInstance() {
    this.counter--;
  }
  shouldResolveImmediately(hl) {
    var _a2;
    return !!((_a2 = _window().grecaptcha) === null || _a2 === void 0 ? void 0 : _a2.render) && (hl === this.hostLanguage || this.counter > 0 || this.librarySeparatelyLoaded);
  }
}
function isHostLanguageValid(hl) {
  return hl.length <= 6 && /^\s*[a-zA-Z0-9\-]*\s*$/.test(hl);
}
__name(isHostLanguageValid, "isHostLanguageValid");
class MockReCaptchaLoaderImpl {
  static {
    __name(this, "MockReCaptchaLoaderImpl");
  }
  async load(auth2) {
    return new MockReCaptcha(auth2);
  }
  clearedOneInstance() {
  }
}
/**
 * @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 RECAPTCHA_VERIFIER_TYPE = "recaptcha";
const DEFAULT_PARAMS = {
  theme: "light",
  type: "image"
};
class RecaptchaVerifier {
  static {
    __name(this, "RecaptchaVerifier");
  }
  /**
   * @param authExtern - The corresponding Firebase {@link Auth} instance.
   *
   * @param containerOrId - The reCAPTCHA container parameter.
   *
   * @remarks
   * This has different meaning depending on whether the reCAPTCHA is hidden or visible. For a
   * visible reCAPTCHA the container must be empty. If a string is used, it has to correspond to
   * an element ID. The corresponding element must also must be in the DOM at the time of
   * initialization.
   *
   * @param parameters - The optional reCAPTCHA parameters.
   *
   * @remarks
   * Check the reCAPTCHA docs for a comprehensive list. All parameters are accepted except for
   * the sitekey. Firebase Auth backend provisions a reCAPTCHA for each project and will
   * configure this upon rendering. For an invisible reCAPTCHA, a size key must have the value
   * 'invisible'.
   */
  constructor(authExtern, containerOrId, parameters = Object.assign({}, DEFAULT_PARAMS)) {
    this.parameters = parameters;
    this.type = RECAPTCHA_VERIFIER_TYPE;
    this.destroyed = false;
    this.widgetId = null;
    this.tokenChangeListeners = /* @__PURE__ */ new Set();
    this.renderPromise = null;
    this.recaptcha = null;
    this.auth = _castAuth(authExtern);
    this.isInvisible = this.parameters.size === "invisible";
    _assert(
      typeof document !== "undefined",
      this.auth,
      "operation-not-supported-in-this-environment"
      /* AuthErrorCode.OPERATION_NOT_SUPPORTED */
    );
    const container = typeof containerOrId === "string" ? document.getElementById(containerOrId) : containerOrId;
    _assert(
      container,
      this.auth,
      "argument-error"
      /* AuthErrorCode.ARGUMENT_ERROR */
    );
    this.container = container;
    this.parameters.callback = this.makeTokenCallback(this.parameters.callback);
    this._recaptchaLoader = this.auth.settings.appVerificationDisabledForTesting ? new MockReCaptchaLoaderImpl() : new ReCaptchaLoaderImpl();
    this.validateStartingState();
  }
  /**
   * Waits for the user to solve the reCAPTCHA and resolves with the reCAPTCHA token.
   *
   * @returns A Promise for the reCAPTCHA token.
   */
  async verify() {
    this.assertNotDestroyed();
    const id2 = await this.render();
    const recaptcha = this.getAssertedRecaptcha();
    const response = recaptcha.getResponse(id2);
    if (response) {
      return response;
    }
    return new Promise((resolve2) => {
      const tokenChange = /* @__PURE__ */ __name((token) => {
        if (!token) {
          return;
        }
        this.tokenChangeListeners.delete(tokenChange);
        resolve2(token);
      }, "tokenChange");
      this.tokenChangeListeners.add(tokenChange);
      if (this.isInvisible) {
        recaptcha.execute(id2);
      }
    });
  }
  /**
   * Renders the reCAPTCHA widget on the page.
   *
   * @returns A Promise that resolves with the reCAPTCHA widget ID.
   */
  render() {
    try {
      this.assertNotDestroyed();
    } catch (e2) {
      return Promise.reject(e2);
    }
    if (this.renderPromise) {
      return this.renderPromise;
    }
    this.renderPromise = this.makeRenderPromise().catch((e2) => {
      this.renderPromise = null;
      throw e2;
    });
    return this.renderPromise;
  }
  /** @internal */
  _reset() {
    this.assertNotDestroyed();
    if (this.widgetId !== null) {
      this.getAssertedRecaptcha().reset(this.widgetId);
    }
  }
  /**
   * Clears the reCAPTCHA widget from the page and destroys the instance.
   */
  clear() {
    this.assertNotDestroyed();
    this.destroyed = true;
    this._recaptchaLoader.clearedOneInstance();
    if (!this.isInvisible) {
      this.container.childNodes.forEach((node2) => {
        this.container.removeChild(node2);
      });
    }
  }
  validateStartingState() {
    _assert(
      !this.parameters.sitekey,
      this.auth,
      "argument-error"
      /* AuthErrorCode.ARGUMENT_ERROR */
    );
    _assert(
      this.isInvisible || !this.container.hasChildNodes(),
      this.auth,
      "argument-error"
      /* AuthErrorCode.ARGUMENT_ERROR */
    );
    _assert(
      typeof document !== "undefined",
      this.auth,
      "operation-not-supported-in-this-environment"
      /* AuthErrorCode.OPERATION_NOT_SUPPORTED */
    );
  }
  makeTokenCallback(existing) {
    return (token) => {
      this.tokenChangeListeners.forEach((listener) => listener(token));
      if (typeof existing === "function") {
        existing(token);
      } else if (typeof existing === "string") {
        const globalFunc = _window()[existing];
        if (typeof globalFunc === "function") {
          globalFunc(token);
        }
      }
    };
  }
  assertNotDestroyed() {
    _assert(
      !this.destroyed,
      this.auth,
      "internal-error"
      /* AuthErrorCode.INTERNAL_ERROR */
    );
  }
  async makeRenderPromise() {
    await this.init();
    if (!this.widgetId) {
      let container = this.container;
      if (!this.isInvisible) {
        const guaranteedEmpty = document.createElement("div");
        container.appendChild(guaranteedEmpty);
        container = guaranteedEmpty;
      }
      this.widgetId = this.getAssertedRecaptcha().render(container, this.parameters);
    }
    return this.widgetId;
  }
  async init() {
    _assert(
      _isHttpOrHttps() && !_isWorker(),
      this.auth,
      "internal-error"
      /* AuthErrorCode.INTERNAL_ERROR */
    );
    await domReady();
    this.recaptcha = await this._recaptchaLoader.load(this.auth, this.auth.languageCode || void 0);
    const siteKey = await getRecaptchaParams(this.auth);
    _assert(
      siteKey,
      this.auth,
      "internal-error"
      /* AuthErrorCode.INTERNAL_ERROR */
    );
    this.parameters.sitekey = siteKey;
  }
  getAssertedRecaptcha() {
    _assert(
      this.recaptcha,
      this.auth,
      "internal-error"
      /* AuthErrorCode.INTERNAL_ERROR */
    );
    return this.recaptcha;
  }
}
function domReady() {
  let resolver = null;
  return new Promise((resolve2) => {
    if (document.readyState === "complete") {
      resolve2();
      return;
    }
    resolver = /* @__PURE__ */ __name(() => resolve2(), "resolver");
    window.addEventListener("load", resolver);
  }).catch((e2) => {
    if (resolver) {
      window.removeEventListener("load", resolver);
    }
    throw e2;
  });
}
__name(domReady, "domReady");
/**
 * @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 ConfirmationResultImpl {
  static {
    __name(this, "ConfirmationResultImpl");
  }
  constructor(verificationId, onConfirmation) {
    this.verificationId = verificationId;
    this.onConfirmation = onConfirmation;
  }
  confirm(verificationCode) {
    const authCredential = PhoneAuthCredential._fromVerification(this.verificationId, verificationCode);
    return this.onConfirmation(authCredential);
  }
}
async function signInWithPhoneNumber(auth2, phoneNumber, appVerifier) {
  if (_isFirebaseServerApp(auth2.app)) {
    return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth2));
  }
  const authInternal = _castAuth(auth2);
  const verificationId = await _verifyPhoneNumber(authInternal, phoneNumber, getModularInstance(appVerifier));
  return new ConfirmationResultImpl(verificationId, (cred) => signInWithCredential(authInternal, cred));
}
__name(signInWithPhoneNumber, "signInWithPhoneNumber");
async function linkWithPhoneNumber(user, phoneNumber, appVerifier) {
  const userInternal = getModularInstance(user);
  await _assertLinkedStatus(
    false,
    userInternal,
    "phone"
    /* ProviderId.PHONE */
  );
  const verificationId = await _verifyPhoneNumber(userInternal.auth, phoneNumber, getModularInstance(appVerifier));
  return new ConfirmationResultImpl(verificationId, (cred) => linkWithCredential(userInternal, cred));
}
__name(linkWithPhoneNumber, "linkWithPhoneNumber");
async function reauthenticateWithPhoneNumber(user, phoneNumber, appVerifier) {
  const userInternal = getModularInstance(user);
  if (_isFirebaseServerApp(userInternal.auth.app)) {
    return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(userInternal.auth));
  }
  const verificationId = await _verifyPhoneNumber(userInternal.auth, phoneNumber, getModularInstance(appVerifier));
  return new ConfirmationResultImpl(verificationId, (cred) => reauthenticateWithCredential(userInternal, cred));
}
__name(reauthenticateWithPhoneNumber, "reauthenticateWithPhoneNumber");
async function _verifyPhoneNumber(auth2, options2, verifier) {
  var _a2;
  if (!auth2._getRecaptchaConfig()) {
    try {
      await _initializeRecaptchaConfig(auth2);
    } catch (error2) {
      console.log("Failed to initialize reCAPTCHA Enterprise config. Triggering the reCAPTCHA v2 verification.");
    }
  }
  try {
    let phoneInfoOptions;
    if (typeof options2 === "string") {
      phoneInfoOptions = {
        phoneNumber: options2
      };
    } else {
      phoneInfoOptions = options2;
    }
    if ("session" in phoneInfoOptions) {
      const session = phoneInfoOptions.session;
      if ("phoneNumber" in phoneInfoOptions) {
        _assert(
          session.type === "enroll",
          auth2,
          "internal-error"
          /* AuthErrorCode.INTERNAL_ERROR */
        );
        const startPhoneMfaEnrollmentRequest = {
          idToken: session.credential,
          phoneEnrollmentInfo: {
            phoneNumber: phoneInfoOptions.phoneNumber,
            clientType: "CLIENT_TYPE_WEB"
            /* RecaptchaClientType.WEB */
          }
        };
        const startEnrollPhoneMfaActionCallback = /* @__PURE__ */ __name(async (authInstance, request) => {
          if (request.phoneEnrollmentInfo.captchaResponse === FAKE_TOKEN) {
            _assert(
              (verifier === null || verifier === void 0 ? void 0 : verifier.type) === RECAPTCHA_VERIFIER_TYPE,
              authInstance,
              "argument-error"
              /* AuthErrorCode.ARGUMENT_ERROR */
            );
            const requestWithRecaptchaV2 = await injectRecaptchaV2Token(authInstance, request, verifier);
            return startEnrollPhoneMfa(authInstance, requestWithRecaptchaV2);
          }
          return startEnrollPhoneMfa(authInstance, request);
        }, "startEnrollPhoneMfaActionCallback");
        const startPhoneMfaEnrollmentResponse = handleRecaptchaFlow(
          auth2,
          startPhoneMfaEnrollmentRequest,
          "mfaSmsEnrollment",
          startEnrollPhoneMfaActionCallback,
          "PHONE_PROVIDER"
          /* RecaptchaAuthProvider.PHONE_PROVIDER */
        );
        const response = await startPhoneMfaEnrollmentResponse.catch((error2) => {
          return Promise.reject(error2);
        });
        return response.phoneSessionInfo.sessionInfo;
      } else {
        _assert(
          session.type === "signin",
          auth2,
          "internal-error"
          /* AuthErrorCode.INTERNAL_ERROR */
        );
        const mfaEnrollmentId = ((_a2 = phoneInfoOptions.multiFactorHint) === null || _a2 === void 0 ? void 0 : _a2.uid) || phoneInfoOptions.multiFactorUid;
        _assert(
          mfaEnrollmentId,
          auth2,
          "missing-multi-factor-info"
          /* AuthErrorCode.MISSING_MFA_INFO */
        );
        const startPhoneMfaSignInRequest = {
          mfaPendingCredential: session.credential,
          mfaEnrollmentId,
          phoneSignInInfo: {
            clientType: "CLIENT_TYPE_WEB"
            /* RecaptchaClientType.WEB */
          }
        };
        const startSignInPhoneMfaActionCallback = /* @__PURE__ */ __name(async (authInstance, request) => {
          if (request.phoneSignInInfo.captchaResponse === FAKE_TOKEN) {
            _assert(
              (verifier === null || verifier === void 0 ? void 0 : verifier.type) === RECAPTCHA_VERIFIER_TYPE,
              authInstance,
              "argument-error"
              /* AuthErrorCode.ARGUMENT_ERROR */
            );
            const requestWithRecaptchaV2 = await injectRecaptchaV2Token(authInstance, request, verifier);
            return startSignInPhoneMfa(authInstance, requestWithRecaptchaV2);
          }
          return startSignInPhoneMfa(authInstance, request);
        }, "startSignInPhoneMfaActionCallback");
        const startPhoneMfaSignInResponse = handleRecaptchaFlow(
          auth2,
          startPhoneMfaSignInRequest,
          "mfaSmsSignIn",
          startSignInPhoneMfaActionCallback,
          "PHONE_PROVIDER"
          /* RecaptchaAuthProvider.PHONE_PROVIDER */
        );
        const response = await startPhoneMfaSignInResponse.catch((error2) => {
          return Promise.reject(error2);
        });
        return response.phoneResponseInfo.sessionInfo;
      }
    } else {
      const sendPhoneVerificationCodeRequest = {
        phoneNumber: phoneInfoOptions.phoneNumber,
        clientType: "CLIENT_TYPE_WEB"
        /* RecaptchaClientType.WEB */
      };
      const sendPhoneVerificationCodeActionCallback = /* @__PURE__ */ __name(async (authInstance, request) => {
        if (request.captchaResponse === FAKE_TOKEN) {
          _assert(
            (verifier === null || verifier === void 0 ? void 0 : verifier.type) === RECAPTCHA_VERIFIER_TYPE,
            authInstance,
            "argument-error"
            /* AuthErrorCode.ARGUMENT_ERROR */
          );
          const requestWithRecaptchaV2 = await injectRecaptchaV2Token(authInstance, request, verifier);
          return sendPhoneVerificationCode(authInstance, requestWithRecaptchaV2);
        }
        return sendPhoneVerificationCode(authInstance, request);
      }, "sendPhoneVerificationCodeActionCallback");
      const sendPhoneVerificationCodeResponse = handleRecaptchaFlow(
        auth2,
        sendPhoneVerificationCodeRequest,
        "sendVerificationCode",
        sendPhoneVerificationCodeActionCallback,
        "PHONE_PROVIDER"
        /* RecaptchaAuthProvider.PHONE_PROVIDER */
      );
      const response = await sendPhoneVerificationCodeResponse.catch((error2) => {
        return Promise.reject(error2);
      });
      return response.sessionInfo;
    }
  } finally {
    verifier === null || verifier === void 0 ? void 0 : verifier._reset();
  }
}
__name(_verifyPhoneNumber, "_verifyPhoneNumber");
async function updatePhoneNumber(user, credential) {
  const userInternal = getModularInstance(user);
  if (_isFirebaseServerApp(userInternal.auth.app)) {
    return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(userInternal.auth));
  }
  await _link$1(userInternal, credential);
}
__name(updatePhoneNumber, "updatePhoneNumber");
async function injectRecaptchaV2Token(auth2, request, recaptchaV2Verifier) {
  _assert(
    recaptchaV2Verifier.type === RECAPTCHA_VERIFIER_TYPE,
    auth2,
    "argument-error"
    /* AuthErrorCode.ARGUMENT_ERROR */
  );
  const recaptchaV2Token = await recaptchaV2Verifier.verify();
  _assert(
    typeof recaptchaV2Token === "string",
    auth2,
    "argument-error"
    /* AuthErrorCode.ARGUMENT_ERROR */
  );
  const newRequest = Object.assign({}, request);
  if ("phoneEnrollmentInfo" in newRequest) {
    const phoneNumber = newRequest.phoneEnrollmentInfo.phoneNumber;
    const captchaResponse = newRequest.phoneEnrollmentInfo.captchaResponse;
    const clientType = newRequest.phoneEnrollmentInfo.clientType;
    const recaptchaVersion = newRequest.phoneEnrollmentInfo.recaptchaVersion;
    Object.assign(newRequest, {
      "phoneEnrollmentInfo": {
        phoneNumber,
        recaptchaToken: recaptchaV2Token,
        captchaResponse,
        clientType,
        recaptchaVersion
      }
    });
    return newRequest;
  } else if ("phoneSignInInfo" in newRequest) {
    const captchaResponse = newRequest.phoneSignInInfo.captchaResponse;
    const clientType = newRequest.phoneSignInInfo.clientType;
    const recaptchaVersion = newRequest.phoneSignInInfo.recaptchaVersion;
    Object.assign(newRequest, {
      "phoneSignInInfo": {
        recaptchaToken: recaptchaV2Token,
        captchaResponse,
        clientType,
        recaptchaVersion
      }
    });
    return newRequest;
  } else {
    Object.assign(newRequest, { "recaptchaToken": recaptchaV2Token });
    return newRequest;
  }
}
__name(injectRecaptchaV2Token, "injectRecaptchaV2Token");
/**
 * @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 PhoneAuthProvider {
  static {
    __name(this, "PhoneAuthProvider");
  }
  /**
   * @param auth - The Firebase {@link Auth} instance in which sign-ins should occur.
   *
   */
  constructor(auth2) {
    this.providerId = PhoneAuthProvider.PROVIDER_ID;
    this.auth = _castAuth(auth2);
  }
  /**
   *
   * Starts a phone number authentication flow by sending a verification code to the given phone
   * number.
   *
   * @example
   * ```javascript
   * const provider = new PhoneAuthProvider(auth);
   * const verificationId = await provider.verifyPhoneNumber(phoneNumber, applicationVerifier);
   * // Obtain verificationCode from the user.
   * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);
   * const userCredential = await signInWithCredential(auth, authCredential);
   * ```
   *
   * @example
   * An alternative flow is provided using the `signInWithPhoneNumber` method.
   * ```javascript
   * const confirmationResult = signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);
   * // Obtain verificationCode from the user.
   * const userCredential = confirmationResult.confirm(verificationCode);
   * ```
   *
   * @param phoneInfoOptions - The user's {@link PhoneInfoOptions}. The phone number should be in
   * E.164 format (e.g. +16505550101).
   * @param applicationVerifier - An {@link ApplicationVerifier}, which prevents
   * requests from unauthorized clients. This SDK includes an implementation
   * based on reCAPTCHA v2, {@link RecaptchaVerifier}. If you've enabled
   * reCAPTCHA Enterprise bot protection in Enforce mode, this parameter is
   * optional; in all other configurations, the parameter is required.
   *
   * @returns A Promise for a verification ID that can be passed to
   * {@link PhoneAuthProvider.credential} to identify this flow.
   */
  verifyPhoneNumber(phoneOptions, applicationVerifier) {
    return _verifyPhoneNumber(this.auth, phoneOptions, getModularInstance(applicationVerifier));
  }
  /**
   * Creates a phone auth credential, given the verification ID from
   * {@link PhoneAuthProvider.verifyPhoneNumber} and the code that was sent to the user's
   * mobile device.
   *
   * @example
   * ```javascript
   * const provider = new PhoneAuthProvider(auth);
   * const verificationId = provider.verifyPhoneNumber(phoneNumber, applicationVerifier);
   * // Obtain verificationCode from the user.
   * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);
   * const userCredential = signInWithCredential(auth, authCredential);
   * ```
   *
   * @example
   * An alternative flow is provided using the `signInWithPhoneNumber` method.
   * ```javascript
   * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);
   * // Obtain verificationCode from the user.
   * const userCredential = await confirmationResult.confirm(verificationCode);
   * ```
   *
   * @param verificationId - The verification ID returned from {@link PhoneAuthProvider.verifyPhoneNumber}.
   * @param verificationCode - The verification code sent to the user's mobile device.
   *
   * @returns The auth provider credential.
   */
  static credential(verificationId, verificationCode) {
    return PhoneAuthCredential._fromVerification(verificationId, verificationCode);
  }
  /**
   * Generates an {@link AuthCredential} from a {@link UserCredential}.
   * @param userCredential - The user credential.
   */
  static credentialFromResult(userCredential) {
    const credential = userCredential;
    return PhoneAuthProvider.credentialFromTaggedObject(credential);
  }
  /**
   * Returns an {@link AuthCredential} when passed an error.
   *
   * @remarks
   *
   * This method works for errors like
   * `auth/account-exists-with-different-credentials`. This is useful for
   * recovering when attempting to set a user's phone number but the number
   * in question is already tied to another account. For example, the following
   * code tries to update the current user's phone number, and if that
   * fails, links the user with the account associated with that number:
   *
   * ```js
   * const provider = new PhoneAuthProvider(auth);
   * const verificationId = await provider.verifyPhoneNumber(number, verifier);
   * try {
   *   const code = ''; // Prompt the user for the verification code
   *   await updatePhoneNumber(
   *       auth.currentUser,
   *       PhoneAuthProvider.credential(verificationId, code));
   * } catch (e) {
   *   if ((e as FirebaseError)?.code === 'auth/account-exists-with-different-credential') {
   *     const cred = PhoneAuthProvider.credentialFromError(e);
   *     await linkWithCredential(auth.currentUser, cred);
   *   }
   * }
   *
   * // At this point, auth.currentUser.phoneNumber === number.
   * ```
   *
   * @param error - The error to generate a credential from.
   */
  static credentialFromError(error2) {
    return PhoneAuthProvider.credentialFromTaggedObject(error2.customData || {});
  }
  static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {
    if (!tokenResponse) {
      return null;
    }
    const { phoneNumber, temporaryProof } = tokenResponse;
    if (phoneNumber && temporaryProof) {
      return PhoneAuthCredential._fromTokenResponse(phoneNumber, temporaryProof);
    }
    return null;
  }
}
PhoneAuthProvider.PROVIDER_ID = "phone";
PhoneAuthProvider.PHONE_SIGN_IN_METHOD = "phone";
/**
 * @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 _withDefaultResolver(auth2, resolverOverride) {
  if (resolverOverride) {
    return _getInstance(resolverOverride);
  }
  _assert(
    auth2._popupRedirectResolver,
    auth2,
    "argument-error"
    /* AuthErrorCode.ARGUMENT_ERROR */
  );
  return auth2._popupRedirectResolver;
}
__name(_withDefaultResolver, "_withDefaultResolver");
/**
 * @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 IdpCredential extends AuthCredential {
  static {
    __name(this, "IdpCredential");
  }
  constructor(params) {
    super(
      "custom",
      "custom"
      /* ProviderId.CUSTOM */
    );
    this.params = params;
  }
  _getIdTokenResponse(auth2) {
    return signInWithIdp(auth2, this._buildIdpRequest());
  }
  _linkToIdToken(auth2, idToken) {
    return signInWithIdp(auth2, this._buildIdpRequest(idToken));
  }
  _getReauthenticationResolver(auth2) {
    return signInWithIdp(auth2, this._buildIdpRequest());
  }
  _buildIdpRequest(idToken) {
    const request = {
      requestUri: this.params.requestUri,
      sessionId: this.params.sessionId,
      postBody: this.params.postBody,
      tenantId: this.params.tenantId,
      pendingToken: this.params.pendingToken,
      returnSecureToken: true,
      returnIdpCredential: true
    };
    if (idToken) {
      request.idToken = idToken;
    }
    return request;
  }
}
function _signIn(params) {
  return _signInWithCredential(params.auth, new IdpCredential(params), params.bypassAuthState);
}
__name(_signIn, "_signIn");
function _reauth(params) {
  const { auth: auth2, user } = params;
  _assert(
    user,
    auth2,
    "internal-error"
    /* AuthErrorCode.INTERNAL_ERROR */
  );
  return _reauthenticate(user, new IdpCredential(params), params.bypassAuthState);
}
__name(_reauth, "_reauth");
async function _link(params) {
  const { auth: auth2, user } = params;
  _assert(
    user,
    auth2,
    "internal-error"
    /* AuthErrorCode.INTERNAL_ERROR */
  );
  return _link$1(user, new IdpCredential(params), params.bypassAuthState);
}
__name(_link, "_link");
/**
 * @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 AbstractPopupRedirectOperation {
  static {
    __name(this, "AbstractPopupRedirectOperation");
  }
  constructor(auth2, filter3, resolver, user, bypassAuthState = false) {
    this.auth = auth2;
    this.resolver = resolver;
    this.user = user;
    this.bypassAuthState = bypassAuthState;
    this.pendingPromise = null;
    this.eventManager = null;
    this.filter = Array.isArray(filter3) ? filter3 : [filter3];
  }
  execute() {
    return new Promise(async (resolve2, reject) => {
      this.pendingPromise = { resolve: resolve2, reject };
      try {
        this.eventManager = await this.resolver._initialize(this.auth);
        await this.onExecution();
        this.eventManager.registerConsumer(this);
      } catch (e2) {
        this.reject(e2);
      }
    });
  }
  async onAuthEvent(event) {
    const { urlResponse, sessionId, postBody, tenantId, error: error2, type } = event;
    if (error2) {
      this.reject(error2);
      return;
    }
    const params = {
      auth: this.auth,
      requestUri: urlResponse,
      sessionId,
      tenantId: tenantId || void 0,
      postBody: postBody || void 0,
      user: this.user,
      bypassAuthState: this.bypassAuthState
    };
    try {
      this.resolve(await this.getIdpTask(type)(params));
    } catch (e2) {
      this.reject(e2);
    }
  }
  onError(error2) {
    this.reject(error2);
  }
  getIdpTask(type) {
    switch (type) {
      case "signInViaPopup":
      case "signInViaRedirect":
        return _signIn;
      case "linkViaPopup":
      case "linkViaRedirect":
        return _link;
      case "reauthViaPopup":
      case "reauthViaRedirect":
        return _reauth;
      default:
        _fail(
          this.auth,
          "internal-error"
          /* AuthErrorCode.INTERNAL_ERROR */
        );
    }
  }
  resolve(cred) {
    debugAssert(this.pendingPromise, "Pending promise was never set");
    this.pendingPromise.resolve(cred);
    this.unregisterAndCleanUp();
  }
  reject(error2) {
    debugAssert(this.pendingPromise, "Pending promise was never set");
    this.pendingPromise.reject(error2);
    this.unregisterAndCleanUp();
  }
  unregisterAndCleanUp() {
    if (this.eventManager) {
      this.eventManager.unregisterConsumer(this);
    }
    this.pendingPromise = null;
    this.cleanUp();
  }
}
/**
 * @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 _POLL_WINDOW_CLOSE_TIMEOUT = new Delay(2e3, 1e4);
async function signInWithPopup(auth2, provider, resolver) {
  if (_isFirebaseServerApp(auth2.app)) {
    return Promise.reject(_createError(
      auth2,
      "operation-not-supported-in-this-environment"
      /* AuthErrorCode.OPERATION_NOT_SUPPORTED */
    ));
  }
  const authInternal = _castAuth(auth2);
  _assertInstanceOf(auth2, provider, FederatedAuthProvider);
  const resolverInternal = _withDefaultResolver(authInternal, resolver);
  const action = new PopupOperation(authInternal, "signInViaPopup", provider, resolverInternal);
  return action.executeNotNull();
}
__name(signInWithPopup, "signInWithPopup");
async function reauthenticateWithPopup(user, provider, resolver) {
  const userInternal = getModularInstance(user);
  if (_isFirebaseServerApp(userInternal.auth.app)) {
    return Promise.reject(_createError(
      userInternal.auth,
      "operation-not-supported-in-this-environment"
      /* AuthErrorCode.OPERATION_NOT_SUPPORTED */
    ));
  }
  _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);
  const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);
  const action = new PopupOperation(userInternal.auth, "reauthViaPopup", provider, resolverInternal, userInternal);
  return action.executeNotNull();
}
__name(reauthenticateWithPopup, "reauthenticateWithPopup");
async function linkWithPopup(user, provider, resolver) {
  const userInternal = getModularInstance(user);
  _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);
  const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);
  const action = new PopupOperation(userInternal.auth, "linkViaPopup", provider, resolverInternal, userInternal);
  return action.executeNotNull();
}
__name(linkWithPopup, "linkWithPopup");
class PopupOperation extends AbstractPopupRedirectOperation {
  static {
    __name(this, "PopupOperation");
  }
  constructor(auth2, filter3, provider, resolver, user) {
    super(auth2, filter3, resolver, user);
    this.provider = provider;
    this.authWindow = null;
    this.pollId = null;
    if (PopupOperation.currentPopupAction) {
      PopupOperation.currentPopupAction.cancel();
    }
    PopupOperation.currentPopupAction = this;
  }
  async executeNotNull() {
    const result = await this.execute();
    _assert(
      result,
      this.auth,
      "internal-error"
      /* AuthErrorCode.INTERNAL_ERROR */
    );
    return result;
  }
  async onExecution() {
    debugAssert(this.filter.length === 1, "Popup operations only handle one event");
    const eventId = _generateEventId();
    this.authWindow = await this.resolver._openPopup(
      this.auth,
      this.provider,
      this.filter[0],
      // There's always one, see constructor
      eventId
    );
    this.authWindow.associatedEvent = eventId;
    this.resolver._originValidation(this.auth).catch((e2) => {
      this.reject(e2);
    });
    this.resolver._isIframeWebStorageSupported(this.auth, (isSupported) => {
      if (!isSupported) {
        this.reject(_createError(
          this.auth,
          "web-storage-unsupported"
          /* AuthErrorCode.WEB_STORAGE_UNSUPPORTED */
        ));
      }
    });
    this.pollUserCancellation();
  }
  get eventId() {
    var _a2;
    return ((_a2 = this.authWindow) === null || _a2 === void 0 ? void 0 : _a2.associatedEvent) || null;
  }
  cancel() {
    this.reject(_createError(
      this.auth,
      "cancelled-popup-request"
      /* AuthErrorCode.EXPIRED_POPUP_REQUEST */
    ));
  }
  cleanUp() {
    if (this.authWindow) {
      this.authWindow.close();
    }
    if (this.pollId) {
      window.clearTimeout(this.pollId);
    }
    this.authWindow = null;
    this.pollId = null;
    PopupOperation.currentPopupAction = null;
  }
  pollUserCancellation() {
    const poll = /* @__PURE__ */ __name(() => {
      var _a2, _b;
      if ((_b = (_a2 = this.authWindow) === null || _a2 === void 0 ? void 0 : _a2.window) === null || _b === void 0 ? void 0 : _b.closed) {
        this.pollId = window.setTimeout(
          () => {
            this.pollId = null;
            this.reject(_createError(
              this.auth,
              "popup-closed-by-user"
              /* AuthErrorCode.POPUP_CLOSED_BY_USER */
            ));
          },
          8e3
          /* _Timeout.AUTH_EVENT */
        );
        return;
      }
      this.pollId = window.setTimeout(poll, _POLL_WINDOW_CLOSE_TIMEOUT.get());
    }, "poll");
    poll();
  }
}
PopupOperation.currentPopupAction = null;
/**
 * @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 PENDING_REDIRECT_KEY = "pendingRedirect";
const redirectOutcomeMap = /* @__PURE__ */ new Map();
class RedirectAction extends AbstractPopupRedirectOperation {
  static {
    __name(this, "RedirectAction");
  }
  constructor(auth2, resolver, bypassAuthState = false) {
    super(auth2, [
      "signInViaRedirect",
      "linkViaRedirect",
      "reauthViaRedirect",
      "unknown"
      /* AuthEventType.UNKNOWN */
    ], resolver, void 0, bypassAuthState);
    this.eventId = null;
  }
  /**
   * Override the execute function; if we already have a redirect result, then
   * just return it.
   */
  async execute() {
    let readyOutcome = redirectOutcomeMap.get(this.auth._key());
    if (!readyOutcome) {
      try {
        const hasPendingRedirect = await _getAndClearPendingRedirectStatus(this.resolver, this.auth);
        const result = hasPendingRedirect ? await super.execute() : null;
        readyOutcome = /* @__PURE__ */ __name(() => Promise.resolve(result), "readyOutcome");
      } catch (e2) {
        readyOutcome = /* @__PURE__ */ __name(() => Promise.reject(e2), "readyOutcome");
      }
      redirectOutcomeMap.set(this.auth._key(), readyOutcome);
    }
    if (!this.bypassAuthState) {
      redirectOutcomeMap.set(this.auth._key(), () => Promise.resolve(null));
    }
    return readyOutcome();
  }
  async onAuthEvent(event) {
    if (event.type === "signInViaRedirect") {
      return super.onAuthEvent(event);
    } else if (event.type === "unknown") {
      this.resolve(null);
      return;
    }
    if (event.eventId) {
      const user = await this.auth._redirectUserForId(event.eventId);
      if (user) {
        this.user = user;
        return super.onAuthEvent(event);
      } else {
        this.resolve(null);
      }
    }
  }
  async onExecution() {
  }
  cleanUp() {
  }
}
async function _getAndClearPendingRedirectStatus(resolver, auth2) {
  const key = pendingRedirectKey(auth2);
  const persistence = resolverPersistence(resolver);
  if (!await persistence._isAvailable()) {
    return false;
  }
  const hasPendingRedirect = await persistence._get(key) === "true";
  await persistence._remove(key);
  return hasPendingRedirect;
}
__name(_getAndClearPendingRedirectStatus, "_getAndClearPendingRedirectStatus");
async function _setPendingRedirectStatus(resolver, auth2) {
  return resolverPersistence(resolver)._set(pendingRedirectKey(auth2), "true");
}
__name(_setPendingRedirectStatus, "_setPendingRedirectStatus");
function _clearRedirectOutcomes() {
  redirectOutcomeMap.clear();
}
__name(_clearRedirectOutcomes, "_clearRedirectOutcomes");
function _overrideRedirectResult(auth2, result) {
  redirectOutcomeMap.set(auth2._key(), result);
}
__name(_overrideRedirectResult, "_overrideRedirectResult");
function resolverPersistence(resolver) {
  return _getInstance(resolver._redirectPersistence);
}
__name(resolverPersistence, "resolverPersistence");
function pendingRedirectKey(auth2) {
  return _persistenceKeyName(PENDING_REDIRECT_KEY, auth2.config.apiKey, auth2.name);
}
__name(pendingRedirectKey, "pendingRedirectKey");
/**
 * @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.
 */
function signInWithRedirect(auth2, provider, resolver) {
  return _signInWithRedirect(auth2, provider, resolver);
}
__name(signInWithRedirect, "signInWithRedirect");
async function _signInWithRedirect(auth2, provider, resolver) {
  if (_isFirebaseServerApp(auth2.app)) {
    return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth2));
  }
  const authInternal = _castAuth(auth2);
  _assertInstanceOf(auth2, provider, FederatedAuthProvider);
  await authInternal._initializationPromise;
  const resolverInternal = _withDefaultResolver(authInternal, resolver);
  await _setPendingRedirectStatus(resolverInternal, authInternal);
  return resolverInternal._openRedirect(
    authInternal,
    provider,
    "signInViaRedirect"
    /* AuthEventType.SIGN_IN_VIA_REDIRECT */
  );
}
__name(_signInWithRedirect, "_signInWithRedirect");
function reauthenticateWithRedirect(user, provider, resolver) {
  return _reauthenticateWithRedirect(user, provider, resolver);
}
__name(reauthenticateWithRedirect, "reauthenticateWithRedirect");
async function _reauthenticateWithRedirect(user, provider, resolver) {
  const userInternal = getModularInstance(user);
  _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);
  if (_isFirebaseServerApp(userInternal.auth.app)) {
    return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(userInternal.auth));
  }
  await userInternal.auth._initializationPromise;
  const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);
  await _setPendingRedirectStatus(resolverInternal, userInternal.auth);
  const eventId = await prepareUserForRedirect(userInternal);
  return resolverInternal._openRedirect(userInternal.auth, provider, "reauthViaRedirect", eventId);
}
__name(_reauthenticateWithRedirect, "_reauthenticateWithRedirect");
function linkWithRedirect(user, provider, resolver) {
  return _linkWithRedirect(user, provider, resolver);
}
__name(linkWithRedirect, "linkWithRedirect");
async function _linkWithRedirect(user, provider, resolver) {
  const userInternal = getModularInstance(user);
  _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);
  await userInternal.auth._initializationPromise;
  const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);
  await _assertLinkedStatus(false, userInternal, provider.providerId);
  await _setPendingRedirectStatus(resolverInternal, userInternal.auth);
  const eventId = await prepareUserForRedirect(userInternal);
  return resolverInternal._openRedirect(userInternal.auth, provider, "linkViaRedirect", eventId);
}
__name(_linkWithRedirect, "_linkWithRedirect");
async function getRedirectResult(auth2, resolver) {
  await _castAuth(auth2)._initializationPromise;
  return _getRedirectResult(auth2, resolver, false);
}
__name(getRedirectResult, "getRedirectResult");
async function _getRedirectResult(auth2, resolverExtern, bypassAuthState = false) {
  if (_isFirebaseServerApp(auth2.app)) {
    return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth2));
  }
  const authInternal = _castAuth(auth2);
  const resolver = _withDefaultResolver(authInternal, resolverExtern);
  const action = new RedirectAction(authInternal, resolver, bypassAuthState);
  const result = await action.execute();
  if (result && !bypassAuthState) {
    delete result.user._redirectEventId;
    await authInternal._persistUserIfCurrent(result.user);
    await authInternal._setRedirectUser(null, resolverExtern);
  }
  return result;
}
__name(_getRedirectResult, "_getRedirectResult");
async function prepareUserForRedirect(user) {
  const eventId = _generateEventId(`${user.uid}:::`);
  user._redirectEventId = eventId;
  await user.auth._setRedirectUser(user);
  await user.auth._persistUserIfCurrent(user);
  return eventId;
}
__name(prepareUserForRedirect, "prepareUserForRedirect");
/**
 * @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 EVENT_DUPLICATION_CACHE_DURATION_MS = 10 * 60 * 1e3;
class AuthEventManager {
  static {
    __name(this, "AuthEventManager");
  }
  constructor(auth2) {
    this.auth = auth2;
    this.cachedEventUids = /* @__PURE__ */ new Set();
    this.consumers = /* @__PURE__ */ new Set();
    this.queuedRedirectEvent = null;
    this.hasHandledPotentialRedirect = false;
    this.lastProcessedEventTime = Date.now();
  }
  registerConsumer(authEventConsumer) {
    this.consumers.add(authEventConsumer);
    if (this.queuedRedirectEvent && this.isEventForConsumer(this.queuedRedirectEvent, authEventConsumer)) {
      this.sendToConsumer(this.queuedRedirectEvent, authEventConsumer);
      this.saveEventToCache(this.queuedRedirectEvent);
      this.queuedRedirectEvent = null;
    }
  }
  unregisterConsumer(authEventConsumer) {
    this.consumers.delete(authEventConsumer);
  }
  onEvent(event) {
    if (this.hasEventBeenHandled(event)) {
      return false;
    }
    let handled = false;
    this.consumers.forEach((consumer) => {
      if (this.isEventForConsumer(event, consumer)) {
        handled = true;
        this.sendToConsumer(event, consumer);
        this.saveEventToCache(event);
      }
    });
    if (this.hasHandledPotentialRedirect || !isRedirectEvent(event)) {
      return handled;
    }
    this.hasHandledPotentialRedirect = true;
    if (!handled) {
      this.queuedRedirectEvent = event;
      handled = true;
    }
    return handled;
  }
  sendToConsumer(event, consumer) {
    var _a2;
    if (event.error && !isNullRedirectEvent(event)) {
      const code2 = ((_a2 = event.error.code) === null || _a2 === void 0 ? void 0 : _a2.split("auth/")[1]) || "internal-error";
      consumer.onError(_createError(this.auth, code2));
    } else {
      consumer.onAuthEvent(event);
    }
  }
  isEventForConsumer(event, consumer) {
    const eventIdMatches = consumer.eventId === null || !!event.eventId && event.eventId === consumer.eventId;
    return consumer.filter.includes(event.type) && eventIdMatches;
  }
  hasEventBeenHandled(event) {
    if (Date.now() - this.lastProcessedEventTime >= EVENT_DUPLICATION_CACHE_DURATION_MS) {
      this.cachedEventUids.clear();
    }
    return this.cachedEventUids.has(eventUid(event));
  }
  saveEventToCache(event) {
    this.cachedEventUids.add(eventUid(event));
    this.lastProcessedEventTime = Date.now();
  }
}
function eventUid(e2) {
  return [e2.type, e2.eventId, e2.sessionId, e2.tenantId].filter((v2) => v2).join("-");
}
__name(eventUid, "eventUid");
function isNullRedirectEvent({ type, error: error2 }) {
  return type === "unknown" && (error2 === null || error2 === void 0 ? void 0 : error2.code) === `auth/${"no-auth-event"}`;
}
__name(isNullRedirectEvent, "isNullRedirectEvent");
function isRedirectEvent(event) {
  switch (event.type) {
    case "signInViaRedirect":
    case "linkViaRedirect":
    case "reauthViaRedirect":
      return true;
    case "unknown":
      return isNullRedirectEvent(event);
    default:
      return false;
  }
}
__name(isRedirectEvent, "isRedirectEvent");
/**
 * @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.
 */
async function _getProjectConfig(auth2, request = {}) {
  return _performApiRequest(auth2, "GET", "/v1/projects", request);
}
__name(_getProjectConfig, "_getProjectConfig");
/**
 * @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 IP_ADDRESS_REGEX = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
const HTTP_REGEX = /^https?/;
async function _validateOrigin(auth2) {
  if (auth2.config.emulator) {
    return;
  }
  const { authorizedDomains } = await _getProjectConfig(auth2);
  for (const domain2 of authorizedDomains) {
    try {
      if (matchDomain(domain2)) {
        return;
      }
    } catch (_a2) {
    }
  }
  _fail(
    auth2,
    "unauthorized-domain"
    /* AuthErrorCode.INVALID_ORIGIN */
  );
}
__name(_validateOrigin, "_validateOrigin");
function matchDomain(expected) {
  const currentUrl = _getCurrentUrl();
  const { protocol, hostname } = new URL(currentUrl);
  if (expected.startsWith("chrome-extension://")) {
    const ceUrl = new URL(expected);
    if (ceUrl.hostname === "" && hostname === "") {
      return protocol === "chrome-extension:" && expected.replace("chrome-extension://", "") === currentUrl.replace("chrome-extension://", "");
    }
    return protocol === "chrome-extension:" && ceUrl.hostname === hostname;
  }
  if (!HTTP_REGEX.test(protocol)) {
    return false;
  }
  if (IP_ADDRESS_REGEX.test(expected)) {
    return hostname === expected;
  }
  const escapedDomainPattern = expected.replace(/\./g, "\\.");
  const re2 = new RegExp("^(.+\\." + escapedDomainPattern + "|" + escapedDomainPattern + ")$", "i");
  return re2.test(hostname);
}
__name(matchDomain, "matchDomain");
/**
 * @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 NETWORK_TIMEOUT = new Delay(3e4, 6e4);
function resetUnloadedGapiModules() {
  const beacon = _window().___jsl;
  if (beacon === null || beacon === void 0 ? void 0 : beacon.H) {
    for (const hint of Object.keys(beacon.H)) {
      beacon.H[hint].r = beacon.H[hint].r || [];
      beacon.H[hint].L = beacon.H[hint].L || [];
      beacon.H[hint].r = [...beacon.H[hint].L];
      if (beacon.CP) {
        for (let i2 = 0; i2 < beacon.CP.length; i2++) {
          beacon.CP[i2] = null;
        }
      }
    }
  }
}
__name(resetUnloadedGapiModules, "resetUnloadedGapiModules");
function loadGapi(auth2) {
  return new Promise((resolve2, reject) => {
    var _a2, _b, _c;
    function loadGapiIframe() {
      resetUnloadedGapiModules();
      gapi.load("gapi.iframes", {
        callback: /* @__PURE__ */ __name(() => {
          resolve2(gapi.iframes.getContext());
        }, "callback"),
        ontimeout: /* @__PURE__ */ __name(() => {
          resetUnloadedGapiModules();
          reject(_createError(
            auth2,
            "network-request-failed"
            /* AuthErrorCode.NETWORK_REQUEST_FAILED */
          ));
        }, "ontimeout"),
        timeout: NETWORK_TIMEOUT.get()
      });
    }
    __name(loadGapiIframe, "loadGapiIframe");
    if ((_b = (_a2 = _window().gapi) === null || _a2 === void 0 ? void 0 : _a2.iframes) === null || _b === void 0 ? void 0 : _b.Iframe) {
      resolve2(gapi.iframes.getContext());
    } else if (!!((_c = _window().gapi) === null || _c === void 0 ? void 0 : _c.load)) {
      loadGapiIframe();
    } else {
      const cbName = _generateCallbackName("iframefcb");
      _window()[cbName] = () => {
        if (!!gapi.load) {
          loadGapiIframe();
        } else {
          reject(_createError(
            auth2,
            "network-request-failed"
            /* AuthErrorCode.NETWORK_REQUEST_FAILED */
          ));
        }
      };
      return _loadJS(`${_gapiScriptUrl()}?onload=${cbName}`).catch((e2) => reject(e2));
    }
  }).catch((error2) => {
    cachedGApiLoader = null;
    throw error2;
  });
}
__name(loadGapi, "loadGapi");
let cachedGApiLoader = null;
function _loadGapi(auth2) {
  cachedGApiLoader = cachedGApiLoader || loadGapi(auth2);
  return cachedGApiLoader;
}
__name(_loadGapi, "_loadGapi");
/**
 * @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 PING_TIMEOUT = new Delay(5e3, 15e3);
const IFRAME_PATH = "__/auth/iframe";
const EMULATED_IFRAME_PATH = "emulator/auth/iframe";
const IFRAME_ATTRIBUTES = {
  style: {
    position: "absolute",
    top: "-100px",
    width: "1px",
    height: "1px"
  },
  "aria-hidden": "true",
  tabindex: "-1"
};
const EID_FROM_APIHOST = /* @__PURE__ */ new Map([
  ["identitytoolkit.googleapis.com", "p"],
  // production
  ["staging-identitytoolkit.sandbox.googleapis.com", "s"],
  // staging
  ["test-identitytoolkit.sandbox.googleapis.com", "t"]
  // test
]);
function getIframeUrl(auth2) {
  const config2 = auth2.config;
  _assert(
    config2.authDomain,
    auth2,
    "auth-domain-config-required"
    /* AuthErrorCode.MISSING_AUTH_DOMAIN */
  );
  const url = config2.emulator ? _emulatorUrl(config2, EMULATED_IFRAME_PATH) : `https://${auth2.config.authDomain}/${IFRAME_PATH}`;
  const params = {
    apiKey: config2.apiKey,
    appName: auth2.name,
    v: SDK_VERSION$1
  };
  const eid = EID_FROM_APIHOST.get(auth2.config.apiHost);
  if (eid) {
    params.eid = eid;
  }
  const frameworks = auth2._getFrameworks();
  if (frameworks.length) {
    params.fw = frameworks.join(",");
  }
  return `${url}?${querystring(params).slice(1)}`;
}
__name(getIframeUrl, "getIframeUrl");
async function _openIframe(auth2) {
  const context = await _loadGapi(auth2);
  const gapi2 = _window().gapi;
  _assert(
    gapi2,
    auth2,
    "internal-error"
    /* AuthErrorCode.INTERNAL_ERROR */
  );
  return context.open({
    where: document.body,
    url: getIframeUrl(auth2),
    messageHandlersFilter: gapi2.iframes.CROSS_ORIGIN_IFRAMES_FILTER,
    attributes: IFRAME_ATTRIBUTES,
    dontclear: true
  }, (iframe) => new Promise(async (resolve2, reject) => {
    await iframe.restyle({
      // Prevent iframe from closing on mouse out.
      setHideOnLeave: false
    });
    const networkError = _createError(
      auth2,
      "network-request-failed"
      /* AuthErrorCode.NETWORK_REQUEST_FAILED */
    );
    const networkErrorTimer = _window().setTimeout(() => {
      reject(networkError);
    }, PING_TIMEOUT.get());
    function clearTimerAndResolve() {
      _window().clearTimeout(networkErrorTimer);
      resolve2(iframe);
    }
    __name(clearTimerAndResolve, "clearTimerAndResolve");
    iframe.ping(clearTimerAndResolve).then(clearTimerAndResolve, () => {
      reject(networkError);
    });
  }));
}
__name(_openIframe, "_openIframe");
/**
 * @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 BASE_POPUP_OPTIONS = {
  location: "yes",
  resizable: "yes",
  statusbar: "yes",
  toolbar: "no"
};
const DEFAULT_WIDTH = 500;
const DEFAULT_HEIGHT = 600;
const TARGET_BLANK = "_blank";
const FIREFOX_EMPTY_URL = "http://localhost";
class AuthPopup {
  static {
    __name(this, "AuthPopup");
  }
  constructor(window2) {
    this.window = window2;
    this.associatedEvent = null;
  }
  close() {
    if (this.window) {
      try {
        this.window.close();
      } catch (e2) {
      }
    }
  }
}
function _open(auth2, url, name2, width2 = DEFAULT_WIDTH, height = DEFAULT_HEIGHT) {
  const top = Math.max((window.screen.availHeight - height) / 2, 0).toString();
  const left = Math.max((window.screen.availWidth - width2) / 2, 0).toString();
  let target = "";
  const options2 = Object.assign(Object.assign({}, BASE_POPUP_OPTIONS), {
    width: width2.toString(),
    height: height.toString(),
    top,
    left
  });
  const ua = getUA().toLowerCase();
  if (name2) {
    target = _isChromeIOS(ua) ? TARGET_BLANK : name2;
  }
  if (_isFirefox(ua)) {
    url = url || FIREFOX_EMPTY_URL;
    options2.scrollbars = "yes";
  }
  const optionsString = Object.entries(options2).reduce((accum, [key, value]) => `${accum}${key}=${value},`, "");
  if (_isIOSStandalone(ua) && target !== "_self") {
    openAsNewWindowIOS(url || "", target);
    return new AuthPopup(null);
  }
  const newWin = window.open(url || "", target, optionsString);
  _assert(
    newWin,
    auth2,
    "popup-blocked"
    /* AuthErrorCode.POPUP_BLOCKED */
  );
  try {
    newWin.focus();
  } catch (e2) {
  }
  return new AuthPopup(newWin);
}
__name(_open, "_open");
function openAsNewWindowIOS(url, target) {
  const el = document.createElement("a");
  el.href = url;
  el.target = target;
  const click2 = document.createEvent("MouseEvent");
  click2.initMouseEvent("click", true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 1, null);
  el.dispatchEvent(click2);
}
__name(openAsNewWindowIOS, "openAsNewWindowIOS");
/**
 * @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 WIDGET_PATH = "__/auth/handler";
const EMULATOR_WIDGET_PATH = "emulator/auth/handler";
const FIREBASE_APP_CHECK_FRAGMENT_ID = encodeURIComponent("fac");
async function _getRedirectUrl(auth2, provider, authType, redirectUrl, eventId, additionalParams) {
  _assert(
    auth2.config.authDomain,
    auth2,
    "auth-domain-config-required"
    /* AuthErrorCode.MISSING_AUTH_DOMAIN */
  );
  _assert(
    auth2.config.apiKey,
    auth2,
    "invalid-api-key"
    /* AuthErrorCode.INVALID_API_KEY */
  );
  const params = {
    apiKey: auth2.config.apiKey,
    appName: auth2.name,
    authType,
    redirectUrl,
    v: SDK_VERSION$1,
    eventId
  };
  if (provider instanceof FederatedAuthProvider) {
    provider.setDefaultLanguage(auth2.languageCode);
    params.providerId = provider.providerId || "";
    if (!isEmpty$4(provider.getCustomParameters())) {
      params.customParameters = JSON.stringify(provider.getCustomParameters());
    }
    for (const [key, value] of Object.entries(additionalParams || {})) {
      params[key] = value;
    }
  }
  if (provider instanceof BaseOAuthProvider) {
    const scopes = provider.getScopes().filter((scope) => scope !== "");
    if (scopes.length > 0) {
      params.scopes = scopes.join(",");
    }
  }
  if (auth2.tenantId) {
    params.tid = auth2.tenantId;
  }
  const paramsDict = params;
  for (const key of Object.keys(paramsDict)) {
    if (paramsDict[key] === void 0) {
      delete paramsDict[key];
    }
  }
  const appCheckToken = await auth2._getAppCheckToken();
  const appCheckTokenFragment = appCheckToken ? `#${FIREBASE_APP_CHECK_FRAGMENT_ID}=${encodeURIComponent(appCheckToken)}` : "";
  return `${getHandlerBase(auth2)}?${querystring(paramsDict).slice(1)}${appCheckTokenFragment}`;
}
__name(_getRedirectUrl, "_getRedirectUrl");
function getHandlerBase({ config: config2 }) {
  if (!config2.emulator) {
    return `https://${config2.authDomain}/${WIDGET_PATH}`;
  }
  return _emulatorUrl(config2, EMULATOR_WIDGET_PATH);
}
__name(getHandlerBase, "getHandlerBase");
/**
 * @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 WEB_STORAGE_SUPPORT_KEY = "webStorageSupport";
class BrowserPopupRedirectResolver {
  static {
    __name(this, "BrowserPopupRedirectResolver");
  }
  constructor() {
    this.eventManagers = {};
    this.iframes = {};
    this.originValidationPromises = {};
    this._redirectPersistence = browserSessionPersistence;
    this._completeRedirectFn = _getRedirectResult;
    this._overrideRedirectResult = _overrideRedirectResult;
  }
  // Wrapping in async even though we don't await anywhere in order
  // to make sure errors are raised as promise rejections
  async _openPopup(auth2, provider, authType, eventId) {
    var _a2;
    debugAssert((_a2 = this.eventManagers[auth2._key()]) === null || _a2 === void 0 ? void 0 : _a2.manager, "_initialize() not called before _openPopup()");
    const url = await _getRedirectUrl(auth2, provider, authType, _getCurrentUrl(), eventId);
    return _open(auth2, url, _generateEventId());
  }
  async _openRedirect(auth2, provider, authType, eventId) {
    await this._originValidation(auth2);
    const url = await _getRedirectUrl(auth2, provider, authType, _getCurrentUrl(), eventId);
    _setWindowLocation(url);
    return new Promise(() => {
    });
  }
  _initialize(auth2) {
    const key = auth2._key();
    if (this.eventManagers[key]) {
      const { manager: manager2, promise: promise2 } = this.eventManagers[key];
      if (manager2) {
        return Promise.resolve(manager2);
      } else {
        debugAssert(promise2, "If manager is not set, promise should be");
        return promise2;
      }
    }
    const promise = this.initAndGetManager(auth2);
    this.eventManagers[key] = { promise };
    promise.catch(() => {
      delete this.eventManagers[key];
    });
    return promise;
  }
  async initAndGetManager(auth2) {
    const iframe = await _openIframe(auth2);
    const manager2 = new AuthEventManager(auth2);
    iframe.register("authEvent", (iframeEvent) => {
      _assert(
        iframeEvent === null || iframeEvent === void 0 ? void 0 : iframeEvent.authEvent,
        auth2,
        "invalid-auth-event"
        /* AuthErrorCode.INVALID_AUTH_EVENT */
      );
      const handled = manager2.onEvent(iframeEvent.authEvent);
      return {
        status: handled ? "ACK" : "ERROR"
        /* GapiOutcome.ERROR */
      };
    }, gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER);
    this.eventManagers[auth2._key()] = { manager: manager2 };
    this.iframes[auth2._key()] = iframe;
    return manager2;
  }
  _isIframeWebStorageSupported(auth2, cb) {
    const iframe = this.iframes[auth2._key()];
    iframe.send(WEB_STORAGE_SUPPORT_KEY, { type: WEB_STORAGE_SUPPORT_KEY }, (result) => {
      var _a2;
      const isSupported = (_a2 = result === null || result === void 0 ? void 0 : result[0]) === null || _a2 === void 0 ? void 0 : _a2[WEB_STORAGE_SUPPORT_KEY];
      if (isSupported !== void 0) {
        cb(!!isSupported);
      }
      _fail(
        auth2,
        "internal-error"
        /* AuthErrorCode.INTERNAL_ERROR */
      );
    }, gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER);
  }
  _originValidation(auth2) {
    const key = auth2._key();
    if (!this.originValidationPromises[key]) {
      this.originValidationPromises[key] = _validateOrigin(auth2);
    }
    return this.originValidationPromises[key];
  }
  get _shouldInitProactively() {
    return _isMobileBrowser() || _isSafari() || _isIOS();
  }
}
const browserPopupRedirectResolver = BrowserPopupRedirectResolver;
class MultiFactorAssertionImpl {
  static {
    __name(this, "MultiFactorAssertionImpl");
  }
  constructor(factorId) {
    this.factorId = factorId;
  }
  _process(auth2, session, displayName) {
    switch (session.type) {
      case "enroll":
        return this._finalizeEnroll(auth2, session.credential, displayName);
      case "signin":
        return this._finalizeSignIn(auth2, session.credential);
      default:
        return debugFail("unexpected MultiFactorSessionType");
    }
  }
}
class PhoneMultiFactorAssertionImpl extends MultiFactorAssertionImpl {
  static {
    __name(this, "PhoneMultiFactorAssertionImpl");
  }
  constructor(credential) {
    super(
      "phone"
      /* FactorId.PHONE */
    );
    this.credential = credential;
  }
  /** @internal */
  static _fromCredential(credential) {
    return new PhoneMultiFactorAssertionImpl(credential);
  }
  /** @internal */
  _finalizeEnroll(auth2, idToken, displayName) {
    return finalizeEnrollPhoneMfa(auth2, {
      idToken,
      displayName,
      phoneVerificationInfo: this.credential._makeVerificationRequest()
    });
  }
  /** @internal */
  _finalizeSignIn(auth2, mfaPendingCredential) {
    return finalizeSignInPhoneMfa(auth2, {
      mfaPendingCredential,
      phoneVerificationInfo: this.credential._makeVerificationRequest()
    });
  }
}
class PhoneMultiFactorGenerator {
  static {
    __name(this, "PhoneMultiFactorGenerator");
  }
  constructor() {
  }
  /**
   * Provides a {@link PhoneMultiFactorAssertion} to confirm ownership of the phone second factor.
   *
   * @remarks
   * This method does not work in a Node.js environment.
   *
   * @param phoneAuthCredential - A credential provided by {@link PhoneAuthProvider.credential}.
   * @returns A {@link PhoneMultiFactorAssertion} which can be used with
   * {@link MultiFactorResolver.resolveSignIn}
   */
  static assertion(credential) {
    return PhoneMultiFactorAssertionImpl._fromCredential(credential);
  }
}
PhoneMultiFactorGenerator.FACTOR_ID = "phone";
class TotpMultiFactorGenerator {
  static {
    __name(this, "TotpMultiFactorGenerator");
  }
  /**
   * Provides a {@link TotpMultiFactorAssertion} to confirm ownership of
   * the TOTP (time-based one-time password) second factor.
   * This assertion is used to complete enrollment in TOTP second factor.
   *
   * @param secret A {@link TotpSecret} containing the shared secret key and other TOTP parameters.
   * @param oneTimePassword One-time password from TOTP App.
   * @returns A {@link TotpMultiFactorAssertion} which can be used with
   * {@link MultiFactorUser.enroll}.
   */
  static assertionForEnrollment(secret, oneTimePassword) {
    return TotpMultiFactorAssertionImpl._fromSecret(secret, oneTimePassword);
  }
  /**
   * Provides a {@link TotpMultiFactorAssertion} to confirm ownership of the TOTP second factor.
   * This assertion is used to complete signIn with TOTP as the second factor.
   *
   * @param enrollmentId identifies the enrolled TOTP second factor.
   * @param oneTimePassword One-time password from TOTP App.
   * @returns A {@link TotpMultiFactorAssertion} which can be used with
   * {@link MultiFactorResolver.resolveSignIn}.
   */
  static assertionForSignIn(enrollmentId, oneTimePassword) {
    return TotpMultiFactorAssertionImpl._fromEnrollmentId(enrollmentId, oneTimePassword);
  }
  /**
   * Returns a promise to {@link TotpSecret} which contains the TOTP shared secret key and other parameters.
   * Creates a TOTP secret as part of enrolling a TOTP second factor.
   * Used for generating a QR code URL or inputting into a TOTP app.
   * This method uses the auth instance corresponding to the user in the multiFactorSession.
   *
   * @param session The {@link MultiFactorSession} that the user is part of.
   * @returns A promise to {@link TotpSecret}.
   */
  static async generateSecret(session) {
    var _a2;
    const mfaSession = session;
    _assert(
      typeof ((_a2 = mfaSession.user) === null || _a2 === void 0 ? void 0 : _a2.auth) !== "undefined",
      "internal-error"
      /* AuthErrorCode.INTERNAL_ERROR */
    );
    const response = await startEnrollTotpMfa(mfaSession.user.auth, {
      idToken: mfaSession.credential,
      totpEnrollmentInfo: {}
    });
    return TotpSecret._fromStartTotpMfaEnrollmentResponse(response, mfaSession.user.auth);
  }
}
TotpMultiFactorGenerator.FACTOR_ID = "totp";
class TotpMultiFactorAssertionImpl extends MultiFactorAssertionImpl {
  static {
    __name(this, "TotpMultiFactorAssertionImpl");
  }
  constructor(otp, enrollmentId, secret) {
    super(
      "totp"
      /* FactorId.TOTP */
    );
    this.otp = otp;
    this.enrollmentId = enrollmentId;
    this.secret = secret;
  }
  /** @internal */
  static _fromSecret(secret, otp) {
    return new TotpMultiFactorAssertionImpl(otp, void 0, secret);
  }
  /** @internal */
  static _fromEnrollmentId(enrollmentId, otp) {
    return new TotpMultiFactorAssertionImpl(otp, enrollmentId);
  }
  /** @internal */
  async _finalizeEnroll(auth2, idToken, displayName) {
    _assert(
      typeof this.secret !== "undefined",
      auth2,
      "argument-error"
      /* AuthErrorCode.ARGUMENT_ERROR */
    );
    return finalizeEnrollTotpMfa(auth2, {
      idToken,
      displayName,
      totpVerificationInfo: this.secret._makeTotpVerificationInfo(this.otp)
    });
  }
  /** @internal */
  async _finalizeSignIn(auth2, mfaPendingCredential) {
    _assert(
      this.enrollmentId !== void 0 && this.otp !== void 0,
      auth2,
      "argument-error"
      /* AuthErrorCode.ARGUMENT_ERROR */
    );
    const totpVerificationInfo = { verificationCode: this.otp };
    return finalizeSignInTotpMfa(auth2, {
      mfaPendingCredential,
      mfaEnrollmentId: this.enrollmentId,
      totpVerificationInfo
    });
  }
}
class TotpSecret {
  static {
    __name(this, "TotpSecret");
  }
  // The public members are declared outside the constructor so the docs can be generated.
  constructor(secretKey, hashingAlgorithm, codeLength, codeIntervalSeconds, enrollmentCompletionDeadline, sessionInfo, auth2) {
    this.sessionInfo = sessionInfo;
    this.auth = auth2;
    this.secretKey = secretKey;
    this.hashingAlgorithm = hashingAlgorithm;
    this.codeLength = codeLength;
    this.codeIntervalSeconds = codeIntervalSeconds;
    this.enrollmentCompletionDeadline = enrollmentCompletionDeadline;
  }
  /** @internal */
  static _fromStartTotpMfaEnrollmentResponse(response, auth2) {
    return new TotpSecret(response.totpSessionInfo.sharedSecretKey, response.totpSessionInfo.hashingAlgorithm, response.totpSessionInfo.verificationCodeLength, response.totpSessionInfo.periodSec, new Date(response.totpSessionInfo.finalizeEnrollmentTime).toUTCString(), response.totpSessionInfo.sessionInfo, auth2);
  }
  /** @internal */
  _makeTotpVerificationInfo(otp) {
    return { sessionInfo: this.sessionInfo, verificationCode: otp };
  }
  /**
   * Returns a QR code URL as described in
   * https://github.com/google/google-authenticator/wiki/Key-Uri-Format
   * This can be displayed to the user as a QR code to be scanned into a TOTP app like Google Authenticator.
   * If the optional parameters are unspecified, an accountName of <userEmail> and issuer of <firebaseAppName> are used.
   *
   * @param accountName the name of the account/app along with a user identifier.
   * @param issuer issuer of the TOTP (likely the app name).
   * @returns A QR code URL string.
   */
  generateQrCodeUrl(accountName, issuer) {
    var _a2;
    let useDefaults = false;
    if (_isEmptyString(accountName) || _isEmptyString(issuer)) {
      useDefaults = true;
    }
    if (useDefaults) {
      if (_isEmptyString(accountName)) {
        accountName = ((_a2 = this.auth.currentUser) === null || _a2 === void 0 ? void 0 : _a2.email) || "unknownuser";
      }
      if (_isEmptyString(issuer)) {
        issuer = this.auth.name;
      }
    }
    return `otpauth://totp/${issuer}:${accountName}?secret=${this.secretKey}&issuer=${issuer}&algorithm=${this.hashingAlgorithm}&digits=${this.codeLength}`;
  }
}
function _isEmptyString(input) {
  return typeof input === "undefined" || (input === null || input === void 0 ? void 0 : input.length) === 0;
}
__name(_isEmptyString, "_isEmptyString");
var name$9 = "@firebase/auth";
var version$3 = "1.10.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.
 */
class AuthInterop {
  static {
    __name(this, "AuthInterop");
  }
  constructor(auth2) {
    this.auth = auth2;
    this.internalListeners = /* @__PURE__ */ new Map();
  }
  getUid() {
    var _a2;
    this.assertAuthConfigured();
    return ((_a2 = this.auth.currentUser) === null || _a2 === void 0 ? void 0 : _a2.uid) || null;
  }
  async getToken(forceRefresh) {
    this.assertAuthConfigured();
    await this.auth._initializationPromise;
    if (!this.auth.currentUser) {
      return null;
    }
    const accessToken = await this.auth.currentUser.getIdToken(forceRefresh);
    return { accessToken };
  }
  addAuthTokenListener(listener) {
    this.assertAuthConfigured();
    if (this.internalListeners.has(listener)) {
      return;
    }
    const unsubscribe = this.auth.onIdTokenChanged((user) => {
      listener((user === null || user === void 0 ? void 0 : user.stsTokenManager.accessToken) || null);
    });
    this.internalListeners.set(listener, unsubscribe);
    this.updateProactiveRefresh();
  }
  removeAuthTokenListener(listener) {
    this.assertAuthConfigured();
    const unsubscribe = this.internalListeners.get(listener);
    if (!unsubscribe) {
      return;
    }
    this.internalListeners.delete(listener);
    unsubscribe();
    this.updateProactiveRefresh();
  }
  assertAuthConfigured() {
    _assert(
      this.auth._initializationPromise,
      "dependent-sdk-initialized-before-auth"
      /* AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH */
    );
  }
  updateProactiveRefresh() {
    if (this.internalListeners.size > 0) {
      this.auth._startProactiveRefresh();
    } else {
      this.auth._stopProactiveRefresh();
    }
  }
}
/**
 * @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.
 */
function getVersionForPlatform(clientPlatform) {
  switch (clientPlatform) {
    case "Node":
      return "node";
    case "ReactNative":
      return "rn";
    case "Worker":
      return "webworker";
    case "Cordova":
      return "cordova";
    case "WebExtension":
      return "web-extension";
    default:
      return void 0;
  }
}
__name(getVersionForPlatform, "getVersionForPlatform");
function registerAuth(clientPlatform) {
  _registerComponent(new Component(
    "auth",
    (container, { options: deps }) => {
      const app2 = container.getProvider("app").getImmediate();
      const heartbeatServiceProvider = container.getProvider("heartbeat");
      const appCheckServiceProvider = container.getProvider("app-check-internal");
      const { apiKey, authDomain } = app2.options;
      _assert(apiKey && !apiKey.includes(":"), "invalid-api-key", { appName: app2.name });
      const config2 = {
        apiKey,
        authDomain,
        clientPlatform,
        apiHost: "identitytoolkit.googleapis.com",
        tokenApiHost: "securetoken.googleapis.com",
        apiScheme: "https",
        sdkClientVersion: _getClientVersion(clientPlatform)
      };
      const authInstance = new AuthImpl(app2, heartbeatServiceProvider, appCheckServiceProvider, config2);
      _initializeAuthInstance(authInstance, deps);
      return authInstance;
    },
    "PUBLIC"
    /* ComponentType.PUBLIC */
  ).setInstantiationMode(
    "EXPLICIT"
    /* InstantiationMode.EXPLICIT */
  ).setInstanceCreatedCallback((container, _instanceIdentifier, _instance) => {
    const authInternalProvider = container.getProvider(
      "auth-internal"
      /* _ComponentName.AUTH_INTERNAL */
    );
    authInternalProvider.initialize();
  }));
  _registerComponent(new Component(
    "auth-internal",
    (container) => {
      const auth2 = _castAuth(container.getProvider(
        "auth"
        /* _ComponentName.AUTH */
      ).getImmediate());
      return ((auth3) => new AuthInterop(auth3))(auth2);
    },
    "PRIVATE"
    /* ComponentType.PRIVATE */
  ).setInstantiationMode(
    "EXPLICIT"
    /* InstantiationMode.EXPLICIT */
  ));
  registerVersion(name$9, version$3, getVersionForPlatform(clientPlatform));
  registerVersion(name$9, version$3, "esm2017");
}
__name(registerAuth, "registerAuth");
/**
 * @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 DEFAULT_ID_TOKEN_MAX_AGE = 5 * 60;
const authIdTokenMaxAge = getExperimentalSetting("authIdTokenMaxAge") || DEFAULT_ID_TOKEN_MAX_AGE;
let lastPostedIdToken = null;
const mintCookieFactory = /* @__PURE__ */ __name((url) => async (user) => {
  const idTokenResult = user && await user.getIdTokenResult();
  const idTokenAge = idTokenResult && ((/* @__PURE__ */ new Date()).getTime() - Date.parse(idTokenResult.issuedAtTime)) / 1e3;
  if (idTokenAge && idTokenAge > authIdTokenMaxAge) {
    return;
  }
  const idToken = idTokenResult === null || idTokenResult === void 0 ? void 0 : idTokenResult.token;
  if (lastPostedIdToken === idToken) {
    return;
  }
  lastPostedIdToken = idToken;
  await fetch(url, {
    method: idToken ? "POST" : "DELETE",
    headers: idToken ? {
      "Authorization": `Bearer ${idToken}`
    } : {}
  });
}, "mintCookieFactory");
function getAuth(app2 = getApp()) {
  const provider = _getProvider(app2, "auth");
  if (provider.isInitialized()) {
    return provider.getImmediate();
  }
  const auth2 = initializeAuth(app2, {
    popupRedirectResolver: browserPopupRedirectResolver,
    persistence: [
      indexedDBLocalPersistence,
      browserLocalPersistence,
      browserSessionPersistence
    ]
  });
  const authTokenSyncPath = getExperimentalSetting("authTokenSyncURL");
  if (authTokenSyncPath && typeof isSecureContext === "boolean" && isSecureContext) {
    const authTokenSyncUrl = new URL(authTokenSyncPath, location.origin);
    if (location.origin === authTokenSyncUrl.origin) {
      const mintCookie = mintCookieFactory(authTokenSyncUrl.toString());
      beforeAuthStateChanged(auth2, mintCookie, () => mintCookie(auth2.currentUser));
      onIdTokenChanged(auth2, (user) => mintCookie(user));
    }
  }
  const authEmulatorHost = getDefaultEmulatorHost("auth");
  if (authEmulatorHost) {
    connectAuthEmulator(auth2, `http://${authEmulatorHost}`);
  }
  return auth2;
}
__name(getAuth, "getAuth");
function getScriptParentElement() {
  var _a2, _b;
  return (_b = (_a2 = document.getElementsByTagName("head")) === null || _a2 === void 0 ? void 0 : _a2[0]) !== null && _b !== void 0 ? _b : document;
}
__name(getScriptParentElement, "getScriptParentElement");
_setExternalJSProvider({
  loadJS(url) {
    return new Promise((resolve2, reject) => {
      const el = document.createElement("script");
      el.setAttribute("src", url);
      el.onload = resolve2;
      el.onerror = (e2) => {
        const error2 = _createError(
          "internal-error"
          /* AuthErrorCode.INTERNAL_ERROR */
        );
        error2.customData = e2;
        reject(error2);
      };
      el.type = "text/javascript";
      el.charset = "UTF-8";
      getScriptParentElement().appendChild(el);
    });
  },
  gapiScript: "https://apis.google.com/js/api.js",
  recaptchaV2Script: "https://www.google.com/recaptcha/api.js",
  recaptchaEnterpriseScript: "https://www.google.com/recaptcha/enterprise.js?render="
});
registerAuth(
  "Browser"
  /* ClientPlatform.BROWSER */
);
/**
 * @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 APP_CHECK_STATES = /* @__PURE__ */ new Map();
const DEFAULT_STATE = {
  activated: false,
  tokenObservers: []
};
const DEBUG_STATE = {
  initialized: false,
  enabled: false
};
function getStateReference(app2) {
  return APP_CHECK_STATES.get(app2) || Object.assign({}, DEFAULT_STATE);
}
__name(getStateReference, "getStateReference");
function setInitialState(app2, state) {
  APP_CHECK_STATES.set(app2, state);
  return APP_CHECK_STATES.get(app2);
}
__name(setInitialState, "setInitialState");
function getDebugState() {
  return DEBUG_STATE;
}
__name(getDebugState, "getDebugState");
/**
 * @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 BASE_ENDPOINT = "https://content-firebaseappcheck.googleapis.com/v1";
const EXCHANGE_RECAPTCHA_TOKEN_METHOD = "exchangeRecaptchaV3Token";
const EXCHANGE_RECAPTCHA_ENTERPRISE_TOKEN_METHOD = "exchangeRecaptchaEnterpriseToken";
const EXCHANGE_DEBUG_TOKEN_METHOD = "exchangeDebugToken";
const TOKEN_REFRESH_TIME = {
  /**
   * The offset time before token natural expiration to run the refresh.
   * This is currently 5 minutes.
   */
  OFFSET_DURATION: 5 * 60 * 1e3,
  /**
   * This is the first retrial wait after an error. This is currently
   * 30 seconds.
   */
  RETRIAL_MIN_WAIT: 30 * 1e3,
  /**
   * This is the maximum retrial wait, currently 16 minutes.
   */
  RETRIAL_MAX_WAIT: 16 * 60 * 1e3
};
const ONE_DAY = 24 * 60 * 60 * 1e3;
/**
 * @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 Refresher {
  static {
    __name(this, "Refresher");
  }
  constructor(operation, retryPolicy, getWaitDuration, lowerBound, upperBound) {
    this.operation = operation;
    this.retryPolicy = retryPolicy;
    this.getWaitDuration = getWaitDuration;
    this.lowerBound = lowerBound;
    this.upperBound = upperBound;
    this.pending = null;
    this.nextErrorWaitInterval = lowerBound;
    if (lowerBound > upperBound) {
      throw new Error("Proactive refresh lower bound greater than upper bound!");
    }
  }
  start() {
    this.nextErrorWaitInterval = this.lowerBound;
    this.process(true).catch(() => {
    });
  }
  stop() {
    if (this.pending) {
      this.pending.reject("cancelled");
      this.pending = null;
    }
  }
  isRunning() {
    return !!this.pending;
  }
  async process(hasSucceeded) {
    this.stop();
    try {
      this.pending = new Deferred();
      this.pending.promise.catch((_e2) => {
      });
      await sleep(this.getNextRun(hasSucceeded));
      this.pending.resolve();
      await this.pending.promise;
      this.pending = new Deferred();
      this.pending.promise.catch((_e2) => {
      });
      await this.operation();
      this.pending.resolve();
      await this.pending.promise;
      this.process(true).catch(() => {
      });
    } catch (error2) {
      if (this.retryPolicy(error2)) {
        this.process(false).catch(() => {
        });
      } else {
        this.stop();
      }
    }
  }
  getNextRun(hasSucceeded) {
    if (hasSucceeded) {
      this.nextErrorWaitInterval = this.lowerBound;
      return this.getWaitDuration();
    } else {
      const currentErrorWaitInterval = this.nextErrorWaitInterval;
      this.nextErrorWaitInterval *= 2;
      if (this.nextErrorWaitInterval > this.upperBound) {
        this.nextErrorWaitInterval = this.upperBound;
      }
      return currentErrorWaitInterval;
    }
  }
}
function sleep(ms) {
  return new Promise((resolve2) => {
    setTimeout(resolve2, ms);
  });
}
__name(sleep, "sleep");
/**
 * @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 ERRORS = {
  [
    "already-initialized"
    /* AppCheckError.ALREADY_INITIALIZED */
  ]: "You have already called initializeAppCheck() for FirebaseApp {$appName} with different options. To avoid this error, call initializeAppCheck() with the same options as when it was originally called. This will return the already initialized instance.",
  [
    "use-before-activation"
    /* AppCheckError.USE_BEFORE_ACTIVATION */
  ]: "App Check is being used before initializeAppCheck() is called for FirebaseApp {$appName}. Call initializeAppCheck() before instantiating other Firebase services.",
  [
    "fetch-network-error"
    /* AppCheckError.FETCH_NETWORK_ERROR */
  ]: "Fetch failed to connect to a network. Check Internet connection. Original error: {$originalErrorMessage}.",
  [
    "fetch-parse-error"
    /* AppCheckError.FETCH_PARSE_ERROR */
  ]: "Fetch client could not parse response. Original error: {$originalErrorMessage}.",
  [
    "fetch-status-error"
    /* AppCheckError.FETCH_STATUS_ERROR */
  ]: "Fetch server returned an HTTP error status. HTTP status: {$httpStatus}.",
  [
    "storage-open"
    /* AppCheckError.STORAGE_OPEN */
  ]: "Error thrown when opening storage. Original error: {$originalErrorMessage}.",
  [
    "storage-get"
    /* AppCheckError.STORAGE_GET */
  ]: "Error thrown when reading from storage. Original error: {$originalErrorMessage}.",
  [
    "storage-set"
    /* AppCheckError.STORAGE_WRITE */
  ]: "Error thrown when writing to storage. Original error: {$originalErrorMessage}.",
  [
    "recaptcha-error"
    /* AppCheckError.RECAPTCHA_ERROR */
  ]: "ReCAPTCHA error.",
  [
    "initial-throttle"
    /* AppCheckError.INITIAL_THROTTLE */
  ]: `{$httpStatus} error. Attempts allowed again after {$time}`,
  [
    "throttled"
    /* AppCheckError.THROTTLED */
  ]: `Requests throttled due to previous {$httpStatus} error. Attempts allowed again after {$time}`
};
const ERROR_FACTORY = new ErrorFactory("appCheck", "AppCheck", ERRORS);
/**
 * @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.
 */
function getRecaptcha(isEnterprise2 = false) {
  var _a2;
  if (isEnterprise2) {
    return (_a2 = self.grecaptcha) === null || _a2 === void 0 ? void 0 : _a2.enterprise;
  }
  return self.grecaptcha;
}
__name(getRecaptcha, "getRecaptcha");
function ensureActivated(app2) {
  if (!getStateReference(app2).activated) {
    throw ERROR_FACTORY.create("use-before-activation", {
      appName: app2.name
    });
  }
}
__name(ensureActivated, "ensureActivated");
function getDurationString(durationInMillis) {
  const totalSeconds = Math.round(durationInMillis / 1e3);
  const days = Math.floor(totalSeconds / (3600 * 24));
  const hours = Math.floor((totalSeconds - days * 3600 * 24) / 3600);
  const minutes = Math.floor((totalSeconds - days * 3600 * 24 - hours * 3600) / 60);
  const seconds = totalSeconds - days * 3600 * 24 - hours * 3600 - minutes * 60;
  let result = "";
  if (days) {
    result += pad(days) + "d:";
  }
  if (hours) {
    result += pad(hours) + "h:";
  }
  result += pad(minutes) + "m:" + pad(seconds) + "s";
  return result;
}
__name(getDurationString, "getDurationString");
function pad(value) {
  if (value === 0) {
    return "00";
  }
  return value >= 10 ? value.toString() : "0" + value;
}
__name(pad, "pad");
/**
 * @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.
 */
async function exchangeToken({ url, body }, heartbeatServiceProvider) {
  const headers = {
    "Content-Type": "application/json"
  };
  const heartbeatService = heartbeatServiceProvider.getImmediate({
    optional: true
  });
  if (heartbeatService) {
    const heartbeatsHeader = await heartbeatService.getHeartbeatsHeader();
    if (heartbeatsHeader) {
      headers["X-Firebase-Client"] = heartbeatsHeader;
    }
  }
  const options2 = {
    method: "POST",
    body: JSON.stringify(body),
    headers
  };
  let response;
  try {
    response = await fetch(url, options2);
  } catch (originalError) {
    throw ERROR_FACTORY.create("fetch-network-error", {
      originalErrorMessage: originalError === null || originalError === void 0 ? void 0 : originalError.message
    });
  }
  if (response.status !== 200) {
    throw ERROR_FACTORY.create("fetch-status-error", {
      httpStatus: response.status
    });
  }
  let responseBody;
  try {
    responseBody = await response.json();
  } catch (originalError) {
    throw ERROR_FACTORY.create("fetch-parse-error", {
      originalErrorMessage: originalError === null || originalError === void 0 ? void 0 : originalError.message
    });
  }
  const match2 = responseBody.ttl.match(/^([\d.]+)(s)$/);
  if (!match2 || !match2[2] || isNaN(Number(match2[1]))) {
    throw ERROR_FACTORY.create("fetch-parse-error", {
      originalErrorMessage: `ttl field (timeToLive) is not in standard Protobuf Duration format: ${responseBody.ttl}`
    });
  }
  const timeToLiveAsNumber = Number(match2[1]) * 1e3;
  const now2 = Date.now();
  return {
    token: responseBody.token,
    expireTimeMillis: now2 + timeToLiveAsNumber,
    issuedAtTimeMillis: now2
  };
}
__name(exchangeToken, "exchangeToken");
function getExchangeRecaptchaV3TokenRequest(app2, reCAPTCHAToken) {
  const { projectId, appId, apiKey } = app2.options;
  return {
    url: `${BASE_ENDPOINT}/projects/${projectId}/apps/${appId}:${EXCHANGE_RECAPTCHA_TOKEN_METHOD}?key=${apiKey}`,
    body: {
      "recaptcha_v3_token": reCAPTCHAToken
    }
  };
}
__name(getExchangeRecaptchaV3TokenRequest, "getExchangeRecaptchaV3TokenRequest");
function getExchangeRecaptchaEnterpriseTokenRequest(app2, reCAPTCHAToken) {
  const { projectId, appId, apiKey } = app2.options;
  return {
    url: `${BASE_ENDPOINT}/projects/${projectId}/apps/${appId}:${EXCHANGE_RECAPTCHA_ENTERPRISE_TOKEN_METHOD}?key=${apiKey}`,
    body: {
      "recaptcha_enterprise_token": reCAPTCHAToken
    }
  };
}
__name(getExchangeRecaptchaEnterpriseTokenRequest, "getExchangeRecaptchaEnterpriseTokenRequest");
function getExchangeDebugTokenRequest(app2, debugToken) {
  const { projectId, appId, apiKey } = app2.options;
  return {
    url: `${BASE_ENDPOINT}/projects/${projectId}/apps/${appId}:${EXCHANGE_DEBUG_TOKEN_METHOD}?key=${apiKey}`,
    body: {
      // eslint-disable-next-line
      debug_token: debugToken
    }
  };
}
__name(getExchangeDebugTokenRequest, "getExchangeDebugTokenRequest");
/**
 * @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 DB_NAME = "firebase-app-check-database";
const DB_VERSION = 1;
const STORE_NAME = "firebase-app-check-store";
const DEBUG_TOKEN_KEY = "debug-token";
let dbPromise = null;
function getDBPromise() {
  if (dbPromise) {
    return dbPromise;
  }
  dbPromise = new Promise((resolve2, reject) => {
    try {
      const request = indexedDB.open(DB_NAME, DB_VERSION);
      request.onsuccess = (event) => {
        resolve2(event.target.result);
      };
      request.onerror = (event) => {
        var _a2;
        reject(ERROR_FACTORY.create("storage-open", {
          originalErrorMessage: (_a2 = event.target.error) === null || _a2 === void 0 ? void 0 : _a2.message
        }));
      };
      request.onupgradeneeded = (event) => {
        const db = event.target.result;
        switch (event.oldVersion) {
          case 0:
            db.createObjectStore(STORE_NAME, {
              keyPath: "compositeKey"
            });
        }
      };
    } catch (e2) {
      reject(ERROR_FACTORY.create("storage-open", {
        originalErrorMessage: e2 === null || e2 === void 0 ? void 0 : e2.message
      }));
    }
  });
  return dbPromise;
}
__name(getDBPromise, "getDBPromise");
function readTokenFromIndexedDB(app2) {
  return read(computeKey(app2));
}
__name(readTokenFromIndexedDB, "readTokenFromIndexedDB");
function writeTokenToIndexedDB(app2, token) {
  return write(computeKey(app2), token);
}
__name(writeTokenToIndexedDB, "writeTokenToIndexedDB");
function writeDebugTokenToIndexedDB(token) {
  return write(DEBUG_TOKEN_KEY, token);
}
__name(writeDebugTokenToIndexedDB, "writeDebugTokenToIndexedDB");
function readDebugTokenFromIndexedDB() {
  return read(DEBUG_TOKEN_KEY);
}
__name(readDebugTokenFromIndexedDB, "readDebugTokenFromIndexedDB");
async function write(key, value) {
  const db = await getDBPromise();
  const transaction = db.transaction(STORE_NAME, "readwrite");
  const store = transaction.objectStore(STORE_NAME);
  const request = store.put({
    compositeKey: key,
    value
  });
  return new Promise((resolve2, reject) => {
    request.onsuccess = (_event) => {
      resolve2();
    };
    transaction.onerror = (event) => {
      var _a2;
      reject(ERROR_FACTORY.create("storage-set", {
        originalErrorMessage: (_a2 = event.target.error) === null || _a2 === void 0 ? void 0 : _a2.message
      }));
    };
  });
}
__name(write, "write");
async function read(key) {
  const db = await getDBPromise();
  const transaction = db.transaction(STORE_NAME, "readonly");
  const store = transaction.objectStore(STORE_NAME);
  const request = store.get(key);
  return new Promise((resolve2, reject) => {
    request.onsuccess = (event) => {
      const result = event.target.result;
      if (result) {
        resolve2(result.value);
      } else {
        resolve2(void 0);
      }
    };
    transaction.onerror = (event) => {
      var _a2;
      reject(ERROR_FACTORY.create("storage-get", {
        originalErrorMessage: (_a2 = event.target.error) === null || _a2 === void 0 ? void 0 : _a2.message
      }));
    };
  });
}
__name(read, "read");
function computeKey(app2) {
  return `${app2.options.appId}-${app2.name}`;
}
__name(computeKey, "computeKey");
/**
 * @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 logger$2 = new Logger("@firebase/app-check");
/**
 * @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.
 */
async function readTokenFromStorage(app2) {
  if (isIndexedDBAvailable()) {
    let token = void 0;
    try {
      token = await readTokenFromIndexedDB(app2);
    } catch (e2) {
      logger$2.warn(`Failed to read token from IndexedDB. Error: ${e2}`);
    }
    return token;
  }
  return void 0;
}
__name(readTokenFromStorage, "readTokenFromStorage");
function writeTokenToStorage(app2, token) {
  if (isIndexedDBAvailable()) {
    return writeTokenToIndexedDB(app2, token).catch((e2) => {
      logger$2.warn(`Failed to write token to IndexedDB. Error: ${e2}`);
    });
  }
  return Promise.resolve();
}
__name(writeTokenToStorage, "writeTokenToStorage");
async function readOrCreateDebugTokenFromStorage() {
  let existingDebugToken = void 0;
  try {
    existingDebugToken = await readDebugTokenFromIndexedDB();
  } catch (_e2) {
  }
  if (!existingDebugToken) {
    const newToken = crypto.randomUUID();
    writeDebugTokenToIndexedDB(newToken).catch((e2) => logger$2.warn(`Failed to persist debug token to IndexedDB. Error: ${e2}`));
    return newToken;
  } else {
    return existingDebugToken;
  }
}
__name(readOrCreateDebugTokenFromStorage, "readOrCreateDebugTokenFromStorage");
/**
 * @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.
 */
function isDebugMode() {
  const debugState = getDebugState();
  return debugState.enabled;
}
__name(isDebugMode, "isDebugMode");
async function getDebugToken() {
  const state = getDebugState();
  if (state.enabled && state.token) {
    return state.token.promise;
  } else {
    throw Error(`
            Can't get debug token in production mode.
        `);
  }
}
__name(getDebugToken, "getDebugToken");
function initializeDebugMode() {
  const globals = getGlobal();
  const debugState = getDebugState();
  debugState.initialized = true;
  if (typeof globals.FIREBASE_APPCHECK_DEBUG_TOKEN !== "string" && globals.FIREBASE_APPCHECK_DEBUG_TOKEN !== true) {
    return;
  }
  debugState.enabled = true;
  const deferredToken = new Deferred();
  debugState.token = deferredToken;
  if (typeof globals.FIREBASE_APPCHECK_DEBUG_TOKEN === "string") {
    deferredToken.resolve(globals.FIREBASE_APPCHECK_DEBUG_TOKEN);
  } else {
    deferredToken.resolve(readOrCreateDebugTokenFromStorage());
  }
}
__name(initializeDebugMode, "initializeDebugMode");
/**
 * @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 defaultTokenErrorData = { error: "UNKNOWN_ERROR" };
function formatDummyToken(tokenErrorData) {
  return base64.encodeString(
    JSON.stringify(tokenErrorData),
    /* webSafe= */
    false
  );
}
__name(formatDummyToken, "formatDummyToken");
async function getToken$2(appCheck, forceRefresh = false, shouldLogErrors = false) {
  const app2 = appCheck.app;
  ensureActivated(app2);
  const state = getStateReference(app2);
  let token = state.token;
  let error2 = void 0;
  if (token && !isValid$1(token)) {
    state.token = void 0;
    token = void 0;
  }
  if (!token) {
    const cachedToken = await state.cachedTokenPromise;
    if (cachedToken) {
      if (isValid$1(cachedToken)) {
        token = cachedToken;
      } else {
        await writeTokenToStorage(app2, void 0);
      }
    }
  }
  if (!forceRefresh && token && isValid$1(token)) {
    return {
      token: token.token
    };
  }
  let shouldCallListeners = false;
  if (isDebugMode()) {
    try {
      if (!state.exchangeTokenPromise) {
        state.exchangeTokenPromise = exchangeToken(getExchangeDebugTokenRequest(app2, await getDebugToken()), appCheck.heartbeatServiceProvider).finally(() => {
          state.exchangeTokenPromise = void 0;
        });
        shouldCallListeners = true;
      }
      const tokenFromDebugExchange = await state.exchangeTokenPromise;
      await writeTokenToStorage(app2, tokenFromDebugExchange);
      state.token = tokenFromDebugExchange;
      return { token: tokenFromDebugExchange.token };
    } catch (e2) {
      if (e2.code === `appCheck/${"throttled"}` || e2.code === `appCheck/${"initial-throttle"}`) {
        logger$2.warn(e2.message);
      } else if (shouldLogErrors) {
        logger$2.error(e2);
      }
      return makeDummyTokenResult(e2);
    }
  }
  try {
    if (!state.exchangeTokenPromise) {
      state.exchangeTokenPromise = state.provider.getToken().finally(() => {
        state.exchangeTokenPromise = void 0;
      });
      shouldCallListeners = true;
    }
    token = await getStateReference(app2).exchangeTokenPromise;
  } catch (e2) {
    if (e2.code === `appCheck/${"throttled"}` || e2.code === `appCheck/${"initial-throttle"}`) {
      logger$2.warn(e2.message);
    } else if (shouldLogErrors) {
      logger$2.error(e2);
    }
    error2 = e2;
  }
  let interopTokenResult;
  if (!token) {
    interopTokenResult = makeDummyTokenResult(error2);
  } else if (error2) {
    if (isValid$1(token)) {
      interopTokenResult = {
        token: token.token,
        internalError: error2
      };
    } else {
      interopTokenResult = makeDummyTokenResult(error2);
    }
  } else {
    interopTokenResult = {
      token: token.token
    };
    state.token = token;
    await writeTokenToStorage(app2, token);
  }
  if (shouldCallListeners) {
    notifyTokenListeners(app2, interopTokenResult);
  }
  return interopTokenResult;
}
__name(getToken$2, "getToken$2");
async function getLimitedUseToken$1(appCheck) {
  const app2 = appCheck.app;
  ensureActivated(app2);
  const { provider } = getStateReference(app2);
  if (isDebugMode()) {
    const debugToken = await getDebugToken();
    const { token } = await exchangeToken(getExchangeDebugTokenRequest(app2, debugToken), appCheck.heartbeatServiceProvider);
    return { token };
  } else {
    const { token } = await provider.getToken();
    return { token };
  }
}
__name(getLimitedUseToken$1, "getLimitedUseToken$1");
function addTokenListener(appCheck, type, listener, onError) {
  const { app: app2 } = appCheck;
  const state = getStateReference(app2);
  const tokenObserver = {
    next: listener,
    error: onError,
    type
  };
  state.tokenObservers = [...state.tokenObservers, tokenObserver];
  if (state.token && isValid$1(state.token)) {
    const validToken = state.token;
    Promise.resolve().then(() => {
      listener({ token: validToken.token });
      initTokenRefresher(appCheck);
    }).catch(() => {
    });
  }
  void state.cachedTokenPromise.then(() => initTokenRefresher(appCheck));
}
__name(addTokenListener, "addTokenListener");
function removeTokenListener(app2, listener) {
  const state = getStateReference(app2);
  const newObservers = state.tokenObservers.filter((tokenObserver) => tokenObserver.next !== listener);
  if (newObservers.length === 0 && state.tokenRefresher && state.tokenRefresher.isRunning()) {
    state.tokenRefresher.stop();
  }
  state.tokenObservers = newObservers;
}
__name(removeTokenListener, "removeTokenListener");
function initTokenRefresher(appCheck) {
  const { app: app2 } = appCheck;
  const state = getStateReference(app2);
  let refresher = state.tokenRefresher;
  if (!refresher) {
    refresher = createTokenRefresher(appCheck);
    state.tokenRefresher = refresher;
  }
  if (!refresher.isRunning() && state.isTokenAutoRefreshEnabled) {
    refresher.start();
  }
}
__name(initTokenRefresher, "initTokenRefresher");
function createTokenRefresher(appCheck) {
  const { app: app2 } = appCheck;
  return new Refresher(
    // Keep in mind when this fails for any reason other than the ones
    // for which we should retry, it will effectively stop the proactive refresh.
    async () => {
      const state = getStateReference(app2);
      let result;
      if (!state.token) {
        result = await getToken$2(appCheck);
      } else {
        result = await getToken$2(appCheck, true);
      }
      if (result.error) {
        throw result.error;
      }
      if (result.internalError) {
        throw result.internalError;
      }
    },
    () => {
      return true;
    },
    () => {
      const state = getStateReference(app2);
      if (state.token) {
        let nextRefreshTimeMillis = state.token.issuedAtTimeMillis + (state.token.expireTimeMillis - state.token.issuedAtTimeMillis) * 0.5 + 5 * 60 * 1e3;
        const latestAllowableRefresh = state.token.expireTimeMillis - 5 * 60 * 1e3;
        nextRefreshTimeMillis = Math.min(nextRefreshTimeMillis, latestAllowableRefresh);
        return Math.max(0, nextRefreshTimeMillis - Date.now());
      } else {
        return 0;
      }
    },
    TOKEN_REFRESH_TIME.RETRIAL_MIN_WAIT,
    TOKEN_REFRESH_TIME.RETRIAL_MAX_WAIT
  );
}
__name(createTokenRefresher, "createTokenRefresher");
function notifyTokenListeners(app2, token) {
  const observers = getStateReference(app2).tokenObservers;
  for (const observer of observers) {
    try {
      if (observer.type === "EXTERNAL" && token.error != null) {
        observer.error(token.error);
      } else {
        observer.next(token);
      }
    } catch (e2) {
    }
  }
}
__name(notifyTokenListeners, "notifyTokenListeners");
function isValid$1(token) {
  return token.expireTimeMillis - Date.now() > 0;
}
__name(isValid$1, "isValid$1");
function makeDummyTokenResult(error2) {
  return {
    token: formatDummyToken(defaultTokenErrorData),
    error: error2
  };
}
__name(makeDummyTokenResult, "makeDummyTokenResult");
/**
 * @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 AppCheckService {
  static {
    __name(this, "AppCheckService");
  }
  constructor(app2, heartbeatServiceProvider) {
    this.app = app2;
    this.heartbeatServiceProvider = heartbeatServiceProvider;
  }
  _delete() {
    const { tokenObservers } = getStateReference(this.app);
    for (const tokenObserver of tokenObservers) {
      removeTokenListener(this.app, tokenObserver.next);
    }
    return Promise.resolve();
  }
}
function factory$1(app2, heartbeatServiceProvider) {
  return new AppCheckService(app2, heartbeatServiceProvider);
}
__name(factory$1, "factory$1");
function internalFactory(appCheck) {
  return {
    getToken: /* @__PURE__ */ __name((forceRefresh) => getToken$2(appCheck, forceRefresh), "getToken"),
    getLimitedUseToken: /* @__PURE__ */ __name(() => getLimitedUseToken$1(appCheck), "getLimitedUseToken"),
    addTokenListener: /* @__PURE__ */ __name((listener) => addTokenListener(appCheck, "INTERNAL", listener), "addTokenListener"),
    removeTokenListener: /* @__PURE__ */ __name((listener) => removeTokenListener(appCheck.app, listener), "removeTokenListener")
  };
}
__name(internalFactory, "internalFactory");
const name$8 = "@firebase/app-check";
const version$2 = "0.8.13";
/**
 * @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 RECAPTCHA_URL = "https://www.google.com/recaptcha/api.js";
const RECAPTCHA_ENTERPRISE_URL = "https://www.google.com/recaptcha/enterprise.js";
function initializeV3(app2, siteKey) {
  const initialized = new Deferred();
  const state = getStateReference(app2);
  state.reCAPTCHAState = { initialized };
  const divId = makeDiv(app2);
  const grecaptcha = getRecaptcha(false);
  if (!grecaptcha) {
    loadReCAPTCHAV3Script(() => {
      const grecaptcha2 = getRecaptcha(false);
      if (!grecaptcha2) {
        throw new Error("no recaptcha");
      }
      queueWidgetRender(app2, siteKey, grecaptcha2, divId, initialized);
    });
  } else {
    queueWidgetRender(app2, siteKey, grecaptcha, divId, initialized);
  }
  return initialized.promise;
}
__name(initializeV3, "initializeV3");
function initializeEnterprise(app2, siteKey) {
  const initialized = new Deferred();
  const state = getStateReference(app2);
  state.reCAPTCHAState = { initialized };
  const divId = makeDiv(app2);
  const grecaptcha = getRecaptcha(true);
  if (!grecaptcha) {
    loadReCAPTCHAEnterpriseScript(() => {
      const grecaptcha2 = getRecaptcha(true);
      if (!grecaptcha2) {
        throw new Error("no recaptcha");
      }
      queueWidgetRender(app2, siteKey, grecaptcha2, divId, initialized);
    });
  } else {
    queueWidgetRender(app2, siteKey, grecaptcha, divId, initialized);
  }
  return initialized.promise;
}
__name(initializeEnterprise, "initializeEnterprise");
function queueWidgetRender(app2, siteKey, grecaptcha, container, initialized) {
  grecaptcha.ready(() => {
    renderInvisibleWidget(app2, siteKey, grecaptcha, container);
    initialized.resolve(grecaptcha);
  });
}
__name(queueWidgetRender, "queueWidgetRender");
function makeDiv(app2) {
  const divId = `fire_app_check_${app2.name}`;
  const invisibleDiv = document.createElement("div");
  invisibleDiv.id = divId;
  invisibleDiv.style.display = "none";
  document.body.appendChild(invisibleDiv);
  return divId;
}
__name(makeDiv, "makeDiv");
async function getToken$1(app2) {
  ensureActivated(app2);
  const reCAPTCHAState = getStateReference(app2).reCAPTCHAState;
  const recaptcha = await reCAPTCHAState.initialized.promise;
  return new Promise((resolve2, _reject) => {
    const reCAPTCHAState2 = getStateReference(app2).reCAPTCHAState;
    recaptcha.ready(() => {
      resolve2(
        // widgetId is guaranteed to be available if reCAPTCHAState.initialized.promise resolved.
        recaptcha.execute(reCAPTCHAState2.widgetId, {
          action: "fire_app_check"
        })
      );
    });
  });
}
__name(getToken$1, "getToken$1");
function renderInvisibleWidget(app2, siteKey, grecaptcha, container) {
  const widgetId = grecaptcha.render(container, {
    sitekey: siteKey,
    size: "invisible",
    // Success callback - set state
    callback: /* @__PURE__ */ __name(() => {
      getStateReference(app2).reCAPTCHAState.succeeded = true;
    }, "callback"),
    // Failure callback - set state
    "error-callback": /* @__PURE__ */ __name(() => {
      getStateReference(app2).reCAPTCHAState.succeeded = false;
    }, "error-callback")
  });
  const state = getStateReference(app2);
  state.reCAPTCHAState = Object.assign(Object.assign({}, state.reCAPTCHAState), {
    // state.reCAPTCHAState is set in the initialize()
    widgetId
  });
}
__name(renderInvisibleWidget, "renderInvisibleWidget");
function loadReCAPTCHAV3Script(onload) {
  const script2 = document.createElement("script");
  script2.src = RECAPTCHA_URL;
  script2.onload = onload;
  document.head.appendChild(script2);
}
__name(loadReCAPTCHAV3Script, "loadReCAPTCHAV3Script");
function loadReCAPTCHAEnterpriseScript(onload) {
  const script2 = document.createElement("script");
  script2.src = RECAPTCHA_ENTERPRISE_URL;
  script2.onload = onload;
  document.head.appendChild(script2);
}
__name(loadReCAPTCHAEnterpriseScript, "loadReCAPTCHAEnterpriseScript");
/**
 * @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 ReCaptchaV3Provider {
  static {
    __name(this, "ReCaptchaV3Provider");
  }
  /**
   * Create a ReCaptchaV3Provider instance.
   * @param siteKey - ReCAPTCHA V3 siteKey.
   */
  constructor(_siteKey) {
    this._siteKey = _siteKey;
    this._throttleData = null;
  }
  /**
   * Returns an App Check token.
   * @internal
   */
  async getToken() {
    var _a2, _b, _c;
    throwIfThrottled(this._throttleData);
    const attestedClaimsToken = await getToken$1(this._app).catch((_e2) => {
      throw ERROR_FACTORY.create(
        "recaptcha-error"
        /* AppCheckError.RECAPTCHA_ERROR */
      );
    });
    if (!((_a2 = getStateReference(this._app).reCAPTCHAState) === null || _a2 === void 0 ? void 0 : _a2.succeeded)) {
      throw ERROR_FACTORY.create(
        "recaptcha-error"
        /* AppCheckError.RECAPTCHA_ERROR */
      );
    }
    let result;
    try {
      result = await exchangeToken(getExchangeRecaptchaV3TokenRequest(this._app, attestedClaimsToken), this._heartbeatServiceProvider);
    } catch (e2) {
      if ((_b = e2.code) === null || _b === void 0 ? void 0 : _b.includes(
        "fetch-status-error"
        /* AppCheckError.FETCH_STATUS_ERROR */
      )) {
        this._throttleData = setBackoff(Number((_c = e2.customData) === null || _c === void 0 ? void 0 : _c.httpStatus), this._throttleData);
        throw ERROR_FACTORY.create("initial-throttle", {
          time: getDurationString(this._throttleData.allowRequestsAfter - Date.now()),
          httpStatus: this._throttleData.httpStatus
        });
      } else {
        throw e2;
      }
    }
    this._throttleData = null;
    return result;
  }
  /**
   * @internal
   */
  initialize(app2) {
    this._app = app2;
    this._heartbeatServiceProvider = _getProvider(app2, "heartbeat");
    initializeV3(app2, this._siteKey).catch(() => {
    });
  }
  /**
   * @internal
   */
  isEqual(otherProvider) {
    if (otherProvider instanceof ReCaptchaV3Provider) {
      return this._siteKey === otherProvider._siteKey;
    } else {
      return false;
    }
  }
}
class ReCaptchaEnterpriseProvider {
  static {
    __name(this, "ReCaptchaEnterpriseProvider");
  }
  /**
   * Create a ReCaptchaEnterpriseProvider instance.
   * @param siteKey - reCAPTCHA Enterprise score-based site key.
   */
  constructor(_siteKey) {
    this._siteKey = _siteKey;
    this._throttleData = null;
  }
  /**
   * Returns an App Check token.
   * @internal
   */
  async getToken() {
    var _a2, _b, _c;
    throwIfThrottled(this._throttleData);
    const attestedClaimsToken = await getToken$1(this._app).catch((_e2) => {
      throw ERROR_FACTORY.create(
        "recaptcha-error"
        /* AppCheckError.RECAPTCHA_ERROR */
      );
    });
    if (!((_a2 = getStateReference(this._app).reCAPTCHAState) === null || _a2 === void 0 ? void 0 : _a2.succeeded)) {
      throw ERROR_FACTORY.create(
        "recaptcha-error"
        /* AppCheckError.RECAPTCHA_ERROR */
      );
    }
    let result;
    try {
      result = await exchangeToken(getExchangeRecaptchaEnterpriseTokenRequest(this._app, attestedClaimsToken), this._heartbeatServiceProvider);
    } catch (e2) {
      if ((_b = e2.code) === null || _b === void 0 ? void 0 : _b.includes(
        "fetch-status-error"
        /* AppCheckError.FETCH_STATUS_ERROR */
      )) {
        this._throttleData = setBackoff(Number((_c = e2.customData) === null || _c === void 0 ? void 0 : _c.httpStatus), this._throttleData);
        throw ERROR_FACTORY.create("initial-throttle", {
          time: getDurationString(this._throttleData.allowRequestsAfter - Date.now()),
          httpStatus: this._throttleData.httpStatus
        });
      } else {
        throw e2;
      }
    }
    this._throttleData = null;
    return result;
  }
  /**
   * @internal
   */
  initialize(app2) {
    this._app = app2;
    this._heartbeatServiceProvider = _getProvider(app2, "heartbeat");
    initializeEnterprise(app2, this._siteKey).catch(() => {
    });
  }
  /**
   * @internal
   */
  isEqual(otherProvider) {
    if (otherProvider instanceof ReCaptchaEnterpriseProvider) {
      return this._siteKey === otherProvider._siteKey;
    } else {
      return false;
    }
  }
}
class CustomProvider {
  static {
    __name(this, "CustomProvider");
  }
  constructor(_customProviderOptions) {
    this._customProviderOptions = _customProviderOptions;
  }
  /**
   * @internal
   */
  async getToken() {
    const customToken = await this._customProviderOptions.getToken();
    const issuedAtTimeSeconds = issuedAtTime(customToken.token);
    const issuedAtTimeMillis = issuedAtTimeSeconds !== null && issuedAtTimeSeconds < Date.now() && issuedAtTimeSeconds > 0 ? issuedAtTimeSeconds * 1e3 : Date.now();
    return Object.assign(Object.assign({}, customToken), { issuedAtTimeMillis });
  }
  /**
   * @internal
   */
  initialize(app2) {
    this._app = app2;
  }
  /**
   * @internal
   */
  isEqual(otherProvider) {
    if (otherProvider instanceof CustomProvider) {
      return this._customProviderOptions.getToken.toString() === otherProvider._customProviderOptions.getToken.toString();
    } else {
      return false;
    }
  }
}
function setBackoff(httpStatus, throttleData) {
  if (httpStatus === 404 || httpStatus === 403) {
    return {
      backoffCount: 1,
      allowRequestsAfter: Date.now() + ONE_DAY,
      httpStatus
    };
  } else {
    const backoffCount = throttleData ? throttleData.backoffCount : 0;
    const backoffMillis = calculateBackoffMillis(backoffCount, 1e3, 2);
    return {
      backoffCount: backoffCount + 1,
      allowRequestsAfter: Date.now() + backoffMillis,
      httpStatus
    };
  }
}
__name(setBackoff, "setBackoff");
function throwIfThrottled(throttleData) {
  if (throttleData) {
    if (Date.now() - throttleData.allowRequestsAfter <= 0) {
      throw ERROR_FACTORY.create("throttled", {
        time: getDurationString(throttleData.allowRequestsAfter - Date.now()),
        httpStatus: throttleData.httpStatus
      });
    }
  }
}
__name(throwIfThrottled, "throwIfThrottled");
/**
 * @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.
 */
function initializeAppCheck(app2 = getApp(), options2) {
  app2 = getModularInstance(app2);
  const provider = _getProvider(app2, "app-check");
  if (!getDebugState().initialized) {
    initializeDebugMode();
  }
  if (isDebugMode()) {
    void getDebugToken().then((token) => (
      // Not using logger because I don't think we ever want this accidentally hidden.
      console.log(`App Check debug token: ${token}. You will need to add it to your app's App Check settings in the Firebase console for it to work.`)
    ));
  }
  if (provider.isInitialized()) {
    const existingInstance = provider.getImmediate();
    const initialOptions = provider.getOptions();
    if (initialOptions.isTokenAutoRefreshEnabled === options2.isTokenAutoRefreshEnabled && initialOptions.provider.isEqual(options2.provider)) {
      return existingInstance;
    } else {
      throw ERROR_FACTORY.create("already-initialized", {
        appName: app2.name
      });
    }
  }
  const appCheck = provider.initialize({ options: options2 });
  _activate(app2, options2.provider, options2.isTokenAutoRefreshEnabled);
  if (getStateReference(app2).isTokenAutoRefreshEnabled) {
    addTokenListener(appCheck, "INTERNAL", () => {
    });
  }
  return appCheck;
}
__name(initializeAppCheck, "initializeAppCheck");
function _activate(app2, provider, isTokenAutoRefreshEnabled) {
  const state = setInitialState(app2, Object.assign({}, DEFAULT_STATE));
  state.activated = true;
  state.provider = provider;
  state.cachedTokenPromise = readTokenFromStorage(app2).then((cachedToken) => {
    if (cachedToken && isValid$1(cachedToken)) {
      state.token = cachedToken;
      notifyTokenListeners(app2, { token: cachedToken.token });
    }
    return cachedToken;
  });
  state.isTokenAutoRefreshEnabled = isTokenAutoRefreshEnabled === void 0 ? app2.automaticDataCollectionEnabled : isTokenAutoRefreshEnabled;
  state.provider.initialize(app2);
}
__name(_activate, "_activate");
function setTokenAutoRefreshEnabled(appCheckInstance, isTokenAutoRefreshEnabled) {
  const app2 = appCheckInstance.app;
  const state = getStateReference(app2);
  if (state.tokenRefresher) {
    if (isTokenAutoRefreshEnabled === true) {
      state.tokenRefresher.start();
    } else {
      state.tokenRefresher.stop();
    }
  }
  state.isTokenAutoRefreshEnabled = isTokenAutoRefreshEnabled;
}
__name(setTokenAutoRefreshEnabled, "setTokenAutoRefreshEnabled");
async function getToken(appCheckInstance, forceRefresh) {
  const result = await getToken$2(appCheckInstance, forceRefresh);
  if (result.error) {
    throw result.error;
  }
  if (result.internalError) {
    throw result.internalError;
  }
  return { token: result.token };
}
__name(getToken, "getToken");
function getLimitedUseToken(appCheckInstance) {
  return getLimitedUseToken$1(appCheckInstance);
}
__name(getLimitedUseToken, "getLimitedUseToken");
function onTokenChanged(appCheckInstance, onNextOrObserver, onError, onCompletion) {
  let nextFn = /* @__PURE__ */ __name(() => {
  }, "nextFn");
  let errorFn = /* @__PURE__ */ __name(() => {
  }, "errorFn");
  if (onNextOrObserver.next != null) {
    nextFn = onNextOrObserver.next.bind(onNextOrObserver);
  } else {
    nextFn = onNextOrObserver;
  }
  if (onNextOrObserver.error != null) {
    errorFn = onNextOrObserver.error.bind(onNextOrObserver);
  } else if (onError) {
    errorFn = onError;
  }
  addTokenListener(appCheckInstance, "EXTERNAL", nextFn, errorFn);
  return () => removeTokenListener(appCheckInstance.app, nextFn);
}
__name(onTokenChanged, "onTokenChanged");
const APP_CHECK_NAME = "app-check";
const APP_CHECK_NAME_INTERNAL = "app-check-internal";
function registerAppCheck() {
  _registerComponent(new Component(
    APP_CHECK_NAME,
    (container) => {
      const app2 = container.getProvider("app").getImmediate();
      const heartbeatServiceProvider = container.getProvider("heartbeat");
      return factory$1(app2, heartbeatServiceProvider);
    },
    "PUBLIC"
    /* ComponentType.PUBLIC */
  ).setInstantiationMode(
    "EXPLICIT"
    /* InstantiationMode.EXPLICIT */
  ).setInstanceCreatedCallback((container, _identifier, _appcheckService) => {
    container.getProvider(APP_CHECK_NAME_INTERNAL).initialize();
  }));
  _registerComponent(new Component(
    APP_CHECK_NAME_INTERNAL,
    (container) => {
      const appCheck = container.getProvider("app-check").getImmediate();
      return internalFactory(appCheck);
    },
    "PUBLIC"
    /* ComponentType.PUBLIC */
  ).setInstantiationMode(
    "EXPLICIT"
    /* InstantiationMode.EXPLICIT */
  ));
  registerVersion(name$8, version$2);
}
__name(registerAppCheck, "registerAppCheck");
registerAppCheck();
const _FirebaseAppInjectionKey = Symbol("firebaseApp");
function useFirebaseApp(name2) {
  return getCurrentInstance() && inject(
    _FirebaseAppInjectionKey,
    // avoid the inject not found warning
    null
  ) || getApp(name2);
}
__name(useFirebaseApp, "useFirebaseApp");
const noop$4 = /* @__PURE__ */ __name(() => {
}, "noop$4");
const isClient$2 = typeof window !== "undefined";
function walkGet(obj, path) {
  return path.split(".").reduce((target, key) => target && target[key], obj);
}
__name(walkGet, "walkGet");
function walkSet(obj, path, value) {
  const keys2 = ("" + path).split(".");
  const key = keys2.pop();
  const target = keys2.reduce(
    (target2, key2) => (
      // @ts-expect-error: FIXME: maybe
      target2 && target2[key2]
    ),
    obj
  );
  if (target == null)
    return;
  return Array.isArray(target) ? target.splice(Number(key), 1, value) : (
    // @ts-expect-error: FIXME: maybe
    target[key] = //
    value
  );
}
__name(walkSet, "walkSet");
function isObject$d(o2) {
  return !!o2 && typeof o2 === "object";
}
__name(isObject$d, "isObject$d");
const ObjectPrototype = Object.prototype;
function isPOJO(obj) {
  return isObject$d(obj) && Object.getPrototypeOf(obj) === ObjectPrototype;
}
__name(isPOJO, "isPOJO");
function isDocumentRef(o2) {
  return isObject$d(o2) && o2.type === "document";
}
__name(isDocumentRef, "isDocumentRef");
function isCollectionRef(o2) {
  return isObject$d(o2) && o2.type === "collection";
}
__name(isCollectionRef, "isCollectionRef");
function isFirestoreDataReference(source) {
  return isDocumentRef(source) || isCollectionRef(source);
}
__name(isFirestoreDataReference, "isFirestoreDataReference");
function isFirestoreQuery(source) {
  return isObject$d(source) && source.type === "query";
}
__name(isFirestoreQuery, "isFirestoreQuery");
function isDatabaseReference(source) {
  return isObject$d(source) && "ref" in source;
}
__name(isDatabaseReference, "isDatabaseReference");
function isStorageReference(source) {
  return isObject$d(source) && typeof source.bucket === "string";
}
__name(isStorageReference, "isStorageReference");
function callOnceWithArg(fn, argFn) {
  let called;
  return () => {
    if (!called) {
      called = true;
      return fn(argFn());
    }
  };
}
__name(callOnceWithArg, "callOnceWithArg");
const ssrContextKey = Symbol.for("v-scx");
function useIsSSR() {
  const instance = getCurrentInstance();
  return !!(isVue2 ? instance && // @ts-expect-error: Vue 2 only API
  instance.proxy.$isServer : inject(ssrContextKey, 0));
}
__name(useIsSSR, "useIsSSR");
function checkWrittenTarget(data, fnName) {
  if (Object.getOwnPropertyDescriptor(data, "data")?.get?.() === data) {
    console.warn(`[VueFire] the passed "options.target" is already the returned value of "${fnName}". If you want to subscribe to a different data source, pass a reactive variable to "${fnName}" instead:
https://vuefire.vuejs.org/guide/realtime-data.html#declarative-realtime-data
This will FAIL in production.`);
    return true;
  }
  return false;
}
__name(checkWrittenTarget, "checkWrittenTarget");
const scopeMap = /* @__PURE__ */ new WeakMap();
function getGlobalScope(firebaseApp2, app2) {
  if (!scopeMap.has(firebaseApp2)) {
    const scope = effectScope(true);
    scopeMap.set(firebaseApp2, scope);
    const { unmount } = app2;
    app2.unmount = () => {
      unmount.call(app2);
      scope.stop();
      scopeMap.delete(firebaseApp2);
    };
  }
  return scopeMap.get(firebaseApp2);
}
__name(getGlobalScope, "getGlobalScope");
const authUserMap = /* @__PURE__ */ new WeakMap();
function useCurrentUser$1(name2) {
  if (false) {
    throw new Error(
      `[VueFire] useCurrentUser() called before the VueFireAuth module was added to the VueFire plugin. This will fail in production.`
    );
  }
  return authUserMap.get(useFirebaseApp(name2));
}
__name(useCurrentUser$1, "useCurrentUser$1");
function useIsCurrentUserLoaded(name2) {
  const currentUser = useCurrentUser$1(name2);
  return computed(() => currentUser.value !== void 0);
}
__name(useIsCurrentUserLoaded, "useIsCurrentUserLoaded");
function updateCurrentUserProfile(profile) {
  return getCurrentUser().then((user) => {
    if (user) {
      return updateProfile(user, profile).then(() => user.reload());
    }
  });
}
__name(updateCurrentUserProfile, "updateCurrentUserProfile");
const initialUserMap = /* @__PURE__ */ new WeakMap();
function _setInitialUser(firebaseApp2, user) {
  initialUserMap.set(firebaseApp2, user);
}
__name(_setInitialUser, "_setInitialUser");
function _getCurrentUserState(name2) {
  const firebaseApp2 = useFirebaseApp(name2);
  if (!initialUserMap.has(firebaseApp2)) {
    let resolve2;
    const promise = new Promise((_resolve) => {
      resolve2 = _resolve;
    });
    const userState = [
      promise,
      (user) => {
        initialUserMap.set(firebaseApp2, user);
        resolve2(user.value);
      }
    ];
    initialUserMap.set(firebaseApp2, userState);
  }
  return initialUserMap.get(firebaseApp2);
}
__name(_getCurrentUserState, "_getCurrentUserState");
function getCurrentUser(name2) {
  const userOrPromise = _getCurrentUserState(name2);
  return Array.isArray(userOrPromise) ? userOrPromise[0] : Promise.resolve(userOrPromise.value);
}
__name(getCurrentUser, "getCurrentUser");
function setupOnAuthStateChanged(user, auth2) {
  onIdTokenChanged(auth2, (userData) => {
    const userOrPromise = _getCurrentUserState();
    user.value = userData;
    if (Array.isArray(userOrPromise)) {
      userOrPromise[1](user);
    }
  });
}
__name(setupOnAuthStateChanged, "setupOnAuthStateChanged");
const AppCheckTokenInjectSymbol = Symbol("app-check-token");
function useAppCheckToken() {
  return inject(AppCheckTokenInjectSymbol);
}
__name(useAppCheckToken, "useAppCheckToken");
function VueFireAppCheck(options2) {
  return (firebaseApp2, app2) => {
    if (!isClient$2)
      return;
    const token = getGlobalScope(firebaseApp2, app2).run(() => ref$3());
    app2.provide(AppCheckTokenInjectSymbol, token);
    if (options2.debug) {
      self.FIREBASE_APPCHECK_DEBUG_TOKEN = options2.debug;
    }
    const appCheck = initializeAppCheck(firebaseApp2, options2);
    onTokenChanged(appCheck, (newToken) => {
      token.value = newToken.token;
    });
    AppCheckMap.set(firebaseApp2, appCheck);
  };
}
__name(VueFireAppCheck, "VueFireAppCheck");
const AppCheckMap = /* @__PURE__ */ new WeakMap();
function useAppCheck(name2) {
  return AppCheckMap.get(useFirebaseApp(name2));
}
__name(useAppCheck, "useAppCheck");
var define_process_env_default = {};
const name$7 = "@firebase/database";
const version$1 = "1.0.14";
/**
 * @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;
}
__name(setSDKVersion, "setSDKVersion");
/**
 * @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 {
  static {
    __name(this, "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$2(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 {
  static {
    __name(this, "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$2(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 = /* @__PURE__ */ __name(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();
}, "createStoragefor");
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 Logger("@firebase/database");
const LUIDGenerator = /* @__PURE__ */ function() {
  let id2 = 1;
  return function() {
    return id2++;
  };
}();
const sha1 = /* @__PURE__ */ __name(function(str) {
  const utf8Bytes = stringToByteArray(str);
  const sha12 = new Sha1();
  sha12.update(utf8Bytes);
  const sha1Bytes = sha12.digest();
  return base64.encodeByteArray(sha1Bytes);
}, "sha1");
const buildLogMessage_ = /* @__PURE__ */ __name(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$2(arg);
    } else {
      message += arg;
    }
    message += " ";
  }
  return message;
}, "buildLogMessage_");
let logger$1 = null;
let firstLog_ = true;
const enableLogging$1 = /* @__PURE__ */ __name(function(logger_, persistent) {
  assert$1(!persistent || logger_ === true || logger_ === false, "Can't turn on custom loggers persistently.");
  if (logger_ === true) {
    logClient.logLevel = LogLevel.VERBOSE;
    logger$1 = logClient.log.bind(logClient);
    if (persistent) {
      SessionStorage.set("logging_enabled", true);
    }
  } else if (typeof logger_ === "function") {
    logger$1 = logger_;
  } else {
    logger$1 = null;
    SessionStorage.remove("logging_enabled");
  }
}, "enableLogging$1");
const log$1 = /* @__PURE__ */ __name(function(...varArgs) {
  if (firstLog_ === true) {
    firstLog_ = false;
    if (logger$1 === null && SessionStorage.get("logging_enabled") === true) {
      enableLogging$1(true);
    }
  }
  if (logger$1) {
    const message = buildLogMessage_.apply(null, varArgs);
    logger$1(message);
  }
}, "log$1");
const logWrapper = /* @__PURE__ */ __name(function(prefix) {
  return function(...varArgs) {
    log$1(prefix, ...varArgs);
  };
}, "logWrapper");
const error$1 = /* @__PURE__ */ __name(function(...varArgs) {
  const message = "FIREBASE INTERNAL ERROR: " + buildLogMessage_(...varArgs);
  logClient.error(message);
}, "error$1");
const fatal = /* @__PURE__ */ __name(function(...varArgs) {
  const message = `FIREBASE FATAL ERROR: ${buildLogMessage_(...varArgs)}`;
  logClient.error(message);
  throw new Error(message);
}, "fatal");
const warn$2 = /* @__PURE__ */ __name(function(...varArgs) {
  const message = "FIREBASE WARNING: " + buildLogMessage_(...varArgs);
  logClient.warn(message);
}, "warn$2");
const warnIfPageIsSecure = /* @__PURE__ */ __name(function() {
  if (typeof window !== "undefined" && window.location && window.location.protocol && window.location.protocol.indexOf("https:") !== -1) {
    warn$2("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().");
  }
}, "warnIfPageIsSecure");
const isInvalidJSONNumber = /* @__PURE__ */ __name(function(data) {
  return typeof data === "number" && (data !== data || // NaN
  data === Number.POSITIVE_INFINITY || data === Number.NEGATIVE_INFINITY);
}, "isInvalidJSONNumber");
const executeWhenDOMReady = /* @__PURE__ */ __name(function(fn) {
  if (isNodeSdk() || document.readyState === "complete") {
    fn();
  } else {
    let called = false;
    const wrappedFn = /* @__PURE__ */ __name(function() {
      if (!document.body) {
        setTimeout(wrappedFn, Math.floor(10));
        return;
      }
      if (!called) {
        called = true;
        fn();
      }
    }, "wrappedFn");
    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);
    }
  }
}, "executeWhenDOMReady");
const MIN_NAME = "[MIN_NAME]";
const MAX_NAME = "[MAX_NAME]";
const nameCompare = /* @__PURE__ */ __name(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;
    }
  }
}, "nameCompare");
const stringCompare = /* @__PURE__ */ __name(function(a2, b2) {
  if (a2 === b2) {
    return 0;
  } else if (a2 < b2) {
    return -1;
  } else {
    return 1;
  }
}, "stringCompare");
const requireKey = /* @__PURE__ */ __name(function(key, obj) {
  if (obj && key in obj) {
    return obj[key];
  } else {
    throw new Error("Missing required key (" + key + ") in object: " + stringify$2(obj));
  }
}, "requireKey");
const ObjectToUniqueKey = /* @__PURE__ */ __name(function(obj) {
  if (typeof obj !== "object" || obj === null) {
    return stringify$2(obj);
  }
  const keys2 = [];
  for (const k2 in obj) {
    keys2.push(k2);
  }
  keys2.sort();
  let key = "{";
  for (let i2 = 0; i2 < keys2.length; i2++) {
    if (i2 !== 0) {
      key += ",";
    }
    key += stringify$2(keys2[i2]);
    key += ":";
    key += ObjectToUniqueKey(obj[keys2[i2]]);
  }
  key += "}";
  return key;
}, "ObjectToUniqueKey");
const splitStringBySize = /* @__PURE__ */ __name(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;
}, "splitStringBySize");
function each(obj, fn) {
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      fn(key, obj[key]);
    }
  }
}
__name(each, "each");
const doubleToIEEE754String = /* @__PURE__ */ __name(function(v2) {
  assert$1(!isInvalidJSONNumber(v2), "Invalid JSON number");
  const ebits = 11, fbits = 52;
  const bias = (1 << ebits - 1) - 1;
  let s2, e2, f2, ln, 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)) {
      ln = Math.min(Math.floor(Math.log(v2) / Math.LN2), bias);
      e2 = ln + bias;
      f2 = Math.round(v2 * Math.pow(2, fbits - ln) - 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();
}, "doubleToIEEE754String");
const isChromeExtensionContentScript = /* @__PURE__ */ __name(function() {
  return !!(typeof window === "object" && window["chrome"] && window["chrome"]["extension"] && !/^chrome/.test(window.location.href));
}, "isChromeExtensionContentScript");
const isWindowsStoreApp = /* @__PURE__ */ __name(function() {
  return typeof Windows === "object" && typeof Windows.UI === "object";
}, "isWindowsStoreApp");
function errorForServerCode(code2, query2) {
  let reason = "Unknown Error";
  if (code2 === "too_big") {
    reason = "The data requested exceeds the maximum size that can be accessed with a single request.";
  } else if (code2 === "permission_denied") {
    reason = "Client doesn't have permission to access the desired data.";
  } else if (code2 === "unavailable") {
    reason = "The service is unavailable";
  }
  const error2 = new Error(code2 + " at " + query2._path.toString() + ": " + reason);
  error2.code = code2.toUpperCase();
  return error2;
}
__name(errorForServerCode, "errorForServerCode");
const INTEGER_REGEXP_ = new RegExp("^-?(0*)\\d{1,10}$");
const INTEGER_32_MIN = -2147483648;
const INTEGER_32_MAX = 2147483647;
const tryParseInt = /* @__PURE__ */ __name(function(str) {
  if (INTEGER_REGEXP_.test(str)) {
    const intVal = Number(str);
    if (intVal >= INTEGER_32_MIN && intVal <= INTEGER_32_MAX) {
      return intVal;
    }
  }
  return null;
}, "tryParseInt");
const exceptionGuard = /* @__PURE__ */ __name(function(fn) {
  try {
    fn();
  } catch (e2) {
    setTimeout(() => {
      const stack = e2.stack || "";
      warn$2("Exception was thrown by user callback.", stack);
      throw e2;
    }, Math.floor(0));
  }
}, "exceptionGuard");
const beingCrawled = /* @__PURE__ */ __name(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;
}, "beingCrawled");
const setTimeoutNonBlocking = /* @__PURE__ */ __name(function(fn, time) {
  const timeout = setTimeout(fn, 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;
}, "setTimeoutNonBlocking");
/**
 * @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 {
  static {
    __name(this, "AppCheckTokenProvider");
  }
  constructor(app2, appCheckProvider) {
    this.appCheckProvider = appCheckProvider;
    this.appName = app2.name;
    if (_isFirebaseServerApp(app2) && app2.settings.appCheckToken) {
      this.serverAppAppCheckToken = app2.settings.appCheckToken;
    }
    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.serverAppAppCheckToken) {
      if (forceRefresh) {
        throw new Error("Attempted reuse of `FirebaseServerApp.appCheckToken` after previous usage failed.");
      }
      return Promise.resolve({ token: this.serverAppAppCheckToken });
    }
    if (!this.appCheck) {
      return new Promise((resolve2, reject) => {
        setTimeout(() => {
          if (this.appCheck) {
            this.getToken(forceRefresh).then(resolve2, reject);
          } else {
            resolve2(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$2(`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 {
  static {
    __name(this, "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((auth2) => this.auth_ = auth2);
    }
  }
  getToken(forceRefresh) {
    if (!this.auth_) {
      return new Promise((resolve2, reject) => {
        setTimeout(() => {
          if (this.auth_) {
            this.getToken(forceRefresh).then(resolve2, reject);
          } else {
            resolve2(null);
          }
        }, 0);
      });
    }
    return this.auth_.getToken(forceRefresh).catch((error2) => {
      if (error2 && error2.code === "auth/token-not-initialized") {
        log$1("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((auth2) => auth2.addAuthTokenListener(listener));
    }
  }
  removeTokenChangeListener(listener) {
    this.authProvider_.get().then((auth2) => auth2.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$2(errorMessage);
  }
}
class EmulatorTokenProvider {
  static {
    __name(this, "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 {
  static {
    __name(this, "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, emulatorOptions = null) {
    this.secure = secure;
    this.namespace = namespace;
    this.webSocketOnly = webSocketOnly;
    this.nodeAdmin = nodeAdmin;
    this.persistenceKey = persistenceKey;
    this.includeNamespaceInQueryParams = includeNamespaceInQueryParams;
    this.isUsingEmulator = isUsingEmulator;
    this.emulatorOptions = emulatorOptions;
    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 query2 = this.includeNamespaceInQueryParams ? `?ns=${this.namespace}` : "";
    return `${protocol}${this.host}/${query2}`;
  }
}
function repoInfoNeedsQueryParam(repoInfo) {
  return repoInfo.host !== repoInfo.internalHost || repoInfo.isCustomHost() || repoInfo.includeNamespaceInQueryParams;
}
__name(repoInfoNeedsQueryParam, "repoInfoNeedsQueryParam");
function repoInfoConnectionURL(repoInfo, type, params) {
  assert$1(typeof type === "string", "typeof type must == string");
  assert$1(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("&");
}
__name(repoInfoConnectionURL, "repoInfoConnectionURL");
/**
 * @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 {
  static {
    __name(this, "StatsCollection");
  }
  constructor() {
    this.counters_ = {};
  }
  incrementCounter(name2, amount = 1) {
    if (!contains$2(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];
}
__name(statsManagerGetCollection, "statsManagerGetCollection");
function statsManagerGetOrCreateReporter(repoInfo, creatorFunction) {
  const hashString = repoInfo.toString();
  if (!reporters[hashString]) {
    reporters[hashString] = creatorFunction();
  }
  return reporters[hashString];
}
__name(statsManagerGetOrCreateReporter, "statsManagerGetOrCreateReporter");
/**
 * @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 {
  static {
    __name(this, "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 {
  static {
    __name(this, "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, onDisconnect2) {
    this.curSegmentNum = 0;
    this.onDisconnect_ = onDisconnect2;
    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 [command2, 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 (command2 === FIREBASE_LONGPOLL_START_PARAM) {
          this.id = arg1;
          this.password = arg2;
        } else if (command2 === 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: " + command2);
        }
      }, (...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 (isNodeSdk()) {
      return false;
    } else 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$2(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(id2, pw) {
    if (isNodeSdk()) {
      return;
    }
    this.myDisconnFrame = document.createElement("iframe");
    const urlParams = {};
    urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = "t";
    urlParams[FIREBASE_LONGPOLL_ID_PARAM] = id2;
    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$2(args).length;
    this.bytesReceived += bytesReceived;
    this.stats_.incrementCounter("bytes_received", bytesReceived);
  }
}
class FirebaseIFrameScriptHolder {
  static {
    __name(this, "FirebaseIFrameScriptHolder");
  }
  /**
   * @param commandCB - The callback to be called when control commands are received 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, onDisconnect2, urlFn) {
    this.onDisconnect = onDisconnect2;
    this.urlFn = urlFn;
    this.outstandingRequests = /* @__PURE__ */ new Set();
    this.pendingSegs = [];
    this.currentSerial = Math.floor(Math.random() * 1e8);
    this.sendNewPolls = true;
    if (!isNodeSdk()) {
      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 script2 = "";
      if (this.myIFrame.src && this.myIFrame.src.substr(0, "javascript:".length) === "javascript:") {
        const currentDomain = document.domain;
        script2 = '<script>document.domain="' + currentDomain + '";<\/script>';
      }
      const iframeContents = "<html><body>" + script2 + "</body></html>";
      try {
        this.myIFrame.doc.open();
        this.myIFrame.doc.write(iframeContents);
        this.myIFrame.doc.close();
      } catch (e2) {
        log$1("frame writing exception");
        if (e2.stack) {
          log$1(e2.stack);
        }
        log$1(e2);
      }
    } else {
      this.commandCB = commandCB;
      this.onMessageCB = onMessageCB;
    }
  }
  /**
   * 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$1("No IE domain setting required");
        }
      } catch (e2) {
        const domain2 = document.domain;
        iframe.src = "javascript:void((function(){document.open();document.domain='" + domain2 + "';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 onDisconnect2 = this.onDisconnect;
    if (onDisconnect2) {
      this.onDisconnect = null;
      onDisconnect2();
    }
  }
  /**
   * 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(id2, pw) {
    this.myID = id2;
    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 = /* @__PURE__ */ __name(() => {
      this.outstandingRequests.delete(serial);
      this.newRequest_();
    }, "doNewRequest");
    const keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL));
    const readyStateCB = /* @__PURE__ */ __name(() => {
      clearTimeout(keepaliveTimeout);
      doNewRequest();
    }, "readyStateCB");
    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) {
    if (isNodeSdk()) {
      this.doNodeLongPoll(url, loadCB);
    } else {
      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$1("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 {
  static {
    __name(this, "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 (!isNodeSdk() && 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, onDisconnect2) {
    this.onDisconnect = onDisconnect2;
    this.onMessage = onMessage;
    this.log_("Websocket connecting to " + this.connURL);
    this.everConnected_ = false;
    PersistentStorage.set("previous_websocket_failure", true);
    try {
      let options2;
      if (isNodeSdk()) {
        const device = this.nodeAdmin ? "AdminNode" : "Node";
        options2 = {
          headers: {
            "User-Agent": `Firebase/${PROTOCOL_VERSION}/${SDK_VERSION}/${process.platform}/${device}`,
            "X-Firebase-GMPID": this.applicationId || ""
          }
        };
        if (this.authToken) {
          options2.headers["Authorization"] = `Bearer ${this.authToken}`;
        }
        if (this.appCheckToken) {
          options2.headers["X-Firebase-AppCheck"] = this.appCheckToken;
        }
        const env = define_process_env_default;
        const proxy = this.connURL.indexOf("wss://") === 0 ? env["HTTPS_PROXY"] || env["https_proxy"] : env["HTTP_PROXY"] || env["http_proxy"];
        if (proxy) {
          options2["proxy"] = { origin: proxy };
        }
      }
      this.mySock = new WebSocketImpl(this.connURL, [], options2);
    } 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$1(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$2(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 {
  static {
    __name(this, "TransportManager");
  }
  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_;
  }
  /**
   * @param repoInfo - Metadata around the namespace we're connecting to
   */
  constructor(repoInfo) {
    this.initTransports_(repoInfo);
  }
  initTransports_(repoInfo) {
    const isWebSocketsAvailable = WebSocketConnection && WebSocketConnection["isAvailable"]();
    let isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection.previouslyFailed();
    if (repoInfo.webSocketOnly) {
      if (!isWebSocketsAvailable) {
        warn$2("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 {
  static {
    __name(this, "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(id2, repoInfo_, applicationId_, appCheckToken_, authToken_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) {
    this.id = id2;
    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$1("Server Error: " + payload);
      } else if (cmd === CONTROL_PONG) {
        this.log_("got pong on primary.");
        this.onPrimaryResponse_();
        this.sendPingOnPrimaryIfNecessary_();
      } else {
        error$1("Unknown control packet command: " + cmd);
      }
    }
  }
  /**
   * @param handshake - The handshake data returned from the server
   */
  onHandshake_(handshake) {
    const timestamp2 = 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_, timestamp2);
      if (PROTOCOL_VERSION !== version2) {
        warn$2("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 onDisconnect2 = this.disconnReceiver_(this.secondaryConn_);
    this.secondaryConn_.open(onMessage, onDisconnect2);
    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, timestamp2) {
    this.log_("Realtime connection established.");
    this.conn_ = conn;
    this.state_ = 1;
    if (this.onReady_) {
      this.onReady_(timestamp2, 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 {
  static {
    __name(this, "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.
 */
let EventEmitter$1 = class EventEmitter2 {
  static {
    __name(this, "EventEmitter");
  }
  constructor(allowedEvents_) {
    this.allowedEvents_ = allowedEvents_;
    this.listeners_ = {};
    assert$1(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$1(this.allowedEvents_.find((et2) => {
      return et2 === 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 EventEmitter$1 {
  static {
    __name(this, "OnlineMonitor");
  }
  static getInstance() {
    return new OnlineMonitor();
  }
  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);
    }
  }
  getInitialEvent(eventType) {
    assert$1(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 {
  static {
    __name(this, "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("");
}
__name(newEmptyPath, "newEmptyPath");
function pathGetFront(path) {
  if (path.pieceNum_ >= path.pieces_.length) {
    return null;
  }
  return path.pieces_[path.pieceNum_];
}
__name(pathGetFront, "pathGetFront");
function pathGetLength(path) {
  return path.pieces_.length - path.pieceNum_;
}
__name(pathGetLength, "pathGetLength");
function pathPopFront(path) {
  let pieceNum = path.pieceNum_;
  if (pieceNum < path.pieces_.length) {
    pieceNum++;
  }
  return new Path(path.pieces_, pieceNum);
}
__name(pathPopFront, "pathPopFront");
function pathGetBack(path) {
  if (path.pieceNum_ < path.pieces_.length) {
    return path.pieces_[path.pieces_.length - 1];
  }
  return null;
}
__name(pathGetBack, "pathGetBack");
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 || "/";
}
__name(pathToUrlEncodedString, "pathToUrlEncodedString");
function pathSlice(path, begin = 0) {
  return path.pieces_.slice(path.pieceNum_ + begin);
}
__name(pathSlice, "pathSlice");
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);
}
__name(pathParent, "pathParent");
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);
}
__name(pathChild, "pathChild");
function pathIsEmpty(path) {
  return path.pieceNum_ >= path.pieces_.length;
}
__name(pathIsEmpty, "pathIsEmpty");
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 + ")");
  }
}
__name(newRelativePath, "newRelativePath");
function pathCompare(left, right) {
  const leftKeys = pathSlice(left, 0);
  const rightKeys = pathSlice(right, 0);
  for (let i2 = 0; i2 < leftKeys.length && i2 < rightKeys.length; i2++) {
    const cmp2 = nameCompare(leftKeys[i2], rightKeys[i2]);
    if (cmp2 !== 0) {
      return cmp2;
    }
  }
  if (leftKeys.length === rightKeys.length) {
    return 0;
  }
  return leftKeys.length < rightKeys.length ? -1 : 1;
}
__name(pathCompare, "pathCompare");
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;
}
__name(pathEquals, "pathEquals");
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;
}
__name(pathContains, "pathContains");
class ValidationPath {
  static {
    __name(this, "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);
}
__name(validationPathPush, "validationPathPush");
function validationPathPop(validationPath) {
  const last = validationPath.parts_.pop();
  validationPath.byteLength_ -= stringLength(last);
  if (validationPath.parts_.length > 0) {
    validationPath.byteLength_ -= 1;
  }
}
__name(validationPathPop, "validationPathPop");
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));
  }
}
__name(validationPathCheckValid, "validationPathCheckValid");
function validationPathToErrorString(validationPath) {
  if (validationPath.parts_.length === 0) {
    return "";
  }
  return "in property '" + validationPath.parts_.join(".") + "'";
}
__name(validationPathToErrorString, "validationPathToErrorString");
/**
 * @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 EventEmitter$1 {
  static {
    __name(this, "VisibilityMonitor");
  }
  static getInstance() {
    return new VisibilityMonitor();
  }
  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);
    }
  }
  getInitialEvent(eventType) {
    assert$1(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 {
  static {
    __name(this, "PersistentConnection");
  }
  /**
   * @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$2(msg));
    assert$1(this.connected_, "sendRequest call when we're not connected not allowed.");
    this.realtime_.sendRequest(msg);
    if (onResponse) {
      this.requestCBHash_[curReqNum] = onResponse;
    }
  }
  get(query2) {
    this.initConnection_();
    const deferred = new Deferred();
    const request = {
      p: query2._path.toString(),
      q: query2._queryObject
    };
    const outstandingGet = {
      action: "g",
      request,
      onComplete: /* @__PURE__ */ __name((message) => {
        const payload = message["d"];
        if (message["s"] === "ok") {
          deferred.resolve(payload);
        } else {
          deferred.reject(payload);
        }
      }, "onComplete")
    };
    this.outstandingGets_.push(outstandingGet);
    this.outstandingGetCount_++;
    const index2 = this.outstandingGets_.length - 1;
    if (this.connected_) {
      this.sendGet_(index2);
    }
    return deferred.promise;
  }
  listen(query2, currentHashFn, tag, onComplete) {
    this.initConnection_();
    const queryId = query2._queryIdentifier;
    const pathString = query2._path.toString();
    this.log_("Listen called for " + pathString + " " + queryId);
    if (!this.listens.has(pathString)) {
      this.listens.set(pathString, /* @__PURE__ */ new Map());
    }
    assert$1(query2._queryParams.isDefault() || !query2._queryParams.loadsAllData(), "listen() called for non-default but complete query");
    assert$1(!this.listens.get(pathString).has(queryId), `listen() called twice for same path/queryId.`);
    const listenSpec = {
      onComplete,
      hashFn: currentHashFn,
      query: query2,
      tag
    };
    this.listens.get(pathString).set(queryId, listenSpec);
    if (this.connected_) {
      this.sendListen_(listenSpec);
    }
  }
  sendGet_(index2) {
    const get22 = this.outstandingGets_[index2];
    this.sendRequest("g", get22.request, (message) => {
      delete this.outstandingGets_[index2];
      this.outstandingGetCount_--;
      if (this.outstandingGetCount_ === 0) {
        this.outstandingGets_ = [];
      }
      if (get22.onComplete) {
        get22.onComplete(message);
      }
    });
  }
  sendListen_(listenSpec) {
    const query2 = listenSpec.query;
    const pathString = query2._path.toString();
    const queryId = query2._queryIdentifier;
    this.log_("Listen on " + pathString + " for " + queryId);
    const req = {
      /*path*/
      p: pathString
    };
    const action = "q";
    if (listenSpec.tag) {
      req["q"] = query2._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, query2);
      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, query2) {
    if (payload && typeof payload === "object" && contains$2(payload, "w")) {
      const warnings = safeGet(payload, "w");
      if (Array.isArray(warnings) && ~warnings.indexOf("no_index")) {
        const indexSpec = '".indexOn": "' + query2._queryParams.getIndex().toString() + '"';
        const indexPath = query2._path.toString();
        warn$2(`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(query2, tag) {
    const pathString = query2._path.toString();
    const queryId = query2._queryIdentifier;
    this.log_("Unlisten called for " + pathString + " " + queryId);
    assert$1(query2._queryParams.isDefault() || !query2._queryParams.loadsAllData(), "unlisten() called for non-default but complete query");
    const listen = this.removeListen_(pathString, queryId);
    if (listen && this.connected_) {
      this.sendUnlisten_(pathString, queryId, query2._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$2(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$1("Unrecognized action received from server: " + stringify$2(action) + "\nAre you using the latest client?");
    }
  }
  onReady_(timestamp2, sessionId) {
    this.log_("connection ready");
    this.connected_ = true;
    this.lastConnectionEstablishedTime_ = (/* @__PURE__ */ new Date()).getTime();
    this.handleTimestamp_(timestamp2);
    this.lastSessionId = sessionId;
    if (this.firstConnection_) {
      this.sendConnectStats_();
    }
    this.restoreState_();
    this.firstConnection_ = false;
    this.onConnectStatus_(true);
  }
  scheduleConnect_(timeout) {
    assert$1(!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 = Math.max(0, (/* @__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 onDisconnect2 = this.onRealtimeDisconnect_.bind(this);
      const connId = this.id + ":" + PersistentConnection.nextConnectionId_++;
      const lastSessionId = this.lastSessionId;
      let canceled2 = false;
      let connection = null;
      const closeFn = /* @__PURE__ */ __name(function() {
        if (connection) {
          connection.close();
        } else {
          canceled2 = true;
          onDisconnect2();
        }
      }, "closeFn");
      const sendRequestFn = /* @__PURE__ */ __name(function(msg) {
        assert$1(connection, "sendRequest call when we're not connected not allowed.");
        connection.sendRequest(msg);
      }, "sendRequestFn");
      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 (!canceled2) {
          log$1("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,
            onDisconnect2,
            /* onKill= */
            (reason) => {
              warn$2(reason + " (" + this.repoInfo_.toString() + ")");
              this.interrupt(SERVER_KILL_INTERRUPT_REASON);
            },
            lastSessionId
          );
        } else {
          log$1("getToken() completed but was canceled");
        }
      } catch (error2) {
        this.log_("Failed to get token: " + error2);
        if (!canceled2) {
          if (this.repoInfo_.nodeAdmin) {
            warn$2(error2);
          }
          closeFn();
        }
      }
    }
  }
  interrupt(reason) {
    log$1("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$1("Resuming connection for reason: " + reason);
    delete this.interruptReasons_[reason];
    if (isEmpty$4(this.interruptReasons_)) {
      this.reconnectDelay_ = RECONNECT_MIN_DELAY;
      if (!this.realtime_) {
        this.scheduleConnect_(0);
      }
    }
  }
  handleTimestamp_(timestamp2) {
    const delta2 = timestamp2 - (/* @__PURE__ */ new Date()).getTime();
    this.onServerInfoUpdate_({ serverTimeOffset: delta2 });
  }
  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, query2) {
    let queryId;
    if (!query2) {
      queryId = "default";
    } else {
      queryId = query2.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 map22 = this.listens.get(normalizedPathString);
      listen = map22.get(queryId);
      map22.delete(queryId);
      if (map22.size === 0) {
        this.listens.delete(normalizedPathString);
      }
    } else {
      listen = void 0;
    }
    return listen;
  }
  onAuthRevoked_(statusCode, explanation) {
    log$1("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$1("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";
    if (isNodeSdk()) {
      if (this.repoInfo_.nodeAdmin) {
        clientName = "admin_node";
      } else {
        clientName = "node";
      }
    }
    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$4(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 {
  static {
    __name(this, "NamedNode");
  }
  constructor(name2, node2) {
    this.name = name2;
    this.node = node2;
  }
  static Wrap(name2, node2) {
    return new NamedNode(name2, node2);
  }
}
/**
 * @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 {
  static {
    __name(this, "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 {
    __name(this, "KeyIndex");
  }
  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(node2) {
    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$1(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.
 */
let SortedMapIterator$1 = class SortedMapIterator2 {
  static {
    __name(this, "SortedMapIterator");
  }
  /**
   * @param node - Node to iterate.
   * @param isReverse_ - Whether or not to iterate in reverse
   */
  constructor(node2, startKey, comparator, isReverse_, resultGenerator_ = null) {
    this.isReverse_ = isReverse_;
    this.resultGenerator_ = resultGenerator_;
    this.nodeStack_ = [];
    let cmp2 = 1;
    while (!node2.isEmpty()) {
      node2 = node2;
      cmp2 = startKey ? comparator(node2.key, startKey) : 1;
      if (isReverse_) {
        cmp2 *= -1;
      }
      if (cmp2 < 0) {
        if (this.isReverse_) {
          node2 = node2.left;
        } else {
          node2 = node2.right;
        }
      } else if (cmp2 === 0) {
        this.nodeStack_.push(node2);
        break;
      } else {
        this.nodeStack_.push(node2);
        if (this.isReverse_) {
          node2 = node2.right;
        } else {
          node2 = node2.left;
        }
      }
    }
  }
  getNext() {
    if (this.nodeStack_.length === 0) {
      return null;
    }
    let node2 = this.nodeStack_.pop();
    let result;
    if (this.resultGenerator_) {
      result = this.resultGenerator_(node2.key, node2.value);
    } else {
      result = { key: node2.key, value: node2.value };
    }
    if (this.isReverse_) {
      node2 = node2.left;
      while (!node2.isEmpty()) {
        this.nodeStack_.push(node2);
        node2 = node2.right;
      }
    } else {
      node2 = node2.right;
      while (!node2.isEmpty()) {
        this.nodeStack_.push(node2);
        node2 = node2.left;
      }
    }
    return result;
  }
  hasNext() {
    return this.nodeStack_.length > 0;
  }
  peek() {
    if (this.nodeStack_.length === 0) {
      return null;
    }
    const node2 = this.nodeStack_[this.nodeStack_.length - 1];
    if (this.resultGenerator_) {
      return this.resultGenerator_(node2.key, node2.value);
    } else {
      return { key: node2.key, value: node2.value };
    }
  }
};
let LLRBNode$1 = class LLRBNode2 {
  static {
    __name(this, "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, color2, left, right) {
    this.key = key;
    this.value = value;
    this.color = color2 != null ? color2 : LLRBNode2.RED;
    this.left = left != null ? left : SortedMap$1.EMPTY_NODE;
    this.right = right != null ? right : SortedMap$1.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, color2, left, right) {
    return new LLRBNode2(key != null ? key : this.key, value != null ? value : this.value, color2 != null ? color2 : 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 cmp2 = comparator(key, n2.key);
    if (cmp2 < 0) {
      n2 = n2.copy(null, null, null, n2.left.insert(key, value, comparator), null);
    } else if (cmp2 === 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$1.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$1.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, LLRBNode2.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, LLRBNode2.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$1.RED = true;
LLRBNode$1.BLACK = false;
class LLRBEmptyNode {
  static {
    __name(this, "LLRBEmptyNode");
  }
  /**
   * Returns a copy of the current node.
   *
   * @returns The node copy.
   */
  copy(key, value, color2, 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$1(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;
  }
}
let SortedMap$1 = class SortedMap2 {
  static {
    __name(this, "SortedMap");
  }
  /**
   * @param comparator_ - Key comparator.
   * @param root_ - Optional root node for the map.
   */
  constructor(comparator_, root_ = SortedMap2.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 SortedMap2(this.comparator_, this.root_.insert(key, value, this.comparator_).copy(null, null, LLRBNode$1.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 SortedMap2(this.comparator_, this.root_.remove(key, this.comparator_).copy(null, null, LLRBNode$1.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 cmp2;
    let node2 = this.root_;
    while (!node2.isEmpty()) {
      cmp2 = this.comparator_(key, node2.key);
      if (cmp2 === 0) {
        return node2.value;
      } else if (cmp2 < 0) {
        node2 = node2.left;
      } else if (cmp2 > 0) {
        node2 = node2.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 cmp2, node2 = this.root_, rightParent = null;
    while (!node2.isEmpty()) {
      cmp2 = this.comparator_(key, node2.key);
      if (cmp2 === 0) {
        if (!node2.left.isEmpty()) {
          node2 = node2.left;
          while (!node2.right.isEmpty()) {
            node2 = node2.right;
          }
          return node2.key;
        } else if (rightParent) {
          return rightParent.key;
        } else {
          return null;
        }
      } else if (cmp2 < 0) {
        node2 = node2.left;
      } else if (cmp2 > 0) {
        rightParent = node2;
        node2 = node2.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$1(this.root_, null, this.comparator_, false, resultGenerator);
  }
  getIteratorFrom(key, resultGenerator) {
    return new SortedMapIterator$1(this.root_, key, this.comparator_, false, resultGenerator);
  }
  getReverseIteratorFrom(key, resultGenerator) {
    return new SortedMapIterator$1(this.root_, key, this.comparator_, true, resultGenerator);
  }
  getReverseIterator(resultGenerator) {
    return new SortedMapIterator$1(this.root_, null, this.comparator_, true, resultGenerator);
  }
};
SortedMap$1.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);
}
__name(NAME_ONLY_COMPARATOR, "NAME_ONLY_COMPARATOR");
function NAME_COMPARATOR(left, right) {
  return nameCompare(left, right);
}
__name(NAME_COMPARATOR, "NAME_COMPARATOR");
/**
 * @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;
}
__name(setMaxNode$1, "setMaxNode$1");
const priorityHashText = /* @__PURE__ */ __name(function(priority) {
  if (typeof priority === "number") {
    return "number:" + doubleToIEEE754String(priority);
  } else {
    return "string:" + priority;
  }
}, "priorityHashText");
const validatePriorityNode = /* @__PURE__ */ __name(function(priorityNode) {
  if (priorityNode.isLeafNode()) {
    const val = priorityNode.val();
    assert$1(typeof val === "string" || typeof val === "number" || typeof val === "object" && contains$2(val, ".sv"), "Priority must be a string or number.");
  } else {
    assert$1(priorityNode === MAX_NODE$2 || priorityNode.isEmpty(), "priority of unexpected type.");
  }
  assert$1(priorityNode === MAX_NODE$2 || priorityNode.getPriority().isEmpty(), "Priority nodes can't have a priority of their own.");
}, "validatePriorityNode");
/**
 * @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 {
  static {
    __name(this, "LeafNode");
  }
  static set __childrenNodeConstructor(val) {
    __childrenNodeConstructor = val;
  }
  static get __childrenNodeConstructor() {
    return __childrenNodeConstructor;
  }
  /**
   * @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$1(this.value_ !== void 0 && this.value_ !== null, "LeafNode shouldn't be created with null/undefined value.");
    validatePriorityNode(this.priorityNode_);
  }
  /** @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$1(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$1(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$1(otherIndex >= 0, "Unknown leaf type: " + otherLeafType);
    assert$1(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;
}
__name(setNodeFromJSON, "setNodeFromJSON");
function setMaxNode(val) {
  MAX_NODE$1 = val;
}
__name(setMaxNode, "setMaxNode");
class PriorityIndex extends Index {
  static {
    __name(this, "PriorityIndex");
  }
  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(node2) {
    return !node2.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 {
  static {
    __name(this, "Base12Num");
  }
  constructor(length) {
    const logBase2 = /* @__PURE__ */ __name((num) => (
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      parseInt(Math.log(num) / LOG_2, 10)
    ), "logBase2");
    const bitMask = /* @__PURE__ */ __name((bits) => parseInt(Array(bits + 1).join("1"), 2), "bitMask");
    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 = /* @__PURE__ */ __name(function(childList, cmp2, keyFn, mapSortFn) {
  childList.sort(cmp2);
  const buildBalancedTree = /* @__PURE__ */ __name(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$1(key, namedNode.node, LLRBNode$1.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$1(key, namedNode.node, LLRBNode$1.BLACK, left, right);
    }
  }, "buildBalancedTree");
  const buildFrom12Array = /* @__PURE__ */ __name(function(base122) {
    let node2 = null;
    let root22 = null;
    let index2 = childList.length;
    const buildPennant = /* @__PURE__ */ __name(function(chunkSize, color2) {
      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$1(key, namedNode.node, color2, null, childTree));
    }, "buildPennant");
    const attachPennant = /* @__PURE__ */ __name(function(pennant) {
      if (node2) {
        node2.left = pennant;
        node2 = pennant;
      } else {
        root22 = pennant;
        node2 = pennant;
      }
    }, "attachPennant");
    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$1.BLACK);
      } else {
        buildPennant(chunkSize, LLRBNode$1.BLACK);
        buildPennant(chunkSize, LLRBNode$1.RED);
      }
    }
    return root22;
  }, "buildFrom12Array");
  const base12 = new Base12Num(childList.length);
  const root2 = buildFrom12Array(base12);
  return new SortedMap$1(mapSortFn || cmp2, root2);
}, "buildChildSet");
/**
 * @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 {
  static {
    __name(this, "IndexMap");
  }
  /**
   * The default IndexMap for nodes without a priority
   */
  static get Default() {
    assert$1(fallbackObject && PRIORITY_INDEX, "ChildrenNode.ts has not been loaded");
    _defaultIndexMap = _defaultIndexMap || new IndexMap({ ".priority": fallbackObject }, { ".priority": PRIORITY_INDEX });
    return _defaultIndexMap;
  }
  constructor(indexes_, indexSet_) {
    this.indexes_ = indexes_;
    this.indexSet_ = indexSet_;
  }
  get(indexKey) {
    const sortedMap = safeGet(this.indexes_, indexKey);
    if (!sortedMap) {
      throw new Error("No index defined for " + indexKey);
    }
    if (sortedMap instanceof SortedMap$1) {
      return sortedMap;
    } else {
      return null;
    }
  }
  hasIndex(indexDefinition) {
    return contains$2(this.indexSet_, indexDefinition.toString());
  }
  addIndex(indexDefinition, existingChildren) {
    assert$1(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$1(this.indexes_, (indexedChildren, indexName) => {
      const index2 = safeGet(this.indexSet_, indexName);
      assert$1(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$1(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 {
  static {
    __name(this, "ChildrenNode");
  }
  static get EMPTY_NODE() {
    return EMPTY_NODE || (EMPTY_NODE = new ChildrenNode(new SortedMap$1(NAME_COMPARATOR), null, IndexMap.Default));
  }
  /**
   * @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$1(!this.priorityNode_ || this.priorityNode_.isEmpty(), "An empty node cannot have a priority");
    }
  }
  /** @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$1(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$1(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 {
  static {
    __name(this, "MaxNode");
  }
  constructor() {
    super(new SortedMap$1(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$1(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 node2 = ChildrenNode.EMPTY_NODE;
    each(json, (key, childData) => {
      if (contains$2(json, key)) {
        if (key.substring(0, 1) !== ".") {
          const childNode = nodeFromJSON(childData);
          if (childNode.isLeafNode() || !childNode.isEmpty()) {
            node2 = node2.updateImmediateChild(key, childNode);
          }
        }
      }
    });
    return node2.updatePriority(nodeFromJSON(priority));
  }
}
__name(nodeFromJSON, "nodeFromJSON");
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 {
  static {
    __name(this, "PathIndex");
  }
  constructor(indexPath_) {
    super();
    this.indexPath_ = indexPath_;
    assert$1(!pathIsEmpty(indexPath_) && pathGetFront(indexPath_) !== ".priority", "Can't create PathIndex with empty path or .priority key");
  }
  extractChild(snap) {
    return snap.getChild(this.indexPath_);
  }
  isDefinedOn(node2) {
    return !node2.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 node2 = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, valueNode);
    return new NamedNode(name2, node2);
  }
  maxPost() {
    const node2 = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, MAX_NODE);
    return new NamedNode(MAX_NAME, node2);
  }
  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 {
  static {
    __name(this, "ValueIndex");
  }
  compare(a2, b2) {
    const indexCmp = a2.node.compareTo(b2.node);
    if (indexCmp === 0) {
      return nameCompare(a2.name, b2.name);
    } else {
      return indexCmp;
    }
  }
  isDefinedOn(node2) {
    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 };
}
__name(changeValue, "changeValue");
function changeChildAdded(childName, snapshotNode) {
  return { type: "child_added", snapshotNode, childName };
}
__name(changeChildAdded, "changeChildAdded");
function changeChildRemoved(childName, snapshotNode) {
  return { type: "child_removed", snapshotNode, childName };
}
__name(changeChildRemoved, "changeChildRemoved");
function changeChildChanged(childName, snapshotNode, oldSnap) {
  return {
    type: "child_changed",
    snapshotNode,
    childName,
    oldSnap
  };
}
__name(changeChildChanged, "changeChildChanged");
function changeChildMoved(childName, snapshotNode) {
  return { type: "child_moved", snapshotNode, childName };
}
__name(changeChildMoved, "changeChildMoved");
/**
 * @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 {
  static {
    __name(this, "IndexedFilter");
  }
  constructor(index_) {
    this.index_ = index_;
  }
  updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {
    assert$1(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$1(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 {
  static {
    __name(this, "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(node2) {
    const isWithinStart = this.startIsInclusive_ ? this.index_.compare(this.getStartPost(), node2) <= 0 : this.index_.compare(this.getStartPost(), node2) < 0;
    const isWithinEnd = this.endIsInclusive_ ? this.index_.compare(node2, this.getEndPost()) <= 0 : this.index_.compare(node2, 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 {
  static {
    __name(this, "LimitedFilter");
  }
  constructor(params) {
    this.withinDirectionalStart = (node2) => this.reverse_ ? this.withinEndPost(node2) : this.withinStartPost(node2);
    this.withinDirectionalEnd = (node2) => this.reverse_ ? this.withinStartPost(node2) : this.withinEndPost(node2);
    this.withinStartPost = (node2) => {
      const compareRes = this.index_.compare(this.rangedFilter_.getStartPost(), node2);
      return this.startIsInclusive_ ? compareRes <= 0 : compareRes < 0;
    };
    this.withinEndPost = (node2) => {
      const compareRes = this.index_.compare(node2, 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 count2 = 0;
        while (iterator.hasNext() && count2 < 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);
            count2++;
          }
        }
      } 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 count2 = 0;
        while (iterator.hasNext()) {
          const next = iterator.getNext();
          const inRange = count2 < this.limit_ && this.withinDirectionalStart(next) && this.withinDirectionalEnd(next);
          if (inRange) {
            count2++;
          } 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 cmp2;
    if (this.reverse_) {
      const indexCmp = this.index_.getCompare();
      cmp2 = /* @__PURE__ */ __name((a2, b2) => indexCmp(b2, a2), "cmp");
    } else {
      cmp2 = this.index_.getCompare();
    }
    const oldEventCache = snap;
    assert$1(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 : cmp2(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 (cmp2(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 {
  static {
    __name(this, "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$1(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$1(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$1(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$1(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$1(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);
  }
}
__name(queryParamsGetNodeFilter, "queryParamsGetNodeFilter");
function queryParamsLimitToFirst(queryParams, newLimit) {
  const newParams = queryParams.copy();
  newParams.limitSet_ = true;
  newParams.limit_ = newLimit;
  newParams.viewFrom_ = "l";
  return newParams;
}
__name(queryParamsLimitToFirst, "queryParamsLimitToFirst");
function queryParamsLimitToLast(queryParams, newLimit) {
  const newParams = queryParams.copy();
  newParams.limitSet_ = true;
  newParams.limit_ = newLimit;
  newParams.viewFrom_ = "r";
  return newParams;
}
__name(queryParamsLimitToLast, "queryParamsLimitToLast");
function queryParamsStartAt(queryParams, indexValue, key) {
  const newParams = queryParams.copy();
  newParams.startSet_ = true;
  if (indexValue === void 0) {
    indexValue = null;
  }
  newParams.indexStartValue_ = indexValue;
  if (key != null) {
    newParams.startNameSet_ = true;
    newParams.indexStartName_ = key;
  } else {
    newParams.startNameSet_ = false;
    newParams.indexStartName_ = "";
  }
  return newParams;
}
__name(queryParamsStartAt, "queryParamsStartAt");
function queryParamsStartAfter(queryParams, indexValue, key) {
  let params;
  if (queryParams.index_ === KEY_INDEX || !!key) {
    params = queryParamsStartAt(queryParams, indexValue, key);
  } else {
    params = queryParamsStartAt(queryParams, indexValue, MAX_NAME);
  }
  params.startAfterSet_ = true;
  return params;
}
__name(queryParamsStartAfter, "queryParamsStartAfter");
function queryParamsEndAt(queryParams, indexValue, key) {
  const newParams = queryParams.copy();
  newParams.endSet_ = true;
  if (indexValue === void 0) {
    indexValue = null;
  }
  newParams.indexEndValue_ = indexValue;
  if (key !== void 0) {
    newParams.endNameSet_ = true;
    newParams.indexEndName_ = key;
  } else {
    newParams.endNameSet_ = false;
    newParams.indexEndName_ = "";
  }
  return newParams;
}
__name(queryParamsEndAt, "queryParamsEndAt");
function queryParamsEndBefore(queryParams, indexValue, key) {
  let params;
  if (queryParams.index_ === KEY_INDEX || !!key) {
    params = queryParamsEndAt(queryParams, indexValue, key);
  } else {
    params = queryParamsEndAt(queryParams, indexValue, MIN_NAME);
  }
  params.endBeforeSet_ = true;
  return params;
}
__name(queryParamsEndBefore, "queryParamsEndBefore");
function queryParamsOrderBy(queryParams, index2) {
  const newParams = queryParams.copy();
  newParams.index_ = index2;
  return newParams;
}
__name(queryParamsOrderBy, "queryParamsOrderBy");
function queryParamsToRestQueryStringParameters(queryParams) {
  const qs = {};
  if (queryParams.isDefault()) {
    return qs;
  }
  let orderBy2;
  if (queryParams.index_ === PRIORITY_INDEX) {
    orderBy2 = "$priority";
  } else if (queryParams.index_ === VALUE_INDEX) {
    orderBy2 = "$value";
  } else if (queryParams.index_ === KEY_INDEX) {
    orderBy2 = "$key";
  } else {
    assert$1(queryParams.index_ instanceof PathIndex, "Unrecognized index type!");
    orderBy2 = queryParams.index_.toString();
  }
  qs[
    "orderBy"
    /* REST_QUERY_CONSTANTS.ORDER_BY */
  ] = stringify$2(orderBy2);
  if (queryParams.startSet_) {
    const startParam = queryParams.startAfterSet_ ? "startAfter" : "startAt";
    qs[startParam] = stringify$2(queryParams.indexStartValue_);
    if (queryParams.startNameSet_) {
      qs[startParam] += "," + stringify$2(queryParams.indexStartName_);
    }
  }
  if (queryParams.endSet_) {
    const endParam = queryParams.endBeforeSet_ ? "endBefore" : "endAt";
    qs[endParam] = stringify$2(queryParams.indexEndValue_);
    if (queryParams.endNameSet_) {
      qs[endParam] += "," + stringify$2(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;
}
__name(queryParamsToRestQueryStringParameters, "queryParamsToRestQueryStringParameters");
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;
}
__name(queryParamsGetQueryObject, "queryParamsGetQueryObject");
/**
 * @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 {
  static {
    __name(this, "ReadonlyRestClient");
  }
  reportStats(stats) {
    throw new Error("Method not implemented.");
  }
  static getListenId_(query2, tag) {
    if (tag !== void 0) {
      return "tag$" + tag;
    } else {
      assert$1(query2._queryParams.isDefault(), "should have a tag if it's not a default query.");
      return query2._path.toString();
    }
  }
  /**
   * @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_ = {};
  }
  /** @inheritDoc */
  listen(query2, currentHashFn, tag, onComplete) {
    const pathString = query2._path.toString();
    this.log_("Listen called for " + pathString + " " + query2._queryIdentifier);
    const listenId = ReadonlyRestClient.getListenId_(query2, tag);
    const thisListen = {};
    this.listens_[listenId] = thisListen;
    const queryStringParameters = queryParamsToRestQueryStringParameters(query2._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(query2, tag) {
    const listenId = ReadonlyRestClient.getListenId_(query2, tag);
    delete this.listens_[listenId];
  }
  get(query2) {
    const queryStringParameters = queryParamsToRestQueryStringParameters(query2._queryParams);
    const pathString = query2._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$2("Failed to parse JSON response for " + url + ": " + xhr.responseText);
            }
            callback(null, res);
          } else {
            if (xhr.status !== 401 && xhr.status !== 404) {
              warn$2("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 {
  static {
    __name(this, "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()
  };
}
__name(newSparseSnapshotTree, "newSparseSnapshotTree");
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);
  }
}
__name(sparseSnapshotTreeRemember, "sparseSnapshotTreeRemember");
function sparseSnapshotTreeForget(sparseSnapshotTree, path) {
  if (pathIsEmpty(path)) {
    sparseSnapshotTree.value = null;
    sparseSnapshotTree.children.clear();
    return true;
  } else {
    if (sparseSnapshotTree.value !== null) {
      if (sparseSnapshotTree.value.isLeafNode()) {
        return false;
      } else {
        const value = sparseSnapshotTree.value;
        sparseSnapshotTree.value = null;
        value.forEachChild(PRIORITY_INDEX, (key, tree) => {
          sparseSnapshotTreeRemember(sparseSnapshotTree, new Path(key), tree);
        });
        return sparseSnapshotTreeForget(sparseSnapshotTree, path);
      }
    } else if (sparseSnapshotTree.children.size > 0) {
      const childKey = pathGetFront(path);
      path = pathPopFront(path);
      if (sparseSnapshotTree.children.has(childKey)) {
        const safeToRemove = sparseSnapshotTreeForget(sparseSnapshotTree.children.get(childKey), path);
        if (safeToRemove) {
          sparseSnapshotTree.children.delete(childKey);
        }
      }
      return sparseSnapshotTree.children.size === 0;
    } else {
      return true;
    }
  }
}
__name(sparseSnapshotTreeForget, "sparseSnapshotTreeForget");
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);
    });
  }
}
__name(sparseSnapshotTreeForEachTree, "sparseSnapshotTreeForEachTree");
function sparseSnapshotTreeForEachChild(sparseSnapshotTree, func) {
  sparseSnapshotTree.children.forEach((tree, key) => {
    func(key, tree);
  });
}
__name(sparseSnapshotTreeForEachChild, "sparseSnapshotTreeForEachChild");
/**
 * @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 {
  static {
    __name(this, "StatsListener");
  }
  constructor(collection_) {
    this.collection_ = collection_;
    this.last_ = null;
  }
  get() {
    const newStats = this.collection_.get();
    const delta2 = Object.assign({}, newStats);
    if (this.last_) {
      each(this.last_, (stat, value) => {
        delta2[stat] = delta2[stat] - value;
      });
    }
    this.last_ = newStats;
    return delta2;
  }
}
/**
 * @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 {
  static {
    __name(this, "StatsReporter");
  }
  constructor(collection2, server_) {
    this.server_ = server_;
    this.statsToReport_ = {};
    this.statsListener_ = new StatsListener(collection2);
    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$2(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
  };
}
__name(newOperationSourceUser, "newOperationSourceUser");
function newOperationSourceServer() {
  return {
    fromUser: false,
    fromServer: true,
    queryId: null,
    tagged: false
  };
}
__name(newOperationSourceServer, "newOperationSourceServer");
function newOperationSourceServerTaggedQuery(queryId) {
  return {
    fromUser: false,
    fromServer: true,
    queryId,
    tagged: true
  };
}
__name(newOperationSourceServerTaggedQuery, "newOperationSourceServerTaggedQuery");
/**
 * @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 {
  static {
    __name(this, "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$1(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$1(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 {
  static {
    __name(this, "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 {
  static {
    __name(this, "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 {
  static {
    __name(this, "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$1(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 {
  static {
    __name(this, "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 {
  static {
    __name(this, "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;
}
__name(eventGeneratorGenerateEventsForChanges, "eventGeneratorGenerateEventsForChanges");
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_));
      }
    });
  });
}
__name(eventGeneratorGenerateEventsForType, "eventGeneratorGenerateEventsForType");
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;
  }
}
__name(eventGeneratorMaterializeSingleChange, "eventGeneratorMaterializeSingleChange");
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);
}
__name(eventGeneratorCompareChanges, "eventGeneratorCompareChanges");
/**
 * @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 };
}
__name(newViewCache, "newViewCache");
function viewCacheUpdateEventSnap(viewCache, eventSnap, complete, filtered) {
  return newViewCache(new CacheNode(eventSnap, complete, filtered), viewCache.serverCache);
}
__name(viewCacheUpdateEventSnap, "viewCacheUpdateEventSnap");
function viewCacheUpdateServerSnap(viewCache, serverSnap, complete, filtered) {
  return newViewCache(viewCache.eventCache, new CacheNode(serverSnap, complete, filtered));
}
__name(viewCacheUpdateServerSnap, "viewCacheUpdateServerSnap");
function viewCacheGetCompleteEventSnap(viewCache) {
  return viewCache.eventCache.isFullyInitialized() ? viewCache.eventCache.getNode() : null;
}
__name(viewCacheGetCompleteEventSnap, "viewCacheGetCompleteEventSnap");
function viewCacheGetCompleteServerSnap(viewCache) {
  return viewCache.serverCache.isFullyInitialized() ? viewCache.serverCache.getNode() : null;
}
__name(viewCacheGetCompleteServerSnap, "viewCacheGetCompleteServerSnap");
/**
 * @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 = /* @__PURE__ */ __name(() => {
  if (!emptyChildrenSingleton) {
    emptyChildrenSingleton = new SortedMap$1(stringCompare);
  }
  return emptyChildrenSingleton;
}, "EmptyChildren");
class ImmutableTree {
  static {
    __name(this, "ImmutableTree");
  }
  static fromObject(obj) {
    let tree = new ImmutableTree(null);
    each(obj, (childPath, childSnap) => {
      tree = tree.set(new Path(childPath), childSnap);
    });
    return tree;
  }
  constructor(value, children = EmptyChildren()) {
    this.value = value;
    this.children = children;
  }
  /**
   * 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(fn) {
    return this.fold_(newEmptyPath(), fn);
  }
  /**
   * Recursive helper for public-facing fold() method
   */
  fold_(pathSoFar, fn) {
    const accum = {};
    this.children.inorderTraversal((childKey, childTree) => {
      accum[childKey] = childTree.fold_(pathChild(pathSoFar, childKey), fn);
    });
    return fn(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 {
  static {
    __name(this, "CompoundWrite");
  }
  constructor(writeTree_) {
    this.writeTree_ = writeTree_;
  }
  static empty() {
    return new CompoundWrite(new ImmutableTree(null));
  }
}
function compoundWriteAddWrite(compoundWrite, path, node2) {
  if (pathIsEmpty(path)) {
    return new CompoundWrite(new ImmutableTree(node2));
  } 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, node2);
      return new CompoundWrite(compoundWrite.writeTree_.set(rootMostPath, value));
    } else {
      const subtree = new ImmutableTree(node2);
      const newWriteTree2 = compoundWrite.writeTree_.setTree(path, subtree);
      return new CompoundWrite(newWriteTree2);
    }
  }
}
__name(compoundWriteAddWrite, "compoundWriteAddWrite");
function compoundWriteAddWrites(compoundWrite, path, updates) {
  let newWrite = compoundWrite;
  each(updates, (childKey, node2) => {
    newWrite = compoundWriteAddWrite(newWrite, pathChild(path, childKey), node2);
  });
  return newWrite;
}
__name(compoundWriteAddWrites, "compoundWriteAddWrites");
function compoundWriteRemoveWrite(compoundWrite, path) {
  if (pathIsEmpty(path)) {
    return CompoundWrite.empty();
  } else {
    const newWriteTree2 = compoundWrite.writeTree_.setTree(path, new ImmutableTree(null));
    return new CompoundWrite(newWriteTree2);
  }
}
__name(compoundWriteRemoveWrite, "compoundWriteRemoveWrite");
function compoundWriteHasCompleteWrite(compoundWrite, path) {
  return compoundWriteGetCompleteNode(compoundWrite, path) != null;
}
__name(compoundWriteHasCompleteWrite, "compoundWriteHasCompleteWrite");
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;
  }
}
__name(compoundWriteGetCompleteNode, "compoundWriteGetCompleteNode");
function compoundWriteGetCompleteChildren(compoundWrite) {
  const children = [];
  const node2 = compoundWrite.writeTree_.value;
  if (node2 != null) {
    if (!node2.isLeafNode()) {
      node2.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;
}
__name(compoundWriteGetCompleteChildren, "compoundWriteGetCompleteChildren");
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));
    }
  }
}
__name(compoundWriteChildCompoundWrite, "compoundWriteChildCompoundWrite");
function compoundWriteIsEmpty(compoundWrite) {
  return compoundWrite.writeTree_.isEmpty();
}
__name(compoundWriteIsEmpty, "compoundWriteIsEmpty");
function compoundWriteApply(compoundWrite, node2) {
  return applySubtreeWrite(newEmptyPath(), compoundWrite.writeTree_, node2);
}
__name(compoundWriteApply, "compoundWriteApply");
function applySubtreeWrite(relativePath, writeTree, node2) {
  if (writeTree.value != null) {
    return node2.updateChild(relativePath, writeTree.value);
  } else {
    let priorityWrite = null;
    writeTree.children.inorderTraversal((childKey, childTree) => {
      if (childKey === ".priority") {
        assert$1(childTree.value !== null, "Priority writes must always be leaf nodes");
        priorityWrite = childTree.value;
      } else {
        node2 = applySubtreeWrite(pathChild(relativePath, childKey), childTree, node2);
      }
    });
    if (!node2.getChild(relativePath).isEmpty() && priorityWrite !== null) {
      node2 = node2.updateChild(pathChild(relativePath, ".priority"), priorityWrite);
    }
    return node2;
  }
}
__name(applySubtreeWrite, "applySubtreeWrite");
/**
 * @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);
}
__name(writeTreeChildWrites, "writeTreeChildWrites");
function writeTreeAddOverwrite(writeTree, path, snap, writeId, visible) {
  assert$1(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;
}
__name(writeTreeAddOverwrite, "writeTreeAddOverwrite");
function writeTreeAddMerge(writeTree, path, changedChildren, writeId) {
  assert$1(writeId > writeTree.lastWriteId, "Stacking an older merge on top of newer ones");
  writeTree.allWrites.push({
    path,
    children: changedChildren,
    writeId,
    visible: true
  });
  writeTree.visibleWrites = compoundWriteAddWrites(writeTree.visibleWrites, path, changedChildren);
  writeTree.lastWriteId = writeId;
}
__name(writeTreeAddMerge, "writeTreeAddMerge");
function writeTreeGetWrite(writeTree, writeId) {
  for (let i2 = 0; i2 < writeTree.allWrites.length; i2++) {
    const record2 = writeTree.allWrites[i2];
    if (record2.writeId === writeId) {
      return record2;
    }
  }
  return null;
}
__name(writeTreeGetWrite, "writeTreeGetWrite");
function writeTreeRemoveWrite(writeTree, writeId) {
  const idx = writeTree.allWrites.findIndex((s2) => {
    return s2.writeId === writeId;
  });
  assert$1(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;
  }
}
__name(writeTreeRemoveWrite, "writeTreeRemoveWrite");
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;
  }
}
__name(writeTreeRecordContainsPath_, "writeTreeRecordContainsPath_");
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;
  }
}
__name(writeTreeResetTree_, "writeTreeResetTree_");
function writeTreeDefaultFilter_(write2) {
  return write2.visible;
}
__name(writeTreeDefaultFilter_, "writeTreeDefaultFilter_");
function writeTreeLayerTree_(writes, filter3, treeRoot) {
  let compoundWrite = CompoundWrite.empty();
  for (let i2 = 0; i2 < writes.length; ++i2) {
    const write2 = writes[i2];
    if (filter3(write2)) {
      const writePath = write2.path;
      let relativePath;
      if (write2.snap) {
        if (pathContains(treeRoot, writePath)) {
          relativePath = newRelativePath(treeRoot, writePath);
          compoundWrite = compoundWriteAddWrite(compoundWrite, relativePath, write2.snap);
        } else if (pathContains(writePath, treeRoot)) {
          relativePath = newRelativePath(writePath, treeRoot);
          compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), write2.snap.getChild(relativePath));
        } else ;
      } else if (write2.children) {
        if (pathContains(treeRoot, writePath)) {
          relativePath = newRelativePath(treeRoot, writePath);
          compoundWrite = compoundWriteAddWrites(compoundWrite, relativePath, write2.children);
        } else if (pathContains(writePath, treeRoot)) {
          relativePath = newRelativePath(writePath, treeRoot);
          if (pathIsEmpty(relativePath)) {
            compoundWrite = compoundWriteAddWrites(compoundWrite, newEmptyPath(), write2.children);
          } else {
            const child2 = safeGet(write2.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;
}
__name(writeTreeLayerTree_, "writeTreeLayerTree_");
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 merge2 = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
    if (!includeHiddenWrites && compoundWriteIsEmpty(merge2)) {
      return completeServerCache;
    } else {
      if (!includeHiddenWrites && completeServerCache == null && !compoundWriteHasCompleteWrite(merge2, newEmptyPath())) {
        return null;
      } else {
        const filter3 = /* @__PURE__ */ __name(function(write2) {
          return (write2.visible || includeHiddenWrites) && (!writeIdsToExclude || !~writeIdsToExclude.indexOf(write2.writeId)) && (pathContains(write2.path, treePath) || pathContains(treePath, write2.path));
        }, "filter");
        const mergeAtPath = writeTreeLayerTree_(writeTree.allWrites, filter3, treePath);
        const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;
        return compoundWriteApply(mergeAtPath, layeredCache);
      }
    }
  }
}
__name(writeTreeCalcCompleteEventCache, "writeTreeCalcCompleteEventCache");
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 merge2 = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
    completeServerChildren.forEachChild(PRIORITY_INDEX, (childName, childNode) => {
      const node2 = compoundWriteApply(compoundWriteChildCompoundWrite(merge2, new Path(childName)), childNode);
      completeChildren = completeChildren.updateImmediateChild(childName, node2);
    });
    compoundWriteGetCompleteChildren(merge2).forEach((namedNode) => {
      completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);
    });
    return completeChildren;
  } else {
    const merge2 = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
    compoundWriteGetCompleteChildren(merge2).forEach((namedNode) => {
      completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);
    });
    return completeChildren;
  }
}
__name(writeTreeCalcCompleteEventChildren, "writeTreeCalcCompleteEventChildren");
function writeTreeCalcEventCacheAfterServerOverwrite(writeTree, treePath, childPath, existingEventSnap, existingServerSnap) {
  assert$1(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));
    }
  }
}
__name(writeTreeCalcEventCacheAfterServerOverwrite, "writeTreeCalcEventCacheAfterServerOverwrite");
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;
    }
  }
}
__name(writeTreeCalcCompleteChild, "writeTreeCalcCompleteChild");
function writeTreeShadowingWrite(writeTree, path) {
  return compoundWriteGetCompleteNode(writeTree.visibleWrites, path);
}
__name(writeTreeShadowingWrite, "writeTreeShadowingWrite");
function writeTreeCalcIndexedSlice(writeTree, treePath, completeServerData, startPost, count2, reverse2, index2) {
  let toIterate;
  const merge2 = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  const shadowingNode = compoundWriteGetCompleteNode(merge2, newEmptyPath());
  if (shadowingNode != null) {
    toIterate = shadowingNode;
  } else if (completeServerData != null) {
    toIterate = compoundWriteApply(merge2, completeServerData);
  } else {
    return [];
  }
  toIterate = toIterate.withIndex(index2);
  if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {
    const nodes = [];
    const cmp2 = index2.getCompare();
    const iter = reverse2 ? toIterate.getReverseIteratorFrom(startPost, index2) : toIterate.getIteratorFrom(startPost, index2);
    let next = iter.getNext();
    while (next && nodes.length < count2) {
      if (cmp2(next, startPost) !== 0) {
        nodes.push(next);
      }
      next = iter.getNext();
    }
    return nodes;
  } else {
    return [];
  }
}
__name(writeTreeCalcIndexedSlice, "writeTreeCalcIndexedSlice");
function newWriteTree() {
  return {
    visibleWrites: CompoundWrite.empty(),
    allWrites: [],
    lastWriteId: -1
  };
}
__name(newWriteTree, "newWriteTree");
function writeTreeRefCalcCompleteEventCache(writeTreeRef, completeServerCache, writeIdsToExclude, includeHiddenWrites) {
  return writeTreeCalcCompleteEventCache(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites);
}
__name(writeTreeRefCalcCompleteEventCache, "writeTreeRefCalcCompleteEventCache");
function writeTreeRefCalcCompleteEventChildren(writeTreeRef, completeServerChildren) {
  return writeTreeCalcCompleteEventChildren(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerChildren);
}
__name(writeTreeRefCalcCompleteEventChildren, "writeTreeRefCalcCompleteEventChildren");
function writeTreeRefCalcEventCacheAfterServerOverwrite(writeTreeRef, path, existingEventSnap, existingServerSnap) {
  return writeTreeCalcEventCacheAfterServerOverwrite(writeTreeRef.writeTree, writeTreeRef.treePath, path, existingEventSnap, existingServerSnap);
}
__name(writeTreeRefCalcEventCacheAfterServerOverwrite, "writeTreeRefCalcEventCacheAfterServerOverwrite");
function writeTreeRefShadowingWrite(writeTreeRef, path) {
  return writeTreeShadowingWrite(writeTreeRef.writeTree, pathChild(writeTreeRef.treePath, path));
}
__name(writeTreeRefShadowingWrite, "writeTreeRefShadowingWrite");
function writeTreeRefCalcIndexedSlice(writeTreeRef, completeServerData, startPost, count2, reverse2, index2) {
  return writeTreeCalcIndexedSlice(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerData, startPost, count2, reverse2, index2);
}
__name(writeTreeRefCalcIndexedSlice, "writeTreeRefCalcIndexedSlice");
function writeTreeRefCalcCompleteChild(writeTreeRef, childKey, existingServerCache) {
  return writeTreeCalcCompleteChild(writeTreeRef.writeTree, writeTreeRef.treePath, childKey, existingServerCache);
}
__name(writeTreeRefCalcCompleteChild, "writeTreeRefCalcCompleteChild");
function writeTreeRefChild(writeTreeRef, childName) {
  return newWriteTreeRef(pathChild(writeTreeRef.treePath, childName), writeTreeRef.writeTree);
}
__name(writeTreeRefChild, "writeTreeRefChild");
function newWriteTreeRef(path, writeTree) {
  return {
    treePath: path,
    writeTree
  };
}
__name(newWriteTreeRef, "newWriteTreeRef");
/**
 * @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 {
  static {
    __name(this, "ChildChangeAccumulator");
  }
  constructor() {
    this.changeMap = /* @__PURE__ */ new Map();
  }
  trackChildChange(change) {
    const type = change.type;
    const childKey = change.childName;
    assert$1(type === "child_added" || type === "child_changed" || type === "child_removed", "Only child changes supported for tracking");
    assert$1(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_ {
  static {
    __name(this, "NoCompleteChildSource_");
  }
  getCompleteChild(childKey) {
    return null;
  }
  getChildAfterChild(index2, child2, reverse2) {
    return null;
  }
}
const NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();
class WriteTreeCompleteChildSource {
  static {
    __name(this, "WriteTreeCompleteChildSource");
  }
  constructor(writes_, viewCache_, optCompleteServerCache_ = null) {
    this.writes_ = writes_;
    this.viewCache_ = viewCache_;
    this.optCompleteServerCache_ = optCompleteServerCache_;
  }
  getCompleteChild(childKey) {
    const node2 = this.viewCache_.eventCache;
    if (node2.isCompleteForChild(childKey)) {
      return node2.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, reverse2) {
    const completeServerData = this.optCompleteServerCache_ != null ? this.optCompleteServerCache_ : viewCacheGetCompleteServerSnap(this.viewCache_);
    const nodes = writeTreeRefCalcIndexedSlice(this.writes_, completeServerData, child2, 1, reverse2, 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(filter3) {
  return { filter: filter3 };
}
__name(newViewProcessor, "newViewProcessor");
function viewProcessorAssertIndexed(viewProcessor, viewCache) {
  assert$1(viewCache.eventCache.getNode().isIndexed(viewProcessor.filter.getIndex()), "Event snap not indexed");
  assert$1(viewCache.serverCache.getNode().isIndexed(viewProcessor.filter.getIndex()), "Server snap not indexed");
}
__name(viewProcessorAssertIndexed, "viewProcessorAssertIndexed");
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$1(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 merge2 = operation;
    if (merge2.source.fromUser) {
      newViewCache2 = viewProcessorApplyUserMerge(viewProcessor, oldViewCache, merge2.path, merge2.children, writesCache, completeCache, accumulator);
    } else {
      assert$1(merge2.source.fromServer, "Unknown source.");
      filterServerNode = merge2.source.tagged || oldViewCache.serverCache.isFiltered();
      newViewCache2 = viewProcessorApplyServerMerge(viewProcessor, oldViewCache, merge2.path, merge2.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 };
}
__name(viewProcessorApplyOperation, "viewProcessorApplyOperation");
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)));
    }
  }
}
__name(viewProcessorMaybeAddValueEvent, "viewProcessorMaybeAddValueEvent");
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$1(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$1(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());
  }
}
__name(viewProcessorGenerateEventCacheAfterServerEvent, "viewProcessorGenerateEventCacheAfterServerEvent");
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);
}
__name(viewProcessorApplyServerOverwrite, "viewProcessorApplyServerOverwrite");
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;
}
__name(viewProcessorApplyUserOverwrite, "viewProcessorApplyUserOverwrite");
function viewProcessorCacheHasChild(viewCache, childKey) {
  return viewCache.eventCache.isCompleteForChild(childKey);
}
__name(viewProcessorCacheHasChild, "viewProcessorCacheHasChild");
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;
}
__name(viewProcessorApplyUserMerge, "viewProcessorApplyUserMerge");
function viewProcessorApplyMerge(viewProcessor, node2, merge2) {
  merge2.foreach((relativePath, childNode) => {
    node2 = node2.updateChild(relativePath, childNode);
  });
  return node2;
}
__name(viewProcessorApplyMerge, "viewProcessorApplyMerge");
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;
}
__name(viewProcessorApplyServerMerge, "viewProcessorApplyServerMerge");
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, node2) => {
        changedChildren = changedChildren.set(new Path(name2), node2);
      });
      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);
  }
}
__name(viewProcessorAckUserWrite, "viewProcessorAckUserWrite");
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);
}
__name(viewProcessorListenComplete, "viewProcessorListenComplete");
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$1(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());
  }
}
__name(viewProcessorRevertUserWrite, "viewProcessorRevertUserWrite");
/**
 * @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 {
  static {
    __name(this, "View");
  }
  constructor(query_, initialViewCache) {
    this.query_ = query_;
    this.eventRegistrations_ = [];
    const params = this.query_._queryParams;
    const indexFilter = new IndexedFilter(params.getIndex());
    const filter3 = queryParamsGetNodeFilter(params);
    this.processor_ = newViewProcessor(filter3);
    const initialServerCache = initialViewCache.serverCache;
    const initialEventCache = initialViewCache.eventCache;
    const serverSnap = indexFilter.updateFullNode(ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null);
    const eventSnap = filter3.updateFullNode(ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null);
    const newServerCache = new CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes());
    const newEventCache = new CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter3.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();
}
__name(viewGetServerCache, "viewGetServerCache");
function viewGetCompleteNode(view) {
  return viewCacheGetCompleteEventSnap(view.viewCache_);
}
__name(viewGetCompleteNode, "viewGetCompleteNode");
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;
}
__name(viewGetCompleteServerCache, "viewGetCompleteServerCache");
function viewIsEmpty(view) {
  return view.eventRegistrations_.length === 0;
}
__name(viewIsEmpty, "viewIsEmpty");
function viewAddEventRegistration(view, eventRegistration) {
  view.eventRegistrations_.push(eventRegistration);
}
__name(viewAddEventRegistration, "viewAddEventRegistration");
function viewRemoveEventRegistration(view, eventRegistration, cancelError) {
  const cancelEvents = [];
  if (cancelError) {
    assert$1(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;
}
__name(viewRemoveEventRegistration, "viewRemoveEventRegistration");
function viewApplyOperation(view, operation, writesCache, completeServerCache) {
  if (operation.type === OperationType.MERGE && operation.source.queryId !== null) {
    assert$1(viewCacheGetCompleteServerSnap(view.viewCache_), "We should always have a full cache before handling merges");
    assert$1(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$1(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);
}
__name(viewApplyOperation, "viewApplyOperation");
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);
}
__name(viewGetInitialEvents, "viewGetInitialEvents");
function viewGenerateEventsForChanges_(view, changes, eventCache, eventRegistration) {
  const registrations = eventRegistration ? [eventRegistration] : view.eventRegistrations_;
  return eventGeneratorGenerateEventsForChanges(view.eventGenerator_, changes, eventCache, registrations);
}
__name(viewGenerateEventsForChanges_, "viewGenerateEventsForChanges_");
/**
 * @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 {
  static {
    __name(this, "SyncPoint");
  }
  constructor() {
    this.views = /* @__PURE__ */ new Map();
  }
}
function syncPointSetReferenceConstructor(val) {
  assert$1(!referenceConstructor$1, "__referenceConstructor has already been defined");
  referenceConstructor$1 = val;
}
__name(syncPointSetReferenceConstructor, "syncPointSetReferenceConstructor");
function syncPointGetReferenceConstructor() {
  assert$1(referenceConstructor$1, "Reference.ts has not been loaded");
  return referenceConstructor$1;
}
__name(syncPointGetReferenceConstructor, "syncPointGetReferenceConstructor");
function syncPointIsEmpty(syncPoint) {
  return syncPoint.views.size === 0;
}
__name(syncPointIsEmpty, "syncPointIsEmpty");
function syncPointApplyOperation(syncPoint, operation, writesCache, optCompleteServerCache) {
  const queryId = operation.source.queryId;
  if (queryId !== null) {
    const view = syncPoint.views.get(queryId);
    assert$1(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;
  }
}
__name(syncPointApplyOperation, "syncPointApplyOperation");
function syncPointGetView(syncPoint, query2, writesCache, serverCache, serverCacheComplete) {
  const queryId = query2._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(query2, viewCache);
  }
  return view;
}
__name(syncPointGetView, "syncPointGetView");
function syncPointAddEventRegistration(syncPoint, query2, eventRegistration, writesCache, serverCache, serverCacheComplete) {
  const view = syncPointGetView(syncPoint, query2, writesCache, serverCache, serverCacheComplete);
  if (!syncPoint.views.has(query2._queryIdentifier)) {
    syncPoint.views.set(query2._queryIdentifier, view);
  }
  viewAddEventRegistration(view, eventRegistration);
  return viewGetInitialEvents(view, eventRegistration);
}
__name(syncPointAddEventRegistration, "syncPointAddEventRegistration");
function syncPointRemoveEventRegistration(syncPoint, query2, eventRegistration, cancelError) {
  const queryId = query2._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())(query2._repo, query2._path));
  }
  return { removed, events: cancelEvents };
}
__name(syncPointRemoveEventRegistration, "syncPointRemoveEventRegistration");
function syncPointGetQueryViews(syncPoint) {
  const result = [];
  for (const view of syncPoint.views.values()) {
    if (!view.query._queryParams.loadsAllData()) {
      result.push(view);
    }
  }
  return result;
}
__name(syncPointGetQueryViews, "syncPointGetQueryViews");
function syncPointGetCompleteServerCache(syncPoint, path) {
  let serverCache = null;
  for (const view of syncPoint.views.values()) {
    serverCache = serverCache || viewGetCompleteServerCache(view, path);
  }
  return serverCache;
}
__name(syncPointGetCompleteServerCache, "syncPointGetCompleteServerCache");
function syncPointViewForQuery(syncPoint, query2) {
  const params = query2._queryParams;
  if (params.loadsAllData()) {
    return syncPointGetCompleteView(syncPoint);
  } else {
    const queryId = query2._queryIdentifier;
    return syncPoint.views.get(queryId);
  }
}
__name(syncPointViewForQuery, "syncPointViewForQuery");
function syncPointViewExistsForQuery(syncPoint, query2) {
  return syncPointViewForQuery(syncPoint, query2) != null;
}
__name(syncPointViewExistsForQuery, "syncPointViewExistsForQuery");
function syncPointHasCompleteView(syncPoint) {
  return syncPointGetCompleteView(syncPoint) != null;
}
__name(syncPointHasCompleteView, "syncPointHasCompleteView");
function syncPointGetCompleteView(syncPoint) {
  for (const view of syncPoint.views.values()) {
    if (view.query._queryParams.loadsAllData()) {
      return view;
    }
  }
  return null;
}
__name(syncPointGetCompleteView, "syncPointGetCompleteView");
/**
 * @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$1(!referenceConstructor, "__referenceConstructor has already been defined");
  referenceConstructor = val;
}
__name(syncTreeSetReferenceConstructor, "syncTreeSetReferenceConstructor");
function syncTreeGetReferenceConstructor() {
  assert$1(referenceConstructor, "Reference.ts has not been loaded");
  return referenceConstructor;
}
__name(syncTreeGetReferenceConstructor, "syncTreeGetReferenceConstructor");
let syncTreeNextQueryTag_ = 1;
class SyncTree {
  static {
    __name(this, "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));
  }
}
__name(syncTreeApplyUserOverwrite, "syncTreeApplyUserOverwrite");
function syncTreeApplyUserMerge(syncTree, path, changedChildren, writeId) {
  writeTreeAddMerge(syncTree.pendingWriteTree_, path, changedChildren, writeId);
  const changeTree = ImmutableTree.fromObject(changedChildren);
  return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceUser(), path, changeTree));
}
__name(syncTreeApplyUserMerge, "syncTreeApplyUserMerge");
function syncTreeAckUserWrite(syncTree, writeId, revert = false) {
  const write2 = writeTreeGetWrite(syncTree.pendingWriteTree_, writeId);
  const needToReevaluate = writeTreeRemoveWrite(syncTree.pendingWriteTree_, writeId);
  if (!needToReevaluate) {
    return [];
  } else {
    let affectedTree = new ImmutableTree(null);
    if (write2.snap != null) {
      affectedTree = affectedTree.set(newEmptyPath(), true);
    } else {
      each(write2.children, (pathString) => {
        affectedTree = affectedTree.set(new Path(pathString), true);
      });
    }
    return syncTreeApplyOperationToSyncPoints_(syncTree, new AckUserWrite(write2.path, affectedTree, revert));
  }
}
__name(syncTreeAckUserWrite, "syncTreeAckUserWrite");
function syncTreeApplyServerOverwrite(syncTree, path, newData) {
  return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceServer(), path, newData));
}
__name(syncTreeApplyServerOverwrite, "syncTreeApplyServerOverwrite");
function syncTreeApplyServerMerge(syncTree, path, changedChildren) {
  const changeTree = ImmutableTree.fromObject(changedChildren);
  return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceServer(), path, changeTree));
}
__name(syncTreeApplyServerMerge, "syncTreeApplyServerMerge");
function syncTreeApplyListenComplete(syncTree, path) {
  return syncTreeApplyOperationToSyncPoints_(syncTree, new ListenComplete(newOperationSourceServer(), path));
}
__name(syncTreeApplyListenComplete, "syncTreeApplyListenComplete");
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 [];
  }
}
__name(syncTreeApplyTaggedListenComplete, "syncTreeApplyTaggedListenComplete");
function syncTreeRemoveEventRegistration(syncTree, query2, eventRegistration, cancelError, skipListenerDedup = false) {
  const path = query2._path;
  const maybeSyncPoint = syncTree.syncPointTree_.get(path);
  let cancelEvents = [];
  if (maybeSyncPoint && (query2._queryIdentifier === "default" || syncPointViewExistsForQuery(maybeSyncPoint, query2))) {
    const removedAndEvents = syncPointRemoveEventRegistration(maybeSyncPoint, query2, 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((query3) => {
        return query3._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_(query2), defaultTag);
        } else {
          removed.forEach((queryToRemove) => {
            const tagToRemove = syncTree.queryToTagMap.get(syncTreeMakeQueryKey_(queryToRemove));
            syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToRemove), tagToRemove);
          });
        }
      }
    }
    syncTreeRemoveTags_(syncTree, removed);
  }
  return cancelEvents;
}
__name(syncTreeRemoveEventRegistration, "syncTreeRemoveEventRegistration");
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 [];
  }
}
__name(syncTreeApplyTaggedQueryOverwrite, "syncTreeApplyTaggedQueryOverwrite");
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 [];
  }
}
__name(syncTreeApplyTaggedQueryMerge, "syncTreeApplyTaggedQueryMerge");
function syncTreeAddEventRegistration(syncTree, query2, eventRegistration, skipSetupListener = false) {
  const path = query2._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, query2);
  if (!viewAlreadyExists && !query2._queryParams.loadsAllData()) {
    const queryKey = syncTreeMakeQueryKey_(query2);
    assert$1(!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, query2, eventRegistration, writesCache, serverCache, serverCacheComplete);
  if (!viewAlreadyExists && !foundAncestorDefaultView && !skipSetupListener) {
    const view = syncPointViewForQuery(syncPoint, query2);
    events2 = events2.concat(syncTreeSetupListener_(syncTree, query2, view));
  }
  return events2;
}
__name(syncTreeAddEventRegistration, "syncTreeAddEventRegistration");
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);
}
__name(syncTreeCalcCompleteEventCache, "syncTreeCalcCompleteEventCache");
function syncTreeGetServerValue(syncTree, query2) {
  const path = query2._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_, query2._path);
  const view = syncPointGetView(syncPoint, query2, writesCache, serverCacheComplete ? serverCacheNode.getNode() : ChildrenNode.EMPTY_NODE, serverCacheComplete);
  return viewGetCompleteNode(view);
}
__name(syncTreeGetServerValue, "syncTreeGetServerValue");
function syncTreeApplyOperationToSyncPoints_(syncTree, operation) {
  return syncTreeApplyOperationHelper_(
    operation,
    syncTree.syncPointTree_,
    /*serverCache=*/
    null,
    writeTreeChildWrites(syncTree.pendingWriteTree_, newEmptyPath())
  );
}
__name(syncTreeApplyOperationToSyncPoints_, "syncTreeApplyOperationToSyncPoints_");
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;
  }
}
__name(syncTreeApplyOperationHelper_, "syncTreeApplyOperationHelper_");
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;
}
__name(syncTreeApplyOperationDescendantsHelper_, "syncTreeApplyOperationDescendantsHelper_");
function syncTreeCreateListenerForView_(syncTree, view) {
  const query2 = view.query;
  const tag = syncTreeTagForQuery(syncTree, query2);
  return {
    hashFn: /* @__PURE__ */ __name(() => {
      const cache = viewGetServerCache(view) || ChildrenNode.EMPTY_NODE;
      return cache.hash();
    }, "hashFn"),
    onComplete: /* @__PURE__ */ __name((status) => {
      if (status === "ok") {
        if (tag) {
          return syncTreeApplyTaggedListenComplete(syncTree, query2._path, tag);
        } else {
          return syncTreeApplyListenComplete(syncTree, query2._path);
        }
      } else {
        const error2 = errorForServerCode(status, query2);
        return syncTreeRemoveEventRegistration(
          syncTree,
          query2,
          /*eventRegistration*/
          null,
          error2
        );
      }
    }, "onComplete")
  };
}
__name(syncTreeCreateListenerForView_, "syncTreeCreateListenerForView_");
function syncTreeTagForQuery(syncTree, query2) {
  const queryKey = syncTreeMakeQueryKey_(query2);
  return syncTree.queryToTagMap.get(queryKey);
}
__name(syncTreeTagForQuery, "syncTreeTagForQuery");
function syncTreeMakeQueryKey_(query2) {
  return query2._path.toString() + "$" + query2._queryIdentifier;
}
__name(syncTreeMakeQueryKey_, "syncTreeMakeQueryKey_");
function syncTreeQueryKeyForTag_(syncTree, tag) {
  return syncTree.tagToQueryMap.get(tag);
}
__name(syncTreeQueryKeyForTag_, "syncTreeQueryKeyForTag_");
function syncTreeParseQueryKey_(queryKey) {
  const splitIndex = queryKey.indexOf("$");
  assert$1(splitIndex !== -1 && splitIndex < queryKey.length - 1, "Bad queryKey.");
  return {
    queryId: queryKey.substr(splitIndex + 1),
    path: new Path(queryKey.substr(0, splitIndex))
  };
}
__name(syncTreeParseQueryKey_, "syncTreeParseQueryKey_");
function syncTreeApplyTaggedOperation_(syncTree, queryPath, operation) {
  const syncPoint = syncTree.syncPointTree_.get(queryPath);
  assert$1(syncPoint, "Missing sync point for query tag that we're tracking");
  const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, queryPath);
  return syncPointApplyOperation(syncPoint, operation, writesCache, null);
}
__name(syncTreeApplyTaggedOperation_, "syncTreeApplyTaggedOperation_");
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;
    }
  });
}
__name(syncTreeCollectDistinctViewsForSubTree_, "syncTreeCollectDistinctViewsForSubTree_");
function syncTreeQueryForListening_(query2) {
  if (query2._queryParams.loadsAllData() && !query2._queryParams.isDefault()) {
    return new (syncTreeGetReferenceConstructor())(query2._repo, query2._path);
  } else {
    return query2;
  }
}
__name(syncTreeQueryForListening_, "syncTreeQueryForListening_");
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);
    }
  }
}
__name(syncTreeRemoveTags_, "syncTreeRemoveTags_");
function syncTreeGetNextQueryTag_() {
  return syncTreeNextQueryTag_++;
}
__name(syncTreeGetNextQueryTag_, "syncTreeGetNextQueryTag_");
function syncTreeSetupListener_(syncTree, query2, view) {
  const path = query2._path;
  const tag = syncTreeTagForQuery(syncTree, query2);
  const listener = syncTreeCreateListenerForView_(syncTree, view);
  const events2 = syncTree.listenProvider_.startListening(syncTreeQueryForListening_(query2), tag, listener.hashFn, listener.onComplete);
  const subtree = syncTree.syncPointTree_.subtree(path);
  if (tag) {
    assert$1(!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;
}
__name(syncTreeSetupListener_, "syncTreeSetupListener_");
/**
 * @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 {
  static {
    __name(this, "ExistingValueProvider");
  }
  constructor(node_) {
    this.node_ = node_;
  }
  getImmediateChild(childName) {
    const child2 = this.node_.getImmediateChild(childName);
    return new ExistingValueProvider(child2);
  }
  node() {
    return this.node_;
  }
}
class DeferredValueProvider {
  static {
    __name(this, "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 = /* @__PURE__ */ __name(function(values) {
  values = values || {};
  values["timestamp"] = values["timestamp"] || (/* @__PURE__ */ new Date()).getTime();
  return values;
}, "generateWithValues");
const resolveDeferredLeafValue = /* @__PURE__ */ __name(function(value, existingVal, serverValues) {
  if (!value || typeof value !== "object") {
    return value;
  }
  assert$1(".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$1(false, "Unexpected server value: " + JSON.stringify(value, null, 2));
  }
}, "resolveDeferredLeafValue");
const resolveScalarDeferredValue = /* @__PURE__ */ __name(function(op, existing, serverValues) {
  switch (op) {
    case "timestamp":
      return serverValues["timestamp"];
    default:
      assert$1(false, "Unexpected server value: " + op);
  }
}, "resolveScalarDeferredValue");
const resolveComplexDeferredValue = /* @__PURE__ */ __name(function(op, existing, unused) {
  if (!op.hasOwnProperty("increment")) {
    assert$1(false, "Unexpected server value: " + JSON.stringify(op, null, 2));
  }
  const delta2 = op["increment"];
  if (typeof delta2 !== "number") {
    assert$1(false, "Unexpected increment value: " + delta2);
  }
  const existingNode = existing.node();
  assert$1(existingNode !== null && typeof existingNode !== "undefined", "Expected ChildrenNode.EMPTY_NODE for nulls");
  if (!existingNode.isLeafNode()) {
    return delta2;
  }
  const leaf = existingNode;
  const existingVal = leaf.getValue();
  if (typeof existingVal !== "number") {
    return delta2;
  }
  return existingVal + delta2;
}, "resolveComplexDeferredValue");
const resolveDeferredValueTree = /* @__PURE__ */ __name(function(path, node2, syncTree, serverValues) {
  return resolveDeferredValue(node2, new DeferredValueProvider(syncTree, path), serverValues);
}, "resolveDeferredValueTree");
const resolveDeferredValueSnapshot = /* @__PURE__ */ __name(function(node2, existing, serverValues) {
  return resolveDeferredValue(node2, new ExistingValueProvider(existing), serverValues);
}, "resolveDeferredValueSnapshot");
function resolveDeferredValue(node2, existingVal, serverValues) {
  const rawPri = node2.getPriority().val();
  const priority = resolveDeferredLeafValue(rawPri, existingVal.getImmediateChild(".priority"), serverValues);
  let newNode;
  if (node2.isLeafNode()) {
    const leafNode = node2;
    const value = resolveDeferredLeafValue(leafNode.getValue(), existingVal, serverValues);
    if (value !== leafNode.getValue() || priority !== leafNode.getPriority().val()) {
      return new LeafNode(value, nodeFromJSON(priority));
    } else {
      return node2;
    }
  } else {
    const childrenNode = node2;
    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;
  }
}
__name(resolveDeferredValue, "resolveDeferredValue");
/**
 * @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 {
  static {
    __name(this, "Tree");
  }
  /**
   * @param name - Optional name of the node.
   * @param parent - Optional parent node.
   * @param node - Optional node to wrap.
   */
  constructor(name2 = "", parent2 = null, node2 = { children: {}, childCount: 0 }) {
    this.name = name2;
    this.parent = parent2;
    this.node = node2;
  }
}
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;
}
__name(treeSubTree, "treeSubTree");
function treeGetValue(tree) {
  return tree.node.value;
}
__name(treeGetValue, "treeGetValue");
function treeSetValue(tree, value) {
  tree.node.value = value;
  treeUpdateParents(tree);
}
__name(treeSetValue, "treeSetValue");
function treeHasChildren(tree) {
  return tree.node.childCount > 0;
}
__name(treeHasChildren, "treeHasChildren");
function treeIsEmpty(tree) {
  return treeGetValue(tree) === void 0 && !treeHasChildren(tree);
}
__name(treeIsEmpty, "treeIsEmpty");
function treeForEachChild(tree, action) {
  each(tree.node.children, (child2, childTree) => {
    action(new Tree(child2, tree, childTree));
  });
}
__name(treeForEachChild, "treeForEachChild");
function treeForEachDescendant(tree, action, includeSelf, childrenFirst) {
  if (includeSelf && !childrenFirst) {
    action(tree);
  }
  treeForEachChild(tree, (child2) => {
    treeForEachDescendant(child2, action, true, childrenFirst);
  });
  if (includeSelf && childrenFirst) {
    action(tree);
  }
}
__name(treeForEachDescendant, "treeForEachDescendant");
function treeForEachAncestor(tree, action, includeSelf) {
  let node2 = includeSelf ? tree : tree.parent;
  while (node2 !== null) {
    if (action(node2)) {
      return true;
    }
    node2 = node2.parent;
  }
  return false;
}
__name(treeForEachAncestor, "treeForEachAncestor");
function treeGetPath(tree) {
  return new Path(tree.parent === null ? tree.name : treeGetPath(tree.parent) + "/" + tree.name);
}
__name(treeGetPath, "treeGetPath");
function treeUpdateParents(tree) {
  if (tree.parent !== null) {
    treeUpdateChild(tree.parent, tree.name, tree);
  }
}
__name(treeUpdateParents, "treeUpdateParents");
function treeUpdateChild(tree, childName, child2) {
  const childEmpty = treeIsEmpty(child2);
  const childExists = contains$2(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);
  }
}
__name(treeUpdateChild, "treeUpdateChild");
/**
 * @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 = /* @__PURE__ */ __name(function(key) {
  return typeof key === "string" && key.length !== 0 && !INVALID_KEY_REGEX_.test(key);
}, "isValidKey");
const isValidPathString = /* @__PURE__ */ __name(function(pathString) {
  return typeof pathString === "string" && pathString.length !== 0 && !INVALID_PATH_REGEX_.test(pathString);
}, "isValidPathString");
const isValidRootPathString = /* @__PURE__ */ __name(function(pathString) {
  if (pathString) {
    pathString = pathString.replace(/^\/*\.info(\/|$)/, "/");
  }
  return isValidPathString(pathString);
}, "isValidRootPathString");
const isValidPriority = /* @__PURE__ */ __name(function(priority) {
  return priority === null || typeof priority === "string" || typeof priority === "number" && !isInvalidJSONNumber(priority) || priority && typeof priority === "object" && // eslint-disable-next-line @typescript-eslint/no-explicit-any
  contains$2(priority, ".sv");
}, "isValidPriority");
const validateFirebaseDataArg = /* @__PURE__ */ __name(function(fnName, value, path, optional) {
  if (optional && value === void 0) {
    return;
  }
  validateFirebaseData(errorPrefix(fnName, "value"), value, path);
}, "validateFirebaseDataArg");
const validateFirebaseData = /* @__PURE__ */ __name(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.");
    }
  }
}, "validateFirebaseData");
const validateFirebaseMergePaths = /* @__PURE__ */ __name(function(errorPrefix2, mergePaths) {
  let i2, curPath;
  for (i2 = 0; i2 < mergePaths.length; i2++) {
    curPath = mergePaths[i2];
    const keys2 = pathSlice(curPath);
    for (let j2 = 0; j2 < keys2.length; j2++) {
      if (keys2[j2] === ".priority" && j2 === keys2.length - 1) ;
      else if (!isValidKey(keys2[j2])) {
        throw new Error(errorPrefix2 + "contains an invalid key (" + keys2[j2] + ") in path " + curPath.toString() + `. Keys must be non-empty strings and can't contain ".", "#", "$", "/", "[", or "]"`);
      }
    }
  }
  mergePaths.sort(pathCompare);
  let prevPath = null;
  for (i2 = 0; i2 < mergePaths.length; i2++) {
    curPath = mergePaths[i2];
    if (prevPath !== null && pathContains(prevPath, curPath)) {
      throw new Error(errorPrefix2 + "contains a path " + prevPath.toString() + " that is ancestor of another path " + curPath.toString());
    }
    prevPath = curPath;
  }
}, "validateFirebaseMergePaths");
const validateFirebaseMergeDataArg = /* @__PURE__ */ __name(function(fnName, data, path, optional) {
  if (optional && data === void 0) {
    return;
  }
  const errorPrefix$1 = errorPrefix(fnName, "values");
  if (!(data && typeof data === "object") || Array.isArray(data)) {
    throw new Error(errorPrefix$1 + " must be an object containing the children to replace.");
  }
  const mergePaths = [];
  each(data, (key, value) => {
    const curPath = new Path(key);
    validateFirebaseData(errorPrefix$1, value, pathChild(path, curPath));
    if (pathGetBack(curPath) === ".priority") {
      if (!isValidPriority(value)) {
        throw new Error(errorPrefix$1 + "contains an invalid value for '" + curPath.toString() + "', which must be a valid Firebase priority (a string, finite number, server value, or null).");
      }
    }
    mergePaths.push(curPath);
  });
  validateFirebaseMergePaths(errorPrefix$1, mergePaths);
}, "validateFirebaseMergeDataArg");
const validatePriority = /* @__PURE__ */ __name(function(fnName, priority, optional) {
  if (optional && priority === void 0) {
    return;
  }
  if (isInvalidJSONNumber(priority)) {
    throw new Error(errorPrefix(fnName, "priority") + "is " + priority.toString() + ", but must be a valid Firebase priority (a string, finite number, server value, or null).");
  }
  if (!isValidPriority(priority)) {
    throw new Error(errorPrefix(fnName, "priority") + "must be a valid Firebase priority (a string, finite number, server value, or null).");
  }
}, "validatePriority");
const validateKey = /* @__PURE__ */ __name(function(fnName, argumentName, key, optional) {
  if (optional && key === void 0) {
    return;
  }
  if (!isValidKey(key)) {
    throw new Error(errorPrefix(fnName, argumentName) + 'was an invalid key = "' + key + `".  Firebase keys must be non-empty strings and can't contain ".", "#", "$", "/", "[", or "]").`);
  }
}, "validateKey");
const validatePathString = /* @__PURE__ */ __name(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 "]"`);
  }
}, "validatePathString");
const validateRootPathString = /* @__PURE__ */ __name(function(fnName, argumentName, pathString, optional) {
  if (pathString) {
    pathString = pathString.replace(/^\/*\.info(\/|$)/, "/");
  }
  validatePathString(fnName, argumentName, pathString, optional);
}, "validateRootPathString");
const validateWritablePath = /* @__PURE__ */ __name(function(fnName, path) {
  if (pathGetFront(path) === ".info") {
    throw new Error(fnName + " failed = Can't modify data under /.info/");
  }
}, "validateWritablePath");
const validateUrl = /* @__PURE__ */ __name(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 "]".`);
  }
}, "validateUrl");
/**
 * @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 {
  static {
    __name(this, "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);
  }
}
__name(eventQueueQueueEvents, "eventQueueQueueEvents");
function eventQueueRaiseEventsAtPath(eventQueue, path, eventDataList) {
  eventQueueQueueEvents(eventQueue, eventDataList);
  eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, (eventPath) => pathEquals(eventPath, path));
}
__name(eventQueueRaiseEventsAtPath, "eventQueueRaiseEventsAtPath");
function eventQueueRaiseEventsForChangedPath(eventQueue, changedPath, eventDataList) {
  eventQueueQueueEvents(eventQueue, eventDataList);
  eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, (eventPath) => pathContains(eventPath, changedPath) || pathContains(changedPath, eventPath));
}
__name(eventQueueRaiseEventsForChangedPath, "eventQueueRaiseEventsForChangedPath");
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_--;
}
__name(eventQueueRaiseQueuedEventsMatchingPredicate, "eventQueueRaiseQueuedEventsMatchingPredicate");
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$1) {
        log$1("event: " + eventData.toString());
      }
      exceptionGuard(eventFn);
    }
  }
}
__name(eventListRaise, "eventListRaise");
/**
 * @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 {
  static {
    __name(this, "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$2(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: /* @__PURE__ */ __name((query2, tag, currentHashFn, onComplete) => {
      let infoEvents = [];
      const node2 = repo.infoData_.getNode(query2._path);
      if (!node2.isEmpty()) {
        infoEvents = syncTreeApplyServerOverwrite(repo.infoSyncTree_, query2._path, node2);
        setTimeout(() => {
          onComplete("ok");
        }, 0);
      }
      return infoEvents;
    }, "startListening"),
    stopListening: /* @__PURE__ */ __name(() => {
    }, "stopListening")
  });
  repoUpdateInfo(repo, "connected", false);
  repo.serverSyncTree_ = new SyncTree({
    startListening: /* @__PURE__ */ __name((query2, tag, currentHashFn, onComplete) => {
      repo.server_.listen(query2, currentHashFn, tag, (status, data) => {
        const events2 = onComplete(status, data);
        eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query2._path, events2);
      });
      return [];
    }, "startListening"),
    stopListening: /* @__PURE__ */ __name((query2, tag) => {
      repo.server_.unlisten(query2, tag);
    }, "stopListening")
  });
}
__name(repoStart, "repoStart");
function repoServerTime(repo) {
  const offsetNode = repo.infoData_.getNode(new Path(".info/serverTimeOffset"));
  const offset = offsetNode.val() || 0;
  return (/* @__PURE__ */ new Date()).getTime() + offset;
}
__name(repoServerTime, "repoServerTime");
function repoGenerateServerValues(repo) {
  return generateWithValues({
    timestamp: repoServerTime(repo)
  });
}
__name(repoGenerateServerValues, "repoGenerateServerValues");
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$1(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$1(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);
}
__name(repoOnDataUpdate, "repoOnDataUpdate");
function repoOnConnectStatus(repo, connectStatus) {
  repoUpdateInfo(repo, "connected", connectStatus);
  if (connectStatus === false) {
    repoRunOnDisconnectEvents(repo);
  }
}
__name(repoOnConnectStatus, "repoOnConnectStatus");
function repoOnServerInfoUpdate(repo, updates) {
  each(updates, (key, value) => {
    repoUpdateInfo(repo, key, value);
  });
}
__name(repoOnServerInfoUpdate, "repoOnServerInfoUpdate");
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);
}
__name(repoUpdateInfo, "repoUpdateInfo");
function repoGetNextWriteId(repo) {
  return repo.nextWriteId_++;
}
__name(repoGetNextWriteId, "repoGetNextWriteId");
function repoGetValue(repo, query2, eventRegistration) {
  const cached = syncTreeGetServerValue(repo.serverSyncTree_, query2);
  if (cached != null) {
    return Promise.resolve(cached);
  }
  return repo.server_.get(query2).then((payload) => {
    const node2 = nodeFromJSON(payload).withIndex(query2._queryParams.getIndex());
    syncTreeAddEventRegistration(repo.serverSyncTree_, query2, eventRegistration, true);
    let events2;
    if (query2._queryParams.loadsAllData()) {
      events2 = syncTreeApplyServerOverwrite(repo.serverSyncTree_, query2._path, node2);
    } else {
      const tag = syncTreeTagForQuery(repo.serverSyncTree_, query2);
      events2 = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, query2._path, node2, tag);
    }
    eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query2._path, events2);
    syncTreeRemoveEventRegistration(repo.serverSyncTree_, query2, eventRegistration, null, true);
    return node2;
  }, (err) => {
    repoLog(repo, "get for query " + stringify$2(query2) + " failed: " + err);
    return Promise.reject(new Error(err));
  });
}
__name(repoGetValue, "repoGetValue");
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$2("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, []);
}
__name(repoSetWithPriority, "repoSetWithPriority");
function repoUpdate(repo, path, childrenToMerge, onComplete) {
  repoLog(repo, "update", { path: path.toString(), value: childrenToMerge });
  let empty2 = true;
  const serverValues = repoGenerateServerValues(repo);
  const changedChildren = {};
  each(childrenToMerge, (changedKey, changedValue) => {
    empty2 = false;
    changedChildren[changedKey] = resolveDeferredValueTree(pathChild(path, changedKey), nodeFromJSON(changedValue), repo.serverSyncTree_, serverValues);
  });
  if (!empty2) {
    const writeId = repoGetNextWriteId(repo);
    const events2 = syncTreeApplyUserMerge(repo.serverSyncTree_, path, changedChildren, writeId);
    eventQueueQueueEvents(repo.eventQueue_, events2);
    repo.server_.merge(path.toString(), childrenToMerge, (status, errorReason) => {
      const success = status === "ok";
      if (!success) {
        warn$2("update at " + path + " failed: " + status);
      }
      const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success);
      const affectedPath = clearEvents.length > 0 ? repoRerunTransactions(repo, path) : path;
      eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, clearEvents);
      repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
    });
    each(childrenToMerge, (changedPath) => {
      const affectedPath = repoAbortTransactions(repo, pathChild(path, changedPath));
      repoRerunTransactions(repo, affectedPath);
    });
    eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, []);
  } else {
    log$1("update() called with empty data.  Don't do anything.");
    repoCallOnCompleteCallback(repo, onComplete, "ok", void 0);
  }
}
__name(repoUpdate, "repoUpdate");
function repoRunOnDisconnectEvents(repo) {
  repoLog(repo, "onDisconnectEvents");
  const serverValues = repoGenerateServerValues(repo);
  const resolvedOnDisconnectTree = newSparseSnapshotTree();
  sparseSnapshotTreeForEachTree(repo.onDisconnect_, newEmptyPath(), (path, node2) => {
    const resolved = resolveDeferredValueTree(path, node2, 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);
}
__name(repoRunOnDisconnectEvents, "repoRunOnDisconnectEvents");
function repoOnDisconnectCancel(repo, path, onComplete) {
  repo.server_.onDisconnectCancel(path.toString(), (status, errorReason) => {
    if (status === "ok") {
      sparseSnapshotTreeForget(repo.onDisconnect_, path);
    }
    repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  });
}
__name(repoOnDisconnectCancel, "repoOnDisconnectCancel");
function repoOnDisconnectSet(repo, path, value, onComplete) {
  const newNode = nodeFromJSON(value);
  repo.server_.onDisconnectPut(path.toString(), newNode.val(
    /*export=*/
    true
  ), (status, errorReason) => {
    if (status === "ok") {
      sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);
    }
    repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  });
}
__name(repoOnDisconnectSet, "repoOnDisconnectSet");
function repoOnDisconnectSetWithPriority(repo, path, value, priority, onComplete) {
  const newNode = nodeFromJSON(value, priority);
  repo.server_.onDisconnectPut(path.toString(), newNode.val(
    /*export=*/
    true
  ), (status, errorReason) => {
    if (status === "ok") {
      sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);
    }
    repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  });
}
__name(repoOnDisconnectSetWithPriority, "repoOnDisconnectSetWithPriority");
function repoOnDisconnectUpdate(repo, path, childrenToMerge, onComplete) {
  if (isEmpty$4(childrenToMerge)) {
    log$1("onDisconnect().update() called with empty data.  Don't do anything.");
    repoCallOnCompleteCallback(repo, onComplete, "ok", void 0);
    return;
  }
  repo.server_.onDisconnectMerge(path.toString(), childrenToMerge, (status, errorReason) => {
    if (status === "ok") {
      each(childrenToMerge, (childName, childNode) => {
        const newChildNode = nodeFromJSON(childNode);
        sparseSnapshotTreeRemember(repo.onDisconnect_, pathChild(path, childName), newChildNode);
      });
    }
    repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  });
}
__name(repoOnDisconnectUpdate, "repoOnDisconnectUpdate");
function repoAddEventCallbackForQuery(repo, query2, eventRegistration) {
  let events2;
  if (pathGetFront(query2._path) === ".info") {
    events2 = syncTreeAddEventRegistration(repo.infoSyncTree_, query2, eventRegistration);
  } else {
    events2 = syncTreeAddEventRegistration(repo.serverSyncTree_, query2, eventRegistration);
  }
  eventQueueRaiseEventsAtPath(repo.eventQueue_, query2._path, events2);
}
__name(repoAddEventCallbackForQuery, "repoAddEventCallbackForQuery");
function repoRemoveEventCallbackForQuery(repo, query2, eventRegistration) {
  let events2;
  if (pathGetFront(query2._path) === ".info") {
    events2 = syncTreeRemoveEventRegistration(repo.infoSyncTree_, query2, eventRegistration);
  } else {
    events2 = syncTreeRemoveEventRegistration(repo.serverSyncTree_, query2, eventRegistration);
  }
  eventQueueRaiseEventsAtPath(repo.eventQueue_, query2._path, events2);
}
__name(repoRemoveEventCallbackForQuery, "repoRemoveEventCallbackForQuery");
function repoInterrupt(repo) {
  if (repo.persistentConnection_) {
    repo.persistentConnection_.interrupt(INTERRUPT_REASON);
  }
}
__name(repoInterrupt, "repoInterrupt");
function repoResume(repo) {
  if (repo.persistentConnection_) {
    repo.persistentConnection_.resume(INTERRUPT_REASON);
  }
}
__name(repoResume, "repoResume");
function repoLog(repo, ...varArgs) {
  let prefix = "";
  if (repo.persistentConnection_) {
    prefix = repo.persistentConnection_.id + ":";
  }
  log$1(prefix, ...varArgs);
}
__name(repoLog, "repoLog");
function repoCallOnCompleteCallback(repo, callback, status, errorReason) {
  if (callback) {
    exceptionGuard(() => {
      if (status === "ok") {
        callback(null);
      } else {
        const code2 = (status || "error").toUpperCase();
        let message = code2;
        if (errorReason) {
          message += ": " + errorReason;
        }
        const error2 = new Error(message);
        error2.code = code2;
        callback(error2);
      }
    });
  }
}
__name(repoCallOnCompleteCallback, "repoCallOnCompleteCallback");
function repoStartTransaction(repo, path, transactionUpdate, onComplete, unwatcher, applyLocally) {
  repoLog(repo, "transaction on " + path);
  const transaction = {
    path,
    update: transactionUpdate,
    onComplete,
    // One of TransactionStatus enums.
    status: null,
    // Used when combining transactions at different locations to figure out
    // which one goes first.
    order: LUIDGenerator(),
    // Whether to raise local events for this transaction.
    applyLocally,
    // Count of how many times we've retried the transaction.
    retryCount: 0,
    // Function to call to clean up our .on() listener.
    unwatcher,
    // Stores why a transaction was aborted.
    abortReason: null,
    currentWriteId: null,
    currentInputSnapshot: null,
    currentOutputSnapshotRaw: null,
    currentOutputSnapshotResolved: null
  };
  const currentState = repoGetLatestState(repo, path, void 0);
  transaction.currentInputSnapshot = currentState;
  const newVal = transaction.update(currentState.val());
  if (newVal === void 0) {
    transaction.unwatcher();
    transaction.currentOutputSnapshotRaw = null;
    transaction.currentOutputSnapshotResolved = null;
    if (transaction.onComplete) {
      transaction.onComplete(null, false, transaction.currentInputSnapshot);
    }
  } else {
    validateFirebaseData("transaction failed: Data returned ", newVal, transaction.path);
    transaction.status = 0;
    const queueNode = treeSubTree(repo.transactionQueueTree_, path);
    const nodeQueue = treeGetValue(queueNode) || [];
    nodeQueue.push(transaction);
    treeSetValue(queueNode, nodeQueue);
    let priorityForNode;
    if (typeof newVal === "object" && newVal !== null && contains$2(newVal, ".priority")) {
      priorityForNode = safeGet(newVal, ".priority");
      assert$1(isValidPriority(priorityForNode), "Invalid priority returned by transaction. Priority must be a valid string, finite number, server value, or null.");
    } else {
      const currentNode = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path) || ChildrenNode.EMPTY_NODE;
      priorityForNode = currentNode.getPriority().val();
    }
    const serverValues = repoGenerateServerValues(repo);
    const newNodeUnresolved = nodeFromJSON(newVal, priorityForNode);
    const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, currentState, serverValues);
    transaction.currentOutputSnapshotRaw = newNodeUnresolved;
    transaction.currentOutputSnapshotResolved = newNode;
    transaction.currentWriteId = repoGetNextWriteId(repo);
    const events2 = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, transaction.currentWriteId, transaction.applyLocally);
    eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events2);
    repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  }
}
__name(repoStartTransaction, "repoStartTransaction");
function repoGetLatestState(repo, path, excludeSets) {
  return syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path, excludeSets) || ChildrenNode.EMPTY_NODE;
}
__name(repoGetLatestState, "repoGetLatestState");
function repoSendReadyTransactions(repo, node2 = repo.transactionQueueTree_) {
  if (!node2) {
    repoPruneCompletedTransactionsBelowNode(repo, node2);
  }
  if (treeGetValue(node2)) {
    const queue = repoBuildTransactionQueue(repo, node2);
    assert$1(queue.length > 0, "Sending zero length transaction queue");
    const allRun = queue.every(
      (transaction) => transaction.status === 0
      /* TransactionStatus.RUN */
    );
    if (allRun) {
      repoSendTransactionQueue(repo, treeGetPath(node2), queue);
    }
  } else if (treeHasChildren(node2)) {
    treeForEachChild(node2, (childNode) => {
      repoSendReadyTransactions(repo, childNode);
    });
  }
}
__name(repoSendReadyTransactions, "repoSendReadyTransactions");
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$1(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$2("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);
}
__name(repoSendTransactionQueue, "repoSendTransactionQueue");
function repoRerunTransactions(repo, changedPath) {
  const rootMostTransactionNode = repoGetAncestorTransactionNode(repo, changedPath);
  const path = treeGetPath(rootMostTransactionNode);
  const queue = repoBuildTransactionQueue(repo, rootMostTransactionNode);
  repoRerunTransactionQueue(repo, queue, path);
  return path;
}
__name(repoRerunTransactions, "repoRerunTransactions");
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$1(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$2(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_);
}
__name(repoRerunTransactionQueue, "repoRerunTransactionQueue");
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;
}
__name(repoGetAncestorTransactionNode, "repoGetAncestorTransactionNode");
function repoBuildTransactionQueue(repo, transactionNode) {
  const transactionQueue = [];
  repoAggregateTransactionQueuesForNode(repo, transactionNode, transactionQueue);
  transactionQueue.sort((a2, b2) => a2.order - b2.order);
  return transactionQueue;
}
__name(repoBuildTransactionQueue, "repoBuildTransactionQueue");
function repoAggregateTransactionQueuesForNode(repo, node2, queue) {
  const nodeQueue = treeGetValue(node2);
  if (nodeQueue) {
    for (let i2 = 0; i2 < nodeQueue.length; i2++) {
      queue.push(nodeQueue[i2]);
    }
  }
  treeForEachChild(node2, (child2) => {
    repoAggregateTransactionQueuesForNode(repo, child2, queue);
  });
}
__name(repoAggregateTransactionQueuesForNode, "repoAggregateTransactionQueuesForNode");
function repoPruneCompletedTransactionsBelowNode(repo, node2) {
  const queue = treeGetValue(node2);
  if (queue) {
    let to = 0;
    for (let from2 = 0; from2 < queue.length; from2++) {
      if (queue[from2].status !== 2) {
        queue[to] = queue[from2];
        to++;
      }
    }
    queue.length = to;
    treeSetValue(node2, queue.length > 0 ? queue : void 0);
  }
  treeForEachChild(node2, (childNode) => {
    repoPruneCompletedTransactionsBelowNode(repo, childNode);
  });
}
__name(repoPruneCompletedTransactionsBelowNode, "repoPruneCompletedTransactionsBelowNode");
function repoAbortTransactions(repo, path) {
  const affectedPath = treeGetPath(repoGetAncestorTransactionNode(repo, path));
  const transactionNode = treeSubTree(repo.transactionQueueTree_, path);
  treeForEachAncestor(transactionNode, (node2) => {
    repoAbortTransactionsOnNode(repo, node2);
  });
  repoAbortTransactionsOnNode(repo, transactionNode);
  treeForEachDescendant(transactionNode, (node2) => {
    repoAbortTransactionsOnNode(repo, node2);
  });
  return affectedPath;
}
__name(repoAbortTransactions, "repoAbortTransactions");
function repoAbortTransactionsOnNode(repo, node2) {
  const queue = treeGetValue(node2);
  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$1(lastSent === i2 - 1, "All SENT items should be at beginning of queue.");
        lastSent = i2;
        queue[i2].status = 3;
        queue[i2].abortReason = "set";
      } else {
        assert$1(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(node2, void 0);
    } else {
      queue.length = lastSent + 1;
    }
    eventQueueRaiseEventsForChangedPath(repo.eventQueue_, treeGetPath(node2), events2);
    for (let i2 = 0; i2 < callbacks.length; i2++) {
      exceptionGuard(callbacks[i2]);
    }
  }
}
__name(repoAbortTransactionsOnNode, "repoAbortTransactionsOnNode");
/**
 * @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;
}
__name(decodePath, "decodePath");
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$2(`Invalid query segment '${segment}' in query '${queryString}'`);
    }
  }
  return results;
}
__name(decodeQuery, "decodeQuery");
const parseRepoInfo = /* @__PURE__ */ __name(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)
  };
}, "parseRepoInfo");
const parseDatabaseURL = /* @__PURE__ */ __name(function(dataURL) {
  let host = "", domain2 = "", subdomain = "", pathString = "", namespace = "";
  let secure = true, scheme2 = "https", port = 443;
  if (typeof dataURL === "string") {
    let colonInd = dataURL.indexOf("//");
    if (colonInd >= 0) {
      scheme2 = 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 = scheme2 === "https" || scheme2 === "wss";
      port = parseInt(host.substring(colonInd + 1), 10);
    } else {
      colonInd = host.length;
    }
    const hostWithoutPort = host.slice(0, colonInd);
    if (hostWithoutPort.toLowerCase() === "localhost") {
      domain2 = "localhost";
    } else if (hostWithoutPort.split(".").length <= 2) {
      domain2 = hostWithoutPort;
    } else {
      const dotInd = host.indexOf(".");
      subdomain = host.substring(0, dotInd).toLowerCase();
      domain2 = host.substring(dotInd + 1);
      namespace = subdomain;
    }
    if ("ns" in queryParams) {
      namespace = queryParams["ns"];
    }
  }
  return {
    host,
    port,
    domain: domain2,
    subdomain,
    secure,
    scheme: scheme2,
    pathString,
    namespace
  };
}, "parseDatabaseURL");
/**
 * @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 PUSH_CHARS = "-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz";
const nextPushId = /* @__PURE__ */ function() {
  let lastPushTime = 0;
  const lastRandChars = [];
  return function(now2) {
    const duplicateTime = now2 === lastPushTime;
    lastPushTime = now2;
    let i2;
    const timeStampChars = new Array(8);
    for (i2 = 7; i2 >= 0; i2--) {
      timeStampChars[i2] = PUSH_CHARS.charAt(now2 % 64);
      now2 = Math.floor(now2 / 64);
    }
    assert$1(now2 === 0, "Cannot push at time == 0");
    let id2 = timeStampChars.join("");
    if (!duplicateTime) {
      for (i2 = 0; i2 < 12; i2++) {
        lastRandChars[i2] = Math.floor(Math.random() * 64);
      }
    } else {
      for (i2 = 11; i2 >= 0 && lastRandChars[i2] === 63; i2--) {
        lastRandChars[i2] = 0;
      }
      lastRandChars[i2]++;
    }
    for (i2 = 0; i2 < 12; i2++) {
      id2 += PUSH_CHARS.charAt(lastRandChars[i2]);
    }
    assert$1(id2.length === 20, "nextPushId: Length should be 20.");
    return id2;
  };
}();
/**
 * @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 {
  static {
    __name(this, "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, snapshot2, prevName) {
    this.eventType = eventType;
    this.eventRegistration = eventRegistration;
    this.snapshot = snapshot2;
    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$2(this.snapshot.exportVal());
  }
}
class CancelEvent {
  static {
    __name(this, "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 {
  static {
    __name(this, "CallbackContext");
  }
  constructor(snapshotCallback, cancelCallback) {
    this.snapshotCallback = snapshotCallback;
    this.cancelCallback = cancelCallback;
  }
  onValue(expDataSnapshot, previousChildName) {
    this.snapshotCallback.call(null, expDataSnapshot, previousChildName);
  }
  onCancel(error2) {
    assert$1(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 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 OnDisconnect {
  static {
    __name(this, "OnDisconnect");
  }
  /** @hideconstructor */
  constructor(_repo, _path) {
    this._repo = _repo;
    this._path = _path;
  }
  /**
   * Cancels all previously queued `onDisconnect()` set or update events for this
   * location and all children.
   *
   * If a write has been queued for this location via a `set()` or `update()` at a
   * parent location, the write at this location will be canceled, though writes
   * to sibling locations will still occur.
   *
   * @returns Resolves when synchronization to the server is complete.
   */
  cancel() {
    const deferred = new Deferred();
    repoOnDisconnectCancel(this._repo, this._path, deferred.wrapCallback(() => {
    }));
    return deferred.promise;
  }
  /**
   * Ensures the data at this location is deleted when the client is disconnected
   * (due to closing the browser, navigating to a new page, or network issues).
   *
   * @returns Resolves when synchronization to the server is complete.
   */
  remove() {
    validateWritablePath("OnDisconnect.remove", this._path);
    const deferred = new Deferred();
    repoOnDisconnectSet(this._repo, this._path, null, deferred.wrapCallback(() => {
    }));
    return deferred.promise;
  }
  /**
   * Ensures the data at this location is set to the specified value when the
   * client is disconnected (due to closing the browser, navigating to a new page,
   * or network issues).
   *
   * `set()` is especially useful for implementing "presence" systems, where a
   * value should be changed or cleared when a user disconnects so that they
   * appear "offline" to other users. See
   * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
   * for more information.
   *
   * Note that `onDisconnect` operations are only triggered once. If you want an
   * operation to occur each time a disconnect occurs, you'll need to re-establish
   * the `onDisconnect` operations each time.
   *
   * @param value - The value to be written to this location on disconnect (can
   * be an object, array, string, number, boolean, or null).
   * @returns Resolves when synchronization to the Database is complete.
   */
  set(value) {
    validateWritablePath("OnDisconnect.set", this._path);
    validateFirebaseDataArg("OnDisconnect.set", value, this._path, false);
    const deferred = new Deferred();
    repoOnDisconnectSet(this._repo, this._path, value, deferred.wrapCallback(() => {
    }));
    return deferred.promise;
  }
  /**
   * Ensures the data at this location is set to the specified value and priority
   * when the client is disconnected (due to closing the browser, navigating to a
   * new page, or network issues).
   *
   * @param value - The value to be written to this location on disconnect (can
   * be an object, array, string, number, boolean, or null).
   * @param priority - The priority to be written (string, number, or null).
   * @returns Resolves when synchronization to the Database is complete.
   */
  setWithPriority(value, priority) {
    validateWritablePath("OnDisconnect.setWithPriority", this._path);
    validateFirebaseDataArg("OnDisconnect.setWithPriority", value, this._path, false);
    validatePriority("OnDisconnect.setWithPriority", priority, false);
    const deferred = new Deferred();
    repoOnDisconnectSetWithPriority(this._repo, this._path, value, priority, deferred.wrapCallback(() => {
    }));
    return deferred.promise;
  }
  /**
   * Writes multiple values at this location when the client is disconnected (due
   * to closing the browser, navigating to a new page, or network issues).
   *
   * The `values` argument contains multiple property-value pairs that will be
   * written to the Database together. Each child property can either be a simple
   * property (for example, "name") or a relative path (for example, "name/first")
   * from the current location to the data to update.
   *
   * As opposed to the `set()` method, `update()` can be use to selectively update
   * only the referenced properties at the current location (instead of replacing
   * all the child properties at the current location).
   *
   * @param values - Object containing multiple values.
   * @returns Resolves when synchronization to the Database is complete.
   */
  update(values) {
    validateWritablePath("OnDisconnect.update", this._path);
    validateFirebaseMergeDataArg("OnDisconnect.update", values, this._path, false);
    const deferred = new Deferred();
    repoOnDisconnectUpdate(this._repo, this._path, values, deferred.wrapCallback(() => {
    }));
    return deferred.promise;
  }
}
/**
 * @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 {
  static {
    __name(this, "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 id2 = ObjectToUniqueKey(obj);
    return id2 === "{}" ? "default" : id2;
  }
  /**
   * 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);
  }
}
function validateNoPreviousOrderByCall(query2, fnName) {
  if (query2._orderByCalled === true) {
    throw new Error(fnName + ": You can't combine multiple orderBy calls.");
  }
}
__name(validateNoPreviousOrderByCall, "validateNoPreviousOrderByCall");
function validateQueryEndpoints(params) {
  let startNode = null;
  let endNode = null;
  if (params.hasStart()) {
    startNode = params.getIndexStartValue();
  }
  if (params.hasEnd()) {
    endNode = params.getIndexEndValue();
  }
  if (params.getIndex() === KEY_INDEX) {
    const tooManyArgsError = "Query: When ordering by key, you may only pass one argument to startAt(), endAt(), or equalTo().";
    const wrongArgTypeError = "Query: When ordering by key, the argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() must be a string.";
    if (params.hasStart()) {
      const startName = params.getIndexStartName();
      if (startName !== MIN_NAME) {
        throw new Error(tooManyArgsError);
      } else if (typeof startNode !== "string") {
        throw new Error(wrongArgTypeError);
      }
    }
    if (params.hasEnd()) {
      const endName = params.getIndexEndName();
      if (endName !== MAX_NAME) {
        throw new Error(tooManyArgsError);
      } else if (typeof endNode !== "string") {
        throw new Error(wrongArgTypeError);
      }
    }
  } else if (params.getIndex() === PRIORITY_INDEX) {
    if (startNode != null && !isValidPriority(startNode) || endNode != null && !isValidPriority(endNode)) {
      throw new Error("Query: When ordering by priority, the first argument passed to startAt(), startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value (null, a number, or a string).");
    }
  } else {
    assert$1(params.getIndex() instanceof PathIndex || params.getIndex() === VALUE_INDEX, "unknown index type.");
    if (startNode != null && typeof startNode === "object" || endNode != null && typeof endNode === "object") {
      throw new Error("Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() cannot be an object.");
    }
  }
}
__name(validateQueryEndpoints, "validateQueryEndpoints");
function validateLimit(params) {
  if (params.hasStart() && params.hasEnd() && params.hasLimit() && !params.hasAnchoredLimit()) {
    throw new Error("Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use limitToFirst() or limitToLast() instead.");
  }
}
__name(validateLimit, "validateLimit");
class ReferenceImpl extends QueryImpl {
  static {
    __name(this, "ReferenceImpl");
  }
  /** @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 {
  static {
    __name(this, "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$1(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, node2) => {
      return action(new DataSnapshot(node2, child$1(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$2(db, path) {
  db = getModularInstance(db);
  db._checkNotDeleted("ref");
  return path !== void 0 ? child$1(db._root, path) : db._root;
}
__name(ref$2, "ref$2");
function refFromURL$1(db, url) {
  db = getModularInstance(db);
  db._checkNotDeleted("refFromURL");
  const parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin);
  validateUrl("refFromURL", parsedURL);
  const repoInfo = parsedURL.repoInfo;
  if (!db._repo.repoInfo_.isCustomHost() && repoInfo.host !== db._repo.repoInfo_.host) {
    fatal("refFromURL: Host name does not match the current database: (found " + repoInfo.host + " but expected " + db._repo.repoInfo_.host + ")");
  }
  return ref$2(db, parsedURL.path.toString());
}
__name(refFromURL$1, "refFromURL$1");
function child$1(parent2, path) {
  parent2 = getModularInstance(parent2);
  if (pathGetFront(parent2._path) === null) {
    validateRootPathString("child", "path", path, false);
  } else {
    validatePathString("child", "path", path, false);
  }
  return new ReferenceImpl(parent2._repo, pathChild(parent2._path, path));
}
__name(child$1, "child$1");
function onDisconnect(ref2) {
  ref2 = getModularInstance(ref2);
  return new OnDisconnect(ref2._repo, ref2._path);
}
__name(onDisconnect, "onDisconnect");
function push(parent2, value) {
  parent2 = getModularInstance(parent2);
  validateWritablePath("push", parent2._path);
  validateFirebaseDataArg("push", value, parent2._path, true);
  const now2 = repoServerTime(parent2._repo);
  const name2 = nextPushId(now2);
  const thenablePushRef = child$1(parent2, name2);
  const pushRef = child$1(parent2, name2);
  let promise;
  if (value != null) {
    promise = set$1(pushRef, value).then(() => pushRef);
  } else {
    promise = Promise.resolve(pushRef);
  }
  thenablePushRef.then = promise.then.bind(promise);
  thenablePushRef.catch = promise.then.bind(promise, void 0);
  return thenablePushRef;
}
__name(push, "push");
function remove$1(ref2) {
  validateWritablePath("remove", ref2._path);
  return set$1(ref2, null);
}
__name(remove$1, "remove$1");
function set$1(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;
}
__name(set$1, "set$1");
function setPriority(ref2, priority) {
  ref2 = getModularInstance(ref2);
  validateWritablePath("setPriority", ref2._path);
  validatePriority("setPriority", priority, false);
  const deferred = new Deferred();
  repoSetWithPriority(ref2._repo, pathChild(ref2._path, ".priority"), priority, null, deferred.wrapCallback(() => {
  }));
  return deferred.promise;
}
__name(setPriority, "setPriority");
function setWithPriority(ref2, value, priority) {
  validateWritablePath("setWithPriority", ref2._path);
  validateFirebaseDataArg("setWithPriority", value, ref2._path, false);
  validatePriority("setWithPriority", priority, false);
  if (ref2.key === ".length" || ref2.key === ".keys") {
    throw "setWithPriority failed: " + ref2.key + " is a read-only object.";
  }
  const deferred = new Deferred();
  repoSetWithPriority(ref2._repo, ref2._path, value, priority, deferred.wrapCallback(() => {
  }));
  return deferred.promise;
}
__name(setWithPriority, "setWithPriority");
function update(ref2, values) {
  validateFirebaseMergeDataArg("update", values, ref2._path, false);
  const deferred = new Deferred();
  repoUpdate(ref2._repo, ref2._path, values, deferred.wrapCallback(() => {
  }));
  return deferred.promise;
}
__name(update, "update");
function get$3(query2) {
  query2 = getModularInstance(query2);
  const callbackContext = new CallbackContext(() => {
  });
  const container = new ValueEventRegistration(callbackContext);
  return repoGetValue(query2._repo, query2, container).then((node2) => {
    return new DataSnapshot(node2, new ReferenceImpl(query2._repo, query2._path), query2._queryParams.getIndex());
  });
}
__name(get$3, "get$3");
class ValueEventRegistration {
  static {
    __name(this, "ValueEventRegistration");
  }
  constructor(callbackContext) {
    this.callbackContext = callbackContext;
  }
  respondsTo(eventType) {
    return eventType === "value";
  }
  createEvent(change, query2) {
    const index2 = query2._queryParams.getIndex();
    return new DataEvent("value", this, new DataSnapshot(change.snapshotNode, new ReferenceImpl(query2._repo, query2._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 {
  static {
    __name(this, "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, query2) {
    assert$1(change.childName != null, "Child events should have a childName.");
    const childRef = child$1(new ReferenceImpl(query2._repo, query2._path), change.childName);
    const index2 = query2._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(query2, eventType, callback, cancelCallbackOrListenOptions, options2) {
  let cancelCallback;
  if (typeof cancelCallbackOrListenOptions === "object") {
    cancelCallback = void 0;
    options2 = cancelCallbackOrListenOptions;
  }
  if (typeof cancelCallbackOrListenOptions === "function") {
    cancelCallback = cancelCallbackOrListenOptions;
  }
  if (options2 && options2.onlyOnce) {
    const userCallback = callback;
    const onceCallback = /* @__PURE__ */ __name((dataSnapshot, previousChildName) => {
      repoRemoveEventCallbackForQuery(query2._repo, query2, container);
      userCallback(dataSnapshot, previousChildName);
    }, "onceCallback");
    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(query2._repo, query2, container);
  return () => repoRemoveEventCallbackForQuery(query2._repo, query2, container);
}
__name(addEventListener$1, "addEventListener$1");
function onValue(query2, callback, cancelCallbackOrListenOptions, options2) {
  return addEventListener$1(query2, "value", callback, cancelCallbackOrListenOptions, options2);
}
__name(onValue, "onValue");
function onChildAdded(query2, callback, cancelCallbackOrListenOptions, options2) {
  return addEventListener$1(query2, "child_added", callback, cancelCallbackOrListenOptions, options2);
}
__name(onChildAdded, "onChildAdded");
function onChildChanged(query2, callback, cancelCallbackOrListenOptions, options2) {
  return addEventListener$1(query2, "child_changed", callback, cancelCallbackOrListenOptions, options2);
}
__name(onChildChanged, "onChildChanged");
function onChildMoved(query2, callback, cancelCallbackOrListenOptions, options2) {
  return addEventListener$1(query2, "child_moved", callback, cancelCallbackOrListenOptions, options2);
}
__name(onChildMoved, "onChildMoved");
function onChildRemoved(query2, callback, cancelCallbackOrListenOptions, options2) {
  return addEventListener$1(query2, "child_removed", callback, cancelCallbackOrListenOptions, options2);
}
__name(onChildRemoved, "onChildRemoved");
function off(query2, eventType, callback) {
  let container = null;
  const expCallback = callback ? new CallbackContext(callback) : null;
  if (eventType === "value") {
    container = new ValueEventRegistration(expCallback);
  } else if (eventType) {
    container = new ChildEventRegistration(eventType, expCallback);
  }
  repoRemoveEventCallbackForQuery(query2._repo, query2, container);
}
__name(off, "off");
let QueryConstraint$1 = class QueryConstraint2 {
  static {
    __name(this, "QueryConstraint");
  }
};
let QueryEndAtConstraint$1 = class QueryEndAtConstraint2 extends QueryConstraint$1 {
  static {
    __name(this, "QueryEndAtConstraint");
  }
  constructor(_value, _key) {
    super();
    this._value = _value;
    this._key = _key;
    this.type = "endAt";
  }
  _apply(query2) {
    validateFirebaseDataArg("endAt", this._value, query2._path, true);
    const newParams = queryParamsEndAt(query2._queryParams, this._value, this._key);
    validateLimit(newParams);
    validateQueryEndpoints(newParams);
    if (query2._queryParams.hasEnd()) {
      throw new Error("endAt: Starting point was already set (by another call to endAt, endBefore or equalTo).");
    }
    return new QueryImpl(query2._repo, query2._path, newParams, query2._orderByCalled);
  }
};
function endAt$1(value, key) {
  validateKey("endAt", "key", key, true);
  return new QueryEndAtConstraint$1(value, key);
}
__name(endAt$1, "endAt$1");
class QueryEndBeforeConstraint extends QueryConstraint$1 {
  static {
    __name(this, "QueryEndBeforeConstraint");
  }
  constructor(_value, _key) {
    super();
    this._value = _value;
    this._key = _key;
    this.type = "endBefore";
  }
  _apply(query2) {
    validateFirebaseDataArg("endBefore", this._value, query2._path, false);
    const newParams = queryParamsEndBefore(query2._queryParams, this._value, this._key);
    validateLimit(newParams);
    validateQueryEndpoints(newParams);
    if (query2._queryParams.hasEnd()) {
      throw new Error("endBefore: Starting point was already set (by another call to endAt, endBefore or equalTo).");
    }
    return new QueryImpl(query2._repo, query2._path, newParams, query2._orderByCalled);
  }
}
function endBefore$1(value, key) {
  validateKey("endBefore", "key", key, true);
  return new QueryEndBeforeConstraint(value, key);
}
__name(endBefore$1, "endBefore$1");
let QueryStartAtConstraint$1 = class QueryStartAtConstraint2 extends QueryConstraint$1 {
  static {
    __name(this, "QueryStartAtConstraint");
  }
  constructor(_value, _key) {
    super();
    this._value = _value;
    this._key = _key;
    this.type = "startAt";
  }
  _apply(query2) {
    validateFirebaseDataArg("startAt", this._value, query2._path, true);
    const newParams = queryParamsStartAt(query2._queryParams, this._value, this._key);
    validateLimit(newParams);
    validateQueryEndpoints(newParams);
    if (query2._queryParams.hasStart()) {
      throw new Error("startAt: Starting point was already set (by another call to startAt, startBefore or equalTo).");
    }
    return new QueryImpl(query2._repo, query2._path, newParams, query2._orderByCalled);
  }
};
function startAt$1(value = null, key) {
  validateKey("startAt", "key", key, true);
  return new QueryStartAtConstraint$1(value, key);
}
__name(startAt$1, "startAt$1");
class QueryStartAfterConstraint extends QueryConstraint$1 {
  static {
    __name(this, "QueryStartAfterConstraint");
  }
  constructor(_value, _key) {
    super();
    this._value = _value;
    this._key = _key;
    this.type = "startAfter";
  }
  _apply(query2) {
    validateFirebaseDataArg("startAfter", this._value, query2._path, false);
    const newParams = queryParamsStartAfter(query2._queryParams, this._value, this._key);
    validateLimit(newParams);
    validateQueryEndpoints(newParams);
    if (query2._queryParams.hasStart()) {
      throw new Error("startAfter: Starting point was already set (by another call to startAt, startAfter, or equalTo).");
    }
    return new QueryImpl(query2._repo, query2._path, newParams, query2._orderByCalled);
  }
}
function startAfter$1(value, key) {
  validateKey("startAfter", "key", key, true);
  return new QueryStartAfterConstraint(value, key);
}
__name(startAfter$1, "startAfter$1");
class QueryLimitToFirstConstraint extends QueryConstraint$1 {
  static {
    __name(this, "QueryLimitToFirstConstraint");
  }
  constructor(_limit) {
    super();
    this._limit = _limit;
    this.type = "limitToFirst";
  }
  _apply(query2) {
    if (query2._queryParams.hasLimit()) {
      throw new Error("limitToFirst: Limit was already set (by another call to limitToFirst or limitToLast).");
    }
    return new QueryImpl(query2._repo, query2._path, queryParamsLimitToFirst(query2._queryParams, this._limit), query2._orderByCalled);
  }
}
function limitToFirst(limit2) {
  if (typeof limit2 !== "number" || Math.floor(limit2) !== limit2 || limit2 <= 0) {
    throw new Error("limitToFirst: First argument must be a positive integer.");
  }
  return new QueryLimitToFirstConstraint(limit2);
}
__name(limitToFirst, "limitToFirst");
class QueryLimitToLastConstraint extends QueryConstraint$1 {
  static {
    __name(this, "QueryLimitToLastConstraint");
  }
  constructor(_limit) {
    super();
    this._limit = _limit;
    this.type = "limitToLast";
  }
  _apply(query2) {
    if (query2._queryParams.hasLimit()) {
      throw new Error("limitToLast: Limit was already set (by another call to limitToFirst or limitToLast).");
    }
    return new QueryImpl(query2._repo, query2._path, queryParamsLimitToLast(query2._queryParams, this._limit), query2._orderByCalled);
  }
}
function limitToLast$1(limit2) {
  if (typeof limit2 !== "number" || Math.floor(limit2) !== limit2 || limit2 <= 0) {
    throw new Error("limitToLast: First argument must be a positive integer.");
  }
  return new QueryLimitToLastConstraint(limit2);
}
__name(limitToLast$1, "limitToLast$1");
class QueryOrderByChildConstraint extends QueryConstraint$1 {
  static {
    __name(this, "QueryOrderByChildConstraint");
  }
  constructor(_path) {
    super();
    this._path = _path;
    this.type = "orderByChild";
  }
  _apply(query2) {
    validateNoPreviousOrderByCall(query2, "orderByChild");
    const parsedPath = new Path(this._path);
    if (pathIsEmpty(parsedPath)) {
      throw new Error("orderByChild: cannot pass in empty path. Use orderByValue() instead.");
    }
    const index2 = new PathIndex(parsedPath);
    const newParams = queryParamsOrderBy(query2._queryParams, index2);
    validateQueryEndpoints(newParams);
    return new QueryImpl(
      query2._repo,
      query2._path,
      newParams,
      /*orderByCalled=*/
      true
    );
  }
}
function orderByChild(path) {
  if (path === "$key") {
    throw new Error('orderByChild: "$key" is invalid.  Use orderByKey() instead.');
  } else if (path === "$priority") {
    throw new Error('orderByChild: "$priority" is invalid.  Use orderByPriority() instead.');
  } else if (path === "$value") {
    throw new Error('orderByChild: "$value" is invalid.  Use orderByValue() instead.');
  }
  validatePathString("orderByChild", "path", path, false);
  return new QueryOrderByChildConstraint(path);
}
__name(orderByChild, "orderByChild");
class QueryOrderByKeyConstraint extends QueryConstraint$1 {
  static {
    __name(this, "QueryOrderByKeyConstraint");
  }
  constructor() {
    super(...arguments);
    this.type = "orderByKey";
  }
  _apply(query2) {
    validateNoPreviousOrderByCall(query2, "orderByKey");
    const newParams = queryParamsOrderBy(query2._queryParams, KEY_INDEX);
    validateQueryEndpoints(newParams);
    return new QueryImpl(
      query2._repo,
      query2._path,
      newParams,
      /*orderByCalled=*/
      true
    );
  }
}
function orderByKey() {
  return new QueryOrderByKeyConstraint();
}
__name(orderByKey, "orderByKey");
class QueryOrderByPriorityConstraint extends QueryConstraint$1 {
  static {
    __name(this, "QueryOrderByPriorityConstraint");
  }
  constructor() {
    super(...arguments);
    this.type = "orderByPriority";
  }
  _apply(query2) {
    validateNoPreviousOrderByCall(query2, "orderByPriority");
    const newParams = queryParamsOrderBy(query2._queryParams, PRIORITY_INDEX);
    validateQueryEndpoints(newParams);
    return new QueryImpl(
      query2._repo,
      query2._path,
      newParams,
      /*orderByCalled=*/
      true
    );
  }
}
function orderByPriority() {
  return new QueryOrderByPriorityConstraint();
}
__name(orderByPriority, "orderByPriority");
class QueryOrderByValueConstraint extends QueryConstraint$1 {
  static {
    __name(this, "QueryOrderByValueConstraint");
  }
  constructor() {
    super(...arguments);
    this.type = "orderByValue";
  }
  _apply(query2) {
    validateNoPreviousOrderByCall(query2, "orderByValue");
    const newParams = queryParamsOrderBy(query2._queryParams, VALUE_INDEX);
    validateQueryEndpoints(newParams);
    return new QueryImpl(
      query2._repo,
      query2._path,
      newParams,
      /*orderByCalled=*/
      true
    );
  }
}
function orderByValue() {
  return new QueryOrderByValueConstraint();
}
__name(orderByValue, "orderByValue");
class QueryEqualToValueConstraint extends QueryConstraint$1 {
  static {
    __name(this, "QueryEqualToValueConstraint");
  }
  constructor(_value, _key) {
    super();
    this._value = _value;
    this._key = _key;
    this.type = "equalTo";
  }
  _apply(query2) {
    validateFirebaseDataArg("equalTo", this._value, query2._path, false);
    if (query2._queryParams.hasStart()) {
      throw new Error("equalTo: Starting point was already set (by another call to startAt/startAfter or equalTo).");
    }
    if (query2._queryParams.hasEnd()) {
      throw new Error("equalTo: Ending point was already set (by another call to endAt/endBefore or equalTo).");
    }
    return new QueryEndAtConstraint$1(this._value, this._key)._apply(new QueryStartAtConstraint$1(this._value, this._key)._apply(query2));
  }
}
function equalTo(value, key) {
  validateKey("equalTo", "key", key, true);
  return new QueryEqualToValueConstraint(value, key);
}
__name(equalTo, "equalTo");
function query$1(query2, ...queryConstraints) {
  let queryImpl = getModularInstance(query2);
  for (const constraint of queryConstraints) {
    queryImpl = constraint._apply(queryImpl);
  }
  return queryImpl;
}
__name(query$1, "query$1");
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, hostAndPort, emulatorOptions, tokenProvider) {
  repo.repoInfo_ = new RepoInfo(
    hostAndPort,
    /* secure= */
    false,
    repo.repoInfo_.namespace,
    repo.repoInfo_.webSocketOnly,
    repo.repoInfo_.nodeAdmin,
    repo.repoInfo_.persistenceKey,
    repo.repoInfo_.includeNamespaceInQueryParams,
    /*isUsingEmulator=*/
    true,
    emulatorOptions
  );
  if (tokenProvider) {
    repo.authTokenProvider_ = tokenProvider;
  }
}
__name(repoManagerApplyEmulatorSettings, "repoManagerApplyEmulatorSettings");
function repoManagerDatabaseFromApp(app2, authProvider, appCheckProvider, url, nodeAdmin) {
  let dbUrl = url || app2.options.databaseURL;
  if (dbUrl === void 0) {
    if (!app2.options.projectId) {
      fatal("Can't determine Firebase Database URL. Be sure to include  a Project ID when calling firebase.initializeApp().");
    }
    log$1("Using default host for project ", app2.options.projectId);
    dbUrl = `${app2.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" && define_process_env_default) {
    dbEmulatorHost = define_process_env_default[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(app2.name, app2.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, app2, authTokenProvider, new AppCheckTokenProvider(app2, appCheckProvider));
  return new Database(repo, app2);
}
__name(repoManagerDatabaseFromApp, "repoManagerDatabaseFromApp");
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];
}
__name(repoManagerDeleteRepo, "repoManagerDeleteRepo");
function repoManagerCreateRepo(repoInfo, app2, authTokenProvider, appCheckProvider) {
  let appRepos = repos[app2.name];
  if (!appRepos) {
    appRepos = {};
    repos[app2.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;
}
__name(repoManagerCreateRepo, "repoManagerCreateRepo");
function repoManagerForceRestClient(forceRestClient2) {
  useRestClient = forceRestClient2;
}
__name(repoManagerForceRestClient, "repoManagerForceRestClient");
class Database {
  static {
    __name(this, "Database");
  }
  /** @hideconstructor */
  constructor(_repoInternal, app2) {
    this._repoInternal = _repoInternal;
    this.app = app2;
    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 checkTransportInit() {
  if (TransportManager.IS_TRANSPORT_INITIALIZED) {
    warn$2("Transport has already been initialized. Please call this function before calling ref or setting up a listener");
  }
}
__name(checkTransportInit, "checkTransportInit");
function forceWebSockets() {
  checkTransportInit();
  BrowserPollConnection.forceDisallow();
}
__name(forceWebSockets, "forceWebSockets");
function forceLongPolling() {
  checkTransportInit();
  WebSocketConnection.forceDisallow();
  BrowserPollConnection.forceAllow();
}
__name(forceLongPolling, "forceLongPolling");
function getDatabase(app2 = getApp(), url) {
  const db = _getProvider(app2, "database").getImmediate({
    identifier: url
  });
  if (!db._instanceStarted) {
    const emulator = getDefaultEmulatorHostnameAndPort("database");
    if (emulator) {
      connectDatabaseEmulator(db, ...emulator);
    }
  }
  return db;
}
__name(getDatabase, "getDatabase");
function connectDatabaseEmulator(db, host, port, options2 = {}) {
  db = getModularInstance(db);
  db._checkNotDeleted("useEmulator");
  const hostAndPort = `${host}:${port}`;
  const repo = db._repoInternal;
  if (db._instanceStarted) {
    if (hostAndPort === db._repoInternal.repoInfo_.host && deepEqual(options2, repo.repoInfo_.emulatorOptions)) {
      return;
    }
    fatal("connectDatabaseEmulator() cannot initialize or alter the emulator configuration after the database instance has started.");
  }
  let tokenProvider = void 0;
  if (repo.repoInfo_.nodeAdmin) {
    if (options2.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 (options2.mockUserToken) {
    const token = typeof options2.mockUserToken === "string" ? options2.mockUserToken : createMockUserToken(options2.mockUserToken, db.app.options.projectId);
    tokenProvider = new EmulatorTokenProvider(token);
  }
  repoManagerApplyEmulatorSettings(repo, hostAndPort, options2, tokenProvider);
}
__name(connectDatabaseEmulator, "connectDatabaseEmulator");
function goOffline(db) {
  db = getModularInstance(db);
  db._checkNotDeleted("goOffline");
  repoInterrupt(db._repo);
}
__name(goOffline, "goOffline");
function goOnline(db) {
  db = getModularInstance(db);
  db._checkNotDeleted("goOnline");
  repoResume(db._repo);
}
__name(goOnline, "goOnline");
function enableLogging(logger2, persistent) {
  enableLogging$1(logger2, persistent);
}
__name(enableLogging, "enableLogging");
/**
 * @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 app2 = container.getProvider("app").getImmediate();
      const authProvider = container.getProvider("auth-internal");
      const appCheckProvider = container.getProvider("app-check-internal");
      return repoManagerDatabaseFromApp(app2, authProvider, appCheckProvider, url);
    },
    "PUBLIC"
    /* ComponentType.PUBLIC */
  ).setMultipleInstances(true));
  registerVersion(name$7, version$1, variant);
  registerVersion(name$7, version$1, "esm2017");
}
__name(registerDatabase, "registerDatabase");
/**
 * @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 SERVER_TIMESTAMP = {
  ".sv": "timestamp"
};
function serverTimestamp$1() {
  return SERVER_TIMESTAMP;
}
__name(serverTimestamp$1, "serverTimestamp$1");
function increment$1(delta2) {
  return {
    ".sv": {
      "increment": delta2
    }
  };
}
__name(increment$1, "increment$1");
/**
 * @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 TransactionResult {
  static {
    __name(this, "TransactionResult");
  }
  /** @hideconstructor */
  constructor(committed, snapshot2) {
    this.committed = committed;
    this.snapshot = snapshot2;
  }
  /** Returns a JSON-serializable representation of this object. */
  toJSON() {
    return { committed: this.committed, snapshot: this.snapshot.toJSON() };
  }
}
function runTransaction$1(ref2, transactionUpdate, options2) {
  var _a2;
  ref2 = getModularInstance(ref2);
  validateWritablePath("Reference.transaction", ref2._path);
  if (ref2.key === ".length" || ref2.key === ".keys") {
    throw "Reference.transaction failed: " + ref2.key + " is a read-only object.";
  }
  const applyLocally = (_a2 = options2 === null || options2 === void 0 ? void 0 : options2.applyLocally) !== null && _a2 !== void 0 ? _a2 : true;
  const deferred = new Deferred();
  const promiseComplete = /* @__PURE__ */ __name((error2, committed, node2) => {
    let dataSnapshot = null;
    if (error2) {
      deferred.reject(error2);
    } else {
      dataSnapshot = new DataSnapshot(node2, new ReferenceImpl(ref2._repo, ref2._path), PRIORITY_INDEX);
      deferred.resolve(new TransactionResult(committed, dataSnapshot));
    }
  }, "promiseComplete");
  const unwatcher = onValue(ref2, () => {
  });
  repoStartTransaction(ref2._repo, ref2._path, transactionUpdate, promiseComplete, unwatcher, applyLocally);
  return deferred.promise;
}
__name(runTransaction$1, "runTransaction$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.
 */
PersistentConnection;
PersistentConnection.prototype.simpleListen = function(pathString, onComplete) {
  this.sendRequest("q", { p: pathString }, onComplete);
};
PersistentConnection.prototype.echo = function(data, onEcho) {
  this.sendRequest("echo", { d: data }, onEcho);
};
Connection;
const hijackHash = /* @__PURE__ */ __name(function(newHash) {
  const oldPut = PersistentConnection.prototype.put;
  PersistentConnection.prototype.put = function(pathString, data, onComplete, hash) {
    if (hash !== void 0) {
      hash = newHash();
    }
    oldPut.call(this, pathString, data, onComplete, hash);
  };
  return function() {
    PersistentConnection.prototype.put = oldPut;
  };
}, "hijackHash");
RepoInfo;
const forceRestClient = /* @__PURE__ */ __name(function(forceRestClient2) {
  repoManagerForceRestClient(forceRestClient2);
}, "forceRestClient");
/**
 * @license
 * Copyright 2023 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 _initStandalone({ app: app2, url, version: version2, customAuthImpl, customAppCheckImpl, nodeAdmin = false }) {
  setSDKVersion(version2);
  const componentContainer = new ComponentContainer("database-standalone");
  const authProvider = new Provider("auth-internal", componentContainer);
  let appCheckProvider;
  if (customAppCheckImpl) {
    appCheckProvider = new Provider("app-check-internal", componentContainer);
    appCheckProvider.setComponent(new Component(
      "app-check-internal",
      () => customAppCheckImpl,
      "PRIVATE"
      /* ComponentType.PRIVATE */
    ));
  }
  authProvider.setComponent(new Component(
    "auth-internal",
    () => customAuthImpl,
    "PRIVATE"
    /* ComponentType.PRIVATE */
  ));
  return repoManagerDatabaseFromApp(app2, authProvider, appCheckProvider, url, nodeAdmin);
}
__name(_initStandalone, "_initStandalone");
registerDatabase();
var commonjsGlobal$2 = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
var bloom_blob_es2018 = {};
/** @license
Copyright The Closure Library Authors.
SPDX-License-Identifier: Apache-2.0
*/
var Integer;
var Md5;
(function() {
  var h2;
  /** @license
  
   Copyright The Closure Library Authors.
   SPDX-License-Identifier: Apache-2.0
  */
  function k2(f2, a2) {
    function c2() {
    }
    __name(c2, "c");
    c2.prototype = a2.prototype;
    f2.D = a2.prototype;
    f2.prototype = new c2();
    f2.prototype.constructor = f2;
    f2.C = function(d2, e2, g2) {
      for (var b2 = Array(arguments.length - 2), r2 = 2; r2 < arguments.length; r2++) b2[r2 - 2] = arguments[r2];
      return a2.prototype[e2].apply(d2, b2);
    };
  }
  __name(k2, "k");
  function l2() {
    this.blockSize = -1;
  }
  __name(l2, "l");
  function m2() {
    this.blockSize = -1;
    this.blockSize = 64;
    this.g = Array(4);
    this.B = Array(this.blockSize);
    this.o = this.h = 0;
    this.s();
  }
  __name(m2, "m");
  k2(m2, l2);
  m2.prototype.s = function() {
    this.g[0] = 1732584193;
    this.g[1] = 4023233417;
    this.g[2] = 2562383102;
    this.g[3] = 271733878;
    this.o = this.h = 0;
  };
  function n2(f2, a2, c2) {
    c2 || (c2 = 0);
    var d2 = Array(16);
    if ("string" === typeof a2) for (var e2 = 0; 16 > e2; ++e2) d2[e2] = a2.charCodeAt(c2++) | a2.charCodeAt(c2++) << 8 | a2.charCodeAt(c2++) << 16 | a2.charCodeAt(c2++) << 24;
    else for (e2 = 0; 16 > e2; ++e2) d2[e2] = a2[c2++] | a2[c2++] << 8 | a2[c2++] << 16 | a2[c2++] << 24;
    a2 = f2.g[0];
    c2 = f2.g[1];
    e2 = f2.g[2];
    var g2 = f2.g[3];
    var b2 = a2 + (g2 ^ c2 & (e2 ^ g2)) + d2[0] + 3614090360 & 4294967295;
    a2 = c2 + (b2 << 7 & 4294967295 | b2 >>> 25);
    b2 = g2 + (e2 ^ a2 & (c2 ^ e2)) + d2[1] + 3905402710 & 4294967295;
    g2 = a2 + (b2 << 12 & 4294967295 | b2 >>> 20);
    b2 = e2 + (c2 ^ g2 & (a2 ^ c2)) + d2[2] + 606105819 & 4294967295;
    e2 = g2 + (b2 << 17 & 4294967295 | b2 >>> 15);
    b2 = c2 + (a2 ^ e2 & (g2 ^ a2)) + d2[3] + 3250441966 & 4294967295;
    c2 = e2 + (b2 << 22 & 4294967295 | b2 >>> 10);
    b2 = a2 + (g2 ^ c2 & (e2 ^ g2)) + d2[4] + 4118548399 & 4294967295;
    a2 = c2 + (b2 << 7 & 4294967295 | b2 >>> 25);
    b2 = g2 + (e2 ^ a2 & (c2 ^ e2)) + d2[5] + 1200080426 & 4294967295;
    g2 = a2 + (b2 << 12 & 4294967295 | b2 >>> 20);
    b2 = e2 + (c2 ^ g2 & (a2 ^ c2)) + d2[6] + 2821735955 & 4294967295;
    e2 = g2 + (b2 << 17 & 4294967295 | b2 >>> 15);
    b2 = c2 + (a2 ^ e2 & (g2 ^ a2)) + d2[7] + 4249261313 & 4294967295;
    c2 = e2 + (b2 << 22 & 4294967295 | b2 >>> 10);
    b2 = a2 + (g2 ^ c2 & (e2 ^ g2)) + d2[8] + 1770035416 & 4294967295;
    a2 = c2 + (b2 << 7 & 4294967295 | b2 >>> 25);
    b2 = g2 + (e2 ^ a2 & (c2 ^ e2)) + d2[9] + 2336552879 & 4294967295;
    g2 = a2 + (b2 << 12 & 4294967295 | b2 >>> 20);
    b2 = e2 + (c2 ^ g2 & (a2 ^ c2)) + d2[10] + 4294925233 & 4294967295;
    e2 = g2 + (b2 << 17 & 4294967295 | b2 >>> 15);
    b2 = c2 + (a2 ^ e2 & (g2 ^ a2)) + d2[11] + 2304563134 & 4294967295;
    c2 = e2 + (b2 << 22 & 4294967295 | b2 >>> 10);
    b2 = a2 + (g2 ^ c2 & (e2 ^ g2)) + d2[12] + 1804603682 & 4294967295;
    a2 = c2 + (b2 << 7 & 4294967295 | b2 >>> 25);
    b2 = g2 + (e2 ^ a2 & (c2 ^ e2)) + d2[13] + 4254626195 & 4294967295;
    g2 = a2 + (b2 << 12 & 4294967295 | b2 >>> 20);
    b2 = e2 + (c2 ^ g2 & (a2 ^ c2)) + d2[14] + 2792965006 & 4294967295;
    e2 = g2 + (b2 << 17 & 4294967295 | b2 >>> 15);
    b2 = c2 + (a2 ^ e2 & (g2 ^ a2)) + d2[15] + 1236535329 & 4294967295;
    c2 = e2 + (b2 << 22 & 4294967295 | b2 >>> 10);
    b2 = a2 + (e2 ^ g2 & (c2 ^ e2)) + d2[1] + 4129170786 & 4294967295;
    a2 = c2 + (b2 << 5 & 4294967295 | b2 >>> 27);
    b2 = g2 + (c2 ^ e2 & (a2 ^ c2)) + d2[6] + 3225465664 & 4294967295;
    g2 = a2 + (b2 << 9 & 4294967295 | b2 >>> 23);
    b2 = e2 + (a2 ^ c2 & (g2 ^ a2)) + d2[11] + 643717713 & 4294967295;
    e2 = g2 + (b2 << 14 & 4294967295 | b2 >>> 18);
    b2 = c2 + (g2 ^ a2 & (e2 ^ g2)) + d2[0] + 3921069994 & 4294967295;
    c2 = e2 + (b2 << 20 & 4294967295 | b2 >>> 12);
    b2 = a2 + (e2 ^ g2 & (c2 ^ e2)) + d2[5] + 3593408605 & 4294967295;
    a2 = c2 + (b2 << 5 & 4294967295 | b2 >>> 27);
    b2 = g2 + (c2 ^ e2 & (a2 ^ c2)) + d2[10] + 38016083 & 4294967295;
    g2 = a2 + (b2 << 9 & 4294967295 | b2 >>> 23);
    b2 = e2 + (a2 ^ c2 & (g2 ^ a2)) + d2[15] + 3634488961 & 4294967295;
    e2 = g2 + (b2 << 14 & 4294967295 | b2 >>> 18);
    b2 = c2 + (g2 ^ a2 & (e2 ^ g2)) + d2[4] + 3889429448 & 4294967295;
    c2 = e2 + (b2 << 20 & 4294967295 | b2 >>> 12);
    b2 = a2 + (e2 ^ g2 & (c2 ^ e2)) + d2[9] + 568446438 & 4294967295;
    a2 = c2 + (b2 << 5 & 4294967295 | b2 >>> 27);
    b2 = g2 + (c2 ^ e2 & (a2 ^ c2)) + d2[14] + 3275163606 & 4294967295;
    g2 = a2 + (b2 << 9 & 4294967295 | b2 >>> 23);
    b2 = e2 + (a2 ^ c2 & (g2 ^ a2)) + d2[3] + 4107603335 & 4294967295;
    e2 = g2 + (b2 << 14 & 4294967295 | b2 >>> 18);
    b2 = c2 + (g2 ^ a2 & (e2 ^ g2)) + d2[8] + 1163531501 & 4294967295;
    c2 = e2 + (b2 << 20 & 4294967295 | b2 >>> 12);
    b2 = a2 + (e2 ^ g2 & (c2 ^ e2)) + d2[13] + 2850285829 & 4294967295;
    a2 = c2 + (b2 << 5 & 4294967295 | b2 >>> 27);
    b2 = g2 + (c2 ^ e2 & (a2 ^ c2)) + d2[2] + 4243563512 & 4294967295;
    g2 = a2 + (b2 << 9 & 4294967295 | b2 >>> 23);
    b2 = e2 + (a2 ^ c2 & (g2 ^ a2)) + d2[7] + 1735328473 & 4294967295;
    e2 = g2 + (b2 << 14 & 4294967295 | b2 >>> 18);
    b2 = c2 + (g2 ^ a2 & (e2 ^ g2)) + d2[12] + 2368359562 & 4294967295;
    c2 = e2 + (b2 << 20 & 4294967295 | b2 >>> 12);
    b2 = a2 + (c2 ^ e2 ^ g2) + d2[5] + 4294588738 & 4294967295;
    a2 = c2 + (b2 << 4 & 4294967295 | b2 >>> 28);
    b2 = g2 + (a2 ^ c2 ^ e2) + d2[8] + 2272392833 & 4294967295;
    g2 = a2 + (b2 << 11 & 4294967295 | b2 >>> 21);
    b2 = e2 + (g2 ^ a2 ^ c2) + d2[11] + 1839030562 & 4294967295;
    e2 = g2 + (b2 << 16 & 4294967295 | b2 >>> 16);
    b2 = c2 + (e2 ^ g2 ^ a2) + d2[14] + 4259657740 & 4294967295;
    c2 = e2 + (b2 << 23 & 4294967295 | b2 >>> 9);
    b2 = a2 + (c2 ^ e2 ^ g2) + d2[1] + 2763975236 & 4294967295;
    a2 = c2 + (b2 << 4 & 4294967295 | b2 >>> 28);
    b2 = g2 + (a2 ^ c2 ^ e2) + d2[4] + 1272893353 & 4294967295;
    g2 = a2 + (b2 << 11 & 4294967295 | b2 >>> 21);
    b2 = e2 + (g2 ^ a2 ^ c2) + d2[7] + 4139469664 & 4294967295;
    e2 = g2 + (b2 << 16 & 4294967295 | b2 >>> 16);
    b2 = c2 + (e2 ^ g2 ^ a2) + d2[10] + 3200236656 & 4294967295;
    c2 = e2 + (b2 << 23 & 4294967295 | b2 >>> 9);
    b2 = a2 + (c2 ^ e2 ^ g2) + d2[13] + 681279174 & 4294967295;
    a2 = c2 + (b2 << 4 & 4294967295 | b2 >>> 28);
    b2 = g2 + (a2 ^ c2 ^ e2) + d2[0] + 3936430074 & 4294967295;
    g2 = a2 + (b2 << 11 & 4294967295 | b2 >>> 21);
    b2 = e2 + (g2 ^ a2 ^ c2) + d2[3] + 3572445317 & 4294967295;
    e2 = g2 + (b2 << 16 & 4294967295 | b2 >>> 16);
    b2 = c2 + (e2 ^ g2 ^ a2) + d2[6] + 76029189 & 4294967295;
    c2 = e2 + (b2 << 23 & 4294967295 | b2 >>> 9);
    b2 = a2 + (c2 ^ e2 ^ g2) + d2[9] + 3654602809 & 4294967295;
    a2 = c2 + (b2 << 4 & 4294967295 | b2 >>> 28);
    b2 = g2 + (a2 ^ c2 ^ e2) + d2[12] + 3873151461 & 4294967295;
    g2 = a2 + (b2 << 11 & 4294967295 | b2 >>> 21);
    b2 = e2 + (g2 ^ a2 ^ c2) + d2[15] + 530742520 & 4294967295;
    e2 = g2 + (b2 << 16 & 4294967295 | b2 >>> 16);
    b2 = c2 + (e2 ^ g2 ^ a2) + d2[2] + 3299628645 & 4294967295;
    c2 = e2 + (b2 << 23 & 4294967295 | b2 >>> 9);
    b2 = a2 + (e2 ^ (c2 | ~g2)) + d2[0] + 4096336452 & 4294967295;
    a2 = c2 + (b2 << 6 & 4294967295 | b2 >>> 26);
    b2 = g2 + (c2 ^ (a2 | ~e2)) + d2[7] + 1126891415 & 4294967295;
    g2 = a2 + (b2 << 10 & 4294967295 | b2 >>> 22);
    b2 = e2 + (a2 ^ (g2 | ~c2)) + d2[14] + 2878612391 & 4294967295;
    e2 = g2 + (b2 << 15 & 4294967295 | b2 >>> 17);
    b2 = c2 + (g2 ^ (e2 | ~a2)) + d2[5] + 4237533241 & 4294967295;
    c2 = e2 + (b2 << 21 & 4294967295 | b2 >>> 11);
    b2 = a2 + (e2 ^ (c2 | ~g2)) + d2[12] + 1700485571 & 4294967295;
    a2 = c2 + (b2 << 6 & 4294967295 | b2 >>> 26);
    b2 = g2 + (c2 ^ (a2 | ~e2)) + d2[3] + 2399980690 & 4294967295;
    g2 = a2 + (b2 << 10 & 4294967295 | b2 >>> 22);
    b2 = e2 + (a2 ^ (g2 | ~c2)) + d2[10] + 4293915773 & 4294967295;
    e2 = g2 + (b2 << 15 & 4294967295 | b2 >>> 17);
    b2 = c2 + (g2 ^ (e2 | ~a2)) + d2[1] + 2240044497 & 4294967295;
    c2 = e2 + (b2 << 21 & 4294967295 | b2 >>> 11);
    b2 = a2 + (e2 ^ (c2 | ~g2)) + d2[8] + 1873313359 & 4294967295;
    a2 = c2 + (b2 << 6 & 4294967295 | b2 >>> 26);
    b2 = g2 + (c2 ^ (a2 | ~e2)) + d2[15] + 4264355552 & 4294967295;
    g2 = a2 + (b2 << 10 & 4294967295 | b2 >>> 22);
    b2 = e2 + (a2 ^ (g2 | ~c2)) + d2[6] + 2734768916 & 4294967295;
    e2 = g2 + (b2 << 15 & 4294967295 | b2 >>> 17);
    b2 = c2 + (g2 ^ (e2 | ~a2)) + d2[13] + 1309151649 & 4294967295;
    c2 = e2 + (b2 << 21 & 4294967295 | b2 >>> 11);
    b2 = a2 + (e2 ^ (c2 | ~g2)) + d2[4] + 4149444226 & 4294967295;
    a2 = c2 + (b2 << 6 & 4294967295 | b2 >>> 26);
    b2 = g2 + (c2 ^ (a2 | ~e2)) + d2[11] + 3174756917 & 4294967295;
    g2 = a2 + (b2 << 10 & 4294967295 | b2 >>> 22);
    b2 = e2 + (a2 ^ (g2 | ~c2)) + d2[2] + 718787259 & 4294967295;
    e2 = g2 + (b2 << 15 & 4294967295 | b2 >>> 17);
    b2 = c2 + (g2 ^ (e2 | ~a2)) + d2[9] + 3951481745 & 4294967295;
    f2.g[0] = f2.g[0] + a2 & 4294967295;
    f2.g[1] = f2.g[1] + (e2 + (b2 << 21 & 4294967295 | b2 >>> 11)) & 4294967295;
    f2.g[2] = f2.g[2] + e2 & 4294967295;
    f2.g[3] = f2.g[3] + g2 & 4294967295;
  }
  __name(n2, "n");
  m2.prototype.u = function(f2, a2) {
    void 0 === a2 && (a2 = f2.length);
    for (var c2 = a2 - this.blockSize, d2 = this.B, e2 = this.h, g2 = 0; g2 < a2; ) {
      if (0 == e2) for (; g2 <= c2; ) n2(this, f2, g2), g2 += this.blockSize;
      if ("string" === typeof f2) for (; g2 < a2; ) {
        if (d2[e2++] = f2.charCodeAt(g2++), e2 == this.blockSize) {
          n2(this, d2);
          e2 = 0;
          break;
        }
      }
      else for (; g2 < a2; ) if (d2[e2++] = f2[g2++], e2 == this.blockSize) {
        n2(this, d2);
        e2 = 0;
        break;
      }
    }
    this.h = e2;
    this.o += a2;
  };
  m2.prototype.v = function() {
    var f2 = Array((56 > this.h ? this.blockSize : 2 * this.blockSize) - this.h);
    f2[0] = 128;
    for (var a2 = 1; a2 < f2.length - 8; ++a2) f2[a2] = 0;
    var c2 = 8 * this.o;
    for (a2 = f2.length - 8; a2 < f2.length; ++a2) f2[a2] = c2 & 255, c2 /= 256;
    this.u(f2);
    f2 = Array(16);
    for (a2 = c2 = 0; 4 > a2; ++a2) for (var d2 = 0; 32 > d2; d2 += 8) f2[c2++] = this.g[a2] >>> d2 & 255;
    return f2;
  };
  function p2(f2, a2) {
    var c2 = q2;
    return Object.prototype.hasOwnProperty.call(c2, f2) ? c2[f2] : c2[f2] = a2(f2);
  }
  __name(p2, "p");
  function t2(f2, a2) {
    this.h = a2;
    for (var c2 = [], d2 = true, e2 = f2.length - 1; 0 <= e2; e2--) {
      var g2 = f2[e2] | 0;
      d2 && g2 == a2 || (c2[e2] = g2, d2 = false);
    }
    this.g = c2;
  }
  __name(t2, "t");
  var q2 = {};
  function u2(f2) {
    return -128 <= f2 && 128 > f2 ? p2(f2, function(a2) {
      return new t2([a2 | 0], 0 > a2 ? -1 : 0);
    }) : new t2([f2 | 0], 0 > f2 ? -1 : 0);
  }
  __name(u2, "u");
  function v2(f2) {
    if (isNaN(f2) || !isFinite(f2)) return w2;
    if (0 > f2) return x2(v2(-f2));
    for (var a2 = [], c2 = 1, d2 = 0; f2 >= c2; d2++) a2[d2] = f2 / c2 | 0, c2 *= 4294967296;
    return new t2(a2, 0);
  }
  __name(v2, "v");
  function y2(f2, a2) {
    if (0 == f2.length) throw Error("number format error: empty string");
    a2 = a2 || 10;
    if (2 > a2 || 36 < a2) throw Error("radix out of range: " + a2);
    if ("-" == f2.charAt(0)) return x2(y2(f2.substring(1), a2));
    if (0 <= f2.indexOf("-")) throw Error('number format error: interior "-" character');
    for (var c2 = v2(Math.pow(a2, 8)), d2 = w2, e2 = 0; e2 < f2.length; e2 += 8) {
      var g2 = Math.min(8, f2.length - e2), b2 = parseInt(f2.substring(e2, e2 + g2), a2);
      8 > g2 ? (g2 = v2(Math.pow(a2, g2)), d2 = d2.j(g2).add(v2(b2))) : (d2 = d2.j(c2), d2 = d2.add(v2(b2)));
    }
    return d2;
  }
  __name(y2, "y");
  var w2 = u2(0), z2 = u2(1), A2 = u2(16777216);
  h2 = t2.prototype;
  h2.m = function() {
    if (B2(this)) return -x2(this).m();
    for (var f2 = 0, a2 = 1, c2 = 0; c2 < this.g.length; c2++) {
      var d2 = this.i(c2);
      f2 += (0 <= d2 ? d2 : 4294967296 + d2) * a2;
      a2 *= 4294967296;
    }
    return f2;
  };
  h2.toString = function(f2) {
    f2 = f2 || 10;
    if (2 > f2 || 36 < f2) throw Error("radix out of range: " + f2);
    if (C2(this)) return "0";
    if (B2(this)) return "-" + x2(this).toString(f2);
    for (var a2 = v2(Math.pow(f2, 6)), c2 = this, d2 = ""; ; ) {
      var e2 = D2(c2, a2).g;
      c2 = F2(c2, e2.j(a2));
      var g2 = ((0 < c2.g.length ? c2.g[0] : c2.h) >>> 0).toString(f2);
      c2 = e2;
      if (C2(c2)) return g2 + d2;
      for (; 6 > g2.length; ) g2 = "0" + g2;
      d2 = g2 + d2;
    }
  };
  h2.i = function(f2) {
    return 0 > f2 ? 0 : f2 < this.g.length ? this.g[f2] : this.h;
  };
  function C2(f2) {
    if (0 != f2.h) return false;
    for (var a2 = 0; a2 < f2.g.length; a2++) if (0 != f2.g[a2]) return false;
    return true;
  }
  __name(C2, "C");
  function B2(f2) {
    return -1 == f2.h;
  }
  __name(B2, "B");
  h2.l = function(f2) {
    f2 = F2(this, f2);
    return B2(f2) ? -1 : C2(f2) ? 0 : 1;
  };
  function x2(f2) {
    for (var a2 = f2.g.length, c2 = [], d2 = 0; d2 < a2; d2++) c2[d2] = ~f2.g[d2];
    return new t2(c2, ~f2.h).add(z2);
  }
  __name(x2, "x");
  h2.abs = function() {
    return B2(this) ? x2(this) : this;
  };
  h2.add = function(f2) {
    for (var a2 = Math.max(this.g.length, f2.g.length), c2 = [], d2 = 0, e2 = 0; e2 <= a2; e2++) {
      var g2 = d2 + (this.i(e2) & 65535) + (f2.i(e2) & 65535), b2 = (g2 >>> 16) + (this.i(e2) >>> 16) + (f2.i(e2) >>> 16);
      d2 = b2 >>> 16;
      g2 &= 65535;
      b2 &= 65535;
      c2[e2] = b2 << 16 | g2;
    }
    return new t2(c2, c2[c2.length - 1] & -2147483648 ? -1 : 0);
  };
  function F2(f2, a2) {
    return f2.add(x2(a2));
  }
  __name(F2, "F");
  h2.j = function(f2) {
    if (C2(this) || C2(f2)) return w2;
    if (B2(this)) return B2(f2) ? x2(this).j(x2(f2)) : x2(x2(this).j(f2));
    if (B2(f2)) return x2(this.j(x2(f2)));
    if (0 > this.l(A2) && 0 > f2.l(A2)) return v2(this.m() * f2.m());
    for (var a2 = this.g.length + f2.g.length, c2 = [], d2 = 0; d2 < 2 * a2; d2++) c2[d2] = 0;
    for (d2 = 0; d2 < this.g.length; d2++) for (var e2 = 0; e2 < f2.g.length; e2++) {
      var g2 = this.i(d2) >>> 16, b2 = this.i(d2) & 65535, r2 = f2.i(e2) >>> 16, E = f2.i(e2) & 65535;
      c2[2 * d2 + 2 * e2] += b2 * E;
      G2(c2, 2 * d2 + 2 * e2);
      c2[2 * d2 + 2 * e2 + 1] += g2 * E;
      G2(c2, 2 * d2 + 2 * e2 + 1);
      c2[2 * d2 + 2 * e2 + 1] += b2 * r2;
      G2(c2, 2 * d2 + 2 * e2 + 1);
      c2[2 * d2 + 2 * e2 + 2] += g2 * r2;
      G2(c2, 2 * d2 + 2 * e2 + 2);
    }
    for (d2 = 0; d2 < a2; d2++) c2[d2] = c2[2 * d2 + 1] << 16 | c2[2 * d2];
    for (d2 = a2; d2 < 2 * a2; d2++) c2[d2] = 0;
    return new t2(c2, 0);
  };
  function G2(f2, a2) {
    for (; (f2[a2] & 65535) != f2[a2]; ) f2[a2 + 1] += f2[a2] >>> 16, f2[a2] &= 65535, a2++;
  }
  __name(G2, "G");
  function H2(f2, a2) {
    this.g = f2;
    this.h = a2;
  }
  __name(H2, "H");
  function D2(f2, a2) {
    if (C2(a2)) throw Error("division by zero");
    if (C2(f2)) return new H2(w2, w2);
    if (B2(f2)) return a2 = D2(x2(f2), a2), new H2(x2(a2.g), x2(a2.h));
    if (B2(a2)) return a2 = D2(f2, x2(a2)), new H2(x2(a2.g), a2.h);
    if (30 < f2.g.length) {
      if (B2(f2) || B2(a2)) throw Error("slowDivide_ only works with positive integers.");
      for (var c2 = z2, d2 = a2; 0 >= d2.l(f2); ) c2 = I2(c2), d2 = I2(d2);
      var e2 = J2(c2, 1), g2 = J2(d2, 1);
      d2 = J2(d2, 2);
      for (c2 = J2(c2, 2); !C2(d2); ) {
        var b2 = g2.add(d2);
        0 >= b2.l(f2) && (e2 = e2.add(c2), g2 = b2);
        d2 = J2(d2, 1);
        c2 = J2(c2, 1);
      }
      a2 = F2(f2, e2.j(a2));
      return new H2(e2, a2);
    }
    for (e2 = w2; 0 <= f2.l(a2); ) {
      c2 = Math.max(1, Math.floor(f2.m() / a2.m()));
      d2 = Math.ceil(Math.log(c2) / Math.LN2);
      d2 = 48 >= d2 ? 1 : Math.pow(2, d2 - 48);
      g2 = v2(c2);
      for (b2 = g2.j(a2); B2(b2) || 0 < b2.l(f2); ) c2 -= d2, g2 = v2(c2), b2 = g2.j(a2);
      C2(g2) && (g2 = z2);
      e2 = e2.add(g2);
      f2 = F2(f2, b2);
    }
    return new H2(e2, f2);
  }
  __name(D2, "D");
  h2.A = function(f2) {
    return D2(this, f2).h;
  };
  h2.and = function(f2) {
    for (var a2 = Math.max(this.g.length, f2.g.length), c2 = [], d2 = 0; d2 < a2; d2++) c2[d2] = this.i(d2) & f2.i(d2);
    return new t2(c2, this.h & f2.h);
  };
  h2.or = function(f2) {
    for (var a2 = Math.max(this.g.length, f2.g.length), c2 = [], d2 = 0; d2 < a2; d2++) c2[d2] = this.i(d2) | f2.i(d2);
    return new t2(c2, this.h | f2.h);
  };
  h2.xor = function(f2) {
    for (var a2 = Math.max(this.g.length, f2.g.length), c2 = [], d2 = 0; d2 < a2; d2++) c2[d2] = this.i(d2) ^ f2.i(d2);
    return new t2(c2, this.h ^ f2.h);
  };
  function I2(f2) {
    for (var a2 = f2.g.length + 1, c2 = [], d2 = 0; d2 < a2; d2++) c2[d2] = f2.i(d2) << 1 | f2.i(d2 - 1) >>> 31;
    return new t2(c2, f2.h);
  }
  __name(I2, "I");
  function J2(f2, a2) {
    var c2 = a2 >> 5;
    a2 %= 32;
    for (var d2 = f2.g.length - c2, e2 = [], g2 = 0; g2 < d2; g2++) e2[g2] = 0 < a2 ? f2.i(g2 + c2) >>> a2 | f2.i(g2 + c2 + 1) << 32 - a2 : f2.i(g2 + c2);
    return new t2(e2, f2.h);
  }
  __name(J2, "J");
  m2.prototype.digest = m2.prototype.v;
  m2.prototype.reset = m2.prototype.s;
  m2.prototype.update = m2.prototype.u;
  Md5 = bloom_blob_es2018.Md5 = m2;
  t2.prototype.add = t2.prototype.add;
  t2.prototype.multiply = t2.prototype.j;
  t2.prototype.modulo = t2.prototype.A;
  t2.prototype.compare = t2.prototype.l;
  t2.prototype.toNumber = t2.prototype.m;
  t2.prototype.toString = t2.prototype.toString;
  t2.prototype.getBits = t2.prototype.i;
  t2.fromNumber = v2;
  t2.fromString = y2;
  Integer = bloom_blob_es2018.Integer = t2;
}).apply(typeof commonjsGlobal$2 !== "undefined" ? commonjsGlobal$2 : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {});
var commonjsGlobal$1 = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
var webchannel_blob_es2018 = {};
/** @license
Copyright The Closure Library Authors.
SPDX-License-Identifier: Apache-2.0
*/
var XhrIo;
var FetchXmlHttpFactory;
var WebChannel;
var EventType;
var ErrorCode$1;
var Stat;
var Event$1;
var getStatEventTarget;
var createWebChannelTransport;
(function() {
  var h2, aa = "function" == typeof Object.defineProperties ? Object.defineProperty : function(a2, b2, c2) {
    if (a2 == Array.prototype || a2 == Object.prototype) return a2;
    a2[b2] = c2.value;
    return a2;
  };
  function ba(a2) {
    a2 = ["object" == typeof globalThis && globalThis, a2, "object" == typeof window && window, "object" == typeof self && self, "object" == typeof commonjsGlobal$1 && commonjsGlobal$1];
    for (var b2 = 0; b2 < a2.length; ++b2) {
      var c2 = a2[b2];
      if (c2 && c2.Math == Math) return c2;
    }
    throw Error("Cannot find global object");
  }
  __name(ba, "ba");
  var ca = ba(this);
  function da(a2, b2) {
    if (b2) a: {
      var c2 = ca;
      a2 = a2.split(".");
      for (var d2 = 0; d2 < a2.length - 1; d2++) {
        var e2 = a2[d2];
        if (!(e2 in c2)) break a;
        c2 = c2[e2];
      }
      a2 = a2[a2.length - 1];
      d2 = c2[a2];
      b2 = b2(d2);
      b2 != d2 && null != b2 && aa(c2, a2, { configurable: true, writable: true, value: b2 });
    }
  }
  __name(da, "da");
  function ea(a2, b2) {
    a2 instanceof String && (a2 += "");
    var c2 = 0, d2 = false, e2 = { next: /* @__PURE__ */ __name(function() {
      if (!d2 && c2 < a2.length) {
        var f2 = c2++;
        return { value: b2(f2, a2[f2]), done: false };
      }
      d2 = true;
      return { done: true, value: void 0 };
    }, "next") };
    e2[Symbol.iterator] = function() {
      return e2;
    };
    return e2;
  }
  __name(ea, "ea");
  da("Array.prototype.values", function(a2) {
    return a2 ? a2 : function() {
      return ea(this, function(b2, c2) {
        return c2;
      });
    };
  });
  /** @license
  
   Copyright The Closure Library Authors.
   SPDX-License-Identifier: Apache-2.0
  */
  var fa = fa || {}, k2 = this || self;
  function ha(a2) {
    var b2 = typeof a2;
    b2 = "object" != b2 ? b2 : a2 ? Array.isArray(a2) ? "array" : b2 : "null";
    return "array" == b2 || "object" == b2 && "number" == typeof a2.length;
  }
  __name(ha, "ha");
  function n2(a2) {
    var b2 = typeof a2;
    return "object" == b2 && null != a2 || "function" == b2;
  }
  __name(n2, "n");
  function ia(a2, b2, c2) {
    return a2.call.apply(a2.bind, arguments);
  }
  __name(ia, "ia");
  function ja2(a2, b2, c2) {
    if (!a2) throw Error();
    if (2 < arguments.length) {
      var d2 = Array.prototype.slice.call(arguments, 2);
      return function() {
        var e2 = Array.prototype.slice.call(arguments);
        Array.prototype.unshift.apply(e2, d2);
        return a2.apply(b2, e2);
      };
    }
    return function() {
      return a2.apply(b2, arguments);
    };
  }
  __name(ja2, "ja");
  function p2(a2, b2, c2) {
    p2 = Function.prototype.bind && -1 != Function.prototype.bind.toString().indexOf("native code") ? ia : ja2;
    return p2.apply(null, arguments);
  }
  __name(p2, "p");
  function ka(a2, b2) {
    var c2 = Array.prototype.slice.call(arguments, 1);
    return function() {
      var d2 = c2.slice();
      d2.push.apply(d2, arguments);
      return a2.apply(this, d2);
    };
  }
  __name(ka, "ka");
  function r2(a2, b2) {
    function c2() {
    }
    __name(c2, "c");
    c2.prototype = b2.prototype;
    a2.aa = b2.prototype;
    a2.prototype = new c2();
    a2.prototype.constructor = a2;
    a2.Qb = function(d2, e2, f2) {
      for (var g2 = Array(arguments.length - 2), m2 = 2; m2 < arguments.length; m2++) g2[m2 - 2] = arguments[m2];
      return b2.prototype[e2].apply(d2, g2);
    };
  }
  __name(r2, "r");
  function la(a2) {
    const b2 = a2.length;
    if (0 < b2) {
      const c2 = Array(b2);
      for (let d2 = 0; d2 < b2; d2++) c2[d2] = a2[d2];
      return c2;
    }
    return [];
  }
  __name(la, "la");
  function ma(a2, b2) {
    for (let c2 = 1; c2 < arguments.length; c2++) {
      const d2 = arguments[c2];
      if (ha(d2)) {
        const e2 = a2.length || 0, f2 = d2.length || 0;
        a2.length = e2 + f2;
        for (let g2 = 0; g2 < f2; g2++) a2[e2 + g2] = d2[g2];
      } else a2.push(d2);
    }
  }
  __name(ma, "ma");
  class na {
    static {
      __name(this, "na");
    }
    constructor(a2, b2) {
      this.i = a2;
      this.j = b2;
      this.h = 0;
      this.g = null;
    }
    get() {
      let a2;
      0 < this.h ? (this.h--, a2 = this.g, this.g = a2.next, a2.next = null) : a2 = this.i();
      return a2;
    }
  }
  function t2(a2) {
    return /^[\s\xa0]*$/.test(a2);
  }
  __name(t2, "t");
  function u2() {
    var a2 = k2.navigator;
    return a2 && (a2 = a2.userAgent) ? a2 : "";
  }
  __name(u2, "u");
  function oa(a2) {
    oa[" "](a2);
    return a2;
  }
  __name(oa, "oa");
  oa[" "] = function() {
  };
  var pa = -1 != u2().indexOf("Gecko") && !(-1 != u2().toLowerCase().indexOf("webkit") && -1 == u2().indexOf("Edge")) && !(-1 != u2().indexOf("Trident") || -1 != u2().indexOf("MSIE")) && -1 == u2().indexOf("Edge");
  function qa(a2, b2, c2) {
    for (const d2 in a2) b2.call(c2, a2[d2], d2, a2);
  }
  __name(qa, "qa");
  function ra(a2, b2) {
    for (const c2 in a2) b2.call(void 0, a2[c2], c2, a2);
  }
  __name(ra, "ra");
  function sa(a2) {
    const b2 = {};
    for (const c2 in a2) b2[c2] = a2[c2];
    return b2;
  }
  __name(sa, "sa");
  const ta2 = "constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");
  function ua(a2, b2) {
    let c2, d2;
    for (let e2 = 1; e2 < arguments.length; e2++) {
      d2 = arguments[e2];
      for (c2 in d2) a2[c2] = d2[c2];
      for (let f2 = 0; f2 < ta2.length; f2++) c2 = ta2[f2], Object.prototype.hasOwnProperty.call(d2, c2) && (a2[c2] = d2[c2]);
    }
  }
  __name(ua, "ua");
  function va(a2) {
    var b2 = 1;
    a2 = a2.split(":");
    const c2 = [];
    for (; 0 < b2 && a2.length; ) c2.push(a2.shift()), b2--;
    a2.length && c2.push(a2.join(":"));
    return c2;
  }
  __name(va, "va");
  function wa(a2) {
    k2.setTimeout(() => {
      throw a2;
    }, 0);
  }
  __name(wa, "wa");
  function xa() {
    var a2 = za;
    let b2 = null;
    a2.g && (b2 = a2.g, a2.g = a2.g.next, a2.g || (a2.h = null), b2.next = null);
    return b2;
  }
  __name(xa, "xa");
  class Aa {
    static {
      __name(this, "Aa");
    }
    constructor() {
      this.h = this.g = null;
    }
    add(a2, b2) {
      const c2 = Ba.get();
      c2.set(a2, b2);
      this.h ? this.h.next = c2 : this.g = c2;
      this.h = c2;
    }
  }
  var Ba = new na(() => new Ca(), (a2) => a2.reset());
  class Ca {
    static {
      __name(this, "Ca");
    }
    constructor() {
      this.next = this.g = this.h = null;
    }
    set(a2, b2) {
      this.h = a2;
      this.g = b2;
      this.next = null;
    }
    reset() {
      this.next = this.g = this.h = null;
    }
  }
  let x2, y2 = false, za = new Aa(), Ea = /* @__PURE__ */ __name(() => {
    const a2 = k2.Promise.resolve(void 0);
    x2 = /* @__PURE__ */ __name(() => {
      a2.then(Da);
    }, "x");
  }, "Ea");
  var Da = /* @__PURE__ */ __name(() => {
    for (var a2; a2 = xa(); ) {
      try {
        a2.h.call(a2.g);
      } catch (c2) {
        wa(c2);
      }
      var b2 = Ba;
      b2.j(a2);
      100 > b2.h && (b2.h++, a2.next = b2.g, b2.g = a2);
    }
    y2 = false;
  }, "Da");
  function z2() {
    this.s = this.s;
    this.C = this.C;
  }
  __name(z2, "z");
  z2.prototype.s = false;
  z2.prototype.ma = function() {
    this.s || (this.s = true, this.N());
  };
  z2.prototype.N = function() {
    if (this.C) for (; this.C.length; ) this.C.shift()();
  };
  function A2(a2, b2) {
    this.type = a2;
    this.g = this.target = b2;
    this.defaultPrevented = false;
  }
  __name(A2, "A");
  A2.prototype.h = function() {
    this.defaultPrevented = true;
  };
  var Fa = function() {
    if (!k2.addEventListener || !Object.defineProperty) return false;
    var a2 = false, b2 = Object.defineProperty({}, "passive", { get: /* @__PURE__ */ __name(function() {
      a2 = true;
    }, "get") });
    try {
      const c2 = /* @__PURE__ */ __name(() => {
      }, "c");
      k2.addEventListener("test", c2, b2);
      k2.removeEventListener("test", c2, b2);
    } catch (c2) {
    }
    return a2;
  }();
  function C2(a2, b2) {
    A2.call(this, a2 ? a2.type : "");
    this.relatedTarget = this.g = this.target = null;
    this.button = this.screenY = this.screenX = this.clientY = this.clientX = 0;
    this.key = "";
    this.metaKey = this.shiftKey = this.altKey = this.ctrlKey = false;
    this.state = null;
    this.pointerId = 0;
    this.pointerType = "";
    this.i = null;
    if (a2) {
      var c2 = this.type = a2.type, d2 = a2.changedTouches && a2.changedTouches.length ? a2.changedTouches[0] : null;
      this.target = a2.target || a2.srcElement;
      this.g = b2;
      if (b2 = a2.relatedTarget) {
        if (pa) {
          a: {
            try {
              oa(b2.nodeName);
              var e2 = true;
              break a;
            } catch (f2) {
            }
            e2 = false;
          }
          e2 || (b2 = null);
        }
      } else "mouseover" == c2 ? b2 = a2.fromElement : "mouseout" == c2 && (b2 = a2.toElement);
      this.relatedTarget = b2;
      d2 ? (this.clientX = void 0 !== d2.clientX ? d2.clientX : d2.pageX, this.clientY = void 0 !== d2.clientY ? d2.clientY : d2.pageY, this.screenX = d2.screenX || 0, this.screenY = d2.screenY || 0) : (this.clientX = void 0 !== a2.clientX ? a2.clientX : a2.pageX, this.clientY = void 0 !== a2.clientY ? a2.clientY : a2.pageY, this.screenX = a2.screenX || 0, this.screenY = a2.screenY || 0);
      this.button = a2.button;
      this.key = a2.key || "";
      this.ctrlKey = a2.ctrlKey;
      this.altKey = a2.altKey;
      this.shiftKey = a2.shiftKey;
      this.metaKey = a2.metaKey;
      this.pointerId = a2.pointerId || 0;
      this.pointerType = "string" === typeof a2.pointerType ? a2.pointerType : Ga[a2.pointerType] || "";
      this.state = a2.state;
      this.i = a2;
      a2.defaultPrevented && C2.aa.h.call(this);
    }
  }
  __name(C2, "C");
  r2(C2, A2);
  var Ga = { 2: "touch", 3: "pen", 4: "mouse" };
  C2.prototype.h = function() {
    C2.aa.h.call(this);
    var a2 = this.i;
    a2.preventDefault ? a2.preventDefault() : a2.returnValue = false;
  };
  var D2 = "closure_listenable_" + (1e6 * Math.random() | 0);
  var Ha = 0;
  function Ia(a2, b2, c2, d2, e2) {
    this.listener = a2;
    this.proxy = null;
    this.src = b2;
    this.type = c2;
    this.capture = !!d2;
    this.ha = e2;
    this.key = ++Ha;
    this.da = this.fa = false;
  }
  __name(Ia, "Ia");
  function Ja(a2) {
    a2.da = true;
    a2.listener = null;
    a2.proxy = null;
    a2.src = null;
    a2.ha = null;
  }
  __name(Ja, "Ja");
  function Ka(a2) {
    this.src = a2;
    this.g = {};
    this.h = 0;
  }
  __name(Ka, "Ka");
  Ka.prototype.add = function(a2, b2, c2, d2, e2) {
    var f2 = a2.toString();
    a2 = this.g[f2];
    a2 || (a2 = this.g[f2] = [], this.h++);
    var g2 = La(a2, b2, d2, e2);
    -1 < g2 ? (b2 = a2[g2], c2 || (b2.fa = false)) : (b2 = new Ia(b2, this.src, f2, !!d2, e2), b2.fa = c2, a2.push(b2));
    return b2;
  };
  function Ma(a2, b2) {
    var c2 = b2.type;
    if (c2 in a2.g) {
      var d2 = a2.g[c2], e2 = Array.prototype.indexOf.call(d2, b2, void 0), f2;
      (f2 = 0 <= e2) && Array.prototype.splice.call(d2, e2, 1);
      f2 && (Ja(b2), 0 == a2.g[c2].length && (delete a2.g[c2], a2.h--));
    }
  }
  __name(Ma, "Ma");
  function La(a2, b2, c2, d2) {
    for (var e2 = 0; e2 < a2.length; ++e2) {
      var f2 = a2[e2];
      if (!f2.da && f2.listener == b2 && f2.capture == !!c2 && f2.ha == d2) return e2;
    }
    return -1;
  }
  __name(La, "La");
  var Na = "closure_lm_" + (1e6 * Math.random() | 0), Oa = {};
  function Qa(a2, b2, c2, d2, e2) {
    if (d2 && d2.once) return Ra(a2, b2, c2, d2, e2);
    if (Array.isArray(b2)) {
      for (var f2 = 0; f2 < b2.length; f2++) Qa(a2, b2[f2], c2, d2, e2);
      return null;
    }
    c2 = Sa(c2);
    return a2 && a2[D2] ? a2.K(b2, c2, n2(d2) ? !!d2.capture : !!d2, e2) : Ta(a2, b2, c2, false, d2, e2);
  }
  __name(Qa, "Qa");
  function Ta(a2, b2, c2, d2, e2, f2) {
    if (!b2) throw Error("Invalid event type");
    var g2 = n2(e2) ? !!e2.capture : !!e2, m2 = Ua(a2);
    m2 || (a2[Na] = m2 = new Ka(a2));
    c2 = m2.add(b2, c2, d2, g2, f2);
    if (c2.proxy) return c2;
    d2 = Va();
    c2.proxy = d2;
    d2.src = a2;
    d2.listener = c2;
    if (a2.addEventListener) Fa || (e2 = g2), void 0 === e2 && (e2 = false), a2.addEventListener(b2.toString(), d2, e2);
    else if (a2.attachEvent) a2.attachEvent(Wa(b2.toString()), d2);
    else if (a2.addListener && a2.removeListener) a2.addListener(d2);
    else throw Error("addEventListener and attachEvent are unavailable.");
    return c2;
  }
  __name(Ta, "Ta");
  function Va() {
    function a2(c2) {
      return b2.call(a2.src, a2.listener, c2);
    }
    __name(a2, "a");
    const b2 = Xa;
    return a2;
  }
  __name(Va, "Va");
  function Ra(a2, b2, c2, d2, e2) {
    if (Array.isArray(b2)) {
      for (var f2 = 0; f2 < b2.length; f2++) Ra(a2, b2[f2], c2, d2, e2);
      return null;
    }
    c2 = Sa(c2);
    return a2 && a2[D2] ? a2.L(b2, c2, n2(d2) ? !!d2.capture : !!d2, e2) : Ta(a2, b2, c2, true, d2, e2);
  }
  __name(Ra, "Ra");
  function Ya(a2, b2, c2, d2, e2) {
    if (Array.isArray(b2)) for (var f2 = 0; f2 < b2.length; f2++) Ya(a2, b2[f2], c2, d2, e2);
    else (d2 = n2(d2) ? !!d2.capture : !!d2, c2 = Sa(c2), a2 && a2[D2]) ? (a2 = a2.i, b2 = String(b2).toString(), b2 in a2.g && (f2 = a2.g[b2], c2 = La(f2, c2, d2, e2), -1 < c2 && (Ja(f2[c2]), Array.prototype.splice.call(f2, c2, 1), 0 == f2.length && (delete a2.g[b2], a2.h--)))) : a2 && (a2 = Ua(a2)) && (b2 = a2.g[b2.toString()], a2 = -1, b2 && (a2 = La(b2, c2, d2, e2)), (c2 = -1 < a2 ? b2[a2] : null) && Za(c2));
  }
  __name(Ya, "Ya");
  function Za(a2) {
    if ("number" !== typeof a2 && a2 && !a2.da) {
      var b2 = a2.src;
      if (b2 && b2[D2]) Ma(b2.i, a2);
      else {
        var c2 = a2.type, d2 = a2.proxy;
        b2.removeEventListener ? b2.removeEventListener(c2, d2, a2.capture) : b2.detachEvent ? b2.detachEvent(Wa(c2), d2) : b2.addListener && b2.removeListener && b2.removeListener(d2);
        (c2 = Ua(b2)) ? (Ma(c2, a2), 0 == c2.h && (c2.src = null, b2[Na] = null)) : Ja(a2);
      }
    }
  }
  __name(Za, "Za");
  function Wa(a2) {
    return a2 in Oa ? Oa[a2] : Oa[a2] = "on" + a2;
  }
  __name(Wa, "Wa");
  function Xa(a2, b2) {
    if (a2.da) a2 = true;
    else {
      b2 = new C2(b2, this);
      var c2 = a2.listener, d2 = a2.ha || a2.src;
      a2.fa && Za(a2);
      a2 = c2.call(d2, b2);
    }
    return a2;
  }
  __name(Xa, "Xa");
  function Ua(a2) {
    a2 = a2[Na];
    return a2 instanceof Ka ? a2 : null;
  }
  __name(Ua, "Ua");
  var $a = "__closure_events_fn_" + (1e9 * Math.random() >>> 0);
  function Sa(a2) {
    if ("function" === typeof a2) return a2;
    a2[$a] || (a2[$a] = function(b2) {
      return a2.handleEvent(b2);
    });
    return a2[$a];
  }
  __name(Sa, "Sa");
  function E() {
    z2.call(this);
    this.i = new Ka(this);
    this.M = this;
    this.F = null;
  }
  __name(E, "E");
  r2(E, z2);
  E.prototype[D2] = true;
  E.prototype.removeEventListener = function(a2, b2, c2, d2) {
    Ya(this, a2, b2, c2, d2);
  };
  function F2(a2, b2) {
    var c2, d2 = a2.F;
    if (d2) for (c2 = []; d2; d2 = d2.F) c2.push(d2);
    a2 = a2.M;
    d2 = b2.type || b2;
    if ("string" === typeof b2) b2 = new A2(b2, a2);
    else if (b2 instanceof A2) b2.target = b2.target || a2;
    else {
      var e2 = b2;
      b2 = new A2(d2, a2);
      ua(b2, e2);
    }
    e2 = true;
    if (c2) for (var f2 = c2.length - 1; 0 <= f2; f2--) {
      var g2 = b2.g = c2[f2];
      e2 = ab(g2, d2, true, b2) && e2;
    }
    g2 = b2.g = a2;
    e2 = ab(g2, d2, true, b2) && e2;
    e2 = ab(g2, d2, false, b2) && e2;
    if (c2) for (f2 = 0; f2 < c2.length; f2++) g2 = b2.g = c2[f2], e2 = ab(g2, d2, false, b2) && e2;
  }
  __name(F2, "F");
  E.prototype.N = function() {
    E.aa.N.call(this);
    if (this.i) {
      var a2 = this.i, c2;
      for (c2 in a2.g) {
        for (var d2 = a2.g[c2], e2 = 0; e2 < d2.length; e2++) Ja(d2[e2]);
        delete a2.g[c2];
        a2.h--;
      }
    }
    this.F = null;
  };
  E.prototype.K = function(a2, b2, c2, d2) {
    return this.i.add(String(a2), b2, false, c2, d2);
  };
  E.prototype.L = function(a2, b2, c2, d2) {
    return this.i.add(String(a2), b2, true, c2, d2);
  };
  function ab(a2, b2, c2, d2) {
    b2 = a2.i.g[String(b2)];
    if (!b2) return true;
    b2 = b2.concat();
    for (var e2 = true, f2 = 0; f2 < b2.length; ++f2) {
      var g2 = b2[f2];
      if (g2 && !g2.da && g2.capture == c2) {
        var m2 = g2.listener, q2 = g2.ha || g2.src;
        g2.fa && Ma(a2.i, g2);
        e2 = false !== m2.call(q2, d2) && e2;
      }
    }
    return e2 && !d2.defaultPrevented;
  }
  __name(ab, "ab");
  function bb(a2, b2, c2) {
    if ("function" === typeof a2) c2 && (a2 = p2(a2, c2));
    else if (a2 && "function" == typeof a2.handleEvent) a2 = p2(a2.handleEvent, a2);
    else throw Error("Invalid listener argument");
    return 2147483647 < Number(b2) ? -1 : k2.setTimeout(a2, b2 || 0);
  }
  __name(bb, "bb");
  function cb(a2) {
    a2.g = bb(() => {
      a2.g = null;
      a2.i && (a2.i = false, cb(a2));
    }, a2.l);
    const b2 = a2.h;
    a2.h = null;
    a2.m.apply(null, b2);
  }
  __name(cb, "cb");
  class eb extends z2 {
    static {
      __name(this, "eb");
    }
    constructor(a2, b2) {
      super();
      this.m = a2;
      this.l = b2;
      this.h = null;
      this.i = false;
      this.g = null;
    }
    j(a2) {
      this.h = arguments;
      this.g ? this.i = true : cb(this);
    }
    N() {
      super.N();
      this.g && (k2.clearTimeout(this.g), this.g = null, this.i = false, this.h = null);
    }
  }
  function G2(a2) {
    z2.call(this);
    this.h = a2;
    this.g = {};
  }
  __name(G2, "G");
  r2(G2, z2);
  var fb = [];
  function gb(a2) {
    qa(a2.g, function(b2, c2) {
      this.g.hasOwnProperty(c2) && Za(b2);
    }, a2);
    a2.g = {};
  }
  __name(gb, "gb");
  G2.prototype.N = function() {
    G2.aa.N.call(this);
    gb(this);
  };
  G2.prototype.handleEvent = function() {
    throw Error("EventHandler.handleEvent not implemented");
  };
  var hb = k2.JSON.stringify;
  var ib = k2.JSON.parse;
  var jb = class {
    static {
      __name(this, "jb");
    }
    stringify(a2) {
      return k2.JSON.stringify(a2, void 0);
    }
    parse(a2) {
      return k2.JSON.parse(a2, void 0);
    }
  };
  function kb() {
  }
  __name(kb, "kb");
  kb.prototype.h = null;
  function lb(a2) {
    return a2.h || (a2.h = a2.i());
  }
  __name(lb, "lb");
  function mb() {
  }
  __name(mb, "mb");
  var H2 = { OPEN: "a", kb: "b", Ja: "c", wb: "d" };
  function nb() {
    A2.call(this, "d");
  }
  __name(nb, "nb");
  r2(nb, A2);
  function ob() {
    A2.call(this, "c");
  }
  __name(ob, "ob");
  r2(ob, A2);
  var I2 = {}, pb = null;
  function qb() {
    return pb = pb || new E();
  }
  __name(qb, "qb");
  I2.La = "serverreachability";
  function rb(a2) {
    A2.call(this, I2.La, a2);
  }
  __name(rb, "rb");
  r2(rb, A2);
  function J2(a2) {
    const b2 = qb();
    F2(b2, new rb(b2));
  }
  __name(J2, "J");
  I2.STAT_EVENT = "statevent";
  function sb(a2, b2) {
    A2.call(this, I2.STAT_EVENT, a2);
    this.stat = b2;
  }
  __name(sb, "sb");
  r2(sb, A2);
  function K2(a2) {
    const b2 = qb();
    F2(b2, new sb(b2, a2));
  }
  __name(K2, "K");
  I2.Ma = "timingevent";
  function tb(a2, b2) {
    A2.call(this, I2.Ma, a2);
    this.size = b2;
  }
  __name(tb, "tb");
  r2(tb, A2);
  function ub(a2, b2) {
    if ("function" !== typeof a2) throw Error("Fn must not be null and must be a function");
    return k2.setTimeout(function() {
      a2();
    }, b2);
  }
  __name(ub, "ub");
  function vb() {
    this.g = true;
  }
  __name(vb, "vb");
  vb.prototype.xa = function() {
    this.g = false;
  };
  function wb(a2, b2, c2, d2, e2, f2) {
    a2.info(function() {
      if (a2.g) if (f2) {
        var g2 = "";
        for (var m2 = f2.split("&"), q2 = 0; q2 < m2.length; q2++) {
          var l2 = m2[q2].split("=");
          if (1 < l2.length) {
            var v2 = l2[0];
            l2 = l2[1];
            var w2 = v2.split("_");
            g2 = 2 <= w2.length && "type" == w2[1] ? g2 + (v2 + "=" + l2 + "&") : g2 + (v2 + "=redacted&");
          }
        }
      } else g2 = null;
      else g2 = f2;
      return "XMLHTTP REQ (" + d2 + ") [attempt " + e2 + "]: " + b2 + "\n" + c2 + "\n" + g2;
    });
  }
  __name(wb, "wb");
  function xb(a2, b2, c2, d2, e2, f2, g2) {
    a2.info(function() {
      return "XMLHTTP RESP (" + d2 + ") [ attempt " + e2 + "]: " + b2 + "\n" + c2 + "\n" + f2 + " " + g2;
    });
  }
  __name(xb, "xb");
  function L2(a2, b2, c2, d2) {
    a2.info(function() {
      return "XMLHTTP TEXT (" + b2 + "): " + yb(a2, c2) + (d2 ? " " + d2 : "");
    });
  }
  __name(L2, "L");
  function zb(a2, b2) {
    a2.info(function() {
      return "TIMEOUT: " + b2;
    });
  }
  __name(zb, "zb");
  vb.prototype.info = function() {
  };
  function yb(a2, b2) {
    if (!a2.g) return b2;
    if (!b2) return null;
    try {
      var c2 = JSON.parse(b2);
      if (c2) {
        for (a2 = 0; a2 < c2.length; a2++) if (Array.isArray(c2[a2])) {
          var d2 = c2[a2];
          if (!(2 > d2.length)) {
            var e2 = d2[1];
            if (Array.isArray(e2) && !(1 > e2.length)) {
              var f2 = e2[0];
              if ("noop" != f2 && "stop" != f2 && "close" != f2) for (var g2 = 1; g2 < e2.length; g2++) e2[g2] = "";
            }
          }
        }
      }
      return hb(c2);
    } catch (m2) {
      return b2;
    }
  }
  __name(yb, "yb");
  var Ab = { NO_ERROR: 0, gb: 1, tb: 2, sb: 3, nb: 4, rb: 5, ub: 6, Ia: 7, TIMEOUT: 8, xb: 9 };
  var Bb = { lb: "complete", Hb: "success", Ja: "error", Ia: "abort", zb: "ready", Ab: "readystatechange", TIMEOUT: "timeout", vb: "incrementaldata", yb: "progress", ob: "downloadprogress", Pb: "uploadprogress" };
  var Cb;
  function Db() {
  }
  __name(Db, "Db");
  r2(Db, kb);
  Db.prototype.g = function() {
    return new XMLHttpRequest();
  };
  Db.prototype.i = function() {
    return {};
  };
  Cb = new Db();
  function M2(a2, b2, c2, d2) {
    this.j = a2;
    this.i = b2;
    this.l = c2;
    this.R = d2 || 1;
    this.U = new G2(this);
    this.I = 45e3;
    this.H = null;
    this.o = false;
    this.m = this.A = this.v = this.L = this.F = this.S = this.B = null;
    this.D = [];
    this.g = null;
    this.C = 0;
    this.s = this.u = null;
    this.X = -1;
    this.J = false;
    this.O = 0;
    this.M = null;
    this.W = this.K = this.T = this.P = false;
    this.h = new Eb();
  }
  __name(M2, "M");
  function Eb() {
    this.i = null;
    this.g = "";
    this.h = false;
  }
  __name(Eb, "Eb");
  var Fb = {}, Gb = {};
  function Hb(a2, b2, c2) {
    a2.L = 1;
    a2.v = Ib(N2(b2));
    a2.m = c2;
    a2.P = true;
    Jb(a2, null);
  }
  __name(Hb, "Hb");
  function Jb(a2, b2) {
    a2.F = Date.now();
    Kb(a2);
    a2.A = N2(a2.v);
    var c2 = a2.A, d2 = a2.R;
    Array.isArray(d2) || (d2 = [String(d2)]);
    Lb(c2.i, "t", d2);
    a2.C = 0;
    c2 = a2.j.J;
    a2.h = new Eb();
    a2.g = Mb(a2.j, c2 ? b2 : null, !a2.m);
    0 < a2.O && (a2.M = new eb(p2(a2.Y, a2, a2.g), a2.O));
    b2 = a2.U;
    c2 = a2.g;
    d2 = a2.ca;
    var e2 = "readystatechange";
    Array.isArray(e2) || (e2 && (fb[0] = e2.toString()), e2 = fb);
    for (var f2 = 0; f2 < e2.length; f2++) {
      var g2 = Qa(c2, e2[f2], d2 || b2.handleEvent, false, b2.h || b2);
      if (!g2) break;
      b2.g[g2.key] = g2;
    }
    b2 = a2.H ? sa(a2.H) : {};
    a2.m ? (a2.u || (a2.u = "POST"), b2["Content-Type"] = "application/x-www-form-urlencoded", a2.g.ea(
      a2.A,
      a2.u,
      a2.m,
      b2
    )) : (a2.u = "GET", a2.g.ea(a2.A, a2.u, null, b2));
    J2();
    wb(a2.i, a2.u, a2.A, a2.l, a2.R, a2.m);
  }
  __name(Jb, "Jb");
  M2.prototype.ca = function(a2) {
    a2 = a2.target;
    const b2 = this.M;
    b2 && 3 == P2(a2) ? b2.j() : this.Y(a2);
  };
  M2.prototype.Y = function(a2) {
    try {
      if (a2 == this.g) a: {
        const w2 = P2(this.g);
        var b2 = this.g.Ba();
        const O2 = this.g.Z();
        if (!(3 > w2) && (3 != w2 || this.g && (this.h.h || this.g.oa() || Nb(this.g)))) {
          this.J || 4 != w2 || 7 == b2 || (8 == b2 || 0 >= O2 ? J2(3) : J2(2));
          Ob(this);
          var c2 = this.g.Z();
          this.X = c2;
          b: if (Pb(this)) {
            var d2 = Nb(this.g);
            a2 = "";
            var e2 = d2.length, f2 = 4 == P2(this.g);
            if (!this.h.i) {
              if ("undefined" === typeof TextDecoder) {
                Q2(this);
                Qb(this);
                var g2 = "";
                break b;
              }
              this.h.i = new k2.TextDecoder();
            }
            for (b2 = 0; b2 < e2; b2++) this.h.h = true, a2 += this.h.i.decode(d2[b2], { stream: !(f2 && b2 == e2 - 1) });
            d2.length = 0;
            this.h.g += a2;
            this.C = 0;
            g2 = this.h.g;
          } else g2 = this.g.oa();
          this.o = 200 == c2;
          xb(this.i, this.u, this.A, this.l, this.R, w2, c2);
          if (this.o) {
            if (this.T && !this.K) {
              b: {
                if (this.g) {
                  var m2, q2 = this.g;
                  if ((m2 = q2.g ? q2.g.getResponseHeader("X-HTTP-Initial-Response") : null) && !t2(m2)) {
                    var l2 = m2;
                    break b;
                  }
                }
                l2 = null;
              }
              if (c2 = l2) L2(this.i, this.l, c2, "Initial handshake response via X-HTTP-Initial-Response"), this.K = true, Rb(this, c2);
              else {
                this.o = false;
                this.s = 3;
                K2(12);
                Q2(this);
                Qb(this);
                break a;
              }
            }
            if (this.P) {
              c2 = true;
              let B2;
              for (; !this.J && this.C < g2.length; ) if (B2 = Sb(this, g2), B2 == Gb) {
                4 == w2 && (this.s = 4, K2(14), c2 = false);
                L2(this.i, this.l, null, "[Incomplete Response]");
                break;
              } else if (B2 == Fb) {
                this.s = 4;
                K2(15);
                L2(this.i, this.l, g2, "[Invalid Chunk]");
                c2 = false;
                break;
              } else L2(this.i, this.l, B2, null), Rb(this, B2);
              Pb(this) && 0 != this.C && (this.h.g = this.h.g.slice(this.C), this.C = 0);
              4 != w2 || 0 != g2.length || this.h.h || (this.s = 1, K2(16), c2 = false);
              this.o = this.o && c2;
              if (!c2) L2(this.i, this.l, g2, "[Invalid Chunked Response]"), Q2(this), Qb(this);
              else if (0 < g2.length && !this.W) {
                this.W = true;
                var v2 = this.j;
                v2.g == this && v2.ba && !v2.M && (v2.j.info("Great, no buffering proxy detected. Bytes received: " + g2.length), Tb(v2), v2.M = true, K2(11));
              }
            } else L2(this.i, this.l, g2, null), Rb(this, g2);
            4 == w2 && Q2(this);
            this.o && !this.J && (4 == w2 ? Ub(this.j, this) : (this.o = false, Kb(this)));
          } else Vb(this.g), 400 == c2 && 0 < g2.indexOf("Unknown SID") ? (this.s = 3, K2(12)) : (this.s = 0, K2(13)), Q2(this), Qb(this);
        }
      }
    } catch (w2) {
    } finally {
    }
  };
  function Pb(a2) {
    return a2.g ? "GET" == a2.u && 2 != a2.L && a2.j.Ca : false;
  }
  __name(Pb, "Pb");
  function Sb(a2, b2) {
    var c2 = a2.C, d2 = b2.indexOf("\n", c2);
    if (-1 == d2) return Gb;
    c2 = Number(b2.substring(c2, d2));
    if (isNaN(c2)) return Fb;
    d2 += 1;
    if (d2 + c2 > b2.length) return Gb;
    b2 = b2.slice(d2, d2 + c2);
    a2.C = d2 + c2;
    return b2;
  }
  __name(Sb, "Sb");
  M2.prototype.cancel = function() {
    this.J = true;
    Q2(this);
  };
  function Kb(a2) {
    a2.S = Date.now() + a2.I;
    Wb(a2, a2.I);
  }
  __name(Kb, "Kb");
  function Wb(a2, b2) {
    if (null != a2.B) throw Error("WatchDog timer not null");
    a2.B = ub(p2(a2.ba, a2), b2);
  }
  __name(Wb, "Wb");
  function Ob(a2) {
    a2.B && (k2.clearTimeout(a2.B), a2.B = null);
  }
  __name(Ob, "Ob");
  M2.prototype.ba = function() {
    this.B = null;
    const a2 = Date.now();
    0 <= a2 - this.S ? (zb(this.i, this.A), 2 != this.L && (J2(), K2(17)), Q2(this), this.s = 2, Qb(this)) : Wb(this, this.S - a2);
  };
  function Qb(a2) {
    0 == a2.j.G || a2.J || Ub(a2.j, a2);
  }
  __name(Qb, "Qb");
  function Q2(a2) {
    Ob(a2);
    var b2 = a2.M;
    b2 && "function" == typeof b2.ma && b2.ma();
    a2.M = null;
    gb(a2.U);
    a2.g && (b2 = a2.g, a2.g = null, b2.abort(), b2.ma());
  }
  __name(Q2, "Q");
  function Rb(a2, b2) {
    try {
      var c2 = a2.j;
      if (0 != c2.G && (c2.g == a2 || Xb(c2.h, a2))) {
        if (!a2.K && Xb(c2.h, a2) && 3 == c2.G) {
          try {
            var d2 = c2.Da.g.parse(b2);
          } catch (l2) {
            d2 = null;
          }
          if (Array.isArray(d2) && 3 == d2.length) {
            var e2 = d2;
            if (0 == e2[0]) a: {
              if (!c2.u) {
                if (c2.g) if (c2.g.F + 3e3 < a2.F) Yb(c2), Zb(c2);
                else break a;
                $b(c2);
                K2(18);
              }
            }
            else c2.za = e2[1], 0 < c2.za - c2.T && 37500 > e2[2] && c2.F && 0 == c2.v && !c2.C && (c2.C = ub(p2(c2.Za, c2), 6e3));
            if (1 >= ac(c2.h) && c2.ca) {
              try {
                c2.ca();
              } catch (l2) {
              }
              c2.ca = void 0;
            }
          } else R(c2, 11);
        } else if ((a2.K || c2.g == a2) && Yb(c2), !t2(b2)) for (e2 = c2.Da.g.parse(b2), b2 = 0; b2 < e2.length; b2++) {
          let l2 = e2[b2];
          c2.T = l2[0];
          l2 = l2[1];
          if (2 == c2.G) if ("c" == l2[0]) {
            c2.K = l2[1];
            c2.ia = l2[2];
            const v2 = l2[3];
            null != v2 && (c2.la = v2, c2.j.info("VER=" + c2.la));
            const w2 = l2[4];
            null != w2 && (c2.Aa = w2, c2.j.info("SVER=" + c2.Aa));
            const O2 = l2[5];
            null != O2 && "number" === typeof O2 && 0 < O2 && (d2 = 1.5 * O2, c2.L = d2, c2.j.info("backChannelRequestTimeoutMs_=" + d2));
            d2 = c2;
            const B2 = a2.g;
            if (B2) {
              const ya = B2.g ? B2.g.getResponseHeader("X-Client-Wire-Protocol") : null;
              if (ya) {
                var f2 = d2.h;
                f2.g || -1 == ya.indexOf("spdy") && -1 == ya.indexOf("quic") && -1 == ya.indexOf("h2") || (f2.j = f2.l, f2.g = /* @__PURE__ */ new Set(), f2.h && (bc(f2, f2.h), f2.h = null));
              }
              if (d2.D) {
                const db = B2.g ? B2.g.getResponseHeader("X-HTTP-Session-Id") : null;
                db && (d2.ya = db, S2(d2.I, d2.D, db));
              }
            }
            c2.G = 3;
            c2.l && c2.l.ua();
            c2.ba && (c2.R = Date.now() - a2.F, c2.j.info("Handshake RTT: " + c2.R + "ms"));
            d2 = c2;
            var g2 = a2;
            d2.qa = cc(d2, d2.J ? d2.ia : null, d2.W);
            if (g2.K) {
              dc(d2.h, g2);
              var m2 = g2, q2 = d2.L;
              q2 && (m2.I = q2);
              m2.B && (Ob(m2), Kb(m2));
              d2.g = g2;
            } else ec(d2);
            0 < c2.i.length && fc(c2);
          } else "stop" != l2[0] && "close" != l2[0] || R(c2, 7);
          else 3 == c2.G && ("stop" == l2[0] || "close" == l2[0] ? "stop" == l2[0] ? R(c2, 7) : gc(c2) : "noop" != l2[0] && c2.l && c2.l.ta(l2), c2.v = 0);
        }
      }
      J2(4);
    } catch (l2) {
    }
  }
  __name(Rb, "Rb");
  var hc = class {
    static {
      __name(this, "hc");
    }
    constructor(a2, b2) {
      this.g = a2;
      this.map = b2;
    }
  };
  function ic(a2) {
    this.l = a2 || 10;
    k2.PerformanceNavigationTiming ? (a2 = k2.performance.getEntriesByType("navigation"), a2 = 0 < a2.length && ("hq" == a2[0].nextHopProtocol || "h2" == a2[0].nextHopProtocol)) : a2 = !!(k2.chrome && k2.chrome.loadTimes && k2.chrome.loadTimes() && k2.chrome.loadTimes().wasFetchedViaSpdy);
    this.j = a2 ? this.l : 1;
    this.g = null;
    1 < this.j && (this.g = /* @__PURE__ */ new Set());
    this.h = null;
    this.i = [];
  }
  __name(ic, "ic");
  function jc(a2) {
    return a2.h ? true : a2.g ? a2.g.size >= a2.j : false;
  }
  __name(jc, "jc");
  function ac(a2) {
    return a2.h ? 1 : a2.g ? a2.g.size : 0;
  }
  __name(ac, "ac");
  function Xb(a2, b2) {
    return a2.h ? a2.h == b2 : a2.g ? a2.g.has(b2) : false;
  }
  __name(Xb, "Xb");
  function bc(a2, b2) {
    a2.g ? a2.g.add(b2) : a2.h = b2;
  }
  __name(bc, "bc");
  function dc(a2, b2) {
    a2.h && a2.h == b2 ? a2.h = null : a2.g && a2.g.has(b2) && a2.g.delete(b2);
  }
  __name(dc, "dc");
  ic.prototype.cancel = function() {
    this.i = kc(this);
    if (this.h) this.h.cancel(), this.h = null;
    else if (this.g && 0 !== this.g.size) {
      for (const a2 of this.g.values()) a2.cancel();
      this.g.clear();
    }
  };
  function kc(a2) {
    if (null != a2.h) return a2.i.concat(a2.h.D);
    if (null != a2.g && 0 !== a2.g.size) {
      let b2 = a2.i;
      for (const c2 of a2.g.values()) b2 = b2.concat(c2.D);
      return b2;
    }
    return la(a2.i);
  }
  __name(kc, "kc");
  function lc(a2) {
    if (a2.V && "function" == typeof a2.V) return a2.V();
    if ("undefined" !== typeof Map && a2 instanceof Map || "undefined" !== typeof Set && a2 instanceof Set) return Array.from(a2.values());
    if ("string" === typeof a2) return a2.split("");
    if (ha(a2)) {
      for (var b2 = [], c2 = a2.length, d2 = 0; d2 < c2; d2++) b2.push(a2[d2]);
      return b2;
    }
    b2 = [];
    c2 = 0;
    for (d2 in a2) b2[c2++] = a2[d2];
    return b2;
  }
  __name(lc, "lc");
  function mc(a2) {
    if (a2.na && "function" == typeof a2.na) return a2.na();
    if (!a2.V || "function" != typeof a2.V) {
      if ("undefined" !== typeof Map && a2 instanceof Map) return Array.from(a2.keys());
      if (!("undefined" !== typeof Set && a2 instanceof Set)) {
        if (ha(a2) || "string" === typeof a2) {
          var b2 = [];
          a2 = a2.length;
          for (var c2 = 0; c2 < a2; c2++) b2.push(c2);
          return b2;
        }
        b2 = [];
        c2 = 0;
        for (const d2 in a2) b2[c2++] = d2;
        return b2;
      }
    }
  }
  __name(mc, "mc");
  function nc(a2, b2) {
    if (a2.forEach && "function" == typeof a2.forEach) a2.forEach(b2, void 0);
    else if (ha(a2) || "string" === typeof a2) Array.prototype.forEach.call(a2, b2, void 0);
    else for (var c2 = mc(a2), d2 = lc(a2), e2 = d2.length, f2 = 0; f2 < e2; f2++) b2.call(void 0, d2[f2], c2 && c2[f2], a2);
  }
  __name(nc, "nc");
  var oc = RegExp("^(?:([^:/?#.]+):)?(?://(?:([^\\\\/?#]*)@)?([^\\\\/?#]*?)(?::([0-9]+))?(?=[\\\\/?#]|$))?([^?#]+)?(?:\\?([^#]*))?(?:#([\\s\\S]*))?$");
  function pc(a2, b2) {
    if (a2) {
      a2 = a2.split("&");
      for (var c2 = 0; c2 < a2.length; c2++) {
        var d2 = a2[c2].indexOf("="), e2 = null;
        if (0 <= d2) {
          var f2 = a2[c2].substring(0, d2);
          e2 = a2[c2].substring(d2 + 1);
        } else f2 = a2[c2];
        b2(f2, e2 ? decodeURIComponent(e2.replace(/\+/g, " ")) : "");
      }
    }
  }
  __name(pc, "pc");
  function T2(a2) {
    this.g = this.o = this.j = "";
    this.s = null;
    this.m = this.l = "";
    this.h = false;
    if (a2 instanceof T2) {
      this.h = a2.h;
      qc(this, a2.j);
      this.o = a2.o;
      this.g = a2.g;
      rc(this, a2.s);
      this.l = a2.l;
      var b2 = a2.i;
      var c2 = new sc();
      c2.i = b2.i;
      b2.g && (c2.g = new Map(b2.g), c2.h = b2.h);
      tc(this, c2);
      this.m = a2.m;
    } else a2 && (b2 = String(a2).match(oc)) ? (this.h = false, qc(this, b2[1] || "", true), this.o = uc(b2[2] || ""), this.g = uc(b2[3] || "", true), rc(this, b2[4]), this.l = uc(b2[5] || "", true), tc(this, b2[6] || "", true), this.m = uc(b2[7] || "")) : (this.h = false, this.i = new sc(null, this.h));
  }
  __name(T2, "T");
  T2.prototype.toString = function() {
    var a2 = [], b2 = this.j;
    b2 && a2.push(vc(b2, wc, true), ":");
    var c2 = this.g;
    if (c2 || "file" == b2) a2.push("//"), (b2 = this.o) && a2.push(vc(b2, wc, true), "@"), a2.push(encodeURIComponent(String(c2)).replace(/%25([0-9a-fA-F]{2})/g, "%$1")), c2 = this.s, null != c2 && a2.push(":", String(c2));
    if (c2 = this.l) this.g && "/" != c2.charAt(0) && a2.push("/"), a2.push(vc(c2, "/" == c2.charAt(0) ? xc : yc, true));
    (c2 = this.i.toString()) && a2.push("?", c2);
    (c2 = this.m) && a2.push("#", vc(c2, zc));
    return a2.join("");
  };
  function N2(a2) {
    return new T2(a2);
  }
  __name(N2, "N");
  function qc(a2, b2, c2) {
    a2.j = c2 ? uc(b2, true) : b2;
    a2.j && (a2.j = a2.j.replace(/:$/, ""));
  }
  __name(qc, "qc");
  function rc(a2, b2) {
    if (b2) {
      b2 = Number(b2);
      if (isNaN(b2) || 0 > b2) throw Error("Bad port number " + b2);
      a2.s = b2;
    } else a2.s = null;
  }
  __name(rc, "rc");
  function tc(a2, b2, c2) {
    b2 instanceof sc ? (a2.i = b2, Ac(a2.i, a2.h)) : (c2 || (b2 = vc(b2, Bc)), a2.i = new sc(b2, a2.h));
  }
  __name(tc, "tc");
  function S2(a2, b2, c2) {
    a2.i.set(b2, c2);
  }
  __name(S2, "S");
  function Ib(a2) {
    S2(a2, "zx", Math.floor(2147483648 * Math.random()).toString(36) + Math.abs(Math.floor(2147483648 * Math.random()) ^ Date.now()).toString(36));
    return a2;
  }
  __name(Ib, "Ib");
  function uc(a2, b2) {
    return a2 ? b2 ? decodeURI(a2.replace(/%25/g, "%2525")) : decodeURIComponent(a2) : "";
  }
  __name(uc, "uc");
  function vc(a2, b2, c2) {
    return "string" === typeof a2 ? (a2 = encodeURI(a2).replace(b2, Cc2), c2 && (a2 = a2.replace(/%25([0-9a-fA-F]{2})/g, "%$1")), a2) : null;
  }
  __name(vc, "vc");
  function Cc2(a2) {
    a2 = a2.charCodeAt(0);
    return "%" + (a2 >> 4 & 15).toString(16) + (a2 & 15).toString(16);
  }
  __name(Cc2, "Cc");
  var wc = /[#\/\?@]/g, yc = /[#\?:]/g, xc = /[#\?]/g, Bc = /[#\?@]/g, zc = /#/g;
  function sc(a2, b2) {
    this.h = this.g = null;
    this.i = a2 || null;
    this.j = !!b2;
  }
  __name(sc, "sc");
  function U2(a2) {
    a2.g || (a2.g = /* @__PURE__ */ new Map(), a2.h = 0, a2.i && pc(a2.i, function(b2, c2) {
      a2.add(decodeURIComponent(b2.replace(/\+/g, " ")), c2);
    }));
  }
  __name(U2, "U");
  h2 = sc.prototype;
  h2.add = function(a2, b2) {
    U2(this);
    this.i = null;
    a2 = V2(this, a2);
    var c2 = this.g.get(a2);
    c2 || this.g.set(a2, c2 = []);
    c2.push(b2);
    this.h += 1;
    return this;
  };
  function Dc(a2, b2) {
    U2(a2);
    b2 = V2(a2, b2);
    a2.g.has(b2) && (a2.i = null, a2.h -= a2.g.get(b2).length, a2.g.delete(b2));
  }
  __name(Dc, "Dc");
  function Ec(a2, b2) {
    U2(a2);
    b2 = V2(a2, b2);
    return a2.g.has(b2);
  }
  __name(Ec, "Ec");
  h2.forEach = function(a2, b2) {
    U2(this);
    this.g.forEach(function(c2, d2) {
      c2.forEach(function(e2) {
        a2.call(b2, e2, d2, this);
      }, this);
    }, this);
  };
  h2.na = function() {
    U2(this);
    const a2 = Array.from(this.g.values()), b2 = Array.from(this.g.keys()), c2 = [];
    for (let d2 = 0; d2 < b2.length; d2++) {
      const e2 = a2[d2];
      for (let f2 = 0; f2 < e2.length; f2++) c2.push(b2[d2]);
    }
    return c2;
  };
  h2.V = function(a2) {
    U2(this);
    let b2 = [];
    if ("string" === typeof a2) Ec(this, a2) && (b2 = b2.concat(this.g.get(V2(this, a2))));
    else {
      a2 = Array.from(this.g.values());
      for (let c2 = 0; c2 < a2.length; c2++) b2 = b2.concat(a2[c2]);
    }
    return b2;
  };
  h2.set = function(a2, b2) {
    U2(this);
    this.i = null;
    a2 = V2(this, a2);
    Ec(this, a2) && (this.h -= this.g.get(a2).length);
    this.g.set(a2, [b2]);
    this.h += 1;
    return this;
  };
  h2.get = function(a2, b2) {
    if (!a2) return b2;
    a2 = this.V(a2);
    return 0 < a2.length ? String(a2[0]) : b2;
  };
  function Lb(a2, b2, c2) {
    Dc(a2, b2);
    0 < c2.length && (a2.i = null, a2.g.set(V2(a2, b2), la(c2)), a2.h += c2.length);
  }
  __name(Lb, "Lb");
  h2.toString = function() {
    if (this.i) return this.i;
    if (!this.g) return "";
    const a2 = [], b2 = Array.from(this.g.keys());
    for (var c2 = 0; c2 < b2.length; c2++) {
      var d2 = b2[c2];
      const f2 = encodeURIComponent(String(d2)), g2 = this.V(d2);
      for (d2 = 0; d2 < g2.length; d2++) {
        var e2 = f2;
        "" !== g2[d2] && (e2 += "=" + encodeURIComponent(String(g2[d2])));
        a2.push(e2);
      }
    }
    return this.i = a2.join("&");
  };
  function V2(a2, b2) {
    b2 = String(b2);
    a2.j && (b2 = b2.toLowerCase());
    return b2;
  }
  __name(V2, "V");
  function Ac(a2, b2) {
    b2 && !a2.j && (U2(a2), a2.i = null, a2.g.forEach(function(c2, d2) {
      var e2 = d2.toLowerCase();
      d2 != e2 && (Dc(this, d2), Lb(this, e2, c2));
    }, a2));
    a2.j = b2;
  }
  __name(Ac, "Ac");
  function Fc(a2, b2) {
    const c2 = new vb();
    if (k2.Image) {
      const d2 = new Image();
      d2.onload = ka(W2, c2, "TestLoadImage: loaded", true, b2, d2);
      d2.onerror = ka(W2, c2, "TestLoadImage: error", false, b2, d2);
      d2.onabort = ka(W2, c2, "TestLoadImage: abort", false, b2, d2);
      d2.ontimeout = ka(W2, c2, "TestLoadImage: timeout", false, b2, d2);
      k2.setTimeout(function() {
        if (d2.ontimeout) d2.ontimeout();
      }, 1e4);
      d2.src = a2;
    } else b2(false);
  }
  __name(Fc, "Fc");
  function Gc(a2, b2) {
    const c2 = new vb(), d2 = new AbortController(), e2 = setTimeout(() => {
      d2.abort();
      W2(c2, "TestPingServer: timeout", false, b2);
    }, 1e4);
    fetch(a2, { signal: d2.signal }).then((f2) => {
      clearTimeout(e2);
      f2.ok ? W2(c2, "TestPingServer: ok", true, b2) : W2(c2, "TestPingServer: server error", false, b2);
    }).catch(() => {
      clearTimeout(e2);
      W2(c2, "TestPingServer: error", false, b2);
    });
  }
  __name(Gc, "Gc");
  function W2(a2, b2, c2, d2, e2) {
    try {
      e2 && (e2.onload = null, e2.onerror = null, e2.onabort = null, e2.ontimeout = null), d2(c2);
    } catch (f2) {
    }
  }
  __name(W2, "W");
  function Hc() {
    this.g = new jb();
  }
  __name(Hc, "Hc");
  function Ic(a2, b2, c2) {
    const d2 = c2 || "";
    try {
      nc(a2, function(e2, f2) {
        let g2 = e2;
        n2(e2) && (g2 = hb(e2));
        b2.push(d2 + f2 + "=" + encodeURIComponent(g2));
      });
    } catch (e2) {
      throw b2.push(d2 + "type=" + encodeURIComponent("_badmap")), e2;
    }
  }
  __name(Ic, "Ic");
  function Jc(a2) {
    this.l = a2.Ub || null;
    this.j = a2.eb || false;
  }
  __name(Jc, "Jc");
  r2(Jc, kb);
  Jc.prototype.g = function() {
    return new Kc(this.l, this.j);
  };
  Jc.prototype.i = /* @__PURE__ */ function(a2) {
    return function() {
      return a2;
    };
  }({});
  function Kc(a2, b2) {
    E.call(this);
    this.D = a2;
    this.o = b2;
    this.m = void 0;
    this.status = this.readyState = 0;
    this.responseType = this.responseText = this.response = this.statusText = "";
    this.onreadystatechange = null;
    this.u = new Headers();
    this.h = null;
    this.B = "GET";
    this.A = "";
    this.g = false;
    this.v = this.j = this.l = null;
  }
  __name(Kc, "Kc");
  r2(Kc, E);
  h2 = Kc.prototype;
  h2.open = function(a2, b2) {
    if (0 != this.readyState) throw this.abort(), Error("Error reopening a connection");
    this.B = a2;
    this.A = b2;
    this.readyState = 1;
    Lc(this);
  };
  h2.send = function(a2) {
    if (1 != this.readyState) throw this.abort(), Error("need to call open() first. ");
    this.g = true;
    const b2 = { headers: this.u, method: this.B, credentials: this.m, cache: void 0 };
    a2 && (b2.body = a2);
    (this.D || k2).fetch(new Request(this.A, b2)).then(this.Sa.bind(this), this.ga.bind(this));
  };
  h2.abort = function() {
    this.response = this.responseText = "";
    this.u = new Headers();
    this.status = 0;
    this.j && this.j.cancel("Request was aborted.").catch(() => {
    });
    1 <= this.readyState && this.g && 4 != this.readyState && (this.g = false, Mc(this));
    this.readyState = 0;
  };
  h2.Sa = function(a2) {
    if (this.g && (this.l = a2, this.h || (this.status = this.l.status, this.statusText = this.l.statusText, this.h = a2.headers, this.readyState = 2, Lc(this)), this.g && (this.readyState = 3, Lc(this), this.g))) if ("arraybuffer" === this.responseType) a2.arrayBuffer().then(this.Qa.bind(this), this.ga.bind(this));
    else if ("undefined" !== typeof k2.ReadableStream && "body" in a2) {
      this.j = a2.body.getReader();
      if (this.o) {
        if (this.responseType) throw Error('responseType must be empty for "streamBinaryChunks" mode responses.');
        this.response = [];
      } else this.response = this.responseText = "", this.v = new TextDecoder();
      Nc(this);
    } else a2.text().then(this.Ra.bind(this), this.ga.bind(this));
  };
  function Nc(a2) {
    a2.j.read().then(a2.Pa.bind(a2)).catch(a2.ga.bind(a2));
  }
  __name(Nc, "Nc");
  h2.Pa = function(a2) {
    if (this.g) {
      if (this.o && a2.value) this.response.push(a2.value);
      else if (!this.o) {
        var b2 = a2.value ? a2.value : new Uint8Array(0);
        if (b2 = this.v.decode(b2, { stream: !a2.done })) this.response = this.responseText += b2;
      }
      a2.done ? Mc(this) : Lc(this);
      3 == this.readyState && Nc(this);
    }
  };
  h2.Ra = function(a2) {
    this.g && (this.response = this.responseText = a2, Mc(this));
  };
  h2.Qa = function(a2) {
    this.g && (this.response = a2, Mc(this));
  };
  h2.ga = function() {
    this.g && Mc(this);
  };
  function Mc(a2) {
    a2.readyState = 4;
    a2.l = null;
    a2.j = null;
    a2.v = null;
    Lc(a2);
  }
  __name(Mc, "Mc");
  h2.setRequestHeader = function(a2, b2) {
    this.u.append(a2, b2);
  };
  h2.getResponseHeader = function(a2) {
    return this.h ? this.h.get(a2.toLowerCase()) || "" : "";
  };
  h2.getAllResponseHeaders = function() {
    if (!this.h) return "";
    const a2 = [], b2 = this.h.entries();
    for (var c2 = b2.next(); !c2.done; ) c2 = c2.value, a2.push(c2[0] + ": " + c2[1]), c2 = b2.next();
    return a2.join("\r\n");
  };
  function Lc(a2) {
    a2.onreadystatechange && a2.onreadystatechange.call(a2);
  }
  __name(Lc, "Lc");
  Object.defineProperty(Kc.prototype, "withCredentials", { get: /* @__PURE__ */ __name(function() {
    return "include" === this.m;
  }, "get"), set: /* @__PURE__ */ __name(function(a2) {
    this.m = a2 ? "include" : "same-origin";
  }, "set") });
  function Oc(a2) {
    let b2 = "";
    qa(a2, function(c2, d2) {
      b2 += d2;
      b2 += ":";
      b2 += c2;
      b2 += "\r\n";
    });
    return b2;
  }
  __name(Oc, "Oc");
  function Pc(a2, b2, c2) {
    a: {
      for (d2 in c2) {
        var d2 = false;
        break a;
      }
      d2 = true;
    }
    d2 || (c2 = Oc(c2), "string" === typeof a2 ? null != c2 && encodeURIComponent(String(c2)) : S2(a2, b2, c2));
  }
  __name(Pc, "Pc");
  function X2(a2) {
    E.call(this);
    this.headers = /* @__PURE__ */ new Map();
    this.o = a2 || null;
    this.h = false;
    this.v = this.g = null;
    this.D = "";
    this.m = 0;
    this.l = "";
    this.j = this.B = this.u = this.A = false;
    this.I = null;
    this.H = "";
    this.J = false;
  }
  __name(X2, "X");
  r2(X2, E);
  var Qc = /^https?$/i, Rc = ["POST", "PUT"];
  h2 = X2.prototype;
  h2.Ha = function(a2) {
    this.J = a2;
  };
  h2.ea = function(a2, b2, c2, d2) {
    if (this.g) throw Error("[goog.net.XhrIo] Object is active with another request=" + this.D + "; newUri=" + a2);
    b2 = b2 ? b2.toUpperCase() : "GET";
    this.D = a2;
    this.l = "";
    this.m = 0;
    this.A = false;
    this.h = true;
    this.g = this.o ? this.o.g() : Cb.g();
    this.v = this.o ? lb(this.o) : lb(Cb);
    this.g.onreadystatechange = p2(this.Ea, this);
    try {
      this.B = true, this.g.open(b2, String(a2), true), this.B = false;
    } catch (f2) {
      Sc(this, f2);
      return;
    }
    a2 = c2 || "";
    c2 = new Map(this.headers);
    if (d2) if (Object.getPrototypeOf(d2) === Object.prototype) for (var e2 in d2) c2.set(e2, d2[e2]);
    else if ("function" === typeof d2.keys && "function" === typeof d2.get) for (const f2 of d2.keys()) c2.set(f2, d2.get(f2));
    else throw Error("Unknown input type for opt_headers: " + String(d2));
    d2 = Array.from(c2.keys()).find((f2) => "content-type" == f2.toLowerCase());
    e2 = k2.FormData && a2 instanceof k2.FormData;
    !(0 <= Array.prototype.indexOf.call(Rc, b2, void 0)) || d2 || e2 || c2.set("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
    for (const [f2, g2] of c2) this.g.setRequestHeader(f2, g2);
    this.H && (this.g.responseType = this.H);
    "withCredentials" in this.g && this.g.withCredentials !== this.J && (this.g.withCredentials = this.J);
    try {
      Tc(this), this.u = true, this.g.send(a2), this.u = false;
    } catch (f2) {
      Sc(this, f2);
    }
  };
  function Sc(a2, b2) {
    a2.h = false;
    a2.g && (a2.j = true, a2.g.abort(), a2.j = false);
    a2.l = b2;
    a2.m = 5;
    Uc(a2);
    Vc(a2);
  }
  __name(Sc, "Sc");
  function Uc(a2) {
    a2.A || (a2.A = true, F2(a2, "complete"), F2(a2, "error"));
  }
  __name(Uc, "Uc");
  h2.abort = function(a2) {
    this.g && this.h && (this.h = false, this.j = true, this.g.abort(), this.j = false, this.m = a2 || 7, F2(this, "complete"), F2(this, "abort"), Vc(this));
  };
  h2.N = function() {
    this.g && (this.h && (this.h = false, this.j = true, this.g.abort(), this.j = false), Vc(this, true));
    X2.aa.N.call(this);
  };
  h2.Ea = function() {
    this.s || (this.B || this.u || this.j ? Wc(this) : this.bb());
  };
  h2.bb = function() {
    Wc(this);
  };
  function Wc(a2) {
    if (a2.h && "undefined" != typeof fa && (!a2.v[1] || 4 != P2(a2) || 2 != a2.Z())) {
      if (a2.u && 4 == P2(a2)) bb(a2.Ea, 0, a2);
      else if (F2(a2, "readystatechange"), 4 == P2(a2)) {
        a2.h = false;
        try {
          const g2 = a2.Z();
          a: switch (g2) {
            case 200:
            case 201:
            case 202:
            case 204:
            case 206:
            case 304:
            case 1223:
              var b2 = true;
              break a;
            default:
              b2 = false;
          }
          var c2;
          if (!(c2 = b2)) {
            var d2;
            if (d2 = 0 === g2) {
              var e2 = String(a2.D).match(oc)[1] || null;
              !e2 && k2.self && k2.self.location && (e2 = k2.self.location.protocol.slice(0, -1));
              d2 = !Qc.test(e2 ? e2.toLowerCase() : "");
            }
            c2 = d2;
          }
          if (c2) F2(a2, "complete"), F2(a2, "success");
          else {
            a2.m = 6;
            try {
              var f2 = 2 < P2(a2) ? a2.g.statusText : "";
            } catch (m2) {
              f2 = "";
            }
            a2.l = f2 + " [" + a2.Z() + "]";
            Uc(a2);
          }
        } finally {
          Vc(a2);
        }
      }
    }
  }
  __name(Wc, "Wc");
  function Vc(a2, b2) {
    if (a2.g) {
      Tc(a2);
      const c2 = a2.g, d2 = a2.v[0] ? () => {
      } : null;
      a2.g = null;
      a2.v = null;
      b2 || F2(a2, "ready");
      try {
        c2.onreadystatechange = d2;
      } catch (e2) {
      }
    }
  }
  __name(Vc, "Vc");
  function Tc(a2) {
    a2.I && (k2.clearTimeout(a2.I), a2.I = null);
  }
  __name(Tc, "Tc");
  h2.isActive = function() {
    return !!this.g;
  };
  function P2(a2) {
    return a2.g ? a2.g.readyState : 0;
  }
  __name(P2, "P");
  h2.Z = function() {
    try {
      return 2 < P2(this) ? this.g.status : -1;
    } catch (a2) {
      return -1;
    }
  };
  h2.oa = function() {
    try {
      return this.g ? this.g.responseText : "";
    } catch (a2) {
      return "";
    }
  };
  h2.Oa = function(a2) {
    if (this.g) {
      var b2 = this.g.responseText;
      a2 && 0 == b2.indexOf(a2) && (b2 = b2.substring(a2.length));
      return ib(b2);
    }
  };
  function Nb(a2) {
    try {
      if (!a2.g) return null;
      if ("response" in a2.g) return a2.g.response;
      switch (a2.H) {
        case "":
        case "text":
          return a2.g.responseText;
        case "arraybuffer":
          if ("mozResponseArrayBuffer" in a2.g) return a2.g.mozResponseArrayBuffer;
      }
      return null;
    } catch (b2) {
      return null;
    }
  }
  __name(Nb, "Nb");
  function Vb(a2) {
    const b2 = {};
    a2 = (a2.g && 2 <= P2(a2) ? a2.g.getAllResponseHeaders() || "" : "").split("\r\n");
    for (let d2 = 0; d2 < a2.length; d2++) {
      if (t2(a2[d2])) continue;
      var c2 = va(a2[d2]);
      const e2 = c2[0];
      c2 = c2[1];
      if ("string" !== typeof c2) continue;
      c2 = c2.trim();
      const f2 = b2[e2] || [];
      b2[e2] = f2;
      f2.push(c2);
    }
    ra(b2, function(d2) {
      return d2.join(", ");
    });
  }
  __name(Vb, "Vb");
  h2.Ba = function() {
    return this.m;
  };
  h2.Ka = function() {
    return "string" === typeof this.l ? this.l : String(this.l);
  };
  function Xc(a2, b2, c2) {
    return c2 && c2.internalChannelParams ? c2.internalChannelParams[a2] || b2 : b2;
  }
  __name(Xc, "Xc");
  function Yc(a2) {
    this.Aa = 0;
    this.i = [];
    this.j = new vb();
    this.ia = this.qa = this.I = this.W = this.g = this.ya = this.D = this.H = this.m = this.S = this.o = null;
    this.Ya = this.U = 0;
    this.Va = Xc("failFast", false, a2);
    this.F = this.C = this.u = this.s = this.l = null;
    this.X = true;
    this.za = this.T = -1;
    this.Y = this.v = this.B = 0;
    this.Ta = Xc("baseRetryDelayMs", 5e3, a2);
    this.cb = Xc("retryDelaySeedMs", 1e4, a2);
    this.Wa = Xc("forwardChannelMaxRetries", 2, a2);
    this.wa = Xc("forwardChannelRequestTimeoutMs", 2e4, a2);
    this.pa = a2 && a2.xmlHttpFactory || void 0;
    this.Xa = a2 && a2.Tb || void 0;
    this.Ca = a2 && a2.useFetchStreams || false;
    this.L = void 0;
    this.J = a2 && a2.supportsCrossDomainXhr || false;
    this.K = "";
    this.h = new ic(a2 && a2.concurrentRequestLimit);
    this.Da = new Hc();
    this.P = a2 && a2.fastHandshake || false;
    this.O = a2 && a2.encodeInitMessageHeaders || false;
    this.P && this.O && (this.O = false);
    this.Ua = a2 && a2.Rb || false;
    a2 && a2.xa && this.j.xa();
    a2 && a2.forceLongPolling && (this.X = false);
    this.ba = !this.P && this.X && a2 && a2.detectBufferingProxy || false;
    this.ja = void 0;
    a2 && a2.longPollingTimeout && 0 < a2.longPollingTimeout && (this.ja = a2.longPollingTimeout);
    this.ca = void 0;
    this.R = 0;
    this.M = false;
    this.ka = this.A = null;
  }
  __name(Yc, "Yc");
  h2 = Yc.prototype;
  h2.la = 8;
  h2.G = 1;
  h2.connect = function(a2, b2, c2, d2) {
    K2(0);
    this.W = a2;
    this.H = b2 || {};
    c2 && void 0 !== d2 && (this.H.OSID = c2, this.H.OAID = d2);
    this.F = this.X;
    this.I = cc(this, null, this.W);
    fc(this);
  };
  function gc(a2) {
    Zc(a2);
    if (3 == a2.G) {
      var b2 = a2.U++, c2 = N2(a2.I);
      S2(c2, "SID", a2.K);
      S2(c2, "RID", b2);
      S2(c2, "TYPE", "terminate");
      $c(a2, c2);
      b2 = new M2(a2, a2.j, b2);
      b2.L = 2;
      b2.v = Ib(N2(c2));
      c2 = false;
      if (k2.navigator && k2.navigator.sendBeacon) try {
        c2 = k2.navigator.sendBeacon(b2.v.toString(), "");
      } catch (d2) {
      }
      !c2 && k2.Image && (new Image().src = b2.v, c2 = true);
      c2 || (b2.g = Mb(b2.j, null), b2.g.ea(b2.v));
      b2.F = Date.now();
      Kb(b2);
    }
    ad(a2);
  }
  __name(gc, "gc");
  function Zb(a2) {
    a2.g && (Tb(a2), a2.g.cancel(), a2.g = null);
  }
  __name(Zb, "Zb");
  function Zc(a2) {
    Zb(a2);
    a2.u && (k2.clearTimeout(a2.u), a2.u = null);
    Yb(a2);
    a2.h.cancel();
    a2.s && ("number" === typeof a2.s && k2.clearTimeout(a2.s), a2.s = null);
  }
  __name(Zc, "Zc");
  function fc(a2) {
    if (!jc(a2.h) && !a2.s) {
      a2.s = true;
      var b2 = a2.Ga;
      x2 || Ea();
      y2 || (x2(), y2 = true);
      za.add(b2, a2);
      a2.B = 0;
    }
  }
  __name(fc, "fc");
  function bd(a2, b2) {
    if (ac(a2.h) >= a2.h.j - (a2.s ? 1 : 0)) return false;
    if (a2.s) return a2.i = b2.D.concat(a2.i), true;
    if (1 == a2.G || 2 == a2.G || a2.B >= (a2.Va ? 0 : a2.Wa)) return false;
    a2.s = ub(p2(a2.Ga, a2, b2), cd(a2, a2.B));
    a2.B++;
    return true;
  }
  __name(bd, "bd");
  h2.Ga = function(a2) {
    if (this.s) if (this.s = null, 1 == this.G) {
      if (!a2) {
        this.U = Math.floor(1e5 * Math.random());
        a2 = this.U++;
        const e2 = new M2(this, this.j, a2);
        let f2 = this.o;
        this.S && (f2 ? (f2 = sa(f2), ua(f2, this.S)) : f2 = this.S);
        null !== this.m || this.O || (e2.H = f2, f2 = null);
        if (this.P) a: {
          var b2 = 0;
          for (var c2 = 0; c2 < this.i.length; c2++) {
            b: {
              var d2 = this.i[c2];
              if ("__data__" in d2.map && (d2 = d2.map.__data__, "string" === typeof d2)) {
                d2 = d2.length;
                break b;
              }
              d2 = void 0;
            }
            if (void 0 === d2) break;
            b2 += d2;
            if (4096 < b2) {
              b2 = c2;
              break a;
            }
            if (4096 === b2 || c2 === this.i.length - 1) {
              b2 = c2 + 1;
              break a;
            }
          }
          b2 = 1e3;
        }
        else b2 = 1e3;
        b2 = dd(this, e2, b2);
        c2 = N2(this.I);
        S2(c2, "RID", a2);
        S2(c2, "CVER", 22);
        this.D && S2(c2, "X-HTTP-Session-Id", this.D);
        $c(this, c2);
        f2 && (this.O ? b2 = "headers=" + encodeURIComponent(String(Oc(f2))) + "&" + b2 : this.m && Pc(c2, this.m, f2));
        bc(this.h, e2);
        this.Ua && S2(c2, "TYPE", "init");
        this.P ? (S2(c2, "$req", b2), S2(c2, "SID", "null"), e2.T = true, Hb(e2, c2, null)) : Hb(e2, c2, b2);
        this.G = 2;
      }
    } else 3 == this.G && (a2 ? ed(this, a2) : 0 == this.i.length || jc(this.h) || ed(this));
  };
  function ed(a2, b2) {
    var c2;
    b2 ? c2 = b2.l : c2 = a2.U++;
    const d2 = N2(a2.I);
    S2(d2, "SID", a2.K);
    S2(d2, "RID", c2);
    S2(d2, "AID", a2.T);
    $c(a2, d2);
    a2.m && a2.o && Pc(d2, a2.m, a2.o);
    c2 = new M2(a2, a2.j, c2, a2.B + 1);
    null === a2.m && (c2.H = a2.o);
    b2 && (a2.i = b2.D.concat(a2.i));
    b2 = dd(a2, c2, 1e3);
    c2.I = Math.round(0.5 * a2.wa) + Math.round(0.5 * a2.wa * Math.random());
    bc(a2.h, c2);
    Hb(c2, d2, b2);
  }
  __name(ed, "ed");
  function $c(a2, b2) {
    a2.H && qa(a2.H, function(c2, d2) {
      S2(b2, d2, c2);
    });
    a2.l && nc({}, function(c2, d2) {
      S2(b2, d2, c2);
    });
  }
  __name($c, "$c");
  function dd(a2, b2, c2) {
    c2 = Math.min(a2.i.length, c2);
    var d2 = a2.l ? p2(a2.l.Na, a2.l, a2) : null;
    a: {
      var e2 = a2.i;
      let f2 = -1;
      for (; ; ) {
        const g2 = ["count=" + c2];
        -1 == f2 ? 0 < c2 ? (f2 = e2[0].g, g2.push("ofs=" + f2)) : f2 = 0 : g2.push("ofs=" + f2);
        let m2 = true;
        for (let q2 = 0; q2 < c2; q2++) {
          let l2 = e2[q2].g;
          const v2 = e2[q2].map;
          l2 -= f2;
          if (0 > l2) f2 = Math.max(0, e2[q2].g - 100), m2 = false;
          else try {
            Ic(v2, g2, "req" + l2 + "_");
          } catch (w2) {
            d2 && d2(v2);
          }
        }
        if (m2) {
          d2 = g2.join("&");
          break a;
        }
      }
    }
    a2 = a2.i.splice(0, c2);
    b2.D = a2;
    return d2;
  }
  __name(dd, "dd");
  function ec(a2) {
    if (!a2.g && !a2.u) {
      a2.Y = 1;
      var b2 = a2.Fa;
      x2 || Ea();
      y2 || (x2(), y2 = true);
      za.add(b2, a2);
      a2.v = 0;
    }
  }
  __name(ec, "ec");
  function $b(a2) {
    if (a2.g || a2.u || 3 <= a2.v) return false;
    a2.Y++;
    a2.u = ub(p2(a2.Fa, a2), cd(a2, a2.v));
    a2.v++;
    return true;
  }
  __name($b, "$b");
  h2.Fa = function() {
    this.u = null;
    fd(this);
    if (this.ba && !(this.M || null == this.g || 0 >= this.R)) {
      var a2 = 2 * this.R;
      this.j.info("BP detection timer enabled: " + a2);
      this.A = ub(p2(this.ab, this), a2);
    }
  };
  h2.ab = function() {
    this.A && (this.A = null, this.j.info("BP detection timeout reached."), this.j.info("Buffering proxy detected and switch to long-polling!"), this.F = false, this.M = true, K2(10), Zb(this), fd(this));
  };
  function Tb(a2) {
    null != a2.A && (k2.clearTimeout(a2.A), a2.A = null);
  }
  __name(Tb, "Tb");
  function fd(a2) {
    a2.g = new M2(a2, a2.j, "rpc", a2.Y);
    null === a2.m && (a2.g.H = a2.o);
    a2.g.O = 0;
    var b2 = N2(a2.qa);
    S2(b2, "RID", "rpc");
    S2(b2, "SID", a2.K);
    S2(b2, "AID", a2.T);
    S2(b2, "CI", a2.F ? "0" : "1");
    !a2.F && a2.ja && S2(b2, "TO", a2.ja);
    S2(b2, "TYPE", "xmlhttp");
    $c(a2, b2);
    a2.m && a2.o && Pc(b2, a2.m, a2.o);
    a2.L && (a2.g.I = a2.L);
    var c2 = a2.g;
    a2 = a2.ia;
    c2.L = 1;
    c2.v = Ib(N2(b2));
    c2.m = null;
    c2.P = true;
    Jb(c2, a2);
  }
  __name(fd, "fd");
  h2.Za = function() {
    null != this.C && (this.C = null, Zb(this), $b(this), K2(19));
  };
  function Yb(a2) {
    null != a2.C && (k2.clearTimeout(a2.C), a2.C = null);
  }
  __name(Yb, "Yb");
  function Ub(a2, b2) {
    var c2 = null;
    if (a2.g == b2) {
      Yb(a2);
      Tb(a2);
      a2.g = null;
      var d2 = 2;
    } else if (Xb(a2.h, b2)) c2 = b2.D, dc(a2.h, b2), d2 = 1;
    else return;
    if (0 != a2.G) {
      if (b2.o) if (1 == d2) {
        c2 = b2.m ? b2.m.length : 0;
        b2 = Date.now() - b2.F;
        var e2 = a2.B;
        d2 = qb();
        F2(d2, new tb(d2, c2));
        fc(a2);
      } else ec(a2);
      else if (e2 = b2.s, 3 == e2 || 0 == e2 && 0 < b2.X || !(1 == d2 && bd(a2, b2) || 2 == d2 && $b(a2))) switch (c2 && 0 < c2.length && (b2 = a2.h, b2.i = b2.i.concat(c2)), e2) {
        case 1:
          R(a2, 5);
          break;
        case 4:
          R(a2, 10);
          break;
        case 3:
          R(a2, 6);
          break;
        default:
          R(a2, 2);
      }
    }
  }
  __name(Ub, "Ub");
  function cd(a2, b2) {
    let c2 = a2.Ta + Math.floor(Math.random() * a2.cb);
    a2.isActive() || (c2 *= 2);
    return c2 * b2;
  }
  __name(cd, "cd");
  function R(a2, b2) {
    a2.j.info("Error code " + b2);
    if (2 == b2) {
      var c2 = p2(a2.fb, a2), d2 = a2.Xa;
      const e2 = !d2;
      d2 = new T2(d2 || "//www.google.com/images/cleardot.gif");
      k2.location && "http" == k2.location.protocol || qc(d2, "https");
      Ib(d2);
      e2 ? Fc(d2.toString(), c2) : Gc(d2.toString(), c2);
    } else K2(2);
    a2.G = 0;
    a2.l && a2.l.sa(b2);
    ad(a2);
    Zc(a2);
  }
  __name(R, "R");
  h2.fb = function(a2) {
    a2 ? (this.j.info("Successfully pinged google.com"), K2(2)) : (this.j.info("Failed to ping google.com"), K2(1));
  };
  function ad(a2) {
    a2.G = 0;
    a2.ka = [];
    if (a2.l) {
      const b2 = kc(a2.h);
      if (0 != b2.length || 0 != a2.i.length) ma(a2.ka, b2), ma(a2.ka, a2.i), a2.h.i.length = 0, la(a2.i), a2.i.length = 0;
      a2.l.ra();
    }
  }
  __name(ad, "ad");
  function cc(a2, b2, c2) {
    var d2 = c2 instanceof T2 ? N2(c2) : new T2(c2);
    if ("" != d2.g) b2 && (d2.g = b2 + "." + d2.g), rc(d2, d2.s);
    else {
      var e2 = k2.location;
      d2 = e2.protocol;
      b2 = b2 ? b2 + "." + e2.hostname : e2.hostname;
      e2 = +e2.port;
      var f2 = new T2(null);
      d2 && qc(f2, d2);
      b2 && (f2.g = b2);
      e2 && rc(f2, e2);
      c2 && (f2.l = c2);
      d2 = f2;
    }
    c2 = a2.D;
    b2 = a2.ya;
    c2 && b2 && S2(d2, c2, b2);
    S2(d2, "VER", a2.la);
    $c(a2, d2);
    return d2;
  }
  __name(cc, "cc");
  function Mb(a2, b2, c2) {
    if (b2 && !a2.J) throw Error("Can't create secondary domain capable XhrIo object.");
    b2 = a2.Ca && !a2.pa ? new X2(new Jc({ eb: c2 })) : new X2(a2.pa);
    b2.Ha(a2.J);
    return b2;
  }
  __name(Mb, "Mb");
  h2.isActive = function() {
    return !!this.l && this.l.isActive(this);
  };
  function gd() {
  }
  __name(gd, "gd");
  h2 = gd.prototype;
  h2.ua = function() {
  };
  h2.ta = function() {
  };
  h2.sa = function() {
  };
  h2.ra = function() {
  };
  h2.isActive = function() {
    return true;
  };
  h2.Na = function() {
  };
  function hd() {
  }
  __name(hd, "hd");
  hd.prototype.g = function(a2, b2) {
    return new Y2(a2, b2);
  };
  function Y2(a2, b2) {
    E.call(this);
    this.g = new Yc(b2);
    this.l = a2;
    this.h = b2 && b2.messageUrlParams || null;
    a2 = b2 && b2.messageHeaders || null;
    b2 && b2.clientProtocolHeaderRequired && (a2 ? a2["X-Client-Protocol"] = "webchannel" : a2 = { "X-Client-Protocol": "webchannel" });
    this.g.o = a2;
    a2 = b2 && b2.initMessageHeaders || null;
    b2 && b2.messageContentType && (a2 ? a2["X-WebChannel-Content-Type"] = b2.messageContentType : a2 = { "X-WebChannel-Content-Type": b2.messageContentType });
    b2 && b2.va && (a2 ? a2["X-WebChannel-Client-Profile"] = b2.va : a2 = { "X-WebChannel-Client-Profile": b2.va });
    this.g.S = a2;
    (a2 = b2 && b2.Sb) && !t2(a2) && (this.g.m = a2);
    this.v = b2 && b2.supportsCrossDomainXhr || false;
    this.u = b2 && b2.sendRawJson || false;
    (b2 = b2 && b2.httpSessionIdParam) && !t2(b2) && (this.g.D = b2, a2 = this.h, null !== a2 && b2 in a2 && (a2 = this.h, b2 in a2 && delete a2[b2]));
    this.j = new Z2(this);
  }
  __name(Y2, "Y");
  r2(Y2, E);
  Y2.prototype.m = function() {
    this.g.l = this.j;
    this.v && (this.g.J = true);
    this.g.connect(this.l, this.h || void 0);
  };
  Y2.prototype.close = function() {
    gc(this.g);
  };
  Y2.prototype.o = function(a2) {
    var b2 = this.g;
    if ("string" === typeof a2) {
      var c2 = {};
      c2.__data__ = a2;
      a2 = c2;
    } else this.u && (c2 = {}, c2.__data__ = hb(a2), a2 = c2);
    b2.i.push(new hc(b2.Ya++, a2));
    3 == b2.G && fc(b2);
  };
  Y2.prototype.N = function() {
    this.g.l = null;
    delete this.j;
    gc(this.g);
    delete this.g;
    Y2.aa.N.call(this);
  };
  function id2(a2) {
    nb.call(this);
    a2.__headers__ && (this.headers = a2.__headers__, this.statusCode = a2.__status__, delete a2.__headers__, delete a2.__status__);
    var b2 = a2.__sm__;
    if (b2) {
      a: {
        for (const c2 in b2) {
          a2 = c2;
          break a;
        }
        a2 = void 0;
      }
      if (this.i = a2) a2 = this.i, b2 = null !== b2 && a2 in b2 ? b2[a2] : void 0;
      this.data = b2;
    } else this.data = a2;
  }
  __name(id2, "id");
  r2(id2, nb);
  function jd() {
    ob.call(this);
    this.status = 1;
  }
  __name(jd, "jd");
  r2(jd, ob);
  function Z2(a2) {
    this.g = a2;
  }
  __name(Z2, "Z");
  r2(Z2, gd);
  Z2.prototype.ua = function() {
    F2(this.g, "a");
  };
  Z2.prototype.ta = function(a2) {
    F2(this.g, new id2(a2));
  };
  Z2.prototype.sa = function(a2) {
    F2(this.g, new jd());
  };
  Z2.prototype.ra = function() {
    F2(this.g, "b");
  };
  hd.prototype.createWebChannel = hd.prototype.g;
  Y2.prototype.send = Y2.prototype.o;
  Y2.prototype.open = Y2.prototype.m;
  Y2.prototype.close = Y2.prototype.close;
  createWebChannelTransport = webchannel_blob_es2018.createWebChannelTransport = function() {
    return new hd();
  };
  getStatEventTarget = webchannel_blob_es2018.getStatEventTarget = function() {
    return qb();
  };
  Event$1 = webchannel_blob_es2018.Event = I2;
  Stat = webchannel_blob_es2018.Stat = { mb: 0, pb: 1, qb: 2, Jb: 3, Ob: 4, Lb: 5, Mb: 6, Kb: 7, Ib: 8, Nb: 9, PROXY: 10, NOPROXY: 11, Gb: 12, Cb: 13, Db: 14, Bb: 15, Eb: 16, Fb: 17, ib: 18, hb: 19, jb: 20 };
  Ab.NO_ERROR = 0;
  Ab.TIMEOUT = 8;
  Ab.HTTP_ERROR = 6;
  ErrorCode$1 = webchannel_blob_es2018.ErrorCode = Ab;
  Bb.COMPLETE = "complete";
  EventType = webchannel_blob_es2018.EventType = Bb;
  mb.EventType = H2;
  H2.OPEN = "a";
  H2.CLOSE = "b";
  H2.ERROR = "c";
  H2.MESSAGE = "d";
  E.prototype.listen = E.prototype.K;
  WebChannel = webchannel_blob_es2018.WebChannel = mb;
  FetchXmlHttpFactory = webchannel_blob_es2018.FetchXmlHttpFactory = Jc;
  X2.prototype.listenOnce = X2.prototype.L;
  X2.prototype.getLastError = X2.prototype.Ka;
  X2.prototype.getLastErrorCode = X2.prototype.Ba;
  X2.prototype.getStatus = X2.prototype.Z;
  X2.prototype.getResponseJson = X2.prototype.Oa;
  X2.prototype.getResponseText = X2.prototype.oa;
  X2.prototype.send = X2.prototype.ea;
  X2.prototype.setWithCredentials = X2.prototype.Ha;
  XhrIo = webchannel_blob_es2018.XhrIo = X2;
}).apply(typeof commonjsGlobal$1 !== "undefined" ? commonjsGlobal$1 : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {});
const S = "@firebase/firestore", b = "4.7.10";
/**
 * @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 User {
  static {
    __name(this, "User");
  }
  constructor(e2) {
    this.uid = e2;
  }
  isAuthenticated() {
    return null != this.uid;
  }
  /**
   * Returns a key representing this user, suitable for inclusion in a
   * dictionary.
   */
  toKey() {
    return this.isAuthenticated() ? "uid:" + this.uid : "anonymous-user";
  }
  isEqual(e2) {
    return e2.uid === this.uid;
  }
}
User.UNAUTHENTICATED = new User(null), // TODO(mikelehen): Look into getting a proper uid-equivalent for
// non-FirebaseAuth providers.
User.GOOGLE_CREDENTIALS = new User("google-credentials-uid"), User.FIRST_PARTY = new User("first-party-uid"), User.MOCK_USER = new User("mock-user");
/**
 * @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 D = "11.5.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.
 */
const v = new Logger("@firebase/firestore");
function __PRIVATE_getLogLevel() {
  return v.logLevel;
}
__name(__PRIVATE_getLogLevel, "__PRIVATE_getLogLevel");
function setLogLevel(e2) {
  v.setLogLevel(e2);
}
__name(setLogLevel, "setLogLevel");
function __PRIVATE_logDebug(e2, ...t2) {
  if (v.logLevel <= LogLevel.DEBUG) {
    const n2 = t2.map(__PRIVATE_argToString);
    v.debug(`Firestore (${D}): ${e2}`, ...n2);
  }
}
__name(__PRIVATE_logDebug, "__PRIVATE_logDebug");
function __PRIVATE_logError(e2, ...t2) {
  if (v.logLevel <= LogLevel.ERROR) {
    const n2 = t2.map(__PRIVATE_argToString);
    v.error(`Firestore (${D}): ${e2}`, ...n2);
  }
}
__name(__PRIVATE_logError, "__PRIVATE_logError");
function __PRIVATE_logWarn(e2, ...t2) {
  if (v.logLevel <= LogLevel.WARN) {
    const n2 = t2.map(__PRIVATE_argToString);
    v.warn(`Firestore (${D}): ${e2}`, ...n2);
  }
}
__name(__PRIVATE_logWarn, "__PRIVATE_logWarn");
function __PRIVATE_argToString(e2) {
  if ("string" == typeof e2) return e2;
  try {
    /**
    * @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.
    */
    return (/* @__PURE__ */ __name(function __PRIVATE_formatJSON(e3) {
      return JSON.stringify(e3);
    }, "__PRIVATE_formatJSON"))(e2);
  } catch (t2) {
    return e2;
  }
}
__name(__PRIVATE_argToString, "__PRIVATE_argToString");
/**
 * @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 fail(e2 = "Unexpected state") {
  const t2 = `FIRESTORE (${D}) INTERNAL ASSERTION FAILED: ` + e2;
  throw __PRIVATE_logError(t2), new Error(t2);
}
__name(fail, "fail");
function __PRIVATE_hardAssert(e2, t2) {
  e2 || fail();
}
__name(__PRIVATE_hardAssert, "__PRIVATE_hardAssert");
function __PRIVATE_debugAssert(e2, t2) {
  e2 || fail();
}
__name(__PRIVATE_debugAssert, "__PRIVATE_debugAssert");
function __PRIVATE_debugCast(e2, t2) {
  return e2;
}
__name(__PRIVATE_debugCast, "__PRIVATE_debugCast");
/**
 * @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 C = {
  // Causes are copied from:
  // https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h
  /** Not an error; returned on success. */
  OK: "ok",
  /** The operation was cancelled (typically by the caller). */
  CANCELLED: "cancelled",
  /** Unknown error or an error from a different error domain. */
  UNKNOWN: "unknown",
  /**
   * Client specified an invalid argument. Note that this differs from
   * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are
   * problematic regardless of the state of the system (e.g., a malformed file
   * name).
   */
  INVALID_ARGUMENT: "invalid-argument",
  /**
   * Deadline expired before operation could complete. For operations that
   * change the state of the system, this error may be returned even if the
   * operation has completed successfully. For example, a successful response
   * from a server could have been delayed long enough for the deadline to
   * expire.
   */
  DEADLINE_EXCEEDED: "deadline-exceeded",
  /** Some requested entity (e.g., file or directory) was not found. */
  NOT_FOUND: "not-found",
  /**
   * Some entity that we attempted to create (e.g., file or directory) already
   * exists.
   */
  ALREADY_EXISTS: "already-exists",
  /**
   * The caller does not have permission to execute the specified operation.
   * PERMISSION_DENIED must not be used for rejections caused by exhausting
   * some resource (use RESOURCE_EXHAUSTED instead for those errors).
   * PERMISSION_DENIED must not be used if the caller cannot be identified
   * (use UNAUTHENTICATED instead for those errors).
   */
  PERMISSION_DENIED: "permission-denied",
  /**
   * The request does not have valid authentication credentials for the
   * operation.
   */
  UNAUTHENTICATED: "unauthenticated",
  /**
   * Some resource has been exhausted, perhaps a per-user quota, or perhaps the
   * entire file system is out of space.
   */
  RESOURCE_EXHAUSTED: "resource-exhausted",
  /**
   * Operation was rejected because the system is not in a state required for
   * the operation's execution. For example, directory to be deleted may be
   * non-empty, an rmdir operation is applied to a non-directory, etc.
   *
   * A litmus test that may help a service implementor in deciding
   * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE:
   *  (a) Use UNAVAILABLE if the client can retry just the failing call.
   *  (b) Use ABORTED if the client should retry at a higher-level
   *      (e.g., restarting a read-modify-write sequence).
   *  (c) Use FAILED_PRECONDITION if the client should not retry until
   *      the system state has been explicitly fixed. E.g., if an "rmdir"
   *      fails because the directory is non-empty, FAILED_PRECONDITION
   *      should be returned since the client should not retry unless
   *      they have first fixed up the directory by deleting files from it.
   *  (d) Use FAILED_PRECONDITION if the client performs conditional
   *      REST Get/Update/Delete on a resource and the resource on the
   *      server does not match the condition. E.g., conflicting
   *      read-modify-write on the same resource.
   */
  FAILED_PRECONDITION: "failed-precondition",
  /**
   * The operation was aborted, typically due to a concurrency issue like
   * sequencer check failures, transaction aborts, etc.
   *
   * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,
   * and UNAVAILABLE.
   */
  ABORTED: "aborted",
  /**
   * Operation was attempted past the valid range. E.g., seeking or reading
   * past end of file.
   *
   * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed
   * if the system state changes. For example, a 32-bit file system will
   * generate INVALID_ARGUMENT if asked to read at an offset that is not in the
   * range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from
   * an offset past the current file size.
   *
   * There is a fair bit of overlap between FAILED_PRECONDITION and
   * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error)
   * when it applies so that callers who are iterating through a space can
   * easily look for an OUT_OF_RANGE error to detect when they are done.
   */
  OUT_OF_RANGE: "out-of-range",
  /** Operation is not implemented or not supported/enabled in this service. */
  UNIMPLEMENTED: "unimplemented",
  /**
   * Internal errors. Means some invariants expected by underlying System has
   * been broken. If you see one of these errors, Something is very broken.
   */
  INTERNAL: "internal",
  /**
   * The service is currently unavailable. This is a most likely a transient
   * condition and may be corrected by retrying with a backoff.
   *
   * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,
   * and UNAVAILABLE.
   */
  UNAVAILABLE: "unavailable",
  /** Unrecoverable data loss or corruption. */
  DATA_LOSS: "data-loss"
};
class FirestoreError extends FirebaseError {
  static {
    __name(this, "FirestoreError");
  }
  /** @hideconstructor */
  constructor(e2, t2) {
    super(e2, t2), this.code = e2, this.message = t2, // HACK: We write a toString property directly because Error is not a real
    // class and so inheritance does not work correctly. We could alternatively
    // do the same "back-door inheritance" trick that FirebaseError does.
    this.toString = () => `${this.name}: [code=${this.code}]: ${this.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.
 */
class __PRIVATE_Deferred {
  static {
    __name(this, "__PRIVATE_Deferred");
  }
  constructor() {
    this.promise = new Promise((e2, t2) => {
      this.resolve = e2, this.reject = t2;
    });
  }
}
/**
 * @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 __PRIVATE_OAuthToken {
  static {
    __name(this, "__PRIVATE_OAuthToken");
  }
  constructor(e2, t2) {
    this.user = t2, this.type = "OAuth", this.headers = /* @__PURE__ */ new Map(), this.headers.set("Authorization", `Bearer ${e2}`);
  }
}
class __PRIVATE_EmptyAuthCredentialsProvider {
  static {
    __name(this, "__PRIVATE_EmptyAuthCredentialsProvider");
  }
  getToken() {
    return Promise.resolve(null);
  }
  invalidateToken() {
  }
  start(e2, t2) {
    e2.enqueueRetryable(() => t2(User.UNAUTHENTICATED));
  }
  shutdown() {
  }
}
class __PRIVATE_EmulatorAuthCredentialsProvider {
  static {
    __name(this, "__PRIVATE_EmulatorAuthCredentialsProvider");
  }
  constructor(e2) {
    this.token = e2, /**
     * Stores the listener registered with setChangeListener()
     * This isn't actually necessary since the UID never changes, but we use this
     * to verify the listen contract is adhered to in tests.
     */
    this.changeListener = null;
  }
  getToken() {
    return Promise.resolve(this.token);
  }
  invalidateToken() {
  }
  start(e2, t2) {
    this.changeListener = t2, // Fire with initial user.
    e2.enqueueRetryable(() => t2(this.token.user));
  }
  shutdown() {
    this.changeListener = null;
  }
}
class __PRIVATE_FirebaseAuthCredentialsProvider {
  static {
    __name(this, "__PRIVATE_FirebaseAuthCredentialsProvider");
  }
  constructor(e2) {
    this.t = e2, /** Tracks the current User. */
    this.currentUser = User.UNAUTHENTICATED, /**
     * Counter used to detect if the token changed while a getToken request was
     * outstanding.
     */
    this.i = 0, this.forceRefresh = false, this.auth = null;
  }
  start(e2, t2) {
    __PRIVATE_hardAssert(void 0 === this.o);
    let n2 = this.i;
    const __PRIVATE_guardedChangeListener = /* @__PURE__ */ __name((e3) => this.i !== n2 ? (n2 = this.i, t2(e3)) : Promise.resolve(), "__PRIVATE_guardedChangeListener");
    let r2 = new __PRIVATE_Deferred();
    this.o = () => {
      this.i++, this.currentUser = this.u(), r2.resolve(), r2 = new __PRIVATE_Deferred(), e2.enqueueRetryable(() => __PRIVATE_guardedChangeListener(this.currentUser));
    };
    const __PRIVATE_awaitNextToken = /* @__PURE__ */ __name(() => {
      const t3 = r2;
      e2.enqueueRetryable(async () => {
        await t3.promise, await __PRIVATE_guardedChangeListener(this.currentUser);
      });
    }, "__PRIVATE_awaitNextToken"), __PRIVATE_registerAuth = /* @__PURE__ */ __name((e3) => {
      __PRIVATE_logDebug("FirebaseAuthCredentialsProvider", "Auth detected"), this.auth = e3, this.o && (this.auth.addAuthTokenListener(this.o), __PRIVATE_awaitNextToken());
    }, "__PRIVATE_registerAuth");
    this.t.onInit((e3) => __PRIVATE_registerAuth(e3)), // Our users can initialize Auth right after Firestore, so we give it
    // a chance to register itself with the component framework before we
    // determine whether to start up in unauthenticated mode.
    setTimeout(() => {
      if (!this.auth) {
        const e3 = this.t.getImmediate({
          optional: true
        });
        e3 ? __PRIVATE_registerAuth(e3) : (
          // If auth is still not available, proceed with `null` user
          (__PRIVATE_logDebug("FirebaseAuthCredentialsProvider", "Auth not yet detected"), r2.resolve(), r2 = new __PRIVATE_Deferred())
        );
      }
    }, 0), __PRIVATE_awaitNextToken();
  }
  getToken() {
    const e2 = this.i, t2 = this.forceRefresh;
    return this.forceRefresh = false, this.auth ? this.auth.getToken(t2).then((t3) => (
      // Cancel the request since the token changed while the request was
      // outstanding so the response is potentially for a previous user (which
      // user, we can't be sure).
      this.i !== e2 ? (__PRIVATE_logDebug("FirebaseAuthCredentialsProvider", "getToken aborted due to token change."), this.getToken()) : t3 ? (__PRIVATE_hardAssert("string" == typeof t3.accessToken), new __PRIVATE_OAuthToken(t3.accessToken, this.currentUser)) : null
    )) : Promise.resolve(null);
  }
  invalidateToken() {
    this.forceRefresh = true;
  }
  shutdown() {
    this.auth && this.o && this.auth.removeAuthTokenListener(this.o), this.o = void 0;
  }
  // Auth.getUid() can return null even with a user logged in. It is because
  // getUid() is synchronous, but the auth code populating Uid is asynchronous.
  // This method should only be called in the AuthTokenListener callback
  // to guarantee to get the actual user.
  u() {
    const e2 = this.auth && this.auth.getUid();
    return __PRIVATE_hardAssert(null === e2 || "string" == typeof e2), new User(e2);
  }
}
class __PRIVATE_FirstPartyToken {
  static {
    __name(this, "__PRIVATE_FirstPartyToken");
  }
  constructor(e2, t2, n2) {
    this.l = e2, this.h = t2, this.P = n2, this.type = "FirstParty", this.user = User.FIRST_PARTY, this.T = /* @__PURE__ */ new Map();
  }
  /**
   * Gets an authorization token, using a provided factory function, or return
   * null.
   */
  I() {
    return this.P ? this.P() : null;
  }
  get headers() {
    this.T.set("X-Goog-AuthUser", this.l);
    const e2 = this.I();
    return e2 && this.T.set("Authorization", e2), this.h && this.T.set("X-Goog-Iam-Authorization-Token", this.h), this.T;
  }
}
class __PRIVATE_FirstPartyAuthCredentialsProvider {
  static {
    __name(this, "__PRIVATE_FirstPartyAuthCredentialsProvider");
  }
  constructor(e2, t2, n2) {
    this.l = e2, this.h = t2, this.P = n2;
  }
  getToken() {
    return Promise.resolve(new __PRIVATE_FirstPartyToken(this.l, this.h, this.P));
  }
  start(e2, t2) {
    e2.enqueueRetryable(() => t2(User.FIRST_PARTY));
  }
  shutdown() {
  }
  invalidateToken() {
  }
}
class AppCheckToken {
  static {
    __name(this, "AppCheckToken");
  }
  constructor(e2) {
    this.value = e2, this.type = "AppCheck", this.headers = /* @__PURE__ */ new Map(), e2 && e2.length > 0 && this.headers.set("x-firebase-appcheck", this.value);
  }
}
class __PRIVATE_FirebaseAppCheckTokenProvider {
  static {
    __name(this, "__PRIVATE_FirebaseAppCheckTokenProvider");
  }
  constructor(t2, n2) {
    this.A = n2, this.forceRefresh = false, this.appCheck = null, this.R = null, this.V = null, _isFirebaseServerApp(t2) && t2.settings.appCheckToken && (this.V = t2.settings.appCheckToken);
  }
  start(e2, t2) {
    __PRIVATE_hardAssert(void 0 === this.o);
    const onTokenChanged2 = /* @__PURE__ */ __name((e3) => {
      null != e3.error && __PRIVATE_logDebug("FirebaseAppCheckTokenProvider", `Error getting App Check token; using placeholder token instead. Error: ${e3.error.message}`);
      const n2 = e3.token !== this.R;
      return this.R = e3.token, __PRIVATE_logDebug("FirebaseAppCheckTokenProvider", `Received ${n2 ? "new" : "existing"} token.`), n2 ? t2(e3.token) : Promise.resolve();
    }, "onTokenChanged");
    this.o = (t3) => {
      e2.enqueueRetryable(() => onTokenChanged2(t3));
    };
    const __PRIVATE_registerAppCheck = /* @__PURE__ */ __name((e3) => {
      __PRIVATE_logDebug("FirebaseAppCheckTokenProvider", "AppCheck detected"), this.appCheck = e3, this.o && this.appCheck.addTokenListener(this.o);
    }, "__PRIVATE_registerAppCheck");
    this.A.onInit((e3) => __PRIVATE_registerAppCheck(e3)), // Our users can initialize AppCheck after Firestore, so we give it
    // a chance to register itself with the component framework.
    setTimeout(() => {
      if (!this.appCheck) {
        const e3 = this.A.getImmediate({
          optional: true
        });
        e3 ? __PRIVATE_registerAppCheck(e3) : (
          // If AppCheck is still not available, proceed without it.
          __PRIVATE_logDebug("FirebaseAppCheckTokenProvider", "AppCheck not yet detected")
        );
      }
    }, 0);
  }
  getToken() {
    if (this.V) return Promise.resolve(new AppCheckToken(this.V));
    const e2 = this.forceRefresh;
    return this.forceRefresh = false, this.appCheck ? this.appCheck.getToken(e2).then((e3) => e3 ? (__PRIVATE_hardAssert("string" == typeof e3.token), this.R = e3.token, new AppCheckToken(e3.token)) : null) : Promise.resolve(null);
  }
  invalidateToken() {
    this.forceRefresh = true;
  }
  shutdown() {
    this.appCheck && this.o && this.appCheck.removeTokenListener(this.o), this.o = void 0;
  }
}
class __PRIVATE_EmptyAppCheckTokenProvider {
  static {
    __name(this, "__PRIVATE_EmptyAppCheckTokenProvider");
  }
  getToken() {
    return Promise.resolve(new AppCheckToken(""));
  }
  invalidateToken() {
  }
  start(e2, t2) {
  }
  shutdown() {
  }
}
/**
 * @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.
 */
function __PRIVATE_randomBytes(e2) {
  const t2 = (
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    "undefined" != typeof self && (self.crypto || self.msCrypto)
  ), n2 = new Uint8Array(e2);
  if (t2 && "function" == typeof t2.getRandomValues) t2.getRandomValues(n2);
  else
    for (let t3 = 0; t3 < e2; t3++) n2[t3] = Math.floor(256 * Math.random());
  return n2;
}
__name(__PRIVATE_randomBytes, "__PRIVATE_randomBytes");
/**
 * @license
 * Copyright 2023 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 __PRIVATE_newTextEncoder() {
  return new TextEncoder();
}
__name(__PRIVATE_newTextEncoder, "__PRIVATE_newTextEncoder");
/**
 * @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 __PRIVATE_AutoId {
  static {
    __name(this, "__PRIVATE_AutoId");
  }
  static newId() {
    const e2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", t2 = 62 * Math.floor(256 / 62);
    let n2 = "";
    for (; n2.length < 20; ) {
      const r2 = __PRIVATE_randomBytes(40);
      for (let i2 = 0; i2 < r2.length; ++i2)
        n2.length < 20 && r2[i2] < t2 && (n2 += e2.charAt(r2[i2] % 62));
    }
    return n2;
  }
}
function __PRIVATE_primitiveComparator(e2, t2) {
  return e2 < t2 ? -1 : e2 > t2 ? 1 : 0;
}
__name(__PRIVATE_primitiveComparator, "__PRIVATE_primitiveComparator");
function __PRIVATE_compareUtf8Strings(e2, t2) {
  let n2 = 0;
  for (; n2 < e2.length && n2 < t2.length; ) {
    const r2 = e2.codePointAt(n2), i2 = t2.codePointAt(n2);
    if (r2 !== i2) {
      if (r2 < 128 && i2 < 128)
        return __PRIVATE_primitiveComparator(r2, i2);
      {
        const s2 = __PRIVATE_newTextEncoder(), o2 = __PRIVATE_compareByteArrays$1(s2.encode(__PRIVATE_getUtf8SafeSubstring(e2, n2)), s2.encode(__PRIVATE_getUtf8SafeSubstring(t2, n2)));
        return 0 !== o2 ? o2 : __PRIVATE_primitiveComparator(r2, i2);
      }
    }
    n2 += r2 > 65535 ? 2 : 1;
  }
  return __PRIVATE_primitiveComparator(e2.length, t2.length);
}
__name(__PRIVATE_compareUtf8Strings, "__PRIVATE_compareUtf8Strings");
function __PRIVATE_getUtf8SafeSubstring(e2, t2) {
  return e2.codePointAt(t2) > 65535 ? e2.substring(t2, t2 + 2) : e2.substring(t2, t2 + 1);
}
__name(__PRIVATE_getUtf8SafeSubstring, "__PRIVATE_getUtf8SafeSubstring");
function __PRIVATE_compareByteArrays$1(e2, t2) {
  for (let n2 = 0; n2 < e2.length && n2 < t2.length; ++n2) if (e2[n2] !== t2[n2]) return __PRIVATE_primitiveComparator(e2[n2], t2[n2]);
  return __PRIVATE_primitiveComparator(e2.length, t2.length);
}
__name(__PRIVATE_compareByteArrays$1, "__PRIVATE_compareByteArrays$1");
function __PRIVATE_arrayEquals(e2, t2, n2) {
  return e2.length === t2.length && e2.every((e3, r2) => n2(e3, t2[r2]));
}
__name(__PRIVATE_arrayEquals, "__PRIVATE_arrayEquals");
function __PRIVATE_immediateSuccessor(e2) {
  return e2 + "\0";
}
__name(__PRIVATE_immediateSuccessor, "__PRIVATE_immediateSuccessor");
/**
 * @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 F = -62135596800, M = 1e6;
class Timestamp {
  static {
    __name(this, "Timestamp");
  }
  /**
   * Creates a new timestamp with the current date, with millisecond precision.
   *
   * @returns a new timestamp representing the current date.
   */
  static now() {
    return Timestamp.fromMillis(Date.now());
  }
  /**
   * Creates a new timestamp from the given date.
   *
   * @param date - The date to initialize the `Timestamp` from.
   * @returns A new `Timestamp` representing the same point in time as the given
   *     date.
   */
  static fromDate(e2) {
    return Timestamp.fromMillis(e2.getTime());
  }
  /**
   * Creates a new timestamp from the given number of milliseconds.
   *
   * @param milliseconds - Number of milliseconds since Unix epoch
   *     1970-01-01T00:00:00Z.
   * @returns A new `Timestamp` representing the same point in time as the given
   *     number of milliseconds.
   */
  static fromMillis(e2) {
    const t2 = Math.floor(e2 / 1e3), n2 = Math.floor((e2 - 1e3 * t2) * M);
    return new Timestamp(t2, n2);
  }
  /**
   * Creates a new timestamp.
   *
   * @param seconds - The number of seconds of UTC time since Unix epoch
   *     1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
   *     9999-12-31T23:59:59Z inclusive.
   * @param nanoseconds - The non-negative fractions of a second at nanosecond
   *     resolution. Negative second values with fractions must still have
   *     non-negative nanoseconds values that count forward in time. Must be
   *     from 0 to 999,999,999 inclusive.
   */
  constructor(e2, t2) {
    if (this.seconds = e2, this.nanoseconds = t2, t2 < 0) throw new FirestoreError(C.INVALID_ARGUMENT, "Timestamp nanoseconds out of range: " + t2);
    if (t2 >= 1e9) throw new FirestoreError(C.INVALID_ARGUMENT, "Timestamp nanoseconds out of range: " + t2);
    if (e2 < F) throw new FirestoreError(C.INVALID_ARGUMENT, "Timestamp seconds out of range: " + e2);
    if (e2 >= 253402300800) throw new FirestoreError(C.INVALID_ARGUMENT, "Timestamp seconds out of range: " + e2);
  }
  /**
   * Converts a `Timestamp` to a JavaScript `Date` object. This conversion
   * causes a loss of precision since `Date` objects only support millisecond
   * precision.
   *
   * @returns JavaScript `Date` object representing the same point in time as
   *     this `Timestamp`, with millisecond precision.
   */
  toDate() {
    return new Date(this.toMillis());
  }
  /**
   * Converts a `Timestamp` to a numeric timestamp (in milliseconds since
   * epoch). This operation causes a loss of precision.
   *
   * @returns The point in time corresponding to this timestamp, represented as
   *     the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.
   */
  toMillis() {
    return 1e3 * this.seconds + this.nanoseconds / M;
  }
  _compareTo(e2) {
    return this.seconds === e2.seconds ? __PRIVATE_primitiveComparator(this.nanoseconds, e2.nanoseconds) : __PRIVATE_primitiveComparator(this.seconds, e2.seconds);
  }
  /**
   * Returns true if this `Timestamp` is equal to the provided one.
   *
   * @param other - The `Timestamp` to compare against.
   * @returns true if this `Timestamp` is equal to the provided one.
   */
  isEqual(e2) {
    return e2.seconds === this.seconds && e2.nanoseconds === this.nanoseconds;
  }
  /** Returns a textual representation of this `Timestamp`. */
  toString() {
    return "Timestamp(seconds=" + this.seconds + ", nanoseconds=" + this.nanoseconds + ")";
  }
  /** Returns a JSON-serializable representation of this `Timestamp`. */
  toJSON() {
    return {
      seconds: this.seconds,
      nanoseconds: this.nanoseconds
    };
  }
  /**
   * Converts this object to a primitive string, which allows `Timestamp` objects
   * to be compared using the `>`, `<=`, `>=` and `>` operators.
   */
  valueOf() {
    const e2 = this.seconds - F;
    return String(e2).padStart(12, "0") + "." + String(this.nanoseconds).padStart(9, "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 SnapshotVersion {
  static {
    __name(this, "SnapshotVersion");
  }
  static fromTimestamp(e2) {
    return new SnapshotVersion(e2);
  }
  static min() {
    return new SnapshotVersion(new Timestamp(0, 0));
  }
  static max() {
    return new SnapshotVersion(new Timestamp(253402300799, 999999999));
  }
  constructor(e2) {
    this.timestamp = e2;
  }
  compareTo(e2) {
    return this.timestamp._compareTo(e2.timestamp);
  }
  isEqual(e2) {
    return this.timestamp.isEqual(e2.timestamp);
  }
  /** Returns a number representation of the version for use in spec tests. */
  toMicroseconds() {
    return 1e6 * this.timestamp.seconds + this.timestamp.nanoseconds / 1e3;
  }
  toString() {
    return "SnapshotVersion(" + this.timestamp.toString() + ")";
  }
  toTimestamp() {
    return this.timestamp;
  }
}
/**
 * @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 x = "__name__";
class BasePath {
  static {
    __name(this, "BasePath");
  }
  constructor(e2, t2, n2) {
    void 0 === t2 ? t2 = 0 : t2 > e2.length && fail(), void 0 === n2 ? n2 = e2.length - t2 : n2 > e2.length - t2 && fail(), this.segments = e2, this.offset = t2, this.len = n2;
  }
  get length() {
    return this.len;
  }
  isEqual(e2) {
    return 0 === BasePath.comparator(this, e2);
  }
  child(e2) {
    const t2 = this.segments.slice(this.offset, this.limit());
    return e2 instanceof BasePath ? e2.forEach((e3) => {
      t2.push(e3);
    }) : t2.push(e2), this.construct(t2);
  }
  /** The index of one past the last segment of the path. */
  limit() {
    return this.offset + this.length;
  }
  popFirst(e2) {
    return e2 = void 0 === e2 ? 1 : e2, this.construct(this.segments, this.offset + e2, this.length - e2);
  }
  popLast() {
    return this.construct(this.segments, this.offset, this.length - 1);
  }
  firstSegment() {
    return this.segments[this.offset];
  }
  lastSegment() {
    return this.get(this.length - 1);
  }
  get(e2) {
    return this.segments[this.offset + e2];
  }
  isEmpty() {
    return 0 === this.length;
  }
  isPrefixOf(e2) {
    if (e2.length < this.length) return false;
    for (let t2 = 0; t2 < this.length; t2++) if (this.get(t2) !== e2.get(t2)) return false;
    return true;
  }
  isImmediateParentOf(e2) {
    if (this.length + 1 !== e2.length) return false;
    for (let t2 = 0; t2 < this.length; t2++) if (this.get(t2) !== e2.get(t2)) return false;
    return true;
  }
  forEach(e2) {
    for (let t2 = this.offset, n2 = this.limit(); t2 < n2; t2++) e2(this.segments[t2]);
  }
  toArray() {
    return this.segments.slice(this.offset, this.limit());
  }
  /**
   * Compare 2 paths segment by segment, prioritizing numeric IDs
   * (e.g., "__id123__") in numeric ascending order, followed by string
   * segments in lexicographical order.
   */
  static comparator(e2, t2) {
    const n2 = Math.min(e2.length, t2.length);
    for (let r2 = 0; r2 < n2; r2++) {
      const n3 = BasePath.compareSegments(e2.get(r2), t2.get(r2));
      if (0 !== n3) return n3;
    }
    return __PRIVATE_primitiveComparator(e2.length, t2.length);
  }
  static compareSegments(e2, t2) {
    const n2 = BasePath.isNumericId(e2), r2 = BasePath.isNumericId(t2);
    return n2 && !r2 ? -1 : !n2 && r2 ? 1 : n2 && r2 ? BasePath.extractNumericId(e2).compare(BasePath.extractNumericId(t2)) : __PRIVATE_compareUtf8Strings(e2, t2);
  }
  // Checks if a segment is a numeric ID (starts with "__id" and ends with "__").
  static isNumericId(e2) {
    return e2.startsWith("__id") && e2.endsWith("__");
  }
  static extractNumericId(e2) {
    return Integer.fromString(e2.substring(4, e2.length - 2));
  }
}
class ResourcePath extends BasePath {
  static {
    __name(this, "ResourcePath");
  }
  construct(e2, t2, n2) {
    return new ResourcePath(e2, t2, n2);
  }
  canonicalString() {
    return this.toArray().join("/");
  }
  toString() {
    return this.canonicalString();
  }
  /**
   * Returns a string representation of this path
   * where each path segment has been encoded with
   * `encodeURIComponent`.
   */
  toUriEncodedString() {
    return this.toArray().map(encodeURIComponent).join("/");
  }
  /**
   * Creates a resource path from the given slash-delimited string. If multiple
   * arguments are provided, all components are combined. Leading and trailing
   * slashes from all components are ignored.
   */
  static fromString(...e2) {
    const t2 = [];
    for (const n2 of e2) {
      if (n2.indexOf("//") >= 0) throw new FirestoreError(C.INVALID_ARGUMENT, `Invalid segment (${n2}). Paths must not contain // in them.`);
      t2.push(...n2.split("/").filter((e3) => e3.length > 0));
    }
    return new ResourcePath(t2);
  }
  static emptyPath() {
    return new ResourcePath([]);
  }
}
const O = /^[_a-zA-Z][_a-zA-Z0-9]*$/;
class FieldPath$1 extends BasePath {
  static {
    __name(this, "FieldPath$1");
  }
  construct(e2, t2, n2) {
    return new FieldPath$1(e2, t2, n2);
  }
  /**
   * Returns true if the string could be used as a segment in a field path
   * without escaping.
   */
  static isValidIdentifier(e2) {
    return O.test(e2);
  }
  canonicalString() {
    return this.toArray().map((e2) => (e2 = e2.replace(/\\/g, "\\\\").replace(/`/g, "\\`"), FieldPath$1.isValidIdentifier(e2) || (e2 = "`" + e2 + "`"), e2)).join(".");
  }
  toString() {
    return this.canonicalString();
  }
  /**
   * Returns true if this field references the key of a document.
   */
  isKeyField() {
    return 1 === this.length && this.get(0) === x;
  }
  /**
   * The field designating the key of a document.
   */
  static keyField() {
    return new FieldPath$1([x]);
  }
  /**
   * Parses a field string from the given server-formatted string.
   *
   * - Splitting the empty string is not allowed (for now at least).
   * - Empty segments within the string (e.g. if there are two consecutive
   *   separators) are not allowed.
   *
   * TODO(b/37244157): we should make this more strict. Right now, it allows
   * non-identifier path components, even if they aren't escaped.
   */
  static fromServerFormat(e2) {
    const t2 = [];
    let n2 = "", r2 = 0;
    const __PRIVATE_addCurrentSegment = /* @__PURE__ */ __name(() => {
      if (0 === n2.length) throw new FirestoreError(C.INVALID_ARGUMENT, `Invalid field path (${e2}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);
      t2.push(n2), n2 = "";
    }, "__PRIVATE_addCurrentSegment");
    let i2 = false;
    for (; r2 < e2.length; ) {
      const t3 = e2[r2];
      if ("\\" === t3) {
        if (r2 + 1 === e2.length) throw new FirestoreError(C.INVALID_ARGUMENT, "Path has trailing escape character: " + e2);
        const t4 = e2[r2 + 1];
        if ("\\" !== t4 && "." !== t4 && "`" !== t4) throw new FirestoreError(C.INVALID_ARGUMENT, "Path has invalid escape sequence: " + e2);
        n2 += t4, r2 += 2;
      } else "`" === t3 ? (i2 = !i2, r2++) : "." !== t3 || i2 ? (n2 += t3, r2++) : (__PRIVATE_addCurrentSegment(), r2++);
    }
    if (__PRIVATE_addCurrentSegment(), i2) throw new FirestoreError(C.INVALID_ARGUMENT, "Unterminated ` in path: " + e2);
    return new FieldPath$1(t2);
  }
  static emptyPath() {
    return new FieldPath$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.
 */
class DocumentKey {
  static {
    __name(this, "DocumentKey");
  }
  constructor(e2) {
    this.path = e2;
  }
  static fromPath(e2) {
    return new DocumentKey(ResourcePath.fromString(e2));
  }
  static fromName(e2) {
    return new DocumentKey(ResourcePath.fromString(e2).popFirst(5));
  }
  static empty() {
    return new DocumentKey(ResourcePath.emptyPath());
  }
  get collectionGroup() {
    return this.path.popLast().lastSegment();
  }
  /** Returns true if the document is in the specified collectionId. */
  hasCollectionId(e2) {
    return this.path.length >= 2 && this.path.get(this.path.length - 2) === e2;
  }
  /** Returns the collection group (i.e. the name of the parent collection) for this key. */
  getCollectionGroup() {
    return this.path.get(this.path.length - 2);
  }
  /** Returns the fully qualified path to the parent collection. */
  getCollectionPath() {
    return this.path.popLast();
  }
  isEqual(e2) {
    return null !== e2 && 0 === ResourcePath.comparator(this.path, e2.path);
  }
  toString() {
    return this.path.toString();
  }
  static comparator(e2, t2) {
    return ResourcePath.comparator(e2.path, t2.path);
  }
  static isDocumentKey(e2) {
    return e2.length % 2 == 0;
  }
  /**
   * Creates and returns a new document key with the given segments.
   *
   * @param segments - The segments of the path to the document
   * @returns A new instance of DocumentKey
   */
  static fromSegments(e2) {
    return new DocumentKey(new ResourcePath(e2.slice()));
  }
}
/**
 * @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 N = -1;
class FieldIndex {
  static {
    __name(this, "FieldIndex");
  }
  constructor(e2, t2, n2, r2) {
    this.indexId = e2, this.collectionGroup = t2, this.fields = n2, this.indexState = r2;
  }
}
function __PRIVATE_fieldIndexGetArraySegment(e2) {
  return e2.fields.find((e3) => 2 === e3.kind);
}
__name(__PRIVATE_fieldIndexGetArraySegment, "__PRIVATE_fieldIndexGetArraySegment");
function __PRIVATE_fieldIndexGetDirectionalSegments(e2) {
  return e2.fields.filter((e3) => 2 !== e3.kind);
}
__name(__PRIVATE_fieldIndexGetDirectionalSegments, "__PRIVATE_fieldIndexGetDirectionalSegments");
function __PRIVATE_fieldIndexSemanticComparator(e2, t2) {
  let n2 = __PRIVATE_primitiveComparator(e2.collectionGroup, t2.collectionGroup);
  if (0 !== n2) return n2;
  for (let r2 = 0; r2 < Math.min(e2.fields.length, t2.fields.length); ++r2) if (n2 = __PRIVATE_indexSegmentComparator(e2.fields[r2], t2.fields[r2]), 0 !== n2) return n2;
  return __PRIVATE_primitiveComparator(e2.fields.length, t2.fields.length);
}
__name(__PRIVATE_fieldIndexSemanticComparator, "__PRIVATE_fieldIndexSemanticComparator");
FieldIndex.UNKNOWN_ID = -1;
class IndexSegment {
  static {
    __name(this, "IndexSegment");
  }
  constructor(e2, t2) {
    this.fieldPath = e2, this.kind = t2;
  }
}
function __PRIVATE_indexSegmentComparator(e2, t2) {
  const n2 = FieldPath$1.comparator(e2.fieldPath, t2.fieldPath);
  return 0 !== n2 ? n2 : __PRIVATE_primitiveComparator(e2.kind, t2.kind);
}
__name(__PRIVATE_indexSegmentComparator, "__PRIVATE_indexSegmentComparator");
class IndexState {
  static {
    __name(this, "IndexState");
  }
  constructor(e2, t2) {
    this.sequenceNumber = e2, this.offset = t2;
  }
  /** The state of an index that has not yet been backfilled. */
  static empty() {
    return new IndexState(0, IndexOffset.min());
  }
}
function __PRIVATE_newIndexOffsetSuccessorFromReadTime(e2, t2) {
  const n2 = e2.toTimestamp().seconds, r2 = e2.toTimestamp().nanoseconds + 1, i2 = SnapshotVersion.fromTimestamp(1e9 === r2 ? new Timestamp(n2 + 1, 0) : new Timestamp(n2, r2));
  return new IndexOffset(i2, DocumentKey.empty(), t2);
}
__name(__PRIVATE_newIndexOffsetSuccessorFromReadTime, "__PRIVATE_newIndexOffsetSuccessorFromReadTime");
function __PRIVATE_newIndexOffsetFromDocument(e2) {
  return new IndexOffset(e2.readTime, e2.key, N);
}
__name(__PRIVATE_newIndexOffsetFromDocument, "__PRIVATE_newIndexOffsetFromDocument");
class IndexOffset {
  static {
    __name(this, "IndexOffset");
  }
  constructor(e2, t2, n2) {
    this.readTime = e2, this.documentKey = t2, this.largestBatchId = n2;
  }
  /** Returns an offset that sorts before all regular offsets. */
  static min() {
    return new IndexOffset(SnapshotVersion.min(), DocumentKey.empty(), N);
  }
  /** Returns an offset that sorts after all regular offsets. */
  static max() {
    return new IndexOffset(SnapshotVersion.max(), DocumentKey.empty(), N);
  }
}
function __PRIVATE_indexOffsetComparator(e2, t2) {
  let n2 = e2.readTime.compareTo(t2.readTime);
  return 0 !== n2 ? n2 : (n2 = DocumentKey.comparator(e2.documentKey, t2.documentKey), 0 !== n2 ? n2 : __PRIVATE_primitiveComparator(e2.largestBatchId, t2.largestBatchId));
}
__name(__PRIVATE_indexOffsetComparator, "__PRIVATE_indexOffsetComparator");
/**
 * @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 B = "The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";
class PersistenceTransaction {
  static {
    __name(this, "PersistenceTransaction");
  }
  constructor() {
    this.onCommittedListeners = [];
  }
  addOnCommittedListener(e2) {
    this.onCommittedListeners.push(e2);
  }
  raiseOnCommittedEvent() {
    this.onCommittedListeners.forEach((e2) => e2());
  }
}
/**
 * @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.
 */
async function __PRIVATE_ignoreIfPrimaryLeaseLoss(e2) {
  if (e2.code !== C.FAILED_PRECONDITION || e2.message !== B) throw e2;
  __PRIVATE_logDebug("LocalStore", "Unexpectedly lost primary lease");
}
__name(__PRIVATE_ignoreIfPrimaryLeaseLoss, "__PRIVATE_ignoreIfPrimaryLeaseLoss");
/**
 * @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 PersistencePromise {
  static {
    __name(this, "PersistencePromise");
  }
  constructor(e2) {
    this.nextCallback = null, this.catchCallback = null, // When the operation resolves, we'll set result or error and mark isDone.
    this.result = void 0, this.error = void 0, this.isDone = false, // Set to true when .then() or .catch() are called and prevents additional
    // chaining.
    this.callbackAttached = false, e2((e3) => {
      this.isDone = true, this.result = e3, this.nextCallback && // value should be defined unless T is Void, but we can't express
      // that in the type system.
      this.nextCallback(e3);
    }, (e3) => {
      this.isDone = true, this.error = e3, this.catchCallback && this.catchCallback(e3);
    });
  }
  catch(e2) {
    return this.next(void 0, e2);
  }
  next(e2, t2) {
    return this.callbackAttached && fail(), this.callbackAttached = true, this.isDone ? this.error ? this.wrapFailure(t2, this.error) : this.wrapSuccess(e2, this.result) : new PersistencePromise((n2, r2) => {
      this.nextCallback = (t3) => {
        this.wrapSuccess(e2, t3).next(n2, r2);
      }, this.catchCallback = (e3) => {
        this.wrapFailure(t2, e3).next(n2, r2);
      };
    });
  }
  toPromise() {
    return new Promise((e2, t2) => {
      this.next(e2, t2);
    });
  }
  wrapUserFunction(e2) {
    try {
      const t2 = e2();
      return t2 instanceof PersistencePromise ? t2 : PersistencePromise.resolve(t2);
    } catch (e3) {
      return PersistencePromise.reject(e3);
    }
  }
  wrapSuccess(e2, t2) {
    return e2 ? this.wrapUserFunction(() => e2(t2)) : PersistencePromise.resolve(t2);
  }
  wrapFailure(e2, t2) {
    return e2 ? this.wrapUserFunction(() => e2(t2)) : PersistencePromise.reject(t2);
  }
  static resolve(e2) {
    return new PersistencePromise((t2, n2) => {
      t2(e2);
    });
  }
  static reject(e2) {
    return new PersistencePromise((t2, n2) => {
      n2(e2);
    });
  }
  static waitFor(e2) {
    return new PersistencePromise((t2, n2) => {
      let r2 = 0, i2 = 0, s2 = false;
      e2.forEach((e3) => {
        ++r2, e3.next(() => {
          ++i2, s2 && i2 === r2 && t2();
        }, (e4) => n2(e4));
      }), s2 = true, i2 === r2 && t2();
    });
  }
  /**
   * Given an array of predicate functions that asynchronously evaluate to a
   * boolean, implements a short-circuiting `or` between the results. Predicates
   * will be evaluated until one of them returns `true`, then stop. The final
   * result will be whether any of them returned `true`.
   */
  static or(e2) {
    let t2 = PersistencePromise.resolve(false);
    for (const n2 of e2) t2 = t2.next((e3) => e3 ? PersistencePromise.resolve(e3) : n2());
    return t2;
  }
  static forEach(e2, t2) {
    const n2 = [];
    return e2.forEach((e3, r2) => {
      n2.push(t2.call(this, e3, r2));
    }), this.waitFor(n2);
  }
  /**
   * Concurrently map all array elements through asynchronous function.
   */
  static mapArray(e2, t2) {
    return new PersistencePromise((n2, r2) => {
      const i2 = e2.length, s2 = new Array(i2);
      let o2 = 0;
      for (let _2 = 0; _2 < i2; _2++) {
        const a2 = _2;
        t2(e2[a2]).next((e3) => {
          s2[a2] = e3, ++o2, o2 === i2 && n2(s2);
        }, (e3) => r2(e3));
      }
    });
  }
  /**
   * An alternative to recursive PersistencePromise calls, that avoids
   * potential memory problems from unbounded chains of promises.
   *
   * The `action` will be called repeatedly while `condition` is true.
   */
  static doWhile(e2, t2) {
    return new PersistencePromise((n2, r2) => {
      const process2 = /* @__PURE__ */ __name(() => {
        true === e2() ? t2().next(() => {
          process2();
        }, r2) : n2();
      }, "process");
      process2();
    });
  }
}
/**
 * @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 L = "SimpleDb";
class __PRIVATE_SimpleDbTransaction {
  static {
    __name(this, "__PRIVATE_SimpleDbTransaction");
  }
  static open(e2, t2, n2, r2) {
    try {
      return new __PRIVATE_SimpleDbTransaction(t2, e2.transaction(r2, n2));
    } catch (e3) {
      throw new __PRIVATE_IndexedDbTransactionError(t2, e3);
    }
  }
  constructor(e2, t2) {
    this.action = e2, this.transaction = t2, this.aborted = false, /**
     * A `Promise` that resolves with the result of the IndexedDb transaction.
     */
    this.m = new __PRIVATE_Deferred(), this.transaction.oncomplete = () => {
      this.m.resolve();
    }, this.transaction.onabort = () => {
      t2.error ? this.m.reject(new __PRIVATE_IndexedDbTransactionError(e2, t2.error)) : this.m.resolve();
    }, this.transaction.onerror = (t3) => {
      const n2 = __PRIVATE_checkForAndReportiOSError(t3.target.error);
      this.m.reject(new __PRIVATE_IndexedDbTransactionError(e2, n2));
    };
  }
  get p() {
    return this.m.promise;
  }
  abort(e2) {
    e2 && this.m.reject(e2), this.aborted || (__PRIVATE_logDebug(L, "Aborting transaction:", e2 ? e2.message : "Client-initiated abort"), this.aborted = true, this.transaction.abort());
  }
  S() {
    const e2 = this.transaction;
    this.aborted || "function" != typeof e2.commit || e2.commit();
  }
  /**
   * Returns a SimpleDbStore<KeyType, ValueType> for the specified store. All
   * operations performed on the SimpleDbStore happen within the context of this
   * transaction and it cannot be used anymore once the transaction is
   * completed.
   *
   * Note that we can't actually enforce that the KeyType and ValueType are
   * correct, but they allow type safety through the rest of the consuming code.
   */
  store(e2) {
    const t2 = this.transaction.objectStore(e2);
    return new __PRIVATE_SimpleDbStore(t2);
  }
}
class __PRIVATE_SimpleDb {
  static {
    __name(this, "__PRIVATE_SimpleDb");
  }
  /** Deletes the specified database. */
  static delete(e2) {
    return __PRIVATE_logDebug(L, "Removing database:", e2), __PRIVATE_wrapRequest(window.indexedDB.deleteDatabase(e2)).toPromise();
  }
  /** Returns true if IndexedDB is available in the current environment. */
  static D() {
    if (!isIndexedDBAvailable()) return false;
    if (__PRIVATE_SimpleDb.v()) return true;
    const e2 = getUA(), t2 = __PRIVATE_SimpleDb.C(e2), n2 = 0 < t2 && t2 < 10, r2 = __PRIVATE_getAndroidVersion(e2), i2 = 0 < r2 && r2 < 4.5;
    return !(e2.indexOf("MSIE ") > 0 || e2.indexOf("Trident/") > 0 || e2.indexOf("Edge/") > 0 || n2 || i2);
  }
  /**
   * Returns true if the backing IndexedDB store is the Node IndexedDBShim
   * (see https://github.com/axemclion/IndexedDBShim).
   */
  static v() {
    var e2;
    return "undefined" != typeof process && "YES" === (null === (e2 = process.__PRIVATE_env) || void 0 === e2 ? void 0 : e2.F);
  }
  /** Helper to get a typed SimpleDbStore from a transaction. */
  static M(e2, t2) {
    return e2.store(t2);
  }
  // visible for testing
  /** Parse User Agent to determine iOS version. Returns -1 if not found. */
  static C(e2) {
    const t2 = e2.match(/i(?:phone|pad|pod) os ([\d_]+)/i), n2 = t2 ? t2[1].split("_").slice(0, 2).join(".") : "-1";
    return Number(n2);
  }
  /*
   * Creates a new SimpleDb wrapper for IndexedDb database `name`.
   *
   * Note that `version` must not be a downgrade. IndexedDB does not support
   * downgrading the schema version. We currently do not support any way to do
   * versioning outside of IndexedDB's versioning mechanism, as only
   * version-upgrade transactions are allowed to do things like create
   * objectstores.
   */
  constructor(e2, t2, n2) {
    this.name = e2, this.version = t2, this.O = n2;
    12.2 === __PRIVATE_SimpleDb.C(getUA()) && __PRIVATE_logError("Firestore persistence suffers from a bug in iOS 12.2 Safari that may cause your app to stop working. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.");
  }
  /**
   * Opens the specified database, creating or upgrading it if necessary.
   */
  async N(e2) {
    return this.db || (__PRIVATE_logDebug(L, "Opening database:", this.name), this.db = await new Promise((t2, n2) => {
      const r2 = indexedDB.open(this.name, this.version);
      r2.onsuccess = (e3) => {
        const n3 = e3.target.result;
        t2(n3);
      }, r2.onblocked = () => {
        n2(new __PRIVATE_IndexedDbTransactionError(e2, "Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed."));
      }, r2.onerror = (t3) => {
        const r3 = t3.target.error;
        "VersionError" === r3.name ? n2(new FirestoreError(C.FAILED_PRECONDITION, "A newer version of the Firestore SDK was previously used and so the persisted data is not compatible with the version of the SDK you are now using. The SDK will operate with persistence disabled. If you need persistence, please re-upgrade to a newer version of the SDK or else clear the persisted IndexedDB data for your app to start fresh.")) : "InvalidStateError" === r3.name ? n2(new FirestoreError(C.FAILED_PRECONDITION, "Unable to open an IndexedDB connection. This could be due to running in a private browsing session on a browser whose private browsing sessions do not support IndexedDB: " + r3)) : n2(new __PRIVATE_IndexedDbTransactionError(e2, r3));
      }, r2.onupgradeneeded = (e3) => {
        __PRIVATE_logDebug(L, 'Database "' + this.name + '" requires upgrade from version:', e3.oldVersion);
        const t3 = e3.target.result;
        this.O.B(t3, r2.transaction, e3.oldVersion, this.version).next(() => {
          __PRIVATE_logDebug(L, "Database upgrade to version " + this.version + " complete");
        });
      };
    })), this.L && (this.db.onversionchange = (e3) => this.L(e3)), this.db;
  }
  k(e2) {
    this.L = e2, this.db && (this.db.onversionchange = (t2) => e2(t2));
  }
  async runTransaction(e2, t2, n2, r2) {
    const i2 = "readonly" === t2;
    let s2 = 0;
    for (; ; ) {
      ++s2;
      try {
        this.db = await this.N(e2);
        const t3 = __PRIVATE_SimpleDbTransaction.open(this.db, e2, i2 ? "readonly" : "readwrite", n2), s3 = r2(t3).next((e3) => (t3.S(), e3)).catch((e3) => (
          // Abort the transaction if there was an error.
          (t3.abort(e3), PersistencePromise.reject(e3))
        )).toPromise();
        return s3.catch(() => {
        }), // Wait for the transaction to complete (i.e. IndexedDb's onsuccess event to
        // fire), but still return the original transactionFnResult back to the
        // caller.
        await t3.p, s3;
      } catch (e3) {
        const t3 = e3, n3 = "FirebaseError" !== t3.name && s2 < 3;
        if (__PRIVATE_logDebug(L, "Transaction failed with error:", t3.message, "Retrying:", n3), this.close(), !n3) return Promise.reject(t3);
      }
    }
  }
  close() {
    this.db && this.db.close(), this.db = void 0;
  }
}
function __PRIVATE_getAndroidVersion(e2) {
  const t2 = e2.match(/Android ([\d.]+)/i), n2 = t2 ? t2[1].split(".").slice(0, 2).join(".") : "-1";
  return Number(n2);
}
__name(__PRIVATE_getAndroidVersion, "__PRIVATE_getAndroidVersion");
class __PRIVATE_IterationController {
  static {
    __name(this, "__PRIVATE_IterationController");
  }
  constructor(e2) {
    this.q = e2, this.$ = false, this.U = null;
  }
  get isDone() {
    return this.$;
  }
  get K() {
    return this.U;
  }
  set cursor(e2) {
    this.q = e2;
  }
  /**
   * This function can be called to stop iteration at any point.
   */
  done() {
    this.$ = true;
  }
  /**
   * This function can be called to skip to that next key, which could be
   * an index or a primary key.
   */
  W(e2) {
    this.U = e2;
  }
  /**
   * Delete the current cursor value from the object store.
   *
   * NOTE: You CANNOT do this with a keysOnly query.
   */
  delete() {
    return __PRIVATE_wrapRequest(this.q.delete());
  }
}
class __PRIVATE_IndexedDbTransactionError extends FirestoreError {
  static {
    __name(this, "__PRIVATE_IndexedDbTransactionError");
  }
  constructor(e2, t2) {
    super(C.UNAVAILABLE, `IndexedDB transaction '${e2}' failed: ${t2}`), this.name = "IndexedDbTransactionError";
  }
}
function __PRIVATE_isIndexedDbTransactionError(e2) {
  return "IndexedDbTransactionError" === e2.name;
}
__name(__PRIVATE_isIndexedDbTransactionError, "__PRIVATE_isIndexedDbTransactionError");
class __PRIVATE_SimpleDbStore {
  static {
    __name(this, "__PRIVATE_SimpleDbStore");
  }
  constructor(e2) {
    this.store = e2;
  }
  put(e2, t2) {
    let n2;
    return void 0 !== t2 ? (__PRIVATE_logDebug(L, "PUT", this.store.name, e2, t2), n2 = this.store.put(t2, e2)) : (__PRIVATE_logDebug(L, "PUT", this.store.name, "<auto-key>", e2), n2 = this.store.put(e2)), __PRIVATE_wrapRequest(n2);
  }
  /**
   * Adds a new value into an Object Store and returns the new key. Similar to
   * IndexedDb's `add()`, this method will fail on primary key collisions.
   *
   * @param value - The object to write.
   * @returns The key of the value to add.
   */
  add(e2) {
    __PRIVATE_logDebug(L, "ADD", this.store.name, e2, e2);
    return __PRIVATE_wrapRequest(this.store.add(e2));
  }
  /**
   * Gets the object with the specified key from the specified store, or null
   * if no object exists with the specified key.
   *
   * @key The key of the object to get.
   * @returns The object with the specified key or null if no object exists.
   */
  get(e2) {
    return __PRIVATE_wrapRequest(this.store.get(e2)).next((t2) => (
      // Normalize nonexistence to null.
      (void 0 === t2 && (t2 = null), __PRIVATE_logDebug(L, "GET", this.store.name, e2, t2), t2)
    ));
  }
  delete(e2) {
    __PRIVATE_logDebug(L, "DELETE", this.store.name, e2);
    return __PRIVATE_wrapRequest(this.store.delete(e2));
  }
  /**
   * If we ever need more of the count variants, we can add overloads. For now,
   * all we need is to count everything in a store.
   *
   * Returns the number of rows in the store.
   */
  count() {
    __PRIVATE_logDebug(L, "COUNT", this.store.name);
    return __PRIVATE_wrapRequest(this.store.count());
  }
  G(e2, t2) {
    const n2 = this.options(e2, t2), r2 = n2.index ? this.store.index(n2.index) : this.store;
    if ("function" == typeof r2.getAll) {
      const e3 = r2.getAll(n2.range);
      return new PersistencePromise((t3, n3) => {
        e3.onerror = (e4) => {
          n3(e4.target.error);
        }, e3.onsuccess = (e4) => {
          t3(e4.target.result);
        };
      });
    }
    {
      const e3 = this.cursor(n2), t3 = [];
      return this.j(e3, (e4, n3) => {
        t3.push(n3);
      }).next(() => t3);
    }
  }
  /**
   * Loads the first `count` elements from the provided index range. Loads all
   * elements if no limit is provided.
   */
  H(e2, t2) {
    const n2 = this.store.getAll(e2, null === t2 ? void 0 : t2);
    return new PersistencePromise((e3, t3) => {
      n2.onerror = (e4) => {
        t3(e4.target.error);
      }, n2.onsuccess = (t4) => {
        e3(t4.target.result);
      };
    });
  }
  J(e2, t2) {
    __PRIVATE_logDebug(L, "DELETE ALL", this.store.name);
    const n2 = this.options(e2, t2);
    n2.Y = false;
    const r2 = this.cursor(n2);
    return this.j(r2, (e3, t3, n3) => n3.delete());
  }
  Z(e2, t2) {
    let n2;
    t2 ? n2 = e2 : (n2 = {}, t2 = e2);
    const r2 = this.cursor(n2);
    return this.j(r2, t2);
  }
  /**
   * Iterates over a store, but waits for the given callback to complete for
   * each entry before iterating the next entry. This allows the callback to do
   * asynchronous work to determine if this iteration should continue.
   *
   * The provided callback should return `true` to continue iteration, and
   * `false` otherwise.
   */
  X(e2) {
    const t2 = this.cursor({});
    return new PersistencePromise((n2, r2) => {
      t2.onerror = (e3) => {
        const t3 = __PRIVATE_checkForAndReportiOSError(e3.target.error);
        r2(t3);
      }, t2.onsuccess = (t3) => {
        const r3 = t3.target.result;
        r3 ? e2(r3.primaryKey, r3.value).next((e3) => {
          e3 ? r3.continue() : n2();
        }) : n2();
      };
    });
  }
  j(e2, t2) {
    const n2 = [];
    return new PersistencePromise((r2, i2) => {
      e2.onerror = (e3) => {
        i2(e3.target.error);
      }, e2.onsuccess = (e3) => {
        const i3 = e3.target.result;
        if (!i3) return void r2();
        const s2 = new __PRIVATE_IterationController(i3), o2 = t2(i3.primaryKey, i3.value, s2);
        if (o2 instanceof PersistencePromise) {
          const e4 = o2.catch((e5) => (s2.done(), PersistencePromise.reject(e5)));
          n2.push(e4);
        }
        s2.isDone ? r2() : null === s2.K ? i3.continue() : i3.continue(s2.K);
      };
    }).next(() => PersistencePromise.waitFor(n2));
  }
  options(e2, t2) {
    let n2;
    return void 0 !== e2 && ("string" == typeof e2 ? n2 = e2 : t2 = e2), {
      index: n2,
      range: t2
    };
  }
  cursor(e2) {
    let t2 = "next";
    if (e2.reverse && (t2 = "prev"), e2.index) {
      const n2 = this.store.index(e2.index);
      return e2.Y ? n2.openKeyCursor(e2.range, t2) : n2.openCursor(e2.range, t2);
    }
    return this.store.openCursor(e2.range, t2);
  }
}
function __PRIVATE_wrapRequest(e2) {
  return new PersistencePromise((t2, n2) => {
    e2.onsuccess = (e3) => {
      const n3 = e3.target.result;
      t2(n3);
    }, e2.onerror = (e3) => {
      const t3 = __PRIVATE_checkForAndReportiOSError(e3.target.error);
      n2(t3);
    };
  });
}
__name(__PRIVATE_wrapRequest, "__PRIVATE_wrapRequest");
let k = false;
function __PRIVATE_checkForAndReportiOSError(e2) {
  const t2 = __PRIVATE_SimpleDb.C(getUA());
  if (t2 >= 12.2 && t2 < 13) {
    const t3 = "An internal error was encountered in the Indexed Database server";
    if (e2.message.indexOf(t3) >= 0) {
      const e3 = new FirestoreError("internal", `IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${t3}'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.`);
      return k || (k = true, // Throw a global exception outside of this promise chain, for the user to
      // potentially catch.
      setTimeout(() => {
        throw e3;
      }, 0)), e3;
    }
  }
  return e2;
}
__name(__PRIVATE_checkForAndReportiOSError, "__PRIVATE_checkForAndReportiOSError");
const q = "IndexBackfiller";
class __PRIVATE_IndexBackfillerScheduler {
  static {
    __name(this, "__PRIVATE_IndexBackfillerScheduler");
  }
  constructor(e2, t2) {
    this.asyncQueue = e2, this.ee = t2, this.task = null;
  }
  start() {
    this.te(15e3);
  }
  stop() {
    this.task && (this.task.cancel(), this.task = null);
  }
  get started() {
    return null !== this.task;
  }
  te(e2) {
    __PRIVATE_logDebug(q, `Scheduled in ${e2}ms`), this.task = this.asyncQueue.enqueueAfterDelay("index_backfill", e2, async () => {
      this.task = null;
      try {
        const e3 = await this.ee.ne();
        __PRIVATE_logDebug(q, `Documents written: ${e3}`);
      } catch (e3) {
        __PRIVATE_isIndexedDbTransactionError(e3) ? __PRIVATE_logDebug(q, "Ignoring IndexedDB error during index backfill: ", e3) : await __PRIVATE_ignoreIfPrimaryLeaseLoss(e3);
      }
      await this.te(6e4);
    });
  }
}
class __PRIVATE_IndexBackfiller {
  static {
    __name(this, "__PRIVATE_IndexBackfiller");
  }
  constructor(e2, t2) {
    this.localStore = e2, this.persistence = t2;
  }
  async ne(e2 = 50) {
    return this.persistence.runTransaction("Backfill Indexes", "readwrite-primary", (t2) => this.re(t2, e2));
  }
  /** Writes index entries until the cap is reached. Returns the number of documents processed. */
  re(e2, t2) {
    const n2 = /* @__PURE__ */ new Set();
    let r2 = t2, i2 = true;
    return PersistencePromise.doWhile(() => true === i2 && r2 > 0, () => this.localStore.indexManager.getNextCollectionGroupToUpdate(e2).next((t3) => {
      if (null !== t3 && !n2.has(t3)) return __PRIVATE_logDebug(q, `Processing collection: ${t3}`), this.ie(e2, t3, r2).next((e3) => {
        r2 -= e3, n2.add(t3);
      });
      i2 = false;
    })).next(() => t2 - r2);
  }
  /**
   * Writes entries for the provided collection group. Returns the number of documents processed.
   */
  ie(e2, t2, n2) {
    return this.localStore.indexManager.getMinOffsetFromCollectionGroup(e2, t2).next((r2) => this.localStore.localDocuments.getNextDocuments(e2, t2, r2, n2).next((n3) => {
      const i2 = n3.changes;
      return this.localStore.indexManager.updateIndexEntries(e2, i2).next(() => this.se(r2, n3)).next((n4) => (__PRIVATE_logDebug(q, `Updating offset: ${n4}`), this.localStore.indexManager.updateCollectionGroup(e2, t2, n4))).next(() => i2.size);
    }));
  }
  /** Returns the next offset based on the provided documents. */
  se(e2, t2) {
    let n2 = e2;
    return t2.changes.forEach((e3, t3) => {
      const r2 = __PRIVATE_newIndexOffsetFromDocument(t3);
      __PRIVATE_indexOffsetComparator(r2, n2) > 0 && (n2 = r2);
    }), new IndexOffset(n2.readTime, n2.documentKey, Math.max(t2.batchId, e2.largestBatchId));
  }
}
/**
 * @license
 * Copyright 2018 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 __PRIVATE_ListenSequence {
  static {
    __name(this, "__PRIVATE_ListenSequence");
  }
  constructor(e2, t2) {
    this.previousValue = e2, t2 && (t2.sequenceNumberHandler = (e3) => this.oe(e3), this._e = (e3) => t2.writeSequenceNumber(e3));
  }
  oe(e2) {
    return this.previousValue = Math.max(e2, this.previousValue), this.previousValue;
  }
  next() {
    const e2 = ++this.previousValue;
    return this._e && this._e(e2), e2;
  }
}
__PRIVATE_ListenSequence.ae = -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 Q = -1;
function __PRIVATE_isNullOrUndefined(e2) {
  return null == e2;
}
__name(__PRIVATE_isNullOrUndefined, "__PRIVATE_isNullOrUndefined");
function __PRIVATE_isNegativeZero(e2) {
  return 0 === e2 && 1 / e2 == -1 / 0;
}
__name(__PRIVATE_isNegativeZero, "__PRIVATE_isNegativeZero");
function isSafeInteger(e2) {
  return "number" == typeof e2 && Number.isInteger(e2) && !__PRIVATE_isNegativeZero(e2) && e2 <= Number.MAX_SAFE_INTEGER && e2 >= Number.MIN_SAFE_INTEGER;
}
__name(isSafeInteger, "isSafeInteger");
/**
 * @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 $ = "";
function __PRIVATE_encodeResourcePath(e2) {
  let t2 = "";
  for (let n2 = 0; n2 < e2.length; n2++) t2.length > 0 && (t2 = __PRIVATE_encodeSeparator(t2)), t2 = __PRIVATE_encodeSegment(e2.get(n2), t2);
  return __PRIVATE_encodeSeparator(t2);
}
__name(__PRIVATE_encodeResourcePath, "__PRIVATE_encodeResourcePath");
function __PRIVATE_encodeSegment(e2, t2) {
  let n2 = t2;
  const r2 = e2.length;
  for (let t3 = 0; t3 < r2; t3++) {
    const r3 = e2.charAt(t3);
    switch (r3) {
      case "\0":
        n2 += "";
        break;
      case $:
        n2 += "";
        break;
      default:
        n2 += r3;
    }
  }
  return n2;
}
__name(__PRIVATE_encodeSegment, "__PRIVATE_encodeSegment");
function __PRIVATE_encodeSeparator(e2) {
  return e2 + $ + "";
}
__name(__PRIVATE_encodeSeparator, "__PRIVATE_encodeSeparator");
function __PRIVATE_decodeResourcePath(e2) {
  const t2 = e2.length;
  if (__PRIVATE_hardAssert(t2 >= 2), 2 === t2) return __PRIVATE_hardAssert(e2.charAt(0) === $ && "" === e2.charAt(1)), ResourcePath.emptyPath();
  const __PRIVATE_lastReasonableEscapeIndex = t2 - 2, n2 = [];
  let r2 = "";
  for (let i2 = 0; i2 < t2; ) {
    const t3 = e2.indexOf($, i2);
    (t3 < 0 || t3 > __PRIVATE_lastReasonableEscapeIndex) && fail();
    switch (e2.charAt(t3 + 1)) {
      case "":
        const s2 = e2.substring(i2, t3);
        let o2;
        0 === r2.length ? (
          // Avoid copying for the common case of a segment that excludes \0
          // and \001
          o2 = s2
        ) : (r2 += s2, o2 = r2, r2 = ""), n2.push(o2);
        break;
      case "":
        r2 += e2.substring(i2, t3), r2 += "\0";
        break;
      case "":
        r2 += e2.substring(i2, t3 + 1);
        break;
      default:
        fail();
    }
    i2 = t3 + 2;
  }
  return new ResourcePath(n2);
}
__name(__PRIVATE_decodeResourcePath, "__PRIVATE_decodeResourcePath");
/**
 * @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 U = "remoteDocuments", K = "owner", W = "owner", G = "mutationQueues", z$1 = "userId", j = "mutations", H = "batchId", J = "userMutationsIndex", Y = ["userId", "batchId"];
/**
 * @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 __PRIVATE_newDbDocumentMutationPrefixForPath(e2, t2) {
  return [e2, __PRIVATE_encodeResourcePath(t2)];
}
__name(__PRIVATE_newDbDocumentMutationPrefixForPath, "__PRIVATE_newDbDocumentMutationPrefixForPath");
function __PRIVATE_newDbDocumentMutationKey(e2, t2, n2) {
  return [e2, __PRIVATE_encodeResourcePath(t2), n2];
}
__name(__PRIVATE_newDbDocumentMutationKey, "__PRIVATE_newDbDocumentMutationKey");
const Z$1 = {}, X = "documentMutations", ee = "remoteDocumentsV14", te$1 = ["prefixPath", "collectionGroup", "readTime", "documentId"], ne = "documentKeyIndex", re = ["prefixPath", "collectionGroup", "documentId"], ie$2 = "collectionGroupIndex", se = ["collectionGroup", "readTime", "prefixPath", "documentId"], oe = "remoteDocumentGlobal", _e = "remoteDocumentGlobalKey", ae = "targets", ue = "queryTargetsIndex", ce = ["canonicalId", "targetId"], le = "targetDocuments", he = ["targetId", "path"], Pe = "documentTargetsIndex", Te = ["path", "targetId"], Ie = "targetGlobalKey", Ee = "targetGlobal", de = "collectionParents", Ae = ["collectionId", "parent"], Re = "clientMetadata", Ve = "clientId", me = "bundles", fe = "bundleId", ge = "namedQueries", pe = "name", ye = "indexConfiguration", we = "indexId", Se = "collectionGroupIndex", be = "collectionGroup", De = "indexState", ve = ["indexId", "uid"], Ce = "sequenceNumberIndex", Fe = ["uid", "sequenceNumber"], Me = "indexEntries", xe = ["indexId", "uid", "arrayValue", "directionalValue", "orderedDocumentKey", "documentKey"], Oe = "documentKeyIndex", Ne = ["indexId", "uid", "orderedDocumentKey"], Be = "documentOverlays", Le = ["userId", "collectionPath", "documentId"], ke = "collectionPathOverlayIndex", qe = ["userId", "collectionPath", "largestBatchId"], Qe = "collectionGroupOverlayIndex", $e = ["userId", "collectionGroup", "largestBatchId"], Ue = "globals", Ke = "name", We = [...[...[...[...[G, j, X, U, ae, K, Ee, le], Re], oe], de], me, ge], Ge = [...We, Be], ze = [G, j, X, ee, ae, K, Ee, le, Re, oe, de, me, ge, Be], je = ze, He = [...je, ye, De, Me], Je = He, Ye = [...He, Ue];
/**
 * @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 __PRIVATE_IndexedDbTransaction extends PersistenceTransaction {
  static {
    __name(this, "__PRIVATE_IndexedDbTransaction");
  }
  constructor(e2, t2) {
    super(), this.ue = e2, this.currentSequenceNumber = t2;
  }
}
function __PRIVATE_getStore(e2, t2) {
  const n2 = __PRIVATE_debugCast(e2);
  return __PRIVATE_SimpleDb.M(n2.ue, t2);
}
__name(__PRIVATE_getStore, "__PRIVATE_getStore");
/**
 * @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 __PRIVATE_objectSize(e2) {
  let t2 = 0;
  for (const n2 in e2) Object.prototype.hasOwnProperty.call(e2, n2) && t2++;
  return t2;
}
__name(__PRIVATE_objectSize, "__PRIVATE_objectSize");
function forEach$2(e2, t2) {
  for (const n2 in e2) Object.prototype.hasOwnProperty.call(e2, n2) && t2(n2, e2[n2]);
}
__name(forEach$2, "forEach$2");
function __PRIVATE_mapToArray(e2, t2) {
  const n2 = [];
  for (const r2 in e2) Object.prototype.hasOwnProperty.call(e2, r2) && n2.push(t2(e2[r2], r2, e2));
  return n2;
}
__name(__PRIVATE_mapToArray, "__PRIVATE_mapToArray");
function isEmpty$3(e2) {
  for (const t2 in e2) if (Object.prototype.hasOwnProperty.call(e2, t2)) return false;
  return true;
}
__name(isEmpty$3, "isEmpty$3");
/**
 * @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 SortedMap {
  static {
    __name(this, "SortedMap");
  }
  constructor(e2, t2) {
    this.comparator = e2, this.root = t2 || LLRBNode.EMPTY;
  }
  // Returns a copy of the map, with the specified key/value added or replaced.
  insert(e2, t2) {
    return new SortedMap(this.comparator, this.root.insert(e2, t2, this.comparator).copy(null, null, LLRBNode.BLACK, null, null));
  }
  // Returns a copy of the map, with the specified key removed.
  remove(e2) {
    return new SortedMap(this.comparator, this.root.remove(e2, this.comparator).copy(null, null, LLRBNode.BLACK, null, null));
  }
  // Returns the value of the node with the given key, or null.
  get(e2) {
    let t2 = this.root;
    for (; !t2.isEmpty(); ) {
      const n2 = this.comparator(e2, t2.key);
      if (0 === n2) return t2.value;
      n2 < 0 ? t2 = t2.left : n2 > 0 && (t2 = t2.right);
    }
    return null;
  }
  // Returns the index of the element in this sorted map, or -1 if it doesn't
  // exist.
  indexOf(e2) {
    let t2 = 0, n2 = this.root;
    for (; !n2.isEmpty(); ) {
      const r2 = this.comparator(e2, n2.key);
      if (0 === r2) return t2 + n2.left.size;
      r2 < 0 ? n2 = n2.left : (
        // Count all nodes left of the node plus the node itself
        (t2 += n2.left.size + 1, n2 = n2.right)
      );
    }
    return -1;
  }
  isEmpty() {
    return this.root.isEmpty();
  }
  // Returns the total number of nodes in the map.
  get size() {
    return this.root.size;
  }
  // 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. If action returns true, traversal is aborted.
  // Returns the first truthy value returned by action, or the last falsey
  // value returned by action.
  inorderTraversal(e2) {
    return this.root.inorderTraversal(e2);
  }
  forEach(e2) {
    this.inorderTraversal((t2, n2) => (e2(t2, n2), false));
  }
  toString() {
    const e2 = [];
    return this.inorderTraversal((t2, n2) => (e2.push(`${t2}:${n2}`), false)), `{${e2.join(", ")}}`;
  }
  // Traverses the map in reverse key order and calls the specified action
  // function 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.
  reverseTraversal(e2) {
    return this.root.reverseTraversal(e2);
  }
  // Returns an iterator over the SortedMap.
  getIterator() {
    return new SortedMapIterator(this.root, null, this.comparator, false);
  }
  getIteratorFrom(e2) {
    return new SortedMapIterator(this.root, e2, this.comparator, false);
  }
  getReverseIterator() {
    return new SortedMapIterator(this.root, null, this.comparator, true);
  }
  getReverseIteratorFrom(e2) {
    return new SortedMapIterator(this.root, e2, this.comparator, true);
  }
}
class SortedMapIterator {
  static {
    __name(this, "SortedMapIterator");
  }
  constructor(e2, t2, n2, r2) {
    this.isReverse = r2, this.nodeStack = [];
    let i2 = 1;
    for (; !e2.isEmpty(); ) if (i2 = t2 ? n2(e2.key, t2) : 1, // flip the comparison if we're going in reverse
    t2 && r2 && (i2 *= -1), i2 < 0)
      e2 = this.isReverse ? e2.left : e2.right;
    else {
      if (0 === i2) {
        this.nodeStack.push(e2);
        break;
      }
      this.nodeStack.push(e2), e2 = this.isReverse ? e2.right : e2.left;
    }
  }
  getNext() {
    let e2 = this.nodeStack.pop();
    const t2 = {
      key: e2.key,
      value: e2.value
    };
    if (this.isReverse) for (e2 = e2.left; !e2.isEmpty(); ) this.nodeStack.push(e2), e2 = e2.right;
    else for (e2 = e2.right; !e2.isEmpty(); ) this.nodeStack.push(e2), e2 = e2.left;
    return t2;
  }
  hasNext() {
    return this.nodeStack.length > 0;
  }
  peek() {
    if (0 === this.nodeStack.length) return null;
    const e2 = this.nodeStack[this.nodeStack.length - 1];
    return {
      key: e2.key,
      value: e2.value
    };
  }
}
class LLRBNode {
  static {
    __name(this, "LLRBNode");
  }
  constructor(e2, t2, n2, r2, i2) {
    this.key = e2, this.value = t2, this.color = null != n2 ? n2 : LLRBNode.RED, this.left = null != r2 ? r2 : LLRBNode.EMPTY, this.right = null != i2 ? i2 : LLRBNode.EMPTY, this.size = this.left.size + 1 + this.right.size;
  }
  // Returns a copy of the current node, optionally replacing pieces of it.
  copy(e2, t2, n2, r2, i2) {
    return new LLRBNode(null != e2 ? e2 : this.key, null != t2 ? t2 : this.value, null != n2 ? n2 : this.color, null != r2 ? r2 : this.left, null != i2 ? i2 : this.right);
  }
  isEmpty() {
    return false;
  }
  // Traverses the tree in key order and calls the specified action function
  // for each node. If action returns true, traversal is aborted.
  // Returns the first truthy value returned by action, or the last falsey
  // value returned by action.
  inorderTraversal(e2) {
    return this.left.inorderTraversal(e2) || e2(this.key, this.value) || this.right.inorderTraversal(e2);
  }
  // Traverses the tree in reverse key order and calls the specified action
  // function for each node. If action returns true, traversal is aborted.
  // Returns the first truthy value returned by action, or the last falsey
  // value returned by action.
  reverseTraversal(e2) {
    return this.right.reverseTraversal(e2) || e2(this.key, this.value) || this.left.reverseTraversal(e2);
  }
  // Returns the minimum node in the tree.
  min() {
    return this.left.isEmpty() ? this : this.left.min();
  }
  // Returns the maximum key in the tree.
  minKey() {
    return this.min().key;
  }
  // Returns the maximum key in the tree.
  maxKey() {
    return this.right.isEmpty() ? this.key : this.right.maxKey();
  }
  // Returns new tree, with the key/value added.
  insert(e2, t2, n2) {
    let r2 = this;
    const i2 = n2(e2, r2.key);
    return r2 = i2 < 0 ? r2.copy(null, null, null, r2.left.insert(e2, t2, n2), null) : 0 === i2 ? r2.copy(null, t2, null, null, null) : r2.copy(null, null, null, null, r2.right.insert(e2, t2, n2)), r2.fixUp();
  }
  removeMin() {
    if (this.left.isEmpty()) return LLRBNode.EMPTY;
    let e2 = this;
    return e2.left.isRed() || e2.left.left.isRed() || (e2 = e2.moveRedLeft()), e2 = e2.copy(null, null, null, e2.left.removeMin(), null), e2.fixUp();
  }
  // Returns new tree, with the specified item removed.
  remove(e2, t2) {
    let n2, r2 = this;
    if (t2(e2, r2.key) < 0) r2.left.isEmpty() || r2.left.isRed() || r2.left.left.isRed() || (r2 = r2.moveRedLeft()), r2 = r2.copy(null, null, null, r2.left.remove(e2, t2), null);
    else {
      if (r2.left.isRed() && (r2 = r2.rotateRight()), r2.right.isEmpty() || r2.right.isRed() || r2.right.left.isRed() || (r2 = r2.moveRedRight()), 0 === t2(e2, r2.key)) {
        if (r2.right.isEmpty()) return LLRBNode.EMPTY;
        n2 = r2.right.min(), r2 = r2.copy(n2.key, n2.value, null, null, r2.right.removeMin());
      }
      r2 = r2.copy(null, null, null, null, r2.right.remove(e2, t2));
    }
    return r2.fixUp();
  }
  isRed() {
    return this.color;
  }
  // Returns new tree after performing any needed rotations.
  fixUp() {
    let e2 = this;
    return e2.right.isRed() && !e2.left.isRed() && (e2 = e2.rotateLeft()), e2.left.isRed() && e2.left.left.isRed() && (e2 = e2.rotateRight()), e2.left.isRed() && e2.right.isRed() && (e2 = e2.colorFlip()), e2;
  }
  moveRedLeft() {
    let e2 = this.colorFlip();
    return e2.right.left.isRed() && (e2 = e2.copy(null, null, null, null, e2.right.rotateRight()), e2 = e2.rotateLeft(), e2 = e2.colorFlip()), e2;
  }
  moveRedRight() {
    let e2 = this.colorFlip();
    return e2.left.left.isRed() && (e2 = e2.rotateRight(), e2 = e2.colorFlip()), e2;
  }
  rotateLeft() {
    const e2 = this.copy(null, null, LLRBNode.RED, null, this.right.left);
    return this.right.copy(null, null, this.color, e2, null);
  }
  rotateRight() {
    const e2 = this.copy(null, null, LLRBNode.RED, this.left.right, null);
    return this.left.copy(null, null, this.color, null, e2);
  }
  colorFlip() {
    const e2 = this.left.copy(null, null, !this.left.color, null, null), t2 = this.right.copy(null, null, !this.right.color, null, null);
    return this.copy(null, null, !this.color, e2, t2);
  }
  // For testing.
  checkMaxDepth() {
    const e2 = this.check();
    return Math.pow(2, e2) <= this.size + 1;
  }
  // In a balanced RB tree, the black-depth (number of black nodes) from root to
  // leaves is equal on both sides.  This function verifies that or asserts.
  check() {
    if (this.isRed() && this.left.isRed()) throw fail();
    if (this.right.isRed()) throw fail();
    const e2 = this.left.check();
    if (e2 !== this.right.check()) throw fail();
    return e2 + (this.isRed() ? 0 : 1);
  }
}
LLRBNode.EMPTY = null, LLRBNode.RED = true, LLRBNode.BLACK = false;
LLRBNode.EMPTY = new // Represents an empty node (a leaf node in the Red-Black Tree).
class LLRBEmptyNode2 {
  static {
    __name(this, "LLRBEmptyNode");
  }
  constructor() {
    this.size = 0;
  }
  get key() {
    throw fail();
  }
  get value() {
    throw fail();
  }
  get color() {
    throw fail();
  }
  get left() {
    throw fail();
  }
  get right() {
    throw fail();
  }
  // Returns a copy of the current node.
  copy(e2, t2, n2, r2, i2) {
    return this;
  }
  // Returns a copy of the tree, with the specified key/value added.
  insert(e2, t2, n2) {
    return new LLRBNode(e2, t2);
  }
  // Returns a copy of the tree, with the specified key removed.
  remove(e2, t2) {
    return this;
  }
  isEmpty() {
    return true;
  }
  inorderTraversal(e2) {
    return false;
  }
  reverseTraversal(e2) {
    return false;
  }
  minKey() {
    return null;
  }
  maxKey() {
    return null;
  }
  isRed() {
    return false;
  }
  // For testing.
  checkMaxDepth() {
    return true;
  }
  check() {
    return 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 SortedSet {
  static {
    __name(this, "SortedSet");
  }
  constructor(e2) {
    this.comparator = e2, this.data = new SortedMap(this.comparator);
  }
  has(e2) {
    return null !== this.data.get(e2);
  }
  first() {
    return this.data.minKey();
  }
  last() {
    return this.data.maxKey();
  }
  get size() {
    return this.data.size;
  }
  indexOf(e2) {
    return this.data.indexOf(e2);
  }
  /** Iterates elements in order defined by "comparator" */
  forEach(e2) {
    this.data.inorderTraversal((t2, n2) => (e2(t2), false));
  }
  /** Iterates over `elem`s such that: range[0] &lt;= elem &lt; range[1]. */
  forEachInRange(e2, t2) {
    const n2 = this.data.getIteratorFrom(e2[0]);
    for (; n2.hasNext(); ) {
      const r2 = n2.getNext();
      if (this.comparator(r2.key, e2[1]) >= 0) return;
      t2(r2.key);
    }
  }
  /**
   * Iterates over `elem`s such that: start &lt;= elem until false is returned.
   */
  forEachWhile(e2, t2) {
    let n2;
    for (n2 = void 0 !== t2 ? this.data.getIteratorFrom(t2) : this.data.getIterator(); n2.hasNext(); ) {
      if (!e2(n2.getNext().key)) return;
    }
  }
  /** Finds the least element greater than or equal to `elem`. */
  firstAfterOrEqual(e2) {
    const t2 = this.data.getIteratorFrom(e2);
    return t2.hasNext() ? t2.getNext().key : null;
  }
  getIterator() {
    return new SortedSetIterator(this.data.getIterator());
  }
  getIteratorFrom(e2) {
    return new SortedSetIterator(this.data.getIteratorFrom(e2));
  }
  /** Inserts or updates an element */
  add(e2) {
    return this.copy(this.data.remove(e2).insert(e2, true));
  }
  /** Deletes an element */
  delete(e2) {
    return this.has(e2) ? this.copy(this.data.remove(e2)) : this;
  }
  isEmpty() {
    return this.data.isEmpty();
  }
  unionWith(e2) {
    let t2 = this;
    return t2.size < e2.size && (t2 = e2, e2 = this), e2.forEach((e3) => {
      t2 = t2.add(e3);
    }), t2;
  }
  isEqual(e2) {
    if (!(e2 instanceof SortedSet)) return false;
    if (this.size !== e2.size) return false;
    const t2 = this.data.getIterator(), n2 = e2.data.getIterator();
    for (; t2.hasNext(); ) {
      const e3 = t2.getNext().key, r2 = n2.getNext().key;
      if (0 !== this.comparator(e3, r2)) return false;
    }
    return true;
  }
  toArray() {
    const e2 = [];
    return this.forEach((t2) => {
      e2.push(t2);
    }), e2;
  }
  toString() {
    const e2 = [];
    return this.forEach((t2) => e2.push(t2)), "SortedSet(" + e2.toString() + ")";
  }
  copy(e2) {
    const t2 = new SortedSet(this.comparator);
    return t2.data = e2, t2;
  }
}
class SortedSetIterator {
  static {
    __name(this, "SortedSetIterator");
  }
  constructor(e2) {
    this.iter = e2;
  }
  getNext() {
    return this.iter.getNext().key;
  }
  hasNext() {
    return this.iter.hasNext();
  }
}
function __PRIVATE_advanceIterator(e2) {
  return e2.hasNext() ? e2.getNext() : void 0;
}
__name(__PRIVATE_advanceIterator, "__PRIVATE_advanceIterator");
/**
 * @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 FieldMask {
  static {
    __name(this, "FieldMask");
  }
  constructor(e2) {
    this.fields = e2, // TODO(dimond): validation of FieldMask
    // Sort the field mask to support `FieldMask.isEqual()` and assert below.
    e2.sort(FieldPath$1.comparator);
  }
  static empty() {
    return new FieldMask([]);
  }
  /**
   * Returns a new FieldMask object that is the result of adding all the given
   * fields paths to this field mask.
   */
  unionWith(e2) {
    let t2 = new SortedSet(FieldPath$1.comparator);
    for (const e3 of this.fields) t2 = t2.add(e3);
    for (const n2 of e2) t2 = t2.add(n2);
    return new FieldMask(t2.toArray());
  }
  /**
   * Verifies that `fieldPath` is included by at least one field in this field
   * mask.
   *
   * This is an O(n) operation, where `n` is the size of the field mask.
   */
  covers(e2) {
    for (const t2 of this.fields) if (t2.isPrefixOf(e2)) return true;
    return false;
  }
  isEqual(e2) {
    return __PRIVATE_arrayEquals(this.fields, e2.fields, (e3, t2) => e3.isEqual(t2));
  }
}
/**
 * @license
 * Copyright 2023 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 __PRIVATE_Base64DecodeError extends Error {
  static {
    __name(this, "__PRIVATE_Base64DecodeError");
  }
  constructor() {
    super(...arguments), this.name = "Base64DecodeError";
  }
}
/**
 * @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.
 */
function __PRIVATE_isBase64Available() {
  return "undefined" != typeof atob;
}
__name(__PRIVATE_isBase64Available, "__PRIVATE_isBase64Available");
/**
 * @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 ByteString {
  static {
    __name(this, "ByteString");
  }
  constructor(e2) {
    this.binaryString = e2;
  }
  static fromBase64String(e2) {
    const t2 = (/* @__PURE__ */ __name(function __PRIVATE_decodeBase64(e3) {
      try {
        return atob(e3);
      } catch (e4) {
        throw "undefined" != typeof DOMException && e4 instanceof DOMException ? new __PRIVATE_Base64DecodeError("Invalid base64 string: " + e4) : e4;
      }
    }, "__PRIVATE_decodeBase64"))(e2);
    return new ByteString(t2);
  }
  static fromUint8Array(e2) {
    const t2 = (
      /**
      * Helper function to convert an Uint8array to a binary string.
      */
      (/* @__PURE__ */ __name(function __PRIVATE_binaryStringFromUint8Array(e3) {
        let t3 = "";
        for (let n2 = 0; n2 < e3.length; ++n2) t3 += String.fromCharCode(e3[n2]);
        return t3;
      }, "__PRIVATE_binaryStringFromUint8Array"))(e2)
    );
    return new ByteString(t2);
  }
  [Symbol.iterator]() {
    let e2 = 0;
    return {
      next: /* @__PURE__ */ __name(() => e2 < this.binaryString.length ? {
        value: this.binaryString.charCodeAt(e2++),
        done: false
      } : {
        value: void 0,
        done: true
      }, "next")
    };
  }
  toBase64() {
    return (/* @__PURE__ */ __name(function __PRIVATE_encodeBase64(e2) {
      return btoa(e2);
    }, "__PRIVATE_encodeBase64"))(this.binaryString);
  }
  toUint8Array() {
    return (/* @__PURE__ */ __name(function __PRIVATE_uint8ArrayFromBinaryString(e2) {
      const t2 = new Uint8Array(e2.length);
      for (let n2 = 0; n2 < e2.length; n2++) t2[n2] = e2.charCodeAt(n2);
      return t2;
    }, "__PRIVATE_uint8ArrayFromBinaryString"))(this.binaryString);
  }
  approximateByteSize() {
    return 2 * this.binaryString.length;
  }
  compareTo(e2) {
    return __PRIVATE_primitiveComparator(this.binaryString, e2.binaryString);
  }
  isEqual(e2) {
    return this.binaryString === e2.binaryString;
  }
}
ByteString.EMPTY_BYTE_STRING = new ByteString("");
const Ze = new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);
function __PRIVATE_normalizeTimestamp(e2) {
  if (__PRIVATE_hardAssert(!!e2), "string" == typeof e2) {
    let t2 = 0;
    const n2 = Ze.exec(e2);
    if (__PRIVATE_hardAssert(!!n2), n2[1]) {
      let e3 = n2[1];
      e3 = (e3 + "000000000").substr(0, 9), t2 = Number(e3);
    }
    const r2 = new Date(e2);
    return {
      seconds: Math.floor(r2.getTime() / 1e3),
      nanos: t2
    };
  }
  return {
    seconds: __PRIVATE_normalizeNumber(e2.seconds),
    nanos: __PRIVATE_normalizeNumber(e2.nanos)
  };
}
__name(__PRIVATE_normalizeTimestamp, "__PRIVATE_normalizeTimestamp");
function __PRIVATE_normalizeNumber(e2) {
  return "number" == typeof e2 ? e2 : "string" == typeof e2 ? Number(e2) : 0;
}
__name(__PRIVATE_normalizeNumber, "__PRIVATE_normalizeNumber");
function __PRIVATE_normalizeByteString(e2) {
  return "string" == typeof e2 ? ByteString.fromBase64String(e2) : ByteString.fromUint8Array(e2);
}
__name(__PRIVATE_normalizeByteString, "__PRIVATE_normalizeByteString");
/**
 * @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 Xe = "server_timestamp", et = "__type__", tt$1 = "__previous_value__", nt = "__local_write_time__";
function __PRIVATE_isServerTimestamp(e2) {
  var t2, n2;
  return (null === (n2 = ((null === (t2 = null == e2 ? void 0 : e2.mapValue) || void 0 === t2 ? void 0 : t2.fields) || {})[et]) || void 0 === n2 ? void 0 : n2.stringValue) === Xe;
}
__name(__PRIVATE_isServerTimestamp, "__PRIVATE_isServerTimestamp");
function __PRIVATE_getPreviousValue(e2) {
  const t2 = e2.mapValue.fields[tt$1];
  return __PRIVATE_isServerTimestamp(t2) ? __PRIVATE_getPreviousValue(t2) : t2;
}
__name(__PRIVATE_getPreviousValue, "__PRIVATE_getPreviousValue");
function __PRIVATE_getLocalWriteTime(e2) {
  const t2 = __PRIVATE_normalizeTimestamp(e2.mapValue.fields[nt].timestampValue);
  return new Timestamp(t2.seconds, t2.nanos);
}
__name(__PRIVATE_getLocalWriteTime, "__PRIVATE_getLocalWriteTime");
/**
 * @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 DatabaseInfo {
  static {
    __name(this, "DatabaseInfo");
  }
  /**
   * Constructs a DatabaseInfo using the provided host, databaseId and
   * persistenceKey.
   *
   * @param databaseId - The database to use.
   * @param appId - The Firebase App Id.
   * @param persistenceKey - A unique identifier for this Firestore's local
   * storage (used in conjunction with the databaseId).
   * @param host - The Firestore backend host to connect to.
   * @param ssl - Whether to use SSL when connecting.
   * @param forceLongPolling - Whether to use the forceLongPolling option
   * when using WebChannel as the network transport.
   * @param autoDetectLongPolling - Whether to use the detectBufferingProxy
   * option when using WebChannel as the network transport.
   * @param longPollingOptions Options that configure long-polling.
   * @param useFetchStreams Whether to use the Fetch API instead of
   * XMLHTTPRequest
   */
  constructor(e2, t2, n2, r2, i2, s2, o2, _2, a2) {
    this.databaseId = e2, this.appId = t2, this.persistenceKey = n2, this.host = r2, this.ssl = i2, this.forceLongPolling = s2, this.autoDetectLongPolling = o2, this.longPollingOptions = _2, this.useFetchStreams = a2;
  }
}
const rt = "(default)";
class DatabaseId {
  static {
    __name(this, "DatabaseId");
  }
  constructor(e2, t2) {
    this.projectId = e2, this.database = t2 || rt;
  }
  static empty() {
    return new DatabaseId("", "");
  }
  get isDefaultDatabase() {
    return this.database === rt;
  }
  isEqual(e2) {
    return e2 instanceof DatabaseId && e2.projectId === this.projectId && e2.database === this.database;
  }
}
/**
 * @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 it = "__type__", st$1 = "__max__", ot = {
  mapValue: {
    fields: {
      __type__: {
        stringValue: st$1
      }
    }
  }
}, _t = "__vector__", at = "value", ut = {
  nullValue: "NULL_VALUE"
};
function __PRIVATE_typeOrder(e2) {
  return "nullValue" in e2 ? 0 : "booleanValue" in e2 ? 1 : "integerValue" in e2 || "doubleValue" in e2 ? 2 : "timestampValue" in e2 ? 3 : "stringValue" in e2 ? 5 : "bytesValue" in e2 ? 6 : "referenceValue" in e2 ? 7 : "geoPointValue" in e2 ? 8 : "arrayValue" in e2 ? 9 : "mapValue" in e2 ? __PRIVATE_isServerTimestamp(e2) ? 4 : __PRIVATE_isMaxValue(e2) ? 9007199254740991 : __PRIVATE_isVectorValue(e2) ? 10 : 11 : fail();
}
__name(__PRIVATE_typeOrder, "__PRIVATE_typeOrder");
function __PRIVATE_valueEquals(e2, t2) {
  if (e2 === t2) return true;
  const n2 = __PRIVATE_typeOrder(e2);
  if (n2 !== __PRIVATE_typeOrder(t2)) return false;
  switch (n2) {
    case 0:
    case 9007199254740991:
      return true;
    case 1:
      return e2.booleanValue === t2.booleanValue;
    case 4:
      return __PRIVATE_getLocalWriteTime(e2).isEqual(__PRIVATE_getLocalWriteTime(t2));
    case 3:
      return (/* @__PURE__ */ __name(function __PRIVATE_timestampEquals(e3, t3) {
        if ("string" == typeof e3.timestampValue && "string" == typeof t3.timestampValue && e3.timestampValue.length === t3.timestampValue.length)
          return e3.timestampValue === t3.timestampValue;
        const n3 = __PRIVATE_normalizeTimestamp(e3.timestampValue), r2 = __PRIVATE_normalizeTimestamp(t3.timestampValue);
        return n3.seconds === r2.seconds && n3.nanos === r2.nanos;
      }, "__PRIVATE_timestampEquals"))(e2, t2);
    case 5:
      return e2.stringValue === t2.stringValue;
    case 6:
      return (/* @__PURE__ */ __name(function __PRIVATE_blobEquals(e3, t3) {
        return __PRIVATE_normalizeByteString(e3.bytesValue).isEqual(__PRIVATE_normalizeByteString(t3.bytesValue));
      }, "__PRIVATE_blobEquals"))(e2, t2);
    case 7:
      return e2.referenceValue === t2.referenceValue;
    case 8:
      return (/* @__PURE__ */ __name(function __PRIVATE_geoPointEquals(e3, t3) {
        return __PRIVATE_normalizeNumber(e3.geoPointValue.latitude) === __PRIVATE_normalizeNumber(t3.geoPointValue.latitude) && __PRIVATE_normalizeNumber(e3.geoPointValue.longitude) === __PRIVATE_normalizeNumber(t3.geoPointValue.longitude);
      }, "__PRIVATE_geoPointEquals"))(e2, t2);
    case 2:
      return (/* @__PURE__ */ __name(function __PRIVATE_numberEquals(e3, t3) {
        if ("integerValue" in e3 && "integerValue" in t3) return __PRIVATE_normalizeNumber(e3.integerValue) === __PRIVATE_normalizeNumber(t3.integerValue);
        if ("doubleValue" in e3 && "doubleValue" in t3) {
          const n3 = __PRIVATE_normalizeNumber(e3.doubleValue), r2 = __PRIVATE_normalizeNumber(t3.doubleValue);
          return n3 === r2 ? __PRIVATE_isNegativeZero(n3) === __PRIVATE_isNegativeZero(r2) : isNaN(n3) && isNaN(r2);
        }
        return false;
      }, "__PRIVATE_numberEquals"))(e2, t2);
    case 9:
      return __PRIVATE_arrayEquals(e2.arrayValue.values || [], t2.arrayValue.values || [], __PRIVATE_valueEquals);
    case 10:
    case 11:
      return (/* @__PURE__ */ __name(function __PRIVATE_objectEquals(e3, t3) {
        const n3 = e3.mapValue.fields || {}, r2 = t3.mapValue.fields || {};
        if (__PRIVATE_objectSize(n3) !== __PRIVATE_objectSize(r2)) return false;
        for (const e4 in n3) if (n3.hasOwnProperty(e4) && (void 0 === r2[e4] || !__PRIVATE_valueEquals(n3[e4], r2[e4]))) return false;
        return true;
      }, "__PRIVATE_objectEquals"))(e2, t2);
    default:
      return fail();
  }
}
__name(__PRIVATE_valueEquals, "__PRIVATE_valueEquals");
function __PRIVATE_arrayValueContains(e2, t2) {
  return void 0 !== (e2.values || []).find((e3) => __PRIVATE_valueEquals(e3, t2));
}
__name(__PRIVATE_arrayValueContains, "__PRIVATE_arrayValueContains");
function __PRIVATE_valueCompare(e2, t2) {
  if (e2 === t2) return 0;
  const n2 = __PRIVATE_typeOrder(e2), r2 = __PRIVATE_typeOrder(t2);
  if (n2 !== r2) return __PRIVATE_primitiveComparator(n2, r2);
  switch (n2) {
    case 0:
    case 9007199254740991:
      return 0;
    case 1:
      return __PRIVATE_primitiveComparator(e2.booleanValue, t2.booleanValue);
    case 2:
      return (/* @__PURE__ */ __name(function __PRIVATE_compareNumbers(e3, t3) {
        const n3 = __PRIVATE_normalizeNumber(e3.integerValue || e3.doubleValue), r3 = __PRIVATE_normalizeNumber(t3.integerValue || t3.doubleValue);
        return n3 < r3 ? -1 : n3 > r3 ? 1 : n3 === r3 ? 0 : (
          // one or both are NaN.
          isNaN(n3) ? isNaN(r3) ? 0 : -1 : 1
        );
      }, "__PRIVATE_compareNumbers"))(e2, t2);
    case 3:
      return __PRIVATE_compareTimestamps(e2.timestampValue, t2.timestampValue);
    case 4:
      return __PRIVATE_compareTimestamps(__PRIVATE_getLocalWriteTime(e2), __PRIVATE_getLocalWriteTime(t2));
    case 5:
      return __PRIVATE_compareUtf8Strings(e2.stringValue, t2.stringValue);
    case 6:
      return (/* @__PURE__ */ __name(function __PRIVATE_compareBlobs(e3, t3) {
        const n3 = __PRIVATE_normalizeByteString(e3), r3 = __PRIVATE_normalizeByteString(t3);
        return n3.compareTo(r3);
      }, "__PRIVATE_compareBlobs"))(e2.bytesValue, t2.bytesValue);
    case 7:
      return (/* @__PURE__ */ __name(function __PRIVATE_compareReferences(e3, t3) {
        const n3 = e3.split("/"), r3 = t3.split("/");
        for (let e4 = 0; e4 < n3.length && e4 < r3.length; e4++) {
          const t4 = __PRIVATE_primitiveComparator(n3[e4], r3[e4]);
          if (0 !== t4) return t4;
        }
        return __PRIVATE_primitiveComparator(n3.length, r3.length);
      }, "__PRIVATE_compareReferences"))(e2.referenceValue, t2.referenceValue);
    case 8:
      return (/* @__PURE__ */ __name(function __PRIVATE_compareGeoPoints(e3, t3) {
        const n3 = __PRIVATE_primitiveComparator(__PRIVATE_normalizeNumber(e3.latitude), __PRIVATE_normalizeNumber(t3.latitude));
        if (0 !== n3) return n3;
        return __PRIVATE_primitiveComparator(__PRIVATE_normalizeNumber(e3.longitude), __PRIVATE_normalizeNumber(t3.longitude));
      }, "__PRIVATE_compareGeoPoints"))(e2.geoPointValue, t2.geoPointValue);
    case 9:
      return __PRIVATE_compareArrays(e2.arrayValue, t2.arrayValue);
    case 10:
      return (/* @__PURE__ */ __name(function __PRIVATE_compareVectors(e3, t3) {
        var n3, r3, i2, s2;
        const o2 = e3.fields || {}, _2 = t3.fields || {}, a2 = null === (n3 = o2[at]) || void 0 === n3 ? void 0 : n3.arrayValue, u2 = null === (r3 = _2[at]) || void 0 === r3 ? void 0 : r3.arrayValue, c2 = __PRIVATE_primitiveComparator((null === (i2 = null == a2 ? void 0 : a2.values) || void 0 === i2 ? void 0 : i2.length) || 0, (null === (s2 = null == u2 ? void 0 : u2.values) || void 0 === s2 ? void 0 : s2.length) || 0);
        if (0 !== c2) return c2;
        return __PRIVATE_compareArrays(a2, u2);
      }, "__PRIVATE_compareVectors"))(e2.mapValue, t2.mapValue);
    case 11:
      return (/* @__PURE__ */ __name(function __PRIVATE_compareMaps(e3, t3) {
        if (e3 === ot.mapValue && t3 === ot.mapValue) return 0;
        if (e3 === ot.mapValue) return 1;
        if (t3 === ot.mapValue) return -1;
        const n3 = e3.fields || {}, r3 = Object.keys(n3), i2 = t3.fields || {}, s2 = Object.keys(i2);
        r3.sort(), s2.sort();
        for (let e4 = 0; e4 < r3.length && e4 < s2.length; ++e4) {
          const t4 = __PRIVATE_compareUtf8Strings(r3[e4], s2[e4]);
          if (0 !== t4) return t4;
          const o2 = __PRIVATE_valueCompare(n3[r3[e4]], i2[s2[e4]]);
          if (0 !== o2) return o2;
        }
        return __PRIVATE_primitiveComparator(r3.length, s2.length);
      }, "__PRIVATE_compareMaps"))(e2.mapValue, t2.mapValue);
    default:
      throw fail();
  }
}
__name(__PRIVATE_valueCompare, "__PRIVATE_valueCompare");
function __PRIVATE_compareTimestamps(e2, t2) {
  if ("string" == typeof e2 && "string" == typeof t2 && e2.length === t2.length) return __PRIVATE_primitiveComparator(e2, t2);
  const n2 = __PRIVATE_normalizeTimestamp(e2), r2 = __PRIVATE_normalizeTimestamp(t2), i2 = __PRIVATE_primitiveComparator(n2.seconds, r2.seconds);
  return 0 !== i2 ? i2 : __PRIVATE_primitiveComparator(n2.nanos, r2.nanos);
}
__name(__PRIVATE_compareTimestamps, "__PRIVATE_compareTimestamps");
function __PRIVATE_compareArrays(e2, t2) {
  const n2 = e2.values || [], r2 = t2.values || [];
  for (let e3 = 0; e3 < n2.length && e3 < r2.length; ++e3) {
    const t3 = __PRIVATE_valueCompare(n2[e3], r2[e3]);
    if (t3) return t3;
  }
  return __PRIVATE_primitiveComparator(n2.length, r2.length);
}
__name(__PRIVATE_compareArrays, "__PRIVATE_compareArrays");
function canonicalId(e2) {
  return __PRIVATE_canonifyValue(e2);
}
__name(canonicalId, "canonicalId");
function __PRIVATE_canonifyValue(e2) {
  return "nullValue" in e2 ? "null" : "booleanValue" in e2 ? "" + e2.booleanValue : "integerValue" in e2 ? "" + e2.integerValue : "doubleValue" in e2 ? "" + e2.doubleValue : "timestampValue" in e2 ? (/* @__PURE__ */ __name(function __PRIVATE_canonifyTimestamp(e3) {
    const t2 = __PRIVATE_normalizeTimestamp(e3);
    return `time(${t2.seconds},${t2.nanos})`;
  }, "__PRIVATE_canonifyTimestamp"))(e2.timestampValue) : "stringValue" in e2 ? e2.stringValue : "bytesValue" in e2 ? (/* @__PURE__ */ __name(function __PRIVATE_canonifyByteString(e3) {
    return __PRIVATE_normalizeByteString(e3).toBase64();
  }, "__PRIVATE_canonifyByteString"))(e2.bytesValue) : "referenceValue" in e2 ? (/* @__PURE__ */ __name(function __PRIVATE_canonifyReference(e3) {
    return DocumentKey.fromName(e3).toString();
  }, "__PRIVATE_canonifyReference"))(e2.referenceValue) : "geoPointValue" in e2 ? (/* @__PURE__ */ __name(function __PRIVATE_canonifyGeoPoint(e3) {
    return `geo(${e3.latitude},${e3.longitude})`;
  }, "__PRIVATE_canonifyGeoPoint"))(e2.geoPointValue) : "arrayValue" in e2 ? (/* @__PURE__ */ __name(function __PRIVATE_canonifyArray(e3) {
    let t2 = "[", n2 = true;
    for (const r2 of e3.values || []) n2 ? n2 = false : t2 += ",", t2 += __PRIVATE_canonifyValue(r2);
    return t2 + "]";
  }, "__PRIVATE_canonifyArray"))(e2.arrayValue) : "mapValue" in e2 ? (/* @__PURE__ */ __name(function __PRIVATE_canonifyMap(e3) {
    const t2 = Object.keys(e3.fields || {}).sort();
    let n2 = "{", r2 = true;
    for (const i2 of t2) r2 ? r2 = false : n2 += ",", n2 += `${i2}:${__PRIVATE_canonifyValue(e3.fields[i2])}`;
    return n2 + "}";
  }, "__PRIVATE_canonifyMap"))(e2.mapValue) : fail();
}
__name(__PRIVATE_canonifyValue, "__PRIVATE_canonifyValue");
function __PRIVATE_estimateByteSize(e2) {
  switch (__PRIVATE_typeOrder(e2)) {
    case 0:
    case 1:
      return 4;
    case 2:
      return 8;
    case 3:
    case 8:
      return 16;
    case 4:
      const t2 = __PRIVATE_getPreviousValue(e2);
      return t2 ? 16 + __PRIVATE_estimateByteSize(t2) : 16;
    case 5:
      return 2 * e2.stringValue.length;
    case 6:
      return __PRIVATE_normalizeByteString(e2.bytesValue).approximateByteSize();
    case 7:
      return e2.referenceValue.length;
    case 9:
      return (/* @__PURE__ */ __name(function __PRIVATE_estimateArrayByteSize(e3) {
        return (e3.values || []).reduce((e4, t3) => e4 + __PRIVATE_estimateByteSize(t3), 0);
      }, "__PRIVATE_estimateArrayByteSize"))(e2.arrayValue);
    case 10:
    case 11:
      return (/* @__PURE__ */ __name(function __PRIVATE_estimateMapByteSize(e3) {
        let t3 = 0;
        return forEach$2(e3.fields, (e4, n2) => {
          t3 += e4.length + __PRIVATE_estimateByteSize(n2);
        }), t3;
      }, "__PRIVATE_estimateMapByteSize"))(e2.mapValue);
    default:
      throw fail();
  }
}
__name(__PRIVATE_estimateByteSize, "__PRIVATE_estimateByteSize");
function __PRIVATE_refValue(e2, t2) {
  return {
    referenceValue: `projects/${e2.projectId}/databases/${e2.database}/documents/${t2.path.canonicalString()}`
  };
}
__name(__PRIVATE_refValue, "__PRIVATE_refValue");
function isInteger(e2) {
  return !!e2 && "integerValue" in e2;
}
__name(isInteger, "isInteger");
function isArray$a(e2) {
  return !!e2 && "arrayValue" in e2;
}
__name(isArray$a, "isArray$a");
function __PRIVATE_isNullValue(e2) {
  return !!e2 && "nullValue" in e2;
}
__name(__PRIVATE_isNullValue, "__PRIVATE_isNullValue");
function __PRIVATE_isNanValue(e2) {
  return !!e2 && "doubleValue" in e2 && isNaN(Number(e2.doubleValue));
}
__name(__PRIVATE_isNanValue, "__PRIVATE_isNanValue");
function __PRIVATE_isMapValue(e2) {
  return !!e2 && "mapValue" in e2;
}
__name(__PRIVATE_isMapValue, "__PRIVATE_isMapValue");
function __PRIVATE_isVectorValue(e2) {
  var t2, n2;
  return (null === (n2 = ((null === (t2 = null == e2 ? void 0 : e2.mapValue) || void 0 === t2 ? void 0 : t2.fields) || {})[it]) || void 0 === n2 ? void 0 : n2.stringValue) === _t;
}
__name(__PRIVATE_isVectorValue, "__PRIVATE_isVectorValue");
function __PRIVATE_deepClone(e2) {
  if (e2.geoPointValue) return {
    geoPointValue: Object.assign({}, e2.geoPointValue)
  };
  if (e2.timestampValue && "object" == typeof e2.timestampValue) return {
    timestampValue: Object.assign({}, e2.timestampValue)
  };
  if (e2.mapValue) {
    const t2 = {
      mapValue: {
        fields: {}
      }
    };
    return forEach$2(e2.mapValue.fields, (e3, n2) => t2.mapValue.fields[e3] = __PRIVATE_deepClone(n2)), t2;
  }
  if (e2.arrayValue) {
    const t2 = {
      arrayValue: {
        values: []
      }
    };
    for (let n2 = 0; n2 < (e2.arrayValue.values || []).length; ++n2) t2.arrayValue.values[n2] = __PRIVATE_deepClone(e2.arrayValue.values[n2]);
    return t2;
  }
  return Object.assign({}, e2);
}
__name(__PRIVATE_deepClone, "__PRIVATE_deepClone");
function __PRIVATE_isMaxValue(e2) {
  return (((e2.mapValue || {}).fields || {}).__type__ || {}).stringValue === st$1;
}
__name(__PRIVATE_isMaxValue, "__PRIVATE_isMaxValue");
const ct = {
  mapValue: {
    fields: {
      [it]: {
        stringValue: _t
      },
      [at]: {
        arrayValue: {}
      }
    }
  }
};
function __PRIVATE_valuesGetLowerBound(e2) {
  return "nullValue" in e2 ? ut : "booleanValue" in e2 ? {
    booleanValue: false
  } : "integerValue" in e2 || "doubleValue" in e2 ? {
    doubleValue: NaN
  } : "timestampValue" in e2 ? {
    timestampValue: {
      seconds: Number.MIN_SAFE_INTEGER
    }
  } : "stringValue" in e2 ? {
    stringValue: ""
  } : "bytesValue" in e2 ? {
    bytesValue: ""
  } : "referenceValue" in e2 ? __PRIVATE_refValue(DatabaseId.empty(), DocumentKey.empty()) : "geoPointValue" in e2 ? {
    geoPointValue: {
      latitude: -90,
      longitude: -180
    }
  } : "arrayValue" in e2 ? {
    arrayValue: {}
  } : "mapValue" in e2 ? __PRIVATE_isVectorValue(e2) ? ct : {
    mapValue: {}
  } : fail();
}
__name(__PRIVATE_valuesGetLowerBound, "__PRIVATE_valuesGetLowerBound");
function __PRIVATE_valuesGetUpperBound(e2) {
  return "nullValue" in e2 ? {
    booleanValue: false
  } : "booleanValue" in e2 ? {
    doubleValue: NaN
  } : "integerValue" in e2 || "doubleValue" in e2 ? {
    timestampValue: {
      seconds: Number.MIN_SAFE_INTEGER
    }
  } : "timestampValue" in e2 ? {
    stringValue: ""
  } : "stringValue" in e2 ? {
    bytesValue: ""
  } : "bytesValue" in e2 ? __PRIVATE_refValue(DatabaseId.empty(), DocumentKey.empty()) : "referenceValue" in e2 ? {
    geoPointValue: {
      latitude: -90,
      longitude: -180
    }
  } : "geoPointValue" in e2 ? {
    arrayValue: {}
  } : "arrayValue" in e2 ? ct : "mapValue" in e2 ? __PRIVATE_isVectorValue(e2) ? {
    mapValue: {}
  } : ot : fail();
}
__name(__PRIVATE_valuesGetUpperBound, "__PRIVATE_valuesGetUpperBound");
function __PRIVATE_lowerBoundCompare(e2, t2) {
  const n2 = __PRIVATE_valueCompare(e2.value, t2.value);
  return 0 !== n2 ? n2 : e2.inclusive && !t2.inclusive ? -1 : !e2.inclusive && t2.inclusive ? 1 : 0;
}
__name(__PRIVATE_lowerBoundCompare, "__PRIVATE_lowerBoundCompare");
function __PRIVATE_upperBoundCompare(e2, t2) {
  const n2 = __PRIVATE_valueCompare(e2.value, t2.value);
  return 0 !== n2 ? n2 : e2.inclusive && !t2.inclusive ? 1 : !e2.inclusive && t2.inclusive ? -1 : 0;
}
__name(__PRIVATE_upperBoundCompare, "__PRIVATE_upperBoundCompare");
/**
 * @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 ObjectValue {
  static {
    __name(this, "ObjectValue");
  }
  constructor(e2) {
    this.value = e2;
  }
  static empty() {
    return new ObjectValue({
      mapValue: {}
    });
  }
  /**
   * Returns the value at the given path or null.
   *
   * @param path - the path to search
   * @returns The value at the path or null if the path is not set.
   */
  field(e2) {
    if (e2.isEmpty()) return this.value;
    {
      let t2 = this.value;
      for (let n2 = 0; n2 < e2.length - 1; ++n2) if (t2 = (t2.mapValue.fields || {})[e2.get(n2)], !__PRIVATE_isMapValue(t2)) return null;
      return t2 = (t2.mapValue.fields || {})[e2.lastSegment()], t2 || null;
    }
  }
  /**
   * Sets the field to the provided value.
   *
   * @param path - The field path to set.
   * @param value - The value to set.
   */
  set(e2, t2) {
    this.getFieldsMap(e2.popLast())[e2.lastSegment()] = __PRIVATE_deepClone(t2);
  }
  /**
   * Sets the provided fields to the provided values.
   *
   * @param data - A map of fields to values (or null for deletes).
   */
  setAll(e2) {
    let t2 = FieldPath$1.emptyPath(), n2 = {}, r2 = [];
    e2.forEach((e3, i3) => {
      if (!t2.isImmediateParentOf(i3)) {
        const e4 = this.getFieldsMap(t2);
        this.applyChanges(e4, n2, r2), n2 = {}, r2 = [], t2 = i3.popLast();
      }
      e3 ? n2[i3.lastSegment()] = __PRIVATE_deepClone(e3) : r2.push(i3.lastSegment());
    });
    const i2 = this.getFieldsMap(t2);
    this.applyChanges(i2, n2, r2);
  }
  /**
   * Removes the field at the specified path. If there is no field at the
   * specified path, nothing is changed.
   *
   * @param path - The field path to remove.
   */
  delete(e2) {
    const t2 = this.field(e2.popLast());
    __PRIVATE_isMapValue(t2) && t2.mapValue.fields && delete t2.mapValue.fields[e2.lastSegment()];
  }
  isEqual(e2) {
    return __PRIVATE_valueEquals(this.value, e2.value);
  }
  /**
   * Returns the map that contains the leaf element of `path`. If the parent
   * entry does not yet exist, or if it is not a map, a new map will be created.
   */
  getFieldsMap(e2) {
    let t2 = this.value;
    t2.mapValue.fields || (t2.mapValue = {
      fields: {}
    });
    for (let n2 = 0; n2 < e2.length; ++n2) {
      let r2 = t2.mapValue.fields[e2.get(n2)];
      __PRIVATE_isMapValue(r2) && r2.mapValue.fields || (r2 = {
        mapValue: {
          fields: {}
        }
      }, t2.mapValue.fields[e2.get(n2)] = r2), t2 = r2;
    }
    return t2.mapValue.fields;
  }
  /**
   * Modifies `fieldsMap` by adding, replacing or deleting the specified
   * entries.
   */
  applyChanges(e2, t2, n2) {
    forEach$2(t2, (t3, n3) => e2[t3] = n3);
    for (const t3 of n2) delete e2[t3];
  }
  clone() {
    return new ObjectValue(__PRIVATE_deepClone(this.value));
  }
}
function __PRIVATE_extractFieldMask(e2) {
  const t2 = [];
  return forEach$2(e2.fields, (e3, n2) => {
    const r2 = new FieldPath$1([e3]);
    if (__PRIVATE_isMapValue(n2)) {
      const e4 = __PRIVATE_extractFieldMask(n2.mapValue).fields;
      if (0 === e4.length)
        t2.push(r2);
      else
        for (const n3 of e4) t2.push(r2.child(n3));
    } else
      t2.push(r2);
  }), new FieldMask(t2);
}
__name(__PRIVATE_extractFieldMask, "__PRIVATE_extractFieldMask");
/**
 * @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 MutableDocument {
  static {
    __name(this, "MutableDocument");
  }
  constructor(e2, t2, n2, r2, i2, s2, o2) {
    this.key = e2, this.documentType = t2, this.version = n2, this.readTime = r2, this.createTime = i2, this.data = s2, this.documentState = o2;
  }
  /**
   * Creates a document with no known version or data, but which can serve as
   * base document for mutations.
   */
  static newInvalidDocument(e2) {
    return new MutableDocument(
      e2,
      0,
      /* version */
      SnapshotVersion.min(),
      /* readTime */
      SnapshotVersion.min(),
      /* createTime */
      SnapshotVersion.min(),
      ObjectValue.empty(),
      0
      /* DocumentState.SYNCED */
    );
  }
  /**
   * Creates a new document that is known to exist with the given data at the
   * given version.
   */
  static newFoundDocument(e2, t2, n2, r2) {
    return new MutableDocument(
      e2,
      1,
      /* version */
      t2,
      /* readTime */
      SnapshotVersion.min(),
      /* createTime */
      n2,
      r2,
      0
      /* DocumentState.SYNCED */
    );
  }
  /** Creates a new document that is known to not exist at the given version. */
  static newNoDocument(e2, t2) {
    return new MutableDocument(
      e2,
      2,
      /* version */
      t2,
      /* readTime */
      SnapshotVersion.min(),
      /* createTime */
      SnapshotVersion.min(),
      ObjectValue.empty(),
      0
      /* DocumentState.SYNCED */
    );
  }
  /**
   * Creates a new document that is known to exist at the given version but
   * whose data is not known (e.g. a document that was updated without a known
   * base document).
   */
  static newUnknownDocument(e2, t2) {
    return new MutableDocument(
      e2,
      3,
      /* version */
      t2,
      /* readTime */
      SnapshotVersion.min(),
      /* createTime */
      SnapshotVersion.min(),
      ObjectValue.empty(),
      2
      /* DocumentState.HAS_COMMITTED_MUTATIONS */
    );
  }
  /**
   * Changes the document type to indicate that it exists and that its version
   * and data are known.
   */
  convertToFoundDocument(e2, t2) {
    return !this.createTime.isEqual(SnapshotVersion.min()) || 2 !== this.documentType && 0 !== this.documentType || (this.createTime = e2), this.version = e2, this.documentType = 1, this.data = t2, this.documentState = 0, this;
  }
  /**
   * Changes the document type to indicate that it doesn't exist at the given
   * version.
   */
  convertToNoDocument(e2) {
    return this.version = e2, this.documentType = 2, this.data = ObjectValue.empty(), this.documentState = 0, this;
  }
  /**
   * Changes the document type to indicate that it exists at a given version but
   * that its data is not known (e.g. a document that was updated without a known
   * base document).
   */
  convertToUnknownDocument(e2) {
    return this.version = e2, this.documentType = 3, this.data = ObjectValue.empty(), this.documentState = 2, this;
  }
  setHasCommittedMutations() {
    return this.documentState = 2, this;
  }
  setHasLocalMutations() {
    return this.documentState = 1, this.version = SnapshotVersion.min(), this;
  }
  setReadTime(e2) {
    return this.readTime = e2, this;
  }
  get hasLocalMutations() {
    return 1 === this.documentState;
  }
  get hasCommittedMutations() {
    return 2 === this.documentState;
  }
  get hasPendingWrites() {
    return this.hasLocalMutations || this.hasCommittedMutations;
  }
  isValidDocument() {
    return 0 !== this.documentType;
  }
  isFoundDocument() {
    return 1 === this.documentType;
  }
  isNoDocument() {
    return 2 === this.documentType;
  }
  isUnknownDocument() {
    return 3 === this.documentType;
  }
  isEqual(e2) {
    return e2 instanceof MutableDocument && this.key.isEqual(e2.key) && this.version.isEqual(e2.version) && this.documentType === e2.documentType && this.documentState === e2.documentState && this.data.isEqual(e2.data);
  }
  mutableCopy() {
    return new MutableDocument(this.key, this.documentType, this.version, this.readTime, this.createTime, this.data.clone(), this.documentState);
  }
  toString() {
    return `Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`;
  }
}
/**
 * @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.
 */
class Bound {
  static {
    __name(this, "Bound");
  }
  constructor(e2, t2) {
    this.position = e2, this.inclusive = t2;
  }
}
function __PRIVATE_boundCompareToDocument(e2, t2, n2) {
  let r2 = 0;
  for (let i2 = 0; i2 < e2.position.length; i2++) {
    const s2 = t2[i2], o2 = e2.position[i2];
    if (s2.field.isKeyField()) r2 = DocumentKey.comparator(DocumentKey.fromName(o2.referenceValue), n2.key);
    else {
      r2 = __PRIVATE_valueCompare(o2, n2.data.field(s2.field));
    }
    if ("desc" === s2.dir && (r2 *= -1), 0 !== r2) break;
  }
  return r2;
}
__name(__PRIVATE_boundCompareToDocument, "__PRIVATE_boundCompareToDocument");
function __PRIVATE_boundEquals(e2, t2) {
  if (null === e2) return null === t2;
  if (null === t2) return false;
  if (e2.inclusive !== t2.inclusive || e2.position.length !== t2.position.length) return false;
  for (let n2 = 0; n2 < e2.position.length; n2++) {
    if (!__PRIVATE_valueEquals(e2.position[n2], t2.position[n2])) return false;
  }
  return true;
}
__name(__PRIVATE_boundEquals, "__PRIVATE_boundEquals");
/**
 * @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.
 */
class OrderBy {
  static {
    __name(this, "OrderBy");
  }
  constructor(e2, t2 = "asc") {
    this.field = e2, this.dir = t2;
  }
}
function __PRIVATE_orderByEquals(e2, t2) {
  return e2.dir === t2.dir && e2.field.isEqual(t2.field);
}
__name(__PRIVATE_orderByEquals, "__PRIVATE_orderByEquals");
/**
 * @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.
 */
class Filter {
  static {
    __name(this, "Filter");
  }
}
class FieldFilter extends Filter {
  static {
    __name(this, "FieldFilter");
  }
  constructor(e2, t2, n2) {
    super(), this.field = e2, this.op = t2, this.value = n2;
  }
  /**
   * Creates a filter based on the provided arguments.
   */
  static create(e2, t2, n2) {
    return e2.isKeyField() ? "in" === t2 || "not-in" === t2 ? this.createKeyFieldInFilter(e2, t2, n2) : new __PRIVATE_KeyFieldFilter(e2, t2, n2) : "array-contains" === t2 ? new __PRIVATE_ArrayContainsFilter(e2, n2) : "in" === t2 ? new __PRIVATE_InFilter(e2, n2) : "not-in" === t2 ? new __PRIVATE_NotInFilter(e2, n2) : "array-contains-any" === t2 ? new __PRIVATE_ArrayContainsAnyFilter(e2, n2) : new FieldFilter(e2, t2, n2);
  }
  static createKeyFieldInFilter(e2, t2, n2) {
    return "in" === t2 ? new __PRIVATE_KeyFieldInFilter(e2, n2) : new __PRIVATE_KeyFieldNotInFilter(e2, n2);
  }
  matches(e2) {
    const t2 = e2.data.field(this.field);
    return "!=" === this.op ? null !== t2 && this.matchesComparison(__PRIVATE_valueCompare(t2, this.value)) : null !== t2 && __PRIVATE_typeOrder(this.value) === __PRIVATE_typeOrder(t2) && this.matchesComparison(__PRIVATE_valueCompare(t2, this.value));
  }
  matchesComparison(e2) {
    switch (this.op) {
      case "<":
        return e2 < 0;
      case "<=":
        return e2 <= 0;
      case "==":
        return 0 === e2;
      case "!=":
        return 0 !== e2;
      case ">":
        return e2 > 0;
      case ">=":
        return e2 >= 0;
      default:
        return fail();
    }
  }
  isInequality() {
    return [
      "<",
      "<=",
      ">",
      ">=",
      "!=",
      "not-in"
      /* Operator.NOT_IN */
    ].indexOf(this.op) >= 0;
  }
  getFlattenedFilters() {
    return [this];
  }
  getFilters() {
    return [this];
  }
}
class CompositeFilter extends Filter {
  static {
    __name(this, "CompositeFilter");
  }
  constructor(e2, t2) {
    super(), this.filters = e2, this.op = t2, this.ce = null;
  }
  /**
   * Creates a filter based on the provided arguments.
   */
  static create(e2, t2) {
    return new CompositeFilter(e2, t2);
  }
  matches(e2) {
    return __PRIVATE_compositeFilterIsConjunction(this) ? void 0 === this.filters.find((t2) => !t2.matches(e2)) : void 0 !== this.filters.find((t2) => t2.matches(e2));
  }
  getFlattenedFilters() {
    return null !== this.ce || (this.ce = this.filters.reduce((e2, t2) => e2.concat(t2.getFlattenedFilters()), [])), this.ce;
  }
  // Returns a mutable copy of `this.filters`
  getFilters() {
    return Object.assign([], this.filters);
  }
}
function __PRIVATE_compositeFilterIsConjunction(e2) {
  return "and" === e2.op;
}
__name(__PRIVATE_compositeFilterIsConjunction, "__PRIVATE_compositeFilterIsConjunction");
function __PRIVATE_compositeFilterIsDisjunction(e2) {
  return "or" === e2.op;
}
__name(__PRIVATE_compositeFilterIsDisjunction, "__PRIVATE_compositeFilterIsDisjunction");
function __PRIVATE_compositeFilterIsFlatConjunction(e2) {
  return __PRIVATE_compositeFilterIsFlat(e2) && __PRIVATE_compositeFilterIsConjunction(e2);
}
__name(__PRIVATE_compositeFilterIsFlatConjunction, "__PRIVATE_compositeFilterIsFlatConjunction");
function __PRIVATE_compositeFilterIsFlat(e2) {
  for (const t2 of e2.filters) if (t2 instanceof CompositeFilter) return false;
  return true;
}
__name(__PRIVATE_compositeFilterIsFlat, "__PRIVATE_compositeFilterIsFlat");
function __PRIVATE_canonifyFilter(e2) {
  if (e2 instanceof FieldFilter)
    return e2.field.canonicalString() + e2.op.toString() + canonicalId(e2.value);
  if (__PRIVATE_compositeFilterIsFlatConjunction(e2))
    return e2.filters.map((e3) => __PRIVATE_canonifyFilter(e3)).join(",");
  {
    const t2 = e2.filters.map((e3) => __PRIVATE_canonifyFilter(e3)).join(",");
    return `${e2.op}(${t2})`;
  }
}
__name(__PRIVATE_canonifyFilter, "__PRIVATE_canonifyFilter");
function __PRIVATE_filterEquals(e2, t2) {
  return e2 instanceof FieldFilter ? (/* @__PURE__ */ __name(function __PRIVATE_fieldFilterEquals(e3, t3) {
    return t3 instanceof FieldFilter && e3.op === t3.op && e3.field.isEqual(t3.field) && __PRIVATE_valueEquals(e3.value, t3.value);
  }, "__PRIVATE_fieldFilterEquals"))(e2, t2) : e2 instanceof CompositeFilter ? (/* @__PURE__ */ __name(function __PRIVATE_compositeFilterEquals(e3, t3) {
    if (t3 instanceof CompositeFilter && e3.op === t3.op && e3.filters.length === t3.filters.length) {
      return e3.filters.reduce((e4, n2, r2) => e4 && __PRIVATE_filterEquals(n2, t3.filters[r2]), true);
    }
    return false;
  }, "__PRIVATE_compositeFilterEquals"))(e2, t2) : void fail();
}
__name(__PRIVATE_filterEquals, "__PRIVATE_filterEquals");
function __PRIVATE_compositeFilterWithAddedFilters(e2, t2) {
  const n2 = e2.filters.concat(t2);
  return CompositeFilter.create(n2, e2.op);
}
__name(__PRIVATE_compositeFilterWithAddedFilters, "__PRIVATE_compositeFilterWithAddedFilters");
function __PRIVATE_stringifyFilter(e2) {
  return e2 instanceof FieldFilter ? (/* @__PURE__ */ __name(function __PRIVATE_stringifyFieldFilter(e3) {
    return `${e3.field.canonicalString()} ${e3.op} ${canonicalId(e3.value)}`;
  }, "__PRIVATE_stringifyFieldFilter"))(e2) : e2 instanceof CompositeFilter ? (/* @__PURE__ */ __name(function __PRIVATE_stringifyCompositeFilter(e3) {
    return e3.op.toString() + " {" + e3.getFilters().map(__PRIVATE_stringifyFilter).join(" ,") + "}";
  }, "__PRIVATE_stringifyCompositeFilter"))(e2) : "Filter";
}
__name(__PRIVATE_stringifyFilter, "__PRIVATE_stringifyFilter");
class __PRIVATE_KeyFieldFilter extends FieldFilter {
  static {
    __name(this, "__PRIVATE_KeyFieldFilter");
  }
  constructor(e2, t2, n2) {
    super(e2, t2, n2), this.key = DocumentKey.fromName(n2.referenceValue);
  }
  matches(e2) {
    const t2 = DocumentKey.comparator(e2.key, this.key);
    return this.matchesComparison(t2);
  }
}
class __PRIVATE_KeyFieldInFilter extends FieldFilter {
  static {
    __name(this, "__PRIVATE_KeyFieldInFilter");
  }
  constructor(e2, t2) {
    super(e2, "in", t2), this.keys = __PRIVATE_extractDocumentKeysFromArrayValue("in", t2);
  }
  matches(e2) {
    return this.keys.some((t2) => t2.isEqual(e2.key));
  }
}
class __PRIVATE_KeyFieldNotInFilter extends FieldFilter {
  static {
    __name(this, "__PRIVATE_KeyFieldNotInFilter");
  }
  constructor(e2, t2) {
    super(e2, "not-in", t2), this.keys = __PRIVATE_extractDocumentKeysFromArrayValue("not-in", t2);
  }
  matches(e2) {
    return !this.keys.some((t2) => t2.isEqual(e2.key));
  }
}
function __PRIVATE_extractDocumentKeysFromArrayValue(e2, t2) {
  var n2;
  return ((null === (n2 = t2.arrayValue) || void 0 === n2 ? void 0 : n2.values) || []).map((e3) => DocumentKey.fromName(e3.referenceValue));
}
__name(__PRIVATE_extractDocumentKeysFromArrayValue, "__PRIVATE_extractDocumentKeysFromArrayValue");
class __PRIVATE_ArrayContainsFilter extends FieldFilter {
  static {
    __name(this, "__PRIVATE_ArrayContainsFilter");
  }
  constructor(e2, t2) {
    super(e2, "array-contains", t2);
  }
  matches(e2) {
    const t2 = e2.data.field(this.field);
    return isArray$a(t2) && __PRIVATE_arrayValueContains(t2.arrayValue, this.value);
  }
}
class __PRIVATE_InFilter extends FieldFilter {
  static {
    __name(this, "__PRIVATE_InFilter");
  }
  constructor(e2, t2) {
    super(e2, "in", t2);
  }
  matches(e2) {
    const t2 = e2.data.field(this.field);
    return null !== t2 && __PRIVATE_arrayValueContains(this.value.arrayValue, t2);
  }
}
class __PRIVATE_NotInFilter extends FieldFilter {
  static {
    __name(this, "__PRIVATE_NotInFilter");
  }
  constructor(e2, t2) {
    super(e2, "not-in", t2);
  }
  matches(e2) {
    if (__PRIVATE_arrayValueContains(this.value.arrayValue, {
      nullValue: "NULL_VALUE"
    })) return false;
    const t2 = e2.data.field(this.field);
    return null !== t2 && !__PRIVATE_arrayValueContains(this.value.arrayValue, t2);
  }
}
class __PRIVATE_ArrayContainsAnyFilter extends FieldFilter {
  static {
    __name(this, "__PRIVATE_ArrayContainsAnyFilter");
  }
  constructor(e2, t2) {
    super(e2, "array-contains-any", t2);
  }
  matches(e2) {
    const t2 = e2.data.field(this.field);
    return !(!isArray$a(t2) || !t2.arrayValue.values) && t2.arrayValue.values.some((e3) => __PRIVATE_arrayValueContains(this.value.arrayValue, e3));
  }
}
/**
 * @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 __PRIVATE_TargetImpl {
  static {
    __name(this, "__PRIVATE_TargetImpl");
  }
  constructor(e2, t2 = null, n2 = [], r2 = [], i2 = null, s2 = null, o2 = null) {
    this.path = e2, this.collectionGroup = t2, this.orderBy = n2, this.filters = r2, this.limit = i2, this.startAt = s2, this.endAt = o2, this.le = null;
  }
}
function __PRIVATE_newTarget(e2, t2 = null, n2 = [], r2 = [], i2 = null, s2 = null, o2 = null) {
  return new __PRIVATE_TargetImpl(e2, t2, n2, r2, i2, s2, o2);
}
__name(__PRIVATE_newTarget, "__PRIVATE_newTarget");
function __PRIVATE_canonifyTarget(e2) {
  const t2 = __PRIVATE_debugCast(e2);
  if (null === t2.le) {
    let e3 = t2.path.canonicalString();
    null !== t2.collectionGroup && (e3 += "|cg:" + t2.collectionGroup), e3 += "|f:", e3 += t2.filters.map((e4) => __PRIVATE_canonifyFilter(e4)).join(","), e3 += "|ob:", e3 += t2.orderBy.map((e4) => (/* @__PURE__ */ __name(function __PRIVATE_canonifyOrderBy(e5) {
      return e5.field.canonicalString() + e5.dir;
    }, "__PRIVATE_canonifyOrderBy"))(e4)).join(","), __PRIVATE_isNullOrUndefined(t2.limit) || (e3 += "|l:", e3 += t2.limit), t2.startAt && (e3 += "|lb:", e3 += t2.startAt.inclusive ? "b:" : "a:", e3 += t2.startAt.position.map((e4) => canonicalId(e4)).join(",")), t2.endAt && (e3 += "|ub:", e3 += t2.endAt.inclusive ? "a:" : "b:", e3 += t2.endAt.position.map((e4) => canonicalId(e4)).join(",")), t2.le = e3;
  }
  return t2.le;
}
__name(__PRIVATE_canonifyTarget, "__PRIVATE_canonifyTarget");
function __PRIVATE_targetEquals(e2, t2) {
  if (e2.limit !== t2.limit) return false;
  if (e2.orderBy.length !== t2.orderBy.length) return false;
  for (let n2 = 0; n2 < e2.orderBy.length; n2++) if (!__PRIVATE_orderByEquals(e2.orderBy[n2], t2.orderBy[n2])) return false;
  if (e2.filters.length !== t2.filters.length) return false;
  for (let n2 = 0; n2 < e2.filters.length; n2++) if (!__PRIVATE_filterEquals(e2.filters[n2], t2.filters[n2])) return false;
  return e2.collectionGroup === t2.collectionGroup && (!!e2.path.isEqual(t2.path) && (!!__PRIVATE_boundEquals(e2.startAt, t2.startAt) && __PRIVATE_boundEquals(e2.endAt, t2.endAt)));
}
__name(__PRIVATE_targetEquals, "__PRIVATE_targetEquals");
function __PRIVATE_targetIsDocumentTarget(e2) {
  return DocumentKey.isDocumentKey(e2.path) && null === e2.collectionGroup && 0 === e2.filters.length;
}
__name(__PRIVATE_targetIsDocumentTarget, "__PRIVATE_targetIsDocumentTarget");
function __PRIVATE_targetGetFieldFiltersForPath(e2, t2) {
  return e2.filters.filter((e3) => e3 instanceof FieldFilter && e3.field.isEqual(t2));
}
__name(__PRIVATE_targetGetFieldFiltersForPath, "__PRIVATE_targetGetFieldFiltersForPath");
function __PRIVATE_targetGetAscendingBound(e2, t2, n2) {
  let r2 = ut, i2 = true;
  for (const n3 of __PRIVATE_targetGetFieldFiltersForPath(e2, t2)) {
    let e3 = ut, t3 = true;
    switch (n3.op) {
      case "<":
      case "<=":
        e3 = __PRIVATE_valuesGetLowerBound(n3.value);
        break;
      case "==":
      case "in":
      case ">=":
        e3 = n3.value;
        break;
      case ">":
        e3 = n3.value, t3 = false;
        break;
      case "!=":
      case "not-in":
        e3 = ut;
    }
    __PRIVATE_lowerBoundCompare({
      value: r2,
      inclusive: i2
    }, {
      value: e3,
      inclusive: t3
    }) < 0 && (r2 = e3, i2 = t3);
  }
  if (null !== n2) for (let s2 = 0; s2 < e2.orderBy.length; ++s2) {
    if (e2.orderBy[s2].field.isEqual(t2)) {
      const e3 = n2.position[s2];
      __PRIVATE_lowerBoundCompare({
        value: r2,
        inclusive: i2
      }, {
        value: e3,
        inclusive: n2.inclusive
      }) < 0 && (r2 = e3, i2 = n2.inclusive);
      break;
    }
  }
  return {
    value: r2,
    inclusive: i2
  };
}
__name(__PRIVATE_targetGetAscendingBound, "__PRIVATE_targetGetAscendingBound");
function __PRIVATE_targetGetDescendingBound(e2, t2, n2) {
  let r2 = ot, i2 = true;
  for (const n3 of __PRIVATE_targetGetFieldFiltersForPath(e2, t2)) {
    let e3 = ot, t3 = true;
    switch (n3.op) {
      case ">=":
      case ">":
        e3 = __PRIVATE_valuesGetUpperBound(n3.value), t3 = false;
        break;
      case "==":
      case "in":
      case "<=":
        e3 = n3.value;
        break;
      case "<":
        e3 = n3.value, t3 = false;
        break;
      case "!=":
      case "not-in":
        e3 = ot;
    }
    __PRIVATE_upperBoundCompare({
      value: r2,
      inclusive: i2
    }, {
      value: e3,
      inclusive: t3
    }) > 0 && (r2 = e3, i2 = t3);
  }
  if (null !== n2) for (let s2 = 0; s2 < e2.orderBy.length; ++s2) {
    if (e2.orderBy[s2].field.isEqual(t2)) {
      const e3 = n2.position[s2];
      __PRIVATE_upperBoundCompare({
        value: r2,
        inclusive: i2
      }, {
        value: e3,
        inclusive: n2.inclusive
      }) > 0 && (r2 = e3, i2 = n2.inclusive);
      break;
    }
  }
  return {
    value: r2,
    inclusive: i2
  };
}
__name(__PRIVATE_targetGetDescendingBound, "__PRIVATE_targetGetDescendingBound");
/**
 * @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 __PRIVATE_QueryImpl {
  static {
    __name(this, "__PRIVATE_QueryImpl");
  }
  /**
   * Initializes a Query with a path and optional additional query constraints.
   * Path must currently be empty if this is a collection group query.
   */
  constructor(e2, t2 = null, n2 = [], r2 = [], i2 = null, s2 = "F", o2 = null, _2 = null) {
    this.path = e2, this.collectionGroup = t2, this.explicitOrderBy = n2, this.filters = r2, this.limit = i2, this.limitType = s2, this.startAt = o2, this.endAt = _2, this.he = null, // The corresponding `Target` of this `Query` instance, for use with
    // non-aggregate queries.
    this.Pe = null, // The corresponding `Target` of this `Query` instance, for use with
    // aggregate queries. Unlike targets for non-aggregate queries,
    // aggregate query targets do not contain normalized order-bys, they only
    // contain explicit order-bys.
    this.Te = null, this.startAt, this.endAt;
  }
}
function __PRIVATE_newQuery(e2, t2, n2, r2, i2, s2, o2, _2) {
  return new __PRIVATE_QueryImpl(e2, t2, n2, r2, i2, s2, o2, _2);
}
__name(__PRIVATE_newQuery, "__PRIVATE_newQuery");
function __PRIVATE_newQueryForPath(e2) {
  return new __PRIVATE_QueryImpl(e2);
}
__name(__PRIVATE_newQueryForPath, "__PRIVATE_newQueryForPath");
function __PRIVATE_queryMatchesAllDocuments(e2) {
  return 0 === e2.filters.length && null === e2.limit && null == e2.startAt && null == e2.endAt && (0 === e2.explicitOrderBy.length || 1 === e2.explicitOrderBy.length && e2.explicitOrderBy[0].field.isKeyField());
}
__name(__PRIVATE_queryMatchesAllDocuments, "__PRIVATE_queryMatchesAllDocuments");
function __PRIVATE_isCollectionGroupQuery(e2) {
  return null !== e2.collectionGroup;
}
__name(__PRIVATE_isCollectionGroupQuery, "__PRIVATE_isCollectionGroupQuery");
function __PRIVATE_queryNormalizedOrderBy(e2) {
  const t2 = __PRIVATE_debugCast(e2);
  if (null === t2.he) {
    t2.he = [];
    const e3 = /* @__PURE__ */ new Set();
    for (const n3 of t2.explicitOrderBy) t2.he.push(n3), e3.add(n3.field.canonicalString());
    const n2 = t2.explicitOrderBy.length > 0 ? t2.explicitOrderBy[t2.explicitOrderBy.length - 1].dir : "asc", r2 = (/* @__PURE__ */ __name(function __PRIVATE_getInequalityFilterFields(e4) {
      let t3 = new SortedSet(FieldPath$1.comparator);
      return e4.filters.forEach((e5) => {
        e5.getFlattenedFilters().forEach((e6) => {
          e6.isInequality() && (t3 = t3.add(e6.field));
        });
      }), t3;
    }, "__PRIVATE_getInequalityFilterFields"))(t2);
    r2.forEach((r3) => {
      e3.has(r3.canonicalString()) || r3.isKeyField() || t2.he.push(new OrderBy(r3, n2));
    }), // Add the document key field to the last if it is not explicitly ordered.
    e3.has(FieldPath$1.keyField().canonicalString()) || t2.he.push(new OrderBy(FieldPath$1.keyField(), n2));
  }
  return t2.he;
}
__name(__PRIVATE_queryNormalizedOrderBy, "__PRIVATE_queryNormalizedOrderBy");
function __PRIVATE_queryToTarget(e2) {
  const t2 = __PRIVATE_debugCast(e2);
  return t2.Pe || (t2.Pe = __PRIVATE__queryToTarget(t2, __PRIVATE_queryNormalizedOrderBy(e2))), t2.Pe;
}
__name(__PRIVATE_queryToTarget, "__PRIVATE_queryToTarget");
function __PRIVATE_queryToAggregateTarget(e2) {
  const t2 = __PRIVATE_debugCast(e2);
  return t2.Te || // Do not include implicit order-bys for aggregate queries.
  (t2.Te = __PRIVATE__queryToTarget(t2, e2.explicitOrderBy)), t2.Te;
}
__name(__PRIVATE_queryToAggregateTarget, "__PRIVATE_queryToAggregateTarget");
function __PRIVATE__queryToTarget(e2, t2) {
  if ("F" === e2.limitType) return __PRIVATE_newTarget(e2.path, e2.collectionGroup, t2, e2.filters, e2.limit, e2.startAt, e2.endAt);
  {
    t2 = t2.map((e3) => {
      const t3 = "desc" === e3.dir ? "asc" : "desc";
      return new OrderBy(e3.field, t3);
    });
    const n2 = e2.endAt ? new Bound(e2.endAt.position, e2.endAt.inclusive) : null, r2 = e2.startAt ? new Bound(e2.startAt.position, e2.startAt.inclusive) : null;
    return __PRIVATE_newTarget(e2.path, e2.collectionGroup, t2, e2.filters, e2.limit, n2, r2);
  }
}
__name(__PRIVATE__queryToTarget, "__PRIVATE__queryToTarget");
function __PRIVATE_queryWithAddedFilter(e2, t2) {
  const n2 = e2.filters.concat([t2]);
  return new __PRIVATE_QueryImpl(e2.path, e2.collectionGroup, e2.explicitOrderBy.slice(), n2, e2.limit, e2.limitType, e2.startAt, e2.endAt);
}
__name(__PRIVATE_queryWithAddedFilter, "__PRIVATE_queryWithAddedFilter");
function __PRIVATE_queryWithLimit(e2, t2, n2) {
  return new __PRIVATE_QueryImpl(e2.path, e2.collectionGroup, e2.explicitOrderBy.slice(), e2.filters.slice(), t2, n2, e2.startAt, e2.endAt);
}
__name(__PRIVATE_queryWithLimit, "__PRIVATE_queryWithLimit");
function __PRIVATE_queryEquals(e2, t2) {
  return __PRIVATE_targetEquals(__PRIVATE_queryToTarget(e2), __PRIVATE_queryToTarget(t2)) && e2.limitType === t2.limitType;
}
__name(__PRIVATE_queryEquals, "__PRIVATE_queryEquals");
function __PRIVATE_canonifyQuery(e2) {
  return `${__PRIVATE_canonifyTarget(__PRIVATE_queryToTarget(e2))}|lt:${e2.limitType}`;
}
__name(__PRIVATE_canonifyQuery, "__PRIVATE_canonifyQuery");
function __PRIVATE_stringifyQuery(e2) {
  return `Query(target=${(/* @__PURE__ */ __name(function __PRIVATE_stringifyTarget(e3) {
    let t2 = e3.path.canonicalString();
    return null !== e3.collectionGroup && (t2 += " collectionGroup=" + e3.collectionGroup), e3.filters.length > 0 && (t2 += `, filters: [${e3.filters.map((e4) => __PRIVATE_stringifyFilter(e4)).join(", ")}]`), __PRIVATE_isNullOrUndefined(e3.limit) || (t2 += ", limit: " + e3.limit), e3.orderBy.length > 0 && (t2 += `, orderBy: [${e3.orderBy.map((e4) => (/* @__PURE__ */ __name(function __PRIVATE_stringifyOrderBy(e5) {
      return `${e5.field.canonicalString()} (${e5.dir})`;
    }, "__PRIVATE_stringifyOrderBy"))(e4)).join(", ")}]`), e3.startAt && (t2 += ", startAt: ", t2 += e3.startAt.inclusive ? "b:" : "a:", t2 += e3.startAt.position.map((e4) => canonicalId(e4)).join(",")), e3.endAt && (t2 += ", endAt: ", t2 += e3.endAt.inclusive ? "a:" : "b:", t2 += e3.endAt.position.map((e4) => canonicalId(e4)).join(",")), `Target(${t2})`;
  }, "__PRIVATE_stringifyTarget"))(__PRIVATE_queryToTarget(e2))}; limitType=${e2.limitType})`;
}
__name(__PRIVATE_stringifyQuery, "__PRIVATE_stringifyQuery");
function __PRIVATE_queryMatches(e2, t2) {
  return t2.isFoundDocument() && (/* @__PURE__ */ __name(function __PRIVATE_queryMatchesPathAndCollectionGroup(e3, t3) {
    const n2 = t3.key.path;
    return null !== e3.collectionGroup ? t3.key.hasCollectionId(e3.collectionGroup) && e3.path.isPrefixOf(n2) : DocumentKey.isDocumentKey(e3.path) ? e3.path.isEqual(n2) : e3.path.isImmediateParentOf(n2);
  }, "__PRIVATE_queryMatchesPathAndCollectionGroup"))(e2, t2) && (/* @__PURE__ */ __name(function __PRIVATE_queryMatchesOrderBy(e3, t3) {
    for (const n2 of __PRIVATE_queryNormalizedOrderBy(e3))
      if (!n2.field.isKeyField() && null === t3.data.field(n2.field)) return false;
    return true;
  }, "__PRIVATE_queryMatchesOrderBy"))(e2, t2) && (/* @__PURE__ */ __name(function __PRIVATE_queryMatchesFilters(e3, t3) {
    for (const n2 of e3.filters) if (!n2.matches(t3)) return false;
    return true;
  }, "__PRIVATE_queryMatchesFilters"))(e2, t2) && (/* @__PURE__ */ __name(function __PRIVATE_queryMatchesBounds(e3, t3) {
    if (e3.startAt && !/**
    * Returns true if a document sorts before a bound using the provided sort
    * order.
    */
    (/* @__PURE__ */ __name(function __PRIVATE_boundSortsBeforeDocument(e4, t4, n2) {
      const r2 = __PRIVATE_boundCompareToDocument(e4, t4, n2);
      return e4.inclusive ? r2 <= 0 : r2 < 0;
    }, "__PRIVATE_boundSortsBeforeDocument"))(e3.startAt, __PRIVATE_queryNormalizedOrderBy(e3), t3)) return false;
    if (e3.endAt && !(/* @__PURE__ */ __name(function __PRIVATE_boundSortsAfterDocument(e4, t4, n2) {
      const r2 = __PRIVATE_boundCompareToDocument(e4, t4, n2);
      return e4.inclusive ? r2 >= 0 : r2 > 0;
    }, "__PRIVATE_boundSortsAfterDocument"))(e3.endAt, __PRIVATE_queryNormalizedOrderBy(e3), t3)) return false;
    return true;
  }, "__PRIVATE_queryMatchesBounds"))(e2, t2);
}
__name(__PRIVATE_queryMatches, "__PRIVATE_queryMatches");
function __PRIVATE_queryCollectionGroup(e2) {
  return e2.collectionGroup || (e2.path.length % 2 == 1 ? e2.path.lastSegment() : e2.path.get(e2.path.length - 2));
}
__name(__PRIVATE_queryCollectionGroup, "__PRIVATE_queryCollectionGroup");
function __PRIVATE_newQueryComparator(e2) {
  return (t2, n2) => {
    let r2 = false;
    for (const i2 of __PRIVATE_queryNormalizedOrderBy(e2)) {
      const e3 = __PRIVATE_compareDocs(i2, t2, n2);
      if (0 !== e3) return e3;
      r2 = r2 || i2.field.isKeyField();
    }
    return 0;
  };
}
__name(__PRIVATE_newQueryComparator, "__PRIVATE_newQueryComparator");
function __PRIVATE_compareDocs(e2, t2, n2) {
  const r2 = e2.field.isKeyField() ? DocumentKey.comparator(t2.key, n2.key) : (/* @__PURE__ */ __name(function __PRIVATE_compareDocumentsByField(e3, t3, n3) {
    const r3 = t3.data.field(e3), i2 = n3.data.field(e3);
    return null !== r3 && null !== i2 ? __PRIVATE_valueCompare(r3, i2) : fail();
  }, "__PRIVATE_compareDocumentsByField"))(e2.field, t2, n2);
  switch (e2.dir) {
    case "asc":
      return r2;
    case "desc":
      return -1 * r2;
    default:
      return fail();
  }
}
__name(__PRIVATE_compareDocs, "__PRIVATE_compareDocs");
/**
 * @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 ObjectMap {
  static {
    __name(this, "ObjectMap");
  }
  constructor(e2, t2) {
    this.mapKeyFn = e2, this.equalsFn = t2, /**
     * The inner map for a key/value pair. Due to the possibility of collisions we
     * keep a list of entries that we do a linear search through to find an actual
     * match. Note that collisions should be rare, so we still expect near
     * constant time lookups in practice.
     */
    this.inner = {}, /** The number of entries stored in the map */
    this.innerSize = 0;
  }
  /** Get a value for this key, or undefined if it does not exist. */
  get(e2) {
    const t2 = this.mapKeyFn(e2), n2 = this.inner[t2];
    if (void 0 !== n2) {
      for (const [t3, r2] of n2) if (this.equalsFn(t3, e2)) return r2;
    }
  }
  has(e2) {
    return void 0 !== this.get(e2);
  }
  /** Put this key and value in the map. */
  set(e2, t2) {
    const n2 = this.mapKeyFn(e2), r2 = this.inner[n2];
    if (void 0 === r2) return this.inner[n2] = [[e2, t2]], void this.innerSize++;
    for (let n3 = 0; n3 < r2.length; n3++) if (this.equalsFn(r2[n3][0], e2))
      return void (r2[n3] = [e2, t2]);
    r2.push([e2, t2]), this.innerSize++;
  }
  /**
   * Remove this key from the map. Returns a boolean if anything was deleted.
   */
  delete(e2) {
    const t2 = this.mapKeyFn(e2), n2 = this.inner[t2];
    if (void 0 === n2) return false;
    for (let r2 = 0; r2 < n2.length; r2++) if (this.equalsFn(n2[r2][0], e2)) return 1 === n2.length ? delete this.inner[t2] : n2.splice(r2, 1), this.innerSize--, true;
    return false;
  }
  forEach(e2) {
    forEach$2(this.inner, (t2, n2) => {
      for (const [t3, r2] of n2) e2(t3, r2);
    });
  }
  isEmpty() {
    return isEmpty$3(this.inner);
  }
  size() {
    return this.innerSize;
  }
}
/**
 * @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 lt = new SortedMap(DocumentKey.comparator);
function __PRIVATE_mutableDocumentMap() {
  return lt;
}
__name(__PRIVATE_mutableDocumentMap, "__PRIVATE_mutableDocumentMap");
const ht = new SortedMap(DocumentKey.comparator);
function documentMap(...e2) {
  let t2 = ht;
  for (const n2 of e2) t2 = t2.insert(n2.key, n2);
  return t2;
}
__name(documentMap, "documentMap");
function __PRIVATE_convertOverlayedDocumentMapToDocumentMap(e2) {
  let t2 = ht;
  return e2.forEach((e3, n2) => t2 = t2.insert(e3, n2.overlayedDocument)), t2;
}
__name(__PRIVATE_convertOverlayedDocumentMapToDocumentMap, "__PRIVATE_convertOverlayedDocumentMapToDocumentMap");
function __PRIVATE_newOverlayMap() {
  return __PRIVATE_newDocumentKeyMap();
}
__name(__PRIVATE_newOverlayMap, "__PRIVATE_newOverlayMap");
function __PRIVATE_newMutationMap() {
  return __PRIVATE_newDocumentKeyMap();
}
__name(__PRIVATE_newMutationMap, "__PRIVATE_newMutationMap");
function __PRIVATE_newDocumentKeyMap() {
  return new ObjectMap((e2) => e2.toString(), (e2, t2) => e2.isEqual(t2));
}
__name(__PRIVATE_newDocumentKeyMap, "__PRIVATE_newDocumentKeyMap");
const Pt = new SortedMap(DocumentKey.comparator);
const Tt = new SortedSet(DocumentKey.comparator);
function __PRIVATE_documentKeySet(...e2) {
  let t2 = Tt;
  for (const n2 of e2) t2 = t2.add(n2);
  return t2;
}
__name(__PRIVATE_documentKeySet, "__PRIVATE_documentKeySet");
const It = new SortedSet(__PRIVATE_primitiveComparator);
function __PRIVATE_targetIdSet() {
  return It;
}
__name(__PRIVATE_targetIdSet, "__PRIVATE_targetIdSet");
/**
 * @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.
 */
function __PRIVATE_toDouble(e2, t2) {
  if (e2.useProto3Json) {
    if (isNaN(t2)) return {
      doubleValue: "NaN"
    };
    if (t2 === 1 / 0) return {
      doubleValue: "Infinity"
    };
    if (t2 === -1 / 0) return {
      doubleValue: "-Infinity"
    };
  }
  return {
    doubleValue: __PRIVATE_isNegativeZero(t2) ? "-0" : t2
  };
}
__name(__PRIVATE_toDouble, "__PRIVATE_toDouble");
function __PRIVATE_toInteger(e2) {
  return {
    integerValue: "" + e2
  };
}
__name(__PRIVATE_toInteger, "__PRIVATE_toInteger");
function toNumber(e2, t2) {
  return isSafeInteger(t2) ? __PRIVATE_toInteger(t2) : __PRIVATE_toDouble(e2, t2);
}
__name(toNumber, "toNumber");
/**
 * @license
 * Copyright 2018 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 TransformOperation {
  static {
    __name(this, "TransformOperation");
  }
  constructor() {
    this._ = void 0;
  }
}
function __PRIVATE_applyTransformOperationToLocalView(e2, t2, n2) {
  return e2 instanceof __PRIVATE_ServerTimestampTransform ? (/* @__PURE__ */ __name(function serverTimestamp$12(e3, t3) {
    const n3 = {
      fields: {
        [et]: {
          stringValue: Xe
        },
        [nt]: {
          timestampValue: {
            seconds: e3.seconds,
            nanos: e3.nanoseconds
          }
        }
      }
    };
    return t3 && __PRIVATE_isServerTimestamp(t3) && (t3 = __PRIVATE_getPreviousValue(t3)), t3 && (n3.fields[tt$1] = t3), {
      mapValue: n3
    };
  }, "serverTimestamp$1"))(n2, t2) : e2 instanceof __PRIVATE_ArrayUnionTransformOperation ? __PRIVATE_applyArrayUnionTransformOperation(e2, t2) : e2 instanceof __PRIVATE_ArrayRemoveTransformOperation ? __PRIVATE_applyArrayRemoveTransformOperation(e2, t2) : (/* @__PURE__ */ __name(function __PRIVATE_applyNumericIncrementTransformOperationToLocalView(e3, t3) {
    const n3 = __PRIVATE_computeTransformOperationBaseValue(e3, t3), r2 = asNumber(n3) + asNumber(e3.Ie);
    return isInteger(n3) && isInteger(e3.Ie) ? __PRIVATE_toInteger(r2) : __PRIVATE_toDouble(e3.serializer, r2);
  }, "__PRIVATE_applyNumericIncrementTransformOperationToLocalView"))(e2, t2);
}
__name(__PRIVATE_applyTransformOperationToLocalView, "__PRIVATE_applyTransformOperationToLocalView");
function __PRIVATE_applyTransformOperationToRemoteDocument(e2, t2, n2) {
  return e2 instanceof __PRIVATE_ArrayUnionTransformOperation ? __PRIVATE_applyArrayUnionTransformOperation(e2, t2) : e2 instanceof __PRIVATE_ArrayRemoveTransformOperation ? __PRIVATE_applyArrayRemoveTransformOperation(e2, t2) : n2;
}
__name(__PRIVATE_applyTransformOperationToRemoteDocument, "__PRIVATE_applyTransformOperationToRemoteDocument");
function __PRIVATE_computeTransformOperationBaseValue(e2, t2) {
  return e2 instanceof __PRIVATE_NumericIncrementTransformOperation ? (
    /** Returns true if `value` is either an IntegerValue or a DoubleValue. */
    (/* @__PURE__ */ __name(function __PRIVATE_isNumber(e3) {
      return isInteger(e3) || (/* @__PURE__ */ __name(function __PRIVATE_isDouble(e4) {
        return !!e4 && "doubleValue" in e4;
      }, "__PRIVATE_isDouble"))(e3);
    }, "__PRIVATE_isNumber"))(t2) ? t2 : {
      integerValue: 0
    }
  ) : null;
}
__name(__PRIVATE_computeTransformOperationBaseValue, "__PRIVATE_computeTransformOperationBaseValue");
class __PRIVATE_ServerTimestampTransform extends TransformOperation {
  static {
    __name(this, "__PRIVATE_ServerTimestampTransform");
  }
}
class __PRIVATE_ArrayUnionTransformOperation extends TransformOperation {
  static {
    __name(this, "__PRIVATE_ArrayUnionTransformOperation");
  }
  constructor(e2) {
    super(), this.elements = e2;
  }
}
function __PRIVATE_applyArrayUnionTransformOperation(e2, t2) {
  const n2 = __PRIVATE_coercedFieldValuesArray(t2);
  for (const t3 of e2.elements) n2.some((e3) => __PRIVATE_valueEquals(e3, t3)) || n2.push(t3);
  return {
    arrayValue: {
      values: n2
    }
  };
}
__name(__PRIVATE_applyArrayUnionTransformOperation, "__PRIVATE_applyArrayUnionTransformOperation");
class __PRIVATE_ArrayRemoveTransformOperation extends TransformOperation {
  static {
    __name(this, "__PRIVATE_ArrayRemoveTransformOperation");
  }
  constructor(e2) {
    super(), this.elements = e2;
  }
}
function __PRIVATE_applyArrayRemoveTransformOperation(e2, t2) {
  let n2 = __PRIVATE_coercedFieldValuesArray(t2);
  for (const t3 of e2.elements) n2 = n2.filter((e3) => !__PRIVATE_valueEquals(e3, t3));
  return {
    arrayValue: {
      values: n2
    }
  };
}
__name(__PRIVATE_applyArrayRemoveTransformOperation, "__PRIVATE_applyArrayRemoveTransformOperation");
class __PRIVATE_NumericIncrementTransformOperation extends TransformOperation {
  static {
    __name(this, "__PRIVATE_NumericIncrementTransformOperation");
  }
  constructor(e2, t2) {
    super(), this.serializer = e2, this.Ie = t2;
  }
}
function asNumber(e2) {
  return __PRIVATE_normalizeNumber(e2.integerValue || e2.doubleValue);
}
__name(asNumber, "asNumber");
function __PRIVATE_coercedFieldValuesArray(e2) {
  return isArray$a(e2) && e2.arrayValue.values ? e2.arrayValue.values.slice() : [];
}
__name(__PRIVATE_coercedFieldValuesArray, "__PRIVATE_coercedFieldValuesArray");
/**
 * @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 FieldTransform {
  static {
    __name(this, "FieldTransform");
  }
  constructor(e2, t2) {
    this.field = e2, this.transform = t2;
  }
}
function __PRIVATE_fieldTransformEquals(e2, t2) {
  return e2.field.isEqual(t2.field) && (/* @__PURE__ */ __name(function __PRIVATE_transformOperationEquals(e3, t3) {
    return e3 instanceof __PRIVATE_ArrayUnionTransformOperation && t3 instanceof __PRIVATE_ArrayUnionTransformOperation || e3 instanceof __PRIVATE_ArrayRemoveTransformOperation && t3 instanceof __PRIVATE_ArrayRemoveTransformOperation ? __PRIVATE_arrayEquals(e3.elements, t3.elements, __PRIVATE_valueEquals) : e3 instanceof __PRIVATE_NumericIncrementTransformOperation && t3 instanceof __PRIVATE_NumericIncrementTransformOperation ? __PRIVATE_valueEquals(e3.Ie, t3.Ie) : e3 instanceof __PRIVATE_ServerTimestampTransform && t3 instanceof __PRIVATE_ServerTimestampTransform;
  }, "__PRIVATE_transformOperationEquals"))(e2.transform, t2.transform);
}
__name(__PRIVATE_fieldTransformEquals, "__PRIVATE_fieldTransformEquals");
class MutationResult {
  static {
    __name(this, "MutationResult");
  }
  constructor(e2, t2) {
    this.version = e2, this.transformResults = t2;
  }
}
class Precondition {
  static {
    __name(this, "Precondition");
  }
  constructor(e2, t2) {
    this.updateTime = e2, this.exists = t2;
  }
  /** Creates a new empty Precondition. */
  static none() {
    return new Precondition();
  }
  /** Creates a new Precondition with an exists flag. */
  static exists(e2) {
    return new Precondition(void 0, e2);
  }
  /** Creates a new Precondition based on a version a document exists at. */
  static updateTime(e2) {
    return new Precondition(e2);
  }
  /** Returns whether this Precondition is empty. */
  get isNone() {
    return void 0 === this.updateTime && void 0 === this.exists;
  }
  isEqual(e2) {
    return this.exists === e2.exists && (this.updateTime ? !!e2.updateTime && this.updateTime.isEqual(e2.updateTime) : !e2.updateTime);
  }
}
function __PRIVATE_preconditionIsValidForDocument(e2, t2) {
  return void 0 !== e2.updateTime ? t2.isFoundDocument() && t2.version.isEqual(e2.updateTime) : void 0 === e2.exists || e2.exists === t2.isFoundDocument();
}
__name(__PRIVATE_preconditionIsValidForDocument, "__PRIVATE_preconditionIsValidForDocument");
class Mutation {
  static {
    __name(this, "Mutation");
  }
}
function __PRIVATE_calculateOverlayMutation(e2, t2) {
  if (!e2.hasLocalMutations || t2 && 0 === t2.fields.length) return null;
  if (null === t2) return e2.isNoDocument() ? new __PRIVATE_DeleteMutation(e2.key, Precondition.none()) : new __PRIVATE_SetMutation(e2.key, e2.data, Precondition.none());
  {
    const n2 = e2.data, r2 = ObjectValue.empty();
    let i2 = new SortedSet(FieldPath$1.comparator);
    for (let e3 of t2.fields) if (!i2.has(e3)) {
      let t3 = n2.field(e3);
      null === t3 && e3.length > 1 && (e3 = e3.popLast(), t3 = n2.field(e3)), null === t3 ? r2.delete(e3) : r2.set(e3, t3), i2 = i2.add(e3);
    }
    return new __PRIVATE_PatchMutation(e2.key, r2, new FieldMask(i2.toArray()), Precondition.none());
  }
}
__name(__PRIVATE_calculateOverlayMutation, "__PRIVATE_calculateOverlayMutation");
function __PRIVATE_mutationApplyToRemoteDocument(e2, t2, n2) {
  e2 instanceof __PRIVATE_SetMutation ? (/* @__PURE__ */ __name(function __PRIVATE_setMutationApplyToRemoteDocument(e3, t3, n3) {
    const r2 = e3.value.clone(), i2 = __PRIVATE_serverTransformResults(e3.fieldTransforms, t3, n3.transformResults);
    r2.setAll(i2), t3.convertToFoundDocument(n3.version, r2).setHasCommittedMutations();
  }, "__PRIVATE_setMutationApplyToRemoteDocument"))(e2, t2, n2) : e2 instanceof __PRIVATE_PatchMutation ? (/* @__PURE__ */ __name(function __PRIVATE_patchMutationApplyToRemoteDocument(e3, t3, n3) {
    if (!__PRIVATE_preconditionIsValidForDocument(e3.precondition, t3))
      return void t3.convertToUnknownDocument(n3.version);
    const r2 = __PRIVATE_serverTransformResults(e3.fieldTransforms, t3, n3.transformResults), i2 = t3.data;
    i2.setAll(__PRIVATE_getPatch(e3)), i2.setAll(r2), t3.convertToFoundDocument(n3.version, i2).setHasCommittedMutations();
  }, "__PRIVATE_patchMutationApplyToRemoteDocument"))(e2, t2, n2) : (/* @__PURE__ */ __name(function __PRIVATE_deleteMutationApplyToRemoteDocument(e3, t3, n3) {
    t3.convertToNoDocument(n3.version).setHasCommittedMutations();
  }, "__PRIVATE_deleteMutationApplyToRemoteDocument"))(0, t2, n2);
}
__name(__PRIVATE_mutationApplyToRemoteDocument, "__PRIVATE_mutationApplyToRemoteDocument");
function __PRIVATE_mutationApplyToLocalView(e2, t2, n2, r2) {
  return e2 instanceof __PRIVATE_SetMutation ? (/* @__PURE__ */ __name(function __PRIVATE_setMutationApplyToLocalView(e3, t3, n3, r3) {
    if (!__PRIVATE_preconditionIsValidForDocument(e3.precondition, t3))
      return n3;
    const i2 = e3.value.clone(), s2 = __PRIVATE_localTransformResults(e3.fieldTransforms, r3, t3);
    return i2.setAll(s2), t3.convertToFoundDocument(t3.version, i2).setHasLocalMutations(), null;
  }, "__PRIVATE_setMutationApplyToLocalView"))(e2, t2, n2, r2) : e2 instanceof __PRIVATE_PatchMutation ? (/* @__PURE__ */ __name(function __PRIVATE_patchMutationApplyToLocalView(e3, t3, n3, r3) {
    if (!__PRIVATE_preconditionIsValidForDocument(e3.precondition, t3)) return n3;
    const i2 = __PRIVATE_localTransformResults(e3.fieldTransforms, r3, t3), s2 = t3.data;
    if (s2.setAll(__PRIVATE_getPatch(e3)), s2.setAll(i2), t3.convertToFoundDocument(t3.version, s2).setHasLocalMutations(), null === n3) return null;
    return n3.unionWith(e3.fieldMask.fields).unionWith(e3.fieldTransforms.map((e4) => e4.field));
  }, "__PRIVATE_patchMutationApplyToLocalView"))(e2, t2, n2, r2) : (/* @__PURE__ */ __name(function __PRIVATE_deleteMutationApplyToLocalView(e3, t3, n3) {
    if (__PRIVATE_preconditionIsValidForDocument(e3.precondition, t3)) return t3.convertToNoDocument(t3.version).setHasLocalMutations(), null;
    return n3;
  }, "__PRIVATE_deleteMutationApplyToLocalView"))(e2, t2, n2);
}
__name(__PRIVATE_mutationApplyToLocalView, "__PRIVATE_mutationApplyToLocalView");
function __PRIVATE_mutationExtractBaseValue(e2, t2) {
  let n2 = null;
  for (const r2 of e2.fieldTransforms) {
    const e3 = t2.data.field(r2.field), i2 = __PRIVATE_computeTransformOperationBaseValue(r2.transform, e3 || null);
    null != i2 && (null === n2 && (n2 = ObjectValue.empty()), n2.set(r2.field, i2));
  }
  return n2 || null;
}
__name(__PRIVATE_mutationExtractBaseValue, "__PRIVATE_mutationExtractBaseValue");
function __PRIVATE_mutationEquals(e2, t2) {
  return e2.type === t2.type && (!!e2.key.isEqual(t2.key) && (!!e2.precondition.isEqual(t2.precondition) && (!!(/* @__PURE__ */ __name(function __PRIVATE_fieldTransformsAreEqual(e3, t3) {
    return void 0 === e3 && void 0 === t3 || !(!e3 || !t3) && __PRIVATE_arrayEquals(e3, t3, (e4, t4) => __PRIVATE_fieldTransformEquals(e4, t4));
  }, "__PRIVATE_fieldTransformsAreEqual"))(e2.fieldTransforms, t2.fieldTransforms) && (0 === e2.type ? e2.value.isEqual(t2.value) : 1 !== e2.type || e2.data.isEqual(t2.data) && e2.fieldMask.isEqual(t2.fieldMask)))));
}
__name(__PRIVATE_mutationEquals, "__PRIVATE_mutationEquals");
class __PRIVATE_SetMutation extends Mutation {
  static {
    __name(this, "__PRIVATE_SetMutation");
  }
  constructor(e2, t2, n2, r2 = []) {
    super(), this.key = e2, this.value = t2, this.precondition = n2, this.fieldTransforms = r2, this.type = 0;
  }
  getFieldMask() {
    return null;
  }
}
class __PRIVATE_PatchMutation extends Mutation {
  static {
    __name(this, "__PRIVATE_PatchMutation");
  }
  constructor(e2, t2, n2, r2, i2 = []) {
    super(), this.key = e2, this.data = t2, this.fieldMask = n2, this.precondition = r2, this.fieldTransforms = i2, this.type = 1;
  }
  getFieldMask() {
    return this.fieldMask;
  }
}
function __PRIVATE_getPatch(e2) {
  const t2 = /* @__PURE__ */ new Map();
  return e2.fieldMask.fields.forEach((n2) => {
    if (!n2.isEmpty()) {
      const r2 = e2.data.field(n2);
      t2.set(n2, r2);
    }
  }), t2;
}
__name(__PRIVATE_getPatch, "__PRIVATE_getPatch");
function __PRIVATE_serverTransformResults(e2, t2, n2) {
  const r2 = /* @__PURE__ */ new Map();
  __PRIVATE_hardAssert(e2.length === n2.length);
  for (let i2 = 0; i2 < n2.length; i2++) {
    const s2 = e2[i2], o2 = s2.transform, _2 = t2.data.field(s2.field);
    r2.set(s2.field, __PRIVATE_applyTransformOperationToRemoteDocument(o2, _2, n2[i2]));
  }
  return r2;
}
__name(__PRIVATE_serverTransformResults, "__PRIVATE_serverTransformResults");
function __PRIVATE_localTransformResults(e2, t2, n2) {
  const r2 = /* @__PURE__ */ new Map();
  for (const i2 of e2) {
    const e3 = i2.transform, s2 = n2.data.field(i2.field);
    r2.set(i2.field, __PRIVATE_applyTransformOperationToLocalView(e3, s2, t2));
  }
  return r2;
}
__name(__PRIVATE_localTransformResults, "__PRIVATE_localTransformResults");
class __PRIVATE_DeleteMutation extends Mutation {
  static {
    __name(this, "__PRIVATE_DeleteMutation");
  }
  constructor(e2, t2) {
    super(), this.key = e2, this.precondition = t2, this.type = 2, this.fieldTransforms = [];
  }
  getFieldMask() {
    return null;
  }
}
class __PRIVATE_VerifyMutation extends Mutation {
  static {
    __name(this, "__PRIVATE_VerifyMutation");
  }
  constructor(e2, t2) {
    super(), this.key = e2, this.precondition = t2, this.type = 3, this.fieldTransforms = [];
  }
  getFieldMask() {
    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.
 */
class MutationBatch {
  static {
    __name(this, "MutationBatch");
  }
  /**
   * @param batchId - The unique ID of this mutation batch.
   * @param localWriteTime - The original write time of this mutation.
   * @param baseMutations - Mutations that are used to populate the base
   * values when this mutation is applied locally. This can be used to locally
   * overwrite values that are persisted in the remote document cache. Base
   * mutations are never sent to the backend.
   * @param mutations - The user-provided mutations in this mutation batch.
   * User-provided mutations are applied both locally and remotely on the
   * backend.
   */
  constructor(e2, t2, n2, r2) {
    this.batchId = e2, this.localWriteTime = t2, this.baseMutations = n2, this.mutations = r2;
  }
  /**
   * Applies all the mutations in this MutationBatch to the specified document
   * to compute the state of the remote document
   *
   * @param document - The document to apply mutations to.
   * @param batchResult - The result of applying the MutationBatch to the
   * backend.
   */
  applyToRemoteDocument(e2, t2) {
    const n2 = t2.mutationResults;
    for (let t3 = 0; t3 < this.mutations.length; t3++) {
      const r2 = this.mutations[t3];
      if (r2.key.isEqual(e2.key)) {
        __PRIVATE_mutationApplyToRemoteDocument(r2, e2, n2[t3]);
      }
    }
  }
  /**
   * Computes the local view of a document given all the mutations in this
   * batch.
   *
   * @param document - The document to apply mutations to.
   * @param mutatedFields - Fields that have been updated before applying this mutation batch.
   * @returns A `FieldMask` representing all the fields that are mutated.
   */
  applyToLocalView(e2, t2) {
    for (const n2 of this.baseMutations) n2.key.isEqual(e2.key) && (t2 = __PRIVATE_mutationApplyToLocalView(n2, e2, t2, this.localWriteTime));
    for (const n2 of this.mutations) n2.key.isEqual(e2.key) && (t2 = __PRIVATE_mutationApplyToLocalView(n2, e2, t2, this.localWriteTime));
    return t2;
  }
  /**
   * Computes the local view for all provided documents given the mutations in
   * this batch. Returns a `DocumentKey` to `Mutation` map which can be used to
   * replace all the mutation applications.
   */
  applyToLocalDocumentSet(e2, t2) {
    const n2 = __PRIVATE_newMutationMap();
    return this.mutations.forEach((r2) => {
      const i2 = e2.get(r2.key), s2 = i2.overlayedDocument;
      let o2 = this.applyToLocalView(s2, i2.mutatedFields);
      o2 = t2.has(r2.key) ? null : o2;
      const _2 = __PRIVATE_calculateOverlayMutation(s2, o2);
      null !== _2 && n2.set(r2.key, _2), s2.isValidDocument() || s2.convertToNoDocument(SnapshotVersion.min());
    }), n2;
  }
  keys() {
    return this.mutations.reduce((e2, t2) => e2.add(t2.key), __PRIVATE_documentKeySet());
  }
  isEqual(e2) {
    return this.batchId === e2.batchId && __PRIVATE_arrayEquals(this.mutations, e2.mutations, (e3, t2) => __PRIVATE_mutationEquals(e3, t2)) && __PRIVATE_arrayEquals(this.baseMutations, e2.baseMutations, (e3, t2) => __PRIVATE_mutationEquals(e3, t2));
  }
}
class MutationBatchResult {
  static {
    __name(this, "MutationBatchResult");
  }
  constructor(e2, t2, n2, r2) {
    this.batch = e2, this.commitVersion = t2, this.mutationResults = n2, this.docVersions = r2;
  }
  /**
   * Creates a new MutationBatchResult for the given batch and results. There
   * must be one result for each mutation in the batch. This static factory
   * caches a document=&gt;version mapping (docVersions).
   */
  static from(e2, t2, n2) {
    __PRIVATE_hardAssert(e2.mutations.length === n2.length);
    let r2 = (/* @__PURE__ */ __name(function __PRIVATE_documentVersionMap() {
      return Pt;
    }, "__PRIVATE_documentVersionMap"))();
    const i2 = e2.mutations;
    for (let e3 = 0; e3 < i2.length; e3++) r2 = r2.insert(i2[e3].key, n2[e3].version);
    return new MutationBatchResult(e2, t2, n2, r2);
  }
}
/**
 * @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.
 */
class Overlay {
  static {
    __name(this, "Overlay");
  }
  constructor(e2, t2) {
    this.largestBatchId = e2, this.mutation = t2;
  }
  getKey() {
    return this.mutation.key;
  }
  isEqual(e2) {
    return null !== e2 && this.mutation === e2.mutation;
  }
  toString() {
    return `Overlay{
      largestBatchId: ${this.largestBatchId},
      mutation: ${this.mutation.toString()}
    }`;
  }
}
/**
 * @license
 * Copyright 2023 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 __PRIVATE_AggregateImpl {
  static {
    __name(this, "__PRIVATE_AggregateImpl");
  }
  constructor(e2, t2, n2) {
    this.alias = e2, this.aggregateType = t2, this.fieldPath = n2;
  }
}
/**
 * @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 ExistenceFilter {
  static {
    __name(this, "ExistenceFilter");
  }
  constructor(e2, t2) {
    this.count = e2, this.unchangedNames = t2;
  }
}
/**
 * @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 Et, dt$1;
function __PRIVATE_isPermanentError(e2) {
  switch (e2) {
    case C.OK:
      return fail();
    case C.CANCELLED:
    case C.UNKNOWN:
    case C.DEADLINE_EXCEEDED:
    case C.RESOURCE_EXHAUSTED:
    case C.INTERNAL:
    case C.UNAVAILABLE:
    case C.UNAUTHENTICATED:
      return false;
    case C.INVALID_ARGUMENT:
    case C.NOT_FOUND:
    case C.ALREADY_EXISTS:
    case C.PERMISSION_DENIED:
    case C.FAILED_PRECONDITION:
    case C.ABORTED:
    case C.OUT_OF_RANGE:
    case C.UNIMPLEMENTED:
    case C.DATA_LOSS:
      return true;
    default:
      return fail();
  }
}
__name(__PRIVATE_isPermanentError, "__PRIVATE_isPermanentError");
function __PRIVATE_mapCodeFromRpcCode(e2) {
  if (void 0 === e2)
    return __PRIVATE_logError("GRPC error has no .code"), C.UNKNOWN;
  switch (e2) {
    case Et.OK:
      return C.OK;
    case Et.CANCELLED:
      return C.CANCELLED;
    case Et.UNKNOWN:
      return C.UNKNOWN;
    case Et.DEADLINE_EXCEEDED:
      return C.DEADLINE_EXCEEDED;
    case Et.RESOURCE_EXHAUSTED:
      return C.RESOURCE_EXHAUSTED;
    case Et.INTERNAL:
      return C.INTERNAL;
    case Et.UNAVAILABLE:
      return C.UNAVAILABLE;
    case Et.UNAUTHENTICATED:
      return C.UNAUTHENTICATED;
    case Et.INVALID_ARGUMENT:
      return C.INVALID_ARGUMENT;
    case Et.NOT_FOUND:
      return C.NOT_FOUND;
    case Et.ALREADY_EXISTS:
      return C.ALREADY_EXISTS;
    case Et.PERMISSION_DENIED:
      return C.PERMISSION_DENIED;
    case Et.FAILED_PRECONDITION:
      return C.FAILED_PRECONDITION;
    case Et.ABORTED:
      return C.ABORTED;
    case Et.OUT_OF_RANGE:
      return C.OUT_OF_RANGE;
    case Et.UNIMPLEMENTED:
      return C.UNIMPLEMENTED;
    case Et.DATA_LOSS:
      return C.DATA_LOSS;
    default:
      return fail();
  }
}
__name(__PRIVATE_mapCodeFromRpcCode, "__PRIVATE_mapCodeFromRpcCode");
(dt$1 = Et || (Et = {}))[dt$1.OK = 0] = "OK", dt$1[dt$1.CANCELLED = 1] = "CANCELLED", dt$1[dt$1.UNKNOWN = 2] = "UNKNOWN", dt$1[dt$1.INVALID_ARGUMENT = 3] = "INVALID_ARGUMENT", dt$1[dt$1.DEADLINE_EXCEEDED = 4] = "DEADLINE_EXCEEDED", dt$1[dt$1.NOT_FOUND = 5] = "NOT_FOUND", dt$1[dt$1.ALREADY_EXISTS = 6] = "ALREADY_EXISTS", dt$1[dt$1.PERMISSION_DENIED = 7] = "PERMISSION_DENIED", dt$1[dt$1.UNAUTHENTICATED = 16] = "UNAUTHENTICATED", dt$1[dt$1.RESOURCE_EXHAUSTED = 8] = "RESOURCE_EXHAUSTED", dt$1[dt$1.FAILED_PRECONDITION = 9] = "FAILED_PRECONDITION", dt$1[dt$1.ABORTED = 10] = "ABORTED", dt$1[dt$1.OUT_OF_RANGE = 11] = "OUT_OF_RANGE", dt$1[dt$1.UNIMPLEMENTED = 12] = "UNIMPLEMENTED", dt$1[dt$1.INTERNAL = 13] = "INTERNAL", dt$1[dt$1.UNAVAILABLE = 14] = "UNAVAILABLE", dt$1[dt$1.DATA_LOSS = 15] = "DATA_LOSS";
/**
 * @license
 * Copyright 2023 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 At = null;
/**
 * @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 Rt = new Integer([4294967295, 4294967295], 0);
function __PRIVATE_getMd5HashValue(e2) {
  const t2 = __PRIVATE_newTextEncoder().encode(e2), n2 = new Md5();
  return n2.update(t2), new Uint8Array(n2.digest());
}
__name(__PRIVATE_getMd5HashValue, "__PRIVATE_getMd5HashValue");
function __PRIVATE_get64BitUints(e2) {
  const t2 = new DataView(e2.buffer), n2 = t2.getUint32(
    0,
    /* littleEndian= */
    true
  ), r2 = t2.getUint32(
    4,
    /* littleEndian= */
    true
  ), i2 = t2.getUint32(
    8,
    /* littleEndian= */
    true
  ), s2 = t2.getUint32(
    12,
    /* littleEndian= */
    true
  );
  return [new Integer([n2, r2], 0), new Integer([i2, s2], 0)];
}
__name(__PRIVATE_get64BitUints, "__PRIVATE_get64BitUints");
class BloomFilter {
  static {
    __name(this, "BloomFilter");
  }
  constructor(e2, t2, n2) {
    if (this.bitmap = e2, this.padding = t2, this.hashCount = n2, t2 < 0 || t2 >= 8) throw new __PRIVATE_BloomFilterError(`Invalid padding: ${t2}`);
    if (n2 < 0) throw new __PRIVATE_BloomFilterError(`Invalid hash count: ${n2}`);
    if (e2.length > 0 && 0 === this.hashCount)
      throw new __PRIVATE_BloomFilterError(`Invalid hash count: ${n2}`);
    if (0 === e2.length && 0 !== t2)
      throw new __PRIVATE_BloomFilterError(`Invalid padding when bitmap length is 0: ${t2}`);
    this.Ee = 8 * e2.length - t2, // Set the bit count in Integer to avoid repetition in mightContain().
    this.de = Integer.fromNumber(this.Ee);
  }
  // Calculate the ith hash value based on the hashed 64bit integers,
  // and calculate its corresponding bit index in the bitmap to be checked.
  Ae(e2, t2, n2) {
    let r2 = e2.add(t2.multiply(Integer.fromNumber(n2)));
    return 1 === r2.compare(Rt) && (r2 = new Integer([r2.getBits(0), r2.getBits(1)], 0)), r2.modulo(this.de).toNumber();
  }
  // Return whether the bit on the given index in the bitmap is set to 1.
  Re(e2) {
    return !!(this.bitmap[Math.floor(e2 / 8)] & 1 << e2 % 8);
  }
  mightContain(e2) {
    if (0 === this.Ee) return false;
    const t2 = __PRIVATE_getMd5HashValue(e2), [n2, r2] = __PRIVATE_get64BitUints(t2);
    for (let e3 = 0; e3 < this.hashCount; e3++) {
      const t3 = this.Ae(n2, r2, e3);
      if (!this.Re(t3)) return false;
    }
    return true;
  }
  /** Create bloom filter for testing purposes only. */
  static create(e2, t2, n2) {
    const r2 = e2 % 8 == 0 ? 0 : 8 - e2 % 8, i2 = new Uint8Array(Math.ceil(e2 / 8)), s2 = new BloomFilter(i2, r2, t2);
    return n2.forEach((e3) => s2.insert(e3)), s2;
  }
  insert(e2) {
    if (0 === this.Ee) return;
    const t2 = __PRIVATE_getMd5HashValue(e2), [n2, r2] = __PRIVATE_get64BitUints(t2);
    for (let e3 = 0; e3 < this.hashCount; e3++) {
      const t3 = this.Ae(n2, r2, e3);
      this.Ve(t3);
    }
  }
  Ve(e2) {
    const t2 = Math.floor(e2 / 8), n2 = e2 % 8;
    this.bitmap[t2] |= 1 << n2;
  }
}
class __PRIVATE_BloomFilterError extends Error {
  static {
    __name(this, "__PRIVATE_BloomFilterError");
  }
  constructor() {
    super(...arguments), this.name = "BloomFilterError";
  }
}
/**
 * @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 RemoteEvent {
  static {
    __name(this, "RemoteEvent");
  }
  constructor(e2, t2, n2, r2, i2) {
    this.snapshotVersion = e2, this.targetChanges = t2, this.targetMismatches = n2, this.documentUpdates = r2, this.resolvedLimboDocuments = i2;
  }
  /**
   * HACK: Views require RemoteEvents in order to determine whether the view is
   * CURRENT, but secondary tabs don't receive remote events. So this method is
   * used to create a synthesized RemoteEvent that can be used to apply a
   * CURRENT status change to a View, for queries executed in a different tab.
   */
  // PORTING NOTE: Multi-tab only
  static createSynthesizedRemoteEventForCurrentChange(e2, t2, n2) {
    const r2 = /* @__PURE__ */ new Map();
    return r2.set(e2, TargetChange.createSynthesizedTargetChangeForCurrentChange(e2, t2, n2)), new RemoteEvent(SnapshotVersion.min(), r2, new SortedMap(__PRIVATE_primitiveComparator), __PRIVATE_mutableDocumentMap(), __PRIVATE_documentKeySet());
  }
}
class TargetChange {
  static {
    __name(this, "TargetChange");
  }
  constructor(e2, t2, n2, r2, i2) {
    this.resumeToken = e2, this.current = t2, this.addedDocuments = n2, this.modifiedDocuments = r2, this.removedDocuments = i2;
  }
  /**
   * This method is used to create a synthesized TargetChanges that can be used to
   * apply a CURRENT status change to a View (for queries executed in a different
   * tab) or for new queries (to raise snapshots with correct CURRENT status).
   */
  static createSynthesizedTargetChangeForCurrentChange(e2, t2, n2) {
    return new TargetChange(n2, t2, __PRIVATE_documentKeySet(), __PRIVATE_documentKeySet(), __PRIVATE_documentKeySet());
  }
}
/**
 * @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 __PRIVATE_DocumentWatchChange {
  static {
    __name(this, "__PRIVATE_DocumentWatchChange");
  }
  constructor(e2, t2, n2, r2) {
    this.me = e2, this.removedTargetIds = t2, this.key = n2, this.fe = r2;
  }
}
class __PRIVATE_ExistenceFilterChange {
  static {
    __name(this, "__PRIVATE_ExistenceFilterChange");
  }
  constructor(e2, t2) {
    this.targetId = e2, this.ge = t2;
  }
}
class __PRIVATE_WatchTargetChange {
  static {
    __name(this, "__PRIVATE_WatchTargetChange");
  }
  constructor(e2, t2, n2 = ByteString.EMPTY_BYTE_STRING, r2 = null) {
    this.state = e2, this.targetIds = t2, this.resumeToken = n2, this.cause = r2;
  }
}
class __PRIVATE_TargetState {
  static {
    __name(this, "__PRIVATE_TargetState");
  }
  constructor() {
    this.pe = 0, /**
     * Keeps track of the document changes since the last raised snapshot.
     *
     * These changes are continuously updated as we receive document updates and
     * always reflect the current set of changes against the last issued snapshot.
     */
    this.ye = __PRIVATE_snapshotChangesMap(), /** See public getters for explanations of these fields. */
    this.we = ByteString.EMPTY_BYTE_STRING, this.Se = false, /**
     * Whether this target state should be included in the next snapshot. We
     * initialize to true so that newly-added targets are included in the next
     * RemoteEvent.
     */
    this.be = true;
  }
  /**
   * Whether this target has been marked 'current'.
   *
   * 'Current' has special meaning in the RPC protocol: It implies that the
   * Watch backend has sent us all changes up to the point at which the target
   * was added and that the target is consistent with the rest of the watch
   * stream.
   */
  get current() {
    return this.Se;
  }
  /** The last resume token sent to us for this target. */
  get resumeToken() {
    return this.we;
  }
  /** Whether this target has pending target adds or target removes. */
  get De() {
    return 0 !== this.pe;
  }
  /** Whether we have modified any state that should trigger a snapshot. */
  get ve() {
    return this.be;
  }
  /**
   * Applies the resume token to the TargetChange, but only when it has a new
   * value. Empty resumeTokens are discarded.
   */
  Ce(e2) {
    e2.approximateByteSize() > 0 && (this.be = true, this.we = e2);
  }
  /**
   * Creates a target change from the current set of changes.
   *
   * To reset the document changes after raising this snapshot, call
   * `clearPendingChanges()`.
   */
  Fe() {
    let e2 = __PRIVATE_documentKeySet(), t2 = __PRIVATE_documentKeySet(), n2 = __PRIVATE_documentKeySet();
    return this.ye.forEach((r2, i2) => {
      switch (i2) {
        case 0:
          e2 = e2.add(r2);
          break;
        case 2:
          t2 = t2.add(r2);
          break;
        case 1:
          n2 = n2.add(r2);
          break;
        default:
          fail();
      }
    }), new TargetChange(this.we, this.Se, e2, t2, n2);
  }
  /**
   * Resets the document changes and sets `hasPendingChanges` to false.
   */
  Me() {
    this.be = false, this.ye = __PRIVATE_snapshotChangesMap();
  }
  xe(e2, t2) {
    this.be = true, this.ye = this.ye.insert(e2, t2);
  }
  Oe(e2) {
    this.be = true, this.ye = this.ye.remove(e2);
  }
  Ne() {
    this.pe += 1;
  }
  Be() {
    this.pe -= 1, __PRIVATE_hardAssert(this.pe >= 0);
  }
  Le() {
    this.be = true, this.Se = true;
  }
}
class __PRIVATE_WatchChangeAggregator {
  static {
    __name(this, "__PRIVATE_WatchChangeAggregator");
  }
  constructor(e2) {
    this.ke = e2, /** The internal state of all tracked targets. */
    this.qe = /* @__PURE__ */ new Map(), /** Keeps track of the documents to update since the last raised snapshot. */
    this.Qe = __PRIVATE_mutableDocumentMap(), this.$e = __PRIVATE_documentTargetMap(), /** A mapping of document keys to their set of target IDs. */
    this.Ue = __PRIVATE_documentTargetMap(), /**
     * A map of targets with existence filter mismatches. These targets are
     * known to be inconsistent and their listens needs to be re-established by
     * RemoteStore.
     */
    this.Ke = new SortedMap(__PRIVATE_primitiveComparator);
  }
  /**
   * Processes and adds the DocumentWatchChange to the current set of changes.
   */
  We(e2) {
    for (const t2 of e2.me) e2.fe && e2.fe.isFoundDocument() ? this.Ge(t2, e2.fe) : this.ze(t2, e2.key, e2.fe);
    for (const t2 of e2.removedTargetIds) this.ze(t2, e2.key, e2.fe);
  }
  /** Processes and adds the WatchTargetChange to the current set of changes. */
  je(e2) {
    this.forEachTarget(e2, (t2) => {
      const n2 = this.He(t2);
      switch (e2.state) {
        case 0:
          this.Je(t2) && n2.Ce(e2.resumeToken);
          break;
        case 1:
          n2.Be(), n2.De || // We have a freshly added target, so we need to reset any state
          // that we had previously. This can happen e.g. when remove and add
          // back a target for existence filter mismatches.
          n2.Me(), n2.Ce(e2.resumeToken);
          break;
        case 2:
          n2.Be(), n2.De || this.removeTarget(t2);
          break;
        case 3:
          this.Je(t2) && (n2.Le(), n2.Ce(e2.resumeToken));
          break;
        case 4:
          this.Je(t2) && // Reset the target and synthesizes removes for all existing
          // documents. The backend will re-add any documents that still
          // match the target before it sends the next global snapshot.
          (this.Ye(t2), n2.Ce(e2.resumeToken));
          break;
        default:
          fail();
      }
    });
  }
  /**
   * Iterates over all targetIds that the watch change applies to: either the
   * targetIds explicitly listed in the change or the targetIds of all currently
   * active targets.
   */
  forEachTarget(e2, t2) {
    e2.targetIds.length > 0 ? e2.targetIds.forEach(t2) : this.qe.forEach((e3, n2) => {
      this.Je(n2) && t2(n2);
    });
  }
  /**
   * Handles existence filters and synthesizes deletes for filter mismatches.
   * Targets that are invalidated by filter mismatches are added to
   * `pendingTargetResets`.
   */
  Ze(e2) {
    const t2 = e2.targetId, n2 = e2.ge.count, r2 = this.Xe(t2);
    if (r2) {
      const i2 = r2.target;
      if (__PRIVATE_targetIsDocumentTarget(i2)) if (0 === n2) {
        const e3 = new DocumentKey(i2.path);
        this.ze(t2, e3, MutableDocument.newNoDocument(e3, SnapshotVersion.min()));
      } else __PRIVATE_hardAssert(1 === n2);
      else {
        const r3 = this.et(t2);
        if (r3 !== n2) {
          const n3 = this.tt(e2), i3 = n3 ? this.nt(n3, e2, r3) : 1;
          if (0 !== i3) {
            this.Ye(t2);
            const e3 = 2 === i3 ? "TargetPurposeExistenceFilterMismatchBloom" : "TargetPurposeExistenceFilterMismatch";
            this.Ke = this.Ke.insert(t2, e3);
          }
          null == At || At.rt((/* @__PURE__ */ __name(function __PRIVATE_createExistenceFilterMismatchInfoForTestingHooks(e3, t3, n4, r4, i4) {
            var s2, o2, _2, a2, u2, c2;
            const l2 = {
              localCacheCount: e3,
              existenceFilterCount: t3.count,
              databaseId: n4.database,
              projectId: n4.projectId
            }, h2 = t3.unchangedNames;
            h2 && (l2.bloomFilter = {
              applied: 0 === i4,
              hashCount: null !== (s2 = null == h2 ? void 0 : h2.hashCount) && void 0 !== s2 ? s2 : 0,
              bitmapLength: null !== (a2 = null === (_2 = null === (o2 = null == h2 ? void 0 : h2.bits) || void 0 === o2 ? void 0 : o2.bitmap) || void 0 === _2 ? void 0 : _2.length) && void 0 !== a2 ? a2 : 0,
              padding: null !== (c2 = null === (u2 = null == h2 ? void 0 : h2.bits) || void 0 === u2 ? void 0 : u2.padding) && void 0 !== c2 ? c2 : 0,
              mightContain: /* @__PURE__ */ __name((e4) => {
                var t4;
                return null !== (t4 = null == r4 ? void 0 : r4.mightContain(e4)) && void 0 !== t4 && t4;
              }, "mightContain")
            });
            return l2;
          }, "__PRIVATE_createExistenceFilterMismatchInfoForTestingHooks"))(r3, e2.ge, this.ke.it(), n3, i3));
        }
      }
    }
  }
  /**
   * Parse the bloom filter from the "unchanged_names" field of an existence
   * filter.
   */
  tt(e2) {
    const t2 = e2.ge.unchangedNames;
    if (!t2 || !t2.bits) return null;
    const { bits: { bitmap: n2 = "", padding: r2 = 0 }, hashCount: i2 = 0 } = t2;
    let s2, o2;
    try {
      s2 = __PRIVATE_normalizeByteString(n2).toUint8Array();
    } catch (e3) {
      if (e3 instanceof __PRIVATE_Base64DecodeError) return __PRIVATE_logWarn("Decoding the base64 bloom filter in existence filter failed (" + e3.message + "); ignoring the bloom filter and falling back to full re-query."), null;
      throw e3;
    }
    try {
      o2 = new BloomFilter(s2, r2, i2);
    } catch (e3) {
      return __PRIVATE_logWarn(e3 instanceof __PRIVATE_BloomFilterError ? "BloomFilter error: " : "Applying bloom filter failed: ", e3), null;
    }
    return 0 === o2.Ee ? null : o2;
  }
  /**
   * Apply bloom filter to remove the deleted documents, and return the
   * application status.
   */
  nt(e2, t2, n2) {
    return t2.ge.count === n2 - this.st(e2, t2.targetId) ? 0 : 2;
  }
  /**
   * Filter out removed documents based on bloom filter membership result and
   * return number of documents removed.
   */
  st(e2, t2) {
    const n2 = this.ke.getRemoteKeysForTarget(t2);
    let r2 = 0;
    return n2.forEach((n3) => {
      const i2 = this.ke.it(), s2 = `projects/${i2.projectId}/databases/${i2.database}/documents/${n3.path.canonicalString()}`;
      e2.mightContain(s2) || (this.ze(
        t2,
        n3,
        /*updatedDocument=*/
        null
      ), r2++);
    }), r2;
  }
  /**
   * Converts the currently accumulated state into a remote event at the
   * provided snapshot version. Resets the accumulated changes before returning.
   */
  ot(e2) {
    const t2 = /* @__PURE__ */ new Map();
    this.qe.forEach((n3, r3) => {
      const i2 = this.Xe(r3);
      if (i2) {
        if (n3.current && __PRIVATE_targetIsDocumentTarget(i2.target)) {
          const t3 = new DocumentKey(i2.target.path);
          this._t(t3).has(r3) || this.ut(r3, t3) || this.ze(r3, t3, MutableDocument.newNoDocument(t3, e2));
        }
        n3.ve && (t2.set(r3, n3.Fe()), n3.Me());
      }
    });
    let n2 = __PRIVATE_documentKeySet();
    this.Ue.forEach((e3, t3) => {
      let r3 = true;
      t3.forEachWhile((e4) => {
        const t4 = this.Xe(e4);
        return !t4 || "TargetPurposeLimboResolution" === t4.purpose || (r3 = false, false);
      }), r3 && (n2 = n2.add(e3));
    }), this.Qe.forEach((t3, n3) => n3.setReadTime(e2));
    const r2 = new RemoteEvent(e2, t2, this.Ke, this.Qe, n2);
    return this.Qe = __PRIVATE_mutableDocumentMap(), this.$e = __PRIVATE_documentTargetMap(), this.Ue = __PRIVATE_documentTargetMap(), this.Ke = new SortedMap(__PRIVATE_primitiveComparator), r2;
  }
  /**
   * Adds the provided document to the internal list of document updates and
   * its document key to the given target's mapping.
   */
  // Visible for testing.
  Ge(e2, t2) {
    if (!this.Je(e2)) return;
    const n2 = this.ut(e2, t2.key) ? 2 : 0;
    this.He(e2).xe(t2.key, n2), this.Qe = this.Qe.insert(t2.key, t2), this.$e = this.$e.insert(t2.key, this._t(t2.key).add(e2)), this.Ue = this.Ue.insert(t2.key, this.ct(t2.key).add(e2));
  }
  /**
   * Removes the provided document from the target mapping. If the
   * document no longer matches the target, but the document's state is still
   * known (e.g. we know that the document was deleted or we received the change
   * that caused the filter mismatch), the new document can be provided
   * to update the remote document cache.
   */
  // Visible for testing.
  ze(e2, t2, n2) {
    if (!this.Je(e2)) return;
    const r2 = this.He(e2);
    this.ut(e2, t2) ? r2.xe(
      t2,
      1
      /* ChangeType.Removed */
    ) : (
      // The document may have entered and left the target before we raised a
      // snapshot, so we can just ignore the change.
      r2.Oe(t2)
    ), this.Ue = this.Ue.insert(t2, this.ct(t2).delete(e2)), this.Ue = this.Ue.insert(t2, this.ct(t2).add(e2)), n2 && (this.Qe = this.Qe.insert(t2, n2));
  }
  removeTarget(e2) {
    this.qe.delete(e2);
  }
  /**
   * Returns the current count of documents in the target. This includes both
   * the number of documents that the LocalStore considers to be part of the
   * target as well as any accumulated changes.
   */
  et(e2) {
    const t2 = this.He(e2).Fe();
    return this.ke.getRemoteKeysForTarget(e2).size + t2.addedDocuments.size - t2.removedDocuments.size;
  }
  /**
   * Increment the number of acks needed from watch before we can consider the
   * server to be 'in-sync' with the client's active targets.
   */
  Ne(e2) {
    this.He(e2).Ne();
  }
  He(e2) {
    let t2 = this.qe.get(e2);
    return t2 || (t2 = new __PRIVATE_TargetState(), this.qe.set(e2, t2)), t2;
  }
  ct(e2) {
    let t2 = this.Ue.get(e2);
    return t2 || (t2 = new SortedSet(__PRIVATE_primitiveComparator), this.Ue = this.Ue.insert(e2, t2)), t2;
  }
  _t(e2) {
    let t2 = this.$e.get(e2);
    return t2 || (t2 = new SortedSet(__PRIVATE_primitiveComparator), this.$e = this.$e.insert(e2, t2)), t2;
  }
  /**
   * Verifies that the user is still interested in this target (by calling
   * `getTargetDataForTarget()`) and that we are not waiting for pending ADDs
   * from watch.
   */
  Je(e2) {
    const t2 = null !== this.Xe(e2);
    return t2 || __PRIVATE_logDebug("WatchChangeAggregator", "Detected inactive target", e2), t2;
  }
  /**
   * Returns the TargetData for an active target (i.e. a target that the user
   * is still interested in that has no outstanding target change requests).
   */
  Xe(e2) {
    const t2 = this.qe.get(e2);
    return t2 && t2.De ? null : this.ke.lt(e2);
  }
  /**
   * Resets the state of a Watch target to its initial state (e.g. sets
   * 'current' to false, clears the resume token and removes its target mapping
   * from all documents).
   */
  Ye(e2) {
    this.qe.set(e2, new __PRIVATE_TargetState());
    this.ke.getRemoteKeysForTarget(e2).forEach((t2) => {
      this.ze(
        e2,
        t2,
        /*updatedDocument=*/
        null
      );
    });
  }
  /**
   * Returns whether the LocalStore considers the document to be part of the
   * specified target.
   */
  ut(e2, t2) {
    return this.ke.getRemoteKeysForTarget(e2).has(t2);
  }
}
function __PRIVATE_documentTargetMap() {
  return new SortedMap(DocumentKey.comparator);
}
__name(__PRIVATE_documentTargetMap, "__PRIVATE_documentTargetMap");
function __PRIVATE_snapshotChangesMap() {
  return new SortedMap(DocumentKey.comparator);
}
__name(__PRIVATE_snapshotChangesMap, "__PRIVATE_snapshotChangesMap");
const Vt = /* @__PURE__ */ (() => {
  const e2 = {
    asc: "ASCENDING",
    desc: "DESCENDING"
  };
  return e2;
})(), mt = /* @__PURE__ */ (() => {
  const e2 = {
    "<": "LESS_THAN",
    "<=": "LESS_THAN_OR_EQUAL",
    ">": "GREATER_THAN",
    ">=": "GREATER_THAN_OR_EQUAL",
    "==": "EQUAL",
    "!=": "NOT_EQUAL",
    "array-contains": "ARRAY_CONTAINS",
    in: "IN",
    "not-in": "NOT_IN",
    "array-contains-any": "ARRAY_CONTAINS_ANY"
  };
  return e2;
})(), ft = /* @__PURE__ */ (() => {
  const e2 = {
    and: "AND",
    or: "OR"
  };
  return e2;
})();
class JsonProtoSerializer {
  static {
    __name(this, "JsonProtoSerializer");
  }
  constructor(e2, t2) {
    this.databaseId = e2, this.useProto3Json = t2;
  }
}
function __PRIVATE_toInt32Proto(e2, t2) {
  return e2.useProto3Json || __PRIVATE_isNullOrUndefined(t2) ? t2 : {
    value: t2
  };
}
__name(__PRIVATE_toInt32Proto, "__PRIVATE_toInt32Proto");
function toTimestamp(e2, t2) {
  if (e2.useProto3Json) {
    return `${new Date(1e3 * t2.seconds).toISOString().replace(/\.\d*/, "").replace("Z", "")}.${("000000000" + t2.nanoseconds).slice(-9)}Z`;
  }
  return {
    seconds: "" + t2.seconds,
    nanos: t2.nanoseconds
  };
}
__name(toTimestamp, "toTimestamp");
function __PRIVATE_toBytes(e2, t2) {
  return e2.useProto3Json ? t2.toBase64() : t2.toUint8Array();
}
__name(__PRIVATE_toBytes, "__PRIVATE_toBytes");
function __PRIVATE_toVersion(e2, t2) {
  return toTimestamp(e2, t2.toTimestamp());
}
__name(__PRIVATE_toVersion, "__PRIVATE_toVersion");
function __PRIVATE_fromVersion(e2) {
  return __PRIVATE_hardAssert(!!e2), SnapshotVersion.fromTimestamp((/* @__PURE__ */ __name(function fromTimestamp(e3) {
    const t2 = __PRIVATE_normalizeTimestamp(e3);
    return new Timestamp(t2.seconds, t2.nanos);
  }, "fromTimestamp"))(e2));
}
__name(__PRIVATE_fromVersion, "__PRIVATE_fromVersion");
function __PRIVATE_toResourceName(e2, t2) {
  return __PRIVATE_toResourcePath(e2, t2).canonicalString();
}
__name(__PRIVATE_toResourceName, "__PRIVATE_toResourceName");
function __PRIVATE_toResourcePath(e2, t2) {
  const n2 = (/* @__PURE__ */ __name(function __PRIVATE_fullyQualifiedPrefixPath(e3) {
    return new ResourcePath(["projects", e3.projectId, "databases", e3.database]);
  }, "__PRIVATE_fullyQualifiedPrefixPath"))(e2).child("documents");
  return void 0 === t2 ? n2 : n2.child(t2);
}
__name(__PRIVATE_toResourcePath, "__PRIVATE_toResourcePath");
function __PRIVATE_fromResourceName(e2) {
  const t2 = ResourcePath.fromString(e2);
  return __PRIVATE_hardAssert(__PRIVATE_isValidResourceName(t2)), t2;
}
__name(__PRIVATE_fromResourceName, "__PRIVATE_fromResourceName");
function __PRIVATE_toName(e2, t2) {
  return __PRIVATE_toResourceName(e2.databaseId, t2.path);
}
__name(__PRIVATE_toName, "__PRIVATE_toName");
function fromName(e2, t2) {
  const n2 = __PRIVATE_fromResourceName(t2);
  if (n2.get(1) !== e2.databaseId.projectId) throw new FirestoreError(C.INVALID_ARGUMENT, "Tried to deserialize key from different project: " + n2.get(1) + " vs " + e2.databaseId.projectId);
  if (n2.get(3) !== e2.databaseId.database) throw new FirestoreError(C.INVALID_ARGUMENT, "Tried to deserialize key from different database: " + n2.get(3) + " vs " + e2.databaseId.database);
  return new DocumentKey(__PRIVATE_extractLocalPathFromResourceName(n2));
}
__name(fromName, "fromName");
function __PRIVATE_toQueryPath(e2, t2) {
  return __PRIVATE_toResourceName(e2.databaseId, t2);
}
__name(__PRIVATE_toQueryPath, "__PRIVATE_toQueryPath");
function __PRIVATE_fromQueryPath(e2) {
  const t2 = __PRIVATE_fromResourceName(e2);
  return 4 === t2.length ? ResourcePath.emptyPath() : __PRIVATE_extractLocalPathFromResourceName(t2);
}
__name(__PRIVATE_fromQueryPath, "__PRIVATE_fromQueryPath");
function __PRIVATE_getEncodedDatabaseId(e2) {
  return new ResourcePath(["projects", e2.databaseId.projectId, "databases", e2.databaseId.database]).canonicalString();
}
__name(__PRIVATE_getEncodedDatabaseId, "__PRIVATE_getEncodedDatabaseId");
function __PRIVATE_extractLocalPathFromResourceName(e2) {
  return __PRIVATE_hardAssert(e2.length > 4 && "documents" === e2.get(4)), e2.popFirst(5);
}
__name(__PRIVATE_extractLocalPathFromResourceName, "__PRIVATE_extractLocalPathFromResourceName");
function __PRIVATE_toMutationDocument(e2, t2, n2) {
  return {
    name: __PRIVATE_toName(e2, t2),
    fields: n2.value.mapValue.fields
  };
}
__name(__PRIVATE_toMutationDocument, "__PRIVATE_toMutationDocument");
function __PRIVATE_fromDocument(e2, t2, n2) {
  const r2 = fromName(e2, t2.name), i2 = __PRIVATE_fromVersion(t2.updateTime), s2 = t2.createTime ? __PRIVATE_fromVersion(t2.createTime) : SnapshotVersion.min(), o2 = new ObjectValue({
    mapValue: {
      fields: t2.fields
    }
  }), _2 = MutableDocument.newFoundDocument(r2, i2, s2, o2);
  return n2 && _2.setHasCommittedMutations(), n2 ? _2.setHasCommittedMutations() : _2;
}
__name(__PRIVATE_fromDocument, "__PRIVATE_fromDocument");
function __PRIVATE_fromBatchGetDocumentsResponse(e2, t2) {
  return "found" in t2 ? (/* @__PURE__ */ __name(function __PRIVATE_fromFound(e3, t3) {
    __PRIVATE_hardAssert(!!t3.found), t3.found.name, t3.found.updateTime;
    const n2 = fromName(e3, t3.found.name), r2 = __PRIVATE_fromVersion(t3.found.updateTime), i2 = t3.found.createTime ? __PRIVATE_fromVersion(t3.found.createTime) : SnapshotVersion.min(), s2 = new ObjectValue({
      mapValue: {
        fields: t3.found.fields
      }
    });
    return MutableDocument.newFoundDocument(n2, r2, i2, s2);
  }, "__PRIVATE_fromFound"))(e2, t2) : "missing" in t2 ? (/* @__PURE__ */ __name(function __PRIVATE_fromMissing(e3, t3) {
    __PRIVATE_hardAssert(!!t3.missing), __PRIVATE_hardAssert(!!t3.readTime);
    const n2 = fromName(e3, t3.missing), r2 = __PRIVATE_fromVersion(t3.readTime);
    return MutableDocument.newNoDocument(n2, r2);
  }, "__PRIVATE_fromMissing"))(e2, t2) : fail();
}
__name(__PRIVATE_fromBatchGetDocumentsResponse, "__PRIVATE_fromBatchGetDocumentsResponse");
function __PRIVATE_fromWatchChange(e2, t2) {
  let n2;
  if ("targetChange" in t2) {
    t2.targetChange;
    const r2 = (/* @__PURE__ */ __name(function __PRIVATE_fromWatchTargetChangeState(e3) {
      return "NO_CHANGE" === e3 ? 0 : "ADD" === e3 ? 1 : "REMOVE" === e3 ? 2 : "CURRENT" === e3 ? 3 : "RESET" === e3 ? 4 : fail();
    }, "__PRIVATE_fromWatchTargetChangeState"))(t2.targetChange.targetChangeType || "NO_CHANGE"), i2 = t2.targetChange.targetIds || [], s2 = (/* @__PURE__ */ __name(function __PRIVATE_fromBytes(e3, t3) {
      return e3.useProto3Json ? (__PRIVATE_hardAssert(void 0 === t3 || "string" == typeof t3), ByteString.fromBase64String(t3 || "")) : (__PRIVATE_hardAssert(void 0 === t3 || // Check if the value is an instance of both Buffer and Uint8Array,
      // despite the fact that Buffer extends Uint8Array. In some
      // environments, such as jsdom, the prototype chain of Buffer
      // does not indicate that it extends Uint8Array.
      t3 instanceof Buffer || t3 instanceof Uint8Array), ByteString.fromUint8Array(t3 || new Uint8Array()));
    }, "__PRIVATE_fromBytes"))(e2, t2.targetChange.resumeToken), o2 = t2.targetChange.cause, _2 = o2 && (/* @__PURE__ */ __name(function __PRIVATE_fromRpcStatus(e3) {
      const t3 = void 0 === e3.code ? C.UNKNOWN : __PRIVATE_mapCodeFromRpcCode(e3.code);
      return new FirestoreError(t3, e3.message || "");
    }, "__PRIVATE_fromRpcStatus"))(o2);
    n2 = new __PRIVATE_WatchTargetChange(r2, i2, s2, _2 || null);
  } else if ("documentChange" in t2) {
    t2.documentChange;
    const r2 = t2.documentChange;
    r2.document, r2.document.name, r2.document.updateTime;
    const i2 = fromName(e2, r2.document.name), s2 = __PRIVATE_fromVersion(r2.document.updateTime), o2 = r2.document.createTime ? __PRIVATE_fromVersion(r2.document.createTime) : SnapshotVersion.min(), _2 = new ObjectValue({
      mapValue: {
        fields: r2.document.fields
      }
    }), a2 = MutableDocument.newFoundDocument(i2, s2, o2, _2), u2 = r2.targetIds || [], c2 = r2.removedTargetIds || [];
    n2 = new __PRIVATE_DocumentWatchChange(u2, c2, a2.key, a2);
  } else if ("documentDelete" in t2) {
    t2.documentDelete;
    const r2 = t2.documentDelete;
    r2.document;
    const i2 = fromName(e2, r2.document), s2 = r2.readTime ? __PRIVATE_fromVersion(r2.readTime) : SnapshotVersion.min(), o2 = MutableDocument.newNoDocument(i2, s2), _2 = r2.removedTargetIds || [];
    n2 = new __PRIVATE_DocumentWatchChange([], _2, o2.key, o2);
  } else if ("documentRemove" in t2) {
    t2.documentRemove;
    const r2 = t2.documentRemove;
    r2.document;
    const i2 = fromName(e2, r2.document), s2 = r2.removedTargetIds || [];
    n2 = new __PRIVATE_DocumentWatchChange([], s2, i2, null);
  } else {
    if (!("filter" in t2)) return fail();
    {
      t2.filter;
      const e3 = t2.filter;
      e3.targetId;
      const { count: r2 = 0, unchangedNames: i2 } = e3, s2 = new ExistenceFilter(r2, i2), o2 = e3.targetId;
      n2 = new __PRIVATE_ExistenceFilterChange(o2, s2);
    }
  }
  return n2;
}
__name(__PRIVATE_fromWatchChange, "__PRIVATE_fromWatchChange");
function toMutation(e2, t2) {
  let n2;
  if (t2 instanceof __PRIVATE_SetMutation) n2 = {
    update: __PRIVATE_toMutationDocument(e2, t2.key, t2.value)
  };
  else if (t2 instanceof __PRIVATE_DeleteMutation) n2 = {
    delete: __PRIVATE_toName(e2, t2.key)
  };
  else if (t2 instanceof __PRIVATE_PatchMutation) n2 = {
    update: __PRIVATE_toMutationDocument(e2, t2.key, t2.data),
    updateMask: __PRIVATE_toDocumentMask(t2.fieldMask)
  };
  else {
    if (!(t2 instanceof __PRIVATE_VerifyMutation)) return fail();
    n2 = {
      verify: __PRIVATE_toName(e2, t2.key)
    };
  }
  return t2.fieldTransforms.length > 0 && (n2.updateTransforms = t2.fieldTransforms.map((e3) => (/* @__PURE__ */ __name(function __PRIVATE_toFieldTransform(e4, t3) {
    const n3 = t3.transform;
    if (n3 instanceof __PRIVATE_ServerTimestampTransform) return {
      fieldPath: t3.field.canonicalString(),
      setToServerValue: "REQUEST_TIME"
    };
    if (n3 instanceof __PRIVATE_ArrayUnionTransformOperation) return {
      fieldPath: t3.field.canonicalString(),
      appendMissingElements: {
        values: n3.elements
      }
    };
    if (n3 instanceof __PRIVATE_ArrayRemoveTransformOperation) return {
      fieldPath: t3.field.canonicalString(),
      removeAllFromArray: {
        values: n3.elements
      }
    };
    if (n3 instanceof __PRIVATE_NumericIncrementTransformOperation) return {
      fieldPath: t3.field.canonicalString(),
      increment: n3.Ie
    };
    throw fail();
  }, "__PRIVATE_toFieldTransform"))(0, e3))), t2.precondition.isNone || (n2.currentDocument = (/* @__PURE__ */ __name(function __PRIVATE_toPrecondition(e3, t3) {
    return void 0 !== t3.updateTime ? {
      updateTime: __PRIVATE_toVersion(e3, t3.updateTime)
    } : void 0 !== t3.exists ? {
      exists: t3.exists
    } : fail();
  }, "__PRIVATE_toPrecondition"))(e2, t2.precondition)), n2;
}
__name(toMutation, "toMutation");
function __PRIVATE_fromMutation(e2, t2) {
  const n2 = t2.currentDocument ? (/* @__PURE__ */ __name(function __PRIVATE_fromPrecondition(e3) {
    return void 0 !== e3.updateTime ? Precondition.updateTime(__PRIVATE_fromVersion(e3.updateTime)) : void 0 !== e3.exists ? Precondition.exists(e3.exists) : Precondition.none();
  }, "__PRIVATE_fromPrecondition"))(t2.currentDocument) : Precondition.none(), r2 = t2.updateTransforms ? t2.updateTransforms.map((t3) => (/* @__PURE__ */ __name(function __PRIVATE_fromFieldTransform(e3, t4) {
    let n3 = null;
    if ("setToServerValue" in t4) __PRIVATE_hardAssert("REQUEST_TIME" === t4.setToServerValue), n3 = new __PRIVATE_ServerTimestampTransform();
    else if ("appendMissingElements" in t4) {
      const e4 = t4.appendMissingElements.values || [];
      n3 = new __PRIVATE_ArrayUnionTransformOperation(e4);
    } else if ("removeAllFromArray" in t4) {
      const e4 = t4.removeAllFromArray.values || [];
      n3 = new __PRIVATE_ArrayRemoveTransformOperation(e4);
    } else "increment" in t4 ? n3 = new __PRIVATE_NumericIncrementTransformOperation(e3, t4.increment) : fail();
    const r3 = FieldPath$1.fromServerFormat(t4.fieldPath);
    return new FieldTransform(r3, n3);
  }, "__PRIVATE_fromFieldTransform"))(e2, t3)) : [];
  if (t2.update) {
    t2.update.name;
    const i2 = fromName(e2, t2.update.name), s2 = new ObjectValue({
      mapValue: {
        fields: t2.update.fields
      }
    });
    if (t2.updateMask) {
      const e3 = (/* @__PURE__ */ __name(function __PRIVATE_fromDocumentMask(e4) {
        const t3 = e4.fieldPaths || [];
        return new FieldMask(t3.map((e5) => FieldPath$1.fromServerFormat(e5)));
      }, "__PRIVATE_fromDocumentMask"))(t2.updateMask);
      return new __PRIVATE_PatchMutation(i2, s2, e3, n2, r2);
    }
    return new __PRIVATE_SetMutation(i2, s2, n2, r2);
  }
  if (t2.delete) {
    const r3 = fromName(e2, t2.delete);
    return new __PRIVATE_DeleteMutation(r3, n2);
  }
  if (t2.verify) {
    const r3 = fromName(e2, t2.verify);
    return new __PRIVATE_VerifyMutation(r3, n2);
  }
  return fail();
}
__name(__PRIVATE_fromMutation, "__PRIVATE_fromMutation");
function __PRIVATE_fromWriteResults(e2, t2) {
  return e2 && e2.length > 0 ? (__PRIVATE_hardAssert(void 0 !== t2), e2.map((e3) => (/* @__PURE__ */ __name(function __PRIVATE_fromWriteResult(e4, t3) {
    let n2 = e4.updateTime ? __PRIVATE_fromVersion(e4.updateTime) : __PRIVATE_fromVersion(t3);
    return n2.isEqual(SnapshotVersion.min()) && // The Firestore Emulator currently returns an update time of 0 for
    // deletes of non-existing documents (rather than null). This breaks the
    // test "get deleted doc while offline with source=cache" as NoDocuments
    // with version 0 are filtered by IndexedDb's RemoteDocumentCache.
    // TODO(#2149): Remove this when Emulator is fixed
    (n2 = __PRIVATE_fromVersion(t3)), new MutationResult(n2, e4.transformResults || []);
  }, "__PRIVATE_fromWriteResult"))(e3, t2))) : [];
}
__name(__PRIVATE_fromWriteResults, "__PRIVATE_fromWriteResults");
function __PRIVATE_toDocumentsTarget(e2, t2) {
  return {
    documents: [__PRIVATE_toQueryPath(e2, t2.path)]
  };
}
__name(__PRIVATE_toDocumentsTarget, "__PRIVATE_toDocumentsTarget");
function __PRIVATE_toQueryTarget(e2, t2) {
  const n2 = {
    structuredQuery: {}
  }, r2 = t2.path;
  let i2;
  null !== t2.collectionGroup ? (i2 = r2, n2.structuredQuery.from = [{
    collectionId: t2.collectionGroup,
    allDescendants: true
  }]) : (i2 = r2.popLast(), n2.structuredQuery.from = [{
    collectionId: r2.lastSegment()
  }]), n2.parent = __PRIVATE_toQueryPath(e2, i2);
  const s2 = (/* @__PURE__ */ __name(function __PRIVATE_toFilters(e3) {
    if (0 === e3.length) return;
    return __PRIVATE_toFilter(CompositeFilter.create(
      e3,
      "and"
      /* CompositeOperator.AND */
    ));
  }, "__PRIVATE_toFilters"))(t2.filters);
  s2 && (n2.structuredQuery.where = s2);
  const o2 = (/* @__PURE__ */ __name(function __PRIVATE_toOrder(e3) {
    if (0 === e3.length) return;
    return e3.map((e4) => (
      // visible for testing
      (/* @__PURE__ */ __name(function __PRIVATE_toPropertyOrder(e5) {
        return {
          field: __PRIVATE_toFieldPathReference(e5.field),
          direction: __PRIVATE_toDirection(e5.dir)
        };
      }, "__PRIVATE_toPropertyOrder"))(e4)
    ));
  }, "__PRIVATE_toOrder"))(t2.orderBy);
  o2 && (n2.structuredQuery.orderBy = o2);
  const _2 = __PRIVATE_toInt32Proto(e2, t2.limit);
  return null !== _2 && (n2.structuredQuery.limit = _2), t2.startAt && (n2.structuredQuery.startAt = (/* @__PURE__ */ __name(function __PRIVATE_toStartAtCursor(e3) {
    return {
      before: e3.inclusive,
      values: e3.position
    };
  }, "__PRIVATE_toStartAtCursor"))(t2.startAt)), t2.endAt && (n2.structuredQuery.endAt = (/* @__PURE__ */ __name(function __PRIVATE_toEndAtCursor(e3) {
    return {
      before: !e3.inclusive,
      values: e3.position
    };
  }, "__PRIVATE_toEndAtCursor"))(t2.endAt)), {
    ht: n2,
    parent: i2
  };
}
__name(__PRIVATE_toQueryTarget, "__PRIVATE_toQueryTarget");
function __PRIVATE_toRunAggregationQueryRequest(e2, t2, n2, r2) {
  const { ht: i2, parent: s2 } = __PRIVATE_toQueryTarget(e2, t2), o2 = {}, _2 = [];
  let a2 = 0;
  return n2.forEach((e3) => {
    const t3 = r2 ? e3.alias : "aggregate_" + a2++;
    o2[t3] = e3.alias, "count" === e3.aggregateType ? _2.push({
      alias: t3,
      count: {}
    }) : "avg" === e3.aggregateType ? _2.push({
      alias: t3,
      avg: {
        field: __PRIVATE_toFieldPathReference(e3.fieldPath)
      }
    }) : "sum" === e3.aggregateType && _2.push({
      alias: t3,
      sum: {
        field: __PRIVATE_toFieldPathReference(e3.fieldPath)
      }
    });
  }), {
    request: {
      structuredAggregationQuery: {
        aggregations: _2,
        structuredQuery: i2.structuredQuery
      },
      parent: i2.parent
    },
    Pt: o2,
    parent: s2
  };
}
__name(__PRIVATE_toRunAggregationQueryRequest, "__PRIVATE_toRunAggregationQueryRequest");
function __PRIVATE_convertQueryTargetToQuery(e2) {
  let t2 = __PRIVATE_fromQueryPath(e2.parent);
  const n2 = e2.structuredQuery, r2 = n2.from ? n2.from.length : 0;
  let i2 = null;
  if (r2 > 0) {
    __PRIVATE_hardAssert(1 === r2);
    const e3 = n2.from[0];
    e3.allDescendants ? i2 = e3.collectionId : t2 = t2.child(e3.collectionId);
  }
  let s2 = [];
  n2.where && (s2 = (/* @__PURE__ */ __name(function __PRIVATE_fromFilters(e3) {
    const t3 = __PRIVATE_fromFilter(e3);
    if (t3 instanceof CompositeFilter && __PRIVATE_compositeFilterIsFlatConjunction(t3)) return t3.getFilters();
    return [t3];
  }, "__PRIVATE_fromFilters"))(n2.where));
  let o2 = [];
  n2.orderBy && (o2 = (/* @__PURE__ */ __name(function __PRIVATE_fromOrder(e3) {
    return e3.map((e4) => (/* @__PURE__ */ __name(function __PRIVATE_fromPropertyOrder(e5) {
      return new OrderBy(
        __PRIVATE_fromFieldPathReference(e5.field),
        // visible for testing
        (/* @__PURE__ */ __name(function __PRIVATE_fromDirection(e6) {
          switch (e6) {
            case "ASCENDING":
              return "asc";
            case "DESCENDING":
              return "desc";
            default:
              return;
          }
        }, "__PRIVATE_fromDirection"))(e5.direction)
      );
    }, "__PRIVATE_fromPropertyOrder"))(e4));
  }, "__PRIVATE_fromOrder"))(n2.orderBy));
  let _2 = null;
  n2.limit && (_2 = (/* @__PURE__ */ __name(function __PRIVATE_fromInt32Proto(e3) {
    let t3;
    return t3 = "object" == typeof e3 ? e3.value : e3, __PRIVATE_isNullOrUndefined(t3) ? null : t3;
  }, "__PRIVATE_fromInt32Proto"))(n2.limit));
  let a2 = null;
  n2.startAt && (a2 = (/* @__PURE__ */ __name(function __PRIVATE_fromStartAtCursor(e3) {
    const t3 = !!e3.before, n3 = e3.values || [];
    return new Bound(n3, t3);
  }, "__PRIVATE_fromStartAtCursor"))(n2.startAt));
  let u2 = null;
  return n2.endAt && (u2 = (/* @__PURE__ */ __name(function __PRIVATE_fromEndAtCursor(e3) {
    const t3 = !e3.before, n3 = e3.values || [];
    return new Bound(n3, t3);
  }, "__PRIVATE_fromEndAtCursor"))(n2.endAt)), __PRIVATE_newQuery(t2, i2, o2, s2, _2, "F", a2, u2);
}
__name(__PRIVATE_convertQueryTargetToQuery, "__PRIVATE_convertQueryTargetToQuery");
function __PRIVATE_toListenRequestLabels(e2, t2) {
  const n2 = (/* @__PURE__ */ __name(function __PRIVATE_toLabel(e3) {
    switch (e3) {
      case "TargetPurposeListen":
        return null;
      case "TargetPurposeExistenceFilterMismatch":
        return "existence-filter-mismatch";
      case "TargetPurposeExistenceFilterMismatchBloom":
        return "existence-filter-mismatch-bloom";
      case "TargetPurposeLimboResolution":
        return "limbo-document";
      default:
        return fail();
    }
  }, "__PRIVATE_toLabel"))(t2.purpose);
  return null == n2 ? null : {
    "goog-listen-tags": n2
  };
}
__name(__PRIVATE_toListenRequestLabels, "__PRIVATE_toListenRequestLabels");
function __PRIVATE_fromFilter(e2) {
  return void 0 !== e2.unaryFilter ? (/* @__PURE__ */ __name(function __PRIVATE_fromUnaryFilter(e3) {
    switch (e3.unaryFilter.op) {
      case "IS_NAN":
        const t2 = __PRIVATE_fromFieldPathReference(e3.unaryFilter.field);
        return FieldFilter.create(t2, "==", {
          doubleValue: NaN
        });
      case "IS_NULL":
        const n2 = __PRIVATE_fromFieldPathReference(e3.unaryFilter.field);
        return FieldFilter.create(n2, "==", {
          nullValue: "NULL_VALUE"
        });
      case "IS_NOT_NAN":
        const r2 = __PRIVATE_fromFieldPathReference(e3.unaryFilter.field);
        return FieldFilter.create(r2, "!=", {
          doubleValue: NaN
        });
      case "IS_NOT_NULL":
        const i2 = __PRIVATE_fromFieldPathReference(e3.unaryFilter.field);
        return FieldFilter.create(i2, "!=", {
          nullValue: "NULL_VALUE"
        });
      default:
        return fail();
    }
  }, "__PRIVATE_fromUnaryFilter"))(e2) : void 0 !== e2.fieldFilter ? (/* @__PURE__ */ __name(function __PRIVATE_fromFieldFilter(e3) {
    return FieldFilter.create(__PRIVATE_fromFieldPathReference(e3.fieldFilter.field), (/* @__PURE__ */ __name(function __PRIVATE_fromOperatorName(e4) {
      switch (e4) {
        case "EQUAL":
          return "==";
        case "NOT_EQUAL":
          return "!=";
        case "GREATER_THAN":
          return ">";
        case "GREATER_THAN_OR_EQUAL":
          return ">=";
        case "LESS_THAN":
          return "<";
        case "LESS_THAN_OR_EQUAL":
          return "<=";
        case "ARRAY_CONTAINS":
          return "array-contains";
        case "IN":
          return "in";
        case "NOT_IN":
          return "not-in";
        case "ARRAY_CONTAINS_ANY":
          return "array-contains-any";
        default:
          return fail();
      }
    }, "__PRIVATE_fromOperatorName"))(e3.fieldFilter.op), e3.fieldFilter.value);
  }, "__PRIVATE_fromFieldFilter"))(e2) : void 0 !== e2.compositeFilter ? (/* @__PURE__ */ __name(function __PRIVATE_fromCompositeFilter(e3) {
    return CompositeFilter.create(e3.compositeFilter.filters.map((e4) => __PRIVATE_fromFilter(e4)), (/* @__PURE__ */ __name(function __PRIVATE_fromCompositeOperatorName(e4) {
      switch (e4) {
        case "AND":
          return "and";
        case "OR":
          return "or";
        default:
          return fail();
      }
    }, "__PRIVATE_fromCompositeOperatorName"))(e3.compositeFilter.op));
  }, "__PRIVATE_fromCompositeFilter"))(e2) : fail();
}
__name(__PRIVATE_fromFilter, "__PRIVATE_fromFilter");
function __PRIVATE_toDirection(e2) {
  return Vt[e2];
}
__name(__PRIVATE_toDirection, "__PRIVATE_toDirection");
function __PRIVATE_toOperatorName(e2) {
  return mt[e2];
}
__name(__PRIVATE_toOperatorName, "__PRIVATE_toOperatorName");
function __PRIVATE_toCompositeOperatorName(e2) {
  return ft[e2];
}
__name(__PRIVATE_toCompositeOperatorName, "__PRIVATE_toCompositeOperatorName");
function __PRIVATE_toFieldPathReference(e2) {
  return {
    fieldPath: e2.canonicalString()
  };
}
__name(__PRIVATE_toFieldPathReference, "__PRIVATE_toFieldPathReference");
function __PRIVATE_fromFieldPathReference(e2) {
  return FieldPath$1.fromServerFormat(e2.fieldPath);
}
__name(__PRIVATE_fromFieldPathReference, "__PRIVATE_fromFieldPathReference");
function __PRIVATE_toFilter(e2) {
  return e2 instanceof FieldFilter ? (/* @__PURE__ */ __name(function __PRIVATE_toUnaryOrFieldFilter(e3) {
    if ("==" === e3.op) {
      if (__PRIVATE_isNanValue(e3.value)) return {
        unaryFilter: {
          field: __PRIVATE_toFieldPathReference(e3.field),
          op: "IS_NAN"
        }
      };
      if (__PRIVATE_isNullValue(e3.value)) return {
        unaryFilter: {
          field: __PRIVATE_toFieldPathReference(e3.field),
          op: "IS_NULL"
        }
      };
    } else if ("!=" === e3.op) {
      if (__PRIVATE_isNanValue(e3.value)) return {
        unaryFilter: {
          field: __PRIVATE_toFieldPathReference(e3.field),
          op: "IS_NOT_NAN"
        }
      };
      if (__PRIVATE_isNullValue(e3.value)) return {
        unaryFilter: {
          field: __PRIVATE_toFieldPathReference(e3.field),
          op: "IS_NOT_NULL"
        }
      };
    }
    return {
      fieldFilter: {
        field: __PRIVATE_toFieldPathReference(e3.field),
        op: __PRIVATE_toOperatorName(e3.op),
        value: e3.value
      }
    };
  }, "__PRIVATE_toUnaryOrFieldFilter"))(e2) : e2 instanceof CompositeFilter ? (/* @__PURE__ */ __name(function __PRIVATE_toCompositeFilter(e3) {
    const t2 = e3.getFilters().map((e4) => __PRIVATE_toFilter(e4));
    if (1 === t2.length) return t2[0];
    return {
      compositeFilter: {
        op: __PRIVATE_toCompositeOperatorName(e3.op),
        filters: t2
      }
    };
  }, "__PRIVATE_toCompositeFilter"))(e2) : fail();
}
__name(__PRIVATE_toFilter, "__PRIVATE_toFilter");
function __PRIVATE_toDocumentMask(e2) {
  const t2 = [];
  return e2.fields.forEach((e3) => t2.push(e3.canonicalString())), {
    fieldPaths: t2
  };
}
__name(__PRIVATE_toDocumentMask, "__PRIVATE_toDocumentMask");
function __PRIVATE_isValidResourceName(e2) {
  return e2.length >= 4 && "projects" === e2.get(0) && "databases" === e2.get(2);
}
__name(__PRIVATE_isValidResourceName, "__PRIVATE_isValidResourceName");
/**
 * @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 TargetData {
  static {
    __name(this, "TargetData");
  }
  constructor(e2, t2, n2, r2, i2 = SnapshotVersion.min(), s2 = SnapshotVersion.min(), o2 = ByteString.EMPTY_BYTE_STRING, _2 = null) {
    this.target = e2, this.targetId = t2, this.purpose = n2, this.sequenceNumber = r2, this.snapshotVersion = i2, this.lastLimboFreeSnapshotVersion = s2, this.resumeToken = o2, this.expectedCount = _2;
  }
  /** Creates a new target data instance with an updated sequence number. */
  withSequenceNumber(e2) {
    return new TargetData(this.target, this.targetId, this.purpose, e2, this.snapshotVersion, this.lastLimboFreeSnapshotVersion, this.resumeToken, this.expectedCount);
  }
  /**
   * Creates a new target data instance with an updated resume token and
   * snapshot version.
   */
  withResumeToken(e2, t2) {
    return new TargetData(
      this.target,
      this.targetId,
      this.purpose,
      this.sequenceNumber,
      t2,
      this.lastLimboFreeSnapshotVersion,
      e2,
      /* expectedCount= */
      null
    );
  }
  /**
   * Creates a new target data instance with an updated expected count.
   */
  withExpectedCount(e2) {
    return new TargetData(this.target, this.targetId, this.purpose, this.sequenceNumber, this.snapshotVersion, this.lastLimboFreeSnapshotVersion, this.resumeToken, e2);
  }
  /**
   * Creates a new target data instance with an updated last limbo free
   * snapshot version number.
   */
  withLastLimboFreeSnapshotVersion(e2) {
    return new TargetData(this.target, this.targetId, this.purpose, this.sequenceNumber, this.snapshotVersion, e2, this.resumeToken, this.expectedCount);
  }
}
/**
 * @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 __PRIVATE_LocalSerializer {
  static {
    __name(this, "__PRIVATE_LocalSerializer");
  }
  constructor(e2) {
    this.Tt = e2;
  }
}
function __PRIVATE_fromDbRemoteDocument(e2, t2) {
  let n2;
  if (t2.document) n2 = __PRIVATE_fromDocument(e2.Tt, t2.document, !!t2.hasCommittedMutations);
  else if (t2.noDocument) {
    const e3 = DocumentKey.fromSegments(t2.noDocument.path), r2 = __PRIVATE_fromDbTimestamp(t2.noDocument.readTime);
    n2 = MutableDocument.newNoDocument(e3, r2), t2.hasCommittedMutations && n2.setHasCommittedMutations();
  } else {
    if (!t2.unknownDocument) return fail();
    {
      const e3 = DocumentKey.fromSegments(t2.unknownDocument.path), r2 = __PRIVATE_fromDbTimestamp(t2.unknownDocument.version);
      n2 = MutableDocument.newUnknownDocument(e3, r2);
    }
  }
  return t2.readTime && n2.setReadTime((/* @__PURE__ */ __name(function __PRIVATE_fromDbTimestampKey(e3) {
    const t3 = new Timestamp(e3[0], e3[1]);
    return SnapshotVersion.fromTimestamp(t3);
  }, "__PRIVATE_fromDbTimestampKey"))(t2.readTime)), n2;
}
__name(__PRIVATE_fromDbRemoteDocument, "__PRIVATE_fromDbRemoteDocument");
function __PRIVATE_toDbRemoteDocument(e2, t2) {
  const n2 = t2.key, r2 = {
    prefixPath: n2.getCollectionPath().popLast().toArray(),
    collectionGroup: n2.collectionGroup,
    documentId: n2.path.lastSegment(),
    readTime: __PRIVATE_toDbTimestampKey(t2.readTime),
    hasCommittedMutations: t2.hasCommittedMutations
  };
  if (t2.isFoundDocument()) r2.document = (/* @__PURE__ */ __name(function __PRIVATE_toDocument(e3, t3) {
    return {
      name: __PRIVATE_toName(e3, t3.key),
      fields: t3.data.value.mapValue.fields,
      updateTime: toTimestamp(e3, t3.version.toTimestamp()),
      createTime: toTimestamp(e3, t3.createTime.toTimestamp())
    };
  }, "__PRIVATE_toDocument"))(e2.Tt, t2);
  else if (t2.isNoDocument()) r2.noDocument = {
    path: n2.path.toArray(),
    readTime: __PRIVATE_toDbTimestamp(t2.version)
  };
  else {
    if (!t2.isUnknownDocument()) return fail();
    r2.unknownDocument = {
      path: n2.path.toArray(),
      version: __PRIVATE_toDbTimestamp(t2.version)
    };
  }
  return r2;
}
__name(__PRIVATE_toDbRemoteDocument, "__PRIVATE_toDbRemoteDocument");
function __PRIVATE_toDbTimestampKey(e2) {
  const t2 = e2.toTimestamp();
  return [t2.seconds, t2.nanoseconds];
}
__name(__PRIVATE_toDbTimestampKey, "__PRIVATE_toDbTimestampKey");
function __PRIVATE_toDbTimestamp(e2) {
  const t2 = e2.toTimestamp();
  return {
    seconds: t2.seconds,
    nanoseconds: t2.nanoseconds
  };
}
__name(__PRIVATE_toDbTimestamp, "__PRIVATE_toDbTimestamp");
function __PRIVATE_fromDbTimestamp(e2) {
  const t2 = new Timestamp(e2.seconds, e2.nanoseconds);
  return SnapshotVersion.fromTimestamp(t2);
}
__name(__PRIVATE_fromDbTimestamp, "__PRIVATE_fromDbTimestamp");
function __PRIVATE_fromDbMutationBatch(e2, t2) {
  const n2 = (t2.baseMutations || []).map((t3) => __PRIVATE_fromMutation(e2.Tt, t3));
  for (let e3 = 0; e3 < t2.mutations.length - 1; ++e3) {
    const n3 = t2.mutations[e3];
    if (e3 + 1 < t2.mutations.length && void 0 !== t2.mutations[e3 + 1].transform) {
      const r3 = t2.mutations[e3 + 1];
      n3.updateTransforms = r3.transform.fieldTransforms, t2.mutations.splice(e3 + 1, 1), ++e3;
    }
  }
  const r2 = t2.mutations.map((t3) => __PRIVATE_fromMutation(e2.Tt, t3)), i2 = Timestamp.fromMillis(t2.localWriteTimeMs);
  return new MutationBatch(t2.batchId, i2, n2, r2);
}
__name(__PRIVATE_fromDbMutationBatch, "__PRIVATE_fromDbMutationBatch");
function __PRIVATE_fromDbTarget(e2) {
  const t2 = __PRIVATE_fromDbTimestamp(e2.readTime), n2 = void 0 !== e2.lastLimboFreeSnapshotVersion ? __PRIVATE_fromDbTimestamp(e2.lastLimboFreeSnapshotVersion) : SnapshotVersion.min();
  let r2;
  return r2 = /**
  * A helper function for figuring out what kind of query has been stored.
  */
  (/* @__PURE__ */ __name(function __PRIVATE_isDocumentQuery(e3) {
    return void 0 !== e3.documents;
  }, "__PRIVATE_isDocumentQuery"))(e2.query) ? (/* @__PURE__ */ __name(function __PRIVATE_fromDocumentsTarget(e3) {
    return __PRIVATE_hardAssert(1 === e3.documents.length), __PRIVATE_queryToTarget(__PRIVATE_newQueryForPath(__PRIVATE_fromQueryPath(e3.documents[0])));
  }, "__PRIVATE_fromDocumentsTarget"))(e2.query) : (/* @__PURE__ */ __name(function __PRIVATE_fromQueryTarget(e3) {
    return __PRIVATE_queryToTarget(__PRIVATE_convertQueryTargetToQuery(e3));
  }, "__PRIVATE_fromQueryTarget"))(e2.query), new TargetData(r2, e2.targetId, "TargetPurposeListen", e2.lastListenSequenceNumber, t2, n2, ByteString.fromBase64String(e2.resumeToken));
}
__name(__PRIVATE_fromDbTarget, "__PRIVATE_fromDbTarget");
function __PRIVATE_toDbTarget(e2, t2) {
  const n2 = __PRIVATE_toDbTimestamp(t2.snapshotVersion), r2 = __PRIVATE_toDbTimestamp(t2.lastLimboFreeSnapshotVersion);
  let i2;
  i2 = __PRIVATE_targetIsDocumentTarget(t2.target) ? __PRIVATE_toDocumentsTarget(e2.Tt, t2.target) : __PRIVATE_toQueryTarget(e2.Tt, t2.target).ht;
  const s2 = t2.resumeToken.toBase64();
  return {
    targetId: t2.targetId,
    canonicalId: __PRIVATE_canonifyTarget(t2.target),
    readTime: n2,
    resumeToken: s2,
    lastListenSequenceNumber: t2.sequenceNumber,
    lastLimboFreeSnapshotVersion: r2,
    query: i2
  };
}
__name(__PRIVATE_toDbTarget, "__PRIVATE_toDbTarget");
function __PRIVATE_fromBundledQuery(e2) {
  const t2 = __PRIVATE_convertQueryTargetToQuery({
    parent: e2.parent,
    structuredQuery: e2.structuredQuery
  });
  return "LAST" === e2.limitType ? __PRIVATE_queryWithLimit(
    t2,
    t2.limit,
    "L"
    /* LimitType.Last */
  ) : t2;
}
__name(__PRIVATE_fromBundledQuery, "__PRIVATE_fromBundledQuery");
function __PRIVATE_fromDbDocumentOverlay(e2, t2) {
  return new Overlay(t2.largestBatchId, __PRIVATE_fromMutation(e2.Tt, t2.overlayMutation));
}
__name(__PRIVATE_fromDbDocumentOverlay, "__PRIVATE_fromDbDocumentOverlay");
function __PRIVATE_toDbDocumentOverlayKey(e2, t2) {
  const n2 = t2.path.lastSegment();
  return [e2, __PRIVATE_encodeResourcePath(t2.path.popLast()), n2];
}
__name(__PRIVATE_toDbDocumentOverlayKey, "__PRIVATE_toDbDocumentOverlayKey");
function __PRIVATE_toDbIndexState(e2, t2, n2, r2) {
  return {
    indexId: e2,
    uid: t2,
    sequenceNumber: n2,
    readTime: __PRIVATE_toDbTimestamp(r2.readTime),
    documentKey: __PRIVATE_encodeResourcePath(r2.documentKey.path),
    largestBatchId: r2.largestBatchId
  };
}
__name(__PRIVATE_toDbIndexState, "__PRIVATE_toDbIndexState");
/**
 * @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 __PRIVATE_IndexedDbBundleCache {
  static {
    __name(this, "__PRIVATE_IndexedDbBundleCache");
  }
  getBundleMetadata(e2, t2) {
    return __PRIVATE_bundlesStore(e2).get(t2).next((e3) => {
      if (e3) return (/* @__PURE__ */ __name(function __PRIVATE_fromDbBundle(e4) {
        return {
          id: e4.bundleId,
          createTime: __PRIVATE_fromDbTimestamp(e4.createTime),
          version: e4.version
        };
      }, "__PRIVATE_fromDbBundle"))(e3);
    });
  }
  saveBundleMetadata(e2, t2) {
    return __PRIVATE_bundlesStore(e2).put((/* @__PURE__ */ __name(function __PRIVATE_toDbBundle(e3) {
      return {
        bundleId: e3.id,
        createTime: __PRIVATE_toDbTimestamp(__PRIVATE_fromVersion(e3.createTime)),
        version: e3.version
      };
    }, "__PRIVATE_toDbBundle"))(t2));
  }
  getNamedQuery(e2, t2) {
    return __PRIVATE_namedQueriesStore(e2).get(t2).next((e3) => {
      if (e3) return (/* @__PURE__ */ __name(function __PRIVATE_fromDbNamedQuery(e4) {
        return {
          name: e4.name,
          query: __PRIVATE_fromBundledQuery(e4.bundledQuery),
          readTime: __PRIVATE_fromDbTimestamp(e4.readTime)
        };
      }, "__PRIVATE_fromDbNamedQuery"))(e3);
    });
  }
  saveNamedQuery(e2, t2) {
    return __PRIVATE_namedQueriesStore(e2).put((/* @__PURE__ */ __name(function __PRIVATE_toDbNamedQuery(e3) {
      return {
        name: e3.name,
        readTime: __PRIVATE_toDbTimestamp(__PRIVATE_fromVersion(e3.readTime)),
        bundledQuery: e3.bundledQuery
      };
    }, "__PRIVATE_toDbNamedQuery"))(t2));
  }
}
function __PRIVATE_bundlesStore(e2) {
  return __PRIVATE_getStore(e2, me);
}
__name(__PRIVATE_bundlesStore, "__PRIVATE_bundlesStore");
function __PRIVATE_namedQueriesStore(e2) {
  return __PRIVATE_getStore(e2, ge);
}
__name(__PRIVATE_namedQueriesStore, "__PRIVATE_namedQueriesStore");
/**
 * @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.
 */
class __PRIVATE_IndexedDbDocumentOverlayCache {
  static {
    __name(this, "__PRIVATE_IndexedDbDocumentOverlayCache");
  }
  /**
   * @param serializer - The document serializer.
   * @param userId - The userId for which we are accessing overlays.
   */
  constructor(e2, t2) {
    this.serializer = e2, this.userId = t2;
  }
  static It(e2, t2) {
    const n2 = t2.uid || "";
    return new __PRIVATE_IndexedDbDocumentOverlayCache(e2, n2);
  }
  getOverlay(e2, t2) {
    return __PRIVATE_documentOverlayStore(e2).get(__PRIVATE_toDbDocumentOverlayKey(this.userId, t2)).next((e3) => e3 ? __PRIVATE_fromDbDocumentOverlay(this.serializer, e3) : null);
  }
  getOverlays(e2, t2) {
    const n2 = __PRIVATE_newOverlayMap();
    return PersistencePromise.forEach(t2, (t3) => this.getOverlay(e2, t3).next((e3) => {
      null !== e3 && n2.set(t3, e3);
    })).next(() => n2);
  }
  saveOverlays(e2, t2, n2) {
    const r2 = [];
    return n2.forEach((n3, i2) => {
      const s2 = new Overlay(t2, i2);
      r2.push(this.Et(e2, s2));
    }), PersistencePromise.waitFor(r2);
  }
  removeOverlaysForBatchId(e2, t2, n2) {
    const r2 = /* @__PURE__ */ new Set();
    t2.forEach((e3) => r2.add(__PRIVATE_encodeResourcePath(e3.getCollectionPath())));
    const i2 = [];
    return r2.forEach((t3) => {
      const r3 = IDBKeyRange.bound(
        [this.userId, t3, n2],
        [this.userId, t3, n2 + 1],
        /*lowerOpen=*/
        false,
        /*upperOpen=*/
        true
      );
      i2.push(__PRIVATE_documentOverlayStore(e2).J(ke, r3));
    }), PersistencePromise.waitFor(i2);
  }
  getOverlaysForCollection(e2, t2, n2) {
    const r2 = __PRIVATE_newOverlayMap(), i2 = __PRIVATE_encodeResourcePath(t2), s2 = IDBKeyRange.bound(
      [this.userId, i2, n2],
      [this.userId, i2, Number.POSITIVE_INFINITY],
      /*lowerOpen=*/
      true
    );
    return __PRIVATE_documentOverlayStore(e2).G(ke, s2).next((e3) => {
      for (const t3 of e3) {
        const e4 = __PRIVATE_fromDbDocumentOverlay(this.serializer, t3);
        r2.set(e4.getKey(), e4);
      }
      return r2;
    });
  }
  getOverlaysForCollectionGroup(e2, t2, n2, r2) {
    const i2 = __PRIVATE_newOverlayMap();
    let s2;
    const o2 = IDBKeyRange.bound(
      [this.userId, t2, n2],
      [this.userId, t2, Number.POSITIVE_INFINITY],
      /*lowerOpen=*/
      true
    );
    return __PRIVATE_documentOverlayStore(e2).Z({
      index: Qe,
      range: o2
    }, (e3, t3, n3) => {
      const o3 = __PRIVATE_fromDbDocumentOverlay(this.serializer, t3);
      i2.size() < r2 || o3.largestBatchId === s2 ? (i2.set(o3.getKey(), o3), s2 = o3.largestBatchId) : n3.done();
    }).next(() => i2);
  }
  Et(e2, t2) {
    return __PRIVATE_documentOverlayStore(e2).put((/* @__PURE__ */ __name(function __PRIVATE_toDbDocumentOverlay(e3, t3, n2) {
      const [r2, i2, s2] = __PRIVATE_toDbDocumentOverlayKey(t3, n2.mutation.key);
      return {
        userId: t3,
        collectionPath: i2,
        documentId: s2,
        collectionGroup: n2.mutation.key.getCollectionGroup(),
        largestBatchId: n2.largestBatchId,
        overlayMutation: toMutation(e3.Tt, n2.mutation)
      };
    }, "__PRIVATE_toDbDocumentOverlay"))(this.serializer, this.userId, t2));
  }
}
function __PRIVATE_documentOverlayStore(e2) {
  return __PRIVATE_getStore(e2, Be);
}
__name(__PRIVATE_documentOverlayStore, "__PRIVATE_documentOverlayStore");
/**
 * @license
 * Copyright 2024 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 __PRIVATE_IndexedDbGlobalsCache {
  static {
    __name(this, "__PRIVATE_IndexedDbGlobalsCache");
  }
  dt(e2) {
    return __PRIVATE_getStore(e2, Ue);
  }
  getSessionToken(e2) {
    return this.dt(e2).get("sessionToken").next((e3) => {
      const t2 = null == e3 ? void 0 : e3.value;
      return t2 ? ByteString.fromUint8Array(t2) : ByteString.EMPTY_BYTE_STRING;
    });
  }
  setSessionToken(e2, t2) {
    return this.dt(e2).put({
      name: "sessionToken",
      value: t2.toUint8Array()
    });
  }
}
/**
 * @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 __PRIVATE_FirestoreIndexValueWriter {
  static {
    __name(this, "__PRIVATE_FirestoreIndexValueWriter");
  }
  constructor() {
  }
  // The write methods below short-circuit writing terminators for values
  // containing a (terminating) truncated value.
  // As an example, consider the resulting encoding for:
  // ["bar", [2, "foo"]] -> (STRING, "bar", TERM, ARRAY, NUMBER, 2, STRING, "foo", TERM, TERM, TERM)
  // ["bar", [2, truncated("foo")]] -> (STRING, "bar", TERM, ARRAY, NUMBER, 2, STRING, "foo", TRUNC)
  // ["bar", truncated(["foo"])] -> (STRING, "bar", TERM, ARRAY. STRING, "foo", TERM, TRUNC)
  /** Writes an index value.  */
  At(e2, t2) {
    this.Rt(e2, t2), // Write separator to split index values
    // (see go/firestore-storage-format#encodings).
    t2.Vt();
  }
  Rt(e2, t2) {
    if ("nullValue" in e2) this.ft(t2, 5);
    else if ("booleanValue" in e2) this.ft(t2, 10), t2.gt(e2.booleanValue ? 1 : 0);
    else if ("integerValue" in e2) this.ft(t2, 15), t2.gt(__PRIVATE_normalizeNumber(e2.integerValue));
    else if ("doubleValue" in e2) {
      const n2 = __PRIVATE_normalizeNumber(e2.doubleValue);
      isNaN(n2) ? this.ft(t2, 13) : (this.ft(t2, 15), __PRIVATE_isNegativeZero(n2) ? (
        // -0.0, 0 and 0.0 are all considered the same
        t2.gt(0)
      ) : t2.gt(n2));
    } else if ("timestampValue" in e2) {
      let n2 = e2.timestampValue;
      this.ft(t2, 20), "string" == typeof n2 && (n2 = __PRIVATE_normalizeTimestamp(n2)), t2.yt(`${n2.seconds || ""}`), t2.gt(n2.nanos || 0);
    } else if ("stringValue" in e2) this.wt(e2.stringValue, t2), this.St(t2);
    else if ("bytesValue" in e2) this.ft(t2, 30), t2.bt(__PRIVATE_normalizeByteString(e2.bytesValue)), this.St(t2);
    else if ("referenceValue" in e2) this.Dt(e2.referenceValue, t2);
    else if ("geoPointValue" in e2) {
      const n2 = e2.geoPointValue;
      this.ft(t2, 45), t2.gt(n2.latitude || 0), t2.gt(n2.longitude || 0);
    } else "mapValue" in e2 ? __PRIVATE_isMaxValue(e2) ? this.ft(t2, Number.MAX_SAFE_INTEGER) : __PRIVATE_isVectorValue(e2) ? this.vt(e2.mapValue, t2) : (this.Ct(e2.mapValue, t2), this.St(t2)) : "arrayValue" in e2 ? (this.Ft(e2.arrayValue, t2), this.St(t2)) : fail();
  }
  wt(e2, t2) {
    this.ft(t2, 25), this.Mt(e2, t2);
  }
  Mt(e2, t2) {
    t2.yt(e2);
  }
  Ct(e2, t2) {
    const n2 = e2.fields || {};
    this.ft(t2, 55);
    for (const e3 of Object.keys(n2)) this.wt(e3, t2), this.Rt(n2[e3], t2);
  }
  vt(e2, t2) {
    var n2, r2;
    const i2 = e2.fields || {};
    this.ft(t2, 53);
    const s2 = at, o2 = (null === (r2 = null === (n2 = i2[s2].arrayValue) || void 0 === n2 ? void 0 : n2.values) || void 0 === r2 ? void 0 : r2.length) || 0;
    this.ft(t2, 15), t2.gt(__PRIVATE_normalizeNumber(o2)), // Vectors then sort by position value
    this.wt(s2, t2), this.Rt(i2[s2], t2);
  }
  Ft(e2, t2) {
    const n2 = e2.values || [];
    this.ft(t2, 50);
    for (const e3 of n2) this.Rt(e3, t2);
  }
  Dt(e2, t2) {
    this.ft(t2, 37);
    DocumentKey.fromName(e2).path.forEach((e3) => {
      this.ft(t2, 60), this.Mt(e3, t2);
    });
  }
  ft(e2, t2) {
    e2.gt(t2);
  }
  St(e2) {
    e2.gt(2);
  }
}
__PRIVATE_FirestoreIndexValueWriter.xt = new __PRIVATE_FirestoreIndexValueWriter();
/**
 * @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 | agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES | CONDITIONS OF ANY KIND, either express | implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const gt = 255;
function __PRIVATE_numberOfLeadingZerosInByte(e2) {
  if (0 === e2) return 8;
  let t2 = 0;
  return e2 >> 4 || // Test if the first four bits are zero.
  (t2 += 4, e2 <<= 4), e2 >> 6 || // Test if the first two (or next two) bits are zero.
  (t2 += 2, e2 <<= 2), e2 >> 7 || // Test if the remaining bit is zero.
  (t2 += 1), t2;
}
__name(__PRIVATE_numberOfLeadingZerosInByte, "__PRIVATE_numberOfLeadingZerosInByte");
function __PRIVATE_unsignedNumLength(e2) {
  const t2 = 64 - (/* @__PURE__ */ __name(function __PRIVATE_numberOfLeadingZeros(e3) {
    let t3 = 0;
    for (let n2 = 0; n2 < 8; ++n2) {
      const r2 = __PRIVATE_numberOfLeadingZerosInByte(255 & e3[n2]);
      if (t3 += r2, 8 !== r2) break;
    }
    return t3;
  }, "__PRIVATE_numberOfLeadingZeros"))(e2);
  return Math.ceil(t2 / 8);
}
__name(__PRIVATE_unsignedNumLength, "__PRIVATE_unsignedNumLength");
class __PRIVATE_OrderedCodeWriter {
  static {
    __name(this, "__PRIVATE_OrderedCodeWriter");
  }
  constructor() {
    this.buffer = new Uint8Array(1024), this.position = 0;
  }
  Ot(e2) {
    const t2 = e2[Symbol.iterator]();
    let n2 = t2.next();
    for (; !n2.done; ) this.Nt(n2.value), n2 = t2.next();
    this.Bt();
  }
  Lt(e2) {
    const t2 = e2[Symbol.iterator]();
    let n2 = t2.next();
    for (; !n2.done; ) this.kt(n2.value), n2 = t2.next();
    this.qt();
  }
  /** Writes utf8 bytes into this byte sequence, ascending. */
  Qt(e2) {
    for (const t2 of e2) {
      const e3 = t2.charCodeAt(0);
      if (e3 < 128) this.Nt(e3);
      else if (e3 < 2048) this.Nt(960 | e3 >>> 6), this.Nt(128 | 63 & e3);
      else if (t2 < "\uD800" || "\uDBFF" < t2) this.Nt(480 | e3 >>> 12), this.Nt(128 | 63 & e3 >>> 6), this.Nt(128 | 63 & e3);
      else {
        const e4 = t2.codePointAt(0);
        this.Nt(240 | e4 >>> 18), this.Nt(128 | 63 & e4 >>> 12), this.Nt(128 | 63 & e4 >>> 6), this.Nt(128 | 63 & e4);
      }
    }
    this.Bt();
  }
  /** Writes utf8 bytes into this byte sequence, descending */
  $t(e2) {
    for (const t2 of e2) {
      const e3 = t2.charCodeAt(0);
      if (e3 < 128) this.kt(e3);
      else if (e3 < 2048) this.kt(960 | e3 >>> 6), this.kt(128 | 63 & e3);
      else if (t2 < "\uD800" || "\uDBFF" < t2) this.kt(480 | e3 >>> 12), this.kt(128 | 63 & e3 >>> 6), this.kt(128 | 63 & e3);
      else {
        const e4 = t2.codePointAt(0);
        this.kt(240 | e4 >>> 18), this.kt(128 | 63 & e4 >>> 12), this.kt(128 | 63 & e4 >>> 6), this.kt(128 | 63 & e4);
      }
    }
    this.qt();
  }
  Ut(e2) {
    const t2 = this.Kt(e2), n2 = __PRIVATE_unsignedNumLength(t2);
    this.Wt(1 + n2), this.buffer[this.position++] = 255 & n2;
    for (let e3 = t2.length - n2; e3 < t2.length; ++e3) this.buffer[this.position++] = 255 & t2[e3];
  }
  Gt(e2) {
    const t2 = this.Kt(e2), n2 = __PRIVATE_unsignedNumLength(t2);
    this.Wt(1 + n2), this.buffer[this.position++] = ~(255 & n2);
    for (let e3 = t2.length - n2; e3 < t2.length; ++e3) this.buffer[this.position++] = ~(255 & t2[e3]);
  }
  /**
   * Writes the "infinity" byte sequence that sorts after all other byte
   * sequences written in ascending order.
   */
  zt() {
    this.jt(gt), this.jt(255);
  }
  /**
   * Writes the "infinity" byte sequence that sorts before all other byte
   * sequences written in descending order.
   */
  Ht() {
    this.Jt(gt), this.Jt(255);
  }
  /**
   * Resets the buffer such that it is the same as when it was newly
   * constructed.
   */
  reset() {
    this.position = 0;
  }
  seed(e2) {
    this.Wt(e2.length), this.buffer.set(e2, this.position), this.position += e2.length;
  }
  /** Makes a copy of the encoded bytes in this buffer.  */
  Yt() {
    return this.buffer.slice(0, this.position);
  }
  /**
   * Encodes `val` into an encoding so that the order matches the IEEE 754
   * floating-point comparison results with the following exceptions:
   *   -0.0 < 0.0
   *   all non-NaN < NaN
   *   NaN = NaN
   */
  Kt(e2) {
    const t2 = (
      /** Converts a JavaScript number to a byte array (using big endian encoding). */
      (/* @__PURE__ */ __name(function __PRIVATE_doubleToLongBits(e3) {
        const t3 = new DataView(new ArrayBuffer(8));
        return t3.setFloat64(
          0,
          e3,
          /* littleEndian= */
          false
        ), new Uint8Array(t3.buffer);
      }, "__PRIVATE_doubleToLongBits"))(e2)
    ), n2 = !!(128 & t2[0]);
    t2[0] ^= n2 ? 255 : 128;
    for (let e3 = 1; e3 < t2.length; ++e3) t2[e3] ^= n2 ? 255 : 0;
    return t2;
  }
  /** Writes a single byte ascending to the buffer. */
  Nt(e2) {
    const t2 = 255 & e2;
    0 === t2 ? (this.jt(0), this.jt(255)) : t2 === gt ? (this.jt(gt), this.jt(0)) : this.jt(t2);
  }
  /** Writes a single byte descending to the buffer.  */
  kt(e2) {
    const t2 = 255 & e2;
    0 === t2 ? (this.Jt(0), this.Jt(255)) : t2 === gt ? (this.Jt(gt), this.Jt(0)) : this.Jt(e2);
  }
  Bt() {
    this.jt(0), this.jt(1);
  }
  qt() {
    this.Jt(0), this.Jt(1);
  }
  jt(e2) {
    this.Wt(1), this.buffer[this.position++] = e2;
  }
  Jt(e2) {
    this.Wt(1), this.buffer[this.position++] = ~e2;
  }
  Wt(e2) {
    const t2 = e2 + this.position;
    if (t2 <= this.buffer.length) return;
    let n2 = 2 * this.buffer.length;
    n2 < t2 && (n2 = t2);
    const r2 = new Uint8Array(n2);
    r2.set(this.buffer), // copy old data
    this.buffer = r2;
  }
}
class __PRIVATE_AscendingIndexByteEncoder {
  static {
    __name(this, "__PRIVATE_AscendingIndexByteEncoder");
  }
  constructor(e2) {
    this.Zt = e2;
  }
  bt(e2) {
    this.Zt.Ot(e2);
  }
  yt(e2) {
    this.Zt.Qt(e2);
  }
  gt(e2) {
    this.Zt.Ut(e2);
  }
  Vt() {
    this.Zt.zt();
  }
}
class __PRIVATE_DescendingIndexByteEncoder {
  static {
    __name(this, "__PRIVATE_DescendingIndexByteEncoder");
  }
  constructor(e2) {
    this.Zt = e2;
  }
  bt(e2) {
    this.Zt.Lt(e2);
  }
  yt(e2) {
    this.Zt.$t(e2);
  }
  gt(e2) {
    this.Zt.Gt(e2);
  }
  Vt() {
    this.Zt.Ht();
  }
}
class __PRIVATE_IndexByteEncoder {
  static {
    __name(this, "__PRIVATE_IndexByteEncoder");
  }
  constructor() {
    this.Zt = new __PRIVATE_OrderedCodeWriter(), this.Xt = new __PRIVATE_AscendingIndexByteEncoder(this.Zt), this.en = new __PRIVATE_DescendingIndexByteEncoder(this.Zt);
  }
  seed(e2) {
    this.Zt.seed(e2);
  }
  tn(e2) {
    return 0 === e2 ? this.Xt : this.en;
  }
  Yt() {
    return this.Zt.Yt();
  }
  reset() {
    this.Zt.reset();
  }
}
/**
 * @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.
 */
class __PRIVATE_IndexEntry {
  static {
    __name(this, "__PRIVATE_IndexEntry");
  }
  constructor(e2, t2, n2, r2) {
    this.indexId = e2, this.documentKey = t2, this.arrayValue = n2, this.directionalValue = r2;
  }
  /**
   * Returns an IndexEntry entry that sorts immediately after the current
   * directional value.
   */
  nn() {
    const e2 = this.directionalValue.length, t2 = 0 === e2 || 255 === this.directionalValue[e2 - 1] ? e2 + 1 : e2, n2 = new Uint8Array(t2);
    return n2.set(this.directionalValue, 0), t2 !== e2 ? n2.set([0], this.directionalValue.length) : ++n2[n2.length - 1], new __PRIVATE_IndexEntry(this.indexId, this.documentKey, this.arrayValue, n2);
  }
}
function __PRIVATE_indexEntryComparator(e2, t2) {
  let n2 = e2.indexId - t2.indexId;
  return 0 !== n2 ? n2 : (n2 = __PRIVATE_compareByteArrays(e2.arrayValue, t2.arrayValue), 0 !== n2 ? n2 : (n2 = __PRIVATE_compareByteArrays(e2.directionalValue, t2.directionalValue), 0 !== n2 ? n2 : DocumentKey.comparator(e2.documentKey, t2.documentKey)));
}
__name(__PRIVATE_indexEntryComparator, "__PRIVATE_indexEntryComparator");
function __PRIVATE_compareByteArrays(e2, t2) {
  for (let n2 = 0; n2 < e2.length && n2 < t2.length; ++n2) {
    const r2 = e2[n2] - t2[n2];
    if (0 !== r2) return r2;
  }
  return e2.length - t2.length;
}
__name(__PRIVATE_compareByteArrays, "__PRIVATE_compareByteArrays");
/**
 * @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.
 */
class __PRIVATE_TargetIndexMatcher {
  static {
    __name(this, "__PRIVATE_TargetIndexMatcher");
  }
  constructor(e2) {
    this.rn = new SortedSet((e3, t2) => FieldPath$1.comparator(e3.field, t2.field)), this.collectionId = null != e2.collectionGroup ? e2.collectionGroup : e2.path.lastSegment(), this.sn = e2.orderBy, this._n = [];
    for (const t2 of e2.filters) {
      const e3 = t2;
      e3.isInequality() ? this.rn = this.rn.add(e3) : this._n.push(e3);
    }
  }
  get an() {
    return this.rn.size > 1;
  }
  /**
   * Returns whether the index can be used to serve the TargetIndexMatcher's
   * target.
   *
   * An index is considered capable of serving the target when:
   * - The target uses all index segments for its filters and orderBy clauses.
   *   The target can have additional filter and orderBy clauses, but not
   *   fewer.
   * - If an ArrayContains/ArrayContainsAnyfilter is used, the index must also
   *   have a corresponding `CONTAINS` segment.
   * - All directional index segments can be mapped to the target as a series of
   *   equality filters, a single inequality filter and a series of orderBy
   *   clauses.
   * - The segments that represent the equality filters may appear out of order.
   * - The optional segment for the inequality filter must appear after all
   *   equality segments.
   * - The segments that represent that orderBy clause of the target must appear
   *   in order after all equality and inequality segments. Single orderBy
   *   clauses cannot be skipped, but a continuous orderBy suffix may be
   *   omitted.
   */
  un(e2) {
    if (__PRIVATE_hardAssert(e2.collectionGroup === this.collectionId), this.an)
      return false;
    const t2 = __PRIVATE_fieldIndexGetArraySegment(e2);
    if (void 0 !== t2 && !this.cn(t2)) return false;
    const n2 = __PRIVATE_fieldIndexGetDirectionalSegments(e2);
    let r2 = /* @__PURE__ */ new Set(), i2 = 0, s2 = 0;
    for (; i2 < n2.length && this.cn(n2[i2]); ++i2) r2 = r2.add(n2[i2].fieldPath.canonicalString());
    if (i2 === n2.length) return true;
    if (this.rn.size > 0) {
      const e3 = this.rn.getIterator().getNext();
      if (!r2.has(e3.field.canonicalString())) {
        const t3 = n2[i2];
        if (!this.ln(e3, t3) || !this.hn(this.sn[s2++], t3)) return false;
      }
      ++i2;
    }
    for (; i2 < n2.length; ++i2) {
      const e3 = n2[i2];
      if (s2 >= this.sn.length || !this.hn(this.sn[s2++], e3)) return false;
    }
    return true;
  }
  /**
   * Returns a full matched field index for this target. Currently multiple
   * inequality query is not supported so function returns null.
   */
  Pn() {
    if (this.an) return null;
    let e2 = new SortedSet(FieldPath$1.comparator);
    const t2 = [];
    for (const n2 of this._n) {
      if (n2.field.isKeyField()) continue;
      if ("array-contains" === n2.op || "array-contains-any" === n2.op) t2.push(new IndexSegment(
        n2.field,
        2
        /* IndexKind.CONTAINS */
      ));
      else {
        if (e2.has(n2.field)) continue;
        e2 = e2.add(n2.field), t2.push(new IndexSegment(
          n2.field,
          0
          /* IndexKind.ASCENDING */
        ));
      }
    }
    for (const n2 of this.sn)
      n2.field.isKeyField() || e2.has(n2.field) || (e2 = e2.add(n2.field), t2.push(new IndexSegment(
        n2.field,
        "asc" === n2.dir ? 0 : 1
        /* IndexKind.DESCENDING */
      )));
    return new FieldIndex(FieldIndex.UNKNOWN_ID, this.collectionId, t2, IndexState.empty());
  }
  cn(e2) {
    for (const t2 of this._n) if (this.ln(t2, e2)) return true;
    return false;
  }
  ln(e2, t2) {
    if (void 0 === e2 || !e2.field.isEqual(t2.fieldPath)) return false;
    const n2 = "array-contains" === e2.op || "array-contains-any" === e2.op;
    return 2 === t2.kind === n2;
  }
  hn(e2, t2) {
    return !!e2.field.isEqual(t2.fieldPath) && (0 === t2.kind && "asc" === e2.dir || 1 === t2.kind && "desc" === e2.dir);
  }
}
/**
 * @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 __PRIVATE_computeInExpansion(e2) {
  var t2, n2;
  if (__PRIVATE_hardAssert(e2 instanceof FieldFilter || e2 instanceof CompositeFilter), e2 instanceof FieldFilter) {
    if (e2 instanceof __PRIVATE_InFilter) {
      const r3 = (null === (n2 = null === (t2 = e2.value.arrayValue) || void 0 === t2 ? void 0 : t2.values) || void 0 === n2 ? void 0 : n2.map((t3) => FieldFilter.create(e2.field, "==", t3))) || [];
      return CompositeFilter.create(
        r3,
        "or"
        /* CompositeOperator.OR */
      );
    }
    return e2;
  }
  const r2 = e2.filters.map((e3) => __PRIVATE_computeInExpansion(e3));
  return CompositeFilter.create(r2, e2.op);
}
__name(__PRIVATE_computeInExpansion, "__PRIVATE_computeInExpansion");
function __PRIVATE_getDnfTerms(e2) {
  if (0 === e2.getFilters().length) return [];
  const t2 = __PRIVATE_computeDistributedNormalForm(__PRIVATE_computeInExpansion(e2));
  return __PRIVATE_hardAssert(__PRIVATE_isDisjunctiveNormalForm(t2)), __PRIVATE_isSingleFieldFilter(t2) || __PRIVATE_isFlatConjunction(t2) ? [t2] : t2.getFilters();
}
__name(__PRIVATE_getDnfTerms, "__PRIVATE_getDnfTerms");
function __PRIVATE_isSingleFieldFilter(e2) {
  return e2 instanceof FieldFilter;
}
__name(__PRIVATE_isSingleFieldFilter, "__PRIVATE_isSingleFieldFilter");
function __PRIVATE_isFlatConjunction(e2) {
  return e2 instanceof CompositeFilter && __PRIVATE_compositeFilterIsFlatConjunction(e2);
}
__name(__PRIVATE_isFlatConjunction, "__PRIVATE_isFlatConjunction");
function __PRIVATE_isDisjunctiveNormalForm(e2) {
  return __PRIVATE_isSingleFieldFilter(e2) || __PRIVATE_isFlatConjunction(e2) || /**
  * Returns true if the given filter is the disjunction of one or more "flat conjunctions" and
  * field filters. e.g. (a == 10) || (b==20 && c==30)
  */
  (/* @__PURE__ */ __name(function __PRIVATE_isDisjunctionOfFieldFiltersAndFlatConjunctions(e3) {
    if (e3 instanceof CompositeFilter && __PRIVATE_compositeFilterIsDisjunction(e3)) {
      for (const t2 of e3.getFilters()) if (!__PRIVATE_isSingleFieldFilter(t2) && !__PRIVATE_isFlatConjunction(t2)) return false;
      return true;
    }
    return false;
  }, "__PRIVATE_isDisjunctionOfFieldFiltersAndFlatConjunctions"))(e2);
}
__name(__PRIVATE_isDisjunctiveNormalForm, "__PRIVATE_isDisjunctiveNormalForm");
function __PRIVATE_computeDistributedNormalForm(e2) {
  if (__PRIVATE_hardAssert(e2 instanceof FieldFilter || e2 instanceof CompositeFilter), e2 instanceof FieldFilter) return e2;
  if (1 === e2.filters.length) return __PRIVATE_computeDistributedNormalForm(e2.filters[0]);
  const t2 = e2.filters.map((e3) => __PRIVATE_computeDistributedNormalForm(e3));
  let n2 = CompositeFilter.create(t2, e2.op);
  return n2 = __PRIVATE_applyAssociation(n2), __PRIVATE_isDisjunctiveNormalForm(n2) ? n2 : (__PRIVATE_hardAssert(n2 instanceof CompositeFilter), __PRIVATE_hardAssert(__PRIVATE_compositeFilterIsConjunction(n2)), __PRIVATE_hardAssert(n2.filters.length > 1), n2.filters.reduce((e3, t3) => __PRIVATE_applyDistribution(e3, t3)));
}
__name(__PRIVATE_computeDistributedNormalForm, "__PRIVATE_computeDistributedNormalForm");
function __PRIVATE_applyDistribution(e2, t2) {
  let n2;
  return __PRIVATE_hardAssert(e2 instanceof FieldFilter || e2 instanceof CompositeFilter), __PRIVATE_hardAssert(t2 instanceof FieldFilter || t2 instanceof CompositeFilter), // FieldFilter FieldFilter
  n2 = e2 instanceof FieldFilter ? t2 instanceof FieldFilter ? (/* @__PURE__ */ __name(function __PRIVATE_applyDistributionFieldFilters(e3, t3) {
    return CompositeFilter.create(
      [e3, t3],
      "and"
      /* CompositeOperator.AND */
    );
  }, "__PRIVATE_applyDistributionFieldFilters"))(e2, t2) : __PRIVATE_applyDistributionFieldAndCompositeFilters(e2, t2) : t2 instanceof FieldFilter ? __PRIVATE_applyDistributionFieldAndCompositeFilters(t2, e2) : (/* @__PURE__ */ __name(function __PRIVATE_applyDistributionCompositeFilters(e3, t3) {
    if (__PRIVATE_hardAssert(e3.filters.length > 0 && t3.filters.length > 0), __PRIVATE_compositeFilterIsConjunction(e3) && __PRIVATE_compositeFilterIsConjunction(t3)) return __PRIVATE_compositeFilterWithAddedFilters(e3, t3.getFilters());
    const n3 = __PRIVATE_compositeFilterIsDisjunction(e3) ? e3 : t3, r2 = __PRIVATE_compositeFilterIsDisjunction(e3) ? t3 : e3, i2 = n3.filters.map((e4) => __PRIVATE_applyDistribution(e4, r2));
    return CompositeFilter.create(
      i2,
      "or"
      /* CompositeOperator.OR */
    );
  }, "__PRIVATE_applyDistributionCompositeFilters"))(e2, t2), __PRIVATE_applyAssociation(n2);
}
__name(__PRIVATE_applyDistribution, "__PRIVATE_applyDistribution");
function __PRIVATE_applyDistributionFieldAndCompositeFilters(e2, t2) {
  if (__PRIVATE_compositeFilterIsConjunction(t2))
    return __PRIVATE_compositeFilterWithAddedFilters(t2, e2.getFilters());
  {
    const n2 = t2.filters.map((t3) => __PRIVATE_applyDistribution(e2, t3));
    return CompositeFilter.create(
      n2,
      "or"
      /* CompositeOperator.OR */
    );
  }
}
__name(__PRIVATE_applyDistributionFieldAndCompositeFilters, "__PRIVATE_applyDistributionFieldAndCompositeFilters");
function __PRIVATE_applyAssociation(e2) {
  if (__PRIVATE_hardAssert(e2 instanceof FieldFilter || e2 instanceof CompositeFilter), e2 instanceof FieldFilter) return e2;
  const t2 = e2.getFilters();
  if (1 === t2.length) return __PRIVATE_applyAssociation(t2[0]);
  if (__PRIVATE_compositeFilterIsFlat(e2)) return e2;
  const n2 = t2.map((e3) => __PRIVATE_applyAssociation(e3)), r2 = [];
  return n2.forEach((t3) => {
    t3 instanceof FieldFilter ? r2.push(t3) : t3 instanceof CompositeFilter && (t3.op === e2.op ? (
      // compositeFilter: (A | (B | C))
      // compositeSubfilter: (B | C)
      // Result: (A | B | C)
      r2.push(...t3.filters)
    ) : (
      // compositeFilter: (A | (B & C))
      // compositeSubfilter: (B & C)
      // Result: (A | (B & C))
      r2.push(t3)
    ));
  }), 1 === r2.length ? r2[0] : CompositeFilter.create(r2, e2.op);
}
__name(__PRIVATE_applyAssociation, "__PRIVATE_applyAssociation");
/**
 * @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 __PRIVATE_MemoryIndexManager {
  static {
    __name(this, "__PRIVATE_MemoryIndexManager");
  }
  constructor() {
    this.Tn = new __PRIVATE_MemoryCollectionParentIndex();
  }
  addToCollectionParentIndex(e2, t2) {
    return this.Tn.add(t2), PersistencePromise.resolve();
  }
  getCollectionParents(e2, t2) {
    return PersistencePromise.resolve(this.Tn.getEntries(t2));
  }
  addFieldIndex(e2, t2) {
    return PersistencePromise.resolve();
  }
  deleteFieldIndex(e2, t2) {
    return PersistencePromise.resolve();
  }
  deleteAllFieldIndexes(e2) {
    return PersistencePromise.resolve();
  }
  createTargetIndexes(e2, t2) {
    return PersistencePromise.resolve();
  }
  getDocumentsMatchingTarget(e2, t2) {
    return PersistencePromise.resolve(null);
  }
  getIndexType(e2, t2) {
    return PersistencePromise.resolve(
      0
      /* IndexType.NONE */
    );
  }
  getFieldIndexes(e2, t2) {
    return PersistencePromise.resolve([]);
  }
  getNextCollectionGroupToUpdate(e2) {
    return PersistencePromise.resolve(null);
  }
  getMinOffset(e2, t2) {
    return PersistencePromise.resolve(IndexOffset.min());
  }
  getMinOffsetFromCollectionGroup(e2, t2) {
    return PersistencePromise.resolve(IndexOffset.min());
  }
  updateCollectionGroup(e2, t2, n2) {
    return PersistencePromise.resolve();
  }
  updateIndexEntries(e2, t2) {
    return PersistencePromise.resolve();
  }
}
class __PRIVATE_MemoryCollectionParentIndex {
  static {
    __name(this, "__PRIVATE_MemoryCollectionParentIndex");
  }
  constructor() {
    this.index = {};
  }
  // Returns false if the entry already existed.
  add(e2) {
    const t2 = e2.lastSegment(), n2 = e2.popLast(), r2 = this.index[t2] || new SortedSet(ResourcePath.comparator), i2 = !r2.has(n2);
    return this.index[t2] = r2.add(n2), i2;
  }
  has(e2) {
    const t2 = e2.lastSegment(), n2 = e2.popLast(), r2 = this.index[t2];
    return r2 && r2.has(n2);
  }
  getEntries(e2) {
    return (this.index[e2] || new SortedSet(ResourcePath.comparator)).toArray();
  }
}
/**
 * @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 pt = "IndexedDbIndexManager", yt = new Uint8Array(0);
class __PRIVATE_IndexedDbIndexManager {
  static {
    __name(this, "__PRIVATE_IndexedDbIndexManager");
  }
  constructor(e2, t2) {
    this.databaseId = t2, /**
     * An in-memory copy of the index entries we've already written since the SDK
     * launched. Used to avoid re-writing the same entry repeatedly.
     *
     * This is *NOT* a complete cache of what's in persistence and so can never be
     * used to satisfy reads.
     */
    this.In = new __PRIVATE_MemoryCollectionParentIndex(), /**
     * Maps from a target to its equivalent list of sub-targets. Each sub-target
     * contains only one term from the target's disjunctive normal form (DNF).
     */
    this.En = new ObjectMap((e3) => __PRIVATE_canonifyTarget(e3), (e3, t3) => __PRIVATE_targetEquals(e3, t3)), this.uid = e2.uid || "";
  }
  /**
   * Adds a new entry to the collection parent index.
   *
   * Repeated calls for the same collectionPath should be avoided within a
   * transaction as IndexedDbIndexManager only caches writes once a transaction
   * has been committed.
   */
  addToCollectionParentIndex(e2, t2) {
    if (!this.In.has(t2)) {
      const n2 = t2.lastSegment(), r2 = t2.popLast();
      e2.addOnCommittedListener(() => {
        this.In.add(t2);
      });
      const i2 = {
        collectionId: n2,
        parent: __PRIVATE_encodeResourcePath(r2)
      };
      return __PRIVATE_collectionParentsStore(e2).put(i2);
    }
    return PersistencePromise.resolve();
  }
  getCollectionParents(e2, t2) {
    const n2 = [], r2 = IDBKeyRange.bound(
      [t2, ""],
      [__PRIVATE_immediateSuccessor(t2), ""],
      /*lowerOpen=*/
      false,
      /*upperOpen=*/
      true
    );
    return __PRIVATE_collectionParentsStore(e2).G(r2).next((e3) => {
      for (const r3 of e3) {
        if (r3.collectionId !== t2) break;
        n2.push(__PRIVATE_decodeResourcePath(r3.parent));
      }
      return n2;
    });
  }
  addFieldIndex(e2, t2) {
    const n2 = __PRIVATE_indexConfigurationStore(e2), r2 = (/* @__PURE__ */ __name(function __PRIVATE_toDbIndexConfiguration(e3) {
      return {
        indexId: e3.indexId,
        collectionGroup: e3.collectionGroup,
        fields: e3.fields.map((e4) => [e4.fieldPath.canonicalString(), e4.kind])
      };
    }, "__PRIVATE_toDbIndexConfiguration"))(t2);
    delete r2.indexId;
    const i2 = n2.add(r2);
    if (t2.indexState) {
      const n3 = __PRIVATE_indexStateStore(e2);
      return i2.next((e3) => {
        n3.put(__PRIVATE_toDbIndexState(e3, this.uid, t2.indexState.sequenceNumber, t2.indexState.offset));
      });
    }
    return i2.next();
  }
  deleteFieldIndex(e2, t2) {
    const n2 = __PRIVATE_indexConfigurationStore(e2), r2 = __PRIVATE_indexStateStore(e2), i2 = __PRIVATE_indexEntriesStore(e2);
    return n2.delete(t2.indexId).next(() => r2.delete(IDBKeyRange.bound(
      [t2.indexId],
      [t2.indexId + 1],
      /*lowerOpen=*/
      false,
      /*upperOpen=*/
      true
    ))).next(() => i2.delete(IDBKeyRange.bound(
      [t2.indexId],
      [t2.indexId + 1],
      /*lowerOpen=*/
      false,
      /*upperOpen=*/
      true
    )));
  }
  deleteAllFieldIndexes(e2) {
    const t2 = __PRIVATE_indexConfigurationStore(e2), n2 = __PRIVATE_indexEntriesStore(e2), r2 = __PRIVATE_indexStateStore(e2);
    return t2.J().next(() => n2.J()).next(() => r2.J());
  }
  createTargetIndexes(e2, t2) {
    return PersistencePromise.forEach(this.dn(t2), (t3) => this.getIndexType(e2, t3).next((n2) => {
      if (0 === n2 || 1 === n2) {
        const n3 = new __PRIVATE_TargetIndexMatcher(t3).Pn();
        if (null != n3) return this.addFieldIndex(e2, n3);
      }
    }));
  }
  getDocumentsMatchingTarget(e2, t2) {
    const n2 = __PRIVATE_indexEntriesStore(e2);
    let r2 = true;
    const i2 = /* @__PURE__ */ new Map();
    return PersistencePromise.forEach(this.dn(t2), (t3) => this.An(e2, t3).next((e3) => {
      r2 && (r2 = !!e3), i2.set(t3, e3);
    })).next(() => {
      if (r2) {
        let e3 = __PRIVATE_documentKeySet();
        const r3 = [];
        return PersistencePromise.forEach(i2, (i3, s2) => {
          __PRIVATE_logDebug(pt, `Using index ${(/* @__PURE__ */ __name(function __PRIVATE_fieldIndexToString(e4) {
            return `id=${e4.indexId}|cg=${e4.collectionGroup}|f=${e4.fields.map((e5) => `${e5.fieldPath}:${e5.kind}`).join(",")}`;
          }, "__PRIVATE_fieldIndexToString"))(i3)} to execute ${__PRIVATE_canonifyTarget(t2)}`);
          const o2 = (/* @__PURE__ */ __name(function __PRIVATE_targetGetArrayValues(e4, t3) {
            const n3 = __PRIVATE_fieldIndexGetArraySegment(t3);
            if (void 0 === n3) return null;
            for (const t4 of __PRIVATE_targetGetFieldFiltersForPath(e4, n3.fieldPath)) switch (t4.op) {
              case "array-contains-any":
                return t4.value.arrayValue.values || [];
              case "array-contains":
                return [t4.value];
            }
            return null;
          }, "__PRIVATE_targetGetArrayValues"))(s2, i3), _2 = (/* @__PURE__ */ __name(function __PRIVATE_targetGetNotInValues(e4, t3) {
            const n3 = /* @__PURE__ */ new Map();
            for (const r4 of __PRIVATE_fieldIndexGetDirectionalSegments(t3)) for (const t4 of __PRIVATE_targetGetFieldFiltersForPath(e4, r4.fieldPath)) switch (t4.op) {
              case "==":
              case "in":
                n3.set(r4.fieldPath.canonicalString(), t4.value);
                break;
              case "not-in":
              case "!=":
                return n3.set(r4.fieldPath.canonicalString(), t4.value), Array.from(n3.values());
            }
            return null;
          }, "__PRIVATE_targetGetNotInValues"))(s2, i3), a2 = (/* @__PURE__ */ __name(function __PRIVATE_targetGetLowerBound(e4, t3) {
            const n3 = [];
            let r4 = true;
            for (const i4 of __PRIVATE_fieldIndexGetDirectionalSegments(t3)) {
              const t4 = 0 === i4.kind ? __PRIVATE_targetGetAscendingBound(e4, i4.fieldPath, e4.startAt) : __PRIVATE_targetGetDescendingBound(e4, i4.fieldPath, e4.startAt);
              n3.push(t4.value), r4 && (r4 = t4.inclusive);
            }
            return new Bound(n3, r4);
          }, "__PRIVATE_targetGetLowerBound"))(s2, i3), u2 = (/* @__PURE__ */ __name(function __PRIVATE_targetGetUpperBound(e4, t3) {
            const n3 = [];
            let r4 = true;
            for (const i4 of __PRIVATE_fieldIndexGetDirectionalSegments(t3)) {
              const t4 = 0 === i4.kind ? __PRIVATE_targetGetDescendingBound(e4, i4.fieldPath, e4.endAt) : __PRIVATE_targetGetAscendingBound(e4, i4.fieldPath, e4.endAt);
              n3.push(t4.value), r4 && (r4 = t4.inclusive);
            }
            return new Bound(n3, r4);
          }, "__PRIVATE_targetGetUpperBound"))(s2, i3), c2 = this.Rn(i3, s2, a2), l2 = this.Rn(i3, s2, u2), h2 = this.Vn(i3, s2, _2), P2 = this.mn(i3.indexId, o2, c2, a2.inclusive, l2, u2.inclusive, h2);
          return PersistencePromise.forEach(P2, (i4) => n2.H(i4, t2.limit).next((t3) => {
            t3.forEach((t4) => {
              const n3 = DocumentKey.fromSegments(t4.documentKey);
              e3.has(n3) || (e3 = e3.add(n3), r3.push(n3));
            });
          }));
        }).next(() => r3);
      }
      return PersistencePromise.resolve(null);
    });
  }
  dn(e2) {
    let t2 = this.En.get(e2);
    if (t2) return t2;
    if (0 === e2.filters.length) t2 = [e2];
    else {
      t2 = __PRIVATE_getDnfTerms(CompositeFilter.create(
        e2.filters,
        "and"
        /* CompositeOperator.AND */
      )).map((t3) => __PRIVATE_newTarget(e2.path, e2.collectionGroup, e2.orderBy, t3.getFilters(), e2.limit, e2.startAt, e2.endAt));
    }
    return this.En.set(e2, t2), t2;
  }
  /**
   * Constructs a key range query on `DbIndexEntryStore` that unions all
   * bounds.
   */
  mn(e2, t2, n2, r2, i2, s2, o2) {
    const _2 = (null != t2 ? t2.length : 1) * Math.max(n2.length, i2.length), a2 = _2 / (null != t2 ? t2.length : 1), u2 = [];
    for (let c2 = 0; c2 < _2; ++c2) {
      const _3 = t2 ? this.fn(t2[c2 / a2]) : yt, l2 = this.gn(e2, _3, n2[c2 % a2], r2), h2 = this.pn(e2, _3, i2[c2 % a2], s2), P2 = o2.map((t3) => this.gn(
        e2,
        _3,
        t3,
        /* inclusive= */
        true
      ));
      u2.push(...this.createRange(l2, h2, P2));
    }
    return u2;
  }
  /** Generates the lower bound for `arrayValue` and `directionalValue`. */
  gn(e2, t2, n2, r2) {
    const i2 = new __PRIVATE_IndexEntry(e2, DocumentKey.empty(), t2, n2);
    return r2 ? i2 : i2.nn();
  }
  /** Generates the upper bound for `arrayValue` and `directionalValue`. */
  pn(e2, t2, n2, r2) {
    const i2 = new __PRIVATE_IndexEntry(e2, DocumentKey.empty(), t2, n2);
    return r2 ? i2.nn() : i2;
  }
  An(e2, t2) {
    const n2 = new __PRIVATE_TargetIndexMatcher(t2), r2 = null != t2.collectionGroup ? t2.collectionGroup : t2.path.lastSegment();
    return this.getFieldIndexes(e2, r2).next((e3) => {
      let t3 = null;
      for (const r3 of e3) {
        n2.un(r3) && (!t3 || r3.fields.length > t3.fields.length) && (t3 = r3);
      }
      return t3;
    });
  }
  getIndexType(e2, t2) {
    let n2 = 2;
    const r2 = this.dn(t2);
    return PersistencePromise.forEach(r2, (t3) => this.An(e2, t3).next((e3) => {
      e3 ? 0 !== n2 && e3.fields.length < (/* @__PURE__ */ __name(function __PRIVATE_targetGetSegmentCount(e4) {
        let t4 = new SortedSet(FieldPath$1.comparator), n3 = false;
        for (const r3 of e4.filters) for (const e5 of r3.getFlattenedFilters())
          e5.field.isKeyField() || // ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filters must be counted separately.
          // For instance, it is possible to have an index for "a ARRAY a ASC". Even
          // though these are on the same field, they should be counted as two
          // separate segments in an index.
          ("array-contains" === e5.op || "array-contains-any" === e5.op ? n3 = true : t4 = t4.add(e5.field));
        for (const n4 of e4.orderBy)
          n4.field.isKeyField() || (t4 = t4.add(n4.field));
        return t4.size + (n3 ? 1 : 0);
      }, "__PRIVATE_targetGetSegmentCount"))(t3) && (n2 = 1) : n2 = 0;
    })).next(() => (
      // OR queries have more than one sub-target (one sub-target per DNF term). We currently consider
      // OR queries that have a `limit` to have a partial index. For such queries we perform sorting
      // and apply the limit in memory as a post-processing step.
      (/* @__PURE__ */ __name(function __PRIVATE_targetHasLimit(e3) {
        return null !== e3.limit;
      }, "__PRIVATE_targetHasLimit"))(t2) && r2.length > 1 && 2 === n2 ? 1 : n2
    ));
  }
  /**
   * Returns the byte encoded form of the directional values in the field index.
   * Returns `null` if the document does not have all fields specified in the
   * index.
   */
  yn(e2, t2) {
    const n2 = new __PRIVATE_IndexByteEncoder();
    for (const r2 of __PRIVATE_fieldIndexGetDirectionalSegments(e2)) {
      const e3 = t2.data.field(r2.fieldPath);
      if (null == e3) return null;
      const i2 = n2.tn(r2.kind);
      __PRIVATE_FirestoreIndexValueWriter.xt.At(e3, i2);
    }
    return n2.Yt();
  }
  /** Encodes a single value to the ascending index format. */
  fn(e2) {
    const t2 = new __PRIVATE_IndexByteEncoder();
    return __PRIVATE_FirestoreIndexValueWriter.xt.At(e2, t2.tn(
      0
      /* IndexKind.ASCENDING */
    )), t2.Yt();
  }
  /**
   * Returns an encoded form of the document key that sorts based on the key
   * ordering of the field index.
   */
  wn(e2, t2) {
    const n2 = new __PRIVATE_IndexByteEncoder();
    return __PRIVATE_FirestoreIndexValueWriter.xt.At(__PRIVATE_refValue(this.databaseId, t2), n2.tn((/* @__PURE__ */ __name(function __PRIVATE_fieldIndexGetKeyOrder(e3) {
      const t3 = __PRIVATE_fieldIndexGetDirectionalSegments(e3);
      return 0 === t3.length ? 0 : t3[t3.length - 1].kind;
    }, "__PRIVATE_fieldIndexGetKeyOrder"))(e2))), n2.Yt();
  }
  /**
   * Encodes the given field values according to the specification in `target`.
   * For IN queries, a list of possible values is returned.
   */
  Vn(e2, t2, n2) {
    if (null === n2) return [];
    let r2 = [];
    r2.push(new __PRIVATE_IndexByteEncoder());
    let i2 = 0;
    for (const s2 of __PRIVATE_fieldIndexGetDirectionalSegments(e2)) {
      const e3 = n2[i2++];
      for (const n3 of r2) if (this.Sn(t2, s2.fieldPath) && isArray$a(e3)) r2 = this.bn(r2, s2, e3);
      else {
        const t3 = n3.tn(s2.kind);
        __PRIVATE_FirestoreIndexValueWriter.xt.At(e3, t3);
      }
    }
    return this.Dn(r2);
  }
  /**
   * Encodes the given bounds according to the specification in `target`. For IN
   * queries, a list of possible values is returned.
   */
  Rn(e2, t2, n2) {
    return this.Vn(e2, t2, n2.position);
  }
  /** Returns the byte representation for the provided encoders. */
  Dn(e2) {
    const t2 = [];
    for (let n2 = 0; n2 < e2.length; ++n2) t2[n2] = e2[n2].Yt();
    return t2;
  }
  /**
   * Creates a separate encoder for each element of an array.
   *
   * The method appends each value to all existing encoders (e.g. filter("a",
   * "==", "a1").filter("b", "in", ["b1", "b2"]) becomes ["a1,b1", "a1,b2"]). A
   * list of new encoders is returned.
   */
  bn(e2, t2, n2) {
    const r2 = [...e2], i2 = [];
    for (const e3 of n2.arrayValue.values || []) for (const n3 of r2) {
      const r3 = new __PRIVATE_IndexByteEncoder();
      r3.seed(n3.Yt()), __PRIVATE_FirestoreIndexValueWriter.xt.At(e3, r3.tn(t2.kind)), i2.push(r3);
    }
    return i2;
  }
  Sn(e2, t2) {
    return !!e2.filters.find((e3) => e3 instanceof FieldFilter && e3.field.isEqual(t2) && ("in" === e3.op || "not-in" === e3.op));
  }
  getFieldIndexes(e2, t2) {
    const n2 = __PRIVATE_indexConfigurationStore(e2), r2 = __PRIVATE_indexStateStore(e2);
    return (t2 ? n2.G(Se, IDBKeyRange.bound(t2, t2)) : n2.G()).next((e3) => {
      const t3 = [];
      return PersistencePromise.forEach(e3, (e4) => r2.get([e4.indexId, this.uid]).next((n3) => {
        t3.push((/* @__PURE__ */ __name(function __PRIVATE_fromDbIndexConfiguration(e5, t4) {
          const n4 = t4 ? new IndexState(t4.sequenceNumber, new IndexOffset(__PRIVATE_fromDbTimestamp(t4.readTime), new DocumentKey(__PRIVATE_decodeResourcePath(t4.documentKey)), t4.largestBatchId)) : IndexState.empty(), r3 = e5.fields.map(([e6, t5]) => new IndexSegment(FieldPath$1.fromServerFormat(e6), t5));
          return new FieldIndex(e5.indexId, e5.collectionGroup, r3, n4);
        }, "__PRIVATE_fromDbIndexConfiguration"))(e4, n3));
      })).next(() => t3);
    });
  }
  getNextCollectionGroupToUpdate(e2) {
    return this.getFieldIndexes(e2).next((e3) => 0 === e3.length ? null : (e3.sort((e4, t2) => {
      const n2 = e4.indexState.sequenceNumber - t2.indexState.sequenceNumber;
      return 0 !== n2 ? n2 : __PRIVATE_primitiveComparator(e4.collectionGroup, t2.collectionGroup);
    }), e3[0].collectionGroup));
  }
  updateCollectionGroup(e2, t2, n2) {
    const r2 = __PRIVATE_indexConfigurationStore(e2), i2 = __PRIVATE_indexStateStore(e2);
    return this.vn(e2).next((e3) => r2.G(Se, IDBKeyRange.bound(t2, t2)).next((t3) => PersistencePromise.forEach(t3, (t4) => i2.put(__PRIVATE_toDbIndexState(t4.indexId, this.uid, e3, n2)))));
  }
  updateIndexEntries(e2, t2) {
    const n2 = /* @__PURE__ */ new Map();
    return PersistencePromise.forEach(t2, (t3, r2) => {
      const i2 = n2.get(t3.collectionGroup);
      return (i2 ? PersistencePromise.resolve(i2) : this.getFieldIndexes(e2, t3.collectionGroup)).next((i3) => (n2.set(t3.collectionGroup, i3), PersistencePromise.forEach(i3, (n3) => this.Cn(e2, t3, n3).next((t4) => {
        const i4 = this.Fn(r2, n3);
        return t4.isEqual(i4) ? PersistencePromise.resolve() : this.Mn(e2, r2, n3, t4, i4);
      }))));
    });
  }
  xn(e2, t2, n2, r2) {
    return __PRIVATE_indexEntriesStore(e2).put({
      indexId: r2.indexId,
      uid: this.uid,
      arrayValue: r2.arrayValue,
      directionalValue: r2.directionalValue,
      orderedDocumentKey: this.wn(n2, t2.key),
      documentKey: t2.key.path.toArray()
    });
  }
  On(e2, t2, n2, r2) {
    return __PRIVATE_indexEntriesStore(e2).delete([r2.indexId, this.uid, r2.arrayValue, r2.directionalValue, this.wn(n2, t2.key), t2.key.path.toArray()]);
  }
  Cn(e2, t2, n2) {
    const r2 = __PRIVATE_indexEntriesStore(e2);
    let i2 = new SortedSet(__PRIVATE_indexEntryComparator);
    return r2.Z({
      index: Oe,
      range: IDBKeyRange.only([n2.indexId, this.uid, this.wn(n2, t2)])
    }, (e3, r3) => {
      i2 = i2.add(new __PRIVATE_IndexEntry(n2.indexId, t2, r3.arrayValue, r3.directionalValue));
    }).next(() => i2);
  }
  /** Creates the index entries for the given document. */
  Fn(e2, t2) {
    let n2 = new SortedSet(__PRIVATE_indexEntryComparator);
    const r2 = this.yn(t2, e2);
    if (null == r2) return n2;
    const i2 = __PRIVATE_fieldIndexGetArraySegment(t2);
    if (null != i2) {
      const s2 = e2.data.field(i2.fieldPath);
      if (isArray$a(s2)) for (const i3 of s2.arrayValue.values || []) n2 = n2.add(new __PRIVATE_IndexEntry(t2.indexId, e2.key, this.fn(i3), r2));
    } else n2 = n2.add(new __PRIVATE_IndexEntry(t2.indexId, e2.key, yt, r2));
    return n2;
  }
  /**
   * Updates the index entries for the provided document by deleting entries
   * that are no longer referenced in `newEntries` and adding all newly added
   * entries.
   */
  Mn(e2, t2, n2, r2, i2) {
    __PRIVATE_logDebug(pt, "Updating index entries for document '%s'", t2.key);
    const s2 = [];
    return (/* @__PURE__ */ __name(function __PRIVATE_diffSortedSets(e3, t3, n3, r3, i3) {
      const s3 = e3.getIterator(), o2 = t3.getIterator();
      let _2 = __PRIVATE_advanceIterator(s3), a2 = __PRIVATE_advanceIterator(o2);
      for (; _2 || a2; ) {
        let e4 = false, t4 = false;
        if (_2 && a2) {
          const r4 = n3(_2, a2);
          r4 < 0 ? (
            // The element was removed if the next element in our ordered
            // walkthrough is only in `before`.
            t4 = true
          ) : r4 > 0 && // The element was added if the next element in our ordered walkthrough
          // is only in `after`.
          (e4 = true);
        } else null != _2 ? t4 = true : e4 = true;
        e4 ? (r3(a2), a2 = __PRIVATE_advanceIterator(o2)) : t4 ? (i3(_2), _2 = __PRIVATE_advanceIterator(s3)) : (_2 = __PRIVATE_advanceIterator(s3), a2 = __PRIVATE_advanceIterator(o2));
      }
    }, "__PRIVATE_diffSortedSets"))(
      r2,
      i2,
      __PRIVATE_indexEntryComparator,
      /* onAdd= */
      (r3) => {
        s2.push(this.xn(e2, t2, n2, r3));
      },
      /* onRemove= */
      (r3) => {
        s2.push(this.On(e2, t2, n2, r3));
      }
    ), PersistencePromise.waitFor(s2);
  }
  vn(e2) {
    let t2 = 1;
    return __PRIVATE_indexStateStore(e2).Z({
      index: Ce,
      reverse: true,
      range: IDBKeyRange.upperBound([this.uid, Number.MAX_SAFE_INTEGER])
    }, (e3, n2, r2) => {
      r2.done(), t2 = n2.sequenceNumber + 1;
    }).next(() => t2);
  }
  /**
   * Returns a new set of IDB ranges that splits the existing range and excludes
   * any values that match the `notInValue` from these ranges. As an example,
   * '[foo > 2 && foo != 3]` becomes  `[foo > 2 && < 3, foo > 3]`.
   */
  createRange(e2, t2, n2) {
    n2 = n2.sort((e3, t3) => __PRIVATE_indexEntryComparator(e3, t3)).filter((e3, t3, n3) => !t3 || 0 !== __PRIVATE_indexEntryComparator(e3, n3[t3 - 1]));
    const r2 = [];
    r2.push(e2);
    for (const i3 of n2) {
      const n3 = __PRIVATE_indexEntryComparator(i3, e2), s2 = __PRIVATE_indexEntryComparator(i3, t2);
      if (0 === n3)
        r2[0] = e2.nn();
      else if (n3 > 0 && s2 < 0)
        r2.push(i3), r2.push(i3.nn());
      else if (s2 > 0)
        break;
    }
    r2.push(t2);
    const i2 = [];
    for (let e3 = 0; e3 < r2.length; e3 += 2) {
      if (this.Nn(r2[e3], r2[e3 + 1])) return [];
      const t3 = [r2[e3].indexId, this.uid, r2[e3].arrayValue, r2[e3].directionalValue, yt, []], n3 = [r2[e3 + 1].indexId, this.uid, r2[e3 + 1].arrayValue, r2[e3 + 1].directionalValue, yt, []];
      i2.push(IDBKeyRange.bound(t3, n3));
    }
    return i2;
  }
  Nn(e2, t2) {
    return __PRIVATE_indexEntryComparator(e2, t2) > 0;
  }
  getMinOffsetFromCollectionGroup(e2, t2) {
    return this.getFieldIndexes(e2, t2).next(__PRIVATE_getMinOffsetFromFieldIndexes);
  }
  getMinOffset(e2, t2) {
    return PersistencePromise.mapArray(this.dn(t2), (t3) => this.An(e2, t3).next((e3) => e3 || fail())).next(__PRIVATE_getMinOffsetFromFieldIndexes);
  }
}
function __PRIVATE_collectionParentsStore(e2) {
  return __PRIVATE_getStore(e2, de);
}
__name(__PRIVATE_collectionParentsStore, "__PRIVATE_collectionParentsStore");
function __PRIVATE_indexEntriesStore(e2) {
  return __PRIVATE_getStore(e2, Me);
}
__name(__PRIVATE_indexEntriesStore, "__PRIVATE_indexEntriesStore");
function __PRIVATE_indexConfigurationStore(e2) {
  return __PRIVATE_getStore(e2, ye);
}
__name(__PRIVATE_indexConfigurationStore, "__PRIVATE_indexConfigurationStore");
function __PRIVATE_indexStateStore(e2) {
  return __PRIVATE_getStore(e2, De);
}
__name(__PRIVATE_indexStateStore, "__PRIVATE_indexStateStore");
function __PRIVATE_getMinOffsetFromFieldIndexes(e2) {
  __PRIVATE_hardAssert(0 !== e2.length);
  let t2 = e2[0].indexState.offset, n2 = t2.largestBatchId;
  for (let r2 = 1; r2 < e2.length; r2++) {
    const i2 = e2[r2].indexState.offset;
    __PRIVATE_indexOffsetComparator(i2, t2) < 0 && (t2 = i2), n2 < i2.largestBatchId && (n2 = i2.largestBatchId);
  }
  return new IndexOffset(t2.readTime, t2.documentKey, n2);
}
__name(__PRIVATE_getMinOffsetFromFieldIndexes, "__PRIVATE_getMinOffsetFromFieldIndexes");
/**
 * @license
 * Copyright 2018 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 wt = {
  didRun: false,
  sequenceNumbersCollected: 0,
  targetsRemoved: 0,
  documentsRemoved: 0
}, St = 41943040;
class LruParams {
  static {
    __name(this, "LruParams");
  }
  static withCacheSize(e2) {
    return new LruParams(e2, LruParams.DEFAULT_COLLECTION_PERCENTILE, LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT);
  }
  constructor(e2, t2, n2) {
    this.cacheSizeCollectionThreshold = e2, this.percentileToCollect = t2, this.maximumSequenceNumbersToCollect = n2;
  }
}
/**
 * @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.
 */
function removeMutationBatch(e2, t2, n2) {
  const r2 = e2.store(j), i2 = e2.store(X), s2 = [], o2 = IDBKeyRange.only(n2.batchId);
  let _2 = 0;
  const a2 = r2.Z({
    range: o2
  }, (e3, t3, n3) => (_2++, n3.delete()));
  s2.push(a2.next(() => {
    __PRIVATE_hardAssert(1 === _2);
  }));
  const u2 = [];
  for (const e3 of n2.mutations) {
    const r3 = __PRIVATE_newDbDocumentMutationKey(t2, e3.key.path, n2.batchId);
    s2.push(i2.delete(r3)), u2.push(e3.key);
  }
  return PersistencePromise.waitFor(s2).next(() => u2);
}
__name(removeMutationBatch, "removeMutationBatch");
function __PRIVATE_dbDocumentSize(e2) {
  if (!e2) return 0;
  let t2;
  if (e2.document) t2 = e2.document;
  else if (e2.unknownDocument) t2 = e2.unknownDocument;
  else {
    if (!e2.noDocument) throw fail();
    t2 = e2.noDocument;
  }
  return JSON.stringify(t2).length;
}
__name(__PRIVATE_dbDocumentSize, "__PRIVATE_dbDocumentSize");
/**
 * @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.
 */
LruParams.DEFAULT_COLLECTION_PERCENTILE = 10, LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT = 1e3, LruParams.DEFAULT = new LruParams(St, LruParams.DEFAULT_COLLECTION_PERCENTILE, LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT), LruParams.DISABLED = new LruParams(-1, 0, 0);
class __PRIVATE_IndexedDbMutationQueue {
  static {
    __name(this, "__PRIVATE_IndexedDbMutationQueue");
  }
  constructor(e2, t2, n2, r2) {
    this.userId = e2, this.serializer = t2, this.indexManager = n2, this.referenceDelegate = r2, /**
     * Caches the document keys for pending mutation batches. If the mutation
     * has been removed from IndexedDb, the cached value may continue to
     * be used to retrieve the batch's document keys. To remove a cached value
     * locally, `removeCachedMutationKeys()` should be invoked either directly
     * or through `removeMutationBatches()`.
     *
     * With multi-tab, when the primary client acknowledges or rejects a mutation,
     * this cache is used by secondary clients to invalidate the local
     * view of the documents that were previously affected by the mutation.
     */
    // PORTING NOTE: Multi-tab only.
    this.Bn = {};
  }
  /**
   * Creates a new mutation queue for the given user.
   * @param user - The user for which to create a mutation queue.
   * @param serializer - The serializer to use when persisting to IndexedDb.
   */
  static It(e2, t2, n2, r2) {
    __PRIVATE_hardAssert("" !== e2.uid);
    const i2 = e2.isAuthenticated() ? e2.uid : "";
    return new __PRIVATE_IndexedDbMutationQueue(i2, t2, n2, r2);
  }
  checkEmpty(e2) {
    let t2 = true;
    const n2 = IDBKeyRange.bound([this.userId, Number.NEGATIVE_INFINITY], [this.userId, Number.POSITIVE_INFINITY]);
    return __PRIVATE_mutationsStore(e2).Z({
      index: J,
      range: n2
    }, (e3, n3, r2) => {
      t2 = false, r2.done();
    }).next(() => t2);
  }
  addMutationBatch(e2, t2, n2, r2) {
    const i2 = __PRIVATE_documentMutationsStore(e2), s2 = __PRIVATE_mutationsStore(e2);
    return s2.add({}).next((o2) => {
      __PRIVATE_hardAssert("number" == typeof o2);
      const _2 = new MutationBatch(o2, t2, n2, r2), a2 = (/* @__PURE__ */ __name(function __PRIVATE_toDbMutationBatch(e3, t3, n3) {
        const r3 = n3.baseMutations.map((t4) => toMutation(e3.Tt, t4)), i3 = n3.mutations.map((t4) => toMutation(e3.Tt, t4));
        return {
          userId: t3,
          batchId: n3.batchId,
          localWriteTimeMs: n3.localWriteTime.toMillis(),
          baseMutations: r3,
          mutations: i3
        };
      }, "__PRIVATE_toDbMutationBatch"))(this.serializer, this.userId, _2), u2 = [];
      let c2 = new SortedSet((e3, t3) => __PRIVATE_primitiveComparator(e3.canonicalString(), t3.canonicalString()));
      for (const e3 of r2) {
        const t3 = __PRIVATE_newDbDocumentMutationKey(this.userId, e3.key.path, o2);
        c2 = c2.add(e3.key.path.popLast()), u2.push(s2.put(a2)), u2.push(i2.put(t3, Z$1));
      }
      return c2.forEach((t3) => {
        u2.push(this.indexManager.addToCollectionParentIndex(e2, t3));
      }), e2.addOnCommittedListener(() => {
        this.Bn[o2] = _2.keys();
      }), PersistencePromise.waitFor(u2).next(() => _2);
    });
  }
  lookupMutationBatch(e2, t2) {
    return __PRIVATE_mutationsStore(e2).get(t2).next((e3) => e3 ? (__PRIVATE_hardAssert(e3.userId === this.userId), __PRIVATE_fromDbMutationBatch(this.serializer, e3)) : null);
  }
  /**
   * Returns the document keys for the mutation batch with the given batchId.
   * For primary clients, this method returns `null` after
   * `removeMutationBatches()` has been called. Secondary clients return a
   * cached result until `removeCachedMutationKeys()` is invoked.
   */
  // PORTING NOTE: Multi-tab only.
  Ln(e2, t2) {
    return this.Bn[t2] ? PersistencePromise.resolve(this.Bn[t2]) : this.lookupMutationBatch(e2, t2).next((e3) => {
      if (e3) {
        const n2 = e3.keys();
        return this.Bn[t2] = n2, n2;
      }
      return null;
    });
  }
  getNextMutationBatchAfterBatchId(e2, t2) {
    const n2 = t2 + 1, r2 = IDBKeyRange.lowerBound([this.userId, n2]);
    let i2 = null;
    return __PRIVATE_mutationsStore(e2).Z({
      index: J,
      range: r2
    }, (e3, t3, r3) => {
      t3.userId === this.userId && (__PRIVATE_hardAssert(t3.batchId >= n2), i2 = __PRIVATE_fromDbMutationBatch(this.serializer, t3)), r3.done();
    }).next(() => i2);
  }
  getHighestUnacknowledgedBatchId(e2) {
    const t2 = IDBKeyRange.upperBound([this.userId, Number.POSITIVE_INFINITY]);
    let n2 = Q;
    return __PRIVATE_mutationsStore(e2).Z({
      index: J,
      range: t2,
      reverse: true
    }, (e3, t3, r2) => {
      n2 = t3.batchId, r2.done();
    }).next(() => n2);
  }
  getAllMutationBatches(e2) {
    const t2 = IDBKeyRange.bound([this.userId, Q], [this.userId, Number.POSITIVE_INFINITY]);
    return __PRIVATE_mutationsStore(e2).G(J, t2).next((e3) => e3.map((e4) => __PRIVATE_fromDbMutationBatch(this.serializer, e4)));
  }
  getAllMutationBatchesAffectingDocumentKey(e2, t2) {
    const n2 = __PRIVATE_newDbDocumentMutationPrefixForPath(this.userId, t2.path), r2 = IDBKeyRange.lowerBound(n2), i2 = [];
    return __PRIVATE_documentMutationsStore(e2).Z({
      range: r2
    }, (n3, r3, s2) => {
      const [o2, _2, a2] = n3, u2 = __PRIVATE_decodeResourcePath(_2);
      if (o2 === this.userId && t2.path.isEqual(u2))
        return __PRIVATE_mutationsStore(e2).get(a2).next((e3) => {
          if (!e3) throw fail();
          __PRIVATE_hardAssert(e3.userId === this.userId), i2.push(__PRIVATE_fromDbMutationBatch(this.serializer, e3));
        });
      s2.done();
    }).next(() => i2);
  }
  getAllMutationBatchesAffectingDocumentKeys(e2, t2) {
    let n2 = new SortedSet(__PRIVATE_primitiveComparator);
    const r2 = [];
    return t2.forEach((t3) => {
      const i2 = __PRIVATE_newDbDocumentMutationPrefixForPath(this.userId, t3.path), s2 = IDBKeyRange.lowerBound(i2), o2 = __PRIVATE_documentMutationsStore(e2).Z({
        range: s2
      }, (e3, r3, i3) => {
        const [s3, o3, _2] = e3, a2 = __PRIVATE_decodeResourcePath(o3);
        s3 === this.userId && t3.path.isEqual(a2) ? n2 = n2.add(_2) : i3.done();
      });
      r2.push(o2);
    }), PersistencePromise.waitFor(r2).next(() => this.kn(e2, n2));
  }
  getAllMutationBatchesAffectingQuery(e2, t2) {
    const n2 = t2.path, r2 = n2.length + 1, i2 = __PRIVATE_newDbDocumentMutationPrefixForPath(this.userId, n2), s2 = IDBKeyRange.lowerBound(i2);
    let o2 = new SortedSet(__PRIVATE_primitiveComparator);
    return __PRIVATE_documentMutationsStore(e2).Z({
      range: s2
    }, (e3, t3, i3) => {
      const [s3, _2, a2] = e3, u2 = __PRIVATE_decodeResourcePath(_2);
      s3 === this.userId && n2.isPrefixOf(u2) ? (
        // Rows with document keys more than one segment longer than the
        // query path can't be matches. For example, a query on 'rooms'
        // can't match the document /rooms/abc/messages/xyx.
        // TODO(mcg): we'll need a different scanner when we implement
        // ancestor queries.
        u2.length === r2 && (o2 = o2.add(a2))
      ) : i3.done();
    }).next(() => this.kn(e2, o2));
  }
  kn(e2, t2) {
    const n2 = [], r2 = [];
    return t2.forEach((t3) => {
      r2.push(__PRIVATE_mutationsStore(e2).get(t3).next((e3) => {
        if (null === e3) throw fail();
        __PRIVATE_hardAssert(e3.userId === this.userId), n2.push(__PRIVATE_fromDbMutationBatch(this.serializer, e3));
      }));
    }), PersistencePromise.waitFor(r2).next(() => n2);
  }
  removeMutationBatch(e2, t2) {
    return removeMutationBatch(e2.ue, this.userId, t2).next((n2) => (e2.addOnCommittedListener(() => {
      this.qn(t2.batchId);
    }), PersistencePromise.forEach(n2, (t3) => this.referenceDelegate.markPotentiallyOrphaned(e2, t3))));
  }
  /**
   * Clears the cached keys for a mutation batch. This method should be
   * called by secondary clients after they process mutation updates.
   *
   * Note that this method does not have to be called from primary clients as
   * the corresponding cache entries are cleared when an acknowledged or
   * rejected batch is removed from the mutation queue.
   */
  // PORTING NOTE: Multi-tab only
  qn(e2) {
    delete this.Bn[e2];
  }
  performConsistencyCheck(e2) {
    return this.checkEmpty(e2).next((t2) => {
      if (!t2) return PersistencePromise.resolve();
      const n2 = IDBKeyRange.lowerBound(
        /**
        * Creates a [userId] key for use in the DbDocumentMutations index to iterate
        * over all of a user's document mutations.
        */
        (/* @__PURE__ */ __name(function __PRIVATE_newDbDocumentMutationPrefixForUser(e3) {
          return [e3];
        }, "__PRIVATE_newDbDocumentMutationPrefixForUser"))(this.userId)
      ), r2 = [];
      return __PRIVATE_documentMutationsStore(e2).Z({
        range: n2
      }, (e3, t3, n3) => {
        if (e3[0] === this.userId) {
          const t4 = __PRIVATE_decodeResourcePath(e3[1]);
          r2.push(t4);
        } else n3.done();
      }).next(() => {
        __PRIVATE_hardAssert(0 === r2.length);
      });
    });
  }
  containsKey(e2, t2) {
    return __PRIVATE_mutationQueueContainsKey(e2, this.userId, t2);
  }
  // PORTING NOTE: Multi-tab only (state is held in memory in other clients).
  /** Returns the mutation queue's metadata from IndexedDb. */
  Qn(e2) {
    return __PRIVATE_mutationQueuesStore(e2).get(this.userId).next((e3) => e3 || {
      userId: this.userId,
      lastAcknowledgedBatchId: Q,
      lastStreamToken: ""
    });
  }
}
function __PRIVATE_mutationQueueContainsKey(e2, t2, n2) {
  const r2 = __PRIVATE_newDbDocumentMutationPrefixForPath(t2, n2.path), i2 = r2[1], s2 = IDBKeyRange.lowerBound(r2);
  let o2 = false;
  return __PRIVATE_documentMutationsStore(e2).Z({
    range: s2,
    Y: true
  }, (e3, n3, r3) => {
    const [
      s3,
      _2,
      /*batchID*/
      a2
    ] = e3;
    s3 === t2 && _2 === i2 && (o2 = true), r3.done();
  }).next(() => o2);
}
__name(__PRIVATE_mutationQueueContainsKey, "__PRIVATE_mutationQueueContainsKey");
function __PRIVATE_mutationsStore(e2) {
  return __PRIVATE_getStore(e2, j);
}
__name(__PRIVATE_mutationsStore, "__PRIVATE_mutationsStore");
function __PRIVATE_documentMutationsStore(e2) {
  return __PRIVATE_getStore(e2, X);
}
__name(__PRIVATE_documentMutationsStore, "__PRIVATE_documentMutationsStore");
function __PRIVATE_mutationQueuesStore(e2) {
  return __PRIVATE_getStore(e2, G);
}
__name(__PRIVATE_mutationQueuesStore, "__PRIVATE_mutationQueuesStore");
/**
 * @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 __PRIVATE_TargetIdGenerator {
  static {
    __name(this, "__PRIVATE_TargetIdGenerator");
  }
  constructor(e2) {
    this.$n = e2;
  }
  next() {
    return this.$n += 2, this.$n;
  }
  static Un() {
    return new __PRIVATE_TargetIdGenerator(0);
  }
  static Kn() {
    return new __PRIVATE_TargetIdGenerator(-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.
 */
class __PRIVATE_IndexedDbTargetCache {
  static {
    __name(this, "__PRIVATE_IndexedDbTargetCache");
  }
  constructor(e2, t2) {
    this.referenceDelegate = e2, this.serializer = t2;
  }
  // PORTING NOTE: We don't cache global metadata for the target cache, since
  // some of it (in particular `highestTargetId`) can be modified by secondary
  // tabs. We could perhaps be more granular (and e.g. still cache
  // `lastRemoteSnapshotVersion` in memory) but for simplicity we currently go
  // to IndexedDb whenever we need to read metadata. We can revisit if it turns
  // out to have a meaningful performance impact.
  allocateTargetId(e2) {
    return this.Wn(e2).next((t2) => {
      const n2 = new __PRIVATE_TargetIdGenerator(t2.highestTargetId);
      return t2.highestTargetId = n2.next(), this.Gn(e2, t2).next(() => t2.highestTargetId);
    });
  }
  getLastRemoteSnapshotVersion(e2) {
    return this.Wn(e2).next((e3) => SnapshotVersion.fromTimestamp(new Timestamp(e3.lastRemoteSnapshotVersion.seconds, e3.lastRemoteSnapshotVersion.nanoseconds)));
  }
  getHighestSequenceNumber(e2) {
    return this.Wn(e2).next((e3) => e3.highestListenSequenceNumber);
  }
  setTargetsMetadata(e2, t2, n2) {
    return this.Wn(e2).next((r2) => (r2.highestListenSequenceNumber = t2, n2 && (r2.lastRemoteSnapshotVersion = n2.toTimestamp()), t2 > r2.highestListenSequenceNumber && (r2.highestListenSequenceNumber = t2), this.Gn(e2, r2)));
  }
  addTargetData(e2, t2) {
    return this.zn(e2, t2).next(() => this.Wn(e2).next((n2) => (n2.targetCount += 1, this.jn(t2, n2), this.Gn(e2, n2))));
  }
  updateTargetData(e2, t2) {
    return this.zn(e2, t2);
  }
  removeTargetData(e2, t2) {
    return this.removeMatchingKeysForTargetId(e2, t2.targetId).next(() => __PRIVATE_targetsStore(e2).delete(t2.targetId)).next(() => this.Wn(e2)).next((t3) => (__PRIVATE_hardAssert(t3.targetCount > 0), t3.targetCount -= 1, this.Gn(e2, t3)));
  }
  /**
   * Drops any targets with sequence number less than or equal to the upper bound, excepting those
   * present in `activeTargetIds`. Document associations for the removed targets are also removed.
   * Returns the number of targets removed.
   */
  removeTargets(e2, t2, n2) {
    let r2 = 0;
    const i2 = [];
    return __PRIVATE_targetsStore(e2).Z((s2, o2) => {
      const _2 = __PRIVATE_fromDbTarget(o2);
      _2.sequenceNumber <= t2 && null === n2.get(_2.targetId) && (r2++, i2.push(this.removeTargetData(e2, _2)));
    }).next(() => PersistencePromise.waitFor(i2)).next(() => r2);
  }
  /**
   * Call provided function with each `TargetData` that we have cached.
   */
  forEachTarget(e2, t2) {
    return __PRIVATE_targetsStore(e2).Z((e3, n2) => {
      const r2 = __PRIVATE_fromDbTarget(n2);
      t2(r2);
    });
  }
  Wn(e2) {
    return __PRIVATE_globalTargetStore(e2).get(Ie).next((e3) => (__PRIVATE_hardAssert(null !== e3), e3));
  }
  Gn(e2, t2) {
    return __PRIVATE_globalTargetStore(e2).put(Ie, t2);
  }
  zn(e2, t2) {
    return __PRIVATE_targetsStore(e2).put(__PRIVATE_toDbTarget(this.serializer, t2));
  }
  /**
   * In-place updates the provided metadata to account for values in the given
   * TargetData. Saving is done separately. Returns true if there were any
   * changes to the metadata.
   */
  jn(e2, t2) {
    let n2 = false;
    return e2.targetId > t2.highestTargetId && (t2.highestTargetId = e2.targetId, n2 = true), e2.sequenceNumber > t2.highestListenSequenceNumber && (t2.highestListenSequenceNumber = e2.sequenceNumber, n2 = true), n2;
  }
  getTargetCount(e2) {
    return this.Wn(e2).next((e3) => e3.targetCount);
  }
  getTargetData(e2, t2) {
    const n2 = __PRIVATE_canonifyTarget(t2), r2 = IDBKeyRange.bound([n2, Number.NEGATIVE_INFINITY], [n2, Number.POSITIVE_INFINITY]);
    let i2 = null;
    return __PRIVATE_targetsStore(e2).Z({
      range: r2,
      index: ue
    }, (e3, n3, r3) => {
      const s2 = __PRIVATE_fromDbTarget(n3);
      __PRIVATE_targetEquals(t2, s2.target) && (i2 = s2, r3.done());
    }).next(() => i2);
  }
  addMatchingKeys(e2, t2, n2) {
    const r2 = [], i2 = __PRIVATE_documentTargetStore(e2);
    return t2.forEach((t3) => {
      const s2 = __PRIVATE_encodeResourcePath(t3.path);
      r2.push(i2.put({
        targetId: n2,
        path: s2
      })), r2.push(this.referenceDelegate.addReference(e2, n2, t3));
    }), PersistencePromise.waitFor(r2);
  }
  removeMatchingKeys(e2, t2, n2) {
    const r2 = __PRIVATE_documentTargetStore(e2);
    return PersistencePromise.forEach(t2, (t3) => {
      const i2 = __PRIVATE_encodeResourcePath(t3.path);
      return PersistencePromise.waitFor([r2.delete([n2, i2]), this.referenceDelegate.removeReference(e2, n2, t3)]);
    });
  }
  removeMatchingKeysForTargetId(e2, t2) {
    const n2 = __PRIVATE_documentTargetStore(e2), r2 = IDBKeyRange.bound(
      [t2],
      [t2 + 1],
      /*lowerOpen=*/
      false,
      /*upperOpen=*/
      true
    );
    return n2.delete(r2);
  }
  getMatchingKeysForTargetId(e2, t2) {
    const n2 = IDBKeyRange.bound(
      [t2],
      [t2 + 1],
      /*lowerOpen=*/
      false,
      /*upperOpen=*/
      true
    ), r2 = __PRIVATE_documentTargetStore(e2);
    let i2 = __PRIVATE_documentKeySet();
    return r2.Z({
      range: n2,
      Y: true
    }, (e3, t3, n3) => {
      const r3 = __PRIVATE_decodeResourcePath(e3[1]), s2 = new DocumentKey(r3);
      i2 = i2.add(s2);
    }).next(() => i2);
  }
  containsKey(e2, t2) {
    const n2 = __PRIVATE_encodeResourcePath(t2.path), r2 = IDBKeyRange.bound(
      [n2],
      [__PRIVATE_immediateSuccessor(n2)],
      /*lowerOpen=*/
      false,
      /*upperOpen=*/
      true
    );
    let i2 = 0;
    return __PRIVATE_documentTargetStore(e2).Z({
      index: Pe,
      Y: true,
      range: r2
    }, ([e3, t3], n3, r3) => {
      0 !== e3 && (i2++, r3.done());
    }).next(() => i2 > 0);
  }
  /**
   * Looks up a TargetData entry by target ID.
   *
   * @param targetId - The target ID of the TargetData entry to look up.
   * @returns The cached TargetData entry, or null if the cache has no entry for
   * the target.
   */
  // PORTING NOTE: Multi-tab only.
  lt(e2, t2) {
    return __PRIVATE_targetsStore(e2).get(t2).next((e3) => e3 ? __PRIVATE_fromDbTarget(e3) : null);
  }
}
function __PRIVATE_targetsStore(e2) {
  return __PRIVATE_getStore(e2, ae);
}
__name(__PRIVATE_targetsStore, "__PRIVATE_targetsStore");
function __PRIVATE_globalTargetStore(e2) {
  return __PRIVATE_getStore(e2, Ee);
}
__name(__PRIVATE_globalTargetStore, "__PRIVATE_globalTargetStore");
function __PRIVATE_documentTargetStore(e2) {
  return __PRIVATE_getStore(e2, le);
}
__name(__PRIVATE_documentTargetStore, "__PRIVATE_documentTargetStore");
/**
 * @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 bt = "LruGarbageCollector", Dt = 1048576;
function __PRIVATE_bufferEntryComparator([e2, t2], [n2, r2]) {
  const i2 = __PRIVATE_primitiveComparator(e2, n2);
  return 0 === i2 ? __PRIVATE_primitiveComparator(t2, r2) : i2;
}
__name(__PRIVATE_bufferEntryComparator, "__PRIVATE_bufferEntryComparator");
class __PRIVATE_RollingSequenceNumberBuffer {
  static {
    __name(this, "__PRIVATE_RollingSequenceNumberBuffer");
  }
  constructor(e2) {
    this.Hn = e2, this.buffer = new SortedSet(__PRIVATE_bufferEntryComparator), this.Jn = 0;
  }
  Yn() {
    return ++this.Jn;
  }
  Zn(e2) {
    const t2 = [e2, this.Yn()];
    if (this.buffer.size < this.Hn) this.buffer = this.buffer.add(t2);
    else {
      const e3 = this.buffer.last();
      __PRIVATE_bufferEntryComparator(t2, e3) < 0 && (this.buffer = this.buffer.delete(e3).add(t2));
    }
  }
  get maxValue() {
    return this.buffer.last()[0];
  }
}
class __PRIVATE_LruScheduler {
  static {
    __name(this, "__PRIVATE_LruScheduler");
  }
  constructor(e2, t2, n2) {
    this.garbageCollector = e2, this.asyncQueue = t2, this.localStore = n2, this.Xn = null;
  }
  start() {
    -1 !== this.garbageCollector.params.cacheSizeCollectionThreshold && this.er(6e4);
  }
  stop() {
    this.Xn && (this.Xn.cancel(), this.Xn = null);
  }
  get started() {
    return null !== this.Xn;
  }
  er(e2) {
    __PRIVATE_logDebug(bt, `Garbage collection scheduled in ${e2}ms`), this.Xn = this.asyncQueue.enqueueAfterDelay("lru_garbage_collection", e2, async () => {
      this.Xn = null;
      try {
        await this.localStore.collectGarbage(this.garbageCollector);
      } catch (e3) {
        __PRIVATE_isIndexedDbTransactionError(e3) ? __PRIVATE_logDebug(bt, "Ignoring IndexedDB error during garbage collection: ", e3) : await __PRIVATE_ignoreIfPrimaryLeaseLoss(e3);
      }
      await this.er(3e5);
    });
  }
}
class __PRIVATE_LruGarbageCollectorImpl {
  static {
    __name(this, "__PRIVATE_LruGarbageCollectorImpl");
  }
  constructor(e2, t2) {
    this.tr = e2, this.params = t2;
  }
  calculateTargetCount(e2, t2) {
    return this.tr.nr(e2).next((e3) => Math.floor(t2 / 100 * e3));
  }
  nthSequenceNumber(e2, t2) {
    if (0 === t2) return PersistencePromise.resolve(__PRIVATE_ListenSequence.ae);
    const n2 = new __PRIVATE_RollingSequenceNumberBuffer(t2);
    return this.tr.forEachTarget(e2, (e3) => n2.Zn(e3.sequenceNumber)).next(() => this.tr.rr(e2, (e3) => n2.Zn(e3))).next(() => n2.maxValue);
  }
  removeTargets(e2, t2, n2) {
    return this.tr.removeTargets(e2, t2, n2);
  }
  removeOrphanedDocuments(e2, t2) {
    return this.tr.removeOrphanedDocuments(e2, t2);
  }
  collect(e2, t2) {
    return -1 === this.params.cacheSizeCollectionThreshold ? (__PRIVATE_logDebug("LruGarbageCollector", "Garbage collection skipped; disabled"), PersistencePromise.resolve(wt)) : this.getCacheSize(e2).next((n2) => n2 < this.params.cacheSizeCollectionThreshold ? (__PRIVATE_logDebug("LruGarbageCollector", `Garbage collection skipped; Cache size ${n2} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`), wt) : this.ir(e2, t2));
  }
  getCacheSize(e2) {
    return this.tr.getCacheSize(e2);
  }
  ir(e2, t2) {
    let n2, r2, i2, s2, o2, _2, u2;
    const c2 = Date.now();
    return this.calculateTargetCount(e2, this.params.percentileToCollect).next((t3) => (
      // Cap at the configured max
      (t3 > this.params.maximumSequenceNumbersToCollect ? (__PRIVATE_logDebug("LruGarbageCollector", `Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${t3}`), r2 = this.params.maximumSequenceNumbersToCollect) : r2 = t3, s2 = Date.now(), this.nthSequenceNumber(e2, r2))
    )).next((r3) => (n2 = r3, o2 = Date.now(), this.removeTargets(e2, n2, t2))).next((t3) => (i2 = t3, _2 = Date.now(), this.removeOrphanedDocuments(e2, n2))).next((e3) => {
      if (u2 = Date.now(), __PRIVATE_getLogLevel() <= LogLevel.DEBUG) {
        __PRIVATE_logDebug("LruGarbageCollector", `LRU Garbage Collection
	Counted targets in ${s2 - c2}ms
	Determined least recently used ${r2} in ` + (o2 - s2) + `ms
	Removed ${i2} targets in ` + (_2 - o2) + `ms
	Removed ${e3} documents in ` + (u2 - _2) + `ms
Total Duration: ${u2 - c2}ms`);
      }
      return PersistencePromise.resolve({
        didRun: true,
        sequenceNumbersCollected: r2,
        targetsRemoved: i2,
        documentsRemoved: e3
      });
    });
  }
}
function __PRIVATE_newLruGarbageCollector(e2, t2) {
  return new __PRIVATE_LruGarbageCollectorImpl(e2, t2);
}
__name(__PRIVATE_newLruGarbageCollector, "__PRIVATE_newLruGarbageCollector");
/**
 * @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 __PRIVATE_IndexedDbLruDelegateImpl {
  static {
    __name(this, "__PRIVATE_IndexedDbLruDelegateImpl");
  }
  constructor(e2, t2) {
    this.db = e2, this.garbageCollector = __PRIVATE_newLruGarbageCollector(this, t2);
  }
  nr(e2) {
    const t2 = this.sr(e2);
    return this.db.getTargetCache().getTargetCount(e2).next((e3) => t2.next((t3) => e3 + t3));
  }
  sr(e2) {
    let t2 = 0;
    return this.rr(e2, (e3) => {
      t2++;
    }).next(() => t2);
  }
  forEachTarget(e2, t2) {
    return this.db.getTargetCache().forEachTarget(e2, t2);
  }
  rr(e2, t2) {
    return this._r(e2, (e3, n2) => t2(n2));
  }
  addReference(e2, t2, n2) {
    return __PRIVATE_writeSentinelKey(e2, n2);
  }
  removeReference(e2, t2, n2) {
    return __PRIVATE_writeSentinelKey(e2, n2);
  }
  removeTargets(e2, t2, n2) {
    return this.db.getTargetCache().removeTargets(e2, t2, n2);
  }
  markPotentiallyOrphaned(e2, t2) {
    return __PRIVATE_writeSentinelKey(e2, t2);
  }
  /**
   * Returns true if anything would prevent this document from being garbage
   * collected, given that the document in question is not present in any
   * targets and has a sequence number less than or equal to the upper bound for
   * the collection run.
   */
  ar(e2, t2) {
    return (/* @__PURE__ */ __name(function __PRIVATE_mutationQueuesContainKey(e3, t3) {
      let n2 = false;
      return __PRIVATE_mutationQueuesStore(e3).X((r2) => __PRIVATE_mutationQueueContainsKey(e3, r2, t3).next((e4) => (e4 && (n2 = true), PersistencePromise.resolve(!e4)))).next(() => n2);
    }, "__PRIVATE_mutationQueuesContainKey"))(e2, t2);
  }
  removeOrphanedDocuments(e2, t2) {
    const n2 = this.db.getRemoteDocumentCache().newChangeBuffer(), r2 = [];
    let i2 = 0;
    return this._r(e2, (s2, o2) => {
      if (o2 <= t2) {
        const t3 = this.ar(e2, s2).next((t4) => {
          if (!t4)
            return i2++, n2.getEntry(e2, s2).next(() => (n2.removeEntry(s2, SnapshotVersion.min()), __PRIVATE_documentTargetStore(e2).delete((/* @__PURE__ */ __name(function __PRIVATE_sentinelKey$1(e3) {
              return [0, __PRIVATE_encodeResourcePath(e3.path)];
            }, "__PRIVATE_sentinelKey$1"))(s2))));
        });
        r2.push(t3);
      }
    }).next(() => PersistencePromise.waitFor(r2)).next(() => n2.apply(e2)).next(() => i2);
  }
  removeTarget(e2, t2) {
    const n2 = t2.withSequenceNumber(e2.currentSequenceNumber);
    return this.db.getTargetCache().updateTargetData(e2, n2);
  }
  updateLimboDocument(e2, t2) {
    return __PRIVATE_writeSentinelKey(e2, t2);
  }
  /**
   * Call provided function for each document in the cache that is 'orphaned'. Orphaned
   * means not a part of any target, so the only entry in the target-document index for
   * that document will be the sentinel row (targetId 0), which will also have the sequence
   * number for the last time the document was accessed.
   */
  _r(e2, t2) {
    const n2 = __PRIVATE_documentTargetStore(e2);
    let r2, i2 = __PRIVATE_ListenSequence.ae;
    return n2.Z({
      index: Pe
    }, ([e3, n3], { path: s2, sequenceNumber: o2 }) => {
      0 === e3 ? (
        // if nextToReport is valid, report it, this is a new key so the
        // last one must not be a member of any targets.
        (i2 !== __PRIVATE_ListenSequence.ae && t2(new DocumentKey(__PRIVATE_decodeResourcePath(r2)), i2), // set nextToReport to be this sequence number. It's the next one we
        // might report, if we don't find any targets for this document.
        // Note that the sequence number must be defined when the targetId
        // is 0.
        i2 = o2, r2 = s2)
      ) : (
        // set nextToReport to be invalid, we know we don't need to report
        // this one since we found a target for it.
        i2 = __PRIVATE_ListenSequence.ae
      );
    }).next(() => {
      i2 !== __PRIVATE_ListenSequence.ae && t2(new DocumentKey(__PRIVATE_decodeResourcePath(r2)), i2);
    });
  }
  getCacheSize(e2) {
    return this.db.getRemoteDocumentCache().getSize(e2);
  }
}
function __PRIVATE_writeSentinelKey(e2, t2) {
  return __PRIVATE_documentTargetStore(e2).put((/* @__PURE__ */ __name(function __PRIVATE_sentinelRow(e3, t3) {
    return {
      targetId: 0,
      path: __PRIVATE_encodeResourcePath(e3.path),
      sequenceNumber: t3
    };
  }, "__PRIVATE_sentinelRow"))(t2, e2.currentSequenceNumber));
}
__name(__PRIVATE_writeSentinelKey, "__PRIVATE_writeSentinelKey");
/**
 * @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 RemoteDocumentChangeBuffer {
  static {
    __name(this, "RemoteDocumentChangeBuffer");
  }
  constructor() {
    this.changes = new ObjectMap((e2) => e2.toString(), (e2, t2) => e2.isEqual(t2)), this.changesApplied = false;
  }
  /**
   * Buffers a `RemoteDocumentCache.addEntry()` call.
   *
   * You can only modify documents that have already been retrieved via
   * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).
   */
  addEntry(e2) {
    this.assertNotApplied(), this.changes.set(e2.key, e2);
  }
  /**
   * Buffers a `RemoteDocumentCache.removeEntry()` call.
   *
   * You can only remove documents that have already been retrieved via
   * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).
   */
  removeEntry(e2, t2) {
    this.assertNotApplied(), this.changes.set(e2, MutableDocument.newInvalidDocument(e2).setReadTime(t2));
  }
  /**
   * Looks up an entry in the cache. The buffered changes will first be checked,
   * and if no buffered change applies, this will forward to
   * `RemoteDocumentCache.getEntry()`.
   *
   * @param transaction - The transaction in which to perform any persistence
   *     operations.
   * @param documentKey - The key of the entry to look up.
   * @returns The cached document or an invalid document if we have nothing
   * cached.
   */
  getEntry(e2, t2) {
    this.assertNotApplied();
    const n2 = this.changes.get(t2);
    return void 0 !== n2 ? PersistencePromise.resolve(n2) : this.getFromCache(e2, t2);
  }
  /**
   * Looks up several entries in the cache, forwarding to
   * `RemoteDocumentCache.getEntry()`.
   *
   * @param transaction - The transaction in which to perform any persistence
   *     operations.
   * @param documentKeys - The keys of the entries to look up.
   * @returns A map of cached documents, indexed by key. If an entry cannot be
   *     found, the corresponding key will be mapped to an invalid document.
   */
  getEntries(e2, t2) {
    return this.getAllFromCache(e2, t2);
  }
  /**
   * Applies buffered changes to the underlying RemoteDocumentCache, using
   * the provided transaction.
   */
  apply(e2) {
    return this.assertNotApplied(), this.changesApplied = true, this.applyChanges(e2);
  }
  /** Helper to assert this.changes is not null  */
  assertNotApplied() {
  }
}
/**
 * @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 __PRIVATE_IndexedDbRemoteDocumentCacheImpl {
  static {
    __name(this, "__PRIVATE_IndexedDbRemoteDocumentCacheImpl");
  }
  constructor(e2) {
    this.serializer = e2;
  }
  setIndexManager(e2) {
    this.indexManager = e2;
  }
  /**
   * Adds the supplied entries to the cache.
   *
   * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer
   * returned by `newChangeBuffer()` to ensure proper accounting of metadata.
   */
  addEntry(e2, t2, n2) {
    return __PRIVATE_remoteDocumentsStore(e2).put(n2);
  }
  /**
   * Removes a document from the cache.
   *
   * All calls of `removeEntry`  are required to go through the RemoteDocumentChangeBuffer
   * returned by `newChangeBuffer()` to ensure proper accounting of metadata.
   */
  removeEntry(e2, t2, n2) {
    return __PRIVATE_remoteDocumentsStore(e2).delete(
      /**
      * Returns a key that can be used for document lookups via the primary key of
      * the DbRemoteDocument object store.
      */
      (/* @__PURE__ */ __name(function __PRIVATE_dbReadTimeKey(e3, t3) {
        const n3 = e3.path.toArray();
        return [
          /* prefix path */
          n3.slice(0, n3.length - 2),
          /* collection id */
          n3[n3.length - 2],
          __PRIVATE_toDbTimestampKey(t3),
          /* document id */
          n3[n3.length - 1]
        ];
      }, "__PRIVATE_dbReadTimeKey"))(t2, n2)
    );
  }
  /**
   * Updates the current cache size.
   *
   * Callers to `addEntry()` and `removeEntry()` *must* call this afterwards to update the
   * cache's metadata.
   */
  updateMetadata(e2, t2) {
    return this.getMetadata(e2).next((n2) => (n2.byteSize += t2, this.ur(e2, n2)));
  }
  getEntry(e2, t2) {
    let n2 = MutableDocument.newInvalidDocument(t2);
    return __PRIVATE_remoteDocumentsStore(e2).Z({
      index: ne,
      range: IDBKeyRange.only(__PRIVATE_dbKey(t2))
    }, (e3, r2) => {
      n2 = this.cr(t2, r2);
    }).next(() => n2);
  }
  /**
   * Looks up an entry in the cache.
   *
   * @param documentKey - The key of the entry to look up.
   * @returns The cached document entry and its size.
   */
  lr(e2, t2) {
    let n2 = {
      size: 0,
      document: MutableDocument.newInvalidDocument(t2)
    };
    return __PRIVATE_remoteDocumentsStore(e2).Z({
      index: ne,
      range: IDBKeyRange.only(__PRIVATE_dbKey(t2))
    }, (e3, r2) => {
      n2 = {
        document: this.cr(t2, r2),
        size: __PRIVATE_dbDocumentSize(r2)
      };
    }).next(() => n2);
  }
  getEntries(e2, t2) {
    let n2 = __PRIVATE_mutableDocumentMap();
    return this.hr(e2, t2, (e3, t3) => {
      const r2 = this.cr(e3, t3);
      n2 = n2.insert(e3, r2);
    }).next(() => n2);
  }
  /**
   * Looks up several entries in the cache.
   *
   * @param documentKeys - The set of keys entries to look up.
   * @returns A map of documents indexed by key and a map of sizes indexed by
   *     key (zero if the document does not exist).
   */
  Pr(e2, t2) {
    let n2 = __PRIVATE_mutableDocumentMap(), r2 = new SortedMap(DocumentKey.comparator);
    return this.hr(e2, t2, (e3, t3) => {
      const i2 = this.cr(e3, t3);
      n2 = n2.insert(e3, i2), r2 = r2.insert(e3, __PRIVATE_dbDocumentSize(t3));
    }).next(() => ({
      documents: n2,
      Tr: r2
    }));
  }
  hr(e2, t2, n2) {
    if (t2.isEmpty()) return PersistencePromise.resolve();
    let r2 = new SortedSet(__PRIVATE_dbKeyComparator);
    t2.forEach((e3) => r2 = r2.add(e3));
    const i2 = IDBKeyRange.bound(__PRIVATE_dbKey(r2.first()), __PRIVATE_dbKey(r2.last())), s2 = r2.getIterator();
    let o2 = s2.getNext();
    return __PRIVATE_remoteDocumentsStore(e2).Z({
      index: ne,
      range: i2
    }, (e3, t3, r3) => {
      const i3 = DocumentKey.fromSegments([...t3.prefixPath, t3.collectionGroup, t3.documentId]);
      for (; o2 && __PRIVATE_dbKeyComparator(o2, i3) < 0; ) n2(o2, null), o2 = s2.getNext();
      o2 && o2.isEqual(i3) && // Key found in cache.
      (n2(o2, t3), o2 = s2.hasNext() ? s2.getNext() : null), // Skip to the next key (if there is one).
      o2 ? r3.W(__PRIVATE_dbKey(o2)) : r3.done();
    }).next(() => {
      for (; o2; ) n2(o2, null), o2 = s2.hasNext() ? s2.getNext() : null;
    });
  }
  getDocumentsMatchingQuery(e2, t2, n2, r2, i2) {
    const s2 = t2.path, o2 = [s2.popLast().toArray(), s2.lastSegment(), __PRIVATE_toDbTimestampKey(n2.readTime), n2.documentKey.path.isEmpty() ? "" : n2.documentKey.path.lastSegment()], _2 = [s2.popLast().toArray(), s2.lastSegment(), [Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], ""];
    return __PRIVATE_remoteDocumentsStore(e2).G(IDBKeyRange.bound(o2, _2, true)).next((e3) => {
      null == i2 || i2.incrementDocumentReadCount(e3.length);
      let n3 = __PRIVATE_mutableDocumentMap();
      for (const i3 of e3) {
        const e4 = this.cr(DocumentKey.fromSegments(i3.prefixPath.concat(i3.collectionGroup, i3.documentId)), i3);
        e4.isFoundDocument() && (__PRIVATE_queryMatches(t2, e4) || r2.has(e4.key)) && // Either the document matches the given query, or it is mutated.
        (n3 = n3.insert(e4.key, e4));
      }
      return n3;
    });
  }
  getAllFromCollectionGroup(e2, t2, n2, r2) {
    let i2 = __PRIVATE_mutableDocumentMap();
    const s2 = __PRIVATE_dbCollectionGroupKey(t2, n2), o2 = __PRIVATE_dbCollectionGroupKey(t2, IndexOffset.max());
    return __PRIVATE_remoteDocumentsStore(e2).Z({
      index: ie$2,
      range: IDBKeyRange.bound(s2, o2, true)
    }, (e3, t3, n3) => {
      const s3 = this.cr(DocumentKey.fromSegments(t3.prefixPath.concat(t3.collectionGroup, t3.documentId)), t3);
      i2 = i2.insert(s3.key, s3), i2.size === r2 && n3.done();
    }).next(() => i2);
  }
  newChangeBuffer(e2) {
    return new __PRIVATE_IndexedDbRemoteDocumentChangeBuffer(this, !!e2 && e2.trackRemovals);
  }
  getSize(e2) {
    return this.getMetadata(e2).next((e3) => e3.byteSize);
  }
  getMetadata(e2) {
    return __PRIVATE_documentGlobalStore(e2).get(_e).next((e3) => (__PRIVATE_hardAssert(!!e3), e3));
  }
  ur(e2, t2) {
    return __PRIVATE_documentGlobalStore(e2).put(_e, t2);
  }
  /**
   * Decodes `dbRemoteDoc` and returns the document (or an invalid document if
   * the document corresponds to the format used for sentinel deletes).
   */
  cr(e2, t2) {
    if (t2) {
      const e3 = __PRIVATE_fromDbRemoteDocument(this.serializer, t2);
      if (!(e3.isNoDocument() && e3.version.isEqual(SnapshotVersion.min()))) return e3;
    }
    return MutableDocument.newInvalidDocument(e2);
  }
}
function __PRIVATE_newIndexedDbRemoteDocumentCache(e2) {
  return new __PRIVATE_IndexedDbRemoteDocumentCacheImpl(e2);
}
__name(__PRIVATE_newIndexedDbRemoteDocumentCache, "__PRIVATE_newIndexedDbRemoteDocumentCache");
class __PRIVATE_IndexedDbRemoteDocumentChangeBuffer extends RemoteDocumentChangeBuffer {
  static {
    __name(this, "__PRIVATE_IndexedDbRemoteDocumentChangeBuffer");
  }
  /**
   * @param documentCache - The IndexedDbRemoteDocumentCache to apply the changes to.
   * @param trackRemovals - Whether to create sentinel deletes that can be tracked by
   * `getNewDocumentChanges()`.
   */
  constructor(e2, t2) {
    super(), this.Ir = e2, this.trackRemovals = t2, // A map of document sizes and read times prior to applying the changes in
    // this buffer.
    this.Er = new ObjectMap((e3) => e3.toString(), (e3, t3) => e3.isEqual(t3));
  }
  applyChanges(e2) {
    const t2 = [];
    let n2 = 0, r2 = new SortedSet((e3, t3) => __PRIVATE_primitiveComparator(e3.canonicalString(), t3.canonicalString()));
    return this.changes.forEach((i2, s2) => {
      const o2 = this.Er.get(i2);
      if (t2.push(this.Ir.removeEntry(e2, i2, o2.readTime)), s2.isValidDocument()) {
        const _2 = __PRIVATE_toDbRemoteDocument(this.Ir.serializer, s2);
        r2 = r2.add(i2.path.popLast());
        const a2 = __PRIVATE_dbDocumentSize(_2);
        n2 += a2 - o2.size, t2.push(this.Ir.addEntry(e2, i2, _2));
      } else if (n2 -= o2.size, this.trackRemovals) {
        const n3 = __PRIVATE_toDbRemoteDocument(this.Ir.serializer, s2.convertToNoDocument(SnapshotVersion.min()));
        t2.push(this.Ir.addEntry(e2, i2, n3));
      }
    }), r2.forEach((n3) => {
      t2.push(this.Ir.indexManager.addToCollectionParentIndex(e2, n3));
    }), t2.push(this.Ir.updateMetadata(e2, n2)), PersistencePromise.waitFor(t2);
  }
  getFromCache(e2, t2) {
    return this.Ir.lr(e2, t2).next((e3) => (this.Er.set(t2, {
      size: e3.size,
      readTime: e3.document.readTime
    }), e3.document));
  }
  getAllFromCache(e2, t2) {
    return this.Ir.Pr(e2, t2).next(({ documents: e3, Tr: t3 }) => (
      // Note: `getAllFromCache` returns two maps instead of a single map from
      // keys to `DocumentSizeEntry`s. This is to allow returning the
      // `MutableDocumentMap` directly, without a conversion.
      (t3.forEach((t4, n2) => {
        this.Er.set(t4, {
          size: n2,
          readTime: e3.get(t4).readTime
        });
      }), e3)
    ));
  }
}
function __PRIVATE_documentGlobalStore(e2) {
  return __PRIVATE_getStore(e2, oe);
}
__name(__PRIVATE_documentGlobalStore, "__PRIVATE_documentGlobalStore");
function __PRIVATE_remoteDocumentsStore(e2) {
  return __PRIVATE_getStore(e2, ee);
}
__name(__PRIVATE_remoteDocumentsStore, "__PRIVATE_remoteDocumentsStore");
function __PRIVATE_dbKey(e2) {
  const t2 = e2.path.toArray();
  return [
    /* prefix path */
    t2.slice(0, t2.length - 2),
    /* collection id */
    t2[t2.length - 2],
    /* document id */
    t2[t2.length - 1]
  ];
}
__name(__PRIVATE_dbKey, "__PRIVATE_dbKey");
function __PRIVATE_dbCollectionGroupKey(e2, t2) {
  const n2 = t2.documentKey.path.toArray();
  return [
    /* collection id */
    e2,
    __PRIVATE_toDbTimestampKey(t2.readTime),
    /* prefix path */
    n2.slice(0, n2.length - 2),
    /* document id */
    n2.length > 0 ? n2[n2.length - 1] : ""
  ];
}
__name(__PRIVATE_dbCollectionGroupKey, "__PRIVATE_dbCollectionGroupKey");
function __PRIVATE_dbKeyComparator(e2, t2) {
  const n2 = e2.path.toArray(), r2 = t2.path.toArray();
  let i2 = 0;
  for (let e3 = 0; e3 < n2.length - 2 && e3 < r2.length - 2; ++e3) if (i2 = __PRIVATE_primitiveComparator(n2[e3], r2[e3]), i2) return i2;
  return i2 = __PRIVATE_primitiveComparator(n2.length, r2.length), i2 || (i2 = __PRIVATE_primitiveComparator(n2[n2.length - 2], r2[r2.length - 2]), i2 || __PRIVATE_primitiveComparator(n2[n2.length - 1], r2[r2.length - 1]));
}
__name(__PRIVATE_dbKeyComparator, "__PRIVATE_dbKeyComparator");
/**
 * @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.
 */
/**
 * @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.
 */
class OverlayedDocument {
  static {
    __name(this, "OverlayedDocument");
  }
  constructor(e2, t2) {
    this.overlayedDocument = e2, this.mutatedFields = t2;
  }
}
/**
 * @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 LocalDocumentsView {
  static {
    __name(this, "LocalDocumentsView");
  }
  constructor(e2, t2, n2, r2) {
    this.remoteDocumentCache = e2, this.mutationQueue = t2, this.documentOverlayCache = n2, this.indexManager = r2;
  }
  /**
   * Get the local view of the document identified by `key`.
   *
   * @returns Local view of the document or null if we don't have any cached
   * state for it.
   */
  getDocument(e2, t2) {
    let n2 = null;
    return this.documentOverlayCache.getOverlay(e2, t2).next((r2) => (n2 = r2, this.remoteDocumentCache.getEntry(e2, t2))).next((e3) => (null !== n2 && __PRIVATE_mutationApplyToLocalView(n2.mutation, e3, FieldMask.empty(), Timestamp.now()), e3));
  }
  /**
   * Gets the local view of the documents identified by `keys`.
   *
   * If we don't have cached state for a document in `keys`, a NoDocument will
   * be stored for that key in the resulting set.
   */
  getDocuments(e2, t2) {
    return this.remoteDocumentCache.getEntries(e2, t2).next((t3) => this.getLocalViewOfDocuments(e2, t3, __PRIVATE_documentKeySet()).next(() => t3));
  }
  /**
   * Similar to `getDocuments`, but creates the local view from the given
   * `baseDocs` without retrieving documents from the local store.
   *
   * @param transaction - The transaction this operation is scoped to.
   * @param docs - The documents to apply local mutations to get the local views.
   * @param existenceStateChanged - The set of document keys whose existence state
   *   is changed. This is useful to determine if some documents overlay needs
   *   to be recalculated.
   */
  getLocalViewOfDocuments(e2, t2, n2 = __PRIVATE_documentKeySet()) {
    const r2 = __PRIVATE_newOverlayMap();
    return this.populateOverlays(e2, r2, t2).next(() => this.computeViews(e2, t2, r2, n2).next((e3) => {
      let t3 = documentMap();
      return e3.forEach((e4, n3) => {
        t3 = t3.insert(e4, n3.overlayedDocument);
      }), t3;
    }));
  }
  /**
   * Gets the overlayed documents for the given document map, which will include
   * the local view of those documents and a `FieldMask` indicating which fields
   * are mutated locally, `null` if overlay is a Set or Delete mutation.
   */
  getOverlayedDocuments(e2, t2) {
    const n2 = __PRIVATE_newOverlayMap();
    return this.populateOverlays(e2, n2, t2).next(() => this.computeViews(e2, t2, n2, __PRIVATE_documentKeySet()));
  }
  /**
   * Fetches the overlays for {@code docs} and adds them to provided overlay map
   * if the map does not already contain an entry for the given document key.
   */
  populateOverlays(e2, t2, n2) {
    const r2 = [];
    return n2.forEach((e3) => {
      t2.has(e3) || r2.push(e3);
    }), this.documentOverlayCache.getOverlays(e2, r2).next((e3) => {
      e3.forEach((e4, n3) => {
        t2.set(e4, n3);
      });
    });
  }
  /**
   * Computes the local view for the given documents.
   *
   * @param docs - The documents to compute views for. It also has the base
   *   version of the documents.
   * @param overlays - The overlays that need to be applied to the given base
   *   version of the documents.
   * @param existenceStateChanged - A set of documents whose existence states
   *   might have changed. This is used to determine if we need to re-calculate
   *   overlays from mutation queues.
   * @return A map represents the local documents view.
   */
  computeViews(e2, t2, n2, r2) {
    let i2 = __PRIVATE_mutableDocumentMap();
    const s2 = __PRIVATE_newDocumentKeyMap(), o2 = (/* @__PURE__ */ __name(function __PRIVATE_newOverlayedDocumentMap() {
      return __PRIVATE_newDocumentKeyMap();
    }, "__PRIVATE_newOverlayedDocumentMap"))();
    return t2.forEach((e3, t3) => {
      const o3 = n2.get(t3.key);
      r2.has(t3.key) && (void 0 === o3 || o3.mutation instanceof __PRIVATE_PatchMutation) ? i2 = i2.insert(t3.key, t3) : void 0 !== o3 ? (s2.set(t3.key, o3.mutation.getFieldMask()), __PRIVATE_mutationApplyToLocalView(o3.mutation, t3, o3.mutation.getFieldMask(), Timestamp.now())) : (
        // no overlay exists
        // Using EMPTY to indicate there is no overlay for the document.
        s2.set(t3.key, FieldMask.empty())
      );
    }), this.recalculateAndSaveOverlays(e2, i2).next((e3) => (e3.forEach((e4, t3) => s2.set(e4, t3)), t2.forEach((e4, t3) => {
      var n3;
      return o2.set(e4, new OverlayedDocument(t3, null !== (n3 = s2.get(e4)) && void 0 !== n3 ? n3 : null));
    }), o2));
  }
  recalculateAndSaveOverlays(e2, t2) {
    const n2 = __PRIVATE_newDocumentKeyMap();
    let r2 = new SortedMap((e3, t3) => e3 - t3), i2 = __PRIVATE_documentKeySet();
    return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(e2, t2).next((e3) => {
      for (const i3 of e3) i3.keys().forEach((e4) => {
        const s2 = t2.get(e4);
        if (null === s2) return;
        let o2 = n2.get(e4) || FieldMask.empty();
        o2 = i3.applyToLocalView(s2, o2), n2.set(e4, o2);
        const _2 = (r2.get(i3.batchId) || __PRIVATE_documentKeySet()).add(e4);
        r2 = r2.insert(i3.batchId, _2);
      });
    }).next(() => {
      const s2 = [], o2 = r2.getReverseIterator();
      for (; o2.hasNext(); ) {
        const r3 = o2.getNext(), _2 = r3.key, a2 = r3.value, u2 = __PRIVATE_newMutationMap();
        a2.forEach((e3) => {
          if (!i2.has(e3)) {
            const r4 = __PRIVATE_calculateOverlayMutation(t2.get(e3), n2.get(e3));
            null !== r4 && u2.set(e3, r4), i2 = i2.add(e3);
          }
        }), s2.push(this.documentOverlayCache.saveOverlays(e2, _2, u2));
      }
      return PersistencePromise.waitFor(s2);
    }).next(() => n2);
  }
  /**
   * Recalculates overlays by reading the documents from remote document cache
   * first, and saves them after they are calculated.
   */
  recalculateAndSaveOverlaysForDocumentKeys(e2, t2) {
    return this.remoteDocumentCache.getEntries(e2, t2).next((t3) => this.recalculateAndSaveOverlays(e2, t3));
  }
  /**
   * Performs a query against the local view of all documents.
   *
   * @param transaction - The persistence transaction.
   * @param query - The query to match documents against.
   * @param offset - Read time and key to start scanning by (exclusive).
   * @param context - A optional tracker to keep a record of important details
   *   during database local query execution.
   */
  getDocumentsMatchingQuery(e2, t2, n2, r2) {
    return (/* @__PURE__ */ __name(function __PRIVATE_isDocumentQuery$1(e3) {
      return DocumentKey.isDocumentKey(e3.path) && null === e3.collectionGroup && 0 === e3.filters.length;
    }, "__PRIVATE_isDocumentQuery$1"))(t2) ? this.getDocumentsMatchingDocumentQuery(e2, t2.path) : __PRIVATE_isCollectionGroupQuery(t2) ? this.getDocumentsMatchingCollectionGroupQuery(e2, t2, n2, r2) : this.getDocumentsMatchingCollectionQuery(e2, t2, n2, r2);
  }
  /**
   * Given a collection group, returns the next documents that follow the provided offset, along
   * with an updated batch ID.
   *
   * <p>The documents returned by this method are ordered by remote version from the provided
   * offset. If there are no more remote documents after the provided offset, documents with
   * mutations in order of batch id from the offset are returned. Since all documents in a batch are
   * returned together, the total number of documents returned can exceed {@code count}.
   *
   * @param transaction
   * @param collectionGroup The collection group for the documents.
   * @param offset The offset to index into.
   * @param count The number of documents to return
   * @return A LocalWriteResult with the documents that follow the provided offset and the last processed batch id.
   */
  getNextDocuments(e2, t2, n2, r2) {
    return this.remoteDocumentCache.getAllFromCollectionGroup(e2, t2, n2, r2).next((i2) => {
      const s2 = r2 - i2.size > 0 ? this.documentOverlayCache.getOverlaysForCollectionGroup(e2, t2, n2.largestBatchId, r2 - i2.size) : PersistencePromise.resolve(__PRIVATE_newOverlayMap());
      let o2 = N, _2 = i2;
      return s2.next((t3) => PersistencePromise.forEach(t3, (t4, n3) => (o2 < n3.largestBatchId && (o2 = n3.largestBatchId), i2.get(t4) ? PersistencePromise.resolve() : this.remoteDocumentCache.getEntry(e2, t4).next((e3) => {
        _2 = _2.insert(t4, e3);
      }))).next(() => this.populateOverlays(e2, t3, i2)).next(() => this.computeViews(e2, _2, t3, __PRIVATE_documentKeySet())).next((e3) => ({
        batchId: o2,
        changes: __PRIVATE_convertOverlayedDocumentMapToDocumentMap(e3)
      })));
    });
  }
  getDocumentsMatchingDocumentQuery(e2, t2) {
    return this.getDocument(e2, new DocumentKey(t2)).next((e3) => {
      let t3 = documentMap();
      return e3.isFoundDocument() && (t3 = t3.insert(e3.key, e3)), t3;
    });
  }
  getDocumentsMatchingCollectionGroupQuery(e2, t2, n2, r2) {
    const i2 = t2.collectionGroup;
    let s2 = documentMap();
    return this.indexManager.getCollectionParents(e2, i2).next((o2) => PersistencePromise.forEach(o2, (o3) => {
      const _2 = (/* @__PURE__ */ __name(function __PRIVATE_asCollectionQueryAtPath(e3, t3) {
        return new __PRIVATE_QueryImpl(
          t3,
          /*collectionGroup=*/
          null,
          e3.explicitOrderBy.slice(),
          e3.filters.slice(),
          e3.limit,
          e3.limitType,
          e3.startAt,
          e3.endAt
        );
      }, "__PRIVATE_asCollectionQueryAtPath"))(t2, o3.child(i2));
      return this.getDocumentsMatchingCollectionQuery(e2, _2, n2, r2).next((e3) => {
        e3.forEach((e4, t3) => {
          s2 = s2.insert(e4, t3);
        });
      });
    }).next(() => s2));
  }
  getDocumentsMatchingCollectionQuery(e2, t2, n2, r2) {
    let i2;
    return this.documentOverlayCache.getOverlaysForCollection(e2, t2.path, n2.largestBatchId).next((s2) => (i2 = s2, this.remoteDocumentCache.getDocumentsMatchingQuery(e2, t2, n2, i2, r2))).next((e3) => {
      i2.forEach((t3, n4) => {
        const r3 = n4.getKey();
        null === e3.get(r3) && (e3 = e3.insert(r3, MutableDocument.newInvalidDocument(r3)));
      });
      let n3 = documentMap();
      return e3.forEach((e4, r3) => {
        const s2 = i2.get(e4);
        void 0 !== s2 && __PRIVATE_mutationApplyToLocalView(s2.mutation, r3, FieldMask.empty(), Timestamp.now()), // Finally, insert the documents that still match the query
        __PRIVATE_queryMatches(t2, r3) && (n3 = n3.insert(e4, r3));
      }), n3;
    });
  }
}
/**
 * @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 __PRIVATE_MemoryBundleCache {
  static {
    __name(this, "__PRIVATE_MemoryBundleCache");
  }
  constructor(e2) {
    this.serializer = e2, this.dr = /* @__PURE__ */ new Map(), this.Ar = /* @__PURE__ */ new Map();
  }
  getBundleMetadata(e2, t2) {
    return PersistencePromise.resolve(this.dr.get(t2));
  }
  saveBundleMetadata(e2, t2) {
    return this.dr.set(
      t2.id,
      /** Decodes a BundleMetadata proto into a BundleMetadata object. */
      (/* @__PURE__ */ __name(function __PRIVATE_fromBundleMetadata(e3) {
        return {
          id: e3.id,
          version: e3.version,
          createTime: __PRIVATE_fromVersion(e3.createTime)
        };
      }, "__PRIVATE_fromBundleMetadata"))(t2)
    ), PersistencePromise.resolve();
  }
  getNamedQuery(e2, t2) {
    return PersistencePromise.resolve(this.Ar.get(t2));
  }
  saveNamedQuery(e2, t2) {
    return this.Ar.set(t2.name, (/* @__PURE__ */ __name(function __PRIVATE_fromProtoNamedQuery(e3) {
      return {
        name: e3.name,
        query: __PRIVATE_fromBundledQuery(e3.bundledQuery),
        readTime: __PRIVATE_fromVersion(e3.readTime)
      };
    }, "__PRIVATE_fromProtoNamedQuery"))(t2)), PersistencePromise.resolve();
  }
}
/**
 * @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.
 */
class __PRIVATE_MemoryDocumentOverlayCache {
  static {
    __name(this, "__PRIVATE_MemoryDocumentOverlayCache");
  }
  constructor() {
    this.overlays = new SortedMap(DocumentKey.comparator), this.Rr = /* @__PURE__ */ new Map();
  }
  getOverlay(e2, t2) {
    return PersistencePromise.resolve(this.overlays.get(t2));
  }
  getOverlays(e2, t2) {
    const n2 = __PRIVATE_newOverlayMap();
    return PersistencePromise.forEach(t2, (t3) => this.getOverlay(e2, t3).next((e3) => {
      null !== e3 && n2.set(t3, e3);
    })).next(() => n2);
  }
  saveOverlays(e2, t2, n2) {
    return n2.forEach((n3, r2) => {
      this.Et(e2, t2, r2);
    }), PersistencePromise.resolve();
  }
  removeOverlaysForBatchId(e2, t2, n2) {
    const r2 = this.Rr.get(n2);
    return void 0 !== r2 && (r2.forEach((e3) => this.overlays = this.overlays.remove(e3)), this.Rr.delete(n2)), PersistencePromise.resolve();
  }
  getOverlaysForCollection(e2, t2, n2) {
    const r2 = __PRIVATE_newOverlayMap(), i2 = t2.length + 1, s2 = new DocumentKey(t2.child("")), o2 = this.overlays.getIteratorFrom(s2);
    for (; o2.hasNext(); ) {
      const e3 = o2.getNext().value, s3 = e3.getKey();
      if (!t2.isPrefixOf(s3.path)) break;
      s3.path.length === i2 && (e3.largestBatchId > n2 && r2.set(e3.getKey(), e3));
    }
    return PersistencePromise.resolve(r2);
  }
  getOverlaysForCollectionGroup(e2, t2, n2, r2) {
    let i2 = new SortedMap((e3, t3) => e3 - t3);
    const s2 = this.overlays.getIterator();
    for (; s2.hasNext(); ) {
      const e3 = s2.getNext().value;
      if (e3.getKey().getCollectionGroup() === t2 && e3.largestBatchId > n2) {
        let t3 = i2.get(e3.largestBatchId);
        null === t3 && (t3 = __PRIVATE_newOverlayMap(), i2 = i2.insert(e3.largestBatchId, t3)), t3.set(e3.getKey(), e3);
      }
    }
    const o2 = __PRIVATE_newOverlayMap(), _2 = i2.getIterator();
    for (; _2.hasNext(); ) {
      if (_2.getNext().value.forEach((e3, t3) => o2.set(e3, t3)), o2.size() >= r2) break;
    }
    return PersistencePromise.resolve(o2);
  }
  Et(e2, t2, n2) {
    const r2 = this.overlays.get(n2.key);
    if (null !== r2) {
      const e3 = this.Rr.get(r2.largestBatchId).delete(n2.key);
      this.Rr.set(r2.largestBatchId, e3);
    }
    this.overlays = this.overlays.insert(n2.key, new Overlay(t2, n2));
    let i2 = this.Rr.get(t2);
    void 0 === i2 && (i2 = __PRIVATE_documentKeySet(), this.Rr.set(t2, i2)), this.Rr.set(t2, i2.add(n2.key));
  }
}
/**
 * @license
 * Copyright 2024 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 __PRIVATE_MemoryGlobalsCache {
  static {
    __name(this, "__PRIVATE_MemoryGlobalsCache");
  }
  constructor() {
    this.sessionToken = ByteString.EMPTY_BYTE_STRING;
  }
  getSessionToken(e2) {
    return PersistencePromise.resolve(this.sessionToken);
  }
  setSessionToken(e2, t2) {
    return this.sessionToken = t2, PersistencePromise.resolve();
  }
}
/**
 * @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 __PRIVATE_ReferenceSet {
  static {
    __name(this, "__PRIVATE_ReferenceSet");
  }
  constructor() {
    this.Vr = new SortedSet(__PRIVATE_DocReference.mr), // A set of outstanding references to a document sorted by target id.
    this.gr = new SortedSet(__PRIVATE_DocReference.pr);
  }
  /** Returns true if the reference set contains no references. */
  isEmpty() {
    return this.Vr.isEmpty();
  }
  /** Adds a reference to the given document key for the given ID. */
  addReference(e2, t2) {
    const n2 = new __PRIVATE_DocReference(e2, t2);
    this.Vr = this.Vr.add(n2), this.gr = this.gr.add(n2);
  }
  /** Add references to the given document keys for the given ID. */
  yr(e2, t2) {
    e2.forEach((e3) => this.addReference(e3, t2));
  }
  /**
   * Removes a reference to the given document key for the given
   * ID.
   */
  removeReference(e2, t2) {
    this.wr(new __PRIVATE_DocReference(e2, t2));
  }
  Sr(e2, t2) {
    e2.forEach((e3) => this.removeReference(e3, t2));
  }
  /**
   * Clears all references with a given ID. Calls removeRef() for each key
   * removed.
   */
  br(e2) {
    const t2 = new DocumentKey(new ResourcePath([])), n2 = new __PRIVATE_DocReference(t2, e2), r2 = new __PRIVATE_DocReference(t2, e2 + 1), i2 = [];
    return this.gr.forEachInRange([n2, r2], (e3) => {
      this.wr(e3), i2.push(e3.key);
    }), i2;
  }
  Dr() {
    this.Vr.forEach((e2) => this.wr(e2));
  }
  wr(e2) {
    this.Vr = this.Vr.delete(e2), this.gr = this.gr.delete(e2);
  }
  vr(e2) {
    const t2 = new DocumentKey(new ResourcePath([])), n2 = new __PRIVATE_DocReference(t2, e2), r2 = new __PRIVATE_DocReference(t2, e2 + 1);
    let i2 = __PRIVATE_documentKeySet();
    return this.gr.forEachInRange([n2, r2], (e3) => {
      i2 = i2.add(e3.key);
    }), i2;
  }
  containsKey(e2) {
    const t2 = new __PRIVATE_DocReference(e2, 0), n2 = this.Vr.firstAfterOrEqual(t2);
    return null !== n2 && e2.isEqual(n2.key);
  }
}
class __PRIVATE_DocReference {
  static {
    __name(this, "__PRIVATE_DocReference");
  }
  constructor(e2, t2) {
    this.key = e2, this.Cr = t2;
  }
  /** Compare by key then by ID */
  static mr(e2, t2) {
    return DocumentKey.comparator(e2.key, t2.key) || __PRIVATE_primitiveComparator(e2.Cr, t2.Cr);
  }
  /** Compare by ID then by key */
  static pr(e2, t2) {
    return __PRIVATE_primitiveComparator(e2.Cr, t2.Cr) || DocumentKey.comparator(e2.key, t2.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.
 */
class __PRIVATE_MemoryMutationQueue {
  static {
    __name(this, "__PRIVATE_MemoryMutationQueue");
  }
  constructor(e2, t2) {
    this.indexManager = e2, this.referenceDelegate = t2, /**
     * The set of all mutations that have been sent but not yet been applied to
     * the backend.
     */
    this.mutationQueue = [], /** Next value to use when assigning sequential IDs to each mutation batch. */
    this.Fr = 1, /** An ordered mapping between documents and the mutations batch IDs. */
    this.Mr = new SortedSet(__PRIVATE_DocReference.mr);
  }
  checkEmpty(e2) {
    return PersistencePromise.resolve(0 === this.mutationQueue.length);
  }
  addMutationBatch(e2, t2, n2, r2) {
    const i2 = this.Fr;
    this.Fr++, this.mutationQueue.length > 0 && this.mutationQueue[this.mutationQueue.length - 1];
    const s2 = new MutationBatch(i2, t2, n2, r2);
    this.mutationQueue.push(s2);
    for (const t3 of r2) this.Mr = this.Mr.add(new __PRIVATE_DocReference(t3.key, i2)), this.indexManager.addToCollectionParentIndex(e2, t3.key.path.popLast());
    return PersistencePromise.resolve(s2);
  }
  lookupMutationBatch(e2, t2) {
    return PersistencePromise.resolve(this.Or(t2));
  }
  getNextMutationBatchAfterBatchId(e2, t2) {
    const n2 = t2 + 1, r2 = this.Nr(n2), i2 = r2 < 0 ? 0 : r2;
    return PersistencePromise.resolve(this.mutationQueue.length > i2 ? this.mutationQueue[i2] : null);
  }
  getHighestUnacknowledgedBatchId() {
    return PersistencePromise.resolve(0 === this.mutationQueue.length ? Q : this.Fr - 1);
  }
  getAllMutationBatches(e2) {
    return PersistencePromise.resolve(this.mutationQueue.slice());
  }
  getAllMutationBatchesAffectingDocumentKey(e2, t2) {
    const n2 = new __PRIVATE_DocReference(t2, 0), r2 = new __PRIVATE_DocReference(t2, Number.POSITIVE_INFINITY), i2 = [];
    return this.Mr.forEachInRange([n2, r2], (e3) => {
      const t3 = this.Or(e3.Cr);
      i2.push(t3);
    }), PersistencePromise.resolve(i2);
  }
  getAllMutationBatchesAffectingDocumentKeys(e2, t2) {
    let n2 = new SortedSet(__PRIVATE_primitiveComparator);
    return t2.forEach((e3) => {
      const t3 = new __PRIVATE_DocReference(e3, 0), r2 = new __PRIVATE_DocReference(e3, Number.POSITIVE_INFINITY);
      this.Mr.forEachInRange([t3, r2], (e4) => {
        n2 = n2.add(e4.Cr);
      });
    }), PersistencePromise.resolve(this.Br(n2));
  }
  getAllMutationBatchesAffectingQuery(e2, t2) {
    const n2 = t2.path, r2 = n2.length + 1;
    let i2 = n2;
    DocumentKey.isDocumentKey(i2) || (i2 = i2.child(""));
    const s2 = new __PRIVATE_DocReference(new DocumentKey(i2), 0);
    let o2 = new SortedSet(__PRIVATE_primitiveComparator);
    return this.Mr.forEachWhile((e3) => {
      const t3 = e3.key.path;
      return !!n2.isPrefixOf(t3) && // Rows with document keys more than one segment longer than the query
      // path can't be matches. For example, a query on 'rooms' can't match
      // the document /rooms/abc/messages/xyx.
      // TODO(mcg): we'll need a different scanner when we implement
      // ancestor queries.
      (t3.length === r2 && (o2 = o2.add(e3.Cr)), true);
    }, s2), PersistencePromise.resolve(this.Br(o2));
  }
  Br(e2) {
    const t2 = [];
    return e2.forEach((e3) => {
      const n2 = this.Or(e3);
      null !== n2 && t2.push(n2);
    }), t2;
  }
  removeMutationBatch(e2, t2) {
    __PRIVATE_hardAssert(0 === this.Lr(t2.batchId, "removed")), this.mutationQueue.shift();
    let n2 = this.Mr;
    return PersistencePromise.forEach(t2.mutations, (r2) => {
      const i2 = new __PRIVATE_DocReference(r2.key, t2.batchId);
      return n2 = n2.delete(i2), this.referenceDelegate.markPotentiallyOrphaned(e2, r2.key);
    }).next(() => {
      this.Mr = n2;
    });
  }
  qn(e2) {
  }
  containsKey(e2, t2) {
    const n2 = new __PRIVATE_DocReference(t2, 0), r2 = this.Mr.firstAfterOrEqual(n2);
    return PersistencePromise.resolve(t2.isEqual(r2 && r2.key));
  }
  performConsistencyCheck(e2) {
    return this.mutationQueue.length, PersistencePromise.resolve();
  }
  /**
   * Finds the index of the given batchId in the mutation queue and asserts that
   * the resulting index is within the bounds of the queue.
   *
   * @param batchId - The batchId to search for
   * @param action - A description of what the caller is doing, phrased in passive
   * form (e.g. "acknowledged" in a routine that acknowledges batches).
   */
  Lr(e2, t2) {
    return this.Nr(e2);
  }
  /**
   * Finds the index of the given batchId in the mutation queue. This operation
   * is O(1).
   *
   * @returns The computed index of the batch with the given batchId, based on
   * the state of the queue. Note this index can be negative if the requested
   * batchId has already been removed from the queue or past the end of the
   * queue if the batchId is larger than the last added batch.
   */
  Nr(e2) {
    if (0 === this.mutationQueue.length)
      return 0;
    return e2 - this.mutationQueue[0].batchId;
  }
  /**
   * A version of lookupMutationBatch that doesn't return a promise, this makes
   * other functions that uses this code easier to read and more efficient.
   */
  Or(e2) {
    const t2 = this.Nr(e2);
    if (t2 < 0 || t2 >= this.mutationQueue.length) return null;
    return this.mutationQueue[t2];
  }
}
/**
 * @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 __PRIVATE_MemoryRemoteDocumentCacheImpl {
  static {
    __name(this, "__PRIVATE_MemoryRemoteDocumentCacheImpl");
  }
  /**
   * @param sizer - Used to assess the size of a document. For eager GC, this is
   * expected to just return 0 to avoid unnecessarily doing the work of
   * calculating the size.
   */
  constructor(e2) {
    this.kr = e2, /** Underlying cache of documents and their read times. */
    this.docs = (/* @__PURE__ */ __name(function __PRIVATE_documentEntryMap() {
      return new SortedMap(DocumentKey.comparator);
    }, "__PRIVATE_documentEntryMap"))(), /** Size of all cached documents. */
    this.size = 0;
  }
  setIndexManager(e2) {
    this.indexManager = e2;
  }
  /**
   * Adds the supplied entry to the cache and updates the cache size as appropriate.
   *
   * All calls of `addEntry`  are required to go through the RemoteDocumentChangeBuffer
   * returned by `newChangeBuffer()`.
   */
  addEntry(e2, t2) {
    const n2 = t2.key, r2 = this.docs.get(n2), i2 = r2 ? r2.size : 0, s2 = this.kr(t2);
    return this.docs = this.docs.insert(n2, {
      document: t2.mutableCopy(),
      size: s2
    }), this.size += s2 - i2, this.indexManager.addToCollectionParentIndex(e2, n2.path.popLast());
  }
  /**
   * Removes the specified entry from the cache and updates the cache size as appropriate.
   *
   * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer
   * returned by `newChangeBuffer()`.
   */
  removeEntry(e2) {
    const t2 = this.docs.get(e2);
    t2 && (this.docs = this.docs.remove(e2), this.size -= t2.size);
  }
  getEntry(e2, t2) {
    const n2 = this.docs.get(t2);
    return PersistencePromise.resolve(n2 ? n2.document.mutableCopy() : MutableDocument.newInvalidDocument(t2));
  }
  getEntries(e2, t2) {
    let n2 = __PRIVATE_mutableDocumentMap();
    return t2.forEach((e3) => {
      const t3 = this.docs.get(e3);
      n2 = n2.insert(e3, t3 ? t3.document.mutableCopy() : MutableDocument.newInvalidDocument(e3));
    }), PersistencePromise.resolve(n2);
  }
  getDocumentsMatchingQuery(e2, t2, n2, r2) {
    let i2 = __PRIVATE_mutableDocumentMap();
    const s2 = t2.path, o2 = new DocumentKey(s2.child("__id-9223372036854775808__")), _2 = this.docs.getIteratorFrom(o2);
    for (; _2.hasNext(); ) {
      const { key: e3, value: { document: o3 } } = _2.getNext();
      if (!s2.isPrefixOf(e3.path)) break;
      e3.path.length > s2.length + 1 || (__PRIVATE_indexOffsetComparator(__PRIVATE_newIndexOffsetFromDocument(o3), n2) <= 0 || (r2.has(o3.key) || __PRIVATE_queryMatches(t2, o3)) && (i2 = i2.insert(o3.key, o3.mutableCopy())));
    }
    return PersistencePromise.resolve(i2);
  }
  getAllFromCollectionGroup(e2, t2, n2, r2) {
    fail();
  }
  qr(e2, t2) {
    return PersistencePromise.forEach(this.docs, (e3) => t2(e3));
  }
  newChangeBuffer(e2) {
    return new __PRIVATE_MemoryRemoteDocumentChangeBuffer(this);
  }
  getSize(e2) {
    return PersistencePromise.resolve(this.size);
  }
}
class __PRIVATE_MemoryRemoteDocumentChangeBuffer extends RemoteDocumentChangeBuffer {
  static {
    __name(this, "__PRIVATE_MemoryRemoteDocumentChangeBuffer");
  }
  constructor(e2) {
    super(), this.Ir = e2;
  }
  applyChanges(e2) {
    const t2 = [];
    return this.changes.forEach((n2, r2) => {
      r2.isValidDocument() ? t2.push(this.Ir.addEntry(e2, r2)) : this.Ir.removeEntry(n2);
    }), PersistencePromise.waitFor(t2);
  }
  getFromCache(e2, t2) {
    return this.Ir.getEntry(e2, t2);
  }
  getAllFromCache(e2, t2) {
    return this.Ir.getEntries(e2, t2);
  }
}
/**
 * @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 __PRIVATE_MemoryTargetCache {
  static {
    __name(this, "__PRIVATE_MemoryTargetCache");
  }
  constructor(e2) {
    this.persistence = e2, /**
     * Maps a target to the data about that target
     */
    this.Qr = new ObjectMap((e3) => __PRIVATE_canonifyTarget(e3), __PRIVATE_targetEquals), /** The last received snapshot version. */
    this.lastRemoteSnapshotVersion = SnapshotVersion.min(), /** The highest numbered target ID encountered. */
    this.highestTargetId = 0, /** The highest sequence number encountered. */
    this.$r = 0, /**
     * A ordered bidirectional mapping between documents and the remote target
     * IDs.
     */
    this.Ur = new __PRIVATE_ReferenceSet(), this.targetCount = 0, this.Kr = __PRIVATE_TargetIdGenerator.Un();
  }
  forEachTarget(e2, t2) {
    return this.Qr.forEach((e3, n2) => t2(n2)), PersistencePromise.resolve();
  }
  getLastRemoteSnapshotVersion(e2) {
    return PersistencePromise.resolve(this.lastRemoteSnapshotVersion);
  }
  getHighestSequenceNumber(e2) {
    return PersistencePromise.resolve(this.$r);
  }
  allocateTargetId(e2) {
    return this.highestTargetId = this.Kr.next(), PersistencePromise.resolve(this.highestTargetId);
  }
  setTargetsMetadata(e2, t2, n2) {
    return n2 && (this.lastRemoteSnapshotVersion = n2), t2 > this.$r && (this.$r = t2), PersistencePromise.resolve();
  }
  zn(e2) {
    this.Qr.set(e2.target, e2);
    const t2 = e2.targetId;
    t2 > this.highestTargetId && (this.Kr = new __PRIVATE_TargetIdGenerator(t2), this.highestTargetId = t2), e2.sequenceNumber > this.$r && (this.$r = e2.sequenceNumber);
  }
  addTargetData(e2, t2) {
    return this.zn(t2), this.targetCount += 1, PersistencePromise.resolve();
  }
  updateTargetData(e2, t2) {
    return this.zn(t2), PersistencePromise.resolve();
  }
  removeTargetData(e2, t2) {
    return this.Qr.delete(t2.target), this.Ur.br(t2.targetId), this.targetCount -= 1, PersistencePromise.resolve();
  }
  removeTargets(e2, t2, n2) {
    let r2 = 0;
    const i2 = [];
    return this.Qr.forEach((s2, o2) => {
      o2.sequenceNumber <= t2 && null === n2.get(o2.targetId) && (this.Qr.delete(s2), i2.push(this.removeMatchingKeysForTargetId(e2, o2.targetId)), r2++);
    }), PersistencePromise.waitFor(i2).next(() => r2);
  }
  getTargetCount(e2) {
    return PersistencePromise.resolve(this.targetCount);
  }
  getTargetData(e2, t2) {
    const n2 = this.Qr.get(t2) || null;
    return PersistencePromise.resolve(n2);
  }
  addMatchingKeys(e2, t2, n2) {
    return this.Ur.yr(t2, n2), PersistencePromise.resolve();
  }
  removeMatchingKeys(e2, t2, n2) {
    this.Ur.Sr(t2, n2);
    const r2 = this.persistence.referenceDelegate, i2 = [];
    return r2 && t2.forEach((t3) => {
      i2.push(r2.markPotentiallyOrphaned(e2, t3));
    }), PersistencePromise.waitFor(i2);
  }
  removeMatchingKeysForTargetId(e2, t2) {
    return this.Ur.br(t2), PersistencePromise.resolve();
  }
  getMatchingKeysForTargetId(e2, t2) {
    const n2 = this.Ur.vr(t2);
    return PersistencePromise.resolve(n2);
  }
  containsKey(e2, t2) {
    return PersistencePromise.resolve(this.Ur.containsKey(t2));
  }
}
/**
 * @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 __PRIVATE_MemoryPersistence {
  static {
    __name(this, "__PRIVATE_MemoryPersistence");
  }
  /**
   * The constructor accepts a factory for creating a reference delegate. This
   * allows both the delegate and this instance to have strong references to
   * each other without having nullable fields that would then need to be
   * checked or asserted on every access.
   */
  constructor(e2, t2) {
    this.Wr = {}, this.overlays = {}, this.Gr = new __PRIVATE_ListenSequence(0), this.zr = false, this.zr = true, this.jr = new __PRIVATE_MemoryGlobalsCache(), this.referenceDelegate = e2(this), this.Hr = new __PRIVATE_MemoryTargetCache(this);
    this.indexManager = new __PRIVATE_MemoryIndexManager(), this.remoteDocumentCache = (/* @__PURE__ */ __name(function __PRIVATE_newMemoryRemoteDocumentCache(e3) {
      return new __PRIVATE_MemoryRemoteDocumentCacheImpl(e3);
    }, "__PRIVATE_newMemoryRemoteDocumentCache"))((e3) => this.referenceDelegate.Jr(e3)), this.serializer = new __PRIVATE_LocalSerializer(t2), this.Yr = new __PRIVATE_MemoryBundleCache(this.serializer);
  }
  start() {
    return Promise.resolve();
  }
  shutdown() {
    return this.zr = false, Promise.resolve();
  }
  get started() {
    return this.zr;
  }
  setDatabaseDeletedListener() {
  }
  setNetworkEnabled() {
  }
  getIndexManager(e2) {
    return this.indexManager;
  }
  getDocumentOverlayCache(e2) {
    let t2 = this.overlays[e2.toKey()];
    return t2 || (t2 = new __PRIVATE_MemoryDocumentOverlayCache(), this.overlays[e2.toKey()] = t2), t2;
  }
  getMutationQueue(e2, t2) {
    let n2 = this.Wr[e2.toKey()];
    return n2 || (n2 = new __PRIVATE_MemoryMutationQueue(t2, this.referenceDelegate), this.Wr[e2.toKey()] = n2), n2;
  }
  getGlobalsCache() {
    return this.jr;
  }
  getTargetCache() {
    return this.Hr;
  }
  getRemoteDocumentCache() {
    return this.remoteDocumentCache;
  }
  getBundleCache() {
    return this.Yr;
  }
  runTransaction(e2, t2, n2) {
    __PRIVATE_logDebug("MemoryPersistence", "Starting transaction:", e2);
    const r2 = new __PRIVATE_MemoryTransaction(this.Gr.next());
    return this.referenceDelegate.Zr(), n2(r2).next((e3) => this.referenceDelegate.Xr(r2).next(() => e3)).toPromise().then((e3) => (r2.raiseOnCommittedEvent(), e3));
  }
  ei(e2, t2) {
    return PersistencePromise.or(Object.values(this.Wr).map((n2) => () => n2.containsKey(e2, t2)));
  }
}
class __PRIVATE_MemoryTransaction extends PersistenceTransaction {
  static {
    __name(this, "__PRIVATE_MemoryTransaction");
  }
  constructor(e2) {
    super(), this.currentSequenceNumber = e2;
  }
}
class __PRIVATE_MemoryEagerDelegate {
  static {
    __name(this, "__PRIVATE_MemoryEagerDelegate");
  }
  constructor(e2) {
    this.persistence = e2, /** Tracks all documents that are active in Query views. */
    this.ti = new __PRIVATE_ReferenceSet(), /** The list of documents that are potentially GCed after each transaction. */
    this.ni = null;
  }
  static ri(e2) {
    return new __PRIVATE_MemoryEagerDelegate(e2);
  }
  get ii() {
    if (this.ni) return this.ni;
    throw fail();
  }
  addReference(e2, t2, n2) {
    return this.ti.addReference(n2, t2), this.ii.delete(n2.toString()), PersistencePromise.resolve();
  }
  removeReference(e2, t2, n2) {
    return this.ti.removeReference(n2, t2), this.ii.add(n2.toString()), PersistencePromise.resolve();
  }
  markPotentiallyOrphaned(e2, t2) {
    return this.ii.add(t2.toString()), PersistencePromise.resolve();
  }
  removeTarget(e2, t2) {
    this.ti.br(t2.targetId).forEach((e3) => this.ii.add(e3.toString()));
    const n2 = this.persistence.getTargetCache();
    return n2.getMatchingKeysForTargetId(e2, t2.targetId).next((e3) => {
      e3.forEach((e4) => this.ii.add(e4.toString()));
    }).next(() => n2.removeTargetData(e2, t2));
  }
  Zr() {
    this.ni = /* @__PURE__ */ new Set();
  }
  Xr(e2) {
    const t2 = this.persistence.getRemoteDocumentCache().newChangeBuffer();
    return PersistencePromise.forEach(this.ii, (n2) => {
      const r2 = DocumentKey.fromPath(n2);
      return this.si(e2, r2).next((e3) => {
        e3 || t2.removeEntry(r2, SnapshotVersion.min());
      });
    }).next(() => (this.ni = null, t2.apply(e2)));
  }
  updateLimboDocument(e2, t2) {
    return this.si(e2, t2).next((e3) => {
      e3 ? this.ii.delete(t2.toString()) : this.ii.add(t2.toString());
    });
  }
  Jr(e2) {
    return 0;
  }
  si(e2, t2) {
    return PersistencePromise.or([() => PersistencePromise.resolve(this.ti.containsKey(t2)), () => this.persistence.getTargetCache().containsKey(e2, t2), () => this.persistence.ei(e2, t2)]);
  }
}
class __PRIVATE_MemoryLruDelegate {
  static {
    __name(this, "__PRIVATE_MemoryLruDelegate");
  }
  constructor(e2, t2) {
    this.persistence = e2, this.oi = new ObjectMap((e3) => __PRIVATE_encodeResourcePath(e3.path), (e3, t3) => e3.isEqual(t3)), this.garbageCollector = __PRIVATE_newLruGarbageCollector(this, t2);
  }
  static ri(e2, t2) {
    return new __PRIVATE_MemoryLruDelegate(e2, t2);
  }
  // No-ops, present so memory persistence doesn't have to care which delegate
  // it has.
  Zr() {
  }
  Xr(e2) {
    return PersistencePromise.resolve();
  }
  forEachTarget(e2, t2) {
    return this.persistence.getTargetCache().forEachTarget(e2, t2);
  }
  nr(e2) {
    const t2 = this.sr(e2);
    return this.persistence.getTargetCache().getTargetCount(e2).next((e3) => t2.next((t3) => e3 + t3));
  }
  sr(e2) {
    let t2 = 0;
    return this.rr(e2, (e3) => {
      t2++;
    }).next(() => t2);
  }
  rr(e2, t2) {
    return PersistencePromise.forEach(this.oi, (n2, r2) => this.ar(e2, n2, r2).next((e3) => e3 ? PersistencePromise.resolve() : t2(r2)));
  }
  removeTargets(e2, t2, n2) {
    return this.persistence.getTargetCache().removeTargets(e2, t2, n2);
  }
  removeOrphanedDocuments(e2, t2) {
    let n2 = 0;
    const r2 = this.persistence.getRemoteDocumentCache(), i2 = r2.newChangeBuffer();
    return r2.qr(e2, (r3) => this.ar(e2, r3, t2).next((e3) => {
      e3 || (n2++, i2.removeEntry(r3, SnapshotVersion.min()));
    })).next(() => i2.apply(e2)).next(() => n2);
  }
  markPotentiallyOrphaned(e2, t2) {
    return this.oi.set(t2, e2.currentSequenceNumber), PersistencePromise.resolve();
  }
  removeTarget(e2, t2) {
    const n2 = t2.withSequenceNumber(e2.currentSequenceNumber);
    return this.persistence.getTargetCache().updateTargetData(e2, n2);
  }
  addReference(e2, t2, n2) {
    return this.oi.set(n2, e2.currentSequenceNumber), PersistencePromise.resolve();
  }
  removeReference(e2, t2, n2) {
    return this.oi.set(n2, e2.currentSequenceNumber), PersistencePromise.resolve();
  }
  updateLimboDocument(e2, t2) {
    return this.oi.set(t2, e2.currentSequenceNumber), PersistencePromise.resolve();
  }
  Jr(e2) {
    let t2 = e2.key.toString().length;
    return e2.isFoundDocument() && (t2 += __PRIVATE_estimateByteSize(e2.data.value)), t2;
  }
  ar(e2, t2, n2) {
    return PersistencePromise.or([() => this.persistence.ei(e2, t2), () => this.persistence.getTargetCache().containsKey(e2, t2), () => {
      const e3 = this.oi.get(t2);
      return PersistencePromise.resolve(void 0 !== e3 && e3 > n2);
    }]);
  }
  getCacheSize(e2) {
    return this.persistence.getRemoteDocumentCache().getSize(e2);
  }
}
/**
 * @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 __PRIVATE_SchemaConverter {
  static {
    __name(this, "__PRIVATE_SchemaConverter");
  }
  constructor(e2) {
    this.serializer = e2;
  }
  /**
   * Performs database creation and schema upgrades.
   *
   * Note that in production, this method is only ever used to upgrade the schema
   * to SCHEMA_VERSION. Different values of toVersion are only used for testing
   * and local feature development.
   */
  B(e2, t2, n2, r2) {
    const i2 = new __PRIVATE_SimpleDbTransaction("createOrUpgrade", t2);
    n2 < 1 && r2 >= 1 && (!(/* @__PURE__ */ __name(function __PRIVATE_createPrimaryClientStore(e3) {
      e3.createObjectStore(K);
    }, "__PRIVATE_createPrimaryClientStore"))(e2), (/* @__PURE__ */ __name(function __PRIVATE_createMutationQueue(e3) {
      e3.createObjectStore(G, {
        keyPath: z$1
      });
      const t3 = e3.createObjectStore(j, {
        keyPath: H,
        autoIncrement: true
      });
      t3.createIndex(J, Y, {
        unique: true
      }), e3.createObjectStore(X);
    }, "__PRIVATE_createMutationQueue"))(e2), __PRIVATE_createQueryCache(e2), (/* @__PURE__ */ __name(function __PRIVATE_createLegacyRemoteDocumentCache(e3) {
      e3.createObjectStore(U);
    }, "__PRIVATE_createLegacyRemoteDocumentCache"))(e2));
    let s2 = PersistencePromise.resolve();
    return n2 < 3 && r2 >= 3 && // Brand new clients don't need to drop and recreate--only clients that
    // potentially have corrupt data.
    (0 !== n2 && (!(/* @__PURE__ */ __name(function __PRIVATE_dropQueryCache(e3) {
      e3.deleteObjectStore(le), e3.deleteObjectStore(ae), e3.deleteObjectStore(Ee);
    }, "__PRIVATE_dropQueryCache"))(e2), __PRIVATE_createQueryCache(e2)), s2 = s2.next(() => (
      /**
      * Creates the target global singleton row.
      *
      * @param txn - The version upgrade transaction for indexeddb
      */
      (/* @__PURE__ */ __name(function __PRIVATE_writeEmptyTargetGlobalEntry(e3) {
        const t3 = e3.store(Ee), n3 = {
          highestTargetId: 0,
          highestListenSequenceNumber: 0,
          lastRemoteSnapshotVersion: SnapshotVersion.min().toTimestamp(),
          targetCount: 0
        };
        return t3.put(Ie, n3);
      }, "__PRIVATE_writeEmptyTargetGlobalEntry"))(i2)
    ))), n2 < 4 && r2 >= 4 && (0 !== n2 && // Schema version 3 uses auto-generated keys to generate globally unique
    // mutation batch IDs (this was previously ensured internally by the
    // client). To migrate to the new schema, we have to read all mutations
    // and write them back out. We preserve the existing batch IDs to guarantee
    // consistency with other object stores. Any further mutation batch IDs will
    // be auto-generated.
    (s2 = s2.next(() => (/* @__PURE__ */ __name(function __PRIVATE_upgradeMutationBatchSchemaAndMigrateData(e3, t3) {
      const n3 = t3.store(j);
      return n3.G().next((n4) => {
        e3.deleteObjectStore(j);
        e3.createObjectStore(j, {
          keyPath: H,
          autoIncrement: true
        }).createIndex(J, Y, {
          unique: true
        });
        const r3 = t3.store(j), i3 = n4.map((e4) => r3.put(e4));
        return PersistencePromise.waitFor(i3);
      });
    }, "__PRIVATE_upgradeMutationBatchSchemaAndMigrateData"))(e2, i2))), s2 = s2.next(() => {
      !(/* @__PURE__ */ __name(function __PRIVATE_createClientMetadataStore(e3) {
        e3.createObjectStore(Re, {
          keyPath: Ve
        });
      }, "__PRIVATE_createClientMetadataStore"))(e2);
    })), n2 < 5 && r2 >= 5 && (s2 = s2.next(() => this._i(i2))), n2 < 6 && r2 >= 6 && (s2 = s2.next(() => ((/* @__PURE__ */ __name(function __PRIVATE_createDocumentGlobalStore(e3) {
      e3.createObjectStore(oe);
    }, "__PRIVATE_createDocumentGlobalStore"))(e2), this.ai(i2)))), n2 < 7 && r2 >= 7 && (s2 = s2.next(() => this.ui(i2))), n2 < 8 && r2 >= 8 && (s2 = s2.next(() => this.ci(e2, i2))), n2 < 9 && r2 >= 9 && (s2 = s2.next(() => {
      !(/* @__PURE__ */ __name(function __PRIVATE_dropRemoteDocumentChangesStore(e3) {
        e3.objectStoreNames.contains("remoteDocumentChanges") && e3.deleteObjectStore("remoteDocumentChanges");
      }, "__PRIVATE_dropRemoteDocumentChangesStore"))(e2);
    })), n2 < 10 && r2 >= 10 && (s2 = s2.next(() => this.li(i2))), n2 < 11 && r2 >= 11 && (s2 = s2.next(() => {
      !(/* @__PURE__ */ __name(function __PRIVATE_createBundlesStore(e3) {
        e3.createObjectStore(me, {
          keyPath: fe
        });
      }, "__PRIVATE_createBundlesStore"))(e2), (/* @__PURE__ */ __name(function __PRIVATE_createNamedQueriesStore(e3) {
        e3.createObjectStore(ge, {
          keyPath: pe
        });
      }, "__PRIVATE_createNamedQueriesStore"))(e2);
    })), n2 < 12 && r2 >= 12 && (s2 = s2.next(() => {
      !(/* @__PURE__ */ __name(function __PRIVATE_createDocumentOverlayStore(e3) {
        const t3 = e3.createObjectStore(Be, {
          keyPath: Le
        });
        t3.createIndex(ke, qe, {
          unique: false
        }), t3.createIndex(Qe, $e, {
          unique: false
        });
      }, "__PRIVATE_createDocumentOverlayStore"))(e2);
    })), n2 < 13 && r2 >= 13 && (s2 = s2.next(() => (/* @__PURE__ */ __name(function __PRIVATE_createRemoteDocumentCache(e3) {
      const t3 = e3.createObjectStore(ee, {
        keyPath: te$1
      });
      t3.createIndex(ne, re), t3.createIndex(ie$2, se);
    }, "__PRIVATE_createRemoteDocumentCache"))(e2)).next(() => this.hi(e2, i2)).next(() => e2.deleteObjectStore(U))), n2 < 14 && r2 >= 14 && (s2 = s2.next(() => this.Pi(e2, i2))), n2 < 15 && r2 >= 15 && (s2 = s2.next(() => (/* @__PURE__ */ __name(function __PRIVATE_createFieldIndex(e3) {
      const t3 = e3.createObjectStore(ye, {
        keyPath: we,
        autoIncrement: true
      });
      t3.createIndex(Se, be, {
        unique: false
      });
      const n3 = e3.createObjectStore(De, {
        keyPath: ve
      });
      n3.createIndex(Ce, Fe, {
        unique: false
      });
      const r3 = e3.createObjectStore(Me, {
        keyPath: xe
      });
      r3.createIndex(Oe, Ne, {
        unique: false
      });
    }, "__PRIVATE_createFieldIndex"))(e2))), n2 < 16 && r2 >= 16 && // Clear the object stores to remove possibly corrupted index entries
    (s2 = s2.next(() => {
      t2.objectStore(De).clear();
    }).next(() => {
      t2.objectStore(Me).clear();
    })), n2 < 17 && r2 >= 17 && (s2 = s2.next(() => {
      !(/* @__PURE__ */ __name(function __PRIVATE_createGlobalsStore(e3) {
        e3.createObjectStore(Ue, {
          keyPath: Ke
        });
      }, "__PRIVATE_createGlobalsStore"))(e2);
    })), s2;
  }
  ai(e2) {
    let t2 = 0;
    return e2.store(U).Z((e3, n2) => {
      t2 += __PRIVATE_dbDocumentSize(n2);
    }).next(() => {
      const n2 = {
        byteSize: t2
      };
      return e2.store(oe).put(_e, n2);
    });
  }
  _i(e2) {
    const t2 = e2.store(G), n2 = e2.store(j);
    return t2.G().next((t3) => PersistencePromise.forEach(t3, (t4) => {
      const r2 = IDBKeyRange.bound([t4.userId, Q], [t4.userId, t4.lastAcknowledgedBatchId]);
      return n2.G(J, r2).next((n3) => PersistencePromise.forEach(n3, (n4) => {
        __PRIVATE_hardAssert(n4.userId === t4.userId);
        const r3 = __PRIVATE_fromDbMutationBatch(this.serializer, n4);
        return removeMutationBatch(e2, t4.userId, r3).next(() => {
        });
      }));
    }));
  }
  /**
   * Ensures that every document in the remote document cache has a corresponding sentinel row
   * with a sequence number. Missing rows are given the most recently used sequence number.
   */
  ui(e2) {
    const t2 = e2.store(le), n2 = e2.store(U);
    return e2.store(Ee).get(Ie).next((e3) => {
      const r2 = [];
      return n2.Z((n3, i2) => {
        const s2 = new ResourcePath(n3), o2 = (/* @__PURE__ */ __name(function __PRIVATE_sentinelKey(e4) {
          return [0, __PRIVATE_encodeResourcePath(e4)];
        }, "__PRIVATE_sentinelKey"))(s2);
        r2.push(t2.get(o2).next((n4) => n4 ? PersistencePromise.resolve() : ((n5) => t2.put({
          targetId: 0,
          path: __PRIVATE_encodeResourcePath(n5),
          sequenceNumber: e3.highestListenSequenceNumber
        }))(s2)));
      }).next(() => PersistencePromise.waitFor(r2));
    });
  }
  ci(e2, t2) {
    e2.createObjectStore(de, {
      keyPath: Ae
    });
    const n2 = t2.store(de), r2 = new __PRIVATE_MemoryCollectionParentIndex(), addEntry = /* @__PURE__ */ __name((e3) => {
      if (r2.add(e3)) {
        const t3 = e3.lastSegment(), r3 = e3.popLast();
        return n2.put({
          collectionId: t3,
          parent: __PRIVATE_encodeResourcePath(r3)
        });
      }
    }, "addEntry");
    return t2.store(U).Z({
      Y: true
    }, (e3, t3) => {
      const n3 = new ResourcePath(e3);
      return addEntry(n3.popLast());
    }).next(() => t2.store(X).Z({
      Y: true
    }, ([e3, t3, n3], r3) => {
      const i2 = __PRIVATE_decodeResourcePath(t3);
      return addEntry(i2.popLast());
    }));
  }
  li(e2) {
    const t2 = e2.store(ae);
    return t2.Z((e3, n2) => {
      const r2 = __PRIVATE_fromDbTarget(n2), i2 = __PRIVATE_toDbTarget(this.serializer, r2);
      return t2.put(i2);
    });
  }
  hi(e2, t2) {
    const n2 = t2.store(U), r2 = [];
    return n2.Z((e3, n3) => {
      const i2 = t2.store(ee), s2 = (/* @__PURE__ */ __name(function __PRIVATE_extractKey(e4) {
        return e4.document ? new DocumentKey(ResourcePath.fromString(e4.document.name).popFirst(5)) : e4.noDocument ? DocumentKey.fromSegments(e4.noDocument.path) : e4.unknownDocument ? DocumentKey.fromSegments(e4.unknownDocument.path) : fail();
      }, "__PRIVATE_extractKey"))(n3).path.toArray(), o2 = {
        prefixPath: s2.slice(0, s2.length - 2),
        collectionGroup: s2[s2.length - 2],
        documentId: s2[s2.length - 1],
        readTime: n3.readTime || [0, 0],
        unknownDocument: n3.unknownDocument,
        noDocument: n3.noDocument,
        document: n3.document,
        hasCommittedMutations: !!n3.hasCommittedMutations
      };
      r2.push(i2.put(o2));
    }).next(() => PersistencePromise.waitFor(r2));
  }
  Pi(e2, t2) {
    const n2 = t2.store(j), r2 = __PRIVATE_newIndexedDbRemoteDocumentCache(this.serializer), i2 = new __PRIVATE_MemoryPersistence(__PRIVATE_MemoryEagerDelegate.ri, this.serializer.Tt);
    return n2.G().next((e3) => {
      const n3 = /* @__PURE__ */ new Map();
      return e3.forEach((e4) => {
        var t3;
        let r3 = null !== (t3 = n3.get(e4.userId)) && void 0 !== t3 ? t3 : __PRIVATE_documentKeySet();
        __PRIVATE_fromDbMutationBatch(this.serializer, e4).keys().forEach((e5) => r3 = r3.add(e5)), n3.set(e4.userId, r3);
      }), PersistencePromise.forEach(n3, (e4, n4) => {
        const s2 = new User(n4), o2 = __PRIVATE_IndexedDbDocumentOverlayCache.It(this.serializer, s2), _2 = i2.getIndexManager(s2), a2 = __PRIVATE_IndexedDbMutationQueue.It(s2, this.serializer, _2, i2.referenceDelegate);
        return new LocalDocumentsView(r2, a2, o2, _2).recalculateAndSaveOverlaysForDocumentKeys(new __PRIVATE_IndexedDbTransaction(t2, __PRIVATE_ListenSequence.ae), e4).next();
      });
    });
  }
}
function __PRIVATE_createQueryCache(e2) {
  e2.createObjectStore(le, {
    keyPath: he
  }).createIndex(Pe, Te, {
    unique: true
  });
  e2.createObjectStore(ae, {
    keyPath: "targetId"
  }).createIndex(ue, ce, {
    unique: true
  }), e2.createObjectStore(Ee);
}
__name(__PRIVATE_createQueryCache, "__PRIVATE_createQueryCache");
const vt = "IndexedDbPersistence", Ct = 18e5, Ft = 5e3, Mt = "Failed to obtain exclusive access to the persistence layer. To allow shared access, multi-tab synchronization has to be enabled in all tabs. If you are using `experimentalForceOwningTab:true`, make sure that only one tab has persistence enabled at any given time.", xt = "main";
class __PRIVATE_IndexedDbPersistence {
  static {
    __name(this, "__PRIVATE_IndexedDbPersistence");
  }
  constructor(e2, t2, n2, r2, i2, s2, o2, _2, a2, u2, c2 = 17) {
    if (this.allowTabSynchronization = e2, this.persistenceKey = t2, this.clientId = n2, this.Ti = i2, this.window = s2, this.document = o2, this.Ii = a2, this.Ei = u2, this.di = c2, this.Gr = null, this.zr = false, this.isPrimary = false, this.networkEnabled = true, /** Our window.unload handler, if registered. */
    this.Ai = null, this.inForeground = false, /** Our 'visibilitychange' listener if registered. */
    this.Ri = null, /** The client metadata refresh task. */
    this.Vi = null, /** The last time we garbage collected the client metadata object store. */
    this.mi = Number.NEGATIVE_INFINITY, /** A listener to notify on primary state changes. */
    this.fi = (e3) => Promise.resolve(), !__PRIVATE_IndexedDbPersistence.D()) throw new FirestoreError(C.UNIMPLEMENTED, "This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");
    this.referenceDelegate = new __PRIVATE_IndexedDbLruDelegateImpl(this, r2), this.gi = t2 + xt, this.serializer = new __PRIVATE_LocalSerializer(_2), this.pi = new __PRIVATE_SimpleDb(this.gi, this.di, new __PRIVATE_SchemaConverter(this.serializer)), this.jr = new __PRIVATE_IndexedDbGlobalsCache(), this.Hr = new __PRIVATE_IndexedDbTargetCache(this.referenceDelegate, this.serializer), this.remoteDocumentCache = __PRIVATE_newIndexedDbRemoteDocumentCache(this.serializer), this.Yr = new __PRIVATE_IndexedDbBundleCache(), this.window && this.window.localStorage ? this.yi = this.window.localStorage : (this.yi = null, false === u2 && __PRIVATE_logError(vt, "LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page."));
  }
  /**
   * Attempt to start IndexedDb persistence.
   *
   * @returns Whether persistence was enabled.
   */
  start() {
    return this.wi().then(() => {
      if (!this.isPrimary && !this.allowTabSynchronization)
        throw new FirestoreError(C.FAILED_PRECONDITION, Mt);
      return this.Si(), this.bi(), this.Di(), this.runTransaction("getHighestListenSequenceNumber", "readonly", (e2) => this.Hr.getHighestSequenceNumber(e2));
    }).then((e2) => {
      this.Gr = new __PRIVATE_ListenSequence(e2, this.Ii);
    }).then(() => {
      this.zr = true;
    }).catch((e2) => (this.pi && this.pi.close(), Promise.reject(e2)));
  }
  /**
   * Registers a listener that gets called when the primary state of the
   * instance changes. Upon registering, this listener is invoked immediately
   * with the current primary state.
   *
   * PORTING NOTE: This is only used for Web multi-tab.
   */
  Ci(e2) {
    return this.fi = async (t2) => {
      if (this.started) return e2(t2);
    }, e2(this.isPrimary);
  }
  /**
   * Registers a listener that gets called when the database receives a
   * version change event indicating that it has deleted.
   *
   * PORTING NOTE: This is only used for Web multi-tab.
   */
  setDatabaseDeletedListener(e2) {
    this.pi.k(async (t2) => {
      null === t2.newVersion && await e2();
    });
  }
  /**
   * Adjusts the current network state in the client's metadata, potentially
   * affecting the primary lease.
   *
   * PORTING NOTE: This is only used for Web multi-tab.
   */
  setNetworkEnabled(e2) {
    this.networkEnabled !== e2 && (this.networkEnabled = e2, // Schedule a primary lease refresh for immediate execution. The eventual
    // lease update will be propagated via `primaryStateListener`.
    this.Ti.enqueueAndForget(async () => {
      this.started && await this.wi();
    }));
  }
  /**
   * Updates the client metadata in IndexedDb and attempts to either obtain or
   * extend the primary lease for the local client. Asynchronously notifies the
   * primary state listener if the client either newly obtained or released its
   * primary lease.
   */
  wi() {
    return this.runTransaction("updateClientMetadataAndTryBecomePrimary", "readwrite", (e2) => __PRIVATE_clientMetadataStore(e2).put({
      clientId: this.clientId,
      updateTimeMs: Date.now(),
      networkEnabled: this.networkEnabled,
      inForeground: this.inForeground
    }).next(() => {
      if (this.isPrimary) return this.Fi(e2).next((e3) => {
        e3 || (this.isPrimary = false, this.Ti.enqueueRetryable(() => this.fi(false)));
      });
    }).next(() => this.Mi(e2)).next((t2) => this.isPrimary && !t2 ? this.xi(e2).next(() => false) : !!t2 && this.Oi(e2).next(() => true))).catch((e2) => {
      if (__PRIVATE_isIndexedDbTransactionError(e2))
        return __PRIVATE_logDebug(vt, "Failed to extend owner lease: ", e2), this.isPrimary;
      if (!this.allowTabSynchronization) throw e2;
      return __PRIVATE_logDebug(vt, "Releasing owner lease after error during lease refresh", e2), /* isPrimary= */
      false;
    }).then((e2) => {
      this.isPrimary !== e2 && this.Ti.enqueueRetryable(() => this.fi(e2)), this.isPrimary = e2;
    });
  }
  Fi(e2) {
    return __PRIVATE_primaryClientStore(e2).get(W).next((e3) => PersistencePromise.resolve(this.Ni(e3)));
  }
  Bi(e2) {
    return __PRIVATE_clientMetadataStore(e2).delete(this.clientId);
  }
  /**
   * If the garbage collection threshold has passed, prunes the
   * RemoteDocumentChanges and the ClientMetadata store based on the last update
   * time of all clients.
   */
  async Li() {
    if (this.isPrimary && !this.ki(this.mi, Ct)) {
      this.mi = Date.now();
      const e2 = await this.runTransaction("maybeGarbageCollectMultiClientState", "readwrite-primary", (e3) => {
        const t2 = __PRIVATE_getStore(e3, Re);
        return t2.G().next((e4) => {
          const n2 = this.qi(e4, Ct), r2 = e4.filter((e5) => -1 === n2.indexOf(e5));
          return PersistencePromise.forEach(r2, (e5) => t2.delete(e5.clientId)).next(() => r2);
        });
      }).catch(() => []);
      if (this.yi) for (const t2 of e2) this.yi.removeItem(this.Qi(t2.clientId));
    }
  }
  /**
   * Schedules a recurring timer to update the client metadata and to either
   * extend or acquire the primary lease if the client is eligible.
   */
  Di() {
    this.Vi = this.Ti.enqueueAfterDelay("client_metadata_refresh", 4e3, () => this.wi().then(() => this.Li()).then(() => this.Di()));
  }
  /** Checks whether `client` is the local client. */
  Ni(e2) {
    return !!e2 && e2.ownerId === this.clientId;
  }
  /**
   * Evaluate the state of all active clients and determine whether the local
   * client is or can act as the holder of the primary lease. Returns whether
   * the client is eligible for the lease, but does not actually acquire it.
   * May return 'false' even if there is no active leaseholder and another
   * (foreground) client should become leaseholder instead.
   */
  Mi(e2) {
    if (this.Ei) return PersistencePromise.resolve(true);
    return __PRIVATE_primaryClientStore(e2).get(W).next((t2) => {
      if (null !== t2 && this.ki(t2.leaseTimestampMs, Ft) && !this.$i(t2.ownerId)) {
        if (this.Ni(t2) && this.networkEnabled) return true;
        if (!this.Ni(t2)) {
          if (!t2.allowTabSynchronization)
            throw new FirestoreError(C.FAILED_PRECONDITION, Mt);
          return false;
        }
      }
      return !(!this.networkEnabled || !this.inForeground) || __PRIVATE_clientMetadataStore(e2).G().next((e3) => void 0 === this.qi(e3, Ft).find((e4) => {
        if (this.clientId !== e4.clientId) {
          const t3 = !this.networkEnabled && e4.networkEnabled, n2 = !this.inForeground && e4.inForeground, r2 = this.networkEnabled === e4.networkEnabled;
          if (t3 || n2 && r2) return true;
        }
        return false;
      }));
    }).next((e3) => (this.isPrimary !== e3 && __PRIVATE_logDebug(vt, `Client ${e3 ? "is" : "is not"} eligible for a primary lease.`), e3));
  }
  async shutdown() {
    this.zr = false, this.Ui(), this.Vi && (this.Vi.cancel(), this.Vi = null), this.Ki(), this.Wi(), // Use `SimpleDb.runTransaction` directly to avoid failing if another tab
    // has obtained the primary lease.
    await this.pi.runTransaction("shutdown", "readwrite", [K, Re], (e2) => {
      const t2 = new __PRIVATE_IndexedDbTransaction(e2, __PRIVATE_ListenSequence.ae);
      return this.xi(t2).next(() => this.Bi(t2));
    }), this.pi.close(), // Remove the entry marking the client as zombied from LocalStorage since
    // we successfully deleted its metadata from IndexedDb.
    this.Gi();
  }
  /**
   * Returns clients that are not zombied and have an updateTime within the
   * provided threshold.
   */
  qi(e2, t2) {
    return e2.filter((e3) => this.ki(e3.updateTimeMs, t2) && !this.$i(e3.clientId));
  }
  /**
   * Returns the IDs of the clients that are currently active. If multi-tab
   * is not supported, returns an array that only contains the local client's
   * ID.
   *
   * PORTING NOTE: This is only used for Web multi-tab.
   */
  zi() {
    return this.runTransaction("getActiveClients", "readonly", (e2) => __PRIVATE_clientMetadataStore(e2).G().next((e3) => this.qi(e3, Ct).map((e4) => e4.clientId)));
  }
  get started() {
    return this.zr;
  }
  getGlobalsCache() {
    return this.jr;
  }
  getMutationQueue(e2, t2) {
    return __PRIVATE_IndexedDbMutationQueue.It(e2, this.serializer, t2, this.referenceDelegate);
  }
  getTargetCache() {
    return this.Hr;
  }
  getRemoteDocumentCache() {
    return this.remoteDocumentCache;
  }
  getIndexManager(e2) {
    return new __PRIVATE_IndexedDbIndexManager(e2, this.serializer.Tt.databaseId);
  }
  getDocumentOverlayCache(e2) {
    return __PRIVATE_IndexedDbDocumentOverlayCache.It(this.serializer, e2);
  }
  getBundleCache() {
    return this.Yr;
  }
  runTransaction(e2, t2, n2) {
    __PRIVATE_logDebug(vt, "Starting transaction:", e2);
    const r2 = "readonly" === t2 ? "readonly" : "readwrite", i2 = (
      /** Returns the object stores for the provided schema. */
      (/* @__PURE__ */ __name(function __PRIVATE_getObjectStores(e3) {
        return 17 === e3 ? Ye : 16 === e3 ? Je : 15 === e3 ? He : 14 === e3 ? je : 13 === e3 ? ze : 12 === e3 ? Ge : 11 === e3 ? We : void fail();
      }, "__PRIVATE_getObjectStores"))(this.di)
    );
    let s2;
    return this.pi.runTransaction(e2, r2, i2, (r3) => (s2 = new __PRIVATE_IndexedDbTransaction(r3, this.Gr ? this.Gr.next() : __PRIVATE_ListenSequence.ae), "readwrite-primary" === t2 ? this.Fi(s2).next((e3) => !!e3 || this.Mi(s2)).next((t3) => {
      if (!t3) throw __PRIVATE_logError(`Failed to obtain primary lease for action '${e2}'.`), this.isPrimary = false, this.Ti.enqueueRetryable(() => this.fi(false)), new FirestoreError(C.FAILED_PRECONDITION, B);
      return n2(s2);
    }).next((e3) => this.Oi(s2).next(() => e3)) : this.ji(s2).next(() => n2(s2)))).then((e3) => (s2.raiseOnCommittedEvent(), e3));
  }
  /**
   * Verifies that the current tab is the primary leaseholder or alternatively
   * that the leaseholder has opted into multi-tab synchronization.
   */
  // TODO(b/114226234): Remove this check when `synchronizeTabs` can no longer
  // be turned off.
  ji(e2) {
    return __PRIVATE_primaryClientStore(e2).get(W).next((e3) => {
      if (null !== e3 && this.ki(e3.leaseTimestampMs, Ft) && !this.$i(e3.ownerId) && !this.Ni(e3) && !(this.Ei || this.allowTabSynchronization && e3.allowTabSynchronization)) throw new FirestoreError(C.FAILED_PRECONDITION, Mt);
    });
  }
  /**
   * Obtains or extends the new primary lease for the local client. This
   * method does not verify that the client is eligible for this lease.
   */
  Oi(e2) {
    const t2 = {
      ownerId: this.clientId,
      allowTabSynchronization: this.allowTabSynchronization,
      leaseTimestampMs: Date.now()
    };
    return __PRIVATE_primaryClientStore(e2).put(W, t2);
  }
  static D() {
    return __PRIVATE_SimpleDb.D();
  }
  /** Checks the primary lease and removes it if we are the current primary. */
  xi(e2) {
    const t2 = __PRIVATE_primaryClientStore(e2);
    return t2.get(W).next((e3) => this.Ni(e3) ? (__PRIVATE_logDebug(vt, "Releasing primary lease."), t2.delete(W)) : PersistencePromise.resolve());
  }
  /** Verifies that `updateTimeMs` is within `maxAgeMs`. */
  ki(e2, t2) {
    const n2 = Date.now();
    return !(e2 < n2 - t2) && (!(e2 > n2) || (__PRIVATE_logError(`Detected an update time that is in the future: ${e2} > ${n2}`), false));
  }
  Si() {
    null !== this.document && "function" == typeof this.document.addEventListener && (this.Ri = () => {
      this.Ti.enqueueAndForget(() => (this.inForeground = "visible" === this.document.visibilityState, this.wi()));
    }, this.document.addEventListener("visibilitychange", this.Ri), this.inForeground = "visible" === this.document.visibilityState);
  }
  Ki() {
    this.Ri && (this.document.removeEventListener("visibilitychange", this.Ri), this.Ri = null);
  }
  /**
   * Attaches a window.unload handler that will synchronously write our
   * clientId to a "zombie client id" location in LocalStorage. This can be used
   * by tabs trying to acquire the primary lease to determine that the lease
   * is no longer valid even if the timestamp is recent. This is particularly
   * important for the refresh case (so the tab correctly re-acquires the
   * primary lease). LocalStorage is used for this rather than IndexedDb because
   * it is a synchronous API and so can be used reliably from  an unload
   * handler.
   */
  bi() {
    var e2;
    "function" == typeof (null === (e2 = this.window) || void 0 === e2 ? void 0 : e2.addEventListener) && (this.Ai = () => {
      this.Ui();
      const e3 = /(?:Version|Mobile)\/1[456]/;
      isSafari$1() && (navigator.appVersion.match(e3) || navigator.userAgent.match(e3)) && // On Safari 14, 15, and 16, we do not run any cleanup actions as it might
      // trigger a bug that prevents Safari from re-opening IndexedDB during
      // the next page load.
      // See https://bugs.webkit.org/show_bug.cgi?id=226547
      this.Ti.enterRestrictedMode(
        /* purgeExistingTasks= */
        true
      ), this.Ti.enqueueAndForget(() => this.shutdown());
    }, this.window.addEventListener("pagehide", this.Ai));
  }
  Wi() {
    this.Ai && (this.window.removeEventListener("pagehide", this.Ai), this.Ai = null);
  }
  /**
   * Returns whether a client is "zombied" based on its LocalStorage entry.
   * Clients become zombied when their tab closes without running all of the
   * cleanup logic in `shutdown()`.
   */
  $i(e2) {
    var t2;
    try {
      const n2 = null !== (null === (t2 = this.yi) || void 0 === t2 ? void 0 : t2.getItem(this.Qi(e2)));
      return __PRIVATE_logDebug(vt, `Client '${e2}' ${n2 ? "is" : "is not"} zombied in LocalStorage`), n2;
    } catch (e3) {
      return __PRIVATE_logError(vt, "Failed to get zombied client id.", e3), false;
    }
  }
  /**
   * Record client as zombied (a client that had its tab closed). Zombied
   * clients are ignored during primary tab selection.
   */
  Ui() {
    if (this.yi) try {
      this.yi.setItem(this.Qi(this.clientId), String(Date.now()));
    } catch (e2) {
      __PRIVATE_logError("Failed to set zombie client id.", e2);
    }
  }
  /** Removes the zombied client entry if it exists. */
  Gi() {
    if (this.yi) try {
      this.yi.removeItem(this.Qi(this.clientId));
    } catch (e2) {
    }
  }
  Qi(e2) {
    return `firestore_zombie_${this.persistenceKey}_${e2}`;
  }
}
function __PRIVATE_primaryClientStore(e2) {
  return __PRIVATE_getStore(e2, K);
}
__name(__PRIVATE_primaryClientStore, "__PRIVATE_primaryClientStore");
function __PRIVATE_clientMetadataStore(e2) {
  return __PRIVATE_getStore(e2, Re);
}
__name(__PRIVATE_clientMetadataStore, "__PRIVATE_clientMetadataStore");
function __PRIVATE_indexedDbStoragePrefix(e2, t2) {
  let n2 = e2.projectId;
  return e2.isDefaultDatabase || (n2 += "." + e2.database), "firestore/" + t2 + "/" + n2 + "/";
}
__name(__PRIVATE_indexedDbStoragePrefix, "__PRIVATE_indexedDbStoragePrefix");
/**
 * @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 __PRIVATE_LocalViewChanges {
  static {
    __name(this, "__PRIVATE_LocalViewChanges");
  }
  constructor(e2, t2, n2, r2) {
    this.targetId = e2, this.fromCache = t2, this.Hi = n2, this.Ji = r2;
  }
  static Yi(e2, t2) {
    let n2 = __PRIVATE_documentKeySet(), r2 = __PRIVATE_documentKeySet();
    for (const e3 of t2.docChanges) switch (e3.type) {
      case 0:
        n2 = n2.add(e3.doc.key);
        break;
      case 1:
        r2 = r2.add(e3.doc.key);
    }
    return new __PRIVATE_LocalViewChanges(e2, t2.fromCache, n2, r2);
  }
}
/**
 * @license
 * Copyright 2023 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 QueryContext {
  static {
    __name(this, "QueryContext");
  }
  constructor() {
    this._documentReadCount = 0;
  }
  get documentReadCount() {
    return this._documentReadCount;
  }
  incrementDocumentReadCount(e2) {
    this._documentReadCount += e2;
  }
}
/**
 * @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 __PRIVATE_QueryEngine {
  static {
    __name(this, "__PRIVATE_QueryEngine");
  }
  constructor() {
    this.Zi = false, this.Xi = false, /**
     * SDK only decides whether it should create index when collection size is
     * larger than this.
     */
    this.es = 100, this.ts = /**
    * This cost represents the evaluation result of
    * (([index, docKey] + [docKey, docContent]) per document in the result set)
    * / ([docKey, docContent] per documents in full collection scan) coming from
    * experiment [enter PR experiment URL here].
    */
    (/* @__PURE__ */ __name(function __PRIVATE_getDefaultRelativeIndexReadCostPerDocument() {
      return isSafari$1() ? 8 : __PRIVATE_getAndroidVersion(getUA()) > 0 ? 6 : 4;
    }, "__PRIVATE_getDefaultRelativeIndexReadCostPerDocument"))();
  }
  /** Sets the document view to query against. */
  initialize(e2, t2) {
    this.ns = e2, this.indexManager = t2, this.Zi = true;
  }
  /** Returns all local documents matching the specified query. */
  getDocumentsMatchingQuery(e2, t2, n2, r2) {
    const i2 = {
      result: null
    };
    return this.rs(e2, t2).next((e3) => {
      i2.result = e3;
    }).next(() => {
      if (!i2.result) return this.ss(e2, t2, r2, n2).next((e3) => {
        i2.result = e3;
      });
    }).next(() => {
      if (i2.result) return;
      const n3 = new QueryContext();
      return this._s(e2, t2, n3).next((r3) => {
        if (i2.result = r3, this.Xi) return this.us(e2, t2, n3, r3.size);
      });
    }).next(() => i2.result);
  }
  us(e2, t2, n2, r2) {
    return n2.documentReadCount < this.es ? (__PRIVATE_getLogLevel() <= LogLevel.DEBUG && __PRIVATE_logDebug("QueryEngine", "SDK will not create cache indexes for query:", __PRIVATE_stringifyQuery(t2), "since it only creates cache indexes for collection contains", "more than or equal to", this.es, "documents"), PersistencePromise.resolve()) : (__PRIVATE_getLogLevel() <= LogLevel.DEBUG && __PRIVATE_logDebug("QueryEngine", "Query:", __PRIVATE_stringifyQuery(t2), "scans", n2.documentReadCount, "local documents and returns", r2, "documents as results."), n2.documentReadCount > this.ts * r2 ? (__PRIVATE_getLogLevel() <= LogLevel.DEBUG && __PRIVATE_logDebug("QueryEngine", "The SDK decides to create cache indexes for query:", __PRIVATE_stringifyQuery(t2), "as using cache indexes may help improve performance."), this.indexManager.createTargetIndexes(e2, __PRIVATE_queryToTarget(t2))) : PersistencePromise.resolve());
  }
  /**
   * Performs an indexed query that evaluates the query based on a collection's
   * persisted index values. Returns `null` if an index is not available.
   */
  rs(e2, t2) {
    if (__PRIVATE_queryMatchesAllDocuments(t2))
      return PersistencePromise.resolve(null);
    let n2 = __PRIVATE_queryToTarget(t2);
    return this.indexManager.getIndexType(e2, n2).next((r2) => 0 === r2 ? null : (null !== t2.limit && 1 === r2 && // We cannot apply a limit for targets that are served using a partial
    // index. If a partial index will be used to serve the target, the
    // query may return a superset of documents that match the target
    // (e.g. if the index doesn't include all the target's filters), or
    // may return the correct set of documents in the wrong order (e.g. if
    // the index doesn't include a segment for one of the orderBys).
    // Therefore, a limit should not be applied in such cases.
    (t2 = __PRIVATE_queryWithLimit(
      t2,
      null,
      "F"
      /* LimitType.First */
    ), n2 = __PRIVATE_queryToTarget(t2)), this.indexManager.getDocumentsMatchingTarget(e2, n2).next((r3) => {
      const i2 = __PRIVATE_documentKeySet(...r3);
      return this.ns.getDocuments(e2, i2).next((r4) => this.indexManager.getMinOffset(e2, n2).next((n3) => {
        const s2 = this.cs(t2, r4);
        return this.ls(t2, s2, i2, n3.readTime) ? this.rs(e2, __PRIVATE_queryWithLimit(
          t2,
          null,
          "F"
          /* LimitType.First */
        )) : this.hs(e2, s2, t2, n3);
      }));
    })));
  }
  /**
   * Performs a query based on the target's persisted query mapping. Returns
   * `null` if the mapping is not available or cannot be used.
   */
  ss(e2, t2, n2, r2) {
    return __PRIVATE_queryMatchesAllDocuments(t2) || r2.isEqual(SnapshotVersion.min()) ? PersistencePromise.resolve(null) : this.ns.getDocuments(e2, n2).next((i2) => {
      const s2 = this.cs(t2, i2);
      return this.ls(t2, s2, n2, r2) ? PersistencePromise.resolve(null) : (__PRIVATE_getLogLevel() <= LogLevel.DEBUG && __PRIVATE_logDebug("QueryEngine", "Re-using previous result from %s to execute query: %s", r2.toString(), __PRIVATE_stringifyQuery(t2)), this.hs(e2, s2, t2, __PRIVATE_newIndexOffsetSuccessorFromReadTime(r2, N)).next((e3) => e3));
    });
  }
  /** Applies the query filter and sorting to the provided documents.  */
  cs(e2, t2) {
    let n2 = new SortedSet(__PRIVATE_newQueryComparator(e2));
    return t2.forEach((t3, r2) => {
      __PRIVATE_queryMatches(e2, r2) && (n2 = n2.add(r2));
    }), n2;
  }
  /**
   * Determines if a limit query needs to be refilled from cache, making it
   * ineligible for index-free execution.
   *
   * @param query - The query.
   * @param sortedPreviousResults - The documents that matched the query when it
   * was last synchronized, sorted by the query's comparator.
   * @param remoteKeys - The document keys that matched the query at the last
   * snapshot.
   * @param limboFreeSnapshotVersion - The version of the snapshot when the
   * query was last synchronized.
   */
  ls(e2, t2, n2, r2) {
    if (null === e2.limit)
      return false;
    if (n2.size !== t2.size)
      return true;
    const i2 = "F" === e2.limitType ? t2.last() : t2.first();
    return !!i2 && (i2.hasPendingWrites || i2.version.compareTo(r2) > 0);
  }
  _s(e2, t2, n2) {
    return __PRIVATE_getLogLevel() <= LogLevel.DEBUG && __PRIVATE_logDebug("QueryEngine", "Using full collection scan to execute query:", __PRIVATE_stringifyQuery(t2)), this.ns.getDocumentsMatchingQuery(e2, t2, IndexOffset.min(), n2);
  }
  /**
   * Combines the results from an indexed execution with the remaining documents
   * that have not yet been indexed.
   */
  hs(e2, t2, n2, r2) {
    return this.ns.getDocumentsMatchingQuery(e2, n2, r2).next((e3) => (
      // Merge with existing results
      (t2.forEach((t3) => {
        e3 = e3.insert(t3.key, t3);
      }), e3)
    ));
  }
}
/**
 * @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 Ot = "LocalStore", Nt = 3e8;
class __PRIVATE_LocalStoreImpl {
  static {
    __name(this, "__PRIVATE_LocalStoreImpl");
  }
  constructor(e2, t2, n2, r2) {
    this.persistence = e2, this.Ps = t2, this.serializer = r2, /**
     * Maps a targetID to data about its target.
     *
     * PORTING NOTE: We are using an immutable data structure on Web to make re-runs
     * of `applyRemoteEvent()` idempotent.
     */
    this.Ts = new SortedMap(__PRIVATE_primitiveComparator), /** Maps a target to its targetID. */
    // TODO(wuandy): Evaluate if TargetId can be part of Target.
    this.Is = new ObjectMap((e3) => __PRIVATE_canonifyTarget(e3), __PRIVATE_targetEquals), /**
     * A per collection group index of the last read time processed by
     * `getNewDocumentChanges()`.
     *
     * PORTING NOTE: This is only used for multi-tab synchronization.
     */
    this.Es = /* @__PURE__ */ new Map(), this.ds = e2.getRemoteDocumentCache(), this.Hr = e2.getTargetCache(), this.Yr = e2.getBundleCache(), this.As(n2);
  }
  As(e2) {
    this.documentOverlayCache = this.persistence.getDocumentOverlayCache(e2), this.indexManager = this.persistence.getIndexManager(e2), this.mutationQueue = this.persistence.getMutationQueue(e2, this.indexManager), this.localDocuments = new LocalDocumentsView(this.ds, this.mutationQueue, this.documentOverlayCache, this.indexManager), this.ds.setIndexManager(this.indexManager), this.Ps.initialize(this.localDocuments, this.indexManager);
  }
  collectGarbage(e2) {
    return this.persistence.runTransaction("Collect garbage", "readwrite-primary", (t2) => e2.collect(t2, this.Ts));
  }
}
function __PRIVATE_newLocalStore(e2, t2, n2, r2) {
  return new __PRIVATE_LocalStoreImpl(e2, t2, n2, r2);
}
__name(__PRIVATE_newLocalStore, "__PRIVATE_newLocalStore");
async function __PRIVATE_localStoreHandleUserChange(e2, t2) {
  const n2 = __PRIVATE_debugCast(e2);
  return await n2.persistence.runTransaction("Handle user change", "readonly", (e3) => {
    let r2;
    return n2.mutationQueue.getAllMutationBatches(e3).next((i2) => (r2 = i2, n2.As(t2), n2.mutationQueue.getAllMutationBatches(e3))).next((t3) => {
      const i2 = [], s2 = [];
      let o2 = __PRIVATE_documentKeySet();
      for (const e4 of r2) {
        i2.push(e4.batchId);
        for (const t4 of e4.mutations) o2 = o2.add(t4.key);
      }
      for (const e4 of t3) {
        s2.push(e4.batchId);
        for (const t4 of e4.mutations) o2 = o2.add(t4.key);
      }
      return n2.localDocuments.getDocuments(e3, o2).next((e4) => ({
        Rs: e4,
        removedBatchIds: i2,
        addedBatchIds: s2
      }));
    });
  });
}
__name(__PRIVATE_localStoreHandleUserChange, "__PRIVATE_localStoreHandleUserChange");
function __PRIVATE_localStoreAcknowledgeBatch(e2, t2) {
  const n2 = __PRIVATE_debugCast(e2);
  return n2.persistence.runTransaction("Acknowledge batch", "readwrite-primary", (e3) => {
    const r2 = t2.batch.keys(), i2 = n2.ds.newChangeBuffer({
      trackRemovals: true
    });
    return (/* @__PURE__ */ __name(function __PRIVATE_applyWriteToRemoteDocuments(e4, t3, n3, r3) {
      const i3 = n3.batch, s2 = i3.keys();
      let o2 = PersistencePromise.resolve();
      return s2.forEach((e5) => {
        o2 = o2.next(() => r3.getEntry(t3, e5)).next((t4) => {
          const s3 = n3.docVersions.get(e5);
          __PRIVATE_hardAssert(null !== s3), t4.version.compareTo(s3) < 0 && (i3.applyToRemoteDocument(t4, n3), t4.isValidDocument() && // We use the commitVersion as the readTime rather than the
          // document's updateTime since the updateTime is not advanced
          // for updates that do not modify the underlying document.
          (t4.setReadTime(n3.commitVersion), r3.addEntry(t4)));
        });
      }), o2.next(() => e4.mutationQueue.removeMutationBatch(t3, i3));
    }, "__PRIVATE_applyWriteToRemoteDocuments"))(n2, e3, t2, i2).next(() => i2.apply(e3)).next(() => n2.mutationQueue.performConsistencyCheck(e3)).next(() => n2.documentOverlayCache.removeOverlaysForBatchId(e3, r2, t2.batch.batchId)).next(() => n2.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e3, (/* @__PURE__ */ __name(function __PRIVATE_getKeysWithTransformResults(e4) {
      let t3 = __PRIVATE_documentKeySet();
      for (let n3 = 0; n3 < e4.mutationResults.length; ++n3) {
        e4.mutationResults[n3].transformResults.length > 0 && (t3 = t3.add(e4.batch.mutations[n3].key));
      }
      return t3;
    }, "__PRIVATE_getKeysWithTransformResults"))(t2))).next(() => n2.localDocuments.getDocuments(e3, r2));
  });
}
__name(__PRIVATE_localStoreAcknowledgeBatch, "__PRIVATE_localStoreAcknowledgeBatch");
function __PRIVATE_localStoreGetLastRemoteSnapshotVersion(e2) {
  const t2 = __PRIVATE_debugCast(e2);
  return t2.persistence.runTransaction("Get last remote snapshot version", "readonly", (e3) => t2.Hr.getLastRemoteSnapshotVersion(e3));
}
__name(__PRIVATE_localStoreGetLastRemoteSnapshotVersion, "__PRIVATE_localStoreGetLastRemoteSnapshotVersion");
function __PRIVATE_localStoreApplyRemoteEventToLocalCache(e2, t2) {
  const n2 = __PRIVATE_debugCast(e2), r2 = t2.snapshotVersion;
  let i2 = n2.Ts;
  return n2.persistence.runTransaction("Apply remote event", "readwrite-primary", (e3) => {
    const s2 = n2.ds.newChangeBuffer({
      trackRemovals: true
    });
    i2 = n2.Ts;
    const o2 = [];
    t2.targetChanges.forEach((s3, _3) => {
      const a3 = i2.get(_3);
      if (!a3) return;
      o2.push(n2.Hr.removeMatchingKeys(e3, s3.removedDocuments, _3).next(() => n2.Hr.addMatchingKeys(e3, s3.addedDocuments, _3)));
      let u2 = a3.withSequenceNumber(e3.currentSequenceNumber);
      null !== t2.targetMismatches.get(_3) ? u2 = u2.withResumeToken(ByteString.EMPTY_BYTE_STRING, SnapshotVersion.min()).withLastLimboFreeSnapshotVersion(SnapshotVersion.min()) : s3.resumeToken.approximateByteSize() > 0 && (u2 = u2.withResumeToken(s3.resumeToken, r2)), i2 = i2.insert(_3, u2), // Update the target data if there are target changes (or if
      // sufficient time has passed since the last update).
      /**
      * Returns true if the newTargetData should be persisted during an update of
      * an active target. TargetData should always be persisted when a target is
      * being released and should not call this function.
      *
      * While the target is active, TargetData updates can be omitted when nothing
      * about the target has changed except metadata like the resume token or
      * snapshot version. Occasionally it's worth the extra write to prevent these
      * values from getting too stale after a crash, but this doesn't have to be
      * too frequent.
      */
      (/* @__PURE__ */ __name(function __PRIVATE_shouldPersistTargetData(e4, t3, n3) {
        if (0 === e4.resumeToken.approximateByteSize()) return true;
        const r3 = t3.snapshotVersion.toMicroseconds() - e4.snapshotVersion.toMicroseconds();
        if (r3 >= Nt) return true;
        const i3 = n3.addedDocuments.size + n3.modifiedDocuments.size + n3.removedDocuments.size;
        return i3 > 0;
      }, "__PRIVATE_shouldPersistTargetData"))(a3, u2, s3) && o2.push(n2.Hr.updateTargetData(e3, u2));
    });
    let _2 = __PRIVATE_mutableDocumentMap(), a2 = __PRIVATE_documentKeySet();
    if (t2.documentUpdates.forEach((r3) => {
      t2.resolvedLimboDocuments.has(r3) && o2.push(n2.persistence.referenceDelegate.updateLimboDocument(e3, r3));
    }), // Each loop iteration only affects its "own" doc, so it's safe to get all
    // the remote documents in advance in a single call.
    o2.push(__PRIVATE_populateDocumentChangeBuffer(e3, s2, t2.documentUpdates).next((e4) => {
      _2 = e4.Vs, a2 = e4.fs;
    })), !r2.isEqual(SnapshotVersion.min())) {
      const t3 = n2.Hr.getLastRemoteSnapshotVersion(e3).next((t4) => n2.Hr.setTargetsMetadata(e3, e3.currentSequenceNumber, r2));
      o2.push(t3);
    }
    return PersistencePromise.waitFor(o2).next(() => s2.apply(e3)).next(() => n2.localDocuments.getLocalViewOfDocuments(e3, _2, a2)).next(() => _2);
  }).then((e3) => (n2.Ts = i2, e3));
}
__name(__PRIVATE_localStoreApplyRemoteEventToLocalCache, "__PRIVATE_localStoreApplyRemoteEventToLocalCache");
function __PRIVATE_populateDocumentChangeBuffer(e2, t2, n2) {
  let r2 = __PRIVATE_documentKeySet(), i2 = __PRIVATE_documentKeySet();
  return n2.forEach((e3) => r2 = r2.add(e3)), t2.getEntries(e2, r2).next((e3) => {
    let r3 = __PRIVATE_mutableDocumentMap();
    return n2.forEach((n3, s2) => {
      const o2 = e3.get(n3);
      s2.isFoundDocument() !== o2.isFoundDocument() && (i2 = i2.add(n3)), // Note: The order of the steps below is important, since we want
      // to ensure that rejected limbo resolutions (which fabricate
      // NoDocuments with SnapshotVersion.min()) never add documents to
      // cache.
      s2.isNoDocument() && s2.version.isEqual(SnapshotVersion.min()) ? (
        // NoDocuments with SnapshotVersion.min() are used in manufactured
        // events. We remove these documents from cache since we lost
        // access.
        (t2.removeEntry(n3, s2.readTime), r3 = r3.insert(n3, s2))
      ) : !o2.isValidDocument() || s2.version.compareTo(o2.version) > 0 || 0 === s2.version.compareTo(o2.version) && o2.hasPendingWrites ? (t2.addEntry(s2), r3 = r3.insert(n3, s2)) : __PRIVATE_logDebug(Ot, "Ignoring outdated watch update for ", n3, ". Current version:", o2.version, " Watch version:", s2.version);
    }), {
      Vs: r3,
      fs: i2
    };
  });
}
__name(__PRIVATE_populateDocumentChangeBuffer, "__PRIVATE_populateDocumentChangeBuffer");
function __PRIVATE_localStoreGetNextMutationBatch(e2, t2) {
  const n2 = __PRIVATE_debugCast(e2);
  return n2.persistence.runTransaction("Get next mutation batch", "readonly", (e3) => (void 0 === t2 && (t2 = Q), n2.mutationQueue.getNextMutationBatchAfterBatchId(e3, t2)));
}
__name(__PRIVATE_localStoreGetNextMutationBatch, "__PRIVATE_localStoreGetNextMutationBatch");
function __PRIVATE_localStoreAllocateTarget(e2, t2) {
  const n2 = __PRIVATE_debugCast(e2);
  return n2.persistence.runTransaction("Allocate target", "readwrite", (e3) => {
    let r2;
    return n2.Hr.getTargetData(e3, t2).next((i2) => i2 ? (
      // This target has been listened to previously, so reuse the
      // previous targetID.
      // TODO(mcg): freshen last accessed date?
      (r2 = i2, PersistencePromise.resolve(r2))
    ) : n2.Hr.allocateTargetId(e3).next((i3) => (r2 = new TargetData(t2, i3, "TargetPurposeListen", e3.currentSequenceNumber), n2.Hr.addTargetData(e3, r2).next(() => r2))));
  }).then((e3) => {
    const r2 = n2.Ts.get(e3.targetId);
    return (null === r2 || e3.snapshotVersion.compareTo(r2.snapshotVersion) > 0) && (n2.Ts = n2.Ts.insert(e3.targetId, e3), n2.Is.set(t2, e3.targetId)), e3;
  });
}
__name(__PRIVATE_localStoreAllocateTarget, "__PRIVATE_localStoreAllocateTarget");
async function __PRIVATE_localStoreReleaseTarget(e2, t2, n2) {
  const r2 = __PRIVATE_debugCast(e2), i2 = r2.Ts.get(t2), s2 = n2 ? "readwrite" : "readwrite-primary";
  try {
    n2 || await r2.persistence.runTransaction("Release target", s2, (e3) => r2.persistence.referenceDelegate.removeTarget(e3, i2));
  } catch (e3) {
    if (!__PRIVATE_isIndexedDbTransactionError(e3)) throw e3;
    __PRIVATE_logDebug(Ot, `Failed to update sequence numbers for target ${t2}: ${e3}`);
  }
  r2.Ts = r2.Ts.remove(t2), r2.Is.delete(i2.target);
}
__name(__PRIVATE_localStoreReleaseTarget, "__PRIVATE_localStoreReleaseTarget");
function __PRIVATE_localStoreExecuteQuery(e2, t2, n2) {
  const r2 = __PRIVATE_debugCast(e2);
  let i2 = SnapshotVersion.min(), s2 = __PRIVATE_documentKeySet();
  return r2.persistence.runTransaction(
    "Execute query",
    "readwrite",
    // Use readwrite instead of readonly so indexes can be created
    // Use readwrite instead of readonly so indexes can be created
    (e3) => (/* @__PURE__ */ __name(function __PRIVATE_localStoreGetTargetData(e4, t3, n3) {
      const r3 = __PRIVATE_debugCast(e4), i3 = r3.Is.get(n3);
      return void 0 !== i3 ? PersistencePromise.resolve(r3.Ts.get(i3)) : r3.Hr.getTargetData(t3, n3);
    }, "__PRIVATE_localStoreGetTargetData"))(r2, e3, __PRIVATE_queryToTarget(t2)).next((t3) => {
      if (t3) return i2 = t3.lastLimboFreeSnapshotVersion, r2.Hr.getMatchingKeysForTargetId(e3, t3.targetId).next((e4) => {
        s2 = e4;
      });
    }).next(() => r2.Ps.getDocumentsMatchingQuery(e3, t2, n2 ? i2 : SnapshotVersion.min(), n2 ? s2 : __PRIVATE_documentKeySet())).next((e4) => (__PRIVATE_setMaxReadTime(r2, __PRIVATE_queryCollectionGroup(t2), e4), {
      documents: e4,
      gs: s2
    }))
  );
}
__name(__PRIVATE_localStoreExecuteQuery, "__PRIVATE_localStoreExecuteQuery");
function __PRIVATE_localStoreGetCachedTarget(e2, t2) {
  const n2 = __PRIVATE_debugCast(e2), r2 = __PRIVATE_debugCast(n2.Hr), i2 = n2.Ts.get(t2);
  return i2 ? Promise.resolve(i2.target) : n2.persistence.runTransaction("Get target data", "readonly", (e3) => r2.lt(e3, t2).next((e4) => e4 ? e4.target : null));
}
__name(__PRIVATE_localStoreGetCachedTarget, "__PRIVATE_localStoreGetCachedTarget");
function __PRIVATE_localStoreGetNewDocumentChanges(e2, t2) {
  const n2 = __PRIVATE_debugCast(e2), r2 = n2.Es.get(t2) || SnapshotVersion.min();
  return n2.persistence.runTransaction("Get new document changes", "readonly", (e3) => n2.ds.getAllFromCollectionGroup(
    e3,
    t2,
    __PRIVATE_newIndexOffsetSuccessorFromReadTime(r2, N),
    /* limit= */
    Number.MAX_SAFE_INTEGER
  )).then((e3) => (__PRIVATE_setMaxReadTime(n2, t2, e3), e3));
}
__name(__PRIVATE_localStoreGetNewDocumentChanges, "__PRIVATE_localStoreGetNewDocumentChanges");
function __PRIVATE_setMaxReadTime(e2, t2, n2) {
  let r2 = e2.Es.get(t2) || SnapshotVersion.min();
  n2.forEach((e3, t3) => {
    t3.readTime.compareTo(r2) > 0 && (r2 = t3.readTime);
  }), e2.Es.set(t2, r2);
}
__name(__PRIVATE_setMaxReadTime, "__PRIVATE_setMaxReadTime");
async function __PRIVATE_localStoreApplyBundledDocuments(e2, t2, n2, r2) {
  const i2 = __PRIVATE_debugCast(e2);
  let s2 = __PRIVATE_documentKeySet(), o2 = __PRIVATE_mutableDocumentMap();
  for (const e3 of n2) {
    const n3 = t2.ps(e3.metadata.name);
    e3.document && (s2 = s2.add(n3));
    const r3 = t2.ys(e3);
    r3.setReadTime(t2.ws(e3.metadata.readTime)), o2 = o2.insert(n3, r3);
  }
  const _2 = i2.ds.newChangeBuffer({
    trackRemovals: true
  }), a2 = await __PRIVATE_localStoreAllocateTarget(i2, (/* @__PURE__ */ __name(function __PRIVATE_umbrellaTarget(e3) {
    return __PRIVATE_queryToTarget(__PRIVATE_newQueryForPath(ResourcePath.fromString(`__bundle__/docs/${e3}`)));
  }, "__PRIVATE_umbrellaTarget"))(r2));
  return i2.persistence.runTransaction("Apply bundle documents", "readwrite", (e3) => __PRIVATE_populateDocumentChangeBuffer(e3, _2, o2).next((t3) => (_2.apply(e3), t3)).next((t3) => i2.Hr.removeMatchingKeysForTargetId(e3, a2.targetId).next(() => i2.Hr.addMatchingKeys(e3, s2, a2.targetId)).next(() => i2.localDocuments.getLocalViewOfDocuments(e3, t3.Vs, t3.fs)).next(() => t3.Vs)));
}
__name(__PRIVATE_localStoreApplyBundledDocuments, "__PRIVATE_localStoreApplyBundledDocuments");
async function __PRIVATE_localStoreSaveNamedQuery(e2, t2, n2 = __PRIVATE_documentKeySet()) {
  const r2 = await __PRIVATE_localStoreAllocateTarget(e2, __PRIVATE_queryToTarget(__PRIVATE_fromBundledQuery(t2.bundledQuery))), i2 = __PRIVATE_debugCast(e2);
  return i2.persistence.runTransaction("Save named query", "readwrite", (e3) => {
    const s2 = __PRIVATE_fromVersion(t2.readTime);
    if (r2.snapshotVersion.compareTo(s2) >= 0) return i2.Yr.saveNamedQuery(e3, t2);
    const o2 = r2.withResumeToken(ByteString.EMPTY_BYTE_STRING, s2);
    return i2.Ts = i2.Ts.insert(o2.targetId, o2), i2.Hr.updateTargetData(e3, o2).next(() => i2.Hr.removeMatchingKeysForTargetId(e3, r2.targetId)).next(() => i2.Hr.addMatchingKeys(e3, n2, r2.targetId)).next(() => i2.Yr.saveNamedQuery(e3, t2));
  });
}
__name(__PRIVATE_localStoreSaveNamedQuery, "__PRIVATE_localStoreSaveNamedQuery");
/**
 * @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 Bt = "firestore_clients";
function createWebStorageClientStateKey(e2, t2) {
  return `${Bt}_${e2}_${t2}`;
}
__name(createWebStorageClientStateKey, "createWebStorageClientStateKey");
const Lt = "firestore_mutations";
function createWebStorageMutationBatchKey(e2, t2, n2) {
  let r2 = `${Lt}_${e2}_${n2}`;
  return t2.isAuthenticated() && (r2 += `_${t2.uid}`), r2;
}
__name(createWebStorageMutationBatchKey, "createWebStorageMutationBatchKey");
const kt = "firestore_targets";
function createWebStorageQueryTargetMetadataKey(e2, t2) {
  return `${kt}_${e2}_${t2}`;
}
__name(createWebStorageQueryTargetMetadataKey, "createWebStorageQueryTargetMetadataKey");
/**
 * @license
 * Copyright 2018 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 qt = "SharedClientState";
class __PRIVATE_MutationMetadata {
  static {
    __name(this, "__PRIVATE_MutationMetadata");
  }
  constructor(e2, t2, n2, r2) {
    this.user = e2, this.batchId = t2, this.state = n2, this.error = r2;
  }
  /**
   * Parses a MutationMetadata from its JSON representation in WebStorage.
   * Logs a warning and returns null if the format of the data is not valid.
   */
  static Ss(e2, t2, n2) {
    const r2 = JSON.parse(n2);
    let i2, s2 = "object" == typeof r2 && -1 !== ["pending", "acknowledged", "rejected"].indexOf(r2.state) && (void 0 === r2.error || "object" == typeof r2.error);
    return s2 && r2.error && (s2 = "string" == typeof r2.error.message && "string" == typeof r2.error.code, s2 && (i2 = new FirestoreError(r2.error.code, r2.error.message))), s2 ? new __PRIVATE_MutationMetadata(e2, t2, r2.state, i2) : (__PRIVATE_logError(qt, `Failed to parse mutation state for ID '${t2}': ${n2}`), null);
  }
  bs() {
    const e2 = {
      state: this.state,
      updateTimeMs: Date.now()
    };
    return this.error && (e2.error = {
      code: this.error.code,
      message: this.error.message
    }), JSON.stringify(e2);
  }
}
class __PRIVATE_QueryTargetMetadata {
  static {
    __name(this, "__PRIVATE_QueryTargetMetadata");
  }
  constructor(e2, t2, n2) {
    this.targetId = e2, this.state = t2, this.error = n2;
  }
  /**
   * Parses a QueryTargetMetadata from its JSON representation in WebStorage.
   * Logs a warning and returns null if the format of the data is not valid.
   */
  static Ss(e2, t2) {
    const n2 = JSON.parse(t2);
    let r2, i2 = "object" == typeof n2 && -1 !== ["not-current", "current", "rejected"].indexOf(n2.state) && (void 0 === n2.error || "object" == typeof n2.error);
    return i2 && n2.error && (i2 = "string" == typeof n2.error.message && "string" == typeof n2.error.code, i2 && (r2 = new FirestoreError(n2.error.code, n2.error.message))), i2 ? new __PRIVATE_QueryTargetMetadata(e2, n2.state, r2) : (__PRIVATE_logError(qt, `Failed to parse target state for ID '${e2}': ${t2}`), null);
  }
  bs() {
    const e2 = {
      state: this.state,
      updateTimeMs: Date.now()
    };
    return this.error && (e2.error = {
      code: this.error.code,
      message: this.error.message
    }), JSON.stringify(e2);
  }
}
class __PRIVATE_RemoteClientState {
  static {
    __name(this, "__PRIVATE_RemoteClientState");
  }
  constructor(e2, t2) {
    this.clientId = e2, this.activeTargetIds = t2;
  }
  /**
   * Parses a RemoteClientState from the JSON representation in WebStorage.
   * Logs a warning and returns null if the format of the data is not valid.
   */
  static Ss(e2, t2) {
    const n2 = JSON.parse(t2);
    let r2 = "object" == typeof n2 && n2.activeTargetIds instanceof Array, i2 = __PRIVATE_targetIdSet();
    for (let e3 = 0; r2 && e3 < n2.activeTargetIds.length; ++e3) r2 = isSafeInteger(n2.activeTargetIds[e3]), i2 = i2.add(n2.activeTargetIds[e3]);
    return r2 ? new __PRIVATE_RemoteClientState(e2, i2) : (__PRIVATE_logError(qt, `Failed to parse client data for instance '${e2}': ${t2}`), null);
  }
}
class __PRIVATE_SharedOnlineState {
  static {
    __name(this, "__PRIVATE_SharedOnlineState");
  }
  constructor(e2, t2) {
    this.clientId = e2, this.onlineState = t2;
  }
  /**
   * Parses a SharedOnlineState from its JSON representation in WebStorage.
   * Logs a warning and returns null if the format of the data is not valid.
   */
  static Ss(e2) {
    const t2 = JSON.parse(e2);
    return "object" == typeof t2 && -1 !== ["Unknown", "Online", "Offline"].indexOf(t2.onlineState) && "string" == typeof t2.clientId ? new __PRIVATE_SharedOnlineState(t2.clientId, t2.onlineState) : (__PRIVATE_logError(qt, `Failed to parse online state: ${e2}`), null);
  }
}
class __PRIVATE_LocalClientState {
  static {
    __name(this, "__PRIVATE_LocalClientState");
  }
  constructor() {
    this.activeTargetIds = __PRIVATE_targetIdSet();
  }
  Ds(e2) {
    this.activeTargetIds = this.activeTargetIds.add(e2);
  }
  vs(e2) {
    this.activeTargetIds = this.activeTargetIds.delete(e2);
  }
  /**
   * Converts this entry into a JSON-encoded format we can use for WebStorage.
   * Does not encode `clientId` as it is part of the key in WebStorage.
   */
  bs() {
    const e2 = {
      activeTargetIds: this.activeTargetIds.toArray(),
      updateTimeMs: Date.now()
    };
    return JSON.stringify(e2);
  }
}
class __PRIVATE_WebStorageSharedClientState {
  static {
    __name(this, "__PRIVATE_WebStorageSharedClientState");
  }
  constructor(e2, t2, n2, r2, i2) {
    this.window = e2, this.Ti = t2, this.persistenceKey = n2, this.Cs = r2, this.syncEngine = null, this.onlineStateHandler = null, this.sequenceNumberHandler = null, this.Fs = this.Ms.bind(this), this.xs = new SortedMap(__PRIVATE_primitiveComparator), this.started = false, /**
     * Captures WebStorage events that occur before `start()` is called. These
     * events are replayed once `WebStorageSharedClientState` is started.
     */
    this.Os = [];
    const s2 = n2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
    this.storage = this.window.localStorage, this.currentUser = i2, this.Ns = createWebStorageClientStateKey(this.persistenceKey, this.Cs), this.Bs = /** Assembles the key for the current sequence number. */
    (/* @__PURE__ */ __name(function createWebStorageSequenceNumberKey(e3) {
      return `firestore_sequence_number_${e3}`;
    }, "createWebStorageSequenceNumberKey"))(this.persistenceKey), this.xs = this.xs.insert(this.Cs, new __PRIVATE_LocalClientState()), this.Ls = new RegExp(`^${Bt}_${s2}_([^_]*)$`), this.ks = new RegExp(`^${Lt}_${s2}_(\\d+)(?:_(.*))?$`), this.qs = new RegExp(`^${kt}_${s2}_(\\d+)$`), this.Qs = /** Assembles the key for the online state of the primary tab. */
    (/* @__PURE__ */ __name(function createWebStorageOnlineStateKey(e3) {
      return `firestore_online_state_${e3}`;
    }, "createWebStorageOnlineStateKey"))(this.persistenceKey), this.$s = (/* @__PURE__ */ __name(function createBundleLoadedKey(e3) {
      return `firestore_bundle_loaded_v2_${e3}`;
    }, "createBundleLoadedKey"))(this.persistenceKey), // Rather than adding the storage observer during start(), we add the
    // storage observer during initialization. This ensures that we collect
    // events before other components populate their initial state (during their
    // respective start() calls). Otherwise, we might for example miss a
    // mutation that is added after LocalStore's start() processed the existing
    // mutations but before we observe WebStorage events.
    this.window.addEventListener("storage", this.Fs);
  }
  /** Returns 'true' if WebStorage is available in the current environment. */
  static D(e2) {
    return !(!e2 || !e2.localStorage);
  }
  async start() {
    const e2 = await this.syncEngine.zi();
    for (const t3 of e2) {
      if (t3 === this.Cs) continue;
      const e3 = this.getItem(createWebStorageClientStateKey(this.persistenceKey, t3));
      if (e3) {
        const n2 = __PRIVATE_RemoteClientState.Ss(t3, e3);
        n2 && (this.xs = this.xs.insert(n2.clientId, n2));
      }
    }
    this.Us();
    const t2 = this.storage.getItem(this.Qs);
    if (t2) {
      const e3 = this.Ks(t2);
      e3 && this.Ws(e3);
    }
    for (const e3 of this.Os) this.Ms(e3);
    this.Os = [], // Register a window unload hook to remove the client metadata entry from
    // WebStorage even if `shutdown()` was not called.
    this.window.addEventListener("pagehide", () => this.shutdown()), this.started = true;
  }
  writeSequenceNumber(e2) {
    this.setItem(this.Bs, JSON.stringify(e2));
  }
  getAllActiveQueryTargets() {
    return this.Gs(this.xs);
  }
  isActiveQueryTarget(e2) {
    let t2 = false;
    return this.xs.forEach((n2, r2) => {
      r2.activeTargetIds.has(e2) && (t2 = true);
    }), t2;
  }
  addPendingMutation(e2) {
    this.zs(e2, "pending");
  }
  updateMutationState(e2, t2, n2) {
    this.zs(e2, t2, n2), // Once a final mutation result is observed by other clients, they no longer
    // access the mutation's metadata entry. Since WebStorage replays events
    // in order, it is safe to delete the entry right after updating it.
    this.js(e2);
  }
  addLocalQueryTarget(e2, t2 = true) {
    let n2 = "not-current";
    if (this.isActiveQueryTarget(e2)) {
      const t3 = this.storage.getItem(createWebStorageQueryTargetMetadataKey(this.persistenceKey, e2));
      if (t3) {
        const r2 = __PRIVATE_QueryTargetMetadata.Ss(e2, t3);
        r2 && (n2 = r2.state);
      }
    }
    return t2 && this.Hs.Ds(e2), this.Us(), n2;
  }
  removeLocalQueryTarget(e2) {
    this.Hs.vs(e2), this.Us();
  }
  isLocalQueryTarget(e2) {
    return this.Hs.activeTargetIds.has(e2);
  }
  clearQueryState(e2) {
    this.removeItem(createWebStorageQueryTargetMetadataKey(this.persistenceKey, e2));
  }
  updateQueryState(e2, t2, n2) {
    this.Js(e2, t2, n2);
  }
  handleUserChange(e2, t2, n2) {
    t2.forEach((e3) => {
      this.js(e3);
    }), this.currentUser = e2, n2.forEach((e3) => {
      this.addPendingMutation(e3);
    });
  }
  setOnlineState(e2) {
    this.Ys(e2);
  }
  notifyBundleLoaded(e2) {
    this.Zs(e2);
  }
  shutdown() {
    this.started && (this.window.removeEventListener("storage", this.Fs), this.removeItem(this.Ns), this.started = false);
  }
  getItem(e2) {
    const t2 = this.storage.getItem(e2);
    return __PRIVATE_logDebug(qt, "READ", e2, t2), t2;
  }
  setItem(e2, t2) {
    __PRIVATE_logDebug(qt, "SET", e2, t2), this.storage.setItem(e2, t2);
  }
  removeItem(e2) {
    __PRIVATE_logDebug(qt, "REMOVE", e2), this.storage.removeItem(e2);
  }
  Ms(e2) {
    const t2 = e2;
    if (t2.storageArea === this.storage) {
      if (__PRIVATE_logDebug(qt, "EVENT", t2.key, t2.newValue), t2.key === this.Ns) return void __PRIVATE_logError("Received WebStorage notification for local change. Another client might have garbage-collected our state");
      this.Ti.enqueueRetryable(async () => {
        if (this.started) {
          if (null !== t2.key) {
            if (this.Ls.test(t2.key)) {
              if (null == t2.newValue) {
                const e3 = this.Xs(t2.key);
                return this.eo(e3, null);
              }
              {
                const e3 = this.no(t2.key, t2.newValue);
                if (e3) return this.eo(e3.clientId, e3);
              }
            } else if (this.ks.test(t2.key)) {
              if (null !== t2.newValue) {
                const e3 = this.ro(t2.key, t2.newValue);
                if (e3) return this.io(e3);
              }
            } else if (this.qs.test(t2.key)) {
              if (null !== t2.newValue) {
                const e3 = this.so(t2.key, t2.newValue);
                if (e3) return this.oo(e3);
              }
            } else if (t2.key === this.Qs) {
              if (null !== t2.newValue) {
                const e3 = this.Ks(t2.newValue);
                if (e3) return this.Ws(e3);
              }
            } else if (t2.key === this.Bs) {
              const e3 = (/* @__PURE__ */ __name(function __PRIVATE_fromWebStorageSequenceNumber(e4) {
                let t3 = __PRIVATE_ListenSequence.ae;
                if (null != e4) try {
                  const n2 = JSON.parse(e4);
                  __PRIVATE_hardAssert("number" == typeof n2), t3 = n2;
                } catch (e5) {
                  __PRIVATE_logError(qt, "Failed to read sequence number from WebStorage", e5);
                }
                return t3;
              }, "__PRIVATE_fromWebStorageSequenceNumber"))(t2.newValue);
              e3 !== __PRIVATE_ListenSequence.ae && this.sequenceNumberHandler(e3);
            } else if (t2.key === this.$s) {
              const e3 = this._o(t2.newValue);
              await Promise.all(e3.map((e4) => this.syncEngine.ao(e4)));
            }
          }
        } else this.Os.push(t2);
      });
    }
  }
  get Hs() {
    return this.xs.get(this.Cs);
  }
  Us() {
    this.setItem(this.Ns, this.Hs.bs());
  }
  zs(e2, t2, n2) {
    const r2 = new __PRIVATE_MutationMetadata(this.currentUser, e2, t2, n2), i2 = createWebStorageMutationBatchKey(this.persistenceKey, this.currentUser, e2);
    this.setItem(i2, r2.bs());
  }
  js(e2) {
    const t2 = createWebStorageMutationBatchKey(this.persistenceKey, this.currentUser, e2);
    this.removeItem(t2);
  }
  Ys(e2) {
    const t2 = {
      clientId: this.Cs,
      onlineState: e2
    };
    this.storage.setItem(this.Qs, JSON.stringify(t2));
  }
  Js(e2, t2, n2) {
    const r2 = createWebStorageQueryTargetMetadataKey(this.persistenceKey, e2), i2 = new __PRIVATE_QueryTargetMetadata(e2, t2, n2);
    this.setItem(r2, i2.bs());
  }
  Zs(e2) {
    const t2 = JSON.stringify(Array.from(e2));
    this.setItem(this.$s, t2);
  }
  /**
   * Parses a client state key in WebStorage. Returns null if the key does not
   * match the expected key format.
   */
  Xs(e2) {
    const t2 = this.Ls.exec(e2);
    return t2 ? t2[1] : null;
  }
  /**
   * Parses a client state in WebStorage. Returns 'null' if the value could not
   * be parsed.
   */
  no(e2, t2) {
    const n2 = this.Xs(e2);
    return __PRIVATE_RemoteClientState.Ss(n2, t2);
  }
  /**
   * Parses a mutation batch state in WebStorage. Returns 'null' if the value
   * could not be parsed.
   */
  ro(e2, t2) {
    const n2 = this.ks.exec(e2), r2 = Number(n2[1]), i2 = void 0 !== n2[2] ? n2[2] : null;
    return __PRIVATE_MutationMetadata.Ss(new User(i2), r2, t2);
  }
  /**
   * Parses a query target state from WebStorage. Returns 'null' if the value
   * could not be parsed.
   */
  so(e2, t2) {
    const n2 = this.qs.exec(e2), r2 = Number(n2[1]);
    return __PRIVATE_QueryTargetMetadata.Ss(r2, t2);
  }
  /**
   * Parses an online state from WebStorage. Returns 'null' if the value
   * could not be parsed.
   */
  Ks(e2) {
    return __PRIVATE_SharedOnlineState.Ss(e2);
  }
  _o(e2) {
    return JSON.parse(e2);
  }
  async io(e2) {
    if (e2.user.uid === this.currentUser.uid) return this.syncEngine.uo(e2.batchId, e2.state, e2.error);
    __PRIVATE_logDebug(qt, `Ignoring mutation for non-active user ${e2.user.uid}`);
  }
  oo(e2) {
    return this.syncEngine.co(e2.targetId, e2.state, e2.error);
  }
  eo(e2, t2) {
    const n2 = t2 ? this.xs.insert(e2, t2) : this.xs.remove(e2), r2 = this.Gs(this.xs), i2 = this.Gs(n2), s2 = [], o2 = [];
    return i2.forEach((e3) => {
      r2.has(e3) || s2.push(e3);
    }), r2.forEach((e3) => {
      i2.has(e3) || o2.push(e3);
    }), this.syncEngine.lo(s2, o2).then(() => {
      this.xs = n2;
    });
  }
  Ws(e2) {
    this.xs.get(e2.clientId) && this.onlineStateHandler(e2.onlineState);
  }
  Gs(e2) {
    let t2 = __PRIVATE_targetIdSet();
    return e2.forEach((e3, n2) => {
      t2 = t2.unionWith(n2.activeTargetIds);
    }), t2;
  }
}
class __PRIVATE_MemorySharedClientState {
  static {
    __name(this, "__PRIVATE_MemorySharedClientState");
  }
  constructor() {
    this.ho = new __PRIVATE_LocalClientState(), this.Po = {}, this.onlineStateHandler = null, this.sequenceNumberHandler = null;
  }
  addPendingMutation(e2) {
  }
  updateMutationState(e2, t2, n2) {
  }
  addLocalQueryTarget(e2, t2 = true) {
    return t2 && this.ho.Ds(e2), this.Po[e2] || "not-current";
  }
  updateQueryState(e2, t2, n2) {
    this.Po[e2] = t2;
  }
  removeLocalQueryTarget(e2) {
    this.ho.vs(e2);
  }
  isLocalQueryTarget(e2) {
    return this.ho.activeTargetIds.has(e2);
  }
  clearQueryState(e2) {
    delete this.Po[e2];
  }
  getAllActiveQueryTargets() {
    return this.ho.activeTargetIds;
  }
  isActiveQueryTarget(e2) {
    return this.ho.activeTargetIds.has(e2);
  }
  start() {
    return this.ho = new __PRIVATE_LocalClientState(), Promise.resolve();
  }
  handleUserChange(e2, t2, n2) {
  }
  setOnlineState(e2) {
  }
  shutdown() {
  }
  writeSequenceNumber(e2) {
  }
  notifyBundleLoaded(e2) {
  }
}
/**
 * @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 __PRIVATE_NoopConnectivityMonitor {
  static {
    __name(this, "__PRIVATE_NoopConnectivityMonitor");
  }
  To(e2) {
  }
  shutdown() {
  }
}
/**
 * @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 Qt = "ConnectivityMonitor";
class __PRIVATE_BrowserConnectivityMonitor {
  static {
    __name(this, "__PRIVATE_BrowserConnectivityMonitor");
  }
  constructor() {
    this.Io = () => this.Eo(), this.Ao = () => this.Ro(), this.Vo = [], this.mo();
  }
  To(e2) {
    this.Vo.push(e2);
  }
  shutdown() {
    window.removeEventListener("online", this.Io), window.removeEventListener("offline", this.Ao);
  }
  mo() {
    window.addEventListener("online", this.Io), window.addEventListener("offline", this.Ao);
  }
  Eo() {
    __PRIVATE_logDebug(Qt, "Network connectivity changed: AVAILABLE");
    for (const e2 of this.Vo) e2(
      0
      /* NetworkStatus.AVAILABLE */
    );
  }
  Ro() {
    __PRIVATE_logDebug(Qt, "Network connectivity changed: UNAVAILABLE");
    for (const e2 of this.Vo) e2(
      1
      /* NetworkStatus.UNAVAILABLE */
    );
  }
  // TODO(chenbrian): Consider passing in window either into this component or
  // here for testing via FakeWindow.
  /** Checks that all used attributes of window are available. */
  static D() {
    return "undefined" != typeof window && void 0 !== window.addEventListener && void 0 !== window.removeEventListener;
  }
}
/**
 * @license
 * Copyright 2023 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 $t$1 = null;
function __PRIVATE_generateUniqueDebugId() {
  return null === $t$1 ? $t$1 = (/* @__PURE__ */ __name(function __PRIVATE_generateInitialUniqueDebugId() {
    return 268435456 + Math.round(2147483648 * Math.random());
  }, "__PRIVATE_generateInitialUniqueDebugId"))() : $t$1++, "0x" + $t$1.toString(16);
}
__name(__PRIVATE_generateUniqueDebugId, "__PRIVATE_generateUniqueDebugId");
/**
 * @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 Ut = "RestConnection", Kt = {
  BatchGetDocuments: "batchGet",
  Commit: "commit",
  RunQuery: "runQuery",
  RunAggregationQuery: "runAggregationQuery"
};
class __PRIVATE_RestConnection {
  static {
    __name(this, "__PRIVATE_RestConnection");
  }
  get fo() {
    return false;
  }
  constructor(e2) {
    this.databaseInfo = e2, this.databaseId = e2.databaseId;
    const t2 = e2.ssl ? "https" : "http", n2 = encodeURIComponent(this.databaseId.projectId), r2 = encodeURIComponent(this.databaseId.database);
    this.po = t2 + "://" + e2.host, this.yo = `projects/${n2}/databases/${r2}`, this.wo = this.databaseId.database === rt ? `project_id=${n2}` : `project_id=${n2}&database_id=${r2}`;
  }
  So(e2, t2, n2, r2, i2) {
    const s2 = __PRIVATE_generateUniqueDebugId(), o2 = this.bo(e2, t2.toUriEncodedString());
    __PRIVATE_logDebug(Ut, `Sending RPC '${e2}' ${s2}:`, o2, n2);
    const _2 = {
      "google-cloud-resource-prefix": this.yo,
      "x-goog-request-params": this.wo
    };
    return this.Do(_2, r2, i2), this.vo(e2, o2, _2, n2).then((t3) => (__PRIVATE_logDebug(Ut, `Received RPC '${e2}' ${s2}: `, t3), t3), (t3) => {
      throw __PRIVATE_logWarn(Ut, `RPC '${e2}' ${s2} failed with error: `, t3, "url: ", o2, "request:", n2), t3;
    });
  }
  Co(e2, t2, n2, r2, i2, s2) {
    return this.So(e2, t2, n2, r2, i2);
  }
  /**
   * Modifies the headers for a request, adding any authorization token if
   * present and any additional headers for the request.
   */
  Do(e2, t2, n2) {
    e2["X-Goog-Api-Client"] = // SDK_VERSION is updated to different value at runtime depending on the entry point,
    // so we need to get its value when we need it in a function.
    (/* @__PURE__ */ __name(function __PRIVATE_getGoogApiClientValue() {
      return "gl-js/ fire/" + D;
    }, "__PRIVATE_getGoogApiClientValue"))(), // Content-Type: text/plain will avoid preflight requests which might
    // mess with CORS and redirects by proxies. If we add custom headers
    // we will need to change this code to potentially use the $httpOverwrite
    // parameter supported by ESF to avoid triggering preflight requests.
    e2["Content-Type"] = "text/plain", this.databaseInfo.appId && (e2["X-Firebase-GMPID"] = this.databaseInfo.appId), t2 && t2.headers.forEach((t3, n3) => e2[n3] = t3), n2 && n2.headers.forEach((t3, n3) => e2[n3] = t3);
  }
  bo(e2, t2) {
    const n2 = Kt[e2];
    return `${this.po}/v1/${t2}:${n2}`;
  }
  /**
   * Closes and cleans up any resources associated with the connection. This
   * implementation is a no-op because there are no resources associated
   * with the RestConnection that need to be cleaned up.
   */
  terminate() {
  }
}
/**
 * @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 __PRIVATE_StreamBridge {
  static {
    __name(this, "__PRIVATE_StreamBridge");
  }
  constructor(e2) {
    this.Fo = e2.Fo, this.Mo = e2.Mo;
  }
  xo(e2) {
    this.Oo = e2;
  }
  No(e2) {
    this.Bo = e2;
  }
  Lo(e2) {
    this.ko = e2;
  }
  onMessage(e2) {
    this.qo = e2;
  }
  close() {
    this.Mo();
  }
  send(e2) {
    this.Fo(e2);
  }
  Qo() {
    this.Oo();
  }
  $o() {
    this.Bo();
  }
  Uo(e2) {
    this.ko(e2);
  }
  Ko(e2) {
    this.qo(e2);
  }
}
/**
 * @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 Wt = "WebChannelConnection";
class __PRIVATE_WebChannelConnection extends __PRIVATE_RestConnection {
  static {
    __name(this, "__PRIVATE_WebChannelConnection");
  }
  constructor(e2) {
    super(e2), this.forceLongPolling = e2.forceLongPolling, this.autoDetectLongPolling = e2.autoDetectLongPolling, this.useFetchStreams = e2.useFetchStreams, this.longPollingOptions = e2.longPollingOptions;
  }
  vo(e2, t2, n2, r2) {
    const i2 = __PRIVATE_generateUniqueDebugId();
    return new Promise((s2, o2) => {
      const _2 = new XhrIo();
      _2.setWithCredentials(true), _2.listenOnce(EventType.COMPLETE, () => {
        try {
          switch (_2.getLastErrorCode()) {
            case ErrorCode$1.NO_ERROR:
              const t3 = _2.getResponseJson();
              __PRIVATE_logDebug(Wt, `XHR for RPC '${e2}' ${i2} received:`, JSON.stringify(t3)), s2(t3);
              break;
            case ErrorCode$1.TIMEOUT:
              __PRIVATE_logDebug(Wt, `RPC '${e2}' ${i2} timed out`), o2(new FirestoreError(C.DEADLINE_EXCEEDED, "Request time out"));
              break;
            case ErrorCode$1.HTTP_ERROR:
              const n3 = _2.getStatus();
              if (__PRIVATE_logDebug(Wt, `RPC '${e2}' ${i2} failed with status:`, n3, "response text:", _2.getResponseText()), n3 > 0) {
                let e3 = _2.getResponseJson();
                Array.isArray(e3) && (e3 = e3[0]);
                const t4 = null == e3 ? void 0 : e3.error;
                if (t4 && t4.status && t4.message) {
                  const e4 = (/* @__PURE__ */ __name(function __PRIVATE_mapCodeFromHttpResponseErrorStatus(e5) {
                    const t5 = e5.toLowerCase().replace(/_/g, "-");
                    return Object.values(C).indexOf(t5) >= 0 ? t5 : C.UNKNOWN;
                  }, "__PRIVATE_mapCodeFromHttpResponseErrorStatus"))(t4.status);
                  o2(new FirestoreError(e4, t4.message));
                } else o2(new FirestoreError(C.UNKNOWN, "Server responded with status " + _2.getStatus()));
              } else
                o2(new FirestoreError(C.UNAVAILABLE, "Connection failed."));
              break;
            default:
              fail();
          }
        } finally {
          __PRIVATE_logDebug(Wt, `RPC '${e2}' ${i2} completed.`);
        }
      });
      const a2 = JSON.stringify(r2);
      __PRIVATE_logDebug(Wt, `RPC '${e2}' ${i2} sending request:`, r2), _2.send(t2, "POST", a2, n2, 15);
    });
  }
  Wo(e2, t2, n2) {
    const r2 = __PRIVATE_generateUniqueDebugId(), i2 = [this.po, "/", "google.firestore.v1.Firestore", "/", e2, "/channel"], s2 = createWebChannelTransport(), o2 = getStatEventTarget(), _2 = {
      // Required for backend stickiness, routing behavior is based on this
      // parameter.
      httpSessionIdParam: "gsessionid",
      initMessageHeaders: {},
      messageUrlParams: {
        // This param is used to improve routing and project isolation by the
        // backend and must be included in every request.
        database: `projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`
      },
      sendRawJson: true,
      supportsCrossDomainXhr: true,
      internalChannelParams: {
        // Override the default timeout (randomized between 10-20 seconds) since
        // a large write batch on a slow internet connection may take a long
        // time to send to the backend. Rather than have WebChannel impose a
        // tight timeout which could lead to infinite timeouts and retries, we
        // set it very large (5-10 minutes) and rely on the browser's builtin
        // timeouts to kick in if the request isn't working.
        forwardChannelRequestTimeoutMs: 6e5
      },
      forceLongPolling: this.forceLongPolling,
      detectBufferingProxy: this.autoDetectLongPolling
    }, a2 = this.longPollingOptions.timeoutSeconds;
    void 0 !== a2 && (_2.longPollingTimeout = Math.round(1e3 * a2)), this.useFetchStreams && (_2.useFetchStreams = true), this.Do(_2.initMessageHeaders, t2, n2), // Sending the custom headers we just added to request.initMessageHeaders
    // (Authorization, etc.) will trigger the browser to make a CORS preflight
    // request because the XHR will no longer meet the criteria for a "simple"
    // CORS request:
    // https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests
    // Therefore to avoid the CORS preflight request (an extra network
    // roundtrip), we use the encodeInitMessageHeaders option to specify that
    // the headers should instead be encoded in the request's POST payload,
    // which is recognized by the webchannel backend.
    _2.encodeInitMessageHeaders = true;
    const u2 = i2.join("");
    __PRIVATE_logDebug(Wt, `Creating RPC '${e2}' stream ${r2}: ${u2}`, _2);
    const c2 = s2.createWebChannel(u2, _2);
    let l2 = false, h2 = false;
    const P2 = new __PRIVATE_StreamBridge({
      Fo: /* @__PURE__ */ __name((t3) => {
        h2 ? __PRIVATE_logDebug(Wt, `Not sending because RPC '${e2}' stream ${r2} is closed:`, t3) : (l2 || (__PRIVATE_logDebug(Wt, `Opening RPC '${e2}' stream ${r2} transport.`), c2.open(), l2 = true), __PRIVATE_logDebug(Wt, `RPC '${e2}' stream ${r2} sending:`, t3), c2.send(t3));
      }, "Fo"),
      Mo: /* @__PURE__ */ __name(() => c2.close(), "Mo")
    }), __PRIVATE_unguardedEventListen = /* @__PURE__ */ __name((e3, t3, n3) => {
      e3.listen(t3, (e4) => {
        try {
          n3(e4);
        } catch (e5) {
          setTimeout(() => {
            throw e5;
          }, 0);
        }
      });
    }, "__PRIVATE_unguardedEventListen");
    return __PRIVATE_unguardedEventListen(c2, WebChannel.EventType.OPEN, () => {
      h2 || (__PRIVATE_logDebug(Wt, `RPC '${e2}' stream ${r2} transport opened.`), P2.Qo());
    }), __PRIVATE_unguardedEventListen(c2, WebChannel.EventType.CLOSE, () => {
      h2 || (h2 = true, __PRIVATE_logDebug(Wt, `RPC '${e2}' stream ${r2} transport closed`), P2.Uo());
    }), __PRIVATE_unguardedEventListen(c2, WebChannel.EventType.ERROR, (t3) => {
      h2 || (h2 = true, __PRIVATE_logWarn(Wt, `RPC '${e2}' stream ${r2} transport errored:`, t3), P2.Uo(new FirestoreError(C.UNAVAILABLE, "The operation could not be completed")));
    }), __PRIVATE_unguardedEventListen(c2, WebChannel.EventType.MESSAGE, (t3) => {
      var n3;
      if (!h2) {
        const i3 = t3.data[0];
        __PRIVATE_hardAssert(!!i3);
        const s3 = i3, o3 = (null == s3 ? void 0 : s3.error) || (null === (n3 = s3[0]) || void 0 === n3 ? void 0 : n3.error);
        if (o3) {
          __PRIVATE_logDebug(Wt, `RPC '${e2}' stream ${r2} received error:`, o3);
          const t4 = o3.status;
          let n4 = (
            /**
            * Maps an error Code from a GRPC status identifier like 'NOT_FOUND'.
            *
            * @returns The Code equivalent to the given status string or undefined if
            *     there is no match.
            */
            (/* @__PURE__ */ __name(function __PRIVATE_mapCodeFromRpcStatus(e3) {
              const t5 = Et[e3];
              if (void 0 !== t5) return __PRIVATE_mapCodeFromRpcCode(t5);
            }, "__PRIVATE_mapCodeFromRpcStatus"))(t4)
          ), i4 = o3.message;
          void 0 === n4 && (n4 = C.INTERNAL, i4 = "Unknown error status: " + t4 + " with message " + o3.message), // Mark closed so no further events are propagated
          h2 = true, P2.Uo(new FirestoreError(n4, i4)), c2.close();
        } else __PRIVATE_logDebug(Wt, `RPC '${e2}' stream ${r2} received:`, i3), P2.Ko(i3);
      }
    }), __PRIVATE_unguardedEventListen(o2, Event$1.STAT_EVENT, (t3) => {
      t3.stat === Stat.PROXY ? __PRIVATE_logDebug(Wt, `RPC '${e2}' stream ${r2} detected buffering proxy`) : t3.stat === Stat.NOPROXY && __PRIVATE_logDebug(Wt, `RPC '${e2}' stream ${r2} detected no buffering proxy`);
    }), setTimeout(() => {
      P2.$o();
    }, 0), P2;
  }
}
/**
 * @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.
 */
/**
 * @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.
 */
function __PRIVATE_getWindow() {
  return "undefined" != typeof window ? window : null;
}
__name(__PRIVATE_getWindow, "__PRIVATE_getWindow");
function getDocument() {
  return "undefined" != typeof document ? document : null;
}
__name(getDocument, "getDocument");
/**
 * @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.
 */
function __PRIVATE_newSerializer(e2) {
  return new JsonProtoSerializer(
    e2,
    /* useProto3Json= */
    true
  );
}
__name(__PRIVATE_newSerializer, "__PRIVATE_newSerializer");
/**
 * @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 __PRIVATE_ExponentialBackoff {
  static {
    __name(this, "__PRIVATE_ExponentialBackoff");
  }
  constructor(e2, t2, n2 = 1e3, r2 = 1.5, i2 = 6e4) {
    this.Ti = e2, this.timerId = t2, this.Go = n2, this.zo = r2, this.jo = i2, this.Ho = 0, this.Jo = null, /** The last backoff attempt, as epoch milliseconds. */
    this.Yo = Date.now(), this.reset();
  }
  /**
   * Resets the backoff delay.
   *
   * The very next backoffAndWait() will have no delay. If it is called again
   * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and
   * subsequent ones will increase according to the backoffFactor.
   */
  reset() {
    this.Ho = 0;
  }
  /**
   * Resets the backoff delay to the maximum delay (e.g. for use after a
   * RESOURCE_EXHAUSTED error).
   */
  Zo() {
    this.Ho = this.jo;
  }
  /**
   * Returns a promise that resolves after currentDelayMs, and increases the
   * delay for any subsequent attempts. If there was a pending backoff operation
   * already, it will be canceled.
   */
  Xo(e2) {
    this.cancel();
    const t2 = Math.floor(this.Ho + this.e_()), n2 = Math.max(0, Date.now() - this.Yo), r2 = Math.max(0, t2 - n2);
    r2 > 0 && __PRIVATE_logDebug("ExponentialBackoff", `Backing off for ${r2} ms (base delay: ${this.Ho} ms, delay with jitter: ${t2} ms, last attempt: ${n2} ms ago)`), this.Jo = this.Ti.enqueueAfterDelay(this.timerId, r2, () => (this.Yo = Date.now(), e2())), // Apply backoff factor to determine next delay and ensure it is within
    // bounds.
    this.Ho *= this.zo, this.Ho < this.Go && (this.Ho = this.Go), this.Ho > this.jo && (this.Ho = this.jo);
  }
  t_() {
    null !== this.Jo && (this.Jo.skipDelay(), this.Jo = null);
  }
  cancel() {
    null !== this.Jo && (this.Jo.cancel(), this.Jo = null);
  }
  /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */
  e_() {
    return (Math.random() - 0.5) * this.Ho;
  }
}
/**
 * @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 Gt = "PersistentStream";
class __PRIVATE_PersistentStream {
  static {
    __name(this, "__PRIVATE_PersistentStream");
  }
  constructor(e2, t2, n2, r2, i2, s2, o2, _2) {
    this.Ti = e2, this.n_ = n2, this.r_ = r2, this.connection = i2, this.authCredentialsProvider = s2, this.appCheckCredentialsProvider = o2, this.listener = _2, this.state = 0, /**
     * A close count that's incremented every time the stream is closed; used by
     * getCloseGuardedDispatcher() to invalidate callbacks that happen after
     * close.
     */
    this.i_ = 0, this.s_ = null, this.o_ = null, this.stream = null, /**
     * Count of response messages received.
     */
    this.__ = 0, this.a_ = new __PRIVATE_ExponentialBackoff(e2, t2);
  }
  /**
   * Returns true if start() has been called and no error has occurred. True
   * indicates the stream is open or in the process of opening (which
   * encompasses respecting backoff, getting auth tokens, and starting the
   * actual RPC). Use isOpen() to determine if the stream is open and ready for
   * outbound requests.
   */
  u_() {
    return 1 === this.state || 5 === this.state || this.c_();
  }
  /**
   * Returns true if the underlying RPC is open (the onOpen() listener has been
   * called) and the stream is ready for outbound requests.
   */
  c_() {
    return 2 === this.state || 3 === this.state;
  }
  /**
   * Starts the RPC. Only allowed if isStarted() returns false. The stream is
   * not immediately ready for use: onOpen() will be invoked when the RPC is
   * ready for outbound requests, at which point isOpen() will return true.
   *
   * When start returns, isStarted() will return true.
   */
  start() {
    this.__ = 0, 4 !== this.state ? this.auth() : this.l_();
  }
  /**
   * Stops the RPC. This call is idempotent and allowed regardless of the
   * current isStarted() state.
   *
   * When stop returns, isStarted() and isOpen() will both return false.
   */
  async stop() {
    this.u_() && await this.close(
      0
      /* PersistentStreamState.Initial */
    );
  }
  /**
   * After an error the stream will usually back off on the next attempt to
   * start it. If the error warrants an immediate restart of the stream, the
   * sender can use this to indicate that the receiver should not back off.
   *
   * Each error will call the onClose() listener. That function can decide to
   * inhibit backoff if required.
   */
  h_() {
    this.state = 0, this.a_.reset();
  }
  /**
   * Marks this stream as idle. If no further actions are performed on the
   * stream for one minute, the stream will automatically close itself and
   * notify the stream's onClose() handler with Status.OK. The stream will then
   * be in a !isStarted() state, requiring the caller to start the stream again
   * before further use.
   *
   * Only streams that are in state 'Open' can be marked idle, as all other
   * states imply pending network operations.
   */
  P_() {
    this.c_() && null === this.s_ && (this.s_ = this.Ti.enqueueAfterDelay(this.n_, 6e4, () => this.T_()));
  }
  /** Sends a message to the underlying stream. */
  I_(e2) {
    this.E_(), this.stream.send(e2);
  }
  /** Called by the idle timer when the stream should close due to inactivity. */
  async T_() {
    if (this.c_())
      return this.close(
        0
        /* PersistentStreamState.Initial */
      );
  }
  /** Marks the stream as active again. */
  E_() {
    this.s_ && (this.s_.cancel(), this.s_ = null);
  }
  /** Cancels the health check delayed operation. */
  d_() {
    this.o_ && (this.o_.cancel(), this.o_ = null);
  }
  /**
   * Closes the stream and cleans up as necessary:
   *
   * * closes the underlying GRPC stream;
   * * calls the onClose handler with the given 'error';
   * * sets internal stream state to 'finalState';
   * * adjusts the backoff timer based on the error
   *
   * A new stream can be opened by calling start().
   *
   * @param finalState - the intended state of the stream after closing.
   * @param error - the error the connection was closed with.
   */
  async close(e2, t2) {
    this.E_(), this.d_(), this.a_.cancel(), // Invalidates any stream-related callbacks (e.g. from auth or the
    // underlying stream), guaranteeing they won't execute.
    this.i_++, 4 !== e2 ? (
      // If this is an intentional close ensure we don't delay our next connection attempt.
      this.a_.reset()
    ) : t2 && t2.code === C.RESOURCE_EXHAUSTED ? (
      // Log the error. (Probably either 'quota exceeded' or 'max queue length reached'.)
      (__PRIVATE_logError(t2.toString()), __PRIVATE_logError("Using maximum backoff delay to prevent overloading the backend."), this.a_.Zo())
    ) : t2 && t2.code === C.UNAUTHENTICATED && 3 !== this.state && // "unauthenticated" error means the token was rejected. This should rarely
    // happen since both Auth and AppCheck ensure a sufficient TTL when we
    // request a token. If a user manually resets their system clock this can
    // fail, however. In this case, we should get a Code.UNAUTHENTICATED error
    // before we received the first message and we need to invalidate the token
    // to ensure that we fetch a new token.
    (this.authCredentialsProvider.invalidateToken(), this.appCheckCredentialsProvider.invalidateToken()), // Clean up the underlying stream because we are no longer interested in events.
    null !== this.stream && (this.A_(), this.stream.close(), this.stream = null), // This state must be assigned before calling onClose() to allow the callback to
    // inhibit backoff or otherwise manipulate the state in its non-started state.
    this.state = e2, // Notify the listener that the stream closed.
    await this.listener.Lo(t2);
  }
  /**
   * Can be overridden to perform additional cleanup before the stream is closed.
   * Calling super.tearDown() is not required.
   */
  A_() {
  }
  auth() {
    this.state = 1;
    const e2 = this.R_(this.i_), t2 = this.i_;
    Promise.all([this.authCredentialsProvider.getToken(), this.appCheckCredentialsProvider.getToken()]).then(([e3, n2]) => {
      this.i_ === t2 && // Normally we'd have to schedule the callback on the AsyncQueue.
      // However, the following calls are safe to be called outside the
      // AsyncQueue since they don't chain asynchronous calls
      this.V_(e3, n2);
    }, (t3) => {
      e2(() => {
        const e3 = new FirestoreError(C.UNKNOWN, "Fetching auth token failed: " + t3.message);
        return this.m_(e3);
      });
    });
  }
  V_(e2, t2) {
    const n2 = this.R_(this.i_);
    this.stream = this.f_(e2, t2), this.stream.xo(() => {
      n2(() => this.listener.xo());
    }), this.stream.No(() => {
      n2(() => (this.state = 2, this.o_ = this.Ti.enqueueAfterDelay(this.r_, 1e4, () => (this.c_() && (this.state = 3), Promise.resolve())), this.listener.No()));
    }), this.stream.Lo((e3) => {
      n2(() => this.m_(e3));
    }), this.stream.onMessage((e3) => {
      n2(() => 1 == ++this.__ ? this.g_(e3) : this.onNext(e3));
    });
  }
  l_() {
    this.state = 5, this.a_.Xo(async () => {
      this.state = 0, this.start();
    });
  }
  // Visible for tests
  m_(e2) {
    return __PRIVATE_logDebug(Gt, `close with error: ${e2}`), this.stream = null, this.close(4, e2);
  }
  /**
   * Returns a "dispatcher" function that dispatches operations onto the
   * AsyncQueue but only runs them if closeCount remains unchanged. This allows
   * us to turn auth / stream callbacks into no-ops if the stream is closed /
   * re-opened, etc.
   */
  R_(e2) {
    return (t2) => {
      this.Ti.enqueueAndForget(() => this.i_ === e2 ? t2() : (__PRIVATE_logDebug(Gt, "stream callback skipped by getCloseGuardedDispatcher."), Promise.resolve()));
    };
  }
}
class __PRIVATE_PersistentListenStream extends __PRIVATE_PersistentStream {
  static {
    __name(this, "__PRIVATE_PersistentListenStream");
  }
  constructor(e2, t2, n2, r2, i2, s2) {
    super(e2, "listen_stream_connection_backoff", "listen_stream_idle", "health_check_timeout", t2, n2, r2, s2), this.serializer = i2;
  }
  f_(e2, t2) {
    return this.connection.Wo("Listen", e2, t2);
  }
  g_(e2) {
    return this.onNext(e2);
  }
  onNext(e2) {
    this.a_.reset();
    const t2 = __PRIVATE_fromWatchChange(this.serializer, e2), n2 = (/* @__PURE__ */ __name(function __PRIVATE_versionFromListenResponse(e3) {
      if (!("targetChange" in e3)) return SnapshotVersion.min();
      const t3 = e3.targetChange;
      return t3.targetIds && t3.targetIds.length ? SnapshotVersion.min() : t3.readTime ? __PRIVATE_fromVersion(t3.readTime) : SnapshotVersion.min();
    }, "__PRIVATE_versionFromListenResponse"))(e2);
    return this.listener.p_(t2, n2);
  }
  /**
   * Registers interest in the results of the given target. If the target
   * includes a resumeToken it will be included in the request. Results that
   * affect the target will be streamed back as WatchChange messages that
   * reference the targetId.
   */
  y_(e2) {
    const t2 = {};
    t2.database = __PRIVATE_getEncodedDatabaseId(this.serializer), t2.addTarget = (/* @__PURE__ */ __name(function __PRIVATE_toTarget(e3, t3) {
      let n3;
      const r2 = t3.target;
      if (n3 = __PRIVATE_targetIsDocumentTarget(r2) ? {
        documents: __PRIVATE_toDocumentsTarget(e3, r2)
      } : {
        query: __PRIVATE_toQueryTarget(e3, r2).ht
      }, n3.targetId = t3.targetId, t3.resumeToken.approximateByteSize() > 0) {
        n3.resumeToken = __PRIVATE_toBytes(e3, t3.resumeToken);
        const r3 = __PRIVATE_toInt32Proto(e3, t3.expectedCount);
        null !== r3 && (n3.expectedCount = r3);
      } else if (t3.snapshotVersion.compareTo(SnapshotVersion.min()) > 0) {
        n3.readTime = toTimestamp(e3, t3.snapshotVersion.toTimestamp());
        const r3 = __PRIVATE_toInt32Proto(e3, t3.expectedCount);
        null !== r3 && (n3.expectedCount = r3);
      }
      return n3;
    }, "__PRIVATE_toTarget"))(this.serializer, e2);
    const n2 = __PRIVATE_toListenRequestLabels(this.serializer, e2);
    n2 && (t2.labels = n2), this.I_(t2);
  }
  /**
   * Unregisters interest in the results of the target associated with the
   * given targetId.
   */
  w_(e2) {
    const t2 = {};
    t2.database = __PRIVATE_getEncodedDatabaseId(this.serializer), t2.removeTarget = e2, this.I_(t2);
  }
}
class __PRIVATE_PersistentWriteStream extends __PRIVATE_PersistentStream {
  static {
    __name(this, "__PRIVATE_PersistentWriteStream");
  }
  constructor(e2, t2, n2, r2, i2, s2) {
    super(e2, "write_stream_connection_backoff", "write_stream_idle", "health_check_timeout", t2, n2, r2, s2), this.serializer = i2;
  }
  /**
   * Tracks whether or not a handshake has been successfully exchanged and
   * the stream is ready to accept mutations.
   */
  get S_() {
    return this.__ > 0;
  }
  // Override of PersistentStream.start
  start() {
    this.lastStreamToken = void 0, super.start();
  }
  A_() {
    this.S_ && this.b_([]);
  }
  f_(e2, t2) {
    return this.connection.Wo("Write", e2, t2);
  }
  g_(e2) {
    return __PRIVATE_hardAssert(!!e2.streamToken), this.lastStreamToken = e2.streamToken, // The first response is always the handshake response
    __PRIVATE_hardAssert(!e2.writeResults || 0 === e2.writeResults.length), this.listener.D_();
  }
  onNext(e2) {
    __PRIVATE_hardAssert(!!e2.streamToken), this.lastStreamToken = e2.streamToken, // A successful first write response means the stream is healthy,
    // Note, that we could consider a successful handshake healthy, however,
    // the write itself might be causing an error we want to back off from.
    this.a_.reset();
    const t2 = __PRIVATE_fromWriteResults(e2.writeResults, e2.commitTime), n2 = __PRIVATE_fromVersion(e2.commitTime);
    return this.listener.v_(n2, t2);
  }
  /**
   * Sends an initial streamToken to the server, performing the handshake
   * required to make the StreamingWrite RPC work. Subsequent
   * calls should wait until onHandshakeComplete was called.
   */
  C_() {
    const e2 = {};
    e2.database = __PRIVATE_getEncodedDatabaseId(this.serializer), this.I_(e2);
  }
  /** Sends a group of mutations to the Firestore backend to apply. */
  b_(e2) {
    const t2 = {
      streamToken: this.lastStreamToken,
      writes: e2.map((e3) => toMutation(this.serializer, e3))
    };
    this.I_(t2);
  }
}
/**
 * @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 Datastore {
  static {
    __name(this, "Datastore");
  }
}
class __PRIVATE_DatastoreImpl extends Datastore {
  static {
    __name(this, "__PRIVATE_DatastoreImpl");
  }
  constructor(e2, t2, n2, r2) {
    super(), this.authCredentials = e2, this.appCheckCredentials = t2, this.connection = n2, this.serializer = r2, this.F_ = false;
  }
  M_() {
    if (this.F_) throw new FirestoreError(C.FAILED_PRECONDITION, "The client has already been terminated.");
  }
  /** Invokes the provided RPC with auth and AppCheck tokens. */
  So(e2, t2, n2, r2) {
    return this.M_(), Promise.all([this.authCredentials.getToken(), this.appCheckCredentials.getToken()]).then(([i2, s2]) => this.connection.So(e2, __PRIVATE_toResourcePath(t2, n2), r2, i2, s2)).catch((e3) => {
      throw "FirebaseError" === e3.name ? (e3.code === C.UNAUTHENTICATED && (this.authCredentials.invalidateToken(), this.appCheckCredentials.invalidateToken()), e3) : new FirestoreError(C.UNKNOWN, e3.toString());
    });
  }
  /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */
  Co(e2, t2, n2, r2, i2) {
    return this.M_(), Promise.all([this.authCredentials.getToken(), this.appCheckCredentials.getToken()]).then(([s2, o2]) => this.connection.Co(e2, __PRIVATE_toResourcePath(t2, n2), r2, s2, o2, i2)).catch((e3) => {
      throw "FirebaseError" === e3.name ? (e3.code === C.UNAUTHENTICATED && (this.authCredentials.invalidateToken(), this.appCheckCredentials.invalidateToken()), e3) : new FirestoreError(C.UNKNOWN, e3.toString());
    });
  }
  terminate() {
    this.F_ = true, this.connection.terminate();
  }
}
class __PRIVATE_OnlineStateTracker {
  static {
    __name(this, "__PRIVATE_OnlineStateTracker");
  }
  constructor(e2, t2) {
    this.asyncQueue = e2, this.onlineStateHandler = t2, /** The current OnlineState. */
    this.state = "Unknown", /**
     * A count of consecutive failures to open the stream. If it reaches the
     * maximum defined by MAX_WATCH_STREAM_FAILURES, we'll set the OnlineState to
     * Offline.
     */
    this.x_ = 0, /**
     * A timer that elapses after ONLINE_STATE_TIMEOUT_MS, at which point we
     * transition from OnlineState.Unknown to OnlineState.Offline without waiting
     * for the stream to actually fail (MAX_WATCH_STREAM_FAILURES times).
     */
    this.O_ = null, /**
     * Whether the client should log a warning message if it fails to connect to
     * the backend (initially true, cleared after a successful stream, or if we've
     * logged the message already).
     */
    this.N_ = true;
  }
  /**
   * Called by RemoteStore when a watch stream is started (including on each
   * backoff attempt).
   *
   * If this is the first attempt, it sets the OnlineState to Unknown and starts
   * the onlineStateTimer.
   */
  B_() {
    0 === this.x_ && (this.L_(
      "Unknown"
      /* OnlineState.Unknown */
    ), this.O_ = this.asyncQueue.enqueueAfterDelay("online_state_timeout", 1e4, () => (this.O_ = null, this.k_("Backend didn't respond within 10 seconds."), this.L_(
      "Offline"
      /* OnlineState.Offline */
    ), Promise.resolve())));
  }
  /**
   * Updates our OnlineState as appropriate after the watch stream reports a
   * failure. The first failure moves us to the 'Unknown' state. We then may
   * allow multiple failures (based on MAX_WATCH_STREAM_FAILURES) before we
   * actually transition to the 'Offline' state.
   */
  q_(e2) {
    "Online" === this.state ? this.L_(
      "Unknown"
      /* OnlineState.Unknown */
    ) : (this.x_++, this.x_ >= 1 && (this.Q_(), this.k_(`Connection failed 1 times. Most recent error: ${e2.toString()}`), this.L_(
      "Offline"
      /* OnlineState.Offline */
    )));
  }
  /**
   * Explicitly sets the OnlineState to the specified state.
   *
   * Note that this resets our timers / failure counters, etc. used by our
   * Offline heuristics, so must not be used in place of
   * handleWatchStreamStart() and handleWatchStreamFailure().
   */
  set(e2) {
    this.Q_(), this.x_ = 0, "Online" === e2 && // We've connected to watch at least once. Don't warn the developer
    // about being offline going forward.
    (this.N_ = false), this.L_(e2);
  }
  L_(e2) {
    e2 !== this.state && (this.state = e2, this.onlineStateHandler(e2));
  }
  k_(e2) {
    const t2 = `Could not reach Cloud Firestore backend. ${e2}
This typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.`;
    this.N_ ? (__PRIVATE_logError(t2), this.N_ = false) : __PRIVATE_logDebug("OnlineStateTracker", t2);
  }
  Q_() {
    null !== this.O_ && (this.O_.cancel(), this.O_ = 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.
 */
const zt = "RemoteStore";
class __PRIVATE_RemoteStoreImpl {
  static {
    __name(this, "__PRIVATE_RemoteStoreImpl");
  }
  constructor(e2, t2, n2, r2, i2) {
    this.localStore = e2, this.datastore = t2, this.asyncQueue = n2, this.remoteSyncer = {}, /**
     * A list of up to MAX_PENDING_WRITES writes that we have fetched from the
     * LocalStore via fillWritePipeline() and have or will send to the write
     * stream.
     *
     * Whenever writePipeline.length > 0 the RemoteStore will attempt to start or
     * restart the write stream. When the stream is established the writes in the
     * pipeline will be sent in order.
     *
     * Writes remain in writePipeline until they are acknowledged by the backend
     * and thus will automatically be re-sent if the stream is interrupted /
     * restarted before they're acknowledged.
     *
     * Write responses from the backend are linked to their originating request
     * purely based on order, and so we can just shift() writes from the front of
     * the writePipeline as we receive responses.
     */
    this.U_ = [], /**
     * A mapping of watched targets that the client cares about tracking and the
     * user has explicitly called a 'listen' for this target.
     *
     * These targets may or may not have been sent to or acknowledged by the
     * server. On re-establishing the listen stream, these targets should be sent
     * to the server. The targets removed with unlistens are removed eagerly
     * without waiting for confirmation from the listen stream.
     */
    this.K_ = /* @__PURE__ */ new Map(), /**
     * A set of reasons for why the RemoteStore may be offline. If empty, the
     * RemoteStore may start its network connections.
     */
    this.W_ = /* @__PURE__ */ new Set(), /**
     * Event handlers that get called when the network is disabled or enabled.
     *
     * PORTING NOTE: These functions are used on the Web client to create the
     * underlying streams (to support tree-shakeable streams). On Android and iOS,
     * the streams are created during construction of RemoteStore.
     */
    this.G_ = [], this.z_ = i2, this.z_.To((e3) => {
      n2.enqueueAndForget(async () => {
        __PRIVATE_canUseNetwork(this) && (__PRIVATE_logDebug(zt, "Restarting streams for network reachability change."), await (/* @__PURE__ */ __name(async function __PRIVATE_restartNetwork(e4) {
          const t3 = __PRIVATE_debugCast(e4);
          t3.W_.add(
            4
            /* OfflineCause.ConnectivityChange */
          ), await __PRIVATE_disableNetworkInternal(t3), t3.j_.set(
            "Unknown"
            /* OnlineState.Unknown */
          ), t3.W_.delete(
            4
            /* OfflineCause.ConnectivityChange */
          ), await __PRIVATE_enableNetworkInternal(t3);
        }, "__PRIVATE_restartNetwork"))(this));
      });
    }), this.j_ = new __PRIVATE_OnlineStateTracker(n2, r2);
  }
}
async function __PRIVATE_enableNetworkInternal(e2) {
  if (__PRIVATE_canUseNetwork(e2)) for (const t2 of e2.G_) await t2(
    /* enabled= */
    true
  );
}
__name(__PRIVATE_enableNetworkInternal, "__PRIVATE_enableNetworkInternal");
async function __PRIVATE_disableNetworkInternal(e2) {
  for (const t2 of e2.G_) await t2(
    /* enabled= */
    false
  );
}
__name(__PRIVATE_disableNetworkInternal, "__PRIVATE_disableNetworkInternal");
function __PRIVATE_remoteStoreListen(e2, t2) {
  const n2 = __PRIVATE_debugCast(e2);
  n2.K_.has(t2.targetId) || // Mark this as something the client is currently listening for.
  (n2.K_.set(t2.targetId, t2), __PRIVATE_shouldStartWatchStream(n2) ? (
    // The listen will be sent in onWatchStreamOpen
    __PRIVATE_startWatchStream(n2)
  ) : __PRIVATE_ensureWatchStream(n2).c_() && __PRIVATE_sendWatchRequest(n2, t2));
}
__name(__PRIVATE_remoteStoreListen, "__PRIVATE_remoteStoreListen");
function __PRIVATE_remoteStoreUnlisten(e2, t2) {
  const n2 = __PRIVATE_debugCast(e2), r2 = __PRIVATE_ensureWatchStream(n2);
  n2.K_.delete(t2), r2.c_() && __PRIVATE_sendUnwatchRequest(n2, t2), 0 === n2.K_.size && (r2.c_() ? r2.P_() : __PRIVATE_canUseNetwork(n2) && // Revert to OnlineState.Unknown if the watch stream is not open and we
  // have no listeners, since without any listens to send we cannot
  // confirm if the stream is healthy and upgrade to OnlineState.Online.
  n2.j_.set(
    "Unknown"
    /* OnlineState.Unknown */
  ));
}
__name(__PRIVATE_remoteStoreUnlisten, "__PRIVATE_remoteStoreUnlisten");
function __PRIVATE_sendWatchRequest(e2, t2) {
  if (e2.H_.Ne(t2.targetId), t2.resumeToken.approximateByteSize() > 0 || t2.snapshotVersion.compareTo(SnapshotVersion.min()) > 0) {
    const n2 = e2.remoteSyncer.getRemoteKeysForTarget(t2.targetId).size;
    t2 = t2.withExpectedCount(n2);
  }
  __PRIVATE_ensureWatchStream(e2).y_(t2);
}
__name(__PRIVATE_sendWatchRequest, "__PRIVATE_sendWatchRequest");
function __PRIVATE_sendUnwatchRequest(e2, t2) {
  e2.H_.Ne(t2), __PRIVATE_ensureWatchStream(e2).w_(t2);
}
__name(__PRIVATE_sendUnwatchRequest, "__PRIVATE_sendUnwatchRequest");
function __PRIVATE_startWatchStream(e2) {
  e2.H_ = new __PRIVATE_WatchChangeAggregator({
    getRemoteKeysForTarget: /* @__PURE__ */ __name((t2) => e2.remoteSyncer.getRemoteKeysForTarget(t2), "getRemoteKeysForTarget"),
    lt: /* @__PURE__ */ __name((t2) => e2.K_.get(t2) || null, "lt"),
    it: /* @__PURE__ */ __name(() => e2.datastore.serializer.databaseId, "it")
  }), __PRIVATE_ensureWatchStream(e2).start(), e2.j_.B_();
}
__name(__PRIVATE_startWatchStream, "__PRIVATE_startWatchStream");
function __PRIVATE_shouldStartWatchStream(e2) {
  return __PRIVATE_canUseNetwork(e2) && !__PRIVATE_ensureWatchStream(e2).u_() && e2.K_.size > 0;
}
__name(__PRIVATE_shouldStartWatchStream, "__PRIVATE_shouldStartWatchStream");
function __PRIVATE_canUseNetwork(e2) {
  return 0 === __PRIVATE_debugCast(e2).W_.size;
}
__name(__PRIVATE_canUseNetwork, "__PRIVATE_canUseNetwork");
function __PRIVATE_cleanUpWatchStreamState(e2) {
  e2.H_ = void 0;
}
__name(__PRIVATE_cleanUpWatchStreamState, "__PRIVATE_cleanUpWatchStreamState");
async function __PRIVATE_onWatchStreamConnected(e2) {
  e2.j_.set(
    "Online"
    /* OnlineState.Online */
  );
}
__name(__PRIVATE_onWatchStreamConnected, "__PRIVATE_onWatchStreamConnected");
async function __PRIVATE_onWatchStreamOpen(e2) {
  e2.K_.forEach((t2, n2) => {
    __PRIVATE_sendWatchRequest(e2, t2);
  });
}
__name(__PRIVATE_onWatchStreamOpen, "__PRIVATE_onWatchStreamOpen");
async function __PRIVATE_onWatchStreamClose(e2, t2) {
  __PRIVATE_cleanUpWatchStreamState(e2), // If we still need the watch stream, retry the connection.
  __PRIVATE_shouldStartWatchStream(e2) ? (e2.j_.q_(t2), __PRIVATE_startWatchStream(e2)) : (
    // No need to restart watch stream because there are no active targets.
    // The online state is set to unknown because there is no active attempt
    // at establishing a connection
    e2.j_.set(
      "Unknown"
      /* OnlineState.Unknown */
    )
  );
}
__name(__PRIVATE_onWatchStreamClose, "__PRIVATE_onWatchStreamClose");
async function __PRIVATE_onWatchStreamChange(e2, t2, n2) {
  if (
    // Mark the client as online since we got a message from the server
    e2.j_.set(
      "Online"
      /* OnlineState.Online */
    ), t2 instanceof __PRIVATE_WatchTargetChange && 2 === t2.state && t2.cause
  )
    try {
      await (/* @__PURE__ */ __name(async function __PRIVATE_handleTargetError(e3, t3) {
        const n3 = t3.cause;
        for (const r2 of t3.targetIds)
          e3.K_.has(r2) && (await e3.remoteSyncer.rejectListen(r2, n3), e3.K_.delete(r2), e3.H_.removeTarget(r2));
      }, "__PRIVATE_handleTargetError"))(e2, t2);
    } catch (n3) {
      __PRIVATE_logDebug(zt, "Failed to remove targets %s: %s ", t2.targetIds.join(","), n3), await __PRIVATE_disableNetworkUntilRecovery(e2, n3);
    }
  else if (t2 instanceof __PRIVATE_DocumentWatchChange ? e2.H_.We(t2) : t2 instanceof __PRIVATE_ExistenceFilterChange ? e2.H_.Ze(t2) : e2.H_.je(t2), !n2.isEqual(SnapshotVersion.min())) try {
    const t3 = await __PRIVATE_localStoreGetLastRemoteSnapshotVersion(e2.localStore);
    n2.compareTo(t3) >= 0 && // We have received a target change with a global snapshot if the snapshot
    // version is not equal to SnapshotVersion.min().
    /**
    * Takes a batch of changes from the Datastore, repackages them as a
    * RemoteEvent, and passes that on to the listener, which is typically the
    * SyncEngine.
    */
    await (/* @__PURE__ */ __name(function __PRIVATE_raiseWatchSnapshot(e3, t4) {
      const n3 = e3.H_.ot(t4);
      return n3.targetChanges.forEach((n4, r2) => {
        if (n4.resumeToken.approximateByteSize() > 0) {
          const i2 = e3.K_.get(r2);
          i2 && e3.K_.set(r2, i2.withResumeToken(n4.resumeToken, t4));
        }
      }), // Re-establish listens for the targets that have been invalidated by
      // existence filter mismatches.
      n3.targetMismatches.forEach((t5, n4) => {
        const r2 = e3.K_.get(t5);
        if (!r2)
          return;
        e3.K_.set(t5, r2.withResumeToken(ByteString.EMPTY_BYTE_STRING, r2.snapshotVersion)), // Cause a hard reset by unwatching and rewatching immediately, but
        // deliberately don't send a resume token so that we get a full update.
        __PRIVATE_sendUnwatchRequest(e3, t5);
        const i2 = new TargetData(r2.target, t5, n4, r2.sequenceNumber);
        __PRIVATE_sendWatchRequest(e3, i2);
      }), e3.remoteSyncer.applyRemoteEvent(n3);
    }, "__PRIVATE_raiseWatchSnapshot"))(e2, n2);
  } catch (t3) {
    __PRIVATE_logDebug(zt, "Failed to raise snapshot:", t3), await __PRIVATE_disableNetworkUntilRecovery(e2, t3);
  }
}
__name(__PRIVATE_onWatchStreamChange, "__PRIVATE_onWatchStreamChange");
async function __PRIVATE_disableNetworkUntilRecovery(e2, t2, n2) {
  if (!__PRIVATE_isIndexedDbTransactionError(t2)) throw t2;
  e2.W_.add(
    1
    /* OfflineCause.IndexedDbFailed */
  ), // Disable network and raise offline snapshots
  await __PRIVATE_disableNetworkInternal(e2), e2.j_.set(
    "Offline"
    /* OnlineState.Offline */
  ), n2 || // Use a simple read operation to determine if IndexedDB recovered.
  // Ideally, we would expose a health check directly on SimpleDb, but
  // RemoteStore only has access to persistence through LocalStore.
  (n2 = /* @__PURE__ */ __name(() => __PRIVATE_localStoreGetLastRemoteSnapshotVersion(e2.localStore), "n")), // Probe IndexedDB periodically and re-enable network
  e2.asyncQueue.enqueueRetryable(async () => {
    __PRIVATE_logDebug(zt, "Retrying IndexedDB access"), await n2(), e2.W_.delete(
      1
      /* OfflineCause.IndexedDbFailed */
    ), await __PRIVATE_enableNetworkInternal(e2);
  });
}
__name(__PRIVATE_disableNetworkUntilRecovery, "__PRIVATE_disableNetworkUntilRecovery");
function __PRIVATE_executeWithRecovery(e2, t2) {
  return t2().catch((n2) => __PRIVATE_disableNetworkUntilRecovery(e2, n2, t2));
}
__name(__PRIVATE_executeWithRecovery, "__PRIVATE_executeWithRecovery");
async function __PRIVATE_fillWritePipeline(e2) {
  const t2 = __PRIVATE_debugCast(e2), n2 = __PRIVATE_ensureWriteStream(t2);
  let r2 = t2.U_.length > 0 ? t2.U_[t2.U_.length - 1].batchId : Q;
  for (; __PRIVATE_canAddToWritePipeline(t2); ) try {
    const e3 = await __PRIVATE_localStoreGetNextMutationBatch(t2.localStore, r2);
    if (null === e3) {
      0 === t2.U_.length && n2.P_();
      break;
    }
    r2 = e3.batchId, __PRIVATE_addToWritePipeline(t2, e3);
  } catch (e3) {
    await __PRIVATE_disableNetworkUntilRecovery(t2, e3);
  }
  __PRIVATE_shouldStartWriteStream(t2) && __PRIVATE_startWriteStream(t2);
}
__name(__PRIVATE_fillWritePipeline, "__PRIVATE_fillWritePipeline");
function __PRIVATE_canAddToWritePipeline(e2) {
  return __PRIVATE_canUseNetwork(e2) && e2.U_.length < 10;
}
__name(__PRIVATE_canAddToWritePipeline, "__PRIVATE_canAddToWritePipeline");
function __PRIVATE_addToWritePipeline(e2, t2) {
  e2.U_.push(t2);
  const n2 = __PRIVATE_ensureWriteStream(e2);
  n2.c_() && n2.S_ && n2.b_(t2.mutations);
}
__name(__PRIVATE_addToWritePipeline, "__PRIVATE_addToWritePipeline");
function __PRIVATE_shouldStartWriteStream(e2) {
  return __PRIVATE_canUseNetwork(e2) && !__PRIVATE_ensureWriteStream(e2).u_() && e2.U_.length > 0;
}
__name(__PRIVATE_shouldStartWriteStream, "__PRIVATE_shouldStartWriteStream");
function __PRIVATE_startWriteStream(e2) {
  __PRIVATE_ensureWriteStream(e2).start();
}
__name(__PRIVATE_startWriteStream, "__PRIVATE_startWriteStream");
async function __PRIVATE_onWriteStreamOpen(e2) {
  __PRIVATE_ensureWriteStream(e2).C_();
}
__name(__PRIVATE_onWriteStreamOpen, "__PRIVATE_onWriteStreamOpen");
async function __PRIVATE_onWriteHandshakeComplete(e2) {
  const t2 = __PRIVATE_ensureWriteStream(e2);
  for (const n2 of e2.U_) t2.b_(n2.mutations);
}
__name(__PRIVATE_onWriteHandshakeComplete, "__PRIVATE_onWriteHandshakeComplete");
async function __PRIVATE_onMutationResult(e2, t2, n2) {
  const r2 = e2.U_.shift(), i2 = MutationBatchResult.from(r2, t2, n2);
  await __PRIVATE_executeWithRecovery(e2, () => e2.remoteSyncer.applySuccessfulWrite(i2)), // It's possible that with the completion of this mutation another
  // slot has freed up.
  await __PRIVATE_fillWritePipeline(e2);
}
__name(__PRIVATE_onMutationResult, "__PRIVATE_onMutationResult");
async function __PRIVATE_onWriteStreamClose(e2, t2) {
  t2 && __PRIVATE_ensureWriteStream(e2).S_ && // This error affects the actual write.
  await (/* @__PURE__ */ __name(async function __PRIVATE_handleWriteError(e3, t3) {
    if ((/* @__PURE__ */ __name(function __PRIVATE_isPermanentWriteError(e4) {
      return __PRIVATE_isPermanentError(e4) && e4 !== C.ABORTED;
    }, "__PRIVATE_isPermanentWriteError"))(t3.code)) {
      const n2 = e3.U_.shift();
      __PRIVATE_ensureWriteStream(e3).h_(), await __PRIVATE_executeWithRecovery(e3, () => e3.remoteSyncer.rejectFailedWrite(n2.batchId, t3)), // It's possible that with the completion of this mutation
      // another slot has freed up.
      await __PRIVATE_fillWritePipeline(e3);
    }
  }, "__PRIVATE_handleWriteError"))(e2, t2), // The write stream might have been started by refilling the write
  // pipeline for failed writes
  __PRIVATE_shouldStartWriteStream(e2) && __PRIVATE_startWriteStream(e2);
}
__name(__PRIVATE_onWriteStreamClose, "__PRIVATE_onWriteStreamClose");
async function __PRIVATE_remoteStoreHandleCredentialChange(e2, t2) {
  const n2 = __PRIVATE_debugCast(e2);
  n2.asyncQueue.verifyOperationInProgress(), __PRIVATE_logDebug(zt, "RemoteStore received new credentials");
  const r2 = __PRIVATE_canUseNetwork(n2);
  n2.W_.add(
    3
    /* OfflineCause.CredentialChange */
  ), await __PRIVATE_disableNetworkInternal(n2), r2 && // Don't set the network status to Unknown if we are offline.
  n2.j_.set(
    "Unknown"
    /* OnlineState.Unknown */
  ), await n2.remoteSyncer.handleCredentialChange(t2), n2.W_.delete(
    3
    /* OfflineCause.CredentialChange */
  ), await __PRIVATE_enableNetworkInternal(n2);
}
__name(__PRIVATE_remoteStoreHandleCredentialChange, "__PRIVATE_remoteStoreHandleCredentialChange");
async function __PRIVATE_remoteStoreApplyPrimaryState(e2, t2) {
  const n2 = __PRIVATE_debugCast(e2);
  t2 ? (n2.W_.delete(
    2
    /* OfflineCause.IsSecondary */
  ), await __PRIVATE_enableNetworkInternal(n2)) : t2 || (n2.W_.add(
    2
    /* OfflineCause.IsSecondary */
  ), await __PRIVATE_disableNetworkInternal(n2), n2.j_.set(
    "Unknown"
    /* OnlineState.Unknown */
  ));
}
__name(__PRIVATE_remoteStoreApplyPrimaryState, "__PRIVATE_remoteStoreApplyPrimaryState");
function __PRIVATE_ensureWatchStream(e2) {
  return e2.J_ || // Create stream (but note that it is not started yet).
  (e2.J_ = (/* @__PURE__ */ __name(function __PRIVATE_newPersistentWatchStream(e3, t2, n2) {
    const r2 = __PRIVATE_debugCast(e3);
    return r2.M_(), new __PRIVATE_PersistentListenStream(t2, r2.connection, r2.authCredentials, r2.appCheckCredentials, r2.serializer, n2);
  }, "__PRIVATE_newPersistentWatchStream"))(e2.datastore, e2.asyncQueue, {
    xo: __PRIVATE_onWatchStreamConnected.bind(null, e2),
    No: __PRIVATE_onWatchStreamOpen.bind(null, e2),
    Lo: __PRIVATE_onWatchStreamClose.bind(null, e2),
    p_: __PRIVATE_onWatchStreamChange.bind(null, e2)
  }), e2.G_.push(async (t2) => {
    t2 ? (e2.J_.h_(), __PRIVATE_shouldStartWatchStream(e2) ? __PRIVATE_startWatchStream(e2) : e2.j_.set(
      "Unknown"
      /* OnlineState.Unknown */
    )) : (await e2.J_.stop(), __PRIVATE_cleanUpWatchStreamState(e2));
  })), e2.J_;
}
__name(__PRIVATE_ensureWatchStream, "__PRIVATE_ensureWatchStream");
function __PRIVATE_ensureWriteStream(e2) {
  return e2.Y_ || // Create stream (but note that it is not started yet).
  (e2.Y_ = (/* @__PURE__ */ __name(function __PRIVATE_newPersistentWriteStream(e3, t2, n2) {
    const r2 = __PRIVATE_debugCast(e3);
    return r2.M_(), new __PRIVATE_PersistentWriteStream(t2, r2.connection, r2.authCredentials, r2.appCheckCredentials, r2.serializer, n2);
  }, "__PRIVATE_newPersistentWriteStream"))(e2.datastore, e2.asyncQueue, {
    xo: /* @__PURE__ */ __name(() => Promise.resolve(), "xo"),
    No: __PRIVATE_onWriteStreamOpen.bind(null, e2),
    Lo: __PRIVATE_onWriteStreamClose.bind(null, e2),
    D_: __PRIVATE_onWriteHandshakeComplete.bind(null, e2),
    v_: __PRIVATE_onMutationResult.bind(null, e2)
  }), e2.G_.push(async (t2) => {
    t2 ? (e2.Y_.h_(), // This will start the write stream if necessary.
    await __PRIVATE_fillWritePipeline(e2)) : (await e2.Y_.stop(), e2.U_.length > 0 && (__PRIVATE_logDebug(zt, `Stopping write stream with ${e2.U_.length} pending writes`), e2.U_ = []));
  })), e2.Y_;
}
__name(__PRIVATE_ensureWriteStream, "__PRIVATE_ensureWriteStream");
/**
 * @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 DelayedOperation {
  static {
    __name(this, "DelayedOperation");
  }
  constructor(e2, t2, n2, r2, i2) {
    this.asyncQueue = e2, this.timerId = t2, this.targetTimeMs = n2, this.op = r2, this.removalCallback = i2, this.deferred = new __PRIVATE_Deferred(), this.then = this.deferred.promise.then.bind(this.deferred.promise), // It's normal for the deferred promise to be canceled (due to cancellation)
    // and so we attach a dummy catch callback to avoid
    // 'UnhandledPromiseRejectionWarning' log spam.
    this.deferred.promise.catch((e3) => {
    });
  }
  get promise() {
    return this.deferred.promise;
  }
  /**
   * Creates and returns a DelayedOperation that has been scheduled to be
   * executed on the provided asyncQueue after the provided delayMs.
   *
   * @param asyncQueue - The queue to schedule the operation on.
   * @param id - A Timer ID identifying the type of operation this is.
   * @param delayMs - The delay (ms) before the operation should be scheduled.
   * @param op - The operation to run.
   * @param removalCallback - A callback to be called synchronously once the
   *   operation is executed or canceled, notifying the AsyncQueue to remove it
   *   from its delayedOperations list.
   *   PORTING NOTE: This exists to prevent making removeDelayedOperation() and
   *   the DelayedOperation class public.
   */
  static createAndSchedule(e2, t2, n2, r2, i2) {
    const s2 = Date.now() + n2, o2 = new DelayedOperation(e2, t2, s2, r2, i2);
    return o2.start(n2), o2;
  }
  /**
   * Starts the timer. This is called immediately after construction by
   * createAndSchedule().
   */
  start(e2) {
    this.timerHandle = setTimeout(() => this.handleDelayElapsed(), e2);
  }
  /**
   * Queues the operation to run immediately (if it hasn't already been run or
   * canceled).
   */
  skipDelay() {
    return this.handleDelayElapsed();
  }
  /**
   * Cancels the operation if it hasn't already been executed or canceled. The
   * promise will be rejected.
   *
   * As long as the operation has not yet been run, calling cancel() provides a
   * guarantee that the operation will not be run.
   */
  cancel(e2) {
    null !== this.timerHandle && (this.clearTimeout(), this.deferred.reject(new FirestoreError(C.CANCELLED, "Operation cancelled" + (e2 ? ": " + e2 : ""))));
  }
  handleDelayElapsed() {
    this.asyncQueue.enqueueAndForget(() => null !== this.timerHandle ? (this.clearTimeout(), this.op().then((e2) => this.deferred.resolve(e2))) : Promise.resolve());
  }
  clearTimeout() {
    null !== this.timerHandle && (this.removalCallback(this), clearTimeout(this.timerHandle), this.timerHandle = null);
  }
}
function __PRIVATE_wrapInUserErrorIfRecoverable(e2, t2) {
  if (__PRIVATE_logError("AsyncQueue", `${t2}: ${e2}`), __PRIVATE_isIndexedDbTransactionError(e2)) return new FirestoreError(C.UNAVAILABLE, `${t2}: ${e2}`);
  throw e2;
}
__name(__PRIVATE_wrapInUserErrorIfRecoverable, "__PRIVATE_wrapInUserErrorIfRecoverable");
/**
 * @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 DocumentSet {
  static {
    __name(this, "DocumentSet");
  }
  /**
   * Returns an empty copy of the existing DocumentSet, using the same
   * comparator.
   */
  static emptySet(e2) {
    return new DocumentSet(e2.comparator);
  }
  /** The default ordering is by key if the comparator is omitted */
  constructor(e2) {
    this.comparator = e2 ? (t2, n2) => e2(t2, n2) || DocumentKey.comparator(t2.key, n2.key) : (e3, t2) => DocumentKey.comparator(e3.key, t2.key), this.keyedMap = documentMap(), this.sortedSet = new SortedMap(this.comparator);
  }
  has(e2) {
    return null != this.keyedMap.get(e2);
  }
  get(e2) {
    return this.keyedMap.get(e2);
  }
  first() {
    return this.sortedSet.minKey();
  }
  last() {
    return this.sortedSet.maxKey();
  }
  isEmpty() {
    return this.sortedSet.isEmpty();
  }
  /**
   * Returns the index of the provided key in the document set, or -1 if the
   * document key is not present in the set;
   */
  indexOf(e2) {
    const t2 = this.keyedMap.get(e2);
    return t2 ? this.sortedSet.indexOf(t2) : -1;
  }
  get size() {
    return this.sortedSet.size;
  }
  /** Iterates documents in order defined by "comparator" */
  forEach(e2) {
    this.sortedSet.inorderTraversal((t2, n2) => (e2(t2), false));
  }
  /** Inserts or updates a document with the same key */
  add(e2) {
    const t2 = this.delete(e2.key);
    return t2.copy(t2.keyedMap.insert(e2.key, e2), t2.sortedSet.insert(e2, null));
  }
  /** Deletes a document with a given key */
  delete(e2) {
    const t2 = this.get(e2);
    return t2 ? this.copy(this.keyedMap.remove(e2), this.sortedSet.remove(t2)) : this;
  }
  isEqual(e2) {
    if (!(e2 instanceof DocumentSet)) return false;
    if (this.size !== e2.size) return false;
    const t2 = this.sortedSet.getIterator(), n2 = e2.sortedSet.getIterator();
    for (; t2.hasNext(); ) {
      const e3 = t2.getNext().key, r2 = n2.getNext().key;
      if (!e3.isEqual(r2)) return false;
    }
    return true;
  }
  toString() {
    const e2 = [];
    return this.forEach((t2) => {
      e2.push(t2.toString());
    }), 0 === e2.length ? "DocumentSet ()" : "DocumentSet (\n  " + e2.join("  \n") + "\n)";
  }
  copy(e2, t2) {
    const n2 = new DocumentSet();
    return n2.comparator = this.comparator, n2.keyedMap = e2, n2.sortedSet = t2, n2;
  }
}
/**
 * @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 __PRIVATE_DocumentChangeSet {
  static {
    __name(this, "__PRIVATE_DocumentChangeSet");
  }
  constructor() {
    this.Z_ = new SortedMap(DocumentKey.comparator);
  }
  track(e2) {
    const t2 = e2.doc.key, n2 = this.Z_.get(t2);
    n2 ? (
      // Merge the new change with the existing change.
      0 !== e2.type && 3 === n2.type ? this.Z_ = this.Z_.insert(t2, e2) : 3 === e2.type && 1 !== n2.type ? this.Z_ = this.Z_.insert(t2, {
        type: n2.type,
        doc: e2.doc
      }) : 2 === e2.type && 2 === n2.type ? this.Z_ = this.Z_.insert(t2, {
        type: 2,
        doc: e2.doc
      }) : 2 === e2.type && 0 === n2.type ? this.Z_ = this.Z_.insert(t2, {
        type: 0,
        doc: e2.doc
      }) : 1 === e2.type && 0 === n2.type ? this.Z_ = this.Z_.remove(t2) : 1 === e2.type && 2 === n2.type ? this.Z_ = this.Z_.insert(t2, {
        type: 1,
        doc: n2.doc
      }) : 0 === e2.type && 1 === n2.type ? this.Z_ = this.Z_.insert(t2, {
        type: 2,
        doc: e2.doc
      }) : (
        // This includes these cases, which don't make sense:
        // Added->Added
        // Removed->Removed
        // Modified->Added
        // Removed->Modified
        // Metadata->Added
        // Removed->Metadata
        fail()
      )
    ) : this.Z_ = this.Z_.insert(t2, e2);
  }
  X_() {
    const e2 = [];
    return this.Z_.inorderTraversal((t2, n2) => {
      e2.push(n2);
    }), e2;
  }
}
class ViewSnapshot {
  static {
    __name(this, "ViewSnapshot");
  }
  constructor(e2, t2, n2, r2, i2, s2, o2, _2, a2) {
    this.query = e2, this.docs = t2, this.oldDocs = n2, this.docChanges = r2, this.mutatedKeys = i2, this.fromCache = s2, this.syncStateChanged = o2, this.excludesMetadataChanges = _2, this.hasCachedResults = a2;
  }
  /** Returns a view snapshot as if all documents in the snapshot were added. */
  static fromInitialDocuments(e2, t2, n2, r2, i2) {
    const s2 = [];
    return t2.forEach((e3) => {
      s2.push({
        type: 0,
        doc: e3
      });
    }), new ViewSnapshot(
      e2,
      t2,
      DocumentSet.emptySet(t2),
      s2,
      n2,
      r2,
      /* syncStateChanged= */
      true,
      /* excludesMetadataChanges= */
      false,
      i2
    );
  }
  get hasPendingWrites() {
    return !this.mutatedKeys.isEmpty();
  }
  isEqual(e2) {
    if (!(this.fromCache === e2.fromCache && this.hasCachedResults === e2.hasCachedResults && this.syncStateChanged === e2.syncStateChanged && this.mutatedKeys.isEqual(e2.mutatedKeys) && __PRIVATE_queryEquals(this.query, e2.query) && this.docs.isEqual(e2.docs) && this.oldDocs.isEqual(e2.oldDocs))) return false;
    const t2 = this.docChanges, n2 = e2.docChanges;
    if (t2.length !== n2.length) return false;
    for (let e3 = 0; e3 < t2.length; e3++) if (t2[e3].type !== n2[e3].type || !t2[e3].doc.isEqual(n2[e3].doc)) return false;
    return 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 __PRIVATE_QueryListenersInfo {
  static {
    __name(this, "__PRIVATE_QueryListenersInfo");
  }
  constructor() {
    this.ea = void 0, this.ta = [];
  }
  // Helper methods that checks if the query has listeners that listening to remote store
  na() {
    return this.ta.some((e2) => e2.ra());
  }
}
class __PRIVATE_EventManagerImpl {
  static {
    __name(this, "__PRIVATE_EventManagerImpl");
  }
  constructor() {
    this.queries = __PRIVATE_newQueriesObjectMap(), this.onlineState = "Unknown", this.ia = /* @__PURE__ */ new Set();
  }
  terminate() {
    !(/* @__PURE__ */ __name(function __PRIVATE_errorAllTargets(e2, t2) {
      const n2 = __PRIVATE_debugCast(e2), r2 = n2.queries;
      n2.queries = __PRIVATE_newQueriesObjectMap(), r2.forEach((e3, n3) => {
        for (const e4 of n3.ta) e4.onError(t2);
      });
    }, "__PRIVATE_errorAllTargets"))(this, new FirestoreError(C.ABORTED, "Firestore shutting down"));
  }
}
function __PRIVATE_newQueriesObjectMap() {
  return new ObjectMap((e2) => __PRIVATE_canonifyQuery(e2), __PRIVATE_queryEquals);
}
__name(__PRIVATE_newQueriesObjectMap, "__PRIVATE_newQueriesObjectMap");
async function __PRIVATE_eventManagerListen(e2, t2) {
  const n2 = __PRIVATE_debugCast(e2);
  let r2 = 3;
  const i2 = t2.query;
  let s2 = n2.queries.get(i2);
  s2 ? !s2.na() && t2.ra() && // Query has been listening to local cache, and tries to add a new listener sourced from watch.
  (r2 = 2) : (s2 = new __PRIVATE_QueryListenersInfo(), r2 = t2.ra() ? 0 : 1);
  try {
    switch (r2) {
      case 0:
        s2.ea = await n2.onListen(
          i2,
          /** enableRemoteListen= */
          true
        );
        break;
      case 1:
        s2.ea = await n2.onListen(
          i2,
          /** enableRemoteListen= */
          false
        );
        break;
      case 2:
        await n2.onFirstRemoteStoreListen(i2);
    }
  } catch (e3) {
    const n3 = __PRIVATE_wrapInUserErrorIfRecoverable(e3, `Initialization of query '${__PRIVATE_stringifyQuery(t2.query)}' failed`);
    return void t2.onError(n3);
  }
  if (n2.queries.set(i2, s2), s2.ta.push(t2), // Run global snapshot listeners if a consistent snapshot has been emitted.
  t2.sa(n2.onlineState), s2.ea) {
    t2.oa(s2.ea) && __PRIVATE_raiseSnapshotsInSyncEvent(n2);
  }
}
__name(__PRIVATE_eventManagerListen, "__PRIVATE_eventManagerListen");
async function __PRIVATE_eventManagerUnlisten(e2, t2) {
  const n2 = __PRIVATE_debugCast(e2), r2 = t2.query;
  let i2 = 3;
  const s2 = n2.queries.get(r2);
  if (s2) {
    const e3 = s2.ta.indexOf(t2);
    e3 >= 0 && (s2.ta.splice(e3, 1), 0 === s2.ta.length ? i2 = t2.ra() ? 0 : 1 : !s2.na() && t2.ra() && // The removed listener is the last one that sourced from watch.
    (i2 = 2));
  }
  switch (i2) {
    case 0:
      return n2.queries.delete(r2), n2.onUnlisten(
        r2,
        /** disableRemoteListen= */
        true
      );
    case 1:
      return n2.queries.delete(r2), n2.onUnlisten(
        r2,
        /** disableRemoteListen= */
        false
      );
    case 2:
      return n2.onLastRemoteStoreUnlisten(r2);
    default:
      return;
  }
}
__name(__PRIVATE_eventManagerUnlisten, "__PRIVATE_eventManagerUnlisten");
function __PRIVATE_eventManagerOnWatchChange(e2, t2) {
  const n2 = __PRIVATE_debugCast(e2);
  let r2 = false;
  for (const e3 of t2) {
    const t3 = e3.query, i2 = n2.queries.get(t3);
    if (i2) {
      for (const t4 of i2.ta) t4.oa(e3) && (r2 = true);
      i2.ea = e3;
    }
  }
  r2 && __PRIVATE_raiseSnapshotsInSyncEvent(n2);
}
__name(__PRIVATE_eventManagerOnWatchChange, "__PRIVATE_eventManagerOnWatchChange");
function __PRIVATE_eventManagerOnWatchError(e2, t2, n2) {
  const r2 = __PRIVATE_debugCast(e2), i2 = r2.queries.get(t2);
  if (i2) for (const e3 of i2.ta) e3.onError(n2);
  r2.queries.delete(t2);
}
__name(__PRIVATE_eventManagerOnWatchError, "__PRIVATE_eventManagerOnWatchError");
function __PRIVATE_raiseSnapshotsInSyncEvent(e2) {
  e2.ia.forEach((e3) => {
    e3.next();
  });
}
__name(__PRIVATE_raiseSnapshotsInSyncEvent, "__PRIVATE_raiseSnapshotsInSyncEvent");
var jt, Ht;
(Ht = jt || (jt = {}))._a = "default", /** Listen to changes in cache only */
Ht.Cache = "cache";
class __PRIVATE_QueryListener {
  static {
    __name(this, "__PRIVATE_QueryListener");
  }
  constructor(e2, t2, n2) {
    this.query = e2, this.aa = t2, /**
     * Initial snapshots (e.g. from cache) may not be propagated to the wrapped
     * observer. This flag is set to true once we've actually raised an event.
     */
    this.ua = false, this.ca = null, this.onlineState = "Unknown", this.options = n2 || {};
  }
  /**
   * Applies the new ViewSnapshot to this listener, raising a user-facing event
   * if applicable (depending on what changed, whether the user has opted into
   * metadata-only changes, etc.). Returns true if a user-facing event was
   * indeed raised.
   */
  oa(e2) {
    if (!this.options.includeMetadataChanges) {
      const t3 = [];
      for (const n2 of e2.docChanges) 3 !== n2.type && t3.push(n2);
      e2 = new ViewSnapshot(
        e2.query,
        e2.docs,
        e2.oldDocs,
        t3,
        e2.mutatedKeys,
        e2.fromCache,
        e2.syncStateChanged,
        /* excludesMetadataChanges= */
        true,
        e2.hasCachedResults
      );
    }
    let t2 = false;
    return this.ua ? this.la(e2) && (this.aa.next(e2), t2 = true) : this.ha(e2, this.onlineState) && (this.Pa(e2), t2 = true), this.ca = e2, t2;
  }
  onError(e2) {
    this.aa.error(e2);
  }
  /** Returns whether a snapshot was raised. */
  sa(e2) {
    this.onlineState = e2;
    let t2 = false;
    return this.ca && !this.ua && this.ha(this.ca, e2) && (this.Pa(this.ca), t2 = true), t2;
  }
  ha(e2, t2) {
    if (!e2.fromCache) return true;
    if (!this.ra()) return true;
    const n2 = "Offline" !== t2;
    return (!this.options.Ta || !n2) && (!e2.docs.isEmpty() || e2.hasCachedResults || "Offline" === t2);
  }
  la(e2) {
    if (e2.docChanges.length > 0) return true;
    const t2 = this.ca && this.ca.hasPendingWrites !== e2.hasPendingWrites;
    return !(!e2.syncStateChanged && !t2) && true === this.options.includeMetadataChanges;
  }
  Pa(e2) {
    e2 = ViewSnapshot.fromInitialDocuments(e2.query, e2.docs, e2.mutatedKeys, e2.fromCache, e2.hasCachedResults), this.ua = true, this.aa.next(e2);
  }
  ra() {
    return this.options.source !== jt.Cache;
  }
}
/**
 * @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 __PRIVATE_SizedBundleElement {
  static {
    __name(this, "__PRIVATE_SizedBundleElement");
  }
  constructor(e2, t2) {
    this.Ia = e2, this.byteLength = t2;
  }
  Ea() {
    return "metadata" in this.Ia;
  }
}
/**
 * @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 __PRIVATE_BundleConverterImpl {
  static {
    __name(this, "__PRIVATE_BundleConverterImpl");
  }
  constructor(e2) {
    this.serializer = e2;
  }
  ps(e2) {
    return fromName(this.serializer, e2);
  }
  /**
   * Converts a BundleDocument to a MutableDocument.
   */
  ys(e2) {
    return e2.metadata.exists ? __PRIVATE_fromDocument(this.serializer, e2.document, false) : MutableDocument.newNoDocument(this.ps(e2.metadata.name), this.ws(e2.metadata.readTime));
  }
  ws(e2) {
    return __PRIVATE_fromVersion(e2);
  }
}
class __PRIVATE_BundleLoader {
  static {
    __name(this, "__PRIVATE_BundleLoader");
  }
  constructor(e2, t2, n2) {
    this.da = e2, this.localStore = t2, this.serializer = n2, /** Batched queries to be saved into storage */
    this.queries = [], /** Batched documents to be saved into storage */
    this.documents = [], /** The collection groups affected by this bundle. */
    this.collectionGroups = /* @__PURE__ */ new Set(), this.progress = __PRIVATE_bundleInitialProgress(e2);
  }
  /**
   * Adds an element from the bundle to the loader.
   *
   * Returns a new progress if adding the element leads to a new progress,
   * otherwise returns null.
   */
  Aa(e2) {
    this.progress.bytesLoaded += e2.byteLength;
    let t2 = this.progress.documentsLoaded;
    if (e2.Ia.namedQuery) this.queries.push(e2.Ia.namedQuery);
    else if (e2.Ia.documentMetadata) {
      this.documents.push({
        metadata: e2.Ia.documentMetadata
      }), e2.Ia.documentMetadata.exists || ++t2;
      const n2 = ResourcePath.fromString(e2.Ia.documentMetadata.name);
      this.collectionGroups.add(n2.get(n2.length - 2));
    } else e2.Ia.document && (this.documents[this.documents.length - 1].document = e2.Ia.document, ++t2);
    return t2 !== this.progress.documentsLoaded ? (this.progress.documentsLoaded = t2, Object.assign({}, this.progress)) : null;
  }
  Ra(e2) {
    const t2 = /* @__PURE__ */ new Map(), n2 = new __PRIVATE_BundleConverterImpl(this.serializer);
    for (const r2 of e2) if (r2.metadata.queries) {
      const e3 = n2.ps(r2.metadata.name);
      for (const n3 of r2.metadata.queries) {
        const r3 = (t2.get(n3) || __PRIVATE_documentKeySet()).add(e3);
        t2.set(n3, r3);
      }
    }
    return t2;
  }
  /**
   * Update the progress to 'Success' and return the updated progress.
   */
  async complete() {
    const e2 = await __PRIVATE_localStoreApplyBundledDocuments(this.localStore, new __PRIVATE_BundleConverterImpl(this.serializer), this.documents, this.da.id), t2 = this.Ra(this.documents);
    for (const e3 of this.queries) await __PRIVATE_localStoreSaveNamedQuery(this.localStore, e3, t2.get(e3.name));
    return this.progress.taskState = "Success", {
      progress: this.progress,
      Va: this.collectionGroups,
      ma: e2
    };
  }
}
function __PRIVATE_bundleInitialProgress(e2) {
  return {
    taskState: "Running",
    documentsLoaded: 0,
    bytesLoaded: 0,
    totalDocuments: e2.totalDocuments,
    totalBytes: e2.totalBytes
  };
}
__name(__PRIVATE_bundleInitialProgress, "__PRIVATE_bundleInitialProgress");
/**
 * @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 __PRIVATE_AddedLimboDocument {
  static {
    __name(this, "__PRIVATE_AddedLimboDocument");
  }
  constructor(e2) {
    this.key = e2;
  }
}
class __PRIVATE_RemovedLimboDocument {
  static {
    __name(this, "__PRIVATE_RemovedLimboDocument");
  }
  constructor(e2) {
    this.key = e2;
  }
}
class __PRIVATE_View {
  static {
    __name(this, "__PRIVATE_View");
  }
  constructor(e2, t2) {
    this.query = e2, this.fa = t2, this.ga = null, this.hasCachedResults = false, /**
     * A flag whether the view is current with the backend. A view is considered
     * current after it has seen the current flag from the backend and did not
     * lose consistency within the watch stream (e.g. because of an existence
     * filter mismatch).
     */
    this.current = false, /** Documents in the view but not in the remote target */
    this.pa = __PRIVATE_documentKeySet(), /** Document Keys that have local changes */
    this.mutatedKeys = __PRIVATE_documentKeySet(), this.ya = __PRIVATE_newQueryComparator(e2), this.wa = new DocumentSet(this.ya);
  }
  /**
   * The set of remote documents that the server has told us belongs to the target associated with
   * this view.
   */
  get Sa() {
    return this.fa;
  }
  /**
   * Iterates over a set of doc changes, applies the query limit, and computes
   * what the new results should be, what the changes were, and whether we may
   * need to go back to the local cache for more results. Does not make any
   * changes to the view.
   * @param docChanges - The doc changes to apply to this view.
   * @param previousChanges - If this is being called with a refill, then start
   *        with this set of docs and changes instead of the current view.
   * @returns a new set of docs, changes, and refill flag.
   */
  ba(e2, t2) {
    const n2 = t2 ? t2.Da : new __PRIVATE_DocumentChangeSet(), r2 = t2 ? t2.wa : this.wa;
    let i2 = t2 ? t2.mutatedKeys : this.mutatedKeys, s2 = r2, o2 = false;
    const _2 = "F" === this.query.limitType && r2.size === this.query.limit ? r2.last() : null, a2 = "L" === this.query.limitType && r2.size === this.query.limit ? r2.first() : null;
    if (e2.inorderTraversal((e3, t3) => {
      const u2 = r2.get(e3), c2 = __PRIVATE_queryMatches(this.query, t3) ? t3 : null, l2 = !!u2 && this.mutatedKeys.has(u2.key), h2 = !!c2 && (c2.hasLocalMutations || // We only consider committed mutations for documents that were
      // mutated during the lifetime of the view.
      this.mutatedKeys.has(c2.key) && c2.hasCommittedMutations);
      let P2 = false;
      if (u2 && c2) {
        u2.data.isEqual(c2.data) ? l2 !== h2 && (n2.track({
          type: 3,
          doc: c2
        }), P2 = true) : this.va(u2, c2) || (n2.track({
          type: 2,
          doc: c2
        }), P2 = true, (_2 && this.ya(c2, _2) > 0 || a2 && this.ya(c2, a2) < 0) && // This doc moved from inside the limit to outside the limit.
        // That means there may be some other doc in the local cache
        // that should be included instead.
        (o2 = true));
      } else !u2 && c2 ? (n2.track({
        type: 0,
        doc: c2
      }), P2 = true) : u2 && !c2 && (n2.track({
        type: 1,
        doc: u2
      }), P2 = true, (_2 || a2) && // A doc was removed from a full limit query. We'll need to
      // requery from the local cache to see if we know about some other
      // doc that should be in the results.
      (o2 = true));
      P2 && (c2 ? (s2 = s2.add(c2), i2 = h2 ? i2.add(e3) : i2.delete(e3)) : (s2 = s2.delete(e3), i2 = i2.delete(e3)));
    }), null !== this.query.limit) for (; s2.size > this.query.limit; ) {
      const e3 = "F" === this.query.limitType ? s2.last() : s2.first();
      s2 = s2.delete(e3.key), i2 = i2.delete(e3.key), n2.track({
        type: 1,
        doc: e3
      });
    }
    return {
      wa: s2,
      Da: n2,
      ls: o2,
      mutatedKeys: i2
    };
  }
  va(e2, t2) {
    return e2.hasLocalMutations && t2.hasCommittedMutations && !t2.hasLocalMutations;
  }
  /**
   * Updates the view with the given ViewDocumentChanges and optionally updates
   * limbo docs and sync state from the provided target change.
   * @param docChanges - The set of changes to make to the view's docs.
   * @param limboResolutionEnabled - Whether to update limbo documents based on
   *        this change.
   * @param targetChange - A target change to apply for computing limbo docs and
   *        sync state.
   * @param targetIsPendingReset - Whether the target is pending to reset due to
   *        existence filter mismatch. If not explicitly specified, it is treated
   *        equivalently to `false`.
   * @returns A new ViewChange with the given docs, changes, and sync state.
   */
  // PORTING NOTE: The iOS/Android clients always compute limbo document changes.
  applyChanges(e2, t2, n2, r2) {
    const i2 = this.wa;
    this.wa = e2.wa, this.mutatedKeys = e2.mutatedKeys;
    const s2 = e2.Da.X_();
    s2.sort((e3, t3) => (/* @__PURE__ */ __name(function __PRIVATE_compareChangeType(e4, t4) {
      const order = /* @__PURE__ */ __name((e5) => {
        switch (e5) {
          case 0:
            return 1;
          case 2:
          case 3:
            return 2;
          case 1:
            return 0;
          default:
            return fail();
        }
      }, "order");
      return order(e4) - order(t4);
    }, "__PRIVATE_compareChangeType"))(e3.type, t3.type) || this.ya(e3.doc, t3.doc)), this.Ca(n2), r2 = null != r2 && r2;
    const o2 = t2 && !r2 ? this.Fa() : [], _2 = 0 === this.pa.size && this.current && !r2 ? 1 : 0, a2 = _2 !== this.ga;
    if (this.ga = _2, 0 !== s2.length || a2) {
      return {
        snapshot: new ViewSnapshot(
          this.query,
          e2.wa,
          i2,
          s2,
          e2.mutatedKeys,
          0 === _2,
          a2,
          /* excludesMetadataChanges= */
          false,
          !!n2 && n2.resumeToken.approximateByteSize() > 0
        ),
        Ma: o2
      };
    }
    return {
      Ma: o2
    };
  }
  /**
   * Applies an OnlineState change to the view, potentially generating a
   * ViewChange if the view's syncState changes as a result.
   */
  sa(e2) {
    return this.current && "Offline" === e2 ? (
      // If we're offline, set `current` to false and then call applyChanges()
      // to refresh our syncState and generate a ViewChange as appropriate. We
      // are guaranteed to get a new TargetChange that sets `current` back to
      // true once the client is back online.
      (this.current = false, this.applyChanges(
        {
          wa: this.wa,
          Da: new __PRIVATE_DocumentChangeSet(),
          mutatedKeys: this.mutatedKeys,
          ls: false
        },
        /* limboResolutionEnabled= */
        false
      ))
    ) : {
      Ma: []
    };
  }
  /**
   * Returns whether the doc for the given key should be in limbo.
   */
  xa(e2) {
    return !this.fa.has(e2) && // The local store doesn't think it's a result, so it shouldn't be in limbo.
    (!!this.wa.has(e2) && !this.wa.get(e2).hasLocalMutations);
  }
  /**
   * Updates syncedDocuments, current, and limbo docs based on the given change.
   * Returns the list of changes to which docs are in limbo.
   */
  Ca(e2) {
    e2 && (e2.addedDocuments.forEach((e3) => this.fa = this.fa.add(e3)), e2.modifiedDocuments.forEach((e3) => {
    }), e2.removedDocuments.forEach((e3) => this.fa = this.fa.delete(e3)), this.current = e2.current);
  }
  Fa() {
    if (!this.current) return [];
    const e2 = this.pa;
    this.pa = __PRIVATE_documentKeySet(), this.wa.forEach((e3) => {
      this.xa(e3.key) && (this.pa = this.pa.add(e3.key));
    });
    const t2 = [];
    return e2.forEach((e3) => {
      this.pa.has(e3) || t2.push(new __PRIVATE_RemovedLimboDocument(e3));
    }), this.pa.forEach((n2) => {
      e2.has(n2) || t2.push(new __PRIVATE_AddedLimboDocument(n2));
    }), t2;
  }
  /**
   * Update the in-memory state of the current view with the state read from
   * persistence.
   *
   * We update the query view whenever a client's primary status changes:
   * - When a client transitions from primary to secondary, it can miss
   *   LocalStorage updates and its query views may temporarily not be
   *   synchronized with the state on disk.
   * - For secondary to primary transitions, the client needs to update the list
   *   of `syncedDocuments` since secondary clients update their query views
   *   based purely on synthesized RemoteEvents.
   *
   * @param queryResult.documents - The documents that match the query according
   * to the LocalStore.
   * @param queryResult.remoteKeys - The keys of the documents that match the
   * query according to the backend.
   *
   * @returns The ViewChange that resulted from this synchronization.
   */
  // PORTING NOTE: Multi-tab only.
  Oa(e2) {
    this.fa = e2.gs, this.pa = __PRIVATE_documentKeySet();
    const t2 = this.ba(e2.documents);
    return this.applyChanges(
      t2,
      /* limboResolutionEnabled= */
      true
    );
  }
  /**
   * Returns a view snapshot as if this query was just listened to. Contains
   * a document add for every existing document and the `fromCache` and
   * `hasPendingWrites` status of the already established view.
   */
  // PORTING NOTE: Multi-tab only.
  Na() {
    return ViewSnapshot.fromInitialDocuments(this.query, this.wa, this.mutatedKeys, 0 === this.ga, this.hasCachedResults);
  }
}
const Jt = "SyncEngine";
class __PRIVATE_QueryView {
  static {
    __name(this, "__PRIVATE_QueryView");
  }
  constructor(e2, t2, n2) {
    this.query = e2, this.targetId = t2, this.view = n2;
  }
}
class LimboResolution {
  static {
    __name(this, "LimboResolution");
  }
  constructor(e2) {
    this.key = e2, /**
     * Set to true once we've received a document. This is used in
     * getRemoteKeysForTarget() and ultimately used by WatchChangeAggregator to
     * decide whether it needs to manufacture a delete event for the target once
     * the target is CURRENT.
     */
    this.Ba = false;
  }
}
class __PRIVATE_SyncEngineImpl {
  static {
    __name(this, "__PRIVATE_SyncEngineImpl");
  }
  constructor(e2, t2, n2, r2, i2, s2) {
    this.localStore = e2, this.remoteStore = t2, this.eventManager = n2, this.sharedClientState = r2, this.currentUser = i2, this.maxConcurrentLimboResolutions = s2, this.La = {}, this.ka = new ObjectMap((e3) => __PRIVATE_canonifyQuery(e3), __PRIVATE_queryEquals), this.qa = /* @__PURE__ */ new Map(), /**
     * The keys of documents that are in limbo for which we haven't yet started a
     * limbo resolution query. The strings in this set are the result of calling
     * `key.path.canonicalString()` where `key` is a `DocumentKey` object.
     *
     * The `Set` type was chosen because it provides efficient lookup and removal
     * of arbitrary elements and it also maintains insertion order, providing the
     * desired queue-like FIFO semantics.
     */
    this.Qa = /* @__PURE__ */ new Set(), /**
     * Keeps track of the target ID for each document that is in limbo with an
     * active target.
     */
    this.$a = new SortedMap(DocumentKey.comparator), /**
     * Keeps track of the information about an active limbo resolution for each
     * active target ID that was started for the purpose of limbo resolution.
     */
    this.Ua = /* @__PURE__ */ new Map(), this.Ka = new __PRIVATE_ReferenceSet(), /** Stores user completion handlers, indexed by User and BatchId. */
    this.Wa = {}, /** Stores user callbacks waiting for all pending writes to be acknowledged. */
    this.Ga = /* @__PURE__ */ new Map(), this.za = __PRIVATE_TargetIdGenerator.Kn(), this.onlineState = "Unknown", // The primary state is set to `true` or `false` immediately after Firestore
    // startup. In the interim, a client should only be considered primary if
    // `isPrimary` is true.
    this.ja = void 0;
  }
  get isPrimaryClient() {
    return true === this.ja;
  }
}
async function __PRIVATE_syncEngineListen(e2, t2, n2 = true) {
  const r2 = __PRIVATE_ensureWatchCallbacks(e2);
  let i2;
  const s2 = r2.ka.get(t2);
  return s2 ? (
    // PORTING NOTE: With Multi-Tab Web, it is possible that a query view
    // already exists when EventManager calls us for the first time. This
    // happens when the primary tab is already listening to this query on
    // behalf of another tab and the user of the primary also starts listening
    // to the query. EventManager will not have an assigned target ID in this
    // case and calls `listen` to obtain this ID.
    (r2.sharedClientState.addLocalQueryTarget(s2.targetId), i2 = s2.view.Na())
  ) : i2 = await __PRIVATE_allocateTargetAndMaybeListen(
    r2,
    t2,
    n2,
    /** shouldInitializeView= */
    true
  ), i2;
}
__name(__PRIVATE_syncEngineListen, "__PRIVATE_syncEngineListen");
async function __PRIVATE_triggerRemoteStoreListen(e2, t2) {
  const n2 = __PRIVATE_ensureWatchCallbacks(e2);
  await __PRIVATE_allocateTargetAndMaybeListen(
    n2,
    t2,
    /** shouldListenToRemote= */
    true,
    /** shouldInitializeView= */
    false
  );
}
__name(__PRIVATE_triggerRemoteStoreListen, "__PRIVATE_triggerRemoteStoreListen");
async function __PRIVATE_allocateTargetAndMaybeListen(e2, t2, n2, r2) {
  const i2 = await __PRIVATE_localStoreAllocateTarget(e2.localStore, __PRIVATE_queryToTarget(t2)), s2 = i2.targetId, o2 = e2.sharedClientState.addLocalQueryTarget(s2, n2);
  let _2;
  return r2 && (_2 = await __PRIVATE_initializeViewAndComputeSnapshot(e2, t2, s2, "current" === o2, i2.resumeToken)), e2.isPrimaryClient && n2 && __PRIVATE_remoteStoreListen(e2.remoteStore, i2), _2;
}
__name(__PRIVATE_allocateTargetAndMaybeListen, "__PRIVATE_allocateTargetAndMaybeListen");
async function __PRIVATE_initializeViewAndComputeSnapshot(e2, t2, n2, r2, i2) {
  e2.Ha = (t3, n3, r3) => (/* @__PURE__ */ __name(async function __PRIVATE_applyDocChanges(e3, t4, n4, r4) {
    let i3 = t4.view.ba(n4);
    i3.ls && // The query has a limit and some docs were removed, so we need
    // to re-run the query against the local store to make sure we
    // didn't lose any good docs that had been past the limit.
    (i3 = await __PRIVATE_localStoreExecuteQuery(
      e3.localStore,
      t4.query,
      /* usePreviousResults= */
      false
    ).then(({ documents: e4 }) => t4.view.ba(e4, i3)));
    const s3 = r4 && r4.targetChanges.get(t4.targetId), o3 = r4 && null != r4.targetMismatches.get(t4.targetId), _3 = t4.view.applyChanges(
      i3,
      /* limboResolutionEnabled= */
      e3.isPrimaryClient,
      s3,
      o3
    );
    return __PRIVATE_updateTrackedLimbos(e3, t4.targetId, _3.Ma), _3.snapshot;
  }, "__PRIVATE_applyDocChanges"))(e2, t3, n3, r3);
  const s2 = await __PRIVATE_localStoreExecuteQuery(
    e2.localStore,
    t2,
    /* usePreviousResults= */
    true
  ), o2 = new __PRIVATE_View(t2, s2.gs), _2 = o2.ba(s2.documents), a2 = TargetChange.createSynthesizedTargetChangeForCurrentChange(n2, r2 && "Offline" !== e2.onlineState, i2), u2 = o2.applyChanges(
    _2,
    /* limboResolutionEnabled= */
    e2.isPrimaryClient,
    a2
  );
  __PRIVATE_updateTrackedLimbos(e2, n2, u2.Ma);
  const c2 = new __PRIVATE_QueryView(t2, n2, o2);
  return e2.ka.set(t2, c2), e2.qa.has(n2) ? e2.qa.get(n2).push(t2) : e2.qa.set(n2, [t2]), u2.snapshot;
}
__name(__PRIVATE_initializeViewAndComputeSnapshot, "__PRIVATE_initializeViewAndComputeSnapshot");
async function __PRIVATE_syncEngineUnlisten(e2, t2, n2) {
  const r2 = __PRIVATE_debugCast(e2), i2 = r2.ka.get(t2), s2 = r2.qa.get(i2.targetId);
  if (s2.length > 1) return r2.qa.set(i2.targetId, s2.filter((e3) => !__PRIVATE_queryEquals(e3, t2))), void r2.ka.delete(t2);
  if (r2.isPrimaryClient) {
    r2.sharedClientState.removeLocalQueryTarget(i2.targetId);
    r2.sharedClientState.isActiveQueryTarget(i2.targetId) || await __PRIVATE_localStoreReleaseTarget(
      r2.localStore,
      i2.targetId,
      /*keepPersistedTargetData=*/
      false
    ).then(() => {
      r2.sharedClientState.clearQueryState(i2.targetId), n2 && __PRIVATE_remoteStoreUnlisten(r2.remoteStore, i2.targetId), __PRIVATE_removeAndCleanupTarget(r2, i2.targetId);
    }).catch(__PRIVATE_ignoreIfPrimaryLeaseLoss);
  } else __PRIVATE_removeAndCleanupTarget(r2, i2.targetId), await __PRIVATE_localStoreReleaseTarget(
    r2.localStore,
    i2.targetId,
    /*keepPersistedTargetData=*/
    true
  );
}
__name(__PRIVATE_syncEngineUnlisten, "__PRIVATE_syncEngineUnlisten");
async function __PRIVATE_triggerRemoteStoreUnlisten(e2, t2) {
  const n2 = __PRIVATE_debugCast(e2), r2 = n2.ka.get(t2), i2 = n2.qa.get(r2.targetId);
  n2.isPrimaryClient && 1 === i2.length && // PORTING NOTE: Unregister the target ID with local Firestore client as
  // watch target.
  (n2.sharedClientState.removeLocalQueryTarget(r2.targetId), __PRIVATE_remoteStoreUnlisten(n2.remoteStore, r2.targetId));
}
__name(__PRIVATE_triggerRemoteStoreUnlisten, "__PRIVATE_triggerRemoteStoreUnlisten");
async function __PRIVATE_syncEngineWrite(e2, t2, n2) {
  const r2 = __PRIVATE_syncEngineEnsureWriteCallbacks(e2);
  try {
    const e3 = await (/* @__PURE__ */ __name(function __PRIVATE_localStoreWriteLocally(e4, t3) {
      const n3 = __PRIVATE_debugCast(e4), r3 = Timestamp.now(), i2 = t3.reduce((e5, t4) => e5.add(t4.key), __PRIVATE_documentKeySet());
      let s2, o2;
      return n3.persistence.runTransaction("Locally write mutations", "readwrite", (e5) => {
        let _2 = __PRIVATE_mutableDocumentMap(), a2 = __PRIVATE_documentKeySet();
        return n3.ds.getEntries(e5, i2).next((e6) => {
          _2 = e6, _2.forEach((e7, t4) => {
            t4.isValidDocument() || (a2 = a2.add(e7));
          });
        }).next(() => n3.localDocuments.getOverlayedDocuments(e5, _2)).next((i3) => {
          s2 = i3;
          const o3 = [];
          for (const e6 of t3) {
            const t4 = __PRIVATE_mutationExtractBaseValue(e6, s2.get(e6.key).overlayedDocument);
            null != t4 && // NOTE: The base state should only be applied if there's some
            // existing document to override, so use a Precondition of
            // exists=true
            o3.push(new __PRIVATE_PatchMutation(e6.key, t4, __PRIVATE_extractFieldMask(t4.value.mapValue), Precondition.exists(true)));
          }
          return n3.mutationQueue.addMutationBatch(e5, r3, o3, t3);
        }).next((t4) => {
          o2 = t4;
          const r4 = t4.applyToLocalDocumentSet(s2, a2);
          return n3.documentOverlayCache.saveOverlays(e5, t4.batchId, r4);
        });
      }).then(() => ({
        batchId: o2.batchId,
        changes: __PRIVATE_convertOverlayedDocumentMapToDocumentMap(s2)
      }));
    }, "__PRIVATE_localStoreWriteLocally"))(r2.localStore, t2);
    r2.sharedClientState.addPendingMutation(e3.batchId), (/* @__PURE__ */ __name(function __PRIVATE_addMutationCallback(e4, t3, n3) {
      let r3 = e4.Wa[e4.currentUser.toKey()];
      r3 || (r3 = new SortedMap(__PRIVATE_primitiveComparator));
      r3 = r3.insert(t3, n3), e4.Wa[e4.currentUser.toKey()] = r3;
    }, "__PRIVATE_addMutationCallback"))(r2, e3.batchId, n2), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(r2, e3.changes), await __PRIVATE_fillWritePipeline(r2.remoteStore);
  } catch (e3) {
    const t3 = __PRIVATE_wrapInUserErrorIfRecoverable(e3, "Failed to persist write");
    n2.reject(t3);
  }
}
__name(__PRIVATE_syncEngineWrite, "__PRIVATE_syncEngineWrite");
async function __PRIVATE_syncEngineApplyRemoteEvent(e2, t2) {
  const n2 = __PRIVATE_debugCast(e2);
  try {
    const e3 = await __PRIVATE_localStoreApplyRemoteEventToLocalCache(n2.localStore, t2);
    t2.targetChanges.forEach((e4, t3) => {
      const r2 = n2.Ua.get(t3);
      r2 && // Since this is a limbo resolution lookup, it's for a single document
      // and it could be added, modified, or removed, but not a combination.
      (__PRIVATE_hardAssert(e4.addedDocuments.size + e4.modifiedDocuments.size + e4.removedDocuments.size <= 1), e4.addedDocuments.size > 0 ? r2.Ba = true : e4.modifiedDocuments.size > 0 ? __PRIVATE_hardAssert(r2.Ba) : e4.removedDocuments.size > 0 && (__PRIVATE_hardAssert(r2.Ba), r2.Ba = false));
    }), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(n2, e3, t2);
  } catch (e3) {
    await __PRIVATE_ignoreIfPrimaryLeaseLoss(e3);
  }
}
__name(__PRIVATE_syncEngineApplyRemoteEvent, "__PRIVATE_syncEngineApplyRemoteEvent");
function __PRIVATE_syncEngineApplyOnlineStateChange(e2, t2, n2) {
  const r2 = __PRIVATE_debugCast(e2);
  if (r2.isPrimaryClient && 0 === n2 || !r2.isPrimaryClient && 1 === n2) {
    const e3 = [];
    r2.ka.forEach((n3, r3) => {
      const i2 = r3.view.sa(t2);
      i2.snapshot && e3.push(i2.snapshot);
    }), (/* @__PURE__ */ __name(function __PRIVATE_eventManagerOnOnlineStateChange(e4, t3) {
      const n3 = __PRIVATE_debugCast(e4);
      n3.onlineState = t3;
      let r3 = false;
      n3.queries.forEach((e5, n4) => {
        for (const e6 of n4.ta)
          e6.sa(t3) && (r3 = true);
      }), r3 && __PRIVATE_raiseSnapshotsInSyncEvent(n3);
    }, "__PRIVATE_eventManagerOnOnlineStateChange"))(r2.eventManager, t2), e3.length && r2.La.p_(e3), r2.onlineState = t2, r2.isPrimaryClient && r2.sharedClientState.setOnlineState(t2);
  }
}
__name(__PRIVATE_syncEngineApplyOnlineStateChange, "__PRIVATE_syncEngineApplyOnlineStateChange");
async function __PRIVATE_syncEngineRejectListen(e2, t2, n2) {
  const r2 = __PRIVATE_debugCast(e2);
  r2.sharedClientState.updateQueryState(t2, "rejected", n2);
  const i2 = r2.Ua.get(t2), s2 = i2 && i2.key;
  if (s2) {
    let e3 = new SortedMap(DocumentKey.comparator);
    e3 = e3.insert(s2, MutableDocument.newNoDocument(s2, SnapshotVersion.min()));
    const n3 = __PRIVATE_documentKeySet().add(s2), i3 = new RemoteEvent(
      SnapshotVersion.min(),
      /* targetChanges= */
      /* @__PURE__ */ new Map(),
      /* targetMismatches= */
      new SortedMap(__PRIVATE_primitiveComparator),
      e3,
      n3
    );
    await __PRIVATE_syncEngineApplyRemoteEvent(r2, i3), // Since this query failed, we won't want to manually unlisten to it.
    // We only remove it from bookkeeping after we successfully applied the
    // RemoteEvent. If `applyRemoteEvent()` throws, we want to re-listen to
    // this query when the RemoteStore restarts the Watch stream, which should
    // re-trigger the target failure.
    r2.$a = r2.$a.remove(s2), r2.Ua.delete(t2), __PRIVATE_pumpEnqueuedLimboResolutions(r2);
  } else await __PRIVATE_localStoreReleaseTarget(
    r2.localStore,
    t2,
    /* keepPersistedTargetData */
    false
  ).then(() => __PRIVATE_removeAndCleanupTarget(r2, t2, n2)).catch(__PRIVATE_ignoreIfPrimaryLeaseLoss);
}
__name(__PRIVATE_syncEngineRejectListen, "__PRIVATE_syncEngineRejectListen");
async function __PRIVATE_syncEngineApplySuccessfulWrite(e2, t2) {
  const n2 = __PRIVATE_debugCast(e2), r2 = t2.batch.batchId;
  try {
    const e3 = await __PRIVATE_localStoreAcknowledgeBatch(n2.localStore, t2);
    __PRIVATE_processUserCallback(
      n2,
      r2,
      /*error=*/
      null
    ), __PRIVATE_triggerPendingWritesCallbacks(n2, r2), n2.sharedClientState.updateMutationState(r2, "acknowledged"), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(n2, e3);
  } catch (e3) {
    await __PRIVATE_ignoreIfPrimaryLeaseLoss(e3);
  }
}
__name(__PRIVATE_syncEngineApplySuccessfulWrite, "__PRIVATE_syncEngineApplySuccessfulWrite");
async function __PRIVATE_syncEngineRejectFailedWrite(e2, t2, n2) {
  const r2 = __PRIVATE_debugCast(e2);
  try {
    const e3 = await (/* @__PURE__ */ __name(function __PRIVATE_localStoreRejectBatch(e4, t3) {
      const n3 = __PRIVATE_debugCast(e4);
      return n3.persistence.runTransaction("Reject batch", "readwrite-primary", (e5) => {
        let r3;
        return n3.mutationQueue.lookupMutationBatch(e5, t3).next((t4) => (__PRIVATE_hardAssert(null !== t4), r3 = t4.keys(), n3.mutationQueue.removeMutationBatch(e5, t4))).next(() => n3.mutationQueue.performConsistencyCheck(e5)).next(() => n3.documentOverlayCache.removeOverlaysForBatchId(e5, r3, t3)).next(() => n3.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e5, r3)).next(() => n3.localDocuments.getDocuments(e5, r3));
      });
    }, "__PRIVATE_localStoreRejectBatch"))(r2.localStore, t2);
    __PRIVATE_processUserCallback(r2, t2, n2), __PRIVATE_triggerPendingWritesCallbacks(r2, t2), r2.sharedClientState.updateMutationState(t2, "rejected", n2), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(r2, e3);
  } catch (n3) {
    await __PRIVATE_ignoreIfPrimaryLeaseLoss(n3);
  }
}
__name(__PRIVATE_syncEngineRejectFailedWrite, "__PRIVATE_syncEngineRejectFailedWrite");
async function __PRIVATE_syncEngineRegisterPendingWritesCallback(e2, t2) {
  const n2 = __PRIVATE_debugCast(e2);
  __PRIVATE_canUseNetwork(n2.remoteStore) || __PRIVATE_logDebug(Jt, "The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.");
  try {
    const e3 = await (/* @__PURE__ */ __name(function __PRIVATE_localStoreGetHighestUnacknowledgedBatchId(e4) {
      const t3 = __PRIVATE_debugCast(e4);
      return t3.persistence.runTransaction("Get highest unacknowledged batch id", "readonly", (e5) => t3.mutationQueue.getHighestUnacknowledgedBatchId(e5));
    }, "__PRIVATE_localStoreGetHighestUnacknowledgedBatchId"))(n2.localStore);
    if (e3 === Q)
      return void t2.resolve();
    const r2 = n2.Ga.get(e3) || [];
    r2.push(t2), n2.Ga.set(e3, r2);
  } catch (e3) {
    const n3 = __PRIVATE_wrapInUserErrorIfRecoverable(e3, "Initialization of waitForPendingWrites() operation failed");
    t2.reject(n3);
  }
}
__name(__PRIVATE_syncEngineRegisterPendingWritesCallback, "__PRIVATE_syncEngineRegisterPendingWritesCallback");
function __PRIVATE_triggerPendingWritesCallbacks(e2, t2) {
  (e2.Ga.get(t2) || []).forEach((e3) => {
    e3.resolve();
  }), e2.Ga.delete(t2);
}
__name(__PRIVATE_triggerPendingWritesCallbacks, "__PRIVATE_triggerPendingWritesCallbacks");
function __PRIVATE_processUserCallback(e2, t2, n2) {
  const r2 = __PRIVATE_debugCast(e2);
  let i2 = r2.Wa[r2.currentUser.toKey()];
  if (i2) {
    const e3 = i2.get(t2);
    e3 && (n2 ? e3.reject(n2) : e3.resolve(), i2 = i2.remove(t2)), r2.Wa[r2.currentUser.toKey()] = i2;
  }
}
__name(__PRIVATE_processUserCallback, "__PRIVATE_processUserCallback");
function __PRIVATE_removeAndCleanupTarget(e2, t2, n2 = null) {
  e2.sharedClientState.removeLocalQueryTarget(t2);
  for (const r2 of e2.qa.get(t2)) e2.ka.delete(r2), n2 && e2.La.Ja(r2, n2);
  if (e2.qa.delete(t2), e2.isPrimaryClient) {
    e2.Ka.br(t2).forEach((t3) => {
      e2.Ka.containsKey(t3) || // We removed the last reference for this key
      __PRIVATE_removeLimboTarget(e2, t3);
    });
  }
}
__name(__PRIVATE_removeAndCleanupTarget, "__PRIVATE_removeAndCleanupTarget");
function __PRIVATE_removeLimboTarget(e2, t2) {
  e2.Qa.delete(t2.path.canonicalString());
  const n2 = e2.$a.get(t2);
  null !== n2 && (__PRIVATE_remoteStoreUnlisten(e2.remoteStore, n2), e2.$a = e2.$a.remove(t2), e2.Ua.delete(n2), __PRIVATE_pumpEnqueuedLimboResolutions(e2));
}
__name(__PRIVATE_removeLimboTarget, "__PRIVATE_removeLimboTarget");
function __PRIVATE_updateTrackedLimbos(e2, t2, n2) {
  for (const r2 of n2) if (r2 instanceof __PRIVATE_AddedLimboDocument) e2.Ka.addReference(r2.key, t2), __PRIVATE_trackLimboChange(e2, r2);
  else if (r2 instanceof __PRIVATE_RemovedLimboDocument) {
    __PRIVATE_logDebug(Jt, "Document no longer in limbo: " + r2.key), e2.Ka.removeReference(r2.key, t2);
    e2.Ka.containsKey(r2.key) || // We removed the last reference for this key
    __PRIVATE_removeLimboTarget(e2, r2.key);
  } else fail();
}
__name(__PRIVATE_updateTrackedLimbos, "__PRIVATE_updateTrackedLimbos");
function __PRIVATE_trackLimboChange(e2, t2) {
  const n2 = t2.key, r2 = n2.path.canonicalString();
  e2.$a.get(n2) || e2.Qa.has(r2) || (__PRIVATE_logDebug(Jt, "New document in limbo: " + n2), e2.Qa.add(r2), __PRIVATE_pumpEnqueuedLimboResolutions(e2));
}
__name(__PRIVATE_trackLimboChange, "__PRIVATE_trackLimboChange");
function __PRIVATE_pumpEnqueuedLimboResolutions(e2) {
  for (; e2.Qa.size > 0 && e2.$a.size < e2.maxConcurrentLimboResolutions; ) {
    const t2 = e2.Qa.values().next().value;
    e2.Qa.delete(t2);
    const n2 = new DocumentKey(ResourcePath.fromString(t2)), r2 = e2.za.next();
    e2.Ua.set(r2, new LimboResolution(n2)), e2.$a = e2.$a.insert(n2, r2), __PRIVATE_remoteStoreListen(e2.remoteStore, new TargetData(__PRIVATE_queryToTarget(__PRIVATE_newQueryForPath(n2.path)), r2, "TargetPurposeLimboResolution", __PRIVATE_ListenSequence.ae));
  }
}
__name(__PRIVATE_pumpEnqueuedLimboResolutions, "__PRIVATE_pumpEnqueuedLimboResolutions");
async function __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(e2, t2, n2) {
  const r2 = __PRIVATE_debugCast(e2), i2 = [], s2 = [], o2 = [];
  r2.ka.isEmpty() || (r2.ka.forEach((e3, _2) => {
    o2.push(r2.Ha(_2, t2, n2).then((e4) => {
      var t3;
      if ((e4 || n2) && r2.isPrimaryClient) {
        const i3 = e4 ? !e4.fromCache : null === (t3 = null == n2 ? void 0 : n2.targetChanges.get(_2.targetId)) || void 0 === t3 ? void 0 : t3.current;
        r2.sharedClientState.updateQueryState(_2.targetId, i3 ? "current" : "not-current");
      }
      if (e4) {
        i2.push(e4);
        const t4 = __PRIVATE_LocalViewChanges.Yi(_2.targetId, e4);
        s2.push(t4);
      }
    }));
  }), await Promise.all(o2), r2.La.p_(i2), await (/* @__PURE__ */ __name(async function __PRIVATE_localStoreNotifyLocalViewChanges(e3, t3) {
    const n3 = __PRIVATE_debugCast(e3);
    try {
      await n3.persistence.runTransaction("notifyLocalViewChanges", "readwrite", (e4) => PersistencePromise.forEach(t3, (t4) => PersistencePromise.forEach(t4.Hi, (r3) => n3.persistence.referenceDelegate.addReference(e4, t4.targetId, r3)).next(() => PersistencePromise.forEach(t4.Ji, (r3) => n3.persistence.referenceDelegate.removeReference(e4, t4.targetId, r3)))));
    } catch (e4) {
      if (!__PRIVATE_isIndexedDbTransactionError(e4)) throw e4;
      __PRIVATE_logDebug(Ot, "Failed to update sequence numbers: " + e4);
    }
    for (const e4 of t3) {
      const t4 = e4.targetId;
      if (!e4.fromCache) {
        const e5 = n3.Ts.get(t4), r3 = e5.snapshotVersion, i3 = e5.withLastLimboFreeSnapshotVersion(r3);
        n3.Ts = n3.Ts.insert(t4, i3);
      }
    }
  }, "__PRIVATE_localStoreNotifyLocalViewChanges"))(r2.localStore, s2));
}
__name(__PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore, "__PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore");
async function __PRIVATE_syncEngineHandleCredentialChange(e2, t2) {
  const n2 = __PRIVATE_debugCast(e2);
  if (!n2.currentUser.isEqual(t2)) {
    __PRIVATE_logDebug(Jt, "User change. New user:", t2.toKey());
    const e3 = await __PRIVATE_localStoreHandleUserChange(n2.localStore, t2);
    n2.currentUser = t2, // Fails tasks waiting for pending writes requested by previous user.
    (/* @__PURE__ */ __name(function __PRIVATE_rejectOutstandingPendingWritesCallbacks(e4, t3) {
      e4.Ga.forEach((e5) => {
        e5.forEach((e6) => {
          e6.reject(new FirestoreError(C.CANCELLED, t3));
        });
      }), e4.Ga.clear();
    }, "__PRIVATE_rejectOutstandingPendingWritesCallbacks"))(n2, "'waitForPendingWrites' promise is rejected due to a user change."), // TODO(b/114226417): Consider calling this only in the primary tab.
    n2.sharedClientState.handleUserChange(t2, e3.removedBatchIds, e3.addedBatchIds), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(n2, e3.Rs);
  }
}
__name(__PRIVATE_syncEngineHandleCredentialChange, "__PRIVATE_syncEngineHandleCredentialChange");
function __PRIVATE_syncEngineGetRemoteKeysForTarget(e2, t2) {
  const n2 = __PRIVATE_debugCast(e2), r2 = n2.Ua.get(t2);
  if (r2 && r2.Ba) return __PRIVATE_documentKeySet().add(r2.key);
  {
    let e3 = __PRIVATE_documentKeySet();
    const r3 = n2.qa.get(t2);
    if (!r3) return e3;
    for (const t3 of r3) {
      const r4 = n2.ka.get(t3);
      e3 = e3.unionWith(r4.view.Sa);
    }
    return e3;
  }
}
__name(__PRIVATE_syncEngineGetRemoteKeysForTarget, "__PRIVATE_syncEngineGetRemoteKeysForTarget");
async function __PRIVATE_synchronizeViewAndComputeSnapshot(e2, t2) {
  const n2 = __PRIVATE_debugCast(e2), r2 = await __PRIVATE_localStoreExecuteQuery(
    n2.localStore,
    t2.query,
    /* usePreviousResults= */
    true
  ), i2 = t2.view.Oa(r2);
  return n2.isPrimaryClient && __PRIVATE_updateTrackedLimbos(n2, t2.targetId, i2.Ma), i2;
}
__name(__PRIVATE_synchronizeViewAndComputeSnapshot, "__PRIVATE_synchronizeViewAndComputeSnapshot");
async function __PRIVATE_syncEngineSynchronizeWithChangedDocuments(e2, t2) {
  const n2 = __PRIVATE_debugCast(e2);
  return __PRIVATE_localStoreGetNewDocumentChanges(n2.localStore, t2).then((e3) => __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(n2, e3));
}
__name(__PRIVATE_syncEngineSynchronizeWithChangedDocuments, "__PRIVATE_syncEngineSynchronizeWithChangedDocuments");
async function __PRIVATE_syncEngineApplyBatchState(e2, t2, n2, r2) {
  const i2 = __PRIVATE_debugCast(e2), s2 = await (/* @__PURE__ */ __name(function __PRIVATE_localStoreLookupMutationDocuments(e3, t3) {
    const n3 = __PRIVATE_debugCast(e3), r3 = __PRIVATE_debugCast(n3.mutationQueue);
    return n3.persistence.runTransaction("Lookup mutation documents", "readonly", (e4) => r3.Ln(e4, t3).next((t4) => t4 ? n3.localDocuments.getDocuments(e4, t4) : PersistencePromise.resolve(null)));
  }, "__PRIVATE_localStoreLookupMutationDocuments"))(i2.localStore, t2);
  null !== s2 ? ("pending" === n2 ? (
    // If we are the primary client, we need to send this write to the
    // backend. Secondary clients will ignore these writes since their remote
    // connection is disabled.
    await __PRIVATE_fillWritePipeline(i2.remoteStore)
  ) : "acknowledged" === n2 || "rejected" === n2 ? (
    // NOTE: Both these methods are no-ops for batches that originated from
    // other clients.
    (__PRIVATE_processUserCallback(i2, t2, r2 || null), __PRIVATE_triggerPendingWritesCallbacks(i2, t2), (/* @__PURE__ */ __name(function __PRIVATE_localStoreRemoveCachedMutationBatchMetadata(e3, t3) {
      __PRIVATE_debugCast(__PRIVATE_debugCast(e3).mutationQueue).qn(t3);
    }, "__PRIVATE_localStoreRemoveCachedMutationBatchMetadata"))(i2.localStore, t2))
  ) : fail(), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(i2, s2)) : (
    // A throttled tab may not have seen the mutation before it was completed
    // and removed from the mutation queue, in which case we won't have cached
    // the affected documents. In this case we can safely ignore the update
    // since that means we didn't apply the mutation locally at all (if we
    // had, we would have cached the affected documents), and so we will just
    // see any resulting document changes via normal remote document updates
    // as applicable.
    __PRIVATE_logDebug(Jt, "Cannot apply mutation batch with id: " + t2)
  );
}
__name(__PRIVATE_syncEngineApplyBatchState, "__PRIVATE_syncEngineApplyBatchState");
async function __PRIVATE_syncEngineApplyPrimaryState(e2, t2) {
  const n2 = __PRIVATE_debugCast(e2);
  if (__PRIVATE_ensureWatchCallbacks(n2), __PRIVATE_syncEngineEnsureWriteCallbacks(n2), true === t2 && true !== n2.ja) {
    const e3 = n2.sharedClientState.getAllActiveQueryTargets(), t3 = await __PRIVATE_synchronizeQueryViewsAndRaiseSnapshots(n2, e3.toArray());
    n2.ja = true, await __PRIVATE_remoteStoreApplyPrimaryState(n2.remoteStore, true);
    for (const e4 of t3) __PRIVATE_remoteStoreListen(n2.remoteStore, e4);
  } else if (false === t2 && false !== n2.ja) {
    const e3 = [];
    let t3 = Promise.resolve();
    n2.qa.forEach((r2, i2) => {
      n2.sharedClientState.isLocalQueryTarget(i2) ? e3.push(i2) : t3 = t3.then(() => (__PRIVATE_removeAndCleanupTarget(n2, i2), __PRIVATE_localStoreReleaseTarget(
        n2.localStore,
        i2,
        /*keepPersistedTargetData=*/
        true
      ))), __PRIVATE_remoteStoreUnlisten(n2.remoteStore, i2);
    }), await t3, await __PRIVATE_synchronizeQueryViewsAndRaiseSnapshots(n2, e3), // PORTING NOTE: Multi-Tab only.
    (/* @__PURE__ */ __name(function __PRIVATE_resetLimboDocuments(e4) {
      const t4 = __PRIVATE_debugCast(e4);
      t4.Ua.forEach((e5, n3) => {
        __PRIVATE_remoteStoreUnlisten(t4.remoteStore, n3);
      }), t4.Ka.Dr(), t4.Ua = /* @__PURE__ */ new Map(), t4.$a = new SortedMap(DocumentKey.comparator);
    }, "__PRIVATE_resetLimboDocuments"))(n2), n2.ja = false, await __PRIVATE_remoteStoreApplyPrimaryState(n2.remoteStore, false);
  }
}
__name(__PRIVATE_syncEngineApplyPrimaryState, "__PRIVATE_syncEngineApplyPrimaryState");
async function __PRIVATE_synchronizeQueryViewsAndRaiseSnapshots(e2, t2, n2) {
  const r2 = __PRIVATE_debugCast(e2), i2 = [], s2 = [];
  for (const e3 of t2) {
    let t3;
    const n3 = r2.qa.get(e3);
    if (n3 && 0 !== n3.length) {
      t3 = await __PRIVATE_localStoreAllocateTarget(r2.localStore, __PRIVATE_queryToTarget(n3[0]));
      for (const e4 of n3) {
        const t4 = r2.ka.get(e4), n4 = await __PRIVATE_synchronizeViewAndComputeSnapshot(r2, t4);
        n4.snapshot && s2.push(n4.snapshot);
      }
    } else {
      const n4 = await __PRIVATE_localStoreGetCachedTarget(r2.localStore, e3);
      t3 = await __PRIVATE_localStoreAllocateTarget(r2.localStore, n4), await __PRIVATE_initializeViewAndComputeSnapshot(
        r2,
        __PRIVATE_synthesizeTargetToQuery(n4),
        e3,
        /*current=*/
        false,
        t3.resumeToken
      );
    }
    i2.push(t3);
  }
  return r2.La.p_(s2), i2;
}
__name(__PRIVATE_synchronizeQueryViewsAndRaiseSnapshots, "__PRIVATE_synchronizeQueryViewsAndRaiseSnapshots");
function __PRIVATE_synthesizeTargetToQuery(e2) {
  return __PRIVATE_newQuery(e2.path, e2.collectionGroup, e2.orderBy, e2.filters, e2.limit, "F", e2.startAt, e2.endAt);
}
__name(__PRIVATE_synthesizeTargetToQuery, "__PRIVATE_synthesizeTargetToQuery");
function __PRIVATE_syncEngineGetActiveClients(e2) {
  return (/* @__PURE__ */ __name(function __PRIVATE_localStoreGetActiveClients(e3) {
    return __PRIVATE_debugCast(__PRIVATE_debugCast(e3).persistence).zi();
  }, "__PRIVATE_localStoreGetActiveClients"))(__PRIVATE_debugCast(e2).localStore);
}
__name(__PRIVATE_syncEngineGetActiveClients, "__PRIVATE_syncEngineGetActiveClients");
async function __PRIVATE_syncEngineApplyTargetState(e2, t2, n2, r2) {
  const i2 = __PRIVATE_debugCast(e2);
  if (i2.ja)
    return void __PRIVATE_logDebug(Jt, "Ignoring unexpected query state notification.");
  const s2 = i2.qa.get(t2);
  if (s2 && s2.length > 0) switch (n2) {
    case "current":
    case "not-current": {
      const e3 = await __PRIVATE_localStoreGetNewDocumentChanges(i2.localStore, __PRIVATE_queryCollectionGroup(s2[0])), r3 = RemoteEvent.createSynthesizedRemoteEventForCurrentChange(t2, "current" === n2, ByteString.EMPTY_BYTE_STRING);
      await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(i2, e3, r3);
      break;
    }
    case "rejected":
      await __PRIVATE_localStoreReleaseTarget(
        i2.localStore,
        t2,
        /* keepPersistedTargetData */
        true
      ), __PRIVATE_removeAndCleanupTarget(i2, t2, r2);
      break;
    default:
      fail();
  }
}
__name(__PRIVATE_syncEngineApplyTargetState, "__PRIVATE_syncEngineApplyTargetState");
async function __PRIVATE_syncEngineApplyActiveTargetsChange(e2, t2, n2) {
  const r2 = __PRIVATE_ensureWatchCallbacks(e2);
  if (r2.ja) {
    for (const e3 of t2) {
      if (r2.qa.has(e3) && r2.sharedClientState.isActiveQueryTarget(e3)) {
        __PRIVATE_logDebug(Jt, "Adding an already active target " + e3);
        continue;
      }
      const t3 = await __PRIVATE_localStoreGetCachedTarget(r2.localStore, e3), n3 = await __PRIVATE_localStoreAllocateTarget(r2.localStore, t3);
      await __PRIVATE_initializeViewAndComputeSnapshot(
        r2,
        __PRIVATE_synthesizeTargetToQuery(t3),
        n3.targetId,
        /*current=*/
        false,
        n3.resumeToken
      ), __PRIVATE_remoteStoreListen(r2.remoteStore, n3);
    }
    for (const e3 of n2)
      r2.qa.has(e3) && // Release queries that are still active.
      await __PRIVATE_localStoreReleaseTarget(
        r2.localStore,
        e3,
        /* keepPersistedTargetData */
        false
      ).then(() => {
        __PRIVATE_remoteStoreUnlisten(r2.remoteStore, e3), __PRIVATE_removeAndCleanupTarget(r2, e3);
      }).catch(__PRIVATE_ignoreIfPrimaryLeaseLoss);
  }
}
__name(__PRIVATE_syncEngineApplyActiveTargetsChange, "__PRIVATE_syncEngineApplyActiveTargetsChange");
function __PRIVATE_ensureWatchCallbacks(e2) {
  const t2 = __PRIVATE_debugCast(e2);
  return t2.remoteStore.remoteSyncer.applyRemoteEvent = __PRIVATE_syncEngineApplyRemoteEvent.bind(null, t2), t2.remoteStore.remoteSyncer.getRemoteKeysForTarget = __PRIVATE_syncEngineGetRemoteKeysForTarget.bind(null, t2), t2.remoteStore.remoteSyncer.rejectListen = __PRIVATE_syncEngineRejectListen.bind(null, t2), t2.La.p_ = __PRIVATE_eventManagerOnWatchChange.bind(null, t2.eventManager), t2.La.Ja = __PRIVATE_eventManagerOnWatchError.bind(null, t2.eventManager), t2;
}
__name(__PRIVATE_ensureWatchCallbacks, "__PRIVATE_ensureWatchCallbacks");
function __PRIVATE_syncEngineEnsureWriteCallbacks(e2) {
  const t2 = __PRIVATE_debugCast(e2);
  return t2.remoteStore.remoteSyncer.applySuccessfulWrite = __PRIVATE_syncEngineApplySuccessfulWrite.bind(null, t2), t2.remoteStore.remoteSyncer.rejectFailedWrite = __PRIVATE_syncEngineRejectFailedWrite.bind(null, t2), t2;
}
__name(__PRIVATE_syncEngineEnsureWriteCallbacks, "__PRIVATE_syncEngineEnsureWriteCallbacks");
function __PRIVATE_syncEngineLoadBundle(e2, t2, n2) {
  const r2 = __PRIVATE_debugCast(e2);
  /** Loads a bundle and returns the list of affected collection groups. */
  (/* @__PURE__ */ __name(async function __PRIVATE_loadBundleImpl(e3, t3, n3) {
    try {
      const r3 = await t3.getMetadata();
      if (await (/* @__PURE__ */ __name(function __PRIVATE_localStoreHasNewerBundle(e4, t4) {
        const n4 = __PRIVATE_debugCast(e4), r4 = __PRIVATE_fromVersion(t4.createTime);
        return n4.persistence.runTransaction("hasNewerBundle", "readonly", (e5) => n4.Yr.getBundleMetadata(e5, t4.id)).then((e5) => !!e5 && e5.createTime.compareTo(r4) >= 0);
      }, "__PRIVATE_localStoreHasNewerBundle"))(e3.localStore, r3)) return await t3.close(), n3._completeWith((/* @__PURE__ */ __name(function __PRIVATE_bundleSuccessProgress(e4) {
        return {
          taskState: "Success",
          documentsLoaded: e4.totalDocuments,
          bytesLoaded: e4.totalBytes,
          totalDocuments: e4.totalDocuments,
          totalBytes: e4.totalBytes
        };
      }, "__PRIVATE_bundleSuccessProgress"))(r3)), Promise.resolve(/* @__PURE__ */ new Set());
      n3._updateProgress(__PRIVATE_bundleInitialProgress(r3));
      const i2 = new __PRIVATE_BundleLoader(r3, e3.localStore, t3.serializer);
      let s2 = await t3.Ya();
      for (; s2; ) {
        const e4 = await i2.Aa(s2);
        e4 && n3._updateProgress(e4), s2 = await t3.Ya();
      }
      const o2 = await i2.complete();
      return await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(
        e3,
        o2.ma,
        /* remoteEvent */
        void 0
      ), // Save metadata, so loading the same bundle will skip.
      await (/* @__PURE__ */ __name(function __PRIVATE_localStoreSaveBundle(e4, t4) {
        const n4 = __PRIVATE_debugCast(e4);
        return n4.persistence.runTransaction("Save bundle", "readwrite", (e5) => n4.Yr.saveBundleMetadata(e5, t4));
      }, "__PRIVATE_localStoreSaveBundle"))(e3.localStore, r3), n3._completeWith(o2.progress), Promise.resolve(o2.Va);
    } catch (e4) {
      return __PRIVATE_logWarn(Jt, `Loading bundle failed with ${e4}`), n3._failWith(e4), Promise.resolve(/* @__PURE__ */ new Set());
    }
  }, "__PRIVATE_loadBundleImpl"))(r2, t2, n2).then((e3) => {
    r2.sharedClientState.notifyBundleLoaded(e3);
  });
}
__name(__PRIVATE_syncEngineLoadBundle, "__PRIVATE_syncEngineLoadBundle");
class __PRIVATE_MemoryOfflineComponentProvider {
  static {
    __name(this, "__PRIVATE_MemoryOfflineComponentProvider");
  }
  constructor() {
    this.kind = "memory", this.synchronizeTabs = false;
  }
  async initialize(e2) {
    this.serializer = __PRIVATE_newSerializer(e2.databaseInfo.databaseId), this.sharedClientState = this.Za(e2), this.persistence = this.Xa(e2), await this.persistence.start(), this.localStore = this.eu(e2), this.gcScheduler = this.tu(e2, this.localStore), this.indexBackfillerScheduler = this.nu(e2, this.localStore);
  }
  tu(e2, t2) {
    return null;
  }
  nu(e2, t2) {
    return null;
  }
  eu(e2) {
    return __PRIVATE_newLocalStore(this.persistence, new __PRIVATE_QueryEngine(), e2.initialUser, this.serializer);
  }
  Xa(e2) {
    return new __PRIVATE_MemoryPersistence(__PRIVATE_MemoryEagerDelegate.ri, this.serializer);
  }
  Za(e2) {
    return new __PRIVATE_MemorySharedClientState();
  }
  async terminate() {
    var e2, t2;
    null === (e2 = this.gcScheduler) || void 0 === e2 || e2.stop(), null === (t2 = this.indexBackfillerScheduler) || void 0 === t2 || t2.stop(), this.sharedClientState.shutdown(), await this.persistence.shutdown();
  }
}
__PRIVATE_MemoryOfflineComponentProvider.provider = {
  build: /* @__PURE__ */ __name(() => new __PRIVATE_MemoryOfflineComponentProvider(), "build")
};
class __PRIVATE_LruGcMemoryOfflineComponentProvider extends __PRIVATE_MemoryOfflineComponentProvider {
  static {
    __name(this, "__PRIVATE_LruGcMemoryOfflineComponentProvider");
  }
  constructor(e2) {
    super(), this.cacheSizeBytes = e2;
  }
  tu(e2, t2) {
    __PRIVATE_hardAssert(this.persistence.referenceDelegate instanceof __PRIVATE_MemoryLruDelegate);
    const n2 = this.persistence.referenceDelegate.garbageCollector;
    return new __PRIVATE_LruScheduler(n2, e2.asyncQueue, t2);
  }
  Xa(e2) {
    const t2 = void 0 !== this.cacheSizeBytes ? LruParams.withCacheSize(this.cacheSizeBytes) : LruParams.DEFAULT;
    return new __PRIVATE_MemoryPersistence((e3) => __PRIVATE_MemoryLruDelegate.ri(e3, t2), this.serializer);
  }
}
class __PRIVATE_IndexedDbOfflineComponentProvider extends __PRIVATE_MemoryOfflineComponentProvider {
  static {
    __name(this, "__PRIVATE_IndexedDbOfflineComponentProvider");
  }
  constructor(e2, t2, n2) {
    super(), this.ru = e2, this.cacheSizeBytes = t2, this.forceOwnership = n2, this.kind = "persistent", this.synchronizeTabs = false;
  }
  async initialize(e2) {
    await super.initialize(e2), await this.ru.initialize(this, e2), // Enqueue writes from a previous session
    await __PRIVATE_syncEngineEnsureWriteCallbacks(this.ru.syncEngine), await __PRIVATE_fillWritePipeline(this.ru.remoteStore), // NOTE: This will immediately call the listener, so we make sure to
    // set it after localStore / remoteStore are started.
    await this.persistence.Ci(() => (this.gcScheduler && !this.gcScheduler.started && this.gcScheduler.start(), this.indexBackfillerScheduler && !this.indexBackfillerScheduler.started && this.indexBackfillerScheduler.start(), Promise.resolve()));
  }
  eu(e2) {
    return __PRIVATE_newLocalStore(this.persistence, new __PRIVATE_QueryEngine(), e2.initialUser, this.serializer);
  }
  tu(e2, t2) {
    const n2 = this.persistence.referenceDelegate.garbageCollector;
    return new __PRIVATE_LruScheduler(n2, e2.asyncQueue, t2);
  }
  nu(e2, t2) {
    const n2 = new __PRIVATE_IndexBackfiller(t2, this.persistence);
    return new __PRIVATE_IndexBackfillerScheduler(e2.asyncQueue, n2);
  }
  Xa(e2) {
    const t2 = __PRIVATE_indexedDbStoragePrefix(e2.databaseInfo.databaseId, e2.databaseInfo.persistenceKey), n2 = void 0 !== this.cacheSizeBytes ? LruParams.withCacheSize(this.cacheSizeBytes) : LruParams.DEFAULT;
    return new __PRIVATE_IndexedDbPersistence(this.synchronizeTabs, t2, e2.clientId, n2, e2.asyncQueue, __PRIVATE_getWindow(), getDocument(), this.serializer, this.sharedClientState, !!this.forceOwnership);
  }
  Za(e2) {
    return new __PRIVATE_MemorySharedClientState();
  }
}
class __PRIVATE_MultiTabOfflineComponentProvider extends __PRIVATE_IndexedDbOfflineComponentProvider {
  static {
    __name(this, "__PRIVATE_MultiTabOfflineComponentProvider");
  }
  constructor(e2, t2) {
    super(
      e2,
      t2,
      /* forceOwnership= */
      false
    ), this.ru = e2, this.cacheSizeBytes = t2, this.synchronizeTabs = true;
  }
  async initialize(e2) {
    await super.initialize(e2);
    const t2 = this.ru.syncEngine;
    this.sharedClientState instanceof __PRIVATE_WebStorageSharedClientState && (this.sharedClientState.syncEngine = {
      uo: __PRIVATE_syncEngineApplyBatchState.bind(null, t2),
      co: __PRIVATE_syncEngineApplyTargetState.bind(null, t2),
      lo: __PRIVATE_syncEngineApplyActiveTargetsChange.bind(null, t2),
      zi: __PRIVATE_syncEngineGetActiveClients.bind(null, t2),
      ao: __PRIVATE_syncEngineSynchronizeWithChangedDocuments.bind(null, t2)
    }, await this.sharedClientState.start()), // NOTE: This will immediately call the listener, so we make sure to
    // set it after localStore / remoteStore are started.
    await this.persistence.Ci(async (e3) => {
      await __PRIVATE_syncEngineApplyPrimaryState(this.ru.syncEngine, e3), this.gcScheduler && (e3 && !this.gcScheduler.started ? this.gcScheduler.start() : e3 || this.gcScheduler.stop()), this.indexBackfillerScheduler && (e3 && !this.indexBackfillerScheduler.started ? this.indexBackfillerScheduler.start() : e3 || this.indexBackfillerScheduler.stop());
    });
  }
  Za(e2) {
    const t2 = __PRIVATE_getWindow();
    if (!__PRIVATE_WebStorageSharedClientState.D(t2)) throw new FirestoreError(C.UNIMPLEMENTED, "IndexedDB persistence is only available on platforms that support LocalStorage.");
    const n2 = __PRIVATE_indexedDbStoragePrefix(e2.databaseInfo.databaseId, e2.databaseInfo.persistenceKey);
    return new __PRIVATE_WebStorageSharedClientState(t2, e2.asyncQueue, n2, e2.clientId, e2.initialUser);
  }
}
class OnlineComponentProvider {
  static {
    __name(this, "OnlineComponentProvider");
  }
  async initialize(e2, t2) {
    this.localStore || (this.localStore = e2.localStore, this.sharedClientState = e2.sharedClientState, this.datastore = this.createDatastore(t2), this.remoteStore = this.createRemoteStore(t2), this.eventManager = this.createEventManager(t2), this.syncEngine = this.createSyncEngine(
      t2,
      /* startAsPrimary=*/
      !e2.synchronizeTabs
    ), this.sharedClientState.onlineStateHandler = (e3) => __PRIVATE_syncEngineApplyOnlineStateChange(
      this.syncEngine,
      e3,
      1
      /* OnlineStateSource.SharedClientState */
    ), this.remoteStore.remoteSyncer.handleCredentialChange = __PRIVATE_syncEngineHandleCredentialChange.bind(null, this.syncEngine), await __PRIVATE_remoteStoreApplyPrimaryState(this.remoteStore, this.syncEngine.isPrimaryClient));
  }
  createEventManager(e2) {
    return (/* @__PURE__ */ __name(function __PRIVATE_newEventManager() {
      return new __PRIVATE_EventManagerImpl();
    }, "__PRIVATE_newEventManager"))();
  }
  createDatastore(e2) {
    const t2 = __PRIVATE_newSerializer(e2.databaseInfo.databaseId), n2 = (/* @__PURE__ */ __name(function __PRIVATE_newConnection(e3) {
      return new __PRIVATE_WebChannelConnection(e3);
    }, "__PRIVATE_newConnection"))(e2.databaseInfo);
    return (/* @__PURE__ */ __name(function __PRIVATE_newDatastore(e3, t3, n3, r2) {
      return new __PRIVATE_DatastoreImpl(e3, t3, n3, r2);
    }, "__PRIVATE_newDatastore"))(e2.authCredentials, e2.appCheckCredentials, n2, t2);
  }
  createRemoteStore(e2) {
    return (/* @__PURE__ */ __name(function __PRIVATE_newRemoteStore(e3, t2, n2, r2, i2) {
      return new __PRIVATE_RemoteStoreImpl(e3, t2, n2, r2, i2);
    }, "__PRIVATE_newRemoteStore"))(this.localStore, this.datastore, e2.asyncQueue, (e3) => __PRIVATE_syncEngineApplyOnlineStateChange(
      this.syncEngine,
      e3,
      0
      /* OnlineStateSource.RemoteStore */
    ), (/* @__PURE__ */ __name(function __PRIVATE_newConnectivityMonitor() {
      return __PRIVATE_BrowserConnectivityMonitor.D() ? new __PRIVATE_BrowserConnectivityMonitor() : new __PRIVATE_NoopConnectivityMonitor();
    }, "__PRIVATE_newConnectivityMonitor"))());
  }
  createSyncEngine(e2, t2) {
    return (/* @__PURE__ */ __name(function __PRIVATE_newSyncEngine(e3, t3, n2, r2, i2, s2, o2) {
      const _2 = new __PRIVATE_SyncEngineImpl(e3, t3, n2, r2, i2, s2);
      return o2 && (_2.ja = true), _2;
    }, "__PRIVATE_newSyncEngine"))(this.localStore, this.remoteStore, this.eventManager, this.sharedClientState, e2.initialUser, e2.maxConcurrentLimboResolutions, t2);
  }
  async terminate() {
    var e2, t2;
    await (/* @__PURE__ */ __name(async function __PRIVATE_remoteStoreShutdown(e3) {
      const t3 = __PRIVATE_debugCast(e3);
      __PRIVATE_logDebug(zt, "RemoteStore shutting down."), t3.W_.add(
        5
        /* OfflineCause.Shutdown */
      ), await __PRIVATE_disableNetworkInternal(t3), t3.z_.shutdown(), // Set the OnlineState to Unknown (rather than Offline) to avoid potentially
      // triggering spurious listener events with cached data, etc.
      t3.j_.set(
        "Unknown"
        /* OnlineState.Unknown */
      );
    }, "__PRIVATE_remoteStoreShutdown"))(this.remoteStore), null === (e2 = this.datastore) || void 0 === e2 || e2.terminate(), null === (t2 = this.eventManager) || void 0 === t2 || t2.terminate();
  }
}
OnlineComponentProvider.provider = {
  build: /* @__PURE__ */ __name(() => new OnlineComponentProvider(), "build")
};
function __PRIVATE_toByteStreamReaderHelper(e2, t2 = 10240) {
  let n2 = 0;
  return {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    async read() {
      if (n2 < e2.byteLength) {
        const r2 = {
          value: e2.slice(n2, n2 + t2),
          done: false
        };
        return n2 += t2, r2;
      }
      return {
        done: true
      };
    },
    async cancel() {
    },
    releaseLock() {
    },
    closed: Promise.resolve()
  };
}
__name(__PRIVATE_toByteStreamReaderHelper, "__PRIVATE_toByteStreamReaderHelper");
/**
 * @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.
 */
/**
 * @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 __PRIVATE_AsyncObserver {
  static {
    __name(this, "__PRIVATE_AsyncObserver");
  }
  constructor(e2) {
    this.observer = e2, /**
     * When set to true, will not raise future events. Necessary to deal with
     * async detachment of listener.
     */
    this.muted = false;
  }
  next(e2) {
    this.muted || this.observer.next && this.iu(this.observer.next, e2);
  }
  error(e2) {
    this.muted || (this.observer.error ? this.iu(this.observer.error, e2) : __PRIVATE_logError("Uncaught Error in snapshot listener:", e2.toString()));
  }
  su() {
    this.muted = true;
  }
  iu(e2, t2) {
    setTimeout(() => {
      this.muted || e2(t2);
    }, 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.
 */
class __PRIVATE_BundleReaderImpl {
  static {
    __name(this, "__PRIVATE_BundleReaderImpl");
  }
  constructor(e2, t2) {
    this.ou = e2, this.serializer = t2, /** Cached bundle metadata. */
    this.metadata = new __PRIVATE_Deferred(), /**
     * Internal buffer to hold bundle content, accumulating incomplete element
     * content.
     */
    this.buffer = new Uint8Array(), this._u = (/* @__PURE__ */ __name(function __PRIVATE_newTextDecoder() {
      return new TextDecoder("utf-8");
    }, "__PRIVATE_newTextDecoder"))(), // Read the metadata (which is the first element).
    this.au().then((e3) => {
      e3 && e3.Ea() ? this.metadata.resolve(e3.Ia.metadata) : this.metadata.reject(new Error(`The first element of the bundle is not a metadata, it is
             ${JSON.stringify(null == e3 ? void 0 : e3.Ia)}`));
    }, (e3) => this.metadata.reject(e3));
  }
  close() {
    return this.ou.cancel();
  }
  async getMetadata() {
    return this.metadata.promise;
  }
  async Ya() {
    return await this.getMetadata(), this.au();
  }
  /**
   * Reads from the head of internal buffer, and pulling more data from
   * underlying stream if a complete element cannot be found, until an
   * element(including the prefixed length and the JSON string) is found.
   *
   * Once a complete element is read, it is dropped from internal buffer.
   *
   * Returns either the bundled element, or null if we have reached the end of
   * the stream.
   */
  async au() {
    const e2 = await this.uu();
    if (null === e2) return null;
    const t2 = this._u.decode(e2), n2 = Number(t2);
    isNaN(n2) && this.cu(`length string (${t2}) is not valid number`);
    const r2 = await this.lu(n2);
    return new __PRIVATE_SizedBundleElement(JSON.parse(r2), e2.length + n2);
  }
  /** First index of '{' from the underlying buffer. */
  hu() {
    return this.buffer.findIndex((e2) => e2 === "{".charCodeAt(0));
  }
  /**
   * Reads from the beginning of the internal buffer, until the first '{', and
   * return the content.
   *
   * If reached end of the stream, returns a null.
   */
  async uu() {
    for (; this.hu() < 0; ) {
      if (await this.Pu()) break;
    }
    if (0 === this.buffer.length) return null;
    const e2 = this.hu();
    e2 < 0 && this.cu("Reached the end of bundle when a length string is expected.");
    const t2 = this.buffer.slice(0, e2);
    return this.buffer = this.buffer.slice(e2), t2;
  }
  /**
   * Reads from a specified position from the internal buffer, for a specified
   * number of bytes, pulling more data from the underlying stream if needed.
   *
   * Returns a string decoded from the read bytes.
   */
  async lu(e2) {
    for (; this.buffer.length < e2; ) {
      await this.Pu() && this.cu("Reached the end of bundle when more is expected.");
    }
    const t2 = this._u.decode(this.buffer.slice(0, e2));
    return this.buffer = this.buffer.slice(e2), t2;
  }
  cu(e2) {
    throw this.ou.cancel(), new Error(`Invalid bundle format: ${e2}`);
  }
  /**
   * Pulls more data from underlying stream to internal buffer.
   * Returns a boolean indicating whether the stream is finished.
   */
  async Pu() {
    const e2 = await this.ou.read();
    if (!e2.done) {
      const t2 = new Uint8Array(this.buffer.length + e2.value.length);
      t2.set(this.buffer), t2.set(e2.value, this.buffer.length), this.buffer = t2;
    }
    return e2.done;
  }
}
/**
 * @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 Transaction$2 {
  static {
    __name(this, "Transaction$2");
  }
  constructor(e2) {
    this.datastore = e2, // The version of each document that was read during this transaction.
    this.readVersions = /* @__PURE__ */ new Map(), this.mutations = [], this.committed = false, /**
     * A deferred usage error that occurred previously in this transaction that
     * will cause the transaction to fail once it actually commits.
     */
    this.lastTransactionError = null, /**
     * Set of documents that have been written in the transaction.
     *
     * When there's more than one write to the same key in a transaction, any
     * writes after the first are handled differently.
     */
    this.writtenDocs = /* @__PURE__ */ new Set();
  }
  async lookup(e2) {
    if (this.ensureCommitNotCalled(), this.mutations.length > 0) throw this.lastTransactionError = new FirestoreError(C.INVALID_ARGUMENT, "Firestore transactions require all reads to be executed before all writes."), this.lastTransactionError;
    const t2 = await (/* @__PURE__ */ __name(async function __PRIVATE_invokeBatchGetDocumentsRpc(e3, t3) {
      const n2 = __PRIVATE_debugCast(e3), r2 = {
        documents: t3.map((e4) => __PRIVATE_toName(n2.serializer, e4))
      }, i2 = await n2.Co("BatchGetDocuments", n2.serializer.databaseId, ResourcePath.emptyPath(), r2, t3.length), s2 = /* @__PURE__ */ new Map();
      i2.forEach((e4) => {
        const t4 = __PRIVATE_fromBatchGetDocumentsResponse(n2.serializer, e4);
        s2.set(t4.key.toString(), t4);
      });
      const o2 = [];
      return t3.forEach((e4) => {
        const t4 = s2.get(e4.toString());
        __PRIVATE_hardAssert(!!t4), o2.push(t4);
      }), o2;
    }, "__PRIVATE_invokeBatchGetDocumentsRpc"))(this.datastore, e2);
    return t2.forEach((e3) => this.recordVersion(e3)), t2;
  }
  set(e2, t2) {
    this.write(t2.toMutation(e2, this.precondition(e2))), this.writtenDocs.add(e2.toString());
  }
  update(e2, t2) {
    try {
      this.write(t2.toMutation(e2, this.preconditionForUpdate(e2)));
    } catch (e3) {
      this.lastTransactionError = e3;
    }
    this.writtenDocs.add(e2.toString());
  }
  delete(e2) {
    this.write(new __PRIVATE_DeleteMutation(e2, this.precondition(e2))), this.writtenDocs.add(e2.toString());
  }
  async commit() {
    if (this.ensureCommitNotCalled(), this.lastTransactionError) throw this.lastTransactionError;
    const e2 = this.readVersions;
    this.mutations.forEach((t2) => {
      e2.delete(t2.key.toString());
    }), // For each document that was read but not written to, we want to perform
    // a `verify` operation.
    e2.forEach((e3, t2) => {
      const n2 = DocumentKey.fromPath(t2);
      this.mutations.push(new __PRIVATE_VerifyMutation(n2, this.precondition(n2)));
    }), await (/* @__PURE__ */ __name(async function __PRIVATE_invokeCommitRpc(e3, t2) {
      const n2 = __PRIVATE_debugCast(e3), r2 = {
        writes: t2.map((e4) => toMutation(n2.serializer, e4))
      };
      await n2.So("Commit", n2.serializer.databaseId, ResourcePath.emptyPath(), r2);
    }, "__PRIVATE_invokeCommitRpc"))(this.datastore, this.mutations), this.committed = true;
  }
  recordVersion(e2) {
    let t2;
    if (e2.isFoundDocument()) t2 = e2.version;
    else {
      if (!e2.isNoDocument()) throw fail();
      t2 = SnapshotVersion.min();
    }
    const n2 = this.readVersions.get(e2.key.toString());
    if (n2) {
      if (!t2.isEqual(n2))
        throw new FirestoreError(C.ABORTED, "Document version changed between two reads.");
    } else this.readVersions.set(e2.key.toString(), t2);
  }
  /**
   * Returns the version of this document when it was read in this transaction,
   * as a precondition, or no precondition if it was not read.
   */
  precondition(e2) {
    const t2 = this.readVersions.get(e2.toString());
    return !this.writtenDocs.has(e2.toString()) && t2 ? t2.isEqual(SnapshotVersion.min()) ? Precondition.exists(false) : Precondition.updateTime(t2) : Precondition.none();
  }
  /**
   * Returns the precondition for a document if the operation is an update.
   */
  preconditionForUpdate(e2) {
    const t2 = this.readVersions.get(e2.toString());
    if (!this.writtenDocs.has(e2.toString()) && t2) {
      if (t2.isEqual(SnapshotVersion.min()))
        throw new FirestoreError(C.INVALID_ARGUMENT, "Can't update a document that doesn't exist.");
      return Precondition.updateTime(t2);
    }
    return Precondition.exists(true);
  }
  write(e2) {
    this.ensureCommitNotCalled(), this.mutations.push(e2);
  }
  ensureCommitNotCalled() {
  }
}
/**
 * @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 __PRIVATE_TransactionRunner {
  static {
    __name(this, "__PRIVATE_TransactionRunner");
  }
  constructor(e2, t2, n2, r2, i2) {
    this.asyncQueue = e2, this.datastore = t2, this.options = n2, this.updateFunction = r2, this.deferred = i2, this.Tu = n2.maxAttempts, this.a_ = new __PRIVATE_ExponentialBackoff(
      this.asyncQueue,
      "transaction_retry"
      /* TimerId.TransactionRetry */
    );
  }
  /** Runs the transaction and sets the result on deferred. */
  Iu() {
    this.Tu -= 1, this.Eu();
  }
  Eu() {
    this.a_.Xo(async () => {
      const e2 = new Transaction$2(this.datastore), t2 = this.du(e2);
      t2 && t2.then((t3) => {
        this.asyncQueue.enqueueAndForget(() => e2.commit().then(() => {
          this.deferred.resolve(t3);
        }).catch((e3) => {
          this.Au(e3);
        }));
      }).catch((e3) => {
        this.Au(e3);
      });
    });
  }
  du(e2) {
    try {
      const t2 = this.updateFunction(e2);
      return !__PRIVATE_isNullOrUndefined(t2) && t2.catch && t2.then ? t2 : (this.deferred.reject(Error("Transaction callback must return a Promise")), null);
    } catch (e3) {
      return this.deferred.reject(e3), null;
    }
  }
  Au(e2) {
    this.Tu > 0 && this.Ru(e2) ? (this.Tu -= 1, this.asyncQueue.enqueueAndForget(() => (this.Eu(), Promise.resolve()))) : this.deferred.reject(e2);
  }
  Ru(e2) {
    if ("FirebaseError" === e2.name) {
      const t2 = e2.code;
      return "aborted" === t2 || "failed-precondition" === t2 || "already-exists" === t2 || !__PRIVATE_isPermanentError(t2);
    }
    return 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 Yt = "FirestoreClient";
class FirestoreClient {
  static {
    __name(this, "FirestoreClient");
  }
  constructor(e2, t2, n2, r2, i2) {
    this.authCredentials = e2, this.appCheckCredentials = t2, this.asyncQueue = n2, this.databaseInfo = r2, this.user = User.UNAUTHENTICATED, this.clientId = __PRIVATE_AutoId.newId(), this.authCredentialListener = () => Promise.resolve(), this.appCheckCredentialListener = () => Promise.resolve(), this._uninitializedComponentsProvider = i2, this.authCredentials.start(n2, async (e3) => {
      __PRIVATE_logDebug(Yt, "Received user=", e3.uid), await this.authCredentialListener(e3), this.user = e3;
    }), this.appCheckCredentials.start(n2, (e3) => (__PRIVATE_logDebug(Yt, "Received new app check token=", e3), this.appCheckCredentialListener(e3, this.user)));
  }
  get configuration() {
    return {
      asyncQueue: this.asyncQueue,
      databaseInfo: this.databaseInfo,
      clientId: this.clientId,
      authCredentials: this.authCredentials,
      appCheckCredentials: this.appCheckCredentials,
      initialUser: this.user,
      maxConcurrentLimboResolutions: 100
    };
  }
  setCredentialChangeListener(e2) {
    this.authCredentialListener = e2;
  }
  setAppCheckTokenChangeListener(e2) {
    this.appCheckCredentialListener = e2;
  }
  terminate() {
    this.asyncQueue.enterRestrictedMode();
    const e2 = new __PRIVATE_Deferred();
    return this.asyncQueue.enqueueAndForgetEvenWhileRestricted(async () => {
      try {
        this._onlineComponents && await this._onlineComponents.terminate(), this._offlineComponents && await this._offlineComponents.terminate(), // The credentials provider must be terminated after shutting down the
        // RemoteStore as it will prevent the RemoteStore from retrieving auth
        // tokens.
        this.authCredentials.shutdown(), this.appCheckCredentials.shutdown(), e2.resolve();
      } catch (t2) {
        const n2 = __PRIVATE_wrapInUserErrorIfRecoverable(t2, "Failed to shutdown persistence");
        e2.reject(n2);
      }
    }), e2.promise;
  }
}
async function __PRIVATE_setOfflineComponentProvider(e2, t2) {
  e2.asyncQueue.verifyOperationInProgress(), __PRIVATE_logDebug(Yt, "Initializing OfflineComponentProvider");
  const n2 = e2.configuration;
  await t2.initialize(n2);
  let r2 = n2.initialUser;
  e2.setCredentialChangeListener(async (e3) => {
    r2.isEqual(e3) || (await __PRIVATE_localStoreHandleUserChange(t2.localStore, e3), r2 = e3);
  }), // When a user calls clearPersistence() in one client, all other clients
  // need to be terminated to allow the delete to succeed.
  t2.persistence.setDatabaseDeletedListener(() => e2.terminate()), e2._offlineComponents = t2;
}
__name(__PRIVATE_setOfflineComponentProvider, "__PRIVATE_setOfflineComponentProvider");
async function __PRIVATE_setOnlineComponentProvider(e2, t2) {
  e2.asyncQueue.verifyOperationInProgress();
  const n2 = await __PRIVATE_ensureOfflineComponents(e2);
  __PRIVATE_logDebug(Yt, "Initializing OnlineComponentProvider"), await t2.initialize(n2, e2.configuration), // The CredentialChangeListener of the online component provider takes
  // precedence over the offline component provider.
  e2.setCredentialChangeListener((e3) => __PRIVATE_remoteStoreHandleCredentialChange(t2.remoteStore, e3)), e2.setAppCheckTokenChangeListener((e3, n3) => __PRIVATE_remoteStoreHandleCredentialChange(t2.remoteStore, n3)), e2._onlineComponents = t2;
}
__name(__PRIVATE_setOnlineComponentProvider, "__PRIVATE_setOnlineComponentProvider");
async function __PRIVATE_ensureOfflineComponents(e2) {
  if (!e2._offlineComponents) if (e2._uninitializedComponentsProvider) {
    __PRIVATE_logDebug(Yt, "Using user provided OfflineComponentProvider");
    try {
      await __PRIVATE_setOfflineComponentProvider(e2, e2._uninitializedComponentsProvider._offline);
    } catch (t2) {
      const n2 = t2;
      if (!(/* @__PURE__ */ __name(function __PRIVATE_canFallbackFromIndexedDbError(e3) {
        return "FirebaseError" === e3.name ? e3.code === C.FAILED_PRECONDITION || e3.code === C.UNIMPLEMENTED : !("undefined" != typeof DOMException && e3 instanceof DOMException) || // When the browser is out of quota we could get either quota exceeded
        // or an aborted error depending on whether the error happened during
        // schema migration.
        22 === e3.code || 20 === e3.code || // Firefox Private Browsing mode disables IndexedDb and returns
        // INVALID_STATE for any usage.
        11 === e3.code;
      }, "__PRIVATE_canFallbackFromIndexedDbError"))(n2)) throw n2;
      __PRIVATE_logWarn("Error using user provided cache. Falling back to memory cache: " + n2), await __PRIVATE_setOfflineComponentProvider(e2, new __PRIVATE_MemoryOfflineComponentProvider());
    }
  } else __PRIVATE_logDebug(Yt, "Using default OfflineComponentProvider"), await __PRIVATE_setOfflineComponentProvider(e2, new __PRIVATE_LruGcMemoryOfflineComponentProvider(void 0));
  return e2._offlineComponents;
}
__name(__PRIVATE_ensureOfflineComponents, "__PRIVATE_ensureOfflineComponents");
async function __PRIVATE_ensureOnlineComponents(e2) {
  return e2._onlineComponents || (e2._uninitializedComponentsProvider ? (__PRIVATE_logDebug(Yt, "Using user provided OnlineComponentProvider"), await __PRIVATE_setOnlineComponentProvider(e2, e2._uninitializedComponentsProvider._online)) : (__PRIVATE_logDebug(Yt, "Using default OnlineComponentProvider"), await __PRIVATE_setOnlineComponentProvider(e2, new OnlineComponentProvider()))), e2._onlineComponents;
}
__name(__PRIVATE_ensureOnlineComponents, "__PRIVATE_ensureOnlineComponents");
function __PRIVATE_getPersistence(e2) {
  return __PRIVATE_ensureOfflineComponents(e2).then((e3) => e3.persistence);
}
__name(__PRIVATE_getPersistence, "__PRIVATE_getPersistence");
function __PRIVATE_getLocalStore(e2) {
  return __PRIVATE_ensureOfflineComponents(e2).then((e3) => e3.localStore);
}
__name(__PRIVATE_getLocalStore, "__PRIVATE_getLocalStore");
function __PRIVATE_getRemoteStore(e2) {
  return __PRIVATE_ensureOnlineComponents(e2).then((e3) => e3.remoteStore);
}
__name(__PRIVATE_getRemoteStore, "__PRIVATE_getRemoteStore");
function __PRIVATE_getSyncEngine(e2) {
  return __PRIVATE_ensureOnlineComponents(e2).then((e3) => e3.syncEngine);
}
__name(__PRIVATE_getSyncEngine, "__PRIVATE_getSyncEngine");
function __PRIVATE_getDatastore(e2) {
  return __PRIVATE_ensureOnlineComponents(e2).then((e3) => e3.datastore);
}
__name(__PRIVATE_getDatastore, "__PRIVATE_getDatastore");
async function __PRIVATE_getEventManager(e2) {
  const t2 = await __PRIVATE_ensureOnlineComponents(e2), n2 = t2.eventManager;
  return n2.onListen = __PRIVATE_syncEngineListen.bind(null, t2.syncEngine), n2.onUnlisten = __PRIVATE_syncEngineUnlisten.bind(null, t2.syncEngine), n2.onFirstRemoteStoreListen = __PRIVATE_triggerRemoteStoreListen.bind(null, t2.syncEngine), n2.onLastRemoteStoreUnlisten = __PRIVATE_triggerRemoteStoreUnlisten.bind(null, t2.syncEngine), n2;
}
__name(__PRIVATE_getEventManager, "__PRIVATE_getEventManager");
function __PRIVATE_firestoreClientEnableNetwork(e2) {
  return e2.asyncQueue.enqueue(async () => {
    const t2 = await __PRIVATE_getPersistence(e2), n2 = await __PRIVATE_getRemoteStore(e2);
    return t2.setNetworkEnabled(true), (/* @__PURE__ */ __name(function __PRIVATE_remoteStoreEnableNetwork(e3) {
      const t3 = __PRIVATE_debugCast(e3);
      return t3.W_.delete(
        0
        /* OfflineCause.UserDisabled */
      ), __PRIVATE_enableNetworkInternal(t3);
    }, "__PRIVATE_remoteStoreEnableNetwork"))(n2);
  });
}
__name(__PRIVATE_firestoreClientEnableNetwork, "__PRIVATE_firestoreClientEnableNetwork");
function __PRIVATE_firestoreClientDisableNetwork(e2) {
  return e2.asyncQueue.enqueue(async () => {
    const t2 = await __PRIVATE_getPersistence(e2), n2 = await __PRIVATE_getRemoteStore(e2);
    return t2.setNetworkEnabled(false), (/* @__PURE__ */ __name(async function __PRIVATE_remoteStoreDisableNetwork(e3) {
      const t3 = __PRIVATE_debugCast(e3);
      t3.W_.add(
        0
        /* OfflineCause.UserDisabled */
      ), await __PRIVATE_disableNetworkInternal(t3), // Set the OnlineState to Offline so get()s return from cache, etc.
      t3.j_.set(
        "Offline"
        /* OnlineState.Offline */
      );
    }, "__PRIVATE_remoteStoreDisableNetwork"))(n2);
  });
}
__name(__PRIVATE_firestoreClientDisableNetwork, "__PRIVATE_firestoreClientDisableNetwork");
function __PRIVATE_firestoreClientGetDocumentFromLocalCache(e2, t2) {
  const n2 = new __PRIVATE_Deferred();
  return e2.asyncQueue.enqueueAndForget(async () => (/* @__PURE__ */ __name(async function __PRIVATE_readDocumentFromCache(e3, t3, n3) {
    try {
      const r2 = await (/* @__PURE__ */ __name(function __PRIVATE_localStoreReadDocument(e4, t4) {
        const n4 = __PRIVATE_debugCast(e4);
        return n4.persistence.runTransaction("read document", "readonly", (e5) => n4.localDocuments.getDocument(e5, t4));
      }, "__PRIVATE_localStoreReadDocument"))(e3, t3);
      r2.isFoundDocument() ? n3.resolve(r2) : r2.isNoDocument() ? n3.resolve(null) : n3.reject(new FirestoreError(C.UNAVAILABLE, "Failed to get document from cache. (However, this document may exist on the server. Run again without setting 'source' in the GetOptions to attempt to retrieve the document from the server.)"));
    } catch (e4) {
      const r2 = __PRIVATE_wrapInUserErrorIfRecoverable(e4, `Failed to get document '${t3} from cache`);
      n3.reject(r2);
    }
  }, "__PRIVATE_readDocumentFromCache"))(await __PRIVATE_getLocalStore(e2), t2, n2)), n2.promise;
}
__name(__PRIVATE_firestoreClientGetDocumentFromLocalCache, "__PRIVATE_firestoreClientGetDocumentFromLocalCache");
function __PRIVATE_firestoreClientGetDocumentViaSnapshotListener(e2, t2, n2 = {}) {
  const r2 = new __PRIVATE_Deferred();
  return e2.asyncQueue.enqueueAndForget(async () => (/* @__PURE__ */ __name(function __PRIVATE_readDocumentViaSnapshotListener(e3, t3, n3, r3, i2) {
    const s2 = new __PRIVATE_AsyncObserver({
      next: /* @__PURE__ */ __name((_2) => {
        s2.su(), t3.enqueueAndForget(() => __PRIVATE_eventManagerUnlisten(e3, o2));
        const a2 = _2.docs.has(n3);
        !a2 && _2.fromCache ? (
          // TODO(dimond): If we're online and the document doesn't
          // exist then we resolve with a doc.exists set to false. If
          // we're offline however, we reject the Promise in this
          // case. Two options: 1) Cache the negative response from
          // the server so we can deliver that even when you're
          // offline 2) Actually reject the Promise in the online case
          // if the document doesn't exist.
          i2.reject(new FirestoreError(C.UNAVAILABLE, "Failed to get document because the client is offline."))
        ) : a2 && _2.fromCache && r3 && "server" === r3.source ? i2.reject(new FirestoreError(C.UNAVAILABLE, 'Failed to get document from server. (However, this document does exist in the local cache. Run again without setting source to "server" to retrieve the cached document.)')) : i2.resolve(_2);
      }, "next"),
      error: /* @__PURE__ */ __name((e4) => i2.reject(e4), "error")
    }), o2 = new __PRIVATE_QueryListener(__PRIVATE_newQueryForPath(n3.path), s2, {
      includeMetadataChanges: true,
      Ta: true
    });
    return __PRIVATE_eventManagerListen(e3, o2);
  }, "__PRIVATE_readDocumentViaSnapshotListener"))(await __PRIVATE_getEventManager(e2), e2.asyncQueue, t2, n2, r2)), r2.promise;
}
__name(__PRIVATE_firestoreClientGetDocumentViaSnapshotListener, "__PRIVATE_firestoreClientGetDocumentViaSnapshotListener");
function __PRIVATE_firestoreClientGetDocumentsFromLocalCache(e2, t2) {
  const n2 = new __PRIVATE_Deferred();
  return e2.asyncQueue.enqueueAndForget(async () => (/* @__PURE__ */ __name(async function __PRIVATE_executeQueryFromCache(e3, t3, n3) {
    try {
      const r2 = await __PRIVATE_localStoreExecuteQuery(
        e3,
        t3,
        /* usePreviousResults= */
        true
      ), i2 = new __PRIVATE_View(t3, r2.gs), s2 = i2.ba(r2.documents), o2 = i2.applyChanges(
        s2,
        /* limboResolutionEnabled= */
        false
      );
      n3.resolve(o2.snapshot);
    } catch (e4) {
      const r2 = __PRIVATE_wrapInUserErrorIfRecoverable(e4, `Failed to execute query '${t3} against cache`);
      n3.reject(r2);
    }
  }, "__PRIVATE_executeQueryFromCache"))(await __PRIVATE_getLocalStore(e2), t2, n2)), n2.promise;
}
__name(__PRIVATE_firestoreClientGetDocumentsFromLocalCache, "__PRIVATE_firestoreClientGetDocumentsFromLocalCache");
function __PRIVATE_firestoreClientGetDocumentsViaSnapshotListener(e2, t2, n2 = {}) {
  const r2 = new __PRIVATE_Deferred();
  return e2.asyncQueue.enqueueAndForget(async () => (/* @__PURE__ */ __name(function __PRIVATE_executeQueryViaSnapshotListener(e3, t3, n3, r3, i2) {
    const s2 = new __PRIVATE_AsyncObserver({
      next: /* @__PURE__ */ __name((n4) => {
        s2.su(), t3.enqueueAndForget(() => __PRIVATE_eventManagerUnlisten(e3, o2)), n4.fromCache && "server" === r3.source ? i2.reject(new FirestoreError(C.UNAVAILABLE, 'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to "server" to retrieve the cached documents.)')) : i2.resolve(n4);
      }, "next"),
      error: /* @__PURE__ */ __name((e4) => i2.reject(e4), "error")
    }), o2 = new __PRIVATE_QueryListener(n3, s2, {
      includeMetadataChanges: true,
      Ta: true
    });
    return __PRIVATE_eventManagerListen(e3, o2);
  }, "__PRIVATE_executeQueryViaSnapshotListener"))(await __PRIVATE_getEventManager(e2), e2.asyncQueue, t2, n2, r2)), r2.promise;
}
__name(__PRIVATE_firestoreClientGetDocumentsViaSnapshotListener, "__PRIVATE_firestoreClientGetDocumentsViaSnapshotListener");
function __PRIVATE_firestoreClientRunAggregateQuery(e2, t2, n2) {
  const r2 = new __PRIVATE_Deferred();
  return e2.asyncQueue.enqueueAndForget(async () => {
    try {
      const i2 = await __PRIVATE_getDatastore(e2);
      r2.resolve((/* @__PURE__ */ __name(async function __PRIVATE_invokeRunAggregationQueryRpc(e3, t3, n3) {
        var r3;
        const i3 = __PRIVATE_debugCast(e3), { request: s2, Pt: o2, parent: _2 } = __PRIVATE_toRunAggregationQueryRequest(i3.serializer, __PRIVATE_queryToAggregateTarget(t3), n3);
        i3.connection.fo || delete s2.parent;
        const a2 = (await i3.Co(
          "RunAggregationQuery",
          i3.serializer.databaseId,
          _2,
          s2,
          /*expectedResponseCount=*/
          1
        )).filter((e4) => !!e4.result);
        __PRIVATE_hardAssert(1 === a2.length);
        const u2 = null === (r3 = a2[0].result) || void 0 === r3 ? void 0 : r3.aggregateFields;
        return Object.keys(u2).reduce((e4, t4) => (e4[o2[t4]] = u2[t4], e4), {});
      }, "__PRIVATE_invokeRunAggregationQueryRpc"))(i2, t2, n2));
    } catch (e3) {
      r2.reject(e3);
    }
  }), r2.promise;
}
__name(__PRIVATE_firestoreClientRunAggregateQuery, "__PRIVATE_firestoreClientRunAggregateQuery");
function __PRIVATE_firestoreClientAddSnapshotsInSyncListener(e2, t2) {
  const n2 = new __PRIVATE_AsyncObserver(t2);
  return e2.asyncQueue.enqueueAndForget(async () => (/* @__PURE__ */ __name(function __PRIVATE_addSnapshotsInSyncListener(e3, t3) {
    __PRIVATE_debugCast(e3).ia.add(t3), // Immediately fire an initial event, indicating all existing listeners
    // are in-sync.
    t3.next();
  }, "__PRIVATE_addSnapshotsInSyncListener"))(await __PRIVATE_getEventManager(e2), n2)), () => {
    n2.su(), e2.asyncQueue.enqueueAndForget(async () => (/* @__PURE__ */ __name(function __PRIVATE_removeSnapshotsInSyncListener(e3, t3) {
      __PRIVATE_debugCast(e3).ia.delete(t3);
    }, "__PRIVATE_removeSnapshotsInSyncListener"))(await __PRIVATE_getEventManager(e2), n2));
  };
}
__name(__PRIVATE_firestoreClientAddSnapshotsInSyncListener, "__PRIVATE_firestoreClientAddSnapshotsInSyncListener");
function __PRIVATE_firestoreClientLoadBundle(e2, t2, n2, r2) {
  const i2 = (/* @__PURE__ */ __name(function __PRIVATE_createBundleReader(e3, t3) {
    let n3;
    n3 = "string" == typeof e3 ? __PRIVATE_newTextEncoder().encode(e3) : e3;
    return (/* @__PURE__ */ __name(function __PRIVATE_newBundleReader(e4, t4) {
      return new __PRIVATE_BundleReaderImpl(e4, t4);
    }, "__PRIVATE_newBundleReader"))((/* @__PURE__ */ __name(function __PRIVATE_toByteStreamReader(e4, t4) {
      if (e4 instanceof Uint8Array) return __PRIVATE_toByteStreamReaderHelper(e4, t4);
      if (e4 instanceof ArrayBuffer) return __PRIVATE_toByteStreamReaderHelper(new Uint8Array(e4), t4);
      if (e4 instanceof ReadableStream) return e4.getReader();
      throw new Error("Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream");
    }, "__PRIVATE_toByteStreamReader"))(n3), t3);
  }, "__PRIVATE_createBundleReader"))(n2, __PRIVATE_newSerializer(t2));
  e2.asyncQueue.enqueueAndForget(async () => {
    __PRIVATE_syncEngineLoadBundle(await __PRIVATE_getSyncEngine(e2), i2, r2);
  });
}
__name(__PRIVATE_firestoreClientLoadBundle, "__PRIVATE_firestoreClientLoadBundle");
function __PRIVATE_firestoreClientGetNamedQuery(e2, t2) {
  return e2.asyncQueue.enqueue(async () => (/* @__PURE__ */ __name(function __PRIVATE_localStoreGetNamedQuery(e3, t3) {
    const n2 = __PRIVATE_debugCast(e3);
    return n2.persistence.runTransaction("Get named query", "readonly", (e4) => n2.Yr.getNamedQuery(e4, t3));
  }, "__PRIVATE_localStoreGetNamedQuery"))(await __PRIVATE_getLocalStore(e2), t2));
}
__name(__PRIVATE_firestoreClientGetNamedQuery, "__PRIVATE_firestoreClientGetNamedQuery");
function __PRIVATE_firestoreClientSetIndexConfiguration(e2, t2) {
  return e2.asyncQueue.enqueue(async () => (/* @__PURE__ */ __name(async function __PRIVATE_localStoreConfigureFieldIndexes(e3, t3) {
    const n2 = __PRIVATE_debugCast(e3), r2 = n2.indexManager, i2 = [];
    return n2.persistence.runTransaction("Configure indexes", "readwrite", (e4) => r2.getFieldIndexes(e4).next((n3) => (
      /**
      * @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.
      */
      /**
      * Compares two array for equality using comparator. The method computes the
      * intersection and invokes `onAdd` for every element that is in `after` but not
      * `before`. `onRemove` is invoked for every element in `before` but missing
      * from `after`.
      *
      * The method creates a copy of both `before` and `after` and runs in O(n log
      * n), where n is the size of the two lists.
      *
      * @param before - The elements that exist in the original array.
      * @param after - The elements to diff against the original array.
      * @param comparator - The comparator for the elements in before and after.
      * @param onAdd - A function to invoke for every element that is part of `
      * after` but not `before`.
      * @param onRemove - A function to invoke for every element that is part of
      * `before` but not `after`.
      */
      (/* @__PURE__ */ __name(function __PRIVATE_diffArrays(e5, t4, n4, r3, i3) {
        e5 = [...e5], t4 = [...t4], e5.sort(n4), t4.sort(n4);
        const s2 = e5.length, o2 = t4.length;
        let _2 = 0, a2 = 0;
        for (; _2 < o2 && a2 < s2; ) {
          const s3 = n4(e5[a2], t4[_2]);
          s3 < 0 ? (
            // The element was removed if the next element in our ordered
            // walkthrough is only in `before`.
            i3(e5[a2++])
          ) : s3 > 0 ? (
            // The element was added if the next element in our ordered walkthrough
            // is only in `after`.
            r3(t4[_2++])
          ) : (_2++, a2++);
        }
        for (; _2 < o2; ) r3(t4[_2++]);
        for (; a2 < s2; ) i3(e5[a2++]);
      }, "__PRIVATE_diffArrays"))(n3, t3, __PRIVATE_fieldIndexSemanticComparator, (t4) => {
        i2.push(r2.addFieldIndex(e4, t4));
      }, (t4) => {
        i2.push(r2.deleteFieldIndex(e4, t4));
      })
    )).next(() => PersistencePromise.waitFor(i2)));
  }, "__PRIVATE_localStoreConfigureFieldIndexes"))(await __PRIVATE_getLocalStore(e2), t2));
}
__name(__PRIVATE_firestoreClientSetIndexConfiguration, "__PRIVATE_firestoreClientSetIndexConfiguration");
function __PRIVATE_firestoreClientSetPersistentCacheIndexAutoCreationEnabled(e2, t2) {
  return e2.asyncQueue.enqueue(async () => (/* @__PURE__ */ __name(function __PRIVATE_localStoreSetIndexAutoCreationEnabled(e3, t3) {
    __PRIVATE_debugCast(e3).Ps.Xi = t3;
  }, "__PRIVATE_localStoreSetIndexAutoCreationEnabled"))(await __PRIVATE_getLocalStore(e2), t2));
}
__name(__PRIVATE_firestoreClientSetPersistentCacheIndexAutoCreationEnabled, "__PRIVATE_firestoreClientSetPersistentCacheIndexAutoCreationEnabled");
function __PRIVATE_firestoreClientDeleteAllFieldIndexes(e2) {
  return e2.asyncQueue.enqueue(async () => (/* @__PURE__ */ __name(function __PRIVATE_localStoreDeleteAllFieldIndexes(e3) {
    const t2 = __PRIVATE_debugCast(e3), n2 = t2.indexManager;
    return t2.persistence.runTransaction("Delete All Indexes", "readwrite", (e4) => n2.deleteAllFieldIndexes(e4));
  }, "__PRIVATE_localStoreDeleteAllFieldIndexes"))(await __PRIVATE_getLocalStore(e2)));
}
__name(__PRIVATE_firestoreClientDeleteAllFieldIndexes, "__PRIVATE_firestoreClientDeleteAllFieldIndexes");
/**
 * @license
 * Copyright 2023 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 __PRIVATE_cloneLongPollingOptions(e2) {
  const t2 = {};
  return void 0 !== e2.timeoutSeconds && (t2.timeoutSeconds = e2.timeoutSeconds), t2;
}
__name(__PRIVATE_cloneLongPollingOptions, "__PRIVATE_cloneLongPollingOptions");
/**
 * @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 Zt = /* @__PURE__ */ new Map();
/**
 * @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 __PRIVATE_validateNonEmptyArgument(e2, t2, n2) {
  if (!n2) throw new FirestoreError(C.INVALID_ARGUMENT, `Function ${e2}() cannot be called with an empty ${t2}.`);
}
__name(__PRIVATE_validateNonEmptyArgument, "__PRIVATE_validateNonEmptyArgument");
function __PRIVATE_validateIsNotUsedTogether(e2, t2, n2, r2) {
  if (true === t2 && true === r2) throw new FirestoreError(C.INVALID_ARGUMENT, `${e2} and ${n2} cannot be used together.`);
}
__name(__PRIVATE_validateIsNotUsedTogether, "__PRIVATE_validateIsNotUsedTogether");
function __PRIVATE_validateDocumentPath(e2) {
  if (!DocumentKey.isDocumentKey(e2)) throw new FirestoreError(C.INVALID_ARGUMENT, `Invalid document reference. Document references must have an even number of segments, but ${e2} has ${e2.length}.`);
}
__name(__PRIVATE_validateDocumentPath, "__PRIVATE_validateDocumentPath");
function __PRIVATE_validateCollectionPath(e2) {
  if (DocumentKey.isDocumentKey(e2)) throw new FirestoreError(C.INVALID_ARGUMENT, `Invalid collection reference. Collection references must have an odd number of segments, but ${e2} has ${e2.length}.`);
}
__name(__PRIVATE_validateCollectionPath, "__PRIVATE_validateCollectionPath");
function __PRIVATE_valueDescription(e2) {
  if (void 0 === e2) return "undefined";
  if (null === e2) return "null";
  if ("string" == typeof e2) return e2.length > 20 && (e2 = `${e2.substring(0, 20)}...`), JSON.stringify(e2);
  if ("number" == typeof e2 || "boolean" == typeof e2) return "" + e2;
  if ("object" == typeof e2) {
    if (e2 instanceof Array) return "an array";
    {
      const t2 = (
        /** try to get the constructor name for an object. */
        (/* @__PURE__ */ __name(function __PRIVATE_tryGetCustomObjectType(e3) {
          if (e3.constructor) return e3.constructor.name;
          return null;
        }, "__PRIVATE_tryGetCustomObjectType"))(e2)
      );
      return t2 ? `a custom ${t2} object` : "an object";
    }
  }
  return "function" == typeof e2 ? "a function" : fail();
}
__name(__PRIVATE_valueDescription, "__PRIVATE_valueDescription");
function __PRIVATE_cast(e2, t2) {
  if ("_delegate" in e2 && // Unwrap Compat types
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  (e2 = e2._delegate), !(e2 instanceof t2)) {
    if (t2.name === e2.constructor.name) throw new FirestoreError(C.INVALID_ARGUMENT, "Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");
    {
      const n2 = __PRIVATE_valueDescription(e2);
      throw new FirestoreError(C.INVALID_ARGUMENT, `Expected type '${t2.name}', but it was: ${n2}`);
    }
  }
  return e2;
}
__name(__PRIVATE_cast, "__PRIVATE_cast");
function __PRIVATE_validatePositiveNumber(e2, t2) {
  if (t2 <= 0) throw new FirestoreError(C.INVALID_ARGUMENT, `Function ${e2}() requires a positive number, but it was: ${t2}.`);
}
__name(__PRIVATE_validatePositiveNumber, "__PRIVATE_validatePositiveNumber");
/**
 * @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 Xt = "firestore.googleapis.com", en$1 = true;
class FirestoreSettingsImpl {
  static {
    __name(this, "FirestoreSettingsImpl");
  }
  constructor(e2) {
    var t2, n2;
    if (void 0 === e2.host) {
      if (void 0 !== e2.ssl) throw new FirestoreError(C.INVALID_ARGUMENT, "Can't provide ssl option if host option is not set");
      this.host = Xt, this.ssl = en$1;
    } else this.host = e2.host, this.ssl = null !== (t2 = e2.ssl) && void 0 !== t2 ? t2 : en$1;
    if (this.credentials = e2.credentials, this.ignoreUndefinedProperties = !!e2.ignoreUndefinedProperties, this.localCache = e2.localCache, void 0 === e2.cacheSizeBytes) this.cacheSizeBytes = St;
    else {
      if (-1 !== e2.cacheSizeBytes && e2.cacheSizeBytes < Dt) throw new FirestoreError(C.INVALID_ARGUMENT, "cacheSizeBytes must be at least 1048576");
      this.cacheSizeBytes = e2.cacheSizeBytes;
    }
    __PRIVATE_validateIsNotUsedTogether("experimentalForceLongPolling", e2.experimentalForceLongPolling, "experimentalAutoDetectLongPolling", e2.experimentalAutoDetectLongPolling), this.experimentalForceLongPolling = !!e2.experimentalForceLongPolling, this.experimentalForceLongPolling ? this.experimentalAutoDetectLongPolling = false : void 0 === e2.experimentalAutoDetectLongPolling ? this.experimentalAutoDetectLongPolling = true : (
      // For backwards compatibility, coerce the value to boolean even though
      // the TypeScript compiler has narrowed the type to boolean already.
      // noinspection PointlessBooleanExpressionJS
      this.experimentalAutoDetectLongPolling = !!e2.experimentalAutoDetectLongPolling
    ), this.experimentalLongPollingOptions = __PRIVATE_cloneLongPollingOptions(null !== (n2 = e2.experimentalLongPollingOptions) && void 0 !== n2 ? n2 : {}), (/* @__PURE__ */ __name(function __PRIVATE_validateLongPollingOptions(e3) {
      if (void 0 !== e3.timeoutSeconds) {
        if (isNaN(e3.timeoutSeconds)) throw new FirestoreError(C.INVALID_ARGUMENT, `invalid long polling timeout: ${e3.timeoutSeconds} (must not be NaN)`);
        if (e3.timeoutSeconds < 5) throw new FirestoreError(C.INVALID_ARGUMENT, `invalid long polling timeout: ${e3.timeoutSeconds} (minimum allowed value is 5)`);
        if (e3.timeoutSeconds > 30) throw new FirestoreError(C.INVALID_ARGUMENT, `invalid long polling timeout: ${e3.timeoutSeconds} (maximum allowed value is 30)`);
      }
    }, "__PRIVATE_validateLongPollingOptions"))(this.experimentalLongPollingOptions), this.useFetchStreams = !!e2.useFetchStreams;
  }
  isEqual(e2) {
    return this.host === e2.host && this.ssl === e2.ssl && this.credentials === e2.credentials && this.cacheSizeBytes === e2.cacheSizeBytes && this.experimentalForceLongPolling === e2.experimentalForceLongPolling && this.experimentalAutoDetectLongPolling === e2.experimentalAutoDetectLongPolling && (/* @__PURE__ */ __name(function __PRIVATE_longPollingOptionsEqual(e3, t2) {
      return e3.timeoutSeconds === t2.timeoutSeconds;
    }, "__PRIVATE_longPollingOptionsEqual"))(this.experimentalLongPollingOptions, e2.experimentalLongPollingOptions) && this.ignoreUndefinedProperties === e2.ignoreUndefinedProperties && this.useFetchStreams === e2.useFetchStreams;
  }
}
class Firestore$1 {
  static {
    __name(this, "Firestore$1");
  }
  /** @hideconstructor */
  constructor(e2, t2, n2, r2) {
    this._authCredentials = e2, this._appCheckCredentials = t2, this._databaseId = n2, this._app = r2, /**
     * Whether it's a Firestore or Firestore Lite instance.
     */
    this.type = "firestore-lite", this._persistenceKey = "(lite)", this._settings = new FirestoreSettingsImpl({}), this._settingsFrozen = false, this._emulatorOptions = {}, // A task that is assigned when the terminate() is invoked and resolved when
    // all components have shut down. Otherwise, Firestore is not terminated,
    // which can mean either the FirestoreClient is in the process of starting,
    // or restarting.
    this._terminateTask = "notTerminated";
  }
  /**
   * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service
   * instance.
   */
  get app() {
    if (!this._app) throw new FirestoreError(C.FAILED_PRECONDITION, "Firestore was not initialized using the Firebase SDK. 'app' is not available");
    return this._app;
  }
  get _initialized() {
    return this._settingsFrozen;
  }
  get _terminated() {
    return "notTerminated" !== this._terminateTask;
  }
  _setSettings(e2) {
    if (this._settingsFrozen) throw new FirestoreError(C.FAILED_PRECONDITION, "Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object.");
    this._settings = new FirestoreSettingsImpl(e2), this._emulatorOptions = e2.emulatorOptions || {}, void 0 !== e2.credentials && (this._authCredentials = (/* @__PURE__ */ __name(function __PRIVATE_makeAuthCredentialsProvider(e3) {
      if (!e3) return new __PRIVATE_EmptyAuthCredentialsProvider();
      switch (e3.type) {
        case "firstParty":
          return new __PRIVATE_FirstPartyAuthCredentialsProvider(e3.sessionIndex || "0", e3.iamToken || null, e3.authTokenFactory || null);
        case "provider":
          return e3.client;
        default:
          throw new FirestoreError(C.INVALID_ARGUMENT, "makeAuthCredentialsProvider failed due to invalid credential type");
      }
    }, "__PRIVATE_makeAuthCredentialsProvider"))(e2.credentials));
  }
  _getSettings() {
    return this._settings;
  }
  _getEmulatorOptions() {
    return this._emulatorOptions;
  }
  _freezeSettings() {
    return this._settingsFrozen = true, this._settings;
  }
  _delete() {
    return "notTerminated" === this._terminateTask && (this._terminateTask = this._terminate()), this._terminateTask;
  }
  async _restart() {
    "notTerminated" === this._terminateTask ? await this._terminate() : this._terminateTask = "notTerminated";
  }
  /** Returns a JSON-serializable representation of this `Firestore` instance. */
  toJSON() {
    return {
      app: this._app,
      databaseId: this._databaseId,
      settings: this._settings
    };
  }
  /**
   * Terminates all components used by this client. Subclasses can override
   * this method to clean up their own dependencies, but must also call this
   * method.
   *
   * Only ever called once.
   */
  _terminate() {
    return (/* @__PURE__ */ __name(function __PRIVATE_removeComponents(e2) {
      const t2 = Zt.get(e2);
      t2 && (__PRIVATE_logDebug("ComponentProvider", "Removing Datastore"), Zt.delete(e2), t2.terminate());
    }, "__PRIVATE_removeComponents"))(this), Promise.resolve();
  }
}
function connectFirestoreEmulator(e2, t2, n2, r2 = {}) {
  var i2;
  const s2 = (e2 = __PRIVATE_cast(e2, Firestore$1))._getSettings(), o2 = Object.assign(Object.assign({}, s2), {
    emulatorOptions: e2._getEmulatorOptions()
  }), _2 = `${t2}:${n2}`;
  s2.host !== Xt && s2.host !== _2 && __PRIVATE_logWarn("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used.");
  const a2 = Object.assign(Object.assign({}, s2), {
    host: _2,
    ssl: false,
    emulatorOptions: r2
  });
  if (!deepEqual(a2, o2) && (e2._setSettings(a2), r2.mockUserToken)) {
    let t3, n3;
    if ("string" == typeof r2.mockUserToken) t3 = r2.mockUserToken, n3 = User.MOCK_USER;
    else {
      t3 = createMockUserToken(r2.mockUserToken, null === (i2 = e2._app) || void 0 === i2 ? void 0 : i2.options.projectId);
      const s3 = r2.mockUserToken.sub || r2.mockUserToken.user_id;
      if (!s3) throw new FirestoreError(C.INVALID_ARGUMENT, "mockUserToken must contain 'sub' or 'user_id' field!");
      n3 = new User(s3);
    }
    e2._authCredentials = new __PRIVATE_EmulatorAuthCredentialsProvider(new __PRIVATE_OAuthToken(t3, n3));
  }
}
__name(connectFirestoreEmulator, "connectFirestoreEmulator");
/**
 * @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 Query {
  static {
    __name(this, "Query");
  }
  // This is the lite version of the Query class in the main SDK.
  /** @hideconstructor protected */
  constructor(e2, t2, n2) {
    this.converter = t2, this._query = n2, /** The type of this Firestore reference. */
    this.type = "query", this.firestore = e2;
  }
  withConverter(e2) {
    return new Query(this.firestore, e2, this._query);
  }
}
class DocumentReference {
  static {
    __name(this, "DocumentReference");
  }
  /** @hideconstructor */
  constructor(e2, t2, n2) {
    this.converter = t2, this._key = n2, /** The type of this Firestore reference. */
    this.type = "document", this.firestore = e2;
  }
  get _path() {
    return this._key.path;
  }
  /**
   * The document's identifier within its collection.
   */
  get id() {
    return this._key.path.lastSegment();
  }
  /**
   * A string representing the path of the referenced document (relative
   * to the root of the database).
   */
  get path() {
    return this._key.path.canonicalString();
  }
  /**
   * The collection this `DocumentReference` belongs to.
   */
  get parent() {
    return new CollectionReference(this.firestore, this.converter, this._key.path.popLast());
  }
  withConverter(e2) {
    return new DocumentReference(this.firestore, e2, this._key);
  }
}
class CollectionReference extends Query {
  static {
    __name(this, "CollectionReference");
  }
  /** @hideconstructor */
  constructor(e2, t2, n2) {
    super(e2, t2, __PRIVATE_newQueryForPath(n2)), this._path = n2, /** The type of this Firestore reference. */
    this.type = "collection";
  }
  /** The collection's identifier. */
  get id() {
    return this._query.path.lastSegment();
  }
  /**
   * A string representing the path of the referenced collection (relative
   * to the root of the database).
   */
  get path() {
    return this._query.path.canonicalString();
  }
  /**
   * A reference to the containing `DocumentReference` if this is a
   * subcollection. If this isn't a subcollection, the reference is null.
   */
  get parent() {
    const e2 = this._path.popLast();
    return e2.isEmpty() ? null : new DocumentReference(
      this.firestore,
      /* converter= */
      null,
      new DocumentKey(e2)
    );
  }
  withConverter(e2) {
    return new CollectionReference(this.firestore, e2, this._path);
  }
}
function collection(e2, t2, ...n2) {
  if (e2 = getModularInstance(e2), __PRIVATE_validateNonEmptyArgument("collection", "path", t2), e2 instanceof Firestore$1) {
    const r2 = ResourcePath.fromString(t2, ...n2);
    return __PRIVATE_validateCollectionPath(r2), new CollectionReference(
      e2,
      /* converter= */
      null,
      r2
    );
  }
  {
    if (!(e2 instanceof DocumentReference || e2 instanceof CollectionReference)) throw new FirestoreError(C.INVALID_ARGUMENT, "Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");
    const r2 = e2._path.child(ResourcePath.fromString(t2, ...n2));
    return __PRIVATE_validateCollectionPath(r2), new CollectionReference(
      e2.firestore,
      /* converter= */
      null,
      r2
    );
  }
}
__name(collection, "collection");
function collectionGroup(e2, t2) {
  if (e2 = __PRIVATE_cast(e2, Firestore$1), __PRIVATE_validateNonEmptyArgument("collectionGroup", "collection id", t2), t2.indexOf("/") >= 0) throw new FirestoreError(C.INVALID_ARGUMENT, `Invalid collection ID '${t2}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);
  return new Query(
    e2,
    /* converter= */
    null,
    (/* @__PURE__ */ __name(function __PRIVATE_newQueryForCollectionGroup(e3) {
      return new __PRIVATE_QueryImpl(ResourcePath.emptyPath(), e3);
    }, "__PRIVATE_newQueryForCollectionGroup"))(t2)
  );
}
__name(collectionGroup, "collectionGroup");
function doc$2(e2, t2, ...n2) {
  if (e2 = getModularInstance(e2), // We allow omission of 'pathString' but explicitly prohibit passing in both
  // 'undefined' and 'null'.
  1 === arguments.length && (t2 = __PRIVATE_AutoId.newId()), __PRIVATE_validateNonEmptyArgument("doc", "path", t2), e2 instanceof Firestore$1) {
    const r2 = ResourcePath.fromString(t2, ...n2);
    return __PRIVATE_validateDocumentPath(r2), new DocumentReference(
      e2,
      /* converter= */
      null,
      new DocumentKey(r2)
    );
  }
  {
    if (!(e2 instanceof DocumentReference || e2 instanceof CollectionReference)) throw new FirestoreError(C.INVALID_ARGUMENT, "Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");
    const r2 = e2._path.child(ResourcePath.fromString(t2, ...n2));
    return __PRIVATE_validateDocumentPath(r2), new DocumentReference(e2.firestore, e2 instanceof CollectionReference ? e2.converter : null, new DocumentKey(r2));
  }
}
__name(doc$2, "doc$2");
function refEqual(e2, t2) {
  return e2 = getModularInstance(e2), t2 = getModularInstance(t2), (e2 instanceof DocumentReference || e2 instanceof CollectionReference) && (t2 instanceof DocumentReference || t2 instanceof CollectionReference) && (e2.firestore === t2.firestore && e2.path === t2.path && e2.converter === t2.converter);
}
__name(refEqual, "refEqual");
function queryEqual(e2, t2) {
  return e2 = getModularInstance(e2), t2 = getModularInstance(t2), e2 instanceof Query && t2 instanceof Query && (e2.firestore === t2.firestore && __PRIVATE_queryEquals(e2._query, t2._query) && e2.converter === t2.converter);
}
__name(queryEqual, "queryEqual");
/**
 * @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 tn = "AsyncQueue";
class __PRIVATE_AsyncQueueImpl {
  static {
    __name(this, "__PRIVATE_AsyncQueueImpl");
  }
  constructor(e2 = Promise.resolve()) {
    this.Vu = [], // Is this AsyncQueue being shut down? Once it is set to true, it will not
    // be changed again.
    this.mu = false, // Operations scheduled to be queued in the future. Operations are
    // automatically removed after they are run or canceled.
    this.fu = [], // visible for testing
    this.gu = null, // Flag set while there's an outstanding AsyncQueue operation, used for
    // assertion sanity-checks.
    this.pu = false, // Enabled during shutdown on Safari to prevent future access to IndexedDB.
    this.yu = false, // List of TimerIds to fast-forward delays for.
    this.wu = [], // Backoff timer used to schedule retries for retryable operations
    this.a_ = new __PRIVATE_ExponentialBackoff(
      this,
      "async_queue_retry"
      /* TimerId.AsyncQueueRetry */
    ), // Visibility handler that triggers an immediate retry of all retryable
    // operations. Meant to speed up recovery when we regain file system access
    // after page comes into foreground.
    this.Su = () => {
      const e3 = getDocument();
      e3 && __PRIVATE_logDebug(tn, "Visibility state changed to " + e3.visibilityState), this.a_.t_();
    }, this.bu = e2;
    const t2 = getDocument();
    t2 && "function" == typeof t2.addEventListener && t2.addEventListener("visibilitychange", this.Su);
  }
  get isShuttingDown() {
    return this.mu;
  }
  /**
   * Adds a new operation to the queue without waiting for it to complete (i.e.
   * we ignore the Promise result).
   */
  enqueueAndForget(e2) {
    this.enqueue(e2);
  }
  enqueueAndForgetEvenWhileRestricted(e2) {
    this.Du(), // eslint-disable-next-line @typescript-eslint/no-floating-promises
    this.vu(e2);
  }
  enterRestrictedMode(e2) {
    if (!this.mu) {
      this.mu = true, this.yu = e2 || false;
      const t2 = getDocument();
      t2 && "function" == typeof t2.removeEventListener && t2.removeEventListener("visibilitychange", this.Su);
    }
  }
  enqueue(e2) {
    if (this.Du(), this.mu)
      return new Promise(() => {
      });
    const t2 = new __PRIVATE_Deferred();
    return this.vu(() => this.mu && this.yu ? Promise.resolve() : (e2().then(t2.resolve, t2.reject), t2.promise)).then(() => t2.promise);
  }
  enqueueRetryable(e2) {
    this.enqueueAndForget(() => (this.Vu.push(e2), this.Cu()));
  }
  /**
   * Runs the next operation from the retryable queue. If the operation fails,
   * reschedules with backoff.
   */
  async Cu() {
    if (0 !== this.Vu.length) {
      try {
        await this.Vu[0](), this.Vu.shift(), this.a_.reset();
      } catch (e2) {
        if (!__PRIVATE_isIndexedDbTransactionError(e2)) throw e2;
        __PRIVATE_logDebug(tn, "Operation failed with retryable error: " + e2);
      }
      this.Vu.length > 0 && // If there are additional operations, we re-schedule `retryNextOp()`.
      // This is necessary to run retryable operations that failed during
      // their initial attempt since we don't know whether they are already
      // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1`
      // needs to  be re-run, we will run `op1`, `op1`, `op2` using the
      // already enqueued calls to `retryNextOp()`. `op3()` will then run in the
      // call scheduled here.
      // Since `backoffAndRun()` cancels an existing backoff and schedules a
      // new backoff on every call, there is only ever a single additional
      // operation in the queue.
      this.a_.Xo(() => this.Cu());
    }
  }
  vu(e2) {
    const t2 = this.bu.then(() => (this.pu = true, e2().catch((e3) => {
      this.gu = e3, this.pu = false;
      const t3 = (
        /**
        * Chrome includes Error.message in Error.stack. Other browsers do not.
        * This returns expected output of message + stack when available.
        * @param error - Error or FirestoreError
        */
        (/* @__PURE__ */ __name(function __PRIVATE_getMessageOrStack(e4) {
          let t4 = e4.message || "";
          e4.stack && (t4 = e4.stack.includes(e4.message) ? e4.stack : e4.message + "\n" + e4.stack);
          return t4;
        }, "__PRIVATE_getMessageOrStack"))(e3)
      );
      throw __PRIVATE_logError("INTERNAL UNHANDLED ERROR: ", t3), e3;
    }).then((e3) => (this.pu = false, e3))));
    return this.bu = t2, t2;
  }
  enqueueAfterDelay(e2, t2, n2) {
    this.Du(), // Fast-forward delays for timerIds that have been overridden.
    this.wu.indexOf(e2) > -1 && (t2 = 0);
    const r2 = DelayedOperation.createAndSchedule(this, e2, t2, n2, (e3) => this.Fu(e3));
    return this.fu.push(r2), r2;
  }
  Du() {
    this.gu && fail();
  }
  verifyOperationInProgress() {
  }
  /**
   * Waits until all currently queued tasks are finished executing. Delayed
   * operations are not run.
   */
  async Mu() {
    let e2;
    do {
      e2 = this.bu, await e2;
    } while (e2 !== this.bu);
  }
  /**
   * For Tests: Determine if a delayed operation with a particular TimerId
   * exists.
   */
  xu(e2) {
    for (const t2 of this.fu) if (t2.timerId === e2) return true;
    return false;
  }
  /**
   * For Tests: Runs some or all delayed operations early.
   *
   * @param lastTimerId - Delayed operations up to and including this TimerId
   * will be drained. Pass TimerId.All to run all delayed operations.
   * @returns a Promise that resolves once all operations have been run.
   */
  Ou(e2) {
    return this.Mu().then(() => {
      this.fu.sort((e3, t2) => e3.targetTimeMs - t2.targetTimeMs);
      for (const t2 of this.fu) if (t2.skipDelay(), "all" !== e2 && t2.timerId === e2) break;
      return this.Mu();
    });
  }
  /**
   * For Tests: Skip all subsequent delays for a timer id.
   */
  Nu(e2) {
    this.wu.push(e2);
  }
  /** Called once a DelayedOperation is run or canceled. */
  Fu(e2) {
    const t2 = this.fu.indexOf(e2);
    this.fu.splice(t2, 1);
  }
}
function __PRIVATE_isPartialObserver(e2) {
  return (/* @__PURE__ */ __name(function __PRIVATE_implementsAnyMethods(e3, t2) {
    if ("object" != typeof e3 || null === e3) return false;
    const n2 = e3;
    for (const e4 of t2) if (e4 in n2 && "function" == typeof n2[e4]) return true;
    return false;
  }, "__PRIVATE_implementsAnyMethods"))(e2, ["next", "error", "complete"]);
}
__name(__PRIVATE_isPartialObserver, "__PRIVATE_isPartialObserver");
class LoadBundleTask {
  static {
    __name(this, "LoadBundleTask");
  }
  constructor() {
    this._progressObserver = {}, this._taskCompletionResolver = new __PRIVATE_Deferred(), this._lastProgress = {
      taskState: "Running",
      totalBytes: 0,
      totalDocuments: 0,
      bytesLoaded: 0,
      documentsLoaded: 0
    };
  }
  /**
   * Registers functions to listen to bundle loading progress events.
   * @param next - Called when there is a progress update from bundle loading. Typically `next` calls occur
   *   each time a Firestore document is loaded from the bundle.
   * @param error - Called when an error occurs during bundle loading. The task aborts after reporting the
   *   error, and there should be no more updates after this.
   * @param complete - Called when the loading task is complete.
   */
  onProgress(e2, t2, n2) {
    this._progressObserver = {
      next: e2,
      error: t2,
      complete: n2
    };
  }
  /**
   * Implements the `Promise<LoadBundleTaskProgress>.catch` interface.
   *
   * @param onRejected - Called when an error occurs during bundle loading.
   */
  catch(e2) {
    return this._taskCompletionResolver.promise.catch(e2);
  }
  /**
   * Implements the `Promise<LoadBundleTaskProgress>.then` interface.
   *
   * @param onFulfilled - Called on the completion of the loading task with a final `LoadBundleTaskProgress` update.
   *   The update will always have its `taskState` set to `"Success"`.
   * @param onRejected - Called when an error occurs during bundle loading.
   */
  then(e2, t2) {
    return this._taskCompletionResolver.promise.then(e2, t2);
  }
  /**
   * Notifies all observers that bundle loading has completed, with a provided
   * `LoadBundleTaskProgress` object.
   *
   * @private
   */
  _completeWith(e2) {
    this._updateProgress(e2), this._progressObserver.complete && this._progressObserver.complete(), this._taskCompletionResolver.resolve(e2);
  }
  /**
   * Notifies all observers that bundle loading has failed, with a provided
   * `Error` as the reason.
   *
   * @private
   */
  _failWith(e2) {
    this._lastProgress.taskState = "Error", this._progressObserver.next && this._progressObserver.next(this._lastProgress), this._progressObserver.error && this._progressObserver.error(e2), this._taskCompletionResolver.reject(e2);
  }
  /**
   * Notifies a progress update of loading a bundle.
   * @param progress - The new progress.
   *
   * @private
   */
  _updateProgress(e2) {
    this._lastProgress = e2, this._progressObserver.next && this._progressObserver.next(e2);
  }
}
/**
 * @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 nn = -1;
class Firestore extends Firestore$1 {
  static {
    __name(this, "Firestore");
  }
  /** @hideconstructor */
  constructor(e2, t2, n2, r2) {
    super(e2, t2, n2, r2), /**
     * Whether it's a {@link Firestore} or Firestore Lite instance.
     */
    this.type = "firestore", this._queue = new __PRIVATE_AsyncQueueImpl(), this._persistenceKey = (null == r2 ? void 0 : r2.name) || "[DEFAULT]";
  }
  async _terminate() {
    if (this._firestoreClient) {
      const e2 = this._firestoreClient.terminate();
      this._queue = new __PRIVATE_AsyncQueueImpl(e2), this._firestoreClient = void 0, await e2;
    }
  }
}
function initializeFirestore(e2, t2, n2) {
  n2 || (n2 = rt);
  const r2 = _getProvider(e2, "firestore");
  if (r2.isInitialized(n2)) {
    const e3 = r2.getImmediate({
      identifier: n2
    }), i2 = r2.getOptions(n2);
    if (deepEqual(i2, t2)) return e3;
    throw new FirestoreError(C.FAILED_PRECONDITION, "initializeFirestore() has already been called with different options. To avoid this error, call initializeFirestore() with the same options as when it was originally called, or call getFirestore() to return the already initialized instance.");
  }
  if (void 0 !== t2.cacheSizeBytes && void 0 !== t2.localCache) throw new FirestoreError(C.INVALID_ARGUMENT, "cache and cacheSizeBytes cannot be specified at the same time as cacheSizeBytes willbe deprecated. Instead, specify the cache size in the cache object");
  if (void 0 !== t2.cacheSizeBytes && -1 !== t2.cacheSizeBytes && t2.cacheSizeBytes < Dt) throw new FirestoreError(C.INVALID_ARGUMENT, "cacheSizeBytes must be at least 1048576");
  return r2.initialize({
    options: t2,
    instanceIdentifier: n2
  });
}
__name(initializeFirestore, "initializeFirestore");
function getFirestore(e2, n2) {
  const r2 = "object" == typeof e2 ? e2 : getApp(), i2 = "string" == typeof e2 ? e2 : n2 || rt, s2 = _getProvider(r2, "firestore").getImmediate({
    identifier: i2
  });
  if (!s2._initialized) {
    const e3 = getDefaultEmulatorHostnameAndPort("firestore");
    e3 && connectFirestoreEmulator(s2, ...e3);
  }
  return s2;
}
__name(getFirestore, "getFirestore");
function ensureFirestoreConfigured(e2) {
  if (e2._terminated) throw new FirestoreError(C.FAILED_PRECONDITION, "The client has already been terminated.");
  return e2._firestoreClient || __PRIVATE_configureFirestore(e2), e2._firestoreClient;
}
__name(ensureFirestoreConfigured, "ensureFirestoreConfigured");
function __PRIVATE_configureFirestore(e2) {
  var t2, n2, r2;
  const i2 = e2._freezeSettings(), s2 = (/* @__PURE__ */ __name(function __PRIVATE_makeDatabaseInfo(e3, t3, n3, r3) {
    return new DatabaseInfo(e3, t3, n3, r3.host, r3.ssl, r3.experimentalForceLongPolling, r3.experimentalAutoDetectLongPolling, __PRIVATE_cloneLongPollingOptions(r3.experimentalLongPollingOptions), r3.useFetchStreams);
  }, "__PRIVATE_makeDatabaseInfo"))(e2._databaseId, (null === (t2 = e2._app) || void 0 === t2 ? void 0 : t2.options.appId) || "", e2._persistenceKey, i2);
  e2._componentsProvider || (null === (n2 = i2.localCache) || void 0 === n2 ? void 0 : n2._offlineComponentProvider) && (null === (r2 = i2.localCache) || void 0 === r2 ? void 0 : r2._onlineComponentProvider) && (e2._componentsProvider = {
    _offline: i2.localCache._offlineComponentProvider,
    _online: i2.localCache._onlineComponentProvider
  }), e2._firestoreClient = new FirestoreClient(e2._authCredentials, e2._appCheckCredentials, e2._queue, s2, e2._componentsProvider && (/* @__PURE__ */ __name(function __PRIVATE_buildComponentProvider(e3) {
    const t3 = null == e3 ? void 0 : e3._online.build();
    return {
      _offline: null == e3 ? void 0 : e3._offline.build(t3),
      _online: t3
    };
  }, "__PRIVATE_buildComponentProvider"))(e2._componentsProvider));
}
__name(__PRIVATE_configureFirestore, "__PRIVATE_configureFirestore");
function enableIndexedDbPersistence(e2, t2) {
  __PRIVATE_logWarn("enableIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");
  const n2 = e2._freezeSettings();
  return __PRIVATE_setPersistenceProviders(e2, OnlineComponentProvider.provider, {
    build: /* @__PURE__ */ __name((e3) => new __PRIVATE_IndexedDbOfflineComponentProvider(e3, n2.cacheSizeBytes, null == t2 ? void 0 : t2.forceOwnership), "build")
  }), Promise.resolve();
}
__name(enableIndexedDbPersistence, "enableIndexedDbPersistence");
async function enableMultiTabIndexedDbPersistence(e2) {
  __PRIVATE_logWarn("enableMultiTabIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");
  const t2 = e2._freezeSettings();
  __PRIVATE_setPersistenceProviders(e2, OnlineComponentProvider.provider, {
    build: /* @__PURE__ */ __name((e3) => new __PRIVATE_MultiTabOfflineComponentProvider(e3, t2.cacheSizeBytes), "build")
  });
}
__name(enableMultiTabIndexedDbPersistence, "enableMultiTabIndexedDbPersistence");
function __PRIVATE_setPersistenceProviders(e2, t2, n2) {
  if ((e2 = __PRIVATE_cast(e2, Firestore))._firestoreClient || e2._terminated) throw new FirestoreError(C.FAILED_PRECONDITION, "Firestore has already been started and persistence can no longer be enabled. You can only enable persistence before calling any other methods on a Firestore object.");
  if (e2._componentsProvider || e2._getSettings().localCache) throw new FirestoreError(C.FAILED_PRECONDITION, "SDK cache is already specified.");
  e2._componentsProvider = {
    _online: t2,
    _offline: n2
  }, __PRIVATE_configureFirestore(e2);
}
__name(__PRIVATE_setPersistenceProviders, "__PRIVATE_setPersistenceProviders");
function clearIndexedDbPersistence(e2) {
  if (e2._initialized && !e2._terminated) throw new FirestoreError(C.FAILED_PRECONDITION, "Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.");
  const t2 = new __PRIVATE_Deferred();
  return e2._queue.enqueueAndForgetEvenWhileRestricted(async () => {
    try {
      await (/* @__PURE__ */ __name(async function __PRIVATE_indexedDbClearPersistence(e3) {
        if (!__PRIVATE_SimpleDb.D()) return Promise.resolve();
        const t3 = e3 + xt;
        await __PRIVATE_SimpleDb.delete(t3);
      }, "__PRIVATE_indexedDbClearPersistence"))(__PRIVATE_indexedDbStoragePrefix(e2._databaseId, e2._persistenceKey)), t2.resolve();
    } catch (e3) {
      t2.reject(e3);
    }
  }), t2.promise;
}
__name(clearIndexedDbPersistence, "clearIndexedDbPersistence");
function waitForPendingWrites(e2) {
  return (/* @__PURE__ */ __name(function __PRIVATE_firestoreClientWaitForPendingWrites(e3) {
    const t2 = new __PRIVATE_Deferred();
    return e3.asyncQueue.enqueueAndForget(async () => __PRIVATE_syncEngineRegisterPendingWritesCallback(await __PRIVATE_getSyncEngine(e3), t2)), t2.promise;
  }, "__PRIVATE_firestoreClientWaitForPendingWrites"))(ensureFirestoreConfigured(e2 = __PRIVATE_cast(e2, Firestore)));
}
__name(waitForPendingWrites, "waitForPendingWrites");
function enableNetwork(e2) {
  return __PRIVATE_firestoreClientEnableNetwork(ensureFirestoreConfigured(e2 = __PRIVATE_cast(e2, Firestore)));
}
__name(enableNetwork, "enableNetwork");
function disableNetwork(e2) {
  return __PRIVATE_firestoreClientDisableNetwork(ensureFirestoreConfigured(e2 = __PRIVATE_cast(e2, Firestore)));
}
__name(disableNetwork, "disableNetwork");
function terminate(e2) {
  return _removeServiceInstance(e2.app, "firestore", e2._databaseId.database), e2._delete();
}
__name(terminate, "terminate");
function loadBundle(e2, t2) {
  const n2 = ensureFirestoreConfigured(e2 = __PRIVATE_cast(e2, Firestore)), r2 = new LoadBundleTask();
  return __PRIVATE_firestoreClientLoadBundle(n2, e2._databaseId, t2, r2), r2;
}
__name(loadBundle, "loadBundle");
function namedQuery(e2, t2) {
  return __PRIVATE_firestoreClientGetNamedQuery(ensureFirestoreConfigured(e2 = __PRIVATE_cast(e2, Firestore)), t2).then((t3) => t3 ? new Query(e2, null, t3.query) : null);
}
__name(namedQuery, "namedQuery");
/**
 * @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.
 */
/**
 * @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.
 */
class AggregateField {
  static {
    __name(this, "AggregateField");
  }
  /**
   * Create a new AggregateField<T>
   * @param aggregateType Specifies the type of aggregation operation to perform.
   * @param _internalFieldPath Optionally specifies the field that is aggregated.
   * @internal
   */
  constructor(e2 = "count", t2) {
    this._internalFieldPath = t2, /** A type string to uniquely identify instances of this class. */
    this.type = "AggregateField", this.aggregateType = e2;
  }
}
class AggregateQuerySnapshot {
  static {
    __name(this, "AggregateQuerySnapshot");
  }
  /** @hideconstructor */
  constructor(e2, t2, n2) {
    this._userDataWriter = t2, this._data = n2, /** A type string to uniquely identify instances of this class. */
    this.type = "AggregateQuerySnapshot", this.query = e2;
  }
  /**
   * Returns the results of the aggregations performed over the underlying
   * query.
   *
   * The keys of the returned object will be the same as those of the
   * `AggregateSpec` object specified to the aggregation method, and the values
   * will be the corresponding aggregation result.
   *
   * @returns The results of the aggregations performed over the underlying
   * query.
   */
  data() {
    return this._userDataWriter.convertObjectMap(this._data);
  }
}
/**
 * @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 Bytes {
  static {
    __name(this, "Bytes");
  }
  /** @hideconstructor */
  constructor(e2) {
    this._byteString = e2;
  }
  /**
   * Creates a new `Bytes` object from the given Base64 string, converting it to
   * bytes.
   *
   * @param base64 - The Base64 string used to create the `Bytes` object.
   */
  static fromBase64String(e2) {
    try {
      return new Bytes(ByteString.fromBase64String(e2));
    } catch (e3) {
      throw new FirestoreError(C.INVALID_ARGUMENT, "Failed to construct data from Base64 string: " + e3);
    }
  }
  /**
   * Creates a new `Bytes` object from the given Uint8Array.
   *
   * @param array - The Uint8Array used to create the `Bytes` object.
   */
  static fromUint8Array(e2) {
    return new Bytes(ByteString.fromUint8Array(e2));
  }
  /**
   * Returns the underlying bytes as a Base64-encoded string.
   *
   * @returns The Base64-encoded string created from the `Bytes` object.
   */
  toBase64() {
    return this._byteString.toBase64();
  }
  /**
   * Returns the underlying bytes in a new `Uint8Array`.
   *
   * @returns The Uint8Array created from the `Bytes` object.
   */
  toUint8Array() {
    return this._byteString.toUint8Array();
  }
  /**
   * Returns a string representation of the `Bytes` object.
   *
   * @returns A string representation of the `Bytes` object.
   */
  toString() {
    return "Bytes(base64: " + this.toBase64() + ")";
  }
  /**
   * Returns true if this `Bytes` object is equal to the provided one.
   *
   * @param other - The `Bytes` object to compare against.
   * @returns true if this `Bytes` object is equal to the provided one.
   */
  isEqual(e2) {
    return this._byteString.isEqual(e2._byteString);
  }
}
/**
 * @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 FieldPath {
  static {
    __name(this, "FieldPath");
  }
  /**
   * Creates a `FieldPath` from the provided field names. If more than one field
   * name is provided, the path will point to a nested field in a document.
   *
   * @param fieldNames - A list of field names.
   */
  constructor(...e2) {
    for (let t2 = 0; t2 < e2.length; ++t2) if (0 === e2[t2].length) throw new FirestoreError(C.INVALID_ARGUMENT, "Invalid field name at argument $(i + 1). Field names must not be empty.");
    this._internalPath = new FieldPath$1(e2);
  }
  /**
   * Returns true if this `FieldPath` is equal to the provided one.
   *
   * @param other - The `FieldPath` to compare against.
   * @returns true if this `FieldPath` is equal to the provided one.
   */
  isEqual(e2) {
    return this._internalPath.isEqual(e2._internalPath);
  }
}
function documentId() {
  return new FieldPath(x);
}
__name(documentId, "documentId");
/**
 * @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 FieldValue {
  static {
    __name(this, "FieldValue");
  }
  /**
   * @param _methodName - The public API endpoint that returns this class.
   * @hideconstructor
   */
  constructor(e2) {
    this._methodName = e2;
  }
}
/**
 * @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 GeoPoint {
  static {
    __name(this, "GeoPoint");
  }
  /**
   * Creates a new immutable `GeoPoint` object with the provided latitude and
   * longitude values.
   * @param latitude - The latitude as number between -90 and 90.
   * @param longitude - The longitude as number between -180 and 180.
   */
  constructor(e2, t2) {
    if (!isFinite(e2) || e2 < -90 || e2 > 90) throw new FirestoreError(C.INVALID_ARGUMENT, "Latitude must be a number between -90 and 90, but was: " + e2);
    if (!isFinite(t2) || t2 < -180 || t2 > 180) throw new FirestoreError(C.INVALID_ARGUMENT, "Longitude must be a number between -180 and 180, but was: " + t2);
    this._lat = e2, this._long = t2;
  }
  /**
   * The latitude of this `GeoPoint` instance.
   */
  get latitude() {
    return this._lat;
  }
  /**
   * The longitude of this `GeoPoint` instance.
   */
  get longitude() {
    return this._long;
  }
  /**
   * Returns true if this `GeoPoint` is equal to the provided one.
   *
   * @param other - The `GeoPoint` to compare against.
   * @returns true if this `GeoPoint` is equal to the provided one.
   */
  isEqual(e2) {
    return this._lat === e2._lat && this._long === e2._long;
  }
  /** Returns a JSON-serializable representation of this GeoPoint. */
  toJSON() {
    return {
      latitude: this._lat,
      longitude: this._long
    };
  }
  /**
   * Actually private to JS consumers of our API, so this function is prefixed
   * with an underscore.
   */
  _compareTo(e2) {
    return __PRIVATE_primitiveComparator(this._lat, e2._lat) || __PRIVATE_primitiveComparator(this._long, e2._long);
  }
}
/**
 * @license
 * Copyright 2024 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 VectorValue {
  static {
    __name(this, "VectorValue");
  }
  /**
   * @private
   * @internal
   */
  constructor(e2) {
    this._values = (e2 || []).map((e3) => e3);
  }
  /**
   * Returns a copy of the raw number array form of the vector.
   */
  toArray() {
    return this._values.map((e2) => e2);
  }
  /**
   * Returns `true` if the two `VectorValue` values have the same raw number arrays, returns `false` otherwise.
   */
  isEqual(e2) {
    return (/* @__PURE__ */ __name(function __PRIVATE_isPrimitiveArrayEqual(e3, t2) {
      if (e3.length !== t2.length) return false;
      for (let n2 = 0; n2 < e3.length; ++n2) if (e3[n2] !== t2[n2]) return false;
      return true;
    }, "__PRIVATE_isPrimitiveArrayEqual"))(this._values, e2._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.
 */
const rn = /^__.*__$/;
class ParsedSetData {
  static {
    __name(this, "ParsedSetData");
  }
  constructor(e2, t2, n2) {
    this.data = e2, this.fieldMask = t2, this.fieldTransforms = n2;
  }
  toMutation(e2, t2) {
    return null !== this.fieldMask ? new __PRIVATE_PatchMutation(e2, this.data, this.fieldMask, t2, this.fieldTransforms) : new __PRIVATE_SetMutation(e2, this.data, t2, this.fieldTransforms);
  }
}
class ParsedUpdateData {
  static {
    __name(this, "ParsedUpdateData");
  }
  constructor(e2, t2, n2) {
    this.data = e2, this.fieldMask = t2, this.fieldTransforms = n2;
  }
  toMutation(e2, t2) {
    return new __PRIVATE_PatchMutation(e2, this.data, this.fieldMask, t2, this.fieldTransforms);
  }
}
function __PRIVATE_isWrite(e2) {
  switch (e2) {
    case 0:
    case 2:
    case 1:
      return true;
    case 3:
    case 4:
      return false;
    default:
      throw fail();
  }
}
__name(__PRIVATE_isWrite, "__PRIVATE_isWrite");
class __PRIVATE_ParseContextImpl {
  static {
    __name(this, "__PRIVATE_ParseContextImpl");
  }
  /**
   * Initializes a ParseContext with the given source and path.
   *
   * @param settings - The settings for the parser.
   * @param databaseId - The database ID of the Firestore instance.
   * @param serializer - The serializer to use to generate the Value proto.
   * @param ignoreUndefinedProperties - Whether to ignore undefined properties
   * rather than throw.
   * @param fieldTransforms - A mutable list of field transforms encountered
   * while parsing the data.
   * @param fieldMask - A mutable list of field paths encountered while parsing
   * the data.
   *
   * TODO(b/34871131): We don't support array paths right now, so path can be
   * null to indicate the context represents any location within an array (in
   * which case certain features will not work and errors will be somewhat
   * compromised).
   */
  constructor(e2, t2, n2, r2, i2, s2) {
    this.settings = e2, this.databaseId = t2, this.serializer = n2, this.ignoreUndefinedProperties = r2, // Minor hack: If fieldTransforms is undefined, we assume this is an
    // external call and we need to validate the entire path.
    void 0 === i2 && this.Bu(), this.fieldTransforms = i2 || [], this.fieldMask = s2 || [];
  }
  get path() {
    return this.settings.path;
  }
  get Lu() {
    return this.settings.Lu;
  }
  /** Returns a new context with the specified settings overwritten. */
  ku(e2) {
    return new __PRIVATE_ParseContextImpl(Object.assign(Object.assign({}, this.settings), e2), this.databaseId, this.serializer, this.ignoreUndefinedProperties, this.fieldTransforms, this.fieldMask);
  }
  qu(e2) {
    var t2;
    const n2 = null === (t2 = this.path) || void 0 === t2 ? void 0 : t2.child(e2), r2 = this.ku({
      path: n2,
      Qu: false
    });
    return r2.$u(e2), r2;
  }
  Uu(e2) {
    var t2;
    const n2 = null === (t2 = this.path) || void 0 === t2 ? void 0 : t2.child(e2), r2 = this.ku({
      path: n2,
      Qu: false
    });
    return r2.Bu(), r2;
  }
  Ku(e2) {
    return this.ku({
      path: void 0,
      Qu: true
    });
  }
  Wu(e2) {
    return __PRIVATE_createError(e2, this.settings.methodName, this.settings.Gu || false, this.path, this.settings.zu);
  }
  /** Returns 'true' if 'fieldPath' was traversed when creating this context. */
  contains(e2) {
    return void 0 !== this.fieldMask.find((t2) => e2.isPrefixOf(t2)) || void 0 !== this.fieldTransforms.find((t2) => e2.isPrefixOf(t2.field));
  }
  Bu() {
    if (this.path) for (let e2 = 0; e2 < this.path.length; e2++) this.$u(this.path.get(e2));
  }
  $u(e2) {
    if (0 === e2.length) throw this.Wu("Document fields must not be empty");
    if (__PRIVATE_isWrite(this.Lu) && rn.test(e2)) throw this.Wu('Document fields cannot begin and end with "__"');
  }
}
class __PRIVATE_UserDataReader {
  static {
    __name(this, "__PRIVATE_UserDataReader");
  }
  constructor(e2, t2, n2) {
    this.databaseId = e2, this.ignoreUndefinedProperties = t2, this.serializer = n2 || __PRIVATE_newSerializer(e2);
  }
  /** Creates a new top-level parse context. */
  ju(e2, t2, n2, r2 = false) {
    return new __PRIVATE_ParseContextImpl({
      Lu: e2,
      methodName: t2,
      zu: n2,
      path: FieldPath$1.emptyPath(),
      Qu: false,
      Gu: r2
    }, this.databaseId, this.serializer, this.ignoreUndefinedProperties);
  }
}
function __PRIVATE_newUserDataReader(e2) {
  const t2 = e2._freezeSettings(), n2 = __PRIVATE_newSerializer(e2._databaseId);
  return new __PRIVATE_UserDataReader(e2._databaseId, !!t2.ignoreUndefinedProperties, n2);
}
__name(__PRIVATE_newUserDataReader, "__PRIVATE_newUserDataReader");
function __PRIVATE_parseSetData(e2, t2, n2, r2, i2, s2 = {}) {
  const o2 = e2.ju(s2.merge || s2.mergeFields ? 2 : 0, t2, n2, i2);
  __PRIVATE_validatePlainObject("Data must be an object, but it was:", o2, r2);
  const _2 = __PRIVATE_parseObject(r2, o2);
  let a2, u2;
  if (s2.merge) a2 = new FieldMask(o2.fieldMask), u2 = o2.fieldTransforms;
  else if (s2.mergeFields) {
    const e3 = [];
    for (const r3 of s2.mergeFields) {
      const i3 = __PRIVATE_fieldPathFromArgument$1(t2, r3, n2);
      if (!o2.contains(i3)) throw new FirestoreError(C.INVALID_ARGUMENT, `Field '${i3}' is specified in your field mask but missing from your input data.`);
      __PRIVATE_fieldMaskContains(e3, i3) || e3.push(i3);
    }
    a2 = new FieldMask(e3), u2 = o2.fieldTransforms.filter((e4) => a2.covers(e4.field));
  } else a2 = null, u2 = o2.fieldTransforms;
  return new ParsedSetData(new ObjectValue(_2), a2, u2);
}
__name(__PRIVATE_parseSetData, "__PRIVATE_parseSetData");
class __PRIVATE_DeleteFieldValueImpl extends FieldValue {
  static {
    __name(this, "__PRIVATE_DeleteFieldValueImpl");
  }
  _toFieldTransform(e2) {
    if (2 !== e2.Lu) throw 1 === e2.Lu ? e2.Wu(`${this._methodName}() can only appear at the top level of your update data`) : e2.Wu(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);
    return e2.fieldMask.push(e2.path), null;
  }
  isEqual(e2) {
    return e2 instanceof __PRIVATE_DeleteFieldValueImpl;
  }
}
function __PRIVATE_createSentinelChildContext(e2, t2, n2) {
  return new __PRIVATE_ParseContextImpl({
    Lu: 3,
    zu: t2.settings.zu,
    methodName: e2._methodName,
    Qu: n2
  }, t2.databaseId, t2.serializer, t2.ignoreUndefinedProperties);
}
__name(__PRIVATE_createSentinelChildContext, "__PRIVATE_createSentinelChildContext");
class __PRIVATE_ServerTimestampFieldValueImpl extends FieldValue {
  static {
    __name(this, "__PRIVATE_ServerTimestampFieldValueImpl");
  }
  _toFieldTransform(e2) {
    return new FieldTransform(e2.path, new __PRIVATE_ServerTimestampTransform());
  }
  isEqual(e2) {
    return e2 instanceof __PRIVATE_ServerTimestampFieldValueImpl;
  }
}
class __PRIVATE_ArrayUnionFieldValueImpl extends FieldValue {
  static {
    __name(this, "__PRIVATE_ArrayUnionFieldValueImpl");
  }
  constructor(e2, t2) {
    super(e2), this.Hu = t2;
  }
  _toFieldTransform(e2) {
    const t2 = __PRIVATE_createSentinelChildContext(
      this,
      e2,
      /*array=*/
      true
    ), n2 = this.Hu.map((e3) => __PRIVATE_parseData(e3, t2)), r2 = new __PRIVATE_ArrayUnionTransformOperation(n2);
    return new FieldTransform(e2.path, r2);
  }
  isEqual(e2) {
    return e2 instanceof __PRIVATE_ArrayUnionFieldValueImpl && deepEqual(this.Hu, e2.Hu);
  }
}
class __PRIVATE_ArrayRemoveFieldValueImpl extends FieldValue {
  static {
    __name(this, "__PRIVATE_ArrayRemoveFieldValueImpl");
  }
  constructor(e2, t2) {
    super(e2), this.Hu = t2;
  }
  _toFieldTransform(e2) {
    const t2 = __PRIVATE_createSentinelChildContext(
      this,
      e2,
      /*array=*/
      true
    ), n2 = this.Hu.map((e3) => __PRIVATE_parseData(e3, t2)), r2 = new __PRIVATE_ArrayRemoveTransformOperation(n2);
    return new FieldTransform(e2.path, r2);
  }
  isEqual(e2) {
    return e2 instanceof __PRIVATE_ArrayRemoveFieldValueImpl && deepEqual(this.Hu, e2.Hu);
  }
}
class __PRIVATE_NumericIncrementFieldValueImpl extends FieldValue {
  static {
    __name(this, "__PRIVATE_NumericIncrementFieldValueImpl");
  }
  constructor(e2, t2) {
    super(e2), this.Ju = t2;
  }
  _toFieldTransform(e2) {
    const t2 = new __PRIVATE_NumericIncrementTransformOperation(e2.serializer, toNumber(e2.serializer, this.Ju));
    return new FieldTransform(e2.path, t2);
  }
  isEqual(e2) {
    return e2 instanceof __PRIVATE_NumericIncrementFieldValueImpl && this.Ju === e2.Ju;
  }
}
function __PRIVATE_parseUpdateData(e2, t2, n2, r2) {
  const i2 = e2.ju(1, t2, n2);
  __PRIVATE_validatePlainObject("Data must be an object, but it was:", i2, r2);
  const s2 = [], o2 = ObjectValue.empty();
  forEach$2(r2, (e3, r3) => {
    const _3 = __PRIVATE_fieldPathFromDotSeparatedString(t2, e3, n2);
    r3 = getModularInstance(r3);
    const a2 = i2.Uu(_3);
    if (r3 instanceof __PRIVATE_DeleteFieldValueImpl)
      s2.push(_3);
    else {
      const e4 = __PRIVATE_parseData(r3, a2);
      null != e4 && (s2.push(_3), o2.set(_3, e4));
    }
  });
  const _2 = new FieldMask(s2);
  return new ParsedUpdateData(o2, _2, i2.fieldTransforms);
}
__name(__PRIVATE_parseUpdateData, "__PRIVATE_parseUpdateData");
function __PRIVATE_parseUpdateVarargs(e2, t2, n2, r2, i2, s2) {
  const o2 = e2.ju(1, t2, n2), _2 = [__PRIVATE_fieldPathFromArgument$1(t2, r2, n2)], a2 = [i2];
  if (s2.length % 2 != 0) throw new FirestoreError(C.INVALID_ARGUMENT, `Function ${t2}() needs to be called with an even number of arguments that alternate between field names and values.`);
  for (let e3 = 0; e3 < s2.length; e3 += 2) _2.push(__PRIVATE_fieldPathFromArgument$1(t2, s2[e3])), a2.push(s2[e3 + 1]);
  const u2 = [], c2 = ObjectValue.empty();
  for (let e3 = _2.length - 1; e3 >= 0; --e3) if (!__PRIVATE_fieldMaskContains(u2, _2[e3])) {
    const t3 = _2[e3];
    let n3 = a2[e3];
    n3 = getModularInstance(n3);
    const r3 = o2.Uu(t3);
    if (n3 instanceof __PRIVATE_DeleteFieldValueImpl)
      u2.push(t3);
    else {
      const e4 = __PRIVATE_parseData(n3, r3);
      null != e4 && (u2.push(t3), c2.set(t3, e4));
    }
  }
  const l2 = new FieldMask(u2);
  return new ParsedUpdateData(c2, l2, o2.fieldTransforms);
}
__name(__PRIVATE_parseUpdateVarargs, "__PRIVATE_parseUpdateVarargs");
function __PRIVATE_parseQueryValue(e2, t2, n2, r2 = false) {
  return __PRIVATE_parseData(n2, e2.ju(r2 ? 4 : 3, t2));
}
__name(__PRIVATE_parseQueryValue, "__PRIVATE_parseQueryValue");
function __PRIVATE_parseData(e2, t2) {
  if (__PRIVATE_looksLikeJsonObject(
    // Unwrap the API type from the Compat SDK. This will return the API type
    // from firestore-exp.
    e2 = getModularInstance(e2)
  )) return __PRIVATE_validatePlainObject("Unsupported field value:", t2, e2), __PRIVATE_parseObject(e2, t2);
  if (e2 instanceof FieldValue)
    return (/* @__PURE__ */ __name(function __PRIVATE_parseSentinelFieldValue(e3, t3) {
      if (!__PRIVATE_isWrite(t3.Lu)) throw t3.Wu(`${e3._methodName}() can only be used with update() and set()`);
      if (!t3.path) throw t3.Wu(`${e3._methodName}() is not currently supported inside arrays`);
      const n2 = e3._toFieldTransform(t3);
      n2 && t3.fieldTransforms.push(n2);
    }, "__PRIVATE_parseSentinelFieldValue"))(e2, t2), null;
  if (void 0 === e2 && t2.ignoreUndefinedProperties)
    return null;
  if (
    // If context.path is null we are inside an array and we don't support
    // field mask paths more granular than the top-level array.
    t2.path && t2.fieldMask.push(t2.path), e2 instanceof Array
  ) {
    if (t2.settings.Qu && 4 !== t2.Lu) throw t2.Wu("Nested arrays are not supported");
    return (/* @__PURE__ */ __name(function __PRIVATE_parseArray(e3, t3) {
      const n2 = [];
      let r2 = 0;
      for (const i2 of e3) {
        let e4 = __PRIVATE_parseData(i2, t3.Ku(r2));
        null == e4 && // Just include nulls in the array for fields being replaced with a
        // sentinel.
        (e4 = {
          nullValue: "NULL_VALUE"
        }), n2.push(e4), r2++;
      }
      return {
        arrayValue: {
          values: n2
        }
      };
    }, "__PRIVATE_parseArray"))(e2, t2);
  }
  return (/* @__PURE__ */ __name(function __PRIVATE_parseScalarValue(e3, t3) {
    if (null === (e3 = getModularInstance(e3))) return {
      nullValue: "NULL_VALUE"
    };
    if ("number" == typeof e3) return toNumber(t3.serializer, e3);
    if ("boolean" == typeof e3) return {
      booleanValue: e3
    };
    if ("string" == typeof e3) return {
      stringValue: e3
    };
    if (e3 instanceof Date) {
      const n2 = Timestamp.fromDate(e3);
      return {
        timestampValue: toTimestamp(t3.serializer, n2)
      };
    }
    if (e3 instanceof Timestamp) {
      const n2 = new Timestamp(e3.seconds, 1e3 * Math.floor(e3.nanoseconds / 1e3));
      return {
        timestampValue: toTimestamp(t3.serializer, n2)
      };
    }
    if (e3 instanceof GeoPoint) return {
      geoPointValue: {
        latitude: e3.latitude,
        longitude: e3.longitude
      }
    };
    if (e3 instanceof Bytes) return {
      bytesValue: __PRIVATE_toBytes(t3.serializer, e3._byteString)
    };
    if (e3 instanceof DocumentReference) {
      const n2 = t3.databaseId, r2 = e3.firestore._databaseId;
      if (!r2.isEqual(n2)) throw t3.Wu(`Document reference is for database ${r2.projectId}/${r2.database} but should be for database ${n2.projectId}/${n2.database}`);
      return {
        referenceValue: __PRIVATE_toResourceName(e3.firestore._databaseId || t3.databaseId, e3._key.path)
      };
    }
    if (e3 instanceof VectorValue)
      return (/* @__PURE__ */ __name(function __PRIVATE_parseVectorValue(e4, t4) {
        const n2 = {
          fields: {
            [it]: {
              stringValue: _t
            },
            [at]: {
              arrayValue: {
                values: e4.toArray().map((e5) => {
                  if ("number" != typeof e5) throw t4.Wu("VectorValues must only contain numeric values.");
                  return __PRIVATE_toDouble(t4.serializer, e5);
                })
              }
            }
          }
        };
        return {
          mapValue: n2
        };
      }, "__PRIVATE_parseVectorValue"))(e3, t3);
    throw t3.Wu(`Unsupported field value: ${__PRIVATE_valueDescription(e3)}`);
  }, "__PRIVATE_parseScalarValue"))(e2, t2);
}
__name(__PRIVATE_parseData, "__PRIVATE_parseData");
function __PRIVATE_parseObject(e2, t2) {
  const n2 = {};
  return isEmpty$3(e2) ? (
    // If we encounter an empty object, we explicitly add it to the update
    // mask to ensure that the server creates a map entry.
    t2.path && t2.path.length > 0 && t2.fieldMask.push(t2.path)
  ) : forEach$2(e2, (e3, r2) => {
    const i2 = __PRIVATE_parseData(r2, t2.qu(e3));
    null != i2 && (n2[e3] = i2);
  }), {
    mapValue: {
      fields: n2
    }
  };
}
__name(__PRIVATE_parseObject, "__PRIVATE_parseObject");
function __PRIVATE_looksLikeJsonObject(e2) {
  return !("object" != typeof e2 || null === e2 || e2 instanceof Array || e2 instanceof Date || e2 instanceof Timestamp || e2 instanceof GeoPoint || e2 instanceof Bytes || e2 instanceof DocumentReference || e2 instanceof FieldValue || e2 instanceof VectorValue);
}
__name(__PRIVATE_looksLikeJsonObject, "__PRIVATE_looksLikeJsonObject");
function __PRIVATE_validatePlainObject(e2, t2, n2) {
  if (!__PRIVATE_looksLikeJsonObject(n2) || !(/* @__PURE__ */ __name(function __PRIVATE_isPlainObject(e3) {
    return "object" == typeof e3 && null !== e3 && (Object.getPrototypeOf(e3) === Object.prototype || null === Object.getPrototypeOf(e3));
  }, "__PRIVATE_isPlainObject"))(n2)) {
    const r2 = __PRIVATE_valueDescription(n2);
    throw "an object" === r2 ? t2.Wu(e2 + " a custom object") : t2.Wu(e2 + " " + r2);
  }
}
__name(__PRIVATE_validatePlainObject, "__PRIVATE_validatePlainObject");
function __PRIVATE_fieldPathFromArgument$1(e2, t2, n2) {
  if (
    // If required, replace the FieldPath Compat class with the firestore-exp
    // FieldPath.
    (t2 = getModularInstance(t2)) instanceof FieldPath
  ) return t2._internalPath;
  if ("string" == typeof t2) return __PRIVATE_fieldPathFromDotSeparatedString(e2, t2);
  throw __PRIVATE_createError(
    "Field path arguments must be of type string or ",
    e2,
    /* hasConverter= */
    false,
    /* path= */
    void 0,
    n2
  );
}
__name(__PRIVATE_fieldPathFromArgument$1, "__PRIVATE_fieldPathFromArgument$1");
const sn = new RegExp("[~\\*/\\[\\]]");
function __PRIVATE_fieldPathFromDotSeparatedString(e2, t2, n2) {
  if (t2.search(sn) >= 0) throw __PRIVATE_createError(
    `Invalid field path (${t2}). Paths must not contain '~', '*', '/', '[', or ']'`,
    e2,
    /* hasConverter= */
    false,
    /* path= */
    void 0,
    n2
  );
  try {
    return new FieldPath(...t2.split("."))._internalPath;
  } catch (r2) {
    throw __PRIVATE_createError(
      `Invalid field path (${t2}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,
      e2,
      /* hasConverter= */
      false,
      /* path= */
      void 0,
      n2
    );
  }
}
__name(__PRIVATE_fieldPathFromDotSeparatedString, "__PRIVATE_fieldPathFromDotSeparatedString");
function __PRIVATE_createError(e2, t2, n2, r2, i2) {
  const s2 = r2 && !r2.isEmpty(), o2 = void 0 !== i2;
  let _2 = `Function ${t2}() called with invalid data`;
  n2 && (_2 += " (via `toFirestore()`)"), _2 += ". ";
  let a2 = "";
  return (s2 || o2) && (a2 += " (found", s2 && (a2 += ` in field ${r2}`), o2 && (a2 += ` in document ${i2}`), a2 += ")"), new FirestoreError(C.INVALID_ARGUMENT, _2 + e2 + a2);
}
__name(__PRIVATE_createError, "__PRIVATE_createError");
function __PRIVATE_fieldMaskContains(e2, t2) {
  return e2.some((e3) => e3.isEqual(t2));
}
__name(__PRIVATE_fieldMaskContains, "__PRIVATE_fieldMaskContains");
/**
 * @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 DocumentSnapshot$1 {
  static {
    __name(this, "DocumentSnapshot$1");
  }
  // Note: This class is stripped down version of the DocumentSnapshot in
  // the legacy SDK. The changes are:
  // - No support for SnapshotMetadata.
  // - No support for SnapshotOptions.
  /** @hideconstructor protected */
  constructor(e2, t2, n2, r2, i2) {
    this._firestore = e2, this._userDataWriter = t2, this._key = n2, this._document = r2, this._converter = i2;
  }
  /** Property of the `DocumentSnapshot` that provides the document's ID. */
  get id() {
    return this._key.path.lastSegment();
  }
  /**
   * The `DocumentReference` for the document included in the `DocumentSnapshot`.
   */
  get ref() {
    return new DocumentReference(this._firestore, this._converter, this._key);
  }
  /**
   * Signals whether or not the document at the snapshot's location exists.
   *
   * @returns true if the document exists.
   */
  exists() {
    return null !== this._document;
  }
  /**
   * Retrieves all fields in the document as an `Object`. Returns `undefined` if
   * the document doesn't exist.
   *
   * @returns An `Object` containing all fields in the document or `undefined`
   * if the document doesn't exist.
   */
  data() {
    if (this._document) {
      if (this._converter) {
        const e2 = new QueryDocumentSnapshot$1(
          this._firestore,
          this._userDataWriter,
          this._key,
          this._document,
          /* converter= */
          null
        );
        return this._converter.fromFirestore(e2);
      }
      return this._userDataWriter.convertValue(this._document.data.value);
    }
  }
  /**
   * Retrieves the field specified by `fieldPath`. Returns `undefined` if the
   * document or field doesn't exist.
   *
   * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific
   * field.
   * @returns The data at the specified field location or undefined if no such
   * field exists in the document.
   */
  // We are using `any` here to avoid an explicit cast by our users.
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  get(e2) {
    if (this._document) {
      const t2 = this._document.data.field(__PRIVATE_fieldPathFromArgument("DocumentSnapshot.get", e2));
      if (null !== t2) return this._userDataWriter.convertValue(t2);
    }
  }
}
class QueryDocumentSnapshot$1 extends DocumentSnapshot$1 {
  static {
    __name(this, "QueryDocumentSnapshot$1");
  }
  /**
   * Retrieves all fields in the document as an `Object`.
   *
   * @override
   * @returns An `Object` containing all fields in the document.
   */
  data() {
    return super.data();
  }
}
function __PRIVATE_fieldPathFromArgument(e2, t2) {
  return "string" == typeof t2 ? __PRIVATE_fieldPathFromDotSeparatedString(e2, t2) : t2 instanceof FieldPath ? t2._internalPath : t2._delegate._internalPath;
}
__name(__PRIVATE_fieldPathFromArgument, "__PRIVATE_fieldPathFromArgument");
/**
 * @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.
 */
function __PRIVATE_validateHasExplicitOrderByForLimitToLast(e2) {
  if ("L" === e2.limitType && 0 === e2.explicitOrderBy.length) throw new FirestoreError(C.UNIMPLEMENTED, "limitToLast() queries require specifying at least one orderBy() clause");
}
__name(__PRIVATE_validateHasExplicitOrderByForLimitToLast, "__PRIVATE_validateHasExplicitOrderByForLimitToLast");
class AppliableConstraint {
  static {
    __name(this, "AppliableConstraint");
  }
}
class QueryConstraint extends AppliableConstraint {
  static {
    __name(this, "QueryConstraint");
  }
}
function query(e2, t2, ...n2) {
  let r2 = [];
  t2 instanceof AppliableConstraint && r2.push(t2), r2 = r2.concat(n2), (/* @__PURE__ */ __name(function __PRIVATE_validateQueryConstraintArray(e3) {
    const t3 = e3.filter((e4) => e4 instanceof QueryCompositeFilterConstraint).length, n3 = e3.filter((e4) => e4 instanceof QueryFieldFilterConstraint).length;
    if (t3 > 1 || t3 > 0 && n3 > 0) throw new FirestoreError(C.INVALID_ARGUMENT, "InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`.");
  }, "__PRIVATE_validateQueryConstraintArray"))(r2);
  for (const t3 of r2) e2 = t3._apply(e2);
  return e2;
}
__name(query, "query");
class QueryFieldFilterConstraint extends QueryConstraint {
  static {
    __name(this, "QueryFieldFilterConstraint");
  }
  /**
   * @internal
   */
  constructor(e2, t2, n2) {
    super(), this._field = e2, this._op = t2, this._value = n2, /** The type of this query constraint */
    this.type = "where";
  }
  static _create(e2, t2, n2) {
    return new QueryFieldFilterConstraint(e2, t2, n2);
  }
  _apply(e2) {
    const t2 = this._parse(e2);
    return __PRIVATE_validateNewFieldFilter(e2._query, t2), new Query(e2.firestore, e2.converter, __PRIVATE_queryWithAddedFilter(e2._query, t2));
  }
  _parse(e2) {
    const t2 = __PRIVATE_newUserDataReader(e2.firestore), n2 = (/* @__PURE__ */ __name(function __PRIVATE_newQueryFilter(e3, t3, n3, r2, i2, s2, o2) {
      let _2;
      if (i2.isKeyField()) {
        if ("array-contains" === s2 || "array-contains-any" === s2) throw new FirestoreError(C.INVALID_ARGUMENT, `Invalid Query. You can't perform '${s2}' queries on documentId().`);
        if ("in" === s2 || "not-in" === s2) {
          __PRIVATE_validateDisjunctiveFilterElements(o2, s2);
          const t4 = [];
          for (const n4 of o2) t4.push(__PRIVATE_parseDocumentIdValue(r2, e3, n4));
          _2 = {
            arrayValue: {
              values: t4
            }
          };
        } else _2 = __PRIVATE_parseDocumentIdValue(r2, e3, o2);
      } else "in" !== s2 && "not-in" !== s2 && "array-contains-any" !== s2 || __PRIVATE_validateDisjunctiveFilterElements(o2, s2), _2 = __PRIVATE_parseQueryValue(
        n3,
        t3,
        o2,
        /* allowArrays= */
        "in" === s2 || "not-in" === s2
      );
      const a2 = FieldFilter.create(i2, s2, _2);
      return a2;
    }, "__PRIVATE_newQueryFilter"))(e2._query, "where", t2, e2.firestore._databaseId, this._field, this._op, this._value);
    return n2;
  }
}
function where(e2, t2, n2) {
  const r2 = t2, i2 = __PRIVATE_fieldPathFromArgument("where", e2);
  return QueryFieldFilterConstraint._create(i2, r2, n2);
}
__name(where, "where");
class QueryCompositeFilterConstraint extends AppliableConstraint {
  static {
    __name(this, "QueryCompositeFilterConstraint");
  }
  /**
   * @internal
   */
  constructor(e2, t2) {
    super(), this.type = e2, this._queryConstraints = t2;
  }
  static _create(e2, t2) {
    return new QueryCompositeFilterConstraint(e2, t2);
  }
  _parse(e2) {
    const t2 = this._queryConstraints.map((t3) => t3._parse(e2)).filter((e3) => e3.getFilters().length > 0);
    return 1 === t2.length ? t2[0] : CompositeFilter.create(t2, this._getOperator());
  }
  _apply(e2) {
    const t2 = this._parse(e2);
    return 0 === t2.getFilters().length ? e2 : ((/* @__PURE__ */ __name(function __PRIVATE_validateNewFilter(e3, t3) {
      let n2 = e3;
      const r2 = t3.getFlattenedFilters();
      for (const e4 of r2) __PRIVATE_validateNewFieldFilter(n2, e4), n2 = __PRIVATE_queryWithAddedFilter(n2, e4);
    }, "__PRIVATE_validateNewFilter"))(e2._query, t2), new Query(e2.firestore, e2.converter, __PRIVATE_queryWithAddedFilter(e2._query, t2)));
  }
  _getQueryConstraints() {
    return this._queryConstraints;
  }
  _getOperator() {
    return "and" === this.type ? "and" : "or";
  }
}
function or(...e2) {
  return e2.forEach((e3) => __PRIVATE_validateQueryFilterConstraint("or", e3)), QueryCompositeFilterConstraint._create("or", e2);
}
__name(or, "or");
function and(...e2) {
  return e2.forEach((e3) => __PRIVATE_validateQueryFilterConstraint("and", e3)), QueryCompositeFilterConstraint._create("and", e2);
}
__name(and, "and");
class QueryOrderByConstraint extends QueryConstraint {
  static {
    __name(this, "QueryOrderByConstraint");
  }
  /**
   * @internal
   */
  constructor(e2, t2) {
    super(), this._field = e2, this._direction = t2, /** The type of this query constraint */
    this.type = "orderBy";
  }
  static _create(e2, t2) {
    return new QueryOrderByConstraint(e2, t2);
  }
  _apply(e2) {
    const t2 = (/* @__PURE__ */ __name(function __PRIVATE_newQueryOrderBy(e3, t3, n2) {
      if (null !== e3.startAt) throw new FirestoreError(C.INVALID_ARGUMENT, "Invalid query. You must not call startAt() or startAfter() before calling orderBy().");
      if (null !== e3.endAt) throw new FirestoreError(C.INVALID_ARGUMENT, "Invalid query. You must not call endAt() or endBefore() before calling orderBy().");
      const r2 = new OrderBy(t3, n2);
      return r2;
    }, "__PRIVATE_newQueryOrderBy"))(e2._query, this._field, this._direction);
    return new Query(e2.firestore, e2.converter, (/* @__PURE__ */ __name(function __PRIVATE_queryWithAddedOrderBy(e3, t3) {
      const n2 = e3.explicitOrderBy.concat([t3]);
      return new __PRIVATE_QueryImpl(e3.path, e3.collectionGroup, n2, e3.filters.slice(), e3.limit, e3.limitType, e3.startAt, e3.endAt);
    }, "__PRIVATE_queryWithAddedOrderBy"))(e2._query, t2));
  }
}
function orderBy(e2, t2 = "asc") {
  const n2 = t2, r2 = __PRIVATE_fieldPathFromArgument("orderBy", e2);
  return QueryOrderByConstraint._create(r2, n2);
}
__name(orderBy, "orderBy");
class QueryLimitConstraint extends QueryConstraint {
  static {
    __name(this, "QueryLimitConstraint");
  }
  /**
   * @internal
   */
  constructor(e2, t2, n2) {
    super(), this.type = e2, this._limit = t2, this._limitType = n2;
  }
  static _create(e2, t2, n2) {
    return new QueryLimitConstraint(e2, t2, n2);
  }
  _apply(e2) {
    return new Query(e2.firestore, e2.converter, __PRIVATE_queryWithLimit(e2._query, this._limit, this._limitType));
  }
}
function limit(e2) {
  return __PRIVATE_validatePositiveNumber("limit", e2), QueryLimitConstraint._create(
    "limit",
    e2,
    "F"
    /* LimitType.First */
  );
}
__name(limit, "limit");
function limitToLast(e2) {
  return __PRIVATE_validatePositiveNumber("limitToLast", e2), QueryLimitConstraint._create(
    "limitToLast",
    e2,
    "L"
    /* LimitType.Last */
  );
}
__name(limitToLast, "limitToLast");
class QueryStartAtConstraint extends QueryConstraint {
  static {
    __name(this, "QueryStartAtConstraint");
  }
  /**
   * @internal
   */
  constructor(e2, t2, n2) {
    super(), this.type = e2, this._docOrFields = t2, this._inclusive = n2;
  }
  static _create(e2, t2, n2) {
    return new QueryStartAtConstraint(e2, t2, n2);
  }
  _apply(e2) {
    const t2 = __PRIVATE_newQueryBoundFromDocOrFields(e2, this.type, this._docOrFields, this._inclusive);
    return new Query(e2.firestore, e2.converter, (/* @__PURE__ */ __name(function __PRIVATE_queryWithStartAt(e3, t3) {
      return new __PRIVATE_QueryImpl(e3.path, e3.collectionGroup, e3.explicitOrderBy.slice(), e3.filters.slice(), e3.limit, e3.limitType, t3, e3.endAt);
    }, "__PRIVATE_queryWithStartAt"))(e2._query, t2));
  }
}
function startAt(...e2) {
  return QueryStartAtConstraint._create(
    "startAt",
    e2,
    /*inclusive=*/
    true
  );
}
__name(startAt, "startAt");
function startAfter(...e2) {
  return QueryStartAtConstraint._create(
    "startAfter",
    e2,
    /*inclusive=*/
    false
  );
}
__name(startAfter, "startAfter");
class QueryEndAtConstraint extends QueryConstraint {
  static {
    __name(this, "QueryEndAtConstraint");
  }
  /**
   * @internal
   */
  constructor(e2, t2, n2) {
    super(), this.type = e2, this._docOrFields = t2, this._inclusive = n2;
  }
  static _create(e2, t2, n2) {
    return new QueryEndAtConstraint(e2, t2, n2);
  }
  _apply(e2) {
    const t2 = __PRIVATE_newQueryBoundFromDocOrFields(e2, this.type, this._docOrFields, this._inclusive);
    return new Query(e2.firestore, e2.converter, (/* @__PURE__ */ __name(function __PRIVATE_queryWithEndAt(e3, t3) {
      return new __PRIVATE_QueryImpl(e3.path, e3.collectionGroup, e3.explicitOrderBy.slice(), e3.filters.slice(), e3.limit, e3.limitType, e3.startAt, t3);
    }, "__PRIVATE_queryWithEndAt"))(e2._query, t2));
  }
}
function endBefore(...e2) {
  return QueryEndAtConstraint._create(
    "endBefore",
    e2,
    /*inclusive=*/
    false
  );
}
__name(endBefore, "endBefore");
function endAt(...e2) {
  return QueryEndAtConstraint._create(
    "endAt",
    e2,
    /*inclusive=*/
    true
  );
}
__name(endAt, "endAt");
function __PRIVATE_newQueryBoundFromDocOrFields(e2, t2, n2, r2) {
  if (n2[0] = getModularInstance(n2[0]), n2[0] instanceof DocumentSnapshot$1) return (/* @__PURE__ */ __name(function __PRIVATE_newQueryBoundFromDocument(e3, t3, n3, r3, i2) {
    if (!r3) throw new FirestoreError(C.NOT_FOUND, `Can't use a DocumentSnapshot that doesn't exist for ${n3}().`);
    const s2 = [];
    for (const n4 of __PRIVATE_queryNormalizedOrderBy(e3)) if (n4.field.isKeyField()) s2.push(__PRIVATE_refValue(t3, r3.key));
    else {
      const e4 = r3.data.field(n4.field);
      if (__PRIVATE_isServerTimestamp(e4)) throw new FirestoreError(C.INVALID_ARGUMENT, 'Invalid query. You are trying to start or end a query using a document for which the field "' + n4.field + '" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');
      if (null === e4) {
        const e5 = n4.field.canonicalString();
        throw new FirestoreError(C.INVALID_ARGUMENT, `Invalid query. You are trying to start or end a query using a document for which the field '${e5}' (used as the orderBy) does not exist.`);
      }
      s2.push(e4);
    }
    return new Bound(s2, i2);
  }, "__PRIVATE_newQueryBoundFromDocument"))(e2._query, e2.firestore._databaseId, t2, n2[0]._document, r2);
  {
    const i2 = __PRIVATE_newUserDataReader(e2.firestore);
    return (/* @__PURE__ */ __name(function __PRIVATE_newQueryBoundFromFields(e3, t3, n3, r3, i3, s2) {
      const o2 = e3.explicitOrderBy;
      if (i3.length > o2.length) throw new FirestoreError(C.INVALID_ARGUMENT, `Too many arguments provided to ${r3}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);
      const _2 = [];
      for (let s3 = 0; s3 < i3.length; s3++) {
        const a2 = i3[s3];
        if (o2[s3].field.isKeyField()) {
          if ("string" != typeof a2) throw new FirestoreError(C.INVALID_ARGUMENT, `Invalid query. Expected a string for document ID in ${r3}(), but got a ${typeof a2}`);
          if (!__PRIVATE_isCollectionGroupQuery(e3) && -1 !== a2.indexOf("/")) throw new FirestoreError(C.INVALID_ARGUMENT, `Invalid query. When querying a collection and ordering by documentId(), the value passed to ${r3}() must be a plain document ID, but '${a2}' contains a slash.`);
          const n4 = e3.path.child(ResourcePath.fromString(a2));
          if (!DocumentKey.isDocumentKey(n4)) throw new FirestoreError(C.INVALID_ARGUMENT, `Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${r3}() must result in a valid document path, but '${n4}' is not because it contains an odd number of segments.`);
          const i4 = new DocumentKey(n4);
          _2.push(__PRIVATE_refValue(t3, i4));
        } else {
          const e4 = __PRIVATE_parseQueryValue(n3, r3, a2);
          _2.push(e4);
        }
      }
      return new Bound(_2, s2);
    }, "__PRIVATE_newQueryBoundFromFields"))(e2._query, e2.firestore._databaseId, i2, t2, n2, r2);
  }
}
__name(__PRIVATE_newQueryBoundFromDocOrFields, "__PRIVATE_newQueryBoundFromDocOrFields");
function __PRIVATE_parseDocumentIdValue(e2, t2, n2) {
  if ("string" == typeof (n2 = getModularInstance(n2))) {
    if ("" === n2) throw new FirestoreError(C.INVALID_ARGUMENT, "Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");
    if (!__PRIVATE_isCollectionGroupQuery(t2) && -1 !== n2.indexOf("/")) throw new FirestoreError(C.INVALID_ARGUMENT, `Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${n2}' contains a '/' character.`);
    const r2 = t2.path.child(ResourcePath.fromString(n2));
    if (!DocumentKey.isDocumentKey(r2)) throw new FirestoreError(C.INVALID_ARGUMENT, `Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${r2}' is not because it has an odd number of segments (${r2.length}).`);
    return __PRIVATE_refValue(e2, new DocumentKey(r2));
  }
  if (n2 instanceof DocumentReference) return __PRIVATE_refValue(e2, n2._key);
  throw new FirestoreError(C.INVALID_ARGUMENT, `Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${__PRIVATE_valueDescription(n2)}.`);
}
__name(__PRIVATE_parseDocumentIdValue, "__PRIVATE_parseDocumentIdValue");
function __PRIVATE_validateDisjunctiveFilterElements(e2, t2) {
  if (!Array.isArray(e2) || 0 === e2.length) throw new FirestoreError(C.INVALID_ARGUMENT, `Invalid Query. A non-empty array is required for '${t2.toString()}' filters.`);
}
__name(__PRIVATE_validateDisjunctiveFilterElements, "__PRIVATE_validateDisjunctiveFilterElements");
function __PRIVATE_validateNewFieldFilter(e2, t2) {
  const n2 = (/* @__PURE__ */ __name(function __PRIVATE_findOpInsideFilters(e3, t3) {
    for (const n3 of e3) for (const e4 of n3.getFlattenedFilters()) if (t3.indexOf(e4.op) >= 0) return e4.op;
    return null;
  }, "__PRIVATE_findOpInsideFilters"))(e2.filters, (/* @__PURE__ */ __name(function __PRIVATE_conflictingOps(e3) {
    switch (e3) {
      case "!=":
        return [
          "!=",
          "not-in"
          /* Operator.NOT_IN */
        ];
      case "array-contains-any":
      case "in":
        return [
          "not-in"
          /* Operator.NOT_IN */
        ];
      case "not-in":
        return [
          "array-contains-any",
          "in",
          "not-in",
          "!="
          /* Operator.NOT_EQUAL */
        ];
      default:
        return [];
    }
  }, "__PRIVATE_conflictingOps"))(t2.op));
  if (null !== n2)
    throw n2 === t2.op ? new FirestoreError(C.INVALID_ARGUMENT, `Invalid query. You cannot use more than one '${t2.op.toString()}' filter.`) : new FirestoreError(C.INVALID_ARGUMENT, `Invalid query. You cannot use '${t2.op.toString()}' filters with '${n2.toString()}' filters.`);
}
__name(__PRIVATE_validateNewFieldFilter, "__PRIVATE_validateNewFieldFilter");
function __PRIVATE_validateQueryFilterConstraint(e2, t2) {
  if (!(t2 instanceof QueryFieldFilterConstraint || t2 instanceof QueryCompositeFilterConstraint)) throw new FirestoreError(C.INVALID_ARGUMENT, `Function ${e2}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`);
}
__name(__PRIVATE_validateQueryFilterConstraint, "__PRIVATE_validateQueryFilterConstraint");
class AbstractUserDataWriter {
  static {
    __name(this, "AbstractUserDataWriter");
  }
  convertValue(e2, t2 = "none") {
    switch (__PRIVATE_typeOrder(e2)) {
      case 0:
        return null;
      case 1:
        return e2.booleanValue;
      case 2:
        return __PRIVATE_normalizeNumber(e2.integerValue || e2.doubleValue);
      case 3:
        return this.convertTimestamp(e2.timestampValue);
      case 4:
        return this.convertServerTimestamp(e2, t2);
      case 5:
        return e2.stringValue;
      case 6:
        return this.convertBytes(__PRIVATE_normalizeByteString(e2.bytesValue));
      case 7:
        return this.convertReference(e2.referenceValue);
      case 8:
        return this.convertGeoPoint(e2.geoPointValue);
      case 9:
        return this.convertArray(e2.arrayValue, t2);
      case 11:
        return this.convertObject(e2.mapValue, t2);
      case 10:
        return this.convertVectorValue(e2.mapValue);
      default:
        throw fail();
    }
  }
  convertObject(e2, t2) {
    return this.convertObjectMap(e2.fields, t2);
  }
  /**
   * @internal
   */
  convertObjectMap(e2, t2 = "none") {
    const n2 = {};
    return forEach$2(e2, (e3, r2) => {
      n2[e3] = this.convertValue(r2, t2);
    }), n2;
  }
  /**
   * @internal
   */
  convertVectorValue(e2) {
    var t2, n2, r2;
    const i2 = null === (r2 = null === (n2 = null === (t2 = e2.fields) || void 0 === t2 ? void 0 : t2[at].arrayValue) || void 0 === n2 ? void 0 : n2.values) || void 0 === r2 ? void 0 : r2.map((e3) => __PRIVATE_normalizeNumber(e3.doubleValue));
    return new VectorValue(i2);
  }
  convertGeoPoint(e2) {
    return new GeoPoint(__PRIVATE_normalizeNumber(e2.latitude), __PRIVATE_normalizeNumber(e2.longitude));
  }
  convertArray(e2, t2) {
    return (e2.values || []).map((e3) => this.convertValue(e3, t2));
  }
  convertServerTimestamp(e2, t2) {
    switch (t2) {
      case "previous":
        const n2 = __PRIVATE_getPreviousValue(e2);
        return null == n2 ? null : this.convertValue(n2, t2);
      case "estimate":
        return this.convertTimestamp(__PRIVATE_getLocalWriteTime(e2));
      default:
        return null;
    }
  }
  convertTimestamp(e2) {
    const t2 = __PRIVATE_normalizeTimestamp(e2);
    return new Timestamp(t2.seconds, t2.nanos);
  }
  convertDocumentKey(e2, t2) {
    const n2 = ResourcePath.fromString(e2);
    __PRIVATE_hardAssert(__PRIVATE_isValidResourceName(n2));
    const r2 = new DatabaseId(n2.get(1), n2.get(3)), i2 = new DocumentKey(n2.popFirst(5));
    return r2.isEqual(t2) || // TODO(b/64130202): Somehow support foreign references.
    __PRIVATE_logError(`Document ${i2} contains a document reference within a different database (${r2.projectId}/${r2.database}) which is not supported. It will be treated as a reference in the current database (${t2.projectId}/${t2.database}) instead.`), i2;
  }
}
/**
 * @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.
 */
function __PRIVATE_applyFirestoreDataConverter(e2, t2, n2) {
  let r2;
  return r2 = e2 ? n2 && (n2.merge || n2.mergeFields) ? e2.toFirestore(t2, n2) : e2.toFirestore(t2) : t2, r2;
}
__name(__PRIVATE_applyFirestoreDataConverter, "__PRIVATE_applyFirestoreDataConverter");
class __PRIVATE_LiteUserDataWriter extends AbstractUserDataWriter {
  static {
    __name(this, "__PRIVATE_LiteUserDataWriter");
  }
  constructor(e2) {
    super(), this.firestore = e2;
  }
  convertBytes(e2) {
    return new Bytes(e2);
  }
  convertReference(e2) {
    const t2 = this.convertDocumentKey(e2, this.firestore._databaseId);
    return new DocumentReference(
      this.firestore,
      /* converter= */
      null,
      t2
    );
  }
}
/**
 * @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 sum(e2) {
  return new AggregateField("sum", __PRIVATE_fieldPathFromArgument$1("sum", e2));
}
__name(sum, "sum");
function average(e2) {
  return new AggregateField("avg", __PRIVATE_fieldPathFromArgument$1("average", e2));
}
__name(average, "average");
function count() {
  return new AggregateField("count");
}
__name(count, "count");
function aggregateFieldEqual(e2, t2) {
  var n2, r2;
  return e2 instanceof AggregateField && t2 instanceof AggregateField && e2.aggregateType === t2.aggregateType && (null === (n2 = e2._internalFieldPath) || void 0 === n2 ? void 0 : n2.canonicalString()) === (null === (r2 = t2._internalFieldPath) || void 0 === r2 ? void 0 : r2.canonicalString());
}
__name(aggregateFieldEqual, "aggregateFieldEqual");
function aggregateQuerySnapshotEqual(e2, t2) {
  return queryEqual(e2.query, t2.query) && deepEqual(e2.data(), t2.data());
}
__name(aggregateQuerySnapshotEqual, "aggregateQuerySnapshotEqual");
/**
 * @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 SnapshotMetadata {
  static {
    __name(this, "SnapshotMetadata");
  }
  /** @hideconstructor */
  constructor(e2, t2) {
    this.hasPendingWrites = e2, this.fromCache = t2;
  }
  /**
   * Returns true if this `SnapshotMetadata` is equal to the provided one.
   *
   * @param other - The `SnapshotMetadata` to compare against.
   * @returns true if this `SnapshotMetadata` is equal to the provided one.
   */
  isEqual(e2) {
    return this.hasPendingWrites === e2.hasPendingWrites && this.fromCache === e2.fromCache;
  }
}
class DocumentSnapshot extends DocumentSnapshot$1 {
  static {
    __name(this, "DocumentSnapshot");
  }
  /** @hideconstructor protected */
  constructor(e2, t2, n2, r2, i2, s2) {
    super(e2, t2, n2, r2, s2), this._firestore = e2, this._firestoreImpl = e2, this.metadata = i2;
  }
  /**
   * Returns whether or not the data exists. True if the document exists.
   */
  exists() {
    return super.exists();
  }
  /**
   * Retrieves all fields in the document as an `Object`. Returns `undefined` if
   * the document doesn't exist.
   *
   * By default, `serverTimestamp()` values that have not yet been
   * set to their final value will be returned as `null`. You can override
   * this by passing an options object.
   *
   * @param options - An options object to configure how data is retrieved from
   * the snapshot (for example the desired behavior for server timestamps that
   * have not yet been set to their final value).
   * @returns An `Object` containing all fields in the document or `undefined` if
   * the document doesn't exist.
   */
  data(e2 = {}) {
    if (this._document) {
      if (this._converter) {
        const t2 = new QueryDocumentSnapshot(
          this._firestore,
          this._userDataWriter,
          this._key,
          this._document,
          this.metadata,
          /* converter= */
          null
        );
        return this._converter.fromFirestore(t2, e2);
      }
      return this._userDataWriter.convertValue(this._document.data.value, e2.serverTimestamps);
    }
  }
  /**
   * Retrieves the field specified by `fieldPath`. Returns `undefined` if the
   * document or field doesn't exist.
   *
   * By default, a `serverTimestamp()` that has not yet been set to
   * its final value will be returned as `null`. You can override this by
   * passing an options object.
   *
   * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific
   * field.
   * @param options - An options object to configure how the field is retrieved
   * from the snapshot (for example the desired behavior for server timestamps
   * that have not yet been set to their final value).
   * @returns The data at the specified field location or undefined if no such
   * field exists in the document.
   */
  // We are using `any` here to avoid an explicit cast by our users.
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  get(e2, t2 = {}) {
    if (this._document) {
      const n2 = this._document.data.field(__PRIVATE_fieldPathFromArgument("DocumentSnapshot.get", e2));
      if (null !== n2) return this._userDataWriter.convertValue(n2, t2.serverTimestamps);
    }
  }
}
class QueryDocumentSnapshot extends DocumentSnapshot {
  static {
    __name(this, "QueryDocumentSnapshot");
  }
  /**
   * Retrieves all fields in the document as an `Object`.
   *
   * By default, `serverTimestamp()` values that have not yet been
   * set to their final value will be returned as `null`. You can override
   * this by passing an options object.
   *
   * @override
   * @param options - An options object to configure how data is retrieved from
   * the snapshot (for example the desired behavior for server timestamps that
   * have not yet been set to their final value).
   * @returns An `Object` containing all fields in the document.
   */
  data(e2 = {}) {
    return super.data(e2);
  }
}
class QuerySnapshot {
  static {
    __name(this, "QuerySnapshot");
  }
  /** @hideconstructor */
  constructor(e2, t2, n2, r2) {
    this._firestore = e2, this._userDataWriter = t2, this._snapshot = r2, this.metadata = new SnapshotMetadata(r2.hasPendingWrites, r2.fromCache), this.query = n2;
  }
  /** An array of all the documents in the `QuerySnapshot`. */
  get docs() {
    const e2 = [];
    return this.forEach((t2) => e2.push(t2)), e2;
  }
  /** The number of documents in the `QuerySnapshot`. */
  get size() {
    return this._snapshot.docs.size;
  }
  /** True if there are no documents in the `QuerySnapshot`. */
  get empty() {
    return 0 === this.size;
  }
  /**
   * Enumerates all of the documents in the `QuerySnapshot`.
   *
   * @param callback - A callback to be called with a `QueryDocumentSnapshot` for
   * each document in the snapshot.
   * @param thisArg - The `this` binding for the callback.
   */
  forEach(e2, t2) {
    this._snapshot.docs.forEach((n2) => {
      e2.call(t2, new QueryDocumentSnapshot(this._firestore, this._userDataWriter, n2.key, n2, new SnapshotMetadata(this._snapshot.mutatedKeys.has(n2.key), this._snapshot.fromCache), this.query.converter));
    });
  }
  /**
   * Returns an array of the documents changes since the last snapshot. If this
   * is the first snapshot, all documents will be in the list as 'added'
   * changes.
   *
   * @param options - `SnapshotListenOptions` that control whether metadata-only
   * changes (i.e. only `DocumentSnapshot.metadata` changed) should trigger
   * snapshot events.
   */
  docChanges(e2 = {}) {
    const t2 = !!e2.includeMetadataChanges;
    if (t2 && this._snapshot.excludesMetadataChanges) throw new FirestoreError(C.INVALID_ARGUMENT, "To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");
    return this._cachedChanges && this._cachedChangesIncludeMetadataChanges === t2 || (this._cachedChanges = /** Calculates the array of `DocumentChange`s for a given `ViewSnapshot`. */
    (/* @__PURE__ */ __name(function __PRIVATE_changesFromSnapshot(e3, t3) {
      if (e3._snapshot.oldDocs.isEmpty()) {
        let t4 = 0;
        return e3._snapshot.docChanges.map((n2) => {
          const r2 = new QueryDocumentSnapshot(e3._firestore, e3._userDataWriter, n2.doc.key, n2.doc, new SnapshotMetadata(e3._snapshot.mutatedKeys.has(n2.doc.key), e3._snapshot.fromCache), e3.query.converter);
          return n2.doc, {
            type: "added",
            doc: r2,
            oldIndex: -1,
            newIndex: t4++
          };
        });
      }
      {
        let n2 = e3._snapshot.oldDocs;
        return e3._snapshot.docChanges.filter((e4) => t3 || 3 !== e4.type).map((t4) => {
          const r2 = new QueryDocumentSnapshot(e3._firestore, e3._userDataWriter, t4.doc.key, t4.doc, new SnapshotMetadata(e3._snapshot.mutatedKeys.has(t4.doc.key), e3._snapshot.fromCache), e3.query.converter);
          let i2 = -1, s2 = -1;
          return 0 !== t4.type && (i2 = n2.indexOf(t4.doc.key), n2 = n2.delete(t4.doc.key)), 1 !== t4.type && (n2 = n2.add(t4.doc), s2 = n2.indexOf(t4.doc.key)), {
            type: __PRIVATE_resultChangeType(t4.type),
            doc: r2,
            oldIndex: i2,
            newIndex: s2
          };
        });
      }
    }, "__PRIVATE_changesFromSnapshot"))(this, t2), this._cachedChangesIncludeMetadataChanges = t2), this._cachedChanges;
  }
}
function __PRIVATE_resultChangeType(e2) {
  switch (e2) {
    case 0:
      return "added";
    case 2:
    case 3:
      return "modified";
    case 1:
      return "removed";
    default:
      return fail();
  }
}
__name(__PRIVATE_resultChangeType, "__PRIVATE_resultChangeType");
function snapshotEqual(e2, t2) {
  return e2 instanceof DocumentSnapshot && t2 instanceof DocumentSnapshot ? e2._firestore === t2._firestore && e2._key.isEqual(t2._key) && (null === e2._document ? null === t2._document : e2._document.isEqual(t2._document)) && e2._converter === t2._converter : e2 instanceof QuerySnapshot && t2 instanceof QuerySnapshot && (e2._firestore === t2._firestore && queryEqual(e2.query, t2.query) && e2.metadata.isEqual(t2.metadata) && e2._snapshot.isEqual(t2._snapshot));
}
__name(snapshotEqual, "snapshotEqual");
/**
 * @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.
 */
function getDoc(e2) {
  e2 = __PRIVATE_cast(e2, DocumentReference);
  const t2 = __PRIVATE_cast(e2.firestore, Firestore);
  return __PRIVATE_firestoreClientGetDocumentViaSnapshotListener(ensureFirestoreConfigured(t2), e2._key).then((n2) => __PRIVATE_convertToDocSnapshot(t2, e2, n2));
}
__name(getDoc, "getDoc");
class __PRIVATE_ExpUserDataWriter extends AbstractUserDataWriter {
  static {
    __name(this, "__PRIVATE_ExpUserDataWriter");
  }
  constructor(e2) {
    super(), this.firestore = e2;
  }
  convertBytes(e2) {
    return new Bytes(e2);
  }
  convertReference(e2) {
    const t2 = this.convertDocumentKey(e2, this.firestore._databaseId);
    return new DocumentReference(
      this.firestore,
      /* converter= */
      null,
      t2
    );
  }
}
function getDocFromCache(e2) {
  e2 = __PRIVATE_cast(e2, DocumentReference);
  const t2 = __PRIVATE_cast(e2.firestore, Firestore), n2 = ensureFirestoreConfigured(t2), r2 = new __PRIVATE_ExpUserDataWriter(t2);
  return __PRIVATE_firestoreClientGetDocumentFromLocalCache(n2, e2._key).then((n3) => new DocumentSnapshot(t2, r2, e2._key, n3, new SnapshotMetadata(
    null !== n3 && n3.hasLocalMutations,
    /* fromCache= */
    true
  ), e2.converter));
}
__name(getDocFromCache, "getDocFromCache");
function getDocFromServer(e2) {
  e2 = __PRIVATE_cast(e2, DocumentReference);
  const t2 = __PRIVATE_cast(e2.firestore, Firestore);
  return __PRIVATE_firestoreClientGetDocumentViaSnapshotListener(ensureFirestoreConfigured(t2), e2._key, {
    source: "server"
  }).then((n2) => __PRIVATE_convertToDocSnapshot(t2, e2, n2));
}
__name(getDocFromServer, "getDocFromServer");
function getDocs(e2) {
  e2 = __PRIVATE_cast(e2, Query);
  const t2 = __PRIVATE_cast(e2.firestore, Firestore), n2 = ensureFirestoreConfigured(t2), r2 = new __PRIVATE_ExpUserDataWriter(t2);
  return __PRIVATE_validateHasExplicitOrderByForLimitToLast(e2._query), __PRIVATE_firestoreClientGetDocumentsViaSnapshotListener(n2, e2._query).then((n3) => new QuerySnapshot(t2, r2, e2, n3));
}
__name(getDocs, "getDocs");
function getDocsFromCache(e2) {
  e2 = __PRIVATE_cast(e2, Query);
  const t2 = __PRIVATE_cast(e2.firestore, Firestore), n2 = ensureFirestoreConfigured(t2), r2 = new __PRIVATE_ExpUserDataWriter(t2);
  return __PRIVATE_firestoreClientGetDocumentsFromLocalCache(n2, e2._query).then((n3) => new QuerySnapshot(t2, r2, e2, n3));
}
__name(getDocsFromCache, "getDocsFromCache");
function getDocsFromServer(e2) {
  e2 = __PRIVATE_cast(e2, Query);
  const t2 = __PRIVATE_cast(e2.firestore, Firestore), n2 = ensureFirestoreConfigured(t2), r2 = new __PRIVATE_ExpUserDataWriter(t2);
  return __PRIVATE_firestoreClientGetDocumentsViaSnapshotListener(n2, e2._query, {
    source: "server"
  }).then((n3) => new QuerySnapshot(t2, r2, e2, n3));
}
__name(getDocsFromServer, "getDocsFromServer");
function setDoc(e2, t2, n2) {
  e2 = __PRIVATE_cast(e2, DocumentReference);
  const r2 = __PRIVATE_cast(e2.firestore, Firestore), i2 = __PRIVATE_applyFirestoreDataConverter(e2.converter, t2, n2);
  return executeWrite(r2, [__PRIVATE_parseSetData(__PRIVATE_newUserDataReader(r2), "setDoc", e2._key, i2, null !== e2.converter, n2).toMutation(e2._key, Precondition.none())]);
}
__name(setDoc, "setDoc");
function updateDoc(e2, t2, n2, ...r2) {
  e2 = __PRIVATE_cast(e2, DocumentReference);
  const i2 = __PRIVATE_cast(e2.firestore, Firestore), s2 = __PRIVATE_newUserDataReader(i2);
  let o2;
  o2 = "string" == typeof // For Compat types, we have to "extract" the underlying types before
  // performing validation.
  (t2 = getModularInstance(t2)) || t2 instanceof FieldPath ? __PRIVATE_parseUpdateVarargs(s2, "updateDoc", e2._key, t2, n2, r2) : __PRIVATE_parseUpdateData(s2, "updateDoc", e2._key, t2);
  return executeWrite(i2, [o2.toMutation(e2._key, Precondition.exists(true))]);
}
__name(updateDoc, "updateDoc");
function deleteDoc(e2) {
  return executeWrite(__PRIVATE_cast(e2.firestore, Firestore), [new __PRIVATE_DeleteMutation(e2._key, Precondition.none())]);
}
__name(deleteDoc, "deleteDoc");
function addDoc(e2, t2) {
  const n2 = __PRIVATE_cast(e2.firestore, Firestore), r2 = doc$2(e2), i2 = __PRIVATE_applyFirestoreDataConverter(e2.converter, t2);
  return executeWrite(n2, [__PRIVATE_parseSetData(__PRIVATE_newUserDataReader(e2.firestore), "addDoc", r2._key, i2, null !== e2.converter, {}).toMutation(r2._key, Precondition.exists(false))]).then(() => r2);
}
__name(addDoc, "addDoc");
function onSnapshot(e2, ...t2) {
  var n2, r2, i2;
  e2 = getModularInstance(e2);
  let s2 = {
    includeMetadataChanges: false,
    source: "default"
  }, o2 = 0;
  "object" != typeof t2[o2] || __PRIVATE_isPartialObserver(t2[o2]) || (s2 = t2[o2], o2++);
  const _2 = {
    includeMetadataChanges: s2.includeMetadataChanges,
    source: s2.source
  };
  if (__PRIVATE_isPartialObserver(t2[o2])) {
    const e3 = t2[o2];
    t2[o2] = null === (n2 = e3.next) || void 0 === n2 ? void 0 : n2.bind(e3), t2[o2 + 1] = null === (r2 = e3.error) || void 0 === r2 ? void 0 : r2.bind(e3), t2[o2 + 2] = null === (i2 = e3.complete) || void 0 === i2 ? void 0 : i2.bind(e3);
  }
  let a2, u2, c2;
  if (e2 instanceof DocumentReference) u2 = __PRIVATE_cast(e2.firestore, Firestore), c2 = __PRIVATE_newQueryForPath(e2._key.path), a2 = {
    next: /* @__PURE__ */ __name((n3) => {
      t2[o2] && t2[o2](__PRIVATE_convertToDocSnapshot(u2, e2, n3));
    }, "next"),
    error: t2[o2 + 1],
    complete: t2[o2 + 2]
  };
  else {
    const n3 = __PRIVATE_cast(e2, Query);
    u2 = __PRIVATE_cast(n3.firestore, Firestore), c2 = n3._query;
    const r3 = new __PRIVATE_ExpUserDataWriter(u2);
    a2 = {
      next: /* @__PURE__ */ __name((e3) => {
        t2[o2] && t2[o2](new QuerySnapshot(u2, r3, n3, e3));
      }, "next"),
      error: t2[o2 + 1],
      complete: t2[o2 + 2]
    }, __PRIVATE_validateHasExplicitOrderByForLimitToLast(e2._query);
  }
  return (/* @__PURE__ */ __name(function __PRIVATE_firestoreClientListen(e3, t3, n3, r3) {
    const i3 = new __PRIVATE_AsyncObserver(r3), s3 = new __PRIVATE_QueryListener(t3, i3, n3);
    return e3.asyncQueue.enqueueAndForget(async () => __PRIVATE_eventManagerListen(await __PRIVATE_getEventManager(e3), s3)), () => {
      i3.su(), e3.asyncQueue.enqueueAndForget(async () => __PRIVATE_eventManagerUnlisten(await __PRIVATE_getEventManager(e3), s3));
    };
  }, "__PRIVATE_firestoreClientListen"))(ensureFirestoreConfigured(u2), c2, _2, a2);
}
__name(onSnapshot, "onSnapshot");
function onSnapshotsInSync(e2, t2) {
  return __PRIVATE_firestoreClientAddSnapshotsInSyncListener(ensureFirestoreConfigured(e2 = __PRIVATE_cast(e2, Firestore)), __PRIVATE_isPartialObserver(t2) ? t2 : {
    next: t2
  });
}
__name(onSnapshotsInSync, "onSnapshotsInSync");
function executeWrite(e2, t2) {
  return (/* @__PURE__ */ __name(function __PRIVATE_firestoreClientWrite(e3, t3) {
    const n2 = new __PRIVATE_Deferred();
    return e3.asyncQueue.enqueueAndForget(async () => __PRIVATE_syncEngineWrite(await __PRIVATE_getSyncEngine(e3), t3, n2)), n2.promise;
  }, "__PRIVATE_firestoreClientWrite"))(ensureFirestoreConfigured(e2), t2);
}
__name(executeWrite, "executeWrite");
function __PRIVATE_convertToDocSnapshot(e2, t2, n2) {
  const r2 = n2.docs.get(t2._key), i2 = new __PRIVATE_ExpUserDataWriter(e2);
  return new DocumentSnapshot(e2, i2, t2._key, r2, new SnapshotMetadata(n2.hasPendingWrites, n2.fromCache), t2.converter);
}
__name(__PRIVATE_convertToDocSnapshot, "__PRIVATE_convertToDocSnapshot");
/**
 * @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 getCountFromServer(e2) {
  return getAggregateFromServer(e2, {
    count: count()
  });
}
__name(getCountFromServer, "getCountFromServer");
function getAggregateFromServer(e2, t2) {
  const n2 = __PRIVATE_cast(e2.firestore, Firestore), r2 = ensureFirestoreConfigured(n2), i2 = __PRIVATE_mapToArray(t2, (e3, t3) => new __PRIVATE_AggregateImpl(t3, e3.aggregateType, e3._internalFieldPath));
  return __PRIVATE_firestoreClientRunAggregateQuery(r2, e2._query, i2).then((t3) => (
    /**
    * Converts the core aggregation result to an `AggregateQuerySnapshot`
    * that can be returned to the consumer.
    * @param query
    * @param aggregateResult Core aggregation result
    * @internal
    */
    (/* @__PURE__ */ __name(function __PRIVATE_convertToAggregateQuerySnapshot(e3, t4, n3) {
      const r3 = new __PRIVATE_ExpUserDataWriter(e3), i3 = new AggregateQuerySnapshot(t4, r3, n3);
      return i3;
    }, "__PRIVATE_convertToAggregateQuerySnapshot"))(n2, e2, t3)
  ));
}
__name(getAggregateFromServer, "getAggregateFromServer");
class __PRIVATE_MemoryLocalCacheImpl {
  static {
    __name(this, "__PRIVATE_MemoryLocalCacheImpl");
  }
  constructor(e2) {
    this.kind = "memory", this._onlineComponentProvider = OnlineComponentProvider.provider, (null == e2 ? void 0 : e2.garbageCollector) ? this._offlineComponentProvider = e2.garbageCollector._offlineComponentProvider : this._offlineComponentProvider = {
      build: /* @__PURE__ */ __name(() => new __PRIVATE_LruGcMemoryOfflineComponentProvider(void 0), "build")
    };
  }
  toJSON() {
    return {
      kind: this.kind
    };
  }
}
class __PRIVATE_PersistentLocalCacheImpl {
  static {
    __name(this, "__PRIVATE_PersistentLocalCacheImpl");
  }
  constructor(e2) {
    let t2;
    this.kind = "persistent", (null == e2 ? void 0 : e2.tabManager) ? (e2.tabManager._initialize(e2), t2 = e2.tabManager) : (t2 = persistentSingleTabManager(void 0), t2._initialize(e2)), this._onlineComponentProvider = t2._onlineComponentProvider, this._offlineComponentProvider = t2._offlineComponentProvider;
  }
  toJSON() {
    return {
      kind: this.kind
    };
  }
}
class __PRIVATE_MemoryEagerGarbageCollectorImpl {
  static {
    __name(this, "__PRIVATE_MemoryEagerGarbageCollectorImpl");
  }
  constructor() {
    this.kind = "memoryEager", this._offlineComponentProvider = __PRIVATE_MemoryOfflineComponentProvider.provider;
  }
  toJSON() {
    return {
      kind: this.kind
    };
  }
}
class __PRIVATE_MemoryLruGarbageCollectorImpl {
  static {
    __name(this, "__PRIVATE_MemoryLruGarbageCollectorImpl");
  }
  constructor(e2) {
    this.kind = "memoryLru", this._offlineComponentProvider = {
      build: /* @__PURE__ */ __name(() => new __PRIVATE_LruGcMemoryOfflineComponentProvider(e2), "build")
    };
  }
  toJSON() {
    return {
      kind: this.kind
    };
  }
}
function memoryEagerGarbageCollector() {
  return new __PRIVATE_MemoryEagerGarbageCollectorImpl();
}
__name(memoryEagerGarbageCollector, "memoryEagerGarbageCollector");
function memoryLruGarbageCollector(e2) {
  return new __PRIVATE_MemoryLruGarbageCollectorImpl(null == e2 ? void 0 : e2.cacheSizeBytes);
}
__name(memoryLruGarbageCollector, "memoryLruGarbageCollector");
function memoryLocalCache(e2) {
  return new __PRIVATE_MemoryLocalCacheImpl(e2);
}
__name(memoryLocalCache, "memoryLocalCache");
function persistentLocalCache(e2) {
  return new __PRIVATE_PersistentLocalCacheImpl(e2);
}
__name(persistentLocalCache, "persistentLocalCache");
class __PRIVATE_SingleTabManagerImpl {
  static {
    __name(this, "__PRIVATE_SingleTabManagerImpl");
  }
  constructor(e2) {
    this.forceOwnership = e2, this.kind = "persistentSingleTab";
  }
  toJSON() {
    return {
      kind: this.kind
    };
  }
  /**
   * @internal
   */
  _initialize(e2) {
    this._onlineComponentProvider = OnlineComponentProvider.provider, this._offlineComponentProvider = {
      build: /* @__PURE__ */ __name((t2) => new __PRIVATE_IndexedDbOfflineComponentProvider(t2, null == e2 ? void 0 : e2.cacheSizeBytes, this.forceOwnership), "build")
    };
  }
}
class __PRIVATE_MultiTabManagerImpl {
  static {
    __name(this, "__PRIVATE_MultiTabManagerImpl");
  }
  constructor() {
    this.kind = "PersistentMultipleTab";
  }
  toJSON() {
    return {
      kind: this.kind
    };
  }
  /**
   * @internal
   */
  _initialize(e2) {
    this._onlineComponentProvider = OnlineComponentProvider.provider, this._offlineComponentProvider = {
      build: /* @__PURE__ */ __name((t2) => new __PRIVATE_MultiTabOfflineComponentProvider(t2, null == e2 ? void 0 : e2.cacheSizeBytes), "build")
    };
  }
}
function persistentSingleTabManager(e2) {
  return new __PRIVATE_SingleTabManagerImpl(null == e2 ? void 0 : e2.forceOwnership);
}
__name(persistentSingleTabManager, "persistentSingleTabManager");
function persistentMultipleTabManager() {
  return new __PRIVATE_MultiTabManagerImpl();
}
__name(persistentMultipleTabManager, "persistentMultipleTabManager");
/**
 * @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 on = {
  maxAttempts: 5
};
/**
 * @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 WriteBatch {
  static {
    __name(this, "WriteBatch");
  }
  /** @hideconstructor */
  constructor(e2, t2) {
    this._firestore = e2, this._commitHandler = t2, this._mutations = [], this._committed = false, this._dataReader = __PRIVATE_newUserDataReader(e2);
  }
  set(e2, t2, n2) {
    this._verifyNotCommitted();
    const r2 = __PRIVATE_validateReference(e2, this._firestore), i2 = __PRIVATE_applyFirestoreDataConverter(r2.converter, t2, n2), s2 = __PRIVATE_parseSetData(this._dataReader, "WriteBatch.set", r2._key, i2, null !== r2.converter, n2);
    return this._mutations.push(s2.toMutation(r2._key, Precondition.none())), this;
  }
  update(e2, t2, n2, ...r2) {
    this._verifyNotCommitted();
    const i2 = __PRIVATE_validateReference(e2, this._firestore);
    let s2;
    return s2 = "string" == typeof (t2 = getModularInstance(t2)) || t2 instanceof FieldPath ? __PRIVATE_parseUpdateVarargs(this._dataReader, "WriteBatch.update", i2._key, t2, n2, r2) : __PRIVATE_parseUpdateData(this._dataReader, "WriteBatch.update", i2._key, t2), this._mutations.push(s2.toMutation(i2._key, Precondition.exists(true))), this;
  }
  /**
   * Deletes the document referred to by the provided {@link DocumentReference}.
   *
   * @param documentRef - A reference to the document to be deleted.
   * @returns This `WriteBatch` instance. Used for chaining method calls.
   */
  delete(e2) {
    this._verifyNotCommitted();
    const t2 = __PRIVATE_validateReference(e2, this._firestore);
    return this._mutations = this._mutations.concat(new __PRIVATE_DeleteMutation(t2._key, Precondition.none())), this;
  }
  /**
   * Commits all of the writes in this write batch as a single atomic unit.
   *
   * The result of these writes will only be reflected in document reads that
   * occur after the returned promise resolves. If the client is offline, the
   * write fails. If you would like to see local modifications or buffer writes
   * until the client is online, use the full Firestore SDK.
   *
   * @returns A `Promise` resolved once all of the writes in the batch have been
   * successfully written to the backend as an atomic unit (note that it won't
   * resolve while you're offline).
   */
  commit() {
    return this._verifyNotCommitted(), this._committed = true, this._mutations.length > 0 ? this._commitHandler(this._mutations) : Promise.resolve();
  }
  _verifyNotCommitted() {
    if (this._committed) throw new FirestoreError(C.FAILED_PRECONDITION, "A write batch can no longer be used after commit() has been called.");
  }
}
function __PRIVATE_validateReference(e2, t2) {
  if ((e2 = getModularInstance(e2)).firestore !== t2) throw new FirestoreError(C.INVALID_ARGUMENT, "Provided document reference is from a different Firestore instance.");
  return e2;
}
__name(__PRIVATE_validateReference, "__PRIVATE_validateReference");
/**
 * @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 Transaction$1 {
  static {
    __name(this, "Transaction$1");
  }
  /** @hideconstructor */
  constructor(e2, t2) {
    this._firestore = e2, this._transaction = t2, this._dataReader = __PRIVATE_newUserDataReader(e2);
  }
  /**
   * Reads the document referenced by the provided {@link DocumentReference}.
   *
   * @param documentRef - A reference to the document to be read.
   * @returns A `DocumentSnapshot` with the read data.
   */
  get(e2) {
    const t2 = __PRIVATE_validateReference(e2, this._firestore), n2 = new __PRIVATE_LiteUserDataWriter(this._firestore);
    return this._transaction.lookup([t2._key]).then((e3) => {
      if (!e3 || 1 !== e3.length) return fail();
      const r2 = e3[0];
      if (r2.isFoundDocument()) return new DocumentSnapshot$1(this._firestore, n2, r2.key, r2, t2.converter);
      if (r2.isNoDocument()) return new DocumentSnapshot$1(this._firestore, n2, t2._key, null, t2.converter);
      throw fail();
    });
  }
  set(e2, t2, n2) {
    const r2 = __PRIVATE_validateReference(e2, this._firestore), i2 = __PRIVATE_applyFirestoreDataConverter(r2.converter, t2, n2), s2 = __PRIVATE_parseSetData(this._dataReader, "Transaction.set", r2._key, i2, null !== r2.converter, n2);
    return this._transaction.set(r2._key, s2), this;
  }
  update(e2, t2, n2, ...r2) {
    const i2 = __PRIVATE_validateReference(e2, this._firestore);
    let s2;
    return s2 = "string" == typeof (t2 = getModularInstance(t2)) || t2 instanceof FieldPath ? __PRIVATE_parseUpdateVarargs(this._dataReader, "Transaction.update", i2._key, t2, n2, r2) : __PRIVATE_parseUpdateData(this._dataReader, "Transaction.update", i2._key, t2), this._transaction.update(i2._key, s2), this;
  }
  /**
   * Deletes the document referred to by the provided {@link DocumentReference}.
   *
   * @param documentRef - A reference to the document to be deleted.
   * @returns This `Transaction` instance. Used for chaining method calls.
   */
  delete(e2) {
    const t2 = __PRIVATE_validateReference(e2, this._firestore);
    return this._transaction.delete(t2._key), this;
  }
}
/**
 * @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.
 */
let Transaction$3 = class Transaction2 extends Transaction$1 {
  static {
    __name(this, "Transaction");
  }
  // This class implements the same logic as the Transaction API in the Lite SDK
  // but is subclassed in order to return its own DocumentSnapshot types.
  /** @hideconstructor */
  constructor(e2, t2) {
    super(e2, t2), this._firestore = e2;
  }
  /**
   * Reads the document referenced by the provided {@link DocumentReference}.
   *
   * @param documentRef - A reference to the document to be read.
   * @returns A `DocumentSnapshot` with the read data.
   */
  get(e2) {
    const t2 = __PRIVATE_validateReference(e2, this._firestore), n2 = new __PRIVATE_ExpUserDataWriter(this._firestore);
    return super.get(e2).then((e3) => new DocumentSnapshot(this._firestore, n2, t2._key, e3._document, new SnapshotMetadata(
      /* hasPendingWrites= */
      false,
      /* fromCache= */
      false
    ), t2.converter));
  }
};
function runTransaction(e2, t2, n2) {
  e2 = __PRIVATE_cast(e2, Firestore);
  const r2 = Object.assign(Object.assign({}, on), n2);
  !(/* @__PURE__ */ __name(function __PRIVATE_validateTransactionOptions(e3) {
    if (e3.maxAttempts < 1) throw new FirestoreError(C.INVALID_ARGUMENT, "Max attempts must be at least 1");
  }, "__PRIVATE_validateTransactionOptions"))(r2);
  return (/* @__PURE__ */ __name(function __PRIVATE_firestoreClientTransaction(e3, t3, n3) {
    const r3 = new __PRIVATE_Deferred();
    return e3.asyncQueue.enqueueAndForget(async () => {
      const i2 = await __PRIVATE_getDatastore(e3);
      new __PRIVATE_TransactionRunner(e3.asyncQueue, i2, n3, t3, r3).Iu();
    }), r3.promise;
  }, "__PRIVATE_firestoreClientTransaction"))(ensureFirestoreConfigured(e2), (n3) => t2(new Transaction$3(e2, n3)), r2);
}
__name(runTransaction, "runTransaction");
/**
 * @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.
 */
function deleteField() {
  return new __PRIVATE_DeleteFieldValueImpl("deleteField");
}
__name(deleteField, "deleteField");
function serverTimestamp() {
  return new __PRIVATE_ServerTimestampFieldValueImpl("serverTimestamp");
}
__name(serverTimestamp, "serverTimestamp");
function arrayUnion(...e2) {
  return new __PRIVATE_ArrayUnionFieldValueImpl("arrayUnion", e2);
}
__name(arrayUnion, "arrayUnion");
function arrayRemove(...e2) {
  return new __PRIVATE_ArrayRemoveFieldValueImpl("arrayRemove", e2);
}
__name(arrayRemove, "arrayRemove");
function increment(e2) {
  return new __PRIVATE_NumericIncrementFieldValueImpl("increment", e2);
}
__name(increment, "increment");
function vector(e2) {
  return new VectorValue(e2);
}
__name(vector, "vector");
/**
 * @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.
 */
function writeBatch(e2) {
  return ensureFirestoreConfigured(e2 = __PRIVATE_cast(e2, Firestore)), new WriteBatch(e2, (t2) => executeWrite(e2, t2));
}
__name(writeBatch, "writeBatch");
/**
 * @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 setIndexConfiguration(e2, t2) {
  const n2 = ensureFirestoreConfigured(e2 = __PRIVATE_cast(e2, Firestore));
  if (!n2._uninitializedComponentsProvider || "memory" === n2._uninitializedComponentsProvider._offline.kind)
    return __PRIVATE_logWarn("Cannot enable indexes when persistence is disabled"), Promise.resolve();
  const r2 = (/* @__PURE__ */ __name(function __PRIVATE_parseIndexes(e3) {
    const t3 = "string" == typeof e3 ? (/* @__PURE__ */ __name(function __PRIVATE_tryParseJson(e4) {
      try {
        return JSON.parse(e4);
      } catch (e5) {
        throw new FirestoreError(C.INVALID_ARGUMENT, "Failed to parse JSON: " + (null == e5 ? void 0 : e5.message));
      }
    }, "__PRIVATE_tryParseJson"))(e3) : e3, n3 = [];
    if (Array.isArray(t3.indexes)) for (const e4 of t3.indexes) {
      const t4 = __PRIVATE_tryGetString(e4, "collectionGroup"), r3 = [];
      if (Array.isArray(e4.fields)) for (const t5 of e4.fields) {
        const e5 = __PRIVATE_fieldPathFromDotSeparatedString("setIndexConfiguration", __PRIVATE_tryGetString(t5, "fieldPath"));
        "CONTAINS" === t5.arrayConfig ? r3.push(new IndexSegment(
          e5,
          2
          /* IndexKind.CONTAINS */
        )) : "ASCENDING" === t5.order ? r3.push(new IndexSegment(
          e5,
          0
          /* IndexKind.ASCENDING */
        )) : "DESCENDING" === t5.order && r3.push(new IndexSegment(
          e5,
          1
          /* IndexKind.DESCENDING */
        ));
      }
      n3.push(new FieldIndex(FieldIndex.UNKNOWN_ID, t4, r3, IndexState.empty()));
    }
    return n3;
  }, "__PRIVATE_parseIndexes"))(t2);
  return __PRIVATE_firestoreClientSetIndexConfiguration(n2, r2);
}
__name(setIndexConfiguration, "setIndexConfiguration");
function __PRIVATE_tryGetString(e2, t2) {
  if ("string" != typeof e2[t2]) throw new FirestoreError(C.INVALID_ARGUMENT, "Missing string value for: " + t2);
  return e2[t2];
}
__name(__PRIVATE_tryGetString, "__PRIVATE_tryGetString");
/**
 * @license
 * Copyright 2023 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 PersistentCacheIndexManager {
  static {
    __name(this, "PersistentCacheIndexManager");
  }
  /** @hideconstructor */
  constructor(e2) {
    this._firestore = e2, /** A type string to uniquely identify instances of this class. */
    this.type = "PersistentCacheIndexManager";
  }
}
function getPersistentCacheIndexManager(e2) {
  var t2;
  e2 = __PRIVATE_cast(e2, Firestore);
  const n2 = _n.get(e2);
  if (n2) return n2;
  if ("persistent" !== (null === (t2 = ensureFirestoreConfigured(e2)._uninitializedComponentsProvider) || void 0 === t2 ? void 0 : t2._offline.kind)) return null;
  const r2 = new PersistentCacheIndexManager(e2);
  return _n.set(e2, r2), r2;
}
__name(getPersistentCacheIndexManager, "getPersistentCacheIndexManager");
function enablePersistentCacheIndexAutoCreation(e2) {
  __PRIVATE_setPersistentCacheIndexAutoCreationEnabled(e2, true);
}
__name(enablePersistentCacheIndexAutoCreation, "enablePersistentCacheIndexAutoCreation");
function disablePersistentCacheIndexAutoCreation(e2) {
  __PRIVATE_setPersistentCacheIndexAutoCreationEnabled(e2, false);
}
__name(disablePersistentCacheIndexAutoCreation, "disablePersistentCacheIndexAutoCreation");
function deleteAllPersistentCacheIndexes(e2) {
  __PRIVATE_firestoreClientDeleteAllFieldIndexes(ensureFirestoreConfigured(e2._firestore)).then((e3) => __PRIVATE_logDebug("deleting all persistent cache indexes succeeded")).catch((e3) => __PRIVATE_logWarn("deleting all persistent cache indexes failed", e3));
}
__name(deleteAllPersistentCacheIndexes, "deleteAllPersistentCacheIndexes");
function __PRIVATE_setPersistentCacheIndexAutoCreationEnabled(e2, t2) {
  __PRIVATE_firestoreClientSetPersistentCacheIndexAutoCreationEnabled(ensureFirestoreConfigured(e2._firestore), t2).then((e3) => __PRIVATE_logDebug(`setting persistent cache index auto creation isEnabled=${t2} succeeded`)).catch((e3) => __PRIVATE_logWarn(`setting persistent cache index auto creation isEnabled=${t2} failed`, e3));
}
__name(__PRIVATE_setPersistentCacheIndexAutoCreationEnabled, "__PRIVATE_setPersistentCacheIndexAutoCreationEnabled");
const _n = /* @__PURE__ */ new WeakMap();
/**
 * @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 _internalQueryToProtoQueryTarget(e2) {
  var t2;
  const n2 = null === (t2 = ensureFirestoreConfigured(__PRIVATE_cast(e2.firestore, Firestore))._onlineComponents) || void 0 === t2 ? void 0 : t2.datastore.serializer;
  return void 0 === n2 ? null : __PRIVATE_toQueryTarget(n2, __PRIVATE_queryToTarget(e2._query)).ht;
}
__name(_internalQueryToProtoQueryTarget, "_internalQueryToProtoQueryTarget");
function _internalAggregationQueryToProtoRunAggregationQueryRequest(e2, t2) {
  var n2;
  const r2 = __PRIVATE_mapToArray(t2, (e3, t3) => new __PRIVATE_AggregateImpl(t3, e3.aggregateType, e3._internalFieldPath)), i2 = null === (n2 = ensureFirestoreConfigured(__PRIVATE_cast(e2.firestore, Firestore))._onlineComponents) || void 0 === n2 ? void 0 : n2.datastore.serializer;
  return void 0 === i2 ? null : __PRIVATE_toRunAggregationQueryRequest(
    i2,
    __PRIVATE_queryToAggregateTarget(e2._query),
    r2,
    /* skipAliasing= */
    true
  ).request;
}
__name(_internalAggregationQueryToProtoRunAggregationQueryRequest, "_internalAggregationQueryToProtoRunAggregationQueryRequest");
/**
 * @license
 * Copyright 2023 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 TestingHooks {
  static {
    __name(this, "TestingHooks");
  }
  constructor() {
    throw new Error("instances of this class should not be created");
  }
  /**
   * Registers a callback to be notified when an existence filter mismatch
   * occurs in the Watch listen stream.
   *
   * The relative order in which callbacks are notified is unspecified; do not
   * rely on any particular ordering. If a given callback is registered multiple
   * times then it will be notified multiple times, once per registration.
   *
   * @param callback the callback to invoke upon existence filter mismatch.
   *
   * @return a function that, when called, unregisters the given callback; only
   * the first invocation of the returned function does anything; all subsequent
   * invocations do nothing.
   */
  static onExistenceFilterMismatch(e2) {
    return __PRIVATE_TestingHooksSpiImpl.instance.onExistenceFilterMismatch(e2);
  }
}
class __PRIVATE_TestingHooksSpiImpl {
  static {
    __name(this, "__PRIVATE_TestingHooksSpiImpl");
  }
  constructor() {
    this.Yu = /* @__PURE__ */ new Map();
  }
  static get instance() {
    return an || (an = new __PRIVATE_TestingHooksSpiImpl(), (/* @__PURE__ */ __name(function __PRIVATE_setTestingHooksSpi(e2) {
      if (At) throw new Error("a TestingHooksSpi instance is already set");
      At = e2;
    }, "__PRIVATE_setTestingHooksSpi"))(an)), an;
  }
  rt(e2) {
    this.Yu.forEach((t2) => t2(e2));
  }
  onExistenceFilterMismatch(e2) {
    const t2 = Symbol(), n2 = this.Yu;
    return n2.set(t2, e2), () => n2.delete(t2);
  }
}
let an = null;
!(/* @__PURE__ */ __name(function __PRIVATE_registerFirestore(e2, t2 = true) {
  !(/* @__PURE__ */ __name(function __PRIVATE_setSDKVersion(e3) {
    D = e3;
  }, "__PRIVATE_setSDKVersion"))(SDK_VERSION$1), _registerComponent(new Component("firestore", (e3, { instanceIdentifier: n2, options: r2 }) => {
    const i2 = e3.getProvider("app").getImmediate(), s2 = new Firestore(new __PRIVATE_FirebaseAuthCredentialsProvider(e3.getProvider("auth-internal")), new __PRIVATE_FirebaseAppCheckTokenProvider(i2, e3.getProvider("app-check-internal")), (/* @__PURE__ */ __name(function __PRIVATE_databaseIdFromApp(e4, t3) {
      if (!Object.prototype.hasOwnProperty.apply(e4.options, ["projectId"])) throw new FirestoreError(C.INVALID_ARGUMENT, '"projectId" not provided in firebase.initializeApp.');
      return new DatabaseId(e4.options.projectId, t3);
    }, "__PRIVATE_databaseIdFromApp"))(i2, n2), i2);
    return r2 = Object.assign({
      useFetchStreams: t2
    }, r2), s2._setSettings(r2), s2;
  }, "PUBLIC").setMultipleInstances(true)), registerVersion(S, b, e2), // BUILD_TARGET will be replaced by values like esm2017, cjs2017, etc during the compilation
  registerVersion(S, b, "esm2017");
}, "__PRIVATE_registerFirestore"))();
/**
 * @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 DEFAULT_HOST = "firebasestorage.googleapis.com";
const CONFIG_STORAGE_BUCKET_KEY = "storageBucket";
const DEFAULT_MAX_OPERATION_RETRY_TIME = 2 * 60 * 1e3;
const DEFAULT_MAX_UPLOAD_RETRY_TIME = 10 * 60 * 1e3;
const DEFAULT_MIN_SLEEP_TIME_MILLIS = 1e3;
/**
 * @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 StorageError extends FirebaseError {
  static {
    __name(this, "StorageError");
  }
  /**
   * @param code - A `StorageErrorCode` string to be prefixed with 'storage/' and
   *  added to the end of the message.
   * @param message  - Error message.
   * @param status_ - Corresponding HTTP Status Code
   */
  constructor(code2, message, status_ = 0) {
    super(prependCode(code2), `Firebase Storage: ${message} (${prependCode(code2)})`);
    this.status_ = status_;
    this.customData = { serverResponse: null };
    this._baseMessage = this.message;
    Object.setPrototypeOf(this, StorageError.prototype);
  }
  get status() {
    return this.status_;
  }
  set status(status) {
    this.status_ = status;
  }
  /**
   * Compares a `StorageErrorCode` against this error's code, filtering out the prefix.
   */
  _codeEquals(code2) {
    return prependCode(code2) === this.code;
  }
  /**
   * Optional response message that was added by the server.
   */
  get serverResponse() {
    return this.customData.serverResponse;
  }
  set serverResponse(serverResponse) {
    this.customData.serverResponse = serverResponse;
    if (this.customData.serverResponse) {
      this.message = `${this._baseMessage}
${this.customData.serverResponse}`;
    } else {
      this.message = this._baseMessage;
    }
  }
}
var StorageErrorCode;
(function(StorageErrorCode2) {
  StorageErrorCode2["UNKNOWN"] = "unknown";
  StorageErrorCode2["OBJECT_NOT_FOUND"] = "object-not-found";
  StorageErrorCode2["BUCKET_NOT_FOUND"] = "bucket-not-found";
  StorageErrorCode2["PROJECT_NOT_FOUND"] = "project-not-found";
  StorageErrorCode2["QUOTA_EXCEEDED"] = "quota-exceeded";
  StorageErrorCode2["UNAUTHENTICATED"] = "unauthenticated";
  StorageErrorCode2["UNAUTHORIZED"] = "unauthorized";
  StorageErrorCode2["UNAUTHORIZED_APP"] = "unauthorized-app";
  StorageErrorCode2["RETRY_LIMIT_EXCEEDED"] = "retry-limit-exceeded";
  StorageErrorCode2["INVALID_CHECKSUM"] = "invalid-checksum";
  StorageErrorCode2["CANCELED"] = "canceled";
  StorageErrorCode2["INVALID_EVENT_NAME"] = "invalid-event-name";
  StorageErrorCode2["INVALID_URL"] = "invalid-url";
  StorageErrorCode2["INVALID_DEFAULT_BUCKET"] = "invalid-default-bucket";
  StorageErrorCode2["NO_DEFAULT_BUCKET"] = "no-default-bucket";
  StorageErrorCode2["CANNOT_SLICE_BLOB"] = "cannot-slice-blob";
  StorageErrorCode2["SERVER_FILE_WRONG_SIZE"] = "server-file-wrong-size";
  StorageErrorCode2["NO_DOWNLOAD_URL"] = "no-download-url";
  StorageErrorCode2["INVALID_ARGUMENT"] = "invalid-argument";
  StorageErrorCode2["INVALID_ARGUMENT_COUNT"] = "invalid-argument-count";
  StorageErrorCode2["APP_DELETED"] = "app-deleted";
  StorageErrorCode2["INVALID_ROOT_OPERATION"] = "invalid-root-operation";
  StorageErrorCode2["INVALID_FORMAT"] = "invalid-format";
  StorageErrorCode2["INTERNAL_ERROR"] = "internal-error";
  StorageErrorCode2["UNSUPPORTED_ENVIRONMENT"] = "unsupported-environment";
})(StorageErrorCode || (StorageErrorCode = {}));
function prependCode(code2) {
  return "storage/" + code2;
}
__name(prependCode, "prependCode");
function unknown() {
  const message = "An unknown error occurred, please check the error payload for server response.";
  return new StorageError(StorageErrorCode.UNKNOWN, message);
}
__name(unknown, "unknown");
function objectNotFound(path) {
  return new StorageError(StorageErrorCode.OBJECT_NOT_FOUND, "Object '" + path + "' does not exist.");
}
__name(objectNotFound, "objectNotFound");
function quotaExceeded(bucket) {
  return new StorageError(StorageErrorCode.QUOTA_EXCEEDED, "Quota for bucket '" + bucket + "' exceeded, please view quota on https://firebase.google.com/pricing/.");
}
__name(quotaExceeded, "quotaExceeded");
function unauthenticated() {
  const message = "User is not authenticated, please authenticate using Firebase Authentication and try again.";
  return new StorageError(StorageErrorCode.UNAUTHENTICATED, message);
}
__name(unauthenticated, "unauthenticated");
function unauthorizedApp() {
  return new StorageError(StorageErrorCode.UNAUTHORIZED_APP, "This app does not have permission to access Firebase Storage on this project.");
}
__name(unauthorizedApp, "unauthorizedApp");
function unauthorized(path) {
  return new StorageError(StorageErrorCode.UNAUTHORIZED, "User does not have permission to access '" + path + "'.");
}
__name(unauthorized, "unauthorized");
function retryLimitExceeded() {
  return new StorageError(StorageErrorCode.RETRY_LIMIT_EXCEEDED, "Max retry time for operation exceeded, please try again.");
}
__name(retryLimitExceeded, "retryLimitExceeded");
function canceled() {
  return new StorageError(StorageErrorCode.CANCELED, "User canceled the upload/download.");
}
__name(canceled, "canceled");
function invalidUrl(url) {
  return new StorageError(StorageErrorCode.INVALID_URL, "Invalid URL '" + url + "'.");
}
__name(invalidUrl, "invalidUrl");
function invalidDefaultBucket(bucket) {
  return new StorageError(StorageErrorCode.INVALID_DEFAULT_BUCKET, "Invalid default bucket '" + bucket + "'.");
}
__name(invalidDefaultBucket, "invalidDefaultBucket");
function noDefaultBucket() {
  return new StorageError(StorageErrorCode.NO_DEFAULT_BUCKET, "No default bucket found. Did you set the '" + CONFIG_STORAGE_BUCKET_KEY + "' property when initializing the app?");
}
__name(noDefaultBucket, "noDefaultBucket");
function cannotSliceBlob() {
  return new StorageError(StorageErrorCode.CANNOT_SLICE_BLOB, "Cannot slice blob for upload. Please retry the upload.");
}
__name(cannotSliceBlob, "cannotSliceBlob");
function serverFileWrongSize() {
  return new StorageError(StorageErrorCode.SERVER_FILE_WRONG_SIZE, "Server recorded incorrect upload file size, please retry the upload.");
}
__name(serverFileWrongSize, "serverFileWrongSize");
function noDownloadURL() {
  return new StorageError(StorageErrorCode.NO_DOWNLOAD_URL, "The given file does not have any download URLs.");
}
__name(noDownloadURL, "noDownloadURL");
function missingPolyFill(polyFill) {
  return new StorageError(StorageErrorCode.UNSUPPORTED_ENVIRONMENT, `${polyFill} is missing. Make sure to install the required polyfills. See https://firebase.google.com/docs/web/environments-js-sdk#polyfills for more information.`);
}
__name(missingPolyFill, "missingPolyFill");
function invalidArgument(message) {
  return new StorageError(StorageErrorCode.INVALID_ARGUMENT, message);
}
__name(invalidArgument, "invalidArgument");
function appDeleted() {
  return new StorageError(StorageErrorCode.APP_DELETED, "The Firebase app was deleted.");
}
__name(appDeleted, "appDeleted");
function invalidRootOperation(name2) {
  return new StorageError(StorageErrorCode.INVALID_ROOT_OPERATION, "The operation '" + name2 + "' cannot be performed on a root reference, create a non-root reference using child, such as .child('file.png').");
}
__name(invalidRootOperation, "invalidRootOperation");
function invalidFormat(format2, message) {
  return new StorageError(StorageErrorCode.INVALID_FORMAT, "String does not match format '" + format2 + "': " + message);
}
__name(invalidFormat, "invalidFormat");
function internalError(message) {
  throw new StorageError(StorageErrorCode.INTERNAL_ERROR, "Internal error: " + message);
}
__name(internalError, "internalError");
/**
 * @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 Location {
  static {
    __name(this, "Location");
  }
  constructor(bucket, path) {
    this.bucket = bucket;
    this.path_ = path;
  }
  get path() {
    return this.path_;
  }
  get isRoot() {
    return this.path.length === 0;
  }
  fullServerUrl() {
    const encode2 = encodeURIComponent;
    return "/b/" + encode2(this.bucket) + "/o/" + encode2(this.path);
  }
  bucketOnlyServerUrl() {
    const encode2 = encodeURIComponent;
    return "/b/" + encode2(this.bucket) + "/o";
  }
  static makeFromBucketSpec(bucketString, host) {
    let bucketLocation;
    try {
      bucketLocation = Location.makeFromUrl(bucketString, host);
    } catch (e2) {
      return new Location(bucketString, "");
    }
    if (bucketLocation.path === "") {
      return bucketLocation;
    } else {
      throw invalidDefaultBucket(bucketString);
    }
  }
  static makeFromUrl(url, host) {
    let location2 = null;
    const bucketDomain = "([A-Za-z0-9.\\-_]+)";
    function gsModify(loc) {
      if (loc.path.charAt(loc.path.length - 1) === "/") {
        loc.path_ = loc.path_.slice(0, -1);
      }
    }
    __name(gsModify, "gsModify");
    const gsPath = "(/(.*))?$";
    const gsRegex = new RegExp("^gs://" + bucketDomain + gsPath, "i");
    const gsIndices = { bucket: 1, path: 3 };
    function httpModify(loc) {
      loc.path_ = decodeURIComponent(loc.path);
    }
    __name(httpModify, "httpModify");
    const version2 = "v[A-Za-z0-9_]+";
    const firebaseStorageHost = host.replace(/[.]/g, "\\.");
    const firebaseStoragePath = "(/([^?#]*).*)?$";
    const firebaseStorageRegExp = new RegExp(`^https?://${firebaseStorageHost}/${version2}/b/${bucketDomain}/o${firebaseStoragePath}`, "i");
    const firebaseStorageIndices = { bucket: 1, path: 3 };
    const cloudStorageHost = host === DEFAULT_HOST ? "(?:storage.googleapis.com|storage.cloud.google.com)" : host;
    const cloudStoragePath = "([^?#]*)";
    const cloudStorageRegExp = new RegExp(`^https?://${cloudStorageHost}/${bucketDomain}/${cloudStoragePath}`, "i");
    const cloudStorageIndices = { bucket: 1, path: 2 };
    const groups = [
      { regex: gsRegex, indices: gsIndices, postModify: gsModify },
      {
        regex: firebaseStorageRegExp,
        indices: firebaseStorageIndices,
        postModify: httpModify
      },
      {
        regex: cloudStorageRegExp,
        indices: cloudStorageIndices,
        postModify: httpModify
      }
    ];
    for (let i2 = 0; i2 < groups.length; i2++) {
      const group = groups[i2];
      const captures = group.regex.exec(url);
      if (captures) {
        const bucketValue = captures[group.indices.bucket];
        let pathValue = captures[group.indices.path];
        if (!pathValue) {
          pathValue = "";
        }
        location2 = new Location(bucketValue, pathValue);
        group.postModify(location2);
        break;
      }
    }
    if (location2 == null) {
      throw invalidUrl(url);
    }
    return location2;
  }
}
class FailRequest {
  static {
    __name(this, "FailRequest");
  }
  constructor(error2) {
    this.promise_ = Promise.reject(error2);
  }
  /** @inheritDoc */
  getPromise() {
    return this.promise_;
  }
  /** @inheritDoc */
  cancel(_appDelete = 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.
 */
function start$1(doRequest, backoffCompleteCb, timeout) {
  let waitSeconds = 1;
  let retryTimeoutId = null;
  let globalTimeoutId = null;
  let hitTimeout = false;
  let cancelState = 0;
  function canceled2() {
    return cancelState === 2;
  }
  __name(canceled2, "canceled");
  let triggeredCallback = false;
  function triggerCallback(...args) {
    if (!triggeredCallback) {
      triggeredCallback = true;
      backoffCompleteCb.apply(null, args);
    }
  }
  __name(triggerCallback, "triggerCallback");
  function callWithDelay(millis) {
    retryTimeoutId = setTimeout(() => {
      retryTimeoutId = null;
      doRequest(responseHandler, canceled2());
    }, millis);
  }
  __name(callWithDelay, "callWithDelay");
  function clearGlobalTimeout() {
    if (globalTimeoutId) {
      clearTimeout(globalTimeoutId);
    }
  }
  __name(clearGlobalTimeout, "clearGlobalTimeout");
  function responseHandler(success, ...args) {
    if (triggeredCallback) {
      clearGlobalTimeout();
      return;
    }
    if (success) {
      clearGlobalTimeout();
      triggerCallback.call(null, success, ...args);
      return;
    }
    const mustStop = canceled2() || hitTimeout;
    if (mustStop) {
      clearGlobalTimeout();
      triggerCallback.call(null, success, ...args);
      return;
    }
    if (waitSeconds < 64) {
      waitSeconds *= 2;
    }
    let waitMillis;
    if (cancelState === 1) {
      cancelState = 2;
      waitMillis = 0;
    } else {
      waitMillis = (waitSeconds + Math.random()) * 1e3;
    }
    callWithDelay(waitMillis);
  }
  __name(responseHandler, "responseHandler");
  let stopped = false;
  function stop2(wasTimeout) {
    if (stopped) {
      return;
    }
    stopped = true;
    clearGlobalTimeout();
    if (triggeredCallback) {
      return;
    }
    if (retryTimeoutId !== null) {
      if (!wasTimeout) {
        cancelState = 2;
      }
      clearTimeout(retryTimeoutId);
      callWithDelay(0);
    } else {
      if (!wasTimeout) {
        cancelState = 1;
      }
    }
  }
  __name(stop2, "stop");
  callWithDelay(0);
  globalTimeoutId = setTimeout(() => {
    hitTimeout = true;
    stop2(true);
  }, timeout);
  return stop2;
}
__name(start$1, "start$1");
function stop(id2) {
  id2(false);
}
__name(stop, "stop");
/**
 * @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 isJustDef(p2) {
  return p2 !== void 0;
}
__name(isJustDef, "isJustDef");
function isFunction$a(p2) {
  return typeof p2 === "function";
}
__name(isFunction$a, "isFunction$a");
function isNonArrayObject(p2) {
  return typeof p2 === "object" && !Array.isArray(p2);
}
__name(isNonArrayObject, "isNonArrayObject");
function isString$7(p2) {
  return typeof p2 === "string" || p2 instanceof String;
}
__name(isString$7, "isString$7");
function isNativeBlob(p2) {
  return isNativeBlobDefined() && p2 instanceof Blob;
}
__name(isNativeBlob, "isNativeBlob");
function isNativeBlobDefined() {
  return typeof Blob !== "undefined";
}
__name(isNativeBlobDefined, "isNativeBlobDefined");
function validateNumber(argument, minValue, maxValue, value) {
  if (value < minValue) {
    throw invalidArgument(`Invalid value for '${argument}'. Expected ${minValue} or greater.`);
  }
  if (value > maxValue) {
    throw invalidArgument(`Invalid value for '${argument}'. Expected ${maxValue} or less.`);
  }
}
__name(validateNumber, "validateNumber");
/**
 * @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 makeUrl(urlPart, host, protocol) {
  let origin2 = host;
  if (protocol == null) {
    origin2 = `https://${host}`;
  }
  return `${protocol}://${origin2}/v0${urlPart}`;
}
__name(makeUrl, "makeUrl");
function makeQueryString(params) {
  const encode2 = encodeURIComponent;
  let queryPart = "?";
  for (const key in params) {
    if (params.hasOwnProperty(key)) {
      const nextPart = encode2(key) + "=" + encode2(params[key]);
      queryPart = queryPart + nextPart + "&";
    }
  }
  queryPart = queryPart.slice(0, -1);
  return queryPart;
}
__name(makeQueryString, "makeQueryString");
var ErrorCode;
(function(ErrorCode2) {
  ErrorCode2[ErrorCode2["NO_ERROR"] = 0] = "NO_ERROR";
  ErrorCode2[ErrorCode2["NETWORK_ERROR"] = 1] = "NETWORK_ERROR";
  ErrorCode2[ErrorCode2["ABORT"] = 2] = "ABORT";
})(ErrorCode || (ErrorCode = {}));
/**
 * @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 isRetryStatusCode(status, additionalRetryCodes) {
  const isFiveHundredCode = status >= 500 && status < 600;
  const extraRetryCodes = [
    // Request Timeout: web server didn't receive full request in time.
    408,
    // Too Many Requests: you're getting rate-limited, basically.
    429
  ];
  const isExtraRetryCode = extraRetryCodes.indexOf(status) !== -1;
  const isAdditionalRetryCode = additionalRetryCodes.indexOf(status) !== -1;
  return isFiveHundredCode || isExtraRetryCode || isAdditionalRetryCode;
}
__name(isRetryStatusCode, "isRetryStatusCode");
/**
 * @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 NetworkRequest {
  static {
    __name(this, "NetworkRequest");
  }
  constructor(url_, method_, headers_, body_, successCodes_, additionalRetryCodes_, callback_, errorCallback_, timeout_, progressCallback_, connectionFactory_, retry = true) {
    this.url_ = url_;
    this.method_ = method_;
    this.headers_ = headers_;
    this.body_ = body_;
    this.successCodes_ = successCodes_;
    this.additionalRetryCodes_ = additionalRetryCodes_;
    this.callback_ = callback_;
    this.errorCallback_ = errorCallback_;
    this.timeout_ = timeout_;
    this.progressCallback_ = progressCallback_;
    this.connectionFactory_ = connectionFactory_;
    this.retry = retry;
    this.pendingConnection_ = null;
    this.backoffId_ = null;
    this.canceled_ = false;
    this.appDelete_ = false;
    this.promise_ = new Promise((resolve2, reject) => {
      this.resolve_ = resolve2;
      this.reject_ = reject;
      this.start_();
    });
  }
  /**
   * Actually starts the retry loop.
   */
  start_() {
    const doTheRequest = /* @__PURE__ */ __name((backoffCallback, canceled2) => {
      if (canceled2) {
        backoffCallback(false, new RequestEndStatus(false, null, true));
        return;
      }
      const connection = this.connectionFactory_();
      this.pendingConnection_ = connection;
      const progressListener = /* @__PURE__ */ __name((progressEvent) => {
        const loaded = progressEvent.loaded;
        const total = progressEvent.lengthComputable ? progressEvent.total : -1;
        if (this.progressCallback_ !== null) {
          this.progressCallback_(loaded, total);
        }
      }, "progressListener");
      if (this.progressCallback_ !== null) {
        connection.addUploadProgressListener(progressListener);
      }
      connection.send(this.url_, this.method_, this.body_, this.headers_).then(() => {
        if (this.progressCallback_ !== null) {
          connection.removeUploadProgressListener(progressListener);
        }
        this.pendingConnection_ = null;
        const hitServer = connection.getErrorCode() === ErrorCode.NO_ERROR;
        const status = connection.getStatus();
        if (!hitServer || isRetryStatusCode(status, this.additionalRetryCodes_) && this.retry) {
          const wasCanceled = connection.getErrorCode() === ErrorCode.ABORT;
          backoffCallback(false, new RequestEndStatus(false, null, wasCanceled));
          return;
        }
        const successCode = this.successCodes_.indexOf(status) !== -1;
        backoffCallback(true, new RequestEndStatus(successCode, connection));
      });
    }, "doTheRequest");
    const backoffDone = /* @__PURE__ */ __name((requestWentThrough, status) => {
      const resolve2 = this.resolve_;
      const reject = this.reject_;
      const connection = status.connection;
      if (status.wasSuccessCode) {
        try {
          const result = this.callback_(connection, connection.getResponse());
          if (isJustDef(result)) {
            resolve2(result);
          } else {
            resolve2();
          }
        } catch (e2) {
          reject(e2);
        }
      } else {
        if (connection !== null) {
          const err = unknown();
          err.serverResponse = connection.getErrorText();
          if (this.errorCallback_) {
            reject(this.errorCallback_(connection, err));
          } else {
            reject(err);
          }
        } else {
          if (status.canceled) {
            const err = this.appDelete_ ? appDeleted() : canceled();
            reject(err);
          } else {
            const err = retryLimitExceeded();
            reject(err);
          }
        }
      }
    }, "backoffDone");
    if (this.canceled_) {
      backoffDone(false, new RequestEndStatus(false, null, true));
    } else {
      this.backoffId_ = start$1(doTheRequest, backoffDone, this.timeout_);
    }
  }
  /** @inheritDoc */
  getPromise() {
    return this.promise_;
  }
  /** @inheritDoc */
  cancel(appDelete) {
    this.canceled_ = true;
    this.appDelete_ = appDelete || false;
    if (this.backoffId_ !== null) {
      stop(this.backoffId_);
    }
    if (this.pendingConnection_ !== null) {
      this.pendingConnection_.abort();
    }
  }
}
class RequestEndStatus {
  static {
    __name(this, "RequestEndStatus");
  }
  constructor(wasSuccessCode, connection, canceled2) {
    this.wasSuccessCode = wasSuccessCode;
    this.connection = connection;
    this.canceled = !!canceled2;
  }
}
function addAuthHeader_(headers, authToken) {
  if (authToken !== null && authToken.length > 0) {
    headers["Authorization"] = "Firebase " + authToken;
  }
}
__name(addAuthHeader_, "addAuthHeader_");
function addVersionHeader_(headers, firebaseVersion) {
  headers["X-Firebase-Storage-Version"] = "webjs/" + (firebaseVersion !== null && firebaseVersion !== void 0 ? firebaseVersion : "AppManager");
}
__name(addVersionHeader_, "addVersionHeader_");
function addGmpidHeader_(headers, appId) {
  if (appId) {
    headers["X-Firebase-GMPID"] = appId;
  }
}
__name(addGmpidHeader_, "addGmpidHeader_");
function addAppCheckHeader_(headers, appCheckToken) {
  if (appCheckToken !== null) {
    headers["X-Firebase-AppCheck"] = appCheckToken;
  }
}
__name(addAppCheckHeader_, "addAppCheckHeader_");
function makeRequest(requestInfo, appId, authToken, appCheckToken, requestFactory, firebaseVersion, retry = true) {
  const queryPart = makeQueryString(requestInfo.urlParams);
  const url = requestInfo.url + queryPart;
  const headers = Object.assign({}, requestInfo.headers);
  addGmpidHeader_(headers, appId);
  addAuthHeader_(headers, authToken);
  addVersionHeader_(headers, firebaseVersion);
  addAppCheckHeader_(headers, appCheckToken);
  return new NetworkRequest(url, requestInfo.method, headers, requestInfo.body, requestInfo.successCodes, requestInfo.additionalRetryCodes, requestInfo.handler, requestInfo.errorHandler, requestInfo.timeout, requestInfo.progressCallback, requestFactory, retry);
}
__name(makeRequest, "makeRequest");
/**
 * @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 getBlobBuilder() {
  if (typeof BlobBuilder !== "undefined") {
    return BlobBuilder;
  } else if (typeof WebKitBlobBuilder !== "undefined") {
    return WebKitBlobBuilder;
  } else {
    return void 0;
  }
}
__name(getBlobBuilder, "getBlobBuilder");
function getBlob$1(...args) {
  const BlobBuilder2 = getBlobBuilder();
  if (BlobBuilder2 !== void 0) {
    const bb = new BlobBuilder2();
    for (let i2 = 0; i2 < args.length; i2++) {
      bb.append(args[i2]);
    }
    return bb.getBlob();
  } else {
    if (isNativeBlobDefined()) {
      return new Blob(args);
    } else {
      throw new StorageError(StorageErrorCode.UNSUPPORTED_ENVIRONMENT, "This browser doesn't seem to support creating Blobs");
    }
  }
}
__name(getBlob$1, "getBlob$1");
function sliceBlob(blob, start2, end) {
  if (blob.webkitSlice) {
    return blob.webkitSlice(start2, end);
  } else if (blob.mozSlice) {
    return blob.mozSlice(start2, end);
  } else if (blob.slice) {
    return blob.slice(start2, end);
  }
  return null;
}
__name(sliceBlob, "sliceBlob");
/**
 * @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 decodeBase64(encoded) {
  if (typeof atob === "undefined") {
    throw missingPolyFill("base-64");
  }
  return atob(encoded);
}
__name(decodeBase64, "decodeBase64");
/**
 * @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 StringFormat = {
  /**
   * Indicates the string should be interpreted "raw", that is, as normal text.
   * The string will be interpreted as UTF-16, then uploaded as a UTF-8 byte
   * sequence.
   * Example: The string 'Hello! \\ud83d\\ude0a' becomes the byte sequence
   * 48 65 6c 6c 6f 21 20 f0 9f 98 8a
   */
  RAW: "raw",
  /**
   * Indicates the string should be interpreted as base64-encoded data.
   * Padding characters (trailing '='s) are optional.
   * Example: The string 'rWmO++E6t7/rlw==' becomes the byte sequence
   * ad 69 8e fb e1 3a b7 bf eb 97
   */
  BASE64: "base64",
  /**
   * Indicates the string should be interpreted as base64url-encoded data.
   * Padding characters (trailing '='s) are optional.
   * Example: The string 'rWmO--E6t7_rlw==' becomes the byte sequence
   * ad 69 8e fb e1 3a b7 bf eb 97
   */
  BASE64URL: "base64url",
  /**
   * Indicates the string is a data URL, such as one obtained from
   * canvas.toDataURL().
   * Example: the string 'data:application/octet-stream;base64,aaaa'
   * becomes the byte sequence
   * 69 a6 9a
   * (the content-type "application/octet-stream" is also applied, but can
   * be overridden in the metadata object).
   */
  DATA_URL: "data_url"
};
class StringData {
  static {
    __name(this, "StringData");
  }
  constructor(data, contentType) {
    this.data = data;
    this.contentType = contentType || null;
  }
}
function dataFromString(format2, stringData) {
  switch (format2) {
    case StringFormat.RAW:
      return new StringData(utf8Bytes_(stringData));
    case StringFormat.BASE64:
    case StringFormat.BASE64URL:
      return new StringData(base64Bytes_(format2, stringData));
    case StringFormat.DATA_URL:
      return new StringData(dataURLBytes_(stringData), dataURLContentType_(stringData));
  }
  throw unknown();
}
__name(dataFromString, "dataFromString");
function utf8Bytes_(value) {
  const b2 = [];
  for (let i2 = 0; i2 < value.length; i2++) {
    let c2 = value.charCodeAt(i2);
    if (c2 <= 127) {
      b2.push(c2);
    } else {
      if (c2 <= 2047) {
        b2.push(192 | c2 >> 6, 128 | c2 & 63);
      } else {
        if ((c2 & 64512) === 55296) {
          const valid = i2 < value.length - 1 && (value.charCodeAt(i2 + 1) & 64512) === 56320;
          if (!valid) {
            b2.push(239, 191, 189);
          } else {
            const hi = c2;
            const lo = value.charCodeAt(++i2);
            c2 = 65536 | (hi & 1023) << 10 | lo & 1023;
            b2.push(240 | c2 >> 18, 128 | c2 >> 12 & 63, 128 | c2 >> 6 & 63, 128 | c2 & 63);
          }
        } else {
          if ((c2 & 64512) === 56320) {
            b2.push(239, 191, 189);
          } else {
            b2.push(224 | c2 >> 12, 128 | c2 >> 6 & 63, 128 | c2 & 63);
          }
        }
      }
    }
  }
  return new Uint8Array(b2);
}
__name(utf8Bytes_, "utf8Bytes_");
function percentEncodedBytes_(value) {
  let decoded;
  try {
    decoded = decodeURIComponent(value);
  } catch (e2) {
    throw invalidFormat(StringFormat.DATA_URL, "Malformed data URL.");
  }
  return utf8Bytes_(decoded);
}
__name(percentEncodedBytes_, "percentEncodedBytes_");
function base64Bytes_(format2, value) {
  switch (format2) {
    case StringFormat.BASE64: {
      const hasMinus = value.indexOf("-") !== -1;
      const hasUnder = value.indexOf("_") !== -1;
      if (hasMinus || hasUnder) {
        const invalidChar = hasMinus ? "-" : "_";
        throw invalidFormat(format2, "Invalid character '" + invalidChar + "' found: is it base64url encoded?");
      }
      break;
    }
    case StringFormat.BASE64URL: {
      const hasPlus = value.indexOf("+") !== -1;
      const hasSlash = value.indexOf("/") !== -1;
      if (hasPlus || hasSlash) {
        const invalidChar = hasPlus ? "+" : "/";
        throw invalidFormat(format2, "Invalid character '" + invalidChar + "' found: is it base64 encoded?");
      }
      value = value.replace(/-/g, "+").replace(/_/g, "/");
      break;
    }
  }
  let bytes;
  try {
    bytes = decodeBase64(value);
  } catch (e2) {
    if (e2.message.includes("polyfill")) {
      throw e2;
    }
    throw invalidFormat(format2, "Invalid character found");
  }
  const array = new Uint8Array(bytes.length);
  for (let i2 = 0; i2 < bytes.length; i2++) {
    array[i2] = bytes.charCodeAt(i2);
  }
  return array;
}
__name(base64Bytes_, "base64Bytes_");
class DataURLParts {
  static {
    __name(this, "DataURLParts");
  }
  constructor(dataURL) {
    this.base64 = false;
    this.contentType = null;
    const matches2 = dataURL.match(/^data:([^,]+)?,/);
    if (matches2 === null) {
      throw invalidFormat(StringFormat.DATA_URL, "Must be formatted 'data:[<mediatype>][;base64],<data>");
    }
    const middle = matches2[1] || null;
    if (middle != null) {
      this.base64 = endsWith$1(middle, ";base64");
      this.contentType = this.base64 ? middle.substring(0, middle.length - ";base64".length) : middle;
    }
    this.rest = dataURL.substring(dataURL.indexOf(",") + 1);
  }
}
function dataURLBytes_(dataUrl) {
  const parts2 = new DataURLParts(dataUrl);
  if (parts2.base64) {
    return base64Bytes_(StringFormat.BASE64, parts2.rest);
  } else {
    return percentEncodedBytes_(parts2.rest);
  }
}
__name(dataURLBytes_, "dataURLBytes_");
function dataURLContentType_(dataUrl) {
  const parts2 = new DataURLParts(dataUrl);
  return parts2.contentType;
}
__name(dataURLContentType_, "dataURLContentType_");
function endsWith$1(s2, end) {
  const longEnough = s2.length >= end.length;
  if (!longEnough) {
    return false;
  }
  return s2.substring(s2.length - end.length) === end;
}
__name(endsWith$1, "endsWith$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.
 */
class FbsBlob {
  static {
    __name(this, "FbsBlob");
  }
  constructor(data, elideCopy) {
    let size = 0;
    let blobType = "";
    if (isNativeBlob(data)) {
      this.data_ = data;
      size = data.size;
      blobType = data.type;
    } else if (data instanceof ArrayBuffer) {
      if (elideCopy) {
        this.data_ = new Uint8Array(data);
      } else {
        this.data_ = new Uint8Array(data.byteLength);
        this.data_.set(new Uint8Array(data));
      }
      size = this.data_.length;
    } else if (data instanceof Uint8Array) {
      if (elideCopy) {
        this.data_ = data;
      } else {
        this.data_ = new Uint8Array(data.length);
        this.data_.set(data);
      }
      size = data.length;
    }
    this.size_ = size;
    this.type_ = blobType;
  }
  size() {
    return this.size_;
  }
  type() {
    return this.type_;
  }
  slice(startByte, endByte) {
    if (isNativeBlob(this.data_)) {
      const realBlob = this.data_;
      const sliced = sliceBlob(realBlob, startByte, endByte);
      if (sliced === null) {
        return null;
      }
      return new FbsBlob(sliced);
    } else {
      const slice2 = new Uint8Array(this.data_.buffer, startByte, endByte - startByte);
      return new FbsBlob(slice2, true);
    }
  }
  static getBlob(...args) {
    if (isNativeBlobDefined()) {
      const blobby = args.map((val) => {
        if (val instanceof FbsBlob) {
          return val.data_;
        } else {
          return val;
        }
      });
      return new FbsBlob(getBlob$1.apply(null, blobby));
    } else {
      const uint8Arrays = args.map((val) => {
        if (isString$7(val)) {
          return dataFromString(StringFormat.RAW, val).data;
        } else {
          return val.data_;
        }
      });
      let finalLength = 0;
      uint8Arrays.forEach((array) => {
        finalLength += array.byteLength;
      });
      const merged = new Uint8Array(finalLength);
      let index2 = 0;
      uint8Arrays.forEach((array) => {
        for (let i2 = 0; i2 < array.length; i2++) {
          merged[index2++] = array[i2];
        }
      });
      return new FbsBlob(merged, true);
    }
  }
  uploadData() {
    return this.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.
 */
function jsonObjectOrNull(s2) {
  let obj;
  try {
    obj = JSON.parse(s2);
  } catch (e2) {
    return null;
  }
  if (isNonArrayObject(obj)) {
    return obj;
  } else {
    return null;
  }
}
__name(jsonObjectOrNull, "jsonObjectOrNull");
/**
 * @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 parent(path) {
  if (path.length === 0) {
    return null;
  }
  const index2 = path.lastIndexOf("/");
  if (index2 === -1) {
    return "";
  }
  const newPath = path.slice(0, index2);
  return newPath;
}
__name(parent, "parent");
function child(path, childPath) {
  const canonicalChildPath = childPath.split("/").filter((component) => component.length > 0).join("/");
  if (path.length === 0) {
    return canonicalChildPath;
  } else {
    return path + "/" + canonicalChildPath;
  }
}
__name(child, "child");
function lastComponent(path) {
  const index2 = path.lastIndexOf("/", path.length - 2);
  if (index2 === -1) {
    return path;
  } else {
    return path.slice(index2 + 1);
  }
}
__name(lastComponent, "lastComponent");
/**
 * @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 noXform_(metadata, value) {
  return value;
}
__name(noXform_, "noXform_");
let Mapping$1 = class Mapping2 {
  static {
    __name(this, "Mapping");
  }
  constructor(server, local, writable, xform) {
    this.server = server;
    this.local = local || server;
    this.writable = !!writable;
    this.xform = xform || noXform_;
  }
};
let mappings_ = null;
function xformPath(fullPath) {
  if (!isString$7(fullPath) || fullPath.length < 2) {
    return fullPath;
  } else {
    return lastComponent(fullPath);
  }
}
__name(xformPath, "xformPath");
function getMappings() {
  if (mappings_) {
    return mappings_;
  }
  const mappings = [];
  mappings.push(new Mapping$1("bucket"));
  mappings.push(new Mapping$1("generation"));
  mappings.push(new Mapping$1("metageneration"));
  mappings.push(new Mapping$1("name", "fullPath", true));
  function mappingsXformPath(_metadata, fullPath) {
    return xformPath(fullPath);
  }
  __name(mappingsXformPath, "mappingsXformPath");
  const nameMapping = new Mapping$1("name");
  nameMapping.xform = mappingsXformPath;
  mappings.push(nameMapping);
  function xformSize(_metadata, size) {
    if (size !== void 0) {
      return Number(size);
    } else {
      return size;
    }
  }
  __name(xformSize, "xformSize");
  const sizeMapping = new Mapping$1("size");
  sizeMapping.xform = xformSize;
  mappings.push(sizeMapping);
  mappings.push(new Mapping$1("timeCreated"));
  mappings.push(new Mapping$1("updated"));
  mappings.push(new Mapping$1("md5Hash", null, true));
  mappings.push(new Mapping$1("cacheControl", null, true));
  mappings.push(new Mapping$1("contentDisposition", null, true));
  mappings.push(new Mapping$1("contentEncoding", null, true));
  mappings.push(new Mapping$1("contentLanguage", null, true));
  mappings.push(new Mapping$1("contentType", null, true));
  mappings.push(new Mapping$1("metadata", "customMetadata", true));
  mappings_ = mappings;
  return mappings_;
}
__name(getMappings, "getMappings");
function addRef(metadata, service) {
  function generateRef() {
    const bucket = metadata["bucket"];
    const path = metadata["fullPath"];
    const loc = new Location(bucket, path);
    return service._makeStorageReference(loc);
  }
  __name(generateRef, "generateRef");
  Object.defineProperty(metadata, "ref", { get: generateRef });
}
__name(addRef, "addRef");
function fromResource(service, resource, mappings) {
  const metadata = {};
  metadata["type"] = "file";
  const len = mappings.length;
  for (let i2 = 0; i2 < len; i2++) {
    const mapping = mappings[i2];
    metadata[mapping.local] = mapping.xform(metadata, resource[mapping.server]);
  }
  addRef(metadata, service);
  return metadata;
}
__name(fromResource, "fromResource");
function fromResourceString(service, resourceString, mappings) {
  const obj = jsonObjectOrNull(resourceString);
  if (obj === null) {
    return null;
  }
  const resource = obj;
  return fromResource(service, resource, mappings);
}
__name(fromResourceString, "fromResourceString");
function downloadUrlFromResourceString(metadata, resourceString, host, protocol) {
  const obj = jsonObjectOrNull(resourceString);
  if (obj === null) {
    return null;
  }
  if (!isString$7(obj["downloadTokens"])) {
    return null;
  }
  const tokens = obj["downloadTokens"];
  if (tokens.length === 0) {
    return null;
  }
  const encode2 = encodeURIComponent;
  const tokensList = tokens.split(",");
  const urls = tokensList.map((token) => {
    const bucket = metadata["bucket"];
    const path = metadata["fullPath"];
    const urlPart = "/b/" + encode2(bucket) + "/o/" + encode2(path);
    const base2 = makeUrl(urlPart, host, protocol);
    const queryString = makeQueryString({
      alt: "media",
      token
    });
    return base2 + queryString;
  });
  return urls[0];
}
__name(downloadUrlFromResourceString, "downloadUrlFromResourceString");
function toResourceString(metadata, mappings) {
  const resource = {};
  const len = mappings.length;
  for (let i2 = 0; i2 < len; i2++) {
    const mapping = mappings[i2];
    if (mapping.writable) {
      resource[mapping.server] = metadata[mapping.local];
    }
  }
  return JSON.stringify(resource);
}
__name(toResourceString, "toResourceString");
/**
 * @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 PREFIXES_KEY = "prefixes";
const ITEMS_KEY = "items";
function fromBackendResponse(service, bucket, resource) {
  const listResult = {
    prefixes: [],
    items: [],
    nextPageToken: resource["nextPageToken"]
  };
  if (resource[PREFIXES_KEY]) {
    for (const path of resource[PREFIXES_KEY]) {
      const pathWithoutTrailingSlash = path.replace(/\/$/, "");
      const reference2 = service._makeStorageReference(new Location(bucket, pathWithoutTrailingSlash));
      listResult.prefixes.push(reference2);
    }
  }
  if (resource[ITEMS_KEY]) {
    for (const item of resource[ITEMS_KEY]) {
      const reference2 = service._makeStorageReference(new Location(bucket, item["name"]));
      listResult.items.push(reference2);
    }
  }
  return listResult;
}
__name(fromBackendResponse, "fromBackendResponse");
function fromResponseString(service, bucket, resourceString) {
  const obj = jsonObjectOrNull(resourceString);
  if (obj === null) {
    return null;
  }
  const resource = obj;
  return fromBackendResponse(service, bucket, resource);
}
__name(fromResponseString, "fromResponseString");
class RequestInfo {
  static {
    __name(this, "RequestInfo");
  }
  constructor(url, method, handler5, timeout) {
    this.url = url;
    this.method = method;
    this.handler = handler5;
    this.timeout = timeout;
    this.urlParams = {};
    this.headers = {};
    this.body = null;
    this.errorHandler = null;
    this.progressCallback = null;
    this.successCodes = [200];
    this.additionalRetryCodes = [];
  }
}
/**
 * @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 handlerCheck(cndn) {
  if (!cndn) {
    throw unknown();
  }
}
__name(handlerCheck, "handlerCheck");
function metadataHandler(service, mappings) {
  function handler5(xhr, text2) {
    const metadata = fromResourceString(service, text2, mappings);
    handlerCheck(metadata !== null);
    return metadata;
  }
  __name(handler5, "handler");
  return handler5;
}
__name(metadataHandler, "metadataHandler");
function listHandler(service, bucket) {
  function handler5(xhr, text2) {
    const listResult = fromResponseString(service, bucket, text2);
    handlerCheck(listResult !== null);
    return listResult;
  }
  __name(handler5, "handler");
  return handler5;
}
__name(listHandler, "listHandler");
function downloadUrlHandler(service, mappings) {
  function handler5(xhr, text2) {
    const metadata = fromResourceString(service, text2, mappings);
    handlerCheck(metadata !== null);
    return downloadUrlFromResourceString(metadata, text2, service.host, service._protocol);
  }
  __name(handler5, "handler");
  return handler5;
}
__name(downloadUrlHandler, "downloadUrlHandler");
function sharedErrorHandler(location2) {
  function errorHandler2(xhr, err) {
    let newErr;
    if (xhr.getStatus() === 401) {
      if (
        // This exact message string is the only consistent part of the
        // server's error response that identifies it as an App Check error.
        xhr.getErrorText().includes("Firebase App Check token is invalid")
      ) {
        newErr = unauthorizedApp();
      } else {
        newErr = unauthenticated();
      }
    } else {
      if (xhr.getStatus() === 402) {
        newErr = quotaExceeded(location2.bucket);
      } else {
        if (xhr.getStatus() === 403) {
          newErr = unauthorized(location2.path);
        } else {
          newErr = err;
        }
      }
    }
    newErr.status = xhr.getStatus();
    newErr.serverResponse = err.serverResponse;
    return newErr;
  }
  __name(errorHandler2, "errorHandler");
  return errorHandler2;
}
__name(sharedErrorHandler, "sharedErrorHandler");
function objectErrorHandler(location2) {
  const shared = sharedErrorHandler(location2);
  function errorHandler2(xhr, err) {
    let newErr = shared(xhr, err);
    if (xhr.getStatus() === 404) {
      newErr = objectNotFound(location2.path);
    }
    newErr.serverResponse = err.serverResponse;
    return newErr;
  }
  __name(errorHandler2, "errorHandler");
  return errorHandler2;
}
__name(objectErrorHandler, "objectErrorHandler");
function getMetadata$2(service, location2, mappings) {
  const urlPart = location2.fullServerUrl();
  const url = makeUrl(urlPart, service.host, service._protocol);
  const method = "GET";
  const timeout = service.maxOperationRetryTime;
  const requestInfo = new RequestInfo(url, method, metadataHandler(service, mappings), timeout);
  requestInfo.errorHandler = objectErrorHandler(location2);
  return requestInfo;
}
__name(getMetadata$2, "getMetadata$2");
function list$2(service, location2, delimiter2, pageToken, maxResults) {
  const urlParams = {};
  if (location2.isRoot) {
    urlParams["prefix"] = "";
  } else {
    urlParams["prefix"] = location2.path + "/";
  }
  if (delimiter2 && delimiter2.length > 0) {
    urlParams["delimiter"] = delimiter2;
  }
  if (pageToken) {
    urlParams["pageToken"] = pageToken;
  }
  if (maxResults) {
    urlParams["maxResults"] = maxResults;
  }
  const urlPart = location2.bucketOnlyServerUrl();
  const url = makeUrl(urlPart, service.host, service._protocol);
  const method = "GET";
  const timeout = service.maxOperationRetryTime;
  const requestInfo = new RequestInfo(url, method, listHandler(service, location2.bucket), timeout);
  requestInfo.urlParams = urlParams;
  requestInfo.errorHandler = sharedErrorHandler(location2);
  return requestInfo;
}
__name(list$2, "list$2");
function getBytes$1(service, location2, maxDownloadSizeBytes) {
  const urlPart = location2.fullServerUrl();
  const url = makeUrl(urlPart, service.host, service._protocol) + "?alt=media";
  const method = "GET";
  const timeout = service.maxOperationRetryTime;
  const requestInfo = new RequestInfo(url, method, (_2, data) => data, timeout);
  requestInfo.errorHandler = objectErrorHandler(location2);
  if (maxDownloadSizeBytes !== void 0) {
    requestInfo.headers["Range"] = `bytes=0-${maxDownloadSizeBytes}`;
    requestInfo.successCodes = [
      200,
      206
      /* Partial Content */
    ];
  }
  return requestInfo;
}
__name(getBytes$1, "getBytes$1");
function getDownloadUrl(service, location2, mappings) {
  const urlPart = location2.fullServerUrl();
  const url = makeUrl(urlPart, service.host, service._protocol);
  const method = "GET";
  const timeout = service.maxOperationRetryTime;
  const requestInfo = new RequestInfo(url, method, downloadUrlHandler(service, mappings), timeout);
  requestInfo.errorHandler = objectErrorHandler(location2);
  return requestInfo;
}
__name(getDownloadUrl, "getDownloadUrl");
function updateMetadata$2(service, location2, metadata, mappings) {
  const urlPart = location2.fullServerUrl();
  const url = makeUrl(urlPart, service.host, service._protocol);
  const method = "PATCH";
  const body = toResourceString(metadata, mappings);
  const headers = { "Content-Type": "application/json; charset=utf-8" };
  const timeout = service.maxOperationRetryTime;
  const requestInfo = new RequestInfo(url, method, metadataHandler(service, mappings), timeout);
  requestInfo.headers = headers;
  requestInfo.body = body;
  requestInfo.errorHandler = objectErrorHandler(location2);
  return requestInfo;
}
__name(updateMetadata$2, "updateMetadata$2");
function deleteObject$2(service, location2) {
  const urlPart = location2.fullServerUrl();
  const url = makeUrl(urlPart, service.host, service._protocol);
  const method = "DELETE";
  const timeout = service.maxOperationRetryTime;
  function handler5(_xhr, _text) {
  }
  __name(handler5, "handler");
  const requestInfo = new RequestInfo(url, method, handler5, timeout);
  requestInfo.successCodes = [200, 204];
  requestInfo.errorHandler = objectErrorHandler(location2);
  return requestInfo;
}
__name(deleteObject$2, "deleteObject$2");
function determineContentType_(metadata, blob) {
  return metadata && metadata["contentType"] || blob && blob.type() || "application/octet-stream";
}
__name(determineContentType_, "determineContentType_");
function metadataForUpload_(location2, blob, metadata) {
  const metadataClone = Object.assign({}, metadata);
  metadataClone["fullPath"] = location2.path;
  metadataClone["size"] = blob.size();
  if (!metadataClone["contentType"]) {
    metadataClone["contentType"] = determineContentType_(null, blob);
  }
  return metadataClone;
}
__name(metadataForUpload_, "metadataForUpload_");
function multipartUpload(service, location2, mappings, blob, metadata) {
  const urlPart = location2.bucketOnlyServerUrl();
  const headers = {
    "X-Goog-Upload-Protocol": "multipart"
  };
  function genBoundary() {
    let str = "";
    for (let i2 = 0; i2 < 2; i2++) {
      str = str + Math.random().toString().slice(2);
    }
    return str;
  }
  __name(genBoundary, "genBoundary");
  const boundary = genBoundary();
  headers["Content-Type"] = "multipart/related; boundary=" + boundary;
  const metadata_ = metadataForUpload_(location2, blob, metadata);
  const metadataString = toResourceString(metadata_, mappings);
  const preBlobPart = "--" + boundary + "\r\nContent-Type: application/json; charset=utf-8\r\n\r\n" + metadataString + "\r\n--" + boundary + "\r\nContent-Type: " + metadata_["contentType"] + "\r\n\r\n";
  const postBlobPart = "\r\n--" + boundary + "--";
  const body = FbsBlob.getBlob(preBlobPart, blob, postBlobPart);
  if (body === null) {
    throw cannotSliceBlob();
  }
  const urlParams = { name: metadata_["fullPath"] };
  const url = makeUrl(urlPart, service.host, service._protocol);
  const method = "POST";
  const timeout = service.maxUploadRetryTime;
  const requestInfo = new RequestInfo(url, method, metadataHandler(service, mappings), timeout);
  requestInfo.urlParams = urlParams;
  requestInfo.headers = headers;
  requestInfo.body = body.uploadData();
  requestInfo.errorHandler = sharedErrorHandler(location2);
  return requestInfo;
}
__name(multipartUpload, "multipartUpload");
class ResumableUploadStatus {
  static {
    __name(this, "ResumableUploadStatus");
  }
  constructor(current, total, finalized, metadata) {
    this.current = current;
    this.total = total;
    this.finalized = !!finalized;
    this.metadata = metadata || null;
  }
}
function checkResumeHeader_(xhr, allowed) {
  let status = null;
  try {
    status = xhr.getResponseHeader("X-Goog-Upload-Status");
  } catch (e2) {
    handlerCheck(false);
  }
  const allowedStatus = allowed || ["active"];
  handlerCheck(!!status && allowedStatus.indexOf(status) !== -1);
  return status;
}
__name(checkResumeHeader_, "checkResumeHeader_");
function createResumableUpload(service, location2, mappings, blob, metadata) {
  const urlPart = location2.bucketOnlyServerUrl();
  const metadataForUpload = metadataForUpload_(location2, blob, metadata);
  const urlParams = { name: metadataForUpload["fullPath"] };
  const url = makeUrl(urlPart, service.host, service._protocol);
  const method = "POST";
  const headers = {
    "X-Goog-Upload-Protocol": "resumable",
    "X-Goog-Upload-Command": "start",
    "X-Goog-Upload-Header-Content-Length": `${blob.size()}`,
    "X-Goog-Upload-Header-Content-Type": metadataForUpload["contentType"],
    "Content-Type": "application/json; charset=utf-8"
  };
  const body = toResourceString(metadataForUpload, mappings);
  const timeout = service.maxUploadRetryTime;
  function handler5(xhr) {
    checkResumeHeader_(xhr);
    let url2;
    try {
      url2 = xhr.getResponseHeader("X-Goog-Upload-URL");
    } catch (e2) {
      handlerCheck(false);
    }
    handlerCheck(isString$7(url2));
    return url2;
  }
  __name(handler5, "handler");
  const requestInfo = new RequestInfo(url, method, handler5, timeout);
  requestInfo.urlParams = urlParams;
  requestInfo.headers = headers;
  requestInfo.body = body;
  requestInfo.errorHandler = sharedErrorHandler(location2);
  return requestInfo;
}
__name(createResumableUpload, "createResumableUpload");
function getResumableUploadStatus(service, location2, url, blob) {
  const headers = { "X-Goog-Upload-Command": "query" };
  function handler5(xhr) {
    const status = checkResumeHeader_(xhr, ["active", "final"]);
    let sizeString = null;
    try {
      sizeString = xhr.getResponseHeader("X-Goog-Upload-Size-Received");
    } catch (e2) {
      handlerCheck(false);
    }
    if (!sizeString) {
      handlerCheck(false);
    }
    const size = Number(sizeString);
    handlerCheck(!isNaN(size));
    return new ResumableUploadStatus(size, blob.size(), status === "final");
  }
  __name(handler5, "handler");
  const method = "POST";
  const timeout = service.maxUploadRetryTime;
  const requestInfo = new RequestInfo(url, method, handler5, timeout);
  requestInfo.headers = headers;
  requestInfo.errorHandler = sharedErrorHandler(location2);
  return requestInfo;
}
__name(getResumableUploadStatus, "getResumableUploadStatus");
const RESUMABLE_UPLOAD_CHUNK_SIZE = 256 * 1024;
function continueResumableUpload(location2, service, url, blob, chunkSize, mappings, status, progressCallback) {
  const status_ = new ResumableUploadStatus(0, 0);
  if (status) {
    status_.current = status.current;
    status_.total = status.total;
  } else {
    status_.current = 0;
    status_.total = blob.size();
  }
  if (blob.size() !== status_.total) {
    throw serverFileWrongSize();
  }
  const bytesLeft = status_.total - status_.current;
  let bytesToUpload = bytesLeft;
  if (chunkSize > 0) {
    bytesToUpload = Math.min(bytesToUpload, chunkSize);
  }
  const startByte = status_.current;
  const endByte = startByte + bytesToUpload;
  let uploadCommand = "";
  if (bytesToUpload === 0) {
    uploadCommand = "finalize";
  } else if (bytesLeft === bytesToUpload) {
    uploadCommand = "upload, finalize";
  } else {
    uploadCommand = "upload";
  }
  const headers = {
    "X-Goog-Upload-Command": uploadCommand,
    "X-Goog-Upload-Offset": `${status_.current}`
  };
  const body = blob.slice(startByte, endByte);
  if (body === null) {
    throw cannotSliceBlob();
  }
  function handler5(xhr, text2) {
    const uploadStatus = checkResumeHeader_(xhr, ["active", "final"]);
    const newCurrent = status_.current + bytesToUpload;
    const size = blob.size();
    let metadata;
    if (uploadStatus === "final") {
      metadata = metadataHandler(service, mappings)(xhr, text2);
    } else {
      metadata = null;
    }
    return new ResumableUploadStatus(newCurrent, size, uploadStatus === "final", metadata);
  }
  __name(handler5, "handler");
  const method = "POST";
  const timeout = service.maxUploadRetryTime;
  const requestInfo = new RequestInfo(url, method, handler5, timeout);
  requestInfo.headers = headers;
  requestInfo.body = body.uploadData();
  requestInfo.progressCallback = progressCallback || null;
  requestInfo.errorHandler = sharedErrorHandler(location2);
  return requestInfo;
}
__name(continueResumableUpload, "continueResumableUpload");
/**
 * @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 TaskEvent = {
  /**
   * For this event,
   * <ul>
   *   <li>The `next` function is triggered on progress updates and when the
   *       task is paused/resumed with an `UploadTaskSnapshot` as the first
   *       argument.</li>
   *   <li>The `error` function is triggered if the upload is canceled or fails
   *       for another reason.</li>
   *   <li>The `complete` function is triggered if the upload completes
   *       successfully.</li>
   * </ul>
   */
  STATE_CHANGED: "state_changed"
};
const TaskState = {
  /** The task is currently transferring data. */
  RUNNING: "running",
  /** The task was paused by the user. */
  PAUSED: "paused",
  /** The task completed successfully. */
  SUCCESS: "success",
  /** The task was canceled. */
  CANCELED: "canceled",
  /** The task failed with an error. */
  ERROR: "error"
};
function taskStateFromInternalTaskState(state) {
  switch (state) {
    case "running":
    case "pausing":
    case "canceling":
      return TaskState.RUNNING;
    case "paused":
      return TaskState.PAUSED;
    case "success":
      return TaskState.SUCCESS;
    case "canceled":
      return TaskState.CANCELED;
    case "error":
      return TaskState.ERROR;
    default:
      return TaskState.ERROR;
  }
}
__name(taskStateFromInternalTaskState, "taskStateFromInternalTaskState");
/**
 * @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 Observer {
  static {
    __name(this, "Observer");
  }
  constructor(nextOrObserver, error2, complete) {
    const asFunctions = isFunction$a(nextOrObserver) || error2 != null || complete != null;
    if (asFunctions) {
      this.next = nextOrObserver;
      this.error = error2 !== null && error2 !== void 0 ? error2 : void 0;
      this.complete = complete !== null && complete !== void 0 ? complete : void 0;
    } else {
      const observer = nextOrObserver;
      this.next = observer.next;
      this.error = observer.error;
      this.complete = observer.complete;
    }
  }
}
/**
 * @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 async(f2) {
  return (...argsToForward) => {
    Promise.resolve().then(() => f2(...argsToForward));
  };
}
__name(async, "async");
/**
 * @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 textFactoryOverride = null;
class XhrConnection {
  static {
    __name(this, "XhrConnection");
  }
  constructor() {
    this.sent_ = false;
    this.xhr_ = new XMLHttpRequest();
    this.initXhr();
    this.errorCode_ = ErrorCode.NO_ERROR;
    this.sendPromise_ = new Promise((resolve2) => {
      this.xhr_.addEventListener("abort", () => {
        this.errorCode_ = ErrorCode.ABORT;
        resolve2();
      });
      this.xhr_.addEventListener("error", () => {
        this.errorCode_ = ErrorCode.NETWORK_ERROR;
        resolve2();
      });
      this.xhr_.addEventListener("load", () => {
        resolve2();
      });
    });
  }
  send(url, method, body, headers) {
    if (this.sent_) {
      throw internalError("cannot .send() more than once");
    }
    this.sent_ = true;
    this.xhr_.open(method, url, true);
    if (headers !== void 0) {
      for (const key in headers) {
        if (headers.hasOwnProperty(key)) {
          this.xhr_.setRequestHeader(key, headers[key].toString());
        }
      }
    }
    if (body !== void 0) {
      this.xhr_.send(body);
    } else {
      this.xhr_.send();
    }
    return this.sendPromise_;
  }
  getErrorCode() {
    if (!this.sent_) {
      throw internalError("cannot .getErrorCode() before sending");
    }
    return this.errorCode_;
  }
  getStatus() {
    if (!this.sent_) {
      throw internalError("cannot .getStatus() before sending");
    }
    try {
      return this.xhr_.status;
    } catch (e2) {
      return -1;
    }
  }
  getResponse() {
    if (!this.sent_) {
      throw internalError("cannot .getResponse() before sending");
    }
    return this.xhr_.response;
  }
  getErrorText() {
    if (!this.sent_) {
      throw internalError("cannot .getErrorText() before sending");
    }
    return this.xhr_.statusText;
  }
  /** Aborts the request. */
  abort() {
    this.xhr_.abort();
  }
  getResponseHeader(header) {
    return this.xhr_.getResponseHeader(header);
  }
  addUploadProgressListener(listener) {
    if (this.xhr_.upload != null) {
      this.xhr_.upload.addEventListener("progress", listener);
    }
  }
  removeUploadProgressListener(listener) {
    if (this.xhr_.upload != null) {
      this.xhr_.upload.removeEventListener("progress", listener);
    }
  }
}
class XhrTextConnection extends XhrConnection {
  static {
    __name(this, "XhrTextConnection");
  }
  initXhr() {
    this.xhr_.responseType = "text";
  }
}
function newTextConnection() {
  return textFactoryOverride ? textFactoryOverride() : new XhrTextConnection();
}
__name(newTextConnection, "newTextConnection");
class XhrBytesConnection extends XhrConnection {
  static {
    __name(this, "XhrBytesConnection");
  }
  initXhr() {
    this.xhr_.responseType = "arraybuffer";
  }
}
function newBytesConnection() {
  return new XhrBytesConnection();
}
__name(newBytesConnection, "newBytesConnection");
class XhrBlobConnection extends XhrConnection {
  static {
    __name(this, "XhrBlobConnection");
  }
  initXhr() {
    this.xhr_.responseType = "blob";
  }
}
function newBlobConnection() {
  return new XhrBlobConnection();
}
__name(newBlobConnection, "newBlobConnection");
/**
 * @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 UploadTask {
  static {
    __name(this, "UploadTask");
  }
  isExponentialBackoffExpired() {
    return this.sleepTime > this.maxSleepTime;
  }
  /**
   * @param ref - The firebaseStorage.Reference object this task came
   *     from, untyped to avoid cyclic dependencies.
   * @param blob - The blob to upload.
   */
  constructor(ref2, blob, metadata = null) {
    this._transferred = 0;
    this._needToFetchStatus = false;
    this._needToFetchMetadata = false;
    this._observers = [];
    this._error = void 0;
    this._uploadUrl = void 0;
    this._request = void 0;
    this._chunkMultiplier = 1;
    this._resolve = void 0;
    this._reject = void 0;
    this._ref = ref2;
    this._blob = blob;
    this._metadata = metadata;
    this._mappings = getMappings();
    this._resumable = this._shouldDoResumable(this._blob);
    this._state = "running";
    this._errorHandler = (error2) => {
      this._request = void 0;
      this._chunkMultiplier = 1;
      if (error2._codeEquals(StorageErrorCode.CANCELED)) {
        this._needToFetchStatus = true;
        this.completeTransitions_();
      } else {
        const backoffExpired = this.isExponentialBackoffExpired();
        if (isRetryStatusCode(error2.status, [])) {
          if (backoffExpired) {
            error2 = retryLimitExceeded();
          } else {
            this.sleepTime = Math.max(this.sleepTime * 2, DEFAULT_MIN_SLEEP_TIME_MILLIS);
            this._needToFetchStatus = true;
            this.completeTransitions_();
            return;
          }
        }
        this._error = error2;
        this._transition(
          "error"
          /* InternalTaskState.ERROR */
        );
      }
    };
    this._metadataErrorHandler = (error2) => {
      this._request = void 0;
      if (error2._codeEquals(StorageErrorCode.CANCELED)) {
        this.completeTransitions_();
      } else {
        this._error = error2;
        this._transition(
          "error"
          /* InternalTaskState.ERROR */
        );
      }
    };
    this.sleepTime = 0;
    this.maxSleepTime = this._ref.storage.maxUploadRetryTime;
    this._promise = new Promise((resolve2, reject) => {
      this._resolve = resolve2;
      this._reject = reject;
      this._start();
    });
    this._promise.then(null, () => {
    });
  }
  _makeProgressCallback() {
    const sizeBefore = this._transferred;
    return (loaded) => this._updateProgress(sizeBefore + loaded);
  }
  _shouldDoResumable(blob) {
    return blob.size() > 256 * 1024;
  }
  _start() {
    if (this._state !== "running") {
      return;
    }
    if (this._request !== void 0) {
      return;
    }
    if (this._resumable) {
      if (this._uploadUrl === void 0) {
        this._createResumable();
      } else {
        if (this._needToFetchStatus) {
          this._fetchStatus();
        } else {
          if (this._needToFetchMetadata) {
            this._fetchMetadata();
          } else {
            this.pendingTimeout = setTimeout(() => {
              this.pendingTimeout = void 0;
              this._continueUpload();
            }, this.sleepTime);
          }
        }
      }
    } else {
      this._oneShotUpload();
    }
  }
  _resolveToken(callback) {
    Promise.all([
      this._ref.storage._getAuthToken(),
      this._ref.storage._getAppCheckToken()
    ]).then(([authToken, appCheckToken]) => {
      switch (this._state) {
        case "running":
          callback(authToken, appCheckToken);
          break;
        case "canceling":
          this._transition(
            "canceled"
            /* InternalTaskState.CANCELED */
          );
          break;
        case "pausing":
          this._transition(
            "paused"
            /* InternalTaskState.PAUSED */
          );
          break;
      }
    });
  }
  // TODO(andysoto): assert false
  _createResumable() {
    this._resolveToken((authToken, appCheckToken) => {
      const requestInfo = createResumableUpload(this._ref.storage, this._ref._location, this._mappings, this._blob, this._metadata);
      const createRequest = this._ref.storage._makeRequest(requestInfo, newTextConnection, authToken, appCheckToken);
      this._request = createRequest;
      createRequest.getPromise().then((url) => {
        this._request = void 0;
        this._uploadUrl = url;
        this._needToFetchStatus = false;
        this.completeTransitions_();
      }, this._errorHandler);
    });
  }
  _fetchStatus() {
    const url = this._uploadUrl;
    this._resolveToken((authToken, appCheckToken) => {
      const requestInfo = getResumableUploadStatus(this._ref.storage, this._ref._location, url, this._blob);
      const statusRequest = this._ref.storage._makeRequest(requestInfo, newTextConnection, authToken, appCheckToken);
      this._request = statusRequest;
      statusRequest.getPromise().then((status) => {
        status = status;
        this._request = void 0;
        this._updateProgress(status.current);
        this._needToFetchStatus = false;
        if (status.finalized) {
          this._needToFetchMetadata = true;
        }
        this.completeTransitions_();
      }, this._errorHandler);
    });
  }
  _continueUpload() {
    const chunkSize = RESUMABLE_UPLOAD_CHUNK_SIZE * this._chunkMultiplier;
    const status = new ResumableUploadStatus(this._transferred, this._blob.size());
    const url = this._uploadUrl;
    this._resolveToken((authToken, appCheckToken) => {
      let requestInfo;
      try {
        requestInfo = continueResumableUpload(this._ref._location, this._ref.storage, url, this._blob, chunkSize, this._mappings, status, this._makeProgressCallback());
      } catch (e2) {
        this._error = e2;
        this._transition(
          "error"
          /* InternalTaskState.ERROR */
        );
        return;
      }
      const uploadRequest = this._ref.storage._makeRequest(
        requestInfo,
        newTextConnection,
        authToken,
        appCheckToken,
        /*retry=*/
        false
        // Upload requests should not be retried as each retry should be preceded by another query request. Which is handled in this file.
      );
      this._request = uploadRequest;
      uploadRequest.getPromise().then((newStatus) => {
        this._increaseMultiplier();
        this._request = void 0;
        this._updateProgress(newStatus.current);
        if (newStatus.finalized) {
          this._metadata = newStatus.metadata;
          this._transition(
            "success"
            /* InternalTaskState.SUCCESS */
          );
        } else {
          this.completeTransitions_();
        }
      }, this._errorHandler);
    });
  }
  _increaseMultiplier() {
    const currentSize = RESUMABLE_UPLOAD_CHUNK_SIZE * this._chunkMultiplier;
    if (currentSize * 2 < 32 * 1024 * 1024) {
      this._chunkMultiplier *= 2;
    }
  }
  _fetchMetadata() {
    this._resolveToken((authToken, appCheckToken) => {
      const requestInfo = getMetadata$2(this._ref.storage, this._ref._location, this._mappings);
      const metadataRequest = this._ref.storage._makeRequest(requestInfo, newTextConnection, authToken, appCheckToken);
      this._request = metadataRequest;
      metadataRequest.getPromise().then((metadata) => {
        this._request = void 0;
        this._metadata = metadata;
        this._transition(
          "success"
          /* InternalTaskState.SUCCESS */
        );
      }, this._metadataErrorHandler);
    });
  }
  _oneShotUpload() {
    this._resolveToken((authToken, appCheckToken) => {
      const requestInfo = multipartUpload(this._ref.storage, this._ref._location, this._mappings, this._blob, this._metadata);
      const multipartRequest = this._ref.storage._makeRequest(requestInfo, newTextConnection, authToken, appCheckToken);
      this._request = multipartRequest;
      multipartRequest.getPromise().then((metadata) => {
        this._request = void 0;
        this._metadata = metadata;
        this._updateProgress(this._blob.size());
        this._transition(
          "success"
          /* InternalTaskState.SUCCESS */
        );
      }, this._errorHandler);
    });
  }
  _updateProgress(transferred) {
    const old = this._transferred;
    this._transferred = transferred;
    if (this._transferred !== old) {
      this._notifyObservers();
    }
  }
  _transition(state) {
    if (this._state === state) {
      return;
    }
    switch (state) {
      case "canceling":
      case "pausing":
        this._state = state;
        if (this._request !== void 0) {
          this._request.cancel();
        } else if (this.pendingTimeout) {
          clearTimeout(this.pendingTimeout);
          this.pendingTimeout = void 0;
          this.completeTransitions_();
        }
        break;
      case "running":
        const wasPaused = this._state === "paused";
        this._state = state;
        if (wasPaused) {
          this._notifyObservers();
          this._start();
        }
        break;
      case "paused":
        this._state = state;
        this._notifyObservers();
        break;
      case "canceled":
        this._error = canceled();
        this._state = state;
        this._notifyObservers();
        break;
      case "error":
        this._state = state;
        this._notifyObservers();
        break;
      case "success":
        this._state = state;
        this._notifyObservers();
        break;
    }
  }
  completeTransitions_() {
    switch (this._state) {
      case "pausing":
        this._transition(
          "paused"
          /* InternalTaskState.PAUSED */
        );
        break;
      case "canceling":
        this._transition(
          "canceled"
          /* InternalTaskState.CANCELED */
        );
        break;
      case "running":
        this._start();
        break;
    }
  }
  /**
   * A snapshot of the current task state.
   */
  get snapshot() {
    const externalState = taskStateFromInternalTaskState(this._state);
    return {
      bytesTransferred: this._transferred,
      totalBytes: this._blob.size(),
      state: externalState,
      metadata: this._metadata,
      task: this,
      ref: this._ref
    };
  }
  /**
   * Adds a callback for an event.
   * @param type - The type of event to listen for.
   * @param nextOrObserver -
   *     The `next` function, which gets called for each item in
   *     the event stream, or an observer object with some or all of these three
   *     properties (`next`, `error`, `complete`).
   * @param error - A function that gets called with a `StorageError`
   *     if the event stream ends due to an error.
   * @param completed - A function that gets called if the
   *     event stream ends normally.
   * @returns
   *     If only the event argument is passed, returns a function you can use to
   *     add callbacks (see the examples above). If more than just the event
   *     argument is passed, returns a function you can call to unregister the
   *     callbacks.
   */
  on(type, nextOrObserver, error2, completed) {
    const observer = new Observer(nextOrObserver || void 0, error2 || void 0, completed || void 0);
    this._addObserver(observer);
    return () => {
      this._removeObserver(observer);
    };
  }
  /**
   * This object behaves like a Promise, and resolves with its snapshot data
   * when the upload completes.
   * @param onFulfilled - The fulfillment callback. Promise chaining works as normal.
   * @param onRejected - The rejection callback.
   */
  then(onFulfilled, onRejected) {
    return this._promise.then(onFulfilled, onRejected);
  }
  /**
   * Equivalent to calling `then(null, onRejected)`.
   */
  catch(onRejected) {
    return this.then(null, onRejected);
  }
  /**
   * Adds the given observer.
   */
  _addObserver(observer) {
    this._observers.push(observer);
    this._notifyObserver(observer);
  }
  /**
   * Removes the given observer.
   */
  _removeObserver(observer) {
    const i2 = this._observers.indexOf(observer);
    if (i2 !== -1) {
      this._observers.splice(i2, 1);
    }
  }
  _notifyObservers() {
    this._finishPromise();
    const observers = this._observers.slice();
    observers.forEach((observer) => {
      this._notifyObserver(observer);
    });
  }
  _finishPromise() {
    if (this._resolve !== void 0) {
      let triggered = true;
      switch (taskStateFromInternalTaskState(this._state)) {
        case TaskState.SUCCESS:
          async(this._resolve.bind(null, this.snapshot))();
          break;
        case TaskState.CANCELED:
        case TaskState.ERROR:
          const toCall = this._reject;
          async(toCall.bind(null, this._error))();
          break;
        default:
          triggered = false;
          break;
      }
      if (triggered) {
        this._resolve = void 0;
        this._reject = void 0;
      }
    }
  }
  _notifyObserver(observer) {
    const externalState = taskStateFromInternalTaskState(this._state);
    switch (externalState) {
      case TaskState.RUNNING:
      case TaskState.PAUSED:
        if (observer.next) {
          async(observer.next.bind(observer, this.snapshot))();
        }
        break;
      case TaskState.SUCCESS:
        if (observer.complete) {
          async(observer.complete.bind(observer))();
        }
        break;
      case TaskState.CANCELED:
      case TaskState.ERROR:
        if (observer.error) {
          async(observer.error.bind(observer, this._error))();
        }
        break;
      default:
        if (observer.error) {
          async(observer.error.bind(observer, this._error))();
        }
    }
  }
  /**
   * Resumes a paused task. Has no effect on a currently running or failed task.
   * @returns True if the operation took effect, false if ignored.
   */
  resume() {
    const valid = this._state === "paused" || this._state === "pausing";
    if (valid) {
      this._transition(
        "running"
        /* InternalTaskState.RUNNING */
      );
    }
    return valid;
  }
  /**
   * Pauses a currently running task. Has no effect on a paused or failed task.
   * @returns True if the operation took effect, false if ignored.
   */
  pause() {
    const valid = this._state === "running";
    if (valid) {
      this._transition(
        "pausing"
        /* InternalTaskState.PAUSING */
      );
    }
    return valid;
  }
  /**
   * Cancels a currently running or paused task. Has no effect on a complete or
   * failed task.
   * @returns True if the operation took effect, false if ignored.
   */
  cancel() {
    const valid = this._state === "running" || this._state === "pausing";
    if (valid) {
      this._transition(
        "canceling"
        /* InternalTaskState.CANCELING */
      );
    }
    return valid;
  }
}
/**
 * @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 Reference {
  static {
    __name(this, "Reference");
  }
  constructor(_service, location2) {
    this._service = _service;
    if (location2 instanceof Location) {
      this._location = location2;
    } else {
      this._location = Location.makeFromUrl(location2, _service.host);
    }
  }
  /**
   * Returns the URL for the bucket and path this object references,
   *     in the form gs://<bucket>/<object-path>
   * @override
   */
  toString() {
    return "gs://" + this._location.bucket + "/" + this._location.path;
  }
  _newRef(service, location2) {
    return new Reference(service, location2);
  }
  /**
   * A reference to the root of this object's bucket.
   */
  get root() {
    const location2 = new Location(this._location.bucket, "");
    return this._newRef(this._service, location2);
  }
  /**
   * The name of the bucket containing this reference's object.
   */
  get bucket() {
    return this._location.bucket;
  }
  /**
   * The full path of this object.
   */
  get fullPath() {
    return this._location.path;
  }
  /**
   * The short name of this object, which is the last component of the full path.
   * For example, if fullPath is 'full/path/image.png', name is 'image.png'.
   */
  get name() {
    return lastComponent(this._location.path);
  }
  /**
   * The `StorageService` instance this `StorageReference` is associated with.
   */
  get storage() {
    return this._service;
  }
  /**
   * A `StorageReference` pointing to the parent location of this `StorageReference`, or null if
   * this reference is the root.
   */
  get parent() {
    const newPath = parent(this._location.path);
    if (newPath === null) {
      return null;
    }
    const location2 = new Location(this._location.bucket, newPath);
    return new Reference(this._service, location2);
  }
  /**
   * Utility function to throw an error in methods that do not accept a root reference.
   */
  _throwIfRoot(name2) {
    if (this._location.path === "") {
      throw invalidRootOperation(name2);
    }
  }
}
function getBytesInternal(ref2, maxDownloadSizeBytes) {
  ref2._throwIfRoot("getBytes");
  const requestInfo = getBytes$1(ref2.storage, ref2._location, maxDownloadSizeBytes);
  return ref2.storage.makeRequestWithTokens(requestInfo, newBytesConnection).then((bytes) => maxDownloadSizeBytes !== void 0 ? (
    // GCS may not honor the Range header for small files
    bytes.slice(0, maxDownloadSizeBytes)
  ) : bytes);
}
__name(getBytesInternal, "getBytesInternal");
function getBlobInternal(ref2, maxDownloadSizeBytes) {
  ref2._throwIfRoot("getBlob");
  const requestInfo = getBytes$1(ref2.storage, ref2._location, maxDownloadSizeBytes);
  return ref2.storage.makeRequestWithTokens(requestInfo, newBlobConnection).then((blob) => maxDownloadSizeBytes !== void 0 ? (
    // GCS may not honor the Range header for small files
    blob.slice(0, maxDownloadSizeBytes)
  ) : blob);
}
__name(getBlobInternal, "getBlobInternal");
function uploadBytes$1(ref2, data, metadata) {
  ref2._throwIfRoot("uploadBytes");
  const requestInfo = multipartUpload(ref2.storage, ref2._location, getMappings(), new FbsBlob(data, true), metadata);
  return ref2.storage.makeRequestWithTokens(requestInfo, newTextConnection).then((finalMetadata) => {
    return {
      metadata: finalMetadata,
      ref: ref2
    };
  });
}
__name(uploadBytes$1, "uploadBytes$1");
function uploadBytesResumable$1(ref2, data, metadata) {
  ref2._throwIfRoot("uploadBytesResumable");
  return new UploadTask(ref2, new FbsBlob(data), metadata);
}
__name(uploadBytesResumable$1, "uploadBytesResumable$1");
function uploadString$1(ref2, value, format2 = StringFormat.RAW, metadata) {
  ref2._throwIfRoot("uploadString");
  const data = dataFromString(format2, value);
  const metadataClone = Object.assign({}, metadata);
  if (metadataClone["contentType"] == null && data.contentType != null) {
    metadataClone["contentType"] = data.contentType;
  }
  return uploadBytes$1(ref2, data.data, metadataClone);
}
__name(uploadString$1, "uploadString$1");
function listAll$1(ref2) {
  const accumulator = {
    prefixes: [],
    items: []
  };
  return listAllHelper(ref2, accumulator).then(() => accumulator);
}
__name(listAll$1, "listAll$1");
async function listAllHelper(ref2, accumulator, pageToken) {
  const opt = {
    // maxResults is 1000 by default.
    pageToken
  };
  const nextPage = await list$1(ref2, opt);
  accumulator.prefixes.push(...nextPage.prefixes);
  accumulator.items.push(...nextPage.items);
  if (nextPage.nextPageToken != null) {
    await listAllHelper(ref2, accumulator, nextPage.nextPageToken);
  }
}
__name(listAllHelper, "listAllHelper");
function list$1(ref2, options2) {
  if (options2 != null) {
    if (typeof options2.maxResults === "number") {
      validateNumber(
        "options.maxResults",
        /* minValue= */
        1,
        /* maxValue= */
        1e3,
        options2.maxResults
      );
    }
  }
  const op = options2 || {};
  const requestInfo = list$2(
    ref2.storage,
    ref2._location,
    /*delimiter= */
    "/",
    op.pageToken,
    op.maxResults
  );
  return ref2.storage.makeRequestWithTokens(requestInfo, newTextConnection);
}
__name(list$1, "list$1");
function getMetadata$1(ref2) {
  ref2._throwIfRoot("getMetadata");
  const requestInfo = getMetadata$2(ref2.storage, ref2._location, getMappings());
  return ref2.storage.makeRequestWithTokens(requestInfo, newTextConnection);
}
__name(getMetadata$1, "getMetadata$1");
function updateMetadata$1(ref2, metadata) {
  ref2._throwIfRoot("updateMetadata");
  const requestInfo = updateMetadata$2(ref2.storage, ref2._location, metadata, getMappings());
  return ref2.storage.makeRequestWithTokens(requestInfo, newTextConnection);
}
__name(updateMetadata$1, "updateMetadata$1");
function getDownloadURL$1(ref2) {
  ref2._throwIfRoot("getDownloadURL");
  const requestInfo = getDownloadUrl(ref2.storage, ref2._location, getMappings());
  return ref2.storage.makeRequestWithTokens(requestInfo, newTextConnection).then((url) => {
    if (url === null) {
      throw noDownloadURL();
    }
    return url;
  });
}
__name(getDownloadURL$1, "getDownloadURL$1");
function deleteObject$1(ref2) {
  ref2._throwIfRoot("deleteObject");
  const requestInfo = deleteObject$2(ref2.storage, ref2._location);
  return ref2.storage.makeRequestWithTokens(requestInfo, newTextConnection);
}
__name(deleteObject$1, "deleteObject$1");
function _getChild$1(ref2, childPath) {
  const newPath = child(ref2._location.path, childPath);
  const location2 = new Location(ref2._location.bucket, newPath);
  return new Reference(ref2.storage, location2);
}
__name(_getChild$1, "_getChild$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.
 */
function isUrl(path) {
  return /^[A-Za-z]+:\/\//.test(path);
}
__name(isUrl, "isUrl");
function refFromURL(service, url) {
  return new Reference(service, url);
}
__name(refFromURL, "refFromURL");
function refFromPath(ref2, path) {
  if (ref2 instanceof FirebaseStorageImpl) {
    const service = ref2;
    if (service._bucket == null) {
      throw noDefaultBucket();
    }
    const reference2 = new Reference(service, service._bucket);
    if (path != null) {
      return refFromPath(reference2, path);
    } else {
      return reference2;
    }
  } else {
    if (path !== void 0) {
      return _getChild$1(ref2, path);
    } else {
      return ref2;
    }
  }
}
__name(refFromPath, "refFromPath");
function ref$1(serviceOrRef, pathOrUrl) {
  if (pathOrUrl && isUrl(pathOrUrl)) {
    if (serviceOrRef instanceof FirebaseStorageImpl) {
      return refFromURL(serviceOrRef, pathOrUrl);
    } else {
      throw invalidArgument("To use ref(service, url), the first argument must be a Storage instance.");
    }
  } else {
    return refFromPath(serviceOrRef, pathOrUrl);
  }
}
__name(ref$1, "ref$1");
function extractBucket(host, config2) {
  const bucketString = config2 === null || config2 === void 0 ? void 0 : config2[CONFIG_STORAGE_BUCKET_KEY];
  if (bucketString == null) {
    return null;
  }
  return Location.makeFromBucketSpec(bucketString, host);
}
__name(extractBucket, "extractBucket");
function connectStorageEmulator$1(storage, host, port, options2 = {}) {
  storage.host = `${host}:${port}`;
  storage._protocol = "http";
  const { mockUserToken } = options2;
  if (mockUserToken) {
    storage._overrideAuthToken = typeof mockUserToken === "string" ? mockUserToken : createMockUserToken(mockUserToken, storage.app.options.projectId);
  }
}
__name(connectStorageEmulator$1, "connectStorageEmulator$1");
class FirebaseStorageImpl {
  static {
    __name(this, "FirebaseStorageImpl");
  }
  constructor(app2, _authProvider, _appCheckProvider, _url, _firebaseVersion) {
    this.app = app2;
    this._authProvider = _authProvider;
    this._appCheckProvider = _appCheckProvider;
    this._url = _url;
    this._firebaseVersion = _firebaseVersion;
    this._bucket = null;
    this._host = DEFAULT_HOST;
    this._protocol = "https";
    this._appId = null;
    this._deleted = false;
    this._maxOperationRetryTime = DEFAULT_MAX_OPERATION_RETRY_TIME;
    this._maxUploadRetryTime = DEFAULT_MAX_UPLOAD_RETRY_TIME;
    this._requests = /* @__PURE__ */ new Set();
    if (_url != null) {
      this._bucket = Location.makeFromBucketSpec(_url, this._host);
    } else {
      this._bucket = extractBucket(this._host, this.app.options);
    }
  }
  /**
   * The host string for this service, in the form of `host` or
   * `host:port`.
   */
  get host() {
    return this._host;
  }
  set host(host) {
    this._host = host;
    if (this._url != null) {
      this._bucket = Location.makeFromBucketSpec(this._url, host);
    } else {
      this._bucket = extractBucket(host, this.app.options);
    }
  }
  /**
   * The maximum time to retry uploads in milliseconds.
   */
  get maxUploadRetryTime() {
    return this._maxUploadRetryTime;
  }
  set maxUploadRetryTime(time) {
    validateNumber(
      "time",
      /* minValue=*/
      0,
      /* maxValue= */
      Number.POSITIVE_INFINITY,
      time
    );
    this._maxUploadRetryTime = time;
  }
  /**
   * The maximum time to retry operations other than uploads or downloads in
   * milliseconds.
   */
  get maxOperationRetryTime() {
    return this._maxOperationRetryTime;
  }
  set maxOperationRetryTime(time) {
    validateNumber(
      "time",
      /* minValue=*/
      0,
      /* maxValue= */
      Number.POSITIVE_INFINITY,
      time
    );
    this._maxOperationRetryTime = time;
  }
  async _getAuthToken() {
    if (this._overrideAuthToken) {
      return this._overrideAuthToken;
    }
    const auth2 = this._authProvider.getImmediate({ optional: true });
    if (auth2) {
      const tokenData = await auth2.getToken();
      if (tokenData !== null) {
        return tokenData.accessToken;
      }
    }
    return null;
  }
  async _getAppCheckToken() {
    if (_isFirebaseServerApp(this.app) && this.app.settings.appCheckToken) {
      return this.app.settings.appCheckToken;
    }
    const appCheck = this._appCheckProvider.getImmediate({ optional: true });
    if (appCheck) {
      const result = await appCheck.getToken();
      return result.token;
    }
    return null;
  }
  /**
   * Stop running requests and prevent more from being created.
   */
  _delete() {
    if (!this._deleted) {
      this._deleted = true;
      this._requests.forEach((request) => request.cancel());
      this._requests.clear();
    }
    return Promise.resolve();
  }
  /**
   * Returns a new firebaseStorage.Reference object referencing this StorageService
   * at the given Location.
   */
  _makeStorageReference(loc) {
    return new Reference(this, loc);
  }
  /**
   * @param requestInfo - HTTP RequestInfo object
   * @param authToken - Firebase auth token
   */
  _makeRequest(requestInfo, requestFactory, authToken, appCheckToken, retry = true) {
    if (!this._deleted) {
      const request = makeRequest(requestInfo, this._appId, authToken, appCheckToken, requestFactory, this._firebaseVersion, retry);
      this._requests.add(request);
      request.getPromise().then(() => this._requests.delete(request), () => this._requests.delete(request));
      return request;
    } else {
      return new FailRequest(appDeleted());
    }
  }
  async makeRequestWithTokens(requestInfo, requestFactory) {
    const [authToken, appCheckToken] = await Promise.all([
      this._getAuthToken(),
      this._getAppCheckToken()
    ]);
    return this._makeRequest(requestInfo, requestFactory, authToken, appCheckToken).getPromise();
  }
}
const name$6 = "@firebase/storage";
const version = "0.13.7";
/**
 * @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 STORAGE_TYPE = "storage";
/**
 * @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.
 */
function getBytes(ref2, maxDownloadSizeBytes) {
  ref2 = getModularInstance(ref2);
  return getBytesInternal(ref2, maxDownloadSizeBytes);
}
__name(getBytes, "getBytes");
function uploadBytes(ref2, data, metadata) {
  ref2 = getModularInstance(ref2);
  return uploadBytes$1(ref2, data, metadata);
}
__name(uploadBytes, "uploadBytes");
function uploadString(ref2, value, format2, metadata) {
  ref2 = getModularInstance(ref2);
  return uploadString$1(ref2, value, format2, metadata);
}
__name(uploadString, "uploadString");
function uploadBytesResumable(ref2, data, metadata) {
  ref2 = getModularInstance(ref2);
  return uploadBytesResumable$1(ref2, data, metadata);
}
__name(uploadBytesResumable, "uploadBytesResumable");
function getMetadata(ref2) {
  ref2 = getModularInstance(ref2);
  return getMetadata$1(ref2);
}
__name(getMetadata, "getMetadata");
function updateMetadata(ref2, metadata) {
  ref2 = getModularInstance(ref2);
  return updateMetadata$1(ref2, metadata);
}
__name(updateMetadata, "updateMetadata");
function list$3(ref2, options2) {
  ref2 = getModularInstance(ref2);
  return list$1(ref2, options2);
}
__name(list$3, "list$3");
function listAll(ref2) {
  ref2 = getModularInstance(ref2);
  return listAll$1(ref2);
}
__name(listAll, "listAll");
function getDownloadURL(ref2) {
  ref2 = getModularInstance(ref2);
  return getDownloadURL$1(ref2);
}
__name(getDownloadURL, "getDownloadURL");
function deleteObject(ref2) {
  ref2 = getModularInstance(ref2);
  return deleteObject$1(ref2);
}
__name(deleteObject, "deleteObject");
function ref(serviceOrRef, pathOrUrl) {
  serviceOrRef = getModularInstance(serviceOrRef);
  return ref$1(serviceOrRef, pathOrUrl);
}
__name(ref, "ref");
function _getChild(ref2, childPath) {
  return _getChild$1(ref2, childPath);
}
__name(_getChild, "_getChild");
function getStorage(app2 = getApp(), bucketUrl) {
  app2 = getModularInstance(app2);
  const storageProvider = _getProvider(app2, STORAGE_TYPE);
  const storageInstance = storageProvider.getImmediate({
    identifier: bucketUrl
  });
  const emulator = getDefaultEmulatorHostnameAndPort("storage");
  if (emulator) {
    connectStorageEmulator(storageInstance, ...emulator);
  }
  return storageInstance;
}
__name(getStorage, "getStorage");
function connectStorageEmulator(storage, host, port, options2 = {}) {
  connectStorageEmulator$1(storage, host, port, options2);
}
__name(connectStorageEmulator, "connectStorageEmulator");
/**
 * @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 getBlob(ref2, maxDownloadSizeBytes) {
  ref2 = getModularInstance(ref2);
  return getBlobInternal(ref2, maxDownloadSizeBytes);
}
__name(getBlob, "getBlob");
function getStream(ref2, maxDownloadSizeBytes) {
  throw new Error("getStream() is only supported by NodeJS builds");
}
__name(getStream, "getStream");
function factory(container, { instanceIdentifier: url }) {
  const app2 = container.getProvider("app").getImmediate();
  const authProvider = container.getProvider("auth-internal");
  const appCheckProvider = container.getProvider("app-check-internal");
  return new FirebaseStorageImpl(app2, authProvider, appCheckProvider, url, SDK_VERSION$1);
}
__name(factory, "factory");
function registerStorage() {
  _registerComponent(new Component(
    STORAGE_TYPE,
    factory,
    "PUBLIC"
    /* ComponentType.PUBLIC */
  ).setMultipleInstances(true));
  registerVersion(name$6, version, "");
  registerVersion(name$6, version, "esm2017");
}
__name(registerStorage, "registerStorage");
registerStorage();
const _initialStatesMap = /* @__PURE__ */ new WeakMap();
function useSSRInitialState(initialState, firebaseApp2) {
  if (!_initialStatesMap.has(firebaseApp2)) {
    _initialStatesMap.set(
      firebaseApp2,
      initialState || { f: {}, r: {}, s: {}, u: {} }
    );
  }
  return _initialStatesMap.get(firebaseApp2);
}
__name(useSSRInitialState, "useSSRInitialState");
function getInitialValue(dataSource, ssrKey, fallbackValue, firebaseApp2) {
  if (!dataSource)
    return fallbackValue;
  const [sourceType, path] = getDataSourceInfo(dataSource);
  if (!sourceType)
    return fallbackValue;
  const initialState = useSSRInitialState(void 0, firebaseApp2)[sourceType] || {};
  const key = ssrKey || path;
  return key && key in initialState ? initialState[key] : fallbackValue;
}
__name(getInitialValue, "getInitialValue");
function deferInitialValueSetup(dataSource, ssrKey, promise, firebaseApp2) {
  if (!dataSource)
    return;
  const [sourceType, path] = getDataSourceInfo(dataSource);
  if (!sourceType)
    return;
  const initialState = useSSRInitialState(
    void 0,
    firebaseApp2
  )[sourceType];
  const key = ssrKey || path;
  if (key) {
    promise.then((value) => {
      initialState[key] = value;
    }).catch(noop$4);
    return key;
  }
}
__name(deferInitialValueSetup, "deferInitialValueSetup");
function getDataSourceInfo(dataSource) {
  return isFirestoreDataReference(dataSource) || isFirestoreQuery(dataSource) ? ["f", dataSource.path] : isDatabaseReference(dataSource) ? ["r", dataSource.toString()] : isStorageReference(dataSource) ? ["s", dataSource.toString()] : [];
}
__name(getDataSourceInfo, "getDataSourceInfo");
const appPendingPromises = /* @__PURE__ */ new WeakMap();
function addPendingPromise(promise, dataSource, ssrKey) {
  const app2 = useFirebaseApp();
  if (!appPendingPromises.has(app2)) {
    appPendingPromises.set(app2, /* @__PURE__ */ new Map());
  }
  const pendingPromises = appPendingPromises.get(app2);
  const key = deferInitialValueSetup(dataSource, ssrKey, promise, app2);
  if (key) {
    pendingPromises.set(key, promise);
  } else {
    if (false) {
      console.warn("[VueFire SSR]: Could not get the path of the data source");
    }
  }
  return key ? () => pendingPromises.delete(key) : noop$4;
}
__name(addPendingPromise, "addPendingPromise");
function usePendingPromises(app2) {
  app2 = app2 || useFirebaseApp();
  const pendingPromises = appPendingPromises.get(app2);
  const p2 = pendingPromises ? Promise.all(
    Array.from(pendingPromises).map(
      ([key, promise]) => promise.then((data) => [key, data])
    )
  ) : Promise.resolve([]);
  appPendingPromises.delete(app2);
  return p2;
}
__name(usePendingPromises, "usePendingPromises");
function createRecordFromDatabaseSnapshot(snapshot2) {
  if (!snapshot2.exists())
    return null;
  const value = snapshot2.val();
  return isObject$d(value) ? Object.defineProperty(value, "id", {
    // allow destructuring without interfering without using the `id` property
    value: snapshot2.key
  }) : {
    // if the value is a primitive we can just return a regular object, it's easier to debug
    // @ts-expect-error: $value doesn't exist
    $value: value,
    id: snapshot2.key
  };
}
__name(createRecordFromDatabaseSnapshot, "createRecordFromDatabaseSnapshot");
function indexForKey(array, key) {
  for (let i2 = 0; i2 < array.length; i2++) {
    if (array[i2].id === key)
      return i2;
  }
  return -1;
}
__name(indexForKey, "indexForKey");
const DEFAULT_OPTIONS$1 = {
  reset: false,
  serialize: createRecordFromDatabaseSnapshot,
  wait: true
};
function bindAsObject(target, document2, resolve2, reject, extraOptions) {
  const options2 = Object.assign({}, DEFAULT_OPTIONS$1, extraOptions);
  let unsubscribe = noop$4;
  function onValueCallback(snapshot2) {
    const value = options2.serialize(snapshot2);
    target.value = value;
    resolve2(value);
  }
  __name(onValueCallback, "onValueCallback");
  if (options2.once) {
    get$3(document2).then(onValueCallback).catch(reject);
  } else {
    unsubscribe = onValue(document2, onValueCallback, reject);
  }
  return (reset2) => {
    unsubscribe();
    if (reset2) {
      const value = typeof reset2 === "function" ? reset2() : null;
      target.value = value;
    }
  };
}
__name(bindAsObject, "bindAsObject");
function bindAsArray(target, collection2, resolve2, reject, extraOptions) {
  const options2 = Object.assign({}, DEFAULT_OPTIONS$1, extraOptions);
  let arrayRef = options2.wait ? [] : target;
  if (!options2.wait) {
    target.value = [];
  }
  let removeChildAddedListener = noop$4;
  let removeChildChangedListener = noop$4;
  let removeChildRemovedListener = noop$4;
  let removeChildMovedListener = noop$4;
  let removeValueListener = noop$4;
  if (options2.once) {
    get$3(collection2).then((data) => {
      const array = [];
      data.forEach((snapshot2) => {
        array.push(options2.serialize(snapshot2));
      });
      resolve2(target.value = array);
    }).catch(reject);
  } else {
    removeChildAddedListener = onChildAdded(
      collection2,
      (snapshot2, prevKey) => {
        const array = toValue$4(arrayRef);
        const index2 = prevKey ? indexForKey(array, prevKey) + 1 : 0;
        array.splice(index2, 0, options2.serialize(snapshot2));
      },
      reject
    );
    removeChildRemovedListener = onChildRemoved(
      collection2,
      (snapshot2) => {
        const array = toValue$4(arrayRef);
        array.splice(indexForKey(array, snapshot2.key), 1);
      },
      reject
    );
    removeChildChangedListener = onChildChanged(
      collection2,
      (snapshot2) => {
        const array = toValue$4(arrayRef);
        array.splice(
          indexForKey(array, snapshot2.key),
          1,
          // cannot be null because it exists
          options2.serialize(snapshot2)
        );
      },
      reject
    );
    removeChildMovedListener = onChildMoved(
      collection2,
      (snapshot2, prevKey) => {
        const array = toValue$4(arrayRef);
        const index2 = indexForKey(array, snapshot2.key);
        const oldRecord = array.splice(index2, 1)[0];
        const newIndex = prevKey ? indexForKey(array, prevKey) + 1 : 0;
        array.splice(newIndex, 0, oldRecord);
      },
      reject
    );
    removeValueListener = onValue(
      collection2,
      () => {
        const array = toValue$4(arrayRef);
        if (options2.wait) {
          target.value = array;
          arrayRef = target;
        }
        resolve2(array);
        removeValueListener();
      },
      reject
    );
  }
  return (reset2) => {
    removeValueListener();
    removeChildAddedListener();
    removeChildRemovedListener();
    removeChildChangedListener();
    removeChildMovedListener();
    if (reset2) {
      const value = typeof reset2 === "function" ? reset2() : [];
      target.value = value;
    }
  };
}
__name(bindAsArray, "bindAsArray");
function _useDatabaseRef(reference2, localOptions = {}, isList2 = false) {
  let unbind = noop$4;
  const options2 = Object.assign({}, DEFAULT_OPTIONS$1, localOptions);
  const initialSourceValue = toValue$4(reference2);
  const data = options2.target || ref$3();
  if (false) {
    if (options2.target && checkWrittenTarget(data, "useDatabaseObject()/useDatabaseList()")) {
      return data;
    }
  }
  const isSSR = useIsSSR();
  if (isSSR) {
    options2.once = true;
  }
  const initialValue = getInitialValue(
    initialSourceValue,
    options2.ssrKey,
    data.value,
    useFirebaseApp()
  );
  data.value = initialValue;
  const hasInitialValue = isList2 ? (initialValue || []).length > 0 : initialValue !== void 0;
  let shouldStartAsPending = !hasInitialValue;
  const error2 = ref$3();
  const pending = ref$3(false);
  const promise = shallowRef();
  const hasCurrentScope = getCurrentScope$1();
  let removePendingPromise = noop$4;
  function bindDatabaseRef() {
    const referenceValue = toValue$4(reference2);
    const newPromise = new Promise((resolve2, reject) => {
      unbind(options2.reset);
      if (!referenceValue) {
        unbind = noop$4;
        return resolve2(null);
      }
      pending.value = shouldStartAsPending;
      shouldStartAsPending = true;
      if (Array.isArray(data.value)) {
        unbind = bindAsArray(
          data,
          referenceValue,
          resolve2,
          reject,
          options2
        );
      } else {
        unbind = bindAsObject(data, referenceValue, resolve2, reject, options2);
      }
    }).catch((reason) => {
      if (promise.value === newPromise) {
        error2.value = reason;
      }
      throw reason;
    }).finally(() => {
      if (promise.value === newPromise) {
        pending.value = false;
      }
    });
    promise.value = newPromise;
  }
  __name(bindDatabaseRef, "bindDatabaseRef");
  let stopWatcher = noop$4;
  if (isRef(reference2) || typeof reference2 === "function") {
    stopWatcher = watch(reference2, bindDatabaseRef);
  }
  bindDatabaseRef();
  if (initialSourceValue) {
    removePendingPromise = addPendingPromise(
      promise.value,
      initialSourceValue,
      options2.ssrKey
    );
  }
  if (hasCurrentScope) {
    onScopeDispose(stop2);
    if (getCurrentInstance()) {
      onServerPrefetch(() => promise.value);
    }
  }
  function stop2(reset2 = options2.reset) {
    stopWatcher();
    removePendingPromise();
    unbind(reset2);
  }
  __name(stop2, "stop");
  return Object.defineProperties(data, {
    // allow destructuring without interfering with the ref itself
    data: { get: /* @__PURE__ */ __name(() => data, "get") },
    error: { get: /* @__PURE__ */ __name(() => error2, "get") },
    pending: { get: /* @__PURE__ */ __name(() => pending, "get") },
    promise: { get: /* @__PURE__ */ __name(() => promise, "get") },
    stop: { get: /* @__PURE__ */ __name(() => stop2, "get") }
  });
}
__name(_useDatabaseRef, "_useDatabaseRef");
function useDatabaseList(reference2, options2) {
  const data = ref$3([]);
  return _useDatabaseRef(
    reference2,
    {
      target: data,
      ...options2
    },
    true
  );
}
__name(useDatabaseList, "useDatabaseList");
const useList = useDatabaseList;
function useDatabaseObject(reference2, options2) {
  const data = ref$3();
  return _useDatabaseRef(reference2, {
    target: data,
    ...options2
  });
}
__name(useDatabaseObject, "useDatabaseObject");
const useObject = useDatabaseObject;
function useDatabase(name2) {
  return getDatabase(useFirebaseApp(name2));
}
__name(useDatabase, "useDatabase");
const firestoreDefaultConverter = {
  toFirestore(data) {
    return data;
  },
  fromFirestore(snapshot2, options2) {
    return snapshot2.exists() ? Object.defineProperties(snapshot2.data(options2), {
      id: { value: snapshot2.id }
      // TODO: check if worth adding or should be through an option
      // It could also be an example in the docs about converters
      // $meta: {
      //   value: snapshot.metadata,
      // },
      // $ref: { get: () => snapshot.ref },
    }) : null;
  }
};
function extractRefs(doc2, oldDoc, subs, options2) {
  if (!isPOJO(doc2))
    return [doc2, {}];
  const dataAndRefs = [
    {},
    {}
  ];
  const subsByPath = Object.keys(subs).reduce(
    (resultSubs, subKey) => {
      const sub = subs[subKey];
      resultSubs[sub.path] = sub.data();
      return resultSubs;
    },
    {}
  );
  function recursiveExtract(doc22, oldDoc2, path, result) {
    oldDoc2 = oldDoc2 || {};
    const [data, refs] = result;
    Object.getOwnPropertyNames(doc22).forEach((propertyName) => {
      const descriptor = Object.getOwnPropertyDescriptor(doc22, propertyName);
      if (descriptor && !descriptor.enumerable) {
        Object.defineProperty(data, propertyName, descriptor);
      }
    });
    for (const key in doc22) {
      const ref2 = doc22[key];
      if (
        // primitives
        ref2 == null || // TODO: check and remove
        // Firestore < 4.13
        ref2 instanceof Date || ref2 instanceof Timestamp || ref2 instanceof GeoPoint
      ) {
        data[key] = ref2;
      } else if (isDocumentRef(ref2)) {
        const refSubKey = path + key;
        data[key] = // if the ref was already bound, keep the same object
        // otherwise set the path as a string so it can be bound later
        // https://github.com/vuejs/vuefire/issues/831
        // https://github.com/vuejs/vuefire/pull/1223
        refSubKey in subs ? oldDoc2[key] : ref2.path;
        refs[refSubKey] = ref2.converter ? ref2 : ref2.withConverter(
          options2.converter
        );
      } else if (Array.isArray(ref2)) {
        data[key] = Array(ref2.length);
        for (let i2 = 0; i2 < ref2.length; i2++) {
          const newRef = ref2[i2];
          if (newRef && newRef.path in subsByPath)
            data[key][i2] = subsByPath[newRef.path];
        }
        recursiveExtract(ref2, oldDoc2[key] || data[key], path + key + ".", [
          data[key],
          refs
        ]);
      } else if (isObject$d(ref2)) {
        data[key] = {};
        recursiveExtract(ref2, oldDoc2[key], path + key + ".", [data[key], refs]);
      } else {
        data[key] = ref2;
      }
    }
  }
  __name(recursiveExtract, "recursiveExtract");
  recursiveExtract(doc2, oldDoc, "", dataAndRefs);
  return dataAndRefs;
}
__name(extractRefs, "extractRefs");
const devalueCustomStringifiers = {
  TimeStamp: /* @__PURE__ */ __name((data) => data instanceof Timestamp && data.toJSON(), "TimeStamp"),
  GeoPoint: /* @__PURE__ */ __name((data) => data instanceof GeoPoint && data.toJSON(), "GeoPoint")
};
const devalueCustomParsers = {
  TimeStamp: /* @__PURE__ */ __name((data) => new Timestamp(data.seconds, data.nanoseconds), "TimeStamp"),
  GeoPoint: /* @__PURE__ */ __name((data) => new GeoPoint(data.latitude, data.longitude), "GeoPoint")
};
const DEFAULT_OPTIONS$2 = {
  reset: false,
  wait: true,
  maxRefDepth: 2,
  converter: firestoreDefaultConverter,
  snapshotOptions: { serverTimestamps: "estimate" }
};
function unsubscribeAll(subs) {
  for (const sub in subs) {
    subs[sub].unsub();
  }
}
__name(unsubscribeAll, "unsubscribeAll");
function updateDataFromDocumentSnapshot(options2, target, path, snapshot2, subs, ops2, depth, resolve2, reject) {
  const [data, refs] = extractRefs(
    // Pass snapshot options
    // @ts-expect-error: FIXME: use better types
    snapshot2.data(options2.snapshotOptions),
    walkGet(target, path),
    subs,
    options2
  );
  ops2.set(target, path, data);
  subscribeToRefs(
    options2,
    target,
    path,
    subs,
    refs,
    ops2,
    depth,
    resolve2,
    reject
  );
}
__name(updateDataFromDocumentSnapshot, "updateDataFromDocumentSnapshot");
function subscribeToDocument({
  ref: ref2,
  target,
  path,
  depth,
  resolve: resolve2,
  reject,
  ops: ops2
}, options2) {
  const subs = /* @__PURE__ */ Object.create(null);
  let unbind = noop$4;
  if (options2.once) {
    getDoc(ref2).then((snapshot2) => {
      if (snapshot2.exists()) {
        updateDataFromDocumentSnapshot(
          options2,
          target,
          path,
          snapshot2,
          subs,
          ops2,
          depth,
          resolve2,
          reject
        );
      } else {
        ops2.set(target, path, null);
        resolve2();
      }
    }).catch(reject);
  } else {
    unbind = onSnapshot(
      ref2,
      (snapshot2) => {
        if (snapshot2.exists()) {
          updateDataFromDocumentSnapshot(
            options2,
            target,
            path,
            snapshot2,
            subs,
            ops2,
            depth,
            resolve2,
            reject
          );
        } else {
          ops2.set(target, path, null);
          resolve2();
        }
      },
      reject
    );
  }
  return () => {
    unbind();
    unsubscribeAll(subs);
  };
}
__name(subscribeToDocument, "subscribeToDocument");
function subscribeToRefs(options2, target, path, subs, refs, ops2, depth, resolve2, reject) {
  const refKeys = Object.keys(refs);
  const missingKeys = Object.keys(subs).filter(
    (refKey) => refKeys.indexOf(refKey) < 0
  );
  missingKeys.forEach((refKey) => {
    subs[refKey].unsub();
    delete subs[refKey];
  });
  if (!refKeys.length || ++depth > options2.maxRefDepth)
    return resolve2(path);
  let resolvedCount = 0;
  const totalToResolve = refKeys.length;
  const validResolves = /* @__PURE__ */ Object.create(null);
  function deepResolve(key) {
    if (key in validResolves) {
      if (++resolvedCount >= totalToResolve)
        resolve2(path);
    }
  }
  __name(deepResolve, "deepResolve");
  refKeys.forEach((refKey) => {
    const sub = subs[refKey];
    const ref2 = refs[refKey];
    const docPath = `${path}.${refKey}`;
    validResolves[docPath] = true;
    if (sub) {
      if (sub.path !== ref2.path)
        sub.unsub();
      else
        return;
    }
    subs[refKey] = {
      data: /* @__PURE__ */ __name(() => walkGet(target, docPath), "data"),
      unsub: subscribeToDocument(
        {
          ref: ref2,
          target,
          path: docPath,
          depth,
          ops: ops2,
          resolve: deepResolve.bind(null, docPath),
          reject
        },
        options2
      ),
      path: ref2.path
    };
  });
}
__name(subscribeToRefs, "subscribeToRefs");
function bindCollection(target, collection2, ops2, resolve2, reject, extraOptions) {
  const options2 = Object.assign({}, DEFAULT_OPTIONS$2, extraOptions);
  const { snapshotListenOptions, snapshotOptions, wait, once: once2 } = options2;
  const key = "value";
  let arrayRef = ref$3(wait ? [] : target.value);
  if (!wait)
    ops2.set(target, key, []);
  const originalResolve = resolve2;
  let isResolved;
  let stopOnSnapshot = noop$4;
  const arraySubs = [];
  const change = {
    added: /* @__PURE__ */ __name(({ newIndex, doc: doc2 }) => {
      arraySubs.splice(newIndex, 0, /* @__PURE__ */ Object.create(null));
      const subs = arraySubs[newIndex];
      const [data, refs] = extractRefs(
        // @ts-expect-error: FIXME: wrong cast, needs better types
        doc2.data(snapshotOptions),
        void 0,
        subs,
        options2
      );
      ops2.add(toValue$4(arrayRef), newIndex, data);
      subscribeToRefs(
        options2,
        arrayRef,
        `${key}.${newIndex}`,
        subs,
        refs,
        ops2,
        0,
        resolve2.bind(null, doc2),
        reject
      );
    }, "added"),
    modified: /* @__PURE__ */ __name(({ oldIndex, newIndex, doc: doc2 }) => {
      const array = toValue$4(arrayRef);
      const subs = arraySubs[oldIndex];
      const oldData = array[oldIndex];
      const [data, refs] = extractRefs(
        // @ts-expect-error: FIXME: Better types
        doc2.data(snapshotOptions),
        oldData,
        subs,
        options2
      );
      arraySubs.splice(newIndex, 0, subs);
      ops2.remove(array, oldIndex);
      ops2.add(array, newIndex, data);
      subscribeToRefs(
        options2,
        arrayRef,
        `${key}.${newIndex}`,
        subs,
        refs,
        ops2,
        0,
        resolve2,
        reject
      );
    }, "modified"),
    removed: /* @__PURE__ */ __name(({ oldIndex }) => {
      const array = toValue$4(arrayRef);
      ops2.remove(array, oldIndex);
      unsubscribeAll(arraySubs.splice(oldIndex, 1)[0]);
    }, "removed")
  };
  function onSnapshotCallback(snapshot2) {
    const docChanges = snapshot2.docChanges(snapshotListenOptions);
    if (!isResolved && docChanges.length) {
      isResolved = true;
      let count2 = 0;
      const expectedItems = docChanges.length;
      const validDocs = /* @__PURE__ */ Object.create(null);
      for (let i2 = 0; i2 < expectedItems; i2++) {
        validDocs[docChanges[i2].doc.id] = true;
      }
      resolve2 = /* @__PURE__ */ __name((data) => {
        if (data && data.id in validDocs) {
          if (++count2 >= expectedItems) {
            if (wait) {
              ops2.set(target, key, toValue$4(arrayRef));
              arrayRef = target;
            }
            originalResolve(toValue$4(arrayRef));
            resolve2 = noop$4;
          }
        }
      }, "resolve");
    }
    docChanges.forEach((c2) => {
      change[c2.type](c2);
    });
    if (!docChanges.length) {
      if (wait) {
        ops2.set(target, key, toValue$4(arrayRef));
        arrayRef = target;
      }
      resolve2(toValue$4(arrayRef));
    }
  }
  __name(onSnapshotCallback, "onSnapshotCallback");
  if (once2) {
    getDocs(collection2).then(onSnapshotCallback).catch(reject);
  } else {
    stopOnSnapshot = onSnapshot(collection2, onSnapshotCallback, reject);
  }
  return (reset2) => {
    stopOnSnapshot();
    if (reset2) {
      const value = typeof reset2 === "function" ? reset2() : [];
      ops2.set(target, key, value);
    }
    arraySubs.forEach(unsubscribeAll);
  };
}
__name(bindCollection, "bindCollection");
function bindDocument(target, document2, ops2, resolve2, reject, extraOptions) {
  const options2 = Object.assign({}, DEFAULT_OPTIONS$2, extraOptions);
  const key = "value";
  const subs = /* @__PURE__ */ Object.create(null);
  resolve2 = callOnceWithArg(resolve2, () => walkGet(target, key));
  let stopOnSnapshot = noop$4;
  function onSnapshotCallback(snapshot2) {
    if (snapshot2.exists()) {
      updateDataFromDocumentSnapshot(
        options2,
        target,
        key,
        snapshot2,
        subs,
        ops2,
        0,
        resolve2,
        reject
      );
    } else {
      ops2.set(target, key, null);
      resolve2(null);
    }
  }
  __name(onSnapshotCallback, "onSnapshotCallback");
  if (options2.once) {
    getDoc(document2).then(onSnapshotCallback).catch(reject);
  } else {
    stopOnSnapshot = onSnapshot(document2, onSnapshotCallback, reject);
  }
  return (reset2) => {
    stopOnSnapshot();
    if (reset2) {
      const value = typeof reset2 === "function" ? reset2() : null;
      ops2.set(target, key, value);
    }
    unsubscribeAll(subs);
  };
}
__name(bindDocument, "bindDocument");
const NO_INITIAL_VALUE = Symbol();
function _useFirestoreRef(docOrCollectionRef, localOptions) {
  let unbind = noop$4;
  const options2 = Object.assign({}, DEFAULT_OPTIONS$2, localOptions);
  const initialSourceValue = toValue$4(docOrCollectionRef);
  const data = options2.target || ref$3();
  if (false) {
    if (options2.target && checkWrittenTarget(data, "useDocument()/useCollection()")) {
      return data;
    }
  }
  if (useIsSSR()) {
    options2.once = true;
  }
  const initialValue = getInitialValue(
    initialSourceValue,
    options2.ssrKey,
    NO_INITIAL_VALUE,
    useFirebaseApp()
  );
  const hasInitialValue = initialValue !== NO_INITIAL_VALUE;
  if (hasInitialValue) {
    data.value = initialValue;
  }
  let shouldStartAsPending = !hasInitialValue;
  const pending = ref$3(false);
  const error2 = ref$3();
  const promise = shallowRef();
  const hasCurrentScope = getCurrentScope$1();
  let removePendingPromise = noop$4;
  function bindFirestoreRef() {
    let docRefValue = toValue$4(docOrCollectionRef);
    const newPromise = new Promise((resolve2, reject) => {
      unbind(options2.reset);
      if (!docRefValue) {
        unbind = noop$4;
        return resolve2(null);
      }
      pending.value = shouldStartAsPending;
      shouldStartAsPending = true;
      if (!docRefValue.converter) {
        docRefValue = docRefValue.withConverter(
          // @ts-expect-error: seems like a ts error
          options2.converter
        );
      }
      unbind = (isDocumentRef(docRefValue) ? bindDocument : bindCollection)(
        // @ts-expect-error: cannot type with the ternary
        data,
        docRefValue,
        ops,
        resolve2,
        reject,
        options2
      );
    }).catch((reason) => {
      if (promise.value === newPromise) {
        error2.value = reason;
      }
      return Promise.reject(reason);
    }).finally(() => {
      if (promise.value === newPromise) {
        pending.value = false;
      }
    });
    promise.value = newPromise;
  }
  __name(bindFirestoreRef, "bindFirestoreRef");
  let stopWatcher = noop$4;
  if (isRef(docOrCollectionRef) || typeof docOrCollectionRef === "function") {
    stopWatcher = watch(docOrCollectionRef, bindFirestoreRef);
  }
  bindFirestoreRef();
  if (initialSourceValue) {
    removePendingPromise = addPendingPromise(
      promise.value,
      initialSourceValue,
      options2.ssrKey
    );
  }
  if (getCurrentInstance()) {
    onServerPrefetch(() => promise.value);
  }
  if (hasCurrentScope) {
    onScopeDispose(stop2);
  }
  function stop2(reset2 = options2.reset) {
    stopWatcher();
    removePendingPromise();
    unbind(reset2);
  }
  __name(stop2, "stop");
  return Object.defineProperties(data, {
    error: { get: /* @__PURE__ */ __name(() => error2, "get") },
    data: { get: /* @__PURE__ */ __name(() => data, "get") },
    pending: { get: /* @__PURE__ */ __name(() => pending, "get") },
    promise: { get: /* @__PURE__ */ __name(() => promise, "get") },
    stop: { get: /* @__PURE__ */ __name(() => stop2, "get") }
  });
}
__name(_useFirestoreRef, "_useFirestoreRef");
const ops = {
  set: /* @__PURE__ */ __name((target, key, value) => walkSet(target, key, value), "set"),
  add: /* @__PURE__ */ __name((array, index2, data) => array.splice(index2, 0, data), "add"),
  remove: /* @__PURE__ */ __name((array, index2) => array.splice(index2, 1), "remove")
};
function useCollection(collectionRef, options2) {
  return _useFirestoreRef(collectionRef, {
    target: ref$3([]),
    ...options2
  });
}
__name(useCollection, "useCollection");
function useDocument(documentRef, options2) {
  return _useFirestoreRef(documentRef, options2);
}
__name(useDocument, "useDocument");
function useFirestore(name2) {
  return getFirestore(useFirebaseApp(name2));
}
__name(useFirestore, "useFirestore");
const databaseUnbinds = /* @__PURE__ */ new WeakMap();
function internalUnbind$1(key, unbinds, reset2) {
  if (unbinds && unbinds[key]) {
    unbinds[key](reset2);
    delete unbinds[key];
  }
}
__name(internalUnbind$1, "internalUnbind$1");
const databasePluginDefaults = {
  bindName: "$databaseBind",
  unbindName: "$databaseUnbind"
};
function databasePlugin(app2, pluginOptions, firebaseApp2) {
  const globalOptions = Object.assign({}, databasePluginDefaults, pluginOptions);
  const { bindName, unbindName } = globalOptions;
  const GlobalTarget = isVue3 ? app2.config.globalProperties : app2.prototype;
  GlobalTarget[unbindName] = /* @__PURE__ */ __name(function databaseUnbind(key, reset2) {
    internalUnbind$1(key, databaseUnbinds.get(this), reset2);
    delete this.$firebaseRefs[key];
  }, "databaseUnbind");
  GlobalTarget[bindName] = /* @__PURE__ */ __name(function databaseBind(key, source, userOptions) {
    const options2 = Object.assign({}, globalOptions, userOptions);
    const target = toRef$1(this.$data, key);
    if (!databaseUnbinds.has(this)) {
      databaseUnbinds.set(this, {});
    }
    const unbinds = databaseUnbinds.get(this);
    if (unbinds[key]) {
      unbinds[key](options2.reset);
    }
    if (pluginOptions) {
      if (!pluginOptions.bindName) {
        GlobalTarget["$rtdbBind"] = GlobalTarget[bindName];
      }
      if (!pluginOptions.unbindName) {
        GlobalTarget["$rtdbUnbind"] = GlobalTarget[unbindName];
      }
    }
    const scope = getGlobalScope(firebaseApp2 || useFirebaseApp(), app2).run(
      () => effectScope()
    );
    const { promise, stop: _unbind } = app2.runWithContext(
      () => scope.run(() => _useDatabaseRef(source, { target, ...options2 }))
    );
    const unbind = /* @__PURE__ */ __name((reset2) => {
      _unbind(reset2);
      scope.stop();
    }, "unbind");
    unbinds[key] = unbind;
    this.$firebaseRefs[key] = source.ref;
    return promise.value;
  }, "databaseBind");
  app2.mixin({
    beforeCreate() {
      this.$firebaseRefs = /* @__PURE__ */ Object.create(null);
    },
    created() {
      let bindings = this.$options.firebase;
      if (typeof bindings === "function") {
        bindings = bindings.call(this);
      }
      if (!bindings)
        return;
      for (const key in bindings) {
        this[bindName](
          // ts
          key,
          bindings[key],
          globalOptions
        );
      }
    },
    beforeUnmount() {
      const unbinds = databaseUnbinds.get(this);
      if (unbinds) {
        for (const key in unbinds) {
          unbinds[key]();
        }
      }
      this.$firebaseRefs = null;
    }
  });
}
__name(databasePlugin, "databasePlugin");
function VueFireDatabaseOptionsAPI(pluginOptions) {
  return (firebaseApp2, app2) => {
    return databasePlugin(app2, pluginOptions, firebaseApp2);
  };
}
__name(VueFireDatabaseOptionsAPI, "VueFireDatabaseOptionsAPI");
const firestoreUnbinds = /* @__PURE__ */ new WeakMap();
function internalUnbind(key, unbinds, reset2) {
  if (unbinds && unbinds[key]) {
    unbinds[key](reset2);
    delete unbinds[key];
  }
}
__name(internalUnbind, "internalUnbind");
const firestorePluginDefaults = {
  bindName: "$firestoreBind",
  unbindName: "$firestoreUnbind"
};
const firestorePlugin = /* @__PURE__ */ __name(function firestorePlugin2(app2, pluginOptions, firebaseApp2) {
  const globalOptions = Object.assign(
    {},
    firestorePluginDefaults,
    pluginOptions
  );
  const { bindName, unbindName } = globalOptions;
  const GlobalTarget = isVue3 ? app2.config.globalProperties : app2.prototype;
  GlobalTarget[unbindName] = /* @__PURE__ */ __name(function firestoreUnbind(key, reset2) {
    internalUnbind(key, firestoreUnbinds.get(this), reset2);
    delete this.$firestoreRefs[key];
  }, "firestoreUnbind");
  GlobalTarget[bindName] = /* @__PURE__ */ __name(function firestoreBind(key, docOrCollectionRef, userOptions) {
    const options2 = Object.assign({}, globalOptions, userOptions);
    const target = toRef$1(this.$data, key);
    if (!firestoreUnbinds.has(this)) {
      firestoreUnbinds.set(this, {});
    }
    const unbinds = firestoreUnbinds.get(this);
    if (unbinds[key]) {
      unbinds[key](options2.reset);
    }
    const scope = getGlobalScope(firebaseApp2 || useFirebaseApp(), app2).run(
      () => effectScope()
    );
    const { promise, stop: _unbind } = app2.runWithContext(
      () => scope.run(
        () => _useFirestoreRef(docOrCollectionRef, {
          target,
          ...options2
        })
      )
    );
    const unbind = /* @__PURE__ */ __name((reset2) => {
      _unbind(reset2);
      scope.stop();
    }, "unbind");
    unbinds[key] = unbind;
    this.$firestoreRefs[key] = // ts
    docOrCollectionRef;
    return promise.value;
  }, "firestoreBind");
  app2.mixin({
    beforeCreate() {
      this.$firestoreRefs = /* @__PURE__ */ Object.create(null);
    },
    created() {
      const { firestore } = this.$options;
      const refs = typeof firestore === "function" ? firestore.call(this) : firestore;
      if (!refs)
        return;
      for (const key in refs) {
        this[bindName](
          key,
          // @ts-expect-error: FIXME: there is probably a wrong type in global properties
          refs[key],
          globalOptions
        );
      }
    },
    beforeUnmount() {
      const unbinds = firestoreUnbinds.get(this);
      if (unbinds) {
        for (const subKey in unbinds) {
          unbinds[subKey]();
        }
      }
      this.$firestoreRefs = null;
    }
  });
}, "firestorePlugin2");
function VueFireFirestoreOptionsAPI(pluginOptions) {
  return (firebaseApp2, app2) => {
    return firestorePlugin(app2, pluginOptions, firebaseApp2);
  };
}
__name(VueFireFirestoreOptionsAPI, "VueFireFirestoreOptionsAPI");
function VueFireAuth(initialUser) {
  return VueFireAuthWithDependencies({
    initialUser,
    dependencies: {
      popupRedirectResolver: browserPopupRedirectResolver,
      persistence: [
        indexedDBLocalPersistence,
        browserLocalPersistence,
        browserSessionPersistence
      ]
    }
  });
}
__name(VueFireAuth, "VueFireAuth");
const _VueFireAuthKey = Symbol("VueFireAuth");
function VueFireAuthOptionsFromAuth({
  auth: auth2,
  initialUser
}) {
  return (firebaseApp2, app2) => {
    const [user, _auth] = _VueFireAuthInit(
      firebaseApp2,
      app2,
      initialUser,
      void 0,
      auth2
    );
    setupOnAuthStateChanged(user, _auth);
  };
}
__name(VueFireAuthOptionsFromAuth, "VueFireAuthOptionsFromAuth");
function VueFireAuthWithDependencies({
  dependencies,
  initialUser
}) {
  return (firebaseApp2, app2) => {
    const [user, auth2] = _VueFireAuthInit(
      firebaseApp2,
      app2,
      initialUser,
      dependencies
    );
    setupOnAuthStateChanged(user, auth2);
  };
}
__name(VueFireAuthWithDependencies, "VueFireAuthWithDependencies");
function _VueFireAuthInit(firebaseApp2, app2, initialUser, dependencies, auth2 = initializeAuth(firebaseApp2, dependencies)) {
  const user = getGlobalScope(firebaseApp2, app2).run(
    () => ref$3(initialUser)
  );
  authUserMap.set(firebaseApp2, user);
  app2.provide(_VueFireAuthKey, auth2);
  return [user, auth2];
}
__name(_VueFireAuthInit, "_VueFireAuthInit");
function useFirebaseAuth(name2) {
  if (false) {
    console.warn(
      `[VueFire] useFirebaseAuth() no longer accepts a name parameter to enable tree shaking. If you have multiple applications, you must use "getAuth(firebaseApp)" or "getAuth(useFirebaseApp(name))" instead.`
    );
  }
  return isClient$2 ? inject(_VueFireAuthKey) : null;
}
__name(useFirebaseAuth, "useFirebaseAuth");
function useFirebaseStorage(name2) {
  return getStorage(useFirebaseApp(name2));
}
__name(useFirebaseStorage, "useFirebaseStorage");
function useStorageFileUrl(storageRef) {
  const initialSourceValue = toValue$4(storageRef);
  const url = ref$3();
  url.value = getInitialValue(
    initialSourceValue,
    void 0,
    url.value,
    useFirebaseApp()
  );
  const promise = shallowRef(Promise.resolve(null));
  let removePendingPromise = noop$4;
  function refresh() {
    const storageSource = toValue$4(storageRef);
    if (storageSource) {
      promise.value = getDownloadURL(storageSource).then((downloadUrl) => url.value = downloadUrl).catch(() => null);
    } else {
      promise.value = Promise.resolve(url.value = null);
    }
    return promise.value;
  }
  __name(refresh, "refresh");
  refresh();
  if (isRef(storageRef) || typeof storageRef === "function") {
    watch(storageRef, refresh);
  }
  if (initialSourceValue) {
    removePendingPromise = addPendingPromise(promise.value, initialSourceValue);
  }
  if (getCurrentScope$1()) {
    onScopeDispose(removePendingPromise);
  }
  if (getCurrentInstance()) {
    onServerPrefetch(() => promise.value);
  }
  return { url, refresh, promise };
}
__name(useStorageFileUrl, "useStorageFileUrl");
function useStorageFileMetadata(storageRef) {
  const initialSourceValue = toValue$4(storageRef);
  const metadata = shallowRef();
  if (initialSourceValue) {
    metadata.value = getInitialValue(
      initialSourceValue,
      // 'm ' is a prefix to differentiate from urls since both are stored in the same object
      "m " + initialSourceValue.toString(),
      metadata.value,
      useFirebaseApp()
    );
  }
  const promise = shallowRef(
    Promise.resolve(null)
  );
  let removePendingPromise = noop$4;
  function refresh() {
    const storageSource = toValue$4(storageRef);
    if (storageSource) {
      promise.value = getMetadata(storageSource).then((data) => metadata.value = data).catch(() => null);
    } else {
      promise.value = Promise.resolve(metadata.value = null);
    }
    return promise.value;
  }
  __name(refresh, "refresh");
  function update2(newMetadata) {
    const storageSource = toValue$4(storageRef);
    if (storageSource) {
      promise.value = updateMetadata(storageSource, newMetadata).then(
        (newData) => {
          return metadata.value = newData;
        }
      );
    } else if (false) {
      console.warn('[VueFire]: "update()" called with no storage source.');
    }
    return promise.value;
  }
  __name(update2, "update");
  refresh();
  if (isRef(storageRef)) {
    watch(storageRef, refresh);
  }
  if (initialSourceValue) {
    removePendingPromise = addPendingPromise(promise.value, initialSourceValue);
  }
  if (getCurrentScope$1()) {
    onScopeDispose(removePendingPromise);
  }
  if (getCurrentInstance()) {
    onServerPrefetch(() => promise.value);
  }
  return { metadata, update: update2, refresh, promise };
}
__name(useStorageFileMetadata, "useStorageFileMetadata");
function useStorageFile(storageRef) {
  const { url, refresh: refreshUrl } = useStorageFileUrl(storageRef);
  const {
    metadata,
    update: updateMetadata2,
    refresh: refreshMetadata
  } = useStorageFileMetadata(storageRef);
  const uploadTask = shallowRef();
  const snapshot2 = shallowRef();
  const uploadError = shallowRef();
  const uploadProgress = computed(() => {
    const snap = toValue$4(snapshot2);
    return snap ? snap.bytesTransferred / snap.totalBytes : null;
  });
  let unsub = noop$4;
  function upload(newData, newMetadata) {
    const storageSource = toValue$4(storageRef);
    const currentTask = toValue$4(uploadTask);
    if (currentTask) {
      currentTask.cancel();
    }
    uploadError.value = null;
    snapshot2.value = null;
    uploadTask.value = null;
    url.value = null;
    metadata.value = null;
    unsub();
    if (storageSource) {
      const newTask = uploadBytesResumable(storageSource, newData, newMetadata);
      uploadTask.value = newTask;
      snapshot2.value = newTask.snapshot;
      unsub = newTask.on("state_changed", (newSnapshot) => {
        snapshot2.value = newSnapshot;
      });
      return newTask.then((finalSnapshot) => {
        metadata.value = finalSnapshot.metadata;
        refreshUrl();
      }).catch((err) => {
        uploadError.value = err;
        return Promise.reject(err);
      }).finally(() => {
        unsub();
        uploadTask.value = null;
      });
    }
  }
  __name(upload, "upload");
  function refresh() {
    return Promise.all([refreshUrl(), refreshMetadata()]);
  }
  __name(refresh, "refresh");
  if (isRef(storageRef) || typeof storageRef === "function") {
    watch(storageRef, (storageSource) => {
      if (!storageSource) {
        if (uploadTask.value) {
          unsub();
          uploadTask.value.cancel();
        }
        uploadTask.value = null;
        snapshot2.value = null;
      }
      refresh();
    });
  }
  if (getCurrentScope$1()) {
    onScopeDispose(unsub);
  }
  return {
    url,
    metadata,
    snapshot: snapshot2,
    uploadTask,
    uploadError,
    uploadProgress,
    upload,
    updateMetadata: updateMetadata2,
    refresh
    // promise,
  };
}
__name(useStorageFile, "useStorageFile");
const useStorage$1 = useFirebaseStorage;
const useStorageUrl = useStorageFileUrl;
const useStorageMetadata = useStorageFileMetadata;
const useStorageObject = useStorageFile;
function VueFire(app2, { firebaseApp: firebaseApp2, modules = [] }) {
  app2.provide(_FirebaseAppInjectionKey, firebaseApp2);
  for (const firebaseModule of modules) {
    firebaseModule(firebaseApp2, app2);
  }
}
__name(VueFire, "VueFire");
const DEV_CONFIG = {
  apiKey: "AIzaSyDa_YMeyzV0SkVe92vBZ1tVikWBmOU5KVE",
  authDomain: "dreamboothy-dev.firebaseapp.com",
  databaseURL: "https://dreamboothy-dev-default-rtdb.firebaseio.com",
  projectId: "dreamboothy-dev",
  storageBucket: "dreamboothy-dev.appspot.com",
  messagingSenderId: "313257147182",
  appId: "1:313257147182:web:be38f6ebf74345fc7618bf",
  measurementId: "G-YEVSMYXSPY"
};
const PROD_CONFIG = {
  apiKey: "AIzaSyC2-fomLqgCjb7ELwta1I9cEarPK8ziTGs",
  authDomain: "dreamboothy.firebaseapp.com",
  databaseURL: "https://dreamboothy-default-rtdb.firebaseio.com",
  projectId: "dreamboothy",
  storageBucket: "dreamboothy.appspot.com",
  messagingSenderId: "357148958219",
  appId: "1:357148958219:web:f5917f72e5f36a2015310e",
  measurementId: "G-3ZBD3MBTG4"
};
const FIREBASE_CONFIG = true ? PROD_CONFIG : DEV_CONFIG;
const scriptRel = "modulepreload";
const assetsURL = /* @__PURE__ */ __name(function(dep, importerUrl) {
  return new URL(dep, importerUrl).href;
}, "assetsURL");
const seen = {};
const __vitePreload = /* @__PURE__ */ __name(function preload(baseModule, deps, importerUrl) {
  let promise = Promise.resolve();
  if (deps && deps.length > 0) {
    const links = document.getElementsByTagName("link");
    const cspNonceMeta = document.querySelector(
      "meta[property=csp-nonce]"
    );
    const cspNonce = cspNonceMeta?.nonce || cspNonceMeta?.getAttribute("nonce");
    promise = Promise.allSettled(
      deps.map((dep) => {
        dep = assetsURL(dep, importerUrl);
        if (dep in seen) return;
        seen[dep] = true;
        const isCss = dep.endsWith(".css");
        const cssSelector = isCss ? '[rel="stylesheet"]' : "";
        const isBaseRelative = !!importerUrl;
        if (isBaseRelative) {
          for (let i2 = links.length - 1; i2 >= 0; i2--) {
            const link22 = links[i2];
            if (link22.href === dep && (!isCss || link22.rel === "stylesheet")) {
              return;
            }
          }
        } else if (document.querySelector(`link[href="${dep}"]${cssSelector}`)) {
          return;
        }
        const link2 = document.createElement("link");
        link2.rel = isCss ? "stylesheet" : scriptRel;
        if (!isCss) {
          link2.as = "script";
        }
        link2.crossOrigin = "";
        link2.href = dep;
        if (cspNonce) {
          link2.setAttribute("nonce", cspNonce);
        }
        document.head.appendChild(link2);
        if (isCss) {
          return new Promise((res, rej) => {
            link2.addEventListener("load", res);
            link2.addEventListener(
              "error",
              () => rej(new Error(`Unable to preload CSS for ${dep}`))
            );
          });
        }
      })
    );
  }
  function handlePreloadError(err) {
    const e2 = new Event("vite:preloadError", {
      cancelable: true
    });
    e2.payload = err;
    window.dispatchEvent(e2);
    if (!e2.defaultPrevented) {
      throw err;
    }
  }
  __name(handlePreloadError, "handlePreloadError");
  return promise.then((res) => {
    for (const item of res || []) {
      if (item.status !== "rejected") continue;
      handlePreloadError(item.reason);
    }
    return baseModule().catch(handlePreloadError);
  });
}, "preload");
/*!
  * vue-router v4.4.3
  * (c) 2024 Eduardo San Martin Morote
  * @license MIT
  */
const isBrowser = typeof document !== "undefined";
function isESModule(obj) {
  return obj.__esModule || obj[Symbol.toStringTag] === "Module";
}
__name(isESModule, "isESModule");
const assign$3 = Object.assign;
function applyToParams(fn, params) {
  const newParams = {};
  for (const key in params) {
    const value = params[key];
    newParams[key] = isArray$9(value) ? value.map(fn) : fn(value);
  }
  return newParams;
}
__name(applyToParams, "applyToParams");
const noop$3 = /* @__PURE__ */ __name(() => {
}, "noop$3");
const isArray$9 = Array.isArray;
function warn$1(msg) {
  const args = Array.from(arguments).slice(1);
  console.warn.apply(console, ["[Vue Router warn]: " + msg].concat(args));
}
__name(warn$1, "warn$1");
const HASH_RE = /#/g;
const AMPERSAND_RE = /&/g;
const SLASH_RE = /\//g;
const EQUAL_RE = /=/g;
const IM_RE = /\?/g;
const PLUS_RE = /\+/g;
const ENC_BRACKET_OPEN_RE = /%5B/g;
const ENC_BRACKET_CLOSE_RE = /%5D/g;
const ENC_CARET_RE = /%5E/g;
const ENC_BACKTICK_RE = /%60/g;
const ENC_CURLY_OPEN_RE = /%7B/g;
const ENC_PIPE_RE = /%7C/g;
const ENC_CURLY_CLOSE_RE = /%7D/g;
const ENC_SPACE_RE = /%20/g;
function commonEncode(text2) {
  return encodeURI("" + text2).replace(ENC_PIPE_RE, "|").replace(ENC_BRACKET_OPEN_RE, "[").replace(ENC_BRACKET_CLOSE_RE, "]");
}
__name(commonEncode, "commonEncode");
function encodeHash(text2) {
  return commonEncode(text2).replace(ENC_CURLY_OPEN_RE, "{").replace(ENC_CURLY_CLOSE_RE, "}").replace(ENC_CARET_RE, "^");
}
__name(encodeHash, "encodeHash");
function encodeQueryValue(text2) {
  return commonEncode(text2).replace(PLUS_RE, "%2B").replace(ENC_SPACE_RE, "+").replace(HASH_RE, "%23").replace(AMPERSAND_RE, "%26").replace(ENC_BACKTICK_RE, "`").replace(ENC_CURLY_OPEN_RE, "{").replace(ENC_CURLY_CLOSE_RE, "}").replace(ENC_CARET_RE, "^");
}
__name(encodeQueryValue, "encodeQueryValue");
function encodeQueryKey(text2) {
  return encodeQueryValue(text2).replace(EQUAL_RE, "%3D");
}
__name(encodeQueryKey, "encodeQueryKey");
function encodePath(text2) {
  return commonEncode(text2).replace(HASH_RE, "%23").replace(IM_RE, "%3F");
}
__name(encodePath, "encodePath");
function encodeParam(text2) {
  return text2 == null ? "" : encodePath(text2).replace(SLASH_RE, "%2F");
}
__name(encodeParam, "encodeParam");
function decode$3(text2) {
  try {
    return decodeURIComponent("" + text2);
  } catch (err) {
  }
  return "" + text2;
}
__name(decode$3, "decode$3");
const TRAILING_SLASH_RE = /\/$/;
const removeTrailingSlash = /* @__PURE__ */ __name((path) => path.replace(TRAILING_SLASH_RE, ""), "removeTrailingSlash");
function parseURL(parseQuery2, location2, currentLocation = "/") {
  let path, query2 = {}, searchString = "", hash = "";
  const hashPos = location2.indexOf("#");
  let searchPos = location2.indexOf("?");
  if (hashPos < searchPos && hashPos >= 0) {
    searchPos = -1;
  }
  if (searchPos > -1) {
    path = location2.slice(0, searchPos);
    searchString = location2.slice(searchPos + 1, hashPos > -1 ? hashPos : location2.length);
    query2 = parseQuery2(searchString);
  }
  if (hashPos > -1) {
    path = path || location2.slice(0, hashPos);
    hash = location2.slice(hashPos, location2.length);
  }
  path = resolveRelativePath(path != null ? path : location2, currentLocation);
  return {
    fullPath: path + (searchString && "?") + searchString + hash,
    path,
    query: query2,
    hash: decode$3(hash)
  };
}
__name(parseURL, "parseURL");
function stringifyURL(stringifyQuery2, location2) {
  const query2 = location2.query ? stringifyQuery2(location2.query) : "";
  return location2.path + (query2 && "?") + query2 + (location2.hash || "");
}
__name(stringifyURL, "stringifyURL");
function stripBase(pathname, base2) {
  if (!base2 || !pathname.toLowerCase().startsWith(base2.toLowerCase()))
    return pathname;
  return pathname.slice(base2.length) || "/";
}
__name(stripBase, "stripBase");
function isSameRouteLocation(stringifyQuery2, a2, b2) {
  const aLastIndex = a2.matched.length - 1;
  const bLastIndex = b2.matched.length - 1;
  return aLastIndex > -1 && aLastIndex === bLastIndex && isSameRouteRecord(a2.matched[aLastIndex], b2.matched[bLastIndex]) && isSameRouteLocationParams(a2.params, b2.params) && stringifyQuery2(a2.query) === stringifyQuery2(b2.query) && a2.hash === b2.hash;
}
__name(isSameRouteLocation, "isSameRouteLocation");
function isSameRouteRecord(a2, b2) {
  return (a2.aliasOf || a2) === (b2.aliasOf || b2);
}
__name(isSameRouteRecord, "isSameRouteRecord");
function isSameRouteLocationParams(a2, b2) {
  if (Object.keys(a2).length !== Object.keys(b2).length)
    return false;
  for (const key in a2) {
    if (!isSameRouteLocationParamsValue(a2[key], b2[key]))
      return false;
  }
  return true;
}
__name(isSameRouteLocationParams, "isSameRouteLocationParams");
function isSameRouteLocationParamsValue(a2, b2) {
  return isArray$9(a2) ? isEquivalentArray(a2, b2) : isArray$9(b2) ? isEquivalentArray(b2, a2) : a2 === b2;
}
__name(isSameRouteLocationParamsValue, "isSameRouteLocationParamsValue");
function isEquivalentArray(a2, b2) {
  return isArray$9(b2) ? a2.length === b2.length && a2.every((value, i2) => value === b2[i2]) : a2.length === 1 && a2[0] === b2;
}
__name(isEquivalentArray, "isEquivalentArray");
function resolveRelativePath(to, from2) {
  if (to.startsWith("/"))
    return to;
  if (false) {
    warn$1(`Cannot resolve a relative location without an absolute path. Trying to resolve "${to}" from "${from2}". It should look like "/${from2}".`);
    return to;
  }
  if (!to)
    return from2;
  const fromSegments = from2.split("/");
  const toSegments = to.split("/");
  const lastToSegment = toSegments[toSegments.length - 1];
  if (lastToSegment === ".." || lastToSegment === ".") {
    toSegments.push("");
  }
  let position = fromSegments.length - 1;
  let toPosition;
  let segment;
  for (toPosition = 0; toPosition < toSegments.length; toPosition++) {
    segment = toSegments[toPosition];
    if (segment === ".")
      continue;
    if (segment === "..") {
      if (position > 1)
        position--;
    } else
      break;
  }
  return fromSegments.slice(0, position).join("/") + "/" + toSegments.slice(toPosition).join("/");
}
__name(resolveRelativePath, "resolveRelativePath");
const START_LOCATION_NORMALIZED = {
  path: "/",
  // TODO: could we use a symbol in the future?
  name: void 0,
  params: {},
  query: {},
  hash: "",
  fullPath: "/",
  matched: [],
  meta: {},
  redirectedFrom: void 0
};
var NavigationType;
(function(NavigationType2) {
  NavigationType2["pop"] = "pop";
  NavigationType2["push"] = "push";
})(NavigationType || (NavigationType = {}));
var NavigationDirection;
(function(NavigationDirection2) {
  NavigationDirection2["back"] = "back";
  NavigationDirection2["forward"] = "forward";
  NavigationDirection2["unknown"] = "";
})(NavigationDirection || (NavigationDirection = {}));
const START = "";
function normalizeBase(base2) {
  if (!base2) {
    if (isBrowser) {
      const baseEl = document.querySelector("base");
      base2 = baseEl && baseEl.getAttribute("href") || "/";
      base2 = base2.replace(/^\w+:\/\/[^\/]+/, "");
    } else {
      base2 = "/";
    }
  }
  if (base2[0] !== "/" && base2[0] !== "#")
    base2 = "/" + base2;
  return removeTrailingSlash(base2);
}
__name(normalizeBase, "normalizeBase");
const BEFORE_HASH_RE = /^[^#]+#/;
function createHref(base2, location2) {
  return base2.replace(BEFORE_HASH_RE, "#") + location2;
}
__name(createHref, "createHref");
function getElementPosition(el, offset) {
  const docRect = document.documentElement.getBoundingClientRect();
  const elRect = el.getBoundingClientRect();
  return {
    behavior: offset.behavior,
    left: elRect.left - docRect.left - (offset.left || 0),
    top: elRect.top - docRect.top - (offset.top || 0)
  };
}
__name(getElementPosition, "getElementPosition");
const computeScrollPosition = /* @__PURE__ */ __name(() => ({
  left: window.scrollX,
  top: window.scrollY
}), "computeScrollPosition");
function scrollToPosition(position) {
  let scrollToOptions;
  if ("el" in position) {
    const positionEl = position.el;
    const isIdSelector = typeof positionEl === "string" && positionEl.startsWith("#");
    if (false) {
      if (!isIdSelector || !document.getElementById(position.el.slice(1))) {
        try {
          const foundEl = document.querySelector(position.el);
          if (isIdSelector && foundEl) {
            warn$1(`The selector "${position.el}" should be passed as "el: document.querySelector('${position.el}')" because it starts with "#".`);
            return;
          }
        } catch (err) {
          warn$1(`The selector "${position.el}" is invalid. If you are using an id selector, make sure to escape it. You can find more information about escaping characters in selectors at https://mathiasbynens.be/notes/css-escapes or use CSS.escape (https://developer.mozilla.org/en-US/docs/Web/API/CSS/escape).`);
          return;
        }
      }
    }
    const el = typeof positionEl === "string" ? isIdSelector ? document.getElementById(positionEl.slice(1)) : document.querySelector(positionEl) : positionEl;
    if (!el) {
      return;
    }
    scrollToOptions = getElementPosition(el, position);
  } else {
    scrollToOptions = position;
  }
  if ("scrollBehavior" in document.documentElement.style)
    window.scrollTo(scrollToOptions);
  else {
    window.scrollTo(scrollToOptions.left != null ? scrollToOptions.left : window.scrollX, scrollToOptions.top != null ? scrollToOptions.top : window.scrollY);
  }
}
__name(scrollToPosition, "scrollToPosition");
function getScrollKey(path, delta2) {
  const position = history.state ? history.state.position - delta2 : -1;
  return position + path;
}
__name(getScrollKey, "getScrollKey");
const scrollPositions = /* @__PURE__ */ new Map();
function saveScrollPosition(key, scrollPosition) {
  scrollPositions.set(key, scrollPosition);
}
__name(saveScrollPosition, "saveScrollPosition");
function getSavedScrollPosition(key) {
  const scroll = scrollPositions.get(key);
  scrollPositions.delete(key);
  return scroll;
}
__name(getSavedScrollPosition, "getSavedScrollPosition");
let createBaseLocation = /* @__PURE__ */ __name(() => location.protocol + "//" + location.host, "createBaseLocation");
function createCurrentLocation(base2, location2) {
  const { pathname, search: search2, hash } = location2;
  const hashPos = base2.indexOf("#");
  if (hashPos > -1) {
    let slicePos = hash.includes(base2.slice(hashPos)) ? base2.slice(hashPos).length : 1;
    let pathFromHash = hash.slice(slicePos);
    if (pathFromHash[0] !== "/")
      pathFromHash = "/" + pathFromHash;
    return stripBase(pathFromHash, "");
  }
  const path = stripBase(pathname, base2);
  return path + search2 + hash;
}
__name(createCurrentLocation, "createCurrentLocation");
function useHistoryListeners(base2, historyState, currentLocation, replace2) {
  let listeners = [];
  let teardowns = [];
  let pauseState = null;
  const popStateHandler = /* @__PURE__ */ __name(({ state }) => {
    const to = createCurrentLocation(base2, location);
    const from2 = currentLocation.value;
    const fromState = historyState.value;
    let delta2 = 0;
    if (state) {
      currentLocation.value = to;
      historyState.value = state;
      if (pauseState && pauseState === from2) {
        pauseState = null;
        return;
      }
      delta2 = fromState ? state.position - fromState.position : 0;
    } else {
      replace2(to);
    }
    listeners.forEach((listener) => {
      listener(currentLocation.value, from2, {
        delta: delta2,
        type: NavigationType.pop,
        direction: delta2 ? delta2 > 0 ? NavigationDirection.forward : NavigationDirection.back : NavigationDirection.unknown
      });
    });
  }, "popStateHandler");
  function pauseListeners() {
    pauseState = currentLocation.value;
  }
  __name(pauseListeners, "pauseListeners");
  function listen(callback) {
    listeners.push(callback);
    const teardown = /* @__PURE__ */ __name(() => {
      const index2 = listeners.indexOf(callback);
      if (index2 > -1)
        listeners.splice(index2, 1);
    }, "teardown");
    teardowns.push(teardown);
    return teardown;
  }
  __name(listen, "listen");
  function beforeUnloadListener() {
    const { history: history2 } = window;
    if (!history2.state)
      return;
    history2.replaceState(assign$3({}, history2.state, { scroll: computeScrollPosition() }), "");
  }
  __name(beforeUnloadListener, "beforeUnloadListener");
  function destroy() {
    for (const teardown of teardowns)
      teardown();
    teardowns = [];
    window.removeEventListener("popstate", popStateHandler);
    window.removeEventListener("beforeunload", beforeUnloadListener);
  }
  __name(destroy, "destroy");
  window.addEventListener("popstate", popStateHandler);
  window.addEventListener("beforeunload", beforeUnloadListener, {
    passive: true
  });
  return {
    pauseListeners,
    listen,
    destroy
  };
}
__name(useHistoryListeners, "useHistoryListeners");
function buildState(back, current, forward, replaced = false, computeScroll = false) {
  return {
    back,
    current,
    forward,
    replaced,
    position: window.history.length,
    scroll: computeScroll ? computeScrollPosition() : null
  };
}
__name(buildState, "buildState");
function useHistoryStateNavigation(base2) {
  const { history: history2, location: location2 } = window;
  const currentLocation = {
    value: createCurrentLocation(base2, location2)
  };
  const historyState = { value: history2.state };
  if (!historyState.value) {
    changeLocation(currentLocation.value, {
      back: null,
      current: currentLocation.value,
      forward: null,
      // the length is off by one, we need to decrease it
      position: history2.length - 1,
      replaced: true,
      // don't add a scroll as the user may have an anchor, and we want
      // scrollBehavior to be triggered without a saved position
      scroll: null
    }, true);
  }
  function changeLocation(to, state, replace22) {
    const hashIndex = base2.indexOf("#");
    const url = hashIndex > -1 ? (location2.host && document.querySelector("base") ? base2 : base2.slice(hashIndex)) + to : createBaseLocation() + base2 + to;
    try {
      history2[replace22 ? "replaceState" : "pushState"](state, "", url);
      historyState.value = state;
    } catch (err) {
      if (false) {
        warn$1("Error with push/replace State", err);
      } else {
        console.error(err);
      }
      location2[replace22 ? "replace" : "assign"](url);
    }
  }
  __name(changeLocation, "changeLocation");
  function replace2(to, data) {
    const state = assign$3({}, history2.state, buildState(
      historyState.value.back,
      // keep back and forward entries but override current position
      to,
      historyState.value.forward,
      true
    ), data, { position: historyState.value.position });
    changeLocation(to, state, true);
    currentLocation.value = to;
  }
  __name(replace2, "replace");
  function push2(to, data) {
    const currentState = assign$3(
      {},
      // use current history state to gracefully handle a wrong call to
      // history.replaceState
      // https://github.com/vuejs/router/issues/366
      historyState.value,
      history2.state,
      {
        forward: to,
        scroll: computeScrollPosition()
      }
    );
    if (false) {
      warn$1(`history.state seems to have been manually replaced without preserving the necessary values. Make sure to preserve existing history state if you are manually calling history.replaceState:

history.replaceState(history.state, '', url)

You can find more information at https://router.vuejs.org/guide/migration/#Usage-of-history-state`);
    }
    changeLocation(currentState.current, currentState, true);
    const state = assign$3({}, buildState(currentLocation.value, to, null), { position: currentState.position + 1 }, data);
    changeLocation(to, state, false);
    currentLocation.value = to;
  }
  __name(push2, "push");
  return {
    location: currentLocation,
    state: historyState,
    push: push2,
    replace: replace2
  };
}
__name(useHistoryStateNavigation, "useHistoryStateNavigation");
function createWebHistory(base2) {
  base2 = normalizeBase(base2);
  const historyNavigation = useHistoryStateNavigation(base2);
  const historyListeners = useHistoryListeners(base2, historyNavigation.state, historyNavigation.location, historyNavigation.replace);
  function go(delta2, triggerListeners = true) {
    if (!triggerListeners)
      historyListeners.pauseListeners();
    history.go(delta2);
  }
  __name(go, "go");
  const routerHistory = assign$3({
    // it's overridden right after
    location: "",
    base: base2,
    go,
    createHref: createHref.bind(null, base2)
  }, historyNavigation, historyListeners);
  Object.defineProperty(routerHistory, "location", {
    enumerable: true,
    get: /* @__PURE__ */ __name(() => historyNavigation.location.value, "get")
  });
  Object.defineProperty(routerHistory, "state", {
    enumerable: true,
    get: /* @__PURE__ */ __name(() => historyNavigation.state.value, "get")
  });
  return routerHistory;
}
__name(createWebHistory, "createWebHistory");
function createMemoryHistory(base2 = "") {
  let listeners = [];
  let queue = [START];
  let position = 0;
  base2 = normalizeBase(base2);
  function setLocation(location2) {
    position++;
    if (position !== queue.length) {
      queue.splice(position);
    }
    queue.push(location2);
  }
  __name(setLocation, "setLocation");
  function triggerListeners(to, from2, { direction, delta: delta2 }) {
    const info = {
      direction,
      delta: delta2,
      type: NavigationType.pop
    };
    for (const callback of listeners) {
      callback(to, from2, info);
    }
  }
  __name(triggerListeners, "triggerListeners");
  const routerHistory = {
    // rewritten by Object.defineProperty
    location: START,
    // TODO: should be kept in queue
    state: {},
    base: base2,
    createHref: createHref.bind(null, base2),
    replace(to) {
      queue.splice(position--, 1);
      setLocation(to);
    },
    push(to, data) {
      setLocation(to);
    },
    listen(callback) {
      listeners.push(callback);
      return () => {
        const index2 = listeners.indexOf(callback);
        if (index2 > -1)
          listeners.splice(index2, 1);
      };
    },
    destroy() {
      listeners = [];
      queue = [START];
      position = 0;
    },
    go(delta2, shouldTrigger = true) {
      const from2 = this.location;
      const direction = (
        // we are considering delta === 0 going forward, but in abstract mode
        // using 0 for the delta doesn't make sense like it does in html5 where
        // it reloads the page
        delta2 < 0 ? NavigationDirection.back : NavigationDirection.forward
      );
      position = Math.max(0, Math.min(position + delta2, queue.length - 1));
      if (shouldTrigger) {
        triggerListeners(this.location, from2, {
          direction,
          delta: delta2
        });
      }
    }
  };
  Object.defineProperty(routerHistory, "location", {
    enumerable: true,
    get: /* @__PURE__ */ __name(() => queue[position], "get")
  });
  return routerHistory;
}
__name(createMemoryHistory, "createMemoryHistory");
function createWebHashHistory(base2) {
  base2 = location.host ? base2 || location.pathname + location.search : "";
  if (!base2.includes("#"))
    base2 += "#";
  if (false) {
    warn$1(`A hash base must end with a "#":
"${base2}" should be "${base2.replace(/#.*$/, "#")}".`);
  }
  return createWebHistory(base2);
}
__name(createWebHashHistory, "createWebHashHistory");
function isRouteLocation(route) {
  return typeof route === "string" || route && typeof route === "object";
}
__name(isRouteLocation, "isRouteLocation");
function isRouteName(name2) {
  return typeof name2 === "string" || typeof name2 === "symbol";
}
__name(isRouteName, "isRouteName");
const NavigationFailureSymbol = Symbol(false ? "navigation failure" : "");
var NavigationFailureType;
(function(NavigationFailureType2) {
  NavigationFailureType2[NavigationFailureType2["aborted"] = 4] = "aborted";
  NavigationFailureType2[NavigationFailureType2["cancelled"] = 8] = "cancelled";
  NavigationFailureType2[NavigationFailureType2["duplicated"] = 16] = "duplicated";
})(NavigationFailureType || (NavigationFailureType = {}));
const ErrorTypeMessages = {
  [
    1
    /* ErrorTypes.MATCHER_NOT_FOUND */
  ]({ location: location2, currentLocation }) {
    return `No match for
 ${JSON.stringify(location2)}${currentLocation ? "\nwhile being at\n" + JSON.stringify(currentLocation) : ""}`;
  },
  [
    2
    /* ErrorTypes.NAVIGATION_GUARD_REDIRECT */
  ]({ from: from2, to }) {
    return `Redirected from "${from2.fullPath}" to "${stringifyRoute(to)}" via a navigation guard.`;
  },
  [
    4
    /* ErrorTypes.NAVIGATION_ABORTED */
  ]({ from: from2, to }) {
    return `Navigation aborted from "${from2.fullPath}" to "${to.fullPath}" via a navigation guard.`;
  },
  [
    8
    /* ErrorTypes.NAVIGATION_CANCELLED */
  ]({ from: from2, to }) {
    return `Navigation cancelled from "${from2.fullPath}" to "${to.fullPath}" with a new navigation.`;
  },
  [
    16
    /* ErrorTypes.NAVIGATION_DUPLICATED */
  ]({ from: from2, to }) {
    return `Avoided redundant navigation to current location: "${from2.fullPath}".`;
  }
};
function createRouterError(type, params) {
  if (false) {
    return assign$3(new Error(ErrorTypeMessages[type](params)), {
      type,
      [NavigationFailureSymbol]: true
    }, params);
  } else {
    return assign$3(new Error(), {
      type,
      [NavigationFailureSymbol]: true
    }, params);
  }
}
__name(createRouterError, "createRouterError");
function isNavigationFailure(error2, type) {
  return error2 instanceof Error && NavigationFailureSymbol in error2 && (type == null || !!(error2.type & type));
}
__name(isNavigationFailure, "isNavigationFailure");
const propertiesToLog = ["params", "query", "hash"];
function stringifyRoute(to) {
  if (typeof to === "string")
    return to;
  if (to.path != null)
    return to.path;
  const location2 = {};
  for (const key of propertiesToLog) {
    if (key in to)
      location2[key] = to[key];
  }
  return JSON.stringify(location2, null, 2);
}
__name(stringifyRoute, "stringifyRoute");
const BASE_PARAM_PATTERN = "[^/]+?";
const BASE_PATH_PARSER_OPTIONS = {
  sensitive: false,
  strict: false,
  start: true,
  end: true
};
const REGEX_CHARS_RE = /[.+*?^${}()[\]/\\]/g;
function tokensToParser(segments, extraOptions) {
  const options2 = assign$3({}, BASE_PATH_PARSER_OPTIONS, extraOptions);
  const score = [];
  let pattern = options2.start ? "^" : "";
  const keys2 = [];
  for (const segment of segments) {
    const segmentScores = segment.length ? [] : [
      90
      /* PathScore.Root */
    ];
    if (options2.strict && !segment.length)
      pattern += "/";
    for (let tokenIndex = 0; tokenIndex < segment.length; tokenIndex++) {
      const token = segment[tokenIndex];
      let subSegmentScore = 40 + (options2.sensitive ? 0.25 : 0);
      if (token.type === 0) {
        if (!tokenIndex)
          pattern += "/";
        pattern += token.value.replace(REGEX_CHARS_RE, "\\$&");
        subSegmentScore += 40;
      } else if (token.type === 1) {
        const { value, repeatable, optional, regexp: regexp2 } = token;
        keys2.push({
          name: value,
          repeatable,
          optional
        });
        const re22 = regexp2 ? regexp2 : BASE_PARAM_PATTERN;
        if (re22 !== BASE_PARAM_PATTERN) {
          subSegmentScore += 10;
          try {
            new RegExp(`(${re22})`);
          } catch (err) {
            throw new Error(`Invalid custom RegExp for param "${value}" (${re22}): ` + err.message);
          }
        }
        let subPattern = repeatable ? `((?:${re22})(?:/(?:${re22}))*)` : `(${re22})`;
        if (!tokenIndex)
          subPattern = // avoid an optional / if there are more segments e.g. /:p?-static
          // or /:p?-:p2
          optional && segment.length < 2 ? `(?:/${subPattern})` : "/" + subPattern;
        if (optional)
          subPattern += "?";
        pattern += subPattern;
        subSegmentScore += 20;
        if (optional)
          subSegmentScore += -8;
        if (repeatable)
          subSegmentScore += -20;
        if (re22 === ".*")
          subSegmentScore += -50;
      }
      segmentScores.push(subSegmentScore);
    }
    score.push(segmentScores);
  }
  if (options2.strict && options2.end) {
    const i2 = score.length - 1;
    score[i2][score[i2].length - 1] += 0.7000000000000001;
  }
  if (!options2.strict)
    pattern += "/?";
  if (options2.end)
    pattern += "$";
  else if (options2.strict)
    pattern += "(?:/|$)";
  const re2 = new RegExp(pattern, options2.sensitive ? "" : "i");
  function parse2(path) {
    const match2 = path.match(re2);
    const params = {};
    if (!match2)
      return null;
    for (let i2 = 1; i2 < match2.length; i2++) {
      const value = match2[i2] || "";
      const key = keys2[i2 - 1];
      params[key.name] = value && key.repeatable ? value.split("/") : value;
    }
    return params;
  }
  __name(parse2, "parse");
  function stringify2(params) {
    let path = "";
    let avoidDuplicatedSlash = false;
    for (const segment of segments) {
      if (!avoidDuplicatedSlash || !path.endsWith("/"))
        path += "/";
      avoidDuplicatedSlash = false;
      for (const token of segment) {
        if (token.type === 0) {
          path += token.value;
        } else if (token.type === 1) {
          const { value, repeatable, optional } = token;
          const param = value in params ? params[value] : "";
          if (isArray$9(param) && !repeatable) {
            throw new Error(`Provided param "${value}" is an array but it is not repeatable (* or + modifiers)`);
          }
          const text2 = isArray$9(param) ? param.join("/") : param;
          if (!text2) {
            if (optional) {
              if (segment.length < 2) {
                if (path.endsWith("/"))
                  path = path.slice(0, -1);
                else
                  avoidDuplicatedSlash = true;
              }
            } else
              throw new Error(`Missing required param "${value}"`);
          }
          path += text2;
        }
      }
    }
    return path || "/";
  }
  __name(stringify2, "stringify");
  return {
    re: re2,
    score,
    keys: keys2,
    parse: parse2,
    stringify: stringify2
  };
}
__name(tokensToParser, "tokensToParser");
function compareScoreArray(a2, b2) {
  let i2 = 0;
  while (i2 < a2.length && i2 < b2.length) {
    const diff2 = b2[i2] - a2[i2];
    if (diff2)
      return diff2;
    i2++;
  }
  if (a2.length < b2.length) {
    return a2.length === 1 && a2[0] === 40 + 40 ? -1 : 1;
  } else if (a2.length > b2.length) {
    return b2.length === 1 && b2[0] === 40 + 40 ? 1 : -1;
  }
  return 0;
}
__name(compareScoreArray, "compareScoreArray");
function comparePathParserScore(a2, b2) {
  let i2 = 0;
  const aScore = a2.score;
  const bScore = b2.score;
  while (i2 < aScore.length && i2 < bScore.length) {
    const comp = compareScoreArray(aScore[i2], bScore[i2]);
    if (comp)
      return comp;
    i2++;
  }
  if (Math.abs(bScore.length - aScore.length) === 1) {
    if (isLastScoreNegative(aScore))
      return 1;
    if (isLastScoreNegative(bScore))
      return -1;
  }
  return bScore.length - aScore.length;
}
__name(comparePathParserScore, "comparePathParserScore");
function isLastScoreNegative(score) {
  const last = score[score.length - 1];
  return score.length > 0 && last[last.length - 1] < 0;
}
__name(isLastScoreNegative, "isLastScoreNegative");
const ROOT_TOKEN = {
  type: 0,
  value: ""
};
const VALID_PARAM_RE = /[a-zA-Z0-9_]/;
function tokenizePath(path) {
  if (!path)
    return [[]];
  if (path === "/")
    return [[ROOT_TOKEN]];
  if (!path.startsWith("/")) {
    throw new Error(false ? `Route paths should start with a "/": "${path}" should be "/${path}".` : `Invalid path "${path}"`);
  }
  function crash(message) {
    throw new Error(`ERR (${state})/"${buffer}": ${message}`);
  }
  __name(crash, "crash");
  let state = 0;
  let previousState = state;
  const tokens = [];
  let segment;
  function finalizeSegment() {
    if (segment)
      tokens.push(segment);
    segment = [];
  }
  __name(finalizeSegment, "finalizeSegment");
  let i2 = 0;
  let char;
  let buffer = "";
  let customRe = "";
  function consumeBuffer() {
    if (!buffer)
      return;
    if (state === 0) {
      segment.push({
        type: 0,
        value: buffer
      });
    } else if (state === 1 || state === 2 || state === 3) {
      if (segment.length > 1 && (char === "*" || char === "+"))
        crash(`A repeatable param (${buffer}) must be alone in its segment. eg: '/:ids+.`);
      segment.push({
        type: 1,
        value: buffer,
        regexp: customRe,
        repeatable: char === "*" || char === "+",
        optional: char === "*" || char === "?"
      });
    } else {
      crash("Invalid state to consume buffer");
    }
    buffer = "";
  }
  __name(consumeBuffer, "consumeBuffer");
  function addCharToBuffer() {
    buffer += char;
  }
  __name(addCharToBuffer, "addCharToBuffer");
  while (i2 < path.length) {
    char = path[i2++];
    if (char === "\\" && state !== 2) {
      previousState = state;
      state = 4;
      continue;
    }
    switch (state) {
      case 0:
        if (char === "/") {
          if (buffer) {
            consumeBuffer();
          }
          finalizeSegment();
        } else if (char === ":") {
          consumeBuffer();
          state = 1;
        } else {
          addCharToBuffer();
        }
        break;
      case 4:
        addCharToBuffer();
        state = previousState;
        break;
      case 1:
        if (char === "(") {
          state = 2;
        } else if (VALID_PARAM_RE.test(char)) {
          addCharToBuffer();
        } else {
          consumeBuffer();
          state = 0;
          if (char !== "*" && char !== "?" && char !== "+")
            i2--;
        }
        break;
      case 2:
        if (char === ")") {
          if (customRe[customRe.length - 1] == "\\")
            customRe = customRe.slice(0, -1) + char;
          else
            state = 3;
        } else {
          customRe += char;
        }
        break;
      case 3:
        consumeBuffer();
        state = 0;
        if (char !== "*" && char !== "?" && char !== "+")
          i2--;
        customRe = "";
        break;
      default:
        crash("Unknown state");
        break;
    }
  }
  if (state === 2)
    crash(`Unfinished custom RegExp for param "${buffer}"`);
  consumeBuffer();
  finalizeSegment();
  return tokens;
}
__name(tokenizePath, "tokenizePath");
function createRouteRecordMatcher(record2, parent2, options2) {
  const parser = tokensToParser(tokenizePath(record2.path), options2);
  if (false) {
    const existingKeys = /* @__PURE__ */ new Set();
    for (const key of parser.keys) {
      if (existingKeys.has(key.name))
        warn$1(`Found duplicated params with name "${key.name}" for path "${record2.path}". Only the last one will be available on "$route.params".`);
      existingKeys.add(key.name);
    }
  }
  const matcher = assign$3(parser, {
    record: record2,
    parent: parent2,
    // these needs to be populated by the parent
    children: [],
    alias: []
  });
  if (parent2) {
    if (!matcher.record.aliasOf === !parent2.record.aliasOf)
      parent2.children.push(matcher);
  }
  return matcher;
}
__name(createRouteRecordMatcher, "createRouteRecordMatcher");
function createRouterMatcher(routes, globalOptions) {
  const matchers = [];
  const matcherMap = /* @__PURE__ */ new Map();
  globalOptions = mergeOptions({ strict: false, end: true, sensitive: false }, globalOptions);
  function getRecordMatcher(name2) {
    return matcherMap.get(name2);
  }
  __name(getRecordMatcher, "getRecordMatcher");
  function addRoute(record2, parent2, originalRecord) {
    const isRootAdd = !originalRecord;
    const mainNormalizedRecord = normalizeRouteRecord(record2);
    if (false) {
      checkChildMissingNameWithEmptyPath(mainNormalizedRecord, parent2);
    }
    mainNormalizedRecord.aliasOf = originalRecord && originalRecord.record;
    const options2 = mergeOptions(globalOptions, record2);
    const normalizedRecords = [
      mainNormalizedRecord
    ];
    if ("alias" in record2) {
      const aliases = typeof record2.alias === "string" ? [record2.alias] : record2.alias;
      for (const alias of aliases) {
        normalizedRecords.push(assign$3({}, mainNormalizedRecord, {
          // this allows us to hold a copy of the `components` option
          // so that async components cache is hold on the original record
          components: originalRecord ? originalRecord.record.components : mainNormalizedRecord.components,
          path: alias,
          // we might be the child of an alias
          aliasOf: originalRecord ? originalRecord.record : mainNormalizedRecord
          // the aliases are always of the same kind as the original since they
          // are defined on the same record
        }));
      }
    }
    let matcher;
    let originalMatcher;
    for (const normalizedRecord of normalizedRecords) {
      const { path } = normalizedRecord;
      if (parent2 && path[0] !== "/") {
        const parentPath = parent2.record.path;
        const connectingSlash = parentPath[parentPath.length - 1] === "/" ? "" : "/";
        normalizedRecord.path = parent2.record.path + (path && connectingSlash + path);
      }
      if (false) {
        throw new Error('Catch all routes ("*") must now be defined using a param with a custom regexp.\nSee more at https://router.vuejs.org/guide/migration/#Removed-star-or-catch-all-routes.');
      }
      matcher = createRouteRecordMatcher(normalizedRecord, parent2, options2);
      if (false)
        checkMissingParamsInAbsolutePath(matcher, parent2);
      if (originalRecord) {
        originalRecord.alias.push(matcher);
        if (false) {
          checkSameParams(originalRecord, matcher);
        }
      } else {
        originalMatcher = originalMatcher || matcher;
        if (originalMatcher !== matcher)
          originalMatcher.alias.push(matcher);
        if (isRootAdd && record2.name && !isAliasRecord(matcher))
          removeRoute(record2.name);
      }
      if (isMatchable(matcher)) {
        insertMatcher(matcher);
      }
      if (mainNormalizedRecord.children) {
        const children = mainNormalizedRecord.children;
        for (let i2 = 0; i2 < children.length; i2++) {
          addRoute(children[i2], matcher, originalRecord && originalRecord.children[i2]);
        }
      }
      originalRecord = originalRecord || matcher;
    }
    return originalMatcher ? () => {
      removeRoute(originalMatcher);
    } : noop$3;
  }
  __name(addRoute, "addRoute");
  function removeRoute(matcherRef) {
    if (isRouteName(matcherRef)) {
      const matcher = matcherMap.get(matcherRef);
      if (matcher) {
        matcherMap.delete(matcherRef);
        matchers.splice(matchers.indexOf(matcher), 1);
        matcher.children.forEach(removeRoute);
        matcher.alias.forEach(removeRoute);
      }
    } else {
      const index2 = matchers.indexOf(matcherRef);
      if (index2 > -1) {
        matchers.splice(index2, 1);
        if (matcherRef.record.name)
          matcherMap.delete(matcherRef.record.name);
        matcherRef.children.forEach(removeRoute);
        matcherRef.alias.forEach(removeRoute);
      }
    }
  }
  __name(removeRoute, "removeRoute");
  function getRoutes() {
    return matchers;
  }
  __name(getRoutes, "getRoutes");
  function insertMatcher(matcher) {
    const index2 = findInsertionIndex(matcher, matchers);
    matchers.splice(index2, 0, matcher);
    if (matcher.record.name && !isAliasRecord(matcher))
      matcherMap.set(matcher.record.name, matcher);
  }
  __name(insertMatcher, "insertMatcher");
  function resolve2(location2, currentLocation) {
    let matcher;
    let params = {};
    let path;
    let name2;
    if ("name" in location2 && location2.name) {
      matcher = matcherMap.get(location2.name);
      if (!matcher)
        throw createRouterError(1, {
          location: location2
        });
      if (false) {
        const invalidParams = Object.keys(location2.params || {}).filter((paramName) => !matcher.keys.find((k2) => k2.name === paramName));
        if (invalidParams.length) {
          warn$1(`Discarded invalid param(s) "${invalidParams.join('", "')}" when navigating. See https://github.com/vuejs/router/blob/main/packages/router/CHANGELOG.md#414-2022-08-22 for more details.`);
        }
      }
      name2 = matcher.record.name;
      params = assign$3(
        // paramsFromLocation is a new object
        paramsFromLocation(
          currentLocation.params,
          // only keep params that exist in the resolved location
          // only keep optional params coming from a parent record
          matcher.keys.filter((k2) => !k2.optional).concat(matcher.parent ? matcher.parent.keys.filter((k2) => k2.optional) : []).map((k2) => k2.name)
        ),
        // discard any existing params in the current location that do not exist here
        // #1497 this ensures better active/exact matching
        location2.params && paramsFromLocation(location2.params, matcher.keys.map((k2) => k2.name))
      );
      path = matcher.stringify(params);
    } else if (location2.path != null) {
      path = location2.path;
      if (false) {
        warn$1(`The Matcher cannot resolve relative paths but received "${path}". Unless you directly called \`matcher.resolve("${path}")\`, this is probably a bug in vue-router. Please open an issue at https://github.com/vuejs/router/issues/new/choose.`);
      }
      matcher = matchers.find((m2) => m2.re.test(path));
      if (matcher) {
        params = matcher.parse(path);
        name2 = matcher.record.name;
      }
    } else {
      matcher = currentLocation.name ? matcherMap.get(currentLocation.name) : matchers.find((m2) => m2.re.test(currentLocation.path));
      if (!matcher)
        throw createRouterError(1, {
          location: location2,
          currentLocation
        });
      name2 = matcher.record.name;
      params = assign$3({}, currentLocation.params, location2.params);
      path = matcher.stringify(params);
    }
    const matched = [];
    let parentMatcher = matcher;
    while (parentMatcher) {
      matched.unshift(parentMatcher.record);
      parentMatcher = parentMatcher.parent;
    }
    return {
      name: name2,
      path,
      params,
      matched,
      meta: mergeMetaFields(matched)
    };
  }
  __name(resolve2, "resolve");
  routes.forEach((route) => addRoute(route));
  function clearRoutes() {
    matchers.length = 0;
    matcherMap.clear();
  }
  __name(clearRoutes, "clearRoutes");
  return {
    addRoute,
    resolve: resolve2,
    removeRoute,
    clearRoutes,
    getRoutes,
    getRecordMatcher
  };
}
__name(createRouterMatcher, "createRouterMatcher");
function paramsFromLocation(params, keys2) {
  const newParams = {};
  for (const key of keys2) {
    if (key in params)
      newParams[key] = params[key];
  }
  return newParams;
}
__name(paramsFromLocation, "paramsFromLocation");
function normalizeRouteRecord(record2) {
  return {
    path: record2.path,
    redirect: record2.redirect,
    name: record2.name,
    meta: record2.meta || {},
    aliasOf: void 0,
    beforeEnter: record2.beforeEnter,
    props: normalizeRecordProps(record2),
    children: record2.children || [],
    instances: {},
    leaveGuards: /* @__PURE__ */ new Set(),
    updateGuards: /* @__PURE__ */ new Set(),
    enterCallbacks: {},
    components: "components" in record2 ? record2.components || null : record2.component && { default: record2.component }
  };
}
__name(normalizeRouteRecord, "normalizeRouteRecord");
function normalizeRecordProps(record2) {
  const propsObject = {};
  const props = record2.props || false;
  if ("component" in record2) {
    propsObject.default = props;
  } else {
    for (const name2 in record2.components)
      propsObject[name2] = typeof props === "object" ? props[name2] : props;
  }
  return propsObject;
}
__name(normalizeRecordProps, "normalizeRecordProps");
function isAliasRecord(record2) {
  while (record2) {
    if (record2.record.aliasOf)
      return true;
    record2 = record2.parent;
  }
  return false;
}
__name(isAliasRecord, "isAliasRecord");
function mergeMetaFields(matched) {
  return matched.reduce((meta, record2) => assign$3(meta, record2.meta), {});
}
__name(mergeMetaFields, "mergeMetaFields");
function mergeOptions(defaults2, partialOptions) {
  const options2 = {};
  for (const key in defaults2) {
    options2[key] = key in partialOptions ? partialOptions[key] : defaults2[key];
  }
  return options2;
}
__name(mergeOptions, "mergeOptions");
function isSameParam(a2, b2) {
  return a2.name === b2.name && a2.optional === b2.optional && a2.repeatable === b2.repeatable;
}
__name(isSameParam, "isSameParam");
function checkSameParams(a2, b2) {
  for (const key of a2.keys) {
    if (!key.optional && !b2.keys.find(isSameParam.bind(null, key)))
      return warn$1(`Alias "${b2.record.path}" and the original record: "${a2.record.path}" must have the exact same param named "${key.name}"`);
  }
  for (const key of b2.keys) {
    if (!key.optional && !a2.keys.find(isSameParam.bind(null, key)))
      return warn$1(`Alias "${b2.record.path}" and the original record: "${a2.record.path}" must have the exact same param named "${key.name}"`);
  }
}
__name(checkSameParams, "checkSameParams");
function checkChildMissingNameWithEmptyPath(mainNormalizedRecord, parent2) {
  if (parent2 && parent2.record.name && !mainNormalizedRecord.name && !mainNormalizedRecord.path) {
    warn$1(`The route named "${String(parent2.record.name)}" has a child without a name and an empty path. Using that name won't render the empty path child so you probably want to move the name to the child instead. If this is intentional, add a name to the child route to remove the warning.`);
  }
}
__name(checkChildMissingNameWithEmptyPath, "checkChildMissingNameWithEmptyPath");
function checkMissingParamsInAbsolutePath(record2, parent2) {
  for (const key of parent2.keys) {
    if (!record2.keys.find(isSameParam.bind(null, key)))
      return warn$1(`Absolute path "${record2.record.path}" must have the exact same param named "${key.name}" as its parent "${parent2.record.path}".`);
  }
}
__name(checkMissingParamsInAbsolutePath, "checkMissingParamsInAbsolutePath");
function findInsertionIndex(matcher, matchers) {
  let lower = 0;
  let upper = matchers.length;
  while (lower !== upper) {
    const mid = lower + upper >> 1;
    const sortOrder = comparePathParserScore(matcher, matchers[mid]);
    if (sortOrder < 0) {
      upper = mid;
    } else {
      lower = mid + 1;
    }
  }
  const insertionAncestor = getInsertionAncestor(matcher);
  if (insertionAncestor) {
    upper = matchers.lastIndexOf(insertionAncestor, upper - 1);
    if (false) {
      warn$1(`Finding ancestor route "${insertionAncestor.record.path}" failed for "${matcher.record.path}"`);
    }
  }
  return upper;
}
__name(findInsertionIndex, "findInsertionIndex");
function getInsertionAncestor(matcher) {
  let ancestor = matcher;
  while (ancestor = ancestor.parent) {
    if (isMatchable(ancestor) && comparePathParserScore(matcher, ancestor) === 0) {
      return ancestor;
    }
  }
  return;
}
__name(getInsertionAncestor, "getInsertionAncestor");
function isMatchable({ record: record2 }) {
  return !!(record2.name || record2.components && Object.keys(record2.components).length || record2.redirect);
}
__name(isMatchable, "isMatchable");
function parseQuery$1(search2) {
  const query2 = {};
  if (search2 === "" || search2 === "?")
    return query2;
  const hasLeadingIM = search2[0] === "?";
  const searchParams = (hasLeadingIM ? search2.slice(1) : search2).split("&");
  for (let i2 = 0; i2 < searchParams.length; ++i2) {
    const searchParam = searchParams[i2].replace(PLUS_RE, " ");
    const eqPos = searchParam.indexOf("=");
    const key = decode$3(eqPos < 0 ? searchParam : searchParam.slice(0, eqPos));
    const value = eqPos < 0 ? null : decode$3(searchParam.slice(eqPos + 1));
    if (key in query2) {
      let currentValue = query2[key];
      if (!isArray$9(currentValue)) {
        currentValue = query2[key] = [currentValue];
      }
      currentValue.push(value);
    } else {
      query2[key] = value;
    }
  }
  return query2;
}
__name(parseQuery$1, "parseQuery$1");
function stringifyQuery(query2) {
  let search2 = "";
  for (let key in query2) {
    const value = query2[key];
    key = encodeQueryKey(key);
    if (value == null) {
      if (value !== void 0) {
        search2 += (search2.length ? "&" : "") + key;
      }
      continue;
    }
    const values = isArray$9(value) ? value.map((v2) => v2 && encodeQueryValue(v2)) : [value && encodeQueryValue(value)];
    values.forEach((value2) => {
      if (value2 !== void 0) {
        search2 += (search2.length ? "&" : "") + key;
        if (value2 != null)
          search2 += "=" + value2;
      }
    });
  }
  return search2;
}
__name(stringifyQuery, "stringifyQuery");
function normalizeQuery(query2) {
  const normalizedQuery = {};
  for (const key in query2) {
    const value = query2[key];
    if (value !== void 0) {
      normalizedQuery[key] = isArray$9(value) ? value.map((v2) => v2 == null ? null : "" + v2) : value == null ? value : "" + value;
    }
  }
  return normalizedQuery;
}
__name(normalizeQuery, "normalizeQuery");
const matchedRouteKey = Symbol(false ? "router view location matched" : "");
const viewDepthKey = Symbol(false ? "router view depth" : "");
const routerKey = Symbol(false ? "router" : "");
const routeLocationKey = Symbol(false ? "route location" : "");
const routerViewLocationKey = Symbol(false ? "router view location" : "");
function useCallbacks() {
  let handlers2 = [];
  function add3(handler5) {
    handlers2.push(handler5);
    return () => {
      const i2 = handlers2.indexOf(handler5);
      if (i2 > -1)
        handlers2.splice(i2, 1);
    };
  }
  __name(add3, "add");
  function reset2() {
    handlers2 = [];
  }
  __name(reset2, "reset");
  return {
    add: add3,
    list: /* @__PURE__ */ __name(() => handlers2.slice(), "list"),
    reset: reset2
  };
}
__name(useCallbacks, "useCallbacks");
function registerGuard(record2, name2, guard) {
  const removeFromList = /* @__PURE__ */ __name(() => {
    record2[name2].delete(guard);
  }, "removeFromList");
  onUnmounted(removeFromList);
  onDeactivated(removeFromList);
  onActivated(() => {
    record2[name2].add(guard);
  });
  record2[name2].add(guard);
}
__name(registerGuard, "registerGuard");
function onBeforeRouteLeave(leaveGuard) {
  if (false) {
    warn$1("getCurrentInstance() returned null. onBeforeRouteLeave() must be called at the top of a setup function");
    return;
  }
  const activeRecord = inject(
    matchedRouteKey,
    // to avoid warning
    {}
  ).value;
  if (!activeRecord) {
    return;
  }
  registerGuard(activeRecord, "leaveGuards", leaveGuard);
}
__name(onBeforeRouteLeave, "onBeforeRouteLeave");
function onBeforeRouteUpdate(updateGuard) {
  if (false) {
    warn$1("getCurrentInstance() returned null. onBeforeRouteUpdate() must be called at the top of a setup function");
    return;
  }
  const activeRecord = inject(
    matchedRouteKey,
    // to avoid warning
    {}
  ).value;
  if (!activeRecord) {
    return;
  }
  registerGuard(activeRecord, "updateGuards", updateGuard);
}
__name(onBeforeRouteUpdate, "onBeforeRouteUpdate");
function guardToPromiseFn(guard, to, from2, record2, name2, runWithContext = (fn) => fn()) {
  const enterCallbackArray = record2 && // name is defined if record is because of the function overload
  (record2.enterCallbacks[name2] = record2.enterCallbacks[name2] || []);
  return () => new Promise((resolve2, reject) => {
    const next = /* @__PURE__ */ __name((valid) => {
      if (valid === false) {
        reject(createRouterError(4, {
          from: from2,
          to
        }));
      } else if (valid instanceof Error) {
        reject(valid);
      } else if (isRouteLocation(valid)) {
        reject(createRouterError(2, {
          from: to,
          to: valid
        }));
      } else {
        if (enterCallbackArray && // since enterCallbackArray is truthy, both record and name also are
        record2.enterCallbacks[name2] === enterCallbackArray && typeof valid === "function") {
          enterCallbackArray.push(valid);
        }
        resolve2();
      }
    }, "next");
    const guardReturn = runWithContext(() => guard.call(record2 && record2.instances[name2], to, from2, false ? canOnlyBeCalledOnce(next, to, from2) : next));
    let guardCall = Promise.resolve(guardReturn);
    if (guard.length < 3)
      guardCall = guardCall.then(next);
    if (false) {
      const message = `The "next" callback was never called inside of ${guard.name ? '"' + guard.name + '"' : ""}:
${guard.toString()}
. If you are returning a value instead of calling "next", make sure to remove the "next" parameter from your function.`;
      if (typeof guardReturn === "object" && "then" in guardReturn) {
        guardCall = guardCall.then((resolvedValue) => {
          if (!next._called) {
            warn$1(message);
            return Promise.reject(new Error("Invalid navigation guard"));
          }
          return resolvedValue;
        });
      } else if (guardReturn !== void 0) {
        if (!next._called) {
          warn$1(message);
          reject(new Error("Invalid navigation guard"));
          return;
        }
      }
    }
    guardCall.catch((err) => reject(err));
  });
}
__name(guardToPromiseFn, "guardToPromiseFn");
function canOnlyBeCalledOnce(next, to, from2) {
  let called = 0;
  return function() {
    if (called++ === 1)
      warn$1(`The "next" callback was called more than once in one navigation guard when going from "${from2.fullPath}" to "${to.fullPath}". It should be called exactly one time in each navigation guard. This will fail in production.`);
    next._called = true;
    if (called === 1)
      next.apply(null, arguments);
  };
}
__name(canOnlyBeCalledOnce, "canOnlyBeCalledOnce");
function extractComponentsGuards(matched, guardType, to, from2, runWithContext = (fn) => fn()) {
  const guards = [];
  for (const record2 of matched) {
    if (false) {
      warn$1(`Record with path "${record2.path}" is either missing a "component(s)" or "children" property.`);
    }
    for (const name2 in record2.components) {
      let rawComponent = record2.components[name2];
      if (false) {
        if (!rawComponent || typeof rawComponent !== "object" && typeof rawComponent !== "function") {
          warn$1(`Component "${name2}" in record with path "${record2.path}" is not a valid component. Received "${String(rawComponent)}".`);
          throw new Error("Invalid route component");
        } else if ("then" in rawComponent) {
          warn$1(`Component "${name2}" in record with path "${record2.path}" is a Promise instead of a function that returns a Promise. Did you write "import('./MyPage.vue')" instead of "() => import('./MyPage.vue')" ? This will break in production if not fixed.`);
          const promise = rawComponent;
          rawComponent = /* @__PURE__ */ __name(() => promise, "rawComponent");
        } else if (rawComponent.__asyncLoader && // warn only once per component
        !rawComponent.__warnedDefineAsync) {
          rawComponent.__warnedDefineAsync = true;
          warn$1(`Component "${name2}" in record with path "${record2.path}" is defined using "defineAsyncComponent()". Write "() => import('./MyPage.vue')" instead of "defineAsyncComponent(() => import('./MyPage.vue'))".`);
        }
      }
      if (guardType !== "beforeRouteEnter" && !record2.instances[name2])
        continue;
      if (isRouteComponent(rawComponent)) {
        const options2 = rawComponent.__vccOpts || rawComponent;
        const guard = options2[guardType];
        guard && guards.push(guardToPromiseFn(guard, to, from2, record2, name2, runWithContext));
      } else {
        let componentPromise = rawComponent();
        if (false) {
          warn$1(`Component "${name2}" in record with path "${record2.path}" is a function that does not return a Promise. If you were passing a functional component, make sure to add a "displayName" to the component. This will break in production if not fixed.`);
          componentPromise = Promise.resolve(componentPromise);
        }
        guards.push(() => componentPromise.then((resolved) => {
          if (!resolved)
            return Promise.reject(new Error(`Couldn't resolve component "${name2}" at "${record2.path}"`));
          const resolvedComponent = isESModule(resolved) ? resolved.default : resolved;
          record2.components[name2] = resolvedComponent;
          const options2 = resolvedComponent.__vccOpts || resolvedComponent;
          const guard = options2[guardType];
          return guard && guardToPromiseFn(guard, to, from2, record2, name2, runWithContext)();
        }));
      }
    }
  }
  return guards;
}
__name(extractComponentsGuards, "extractComponentsGuards");
function isRouteComponent(component) {
  return typeof component === "object" || "displayName" in component || "props" in component || "__vccOpts" in component;
}
__name(isRouteComponent, "isRouteComponent");
function loadRouteLocation(route) {
  return route.matched.every((record2) => record2.redirect) ? Promise.reject(new Error("Cannot load a route that redirects.")) : Promise.all(route.matched.map((record2) => record2.components && Promise.all(Object.keys(record2.components).reduce((promises, name2) => {
    const rawComponent = record2.components[name2];
    if (typeof rawComponent === "function" && !("displayName" in rawComponent)) {
      promises.push(rawComponent().then((resolved) => {
        if (!resolved)
          return Promise.reject(new Error(`Couldn't resolve component "${name2}" at "${record2.path}". Ensure you passed a function that returns a promise.`));
        const resolvedComponent = isESModule(resolved) ? resolved.default : resolved;
        record2.components[name2] = resolvedComponent;
        return;
      }));
    }
    return promises;
  }, [])))).then(() => route);
}
__name(loadRouteLocation, "loadRouteLocation");
function useLink(props) {
  const router2 = inject(routerKey);
  const currentRoute = inject(routeLocationKey);
  let hasPrevious = false;
  let previousTo = null;
  const route = computed(() => {
    const to = unref(props.to);
    if (false) {
      if (!isRouteLocation(to)) {
        if (hasPrevious) {
          warn$1(`Invalid value for prop "to" in useLink()
- to:`, to, `
- previous to:`, previousTo, `
- props:`, props);
        } else {
          warn$1(`Invalid value for prop "to" in useLink()
- to:`, to, `
- props:`, props);
        }
      }
      previousTo = to;
      hasPrevious = true;
    }
    return router2.resolve(to);
  });
  const activeRecordIndex = computed(() => {
    const { matched } = route.value;
    const { length } = matched;
    const routeMatched = matched[length - 1];
    const currentMatched = currentRoute.matched;
    if (!routeMatched || !currentMatched.length)
      return -1;
    const index2 = currentMatched.findIndex(isSameRouteRecord.bind(null, routeMatched));
    if (index2 > -1)
      return index2;
    const parentRecordPath = getOriginalPath(matched[length - 2]);
    return (
      // we are dealing with nested routes
      length > 1 && // if the parent and matched route have the same path, this link is
      // referring to the empty child. Or we currently are on a different
      // child of the same parent
      getOriginalPath(routeMatched) === parentRecordPath && // avoid comparing the child with its parent
      currentMatched[currentMatched.length - 1].path !== parentRecordPath ? currentMatched.findIndex(isSameRouteRecord.bind(null, matched[length - 2])) : index2
    );
  });
  const isActive2 = computed(() => activeRecordIndex.value > -1 && includesParams(currentRoute.params, route.value.params));
  const isExactActive = computed(() => activeRecordIndex.value > -1 && activeRecordIndex.value === currentRoute.matched.length - 1 && isSameRouteLocationParams(currentRoute.params, route.value.params));
  function navigate(e2 = {}) {
    if (guardEvent(e2)) {
      return router2[unref(props.replace) ? "replace" : "push"](
        unref(props.to)
        // avoid uncaught errors are they are logged anyway
      ).catch(noop$3);
    }
    return Promise.resolve();
  }
  __name(navigate, "navigate");
  if (false) {
    const instance = getCurrentInstance();
    if (instance) {
      const linkContextDevtools = {
        route: route.value,
        isActive: isActive2.value,
        isExactActive: isExactActive.value,
        error: null
      };
      instance.__vrl_devtools = instance.__vrl_devtools || [];
      instance.__vrl_devtools.push(linkContextDevtools);
      watchEffect(() => {
        linkContextDevtools.route = route.value;
        linkContextDevtools.isActive = isActive2.value;
        linkContextDevtools.isExactActive = isExactActive.value;
        linkContextDevtools.error = isRouteLocation(unref(props.to)) ? null : 'Invalid "to" value';
      }, { flush: "post" });
    }
  }
  return {
    route,
    href: computed(() => route.value.href),
    isActive: isActive2,
    isExactActive,
    navigate
  };
}
__name(useLink, "useLink");
const RouterLinkImpl = /* @__PURE__ */ defineComponent({
  name: "RouterLink",
  compatConfig: { MODE: 3 },
  props: {
    to: {
      type: [String, Object],
      required: true
    },
    replace: Boolean,
    activeClass: String,
    // inactiveClass: String,
    exactActiveClass: String,
    custom: Boolean,
    ariaCurrentValue: {
      type: String,
      default: "page"
    }
  },
  useLink,
  setup(props, { slots }) {
    const link2 = reactive(useLink(props));
    const { options: options2 } = inject(routerKey);
    const elClass = computed(() => ({
      [getLinkClass(props.activeClass, options2.linkActiveClass, "router-link-active")]: link2.isActive,
      // [getLinkClass(
      //   props.inactiveClass,
      //   options.linkInactiveClass,
      //   'router-link-inactive'
      // )]: !link.isExactActive,
      [getLinkClass(props.exactActiveClass, options2.linkExactActiveClass, "router-link-exact-active")]: link2.isExactActive
    }));
    return () => {
      const children = slots.default && slots.default(link2);
      return props.custom ? children : h$2("a", {
        "aria-current": link2.isExactActive ? props.ariaCurrentValue : null,
        href: link2.href,
        // this would override user added attrs but Vue will still add
        // the listener, so we end up triggering both
        onClick: link2.navigate,
        class: elClass.value
      }, children);
    };
  }
});
const RouterLink = RouterLinkImpl;
function guardEvent(e2) {
  if (e2.metaKey || e2.altKey || e2.ctrlKey || e2.shiftKey)
    return;
  if (e2.defaultPrevented)
    return;
  if (e2.button !== void 0 && e2.button !== 0)
    return;
  if (e2.currentTarget && e2.currentTarget.getAttribute) {
    const target = e2.currentTarget.getAttribute("target");
    if (/\b_blank\b/i.test(target))
      return;
  }
  if (e2.preventDefault)
    e2.preventDefault();
  return true;
}
__name(guardEvent, "guardEvent");
function includesParams(outer, inner) {
  for (const key in inner) {
    const innerValue = inner[key];
    const outerValue = outer[key];
    if (typeof innerValue === "string") {
      if (innerValue !== outerValue)
        return false;
    } else {
      if (!isArray$9(outerValue) || outerValue.length !== innerValue.length || innerValue.some((value, i2) => value !== outerValue[i2]))
        return false;
    }
  }
  return true;
}
__name(includesParams, "includesParams");
function getOriginalPath(record2) {
  return record2 ? record2.aliasOf ? record2.aliasOf.path : record2.path : "";
}
__name(getOriginalPath, "getOriginalPath");
const getLinkClass = /* @__PURE__ */ __name((propClass, globalClass, defaultClass) => propClass != null ? propClass : globalClass != null ? globalClass : defaultClass, "getLinkClass");
const RouterViewImpl = /* @__PURE__ */ defineComponent({
  name: "RouterView",
  // #674 we manually inherit them
  inheritAttrs: false,
  props: {
    name: {
      type: String,
      default: "default"
    },
    route: Object
  },
  // Better compat for @vue/compat users
  // https://github.com/vuejs/router/issues/1315
  compatConfig: { MODE: 3 },
  setup(props, { attrs: attrs2, slots }) {
    const injectedRoute = inject(routerViewLocationKey);
    const routeToDisplay = computed(() => props.route || injectedRoute.value);
    const injectedDepth = inject(viewDepthKey, 0);
    const depth = computed(() => {
      let initialDepth = unref(injectedDepth);
      const { matched } = routeToDisplay.value;
      let matchedRoute;
      while ((matchedRoute = matched[initialDepth]) && !matchedRoute.components) {
        initialDepth++;
      }
      return initialDepth;
    });
    const matchedRouteRef = computed(() => routeToDisplay.value.matched[depth.value]);
    provide(viewDepthKey, computed(() => depth.value + 1));
    provide(matchedRouteKey, matchedRouteRef);
    provide(routerViewLocationKey, routeToDisplay);
    const viewRef = ref$3();
    watch(() => [viewRef.value, matchedRouteRef.value, props.name], ([instance, to, name2], [oldInstance, from2, oldName]) => {
      if (to) {
        to.instances[name2] = instance;
        if (from2 && from2 !== to && instance && instance === oldInstance) {
          if (!to.leaveGuards.size) {
            to.leaveGuards = from2.leaveGuards;
          }
          if (!to.updateGuards.size) {
            to.updateGuards = from2.updateGuards;
          }
        }
      }
      if (instance && to && // if there is no instance but to and from are the same this might be
      // the first visit
      (!from2 || !isSameRouteRecord(to, from2) || !oldInstance)) {
        (to.enterCallbacks[name2] || []).forEach((callback) => callback(instance));
      }
    }, { flush: "post" });
    return () => {
      const route = routeToDisplay.value;
      const currentName = props.name;
      const matchedRoute = matchedRouteRef.value;
      const ViewComponent = matchedRoute && matchedRoute.components[currentName];
      if (!ViewComponent) {
        return normalizeSlot(slots.default, { Component: ViewComponent, route });
      }
      const routePropsOption = matchedRoute.props[currentName];
      const routeProps = routePropsOption ? routePropsOption === true ? route.params : typeof routePropsOption === "function" ? routePropsOption(route) : routePropsOption : null;
      const onVnodeUnmounted = /* @__PURE__ */ __name((vnode) => {
        if (vnode.component.isUnmounted) {
          matchedRoute.instances[currentName] = null;
        }
      }, "onVnodeUnmounted");
      const component = h$2(ViewComponent, assign$3({}, routeProps, attrs2, {
        onVnodeUnmounted,
        ref: viewRef
      }));
      if (false) {
        const info = {
          depth: depth.value,
          name: matchedRoute.name,
          path: matchedRoute.path,
          meta: matchedRoute.meta
        };
        const internalInstances = isArray$9(component.ref) ? component.ref.map((r2) => r2.i) : [component.ref.i];
        internalInstances.forEach((instance) => {
          instance.__vrv_devtools = info;
        });
      }
      return (
        // pass the vnode to the slot as a prop.
        // h and <component :is="..."> both accept vnodes
        normalizeSlot(slots.default, { Component: component, route }) || component
      );
    };
  }
});
function normalizeSlot(slot, data) {
  if (!slot)
    return null;
  const slotContent = slot(data);
  return slotContent.length === 1 ? slotContent[0] : slotContent;
}
__name(normalizeSlot, "normalizeSlot");
const RouterView = RouterViewImpl;
function warnDeprecatedUsage() {
  const instance = getCurrentInstance();
  const parentName = instance.parent && instance.parent.type.name;
  const parentSubTreeType = instance.parent && instance.parent.subTree && instance.parent.subTree.type;
  if (parentName && (parentName === "KeepAlive" || parentName.includes("Transition")) && typeof parentSubTreeType === "object" && parentSubTreeType.name === "RouterView") {
    const comp = parentName === "KeepAlive" ? "keep-alive" : "transition";
    warn$1(`<router-view> can no longer be used directly inside <transition> or <keep-alive>.
Use slot props instead:

<router-view v-slot="{ Component }">
  <${comp}>
    <component :is="Component" />
  </${comp}>
</router-view>`);
  }
}
__name(warnDeprecatedUsage, "warnDeprecatedUsage");
function formatRouteLocation(routeLocation, tooltip) {
  const copy2 = assign$3({}, routeLocation, {
    // remove variables that can contain vue instances
    matched: routeLocation.matched.map((matched) => omit$2(matched, ["instances", "children", "aliasOf"]))
  });
  return {
    _custom: {
      type: null,
      readOnly: true,
      display: routeLocation.fullPath,
      tooltip,
      value: copy2
    }
  };
}
__name(formatRouteLocation, "formatRouteLocation");
function formatDisplay(display) {
  return {
    _custom: {
      display
    }
  };
}
__name(formatDisplay, "formatDisplay");
let routerId = 0;
function addDevtools(app2, router2, matcher) {
  if (router2.__hasDevtools)
    return;
  router2.__hasDevtools = true;
  const id2 = routerId++;
  setupDevtoolsPlugin({
    id: "org.vuejs.router" + (id2 ? "." + id2 : ""),
    label: "Vue Router",
    packageName: "vue-router",
    homepage: "https://router.vuejs.org",
    logo: "https://router.vuejs.org/logo.png",
    componentStateTypes: ["Routing"],
    app: app2
  }, (api2) => {
    if (typeof api2.now !== "function") {
      console.warn("[Vue Router]: You seem to be using an outdated version of Vue Devtools. Are you still using the Beta release instead of the stable one? You can find the links at https://devtools.vuejs.org/guide/installation.html.");
    }
    api2.on.inspectComponent((payload, ctx) => {
      if (payload.instanceData) {
        payload.instanceData.state.push({
          type: "Routing",
          key: "$route",
          editable: false,
          value: formatRouteLocation(router2.currentRoute.value, "Current Route")
        });
      }
    });
    api2.on.visitComponentTree(({ treeNode: node2, componentInstance }) => {
      if (componentInstance.__vrv_devtools) {
        const info = componentInstance.__vrv_devtools;
        node2.tags.push({
          label: (info.name ? `${info.name.toString()}: ` : "") + info.path,
          textColor: 0,
          tooltip: "This component is rendered by &lt;router-view&gt;",
          backgroundColor: PINK_500
        });
      }
      if (isArray$9(componentInstance.__vrl_devtools)) {
        componentInstance.__devtoolsApi = api2;
        componentInstance.__vrl_devtools.forEach((devtoolsData) => {
          let label = devtoolsData.route.path;
          let backgroundColor = ORANGE_400;
          let tooltip = "";
          let textColor = 0;
          if (devtoolsData.error) {
            label = devtoolsData.error;
            backgroundColor = RED_100;
            textColor = RED_700;
          } else if (devtoolsData.isExactActive) {
            backgroundColor = LIME_500;
            tooltip = "This is exactly active";
          } else if (devtoolsData.isActive) {
            backgroundColor = BLUE_600;
            tooltip = "This link is active";
          }
          node2.tags.push({
            label,
            textColor,
            tooltip,
            backgroundColor
          });
        });
      }
    });
    watch(router2.currentRoute, () => {
      refreshRoutesView();
      api2.notifyComponentUpdate();
      api2.sendInspectorTree(routerInspectorId);
      api2.sendInspectorState(routerInspectorId);
    });
    const navigationsLayerId = "router:navigations:" + id2;
    api2.addTimelineLayer({
      id: navigationsLayerId,
      label: `Router${id2 ? " " + id2 : ""} Navigations`,
      color: 4237508
    });
    router2.onError((error2, to) => {
      api2.addTimelineEvent({
        layerId: navigationsLayerId,
        event: {
          title: "Error during Navigation",
          subtitle: to.fullPath,
          logType: "error",
          time: api2.now(),
          data: { error: error2 },
          groupId: to.meta.__navigationId
        }
      });
    });
    let navigationId = 0;
    router2.beforeEach((to, from2) => {
      const data = {
        guard: formatDisplay("beforeEach"),
        from: formatRouteLocation(from2, "Current Location during this navigation"),
        to: formatRouteLocation(to, "Target location")
      };
      Object.defineProperty(to.meta, "__navigationId", {
        value: navigationId++
      });
      api2.addTimelineEvent({
        layerId: navigationsLayerId,
        event: {
          time: api2.now(),
          title: "Start of navigation",
          subtitle: to.fullPath,
          data,
          groupId: to.meta.__navigationId
        }
      });
    });
    router2.afterEach((to, from2, failure) => {
      const data = {
        guard: formatDisplay("afterEach")
      };
      if (failure) {
        data.failure = {
          _custom: {
            type: Error,
            readOnly: true,
            display: failure ? failure.message : "",
            tooltip: "Navigation Failure",
            value: failure
          }
        };
        data.status = formatDisplay("❌");
      } else {
        data.status = formatDisplay("✅");
      }
      data.from = formatRouteLocation(from2, "Current Location during this navigation");
      data.to = formatRouteLocation(to, "Target location");
      api2.addTimelineEvent({
        layerId: navigationsLayerId,
        event: {
          title: "End of navigation",
          subtitle: to.fullPath,
          time: api2.now(),
          data,
          logType: failure ? "warning" : "default",
          groupId: to.meta.__navigationId
        }
      });
    });
    const routerInspectorId = "router-inspector:" + id2;
    api2.addInspector({
      id: routerInspectorId,
      label: "Routes" + (id2 ? " " + id2 : ""),
      icon: "book",
      treeFilterPlaceholder: "Search routes"
    });
    function refreshRoutesView() {
      if (!activeRoutesPayload)
        return;
      const payload = activeRoutesPayload;
      let routes = matcher.getRoutes().filter((route) => !route.parent || // these routes have a parent with no component which will not appear in the view
      // therefore we still need to include them
      !route.parent.record.components);
      routes.forEach(resetMatchStateOnRouteRecord);
      if (payload.filter) {
        routes = routes.filter((route) => (
          // save matches state based on the payload
          isRouteMatching(route, payload.filter.toLowerCase())
        ));
      }
      routes.forEach((route) => markRouteRecordActive(route, router2.currentRoute.value));
      payload.rootNodes = routes.map(formatRouteRecordForInspector);
    }
    __name(refreshRoutesView, "refreshRoutesView");
    let activeRoutesPayload;
    api2.on.getInspectorTree((payload) => {
      activeRoutesPayload = payload;
      if (payload.app === app2 && payload.inspectorId === routerInspectorId) {
        refreshRoutesView();
      }
    });
    api2.on.getInspectorState((payload) => {
      if (payload.app === app2 && payload.inspectorId === routerInspectorId) {
        const routes = matcher.getRoutes();
        const route = routes.find((route2) => route2.record.__vd_id === payload.nodeId);
        if (route) {
          payload.state = {
            options: formatRouteRecordMatcherForStateInspector(route)
          };
        }
      }
    });
    api2.sendInspectorTree(routerInspectorId);
    api2.sendInspectorState(routerInspectorId);
  });
}
__name(addDevtools, "addDevtools");
function modifierForKey(key) {
  if (key.optional) {
    return key.repeatable ? "*" : "?";
  } else {
    return key.repeatable ? "+" : "";
  }
}
__name(modifierForKey, "modifierForKey");
function formatRouteRecordMatcherForStateInspector(route) {
  const { record: record2 } = route;
  const fields = [
    { editable: false, key: "path", value: record2.path }
  ];
  if (record2.name != null) {
    fields.push({
      editable: false,
      key: "name",
      value: record2.name
    });
  }
  fields.push({ editable: false, key: "regexp", value: route.re });
  if (route.keys.length) {
    fields.push({
      editable: false,
      key: "keys",
      value: {
        _custom: {
          type: null,
          readOnly: true,
          display: route.keys.map((key) => `${key.name}${modifierForKey(key)}`).join(" "),
          tooltip: "Param keys",
          value: route.keys
        }
      }
    });
  }
  if (record2.redirect != null) {
    fields.push({
      editable: false,
      key: "redirect",
      value: record2.redirect
    });
  }
  if (route.alias.length) {
    fields.push({
      editable: false,
      key: "aliases",
      value: route.alias.map((alias) => alias.record.path)
    });
  }
  if (Object.keys(route.record.meta).length) {
    fields.push({
      editable: false,
      key: "meta",
      value: route.record.meta
    });
  }
  fields.push({
    key: "score",
    editable: false,
    value: {
      _custom: {
        type: null,
        readOnly: true,
        display: route.score.map((score) => score.join(", ")).join(" | "),
        tooltip: "Score used to sort routes",
        value: route.score
      }
    }
  });
  return fields;
}
__name(formatRouteRecordMatcherForStateInspector, "formatRouteRecordMatcherForStateInspector");
const PINK_500 = 15485081;
const BLUE_600 = 2450411;
const LIME_500 = 8702998;
const CYAN_400 = 2282478;
const ORANGE_400 = 16486972;
const DARK = 6710886;
const RED_100 = 16704226;
const RED_700 = 12131356;
function formatRouteRecordForInspector(route) {
  const tags = [];
  const { record: record2 } = route;
  if (record2.name != null) {
    tags.push({
      label: String(record2.name),
      textColor: 0,
      backgroundColor: CYAN_400
    });
  }
  if (record2.aliasOf) {
    tags.push({
      label: "alias",
      textColor: 0,
      backgroundColor: ORANGE_400
    });
  }
  if (route.__vd_match) {
    tags.push({
      label: "matches",
      textColor: 0,
      backgroundColor: PINK_500
    });
  }
  if (route.__vd_exactActive) {
    tags.push({
      label: "exact",
      textColor: 0,
      backgroundColor: LIME_500
    });
  }
  if (route.__vd_active) {
    tags.push({
      label: "active",
      textColor: 0,
      backgroundColor: BLUE_600
    });
  }
  if (record2.redirect) {
    tags.push({
      label: typeof record2.redirect === "string" ? `redirect: ${record2.redirect}` : "redirects",
      textColor: 16777215,
      backgroundColor: DARK
    });
  }
  let id2 = record2.__vd_id;
  if (id2 == null) {
    id2 = String(routeRecordId++);
    record2.__vd_id = id2;
  }
  return {
    id: id2,
    label: record2.path,
    tags,
    children: route.children.map(formatRouteRecordForInspector)
  };
}
__name(formatRouteRecordForInspector, "formatRouteRecordForInspector");
let routeRecordId = 0;
const EXTRACT_REGEXP_RE = /^\/(.*)\/([a-z]*)$/;
function markRouteRecordActive(route, currentRoute) {
  const isExactActive = currentRoute.matched.length && isSameRouteRecord(currentRoute.matched[currentRoute.matched.length - 1], route.record);
  route.__vd_exactActive = route.__vd_active = isExactActive;
  if (!isExactActive) {
    route.__vd_active = currentRoute.matched.some((match2) => isSameRouteRecord(match2, route.record));
  }
  route.children.forEach((childRoute) => markRouteRecordActive(childRoute, currentRoute));
}
__name(markRouteRecordActive, "markRouteRecordActive");
function resetMatchStateOnRouteRecord(route) {
  route.__vd_match = false;
  route.children.forEach(resetMatchStateOnRouteRecord);
}
__name(resetMatchStateOnRouteRecord, "resetMatchStateOnRouteRecord");
function isRouteMatching(route, filter3) {
  const found2 = String(route.re).match(EXTRACT_REGEXP_RE);
  route.__vd_match = false;
  if (!found2 || found2.length < 3) {
    return false;
  }
  const nonEndingRE = new RegExp(found2[1].replace(/\$$/, ""), found2[2]);
  if (nonEndingRE.test(filter3)) {
    route.children.forEach((child2) => isRouteMatching(child2, filter3));
    if (route.record.path !== "/" || filter3 === "/") {
      route.__vd_match = route.re.test(filter3);
      return true;
    }
    return false;
  }
  const path = route.record.path.toLowerCase();
  const decodedPath = decode$3(path);
  if (!filter3.startsWith("/") && (decodedPath.includes(filter3) || path.includes(filter3)))
    return true;
  if (decodedPath.startsWith(filter3) || path.startsWith(filter3))
    return true;
  if (route.record.name && String(route.record.name).includes(filter3))
    return true;
  return route.children.some((child2) => isRouteMatching(child2, filter3));
}
__name(isRouteMatching, "isRouteMatching");
function omit$2(obj, keys2) {
  const ret = {};
  for (const key in obj) {
    if (!keys2.includes(key)) {
      ret[key] = obj[key];
    }
  }
  return ret;
}
__name(omit$2, "omit$2");
function createRouter(options2) {
  const matcher = createRouterMatcher(options2.routes, options2);
  const parseQuery$1$1 = options2.parseQuery || parseQuery$1;
  const stringifyQuery$1 = options2.stringifyQuery || stringifyQuery;
  const routerHistory = options2.history;
  if (false)
    throw new Error('Provide the "history" option when calling "createRouter()": https://router.vuejs.org/api/interfaces/RouterOptions.html#history');
  const beforeGuards = useCallbacks();
  const beforeResolveGuards = useCallbacks();
  const afterGuards = useCallbacks();
  const currentRoute = shallowRef(START_LOCATION_NORMALIZED);
  let pendingLocation = START_LOCATION_NORMALIZED;
  if (isBrowser && options2.scrollBehavior && "scrollRestoration" in history) {
    history.scrollRestoration = "manual";
  }
  const normalizeParams = applyToParams.bind(null, (paramValue) => "" + paramValue);
  const encodeParams = applyToParams.bind(null, encodeParam);
  const decodeParams = (
    // @ts-expect-error: intentionally avoid the type check
    applyToParams.bind(null, decode$3)
  );
  function addRoute(parentOrRoute, route) {
    let parent2;
    let record2;
    if (isRouteName(parentOrRoute)) {
      parent2 = matcher.getRecordMatcher(parentOrRoute);
      if (false) {
        warn$1(`Parent route "${String(parentOrRoute)}" not found when adding child route`, route);
      }
      record2 = route;
    } else {
      record2 = parentOrRoute;
    }
    return matcher.addRoute(record2, parent2);
  }
  __name(addRoute, "addRoute");
  function removeRoute(name2) {
    const recordMatcher = matcher.getRecordMatcher(name2);
    if (recordMatcher) {
      matcher.removeRoute(recordMatcher);
    } else if (false) {
      warn$1(`Cannot remove non-existent route "${String(name2)}"`);
    }
  }
  __name(removeRoute, "removeRoute");
  function getRoutes() {
    return matcher.getRoutes().map((routeMatcher) => routeMatcher.record);
  }
  __name(getRoutes, "getRoutes");
  function hasRoute(name2) {
    return !!matcher.getRecordMatcher(name2);
  }
  __name(hasRoute, "hasRoute");
  function resolve2(rawLocation, currentLocation) {
    currentLocation = assign$3({}, currentLocation || currentRoute.value);
    if (typeof rawLocation === "string") {
      const locationNormalized = parseURL(parseQuery$1$1, rawLocation, currentLocation.path);
      const matchedRoute2 = matcher.resolve({ path: locationNormalized.path }, currentLocation);
      const href2 = routerHistory.createHref(locationNormalized.fullPath);
      if (false) {
        if (href2.startsWith("//"))
          warn$1(`Location "${rawLocation}" resolved to "${href2}". A resolved location cannot start with multiple slashes.`);
        else if (!matchedRoute2.matched.length) {
          warn$1(`No match found for location with path "${rawLocation}"`);
        }
      }
      return assign$3(locationNormalized, matchedRoute2, {
        params: decodeParams(matchedRoute2.params),
        hash: decode$3(locationNormalized.hash),
        redirectedFrom: void 0,
        href: href2
      });
    }
    if (false) {
      warn$1(`router.resolve() was passed an invalid location. This will fail in production.
- Location:`, rawLocation);
      return resolve2({});
    }
    let matcherLocation;
    if (rawLocation.path != null) {
      if (false) {
        warn$1(`Path "${rawLocation.path}" was passed with params but they will be ignored. Use a named route alongside params instead.`);
      }
      matcherLocation = assign$3({}, rawLocation, {
        path: parseURL(parseQuery$1$1, rawLocation.path, currentLocation.path).path
      });
    } else {
      const targetParams = assign$3({}, rawLocation.params);
      for (const key in targetParams) {
        if (targetParams[key] == null) {
          delete targetParams[key];
        }
      }
      matcherLocation = assign$3({}, rawLocation, {
        params: encodeParams(targetParams)
      });
      currentLocation.params = encodeParams(currentLocation.params);
    }
    const matchedRoute = matcher.resolve(matcherLocation, currentLocation);
    const hash = rawLocation.hash || "";
    if (false) {
      warn$1(`A \`hash\` should always start with the character "#". Replace "${hash}" with "#${hash}".`);
    }
    matchedRoute.params = normalizeParams(decodeParams(matchedRoute.params));
    const fullPath = stringifyURL(stringifyQuery$1, assign$3({}, rawLocation, {
      hash: encodeHash(hash),
      path: matchedRoute.path
    }));
    const href = routerHistory.createHref(fullPath);
    if (false) {
      if (href.startsWith("//")) {
        warn$1(`Location "${rawLocation}" resolved to "${href}". A resolved location cannot start with multiple slashes.`);
      } else if (!matchedRoute.matched.length) {
        warn$1(`No match found for location with path "${rawLocation.path != null ? rawLocation.path : rawLocation}"`);
      }
    }
    return assign$3({
      fullPath,
      // keep the hash encoded so fullPath is effectively path + encodedQuery +
      // hash
      hash,
      query: (
        // if the user is using a custom query lib like qs, we might have
        // nested objects, so we keep the query as is, meaning it can contain
        // numbers at `$route.query`, but at the point, the user will have to
        // use their own type anyway.
        // https://github.com/vuejs/router/issues/328#issuecomment-649481567
        stringifyQuery$1 === stringifyQuery ? normalizeQuery(rawLocation.query) : rawLocation.query || {}
      )
    }, matchedRoute, {
      redirectedFrom: void 0,
      href
    });
  }
  __name(resolve2, "resolve");
  function locationAsObject(to) {
    return typeof to === "string" ? parseURL(parseQuery$1$1, to, currentRoute.value.path) : assign$3({}, to);
  }
  __name(locationAsObject, "locationAsObject");
  function checkCanceledNavigation(to, from2) {
    if (pendingLocation !== to) {
      return createRouterError(8, {
        from: from2,
        to
      });
    }
  }
  __name(checkCanceledNavigation, "checkCanceledNavigation");
  function push2(to) {
    return pushWithRedirect(to);
  }
  __name(push2, "push");
  function replace2(to) {
    return push2(assign$3(locationAsObject(to), { replace: true }));
  }
  __name(replace2, "replace");
  function handleRedirectRecord(to) {
    const lastMatched = to.matched[to.matched.length - 1];
    if (lastMatched && lastMatched.redirect) {
      const { redirect } = lastMatched;
      let newTargetLocation = typeof redirect === "function" ? redirect(to) : redirect;
      if (typeof newTargetLocation === "string") {
        newTargetLocation = newTargetLocation.includes("?") || newTargetLocation.includes("#") ? newTargetLocation = locationAsObject(newTargetLocation) : (
          // force empty params
          { path: newTargetLocation }
        );
        newTargetLocation.params = {};
      }
      if (false) {
        warn$1(`Invalid redirect found:
${JSON.stringify(newTargetLocation, null, 2)}
 when navigating to "${to.fullPath}". A redirect must contain a name or path. This will break in production.`);
        throw new Error("Invalid redirect");
      }
      return assign$3({
        query: to.query,
        hash: to.hash,
        // avoid transferring params if the redirect has a path
        params: newTargetLocation.path != null ? {} : to.params
      }, newTargetLocation);
    }
  }
  __name(handleRedirectRecord, "handleRedirectRecord");
  function pushWithRedirect(to, redirectedFrom) {
    const targetLocation = pendingLocation = resolve2(to);
    const from2 = currentRoute.value;
    const data = to.state;
    const force = to.force;
    const replace22 = to.replace === true;
    const shouldRedirect = handleRedirectRecord(targetLocation);
    if (shouldRedirect)
      return pushWithRedirect(
        assign$3(locationAsObject(shouldRedirect), {
          state: typeof shouldRedirect === "object" ? assign$3({}, data, shouldRedirect.state) : data,
          force,
          replace: replace22
        }),
        // keep original redirectedFrom if it exists
        redirectedFrom || targetLocation
      );
    const toLocation = targetLocation;
    toLocation.redirectedFrom = redirectedFrom;
    let failure;
    if (!force && isSameRouteLocation(stringifyQuery$1, from2, targetLocation)) {
      failure = createRouterError(16, { to: toLocation, from: from2 });
      handleScroll(
        from2,
        from2,
        // this is a push, the only way for it to be triggered from a
        // history.listen is with a redirect, which makes it become a push
        true,
        // This cannot be the first navigation because the initial location
        // cannot be manually navigated to
        false
      );
    }
    return (failure ? Promise.resolve(failure) : navigate(toLocation, from2)).catch((error2) => isNavigationFailure(error2) ? (
      // navigation redirects still mark the router as ready
      isNavigationFailure(
        error2,
        2
        /* ErrorTypes.NAVIGATION_GUARD_REDIRECT */
      ) ? error2 : markAsReady(error2)
    ) : (
      // reject any unknown error
      triggerError(error2, toLocation, from2)
    )).then((failure2) => {
      if (failure2) {
        if (isNavigationFailure(
          failure2,
          2
          /* ErrorTypes.NAVIGATION_GUARD_REDIRECT */
        )) {
          if (false) {
            warn$1(`Detected a possibly infinite redirection in a navigation guard when going from "${from2.fullPath}" to "${toLocation.fullPath}". Aborting to avoid a Stack Overflow.
 Are you always returning a new location within a navigation guard? That would lead to this error. Only return when redirecting or aborting, that should fix this. This might break in production if not fixed.`);
            return Promise.reject(new Error("Infinite redirect in navigation guard"));
          }
          return pushWithRedirect(
            // keep options
            assign$3({
              // preserve an existing replacement but allow the redirect to override it
              replace: replace22
            }, locationAsObject(failure2.to), {
              state: typeof failure2.to === "object" ? assign$3({}, data, failure2.to.state) : data,
              force
            }),
            // preserve the original redirectedFrom if any
            redirectedFrom || toLocation
          );
        }
      } else {
        failure2 = finalizeNavigation(toLocation, from2, true, replace22, data);
      }
      triggerAfterEach(toLocation, from2, failure2);
      return failure2;
    });
  }
  __name(pushWithRedirect, "pushWithRedirect");
  function checkCanceledNavigationAndReject(to, from2) {
    const error2 = checkCanceledNavigation(to, from2);
    return error2 ? Promise.reject(error2) : Promise.resolve();
  }
  __name(checkCanceledNavigationAndReject, "checkCanceledNavigationAndReject");
  function runWithContext(fn) {
    const app2 = installedApps.values().next().value;
    return app2 && typeof app2.runWithContext === "function" ? app2.runWithContext(fn) : fn();
  }
  __name(runWithContext, "runWithContext");
  function navigate(to, from2) {
    let guards;
    const [leavingRecords, updatingRecords, enteringRecords] = extractChangingRecords(to, from2);
    guards = extractComponentsGuards(leavingRecords.reverse(), "beforeRouteLeave", to, from2);
    for (const record2 of leavingRecords) {
      record2.leaveGuards.forEach((guard) => {
        guards.push(guardToPromiseFn(guard, to, from2));
      });
    }
    const canceledNavigationCheck = checkCanceledNavigationAndReject.bind(null, to, from2);
    guards.push(canceledNavigationCheck);
    return runGuardQueue(guards).then(() => {
      guards = [];
      for (const guard of beforeGuards.list()) {
        guards.push(guardToPromiseFn(guard, to, from2));
      }
      guards.push(canceledNavigationCheck);
      return runGuardQueue(guards);
    }).then(() => {
      guards = extractComponentsGuards(updatingRecords, "beforeRouteUpdate", to, from2);
      for (const record2 of updatingRecords) {
        record2.updateGuards.forEach((guard) => {
          guards.push(guardToPromiseFn(guard, to, from2));
        });
      }
      guards.push(canceledNavigationCheck);
      return runGuardQueue(guards);
    }).then(() => {
      guards = [];
      for (const record2 of enteringRecords) {
        if (record2.beforeEnter) {
          if (isArray$9(record2.beforeEnter)) {
            for (const beforeEnter of record2.beforeEnter)
              guards.push(guardToPromiseFn(beforeEnter, to, from2));
          } else {
            guards.push(guardToPromiseFn(record2.beforeEnter, to, from2));
          }
        }
      }
      guards.push(canceledNavigationCheck);
      return runGuardQueue(guards);
    }).then(() => {
      to.matched.forEach((record2) => record2.enterCallbacks = {});
      guards = extractComponentsGuards(enteringRecords, "beforeRouteEnter", to, from2, runWithContext);
      guards.push(canceledNavigationCheck);
      return runGuardQueue(guards);
    }).then(() => {
      guards = [];
      for (const guard of beforeResolveGuards.list()) {
        guards.push(guardToPromiseFn(guard, to, from2));
      }
      guards.push(canceledNavigationCheck);
      return runGuardQueue(guards);
    }).catch((err) => isNavigationFailure(
      err,
      8
      /* ErrorTypes.NAVIGATION_CANCELLED */
    ) ? err : Promise.reject(err));
  }
  __name(navigate, "navigate");
  function triggerAfterEach(to, from2, failure) {
    afterGuards.list().forEach((guard) => runWithContext(() => guard(to, from2, failure)));
  }
  __name(triggerAfterEach, "triggerAfterEach");
  function finalizeNavigation(toLocation, from2, isPush, replace22, data) {
    const error2 = checkCanceledNavigation(toLocation, from2);
    if (error2)
      return error2;
    const isFirstNavigation = from2 === START_LOCATION_NORMALIZED;
    const state = !isBrowser ? {} : history.state;
    if (isPush) {
      if (replace22 || isFirstNavigation)
        routerHistory.replace(toLocation.fullPath, assign$3({
          scroll: isFirstNavigation && state && state.scroll
        }, data));
      else
        routerHistory.push(toLocation.fullPath, data);
    }
    currentRoute.value = toLocation;
    handleScroll(toLocation, from2, isPush, isFirstNavigation);
    markAsReady();
  }
  __name(finalizeNavigation, "finalizeNavigation");
  let removeHistoryListener;
  function setupListeners() {
    if (removeHistoryListener)
      return;
    removeHistoryListener = routerHistory.listen((to, _from, info) => {
      if (!router2.listening)
        return;
      const toLocation = resolve2(to);
      const shouldRedirect = handleRedirectRecord(toLocation);
      if (shouldRedirect) {
        pushWithRedirect(assign$3(shouldRedirect, { replace: true }), toLocation).catch(noop$3);
        return;
      }
      pendingLocation = toLocation;
      const from2 = currentRoute.value;
      if (isBrowser) {
        saveScrollPosition(getScrollKey(from2.fullPath, info.delta), computeScrollPosition());
      }
      navigate(toLocation, from2).catch((error2) => {
        if (isNavigationFailure(
          error2,
          4 | 8
          /* ErrorTypes.NAVIGATION_CANCELLED */
        )) {
          return error2;
        }
        if (isNavigationFailure(
          error2,
          2
          /* ErrorTypes.NAVIGATION_GUARD_REDIRECT */
        )) {
          pushWithRedirect(
            error2.to,
            toLocation
            // avoid an uncaught rejection, let push call triggerError
          ).then((failure) => {
            if (isNavigationFailure(
              failure,
              4 | 16
              /* ErrorTypes.NAVIGATION_DUPLICATED */
            ) && !info.delta && info.type === NavigationType.pop) {
              routerHistory.go(-1, false);
            }
          }).catch(noop$3);
          return Promise.reject();
        }
        if (info.delta) {
          routerHistory.go(-info.delta, false);
        }
        return triggerError(error2, toLocation, from2);
      }).then((failure) => {
        failure = failure || finalizeNavigation(
          // after navigation, all matched components are resolved
          toLocation,
          from2,
          false
        );
        if (failure) {
          if (info.delta && // a new navigation has been triggered, so we do not want to revert, that will change the current history
          // entry while a different route is displayed
          !isNavigationFailure(
            failure,
            8
            /* ErrorTypes.NAVIGATION_CANCELLED */
          )) {
            routerHistory.go(-info.delta, false);
          } else if (info.type === NavigationType.pop && isNavigationFailure(
            failure,
            4 | 16
            /* ErrorTypes.NAVIGATION_DUPLICATED */
          )) {
            routerHistory.go(-1, false);
          }
        }
        triggerAfterEach(toLocation, from2, failure);
      }).catch(noop$3);
    });
  }
  __name(setupListeners, "setupListeners");
  let readyHandlers = useCallbacks();
  let errorListeners = useCallbacks();
  let ready;
  function triggerError(error2, to, from2) {
    markAsReady(error2);
    const list2 = errorListeners.list();
    if (list2.length) {
      list2.forEach((handler5) => handler5(error2, to, from2));
    } else {
      if (false) {
        warn$1("uncaught error during route navigation:");
      }
      console.error(error2);
    }
    return Promise.reject(error2);
  }
  __name(triggerError, "triggerError");
  function isReady() {
    if (ready && currentRoute.value !== START_LOCATION_NORMALIZED)
      return Promise.resolve();
    return new Promise((resolve22, reject) => {
      readyHandlers.add([resolve22, reject]);
    });
  }
  __name(isReady, "isReady");
  function markAsReady(err) {
    if (!ready) {
      ready = !err;
      setupListeners();
      readyHandlers.list().forEach(([resolve22, reject]) => err ? reject(err) : resolve22());
      readyHandlers.reset();
    }
    return err;
  }
  __name(markAsReady, "markAsReady");
  function handleScroll(to, from2, isPush, isFirstNavigation) {
    const { scrollBehavior } = options2;
    if (!isBrowser || !scrollBehavior)
      return Promise.resolve();
    const scrollPosition = !isPush && getSavedScrollPosition(getScrollKey(to.fullPath, 0)) || (isFirstNavigation || !isPush) && history.state && history.state.scroll || null;
    return nextTick().then(() => scrollBehavior(to, from2, scrollPosition)).then((position) => position && scrollToPosition(position)).catch((err) => triggerError(err, to, from2));
  }
  __name(handleScroll, "handleScroll");
  const go = /* @__PURE__ */ __name((delta2) => routerHistory.go(delta2), "go");
  let started;
  const installedApps = /* @__PURE__ */ new Set();
  const router2 = {
    currentRoute,
    listening: true,
    addRoute,
    removeRoute,
    clearRoutes: matcher.clearRoutes,
    hasRoute,
    getRoutes,
    resolve: resolve2,
    options: options2,
    push: push2,
    replace: replace2,
    go,
    back: /* @__PURE__ */ __name(() => go(-1), "back"),
    forward: /* @__PURE__ */ __name(() => go(1), "forward"),
    beforeEach: beforeGuards.add,
    beforeResolve: beforeResolveGuards.add,
    afterEach: afterGuards.add,
    onError: errorListeners.add,
    isReady,
    install(app2) {
      const router22 = this;
      app2.component("RouterLink", RouterLink);
      app2.component("RouterView", RouterView);
      app2.config.globalProperties.$router = router22;
      Object.defineProperty(app2.config.globalProperties, "$route", {
        enumerable: true,
        get: /* @__PURE__ */ __name(() => unref(currentRoute), "get")
      });
      if (isBrowser && // used for the initial navigation client side to avoid pushing
      // multiple times when the router is used in multiple apps
      !started && currentRoute.value === START_LOCATION_NORMALIZED) {
        started = true;
        push2(routerHistory.location).catch((err) => {
          if (false)
            warn$1("Unexpected error when starting the router:", err);
        });
      }
      const reactiveRoute = {};
      for (const key in START_LOCATION_NORMALIZED) {
        Object.defineProperty(reactiveRoute, key, {
          get: /* @__PURE__ */ __name(() => currentRoute.value[key], "get"),
          enumerable: true
        });
      }
      app2.provide(routerKey, router22);
      app2.provide(routeLocationKey, shallowReactive(reactiveRoute));
      app2.provide(routerViewLocationKey, currentRoute);
      const unmountApp = app2.unmount;
      installedApps.add(app2);
      app2.unmount = function() {
        installedApps.delete(app2);
        if (installedApps.size < 1) {
          pendingLocation = START_LOCATION_NORMALIZED;
          removeHistoryListener && removeHistoryListener();
          removeHistoryListener = null;
          currentRoute.value = START_LOCATION_NORMALIZED;
          started = false;
          ready = false;
        }
        unmountApp();
      };
      if (false) {
        addDevtools(app2, router22, matcher);
      }
    }
  };
  function runGuardQueue(guards) {
    return guards.reduce((promise, guard) => promise.then(() => runWithContext(guard)), Promise.resolve());
  }
  __name(runGuardQueue, "runGuardQueue");
  return router2;
}
__name(createRouter, "createRouter");
function extractChangingRecords(to, from2) {
  const leavingRecords = [];
  const updatingRecords = [];
  const enteringRecords = [];
  const len = Math.max(from2.matched.length, to.matched.length);
  for (let i2 = 0; i2 < len; i2++) {
    const recordFrom = from2.matched[i2];
    if (recordFrom) {
      if (to.matched.find((record2) => isSameRouteRecord(record2, recordFrom)))
        updatingRecords.push(recordFrom);
      else
        leavingRecords.push(recordFrom);
    }
    const recordTo = to.matched[i2];
    if (recordTo) {
      if (!from2.matched.find((record2) => isSameRouteRecord(record2, recordTo))) {
        enteringRecords.push(recordTo);
      }
    }
  }
  return [leavingRecords, updatingRecords, enteringRecords];
}
__name(extractChangingRecords, "extractChangingRecords");
function useRouter() {
  return inject(routerKey);
}
__name(useRouter, "useRouter");
function useRoute(_name) {
  return inject(routeLocationKey);
}
__name(useRoute, "useRoute");
function computedEager(fn, options2) {
  var _a2;
  const result = shallowRef();
  watchEffect(() => {
    result.value = fn();
  }, {
    ...options2,
    flush: (_a2 = options2 == null ? void 0 : options2.flush) != null ? _a2 : "sync"
  });
  return readonly(result);
}
__name(computedEager, "computedEager");
function computedWithControl(source, fn) {
  let v2 = void 0;
  let track;
  let trigger;
  const dirty = ref$3(true);
  const update2 = /* @__PURE__ */ __name(() => {
    dirty.value = true;
    trigger();
  }, "update");
  watch(source, update2, { flush: "sync" });
  const get22 = typeof fn === "function" ? fn : fn.get;
  const set22 = typeof fn === "function" ? void 0 : fn.set;
  const result = customRef((_track, _trigger) => {
    track = _track;
    trigger = _trigger;
    return {
      get() {
        if (dirty.value) {
          v2 = get22(v2);
          dirty.value = false;
        }
        track();
        return v2;
      },
      set(v22) {
        set22 == null ? void 0 : set22(v22);
      }
    };
  });
  if (Object.isExtensible(result))
    result.trigger = update2;
  return result;
}
__name(computedWithControl, "computedWithControl");
function tryOnScopeDispose(fn) {
  if (getCurrentScope$1()) {
    onScopeDispose(fn);
    return true;
  }
  return false;
}
__name(tryOnScopeDispose, "tryOnScopeDispose");
function createEventHook() {
  const fns = /* @__PURE__ */ new Set();
  const off2 = /* @__PURE__ */ __name((fn) => {
    fns.delete(fn);
  }, "off");
  const on2 = /* @__PURE__ */ __name((fn) => {
    fns.add(fn);
    const offFn = /* @__PURE__ */ __name(() => off2(fn), "offFn");
    tryOnScopeDispose(offFn);
    return {
      off: offFn
    };
  }, "on");
  const trigger = /* @__PURE__ */ __name((...args) => {
    return Promise.all(Array.from(fns).map((fn) => fn(...args)));
  }, "trigger");
  return {
    on: on2,
    off: off2,
    trigger
  };
}
__name(createEventHook, "createEventHook");
function createGlobalState(stateFactory) {
  let initialized = false;
  let state;
  const scope = effectScope(true);
  return (...args) => {
    if (!initialized) {
      state = scope.run(() => stateFactory(...args));
      initialized = true;
    }
    return state;
  };
}
__name(createGlobalState, "createGlobalState");
const localProvidedStateMap = /* @__PURE__ */ new WeakMap();
const provideLocal = /* @__PURE__ */ __name((key, value) => {
  var _a2;
  const instance = (_a2 = getCurrentInstance()) == null ? void 0 : _a2.proxy;
  if (instance == null)
    throw new Error("provideLocal must be called in setup");
  if (!localProvidedStateMap.has(instance))
    localProvidedStateMap.set(instance, /* @__PURE__ */ Object.create(null));
  const localProvidedState = localProvidedStateMap.get(instance);
  localProvidedState[key] = value;
  provide(key, value);
}, "provideLocal");
const injectLocal = /* @__PURE__ */ __name((...args) => {
  var _a2;
  const key = args[0];
  const instance = (_a2 = getCurrentInstance()) == null ? void 0 : _a2.proxy;
  if (instance == null)
    throw new Error("injectLocal must be called in setup");
  if (localProvidedStateMap.has(instance) && key in localProvidedStateMap.get(instance))
    return localProvidedStateMap.get(instance)[key];
  return inject(...args);
}, "injectLocal");
function createInjectionState(composable, options2) {
  const key = (options2 == null ? void 0 : options2.injectionKey) || Symbol(composable.name || "InjectionState");
  const defaultValue = options2 == null ? void 0 : options2.defaultValue;
  const useProvidingState = /* @__PURE__ */ __name((...args) => {
    const state = composable(...args);
    provideLocal(key, state);
    return state;
  }, "useProvidingState");
  const useInjectedState = /* @__PURE__ */ __name(() => injectLocal(key, defaultValue), "useInjectedState");
  return [useProvidingState, useInjectedState];
}
__name(createInjectionState, "createInjectionState");
function createSharedComposable(composable) {
  let subscribers = 0;
  let state;
  let scope;
  const dispose = /* @__PURE__ */ __name(() => {
    subscribers -= 1;
    if (scope && subscribers <= 0) {
      scope.stop();
      state = void 0;
      scope = void 0;
    }
  }, "dispose");
  return (...args) => {
    subscribers += 1;
    if (!state) {
      scope = effectScope(true);
      state = scope.run(() => composable(...args));
    }
    tryOnScopeDispose(dispose);
    return state;
  };
}
__name(createSharedComposable, "createSharedComposable");
function extendRef(ref2, extend3, { enumerable = false, unwrap: unwrap2 = true } = {}) {
  if (!isVue3 && !version$6.startsWith("2.7.")) {
    if (false)
      throw new Error("[VueUse] extendRef only works in Vue 2.7 or above.");
    return;
  }
  for (const [key, value] of Object.entries(extend3)) {
    if (key === "value")
      continue;
    if (isRef(value) && unwrap2) {
      Object.defineProperty(ref2, key, {
        get() {
          return value.value;
        },
        set(v2) {
          value.value = v2;
        },
        enumerable
      });
    } else {
      Object.defineProperty(ref2, key, { value, enumerable });
    }
  }
  return ref2;
}
__name(extendRef, "extendRef");
function get$2(obj, key) {
  if (key == null)
    return unref(obj);
  return unref(obj)[key];
}
__name(get$2, "get$2");
function isDefined$1(v2) {
  return unref(v2) != null;
}
__name(isDefined$1, "isDefined$1");
function makeDestructurable(obj, arr) {
  if (typeof Symbol !== "undefined") {
    const clone2 = { ...obj };
    Object.defineProperty(clone2, Symbol.iterator, {
      enumerable: false,
      value() {
        let index2 = 0;
        return {
          next: /* @__PURE__ */ __name(() => ({
            value: arr[index2++],
            done: index2 > arr.length
          }), "next")
        };
      }
    });
    return clone2;
  } else {
    return Object.assign([...arr], obj);
  }
}
__name(makeDestructurable, "makeDestructurable");
function toValue$3(r2) {
  return typeof r2 === "function" ? r2() : unref(r2);
}
__name(toValue$3, "toValue$3");
const resolveUnref = toValue$3;
function reactify(fn, options2) {
  const unrefFn = (options2 == null ? void 0 : options2.computedGetter) === false ? unref : toValue$3;
  return function(...args) {
    return computed(() => fn.apply(this, args.map((i2) => unrefFn(i2))));
  };
}
__name(reactify, "reactify");
function reactifyObject(obj, optionsOrKeys = {}) {
  let keys2 = [];
  let options2;
  if (Array.isArray(optionsOrKeys)) {
    keys2 = optionsOrKeys;
  } else {
    options2 = optionsOrKeys;
    const { includeOwnProperties = true } = optionsOrKeys;
    keys2.push(...Object.keys(obj));
    if (includeOwnProperties)
      keys2.push(...Object.getOwnPropertyNames(obj));
  }
  return Object.fromEntries(
    keys2.map((key) => {
      const value = obj[key];
      return [
        key,
        typeof value === "function" ? reactify(value.bind(obj), options2) : value
      ];
    })
  );
}
__name(reactifyObject, "reactifyObject");
function toReactive(objectRef) {
  if (!isRef(objectRef))
    return reactive(objectRef);
  const proxy = new Proxy({}, {
    get(_2, p2, receiver) {
      return unref(Reflect.get(objectRef.value, p2, receiver));
    },
    set(_2, p2, value) {
      if (isRef(objectRef.value[p2]) && !isRef(value))
        objectRef.value[p2].value = value;
      else
        objectRef.value[p2] = value;
      return true;
    },
    deleteProperty(_2, p2) {
      return Reflect.deleteProperty(objectRef.value, p2);
    },
    has(_2, p2) {
      return Reflect.has(objectRef.value, p2);
    },
    ownKeys() {
      return Object.keys(objectRef.value);
    },
    getOwnPropertyDescriptor() {
      return {
        enumerable: true,
        configurable: true
      };
    }
  });
  return reactive(proxy);
}
__name(toReactive, "toReactive");
function reactiveComputed(fn) {
  return toReactive(computed(fn));
}
__name(reactiveComputed, "reactiveComputed");
function reactiveOmit(obj, ...keys2) {
  const flatKeys = keys2.flat();
  const predicate = flatKeys[0];
  return reactiveComputed(() => typeof predicate === "function" ? Object.fromEntries(Object.entries(toRefs$1(obj)).filter(([k2, v2]) => !predicate(toValue$3(v2), k2))) : Object.fromEntries(Object.entries(toRefs$1(obj)).filter((e2) => !flatKeys.includes(e2[0]))));
}
__name(reactiveOmit, "reactiveOmit");
const isClient$1 = typeof window !== "undefined" && typeof document !== "undefined";
const isWorker = typeof WorkerGlobalScope !== "undefined" && globalThis instanceof WorkerGlobalScope;
const isDef = /* @__PURE__ */ __name((val) => typeof val !== "undefined", "isDef");
const notNullish = /* @__PURE__ */ __name((val) => val != null, "notNullish");
const assert = /* @__PURE__ */ __name((condition, ...infos) => {
  if (!condition)
    console.warn(...infos);
}, "assert");
const toString$2 = Object.prototype.toString;
const isObject$c = /* @__PURE__ */ __name((val) => toString$2.call(val) === "[object Object]", "isObject$c");
const now = /* @__PURE__ */ __name(() => Date.now(), "now");
const timestamp = /* @__PURE__ */ __name(() => +Date.now(), "timestamp");
const clamp$1 = /* @__PURE__ */ __name((n2, min, max) => Math.min(max, Math.max(min, n2)), "clamp$1");
const noop$2 = /* @__PURE__ */ __name(() => {
}, "noop$2");
const rand = /* @__PURE__ */ __name((min, max) => {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}, "rand");
const hasOwn$1 = /* @__PURE__ */ __name((val, key) => Object.prototype.hasOwnProperty.call(val, key), "hasOwn$1");
const isIOS$1 = /* @__PURE__ */ getIsIOS();
function getIsIOS() {
  var _a2, _b;
  return isClient$1 && ((_a2 = window == null ? void 0 : window.navigator) == null ? void 0 : _a2.userAgent) && (/iP(?:ad|hone|od)/.test(window.navigator.userAgent) || ((_b = window == null ? void 0 : window.navigator) == null ? void 0 : _b.maxTouchPoints) > 2 && /iPad|Macintosh/.test(window == null ? void 0 : window.navigator.userAgent));
}
__name(getIsIOS, "getIsIOS");
function createFilterWrapper(filter3, fn) {
  function wrapper(...args) {
    return new Promise((resolve2, reject) => {
      Promise.resolve(filter3(() => fn.apply(this, args), { fn, thisArg: this, args })).then(resolve2).catch(reject);
    });
  }
  __name(wrapper, "wrapper");
  return wrapper;
}
__name(createFilterWrapper, "createFilterWrapper");
const bypassFilter = /* @__PURE__ */ __name((invoke2) => {
  return invoke2();
}, "bypassFilter");
function debounceFilter(ms, options2 = {}) {
  let timer;
  let maxTimer;
  let lastRejector = noop$2;
  const _clearTimeout = /* @__PURE__ */ __name((timer2) => {
    clearTimeout(timer2);
    lastRejector();
    lastRejector = noop$2;
  }, "_clearTimeout");
  const filter3 = /* @__PURE__ */ __name((invoke2) => {
    const duration = toValue$3(ms);
    const maxDuration = toValue$3(options2.maxWait);
    if (timer)
      _clearTimeout(timer);
    if (duration <= 0 || maxDuration !== void 0 && maxDuration <= 0) {
      if (maxTimer) {
        _clearTimeout(maxTimer);
        maxTimer = null;
      }
      return Promise.resolve(invoke2());
    }
    return new Promise((resolve2, reject) => {
      lastRejector = options2.rejectOnCancel ? reject : resolve2;
      if (maxDuration && !maxTimer) {
        maxTimer = setTimeout(() => {
          if (timer)
            _clearTimeout(timer);
          maxTimer = null;
          resolve2(invoke2());
        }, maxDuration);
      }
      timer = setTimeout(() => {
        if (maxTimer)
          _clearTimeout(maxTimer);
        maxTimer = null;
        resolve2(invoke2());
      }, duration);
    });
  }, "filter");
  return filter3;
}
__name(debounceFilter, "debounceFilter");
function throttleFilter(...args) {
  let lastExec = 0;
  let timer;
  let isLeading = true;
  let lastRejector = noop$2;
  let lastValue;
  let ms;
  let trailing;
  let leading;
  let rejectOnCancel;
  if (!isRef(args[0]) && typeof args[0] === "object")
    ({ delay: ms, trailing = true, leading = true, rejectOnCancel = false } = args[0]);
  else
    [ms, trailing = true, leading = true, rejectOnCancel = false] = args;
  const clear = /* @__PURE__ */ __name(() => {
    if (timer) {
      clearTimeout(timer);
      timer = void 0;
      lastRejector();
      lastRejector = noop$2;
    }
  }, "clear");
  const filter3 = /* @__PURE__ */ __name((_invoke) => {
    const duration = toValue$3(ms);
    const elapsed = Date.now() - lastExec;
    const invoke2 = /* @__PURE__ */ __name(() => {
      return lastValue = _invoke();
    }, "invoke2");
    clear();
    if (duration <= 0) {
      lastExec = Date.now();
      return invoke2();
    }
    if (elapsed > duration && (leading || !isLeading)) {
      lastExec = Date.now();
      invoke2();
    } else if (trailing) {
      lastValue = new Promise((resolve2, reject) => {
        lastRejector = rejectOnCancel ? reject : resolve2;
        timer = setTimeout(() => {
          lastExec = Date.now();
          isLeading = true;
          resolve2(invoke2());
          clear();
        }, Math.max(0, duration - elapsed));
      });
    }
    if (!leading && !timer)
      timer = setTimeout(() => isLeading = true, duration);
    isLeading = false;
    return lastValue;
  }, "filter");
  return filter3;
}
__name(throttleFilter, "throttleFilter");
function pausableFilter(extendFilter = bypassFilter) {
  const isActive2 = ref$3(true);
  function pause() {
    isActive2.value = false;
  }
  __name(pause, "pause");
  function resume() {
    isActive2.value = true;
  }
  __name(resume, "resume");
  const eventFilter = /* @__PURE__ */ __name((...args) => {
    if (isActive2.value)
      extendFilter(...args);
  }, "eventFilter");
  return { isActive: readonly(isActive2), pause, resume, eventFilter };
}
__name(pausableFilter, "pausableFilter");
const directiveHooks = {
  mounted: isVue3 ? "mounted" : "inserted",
  updated: isVue3 ? "updated" : "componentUpdated",
  unmounted: isVue3 ? "unmounted" : "unbind"
};
function cacheStringFunction(fn) {
  const cache = /* @__PURE__ */ Object.create(null);
  return (str) => {
    const hit = cache[str];
    return hit || (cache[str] = fn(str));
  };
}
__name(cacheStringFunction, "cacheStringFunction");
const hyphenateRE = /\B([A-Z])/g;
const hyphenate = cacheStringFunction((str) => str.replace(hyphenateRE, "-$1").toLowerCase());
const camelizeRE = /-(\w)/g;
const camelize = cacheStringFunction((str) => {
  return str.replace(camelizeRE, (_2, c2) => c2 ? c2.toUpperCase() : "");
});
function promiseTimeout(ms, throwOnTimeout = false, reason = "Timeout") {
  return new Promise((resolve2, reject) => {
    if (throwOnTimeout)
      setTimeout(() => reject(reason), ms);
    else
      setTimeout(resolve2, ms);
  });
}
__name(promiseTimeout, "promiseTimeout");
function identity(arg) {
  return arg;
}
__name(identity, "identity");
function createSingletonPromise(fn) {
  let _promise;
  function wrapper() {
    if (!_promise)
      _promise = fn();
    return _promise;
  }
  __name(wrapper, "wrapper");
  wrapper.reset = async () => {
    const _prev = _promise;
    _promise = void 0;
    if (_prev)
      await _prev;
  };
  return wrapper;
}
__name(createSingletonPromise, "createSingletonPromise");
function invoke(fn) {
  return fn();
}
__name(invoke, "invoke");
function containsProp(obj, ...props) {
  return props.some((k2) => k2 in obj);
}
__name(containsProp, "containsProp");
function increaseWithUnit(target, delta2) {
  var _a2;
  if (typeof target === "number")
    return target + delta2;
  const value = ((_a2 = target.match(/^-?\d+\.?\d*/)) == null ? void 0 : _a2[0]) || "";
  const unit = target.slice(value.length);
  const result = Number.parseFloat(value) + delta2;
  if (Number.isNaN(result))
    return target;
  return result + unit;
}
__name(increaseWithUnit, "increaseWithUnit");
function objectPick(obj, keys2, omitUndefined = false) {
  return keys2.reduce((n2, k2) => {
    if (k2 in obj) {
      if (!omitUndefined || obj[k2] !== void 0)
        n2[k2] = obj[k2];
    }
    return n2;
  }, {});
}
__name(objectPick, "objectPick");
function objectOmit(obj, keys2, omitUndefined = false) {
  return Object.fromEntries(Object.entries(obj).filter(([key, value]) => {
    return (!omitUndefined || value !== void 0) && !keys2.includes(key);
  }));
}
__name(objectOmit, "objectOmit");
function objectEntries(obj) {
  return Object.entries(obj);
}
__name(objectEntries, "objectEntries");
function getLifeCycleTarget(target) {
  return target || getCurrentInstance();
}
__name(getLifeCycleTarget, "getLifeCycleTarget");
function toRef(...args) {
  if (args.length !== 1)
    return toRef$1(...args);
  const r2 = args[0];
  return typeof r2 === "function" ? readonly(customRef(() => ({ get: r2, set: noop$2 }))) : ref$3(r2);
}
__name(toRef, "toRef");
const resolveRef = toRef;
function reactivePick(obj, ...keys2) {
  const flatKeys = keys2.flat();
  const predicate = flatKeys[0];
  return reactiveComputed(() => typeof predicate === "function" ? Object.fromEntries(Object.entries(toRefs$1(obj)).filter(([k2, v2]) => predicate(toValue$3(v2), k2))) : Object.fromEntries(flatKeys.map((k2) => [k2, toRef(obj, k2)])));
}
__name(reactivePick, "reactivePick");
function refAutoReset(defaultValue, afterMs = 1e4) {
  return customRef((track, trigger) => {
    let value = toValue$3(defaultValue);
    let timer;
    const resetAfter = /* @__PURE__ */ __name(() => setTimeout(() => {
      value = toValue$3(defaultValue);
      trigger();
    }, toValue$3(afterMs)), "resetAfter");
    tryOnScopeDispose(() => {
      clearTimeout(timer);
    });
    return {
      get() {
        track();
        return value;
      },
      set(newValue2) {
        value = newValue2;
        trigger();
        clearTimeout(timer);
        timer = resetAfter();
      }
    };
  });
}
__name(refAutoReset, "refAutoReset");
function useDebounceFn(fn, ms = 200, options2 = {}) {
  return createFilterWrapper(
    debounceFilter(ms, options2),
    fn
  );
}
__name(useDebounceFn, "useDebounceFn");
function refDebounced(value, ms = 200, options2 = {}) {
  const debounced = ref$3(value.value);
  const updater = useDebounceFn(() => {
    debounced.value = value.value;
  }, ms, options2);
  watch(value, () => updater());
  return debounced;
}
__name(refDebounced, "refDebounced");
function refDefault(source, defaultValue) {
  return computed({
    get() {
      var _a2;
      return (_a2 = source.value) != null ? _a2 : defaultValue;
    },
    set(value) {
      source.value = value;
    }
  });
}
__name(refDefault, "refDefault");
function useThrottleFn(fn, ms = 200, trailing = false, leading = true, rejectOnCancel = false) {
  return createFilterWrapper(
    throttleFilter(ms, trailing, leading, rejectOnCancel),
    fn
  );
}
__name(useThrottleFn, "useThrottleFn");
function refThrottled(value, delay = 200, trailing = true, leading = true) {
  if (delay <= 0)
    return value;
  const throttled = ref$3(value.value);
  const updater = useThrottleFn(() => {
    throttled.value = value.value;
  }, delay, trailing, leading);
  watch(value, () => updater());
  return throttled;
}
__name(refThrottled, "refThrottled");
function refWithControl(initial, options2 = {}) {
  let source = initial;
  let track;
  let trigger;
  const ref2 = customRef((_track, _trigger) => {
    track = _track;
    trigger = _trigger;
    return {
      get() {
        return get22();
      },
      set(v2) {
        set22(v2);
      }
    };
  });
  function get22(tracking = true) {
    if (tracking)
      track();
    return source;
  }
  __name(get22, "get2");
  function set22(value, triggering = true) {
    var _a2, _b;
    if (value === source)
      return;
    const old = source;
    if (((_a2 = options2.onBeforeChange) == null ? void 0 : _a2.call(options2, value, old)) === false)
      return;
    source = value;
    (_b = options2.onChanged) == null ? void 0 : _b.call(options2, value, old);
    if (triggering)
      trigger();
  }
  __name(set22, "set2");
  const untrackedGet = /* @__PURE__ */ __name(() => get22(false), "untrackedGet");
  const silentSet = /* @__PURE__ */ __name((v2) => set22(v2, false), "silentSet");
  const peek = /* @__PURE__ */ __name(() => get22(false), "peek");
  const lay = /* @__PURE__ */ __name((v2) => set22(v2, false), "lay");
  return extendRef(
    ref2,
    {
      get: get22,
      set: set22,
      untrackedGet,
      silentSet,
      peek,
      lay
    },
    { enumerable: true }
  );
}
__name(refWithControl, "refWithControl");
const controlledRef = refWithControl;
function set(...args) {
  if (args.length === 2) {
    const [ref2, value] = args;
    ref2.value = value;
  }
  if (args.length === 3) {
    if (isVue2) {
      set$2(...args);
    } else {
      const [target, key, value] = args;
      target[key] = value;
    }
  }
}
__name(set, "set");
function watchWithFilter(source, cb, options2 = {}) {
  const {
    eventFilter = bypassFilter,
    ...watchOptions
  } = options2;
  return watch(
    source,
    createFilterWrapper(
      eventFilter,
      cb
    ),
    watchOptions
  );
}
__name(watchWithFilter, "watchWithFilter");
function watchPausable(source, cb, options2 = {}) {
  const {
    eventFilter: filter3,
    ...watchOptions
  } = options2;
  const { eventFilter, pause, resume, isActive: isActive2 } = pausableFilter(filter3);
  const stop2 = watchWithFilter(
    source,
    cb,
    {
      ...watchOptions,
      eventFilter
    }
  );
  return { stop: stop2, pause, resume, isActive: isActive2 };
}
__name(watchPausable, "watchPausable");
function syncRef(left, right, ...[options2]) {
  const {
    flush: flush2 = "sync",
    deep = false,
    immediate = true,
    direction = "both",
    transform = {}
  } = options2 || {};
  const watchers = [];
  const transformLTR = "ltr" in transform && transform.ltr || ((v2) => v2);
  const transformRTL = "rtl" in transform && transform.rtl || ((v2) => v2);
  if (direction === "both" || direction === "ltr") {
    watchers.push(watchPausable(
      left,
      (newValue2) => {
        watchers.forEach((w2) => w2.pause());
        right.value = transformLTR(newValue2);
        watchers.forEach((w2) => w2.resume());
      },
      { flush: flush2, deep, immediate }
    ));
  }
  if (direction === "both" || direction === "rtl") {
    watchers.push(watchPausable(
      right,
      (newValue2) => {
        watchers.forEach((w2) => w2.pause());
        left.value = transformRTL(newValue2);
        watchers.forEach((w2) => w2.resume());
      },
      { flush: flush2, deep, immediate }
    ));
  }
  const stop2 = /* @__PURE__ */ __name(() => {
    watchers.forEach((w2) => w2.stop());
  }, "stop");
  return stop2;
}
__name(syncRef, "syncRef");
function syncRefs(source, targets, options2 = {}) {
  const {
    flush: flush2 = "sync",
    deep = false,
    immediate = true
  } = options2;
  if (!Array.isArray(targets))
    targets = [targets];
  return watch(
    source,
    (newValue2) => targets.forEach((target) => target.value = newValue2),
    { flush: flush2, deep, immediate }
  );
}
__name(syncRefs, "syncRefs");
function toRefs(objectRef, options2 = {}) {
  if (!isRef(objectRef))
    return toRefs$1(objectRef);
  const result = Array.isArray(objectRef.value) ? Array.from({ length: objectRef.value.length }) : {};
  for (const key in objectRef.value) {
    result[key] = customRef(() => ({
      get() {
        return objectRef.value[key];
      },
      set(v2) {
        var _a2;
        const replaceRef = (_a2 = toValue$3(options2.replaceRef)) != null ? _a2 : true;
        if (replaceRef) {
          if (Array.isArray(objectRef.value)) {
            const copy2 = [...objectRef.value];
            copy2[key] = v2;
            objectRef.value = copy2;
          } else {
            const newObject = { ...objectRef.value, [key]: v2 };
            Object.setPrototypeOf(newObject, Object.getPrototypeOf(objectRef.value));
            objectRef.value = newObject;
          }
        } else {
          objectRef.value[key] = v2;
        }
      }
    }));
  }
  return result;
}
__name(toRefs, "toRefs");
function tryOnBeforeMount(fn, sync = true, target) {
  const instance = getLifeCycleTarget(target);
  if (instance)
    onBeforeMount(fn, target);
  else if (sync)
    fn();
  else
    nextTick(fn);
}
__name(tryOnBeforeMount, "tryOnBeforeMount");
function tryOnBeforeUnmount(fn, target) {
  const instance = getLifeCycleTarget(target);
  if (instance)
    onBeforeUnmount(fn, target);
}
__name(tryOnBeforeUnmount, "tryOnBeforeUnmount");
function tryOnMounted$2(fn, sync = true, target) {
  const instance = getLifeCycleTarget();
  if (instance)
    onMounted(fn, target);
  else if (sync)
    fn();
  else
    nextTick(fn);
}
__name(tryOnMounted$2, "tryOnMounted$2");
function tryOnUnmounted(fn, target) {
  const instance = getLifeCycleTarget(target);
  if (instance)
    onUnmounted(fn, target);
}
__name(tryOnUnmounted, "tryOnUnmounted");
function createUntil(r2, isNot = false) {
  function toMatch(condition, { flush: flush2 = "sync", deep = false, timeout, throwOnTimeout } = {}) {
    let stop2 = null;
    const watcher = new Promise((resolve2) => {
      stop2 = watch(
        r2,
        (v2) => {
          if (condition(v2) !== isNot) {
            if (stop2)
              stop2();
            else
              nextTick(() => stop2 == null ? void 0 : stop2());
            resolve2(v2);
          }
        },
        {
          flush: flush2,
          deep,
          immediate: true
        }
      );
    });
    const promises = [watcher];
    if (timeout != null) {
      promises.push(
        promiseTimeout(timeout, throwOnTimeout).then(() => toValue$3(r2)).finally(() => stop2 == null ? void 0 : stop2())
      );
    }
    return Promise.race(promises);
  }
  __name(toMatch, "toMatch");
  function toBe(value, options2) {
    if (!isRef(value))
      return toMatch((v2) => v2 === value, options2);
    const { flush: flush2 = "sync", deep = false, timeout, throwOnTimeout } = options2 != null ? options2 : {};
    let stop2 = null;
    const watcher = new Promise((resolve2) => {
      stop2 = watch(
        [r2, value],
        ([v1, v2]) => {
          if (isNot !== (v1 === v2)) {
            if (stop2)
              stop2();
            else
              nextTick(() => stop2 == null ? void 0 : stop2());
            resolve2(v1);
          }
        },
        {
          flush: flush2,
          deep,
          immediate: true
        }
      );
    });
    const promises = [watcher];
    if (timeout != null) {
      promises.push(
        promiseTimeout(timeout, throwOnTimeout).then(() => toValue$3(r2)).finally(() => {
          stop2 == null ? void 0 : stop2();
          return toValue$3(r2);
        })
      );
    }
    return Promise.race(promises);
  }
  __name(toBe, "toBe");
  function toBeTruthy(options2) {
    return toMatch((v2) => Boolean(v2), options2);
  }
  __name(toBeTruthy, "toBeTruthy");
  function toBeNull(options2) {
    return toBe(null, options2);
  }
  __name(toBeNull, "toBeNull");
  function toBeUndefined(options2) {
    return toBe(void 0, options2);
  }
  __name(toBeUndefined, "toBeUndefined");
  function toBeNaN(options2) {
    return toMatch(Number.isNaN, options2);
  }
  __name(toBeNaN, "toBeNaN");
  function toContains(value, options2) {
    return toMatch((v2) => {
      const array = Array.from(v2);
      return array.includes(value) || array.includes(toValue$3(value));
    }, options2);
  }
  __name(toContains, "toContains");
  function changed(options2) {
    return changedTimes(1, options2);
  }
  __name(changed, "changed");
  function changedTimes(n2 = 1, options2) {
    let count2 = -1;
    return toMatch(() => {
      count2 += 1;
      return count2 >= n2;
    }, options2);
  }
  __name(changedTimes, "changedTimes");
  if (Array.isArray(toValue$3(r2))) {
    const instance = {
      toMatch,
      toContains,
      changed,
      changedTimes,
      get not() {
        return createUntil(r2, !isNot);
      }
    };
    return instance;
  } else {
    const instance = {
      toMatch,
      toBe,
      toBeTruthy,
      toBeNull,
      toBeNaN,
      toBeUndefined,
      changed,
      changedTimes,
      get not() {
        return createUntil(r2, !isNot);
      }
    };
    return instance;
  }
}
__name(createUntil, "createUntil");
function until(r2) {
  return createUntil(r2);
}
__name(until, "until");
function defaultComparator(value, othVal) {
  return value === othVal;
}
__name(defaultComparator, "defaultComparator");
function useArrayDifference(...args) {
  var _a2;
  const list2 = args[0];
  const values = args[1];
  let compareFn = (_a2 = args[2]) != null ? _a2 : defaultComparator;
  if (typeof compareFn === "string") {
    const key = compareFn;
    compareFn = /* @__PURE__ */ __name((value, othVal) => value[key] === othVal[key], "compareFn");
  }
  return computed(() => toValue$3(list2).filter((x2) => toValue$3(values).findIndex((y2) => compareFn(x2, y2)) === -1));
}
__name(useArrayDifference, "useArrayDifference");
function useArrayEvery(list2, fn) {
  return computed(() => toValue$3(list2).every((element, index2, array) => fn(toValue$3(element), index2, array)));
}
__name(useArrayEvery, "useArrayEvery");
function useArrayFilter(list2, fn) {
  return computed(() => toValue$3(list2).map((i2) => toValue$3(i2)).filter(fn));
}
__name(useArrayFilter, "useArrayFilter");
function useArrayFind(list2, fn) {
  return computed(() => toValue$3(
    toValue$3(list2).find((element, index2, array) => fn(toValue$3(element), index2, array))
  ));
}
__name(useArrayFind, "useArrayFind");
function useArrayFindIndex(list2, fn) {
  return computed(() => toValue$3(list2).findIndex((element, index2, array) => fn(toValue$3(element), index2, array)));
}
__name(useArrayFindIndex, "useArrayFindIndex");
function findLast$2(arr, cb) {
  let index2 = arr.length;
  while (index2-- > 0) {
    if (cb(arr[index2], index2, arr))
      return arr[index2];
  }
  return void 0;
}
__name(findLast$2, "findLast$2");
function useArrayFindLast(list2, fn) {
  return computed(() => toValue$3(
    !Array.prototype.findLast ? findLast$2(toValue$3(list2), (element, index2, array) => fn(toValue$3(element), index2, array)) : toValue$3(list2).findLast((element, index2, array) => fn(toValue$3(element), index2, array))
  ));
}
__name(useArrayFindLast, "useArrayFindLast");
function isArrayIncludesOptions(obj) {
  return isObject$c(obj) && containsProp(obj, "formIndex", "comparator");
}
__name(isArrayIncludesOptions, "isArrayIncludesOptions");
function useArrayIncludes(...args) {
  var _a2;
  const list2 = args[0];
  const value = args[1];
  let comparator = args[2];
  let formIndex = 0;
  if (isArrayIncludesOptions(comparator)) {
    formIndex = (_a2 = comparator.fromIndex) != null ? _a2 : 0;
    comparator = comparator.comparator;
  }
  if (typeof comparator === "string") {
    const key = comparator;
    comparator = /* @__PURE__ */ __name((element, value2) => element[key] === toValue$3(value2), "comparator");
  }
  comparator = comparator != null ? comparator : (element, value2) => element === toValue$3(value2);
  return computed(() => toValue$3(list2).slice(formIndex).some((element, index2, array) => comparator(
    toValue$3(element),
    toValue$3(value),
    index2,
    toValue$3(array)
  )));
}
__name(useArrayIncludes, "useArrayIncludes");
function useArrayJoin(list2, separator) {
  return computed(() => toValue$3(list2).map((i2) => toValue$3(i2)).join(toValue$3(separator)));
}
__name(useArrayJoin, "useArrayJoin");
function useArrayMap(list2, fn) {
  return computed(() => toValue$3(list2).map((i2) => toValue$3(i2)).map(fn));
}
__name(useArrayMap, "useArrayMap");
function useArrayReduce(list2, reducer, ...args) {
  const reduceCallback = /* @__PURE__ */ __name((sum2, value, index2) => reducer(toValue$3(sum2), toValue$3(value), index2), "reduceCallback");
  return computed(() => {
    const resolved = toValue$3(list2);
    return args.length ? resolved.reduce(reduceCallback, toValue$3(args[0])) : resolved.reduce(reduceCallback);
  });
}
__name(useArrayReduce, "useArrayReduce");
function useArraySome(list2, fn) {
  return computed(() => toValue$3(list2).some((element, index2, array) => fn(toValue$3(element), index2, array)));
}
__name(useArraySome, "useArraySome");
function uniq(array) {
  return Array.from(new Set(array));
}
__name(uniq, "uniq");
function uniqueElementsBy(array, fn) {
  return array.reduce((acc, v2) => {
    if (!acc.some((x2) => fn(v2, x2, array)))
      acc.push(v2);
    return acc;
  }, []);
}
__name(uniqueElementsBy, "uniqueElementsBy");
function useArrayUnique(list2, compareFn) {
  return computed(() => {
    const resolvedList = toValue$3(list2).map((element) => toValue$3(element));
    return compareFn ? uniqueElementsBy(resolvedList, compareFn) : uniq(resolvedList);
  });
}
__name(useArrayUnique, "useArrayUnique");
function useCounter(initialValue = 0, options2 = {}) {
  let _initialValue = unref(initialValue);
  const count2 = ref$3(initialValue);
  const {
    max = Number.POSITIVE_INFINITY,
    min = Number.NEGATIVE_INFINITY
  } = options2;
  const inc = /* @__PURE__ */ __name((delta2 = 1) => count2.value = Math.max(Math.min(max, count2.value + delta2), min), "inc");
  const dec = /* @__PURE__ */ __name((delta2 = 1) => count2.value = Math.min(Math.max(min, count2.value - delta2), max), "dec");
  const get22 = /* @__PURE__ */ __name(() => count2.value, "get2");
  const set22 = /* @__PURE__ */ __name((val) => count2.value = Math.max(min, Math.min(max, val)), "set2");
  const reset2 = /* @__PURE__ */ __name((val = _initialValue) => {
    _initialValue = val;
    return set22(val);
  }, "reset");
  return { count: count2, inc, dec, get: get22, set: set22, reset: reset2 };
}
__name(useCounter, "useCounter");
const REGEX_PARSE = /^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[T\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/i;
const REGEX_FORMAT = /[YMDHhms]o|\[([^\]]+)\]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a{1,2}|A{1,2}|m{1,2}|s{1,2}|Z{1,2}|SSS/g;
function defaultMeridiem(hours, minutes, isLowercase, hasPeriod) {
  let m2 = hours < 12 ? "AM" : "PM";
  if (hasPeriod)
    m2 = m2.split("").reduce((acc, curr) => acc += `${curr}.`, "");
  return isLowercase ? m2.toLowerCase() : m2;
}
__name(defaultMeridiem, "defaultMeridiem");
function formatOrdinal(num) {
  const suffixes = ["th", "st", "nd", "rd"];
  const v2 = num % 100;
  return num + (suffixes[(v2 - 20) % 10] || suffixes[v2] || suffixes[0]);
}
__name(formatOrdinal, "formatOrdinal");
function formatDate$1(date, formatStr, options2 = {}) {
  var _a2;
  const years = date.getFullYear();
  const month = date.getMonth();
  const days = date.getDate();
  const hours = date.getHours();
  const minutes = date.getMinutes();
  const seconds = date.getSeconds();
  const milliseconds = date.getMilliseconds();
  const day = date.getDay();
  const meridiem = (_a2 = options2.customMeridiem) != null ? _a2 : defaultMeridiem;
  const matches2 = {
    Yo: /* @__PURE__ */ __name(() => formatOrdinal(years), "Yo"),
    YY: /* @__PURE__ */ __name(() => String(years).slice(-2), "YY"),
    YYYY: /* @__PURE__ */ __name(() => years, "YYYY"),
    M: /* @__PURE__ */ __name(() => month + 1, "M"),
    Mo: /* @__PURE__ */ __name(() => formatOrdinal(month + 1), "Mo"),
    MM: /* @__PURE__ */ __name(() => `${month + 1}`.padStart(2, "0"), "MM"),
    MMM: /* @__PURE__ */ __name(() => date.toLocaleDateString(toValue$3(options2.locales), { month: "short" }), "MMM"),
    MMMM: /* @__PURE__ */ __name(() => date.toLocaleDateString(toValue$3(options2.locales), { month: "long" }), "MMMM"),
    D: /* @__PURE__ */ __name(() => String(days), "D"),
    Do: /* @__PURE__ */ __name(() => formatOrdinal(days), "Do"),
    DD: /* @__PURE__ */ __name(() => `${days}`.padStart(2, "0"), "DD"),
    H: /* @__PURE__ */ __name(() => String(hours), "H"),
    Ho: /* @__PURE__ */ __name(() => formatOrdinal(hours), "Ho"),
    HH: /* @__PURE__ */ __name(() => `${hours}`.padStart(2, "0"), "HH"),
    h: /* @__PURE__ */ __name(() => `${hours % 12 || 12}`.padStart(1, "0"), "h"),
    ho: /* @__PURE__ */ __name(() => formatOrdinal(hours % 12 || 12), "ho"),
    hh: /* @__PURE__ */ __name(() => `${hours % 12 || 12}`.padStart(2, "0"), "hh"),
    m: /* @__PURE__ */ __name(() => String(minutes), "m"),
    mo: /* @__PURE__ */ __name(() => formatOrdinal(minutes), "mo"),
    mm: /* @__PURE__ */ __name(() => `${minutes}`.padStart(2, "0"), "mm"),
    s: /* @__PURE__ */ __name(() => String(seconds), "s"),
    so: /* @__PURE__ */ __name(() => formatOrdinal(seconds), "so"),
    ss: /* @__PURE__ */ __name(() => `${seconds}`.padStart(2, "0"), "ss"),
    SSS: /* @__PURE__ */ __name(() => `${milliseconds}`.padStart(3, "0"), "SSS"),
    d: /* @__PURE__ */ __name(() => day, "d"),
    dd: /* @__PURE__ */ __name(() => date.toLocaleDateString(toValue$3(options2.locales), { weekday: "narrow" }), "dd"),
    ddd: /* @__PURE__ */ __name(() => date.toLocaleDateString(toValue$3(options2.locales), { weekday: "short" }), "ddd"),
    dddd: /* @__PURE__ */ __name(() => date.toLocaleDateString(toValue$3(options2.locales), { weekday: "long" }), "dddd"),
    A: /* @__PURE__ */ __name(() => meridiem(hours, minutes), "A"),
    AA: /* @__PURE__ */ __name(() => meridiem(hours, minutes, false, true), "AA"),
    a: /* @__PURE__ */ __name(() => meridiem(hours, minutes, true), "a"),
    aa: /* @__PURE__ */ __name(() => meridiem(hours, minutes, true, true), "aa")
  };
  return formatStr.replace(REGEX_FORMAT, (match2, $1) => {
    var _a22, _b;
    return (_b = $1 != null ? $1 : (_a22 = matches2[match2]) == null ? void 0 : _a22.call(matches2)) != null ? _b : match2;
  });
}
__name(formatDate$1, "formatDate$1");
function normalizeDate(date) {
  if (date === null)
    return new Date(Number.NaN);
  if (date === void 0)
    return /* @__PURE__ */ new Date();
  if (date instanceof Date)
    return new Date(date);
  if (typeof date === "string" && !/Z$/i.test(date)) {
    const d2 = date.match(REGEX_PARSE);
    if (d2) {
      const m2 = d2[2] - 1 || 0;
      const ms = (d2[7] || "0").substring(0, 3);
      return new Date(d2[1], m2, d2[3] || 1, d2[4] || 0, d2[5] || 0, d2[6] || 0, ms);
    }
  }
  return new Date(date);
}
__name(normalizeDate, "normalizeDate");
function useDateFormat(date, formatStr = "HH:mm:ss", options2 = {}) {
  return computed(() => formatDate$1(normalizeDate(toValue$3(date)), toValue$3(formatStr), options2));
}
__name(useDateFormat, "useDateFormat");
function useIntervalFn(cb, interval = 1e3, options2 = {}) {
  const {
    immediate = true,
    immediateCallback = false
  } = options2;
  let timer = null;
  const isActive2 = ref$3(false);
  function clean() {
    if (timer) {
      clearInterval(timer);
      timer = null;
    }
  }
  __name(clean, "clean");
  function pause() {
    isActive2.value = false;
    clean();
  }
  __name(pause, "pause");
  function resume() {
    const intervalValue = toValue$3(interval);
    if (intervalValue <= 0)
      return;
    isActive2.value = true;
    if (immediateCallback)
      cb();
    clean();
    timer = setInterval(cb, intervalValue);
  }
  __name(resume, "resume");
  if (immediate && isClient$1)
    resume();
  if (isRef(interval) || typeof interval === "function") {
    const stopWatch = watch(interval, () => {
      if (isActive2.value && isClient$1)
        resume();
    });
    tryOnScopeDispose(stopWatch);
  }
  tryOnScopeDispose(pause);
  return {
    isActive: isActive2,
    pause,
    resume
  };
}
__name(useIntervalFn, "useIntervalFn");
function useInterval(interval = 1e3, options2 = {}) {
  const {
    controls: exposeControls = false,
    immediate = true,
    callback
  } = options2;
  const counter = ref$3(0);
  const update2 = /* @__PURE__ */ __name(() => counter.value += 1, "update");
  const reset2 = /* @__PURE__ */ __name(() => {
    counter.value = 0;
  }, "reset");
  const controls = useIntervalFn(
    callback ? () => {
      update2();
      callback(counter.value);
    } : update2,
    interval,
    { immediate }
  );
  if (exposeControls) {
    return {
      counter,
      reset: reset2,
      ...controls
    };
  } else {
    return counter;
  }
}
__name(useInterval, "useInterval");
function useLastChanged(source, options2 = {}) {
  var _a2;
  const ms = ref$3((_a2 = options2.initialValue) != null ? _a2 : null);
  watch(
    source,
    () => ms.value = timestamp(),
    options2
  );
  return ms;
}
__name(useLastChanged, "useLastChanged");
function useTimeoutFn(cb, interval, options2 = {}) {
  const {
    immediate = true
  } = options2;
  const isPending = ref$3(false);
  let timer = null;
  function clear() {
    if (timer) {
      clearTimeout(timer);
      timer = null;
    }
  }
  __name(clear, "clear");
  function stop2() {
    isPending.value = false;
    clear();
  }
  __name(stop2, "stop");
  function start2(...args) {
    clear();
    isPending.value = true;
    timer = setTimeout(() => {
      isPending.value = false;
      timer = null;
      cb(...args);
    }, toValue$3(interval));
  }
  __name(start2, "start");
  if (immediate) {
    isPending.value = true;
    if (isClient$1)
      start2();
  }
  tryOnScopeDispose(stop2);
  return {
    isPending: readonly(isPending),
    start: start2,
    stop: stop2
  };
}
__name(useTimeoutFn, "useTimeoutFn");
function useTimeout(interval = 1e3, options2 = {}) {
  const {
    controls: exposeControls = false,
    callback
  } = options2;
  const controls = useTimeoutFn(
    callback != null ? callback : noop$2,
    interval,
    options2
  );
  const ready = computed(() => !controls.isPending.value);
  if (exposeControls) {
    return {
      ready,
      ...controls
    };
  } else {
    return ready;
  }
}
__name(useTimeout, "useTimeout");
function useToNumber(value, options2 = {}) {
  const {
    method = "parseFloat",
    radix,
    nanToZero
  } = options2;
  return computed(() => {
    let resolved = toValue$3(value);
    if (typeof resolved === "string")
      resolved = Number[method](resolved, radix);
    if (nanToZero && Number.isNaN(resolved))
      resolved = 0;
    return resolved;
  });
}
__name(useToNumber, "useToNumber");
function useToString(value) {
  return computed(() => `${toValue$3(value)}`);
}
__name(useToString, "useToString");
function useToggle(initialValue = false, options2 = {}) {
  const {
    truthyValue = true,
    falsyValue = false
  } = options2;
  const valueIsRef = isRef(initialValue);
  const _value = ref$3(initialValue);
  function toggle(value) {
    if (arguments.length) {
      _value.value = value;
      return _value.value;
    } else {
      const truthy = toValue$3(truthyValue);
      _value.value = _value.value === truthy ? toValue$3(falsyValue) : truthy;
      return _value.value;
    }
  }
  __name(toggle, "toggle");
  if (valueIsRef)
    return toggle;
  else
    return [_value, toggle];
}
__name(useToggle, "useToggle");
function watchArray(source, cb, options2) {
  let oldList = (options2 == null ? void 0 : options2.immediate) ? [] : [...source instanceof Function ? source() : Array.isArray(source) ? source : toValue$3(source)];
  return watch(source, (newList, _2, onCleanup) => {
    const oldListRemains = Array.from({ length: oldList.length });
    const added = [];
    for (const obj of newList) {
      let found2 = false;
      for (let i2 = 0; i2 < oldList.length; i2++) {
        if (!oldListRemains[i2] && obj === oldList[i2]) {
          oldListRemains[i2] = true;
          found2 = true;
          break;
        }
      }
      if (!found2)
        added.push(obj);
    }
    const removed = oldList.filter((_22, i2) => !oldListRemains[i2]);
    cb(newList, oldList, added, removed, onCleanup);
    oldList = [...newList];
  }, options2);
}
__name(watchArray, "watchArray");
function watchAtMost(source, cb, options2) {
  const {
    count: count2,
    ...watchOptions
  } = options2;
  const current = ref$3(0);
  const stop2 = watchWithFilter(
    source,
    (...args) => {
      current.value += 1;
      if (current.value >= toValue$3(count2))
        nextTick(() => stop2());
      cb(...args);
    },
    watchOptions
  );
  return { count: current, stop: stop2 };
}
__name(watchAtMost, "watchAtMost");
function watchDebounced(source, cb, options2 = {}) {
  const {
    debounce: debounce2 = 0,
    maxWait = void 0,
    ...watchOptions
  } = options2;
  return watchWithFilter(
    source,
    cb,
    {
      ...watchOptions,
      eventFilter: debounceFilter(debounce2, { maxWait })
    }
  );
}
__name(watchDebounced, "watchDebounced");
function watchDeep(source, cb, options2) {
  return watch(
    source,
    cb,
    {
      ...options2,
      deep: true
    }
  );
}
__name(watchDeep, "watchDeep");
function watchIgnorable(source, cb, options2 = {}) {
  const {
    eventFilter = bypassFilter,
    ...watchOptions
  } = options2;
  const filteredCb = createFilterWrapper(
    eventFilter,
    cb
  );
  let ignoreUpdates;
  let ignorePrevAsyncUpdates;
  let stop2;
  if (watchOptions.flush === "sync") {
    const ignore = ref$3(false);
    ignorePrevAsyncUpdates = /* @__PURE__ */ __name(() => {
    }, "ignorePrevAsyncUpdates");
    ignoreUpdates = /* @__PURE__ */ __name((updater) => {
      ignore.value = true;
      updater();
      ignore.value = false;
    }, "ignoreUpdates");
    stop2 = watch(
      source,
      (...args) => {
        if (!ignore.value)
          filteredCb(...args);
      },
      watchOptions
    );
  } else {
    const disposables = [];
    const ignoreCounter = ref$3(0);
    const syncCounter = ref$3(0);
    ignorePrevAsyncUpdates = /* @__PURE__ */ __name(() => {
      ignoreCounter.value = syncCounter.value;
    }, "ignorePrevAsyncUpdates");
    disposables.push(
      watch(
        source,
        () => {
          syncCounter.value++;
        },
        { ...watchOptions, flush: "sync" }
      )
    );
    ignoreUpdates = /* @__PURE__ */ __name((updater) => {
      const syncCounterPrev = syncCounter.value;
      updater();
      ignoreCounter.value += syncCounter.value - syncCounterPrev;
    }, "ignoreUpdates");
    disposables.push(
      watch(
        source,
        (...args) => {
          const ignore = ignoreCounter.value > 0 && ignoreCounter.value === syncCounter.value;
          ignoreCounter.value = 0;
          syncCounter.value = 0;
          if (ignore)
            return;
          filteredCb(...args);
        },
        watchOptions
      )
    );
    stop2 = /* @__PURE__ */ __name(() => {
      disposables.forEach((fn) => fn());
    }, "stop");
  }
  return { stop: stop2, ignoreUpdates, ignorePrevAsyncUpdates };
}
__name(watchIgnorable, "watchIgnorable");
function watchImmediate(source, cb, options2) {
  return watch(
    source,
    cb,
    {
      ...options2,
      immediate: true
    }
  );
}
__name(watchImmediate, "watchImmediate");
function watchOnce(source, cb, options2) {
  const stop2 = watch(source, (...args) => {
    nextTick(() => stop2());
    return cb(...args);
  }, options2);
  return stop2;
}
__name(watchOnce, "watchOnce");
function watchThrottled(source, cb, options2 = {}) {
  const {
    throttle: throttle2 = 0,
    trailing = true,
    leading = true,
    ...watchOptions
  } = options2;
  return watchWithFilter(
    source,
    cb,
    {
      ...watchOptions,
      eventFilter: throttleFilter(throttle2, trailing, leading)
    }
  );
}
__name(watchThrottled, "watchThrottled");
function watchTriggerable(source, cb, options2 = {}) {
  let cleanupFn;
  function onEffect() {
    if (!cleanupFn)
      return;
    const fn = cleanupFn;
    cleanupFn = void 0;
    fn();
  }
  __name(onEffect, "onEffect");
  function onCleanup(callback) {
    cleanupFn = callback;
  }
  __name(onCleanup, "onCleanup");
  const _cb = /* @__PURE__ */ __name((value, oldValue) => {
    onEffect();
    return cb(value, oldValue, onCleanup);
  }, "_cb");
  const res = watchIgnorable(source, _cb, options2);
  const { ignoreUpdates } = res;
  const trigger = /* @__PURE__ */ __name(() => {
    let res2;
    ignoreUpdates(() => {
      res2 = _cb(getWatchSources(source), getOldValue(source));
    });
    return res2;
  }, "trigger");
  return {
    ...res,
    trigger
  };
}
__name(watchTriggerable, "watchTriggerable");
function getWatchSources(sources) {
  if (isReactive(sources))
    return sources;
  if (Array.isArray(sources))
    return sources.map((item) => toValue$3(item));
  return toValue$3(sources);
}
__name(getWatchSources, "getWatchSources");
function getOldValue(source) {
  return Array.isArray(source) ? source.map(() => void 0) : void 0;
}
__name(getOldValue, "getOldValue");
function whenever(source, cb, options2) {
  const stop2 = watch(
    source,
    (v2, ov, onInvalidate) => {
      if (v2) {
        if (options2 == null ? void 0 : options2.once)
          nextTick(() => stop2());
        cb(v2, ov, onInvalidate);
      }
    },
    {
      ...options2,
      once: false
    }
  );
  return stop2;
}
__name(whenever, "whenever");
function computedAsync(evaluationCallback, initialState, optionsOrRef) {
  let options2;
  if (isRef(optionsOrRef)) {
    options2 = {
      evaluating: optionsOrRef
    };
  } else {
    options2 = optionsOrRef || {};
  }
  const {
    lazy = false,
    evaluating = void 0,
    shallow = true,
    onError = noop$2
  } = options2;
  const started = ref$3(!lazy);
  const current = shallow ? shallowRef(initialState) : ref$3(initialState);
  let counter = 0;
  watchEffect(async (onInvalidate) => {
    if (!started.value)
      return;
    counter++;
    const counterAtBeginning = counter;
    let hasFinished = false;
    if (evaluating) {
      Promise.resolve().then(() => {
        evaluating.value = true;
      });
    }
    try {
      const result = await evaluationCallback((cancelCallback) => {
        onInvalidate(() => {
          if (evaluating)
            evaluating.value = false;
          if (!hasFinished)
            cancelCallback();
        });
      });
      if (counterAtBeginning === counter)
        current.value = result;
    } catch (e2) {
      onError(e2);
    } finally {
      if (evaluating && counterAtBeginning === counter)
        evaluating.value = false;
      hasFinished = true;
    }
  });
  if (lazy) {
    return computed(() => {
      started.value = true;
      return current.value;
    });
  } else {
    return current;
  }
}
__name(computedAsync, "computedAsync");
function computedInject(key, options2, defaultSource, treatDefaultAsFactory) {
  let source = inject(key);
  if (defaultSource)
    source = inject(key, defaultSource);
  if (treatDefaultAsFactory)
    source = inject(key, defaultSource, treatDefaultAsFactory);
  if (typeof options2 === "function") {
    return computed((ctx) => options2(source, ctx));
  } else {
    return computed({
      get: /* @__PURE__ */ __name((ctx) => options2.get(source, ctx), "get"),
      set: options2.set
    });
  }
}
__name(computedInject, "computedInject");
function createReusableTemplate(options2 = {}) {
  if (!isVue3 && !version$6.startsWith("2.7.")) {
    if (false)
      throw new Error("[VueUse] createReusableTemplate only works in Vue 2.7 or above.");
    return;
  }
  const {
    inheritAttrs = true
  } = options2;
  const render2 = shallowRef();
  const define = /* @__PURE__ */ defineComponent({
    setup(_2, { slots }) {
      return () => {
        render2.value = slots.default;
      };
    }
  });
  const reuse = /* @__PURE__ */ defineComponent({
    inheritAttrs,
    setup(_2, { attrs: attrs2, slots }) {
      return () => {
        var _a2;
        if (!render2.value && false)
          throw new Error("[VueUse] Failed to find the definition of reusable template");
        const vnode = (_a2 = render2.value) == null ? void 0 : _a2.call(render2, { ...keysToCamelKebabCase(attrs2), $slots: slots });
        return inheritAttrs && (vnode == null ? void 0 : vnode.length) === 1 ? vnode[0] : vnode;
      };
    }
  });
  return makeDestructurable(
    { define, reuse },
    [define, reuse]
  );
}
__name(createReusableTemplate, "createReusableTemplate");
function keysToCamelKebabCase(obj) {
  const newObj = {};
  for (const key in obj)
    newObj[camelize(key)] = obj[key];
  return newObj;
}
__name(keysToCamelKebabCase, "keysToCamelKebabCase");
function createTemplatePromise(options2 = {}) {
  if (!isVue3) {
    if (false)
      throw new Error("[VueUse] createTemplatePromise only works in Vue 3 or above.");
    return;
  }
  let index2 = 0;
  const instances2 = ref$3([]);
  function create2(...args) {
    const props = shallowReactive({
      key: index2++,
      args,
      promise: void 0,
      resolve: /* @__PURE__ */ __name(() => {
      }, "resolve"),
      reject: /* @__PURE__ */ __name(() => {
      }, "reject"),
      isResolving: false,
      options: options2
    });
    instances2.value.push(props);
    props.promise = new Promise((_resolve, _reject) => {
      props.resolve = (v2) => {
        props.isResolving = true;
        return _resolve(v2);
      };
      props.reject = _reject;
    }).finally(() => {
      props.promise = void 0;
      const index22 = instances2.value.indexOf(props);
      if (index22 !== -1)
        instances2.value.splice(index22, 1);
    });
    return props.promise;
  }
  __name(create2, "create");
  function start2(...args) {
    if (options2.singleton && instances2.value.length > 0)
      return instances2.value[0].promise;
    return create2(...args);
  }
  __name(start2, "start");
  const component = /* @__PURE__ */ defineComponent((_2, { slots }) => {
    const renderList2 = /* @__PURE__ */ __name(() => instances2.value.map((props) => {
      var _a2;
      return h$2(Fragment$1, { key: props.key }, (_a2 = slots.default) == null ? void 0 : _a2.call(slots, props));
    }), "renderList");
    if (options2.transition)
      return () => h$2(TransitionGroup, options2.transition, renderList2);
    return renderList2;
  });
  component.start = start2;
  return component;
}
__name(createTemplatePromise, "createTemplatePromise");
function createUnrefFn(fn) {
  return function(...args) {
    return fn.apply(this, args.map((i2) => toValue$3(i2)));
  };
}
__name(createUnrefFn, "createUnrefFn");
function unrefElement(elRef) {
  var _a2;
  const plain = toValue$3(elRef);
  return (_a2 = plain == null ? void 0 : plain.$el) != null ? _a2 : plain;
}
__name(unrefElement, "unrefElement");
const defaultWindow = isClient$1 ? window : void 0;
const defaultDocument = isClient$1 ? window.document : void 0;
const defaultNavigator = isClient$1 ? window.navigator : void 0;
const defaultLocation = isClient$1 ? window.location : void 0;
function useEventListener(...args) {
  let target;
  let events2;
  let listeners;
  let options2;
  if (typeof args[0] === "string" || Array.isArray(args[0])) {
    [events2, listeners, options2] = args;
    target = defaultWindow;
  } else {
    [target, events2, listeners, options2] = args;
  }
  if (!target)
    return noop$2;
  if (!Array.isArray(events2))
    events2 = [events2];
  if (!Array.isArray(listeners))
    listeners = [listeners];
  const cleanups = [];
  const cleanup = /* @__PURE__ */ __name(() => {
    cleanups.forEach((fn) => fn());
    cleanups.length = 0;
  }, "cleanup");
  const register2 = /* @__PURE__ */ __name((el, event, listener, options22) => {
    el.addEventListener(event, listener, options22);
    return () => el.removeEventListener(event, listener, options22);
  }, "register");
  const stopWatch = watch(
    () => [unrefElement(target), toValue$3(options2)],
    ([el, options22]) => {
      cleanup();
      if (!el)
        return;
      const optionsClone = isObject$c(options22) ? { ...options22 } : options22;
      cleanups.push(
        ...events2.flatMap((event) => {
          return listeners.map((listener) => register2(el, event, listener, optionsClone));
        })
      );
    },
    { immediate: true, flush: "post" }
  );
  const stop2 = /* @__PURE__ */ __name(() => {
    stopWatch();
    cleanup();
  }, "stop");
  tryOnScopeDispose(stop2);
  return stop2;
}
__name(useEventListener, "useEventListener");
let _iOSWorkaround = false;
function onClickOutside(target, handler5, options2 = {}) {
  const { window: window2 = defaultWindow, ignore = [], capture = true, detectIframe = false } = options2;
  if (!window2)
    return noop$2;
  if (isIOS$1 && !_iOSWorkaround) {
    _iOSWorkaround = true;
    Array.from(window2.document.body.children).forEach((el) => el.addEventListener("click", noop$2));
    window2.document.documentElement.addEventListener("click", noop$2);
  }
  let shouldListen = true;
  const shouldIgnore = /* @__PURE__ */ __name((event) => {
    return ignore.some((target2) => {
      if (typeof target2 === "string") {
        return Array.from(window2.document.querySelectorAll(target2)).some((el) => el === event.target || event.composedPath().includes(el));
      } else {
        const el = unrefElement(target2);
        return el && (event.target === el || event.composedPath().includes(el));
      }
    });
  }, "shouldIgnore");
  const listener = /* @__PURE__ */ __name((event) => {
    const el = unrefElement(target);
    if (!el || el === event.target || event.composedPath().includes(el))
      return;
    if (event.detail === 0)
      shouldListen = !shouldIgnore(event);
    if (!shouldListen) {
      shouldListen = true;
      return;
    }
    handler5(event);
  }, "listener");
  const cleanup = [
    useEventListener(window2, "click", listener, { passive: true, capture }),
    useEventListener(window2, "pointerdown", (e2) => {
      const el = unrefElement(target);
      shouldListen = !shouldIgnore(e2) && !!(el && !e2.composedPath().includes(el));
    }, { passive: true }),
    detectIframe && useEventListener(window2, "blur", (event) => {
      setTimeout(() => {
        var _a2;
        const el = unrefElement(target);
        if (((_a2 = window2.document.activeElement) == null ? void 0 : _a2.tagName) === "IFRAME" && !(el == null ? void 0 : el.contains(window2.document.activeElement))) {
          handler5(event);
        }
      }, 0);
    })
  ].filter(Boolean);
  const stop2 = /* @__PURE__ */ __name(() => cleanup.forEach((fn) => fn()), "stop");
  return stop2;
}
__name(onClickOutside, "onClickOutside");
function createKeyPredicate(keyFilter) {
  if (typeof keyFilter === "function")
    return keyFilter;
  else if (typeof keyFilter === "string")
    return (event) => event.key === keyFilter;
  else if (Array.isArray(keyFilter))
    return (event) => keyFilter.includes(event.key);
  return () => true;
}
__name(createKeyPredicate, "createKeyPredicate");
function onKeyStroke(...args) {
  let key;
  let handler5;
  let options2 = {};
  if (args.length === 3) {
    key = args[0];
    handler5 = args[1];
    options2 = args[2];
  } else if (args.length === 2) {
    if (typeof args[1] === "object") {
      key = true;
      handler5 = args[0];
      options2 = args[1];
    } else {
      key = args[0];
      handler5 = args[1];
    }
  } else {
    key = true;
    handler5 = args[0];
  }
  const {
    target = defaultWindow,
    eventName = "keydown",
    passive = false,
    dedupe = false
  } = options2;
  const predicate = createKeyPredicate(key);
  const listener = /* @__PURE__ */ __name((e2) => {
    if (e2.repeat && toValue$3(dedupe))
      return;
    if (predicate(e2))
      handler5(e2);
  }, "listener");
  return useEventListener(target, eventName, listener, passive);
}
__name(onKeyStroke, "onKeyStroke");
function onKeyDown(key, handler5, options2 = {}) {
  return onKeyStroke(key, handler5, { ...options2, eventName: "keydown" });
}
__name(onKeyDown, "onKeyDown");
function onKeyPressed(key, handler5, options2 = {}) {
  return onKeyStroke(key, handler5, { ...options2, eventName: "keypress" });
}
__name(onKeyPressed, "onKeyPressed");
function onKeyUp(key, handler5, options2 = {}) {
  return onKeyStroke(key, handler5, { ...options2, eventName: "keyup" });
}
__name(onKeyUp, "onKeyUp");
const DEFAULT_DELAY = 500;
const DEFAULT_THRESHOLD = 10;
function onLongPress(target, handler5, options2) {
  var _a2, _b;
  const elementRef = computed(() => unrefElement(target));
  let timeout;
  let posStart;
  let startTimestamp;
  let hasLongPressed = false;
  function clear() {
    if (timeout) {
      clearTimeout(timeout);
      timeout = void 0;
    }
    posStart = void 0;
    startTimestamp = void 0;
    hasLongPressed = false;
  }
  __name(clear, "clear");
  function onRelease(ev) {
    var _a22, _b2, _c;
    const [_startTimestamp, _posStart, _hasLongPressed] = [startTimestamp, posStart, hasLongPressed];
    clear();
    if (!(options2 == null ? void 0 : options2.onMouseUp) || !_posStart || !_startTimestamp)
      return;
    if (((_a22 = options2 == null ? void 0 : options2.modifiers) == null ? void 0 : _a22.self) && ev.target !== elementRef.value)
      return;
    if ((_b2 = options2 == null ? void 0 : options2.modifiers) == null ? void 0 : _b2.prevent)
      ev.preventDefault();
    if ((_c = options2 == null ? void 0 : options2.modifiers) == null ? void 0 : _c.stop)
      ev.stopPropagation();
    const dx = ev.x - _posStart.x;
    const dy = ev.y - _posStart.y;
    const distance2 = Math.sqrt(dx * dx + dy * dy);
    options2.onMouseUp(ev.timeStamp - _startTimestamp, distance2, _hasLongPressed);
  }
  __name(onRelease, "onRelease");
  function onDown(ev) {
    var _a22, _b2, _c, _d;
    if (((_a22 = options2 == null ? void 0 : options2.modifiers) == null ? void 0 : _a22.self) && ev.target !== elementRef.value)
      return;
    clear();
    if ((_b2 = options2 == null ? void 0 : options2.modifiers) == null ? void 0 : _b2.prevent)
      ev.preventDefault();
    if ((_c = options2 == null ? void 0 : options2.modifiers) == null ? void 0 : _c.stop)
      ev.stopPropagation();
    posStart = {
      x: ev.x,
      y: ev.y
    };
    startTimestamp = ev.timeStamp;
    timeout = setTimeout(
      () => {
        hasLongPressed = true;
        handler5(ev);
      },
      (_d = options2 == null ? void 0 : options2.delay) != null ? _d : DEFAULT_DELAY
    );
  }
  __name(onDown, "onDown");
  function onMove(ev) {
    var _a22, _b2, _c, _d;
    if (((_a22 = options2 == null ? void 0 : options2.modifiers) == null ? void 0 : _a22.self) && ev.target !== elementRef.value)
      return;
    if (!posStart || (options2 == null ? void 0 : options2.distanceThreshold) === false)
      return;
    if ((_b2 = options2 == null ? void 0 : options2.modifiers) == null ? void 0 : _b2.prevent)
      ev.preventDefault();
    if ((_c = options2 == null ? void 0 : options2.modifiers) == null ? void 0 : _c.stop)
      ev.stopPropagation();
    const dx = ev.x - posStart.x;
    const dy = ev.y - posStart.y;
    const distance2 = Math.sqrt(dx * dx + dy * dy);
    if (distance2 >= ((_d = options2 == null ? void 0 : options2.distanceThreshold) != null ? _d : DEFAULT_THRESHOLD))
      clear();
  }
  __name(onMove, "onMove");
  const listenerOptions = {
    capture: (_a2 = options2 == null ? void 0 : options2.modifiers) == null ? void 0 : _a2.capture,
    once: (_b = options2 == null ? void 0 : options2.modifiers) == null ? void 0 : _b.once
  };
  const cleanup = [
    useEventListener(elementRef, "pointerdown", onDown, listenerOptions),
    useEventListener(elementRef, "pointermove", onMove, listenerOptions),
    useEventListener(elementRef, ["pointerup", "pointerleave"], onRelease, listenerOptions)
  ];
  const stop2 = /* @__PURE__ */ __name(() => cleanup.forEach((fn) => fn()), "stop");
  return stop2;
}
__name(onLongPress, "onLongPress");
function isFocusedElementEditable() {
  const { activeElement, body } = document;
  if (!activeElement)
    return false;
  if (activeElement === body)
    return false;
  switch (activeElement.tagName) {
    case "INPUT":
    case "TEXTAREA":
      return true;
  }
  return activeElement.hasAttribute("contenteditable");
}
__name(isFocusedElementEditable, "isFocusedElementEditable");
function isTypedCharValid({
  keyCode,
  metaKey,
  ctrlKey,
  altKey
}) {
  if (metaKey || ctrlKey || altKey)
    return false;
  if (keyCode >= 48 && keyCode <= 57)
    return true;
  if (keyCode >= 65 && keyCode <= 90)
    return true;
  if (keyCode >= 97 && keyCode <= 122)
    return true;
  return false;
}
__name(isTypedCharValid, "isTypedCharValid");
function onStartTyping(callback, options2 = {}) {
  const { document: document2 = defaultDocument } = options2;
  const keydown = /* @__PURE__ */ __name((event) => {
    if (!isFocusedElementEditable() && isTypedCharValid(event)) {
      callback(event);
    }
  }, "keydown");
  if (document2)
    useEventListener(document2, "keydown", keydown, { passive: true });
}
__name(onStartTyping, "onStartTyping");
function templateRef(key, initialValue = null) {
  const instance = getCurrentInstance();
  let _trigger = /* @__PURE__ */ __name(() => {
  }, "_trigger");
  const element = customRef((track, trigger) => {
    _trigger = trigger;
    return {
      get() {
        var _a2, _b;
        track();
        return (_b = (_a2 = instance == null ? void 0 : instance.proxy) == null ? void 0 : _a2.$refs[key]) != null ? _b : initialValue;
      },
      set() {
      }
    };
  });
  tryOnMounted$2(_trigger);
  onUpdated(_trigger);
  return element;
}
__name(templateRef, "templateRef");
function useMounted() {
  const isMounted = ref$3(false);
  const instance = getCurrentInstance();
  if (instance) {
    onMounted(() => {
      isMounted.value = true;
    }, isVue2 ? void 0 : instance);
  }
  return isMounted;
}
__name(useMounted, "useMounted");
function useSupported(callback) {
  const isMounted = useMounted();
  return computed(() => {
    isMounted.value;
    return Boolean(callback());
  });
}
__name(useSupported, "useSupported");
function useMutationObserver(target, callback, options2 = {}) {
  const { window: window2 = defaultWindow, ...mutationOptions } = options2;
  let observer;
  const isSupported = useSupported(() => window2 && "MutationObserver" in window2);
  const cleanup = /* @__PURE__ */ __name(() => {
    if (observer) {
      observer.disconnect();
      observer = void 0;
    }
  }, "cleanup");
  const targets = computed(() => {
    const value = toValue$3(target);
    const items = (Array.isArray(value) ? value : [value]).map(unrefElement).filter(notNullish);
    return new Set(items);
  });
  const stopWatch = watch(
    () => targets.value,
    (targets2) => {
      cleanup();
      if (isSupported.value && targets2.size) {
        observer = new MutationObserver(callback);
        targets2.forEach((el) => observer.observe(el, mutationOptions));
      }
    },
    { immediate: true, flush: "post" }
  );
  const takeRecords = /* @__PURE__ */ __name(() => {
    return observer == null ? void 0 : observer.takeRecords();
  }, "takeRecords");
  const stop2 = /* @__PURE__ */ __name(() => {
    stopWatch();
    cleanup();
  }, "stop");
  tryOnScopeDispose(stop2);
  return {
    isSupported,
    stop: stop2,
    takeRecords
  };
}
__name(useMutationObserver, "useMutationObserver");
function useActiveElement(options2 = {}) {
  var _a2;
  const {
    window: window2 = defaultWindow,
    deep = true,
    triggerOnRemoval = false
  } = options2;
  const document2 = (_a2 = options2.document) != null ? _a2 : window2 == null ? void 0 : window2.document;
  const getDeepActiveElement = /* @__PURE__ */ __name(() => {
    var _a22;
    let element = document2 == null ? void 0 : document2.activeElement;
    if (deep) {
      while (element == null ? void 0 : element.shadowRoot)
        element = (_a22 = element == null ? void 0 : element.shadowRoot) == null ? void 0 : _a22.activeElement;
    }
    return element;
  }, "getDeepActiveElement");
  const activeElement = ref$3();
  const trigger = /* @__PURE__ */ __name(() => {
    activeElement.value = getDeepActiveElement();
  }, "trigger");
  if (window2) {
    useEventListener(window2, "blur", (event) => {
      if (event.relatedTarget !== null)
        return;
      trigger();
    }, true);
    useEventListener(window2, "focus", trigger, true);
  }
  if (triggerOnRemoval) {
    useMutationObserver(document2, (mutations) => {
      mutations.filter((m2) => m2.removedNodes.length).map((n2) => Array.from(n2.removedNodes)).flat().forEach((node2) => {
        if (node2 === activeElement.value)
          trigger();
      });
    }, {
      childList: true,
      subtree: true
    });
  }
  trigger();
  return activeElement;
}
__name(useActiveElement, "useActiveElement");
function useRafFn(fn, options2 = {}) {
  const {
    immediate = true,
    fpsLimit = void 0,
    window: window2 = defaultWindow
  } = options2;
  const isActive2 = ref$3(false);
  const intervalLimit = fpsLimit ? 1e3 / fpsLimit : null;
  let previousFrameTimestamp = 0;
  let rafId = null;
  function loop(timestamp2) {
    if (!isActive2.value || !window2)
      return;
    if (!previousFrameTimestamp)
      previousFrameTimestamp = timestamp2;
    const delta2 = timestamp2 - previousFrameTimestamp;
    if (intervalLimit && delta2 < intervalLimit) {
      rafId = window2.requestAnimationFrame(loop);
      return;
    }
    previousFrameTimestamp = timestamp2;
    fn({ delta: delta2, timestamp: timestamp2 });
    rafId = window2.requestAnimationFrame(loop);
  }
  __name(loop, "loop");
  function resume() {
    if (!isActive2.value && window2) {
      isActive2.value = true;
      previousFrameTimestamp = 0;
      rafId = window2.requestAnimationFrame(loop);
    }
  }
  __name(resume, "resume");
  function pause() {
    isActive2.value = false;
    if (rafId != null && window2) {
      window2.cancelAnimationFrame(rafId);
      rafId = null;
    }
  }
  __name(pause, "pause");
  if (immediate)
    resume();
  tryOnScopeDispose(pause);
  return {
    isActive: readonly(isActive2),
    pause,
    resume
  };
}
__name(useRafFn, "useRafFn");
function useAnimate(target, keyframes, options2) {
  let config2;
  let animateOptions;
  if (isObject$c(options2)) {
    config2 = options2;
    animateOptions = objectOmit(options2, ["window", "immediate", "commitStyles", "persist", "onReady", "onError"]);
  } else {
    config2 = { duration: options2 };
    animateOptions = options2;
  }
  const {
    window: window2 = defaultWindow,
    immediate = true,
    commitStyles,
    persist,
    playbackRate: _playbackRate = 1,
    onReady,
    onError = /* @__PURE__ */ __name((e2) => {
      console.error(e2);
    }, "onError")
  } = config2;
  const isSupported = useSupported(() => window2 && HTMLElement && "animate" in HTMLElement.prototype);
  const animate = shallowRef(void 0);
  const store = shallowReactive({
    startTime: null,
    currentTime: null,
    timeline: null,
    playbackRate: _playbackRate,
    pending: false,
    playState: immediate ? "idle" : "paused",
    replaceState: "active"
  });
  const pending = computed(() => store.pending);
  const playState = computed(() => store.playState);
  const replaceState = computed(() => store.replaceState);
  const startTime = computed({
    get() {
      return store.startTime;
    },
    set(value) {
      store.startTime = value;
      if (animate.value)
        animate.value.startTime = value;
    }
  });
  const currentTime = computed({
    get() {
      return store.currentTime;
    },
    set(value) {
      store.currentTime = value;
      if (animate.value) {
        animate.value.currentTime = value;
        syncResume();
      }
    }
  });
  const timeline = computed({
    get() {
      return store.timeline;
    },
    set(value) {
      store.timeline = value;
      if (animate.value)
        animate.value.timeline = value;
    }
  });
  const playbackRate = computed({
    get() {
      return store.playbackRate;
    },
    set(value) {
      store.playbackRate = value;
      if (animate.value)
        animate.value.playbackRate = value;
    }
  });
  const play = /* @__PURE__ */ __name(() => {
    if (animate.value) {
      try {
        animate.value.play();
        syncResume();
      } catch (e2) {
        syncPause();
        onError(e2);
      }
    } else {
      update2();
    }
  }, "play");
  const pause = /* @__PURE__ */ __name(() => {
    var _a2;
    try {
      (_a2 = animate.value) == null ? void 0 : _a2.pause();
      syncPause();
    } catch (e2) {
      onError(e2);
    }
  }, "pause");
  const reverse2 = /* @__PURE__ */ __name(() => {
    var _a2;
    if (!animate.value)
      update2();
    try {
      (_a2 = animate.value) == null ? void 0 : _a2.reverse();
      syncResume();
    } catch (e2) {
      syncPause();
      onError(e2);
    }
  }, "reverse");
  const finish = /* @__PURE__ */ __name(() => {
    var _a2;
    try {
      (_a2 = animate.value) == null ? void 0 : _a2.finish();
      syncPause();
    } catch (e2) {
      onError(e2);
    }
  }, "finish");
  const cancel = /* @__PURE__ */ __name(() => {
    var _a2;
    try {
      (_a2 = animate.value) == null ? void 0 : _a2.cancel();
      syncPause();
    } catch (e2) {
      onError(e2);
    }
  }, "cancel");
  watch(() => unrefElement(target), (el) => {
    if (el)
      update2();
  });
  watch(() => keyframes, (value) => {
    if (animate.value)
      update2();
    if (!unrefElement(target) && animate.value) {
      animate.value.effect = new KeyframeEffect(
        unrefElement(target),
        toValue$3(value),
        animateOptions
      );
    }
  }, { deep: true });
  tryOnMounted$2(() => update2(true), false);
  tryOnScopeDispose(cancel);
  function update2(init2) {
    const el = unrefElement(target);
    if (!isSupported.value || !el)
      return;
    if (!animate.value)
      animate.value = el.animate(toValue$3(keyframes), animateOptions);
    if (persist)
      animate.value.persist();
    if (_playbackRate !== 1)
      animate.value.playbackRate = _playbackRate;
    if (init2 && !immediate)
      animate.value.pause();
    else
      syncResume();
    onReady == null ? void 0 : onReady(animate.value);
  }
  __name(update2, "update");
  useEventListener(animate, ["cancel", "finish", "remove"], syncPause);
  useEventListener(animate, "finish", () => {
    var _a2;
    if (commitStyles)
      (_a2 = animate.value) == null ? void 0 : _a2.commitStyles();
  });
  const { resume: resumeRef, pause: pauseRef } = useRafFn(() => {
    if (!animate.value)
      return;
    store.pending = animate.value.pending;
    store.playState = animate.value.playState;
    store.replaceState = animate.value.replaceState;
    store.startTime = animate.value.startTime;
    store.currentTime = animate.value.currentTime;
    store.timeline = animate.value.timeline;
    store.playbackRate = animate.value.playbackRate;
  }, { immediate: false });
  function syncResume() {
    if (isSupported.value)
      resumeRef();
  }
  __name(syncResume, "syncResume");
  function syncPause() {
    if (isSupported.value && window2)
      window2.requestAnimationFrame(pauseRef);
  }
  __name(syncPause, "syncPause");
  return {
    isSupported,
    animate,
    // actions
    play,
    pause,
    reverse: reverse2,
    finish,
    cancel,
    // state
    pending,
    playState,
    replaceState,
    startTime,
    currentTime,
    timeline,
    playbackRate
  };
}
__name(useAnimate, "useAnimate");
function useAsyncQueue(tasks, options2) {
  const {
    interrupt = true,
    onError = noop$2,
    onFinished = noop$2,
    signal
  } = options2 || {};
  const promiseState = {
    aborted: "aborted",
    fulfilled: "fulfilled",
    pending: "pending",
    rejected: "rejected"
  };
  const initialResult = Array.from(Array.from({ length: tasks.length }), () => ({ state: promiseState.pending, data: null }));
  const result = reactive(initialResult);
  const activeIndex = ref$3(-1);
  if (!tasks || tasks.length === 0) {
    onFinished();
    return {
      activeIndex,
      result
    };
  }
  function updateResult(state, res) {
    activeIndex.value++;
    result[activeIndex.value].data = res;
    result[activeIndex.value].state = state;
  }
  __name(updateResult, "updateResult");
  tasks.reduce((prev, curr) => {
    return prev.then((prevRes) => {
      var _a2;
      if (signal == null ? void 0 : signal.aborted) {
        updateResult(promiseState.aborted, new Error("aborted"));
        return;
      }
      if (((_a2 = result[activeIndex.value]) == null ? void 0 : _a2.state) === promiseState.rejected && interrupt) {
        onFinished();
        return;
      }
      const done = curr(prevRes).then((currentRes) => {
        updateResult(promiseState.fulfilled, currentRes);
        if (activeIndex.value === tasks.length - 1)
          onFinished();
        return currentRes;
      });
      if (!signal)
        return done;
      return Promise.race([done, whenAborted(signal)]);
    }).catch((e2) => {
      if (signal == null ? void 0 : signal.aborted) {
        updateResult(promiseState.aborted, e2);
        return e2;
      }
      updateResult(promiseState.rejected, e2);
      onError();
      return e2;
    });
  }, Promise.resolve());
  return {
    activeIndex,
    result
  };
}
__name(useAsyncQueue, "useAsyncQueue");
function whenAborted(signal) {
  return new Promise((resolve2, reject) => {
    const error2 = new Error("aborted");
    if (signal.aborted)
      reject(error2);
    else
      signal.addEventListener("abort", () => reject(error2), { once: true });
  });
}
__name(whenAborted, "whenAborted");
function useAsyncState(promise, initialState, options2) {
  const {
    immediate = true,
    delay = 0,
    onError = noop$2,
    onSuccess = noop$2,
    resetOnExecute = true,
    shallow = true,
    throwError
  } = options2 != null ? options2 : {};
  const state = shallow ? shallowRef(initialState) : ref$3(initialState);
  const isReady = ref$3(false);
  const isLoading = ref$3(false);
  const error2 = shallowRef(void 0);
  async function execute(delay2 = 0, ...args) {
    if (resetOnExecute)
      state.value = initialState;
    error2.value = void 0;
    isReady.value = false;
    isLoading.value = true;
    if (delay2 > 0)
      await promiseTimeout(delay2);
    const _promise = typeof promise === "function" ? promise(...args) : promise;
    try {
      const data = await _promise;
      state.value = data;
      isReady.value = true;
      onSuccess(data);
    } catch (e2) {
      error2.value = e2;
      onError(e2);
      if (throwError)
        throw e2;
    } finally {
      isLoading.value = false;
    }
    return state.value;
  }
  __name(execute, "execute");
  if (immediate)
    execute(delay);
  const shell = {
    state,
    isReady,
    isLoading,
    error: error2,
    execute
  };
  function waitUntilIsLoaded() {
    return new Promise((resolve2, reject) => {
      until(isLoading).toBe(false).then(() => resolve2(shell)).catch(reject);
    });
  }
  __name(waitUntilIsLoaded, "waitUntilIsLoaded");
  return {
    ...shell,
    then(onFulfilled, onRejected) {
      return waitUntilIsLoaded().then(onFulfilled, onRejected);
    }
  };
}
__name(useAsyncState, "useAsyncState");
const defaults$2 = {
  array: /* @__PURE__ */ __name((v2) => JSON.stringify(v2), "array"),
  object: /* @__PURE__ */ __name((v2) => JSON.stringify(v2), "object"),
  set: /* @__PURE__ */ __name((v2) => JSON.stringify(Array.from(v2)), "set"),
  map: /* @__PURE__ */ __name((v2) => JSON.stringify(Object.fromEntries(v2)), "map"),
  null: /* @__PURE__ */ __name(() => "", "null")
};
function getDefaultSerialization(target) {
  if (!target)
    return defaults$2.null;
  if (target instanceof Map)
    return defaults$2.map;
  else if (target instanceof Set)
    return defaults$2.set;
  else if (Array.isArray(target))
    return defaults$2.array;
  else
    return defaults$2.object;
}
__name(getDefaultSerialization, "getDefaultSerialization");
function useBase64(target, options2) {
  const base642 = ref$3("");
  const promise = ref$3();
  function execute() {
    if (!isClient$1)
      return;
    promise.value = new Promise((resolve2, reject) => {
      try {
        const _target = toValue$3(target);
        if (_target == null) {
          resolve2("");
        } else if (typeof _target === "string") {
          resolve2(blobToBase64(new Blob([_target], { type: "text/plain" })));
        } else if (_target instanceof Blob) {
          resolve2(blobToBase64(_target));
        } else if (_target instanceof ArrayBuffer) {
          resolve2(window.btoa(String.fromCharCode(...new Uint8Array(_target))));
        } else if (_target instanceof HTMLCanvasElement) {
          resolve2(_target.toDataURL(options2 == null ? void 0 : options2.type, options2 == null ? void 0 : options2.quality));
        } else if (_target instanceof HTMLImageElement) {
          const img = _target.cloneNode(false);
          img.crossOrigin = "Anonymous";
          imgLoaded(img).then(() => {
            const canvas2 = document.createElement("canvas");
            const ctx = canvas2.getContext("2d");
            canvas2.width = img.width;
            canvas2.height = img.height;
            ctx.drawImage(img, 0, 0, canvas2.width, canvas2.height);
            resolve2(canvas2.toDataURL(options2 == null ? void 0 : options2.type, options2 == null ? void 0 : options2.quality));
          }).catch(reject);
        } else if (typeof _target === "object") {
          const _serializeFn = (options2 == null ? void 0 : options2.serializer) || getDefaultSerialization(_target);
          const serialized = _serializeFn(_target);
          return resolve2(blobToBase64(new Blob([serialized], { type: "application/json" })));
        } else {
          reject(new Error("target is unsupported types"));
        }
      } catch (error2) {
        reject(error2);
      }
    });
    promise.value.then((res) => base642.value = res);
    return promise.value;
  }
  __name(execute, "execute");
  if (isRef(target) || typeof target === "function")
    watch(target, execute, { immediate: true });
  else
    execute();
  return {
    base64: base642,
    promise,
    execute
  };
}
__name(useBase64, "useBase64");
function imgLoaded(img) {
  return new Promise((resolve2, reject) => {
    if (!img.complete) {
      img.onload = () => {
        resolve2();
      };
      img.onerror = reject;
    } else {
      resolve2();
    }
  });
}
__name(imgLoaded, "imgLoaded");
function blobToBase64(blob) {
  return new Promise((resolve2, reject) => {
    const fr2 = new FileReader();
    fr2.onload = (e2) => {
      resolve2(e2.target.result);
    };
    fr2.onerror = reject;
    fr2.readAsDataURL(blob);
  });
}
__name(blobToBase64, "blobToBase64");
function useBattery(options2 = {}) {
  const { navigator: navigator2 = defaultNavigator } = options2;
  const events2 = ["chargingchange", "chargingtimechange", "dischargingtimechange", "levelchange"];
  const isSupported = useSupported(() => navigator2 && "getBattery" in navigator2 && typeof navigator2.getBattery === "function");
  const charging = ref$3(false);
  const chargingTime = ref$3(0);
  const dischargingTime = ref$3(0);
  const level = ref$3(1);
  let battery;
  function updateBatteryInfo() {
    charging.value = this.charging;
    chargingTime.value = this.chargingTime || 0;
    dischargingTime.value = this.dischargingTime || 0;
    level.value = this.level;
  }
  __name(updateBatteryInfo, "updateBatteryInfo");
  if (isSupported.value) {
    navigator2.getBattery().then((_battery) => {
      battery = _battery;
      updateBatteryInfo.call(battery);
      useEventListener(battery, events2, updateBatteryInfo, { passive: true });
    });
  }
  return {
    isSupported,
    charging,
    chargingTime,
    dischargingTime,
    level
  };
}
__name(useBattery, "useBattery");
function useBluetooth(options2) {
  let {
    acceptAllDevices = false
  } = options2 || {};
  const {
    filters = void 0,
    optionalServices = void 0,
    navigator: navigator2 = defaultNavigator
  } = options2 || {};
  const isSupported = useSupported(() => navigator2 && "bluetooth" in navigator2);
  const device = shallowRef(void 0);
  const error2 = shallowRef(null);
  watch(device, () => {
    connectToBluetoothGATTServer();
  });
  async function requestDevice() {
    if (!isSupported.value)
      return;
    error2.value = null;
    if (filters && filters.length > 0)
      acceptAllDevices = false;
    try {
      device.value = await (navigator2 == null ? void 0 : navigator2.bluetooth.requestDevice({
        acceptAllDevices,
        filters,
        optionalServices
      }));
    } catch (err) {
      error2.value = err;
    }
  }
  __name(requestDevice, "requestDevice");
  const server = ref$3();
  const isConnected = computed(() => {
    var _a2;
    return ((_a2 = server.value) == null ? void 0 : _a2.connected) || false;
  });
  async function connectToBluetoothGATTServer() {
    error2.value = null;
    if (device.value && device.value.gatt) {
      device.value.addEventListener("gattserverdisconnected", () => {
      });
      try {
        server.value = await device.value.gatt.connect();
      } catch (err) {
        error2.value = err;
      }
    }
  }
  __name(connectToBluetoothGATTServer, "connectToBluetoothGATTServer");
  tryOnMounted$2(() => {
    var _a2;
    if (device.value)
      (_a2 = device.value.gatt) == null ? void 0 : _a2.connect();
  });
  tryOnScopeDispose(() => {
    var _a2;
    if (device.value)
      (_a2 = device.value.gatt) == null ? void 0 : _a2.disconnect();
  });
  return {
    isSupported,
    isConnected,
    // Device:
    device,
    requestDevice,
    // Server:
    server,
    // Errors:
    error: error2
  };
}
__name(useBluetooth, "useBluetooth");
function useMediaQuery(query2, options2 = {}) {
  const { window: window2 = defaultWindow } = options2;
  const isSupported = useSupported(() => window2 && "matchMedia" in window2 && typeof window2.matchMedia === "function");
  let mediaQuery;
  const matches2 = ref$3(false);
  const handler5 = /* @__PURE__ */ __name((event) => {
    matches2.value = event.matches;
  }, "handler");
  const cleanup = /* @__PURE__ */ __name(() => {
    if (!mediaQuery)
      return;
    if ("removeEventListener" in mediaQuery)
      mediaQuery.removeEventListener("change", handler5);
    else
      mediaQuery.removeListener(handler5);
  }, "cleanup");
  const stopWatch = watchEffect(() => {
    if (!isSupported.value)
      return;
    cleanup();
    mediaQuery = window2.matchMedia(toValue$3(query2));
    if ("addEventListener" in mediaQuery)
      mediaQuery.addEventListener("change", handler5);
    else
      mediaQuery.addListener(handler5);
    matches2.value = mediaQuery.matches;
  });
  tryOnScopeDispose(() => {
    stopWatch();
    cleanup();
    mediaQuery = void 0;
  });
  return matches2;
}
__name(useMediaQuery, "useMediaQuery");
const breakpointsTailwind = {
  "sm": 640,
  "md": 768,
  "lg": 1024,
  "xl": 1280,
  "2xl": 1536
};
const breakpointsBootstrapV5 = {
  xs: 0,
  sm: 576,
  md: 768,
  lg: 992,
  xl: 1200,
  xxl: 1400
};
const breakpointsVuetifyV2 = {
  xs: 0,
  sm: 600,
  md: 960,
  lg: 1264,
  xl: 1904
};
const breakpointsVuetifyV3 = {
  xs: 0,
  sm: 600,
  md: 960,
  lg: 1280,
  xl: 1920,
  xxl: 2560
};
const breakpointsVuetify = breakpointsVuetifyV2;
const breakpointsAntDesign = {
  xs: 480,
  sm: 576,
  md: 768,
  lg: 992,
  xl: 1200,
  xxl: 1600
};
const breakpointsQuasar = {
  xs: 0,
  sm: 600,
  md: 1024,
  lg: 1440,
  xl: 1920
};
const breakpointsSematic = {
  mobileS: 320,
  mobileM: 375,
  mobileL: 425,
  tablet: 768,
  laptop: 1024,
  laptopL: 1440,
  desktop4K: 2560
};
const breakpointsMasterCss = {
  "3xs": 360,
  "2xs": 480,
  "xs": 600,
  "sm": 768,
  "md": 1024,
  "lg": 1280,
  "xl": 1440,
  "2xl": 1600,
  "3xl": 1920,
  "4xl": 2560
};
const breakpointsPrimeFlex = {
  sm: 576,
  md: 768,
  lg: 992,
  xl: 1200
};
function useBreakpoints(breakpoints, options2 = {}) {
  function getValue2(k2, delta2) {
    let v2 = toValue$3(breakpoints[toValue$3(k2)]);
    if (delta2 != null)
      v2 = increaseWithUnit(v2, delta2);
    if (typeof v2 === "number")
      v2 = `${v2}px`;
    return v2;
  }
  __name(getValue2, "getValue2");
  const { window: window2 = defaultWindow, strategy = "min-width" } = options2;
  function match2(query2) {
    if (!window2)
      return false;
    return window2.matchMedia(query2).matches;
  }
  __name(match2, "match");
  const greaterOrEqual = /* @__PURE__ */ __name((k2) => {
    return useMediaQuery(() => `(min-width: ${getValue2(k2)})`, options2);
  }, "greaterOrEqual");
  const smallerOrEqual = /* @__PURE__ */ __name((k2) => {
    return useMediaQuery(() => `(max-width: ${getValue2(k2)})`, options2);
  }, "smallerOrEqual");
  const shortcutMethods = Object.keys(breakpoints).reduce((shortcuts, k2) => {
    Object.defineProperty(shortcuts, k2, {
      get: /* @__PURE__ */ __name(() => strategy === "min-width" ? greaterOrEqual(k2) : smallerOrEqual(k2), "get"),
      enumerable: true,
      configurable: true
    });
    return shortcuts;
  }, {});
  function current() {
    const points = Object.keys(breakpoints).map((i2) => [i2, greaterOrEqual(i2)]);
    return computed(() => points.filter(([, v2]) => v2.value).map(([k2]) => k2));
  }
  __name(current, "current");
  return Object.assign(shortcutMethods, {
    greaterOrEqual,
    smallerOrEqual,
    greater(k2) {
      return useMediaQuery(() => `(min-width: ${getValue2(k2, 0.1)})`, options2);
    },
    smaller(k2) {
      return useMediaQuery(() => `(max-width: ${getValue2(k2, -0.1)})`, options2);
    },
    between(a2, b2) {
      return useMediaQuery(() => `(min-width: ${getValue2(a2)}) and (max-width: ${getValue2(b2, -0.1)})`, options2);
    },
    isGreater(k2) {
      return match2(`(min-width: ${getValue2(k2, 0.1)})`);
    },
    isGreaterOrEqual(k2) {
      return match2(`(min-width: ${getValue2(k2)})`);
    },
    isSmaller(k2) {
      return match2(`(max-width: ${getValue2(k2, -0.1)})`);
    },
    isSmallerOrEqual(k2) {
      return match2(`(max-width: ${getValue2(k2)})`);
    },
    isInBetween(a2, b2) {
      return match2(`(min-width: ${getValue2(a2)}) and (max-width: ${getValue2(b2, -0.1)})`);
    },
    current,
    active() {
      const bps = current();
      return computed(() => bps.value.length === 0 ? "" : bps.value.at(-1));
    }
  });
}
__name(useBreakpoints, "useBreakpoints");
function useBroadcastChannel(options2) {
  const {
    name: name2,
    window: window2 = defaultWindow
  } = options2;
  const isSupported = useSupported(() => window2 && "BroadcastChannel" in window2);
  const isClosed = ref$3(false);
  const channel = ref$3();
  const data = ref$3();
  const error2 = shallowRef(null);
  const post = /* @__PURE__ */ __name((data2) => {
    if (channel.value)
      channel.value.postMessage(data2);
  }, "post");
  const close2 = /* @__PURE__ */ __name(() => {
    if (channel.value)
      channel.value.close();
    isClosed.value = true;
  }, "close");
  if (isSupported.value) {
    tryOnMounted$2(() => {
      error2.value = null;
      channel.value = new BroadcastChannel(name2);
      channel.value.addEventListener("message", (e2) => {
        data.value = e2.data;
      }, { passive: true });
      channel.value.addEventListener("messageerror", (e2) => {
        error2.value = e2;
      }, { passive: true });
      channel.value.addEventListener("close", () => {
        isClosed.value = true;
      });
    });
  }
  tryOnScopeDispose(() => {
    close2();
  });
  return {
    isSupported,
    channel,
    data,
    post,
    close: close2,
    error: error2,
    isClosed
  };
}
__name(useBroadcastChannel, "useBroadcastChannel");
const WRITABLE_PROPERTIES = [
  "hash",
  "host",
  "hostname",
  "href",
  "pathname",
  "port",
  "protocol",
  "search"
];
function useBrowserLocation(options2 = {}) {
  const { window: window2 = defaultWindow } = options2;
  const refs = Object.fromEntries(
    WRITABLE_PROPERTIES.map((key) => [key, ref$3()])
  );
  for (const [key, ref2] of objectEntries(refs)) {
    watch(ref2, (value) => {
      if (!(window2 == null ? void 0 : window2.location) || window2.location[key] === value)
        return;
      window2.location[key] = value;
    });
  }
  const buildState2 = /* @__PURE__ */ __name((trigger) => {
    var _a2;
    const { state: state2, length } = (window2 == null ? void 0 : window2.history) || {};
    const { origin: origin2 } = (window2 == null ? void 0 : window2.location) || {};
    for (const key of WRITABLE_PROPERTIES)
      refs[key].value = (_a2 = window2 == null ? void 0 : window2.location) == null ? void 0 : _a2[key];
    return reactive({
      trigger,
      state: state2,
      length,
      origin: origin2,
      ...refs
    });
  }, "buildState");
  const state = ref$3(buildState2("load"));
  if (window2) {
    useEventListener(window2, "popstate", () => state.value = buildState2("popstate"), { passive: true });
    useEventListener(window2, "hashchange", () => state.value = buildState2("hashchange"), { passive: true });
  }
  return state;
}
__name(useBrowserLocation, "useBrowserLocation");
function useCached(refValue, comparator = (a2, b2) => a2 === b2, watchOptions) {
  const cachedValue = ref$3(refValue.value);
  watch(() => refValue.value, (value) => {
    if (!comparator(value, cachedValue.value))
      cachedValue.value = value;
  }, watchOptions);
  return cachedValue;
}
__name(useCached, "useCached");
function usePermission(permissionDesc, options2 = {}) {
  const {
    controls = false,
    navigator: navigator2 = defaultNavigator
  } = options2;
  const isSupported = useSupported(() => navigator2 && "permissions" in navigator2);
  let permissionStatus;
  const desc = typeof permissionDesc === "string" ? { name: permissionDesc } : permissionDesc;
  const state = ref$3();
  const onChange2 = /* @__PURE__ */ __name(() => {
    if (permissionStatus)
      state.value = permissionStatus.state;
  }, "onChange");
  const query2 = createSingletonPromise(async () => {
    if (!isSupported.value)
      return;
    if (!permissionStatus) {
      try {
        permissionStatus = await navigator2.permissions.query(desc);
        useEventListener(permissionStatus, "change", onChange2);
        onChange2();
      } catch (e2) {
        state.value = "prompt";
      }
    }
    return permissionStatus;
  });
  query2();
  if (controls) {
    return {
      state,
      isSupported,
      query: query2
    };
  } else {
    return state;
  }
}
__name(usePermission, "usePermission");
function useClipboard(options2 = {}) {
  const {
    navigator: navigator2 = defaultNavigator,
    read: read2 = false,
    source,
    copiedDuring = 1500,
    legacy = false
  } = options2;
  const isClipboardApiSupported = useSupported(() => navigator2 && "clipboard" in navigator2);
  const permissionRead = usePermission("clipboard-read");
  const permissionWrite = usePermission("clipboard-write");
  const isSupported = computed(() => isClipboardApiSupported.value || legacy);
  const text2 = ref$3("");
  const copied = ref$3(false);
  const timeout = useTimeoutFn(() => copied.value = false, copiedDuring);
  function updateText() {
    if (isClipboardApiSupported.value && isAllowed(permissionRead.value)) {
      navigator2.clipboard.readText().then((value) => {
        text2.value = value;
      });
    } else {
      text2.value = legacyRead();
    }
  }
  __name(updateText, "updateText");
  if (isSupported.value && read2)
    useEventListener(["copy", "cut"], updateText);
  async function copy2(value = toValue$3(source)) {
    if (isSupported.value && value != null) {
      if (isClipboardApiSupported.value && isAllowed(permissionWrite.value))
        await navigator2.clipboard.writeText(value);
      else
        legacyCopy(value);
      text2.value = value;
      copied.value = true;
      timeout.start();
    }
  }
  __name(copy2, "copy");
  function legacyCopy(value) {
    const ta2 = document.createElement("textarea");
    ta2.value = value != null ? value : "";
    ta2.style.position = "absolute";
    ta2.style.opacity = "0";
    document.body.appendChild(ta2);
    ta2.select();
    document.execCommand("copy");
    ta2.remove();
  }
  __name(legacyCopy, "legacyCopy");
  function legacyRead() {
    var _a2, _b, _c;
    return (_c = (_b = (_a2 = document == null ? void 0 : document.getSelection) == null ? void 0 : _a2.call(document)) == null ? void 0 : _b.toString()) != null ? _c : "";
  }
  __name(legacyRead, "legacyRead");
  function isAllowed(status) {
    return status === "granted" || status === "prompt";
  }
  __name(isAllowed, "isAllowed");
  return {
    isSupported,
    text: text2,
    copied,
    copy: copy2
  };
}
__name(useClipboard, "useClipboard");
function useClipboardItems(options2 = {}) {
  const {
    navigator: navigator2 = defaultNavigator,
    read: read2 = false,
    source,
    copiedDuring = 1500
  } = options2;
  const isSupported = useSupported(() => navigator2 && "clipboard" in navigator2);
  const content = ref$3([]);
  const copied = ref$3(false);
  const timeout = useTimeoutFn(() => copied.value = false, copiedDuring);
  function updateContent() {
    if (isSupported.value) {
      navigator2.clipboard.read().then((items) => {
        content.value = items;
      });
    }
  }
  __name(updateContent, "updateContent");
  if (isSupported.value && read2)
    useEventListener(["copy", "cut"], updateContent);
  async function copy2(value = toValue$3(source)) {
    if (isSupported.value && value != null) {
      await navigator2.clipboard.write(value);
      content.value = value;
      copied.value = true;
      timeout.start();
    }
  }
  __name(copy2, "copy");
  return {
    isSupported,
    content,
    copied,
    copy: copy2
  };
}
__name(useClipboardItems, "useClipboardItems");
function cloneFnJSON(source) {
  return JSON.parse(JSON.stringify(source));
}
__name(cloneFnJSON, "cloneFnJSON");
function useCloned(source, options2 = {}) {
  const cloned = ref$3({});
  const {
    manual,
    clone: clone2 = cloneFnJSON,
    // watch options
    deep = true,
    immediate = true
  } = options2;
  function sync() {
    cloned.value = clone2(toValue$3(source));
  }
  __name(sync, "sync");
  if (!manual && (isRef(source) || typeof source === "function")) {
    watch(source, sync, {
      ...options2,
      deep,
      immediate
    });
  } else {
    sync();
  }
  return { cloned, sync };
}
__name(useCloned, "useCloned");
const _global$1 = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
const globalKey = "__vueuse_ssr_handlers__";
const handlers$1 = /* @__PURE__ */ getHandlers();
function getHandlers() {
  if (!(globalKey in _global$1))
    _global$1[globalKey] = _global$1[globalKey] || {};
  return _global$1[globalKey];
}
__name(getHandlers, "getHandlers");
function getSSRHandler(key, fallback) {
  return handlers$1[key] || fallback;
}
__name(getSSRHandler, "getSSRHandler");
function setSSRHandler(key, fn) {
  handlers$1[key] = fn;
}
__name(setSSRHandler, "setSSRHandler");
function guessSerializerType(rawInit) {
  return rawInit == null ? "any" : rawInit instanceof Set ? "set" : rawInit instanceof Map ? "map" : rawInit instanceof Date ? "date" : typeof rawInit === "boolean" ? "boolean" : typeof rawInit === "string" ? "string" : typeof rawInit === "object" ? "object" : !Number.isNaN(rawInit) ? "number" : "any";
}
__name(guessSerializerType, "guessSerializerType");
const StorageSerializers = {
  boolean: {
    read: /* @__PURE__ */ __name((v2) => v2 === "true", "read"),
    write: /* @__PURE__ */ __name((v2) => String(v2), "write")
  },
  object: {
    read: /* @__PURE__ */ __name((v2) => JSON.parse(v2), "read"),
    write: /* @__PURE__ */ __name((v2) => JSON.stringify(v2), "write")
  },
  number: {
    read: /* @__PURE__ */ __name((v2) => Number.parseFloat(v2), "read"),
    write: /* @__PURE__ */ __name((v2) => String(v2), "write")
  },
  any: {
    read: /* @__PURE__ */ __name((v2) => v2, "read"),
    write: /* @__PURE__ */ __name((v2) => String(v2), "write")
  },
  string: {
    read: /* @__PURE__ */ __name((v2) => v2, "read"),
    write: /* @__PURE__ */ __name((v2) => String(v2), "write")
  },
  map: {
    read: /* @__PURE__ */ __name((v2) => new Map(JSON.parse(v2)), "read"),
    write: /* @__PURE__ */ __name((v2) => JSON.stringify(Array.from(v2.entries())), "write")
  },
  set: {
    read: /* @__PURE__ */ __name((v2) => new Set(JSON.parse(v2)), "read"),
    write: /* @__PURE__ */ __name((v2) => JSON.stringify(Array.from(v2)), "write")
  },
  date: {
    read: /* @__PURE__ */ __name((v2) => new Date(v2), "read"),
    write: /* @__PURE__ */ __name((v2) => v2.toISOString(), "write")
  }
};
const customStorageEventName = "vueuse-storage";
function useStorage(key, defaults2, storage, options2 = {}) {
  var _a2;
  const {
    flush: flush2 = "pre",
    deep = true,
    listenToStorageChanges = true,
    writeDefaults = true,
    mergeDefaults = false,
    shallow,
    window: window2 = defaultWindow,
    eventFilter,
    onError = /* @__PURE__ */ __name((e2) => {
      console.error(e2);
    }, "onError"),
    initOnMounted
  } = options2;
  const data = (shallow ? shallowRef : ref$3)(typeof defaults2 === "function" ? defaults2() : defaults2);
  if (!storage) {
    try {
      storage = getSSRHandler("getDefaultStorage", () => {
        var _a22;
        return (_a22 = defaultWindow) == null ? void 0 : _a22.localStorage;
      })();
    } catch (e2) {
      onError(e2);
    }
  }
  if (!storage)
    return data;
  const rawInit = toValue$3(defaults2);
  const type = guessSerializerType(rawInit);
  const serializer = (_a2 = options2.serializer) != null ? _a2 : StorageSerializers[type];
  const { pause: pauseWatch, resume: resumeWatch } = watchPausable(
    data,
    () => write2(data.value),
    { flush: flush2, deep, eventFilter }
  );
  if (window2 && listenToStorageChanges) {
    tryOnMounted$2(() => {
      if (storage instanceof Storage)
        useEventListener(window2, "storage", update2);
      else
        useEventListener(window2, customStorageEventName, updateFromCustomEvent);
      if (initOnMounted)
        update2();
    });
  }
  if (!initOnMounted)
    update2();
  function dispatchWriteEvent(oldValue, newValue2) {
    if (window2 && !(storage instanceof Storage)) {
      window2.dispatchEvent(new CustomEvent(customStorageEventName, {
        detail: {
          key,
          oldValue,
          newValue: newValue2,
          storageArea: storage
        }
      }));
    }
  }
  __name(dispatchWriteEvent, "dispatchWriteEvent");
  function write2(v2) {
    try {
      const oldValue = storage.getItem(key);
      if (v2 == null) {
        dispatchWriteEvent(oldValue, null);
        storage.removeItem(key);
      } else {
        const serialized = serializer.write(v2);
        if (oldValue !== serialized) {
          storage.setItem(key, serialized);
          dispatchWriteEvent(oldValue, serialized);
        }
      }
    } catch (e2) {
      onError(e2);
    }
  }
  __name(write2, "write");
  function read2(event) {
    const rawValue = event ? event.newValue : storage.getItem(key);
    if (rawValue == null) {
      if (writeDefaults && rawInit != null)
        storage.setItem(key, serializer.write(rawInit));
      return rawInit;
    } else if (!event && mergeDefaults) {
      const value = serializer.read(rawValue);
      if (typeof mergeDefaults === "function")
        return mergeDefaults(value, rawInit);
      else if (type === "object" && !Array.isArray(value))
        return { ...rawInit, ...value };
      return value;
    } else if (typeof rawValue !== "string") {
      return rawValue;
    } else {
      return serializer.read(rawValue);
    }
  }
  __name(read2, "read");
  function update2(event) {
    if (event && event.storageArea !== storage)
      return;
    if (event && event.key == null) {
      data.value = rawInit;
      return;
    }
    if (event && event.key !== key)
      return;
    pauseWatch();
    try {
      if ((event == null ? void 0 : event.newValue) !== serializer.write(data.value))
        data.value = read2(event);
    } catch (e2) {
      onError(e2);
    } finally {
      if (event)
        nextTick(resumeWatch);
      else
        resumeWatch();
    }
  }
  __name(update2, "update");
  function updateFromCustomEvent(event) {
    update2(event.detail);
  }
  __name(updateFromCustomEvent, "updateFromCustomEvent");
  return data;
}
__name(useStorage, "useStorage");
function usePreferredDark(options2) {
  return useMediaQuery("(prefers-color-scheme: dark)", options2);
}
__name(usePreferredDark, "usePreferredDark");
const CSS_DISABLE_TRANS = "*,*::before,*::after{-webkit-transition:none!important;-moz-transition:none!important;-o-transition:none!important;-ms-transition:none!important;transition:none!important}";
function useColorMode(options2 = {}) {
  const {
    selector = "html",
    attribute: attribute2 = "class",
    initialValue = "auto",
    window: window2 = defaultWindow,
    storage,
    storageKey = "vueuse-color-scheme",
    listenToStorageChanges = true,
    storageRef,
    emitAuto,
    disableTransition = true
  } = options2;
  const modes = {
    auto: "",
    light: "light",
    dark: "dark",
    ...options2.modes || {}
  };
  const preferredDark = usePreferredDark({ window: window2 });
  const system = computed(() => preferredDark.value ? "dark" : "light");
  const store = storageRef || (storageKey == null ? toRef(initialValue) : useStorage(storageKey, initialValue, storage, { window: window2, listenToStorageChanges }));
  const state = computed(() => store.value === "auto" ? system.value : store.value);
  const updateHTMLAttrs = getSSRHandler(
    "updateHTMLAttrs",
    (selector2, attribute22, value) => {
      const el = typeof selector2 === "string" ? window2 == null ? void 0 : window2.document.querySelector(selector2) : unrefElement(selector2);
      if (!el)
        return;
      const classesToAdd = /* @__PURE__ */ new Set();
      const classesToRemove = /* @__PURE__ */ new Set();
      let attributeToChange = null;
      if (attribute22 === "class") {
        const current = value.split(/\s/g);
        Object.values(modes).flatMap((i2) => (i2 || "").split(/\s/g)).filter(Boolean).forEach((v2) => {
          if (current.includes(v2))
            classesToAdd.add(v2);
          else
            classesToRemove.add(v2);
        });
      } else {
        attributeToChange = { key: attribute22, value };
      }
      if (classesToAdd.size === 0 && classesToRemove.size === 0 && attributeToChange === null)
        return;
      let style2;
      if (disableTransition) {
        style2 = window2.document.createElement("style");
        style2.appendChild(document.createTextNode(CSS_DISABLE_TRANS));
        window2.document.head.appendChild(style2);
      }
      for (const c2 of classesToAdd) {
        el.classList.add(c2);
      }
      for (const c2 of classesToRemove) {
        el.classList.remove(c2);
      }
      if (attributeToChange) {
        el.setAttribute(attributeToChange.key, attributeToChange.value);
      }
      if (disableTransition) {
        window2.getComputedStyle(style2).opacity;
        document.head.removeChild(style2);
      }
    }
  );
  function defaultOnChanged(mode) {
    var _a2;
    updateHTMLAttrs(selector, attribute2, (_a2 = modes[mode]) != null ? _a2 : mode);
  }
  __name(defaultOnChanged, "defaultOnChanged");
  function onChanged(mode) {
    if (options2.onChanged)
      options2.onChanged(mode, defaultOnChanged);
    else
      defaultOnChanged(mode);
  }
  __name(onChanged, "onChanged");
  watch(state, onChanged, { flush: "post", immediate: true });
  tryOnMounted$2(() => onChanged(state.value));
  const auto = computed({
    get() {
      return emitAuto ? store.value : state.value;
    },
    set(v2) {
      store.value = v2;
    }
  });
  try {
    return Object.assign(auto, { store, system, state });
  } catch (e2) {
    return auto;
  }
}
__name(useColorMode, "useColorMode");
function useConfirmDialog(revealed = ref$3(false)) {
  const confirmHook = createEventHook();
  const cancelHook = createEventHook();
  const revealHook = createEventHook();
  let _resolve = noop$2;
  const reveal = /* @__PURE__ */ __name((data) => {
    revealHook.trigger(data);
    revealed.value = true;
    return new Promise((resolve2) => {
      _resolve = resolve2;
    });
  }, "reveal");
  const confirm2 = /* @__PURE__ */ __name((data) => {
    revealed.value = false;
    confirmHook.trigger(data);
    _resolve({ data, isCanceled: false });
  }, "confirm");
  const cancel = /* @__PURE__ */ __name((data) => {
    revealed.value = false;
    cancelHook.trigger(data);
    _resolve({ data, isCanceled: true });
  }, "cancel");
  return {
    isRevealed: computed(() => revealed.value),
    reveal,
    confirm: confirm2,
    cancel,
    onReveal: revealHook.on,
    onConfirm: confirmHook.on,
    onCancel: cancelHook.on
  };
}
__name(useConfirmDialog, "useConfirmDialog");
function useCssVar(prop2, target, options2 = {}) {
  const { window: window2 = defaultWindow, initialValue, observe: observe2 = false } = options2;
  const variable = ref$3(initialValue);
  const elRef = computed(() => {
    var _a2;
    return unrefElement(target) || ((_a2 = window2 == null ? void 0 : window2.document) == null ? void 0 : _a2.documentElement);
  });
  function updateCssVar() {
    var _a2;
    const key = toValue$3(prop2);
    const el = toValue$3(elRef);
    if (el && window2 && key) {
      const value = (_a2 = window2.getComputedStyle(el).getPropertyValue(key)) == null ? void 0 : _a2.trim();
      variable.value = value || initialValue;
    }
  }
  __name(updateCssVar, "updateCssVar");
  if (observe2) {
    useMutationObserver(elRef, updateCssVar, {
      attributeFilter: ["style", "class"],
      window: window2
    });
  }
  watch(
    [elRef, () => toValue$3(prop2)],
    (_2, old) => {
      if (old[0] && old[1] && window2)
        window2.getComputedStyle(old[0]).removeProperty(old[1]);
      updateCssVar();
    },
    { immediate: true }
  );
  watch(
    variable,
    (val) => {
      var _a2;
      const raw_prop = toValue$3(prop2);
      if (((_a2 = elRef.value) == null ? void 0 : _a2.style) && raw_prop) {
        if (val == null)
          elRef.value.style.removeProperty(raw_prop);
        else
          elRef.value.style.setProperty(raw_prop, val);
      }
    }
  );
  return variable;
}
__name(useCssVar, "useCssVar");
function useCurrentElement(rootComponent) {
  const vm = getCurrentInstance();
  const currentElement = computedWithControl(
    () => null,
    () => rootComponent ? unrefElement(rootComponent) : vm.proxy.$el
  );
  onUpdated(currentElement.trigger);
  onMounted(currentElement.trigger);
  return currentElement;
}
__name(useCurrentElement, "useCurrentElement");
function useCycleList(list2, options2) {
  const state = shallowRef(getInitialValue2());
  const listRef = toRef(list2);
  const index2 = computed({
    get() {
      var _a2;
      const targetList = listRef.value;
      let index22 = (options2 == null ? void 0 : options2.getIndexOf) ? options2.getIndexOf(state.value, targetList) : targetList.indexOf(state.value);
      if (index22 < 0)
        index22 = (_a2 = options2 == null ? void 0 : options2.fallbackIndex) != null ? _a2 : 0;
      return index22;
    },
    set(v2) {
      set22(v2);
    }
  });
  function set22(i2) {
    const targetList = listRef.value;
    const length = targetList.length;
    const index22 = (i2 % length + length) % length;
    const value = targetList[index22];
    state.value = value;
    return value;
  }
  __name(set22, "set2");
  function shift2(delta2 = 1) {
    return set22(index2.value + delta2);
  }
  __name(shift2, "shift");
  function next(n2 = 1) {
    return shift2(n2);
  }
  __name(next, "next");
  function prev(n2 = 1) {
    return shift2(-n2);
  }
  __name(prev, "prev");
  function getInitialValue2() {
    var _a2, _b;
    return (_b = toValue$3((_a2 = options2 == null ? void 0 : options2.initialValue) != null ? _a2 : toValue$3(list2)[0])) != null ? _b : void 0;
  }
  __name(getInitialValue2, "getInitialValue");
  watch(listRef, () => set22(index2.value));
  return {
    state,
    index: index2,
    next,
    prev,
    go: set22
  };
}
__name(useCycleList, "useCycleList");
function useDark(options2 = {}) {
  const {
    valueDark = "dark",
    valueLight = "",
    window: window2 = defaultWindow
  } = options2;
  const mode = useColorMode({
    ...options2,
    onChanged: /* @__PURE__ */ __name((mode2, defaultHandler) => {
      var _a2;
      if (options2.onChanged)
        (_a2 = options2.onChanged) == null ? void 0 : _a2.call(options2, mode2 === "dark", defaultHandler, mode2);
      else
        defaultHandler(mode2);
    }, "onChanged"),
    modes: {
      dark: valueDark,
      light: valueLight
    }
  });
  const system = computed(() => {
    if (mode.system) {
      return mode.system.value;
    } else {
      const preferredDark = usePreferredDark({ window: window2 });
      return preferredDark.value ? "dark" : "light";
    }
  });
  const isDark = computed({
    get() {
      return mode.value === "dark";
    },
    set(v2) {
      const modeVal = v2 ? "dark" : "light";
      if (system.value === modeVal)
        mode.value = "auto";
      else
        mode.value = modeVal;
    }
  });
  return isDark;
}
__name(useDark, "useDark");
function fnBypass(v2) {
  return v2;
}
__name(fnBypass, "fnBypass");
function fnSetSource(source, value) {
  return source.value = value;
}
__name(fnSetSource, "fnSetSource");
function defaultDump(clone2) {
  return clone2 ? typeof clone2 === "function" ? clone2 : cloneFnJSON : fnBypass;
}
__name(defaultDump, "defaultDump");
function defaultParse(clone2) {
  return clone2 ? typeof clone2 === "function" ? clone2 : cloneFnJSON : fnBypass;
}
__name(defaultParse, "defaultParse");
function useManualRefHistory(source, options2 = {}) {
  const {
    clone: clone2 = false,
    dump = defaultDump(clone2),
    parse: parse2 = defaultParse(clone2),
    setSource = fnSetSource
  } = options2;
  function _createHistoryRecord() {
    return markRaw({
      snapshot: dump(source.value),
      timestamp: timestamp()
    });
  }
  __name(_createHistoryRecord, "_createHistoryRecord");
  const last = ref$3(_createHistoryRecord());
  const undoStack = ref$3([]);
  const redoStack = ref$3([]);
  const _setSource = /* @__PURE__ */ __name((record2) => {
    setSource(source, parse2(record2.snapshot));
    last.value = record2;
  }, "_setSource");
  const commit = /* @__PURE__ */ __name(() => {
    undoStack.value.unshift(last.value);
    last.value = _createHistoryRecord();
    if (options2.capacity && undoStack.value.length > options2.capacity)
      undoStack.value.splice(options2.capacity, Number.POSITIVE_INFINITY);
    if (redoStack.value.length)
      redoStack.value.splice(0, redoStack.value.length);
  }, "commit");
  const clear = /* @__PURE__ */ __name(() => {
    undoStack.value.splice(0, undoStack.value.length);
    redoStack.value.splice(0, redoStack.value.length);
  }, "clear");
  const undo2 = /* @__PURE__ */ __name(() => {
    const state = undoStack.value.shift();
    if (state) {
      redoStack.value.unshift(last.value);
      _setSource(state);
    }
  }, "undo");
  const redo2 = /* @__PURE__ */ __name(() => {
    const state = redoStack.value.shift();
    if (state) {
      undoStack.value.unshift(last.value);
      _setSource(state);
    }
  }, "redo");
  const reset2 = /* @__PURE__ */ __name(() => {
    _setSource(last.value);
  }, "reset");
  const history2 = computed(() => [last.value, ...undoStack.value]);
  const canUndo = computed(() => undoStack.value.length > 0);
  const canRedo = computed(() => redoStack.value.length > 0);
  return {
    source,
    undoStack,
    redoStack,
    last,
    history: history2,
    canUndo,
    canRedo,
    clear,
    commit,
    reset: reset2,
    undo: undo2,
    redo: redo2
  };
}
__name(useManualRefHistory, "useManualRefHistory");
function useRefHistory(source, options2 = {}) {
  const {
    deep = false,
    flush: flush2 = "pre",
    eventFilter
  } = options2;
  const {
    eventFilter: composedFilter,
    pause,
    resume: resumeTracking,
    isActive: isTracking
  } = pausableFilter(eventFilter);
  const {
    ignoreUpdates,
    ignorePrevAsyncUpdates,
    stop: stop2
  } = watchIgnorable(
    source,
    commit,
    { deep, flush: flush2, eventFilter: composedFilter }
  );
  function setSource(source2, value) {
    ignorePrevAsyncUpdates();
    ignoreUpdates(() => {
      source2.value = value;
    });
  }
  __name(setSource, "setSource");
  const manualHistory = useManualRefHistory(source, { ...options2, clone: options2.clone || deep, setSource });
  const { clear, commit: manualCommit } = manualHistory;
  function commit() {
    ignorePrevAsyncUpdates();
    manualCommit();
  }
  __name(commit, "commit");
  function resume(commitNow) {
    resumeTracking();
    if (commitNow)
      commit();
  }
  __name(resume, "resume");
  function batch(fn) {
    let canceled2 = false;
    const cancel = /* @__PURE__ */ __name(() => canceled2 = true, "cancel");
    ignoreUpdates(() => {
      fn(cancel);
    });
    if (!canceled2)
      commit();
  }
  __name(batch, "batch");
  function dispose() {
    stop2();
    clear();
  }
  __name(dispose, "dispose");
  return {
    ...manualHistory,
    isTracking,
    pause,
    resume,
    commit,
    batch,
    dispose
  };
}
__name(useRefHistory, "useRefHistory");
function useDebouncedRefHistory(source, options2 = {}) {
  const filter3 = options2.debounce ? debounceFilter(options2.debounce) : void 0;
  const history2 = useRefHistory(source, { ...options2, eventFilter: filter3 });
  return {
    ...history2
  };
}
__name(useDebouncedRefHistory, "useDebouncedRefHistory");
function useDeviceMotion(options2 = {}) {
  const {
    window: window2 = defaultWindow,
    eventFilter = bypassFilter
  } = options2;
  const acceleration = ref$3({ x: null, y: null, z: null });
  const rotationRate = ref$3({ alpha: null, beta: null, gamma: null });
  const interval = ref$3(0);
  const accelerationIncludingGravity = ref$3({
    x: null,
    y: null,
    z: null
  });
  if (window2) {
    const onDeviceMotion = createFilterWrapper(
      eventFilter,
      (event) => {
        acceleration.value = event.acceleration;
        accelerationIncludingGravity.value = event.accelerationIncludingGravity;
        rotationRate.value = event.rotationRate;
        interval.value = event.interval;
      }
    );
    useEventListener(window2, "devicemotion", onDeviceMotion);
  }
  return {
    acceleration,
    accelerationIncludingGravity,
    rotationRate,
    interval
  };
}
__name(useDeviceMotion, "useDeviceMotion");
function useDeviceOrientation(options2 = {}) {
  const { window: window2 = defaultWindow } = options2;
  const isSupported = useSupported(() => window2 && "DeviceOrientationEvent" in window2);
  const isAbsolute2 = ref$3(false);
  const alpha2 = ref$3(null);
  const beta = ref$3(null);
  const gamma = ref$3(null);
  if (window2 && isSupported.value) {
    useEventListener(window2, "deviceorientation", (event) => {
      isAbsolute2.value = event.absolute;
      alpha2.value = event.alpha;
      beta.value = event.beta;
      gamma.value = event.gamma;
    });
  }
  return {
    isSupported,
    isAbsolute: isAbsolute2,
    alpha: alpha2,
    beta,
    gamma
  };
}
__name(useDeviceOrientation, "useDeviceOrientation");
function useDevicePixelRatio(options2 = {}) {
  const {
    window: window2 = defaultWindow
  } = options2;
  const pixelRatio = ref$3(1);
  if (window2) {
    let observe2 = /* @__PURE__ */ __name(function() {
      pixelRatio.value = window2.devicePixelRatio;
      cleanup2();
      media = window2.matchMedia(`(resolution: ${pixelRatio.value}dppx)`);
      media.addEventListener("change", observe2, { once: true });
    }, "observe2"), cleanup2 = /* @__PURE__ */ __name(function() {
      media == null ? void 0 : media.removeEventListener("change", observe2);
    }, "cleanup2");
    let media;
    observe2();
    tryOnScopeDispose(cleanup2);
  }
  return { pixelRatio };
}
__name(useDevicePixelRatio, "useDevicePixelRatio");
function useDevicesList(options2 = {}) {
  const {
    navigator: navigator2 = defaultNavigator,
    requestPermissions = false,
    constraints = { audio: true, video: true },
    onUpdated: onUpdated2
  } = options2;
  const devices = ref$3([]);
  const videoInputs = computed(() => devices.value.filter((i2) => i2.kind === "videoinput"));
  const audioInputs = computed(() => devices.value.filter((i2) => i2.kind === "audioinput"));
  const audioOutputs = computed(() => devices.value.filter((i2) => i2.kind === "audiooutput"));
  const isSupported = useSupported(() => navigator2 && navigator2.mediaDevices && navigator2.mediaDevices.enumerateDevices);
  const permissionGranted = ref$3(false);
  let stream;
  async function update2() {
    if (!isSupported.value)
      return;
    devices.value = await navigator2.mediaDevices.enumerateDevices();
    onUpdated2 == null ? void 0 : onUpdated2(devices.value);
    if (stream) {
      stream.getTracks().forEach((t2) => t2.stop());
      stream = null;
    }
  }
  __name(update2, "update");
  async function ensurePermissions() {
    if (!isSupported.value)
      return false;
    if (permissionGranted.value)
      return true;
    const { state, query: query2 } = usePermission("camera", { controls: true });
    await query2();
    if (state.value !== "granted") {
      stream = await navigator2.mediaDevices.getUserMedia(constraints);
      update2();
      permissionGranted.value = true;
    } else {
      permissionGranted.value = true;
    }
    return permissionGranted.value;
  }
  __name(ensurePermissions, "ensurePermissions");
  if (isSupported.value) {
    if (requestPermissions)
      ensurePermissions();
    useEventListener(navigator2.mediaDevices, "devicechange", update2);
    update2();
  }
  return {
    devices,
    ensurePermissions,
    permissionGranted,
    videoInputs,
    audioInputs,
    audioOutputs,
    isSupported
  };
}
__name(useDevicesList, "useDevicesList");
function useDisplayMedia(options2 = {}) {
  var _a2;
  const enabled = ref$3((_a2 = options2.enabled) != null ? _a2 : false);
  const video = options2.video;
  const audio = options2.audio;
  const { navigator: navigator2 = defaultNavigator } = options2;
  const isSupported = useSupported(() => {
    var _a22;
    return (_a22 = navigator2 == null ? void 0 : navigator2.mediaDevices) == null ? void 0 : _a22.getDisplayMedia;
  });
  const constraint = { audio, video };
  const stream = shallowRef();
  async function _start() {
    var _a22;
    if (!isSupported.value || stream.value)
      return;
    stream.value = await navigator2.mediaDevices.getDisplayMedia(constraint);
    (_a22 = stream.value) == null ? void 0 : _a22.getTracks().forEach((t2) => t2.addEventListener("ended", stop2));
    return stream.value;
  }
  __name(_start, "_start");
  async function _stop() {
    var _a22;
    (_a22 = stream.value) == null ? void 0 : _a22.getTracks().forEach((t2) => t2.stop());
    stream.value = void 0;
  }
  __name(_stop, "_stop");
  function stop2() {
    _stop();
    enabled.value = false;
  }
  __name(stop2, "stop");
  async function start2() {
    await _start();
    if (stream.value)
      enabled.value = true;
    return stream.value;
  }
  __name(start2, "start");
  watch(
    enabled,
    (v2) => {
      if (v2)
        _start();
      else
        _stop();
    },
    { immediate: true }
  );
  return {
    isSupported,
    stream,
    start: start2,
    stop: stop2,
    enabled
  };
}
__name(useDisplayMedia, "useDisplayMedia");
function useDocumentVisibility(options2 = {}) {
  const { document: document2 = defaultDocument } = options2;
  if (!document2)
    return ref$3("visible");
  const visibility = ref$3(document2.visibilityState);
  useEventListener(document2, "visibilitychange", () => {
    visibility.value = document2.visibilityState;
  });
  return visibility;
}
__name(useDocumentVisibility, "useDocumentVisibility");
function useDraggable(target, options2 = {}) {
  var _a2, _b;
  const {
    pointerTypes,
    preventDefault: preventDefault2,
    stopPropagation,
    exact,
    onMove,
    onEnd,
    onStart,
    initialValue,
    axis = "both",
    draggingElement = defaultWindow,
    containerElement,
    handle: draggingHandle = target,
    buttons = [0]
  } = options2;
  const position = ref$3(
    (_a2 = toValue$3(initialValue)) != null ? _a2 : { x: 0, y: 0 }
  );
  const pressedDelta = ref$3();
  const filterEvent = /* @__PURE__ */ __name((e2) => {
    if (pointerTypes)
      return pointerTypes.includes(e2.pointerType);
    return true;
  }, "filterEvent");
  const handleEvent = /* @__PURE__ */ __name((e2) => {
    if (toValue$3(preventDefault2))
      e2.preventDefault();
    if (toValue$3(stopPropagation))
      e2.stopPropagation();
  }, "handleEvent");
  const start2 = /* @__PURE__ */ __name((e2) => {
    var _a22;
    if (!toValue$3(buttons).includes(e2.button))
      return;
    if (toValue$3(options2.disabled) || !filterEvent(e2))
      return;
    if (toValue$3(exact) && e2.target !== toValue$3(target))
      return;
    const container = toValue$3(containerElement);
    const containerRect = (_a22 = container == null ? void 0 : container.getBoundingClientRect) == null ? void 0 : _a22.call(container);
    const targetRect = toValue$3(target).getBoundingClientRect();
    const pos = {
      x: e2.clientX - (container ? targetRect.left - containerRect.left + container.scrollLeft : targetRect.left),
      y: e2.clientY - (container ? targetRect.top - containerRect.top + container.scrollTop : targetRect.top)
    };
    if ((onStart == null ? void 0 : onStart(pos, e2)) === false)
      return;
    pressedDelta.value = pos;
    handleEvent(e2);
  }, "start");
  const move = /* @__PURE__ */ __name((e2) => {
    if (toValue$3(options2.disabled) || !filterEvent(e2))
      return;
    if (!pressedDelta.value)
      return;
    const container = toValue$3(containerElement);
    const targetRect = toValue$3(target).getBoundingClientRect();
    let { x: x2, y: y2 } = position.value;
    if (axis === "x" || axis === "both") {
      x2 = e2.clientX - pressedDelta.value.x;
      if (container)
        x2 = Math.min(Math.max(0, x2), container.scrollWidth - targetRect.width);
    }
    if (axis === "y" || axis === "both") {
      y2 = e2.clientY - pressedDelta.value.y;
      if (container)
        y2 = Math.min(Math.max(0, y2), container.scrollHeight - targetRect.height);
    }
    position.value = {
      x: x2,
      y: y2
    };
    onMove == null ? void 0 : onMove(position.value, e2);
    handleEvent(e2);
  }, "move");
  const end = /* @__PURE__ */ __name((e2) => {
    if (toValue$3(options2.disabled) || !filterEvent(e2))
      return;
    if (!pressedDelta.value)
      return;
    pressedDelta.value = void 0;
    onEnd == null ? void 0 : onEnd(position.value, e2);
    handleEvent(e2);
  }, "end");
  if (isClient$1) {
    const config2 = { capture: (_b = options2.capture) != null ? _b : true };
    useEventListener(draggingHandle, "pointerdown", start2, config2);
    useEventListener(draggingElement, "pointermove", move, config2);
    useEventListener(draggingElement, "pointerup", end, config2);
  }
  return {
    ...toRefs(position),
    position,
    isDragging: computed(() => !!pressedDelta.value),
    style: computed(
      () => `left:${position.value.x}px;top:${position.value.y}px;`
    )
  };
}
__name(useDraggable, "useDraggable");
function useDropZone(target, options2 = {}) {
  const isOverDropZone = ref$3(false);
  const files = shallowRef(null);
  let counter = 0;
  let isDataTypeIncluded = true;
  if (isClient$1) {
    const _options = typeof options2 === "function" ? { onDrop: options2 } : options2;
    const getFiles = /* @__PURE__ */ __name((event) => {
      var _a2, _b;
      const list2 = Array.from((_b = (_a2 = event.dataTransfer) == null ? void 0 : _a2.files) != null ? _b : []);
      return files.value = list2.length === 0 ? null : list2;
    }, "getFiles");
    useEventListener(target, "dragenter", (event) => {
      var _a2, _b;
      const types = Array.from(((_a2 = event == null ? void 0 : event.dataTransfer) == null ? void 0 : _a2.items) || []).map((i2) => i2.kind === "file" ? i2.type : null).filter(notNullish);
      if (_options.dataTypes && event.dataTransfer) {
        const dataTypes2 = unref(_options.dataTypes);
        isDataTypeIncluded = typeof dataTypes2 === "function" ? dataTypes2(types) : dataTypes2 ? dataTypes2.some((item) => types.includes(item)) : true;
        if (!isDataTypeIncluded)
          return;
      }
      event.preventDefault();
      counter += 1;
      isOverDropZone.value = true;
      (_b = _options.onEnter) == null ? void 0 : _b.call(_options, getFiles(event), event);
    });
    useEventListener(target, "dragover", (event) => {
      var _a2;
      if (!isDataTypeIncluded)
        return;
      event.preventDefault();
      (_a2 = _options.onOver) == null ? void 0 : _a2.call(_options, getFiles(event), event);
    });
    useEventListener(target, "dragleave", (event) => {
      var _a2;
      if (!isDataTypeIncluded)
        return;
      event.preventDefault();
      counter -= 1;
      if (counter === 0)
        isOverDropZone.value = false;
      (_a2 = _options.onLeave) == null ? void 0 : _a2.call(_options, getFiles(event), event);
    });
    useEventListener(target, "drop", (event) => {
      var _a2;
      event.preventDefault();
      counter = 0;
      isOverDropZone.value = false;
      (_a2 = _options.onDrop) == null ? void 0 : _a2.call(_options, getFiles(event), event);
    });
  }
  return {
    files,
    isOverDropZone
  };
}
__name(useDropZone, "useDropZone");
function useResizeObserver(target, callback, options2 = {}) {
  const { window: window2 = defaultWindow, ...observerOptions } = options2;
  let observer;
  const isSupported = useSupported(() => window2 && "ResizeObserver" in window2);
  const cleanup = /* @__PURE__ */ __name(() => {
    if (observer) {
      observer.disconnect();
      observer = void 0;
    }
  }, "cleanup");
  const targets = computed(() => {
    const _targets = toValue$3(target);
    return Array.isArray(_targets) ? _targets.map((el) => unrefElement(el)) : [unrefElement(_targets)];
  });
  const stopWatch = watch(
    targets,
    (els) => {
      cleanup();
      if (isSupported.value && window2) {
        observer = new ResizeObserver(callback);
        for (const _el of els) {
          if (_el)
            observer.observe(_el, observerOptions);
        }
      }
    },
    { immediate: true, flush: "post" }
  );
  const stop2 = /* @__PURE__ */ __name(() => {
    cleanup();
    stopWatch();
  }, "stop");
  tryOnScopeDispose(stop2);
  return {
    isSupported,
    stop: stop2
  };
}
__name(useResizeObserver, "useResizeObserver");
function useElementBounding(target, options2 = {}) {
  const {
    reset: reset2 = true,
    windowResize = true,
    windowScroll = true,
    immediate = true,
    updateTiming = "sync"
  } = options2;
  const height = ref$3(0);
  const bottom = ref$3(0);
  const left = ref$3(0);
  const right = ref$3(0);
  const top = ref$3(0);
  const width2 = ref$3(0);
  const x2 = ref$3(0);
  const y2 = ref$3(0);
  function recalculate() {
    const el = unrefElement(target);
    if (!el) {
      if (reset2) {
        height.value = 0;
        bottom.value = 0;
        left.value = 0;
        right.value = 0;
        top.value = 0;
        width2.value = 0;
        x2.value = 0;
        y2.value = 0;
      }
      return;
    }
    const rect = el.getBoundingClientRect();
    height.value = rect.height;
    bottom.value = rect.bottom;
    left.value = rect.left;
    right.value = rect.right;
    top.value = rect.top;
    width2.value = rect.width;
    x2.value = rect.x;
    y2.value = rect.y;
  }
  __name(recalculate, "recalculate");
  function update2() {
    if (updateTiming === "sync")
      recalculate();
    else if (updateTiming === "next-frame")
      requestAnimationFrame(() => recalculate());
  }
  __name(update2, "update");
  useResizeObserver(target, update2);
  watch(() => unrefElement(target), (ele) => !ele && update2());
  useMutationObserver(target, update2, {
    attributeFilter: ["style", "class"]
  });
  if (windowScroll)
    useEventListener("scroll", update2, { capture: true, passive: true });
  if (windowResize)
    useEventListener("resize", update2, { passive: true });
  tryOnMounted$2(() => {
    if (immediate)
      update2();
  });
  return {
    height,
    bottom,
    left,
    right,
    top,
    width: width2,
    x: x2,
    y: y2,
    update: update2
  };
}
__name(useElementBounding, "useElementBounding");
function useElementByPoint(options2) {
  const {
    x: x2,
    y: y2,
    document: document2 = defaultDocument,
    multiple,
    interval = "requestAnimationFrame",
    immediate = true
  } = options2;
  const isSupported = useSupported(() => {
    if (toValue$3(multiple))
      return document2 && "elementsFromPoint" in document2;
    return document2 && "elementFromPoint" in document2;
  });
  const element = ref$3(null);
  const cb = /* @__PURE__ */ __name(() => {
    var _a2, _b;
    element.value = toValue$3(multiple) ? (_a2 = document2 == null ? void 0 : document2.elementsFromPoint(toValue$3(x2), toValue$3(y2))) != null ? _a2 : [] : (_b = document2 == null ? void 0 : document2.elementFromPoint(toValue$3(x2), toValue$3(y2))) != null ? _b : null;
  }, "cb");
  const controls = interval === "requestAnimationFrame" ? useRafFn(cb, { immediate }) : useIntervalFn(cb, interval, { immediate });
  return {
    isSupported,
    element,
    ...controls
  };
}
__name(useElementByPoint, "useElementByPoint");
function useElementHover(el, options2 = {}) {
  const {
    delayEnter = 0,
    delayLeave = 0,
    window: window2 = defaultWindow
  } = options2;
  const isHovered = ref$3(false);
  let timer;
  const toggle = /* @__PURE__ */ __name((entering) => {
    const delay = entering ? delayEnter : delayLeave;
    if (timer) {
      clearTimeout(timer);
      timer = void 0;
    }
    if (delay)
      timer = setTimeout(() => isHovered.value = entering, delay);
    else
      isHovered.value = entering;
  }, "toggle");
  if (!window2)
    return isHovered;
  useEventListener(el, "mouseenter", () => toggle(true), { passive: true });
  useEventListener(el, "mouseleave", () => toggle(false), { passive: true });
  return isHovered;
}
__name(useElementHover, "useElementHover");
function useElementSize(target, initialSize = { width: 0, height: 0 }, options2 = {}) {
  const { window: window2 = defaultWindow, box = "content-box" } = options2;
  const isSVG = computed(() => {
    var _a2, _b;
    return (_b = (_a2 = unrefElement(target)) == null ? void 0 : _a2.namespaceURI) == null ? void 0 : _b.includes("svg");
  });
  const width2 = ref$3(initialSize.width);
  const height = ref$3(initialSize.height);
  const { stop: stop1 } = useResizeObserver(
    target,
    ([entry]) => {
      const boxSize = box === "border-box" ? entry.borderBoxSize : box === "content-box" ? entry.contentBoxSize : entry.devicePixelContentBoxSize;
      if (window2 && isSVG.value) {
        const $elem = unrefElement(target);
        if ($elem) {
          const rect = $elem.getBoundingClientRect();
          width2.value = rect.width;
          height.value = rect.height;
        }
      } else {
        if (boxSize) {
          const formatBoxSize = Array.isArray(boxSize) ? boxSize : [boxSize];
          width2.value = formatBoxSize.reduce((acc, { inlineSize }) => acc + inlineSize, 0);
          height.value = formatBoxSize.reduce((acc, { blockSize }) => acc + blockSize, 0);
        } else {
          width2.value = entry.contentRect.width;
          height.value = entry.contentRect.height;
        }
      }
    },
    options2
  );
  tryOnMounted$2(() => {
    const ele = unrefElement(target);
    if (ele) {
      width2.value = "offsetWidth" in ele ? ele.offsetWidth : initialSize.width;
      height.value = "offsetHeight" in ele ? ele.offsetHeight : initialSize.height;
    }
  });
  const stop2 = watch(
    () => unrefElement(target),
    (ele) => {
      width2.value = ele ? initialSize.width : 0;
      height.value = ele ? initialSize.height : 0;
    }
  );
  function stop3() {
    stop1();
    stop2();
  }
  __name(stop3, "stop");
  return {
    width: width2,
    height,
    stop: stop3
  };
}
__name(useElementSize, "useElementSize");
function useIntersectionObserver(target, callback, options2 = {}) {
  const {
    root: root2,
    rootMargin = "0px",
    threshold = 0,
    window: window2 = defaultWindow,
    immediate = true
  } = options2;
  const isSupported = useSupported(() => window2 && "IntersectionObserver" in window2);
  const targets = computed(() => {
    const _target = toValue$3(target);
    return (Array.isArray(_target) ? _target : [_target]).map(unrefElement).filter(notNullish);
  });
  let cleanup = noop$2;
  const isActive2 = ref$3(immediate);
  const stopWatch = isSupported.value ? watch(
    () => [targets.value, unrefElement(root2), isActive2.value],
    ([targets2, root22]) => {
      cleanup();
      if (!isActive2.value)
        return;
      if (!targets2.length)
        return;
      const observer = new IntersectionObserver(
        callback,
        {
          root: unrefElement(root22),
          rootMargin,
          threshold
        }
      );
      targets2.forEach((el) => el && observer.observe(el));
      cleanup = /* @__PURE__ */ __name(() => {
        observer.disconnect();
        cleanup = noop$2;
      }, "cleanup");
    },
    { immediate, flush: "post" }
  ) : noop$2;
  const stop2 = /* @__PURE__ */ __name(() => {
    cleanup();
    stopWatch();
    isActive2.value = false;
  }, "stop");
  tryOnScopeDispose(stop2);
  return {
    isSupported,
    isActive: isActive2,
    pause() {
      cleanup();
      isActive2.value = false;
    },
    resume() {
      isActive2.value = true;
    },
    stop: stop2
  };
}
__name(useIntersectionObserver, "useIntersectionObserver");
function useElementVisibility(element, options2 = {}) {
  const { window: window2 = defaultWindow, scrollTarget, threshold = 0 } = options2;
  const elementIsVisible = ref$3(false);
  useIntersectionObserver(
    element,
    (intersectionObserverEntries) => {
      let isIntersecting = elementIsVisible.value;
      let latestTime = 0;
      for (const entry of intersectionObserverEntries) {
        if (entry.time >= latestTime) {
          latestTime = entry.time;
          isIntersecting = entry.isIntersecting;
        }
      }
      elementIsVisible.value = isIntersecting;
    },
    {
      root: scrollTarget,
      window: window2,
      threshold
    }
  );
  return elementIsVisible;
}
__name(useElementVisibility, "useElementVisibility");
const events = /* @__PURE__ */ new Map();
function useEventBus(key) {
  const scope = getCurrentScope$1();
  function on2(listener) {
    var _a2;
    const listeners = events.get(key) || /* @__PURE__ */ new Set();
    listeners.add(listener);
    events.set(key, listeners);
    const _off = /* @__PURE__ */ __name(() => off2(listener), "_off");
    (_a2 = scope == null ? void 0 : scope.cleanups) == null ? void 0 : _a2.push(_off);
    return _off;
  }
  __name(on2, "on");
  function once2(listener) {
    function _listener(...args) {
      off2(_listener);
      listener(...args);
    }
    __name(_listener, "_listener");
    return on2(_listener);
  }
  __name(once2, "once");
  function off2(listener) {
    const listeners = events.get(key);
    if (!listeners)
      return;
    listeners.delete(listener);
    if (!listeners.size)
      reset2();
  }
  __name(off2, "off");
  function reset2() {
    events.delete(key);
  }
  __name(reset2, "reset");
  function emit(event, payload) {
    var _a2;
    (_a2 = events.get(key)) == null ? void 0 : _a2.forEach((v2) => v2(event, payload));
  }
  __name(emit, "emit");
  return { on: on2, once: once2, off: off2, emit, reset: reset2 };
}
__name(useEventBus, "useEventBus");
function resolveNestedOptions$1(options2) {
  if (options2 === true)
    return {};
  return options2;
}
__name(resolveNestedOptions$1, "resolveNestedOptions$1");
function useEventSource(url, events2 = [], options2 = {}) {
  const event = ref$3(null);
  const data = ref$3(null);
  const status = ref$3("CONNECTING");
  const eventSource = ref$3(null);
  const error2 = shallowRef(null);
  const urlRef = toRef(url);
  const lastEventId2 = shallowRef(null);
  let explicitlyClosed = false;
  let retried = 0;
  const {
    withCredentials = false,
    immediate = true
  } = options2;
  const close2 = /* @__PURE__ */ __name(() => {
    if (isClient$1 && eventSource.value) {
      eventSource.value.close();
      eventSource.value = null;
      status.value = "CLOSED";
      explicitlyClosed = true;
    }
  }, "close");
  const _init = /* @__PURE__ */ __name(() => {
    if (explicitlyClosed || typeof urlRef.value === "undefined")
      return;
    const es2 = new EventSource(urlRef.value, { withCredentials });
    status.value = "CONNECTING";
    eventSource.value = es2;
    es2.onopen = () => {
      status.value = "OPEN";
      error2.value = null;
    };
    es2.onerror = (e2) => {
      status.value = "CLOSED";
      error2.value = e2;
      if (es2.readyState === 2 && !explicitlyClosed && options2.autoReconnect) {
        es2.close();
        const {
          retries = -1,
          delay = 1e3,
          onFailed
        } = resolveNestedOptions$1(options2.autoReconnect);
        retried += 1;
        if (typeof retries === "number" && (retries < 0 || retried < retries))
          setTimeout(_init, delay);
        else if (typeof retries === "function" && retries())
          setTimeout(_init, delay);
        else
          onFailed == null ? void 0 : onFailed();
      }
    };
    es2.onmessage = (e2) => {
      event.value = null;
      data.value = e2.data;
      lastEventId2.value = e2.lastEventId;
    };
    for (const event_name of events2) {
      useEventListener(es2, event_name, (e2) => {
        event.value = event_name;
        data.value = e2.data || null;
      });
    }
  }, "_init");
  const open2 = /* @__PURE__ */ __name(() => {
    if (!isClient$1)
      return;
    close2();
    explicitlyClosed = false;
    retried = 0;
    _init();
  }, "open");
  if (immediate)
    watch(urlRef, open2, { immediate: true });
  tryOnScopeDispose(close2);
  return {
    eventSource,
    event,
    data,
    status,
    error: error2,
    open: open2,
    close: close2,
    lastEventId: lastEventId2
  };
}
__name(useEventSource, "useEventSource");
function useEyeDropper(options2 = {}) {
  const { initialValue = "" } = options2;
  const isSupported = useSupported(() => typeof window !== "undefined" && "EyeDropper" in window);
  const sRGBHex = ref$3(initialValue);
  async function open2(openOptions) {
    if (!isSupported.value)
      return;
    const eyeDropper = new window.EyeDropper();
    const result = await eyeDropper.open(openOptions);
    sRGBHex.value = result.sRGBHex;
    return result;
  }
  __name(open2, "open");
  return { isSupported, sRGBHex, open: open2 };
}
__name(useEyeDropper, "useEyeDropper");
function useFavicon(newIcon = null, options2 = {}) {
  const {
    baseUrl = "",
    rel = "icon",
    document: document2 = defaultDocument
  } = options2;
  const favicon = toRef(newIcon);
  const applyIcon = /* @__PURE__ */ __name((icon2) => {
    const elements = document2 == null ? void 0 : document2.head.querySelectorAll(`link[rel*="${rel}"]`);
    if (!elements || elements.length === 0) {
      const link2 = document2 == null ? void 0 : document2.createElement("link");
      if (link2) {
        link2.rel = rel;
        link2.href = `${baseUrl}${icon2}`;
        link2.type = `image/${icon2.split(".").pop()}`;
        document2 == null ? void 0 : document2.head.append(link2);
      }
      return;
    }
    elements == null ? void 0 : elements.forEach((el) => el.href = `${baseUrl}${icon2}`);
  }, "applyIcon");
  watch(
    favicon,
    (i2, o2) => {
      if (typeof i2 === "string" && i2 !== o2)
        applyIcon(i2);
    },
    { immediate: true }
  );
  return favicon;
}
__name(useFavicon, "useFavicon");
const payloadMapping = {
  json: "application/json",
  text: "text/plain"
};
function isFetchOptions(obj) {
  return obj && containsProp(obj, "immediate", "refetch", "initialData", "timeout", "beforeFetch", "afterFetch", "onFetchError", "fetch", "updateDataOnError");
}
__name(isFetchOptions, "isFetchOptions");
const reAbsolute = /^(?:[a-z][a-z\d+\-.]*:)?\/\//i;
function isAbsoluteURL$1(url) {
  return reAbsolute.test(url);
}
__name(isAbsoluteURL$1, "isAbsoluteURL$1");
function headersToObject$1(headers) {
  if (typeof Headers !== "undefined" && headers instanceof Headers)
    return Object.fromEntries(headers.entries());
  return headers;
}
__name(headersToObject$1, "headersToObject$1");
function combineCallbacks(combination, ...callbacks) {
  if (combination === "overwrite") {
    return async (ctx) => {
      const callback = callbacks[callbacks.length - 1];
      if (callback)
        return { ...ctx, ...await callback(ctx) };
      return ctx;
    };
  } else {
    return async (ctx) => {
      for (const callback of callbacks) {
        if (callback)
          ctx = { ...ctx, ...await callback(ctx) };
      }
      return ctx;
    };
  }
}
__name(combineCallbacks, "combineCallbacks");
function createFetch(config2 = {}) {
  const _combination = config2.combination || "chain";
  const _options = config2.options || {};
  const _fetchOptions = config2.fetchOptions || {};
  function useFactoryFetch(url, ...args) {
    const computedUrl = computed(() => {
      const baseUrl = toValue$3(config2.baseUrl);
      const targetUrl = toValue$3(url);
      return baseUrl && !isAbsoluteURL$1(targetUrl) ? joinPaths(baseUrl, targetUrl) : targetUrl;
    });
    let options2 = _options;
    let fetchOptions = _fetchOptions;
    if (args.length > 0) {
      if (isFetchOptions(args[0])) {
        options2 = {
          ...options2,
          ...args[0],
          beforeFetch: combineCallbacks(_combination, _options.beforeFetch, args[0].beforeFetch),
          afterFetch: combineCallbacks(_combination, _options.afterFetch, args[0].afterFetch),
          onFetchError: combineCallbacks(_combination, _options.onFetchError, args[0].onFetchError)
        };
      } else {
        fetchOptions = {
          ...fetchOptions,
          ...args[0],
          headers: {
            ...headersToObject$1(fetchOptions.headers) || {},
            ...headersToObject$1(args[0].headers) || {}
          }
        };
      }
    }
    if (args.length > 1 && isFetchOptions(args[1])) {
      options2 = {
        ...options2,
        ...args[1],
        beforeFetch: combineCallbacks(_combination, _options.beforeFetch, args[1].beforeFetch),
        afterFetch: combineCallbacks(_combination, _options.afterFetch, args[1].afterFetch),
        onFetchError: combineCallbacks(_combination, _options.onFetchError, args[1].onFetchError)
      };
    }
    return useFetch(computedUrl, fetchOptions, options2);
  }
  __name(useFactoryFetch, "useFactoryFetch");
  return useFactoryFetch;
}
__name(createFetch, "createFetch");
function useFetch(url, ...args) {
  var _a2;
  const supportsAbort = typeof AbortController === "function";
  let fetchOptions = {};
  let options2 = {
    immediate: true,
    refetch: false,
    timeout: 0,
    updateDataOnError: false
  };
  const config2 = {
    method: "GET",
    type: "text",
    payload: void 0
  };
  if (args.length > 0) {
    if (isFetchOptions(args[0]))
      options2 = { ...options2, ...args[0] };
    else
      fetchOptions = args[0];
  }
  if (args.length > 1) {
    if (isFetchOptions(args[1]))
      options2 = { ...options2, ...args[1] };
  }
  const {
    fetch: fetch2 = (_a2 = defaultWindow) == null ? void 0 : _a2.fetch,
    initialData,
    timeout
  } = options2;
  const responseEvent = createEventHook();
  const errorEvent = createEventHook();
  const finallyEvent = createEventHook();
  const isFinished = ref$3(false);
  const isFetching2 = ref$3(false);
  const aborted = ref$3(false);
  const statusCode = ref$3(null);
  const response = shallowRef(null);
  const error2 = shallowRef(null);
  const data = shallowRef(initialData || null);
  const canAbort = computed(() => supportsAbort && isFetching2.value);
  let controller;
  let timer;
  const abort = /* @__PURE__ */ __name(() => {
    if (supportsAbort) {
      controller == null ? void 0 : controller.abort();
      controller = new AbortController();
      controller.signal.onabort = () => aborted.value = true;
      fetchOptions = {
        ...fetchOptions,
        signal: controller.signal
      };
    }
  }, "abort");
  const loading = /* @__PURE__ */ __name((isLoading) => {
    isFetching2.value = isLoading;
    isFinished.value = !isLoading;
  }, "loading");
  if (timeout)
    timer = useTimeoutFn(abort, timeout, { immediate: false });
  let executeCounter = 0;
  const execute = /* @__PURE__ */ __name(async (throwOnFailed = false) => {
    var _a22, _b;
    abort();
    loading(true);
    error2.value = null;
    statusCode.value = null;
    aborted.value = false;
    executeCounter += 1;
    const currentExecuteCounter = executeCounter;
    const defaultFetchOptions = {
      method: config2.method,
      headers: {}
    };
    if (config2.payload) {
      const headers = headersToObject$1(defaultFetchOptions.headers);
      const payload = toValue$3(config2.payload);
      if (!config2.payloadType && payload && Object.getPrototypeOf(payload) === Object.prototype && !(payload instanceof FormData))
        config2.payloadType = "json";
      if (config2.payloadType)
        headers["Content-Type"] = (_a22 = payloadMapping[config2.payloadType]) != null ? _a22 : config2.payloadType;
      defaultFetchOptions.body = config2.payloadType === "json" ? JSON.stringify(payload) : payload;
    }
    let isCanceled = false;
    const context = {
      url: toValue$3(url),
      options: {
        ...defaultFetchOptions,
        ...fetchOptions
      },
      cancel: /* @__PURE__ */ __name(() => {
        isCanceled = true;
      }, "cancel")
    };
    if (options2.beforeFetch)
      Object.assign(context, await options2.beforeFetch(context));
    if (isCanceled || !fetch2) {
      loading(false);
      return Promise.resolve(null);
    }
    let responseData = null;
    if (timer)
      timer.start();
    return fetch2(
      context.url,
      {
        ...defaultFetchOptions,
        ...context.options,
        headers: {
          ...headersToObject$1(defaultFetchOptions.headers),
          ...headersToObject$1((_b = context.options) == null ? void 0 : _b.headers)
        }
      }
    ).then(async (fetchResponse) => {
      response.value = fetchResponse;
      statusCode.value = fetchResponse.status;
      responseData = await fetchResponse.clone()[config2.type]();
      if (!fetchResponse.ok) {
        data.value = initialData || null;
        throw new Error(fetchResponse.statusText);
      }
      if (options2.afterFetch) {
        ({ data: responseData } = await options2.afterFetch({
          data: responseData,
          response: fetchResponse
        }));
      }
      data.value = responseData;
      responseEvent.trigger(fetchResponse);
      return fetchResponse;
    }).catch(async (fetchError) => {
      let errorData = fetchError.message || fetchError.name;
      if (options2.onFetchError) {
        ({ error: errorData, data: responseData } = await options2.onFetchError({
          data: responseData,
          error: fetchError,
          response: response.value
        }));
      }
      error2.value = errorData;
      if (options2.updateDataOnError)
        data.value = responseData;
      errorEvent.trigger(fetchError);
      if (throwOnFailed)
        throw fetchError;
      return null;
    }).finally(() => {
      if (currentExecuteCounter === executeCounter)
        loading(false);
      if (timer)
        timer.stop();
      finallyEvent.trigger(null);
    });
  }, "execute");
  const refetch = toRef(options2.refetch);
  watch(
    [
      refetch,
      toRef(url)
    ],
    ([refetch2]) => refetch2 && execute(),
    { deep: true }
  );
  const shell = {
    isFinished: readonly(isFinished),
    isFetching: readonly(isFetching2),
    statusCode,
    response,
    error: error2,
    data,
    canAbort,
    aborted,
    abort,
    execute,
    onFetchResponse: responseEvent.on,
    onFetchError: errorEvent.on,
    onFetchFinally: finallyEvent.on,
    // method
    get: setMethod("GET"),
    put: setMethod("PUT"),
    post: setMethod("POST"),
    delete: setMethod("DELETE"),
    patch: setMethod("PATCH"),
    head: setMethod("HEAD"),
    options: setMethod("OPTIONS"),
    // type
    json: setType2("json"),
    text: setType2("text"),
    blob: setType2("blob"),
    arrayBuffer: setType2("arrayBuffer"),
    formData: setType2("formData")
  };
  function setMethod(method) {
    return (payload, payloadType) => {
      if (!isFetching2.value) {
        config2.method = method;
        config2.payload = payload;
        config2.payloadType = payloadType;
        if (isRef(config2.payload)) {
          watch(
            [
              refetch,
              toRef(config2.payload)
            ],
            ([refetch2]) => refetch2 && execute(),
            { deep: true }
          );
        }
        return {
          ...shell,
          then(onFulfilled, onRejected) {
            return waitUntilFinished().then(onFulfilled, onRejected);
          }
        };
      }
      return void 0;
    };
  }
  __name(setMethod, "setMethod");
  function waitUntilFinished() {
    return new Promise((resolve2, reject) => {
      until(isFinished).toBe(true).then(() => resolve2(shell)).catch((error22) => reject(error22));
    });
  }
  __name(waitUntilFinished, "waitUntilFinished");
  function setType2(type) {
    return () => {
      if (!isFetching2.value) {
        config2.type = type;
        return {
          ...shell,
          then(onFulfilled, onRejected) {
            return waitUntilFinished().then(onFulfilled, onRejected);
          }
        };
      }
      return void 0;
    };
  }
  __name(setType2, "setType");
  if (options2.immediate)
    Promise.resolve().then(() => execute());
  return {
    ...shell,
    then(onFulfilled, onRejected) {
      return waitUntilFinished().then(onFulfilled, onRejected);
    }
  };
}
__name(useFetch, "useFetch");
function joinPaths(start2, end) {
  if (!start2.endsWith("/") && !end.startsWith("/"))
    return `${start2}/${end}`;
  return `${start2}${end}`;
}
__name(joinPaths, "joinPaths");
const DEFAULT_OPTIONS = {
  multiple: true,
  accept: "*",
  reset: false,
  directory: false
};
function useFileDialog(options2 = {}) {
  const {
    document: document2 = defaultDocument
  } = options2;
  const files = ref$3(null);
  const { on: onChange2, trigger } = createEventHook();
  let input;
  if (document2) {
    input = document2.createElement("input");
    input.type = "file";
    input.onchange = (event) => {
      const result = event.target;
      files.value = result.files;
      trigger(files.value);
    };
  }
  const reset2 = /* @__PURE__ */ __name(() => {
    files.value = null;
    if (input && input.value) {
      input.value = "";
      trigger(null);
    }
  }, "reset");
  const open2 = /* @__PURE__ */ __name((localOptions) => {
    if (!input)
      return;
    const _options = {
      ...DEFAULT_OPTIONS,
      ...options2,
      ...localOptions
    };
    input.multiple = _options.multiple;
    input.accept = _options.accept;
    input.webkitdirectory = _options.directory;
    if (hasOwn$1(_options, "capture"))
      input.capture = _options.capture;
    if (_options.reset)
      reset2();
    input.click();
  }, "open");
  return {
    files: readonly(files),
    open: open2,
    reset: reset2,
    onChange: onChange2
  };
}
__name(useFileDialog, "useFileDialog");
function useFileSystemAccess(options2 = {}) {
  const {
    window: _window2 = defaultWindow,
    dataType = "Text"
  } = options2;
  const window2 = _window2;
  const isSupported = useSupported(() => window2 && "showSaveFilePicker" in window2 && "showOpenFilePicker" in window2);
  const fileHandle = ref$3();
  const data = ref$3();
  const file = ref$3();
  const fileName = computed(() => {
    var _a2, _b;
    return (_b = (_a2 = file.value) == null ? void 0 : _a2.name) != null ? _b : "";
  });
  const fileMIME = computed(() => {
    var _a2, _b;
    return (_b = (_a2 = file.value) == null ? void 0 : _a2.type) != null ? _b : "";
  });
  const fileSize = computed(() => {
    var _a2, _b;
    return (_b = (_a2 = file.value) == null ? void 0 : _a2.size) != null ? _b : 0;
  });
  const fileLastModified = computed(() => {
    var _a2, _b;
    return (_b = (_a2 = file.value) == null ? void 0 : _a2.lastModified) != null ? _b : 0;
  });
  async function open2(_options = {}) {
    if (!isSupported.value)
      return;
    const [handle] = await window2.showOpenFilePicker({ ...toValue$3(options2), ..._options });
    fileHandle.value = handle;
    await updateData();
  }
  __name(open2, "open");
  async function create2(_options = {}) {
    if (!isSupported.value)
      return;
    fileHandle.value = await window2.showSaveFilePicker({ ...options2, ..._options });
    data.value = void 0;
    await updateData();
  }
  __name(create2, "create");
  async function save(_options = {}) {
    if (!isSupported.value)
      return;
    if (!fileHandle.value)
      return saveAs2(_options);
    if (data.value) {
      const writableStream = await fileHandle.value.createWritable();
      await writableStream.write(data.value);
      await writableStream.close();
    }
    await updateFile();
  }
  __name(save, "save");
  async function saveAs2(_options = {}) {
    if (!isSupported.value)
      return;
    fileHandle.value = await window2.showSaveFilePicker({ ...options2, ..._options });
    if (data.value) {
      const writableStream = await fileHandle.value.createWritable();
      await writableStream.write(data.value);
      await writableStream.close();
    }
    await updateFile();
  }
  __name(saveAs2, "saveAs");
  async function updateFile() {
    var _a2;
    file.value = await ((_a2 = fileHandle.value) == null ? void 0 : _a2.getFile());
  }
  __name(updateFile, "updateFile");
  async function updateData() {
    var _a2, _b;
    await updateFile();
    const type = toValue$3(dataType);
    if (type === "Text")
      data.value = await ((_a2 = file.value) == null ? void 0 : _a2.text());
    else if (type === "ArrayBuffer")
      data.value = await ((_b = file.value) == null ? void 0 : _b.arrayBuffer());
    else if (type === "Blob")
      data.value = file.value;
  }
  __name(updateData, "updateData");
  watch(() => toValue$3(dataType), updateData);
  return {
    isSupported,
    data,
    file,
    fileName,
    fileMIME,
    fileSize,
    fileLastModified,
    open: open2,
    create: create2,
    save,
    saveAs: saveAs2,
    updateData
  };
}
__name(useFileSystemAccess, "useFileSystemAccess");
function useFocus(target, options2 = {}) {
  const { initialValue = false, focusVisible = false, preventScroll = false } = options2;
  const innerFocused = ref$3(false);
  const targetElement = computed(() => unrefElement(target));
  useEventListener(targetElement, "focus", (event) => {
    var _a2, _b;
    if (!focusVisible || ((_b = (_a2 = event.target).matches) == null ? void 0 : _b.call(_a2, ":focus-visible")))
      innerFocused.value = true;
  });
  useEventListener(targetElement, "blur", () => innerFocused.value = false);
  const focused = computed({
    get: /* @__PURE__ */ __name(() => innerFocused.value, "get"),
    set(value) {
      var _a2, _b;
      if (!value && innerFocused.value)
        (_a2 = targetElement.value) == null ? void 0 : _a2.blur();
      else if (value && !innerFocused.value)
        (_b = targetElement.value) == null ? void 0 : _b.focus({ preventScroll });
    }
  });
  watch(
    targetElement,
    () => {
      focused.value = initialValue;
    },
    { immediate: true, flush: "post" }
  );
  return { focused };
}
__name(useFocus, "useFocus");
function useFocusWithin(target, options2 = {}) {
  const activeElement = useActiveElement(options2);
  const targetElement = computed(() => unrefElement(target));
  const focused = computed(() => targetElement.value && activeElement.value ? targetElement.value.contains(activeElement.value) : false);
  return { focused };
}
__name(useFocusWithin, "useFocusWithin");
function useFps(options2) {
  var _a2;
  const fps = ref$3(0);
  if (typeof performance === "undefined")
    return fps;
  const every = (_a2 = options2 == null ? void 0 : options2.every) != null ? _a2 : 10;
  let last = performance.now();
  let ticks = 0;
  useRafFn(() => {
    ticks += 1;
    if (ticks >= every) {
      const now2 = performance.now();
      const diff2 = now2 - last;
      fps.value = Math.round(1e3 / (diff2 / ticks));
      last = now2;
      ticks = 0;
    }
  });
  return fps;
}
__name(useFps, "useFps");
const eventHandlers = [
  "fullscreenchange",
  "webkitfullscreenchange",
  "webkitendfullscreen",
  "mozfullscreenchange",
  "MSFullscreenChange"
];
function useFullscreen(target, options2 = {}) {
  const {
    document: document2 = defaultDocument,
    autoExit = false
  } = options2;
  const targetRef = computed(() => {
    var _a2;
    return (_a2 = unrefElement(target)) != null ? _a2 : document2 == null ? void 0 : document2.querySelector("html");
  });
  const isFullscreen = ref$3(false);
  const requestMethod = computed(() => {
    return [
      "requestFullscreen",
      "webkitRequestFullscreen",
      "webkitEnterFullscreen",
      "webkitEnterFullScreen",
      "webkitRequestFullScreen",
      "mozRequestFullScreen",
      "msRequestFullscreen"
    ].find((m2) => document2 && m2 in document2 || targetRef.value && m2 in targetRef.value);
  });
  const exitMethod = computed(() => {
    return [
      "exitFullscreen",
      "webkitExitFullscreen",
      "webkitExitFullScreen",
      "webkitCancelFullScreen",
      "mozCancelFullScreen",
      "msExitFullscreen"
    ].find((m2) => document2 && m2 in document2 || targetRef.value && m2 in targetRef.value);
  });
  const fullscreenEnabled = computed(() => {
    return [
      "fullScreen",
      "webkitIsFullScreen",
      "webkitDisplayingFullscreen",
      "mozFullScreen",
      "msFullscreenElement"
    ].find((m2) => document2 && m2 in document2 || targetRef.value && m2 in targetRef.value);
  });
  const fullscreenElementMethod = [
    "fullscreenElement",
    "webkitFullscreenElement",
    "mozFullScreenElement",
    "msFullscreenElement"
  ].find((m2) => document2 && m2 in document2);
  const isSupported = useSupported(() => targetRef.value && document2 && requestMethod.value !== void 0 && exitMethod.value !== void 0 && fullscreenEnabled.value !== void 0);
  const isCurrentElementFullScreen = /* @__PURE__ */ __name(() => {
    if (fullscreenElementMethod)
      return (document2 == null ? void 0 : document2[fullscreenElementMethod]) === targetRef.value;
    return false;
  }, "isCurrentElementFullScreen");
  const isElementFullScreen = /* @__PURE__ */ __name(() => {
    if (fullscreenEnabled.value) {
      if (document2 && document2[fullscreenEnabled.value] != null) {
        return document2[fullscreenEnabled.value];
      } else {
        const target2 = targetRef.value;
        if ((target2 == null ? void 0 : target2[fullscreenEnabled.value]) != null) {
          return Boolean(target2[fullscreenEnabled.value]);
        }
      }
    }
    return false;
  }, "isElementFullScreen");
  async function exit() {
    if (!isSupported.value || !isFullscreen.value)
      return;
    if (exitMethod.value) {
      if ((document2 == null ? void 0 : document2[exitMethod.value]) != null) {
        await document2[exitMethod.value]();
      } else {
        const target2 = targetRef.value;
        if ((target2 == null ? void 0 : target2[exitMethod.value]) != null)
          await target2[exitMethod.value]();
      }
    }
    isFullscreen.value = false;
  }
  __name(exit, "exit");
  async function enter2() {
    if (!isSupported.value || isFullscreen.value)
      return;
    if (isElementFullScreen())
      await exit();
    const target2 = targetRef.value;
    if (requestMethod.value && (target2 == null ? void 0 : target2[requestMethod.value]) != null) {
      await target2[requestMethod.value]();
      isFullscreen.value = true;
    }
  }
  __name(enter2, "enter");
  async function toggle() {
    await (isFullscreen.value ? exit() : enter2());
  }
  __name(toggle, "toggle");
  const handlerCallback = /* @__PURE__ */ __name(() => {
    const isElementFullScreenValue = isElementFullScreen();
    if (!isElementFullScreenValue || isElementFullScreenValue && isCurrentElementFullScreen())
      isFullscreen.value = isElementFullScreenValue;
  }, "handlerCallback");
  useEventListener(document2, eventHandlers, handlerCallback, false);
  useEventListener(() => unrefElement(targetRef), eventHandlers, handlerCallback, false);
  if (autoExit)
    tryOnScopeDispose(exit);
  return {
    isSupported,
    isFullscreen,
    enter: enter2,
    exit,
    toggle
  };
}
__name(useFullscreen, "useFullscreen");
function mapGamepadToXbox360Controller(gamepad) {
  return computed(() => {
    if (gamepad.value) {
      return {
        buttons: {
          a: gamepad.value.buttons[0],
          b: gamepad.value.buttons[1],
          x: gamepad.value.buttons[2],
          y: gamepad.value.buttons[3]
        },
        bumper: {
          left: gamepad.value.buttons[4],
          right: gamepad.value.buttons[5]
        },
        triggers: {
          left: gamepad.value.buttons[6],
          right: gamepad.value.buttons[7]
        },
        stick: {
          left: {
            horizontal: gamepad.value.axes[0],
            vertical: gamepad.value.axes[1],
            button: gamepad.value.buttons[10]
          },
          right: {
            horizontal: gamepad.value.axes[2],
            vertical: gamepad.value.axes[3],
            button: gamepad.value.buttons[11]
          }
        },
        dpad: {
          up: gamepad.value.buttons[12],
          down: gamepad.value.buttons[13],
          left: gamepad.value.buttons[14],
          right: gamepad.value.buttons[15]
        },
        back: gamepad.value.buttons[8],
        start: gamepad.value.buttons[9]
      };
    }
    return null;
  });
}
__name(mapGamepadToXbox360Controller, "mapGamepadToXbox360Controller");
function useGamepad(options2 = {}) {
  const {
    navigator: navigator2 = defaultNavigator
  } = options2;
  const isSupported = useSupported(() => navigator2 && "getGamepads" in navigator2);
  const gamepads = ref$3([]);
  const onConnectedHook = createEventHook();
  const onDisconnectedHook = createEventHook();
  const stateFromGamepad = /* @__PURE__ */ __name((gamepad) => {
    const hapticActuators = [];
    const vibrationActuator = "vibrationActuator" in gamepad ? gamepad.vibrationActuator : null;
    if (vibrationActuator)
      hapticActuators.push(vibrationActuator);
    if (gamepad.hapticActuators)
      hapticActuators.push(...gamepad.hapticActuators);
    return {
      id: gamepad.id,
      index: gamepad.index,
      connected: gamepad.connected,
      mapping: gamepad.mapping,
      timestamp: gamepad.timestamp,
      vibrationActuator: gamepad.vibrationActuator,
      hapticActuators,
      axes: gamepad.axes.map((axes) => axes),
      buttons: gamepad.buttons.map((button) => ({ pressed: button.pressed, touched: button.touched, value: button.value }))
    };
  }, "stateFromGamepad");
  const updateGamepadState = /* @__PURE__ */ __name(() => {
    const _gamepads = (navigator2 == null ? void 0 : navigator2.getGamepads()) || [];
    for (const gamepad of _gamepads) {
      if (gamepad && gamepads.value[gamepad.index])
        gamepads.value[gamepad.index] = stateFromGamepad(gamepad);
    }
  }, "updateGamepadState");
  const { isActive: isActive2, pause, resume } = useRafFn(updateGamepadState);
  const onGamepadConnected = /* @__PURE__ */ __name((gamepad) => {
    if (!gamepads.value.some(({ index: index2 }) => index2 === gamepad.index)) {
      gamepads.value.push(stateFromGamepad(gamepad));
      onConnectedHook.trigger(gamepad.index);
    }
    resume();
  }, "onGamepadConnected");
  const onGamepadDisconnected = /* @__PURE__ */ __name((gamepad) => {
    gamepads.value = gamepads.value.filter((x2) => x2.index !== gamepad.index);
    onDisconnectedHook.trigger(gamepad.index);
  }, "onGamepadDisconnected");
  useEventListener("gamepadconnected", (e2) => onGamepadConnected(e2.gamepad));
  useEventListener("gamepaddisconnected", (e2) => onGamepadDisconnected(e2.gamepad));
  tryOnMounted$2(() => {
    const _gamepads = (navigator2 == null ? void 0 : navigator2.getGamepads()) || [];
    for (const gamepad of _gamepads) {
      if (gamepad && gamepads.value[gamepad.index])
        onGamepadConnected(gamepad);
    }
  });
  pause();
  return {
    isSupported,
    onConnected: onConnectedHook.on,
    onDisconnected: onDisconnectedHook.on,
    gamepads,
    pause,
    resume,
    isActive: isActive2
  };
}
__name(useGamepad, "useGamepad");
function useGeolocation(options2 = {}) {
  const {
    enableHighAccuracy = true,
    maximumAge = 3e4,
    timeout = 27e3,
    navigator: navigator2 = defaultNavigator,
    immediate = true
  } = options2;
  const isSupported = useSupported(() => navigator2 && "geolocation" in navigator2);
  const locatedAt = ref$3(null);
  const error2 = shallowRef(null);
  const coords = ref$3({
    accuracy: 0,
    latitude: Number.POSITIVE_INFINITY,
    longitude: Number.POSITIVE_INFINITY,
    altitude: null,
    altitudeAccuracy: null,
    heading: null,
    speed: null
  });
  function updatePosition(position) {
    locatedAt.value = position.timestamp;
    coords.value = position.coords;
    error2.value = null;
  }
  __name(updatePosition, "updatePosition");
  let watcher;
  function resume() {
    if (isSupported.value) {
      watcher = navigator2.geolocation.watchPosition(
        updatePosition,
        (err) => error2.value = err,
        {
          enableHighAccuracy,
          maximumAge,
          timeout
        }
      );
    }
  }
  __name(resume, "resume");
  if (immediate)
    resume();
  function pause() {
    if (watcher && navigator2)
      navigator2.geolocation.clearWatch(watcher);
  }
  __name(pause, "pause");
  tryOnScopeDispose(() => {
    pause();
  });
  return {
    isSupported,
    coords,
    locatedAt,
    error: error2,
    resume,
    pause
  };
}
__name(useGeolocation, "useGeolocation");
const defaultEvents$1 = ["mousemove", "mousedown", "resize", "keydown", "touchstart", "wheel"];
const oneMinute = 6e4;
function useIdle(timeout = oneMinute, options2 = {}) {
  const {
    initialState = false,
    listenForVisibilityChange = true,
    events: events2 = defaultEvents$1,
    window: window2 = defaultWindow,
    eventFilter = throttleFilter(50)
  } = options2;
  const idle = ref$3(initialState);
  const lastActive = ref$3(timestamp());
  let timer;
  const reset2 = /* @__PURE__ */ __name(() => {
    idle.value = false;
    clearTimeout(timer);
    timer = setTimeout(() => idle.value = true, timeout);
  }, "reset");
  const onEvent = createFilterWrapper(
    eventFilter,
    () => {
      lastActive.value = timestamp();
      reset2();
    }
  );
  if (window2) {
    const document2 = window2.document;
    for (const event of events2)
      useEventListener(window2, event, onEvent, { passive: true });
    if (listenForVisibilityChange) {
      useEventListener(document2, "visibilitychange", () => {
        if (!document2.hidden)
          onEvent();
      });
    }
    reset2();
  }
  return {
    idle,
    lastActive,
    reset: reset2
  };
}
__name(useIdle, "useIdle");
async function loadImage(options2) {
  return new Promise((resolve2, reject) => {
    const img = new Image();
    const { src, srcset, sizes, class: clazz, loading, crossorigin, referrerPolicy } = options2;
    img.src = src;
    if (srcset)
      img.srcset = srcset;
    if (sizes)
      img.sizes = sizes;
    if (clazz)
      img.className = clazz;
    if (loading)
      img.loading = loading;
    if (crossorigin)
      img.crossOrigin = crossorigin;
    if (referrerPolicy)
      img.referrerPolicy = referrerPolicy;
    img.onload = () => resolve2(img);
    img.onerror = reject;
  });
}
__name(loadImage, "loadImage");
function useImage(options2, asyncStateOptions = {}) {
  const state = useAsyncState(
    () => loadImage(toValue$3(options2)),
    void 0,
    {
      resetOnExecute: true,
      ...asyncStateOptions
    }
  );
  watch(
    () => toValue$3(options2),
    () => state.execute(asyncStateOptions.delay),
    { deep: true }
  );
  return state;
}
__name(useImage, "useImage");
const ARRIVED_STATE_THRESHOLD_PIXELS = 1;
function useScroll(element, options2 = {}) {
  const {
    throttle: throttle2 = 0,
    idle = 200,
    onStop = noop$2,
    onScroll = noop$2,
    offset = {
      left: 0,
      right: 0,
      top: 0,
      bottom: 0
    },
    eventListenerOptions = {
      capture: false,
      passive: true
    },
    behavior = "auto",
    window: window2 = defaultWindow,
    onError = /* @__PURE__ */ __name((e2) => {
      console.error(e2);
    }, "onError")
  } = options2;
  const internalX = ref$3(0);
  const internalY = ref$3(0);
  const x2 = computed({
    get() {
      return internalX.value;
    },
    set(x22) {
      scrollTo2(x22, void 0);
    }
  });
  const y2 = computed({
    get() {
      return internalY.value;
    },
    set(y22) {
      scrollTo2(void 0, y22);
    }
  });
  function scrollTo2(_x, _y) {
    var _a2, _b, _c, _d;
    if (!window2)
      return;
    const _element = toValue$3(element);
    if (!_element)
      return;
    (_c = _element instanceof Document ? window2.document.body : _element) == null ? void 0 : _c.scrollTo({
      top: (_a2 = toValue$3(_y)) != null ? _a2 : y2.value,
      left: (_b = toValue$3(_x)) != null ? _b : x2.value,
      behavior: toValue$3(behavior)
    });
    const scrollContainer = ((_d = _element == null ? void 0 : _element.document) == null ? void 0 : _d.documentElement) || (_element == null ? void 0 : _element.documentElement) || _element;
    if (x2 != null)
      internalX.value = scrollContainer.scrollLeft;
    if (y2 != null)
      internalY.value = scrollContainer.scrollTop;
  }
  __name(scrollTo2, "scrollTo2");
  const isScrolling = ref$3(false);
  const arrivedState = reactive({
    left: true,
    right: false,
    top: true,
    bottom: false
  });
  const directions = reactive({
    left: false,
    right: false,
    top: false,
    bottom: false
  });
  const onScrollEnd = /* @__PURE__ */ __name((e2) => {
    if (!isScrolling.value)
      return;
    isScrolling.value = false;
    directions.left = false;
    directions.right = false;
    directions.top = false;
    directions.bottom = false;
    onStop(e2);
  }, "onScrollEnd");
  const onScrollEndDebounced = useDebounceFn(onScrollEnd, throttle2 + idle);
  const setArrivedState = /* @__PURE__ */ __name((target) => {
    var _a2;
    if (!window2)
      return;
    const el = ((_a2 = target == null ? void 0 : target.document) == null ? void 0 : _a2.documentElement) || (target == null ? void 0 : target.documentElement) || unrefElement(target);
    const { display, flexDirection } = getComputedStyle(el);
    const scrollLeft = el.scrollLeft;
    directions.left = scrollLeft < internalX.value;
    directions.right = scrollLeft > internalX.value;
    const left = Math.abs(scrollLeft) <= (offset.left || 0);
    const right = Math.abs(scrollLeft) + el.clientWidth >= el.scrollWidth - (offset.right || 0) - ARRIVED_STATE_THRESHOLD_PIXELS;
    if (display === "flex" && flexDirection === "row-reverse") {
      arrivedState.left = right;
      arrivedState.right = left;
    } else {
      arrivedState.left = left;
      arrivedState.right = right;
    }
    internalX.value = scrollLeft;
    let scrollTop = el.scrollTop;
    if (target === window2.document && !scrollTop)
      scrollTop = window2.document.body.scrollTop;
    directions.top = scrollTop < internalY.value;
    directions.bottom = scrollTop > internalY.value;
    const top = Math.abs(scrollTop) <= (offset.top || 0);
    const bottom = Math.abs(scrollTop) + el.clientHeight >= el.scrollHeight - (offset.bottom || 0) - ARRIVED_STATE_THRESHOLD_PIXELS;
    if (display === "flex" && flexDirection === "column-reverse") {
      arrivedState.top = bottom;
      arrivedState.bottom = top;
    } else {
      arrivedState.top = top;
      arrivedState.bottom = bottom;
    }
    internalY.value = scrollTop;
  }, "setArrivedState");
  const onScrollHandler = /* @__PURE__ */ __name((e2) => {
    var _a2;
    if (!window2)
      return;
    const eventTarget = (_a2 = e2.target.documentElement) != null ? _a2 : e2.target;
    setArrivedState(eventTarget);
    isScrolling.value = true;
    onScrollEndDebounced(e2);
    onScroll(e2);
  }, "onScrollHandler");
  useEventListener(
    element,
    "scroll",
    throttle2 ? useThrottleFn(onScrollHandler, throttle2, true, false) : onScrollHandler,
    eventListenerOptions
  );
  tryOnMounted$2(() => {
    try {
      const _element = toValue$3(element);
      if (!_element)
        return;
      setArrivedState(_element);
    } catch (e2) {
      onError(e2);
    }
  });
  useEventListener(
    element,
    "scrollend",
    onScrollEnd,
    eventListenerOptions
  );
  return {
    x: x2,
    y: y2,
    isScrolling,
    arrivedState,
    directions,
    measure() {
      const _element = toValue$3(element);
      if (window2 && _element)
        setArrivedState(_element);
    }
  };
}
__name(useScroll, "useScroll");
function resolveElement(el) {
  if (typeof Window !== "undefined" && el instanceof Window)
    return el.document.documentElement;
  if (typeof Document !== "undefined" && el instanceof Document)
    return el.documentElement;
  return el;
}
__name(resolveElement, "resolveElement");
function useInfiniteScroll(element, onLoadMore, options2 = {}) {
  var _a2;
  const {
    direction = "bottom",
    interval = 100,
    canLoadMore = /* @__PURE__ */ __name(() => true, "canLoadMore")
  } = options2;
  const state = reactive(useScroll(
    element,
    {
      ...options2,
      offset: {
        [direction]: (_a2 = options2.distance) != null ? _a2 : 0,
        ...options2.offset
      }
    }
  ));
  const promise = ref$3();
  const isLoading = computed(() => !!promise.value);
  const observedElement = computed(() => {
    return resolveElement(toValue$3(element));
  });
  const isElementVisible = useElementVisibility(observedElement);
  function checkAndLoad() {
    state.measure();
    if (!observedElement.value || !isElementVisible.value || !canLoadMore(observedElement.value))
      return;
    const { scrollHeight, clientHeight, scrollWidth, clientWidth } = observedElement.value;
    const isNarrower = direction === "bottom" || direction === "top" ? scrollHeight <= clientHeight : scrollWidth <= clientWidth;
    if (state.arrivedState[direction] || isNarrower) {
      if (!promise.value) {
        promise.value = Promise.all([
          onLoadMore(state),
          new Promise((resolve2) => setTimeout(resolve2, interval))
        ]).finally(() => {
          promise.value = null;
          nextTick(() => checkAndLoad());
        });
      }
    }
  }
  __name(checkAndLoad, "checkAndLoad");
  watch(
    () => [state.arrivedState[direction], isElementVisible.value],
    checkAndLoad,
    { immediate: true }
  );
  return {
    isLoading,
    reset() {
      nextTick(() => checkAndLoad());
    }
  };
}
__name(useInfiniteScroll, "useInfiniteScroll");
const defaultEvents = ["mousedown", "mouseup", "keydown", "keyup"];
function useKeyModifier(modifier, options2 = {}) {
  const {
    events: events2 = defaultEvents,
    document: document2 = defaultDocument,
    initial = null
  } = options2;
  const state = ref$3(initial);
  if (document2) {
    events2.forEach((listenerEvent) => {
      useEventListener(document2, listenerEvent, (evt) => {
        if (typeof evt.getModifierState === "function")
          state.value = evt.getModifierState(modifier);
      });
    });
  }
  return state;
}
__name(useKeyModifier, "useKeyModifier");
function useLocalStorage(key, initialValue, options2 = {}) {
  const { window: window2 = defaultWindow } = options2;
  return useStorage(key, initialValue, window2 == null ? void 0 : window2.localStorage, options2);
}
__name(useLocalStorage, "useLocalStorage");
const DefaultMagicKeysAliasMap = {
  ctrl: "control",
  command: "meta",
  cmd: "meta",
  option: "alt",
  up: "arrowup",
  down: "arrowdown",
  left: "arrowleft",
  right: "arrowright"
};
function useMagicKeys(options2 = {}) {
  const {
    reactive: useReactive = false,
    target = defaultWindow,
    aliasMap = DefaultMagicKeysAliasMap,
    passive = true,
    onEventFired = noop$2
  } = options2;
  const current = reactive(/* @__PURE__ */ new Set());
  const obj = {
    toJSON() {
      return {};
    },
    current
  };
  const refs = useReactive ? reactive(obj) : obj;
  const metaDeps = /* @__PURE__ */ new Set();
  const usedKeys = /* @__PURE__ */ new Set();
  function setRefs(key, value) {
    if (key in refs) {
      if (useReactive)
        refs[key] = value;
      else
        refs[key].value = value;
    }
  }
  __name(setRefs, "setRefs");
  function reset2() {
    current.clear();
    for (const key of usedKeys)
      setRefs(key, false);
  }
  __name(reset2, "reset");
  function updateRefs(e2, value) {
    var _a2, _b;
    const key = (_a2 = e2.key) == null ? void 0 : _a2.toLowerCase();
    const code2 = (_b = e2.code) == null ? void 0 : _b.toLowerCase();
    const values = [code2, key].filter(Boolean);
    if (key) {
      if (value)
        current.add(key);
      else
        current.delete(key);
    }
    for (const key2 of values) {
      usedKeys.add(key2);
      setRefs(key2, value);
    }
    if (key === "meta" && !value) {
      metaDeps.forEach((key2) => {
        current.delete(key2);
        setRefs(key2, false);
      });
      metaDeps.clear();
    } else if (typeof e2.getModifierState === "function" && e2.getModifierState("Meta") && value) {
      [...current, ...values].forEach((key2) => metaDeps.add(key2));
    }
  }
  __name(updateRefs, "updateRefs");
  useEventListener(target, "keydown", (e2) => {
    updateRefs(e2, true);
    return onEventFired(e2);
  }, { passive });
  useEventListener(target, "keyup", (e2) => {
    updateRefs(e2, false);
    return onEventFired(e2);
  }, { passive });
  useEventListener("blur", reset2, { passive: true });
  useEventListener("focus", reset2, { passive: true });
  const proxy = new Proxy(
    refs,
    {
      get(target2, prop2, rec) {
        if (typeof prop2 !== "string")
          return Reflect.get(target2, prop2, rec);
        prop2 = prop2.toLowerCase();
        if (prop2 in aliasMap)
          prop2 = aliasMap[prop2];
        if (!(prop2 in refs)) {
          if (/[+_-]/.test(prop2)) {
            const keys2 = prop2.split(/[+_-]/g).map((i2) => i2.trim());
            refs[prop2] = computed(() => keys2.every((key) => toValue$3(proxy[key])));
          } else {
            refs[prop2] = ref$3(false);
          }
        }
        const r2 = Reflect.get(target2, prop2, rec);
        return useReactive ? toValue$3(r2) : r2;
      }
    }
  );
  return proxy;
}
__name(useMagicKeys, "useMagicKeys");
function usingElRef(source, cb) {
  if (toValue$3(source))
    cb(toValue$3(source));
}
__name(usingElRef, "usingElRef");
function timeRangeToArray(timeRanges) {
  let ranges = [];
  for (let i2 = 0; i2 < timeRanges.length; ++i2)
    ranges = [...ranges, [timeRanges.start(i2), timeRanges.end(i2)]];
  return ranges;
}
__name(timeRangeToArray, "timeRangeToArray");
function tracksToArray(tracks) {
  return Array.from(tracks).map(({ label, kind, language, mode, activeCues, cues, inBandMetadataTrackDispatchType }, id2) => ({ id: id2, label, kind, language, mode, activeCues, cues, inBandMetadataTrackDispatchType }));
}
__name(tracksToArray, "tracksToArray");
const defaultOptions$1 = {
  src: "",
  tracks: []
};
function useMediaControls(target, options2 = {}) {
  target = toRef(target);
  options2 = {
    ...defaultOptions$1,
    ...options2
  };
  const {
    document: document2 = defaultDocument
  } = options2;
  const currentTime = ref$3(0);
  const duration = ref$3(0);
  const seeking = ref$3(false);
  const volume = ref$3(1);
  const waiting = ref$3(false);
  const ended = ref$3(false);
  const playing = ref$3(false);
  const rate = ref$3(1);
  const stalled = ref$3(false);
  const buffered = ref$3([]);
  const tracks = ref$3([]);
  const selectedTrack = ref$3(-1);
  const isPictureInPicture = ref$3(false);
  const muted = ref$3(false);
  const supportsPictureInPicture = document2 && "pictureInPictureEnabled" in document2;
  const sourceErrorEvent = createEventHook();
  const disableTrack = /* @__PURE__ */ __name((track) => {
    usingElRef(target, (el) => {
      if (track) {
        const id2 = typeof track === "number" ? track : track.id;
        el.textTracks[id2].mode = "disabled";
      } else {
        for (let i2 = 0; i2 < el.textTracks.length; ++i2)
          el.textTracks[i2].mode = "disabled";
      }
      selectedTrack.value = -1;
    });
  }, "disableTrack");
  const enableTrack = /* @__PURE__ */ __name((track, disableTracks = true) => {
    usingElRef(target, (el) => {
      const id2 = typeof track === "number" ? track : track.id;
      if (disableTracks)
        disableTrack();
      el.textTracks[id2].mode = "showing";
      selectedTrack.value = id2;
    });
  }, "enableTrack");
  const togglePictureInPicture = /* @__PURE__ */ __name(() => {
    return new Promise((resolve2, reject) => {
      usingElRef(target, async (el) => {
        if (supportsPictureInPicture) {
          if (!isPictureInPicture.value) {
            el.requestPictureInPicture().then(resolve2).catch(reject);
          } else {
            document2.exitPictureInPicture().then(resolve2).catch(reject);
          }
        }
      });
    });
  }, "togglePictureInPicture");
  watchEffect(() => {
    if (!document2)
      return;
    const el = toValue$3(target);
    if (!el)
      return;
    const src = toValue$3(options2.src);
    let sources = [];
    if (!src)
      return;
    if (typeof src === "string")
      sources = [{ src }];
    else if (Array.isArray(src))
      sources = src;
    else if (isObject$c(src))
      sources = [src];
    el.querySelectorAll("source").forEach((e2) => {
      e2.removeEventListener("error", sourceErrorEvent.trigger);
      e2.remove();
    });
    sources.forEach(({ src: src2, type }) => {
      const source = document2.createElement("source");
      source.setAttribute("src", src2);
      source.setAttribute("type", type || "");
      source.addEventListener("error", sourceErrorEvent.trigger);
      el.appendChild(source);
    });
    el.load();
  });
  tryOnScopeDispose(() => {
    const el = toValue$3(target);
    if (!el)
      return;
    el.querySelectorAll("source").forEach((e2) => e2.removeEventListener("error", sourceErrorEvent.trigger));
  });
  watch([target, volume], () => {
    const el = toValue$3(target);
    if (!el)
      return;
    el.volume = volume.value;
  });
  watch([target, muted], () => {
    const el = toValue$3(target);
    if (!el)
      return;
    el.muted = muted.value;
  });
  watch([target, rate], () => {
    const el = toValue$3(target);
    if (!el)
      return;
    el.playbackRate = rate.value;
  });
  watchEffect(() => {
    if (!document2)
      return;
    const textTracks = toValue$3(options2.tracks);
    const el = toValue$3(target);
    if (!textTracks || !textTracks.length || !el)
      return;
    el.querySelectorAll("track").forEach((e2) => e2.remove());
    textTracks.forEach(({ default: isDefault, kind, label, src, srcLang }, i2) => {
      const track = document2.createElement("track");
      track.default = isDefault || false;
      track.kind = kind;
      track.label = label;
      track.src = src;
      track.srclang = srcLang;
      if (track.default)
        selectedTrack.value = i2;
      el.appendChild(track);
    });
  });
  const { ignoreUpdates: ignoreCurrentTimeUpdates } = watchIgnorable(currentTime, (time) => {
    const el = toValue$3(target);
    if (!el)
      return;
    el.currentTime = time;
  });
  const { ignoreUpdates: ignorePlayingUpdates } = watchIgnorable(playing, (isPlaying) => {
    const el = toValue$3(target);
    if (!el)
      return;
    if (isPlaying)
      el.play();
    else
      el.pause();
  });
  useEventListener(target, "timeupdate", () => ignoreCurrentTimeUpdates(() => currentTime.value = toValue$3(target).currentTime));
  useEventListener(target, "durationchange", () => duration.value = toValue$3(target).duration);
  useEventListener(target, "progress", () => buffered.value = timeRangeToArray(toValue$3(target).buffered));
  useEventListener(target, "seeking", () => seeking.value = true);
  useEventListener(target, "seeked", () => seeking.value = false);
  useEventListener(target, ["waiting", "loadstart"], () => {
    waiting.value = true;
    ignorePlayingUpdates(() => playing.value = false);
  });
  useEventListener(target, "loadeddata", () => waiting.value = false);
  useEventListener(target, "playing", () => {
    waiting.value = false;
    ended.value = false;
    ignorePlayingUpdates(() => playing.value = true);
  });
  useEventListener(target, "ratechange", () => rate.value = toValue$3(target).playbackRate);
  useEventListener(target, "stalled", () => stalled.value = true);
  useEventListener(target, "ended", () => ended.value = true);
  useEventListener(target, "pause", () => ignorePlayingUpdates(() => playing.value = false));
  useEventListener(target, "play", () => ignorePlayingUpdates(() => playing.value = true));
  useEventListener(target, "enterpictureinpicture", () => isPictureInPicture.value = true);
  useEventListener(target, "leavepictureinpicture", () => isPictureInPicture.value = false);
  useEventListener(target, "volumechange", () => {
    const el = toValue$3(target);
    if (!el)
      return;
    volume.value = el.volume;
    muted.value = el.muted;
  });
  const listeners = [];
  const stop2 = watch([target], () => {
    const el = toValue$3(target);
    if (!el)
      return;
    stop2();
    listeners[0] = useEventListener(el.textTracks, "addtrack", () => tracks.value = tracksToArray(el.textTracks));
    listeners[1] = useEventListener(el.textTracks, "removetrack", () => tracks.value = tracksToArray(el.textTracks));
    listeners[2] = useEventListener(el.textTracks, "change", () => tracks.value = tracksToArray(el.textTracks));
  });
  tryOnScopeDispose(() => listeners.forEach((listener) => listener()));
  return {
    currentTime,
    duration,
    waiting,
    seeking,
    ended,
    stalled,
    buffered,
    playing,
    rate,
    // Volume
    volume,
    muted,
    // Tracks
    tracks,
    selectedTrack,
    enableTrack,
    disableTrack,
    // Picture in Picture
    supportsPictureInPicture,
    togglePictureInPicture,
    isPictureInPicture,
    // Events
    onSourceError: sourceErrorEvent.on
  };
}
__name(useMediaControls, "useMediaControls");
function getMapVue2Compat() {
  const data = shallowReactive({});
  return {
    get: /* @__PURE__ */ __name((key) => data[key], "get"),
    set: /* @__PURE__ */ __name((key, value) => set$2(data, key, value), "set"),
    has: /* @__PURE__ */ __name((key) => hasOwn$1(data, key), "has"),
    delete: /* @__PURE__ */ __name((key) => del$1(data, key), "delete"),
    clear: /* @__PURE__ */ __name(() => {
      Object.keys(data).forEach((key) => {
        del$1(data, key);
      });
    }, "clear")
  };
}
__name(getMapVue2Compat, "getMapVue2Compat");
function useMemoize(resolver, options2) {
  const initCache = /* @__PURE__ */ __name(() => {
    if (options2 == null ? void 0 : options2.cache)
      return shallowReactive(options2.cache);
    if (isVue2)
      return getMapVue2Compat();
    return shallowReactive(/* @__PURE__ */ new Map());
  }, "initCache");
  const cache = initCache();
  const generateKey = /* @__PURE__ */ __name((...args) => (options2 == null ? void 0 : options2.getKey) ? options2.getKey(...args) : JSON.stringify(args), "generateKey");
  const _loadData = /* @__PURE__ */ __name((key, ...args) => {
    cache.set(key, resolver(...args));
    return cache.get(key);
  }, "_loadData");
  const loadData = /* @__PURE__ */ __name((...args) => _loadData(generateKey(...args), ...args), "loadData");
  const deleteData = /* @__PURE__ */ __name((...args) => {
    cache.delete(generateKey(...args));
  }, "deleteData");
  const clearData = /* @__PURE__ */ __name(() => {
    cache.clear();
  }, "clearData");
  const memoized = /* @__PURE__ */ __name((...args) => {
    const key = generateKey(...args);
    if (cache.has(key))
      return cache.get(key);
    return _loadData(key, ...args);
  }, "memoized");
  memoized.load = loadData;
  memoized.delete = deleteData;
  memoized.clear = clearData;
  memoized.generateKey = generateKey;
  memoized.cache = cache;
  return memoized;
}
__name(useMemoize, "useMemoize");
function useMemory(options2 = {}) {
  const memory = ref$3();
  const isSupported = useSupported(() => typeof performance !== "undefined" && "memory" in performance);
  if (isSupported.value) {
    const { interval = 1e3 } = options2;
    useIntervalFn(() => {
      memory.value = performance.memory;
    }, interval, { immediate: options2.immediate, immediateCallback: options2.immediateCallback });
  }
  return { isSupported, memory };
}
__name(useMemory, "useMemory");
const UseMouseBuiltinExtractors = {
  page: /* @__PURE__ */ __name((event) => [event.pageX, event.pageY], "page"),
  client: /* @__PURE__ */ __name((event) => [event.clientX, event.clientY], "client"),
  screen: /* @__PURE__ */ __name((event) => [event.screenX, event.screenY], "screen"),
  movement: /* @__PURE__ */ __name((event) => event instanceof Touch ? null : [event.movementX, event.movementY], "movement")
};
function useMouse(options2 = {}) {
  const {
    type = "page",
    touch = true,
    resetOnTouchEnds = false,
    initialValue = { x: 0, y: 0 },
    window: window2 = defaultWindow,
    target = window2,
    scroll = true,
    eventFilter
  } = options2;
  let _prevMouseEvent = null;
  const x2 = ref$3(initialValue.x);
  const y2 = ref$3(initialValue.y);
  const sourceType = ref$3(null);
  const extractor = typeof type === "function" ? type : UseMouseBuiltinExtractors[type];
  const mouseHandler = /* @__PURE__ */ __name((event) => {
    const result = extractor(event);
    _prevMouseEvent = event;
    if (result) {
      [x2.value, y2.value] = result;
      sourceType.value = "mouse";
    }
  }, "mouseHandler");
  const touchHandler = /* @__PURE__ */ __name((event) => {
    if (event.touches.length > 0) {
      const result = extractor(event.touches[0]);
      if (result) {
        [x2.value, y2.value] = result;
        sourceType.value = "touch";
      }
    }
  }, "touchHandler");
  const scrollHandler = /* @__PURE__ */ __name(() => {
    if (!_prevMouseEvent || !window2)
      return;
    const pos = extractor(_prevMouseEvent);
    if (_prevMouseEvent instanceof MouseEvent && pos) {
      x2.value = pos[0] + window2.scrollX;
      y2.value = pos[1] + window2.scrollY;
    }
  }, "scrollHandler");
  const reset2 = /* @__PURE__ */ __name(() => {
    x2.value = initialValue.x;
    y2.value = initialValue.y;
  }, "reset");
  const mouseHandlerWrapper = eventFilter ? (event) => eventFilter(() => mouseHandler(event), {}) : (event) => mouseHandler(event);
  const touchHandlerWrapper = eventFilter ? (event) => eventFilter(() => touchHandler(event), {}) : (event) => touchHandler(event);
  const scrollHandlerWrapper = eventFilter ? () => eventFilter(() => scrollHandler(), {}) : () => scrollHandler();
  if (target) {
    const listenerOptions = { passive: true };
    useEventListener(target, ["mousemove", "dragover"], mouseHandlerWrapper, listenerOptions);
    if (touch && type !== "movement") {
      useEventListener(target, ["touchstart", "touchmove"], touchHandlerWrapper, listenerOptions);
      if (resetOnTouchEnds)
        useEventListener(target, "touchend", reset2, listenerOptions);
    }
    if (scroll && type === "page")
      useEventListener(window2, "scroll", scrollHandlerWrapper, { passive: true });
  }
  return {
    x: x2,
    y: y2,
    sourceType
  };
}
__name(useMouse, "useMouse");
function useMouseInElement(target, options2 = {}) {
  const {
    handleOutside = true,
    window: window2 = defaultWindow
  } = options2;
  const type = options2.type || "page";
  const { x: x2, y: y2, sourceType } = useMouse(options2);
  const targetRef = ref$3(target != null ? target : window2 == null ? void 0 : window2.document.body);
  const elementX = ref$3(0);
  const elementY = ref$3(0);
  const elementPositionX = ref$3(0);
  const elementPositionY = ref$3(0);
  const elementHeight = ref$3(0);
  const elementWidth = ref$3(0);
  const isOutside = ref$3(true);
  let stop2 = /* @__PURE__ */ __name(() => {
  }, "stop");
  if (window2) {
    stop2 = watch(
      [targetRef, x2, y2],
      () => {
        const el = unrefElement(targetRef);
        if (!el || !(el instanceof HTMLElement))
          return;
        const {
          left,
          top,
          width: width2,
          height
        } = el.getBoundingClientRect();
        elementPositionX.value = left + (type === "page" ? window2.pageXOffset : 0);
        elementPositionY.value = top + (type === "page" ? window2.pageYOffset : 0);
        elementHeight.value = height;
        elementWidth.value = width2;
        const elX = x2.value - elementPositionX.value;
        const elY = y2.value - elementPositionY.value;
        isOutside.value = width2 === 0 || height === 0 || elX < 0 || elY < 0 || elX > width2 || elY > height;
        if (handleOutside || !isOutside.value) {
          elementX.value = elX;
          elementY.value = elY;
        }
      },
      { immediate: true }
    );
    useEventListener(document, "mouseleave", () => {
      isOutside.value = true;
    });
  }
  return {
    x: x2,
    y: y2,
    sourceType,
    elementX,
    elementY,
    elementPositionX,
    elementPositionY,
    elementHeight,
    elementWidth,
    isOutside,
    stop: stop2
  };
}
__name(useMouseInElement, "useMouseInElement");
function useMousePressed(options2 = {}) {
  const {
    touch = true,
    drag = true,
    capture = false,
    initialValue = false,
    window: window2 = defaultWindow
  } = options2;
  const pressed = ref$3(initialValue);
  const sourceType = ref$3(null);
  if (!window2) {
    return {
      pressed,
      sourceType
    };
  }
  const onPressed = /* @__PURE__ */ __name((srcType) => () => {
    pressed.value = true;
    sourceType.value = srcType;
  }, "onPressed");
  const onReleased = /* @__PURE__ */ __name(() => {
    pressed.value = false;
    sourceType.value = null;
  }, "onReleased");
  const target = computed(() => unrefElement(options2.target) || window2);
  useEventListener(target, "mousedown", onPressed("mouse"), { passive: true, capture });
  useEventListener(window2, "mouseleave", onReleased, { passive: true, capture });
  useEventListener(window2, "mouseup", onReleased, { passive: true, capture });
  if (drag) {
    useEventListener(target, "dragstart", onPressed("mouse"), { passive: true, capture });
    useEventListener(window2, "drop", onReleased, { passive: true, capture });
    useEventListener(window2, "dragend", onReleased, { passive: true, capture });
  }
  if (touch) {
    useEventListener(target, "touchstart", onPressed("touch"), { passive: true, capture });
    useEventListener(window2, "touchend", onReleased, { passive: true, capture });
    useEventListener(window2, "touchcancel", onReleased, { passive: true, capture });
  }
  return {
    pressed,
    sourceType
  };
}
__name(useMousePressed, "useMousePressed");
function useNavigatorLanguage(options2 = {}) {
  const { window: window2 = defaultWindow } = options2;
  const navigator2 = window2 == null ? void 0 : window2.navigator;
  const isSupported = useSupported(() => navigator2 && "language" in navigator2);
  const language = ref$3(navigator2 == null ? void 0 : navigator2.language);
  useEventListener(window2, "languagechange", () => {
    if (navigator2)
      language.value = navigator2.language;
  });
  return {
    isSupported,
    language
  };
}
__name(useNavigatorLanguage, "useNavigatorLanguage");
function useNetwork(options2 = {}) {
  const { window: window2 = defaultWindow } = options2;
  const navigator2 = window2 == null ? void 0 : window2.navigator;
  const isSupported = useSupported(() => navigator2 && "connection" in navigator2);
  const isOnline = ref$3(true);
  const saveData = ref$3(false);
  const offlineAt = ref$3(void 0);
  const onlineAt = ref$3(void 0);
  const downlink = ref$3(void 0);
  const downlinkMax = ref$3(void 0);
  const rtt = ref$3(void 0);
  const effectiveType = ref$3(void 0);
  const type = ref$3("unknown");
  const connection = isSupported.value && navigator2.connection;
  function updateNetworkInformation() {
    if (!navigator2)
      return;
    isOnline.value = navigator2.onLine;
    offlineAt.value = isOnline.value ? void 0 : Date.now();
    onlineAt.value = isOnline.value ? Date.now() : void 0;
    if (connection) {
      downlink.value = connection.downlink;
      downlinkMax.value = connection.downlinkMax;
      effectiveType.value = connection.effectiveType;
      rtt.value = connection.rtt;
      saveData.value = connection.saveData;
      type.value = connection.type;
    }
  }
  __name(updateNetworkInformation, "updateNetworkInformation");
  if (window2) {
    useEventListener(window2, "offline", () => {
      isOnline.value = false;
      offlineAt.value = Date.now();
    });
    useEventListener(window2, "online", () => {
      isOnline.value = true;
      onlineAt.value = Date.now();
    });
  }
  if (connection)
    useEventListener(connection, "change", updateNetworkInformation, false);
  updateNetworkInformation();
  return {
    isSupported,
    isOnline,
    saveData,
    offlineAt,
    onlineAt,
    downlink,
    downlinkMax,
    effectiveType,
    rtt,
    type
  };
}
__name(useNetwork, "useNetwork");
function useNow(options2 = {}) {
  const {
    controls: exposeControls = false,
    interval = "requestAnimationFrame"
  } = options2;
  const now2 = ref$3(/* @__PURE__ */ new Date());
  const update2 = /* @__PURE__ */ __name(() => now2.value = /* @__PURE__ */ new Date(), "update");
  const controls = interval === "requestAnimationFrame" ? useRafFn(update2, { immediate: true }) : useIntervalFn(update2, interval, { immediate: true });
  if (exposeControls) {
    return {
      now: now2,
      ...controls
    };
  } else {
    return now2;
  }
}
__name(useNow, "useNow");
function useObjectUrl(object) {
  const url = ref$3();
  const release = /* @__PURE__ */ __name(() => {
    if (url.value)
      URL.revokeObjectURL(url.value);
    url.value = void 0;
  }, "release");
  watch(
    () => toValue$3(object),
    (newObject) => {
      release();
      if (newObject)
        url.value = URL.createObjectURL(newObject);
    },
    { immediate: true }
  );
  tryOnScopeDispose(release);
  return readonly(url);
}
__name(useObjectUrl, "useObjectUrl");
function useClamp(value, min, max) {
  if (typeof value === "function" || isReadonly(value))
    return computed(() => clamp$1(toValue$3(value), toValue$3(min), toValue$3(max)));
  const _value = ref$3(value);
  return computed({
    get() {
      return _value.value = clamp$1(_value.value, toValue$3(min), toValue$3(max));
    },
    set(value2) {
      _value.value = clamp$1(value2, toValue$3(min), toValue$3(max));
    }
  });
}
__name(useClamp, "useClamp");
function useOffsetPagination(options2) {
  const {
    total = Number.POSITIVE_INFINITY,
    pageSize = 10,
    page = 1,
    onPageChange = noop$2,
    onPageSizeChange = noop$2,
    onPageCountChange = noop$2
  } = options2;
  const currentPageSize = useClamp(pageSize, 1, Number.POSITIVE_INFINITY);
  const pageCount = computed(() => Math.max(
    1,
    Math.ceil(toValue$3(total) / toValue$3(currentPageSize))
  ));
  const currentPage = useClamp(page, 1, pageCount);
  const isFirstPage = computed(() => currentPage.value === 1);
  const isLastPage = computed(() => currentPage.value === pageCount.value);
  if (isRef(page)) {
    syncRef(page, currentPage, {
      direction: isReadonly(page) ? "ltr" : "both"
    });
  }
  if (isRef(pageSize)) {
    syncRef(pageSize, currentPageSize, {
      direction: isReadonly(pageSize) ? "ltr" : "both"
    });
  }
  function prev() {
    currentPage.value--;
  }
  __name(prev, "prev");
  function next() {
    currentPage.value++;
  }
  __name(next, "next");
  const returnValue = {
    currentPage,
    currentPageSize,
    pageCount,
    isFirstPage,
    isLastPage,
    prev,
    next
  };
  watch(currentPage, () => {
    onPageChange(reactive(returnValue));
  });
  watch(currentPageSize, () => {
    onPageSizeChange(reactive(returnValue));
  });
  watch(pageCount, () => {
    onPageCountChange(reactive(returnValue));
  });
  return returnValue;
}
__name(useOffsetPagination, "useOffsetPagination");
function useOnline(options2 = {}) {
  const { isOnline } = useNetwork(options2);
  return isOnline;
}
__name(useOnline, "useOnline");
function usePageLeave(options2 = {}) {
  const { window: window2 = defaultWindow } = options2;
  const isLeft = ref$3(false);
  const handler5 = /* @__PURE__ */ __name((event) => {
    if (!window2)
      return;
    event = event || window2.event;
    const from2 = event.relatedTarget || event.toElement;
    isLeft.value = !from2;
  }, "handler");
  if (window2) {
    useEventListener(window2, "mouseout", handler5, { passive: true });
    useEventListener(window2.document, "mouseleave", handler5, { passive: true });
    useEventListener(window2.document, "mouseenter", handler5, { passive: true });
  }
  return isLeft;
}
__name(usePageLeave, "usePageLeave");
function useScreenOrientation(options2 = {}) {
  const {
    window: window2 = defaultWindow
  } = options2;
  const isSupported = useSupported(() => window2 && "screen" in window2 && "orientation" in window2.screen);
  const screenOrientation = isSupported.value ? window2.screen.orientation : {};
  const orientation = ref$3(screenOrientation.type);
  const angle = ref$3(screenOrientation.angle || 0);
  if (isSupported.value) {
    useEventListener(window2, "orientationchange", () => {
      orientation.value = screenOrientation.type;
      angle.value = screenOrientation.angle;
    });
  }
  const lockOrientation = /* @__PURE__ */ __name((type) => {
    if (isSupported.value && typeof screenOrientation.lock === "function")
      return screenOrientation.lock(type);
    return Promise.reject(new Error("Not supported"));
  }, "lockOrientation");
  const unlockOrientation = /* @__PURE__ */ __name(() => {
    if (isSupported.value && typeof screenOrientation.unlock === "function")
      screenOrientation.unlock();
  }, "unlockOrientation");
  return {
    isSupported,
    orientation,
    angle,
    lockOrientation,
    unlockOrientation
  };
}
__name(useScreenOrientation, "useScreenOrientation");
function useParallax(target, options2 = {}) {
  const {
    deviceOrientationTiltAdjust = /* @__PURE__ */ __name((i2) => i2, "deviceOrientationTiltAdjust"),
    deviceOrientationRollAdjust = /* @__PURE__ */ __name((i2) => i2, "deviceOrientationRollAdjust"),
    mouseTiltAdjust = /* @__PURE__ */ __name((i2) => i2, "mouseTiltAdjust"),
    mouseRollAdjust = /* @__PURE__ */ __name((i2) => i2, "mouseRollAdjust"),
    window: window2 = defaultWindow
  } = options2;
  const orientation = reactive(useDeviceOrientation({ window: window2 }));
  const screenOrientation = reactive(useScreenOrientation({ window: window2 }));
  const {
    elementX: x2,
    elementY: y2,
    elementWidth: width2,
    elementHeight: height
  } = useMouseInElement(target, { handleOutside: false, window: window2 });
  const source = computed(() => {
    if (orientation.isSupported && (orientation.alpha != null && orientation.alpha !== 0 || orientation.gamma != null && orientation.gamma !== 0)) {
      return "deviceOrientation";
    }
    return "mouse";
  });
  const roll = computed(() => {
    if (source.value === "deviceOrientation") {
      let value;
      switch (screenOrientation.orientation) {
        case "landscape-primary":
          value = orientation.gamma / 90;
          break;
        case "landscape-secondary":
          value = -orientation.gamma / 90;
          break;
        case "portrait-primary":
          value = -orientation.beta / 90;
          break;
        case "portrait-secondary":
          value = orientation.beta / 90;
          break;
        default:
          value = -orientation.beta / 90;
      }
      return deviceOrientationRollAdjust(value);
    } else {
      const value = -(y2.value - height.value / 2) / height.value;
      return mouseRollAdjust(value);
    }
  });
  const tilt = computed(() => {
    if (source.value === "deviceOrientation") {
      let value;
      switch (screenOrientation.orientation) {
        case "landscape-primary":
          value = orientation.beta / 90;
          break;
        case "landscape-secondary":
          value = -orientation.beta / 90;
          break;
        case "portrait-primary":
          value = orientation.gamma / 90;
          break;
        case "portrait-secondary":
          value = -orientation.gamma / 90;
          break;
        default:
          value = orientation.gamma / 90;
      }
      return deviceOrientationTiltAdjust(value);
    } else {
      const value = (x2.value - width2.value / 2) / width2.value;
      return mouseTiltAdjust(value);
    }
  });
  return { roll, tilt, source };
}
__name(useParallax, "useParallax");
function useParentElement(element = useCurrentElement()) {
  const parentElement = shallowRef();
  const update2 = /* @__PURE__ */ __name(() => {
    const el = unrefElement(element);
    if (el)
      parentElement.value = el.parentElement;
  }, "update");
  tryOnMounted$2(update2);
  watch(() => toValue$3(element), update2);
  return parentElement;
}
__name(useParentElement, "useParentElement");
function usePerformanceObserver(options2, callback) {
  const {
    window: window2 = defaultWindow,
    immediate = true,
    ...performanceOptions
  } = options2;
  const isSupported = useSupported(() => window2 && "PerformanceObserver" in window2);
  let observer;
  const stop2 = /* @__PURE__ */ __name(() => {
    observer == null ? void 0 : observer.disconnect();
  }, "stop");
  const start2 = /* @__PURE__ */ __name(() => {
    if (isSupported.value) {
      stop2();
      observer = new PerformanceObserver(callback);
      observer.observe(performanceOptions);
    }
  }, "start");
  tryOnScopeDispose(stop2);
  if (immediate)
    start2();
  return {
    isSupported,
    start: start2,
    stop: stop2
  };
}
__name(usePerformanceObserver, "usePerformanceObserver");
const defaultState = {
  x: 0,
  y: 0,
  pointerId: 0,
  pressure: 0,
  tiltX: 0,
  tiltY: 0,
  width: 0,
  height: 0,
  twist: 0,
  pointerType: null
};
const keys$6 = /* @__PURE__ */ Object.keys(defaultState);
function usePointer(options2 = {}) {
  const {
    target = defaultWindow
  } = options2;
  const isInside = ref$3(false);
  const state = ref$3(options2.initialValue || {});
  Object.assign(state.value, defaultState, state.value);
  const handler5 = /* @__PURE__ */ __name((event) => {
    isInside.value = true;
    if (options2.pointerTypes && !options2.pointerTypes.includes(event.pointerType))
      return;
    state.value = objectPick(event, keys$6, false);
  }, "handler");
  if (target) {
    const listenerOptions = { passive: true };
    useEventListener(target, ["pointerdown", "pointermove", "pointerup"], handler5, listenerOptions);
    useEventListener(target, "pointerleave", () => isInside.value = false, listenerOptions);
  }
  return {
    ...toRefs(state),
    isInside
  };
}
__name(usePointer, "usePointer");
function usePointerLock(target, options2 = {}) {
  const { document: document2 = defaultDocument } = options2;
  const isSupported = useSupported(() => document2 && "pointerLockElement" in document2);
  const element = ref$3();
  const triggerElement = ref$3();
  let targetElement;
  if (isSupported.value) {
    useEventListener(document2, "pointerlockchange", () => {
      var _a2;
      const currentElement = (_a2 = document2.pointerLockElement) != null ? _a2 : element.value;
      if (targetElement && currentElement === targetElement) {
        element.value = document2.pointerLockElement;
        if (!element.value)
          targetElement = triggerElement.value = null;
      }
    });
    useEventListener(document2, "pointerlockerror", () => {
      var _a2;
      const currentElement = (_a2 = document2.pointerLockElement) != null ? _a2 : element.value;
      if (targetElement && currentElement === targetElement) {
        const action = document2.pointerLockElement ? "release" : "acquire";
        throw new Error(`Failed to ${action} pointer lock.`);
      }
    });
  }
  async function lock(e2) {
    var _a2;
    if (!isSupported.value)
      throw new Error("Pointer Lock API is not supported by your browser.");
    triggerElement.value = e2 instanceof Event ? e2.currentTarget : null;
    targetElement = e2 instanceof Event ? (_a2 = unrefElement(target)) != null ? _a2 : triggerElement.value : unrefElement(e2);
    if (!targetElement)
      throw new Error("Target element undefined.");
    targetElement.requestPointerLock();
    return await until(element).toBe(targetElement);
  }
  __name(lock, "lock");
  async function unlock() {
    if (!element.value)
      return false;
    document2.exitPointerLock();
    await until(element).toBeNull();
    return true;
  }
  __name(unlock, "unlock");
  return {
    isSupported,
    element,
    triggerElement,
    lock,
    unlock
  };
}
__name(usePointerLock, "usePointerLock");
function usePointerSwipe(target, options2 = {}) {
  const targetRef = toRef(target);
  const {
    threshold = 50,
    onSwipe,
    onSwipeEnd,
    onSwipeStart,
    disableTextSelect = false
  } = options2;
  const posStart = reactive({ x: 0, y: 0 });
  const updatePosStart = /* @__PURE__ */ __name((x2, y2) => {
    posStart.x = x2;
    posStart.y = y2;
  }, "updatePosStart");
  const posEnd = reactive({ x: 0, y: 0 });
  const updatePosEnd = /* @__PURE__ */ __name((x2, y2) => {
    posEnd.x = x2;
    posEnd.y = y2;
  }, "updatePosEnd");
  const distanceX = computed(() => posStart.x - posEnd.x);
  const distanceY = computed(() => posStart.y - posEnd.y);
  const { max, abs } = Math;
  const isThresholdExceeded = computed(() => max(abs(distanceX.value), abs(distanceY.value)) >= threshold);
  const isSwiping = ref$3(false);
  const isPointerDown = ref$3(false);
  const direction = computed(() => {
    if (!isThresholdExceeded.value)
      return "none";
    if (abs(distanceX.value) > abs(distanceY.value)) {
      return distanceX.value > 0 ? "left" : "right";
    } else {
      return distanceY.value > 0 ? "up" : "down";
    }
  });
  const eventIsAllowed = /* @__PURE__ */ __name((e2) => {
    var _a2, _b, _c;
    const isReleasingButton = e2.buttons === 0;
    const isPrimaryButton = e2.buttons === 1;
    return (_c = (_b = (_a2 = options2.pointerTypes) == null ? void 0 : _a2.includes(e2.pointerType)) != null ? _b : isReleasingButton || isPrimaryButton) != null ? _c : true;
  }, "eventIsAllowed");
  const stops = [
    useEventListener(target, "pointerdown", (e2) => {
      if (!eventIsAllowed(e2))
        return;
      isPointerDown.value = true;
      const eventTarget = e2.target;
      eventTarget == null ? void 0 : eventTarget.setPointerCapture(e2.pointerId);
      const { clientX: x2, clientY: y2 } = e2;
      updatePosStart(x2, y2);
      updatePosEnd(x2, y2);
      onSwipeStart == null ? void 0 : onSwipeStart(e2);
    }),
    useEventListener(target, "pointermove", (e2) => {
      if (!eventIsAllowed(e2))
        return;
      if (!isPointerDown.value)
        return;
      const { clientX: x2, clientY: y2 } = e2;
      updatePosEnd(x2, y2);
      if (!isSwiping.value && isThresholdExceeded.value)
        isSwiping.value = true;
      if (isSwiping.value)
        onSwipe == null ? void 0 : onSwipe(e2);
    }),
    useEventListener(target, "pointerup", (e2) => {
      if (!eventIsAllowed(e2))
        return;
      if (isSwiping.value)
        onSwipeEnd == null ? void 0 : onSwipeEnd(e2, direction.value);
      isPointerDown.value = false;
      isSwiping.value = false;
    })
  ];
  tryOnMounted$2(() => {
    var _a2, _b, _c, _d, _e2, _f, _g, _h;
    (_b = (_a2 = targetRef.value) == null ? void 0 : _a2.style) == null ? void 0 : _b.setProperty("touch-action", "none");
    if (disableTextSelect) {
      (_d = (_c = targetRef.value) == null ? void 0 : _c.style) == null ? void 0 : _d.setProperty("-webkit-user-select", "none");
      (_f = (_e2 = targetRef.value) == null ? void 0 : _e2.style) == null ? void 0 : _f.setProperty("-ms-user-select", "none");
      (_h = (_g = targetRef.value) == null ? void 0 : _g.style) == null ? void 0 : _h.setProperty("user-select", "none");
    }
  });
  const stop2 = /* @__PURE__ */ __name(() => stops.forEach((s2) => s2()), "stop");
  return {
    isSwiping: readonly(isSwiping),
    direction: readonly(direction),
    posStart: readonly(posStart),
    posEnd: readonly(posEnd),
    distanceX,
    distanceY,
    stop: stop2
  };
}
__name(usePointerSwipe, "usePointerSwipe");
function usePreferredColorScheme(options2) {
  const isLight = useMediaQuery("(prefers-color-scheme: light)", options2);
  const isDark = useMediaQuery("(prefers-color-scheme: dark)", options2);
  return computed(() => {
    if (isDark.value)
      return "dark";
    if (isLight.value)
      return "light";
    return "no-preference";
  });
}
__name(usePreferredColorScheme, "usePreferredColorScheme");
function usePreferredContrast(options2) {
  const isMore = useMediaQuery("(prefers-contrast: more)", options2);
  const isLess = useMediaQuery("(prefers-contrast: less)", options2);
  const isCustom = useMediaQuery("(prefers-contrast: custom)", options2);
  return computed(() => {
    if (isMore.value)
      return "more";
    if (isLess.value)
      return "less";
    if (isCustom.value)
      return "custom";
    return "no-preference";
  });
}
__name(usePreferredContrast, "usePreferredContrast");
function usePreferredLanguages(options2 = {}) {
  const { window: window2 = defaultWindow } = options2;
  if (!window2)
    return ref$3(["en"]);
  const navigator2 = window2.navigator;
  const value = ref$3(navigator2.languages);
  useEventListener(window2, "languagechange", () => {
    value.value = navigator2.languages;
  });
  return value;
}
__name(usePreferredLanguages, "usePreferredLanguages");
function usePreferredReducedMotion(options2) {
  const isReduced = useMediaQuery("(prefers-reduced-motion: reduce)", options2);
  return computed(() => {
    if (isReduced.value)
      return "reduce";
    return "no-preference";
  });
}
__name(usePreferredReducedMotion, "usePreferredReducedMotion");
function usePrevious(value, initialValue) {
  const previous = shallowRef(initialValue);
  watch(
    toRef(value),
    (_2, oldValue) => {
      previous.value = oldValue;
    },
    { flush: "sync" }
  );
  return readonly(previous);
}
__name(usePrevious, "usePrevious");
const topVarName = "--vueuse-safe-area-top";
const rightVarName = "--vueuse-safe-area-right";
const bottomVarName = "--vueuse-safe-area-bottom";
const leftVarName = "--vueuse-safe-area-left";
function useScreenSafeArea() {
  const top = ref$3("");
  const right = ref$3("");
  const bottom = ref$3("");
  const left = ref$3("");
  if (isClient$1) {
    const topCssVar = useCssVar(topVarName);
    const rightCssVar = useCssVar(rightVarName);
    const bottomCssVar = useCssVar(bottomVarName);
    const leftCssVar = useCssVar(leftVarName);
    topCssVar.value = "env(safe-area-inset-top, 0px)";
    rightCssVar.value = "env(safe-area-inset-right, 0px)";
    bottomCssVar.value = "env(safe-area-inset-bottom, 0px)";
    leftCssVar.value = "env(safe-area-inset-left, 0px)";
    update2();
    useEventListener("resize", useDebounceFn(update2));
  }
  function update2() {
    top.value = getValue$2(topVarName);
    right.value = getValue$2(rightVarName);
    bottom.value = getValue$2(bottomVarName);
    left.value = getValue$2(leftVarName);
  }
  __name(update2, "update");
  return {
    top,
    right,
    bottom,
    left,
    update: update2
  };
}
__name(useScreenSafeArea, "useScreenSafeArea");
function getValue$2(position) {
  return getComputedStyle(document.documentElement).getPropertyValue(position);
}
__name(getValue$2, "getValue$2");
function useScriptTag(src, onLoaded = noop$2, options2 = {}) {
  const {
    immediate = true,
    manual = false,
    type = "text/javascript",
    async: async2 = true,
    crossOrigin,
    referrerPolicy,
    noModule,
    defer,
    document: document2 = defaultDocument,
    attrs: attrs2 = {}
  } = options2;
  const scriptTag = ref$3(null);
  let _promise = null;
  const loadScript = /* @__PURE__ */ __name((waitForScriptLoad) => new Promise((resolve2, reject) => {
    const resolveWithElement = /* @__PURE__ */ __name((el2) => {
      scriptTag.value = el2;
      resolve2(el2);
      return el2;
    }, "resolveWithElement");
    if (!document2) {
      resolve2(false);
      return;
    }
    let shouldAppend = false;
    let el = document2.querySelector(`script[src="${toValue$3(src)}"]`);
    if (!el) {
      el = document2.createElement("script");
      el.type = type;
      el.async = async2;
      el.src = toValue$3(src);
      if (defer)
        el.defer = defer;
      if (crossOrigin)
        el.crossOrigin = crossOrigin;
      if (noModule)
        el.noModule = noModule;
      if (referrerPolicy)
        el.referrerPolicy = referrerPolicy;
      Object.entries(attrs2).forEach(([name2, value]) => el == null ? void 0 : el.setAttribute(name2, value));
      shouldAppend = true;
    } else if (el.hasAttribute("data-loaded")) {
      resolveWithElement(el);
    }
    el.addEventListener("error", (event) => reject(event));
    el.addEventListener("abort", (event) => reject(event));
    el.addEventListener("load", () => {
      el.setAttribute("data-loaded", "true");
      onLoaded(el);
      resolveWithElement(el);
    });
    if (shouldAppend)
      el = document2.head.appendChild(el);
    if (!waitForScriptLoad)
      resolveWithElement(el);
  }), "loadScript");
  const load2 = /* @__PURE__ */ __name((waitForScriptLoad = true) => {
    if (!_promise)
      _promise = loadScript(waitForScriptLoad);
    return _promise;
  }, "load");
  const unload = /* @__PURE__ */ __name(() => {
    if (!document2)
      return;
    _promise = null;
    if (scriptTag.value)
      scriptTag.value = null;
    const el = document2.querySelector(`script[src="${toValue$3(src)}"]`);
    if (el)
      document2.head.removeChild(el);
  }, "unload");
  if (immediate && !manual)
    tryOnMounted$2(load2);
  if (!manual)
    tryOnUnmounted(unload);
  return { scriptTag, load: load2, unload };
}
__name(useScriptTag, "useScriptTag");
function checkOverflowScroll(ele) {
  const style2 = window.getComputedStyle(ele);
  if (style2.overflowX === "scroll" || style2.overflowY === "scroll" || style2.overflowX === "auto" && ele.clientWidth < ele.scrollWidth || style2.overflowY === "auto" && ele.clientHeight < ele.scrollHeight) {
    return true;
  } else {
    const parent2 = ele.parentNode;
    if (!parent2 || parent2.tagName === "BODY")
      return false;
    return checkOverflowScroll(parent2);
  }
}
__name(checkOverflowScroll, "checkOverflowScroll");
function preventDefault(rawEvent) {
  const e2 = rawEvent || window.event;
  const _target = e2.target;
  if (checkOverflowScroll(_target))
    return false;
  if (e2.touches.length > 1)
    return true;
  if (e2.preventDefault)
    e2.preventDefault();
  return false;
}
__name(preventDefault, "preventDefault");
const elInitialOverflow = /* @__PURE__ */ new WeakMap();
function useScrollLock(element, initialState = false) {
  const isLocked = ref$3(initialState);
  let stopTouchMoveListener = null;
  let initialOverflow = "";
  watch(toRef(element), (el) => {
    const target = resolveElement(toValue$3(el));
    if (target) {
      const ele = target;
      if (!elInitialOverflow.get(ele))
        elInitialOverflow.set(ele, ele.style.overflow);
      if (ele.style.overflow !== "hidden")
        initialOverflow = ele.style.overflow;
      if (ele.style.overflow === "hidden")
        return isLocked.value = true;
      if (isLocked.value)
        return ele.style.overflow = "hidden";
    }
  }, {
    immediate: true
  });
  const lock = /* @__PURE__ */ __name(() => {
    const el = resolveElement(toValue$3(element));
    if (!el || isLocked.value)
      return;
    if (isIOS$1) {
      stopTouchMoveListener = useEventListener(
        el,
        "touchmove",
        (e2) => {
          preventDefault(e2);
        },
        { passive: false }
      );
    }
    el.style.overflow = "hidden";
    isLocked.value = true;
  }, "lock");
  const unlock = /* @__PURE__ */ __name(() => {
    const el = resolveElement(toValue$3(element));
    if (!el || !isLocked.value)
      return;
    if (isIOS$1)
      stopTouchMoveListener == null ? void 0 : stopTouchMoveListener();
    el.style.overflow = initialOverflow;
    elInitialOverflow.delete(el);
    isLocked.value = false;
  }, "unlock");
  tryOnScopeDispose(unlock);
  return computed({
    get() {
      return isLocked.value;
    },
    set(v2) {
      if (v2)
        lock();
      else unlock();
    }
  });
}
__name(useScrollLock, "useScrollLock");
function useSessionStorage(key, initialValue, options2 = {}) {
  const { window: window2 = defaultWindow } = options2;
  return useStorage(key, initialValue, window2 == null ? void 0 : window2.sessionStorage, options2);
}
__name(useSessionStorage, "useSessionStorage");
function useShare(shareOptions = {}, options2 = {}) {
  const { navigator: navigator2 = defaultNavigator } = options2;
  const _navigator2 = navigator2;
  const isSupported = useSupported(() => _navigator2 && "canShare" in _navigator2);
  const share = /* @__PURE__ */ __name(async (overrideOptions = {}) => {
    if (isSupported.value) {
      const data = {
        ...toValue$3(shareOptions),
        ...toValue$3(overrideOptions)
      };
      let granted = true;
      if (data.files && _navigator2.canShare)
        granted = _navigator2.canShare({ files: data.files });
      if (granted)
        return _navigator2.share(data);
    }
  }, "share");
  return {
    isSupported,
    share
  };
}
__name(useShare, "useShare");
const defaultSortFn = /* @__PURE__ */ __name((source, compareFn) => source.sort(compareFn), "defaultSortFn");
const defaultCompare = /* @__PURE__ */ __name((a2, b2) => a2 - b2, "defaultCompare");
function useSorted(...args) {
  var _a2, _b, _c, _d;
  const [source] = args;
  let compareFn = defaultCompare;
  let options2 = {};
  if (args.length === 2) {
    if (typeof args[1] === "object") {
      options2 = args[1];
      compareFn = (_a2 = options2.compareFn) != null ? _a2 : defaultCompare;
    } else {
      compareFn = (_b = args[1]) != null ? _b : defaultCompare;
    }
  } else if (args.length > 2) {
    compareFn = (_c = args[1]) != null ? _c : defaultCompare;
    options2 = (_d = args[2]) != null ? _d : {};
  }
  const {
    dirty = false,
    sortFn = defaultSortFn
  } = options2;
  if (!dirty)
    return computed(() => sortFn([...toValue$3(source)], compareFn));
  watchEffect(() => {
    const result = sortFn(toValue$3(source), compareFn);
    if (isRef(source))
      source.value = result;
    else
      source.splice(0, source.length, ...result);
  });
  return source;
}
__name(useSorted, "useSorted");
function useSpeechRecognition(options2 = {}) {
  const {
    interimResults = true,
    continuous = true,
    maxAlternatives = 1,
    window: window2 = defaultWindow
  } = options2;
  const lang = toRef(options2.lang || "en-US");
  const isListening = ref$3(false);
  const isFinal = ref$3(false);
  const result = ref$3("");
  const error2 = shallowRef(void 0);
  const toggle = /* @__PURE__ */ __name((value = !isListening.value) => {
    isListening.value = value;
  }, "toggle");
  const start2 = /* @__PURE__ */ __name(() => {
    isListening.value = true;
  }, "start");
  const stop2 = /* @__PURE__ */ __name(() => {
    isListening.value = false;
  }, "stop");
  const SpeechRecognition = window2 && (window2.SpeechRecognition || window2.webkitSpeechRecognition);
  const isSupported = useSupported(() => SpeechRecognition);
  let recognition;
  if (isSupported.value) {
    recognition = new SpeechRecognition();
    recognition.continuous = continuous;
    recognition.interimResults = interimResults;
    recognition.lang = toValue$3(lang);
    recognition.maxAlternatives = maxAlternatives;
    recognition.onstart = () => {
      isFinal.value = false;
    };
    watch(lang, (lang2) => {
      if (recognition && !isListening.value)
        recognition.lang = lang2;
    });
    recognition.onresult = (event) => {
      const currentResult = event.results[event.resultIndex];
      const { transcript } = currentResult[0];
      isFinal.value = currentResult.isFinal;
      result.value = transcript;
      error2.value = void 0;
    };
    recognition.onerror = (event) => {
      error2.value = event;
    };
    recognition.onend = () => {
      isListening.value = false;
      recognition.lang = toValue$3(lang);
    };
    watch(isListening, () => {
      if (isListening.value)
        recognition.start();
      else
        recognition.stop();
    });
  }
  tryOnScopeDispose(() => {
    isListening.value = false;
  });
  return {
    isSupported,
    isListening,
    isFinal,
    recognition,
    result,
    error: error2,
    toggle,
    start: start2,
    stop: stop2
  };
}
__name(useSpeechRecognition, "useSpeechRecognition");
function useSpeechSynthesis(text2, options2 = {}) {
  const {
    pitch = 1,
    rate = 1,
    volume = 1,
    window: window2 = defaultWindow
  } = options2;
  const synth = window2 && window2.speechSynthesis;
  const isSupported = useSupported(() => synth);
  const isPlaying = ref$3(false);
  const status = ref$3("init");
  const spokenText = toRef(text2 || "");
  const lang = toRef(options2.lang || "en-US");
  const error2 = shallowRef(void 0);
  const toggle = /* @__PURE__ */ __name((value = !isPlaying.value) => {
    isPlaying.value = value;
  }, "toggle");
  const bindEventsForUtterance = /* @__PURE__ */ __name((utterance2) => {
    utterance2.lang = toValue$3(lang);
    utterance2.voice = toValue$3(options2.voice) || null;
    utterance2.pitch = toValue$3(pitch);
    utterance2.rate = toValue$3(rate);
    utterance2.volume = volume;
    utterance2.onstart = () => {
      isPlaying.value = true;
      status.value = "play";
    };
    utterance2.onpause = () => {
      isPlaying.value = false;
      status.value = "pause";
    };
    utterance2.onresume = () => {
      isPlaying.value = true;
      status.value = "play";
    };
    utterance2.onend = () => {
      isPlaying.value = false;
      status.value = "end";
    };
    utterance2.onerror = (event) => {
      error2.value = event;
    };
  }, "bindEventsForUtterance");
  const utterance = computed(() => {
    isPlaying.value = false;
    status.value = "init";
    const newUtterance = new SpeechSynthesisUtterance(spokenText.value);
    bindEventsForUtterance(newUtterance);
    return newUtterance;
  });
  const speak = /* @__PURE__ */ __name(() => {
    synth.cancel();
    if (utterance)
      synth.speak(utterance.value);
  }, "speak");
  const stop2 = /* @__PURE__ */ __name(() => {
    synth.cancel();
    isPlaying.value = false;
  }, "stop");
  if (isSupported.value) {
    bindEventsForUtterance(utterance.value);
    watch(lang, (lang2) => {
      if (utterance.value && !isPlaying.value)
        utterance.value.lang = lang2;
    });
    if (options2.voice) {
      watch(options2.voice, () => {
        synth.cancel();
      });
    }
    watch(isPlaying, () => {
      if (isPlaying.value)
        synth.resume();
      else
        synth.pause();
    });
  }
  tryOnScopeDispose(() => {
    isPlaying.value = false;
  });
  return {
    isSupported,
    isPlaying,
    status,
    utterance,
    error: error2,
    stop: stop2,
    toggle,
    speak
  };
}
__name(useSpeechSynthesis, "useSpeechSynthesis");
function useStepper(steps, initialStep) {
  const stepsRef = ref$3(steps);
  const stepNames = computed(() => Array.isArray(stepsRef.value) ? stepsRef.value : Object.keys(stepsRef.value));
  const index2 = ref$3(stepNames.value.indexOf(initialStep != null ? initialStep : stepNames.value[0]));
  const current = computed(() => at2(index2.value));
  const isFirst = computed(() => index2.value === 0);
  const isLast = computed(() => index2.value === stepNames.value.length - 1);
  const next = computed(() => stepNames.value[index2.value + 1]);
  const previous = computed(() => stepNames.value[index2.value - 1]);
  function at2(index22) {
    if (Array.isArray(stepsRef.value))
      return stepsRef.value[index22];
    return stepsRef.value[stepNames.value[index22]];
  }
  __name(at2, "at");
  function get3(step) {
    if (!stepNames.value.includes(step))
      return;
    return at2(stepNames.value.indexOf(step));
  }
  __name(get3, "get");
  function goTo(step) {
    if (stepNames.value.includes(step))
      index2.value = stepNames.value.indexOf(step);
  }
  __name(goTo, "goTo");
  function goToNext() {
    if (isLast.value)
      return;
    index2.value++;
  }
  __name(goToNext, "goToNext");
  function goToPrevious() {
    if (isFirst.value)
      return;
    index2.value--;
  }
  __name(goToPrevious, "goToPrevious");
  function goBackTo(step) {
    if (isAfter(step))
      goTo(step);
  }
  __name(goBackTo, "goBackTo");
  function isNext(step) {
    return stepNames.value.indexOf(step) === index2.value + 1;
  }
  __name(isNext, "isNext");
  function isPrevious(step) {
    return stepNames.value.indexOf(step) === index2.value - 1;
  }
  __name(isPrevious, "isPrevious");
  function isCurrent(step) {
    return stepNames.value.indexOf(step) === index2.value;
  }
  __name(isCurrent, "isCurrent");
  function isBefore(step) {
    return index2.value < stepNames.value.indexOf(step);
  }
  __name(isBefore, "isBefore");
  function isAfter(step) {
    return index2.value > stepNames.value.indexOf(step);
  }
  __name(isAfter, "isAfter");
  return {
    steps: stepsRef,
    stepNames,
    index: index2,
    current,
    next,
    previous,
    isFirst,
    isLast,
    at: at2,
    get: get3,
    goTo,
    goToNext,
    goToPrevious,
    goBackTo,
    isNext,
    isPrevious,
    isCurrent,
    isBefore,
    isAfter
  };
}
__name(useStepper, "useStepper");
function useStorageAsync(key, initialValue, storage, options2 = {}) {
  var _a2;
  const {
    flush: flush2 = "pre",
    deep = true,
    listenToStorageChanges = true,
    writeDefaults = true,
    mergeDefaults = false,
    shallow,
    window: window2 = defaultWindow,
    eventFilter,
    onError = /* @__PURE__ */ __name((e2) => {
      console.error(e2);
    }, "onError")
  } = options2;
  const rawInit = toValue$3(initialValue);
  const type = guessSerializerType(rawInit);
  const data = (shallow ? shallowRef : ref$3)(initialValue);
  const serializer = (_a2 = options2.serializer) != null ? _a2 : StorageSerializers[type];
  if (!storage) {
    try {
      storage = getSSRHandler("getDefaultStorageAsync", () => {
        var _a22;
        return (_a22 = defaultWindow) == null ? void 0 : _a22.localStorage;
      })();
    } catch (e2) {
      onError(e2);
    }
  }
  async function read2(event) {
    if (!storage || event && event.key !== key)
      return;
    try {
      const rawValue = event ? event.newValue : await storage.getItem(key);
      if (rawValue == null) {
        data.value = rawInit;
        if (writeDefaults && rawInit !== null)
          await storage.setItem(key, await serializer.write(rawInit));
      } else if (mergeDefaults) {
        const value = await serializer.read(rawValue);
        if (typeof mergeDefaults === "function")
          data.value = mergeDefaults(value, rawInit);
        else if (type === "object" && !Array.isArray(value))
          data.value = { ...rawInit, ...value };
        else data.value = value;
      } else {
        data.value = await serializer.read(rawValue);
      }
    } catch (e2) {
      onError(e2);
    }
  }
  __name(read2, "read");
  read2();
  if (window2 && listenToStorageChanges)
    useEventListener(window2, "storage", (e2) => Promise.resolve().then(() => read2(e2)));
  if (storage) {
    watchWithFilter(
      data,
      async () => {
        try {
          if (data.value == null)
            await storage.removeItem(key);
          else
            await storage.setItem(key, await serializer.write(data.value));
        } catch (e2) {
          onError(e2);
        }
      },
      {
        flush: flush2,
        deep,
        eventFilter
      }
    );
  }
  return data;
}
__name(useStorageAsync, "useStorageAsync");
let _id$1 = 0;
function useStyleTag(css3, options2 = {}) {
  const isLoaded = ref$3(false);
  const {
    document: document2 = defaultDocument,
    immediate = true,
    manual = false,
    id: id2 = `vueuse_styletag_${++_id$1}`
  } = options2;
  const cssRef = ref$3(css3);
  let stop2 = /* @__PURE__ */ __name(() => {
  }, "stop");
  const load2 = /* @__PURE__ */ __name(() => {
    if (!document2)
      return;
    const el = document2.getElementById(id2) || document2.createElement("style");
    if (!el.isConnected) {
      el.id = id2;
      if (options2.media)
        el.media = options2.media;
      document2.head.appendChild(el);
    }
    if (isLoaded.value)
      return;
    stop2 = watch(
      cssRef,
      (value) => {
        el.textContent = value;
      },
      { immediate: true }
    );
    isLoaded.value = true;
  }, "load");
  const unload = /* @__PURE__ */ __name(() => {
    if (!document2 || !isLoaded.value)
      return;
    stop2();
    document2.head.removeChild(document2.getElementById(id2));
    isLoaded.value = false;
  }, "unload");
  if (immediate && !manual)
    tryOnMounted$2(load2);
  if (!manual)
    tryOnScopeDispose(unload);
  return {
    id: id2,
    css: cssRef,
    unload,
    load: load2,
    isLoaded: readonly(isLoaded)
  };
}
__name(useStyleTag, "useStyleTag");
function useSwipe(target, options2 = {}) {
  const {
    threshold = 50,
    onSwipe,
    onSwipeEnd,
    onSwipeStart,
    passive = true,
    window: window2 = defaultWindow
  } = options2;
  const coordsStart = reactive({ x: 0, y: 0 });
  const coordsEnd = reactive({ x: 0, y: 0 });
  const diffX = computed(() => coordsStart.x - coordsEnd.x);
  const diffY = computed(() => coordsStart.y - coordsEnd.y);
  const { max, abs } = Math;
  const isThresholdExceeded = computed(() => max(abs(diffX.value), abs(diffY.value)) >= threshold);
  const isSwiping = ref$3(false);
  const direction = computed(() => {
    if (!isThresholdExceeded.value)
      return "none";
    if (abs(diffX.value) > abs(diffY.value)) {
      return diffX.value > 0 ? "left" : "right";
    } else {
      return diffY.value > 0 ? "up" : "down";
    }
  });
  const getTouchEventCoords = /* @__PURE__ */ __name((e2) => [e2.touches[0].clientX, e2.touches[0].clientY], "getTouchEventCoords");
  const updateCoordsStart = /* @__PURE__ */ __name((x2, y2) => {
    coordsStart.x = x2;
    coordsStart.y = y2;
  }, "updateCoordsStart");
  const updateCoordsEnd = /* @__PURE__ */ __name((x2, y2) => {
    coordsEnd.x = x2;
    coordsEnd.y = y2;
  }, "updateCoordsEnd");
  let listenerOptions;
  const isPassiveEventSupported = checkPassiveEventSupport(window2 == null ? void 0 : window2.document);
  if (!passive)
    listenerOptions = isPassiveEventSupported ? { passive: false, capture: true } : { capture: true };
  else
    listenerOptions = isPassiveEventSupported ? { passive: true } : { capture: false };
  const onTouchEnd = /* @__PURE__ */ __name((e2) => {
    if (isSwiping.value)
      onSwipeEnd == null ? void 0 : onSwipeEnd(e2, direction.value);
    isSwiping.value = false;
  }, "onTouchEnd");
  const stops = [
    useEventListener(target, "touchstart", (e2) => {
      if (e2.touches.length !== 1)
        return;
      if (listenerOptions.capture && !listenerOptions.passive)
        e2.preventDefault();
      const [x2, y2] = getTouchEventCoords(e2);
      updateCoordsStart(x2, y2);
      updateCoordsEnd(x2, y2);
      onSwipeStart == null ? void 0 : onSwipeStart(e2);
    }, listenerOptions),
    useEventListener(target, "touchmove", (e2) => {
      if (e2.touches.length !== 1)
        return;
      const [x2, y2] = getTouchEventCoords(e2);
      updateCoordsEnd(x2, y2);
      if (!isSwiping.value && isThresholdExceeded.value)
        isSwiping.value = true;
      if (isSwiping.value)
        onSwipe == null ? void 0 : onSwipe(e2);
    }, listenerOptions),
    useEventListener(target, ["touchend", "touchcancel"], onTouchEnd, listenerOptions)
  ];
  const stop2 = /* @__PURE__ */ __name(() => stops.forEach((s2) => s2()), "stop");
  return {
    isPassiveEventSupported,
    isSwiping,
    direction,
    coordsStart,
    coordsEnd,
    lengthX: diffX,
    lengthY: diffY,
    stop: stop2
  };
}
__name(useSwipe, "useSwipe");
function checkPassiveEventSupport(document2) {
  if (!document2)
    return false;
  let supportsPassive = false;
  const optionsBlock = {
    get passive() {
      supportsPassive = true;
      return false;
    }
  };
  document2.addEventListener("x", noop$2, optionsBlock);
  document2.removeEventListener("x", noop$2);
  return supportsPassive;
}
__name(checkPassiveEventSupport, "checkPassiveEventSupport");
function useTemplateRefsList() {
  const refs = ref$3([]);
  refs.value.set = (el) => {
    if (el)
      refs.value.push(el);
  };
  onBeforeUpdate(() => {
    refs.value.length = 0;
  });
  return refs;
}
__name(useTemplateRefsList, "useTemplateRefsList");
function useTextDirection(options2 = {}) {
  const {
    document: document2 = defaultDocument,
    selector = "html",
    observe: observe2 = false,
    initialValue = "ltr"
  } = options2;
  function getValue2() {
    var _a2, _b;
    return (_b = (_a2 = document2 == null ? void 0 : document2.querySelector(selector)) == null ? void 0 : _a2.getAttribute("dir")) != null ? _b : initialValue;
  }
  __name(getValue2, "getValue2");
  const dir = ref$3(getValue2());
  tryOnMounted$2(() => dir.value = getValue2());
  if (observe2 && document2) {
    useMutationObserver(
      document2.querySelector(selector),
      () => dir.value = getValue2(),
      { attributes: true }
    );
  }
  return computed({
    get() {
      return dir.value;
    },
    set(v2) {
      var _a2, _b;
      dir.value = v2;
      if (!document2)
        return;
      if (dir.value)
        (_a2 = document2.querySelector(selector)) == null ? void 0 : _a2.setAttribute("dir", dir.value);
      else
        (_b = document2.querySelector(selector)) == null ? void 0 : _b.removeAttribute("dir");
    }
  });
}
__name(useTextDirection, "useTextDirection");
function getRangesFromSelection(selection) {
  var _a2;
  const rangeCount = (_a2 = selection.rangeCount) != null ? _a2 : 0;
  return Array.from({ length: rangeCount }, (_2, i2) => selection.getRangeAt(i2));
}
__name(getRangesFromSelection, "getRangesFromSelection");
function useTextSelection(options2 = {}) {
  const {
    window: window2 = defaultWindow
  } = options2;
  const selection = ref$3(null);
  const text2 = computed(() => {
    var _a2, _b;
    return (_b = (_a2 = selection.value) == null ? void 0 : _a2.toString()) != null ? _b : "";
  });
  const ranges = computed(() => selection.value ? getRangesFromSelection(selection.value) : []);
  const rects = computed(() => ranges.value.map((range) => range.getBoundingClientRect()));
  function onSelectionChange() {
    selection.value = null;
    if (window2)
      selection.value = window2.getSelection();
  }
  __name(onSelectionChange, "onSelectionChange");
  if (window2)
    useEventListener(window2.document, "selectionchange", onSelectionChange);
  return {
    text: text2,
    rects,
    ranges,
    selection
  };
}
__name(useTextSelection, "useTextSelection");
function useTextareaAutosize(options2) {
  var _a2;
  const textarea = ref$3(options2 == null ? void 0 : options2.element);
  const input = ref$3(options2 == null ? void 0 : options2.input);
  const styleProp = (_a2 = options2 == null ? void 0 : options2.styleProp) != null ? _a2 : "height";
  const textareaScrollHeight = ref$3(1);
  const textareaOldWidth = ref$3(0);
  function triggerResize() {
    var _a22;
    if (!textarea.value)
      return;
    let height = "";
    textarea.value.style[styleProp] = "1px";
    textareaScrollHeight.value = (_a22 = textarea.value) == null ? void 0 : _a22.scrollHeight;
    const _styleTarget = toValue$3(options2 == null ? void 0 : options2.styleTarget);
    if (_styleTarget)
      _styleTarget.style[styleProp] = `${textareaScrollHeight.value}px`;
    else
      height = `${textareaScrollHeight.value}px`;
    textarea.value.style[styleProp] = height;
  }
  __name(triggerResize, "triggerResize");
  watch([input, textarea], () => nextTick(triggerResize), { immediate: true });
  watch(textareaScrollHeight, () => {
    var _a22;
    return (_a22 = options2 == null ? void 0 : options2.onResize) == null ? void 0 : _a22.call(options2);
  });
  useResizeObserver(textarea, ([{ contentRect }]) => {
    if (textareaOldWidth.value === contentRect.width)
      return;
    textareaOldWidth.value = contentRect.width;
    triggerResize();
  });
  if (options2 == null ? void 0 : options2.watch)
    watch(options2.watch, triggerResize, { immediate: true, deep: true });
  return {
    textarea,
    input,
    triggerResize
  };
}
__name(useTextareaAutosize, "useTextareaAutosize");
function useThrottledRefHistory(source, options2 = {}) {
  const { throttle: throttle2 = 200, trailing = true } = options2;
  const filter3 = throttleFilter(throttle2, trailing);
  const history2 = useRefHistory(source, { ...options2, eventFilter: filter3 });
  return {
    ...history2
  };
}
__name(useThrottledRefHistory, "useThrottledRefHistory");
const DEFAULT_UNITS = [
  { max: 6e4, value: 1e3, name: "second" },
  { max: 276e4, value: 6e4, name: "minute" },
  { max: 72e6, value: 36e5, name: "hour" },
  { max: 5184e5, value: 864e5, name: "day" },
  { max: 24192e5, value: 6048e5, name: "week" },
  { max: 28512e6, value: 2592e6, name: "month" },
  { max: Number.POSITIVE_INFINITY, value: 31536e6, name: "year" }
];
const DEFAULT_MESSAGES = {
  justNow: "just now",
  past: /* @__PURE__ */ __name((n2) => n2.match(/\d/) ? `${n2} ago` : n2, "past"),
  future: /* @__PURE__ */ __name((n2) => n2.match(/\d/) ? `in ${n2}` : n2, "future"),
  month: /* @__PURE__ */ __name((n2, past) => n2 === 1 ? past ? "last month" : "next month" : `${n2} month${n2 > 1 ? "s" : ""}`, "month"),
  year: /* @__PURE__ */ __name((n2, past) => n2 === 1 ? past ? "last year" : "next year" : `${n2} year${n2 > 1 ? "s" : ""}`, "year"),
  day: /* @__PURE__ */ __name((n2, past) => n2 === 1 ? past ? "yesterday" : "tomorrow" : `${n2} day${n2 > 1 ? "s" : ""}`, "day"),
  week: /* @__PURE__ */ __name((n2, past) => n2 === 1 ? past ? "last week" : "next week" : `${n2} week${n2 > 1 ? "s" : ""}`, "week"),
  hour: /* @__PURE__ */ __name((n2) => `${n2} hour${n2 > 1 ? "s" : ""}`, "hour"),
  minute: /* @__PURE__ */ __name((n2) => `${n2} minute${n2 > 1 ? "s" : ""}`, "minute"),
  second: /* @__PURE__ */ __name((n2) => `${n2} second${n2 > 1 ? "s" : ""}`, "second"),
  invalid: ""
};
function DEFAULT_FORMATTER(date) {
  return date.toISOString().slice(0, 10);
}
__name(DEFAULT_FORMATTER, "DEFAULT_FORMATTER");
function useTimeAgo(time, options2 = {}) {
  const {
    controls: exposeControls = false,
    updateInterval = 3e4
  } = options2;
  const { now: now2, ...controls } = useNow({ interval: updateInterval, controls: true });
  const timeAgo = computed(() => formatTimeAgo(new Date(toValue$3(time)), options2, toValue$3(now2)));
  if (exposeControls) {
    return {
      timeAgo,
      ...controls
    };
  } else {
    return timeAgo;
  }
}
__name(useTimeAgo, "useTimeAgo");
function formatTimeAgo(from2, options2 = {}, now2 = Date.now()) {
  var _a2;
  const {
    max,
    messages: messages2 = DEFAULT_MESSAGES,
    fullDateFormatter = DEFAULT_FORMATTER,
    units = DEFAULT_UNITS,
    showSecond = false,
    rounding = "round"
  } = options2;
  const roundFn = typeof rounding === "number" ? (n2) => +n2.toFixed(rounding) : Math[rounding];
  const diff2 = +now2 - +from2;
  const absDiff = Math.abs(diff2);
  function getValue2(diff22, unit) {
    return roundFn(Math.abs(diff22) / unit.value);
  }
  __name(getValue2, "getValue2");
  function format2(diff22, unit) {
    const val = getValue2(diff22, unit);
    const past = diff22 > 0;
    const str = applyFormat(unit.name, val, past);
    return applyFormat(past ? "past" : "future", str, past);
  }
  __name(format2, "format");
  function applyFormat(name2, val, isPast) {
    const formatter = messages2[name2];
    if (typeof formatter === "function")
      return formatter(val, isPast);
    return formatter.replace("{0}", val.toString());
  }
  __name(applyFormat, "applyFormat");
  if (absDiff < 6e4 && !showSecond)
    return messages2.justNow;
  if (typeof max === "number" && absDiff > max)
    return fullDateFormatter(new Date(from2));
  if (typeof max === "string") {
    const unitMax = (_a2 = units.find((i2) => i2.name === max)) == null ? void 0 : _a2.max;
    if (unitMax && absDiff > unitMax)
      return fullDateFormatter(new Date(from2));
  }
  for (const [idx, unit] of units.entries()) {
    const val = getValue2(diff2, unit);
    if (val <= 0 && units[idx - 1])
      return format2(diff2, units[idx - 1]);
    if (absDiff < unit.max)
      return format2(diff2, unit);
  }
  return messages2.invalid;
}
__name(formatTimeAgo, "formatTimeAgo");
function useTimeoutPoll(fn, interval, timeoutPollOptions) {
  const { start: start2 } = useTimeoutFn(loop, interval, { immediate: false });
  const isActive2 = ref$3(false);
  async function loop() {
    if (!isActive2.value)
      return;
    await fn();
    start2();
  }
  __name(loop, "loop");
  function resume() {
    if (!isActive2.value) {
      isActive2.value = true;
      loop();
    }
  }
  __name(resume, "resume");
  function pause() {
    isActive2.value = false;
  }
  __name(pause, "pause");
  if (timeoutPollOptions == null ? void 0 : timeoutPollOptions.immediate)
    resume();
  tryOnScopeDispose(pause);
  return {
    isActive: isActive2,
    pause,
    resume
  };
}
__name(useTimeoutPoll, "useTimeoutPoll");
function useTimestamp(options2 = {}) {
  const {
    controls: exposeControls = false,
    offset = 0,
    immediate = true,
    interval = "requestAnimationFrame",
    callback
  } = options2;
  const ts2 = ref$3(timestamp() + offset);
  const update2 = /* @__PURE__ */ __name(() => ts2.value = timestamp() + offset, "update");
  const cb = callback ? () => {
    update2();
    callback(ts2.value);
  } : update2;
  const controls = interval === "requestAnimationFrame" ? useRafFn(cb, { immediate }) : useIntervalFn(cb, interval, { immediate });
  if (exposeControls) {
    return {
      timestamp: ts2,
      ...controls
    };
  } else {
    return ts2;
  }
}
__name(useTimestamp, "useTimestamp");
function useTitle(newTitle = null, options2 = {}) {
  var _a2, _b, _c;
  const {
    document: document2 = defaultDocument,
    restoreOnUnmount = /* @__PURE__ */ __name((t2) => t2, "restoreOnUnmount")
  } = options2;
  const originalTitle = (_a2 = document2 == null ? void 0 : document2.title) != null ? _a2 : "";
  const title = toRef((_b = newTitle != null ? newTitle : document2 == null ? void 0 : document2.title) != null ? _b : null);
  const isReadonly2 = newTitle && typeof newTitle === "function";
  function format2(t2) {
    if (!("titleTemplate" in options2))
      return t2;
    const template = options2.titleTemplate || "%s";
    return typeof template === "function" ? template(t2) : toValue$3(template).replace(/%s/g, t2);
  }
  __name(format2, "format");
  watch(
    title,
    (t2, o2) => {
      if (t2 !== o2 && document2)
        document2.title = format2(typeof t2 === "string" ? t2 : "");
    },
    { immediate: true }
  );
  if (options2.observe && !options2.titleTemplate && document2 && !isReadonly2) {
    useMutationObserver(
      (_c = document2.head) == null ? void 0 : _c.querySelector("title"),
      () => {
        if (document2 && document2.title !== title.value)
          title.value = format2(document2.title);
      },
      { childList: true }
    );
  }
  tryOnBeforeUnmount(() => {
    if (restoreOnUnmount) {
      const restoredTitle = restoreOnUnmount(originalTitle, title.value || "");
      if (restoredTitle != null && document2)
        document2.title = restoredTitle;
    }
  });
  return title;
}
__name(useTitle, "useTitle");
const _TransitionPresets = {
  easeInSine: [0.12, 0, 0.39, 0],
  easeOutSine: [0.61, 1, 0.88, 1],
  easeInOutSine: [0.37, 0, 0.63, 1],
  easeInQuad: [0.11, 0, 0.5, 0],
  easeOutQuad: [0.5, 1, 0.89, 1],
  easeInOutQuad: [0.45, 0, 0.55, 1],
  easeInCubic: [0.32, 0, 0.67, 0],
  easeOutCubic: [0.33, 1, 0.68, 1],
  easeInOutCubic: [0.65, 0, 0.35, 1],
  easeInQuart: [0.5, 0, 0.75, 0],
  easeOutQuart: [0.25, 1, 0.5, 1],
  easeInOutQuart: [0.76, 0, 0.24, 1],
  easeInQuint: [0.64, 0, 0.78, 0],
  easeOutQuint: [0.22, 1, 0.36, 1],
  easeInOutQuint: [0.83, 0, 0.17, 1],
  easeInExpo: [0.7, 0, 0.84, 0],
  easeOutExpo: [0.16, 1, 0.3, 1],
  easeInOutExpo: [0.87, 0, 0.13, 1],
  easeInCirc: [0.55, 0, 1, 0.45],
  easeOutCirc: [0, 0.55, 0.45, 1],
  easeInOutCirc: [0.85, 0, 0.15, 1],
  easeInBack: [0.36, 0, 0.66, -0.56],
  easeOutBack: [0.34, 1.56, 0.64, 1],
  easeInOutBack: [0.68, -0.6, 0.32, 1.6]
};
const TransitionPresets = /* @__PURE__ */ Object.assign({}, { linear: identity }, _TransitionPresets);
function createEasingFunction([p0, p1, p2, p3]) {
  const a2 = /* @__PURE__ */ __name((a1, a22) => 1 - 3 * a22 + 3 * a1, "a");
  const b2 = /* @__PURE__ */ __name((a1, a22) => 3 * a22 - 6 * a1, "b");
  const c2 = /* @__PURE__ */ __name((a1) => 3 * a1, "c");
  const calcBezier = /* @__PURE__ */ __name((t2, a1, a22) => ((a2(a1, a22) * t2 + b2(a1, a22)) * t2 + c2(a1)) * t2, "calcBezier");
  const getSlope = /* @__PURE__ */ __name((t2, a1, a22) => 3 * a2(a1, a22) * t2 * t2 + 2 * b2(a1, a22) * t2 + c2(a1), "getSlope");
  const getTforX = /* @__PURE__ */ __name((x2) => {
    let aGuessT = x2;
    for (let i2 = 0; i2 < 4; ++i2) {
      const currentSlope = getSlope(aGuessT, p0, p2);
      if (currentSlope === 0)
        return aGuessT;
      const currentX = calcBezier(aGuessT, p0, p2) - x2;
      aGuessT -= currentX / currentSlope;
    }
    return aGuessT;
  }, "getTforX");
  return (x2) => p0 === p1 && p2 === p3 ? x2 : calcBezier(getTforX(x2), p1, p3);
}
__name(createEasingFunction, "createEasingFunction");
function lerp(a2, b2, alpha2) {
  return a2 + alpha2 * (b2 - a2);
}
__name(lerp, "lerp");
function toVec(t2) {
  return (typeof t2 === "number" ? [t2] : t2) || [];
}
__name(toVec, "toVec");
function executeTransition(source, from2, to, options2 = {}) {
  var _a2, _b;
  const fromVal = toValue$3(from2);
  const toVal = toValue$3(to);
  const v1 = toVec(fromVal);
  const v2 = toVec(toVal);
  const duration = (_a2 = toValue$3(options2.duration)) != null ? _a2 : 1e3;
  const startedAt = Date.now();
  const endAt2 = Date.now() + duration;
  const trans = typeof options2.transition === "function" ? options2.transition : (_b = toValue$3(options2.transition)) != null ? _b : identity;
  const ease = typeof trans === "function" ? trans : createEasingFunction(trans);
  return new Promise((resolve2) => {
    source.value = fromVal;
    const tick = /* @__PURE__ */ __name(() => {
      var _a22;
      if ((_a22 = options2.abort) == null ? void 0 : _a22.call(options2)) {
        resolve2();
        return;
      }
      const now2 = Date.now();
      const alpha2 = ease((now2 - startedAt) / duration);
      const arr = toVec(source.value).map((n2, i2) => lerp(v1[i2], v2[i2], alpha2));
      if (Array.isArray(source.value))
        source.value = arr.map((n2, i2) => {
          var _a3, _b2;
          return lerp((_a3 = v1[i2]) != null ? _a3 : 0, (_b2 = v2[i2]) != null ? _b2 : 0, alpha2);
        });
      else if (typeof source.value === "number")
        source.value = arr[0];
      if (now2 < endAt2) {
        requestAnimationFrame(tick);
      } else {
        source.value = toVal;
        resolve2();
      }
    }, "tick");
    tick();
  });
}
__name(executeTransition, "executeTransition");
function useTransition(source, options2 = {}) {
  let currentId = 0;
  const sourceVal = /* @__PURE__ */ __name(() => {
    const v2 = toValue$3(source);
    return typeof v2 === "number" ? v2 : v2.map(toValue$3);
  }, "sourceVal");
  const outputRef = ref$3(sourceVal());
  watch(sourceVal, async (to) => {
    var _a2, _b;
    if (toValue$3(options2.disabled))
      return;
    const id2 = ++currentId;
    if (options2.delay)
      await promiseTimeout(toValue$3(options2.delay));
    if (id2 !== currentId)
      return;
    const toVal = Array.isArray(to) ? to.map(toValue$3) : toValue$3(to);
    (_a2 = options2.onStarted) == null ? void 0 : _a2.call(options2);
    await executeTransition(outputRef, outputRef.value, toVal, {
      ...options2,
      abort: /* @__PURE__ */ __name(() => {
        var _a22;
        return id2 !== currentId || ((_a22 = options2.abort) == null ? void 0 : _a22.call(options2));
      }, "abort")
    });
    (_b = options2.onFinished) == null ? void 0 : _b.call(options2);
  }, { deep: true });
  watch(() => toValue$3(options2.disabled), (disabled) => {
    if (disabled) {
      currentId++;
      outputRef.value = sourceVal();
    }
  });
  tryOnScopeDispose(() => {
    currentId++;
  });
  return computed(() => toValue$3(options2.disabled) ? sourceVal() : outputRef.value);
}
__name(useTransition, "useTransition");
function useUrlSearchParams(mode = "history", options2 = {}) {
  const {
    initialValue = {},
    removeNullishValues = true,
    removeFalsyValues = false,
    write: enableWrite = true,
    window: window2 = defaultWindow
  } = options2;
  if (!window2)
    return reactive(initialValue);
  const state = reactive({});
  function getRawParams() {
    if (mode === "history") {
      return window2.location.search || "";
    } else if (mode === "hash") {
      const hash = window2.location.hash || "";
      const index2 = hash.indexOf("?");
      return index2 > 0 ? hash.slice(index2) : "";
    } else {
      return (window2.location.hash || "").replace(/^#/, "");
    }
  }
  __name(getRawParams, "getRawParams");
  function constructQuery(params) {
    const stringified = params.toString();
    if (mode === "history")
      return `${stringified ? `?${stringified}` : ""}${window2.location.hash || ""}`;
    if (mode === "hash-params")
      return `${window2.location.search || ""}${stringified ? `#${stringified}` : ""}`;
    const hash = window2.location.hash || "#";
    const index2 = hash.indexOf("?");
    if (index2 > 0)
      return `${hash.slice(0, index2)}${stringified ? `?${stringified}` : ""}`;
    return `${hash}${stringified ? `?${stringified}` : ""}`;
  }
  __name(constructQuery, "constructQuery");
  function read2() {
    return new URLSearchParams(getRawParams());
  }
  __name(read2, "read");
  function updateState(params) {
    const unusedKeys = new Set(Object.keys(state));
    for (const key of params.keys()) {
      const paramsForKey = params.getAll(key);
      state[key] = paramsForKey.length > 1 ? paramsForKey : params.get(key) || "";
      unusedKeys.delete(key);
    }
    Array.from(unusedKeys).forEach((key) => delete state[key]);
  }
  __name(updateState, "updateState");
  const { pause, resume } = watchPausable(
    state,
    () => {
      const params = new URLSearchParams("");
      Object.keys(state).forEach((key) => {
        const mapEntry = state[key];
        if (Array.isArray(mapEntry))
          mapEntry.forEach((value) => params.append(key, value));
        else if (removeNullishValues && mapEntry == null)
          params.delete(key);
        else if (removeFalsyValues && !mapEntry)
          params.delete(key);
        else
          params.set(key, mapEntry);
      });
      write2(params);
    },
    { deep: true }
  );
  function write2(params, shouldUpdate) {
    pause();
    if (shouldUpdate)
      updateState(params);
    window2.history.replaceState(
      window2.history.state,
      window2.document.title,
      window2.location.pathname + constructQuery(params)
    );
    resume();
  }
  __name(write2, "write");
  function onChanged() {
    if (!enableWrite)
      return;
    write2(read2(), true);
  }
  __name(onChanged, "onChanged");
  useEventListener(window2, "popstate", onChanged, false);
  if (mode !== "history")
    useEventListener(window2, "hashchange", onChanged, false);
  const initial = read2();
  if (initial.keys().next().value)
    updateState(initial);
  else
    Object.assign(state, initialValue);
  return state;
}
__name(useUrlSearchParams, "useUrlSearchParams");
function useUserMedia(options2 = {}) {
  var _a2, _b;
  const enabled = ref$3((_a2 = options2.enabled) != null ? _a2 : false);
  const autoSwitch = ref$3((_b = options2.autoSwitch) != null ? _b : true);
  const constraints = ref$3(options2.constraints);
  const { navigator: navigator2 = defaultNavigator } = options2;
  const isSupported = useSupported(() => {
    var _a22;
    return (_a22 = navigator2 == null ? void 0 : navigator2.mediaDevices) == null ? void 0 : _a22.getUserMedia;
  });
  const stream = shallowRef();
  function getDeviceOptions(type) {
    switch (type) {
      case "video": {
        if (constraints.value)
          return constraints.value.video || false;
        break;
      }
      case "audio": {
        if (constraints.value)
          return constraints.value.audio || false;
        break;
      }
    }
  }
  __name(getDeviceOptions, "getDeviceOptions");
  async function _start() {
    if (!isSupported.value || stream.value)
      return;
    stream.value = await navigator2.mediaDevices.getUserMedia({
      video: getDeviceOptions("video"),
      audio: getDeviceOptions("audio")
    });
    return stream.value;
  }
  __name(_start, "_start");
  function _stop() {
    var _a22;
    (_a22 = stream.value) == null ? void 0 : _a22.getTracks().forEach((t2) => t2.stop());
    stream.value = void 0;
  }
  __name(_stop, "_stop");
  function stop2() {
    _stop();
    enabled.value = false;
  }
  __name(stop2, "stop");
  async function start2() {
    await _start();
    if (stream.value)
      enabled.value = true;
    return stream.value;
  }
  __name(start2, "start");
  async function restart() {
    _stop();
    return await start2();
  }
  __name(restart, "restart");
  watch(
    enabled,
    (v2) => {
      if (v2)
        _start();
      else _stop();
    },
    { immediate: true }
  );
  watch(
    constraints,
    () => {
      if (autoSwitch.value && stream.value)
        restart();
    },
    { immediate: true }
  );
  tryOnScopeDispose(() => {
    stop2();
  });
  return {
    isSupported,
    stream,
    start: start2,
    stop: stop2,
    restart,
    constraints,
    enabled,
    autoSwitch
  };
}
__name(useUserMedia, "useUserMedia");
function useVModel(props, key, emit, options2 = {}) {
  var _a2, _b, _c, _d, _e2;
  const {
    clone: clone2 = false,
    passive = false,
    eventName,
    deep = false,
    defaultValue,
    shouldEmit
  } = options2;
  const vm = getCurrentInstance();
  const _emit = emit || (vm == null ? void 0 : vm.emit) || ((_a2 = vm == null ? void 0 : vm.$emit) == null ? void 0 : _a2.bind(vm)) || ((_c = (_b = vm == null ? void 0 : vm.proxy) == null ? void 0 : _b.$emit) == null ? void 0 : _c.bind(vm == null ? void 0 : vm.proxy));
  let event = eventName;
  if (!key) {
    if (isVue2) {
      const modelOptions = (_e2 = (_d = vm == null ? void 0 : vm.proxy) == null ? void 0 : _d.$options) == null ? void 0 : _e2.model;
      key = (modelOptions == null ? void 0 : modelOptions.value) || "value";
      if (!eventName)
        event = (modelOptions == null ? void 0 : modelOptions.event) || "input";
    } else {
      key = "modelValue";
    }
  }
  event = event || `update:${key.toString()}`;
  const cloneFn = /* @__PURE__ */ __name((val) => !clone2 ? val : typeof clone2 === "function" ? clone2(val) : cloneFnJSON(val), "cloneFn");
  const getValue2 = /* @__PURE__ */ __name(() => isDef(props[key]) ? cloneFn(props[key]) : defaultValue, "getValue2");
  const triggerEmit = /* @__PURE__ */ __name((value) => {
    if (shouldEmit) {
      if (shouldEmit(value))
        _emit(event, value);
    } else {
      _emit(event, value);
    }
  }, "triggerEmit");
  if (passive) {
    const initialValue = getValue2();
    const proxy = ref$3(initialValue);
    let isUpdating = false;
    watch(
      () => props[key],
      (v2) => {
        if (!isUpdating) {
          isUpdating = true;
          proxy.value = cloneFn(v2);
          nextTick(() => isUpdating = false);
        }
      }
    );
    watch(
      proxy,
      (v2) => {
        if (!isUpdating && (v2 !== props[key] || deep))
          triggerEmit(v2);
      },
      { deep }
    );
    return proxy;
  } else {
    return computed({
      get() {
        return getValue2();
      },
      set(value) {
        triggerEmit(value);
      }
    });
  }
}
__name(useVModel, "useVModel");
function useVModels(props, emit, options2 = {}) {
  const ret = {};
  for (const key in props) {
    ret[key] = useVModel(
      props,
      key,
      emit,
      options2
    );
  }
  return ret;
}
__name(useVModels, "useVModels");
function useVibrate(options2) {
  const {
    pattern = [],
    interval = 0,
    navigator: navigator2 = defaultNavigator
  } = options2 || {};
  const isSupported = useSupported(() => typeof navigator2 !== "undefined" && "vibrate" in navigator2);
  const patternRef = toRef(pattern);
  let intervalControls;
  const vibrate = /* @__PURE__ */ __name((pattern2 = patternRef.value) => {
    if (isSupported.value)
      navigator2.vibrate(pattern2);
  }, "vibrate");
  const stop2 = /* @__PURE__ */ __name(() => {
    if (isSupported.value)
      navigator2.vibrate(0);
    intervalControls == null ? void 0 : intervalControls.pause();
  }, "stop");
  if (interval > 0) {
    intervalControls = useIntervalFn(
      vibrate,
      interval,
      {
        immediate: false,
        immediateCallback: false
      }
    );
  }
  return {
    isSupported,
    pattern,
    intervalControls,
    vibrate,
    stop: stop2
  };
}
__name(useVibrate, "useVibrate");
function useVirtualList(list2, options2) {
  const { containerStyle, wrapperProps, scrollTo: scrollTo2, calculateRange, currentList, containerRef } = "itemHeight" in options2 ? useVerticalVirtualList(options2, list2) : useHorizontalVirtualList(options2, list2);
  return {
    list: currentList,
    scrollTo: scrollTo2,
    containerProps: {
      ref: containerRef,
      onScroll: /* @__PURE__ */ __name(() => {
        calculateRange();
      }, "onScroll"),
      style: containerStyle
    },
    wrapperProps
  };
}
__name(useVirtualList, "useVirtualList");
function useVirtualListResources(list2) {
  const containerRef = ref$3(null);
  const size = useElementSize(containerRef);
  const currentList = ref$3([]);
  const source = shallowRef(list2);
  const state = ref$3({ start: 0, end: 10 });
  return { state, source, currentList, size, containerRef };
}
__name(useVirtualListResources, "useVirtualListResources");
function createGetViewCapacity(state, source, itemSize) {
  return (containerSize) => {
    if (typeof itemSize === "number")
      return Math.ceil(containerSize / itemSize);
    const { start: start2 = 0 } = state.value;
    let sum2 = 0;
    let capacity = 0;
    for (let i2 = start2; i2 < source.value.length; i2++) {
      const size = itemSize(i2);
      sum2 += size;
      capacity = i2;
      if (sum2 > containerSize)
        break;
    }
    return capacity - start2;
  };
}
__name(createGetViewCapacity, "createGetViewCapacity");
function createGetOffset(source, itemSize) {
  return (scrollDirection) => {
    if (typeof itemSize === "number")
      return Math.floor(scrollDirection / itemSize) + 1;
    let sum2 = 0;
    let offset = 0;
    for (let i2 = 0; i2 < source.value.length; i2++) {
      const size = itemSize(i2);
      sum2 += size;
      if (sum2 >= scrollDirection) {
        offset = i2;
        break;
      }
    }
    return offset + 1;
  };
}
__name(createGetOffset, "createGetOffset");
function createCalculateRange(type, overscan, getOffset2, getViewCapacity, { containerRef, state, currentList, source }) {
  return () => {
    const element = containerRef.value;
    if (element) {
      const offset = getOffset2(type === "vertical" ? element.scrollTop : element.scrollLeft);
      const viewCapacity = getViewCapacity(type === "vertical" ? element.clientHeight : element.clientWidth);
      const from2 = offset - overscan;
      const to = offset + viewCapacity + overscan;
      state.value = {
        start: from2 < 0 ? 0 : from2,
        end: to > source.value.length ? source.value.length : to
      };
      currentList.value = source.value.slice(state.value.start, state.value.end).map((ele, index2) => ({
        data: ele,
        index: index2 + state.value.start
      }));
    }
  };
}
__name(createCalculateRange, "createCalculateRange");
function createGetDistance(itemSize, source) {
  return (index2) => {
    if (typeof itemSize === "number") {
      const size2 = index2 * itemSize;
      return size2;
    }
    const size = source.value.slice(0, index2).reduce((sum2, _2, i2) => sum2 + itemSize(i2), 0);
    return size;
  };
}
__name(createGetDistance, "createGetDistance");
function useWatchForSizes(size, list2, containerRef, calculateRange) {
  watch([size.width, size.height, list2, containerRef], () => {
    calculateRange();
  });
}
__name(useWatchForSizes, "useWatchForSizes");
function createComputedTotalSize(itemSize, source) {
  return computed(() => {
    if (typeof itemSize === "number")
      return source.value.length * itemSize;
    return source.value.reduce((sum2, _2, index2) => sum2 + itemSize(index2), 0);
  });
}
__name(createComputedTotalSize, "createComputedTotalSize");
const scrollToDictionaryForElementScrollKey = {
  horizontal: "scrollLeft",
  vertical: "scrollTop"
};
function createScrollTo(type, calculateRange, getDistance, containerRef) {
  return (index2) => {
    if (containerRef.value) {
      containerRef.value[scrollToDictionaryForElementScrollKey[type]] = getDistance(index2);
      calculateRange();
    }
  };
}
__name(createScrollTo, "createScrollTo");
function useHorizontalVirtualList(options2, list2) {
  const resources = useVirtualListResources(list2);
  const { state, source, currentList, size, containerRef } = resources;
  const containerStyle = { overflowX: "auto" };
  const { itemWidth, overscan = 5 } = options2;
  const getViewCapacity = createGetViewCapacity(state, source, itemWidth);
  const getOffset2 = createGetOffset(source, itemWidth);
  const calculateRange = createCalculateRange("horizontal", overscan, getOffset2, getViewCapacity, resources);
  const getDistanceLeft = createGetDistance(itemWidth, source);
  const offsetLeft = computed(() => getDistanceLeft(state.value.start));
  const totalWidth = createComputedTotalSize(itemWidth, source);
  useWatchForSizes(size, list2, containerRef, calculateRange);
  const scrollTo2 = createScrollTo("horizontal", calculateRange, getDistanceLeft, containerRef);
  const wrapperProps = computed(() => {
    return {
      style: {
        height: "100%",
        width: `${totalWidth.value - offsetLeft.value}px`,
        marginLeft: `${offsetLeft.value}px`,
        display: "flex"
      }
    };
  });
  return {
    scrollTo: scrollTo2,
    calculateRange,
    wrapperProps,
    containerStyle,
    currentList,
    containerRef
  };
}
__name(useHorizontalVirtualList, "useHorizontalVirtualList");
function useVerticalVirtualList(options2, list2) {
  const resources = useVirtualListResources(list2);
  const { state, source, currentList, size, containerRef } = resources;
  const containerStyle = { overflowY: "auto" };
  const { itemHeight, overscan = 5 } = options2;
  const getViewCapacity = createGetViewCapacity(state, source, itemHeight);
  const getOffset2 = createGetOffset(source, itemHeight);
  const calculateRange = createCalculateRange("vertical", overscan, getOffset2, getViewCapacity, resources);
  const getDistanceTop = createGetDistance(itemHeight, source);
  const offsetTop = computed(() => getDistanceTop(state.value.start));
  const totalHeight = createComputedTotalSize(itemHeight, source);
  useWatchForSizes(size, list2, containerRef, calculateRange);
  const scrollTo2 = createScrollTo("vertical", calculateRange, getDistanceTop, containerRef);
  const wrapperProps = computed(() => {
    return {
      style: {
        width: "100%",
        height: `${totalHeight.value - offsetTop.value}px`,
        marginTop: `${offsetTop.value}px`
      }
    };
  });
  return {
    calculateRange,
    scrollTo: scrollTo2,
    containerStyle,
    wrapperProps,
    currentList,
    containerRef
  };
}
__name(useVerticalVirtualList, "useVerticalVirtualList");
function useWakeLock(options2 = {}) {
  const {
    navigator: navigator2 = defaultNavigator,
    document: document2 = defaultDocument
  } = options2;
  const requestedType = ref$3(false);
  const sentinel = shallowRef(null);
  const documentVisibility = useDocumentVisibility({ document: document2 });
  const isSupported = useSupported(() => navigator2 && "wakeLock" in navigator2);
  const isActive2 = computed(() => !!sentinel.value && documentVisibility.value === "visible");
  if (isSupported.value) {
    useEventListener(sentinel, "release", () => {
      var _a2, _b;
      requestedType.value = (_b = (_a2 = sentinel.value) == null ? void 0 : _a2.type) != null ? _b : false;
    });
    whenever(
      () => documentVisibility.value === "visible" && (document2 == null ? void 0 : document2.visibilityState) === "visible" && requestedType.value,
      (type) => {
        requestedType.value = false;
        forceRequest(type);
      }
    );
  }
  async function forceRequest(type) {
    var _a2;
    await ((_a2 = sentinel.value) == null ? void 0 : _a2.release());
    sentinel.value = isSupported.value ? await navigator2.wakeLock.request(type) : null;
  }
  __name(forceRequest, "forceRequest");
  async function request(type) {
    if (documentVisibility.value === "visible")
      await forceRequest(type);
    else
      requestedType.value = type;
  }
  __name(request, "request");
  async function release() {
    requestedType.value = false;
    const s2 = sentinel.value;
    sentinel.value = null;
    await (s2 == null ? void 0 : s2.release());
  }
  __name(release, "release");
  return {
    sentinel,
    isSupported,
    isActive: isActive2,
    request,
    forceRequest,
    release
  };
}
__name(useWakeLock, "useWakeLock");
function useWebNotification(options2 = {}) {
  const {
    window: window2 = defaultWindow,
    requestPermissions: _requestForPermissions = true
  } = options2;
  const defaultWebNotificationOptions = options2;
  const isSupported = useSupported(() => {
    if (!window2 || !("Notification" in window2))
      return false;
    try {
      new Notification("");
    } catch (e2) {
      return false;
    }
    return true;
  });
  const permissionGranted = ref$3(isSupported.value && "permission" in Notification && Notification.permission === "granted");
  const notification = ref$3(null);
  const ensurePermissions = /* @__PURE__ */ __name(async () => {
    if (!isSupported.value)
      return;
    if (!permissionGranted.value && Notification.permission !== "denied") {
      const result = await Notification.requestPermission();
      if (result === "granted")
        permissionGranted.value = true;
    }
    return permissionGranted.value;
  }, "ensurePermissions");
  const { on: onClick, trigger: clickTrigger } = createEventHook();
  const { on: onShow, trigger: showTrigger } = createEventHook();
  const { on: onError, trigger: errorTrigger } = createEventHook();
  const { on: onClose, trigger: closeTrigger } = createEventHook();
  const show = /* @__PURE__ */ __name(async (overrides) => {
    if (!isSupported.value || !permissionGranted.value)
      return;
    const options22 = Object.assign({}, defaultWebNotificationOptions, overrides);
    notification.value = new Notification(options22.title || "", options22);
    notification.value.onclick = clickTrigger;
    notification.value.onshow = showTrigger;
    notification.value.onerror = errorTrigger;
    notification.value.onclose = closeTrigger;
    return notification.value;
  }, "show");
  const close2 = /* @__PURE__ */ __name(() => {
    if (notification.value)
      notification.value.close();
    notification.value = null;
  }, "close");
  if (_requestForPermissions)
    tryOnMounted$2(ensurePermissions);
  tryOnScopeDispose(close2);
  if (isSupported.value && window2) {
    const document2 = window2.document;
    useEventListener(document2, "visibilitychange", (e2) => {
      e2.preventDefault();
      if (document2.visibilityState === "visible") {
        close2();
      }
    });
  }
  return {
    isSupported,
    notification,
    ensurePermissions,
    permissionGranted,
    show,
    close: close2,
    onClick,
    onShow,
    onError,
    onClose
  };
}
__name(useWebNotification, "useWebNotification");
const DEFAULT_PING_MESSAGE = "ping";
function resolveNestedOptions(options2) {
  if (options2 === true)
    return {};
  return options2;
}
__name(resolveNestedOptions, "resolveNestedOptions");
function useWebSocket(url, options2 = {}) {
  const {
    onConnected,
    onDisconnected,
    onError,
    onMessage,
    immediate = true,
    autoClose = true,
    protocols = []
  } = options2;
  const data = ref$3(null);
  const status = ref$3("CLOSED");
  const wsRef = ref$3();
  const urlRef = toRef(url);
  let heartbeatPause;
  let heartbeatResume;
  let explicitlyClosed = false;
  let retried = 0;
  let bufferedData = [];
  let pongTimeoutWait;
  const _sendBuffer = /* @__PURE__ */ __name(() => {
    if (bufferedData.length && wsRef.value && status.value === "OPEN") {
      for (const buffer of bufferedData)
        wsRef.value.send(buffer);
      bufferedData = [];
    }
  }, "_sendBuffer");
  const resetHeartbeat = /* @__PURE__ */ __name(() => {
    clearTimeout(pongTimeoutWait);
    pongTimeoutWait = void 0;
  }, "resetHeartbeat");
  const close2 = /* @__PURE__ */ __name((code2 = 1e3, reason) => {
    if (!isClient$1 || !wsRef.value)
      return;
    explicitlyClosed = true;
    resetHeartbeat();
    heartbeatPause == null ? void 0 : heartbeatPause();
    wsRef.value.close(code2, reason);
    wsRef.value = void 0;
  }, "close");
  const send = /* @__PURE__ */ __name((data2, useBuffer = true) => {
    if (!wsRef.value || status.value !== "OPEN") {
      if (useBuffer)
        bufferedData.push(data2);
      return false;
    }
    _sendBuffer();
    wsRef.value.send(data2);
    return true;
  }, "send");
  const _init = /* @__PURE__ */ __name(() => {
    if (explicitlyClosed || typeof urlRef.value === "undefined")
      return;
    const ws = new WebSocket(urlRef.value, protocols);
    wsRef.value = ws;
    status.value = "CONNECTING";
    ws.onopen = () => {
      status.value = "OPEN";
      onConnected == null ? void 0 : onConnected(ws);
      heartbeatResume == null ? void 0 : heartbeatResume();
      _sendBuffer();
    };
    ws.onclose = (ev) => {
      status.value = "CLOSED";
      onDisconnected == null ? void 0 : onDisconnected(ws, ev);
      if (!explicitlyClosed && options2.autoReconnect) {
        const {
          retries = -1,
          delay = 1e3,
          onFailed
        } = resolveNestedOptions(options2.autoReconnect);
        retried += 1;
        if (typeof retries === "number" && (retries < 0 || retried < retries))
          setTimeout(_init, delay);
        else if (typeof retries === "function" && retries())
          setTimeout(_init, delay);
        else
          onFailed == null ? void 0 : onFailed();
      }
    };
    ws.onerror = (e2) => {
      onError == null ? void 0 : onError(ws, e2);
    };
    ws.onmessage = (e2) => {
      if (options2.heartbeat) {
        resetHeartbeat();
        const {
          message = DEFAULT_PING_MESSAGE,
          responseMessage = message
        } = resolveNestedOptions(options2.heartbeat);
        if (e2.data === responseMessage)
          return;
      }
      data.value = e2.data;
      onMessage == null ? void 0 : onMessage(ws, e2);
    };
  }, "_init");
  if (options2.heartbeat) {
    const {
      message = DEFAULT_PING_MESSAGE,
      interval = 1e3,
      pongTimeout = 1e3
    } = resolveNestedOptions(options2.heartbeat);
    const { pause, resume } = useIntervalFn(
      () => {
        send(message, false);
        if (pongTimeoutWait != null)
          return;
        pongTimeoutWait = setTimeout(() => {
          close2();
          explicitlyClosed = false;
        }, pongTimeout);
      },
      interval,
      { immediate: false }
    );
    heartbeatPause = pause;
    heartbeatResume = resume;
  }
  if (autoClose) {
    if (isClient$1)
      useEventListener("beforeunload", () => close2());
    tryOnScopeDispose(close2);
  }
  const open2 = /* @__PURE__ */ __name(() => {
    if (!isClient$1 && !isWorker)
      return;
    close2();
    explicitlyClosed = false;
    retried = 0;
    _init();
  }, "open");
  if (immediate)
    open2();
  watch(urlRef, open2);
  return {
    data,
    status,
    close: close2,
    send,
    open: open2,
    ws: wsRef
  };
}
__name(useWebSocket, "useWebSocket");
function useWebWorker(arg0, workerOptions, options2) {
  const {
    window: window2 = defaultWindow
  } = options2 != null ? options2 : {};
  const data = ref$3(null);
  const worker = shallowRef();
  const post = /* @__PURE__ */ __name((...args) => {
    if (!worker.value)
      return;
    worker.value.postMessage(...args);
  }, "post");
  const terminate2 = /* @__PURE__ */ __name(function terminate22() {
    if (!worker.value)
      return;
    worker.value.terminate();
  }, "terminate2");
  if (window2) {
    if (typeof arg0 === "string")
      worker.value = new Worker(arg0, workerOptions);
    else if (typeof arg0 === "function")
      worker.value = arg0();
    else
      worker.value = arg0;
    worker.value.onmessage = (e2) => {
      data.value = e2.data;
    };
    tryOnScopeDispose(() => {
      if (worker.value)
        worker.value.terminate();
    });
  }
  return {
    data,
    post,
    terminate: terminate2,
    worker
  };
}
__name(useWebWorker, "useWebWorker");
function jobRunner(userFunc) {
  return (e2) => {
    const userFuncArgs = e2.data[0];
    return Promise.resolve(userFunc.apply(void 0, userFuncArgs)).then((result) => {
      postMessage(["SUCCESS", result]);
    }).catch((error2) => {
      postMessage(["ERROR", error2]);
    });
  };
}
__name(jobRunner, "jobRunner");
function depsParser(deps, localDeps) {
  if (deps.length === 0 && localDeps.length === 0)
    return "";
  const depsString = deps.map((dep) => `'${dep}'`).toString();
  const depsFunctionString = localDeps.filter((dep) => typeof dep === "function").map((fn) => {
    const str = fn.toString();
    if (str.trim().startsWith("function")) {
      return str;
    } else {
      const name2 = fn.name;
      return `const ${name2} = ${str}`;
    }
  }).join(";");
  const importString = `importScripts(${depsString});`;
  return `${depsString.trim() === "" ? "" : importString} ${depsFunctionString}`;
}
__name(depsParser, "depsParser");
function createWorkerBlobUrl(fn, deps, localDeps) {
  const blobCode = `${depsParser(deps, localDeps)}; onmessage=(${jobRunner})(${fn})`;
  const blob = new Blob([blobCode], { type: "text/javascript" });
  const url = URL.createObjectURL(blob);
  return url;
}
__name(createWorkerBlobUrl, "createWorkerBlobUrl");
function useWebWorkerFn(fn, options2 = {}) {
  const {
    dependencies = [],
    localDependencies = [],
    timeout,
    window: window2 = defaultWindow
  } = options2;
  const worker = ref$3();
  const workerStatus = ref$3("PENDING");
  const promise = ref$3({});
  const timeoutId = ref$3();
  const workerTerminate = /* @__PURE__ */ __name((status = "PENDING") => {
    if (worker.value && worker.value._url && window2) {
      worker.value.terminate();
      URL.revokeObjectURL(worker.value._url);
      promise.value = {};
      worker.value = void 0;
      window2.clearTimeout(timeoutId.value);
      workerStatus.value = status;
    }
  }, "workerTerminate");
  workerTerminate();
  tryOnScopeDispose(workerTerminate);
  const generateWorker = /* @__PURE__ */ __name(() => {
    const blobUrl = createWorkerBlobUrl(fn, dependencies, localDependencies);
    const newWorker = new Worker(blobUrl);
    newWorker._url = blobUrl;
    newWorker.onmessage = (e2) => {
      const { resolve: resolve2 = /* @__PURE__ */ __name(() => {
      }, "resolve"), reject = /* @__PURE__ */ __name(() => {
      }, "reject") } = promise.value;
      const [status, result] = e2.data;
      switch (status) {
        case "SUCCESS":
          resolve2(result);
          workerTerminate(status);
          break;
        default:
          reject(result);
          workerTerminate("ERROR");
          break;
      }
    };
    newWorker.onerror = (e2) => {
      const { reject = /* @__PURE__ */ __name(() => {
      }, "reject") } = promise.value;
      e2.preventDefault();
      reject(e2);
      workerTerminate("ERROR");
    };
    if (timeout) {
      timeoutId.value = setTimeout(
        () => workerTerminate("TIMEOUT_EXPIRED"),
        timeout
      );
    }
    return newWorker;
  }, "generateWorker");
  const callWorker = /* @__PURE__ */ __name((...fnArgs) => new Promise((resolve2, reject) => {
    var _a2;
    promise.value = {
      resolve: resolve2,
      reject
    };
    (_a2 = worker.value) == null ? void 0 : _a2.postMessage([[...fnArgs]]);
    workerStatus.value = "RUNNING";
  }), "callWorker");
  const workerFn = /* @__PURE__ */ __name((...fnArgs) => {
    if (workerStatus.value === "RUNNING") {
      console.error(
        "[useWebWorkerFn] You can only run one instance of the worker at a time."
      );
      return Promise.reject();
    }
    worker.value = generateWorker();
    return callWorker(...fnArgs);
  }, "workerFn");
  return {
    workerFn,
    workerStatus,
    workerTerminate
  };
}
__name(useWebWorkerFn, "useWebWorkerFn");
function useWindowFocus(options2 = {}) {
  const { window: window2 = defaultWindow } = options2;
  if (!window2)
    return ref$3(false);
  const focused = ref$3(window2.document.hasFocus());
  useEventListener(window2, "blur", () => {
    focused.value = false;
  });
  useEventListener(window2, "focus", () => {
    focused.value = true;
  });
  return focused;
}
__name(useWindowFocus, "useWindowFocus");
function useWindowScroll(options2 = {}) {
  const { window: window2 = defaultWindow, behavior = "auto" } = options2;
  if (!window2) {
    return {
      x: ref$3(0),
      y: ref$3(0)
    };
  }
  const internalX = ref$3(window2.scrollX);
  const internalY = ref$3(window2.scrollY);
  const x2 = computed({
    get() {
      return internalX.value;
    },
    set(x22) {
      scrollTo({ left: x22, behavior });
    }
  });
  const y2 = computed({
    get() {
      return internalY.value;
    },
    set(y22) {
      scrollTo({ top: y22, behavior });
    }
  });
  useEventListener(
    window2,
    "scroll",
    () => {
      internalX.value = window2.scrollX;
      internalY.value = window2.scrollY;
    },
    {
      capture: false,
      passive: true
    }
  );
  return { x: x2, y: y2 };
}
__name(useWindowScroll, "useWindowScroll");
function useWindowSize(options2 = {}) {
  const {
    window: window2 = defaultWindow,
    initialWidth = Number.POSITIVE_INFINITY,
    initialHeight = Number.POSITIVE_INFINITY,
    listenOrientation = true,
    includeScrollbar = true,
    type = "inner"
  } = options2;
  const width2 = ref$3(initialWidth);
  const height = ref$3(initialHeight);
  const update2 = /* @__PURE__ */ __name(() => {
    if (window2) {
      if (type === "outer") {
        width2.value = window2.outerWidth;
        height.value = window2.outerHeight;
      } else if (includeScrollbar) {
        width2.value = window2.innerWidth;
        height.value = window2.innerHeight;
      } else {
        width2.value = window2.document.documentElement.clientWidth;
        height.value = window2.document.documentElement.clientHeight;
      }
    }
  }, "update");
  update2();
  tryOnMounted$2(update2);
  useEventListener("resize", update2, { passive: true });
  if (listenOrientation) {
    const matches2 = useMediaQuery("(orientation: portrait)");
    watch(matches2, () => update2());
  }
  return { width: width2, height };
}
__name(useWindowSize, "useWindowSize");
const _hoisted_1$1w = { class: "w-full h-full overflow-hidden relative" };
const _sfc_main$1T = /* @__PURE__ */ defineComponent({
  __name: "LayoutDefault",
  setup(__props) {
    useFavicon("/assets/favicon.ico");
    return (_ctx, _cache) => {
      const _component_router_view = resolveComponent("router-view");
      return openBlock(), createElementBlock("main", _hoisted_1$1w, [
        createVNode(_component_router_view)
      ]);
    };
  }
});
"use strict";
function bind$3(fn, thisArg) {
  return /* @__PURE__ */ __name(function wrap2() {
    return fn.apply(thisArg, arguments);
  }, "wrap");
}
__name(bind$3, "bind$3");
"use strict";
const { toString: toString$1 } = Object.prototype;
const { getPrototypeOf } = Object;
const kindOf = /* @__PURE__ */ ((cache) => (thing) => {
  const str = toString$1.call(thing);
  return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
})(/* @__PURE__ */ Object.create(null));
const kindOfTest = /* @__PURE__ */ __name((type) => {
  type = type.toLowerCase();
  return (thing) => kindOf(thing) === type;
}, "kindOfTest");
const typeOfTest = /* @__PURE__ */ __name((type) => (thing) => typeof thing === type, "typeOfTest");
const { isArray: isArray$8 } = Array;
const isUndefined = typeOfTest("undefined");
function isBuffer$4(val) {
  return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && isFunction$9(val.constructor.isBuffer) && val.constructor.isBuffer(val);
}
__name(isBuffer$4, "isBuffer$4");
const isArrayBuffer = kindOfTest("ArrayBuffer");
function isArrayBufferView(val) {
  let result;
  if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView) {
    result = ArrayBuffer.isView(val);
  } else {
    result = val && val.buffer && isArrayBuffer(val.buffer);
  }
  return result;
}
__name(isArrayBufferView, "isArrayBufferView");
const isString$6 = typeOfTest("string");
const isFunction$9 = typeOfTest("function");
const isNumber$5 = typeOfTest("number");
const isObject$b = /* @__PURE__ */ __name((thing) => thing !== null && typeof thing === "object", "isObject$b");
const isBoolean$1 = /* @__PURE__ */ __name((thing) => thing === true || thing === false, "isBoolean$1");
const isPlainObject$1 = /* @__PURE__ */ __name((val) => {
  if (kindOf(val) !== "object") {
    return false;
  }
  const prototype2 = getPrototypeOf(val);
  return (prototype2 === null || prototype2 === Object.prototype || Object.getPrototypeOf(prototype2) === null) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val);
}, "isPlainObject$1");
const isDate$2 = kindOfTest("Date");
const isFile = kindOfTest("File");
const isBlob = kindOfTest("Blob");
const isFileList = kindOfTest("FileList");
const isStream = /* @__PURE__ */ __name((val) => isObject$b(val) && isFunction$9(val.pipe), "isStream");
const isFormData = /* @__PURE__ */ __name((thing) => {
  let kind;
  return thing && (typeof FormData === "function" && thing instanceof FormData || isFunction$9(thing.append) && ((kind = kindOf(thing)) === "formdata" || // detect form-data instance
  kind === "object" && isFunction$9(thing.toString) && thing.toString() === "[object FormData]"));
}, "isFormData");
const isURLSearchParams = kindOfTest("URLSearchParams");
const [isReadableStream, isRequest, isResponse, isHeaders] = ["ReadableStream", "Request", "Response", "Headers"].map(kindOfTest);
const trim = /* @__PURE__ */ __name((str) => str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ""), "trim");
function forEach$1(obj, fn, { allOwnKeys = false } = {}) {
  if (obj === null || typeof obj === "undefined") {
    return;
  }
  let i2;
  let l2;
  if (typeof obj !== "object") {
    obj = [obj];
  }
  if (isArray$8(obj)) {
    for (i2 = 0, l2 = obj.length; i2 < l2; i2++) {
      fn.call(null, obj[i2], i2, obj);
    }
  } else {
    const keys2 = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
    const len = keys2.length;
    let key;
    for (i2 = 0; i2 < len; i2++) {
      key = keys2[i2];
      fn.call(null, obj[key], key, obj);
    }
  }
}
__name(forEach$1, "forEach$1");
function findKey(obj, key) {
  key = key.toLowerCase();
  const keys2 = Object.keys(obj);
  let i2 = keys2.length;
  let _key;
  while (i2-- > 0) {
    _key = keys2[i2];
    if (key === _key.toLowerCase()) {
      return _key;
    }
  }
  return null;
}
__name(findKey, "findKey");
const _global = (() => {
  if (typeof globalThis !== "undefined") return globalThis;
  return typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : global;
})();
const isContextDefined = /* @__PURE__ */ __name((context) => !isUndefined(context) && context !== _global, "isContextDefined");
function merge$1() {
  const { caseless } = isContextDefined(this) && this || {};
  const result = {};
  const assignValue2 = /* @__PURE__ */ __name((val, key) => {
    const targetKey = caseless && findKey(result, key) || key;
    if (isPlainObject$1(result[targetKey]) && isPlainObject$1(val)) {
      result[targetKey] = merge$1(result[targetKey], val);
    } else if (isPlainObject$1(val)) {
      result[targetKey] = merge$1({}, val);
    } else if (isArray$8(val)) {
      result[targetKey] = val.slice();
    } else {
      result[targetKey] = val;
    }
  }, "assignValue");
  for (let i2 = 0, l2 = arguments.length; i2 < l2; i2++) {
    arguments[i2] && forEach$1(arguments[i2], assignValue2);
  }
  return result;
}
__name(merge$1, "merge$1");
const extend = /* @__PURE__ */ __name((a2, b2, thisArg, { allOwnKeys } = {}) => {
  forEach$1(b2, (val, key) => {
    if (thisArg && isFunction$9(val)) {
      a2[key] = bind$3(val, thisArg);
    } else {
      a2[key] = val;
    }
  }, { allOwnKeys });
  return a2;
}, "extend");
const stripBOM = /* @__PURE__ */ __name((content) => {
  if (content.charCodeAt(0) === 65279) {
    content = content.slice(1);
  }
  return content;
}, "stripBOM");
const inherits = /* @__PURE__ */ __name((constructor, superConstructor, props, descriptors2) => {
  constructor.prototype = Object.create(superConstructor.prototype, descriptors2);
  constructor.prototype.constructor = constructor;
  Object.defineProperty(constructor, "super", {
    value: superConstructor.prototype
  });
  props && Object.assign(constructor.prototype, props);
}, "inherits");
const toFlatObject = /* @__PURE__ */ __name((sourceObj, destObj, filter3, propFilter) => {
  let props;
  let i2;
  let prop2;
  const merged = {};
  destObj = destObj || {};
  if (sourceObj == null) return destObj;
  do {
    props = Object.getOwnPropertyNames(sourceObj);
    i2 = props.length;
    while (i2-- > 0) {
      prop2 = props[i2];
      if ((!propFilter || propFilter(prop2, sourceObj, destObj)) && !merged[prop2]) {
        destObj[prop2] = sourceObj[prop2];
        merged[prop2] = true;
      }
    }
    sourceObj = filter3 !== false && getPrototypeOf(sourceObj);
  } while (sourceObj && (!filter3 || filter3(sourceObj, destObj)) && sourceObj !== Object.prototype);
  return destObj;
}, "toFlatObject");
const endsWith = /* @__PURE__ */ __name((str, searchString, position) => {
  str = String(str);
  if (position === void 0 || position > str.length) {
    position = str.length;
  }
  position -= searchString.length;
  const lastIndex = str.indexOf(searchString, position);
  return lastIndex !== -1 && lastIndex === position;
}, "endsWith");
const toArray$1 = /* @__PURE__ */ __name((thing) => {
  if (!thing) return null;
  if (isArray$8(thing)) return thing;
  let i2 = thing.length;
  if (!isNumber$5(i2)) return null;
  const arr = new Array(i2);
  while (i2-- > 0) {
    arr[i2] = thing[i2];
  }
  return arr;
}, "toArray$1");
const isTypedArray$3 = /* @__PURE__ */ ((TypedArray) => {
  return (thing) => {
    return TypedArray && thing instanceof TypedArray;
  };
})(typeof Uint8Array !== "undefined" && getPrototypeOf(Uint8Array));
const forEachEntry = /* @__PURE__ */ __name((obj, fn) => {
  const generator = obj && obj[Symbol.iterator];
  const iterator = generator.call(obj);
  let result;
  while ((result = iterator.next()) && !result.done) {
    const pair = result.value;
    fn.call(obj, pair[0], pair[1]);
  }
}, "forEachEntry");
const matchAll = /* @__PURE__ */ __name((regExp, str) => {
  let matches2;
  const arr = [];
  while ((matches2 = regExp.exec(str)) !== null) {
    arr.push(matches2);
  }
  return arr;
}, "matchAll");
const isHTMLForm = kindOfTest("HTMLFormElement");
const toCamelCase = /* @__PURE__ */ __name((str) => {
  return str.toLowerCase().replace(
    /[-_\s]([a-z\d])(\w*)/g,
    /* @__PURE__ */ __name(function replacer(m2, p1, p2) {
      return p1.toUpperCase() + p2;
    }, "replacer")
  );
}, "toCamelCase");
const hasOwnProperty$a = (({ hasOwnProperty: hasOwnProperty2 }) => (obj, prop2) => hasOwnProperty2.call(obj, prop2))(Object.prototype);
const isRegExp$2 = kindOfTest("RegExp");
const reduceDescriptors = /* @__PURE__ */ __name((obj, reducer) => {
  const descriptors2 = Object.getOwnPropertyDescriptors(obj);
  const reducedDescriptors = {};
  forEach$1(descriptors2, (descriptor, name2) => {
    let ret;
    if ((ret = reducer(descriptor, name2, obj)) !== false) {
      reducedDescriptors[name2] = ret || descriptor;
    }
  });
  Object.defineProperties(obj, reducedDescriptors);
}, "reduceDescriptors");
const freezeMethods = /* @__PURE__ */ __name((obj) => {
  reduceDescriptors(obj, (descriptor, name2) => {
    if (isFunction$9(obj) && ["arguments", "caller", "callee"].indexOf(name2) !== -1) {
      return false;
    }
    const value = obj[name2];
    if (!isFunction$9(value)) return;
    descriptor.enumerable = false;
    if ("writable" in descriptor) {
      descriptor.writable = false;
      return;
    }
    if (!descriptor.set) {
      descriptor.set = () => {
        throw Error("Can not rewrite read-only method '" + name2 + "'");
      };
    }
  });
}, "freezeMethods");
const toObjectSet = /* @__PURE__ */ __name((arrayOrString, delimiter2) => {
  const obj = {};
  const define = /* @__PURE__ */ __name((arr) => {
    arr.forEach((value) => {
      obj[value] = true;
    });
  }, "define");
  isArray$8(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter2));
  return obj;
}, "toObjectSet");
const noop$1 = /* @__PURE__ */ __name(() => {
}, "noop$1");
const toFiniteNumber = /* @__PURE__ */ __name((value, defaultValue) => {
  return value != null && Number.isFinite(value = +value) ? value : defaultValue;
}, "toFiniteNumber");
function isSpecCompliantForm(thing) {
  return !!(thing && isFunction$9(thing.append) && thing[Symbol.toStringTag] === "FormData" && thing[Symbol.iterator]);
}
__name(isSpecCompliantForm, "isSpecCompliantForm");
const toJSONObject = /* @__PURE__ */ __name((obj) => {
  const stack = new Array(10);
  const visit2 = /* @__PURE__ */ __name((source, i2) => {
    if (isObject$b(source)) {
      if (stack.indexOf(source) >= 0) {
        return;
      }
      if (!("toJSON" in source)) {
        stack[i2] = source;
        const target = isArray$8(source) ? [] : {};
        forEach$1(source, (value, key) => {
          const reducedValue = visit2(value, i2 + 1);
          !isUndefined(reducedValue) && (target[key] = reducedValue);
        });
        stack[i2] = void 0;
        return target;
      }
    }
    return source;
  }, "visit");
  return visit2(obj, 0);
}, "toJSONObject");
const isAsyncFn = kindOfTest("AsyncFunction");
const isThenable = /* @__PURE__ */ __name((thing) => thing && (isObject$b(thing) || isFunction$9(thing)) && isFunction$9(thing.then) && isFunction$9(thing.catch), "isThenable");
const _setImmediate = ((setImmediateSupported, postMessageSupported) => {
  if (setImmediateSupported) {
    return setImmediate;
  }
  return postMessageSupported ? ((token, callbacks) => {
    _global.addEventListener("message", ({ source, data }) => {
      if (source === _global && data === token) {
        callbacks.length && callbacks.shift()();
      }
    }, false);
    return (cb) => {
      callbacks.push(cb);
      _global.postMessage(token, "*");
    };
  })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb);
})(
  typeof setImmediate === "function",
  isFunction$9(_global.postMessage)
);
const asap = typeof queueMicrotask !== "undefined" ? queueMicrotask.bind(_global) : typeof process !== "undefined" && process.nextTick || _setImmediate;
const utils$2 = {
  isArray: isArray$8,
  isArrayBuffer,
  isBuffer: isBuffer$4,
  isFormData,
  isArrayBufferView,
  isString: isString$6,
  isNumber: isNumber$5,
  isBoolean: isBoolean$1,
  isObject: isObject$b,
  isPlainObject: isPlainObject$1,
  isReadableStream,
  isRequest,
  isResponse,
  isHeaders,
  isUndefined,
  isDate: isDate$2,
  isFile,
  isBlob,
  isRegExp: isRegExp$2,
  isFunction: isFunction$9,
  isStream,
  isURLSearchParams,
  isTypedArray: isTypedArray$3,
  isFileList,
  forEach: forEach$1,
  merge: merge$1,
  extend,
  trim,
  stripBOM,
  inherits,
  toFlatObject,
  kindOf,
  kindOfTest,
  endsWith,
  toArray: toArray$1,
  forEachEntry,
  matchAll,
  isHTMLForm,
  hasOwnProperty: hasOwnProperty$a,
  hasOwnProp: hasOwnProperty$a,
  // an alias to avoid ESLint no-prototype-builtins detection
  reduceDescriptors,
  freezeMethods,
  toObjectSet,
  toCamelCase,
  noop: noop$1,
  toFiniteNumber,
  findKey,
  global: _global,
  isContextDefined,
  isSpecCompliantForm,
  toJSONObject,
  isAsyncFn,
  isThenable,
  setImmediate: _setImmediate,
  asap
};
"use strict";
function AxiosError$1(message, code2, config2, request, response) {
  Error.call(this);
  if (Error.captureStackTrace) {
    Error.captureStackTrace(this, this.constructor);
  } else {
    this.stack = new Error().stack;
  }
  this.message = message;
  this.name = "AxiosError";
  code2 && (this.code = code2);
  config2 && (this.config = config2);
  request && (this.request = request);
  if (response) {
    this.response = response;
    this.status = response.status ? response.status : null;
  }
}
__name(AxiosError$1, "AxiosError$1");
utils$2.inherits(AxiosError$1, Error, {
  toJSON: /* @__PURE__ */ __name(function toJSON() {
    return {
      // Standard
      message: this.message,
      name: this.name,
      // Microsoft
      description: this.description,
      number: this.number,
      // Mozilla
      fileName: this.fileName,
      lineNumber: this.lineNumber,
      columnNumber: this.columnNumber,
      stack: this.stack,
      // Axios
      config: utils$2.toJSONObject(this.config),
      code: this.code,
      status: this.status
    };
  }, "toJSON")
});
const prototype$1 = AxiosError$1.prototype;
const descriptors = {};
[
  "ERR_BAD_OPTION_VALUE",
  "ERR_BAD_OPTION",
  "ECONNABORTED",
  "ETIMEDOUT",
  "ERR_NETWORK",
  "ERR_FR_TOO_MANY_REDIRECTS",
  "ERR_DEPRECATED",
  "ERR_BAD_RESPONSE",
  "ERR_BAD_REQUEST",
  "ERR_CANCELED",
  "ERR_NOT_SUPPORT",
  "ERR_INVALID_URL"
  // eslint-disable-next-line func-names
].forEach((code2) => {
  descriptors[code2] = { value: code2 };
});
Object.defineProperties(AxiosError$1, descriptors);
Object.defineProperty(prototype$1, "isAxiosError", { value: true });
AxiosError$1.from = (error2, code2, config2, request, response, customProps) => {
  const axiosError = Object.create(prototype$1);
  utils$2.toFlatObject(error2, axiosError, /* @__PURE__ */ __name(function filter3(obj) {
    return obj !== Error.prototype;
  }, "filter"), (prop2) => {
    return prop2 !== "isAxiosError";
  });
  AxiosError$1.call(axiosError, error2.message, code2, config2, request, response);
  axiosError.cause = error2;
  axiosError.name = error2.name;
  customProps && Object.assign(axiosError, customProps);
  return axiosError;
};
const httpAdapter = null;
"use strict";
function isVisitable(thing) {
  return utils$2.isPlainObject(thing) || utils$2.isArray(thing);
}
__name(isVisitable, "isVisitable");
function removeBrackets(key) {
  return utils$2.endsWith(key, "[]") ? key.slice(0, -2) : key;
}
__name(removeBrackets, "removeBrackets");
function renderKey(path, key, dots) {
  if (!path) return key;
  return path.concat(key).map(/* @__PURE__ */ __name(function each2(token, i2) {
    token = removeBrackets(token);
    return !dots && i2 ? "[" + token + "]" : token;
  }, "each")).join(dots ? "." : "");
}
__name(renderKey, "renderKey");
function isFlatArray(arr) {
  return utils$2.isArray(arr) && !arr.some(isVisitable);
}
__name(isFlatArray, "isFlatArray");
const predicates = utils$2.toFlatObject(utils$2, {}, null, /* @__PURE__ */ __name(function filter2(prop2) {
  return /^is[A-Z]/.test(prop2);
}, "filter"));
function toFormData$1(obj, formData, options2) {
  if (!utils$2.isObject(obj)) {
    throw new TypeError("target must be an object");
  }
  formData = formData || new (httpAdapter || FormData)();
  options2 = utils$2.toFlatObject(options2, {
    metaTokens: true,
    dots: false,
    indexes: false
  }, false, /* @__PURE__ */ __name(function defined(option, source) {
    return !utils$2.isUndefined(source[option]);
  }, "defined"));
  const metaTokens = options2.metaTokens;
  const visitor = options2.visitor || defaultVisitor;
  const dots = options2.dots;
  const indexes = options2.indexes;
  const _Blob = options2.Blob || typeof Blob !== "undefined" && Blob;
  const useBlob = _Blob && utils$2.isSpecCompliantForm(formData);
  if (!utils$2.isFunction(visitor)) {
    throw new TypeError("visitor must be a function");
  }
  function convertValue(value) {
    if (value === null) return "";
    if (utils$2.isDate(value)) {
      return value.toISOString();
    }
    if (!useBlob && utils$2.isBlob(value)) {
      throw new AxiosError$1("Blob is not supported. Use a Buffer instead.");
    }
    if (utils$2.isArrayBuffer(value) || utils$2.isTypedArray(value)) {
      return useBlob && typeof Blob === "function" ? new Blob([value]) : Buffer.from(value);
    }
    return value;
  }
  __name(convertValue, "convertValue");
  function defaultVisitor(value, key, path) {
    let arr = value;
    if (value && !path && typeof value === "object") {
      if (utils$2.endsWith(key, "{}")) {
        key = metaTokens ? key : key.slice(0, -2);
        value = JSON.stringify(value);
      } else if (utils$2.isArray(value) && isFlatArray(value) || (utils$2.isFileList(value) || utils$2.endsWith(key, "[]")) && (arr = utils$2.toArray(value))) {
        key = removeBrackets(key);
        arr.forEach(/* @__PURE__ */ __name(function each2(el, index2) {
          !(utils$2.isUndefined(el) || el === null) && formData.append(
            // eslint-disable-next-line no-nested-ternary
            indexes === true ? renderKey([key], index2, dots) : indexes === null ? key : key + "[]",
            convertValue(el)
          );
        }, "each"));
        return false;
      }
    }
    if (isVisitable(value)) {
      return true;
    }
    formData.append(renderKey(path, key, dots), convertValue(value));
    return false;
  }
  __name(defaultVisitor, "defaultVisitor");
  const stack = [];
  const exposedHelpers = Object.assign(predicates, {
    defaultVisitor,
    convertValue,
    isVisitable
  });
  function build(value, path) {
    if (utils$2.isUndefined(value)) return;
    if (stack.indexOf(value) !== -1) {
      throw Error("Circular reference detected in " + path.join("."));
    }
    stack.push(value);
    utils$2.forEach(value, /* @__PURE__ */ __name(function each2(el, key) {
      const result = !(utils$2.isUndefined(el) || el === null) && visitor.call(
        formData,
        el,
        utils$2.isString(key) ? key.trim() : key,
        path,
        exposedHelpers
      );
      if (result === true) {
        build(el, path ? path.concat(key) : [key]);
      }
    }, "each"));
    stack.pop();
  }
  __name(build, "build");
  if (!utils$2.isObject(obj)) {
    throw new TypeError("data must be an object");
  }
  build(obj);
  return formData;
}
__name(toFormData$1, "toFormData$1");
"use strict";
function encode$4(str) {
  const charMap = {
    "!": "%21",
    "'": "%27",
    "(": "%28",
    ")": "%29",
    "~": "%7E",
    "%20": "+",
    "%00": "\0"
  };
  return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, /* @__PURE__ */ __name(function replacer(match2) {
    return charMap[match2];
  }, "replacer"));
}
__name(encode$4, "encode$4");
function AxiosURLSearchParams(params, options2) {
  this._pairs = [];
  params && toFormData$1(params, this, options2);
}
__name(AxiosURLSearchParams, "AxiosURLSearchParams");
const prototype = AxiosURLSearchParams.prototype;
prototype.append = /* @__PURE__ */ __name(function append(name2, value) {
  this._pairs.push([name2, value]);
}, "append");
prototype.toString = /* @__PURE__ */ __name(function toString2(encoder) {
  const _encode = encoder ? function(value) {
    return encoder.call(this, value, encode$4);
  } : encode$4;
  return this._pairs.map(/* @__PURE__ */ __name(function each2(pair) {
    return _encode(pair[0]) + "=" + _encode(pair[1]);
  }, "each"), "").join("&");
}, "toString");
"use strict";
function encode$3(val) {
  return encodeURIComponent(val).replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(/%20/g, "+").replace(/%5B/gi, "[").replace(/%5D/gi, "]");
}
__name(encode$3, "encode$3");
function buildURL(url, params, options2) {
  if (!params) {
    return url;
  }
  const _encode = options2 && options2.encode || encode$3;
  if (utils$2.isFunction(options2)) {
    options2 = {
      serialize: options2
    };
  }
  const serializeFn = options2 && options2.serialize;
  let serializedParams;
  if (serializeFn) {
    serializedParams = serializeFn(params, options2);
  } else {
    serializedParams = utils$2.isURLSearchParams(params) ? params.toString() : new AxiosURLSearchParams(params, options2).toString(_encode);
  }
  if (serializedParams) {
    const hashmarkIndex = url.indexOf("#");
    if (hashmarkIndex !== -1) {
      url = url.slice(0, hashmarkIndex);
    }
    url += (url.indexOf("?") === -1 ? "?" : "&") + serializedParams;
  }
  return url;
}
__name(buildURL, "buildURL");
"use strict";
class InterceptorManager {
  static {
    __name(this, "InterceptorManager");
  }
  constructor() {
    this.handlers = [];
  }
  /**
   * Add a new interceptor to the stack
   *
   * @param {Function} fulfilled The function to handle `then` for a `Promise`
   * @param {Function} rejected The function to handle `reject` for a `Promise`
   *
   * @return {Number} An ID used to remove interceptor later
   */
  use(fulfilled, rejected, options2) {
    this.handlers.push({
      fulfilled,
      rejected,
      synchronous: options2 ? options2.synchronous : false,
      runWhen: options2 ? options2.runWhen : null
    });
    return this.handlers.length - 1;
  }
  /**
   * Remove an interceptor from the stack
   *
   * @param {Number} id The ID that was returned by `use`
   *
   * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise
   */
  eject(id2) {
    if (this.handlers[id2]) {
      this.handlers[id2] = null;
    }
  }
  /**
   * Clear all interceptors from the stack
   *
   * @returns {void}
   */
  clear() {
    if (this.handlers) {
      this.handlers = [];
    }
  }
  /**
   * Iterate over all the registered interceptors
   *
   * This method is particularly useful for skipping over any
   * interceptors that may have become `null` calling `eject`.
   *
   * @param {Function} fn The function to call for each interceptor
   *
   * @returns {void}
   */
  forEach(fn) {
    utils$2.forEach(this.handlers, /* @__PURE__ */ __name(function forEachHandler(h2) {
      if (h2 !== null) {
        fn(h2);
      }
    }, "forEachHandler"));
  }
}
"use strict";
const transitionalDefaults = {
  silentJSONParsing: true,
  forcedJSONParsing: true,
  clarifyTimeoutError: false
};
"use strict";
const URLSearchParams$1 = typeof URLSearchParams !== "undefined" ? URLSearchParams : AxiosURLSearchParams;
"use strict";
const FormData$1 = typeof FormData !== "undefined" ? FormData : null;
"use strict";
const Blob$1 = typeof Blob !== "undefined" ? Blob : null;
const platform$1 = {
  isBrowser: true,
  classes: {
    URLSearchParams: URLSearchParams$1,
    FormData: FormData$1,
    Blob: Blob$1
  },
  protocols: ["http", "https", "file", "blob", "url", "data"]
};
const hasBrowserEnv = typeof window !== "undefined" && typeof document !== "undefined";
const _navigator = typeof navigator === "object" && navigator || void 0;
const hasStandardBrowserEnv = hasBrowserEnv && (!_navigator || ["ReactNative", "NativeScript", "NS"].indexOf(_navigator.product) < 0);
const hasStandardBrowserWebWorkerEnv = (() => {
  return typeof WorkerGlobalScope !== "undefined" && // eslint-disable-next-line no-undef
  self instanceof WorkerGlobalScope && typeof self.importScripts === "function";
})();
const origin = hasBrowserEnv && window.location.href || "http://localhost";
const utils$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  hasBrowserEnv,
  hasStandardBrowserEnv,
  hasStandardBrowserWebWorkerEnv,
  navigator: _navigator,
  origin
}, Symbol.toStringTag, { value: "Module" }));
const platform = {
  ...utils$1,
  ...platform$1
};
"use strict";
function toURLEncodedForm(data, options2) {
  return toFormData$1(data, new platform.classes.URLSearchParams(), Object.assign({
    visitor: /* @__PURE__ */ __name(function(value, key, path, helpers2) {
      if (platform.isNode && utils$2.isBuffer(value)) {
        this.append(key, value.toString("base64"));
        return false;
      }
      return helpers2.defaultVisitor.apply(this, arguments);
    }, "visitor")
  }, options2));
}
__name(toURLEncodedForm, "toURLEncodedForm");
"use strict";
function parsePropPath(name2) {
  return utils$2.matchAll(/\w+|\[(\w*)]/g, name2).map((match2) => {
    return match2[0] === "[]" ? "" : match2[1] || match2[0];
  });
}
__name(parsePropPath, "parsePropPath");
function arrayToObject(arr) {
  const obj = {};
  const keys2 = Object.keys(arr);
  let i2;
  const len = keys2.length;
  let key;
  for (i2 = 0; i2 < len; i2++) {
    key = keys2[i2];
    obj[key] = arr[key];
  }
  return obj;
}
__name(arrayToObject, "arrayToObject");
function formDataToJSON(formData) {
  function buildPath(path, value, target, index2) {
    let name2 = path[index2++];
    if (name2 === "__proto__") return true;
    const isNumericKey = Number.isFinite(+name2);
    const isLast = index2 >= path.length;
    name2 = !name2 && utils$2.isArray(target) ? target.length : name2;
    if (isLast) {
      if (utils$2.hasOwnProp(target, name2)) {
        target[name2] = [target[name2], value];
      } else {
        target[name2] = value;
      }
      return !isNumericKey;
    }
    if (!target[name2] || !utils$2.isObject(target[name2])) {
      target[name2] = [];
    }
    const result = buildPath(path, value, target[name2], index2);
    if (result && utils$2.isArray(target[name2])) {
      target[name2] = arrayToObject(target[name2]);
    }
    return !isNumericKey;
  }
  __name(buildPath, "buildPath");
  if (utils$2.isFormData(formData) && utils$2.isFunction(formData.entries)) {
    const obj = {};
    utils$2.forEachEntry(formData, (name2, value) => {
      buildPath(parsePropPath(name2), value, obj, 0);
    });
    return obj;
  }
  return null;
}
__name(formDataToJSON, "formDataToJSON");
"use strict";
function stringifySafely(rawValue, parser, encoder) {
  if (utils$2.isString(rawValue)) {
    try {
      (parser || JSON.parse)(rawValue);
      return utils$2.trim(rawValue);
    } catch (e2) {
      if (e2.name !== "SyntaxError") {
        throw e2;
      }
    }
  }
  return (encoder || JSON.stringify)(rawValue);
}
__name(stringifySafely, "stringifySafely");
const defaults$1 = {
  transitional: transitionalDefaults,
  adapter: ["xhr", "http", "fetch"],
  transformRequest: [/* @__PURE__ */ __name(function transformRequest(data, headers) {
    const contentType = headers.getContentType() || "";
    const hasJSONContentType = contentType.indexOf("application/json") > -1;
    const isObjectPayload = utils$2.isObject(data);
    if (isObjectPayload && utils$2.isHTMLForm(data)) {
      data = new FormData(data);
    }
    const isFormData2 = utils$2.isFormData(data);
    if (isFormData2) {
      return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;
    }
    if (utils$2.isArrayBuffer(data) || utils$2.isBuffer(data) || utils$2.isStream(data) || utils$2.isFile(data) || utils$2.isBlob(data) || utils$2.isReadableStream(data)) {
      return data;
    }
    if (utils$2.isArrayBufferView(data)) {
      return data.buffer;
    }
    if (utils$2.isURLSearchParams(data)) {
      headers.setContentType("application/x-www-form-urlencoded;charset=utf-8", false);
      return data.toString();
    }
    let isFileList2;
    if (isObjectPayload) {
      if (contentType.indexOf("application/x-www-form-urlencoded") > -1) {
        return toURLEncodedForm(data, this.formSerializer).toString();
      }
      if ((isFileList2 = utils$2.isFileList(data)) || contentType.indexOf("multipart/form-data") > -1) {
        const _FormData = this.env && this.env.FormData;
        return toFormData$1(
          isFileList2 ? { "files[]": data } : data,
          _FormData && new _FormData(),
          this.formSerializer
        );
      }
    }
    if (isObjectPayload || hasJSONContentType) {
      headers.setContentType("application/json", false);
      return stringifySafely(data);
    }
    return data;
  }, "transformRequest")],
  transformResponse: [/* @__PURE__ */ __name(function transformResponse(data) {
    const transitional2 = this.transitional || defaults$1.transitional;
    const forcedJSONParsing = transitional2 && transitional2.forcedJSONParsing;
    const JSONRequested = this.responseType === "json";
    if (utils$2.isResponse(data) || utils$2.isReadableStream(data)) {
      return data;
    }
    if (data && utils$2.isString(data) && (forcedJSONParsing && !this.responseType || JSONRequested)) {
      const silentJSONParsing = transitional2 && transitional2.silentJSONParsing;
      const strictJSONParsing = !silentJSONParsing && JSONRequested;
      try {
        return JSON.parse(data);
      } catch (e2) {
        if (strictJSONParsing) {
          if (e2.name === "SyntaxError") {
            throw AxiosError$1.from(e2, AxiosError$1.ERR_BAD_RESPONSE, this, null, this.response);
          }
          throw e2;
        }
      }
    }
    return data;
  }, "transformResponse")],
  /**
   * A timeout in milliseconds to abort a request. If set to 0 (default) a
   * timeout is not created.
   */
  timeout: 0,
  xsrfCookieName: "XSRF-TOKEN",
  xsrfHeaderName: "X-XSRF-TOKEN",
  maxContentLength: -1,
  maxBodyLength: -1,
  env: {
    FormData: platform.classes.FormData,
    Blob: platform.classes.Blob
  },
  validateStatus: /* @__PURE__ */ __name(function validateStatus(status) {
    return status >= 200 && status < 300;
  }, "validateStatus"),
  headers: {
    common: {
      "Accept": "application/json, text/plain, */*",
      "Content-Type": void 0
    }
  }
};
utils$2.forEach(["delete", "get", "head", "post", "put", "patch"], (method) => {
  defaults$1.headers[method] = {};
});
"use strict";
const ignoreDuplicateOf = utils$2.toObjectSet([
  "age",
  "authorization",
  "content-length",
  "content-type",
  "etag",
  "expires",
  "from",
  "host",
  "if-modified-since",
  "if-unmodified-since",
  "last-modified",
  "location",
  "max-forwards",
  "proxy-authorization",
  "referer",
  "retry-after",
  "user-agent"
]);
const parseHeaders = /* @__PURE__ */ __name((rawHeaders) => {
  const parsed = {};
  let key;
  let val;
  let i2;
  rawHeaders && rawHeaders.split("\n").forEach(/* @__PURE__ */ __name(function parser(line) {
    i2 = line.indexOf(":");
    key = line.substring(0, i2).trim().toLowerCase();
    val = line.substring(i2 + 1).trim();
    if (!key || parsed[key] && ignoreDuplicateOf[key]) {
      return;
    }
    if (key === "set-cookie") {
      if (parsed[key]) {
        parsed[key].push(val);
      } else {
        parsed[key] = [val];
      }
    } else {
      parsed[key] = parsed[key] ? parsed[key] + ", " + val : val;
    }
  }, "parser"));
  return parsed;
}, "parseHeaders");
"use strict";
const $internals = Symbol("internals");
function normalizeHeader(header) {
  return header && String(header).trim().toLowerCase();
}
__name(normalizeHeader, "normalizeHeader");
function normalizeValue(value) {
  if (value === false || value == null) {
    return value;
  }
  return utils$2.isArray(value) ? value.map(normalizeValue) : String(value);
}
__name(normalizeValue, "normalizeValue");
function parseTokens(str) {
  const tokens = /* @__PURE__ */ Object.create(null);
  const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
  let match2;
  while (match2 = tokensRE.exec(str)) {
    tokens[match2[1]] = match2[2];
  }
  return tokens;
}
__name(parseTokens, "parseTokens");
const isValidHeaderName = /* @__PURE__ */ __name((str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim()), "isValidHeaderName");
function matchHeaderValue(context, value, header, filter3, isHeaderNameFilter) {
  if (utils$2.isFunction(filter3)) {
    return filter3.call(this, value, header);
  }
  if (isHeaderNameFilter) {
    value = header;
  }
  if (!utils$2.isString(value)) return;
  if (utils$2.isString(filter3)) {
    return value.indexOf(filter3) !== -1;
  }
  if (utils$2.isRegExp(filter3)) {
    return filter3.test(value);
  }
}
__name(matchHeaderValue, "matchHeaderValue");
function formatHeader(header) {
  return header.trim().toLowerCase().replace(/([a-z\d])(\w*)/g, (w2, char, str) => {
    return char.toUpperCase() + str;
  });
}
__name(formatHeader, "formatHeader");
function buildAccessors(obj, header) {
  const accessorName = utils$2.toCamelCase(" " + header);
  ["get", "set", "has"].forEach((methodName) => {
    Object.defineProperty(obj, methodName + accessorName, {
      value: /* @__PURE__ */ __name(function(arg1, arg2, arg3) {
        return this[methodName].call(this, header, arg1, arg2, arg3);
      }, "value"),
      configurable: true
    });
  });
}
__name(buildAccessors, "buildAccessors");
let AxiosHeaders$1 = class AxiosHeaders2 {
  static {
    __name(this, "AxiosHeaders");
  }
  constructor(headers) {
    headers && this.set(headers);
  }
  set(header, valueOrRewrite, rewrite) {
    const self2 = this;
    function setHeader(_value, _header, _rewrite) {
      const lHeader = normalizeHeader(_header);
      if (!lHeader) {
        throw new Error("header name must be a non-empty string");
      }
      const key = utils$2.findKey(self2, lHeader);
      if (!key || self2[key] === void 0 || _rewrite === true || _rewrite === void 0 && self2[key] !== false) {
        self2[key || _header] = normalizeValue(_value);
      }
    }
    __name(setHeader, "setHeader");
    const setHeaders = /* @__PURE__ */ __name((headers, _rewrite) => utils$2.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite)), "setHeaders");
    if (utils$2.isPlainObject(header) || header instanceof this.constructor) {
      setHeaders(header, valueOrRewrite);
    } else if (utils$2.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
      setHeaders(parseHeaders(header), valueOrRewrite);
    } else if (utils$2.isHeaders(header)) {
      for (const [key, value] of header.entries()) {
        setHeader(value, key, rewrite);
      }
    } else {
      header != null && setHeader(valueOrRewrite, header, rewrite);
    }
    return this;
  }
  get(header, parser) {
    header = normalizeHeader(header);
    if (header) {
      const key = utils$2.findKey(this, header);
      if (key) {
        const value = this[key];
        if (!parser) {
          return value;
        }
        if (parser === true) {
          return parseTokens(value);
        }
        if (utils$2.isFunction(parser)) {
          return parser.call(this, value, key);
        }
        if (utils$2.isRegExp(parser)) {
          return parser.exec(value);
        }
        throw new TypeError("parser must be boolean|regexp|function");
      }
    }
  }
  has(header, matcher) {
    header = normalizeHeader(header);
    if (header) {
      const key = utils$2.findKey(this, header);
      return !!(key && this[key] !== void 0 && (!matcher || matchHeaderValue(this, this[key], key, matcher)));
    }
    return false;
  }
  delete(header, matcher) {
    const self2 = this;
    let deleted = false;
    function deleteHeader(_header) {
      _header = normalizeHeader(_header);
      if (_header) {
        const key = utils$2.findKey(self2, _header);
        if (key && (!matcher || matchHeaderValue(self2, self2[key], key, matcher))) {
          delete self2[key];
          deleted = true;
        }
      }
    }
    __name(deleteHeader, "deleteHeader");
    if (utils$2.isArray(header)) {
      header.forEach(deleteHeader);
    } else {
      deleteHeader(header);
    }
    return deleted;
  }
  clear(matcher) {
    const keys2 = Object.keys(this);
    let i2 = keys2.length;
    let deleted = false;
    while (i2--) {
      const key = keys2[i2];
      if (!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {
        delete this[key];
        deleted = true;
      }
    }
    return deleted;
  }
  normalize(format2) {
    const self2 = this;
    const headers = {};
    utils$2.forEach(this, (value, header) => {
      const key = utils$2.findKey(headers, header);
      if (key) {
        self2[key] = normalizeValue(value);
        delete self2[header];
        return;
      }
      const normalized = format2 ? formatHeader(header) : String(header).trim();
      if (normalized !== header) {
        delete self2[header];
      }
      self2[normalized] = normalizeValue(value);
      headers[normalized] = true;
    });
    return this;
  }
  concat(...targets) {
    return this.constructor.concat(this, ...targets);
  }
  toJSON(asStrings) {
    const obj = /* @__PURE__ */ Object.create(null);
    utils$2.forEach(this, (value, header) => {
      value != null && value !== false && (obj[header] = asStrings && utils$2.isArray(value) ? value.join(", ") : value);
    });
    return obj;
  }
  [Symbol.iterator]() {
    return Object.entries(this.toJSON())[Symbol.iterator]();
  }
  toString() {
    return Object.entries(this.toJSON()).map(([header, value]) => header + ": " + value).join("\n");
  }
  get [Symbol.toStringTag]() {
    return "AxiosHeaders";
  }
  static from(thing) {
    return thing instanceof this ? thing : new this(thing);
  }
  static concat(first2, ...targets) {
    const computed2 = new this(first2);
    targets.forEach((target) => computed2.set(target));
    return computed2;
  }
  static accessor(header) {
    const internals = this[$internals] = this[$internals] = {
      accessors: {}
    };
    const accessors = internals.accessors;
    const prototype2 = this.prototype;
    function defineAccessor(_header) {
      const lHeader = normalizeHeader(_header);
      if (!accessors[lHeader]) {
        buildAccessors(prototype2, _header);
        accessors[lHeader] = true;
      }
    }
    __name(defineAccessor, "defineAccessor");
    utils$2.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);
    return this;
  }
};
AxiosHeaders$1.accessor(["Content-Type", "Content-Length", "Accept", "Accept-Encoding", "User-Agent", "Authorization"]);
utils$2.reduceDescriptors(AxiosHeaders$1.prototype, ({ value }, key) => {
  let mapped = key[0].toUpperCase() + key.slice(1);
  return {
    get: /* @__PURE__ */ __name(() => value, "get"),
    set(headerValue) {
      this[mapped] = headerValue;
    }
  };
});
utils$2.freezeMethods(AxiosHeaders$1);
"use strict";
function transformData(fns, response) {
  const config2 = this || defaults$1;
  const context = response || config2;
  const headers = AxiosHeaders$1.from(context.headers);
  let data = context.data;
  utils$2.forEach(fns, /* @__PURE__ */ __name(function transform(fn) {
    data = fn.call(config2, data, headers.normalize(), response ? response.status : void 0);
  }, "transform"));
  headers.normalize();
  return data;
}
__name(transformData, "transformData");
"use strict";
function isCancel$1(value) {
  return !!(value && value.__CANCEL__);
}
__name(isCancel$1, "isCancel$1");
"use strict";
function CanceledError$1(message, config2, request) {
  AxiosError$1.call(this, message == null ? "canceled" : message, AxiosError$1.ERR_CANCELED, config2, request);
  this.name = "CanceledError";
}
__name(CanceledError$1, "CanceledError$1");
utils$2.inherits(CanceledError$1, AxiosError$1, {
  __CANCEL__: true
});
"use strict";
function settle(resolve2, reject, response) {
  const validateStatus2 = response.config.validateStatus;
  if (!response.status || !validateStatus2 || validateStatus2(response.status)) {
    resolve2(response);
  } else {
    reject(new AxiosError$1(
      "Request failed with status code " + response.status,
      [AxiosError$1.ERR_BAD_REQUEST, AxiosError$1.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],
      response.config,
      response.request,
      response
    ));
  }
}
__name(settle, "settle");
"use strict";
function parseProtocol(url) {
  const match2 = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
  return match2 && match2[1] || "";
}
__name(parseProtocol, "parseProtocol");
"use strict";
function speedometer(samplesCount, min) {
  samplesCount = samplesCount || 10;
  const bytes = new Array(samplesCount);
  const timestamps = new Array(samplesCount);
  let head = 0;
  let tail = 0;
  let firstSampleTS;
  min = min !== void 0 ? min : 1e3;
  return /* @__PURE__ */ __name(function push2(chunkLength) {
    const now2 = Date.now();
    const startedAt = timestamps[tail];
    if (!firstSampleTS) {
      firstSampleTS = now2;
    }
    bytes[head] = chunkLength;
    timestamps[head] = now2;
    let i2 = tail;
    let bytesCount = 0;
    while (i2 !== head) {
      bytesCount += bytes[i2++];
      i2 = i2 % samplesCount;
    }
    head = (head + 1) % samplesCount;
    if (head === tail) {
      tail = (tail + 1) % samplesCount;
    }
    if (now2 - firstSampleTS < min) {
      return;
    }
    const passed = startedAt && now2 - startedAt;
    return passed ? Math.round(bytesCount * 1e3 / passed) : void 0;
  }, "push");
}
__name(speedometer, "speedometer");
function throttle(fn, freq) {
  let timestamp2 = 0;
  let threshold = 1e3 / freq;
  let lastArgs;
  let timer;
  const invoke2 = /* @__PURE__ */ __name((args, now2 = Date.now()) => {
    timestamp2 = now2;
    lastArgs = null;
    if (timer) {
      clearTimeout(timer);
      timer = null;
    }
    fn.apply(null, args);
  }, "invoke");
  const throttled = /* @__PURE__ */ __name((...args) => {
    const now2 = Date.now();
    const passed = now2 - timestamp2;
    if (passed >= threshold) {
      invoke2(args, now2);
    } else {
      lastArgs = args;
      if (!timer) {
        timer = setTimeout(() => {
          timer = null;
          invoke2(lastArgs);
        }, threshold - passed);
      }
    }
  }, "throttled");
  const flush2 = /* @__PURE__ */ __name(() => lastArgs && invoke2(lastArgs), "flush");
  return [throttled, flush2];
}
__name(throttle, "throttle");
const progressEventReducer = /* @__PURE__ */ __name((listener, isDownloadStream, freq = 3) => {
  let bytesNotified = 0;
  const _speedometer = speedometer(50, 250);
  return throttle((e2) => {
    const loaded = e2.loaded;
    const total = e2.lengthComputable ? e2.total : void 0;
    const progressBytes = loaded - bytesNotified;
    const rate = _speedometer(progressBytes);
    const inRange = loaded <= total;
    bytesNotified = loaded;
    const data = {
      loaded,
      total,
      progress: total ? loaded / total : void 0,
      bytes: progressBytes,
      rate: rate ? rate : void 0,
      estimated: rate && total && inRange ? (total - loaded) / rate : void 0,
      event: e2,
      lengthComputable: total != null,
      [isDownloadStream ? "download" : "upload"]: true
    };
    listener(data);
  }, freq);
}, "progressEventReducer");
const progressEventDecorator = /* @__PURE__ */ __name((total, throttled) => {
  const lengthComputable = total != null;
  return [(loaded) => throttled[0]({
    lengthComputable,
    total,
    loaded
  }), throttled[1]];
}, "progressEventDecorator");
const asyncDecorator = /* @__PURE__ */ __name((fn) => (...args) => utils$2.asap(() => fn(...args)), "asyncDecorator");
const isURLSameOrigin = platform.hasStandardBrowserEnv ? /* @__PURE__ */ ((origin2, isMSIE) => (url) => {
  url = new URL(url, platform.origin);
  return origin2.protocol === url.protocol && origin2.host === url.host && (isMSIE || origin2.port === url.port);
})(
  new URL(platform.origin),
  platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent)
) : () => true;
const cookies = platform.hasStandardBrowserEnv ? (
  // Standard browser envs support document.cookie
  {
    write(name2, value, expires, path, domain2, secure) {
      const cookie = [name2 + "=" + encodeURIComponent(value)];
      utils$2.isNumber(expires) && cookie.push("expires=" + new Date(expires).toGMTString());
      utils$2.isString(path) && cookie.push("path=" + path);
      utils$2.isString(domain2) && cookie.push("domain=" + domain2);
      secure === true && cookie.push("secure");
      document.cookie = cookie.join("; ");
    },
    read(name2) {
      const match2 = document.cookie.match(new RegExp("(^|;\\s*)(" + name2 + ")=([^;]*)"));
      return match2 ? decodeURIComponent(match2[3]) : null;
    },
    remove(name2) {
      this.write(name2, "", Date.now() - 864e5);
    }
  }
) : (
  // Non-standard browser env (web workers, react-native) lack needed support.
  {
    write() {
    },
    read() {
      return null;
    },
    remove() {
    }
  }
);
"use strict";
function isAbsoluteURL(url) {
  return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
}
__name(isAbsoluteURL, "isAbsoluteURL");
"use strict";
function combineURLs(baseURL, relativeURL) {
  return relativeURL ? baseURL.replace(/\/?\/$/, "") + "/" + relativeURL.replace(/^\/+/, "") : baseURL;
}
__name(combineURLs, "combineURLs");
"use strict";
function buildFullPath(baseURL, requestedURL, allowAbsoluteUrls) {
  let isRelativeUrl = !isAbsoluteURL(requestedURL);
  if (baseURL && isRelativeUrl || allowAbsoluteUrls == false) {
    return combineURLs(baseURL, requestedURL);
  }
  return requestedURL;
}
__name(buildFullPath, "buildFullPath");
"use strict";
const headersToObject = /* @__PURE__ */ __name((thing) => thing instanceof AxiosHeaders$1 ? { ...thing } : thing, "headersToObject");
function mergeConfig$1(config1, config2) {
  config2 = config2 || {};
  const config3 = {};
  function getMergedValue(target, source, prop2, caseless) {
    if (utils$2.isPlainObject(target) && utils$2.isPlainObject(source)) {
      return utils$2.merge.call({ caseless }, target, source);
    } else if (utils$2.isPlainObject(source)) {
      return utils$2.merge({}, source);
    } else if (utils$2.isArray(source)) {
      return source.slice();
    }
    return source;
  }
  __name(getMergedValue, "getMergedValue");
  function mergeDeepProperties(a2, b2, prop2, caseless) {
    if (!utils$2.isUndefined(b2)) {
      return getMergedValue(a2, b2, prop2, caseless);
    } else if (!utils$2.isUndefined(a2)) {
      return getMergedValue(void 0, a2, prop2, caseless);
    }
  }
  __name(mergeDeepProperties, "mergeDeepProperties");
  function valueFromConfig2(a2, b2) {
    if (!utils$2.isUndefined(b2)) {
      return getMergedValue(void 0, b2);
    }
  }
  __name(valueFromConfig2, "valueFromConfig2");
  function defaultToConfig2(a2, b2) {
    if (!utils$2.isUndefined(b2)) {
      return getMergedValue(void 0, b2);
    } else if (!utils$2.isUndefined(a2)) {
      return getMergedValue(void 0, a2);
    }
  }
  __name(defaultToConfig2, "defaultToConfig2");
  function mergeDirectKeys(a2, b2, prop2) {
    if (prop2 in config2) {
      return getMergedValue(a2, b2);
    } else if (prop2 in config1) {
      return getMergedValue(void 0, a2);
    }
  }
  __name(mergeDirectKeys, "mergeDirectKeys");
  const mergeMap = {
    url: valueFromConfig2,
    method: valueFromConfig2,
    data: valueFromConfig2,
    baseURL: defaultToConfig2,
    transformRequest: defaultToConfig2,
    transformResponse: defaultToConfig2,
    paramsSerializer: defaultToConfig2,
    timeout: defaultToConfig2,
    timeoutMessage: defaultToConfig2,
    withCredentials: defaultToConfig2,
    withXSRFToken: defaultToConfig2,
    adapter: defaultToConfig2,
    responseType: defaultToConfig2,
    xsrfCookieName: defaultToConfig2,
    xsrfHeaderName: defaultToConfig2,
    onUploadProgress: defaultToConfig2,
    onDownloadProgress: defaultToConfig2,
    decompress: defaultToConfig2,
    maxContentLength: defaultToConfig2,
    maxBodyLength: defaultToConfig2,
    beforeRedirect: defaultToConfig2,
    transport: defaultToConfig2,
    httpAgent: defaultToConfig2,
    httpsAgent: defaultToConfig2,
    cancelToken: defaultToConfig2,
    socketPath: defaultToConfig2,
    responseEncoding: defaultToConfig2,
    validateStatus: mergeDirectKeys,
    headers: /* @__PURE__ */ __name((a2, b2, prop2) => mergeDeepProperties(headersToObject(a2), headersToObject(b2), prop2, true), "headers")
  };
  utils$2.forEach(Object.keys(Object.assign({}, config1, config2)), /* @__PURE__ */ __name(function computeConfigValue(prop2) {
    const merge2 = mergeMap[prop2] || mergeDeepProperties;
    const configValue = merge2(config1[prop2], config2[prop2], prop2);
    utils$2.isUndefined(configValue) && merge2 !== mergeDirectKeys || (config3[prop2] = configValue);
  }, "computeConfigValue"));
  return config3;
}
__name(mergeConfig$1, "mergeConfig$1");
const resolveConfig = /* @__PURE__ */ __name((config2) => {
  const newConfig = mergeConfig$1({}, config2);
  let { data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth: auth2 } = newConfig;
  newConfig.headers = headers = AxiosHeaders$1.from(headers);
  newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url), config2.params, config2.paramsSerializer);
  if (auth2) {
    headers.set(
      "Authorization",
      "Basic " + btoa((auth2.username || "") + ":" + (auth2.password ? unescape(encodeURIComponent(auth2.password)) : ""))
    );
  }
  let contentType;
  if (utils$2.isFormData(data)) {
    if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) {
      headers.setContentType(void 0);
    } else if ((contentType = headers.getContentType()) !== false) {
      const [type, ...tokens] = contentType ? contentType.split(";").map((token) => token.trim()).filter(Boolean) : [];
      headers.setContentType([type || "multipart/form-data", ...tokens].join("; "));
    }
  }
  if (platform.hasStandardBrowserEnv) {
    withXSRFToken && utils$2.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig));
    if (withXSRFToken || withXSRFToken !== false && isURLSameOrigin(newConfig.url)) {
      const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName);
      if (xsrfValue) {
        headers.set(xsrfHeaderName, xsrfValue);
      }
    }
  }
  return newConfig;
}, "resolveConfig");
const isXHRAdapterSupported = typeof XMLHttpRequest !== "undefined";
const xhrAdapter = isXHRAdapterSupported && function(config2) {
  return new Promise(/* @__PURE__ */ __name(function dispatchXhrRequest(resolve2, reject) {
    const _config = resolveConfig(config2);
    let requestData = _config.data;
    const requestHeaders = AxiosHeaders$1.from(_config.headers).normalize();
    let { responseType, onUploadProgress, onDownloadProgress } = _config;
    let onCanceled;
    let uploadThrottled, downloadThrottled;
    let flushUpload, flushDownload;
    function done() {
      flushUpload && flushUpload();
      flushDownload && flushDownload();
      _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled);
      _config.signal && _config.signal.removeEventListener("abort", onCanceled);
    }
    __name(done, "done");
    let request = new XMLHttpRequest();
    request.open(_config.method.toUpperCase(), _config.url, true);
    request.timeout = _config.timeout;
    function onloadend() {
      if (!request) {
        return;
      }
      const responseHeaders = AxiosHeaders$1.from(
        "getAllResponseHeaders" in request && request.getAllResponseHeaders()
      );
      const responseData = !responseType || responseType === "text" || responseType === "json" ? request.responseText : request.response;
      const response = {
        data: responseData,
        status: request.status,
        statusText: request.statusText,
        headers: responseHeaders,
        config: config2,
        request
      };
      settle(/* @__PURE__ */ __name(function _resolve(value) {
        resolve2(value);
        done();
      }, "_resolve"), /* @__PURE__ */ __name(function _reject(err) {
        reject(err);
        done();
      }, "_reject"), response);
      request = null;
    }
    __name(onloadend, "onloadend");
    if ("onloadend" in request) {
      request.onloadend = onloadend;
    } else {
      request.onreadystatechange = /* @__PURE__ */ __name(function handleLoad() {
        if (!request || request.readyState !== 4) {
          return;
        }
        if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf("file:") === 0)) {
          return;
        }
        setTimeout(onloadend);
      }, "handleLoad");
    }
    request.onabort = /* @__PURE__ */ __name(function handleAbort() {
      if (!request) {
        return;
      }
      reject(new AxiosError$1("Request aborted", AxiosError$1.ECONNABORTED, config2, request));
      request = null;
    }, "handleAbort");
    request.onerror = /* @__PURE__ */ __name(function handleError() {
      reject(new AxiosError$1("Network Error", AxiosError$1.ERR_NETWORK, config2, request));
      request = null;
    }, "handleError");
    request.ontimeout = /* @__PURE__ */ __name(function handleTimeout() {
      let timeoutErrorMessage = _config.timeout ? "timeout of " + _config.timeout + "ms exceeded" : "timeout exceeded";
      const transitional2 = _config.transitional || transitionalDefaults;
      if (_config.timeoutErrorMessage) {
        timeoutErrorMessage = _config.timeoutErrorMessage;
      }
      reject(new AxiosError$1(
        timeoutErrorMessage,
        transitional2.clarifyTimeoutError ? AxiosError$1.ETIMEDOUT : AxiosError$1.ECONNABORTED,
        config2,
        request
      ));
      request = null;
    }, "handleTimeout");
    requestData === void 0 && requestHeaders.setContentType(null);
    if ("setRequestHeader" in request) {
      utils$2.forEach(requestHeaders.toJSON(), /* @__PURE__ */ __name(function setRequestHeader(val, key) {
        request.setRequestHeader(key, val);
      }, "setRequestHeader"));
    }
    if (!utils$2.isUndefined(_config.withCredentials)) {
      request.withCredentials = !!_config.withCredentials;
    }
    if (responseType && responseType !== "json") {
      request.responseType = _config.responseType;
    }
    if (onDownloadProgress) {
      [downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true);
      request.addEventListener("progress", downloadThrottled);
    }
    if (onUploadProgress && request.upload) {
      [uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress);
      request.upload.addEventListener("progress", uploadThrottled);
      request.upload.addEventListener("loadend", flushUpload);
    }
    if (_config.cancelToken || _config.signal) {
      onCanceled = /* @__PURE__ */ __name((cancel) => {
        if (!request) {
          return;
        }
        reject(!cancel || cancel.type ? new CanceledError$1(null, config2, request) : cancel);
        request.abort();
        request = null;
      }, "onCanceled");
      _config.cancelToken && _config.cancelToken.subscribe(onCanceled);
      if (_config.signal) {
        _config.signal.aborted ? onCanceled() : _config.signal.addEventListener("abort", onCanceled);
      }
    }
    const protocol = parseProtocol(_config.url);
    if (protocol && platform.protocols.indexOf(protocol) === -1) {
      reject(new AxiosError$1("Unsupported protocol " + protocol + ":", AxiosError$1.ERR_BAD_REQUEST, config2));
      return;
    }
    request.send(requestData || null);
  }, "dispatchXhrRequest"));
};
const composeSignals = /* @__PURE__ */ __name((signals, timeout) => {
  const { length } = signals = signals ? signals.filter(Boolean) : [];
  if (timeout || length) {
    let controller = new AbortController();
    let aborted;
    const onabort = /* @__PURE__ */ __name(function(reason) {
      if (!aborted) {
        aborted = true;
        unsubscribe();
        const err = reason instanceof Error ? reason : this.reason;
        controller.abort(err instanceof AxiosError$1 ? err : new CanceledError$1(err instanceof Error ? err.message : err));
      }
    }, "onabort");
    let timer = timeout && setTimeout(() => {
      timer = null;
      onabort(new AxiosError$1(`timeout ${timeout} of ms exceeded`, AxiosError$1.ETIMEDOUT));
    }, timeout);
    const unsubscribe = /* @__PURE__ */ __name(() => {
      if (signals) {
        timer && clearTimeout(timer);
        timer = null;
        signals.forEach((signal2) => {
          signal2.unsubscribe ? signal2.unsubscribe(onabort) : signal2.removeEventListener("abort", onabort);
        });
        signals = null;
      }
    }, "unsubscribe");
    signals.forEach((signal2) => signal2.addEventListener("abort", onabort));
    const { signal } = controller;
    signal.unsubscribe = () => utils$2.asap(unsubscribe);
    return signal;
  }
}, "composeSignals");
const streamChunk = /* @__PURE__ */ __name(function* (chunk, chunkSize) {
  let len = chunk.byteLength;
  if (!chunkSize || len < chunkSize) {
    yield chunk;
    return;
  }
  let pos = 0;
  let end;
  while (pos < len) {
    end = pos + chunkSize;
    yield chunk.slice(pos, end);
    pos = end;
  }
}, "streamChunk");
const readBytes = /* @__PURE__ */ __name(async function* (iterable, chunkSize) {
  for await (const chunk of readStream(iterable)) {
    yield* streamChunk(chunk, chunkSize);
  }
}, "readBytes");
const readStream = /* @__PURE__ */ __name(async function* (stream) {
  if (stream[Symbol.asyncIterator]) {
    yield* stream;
    return;
  }
  const reader = stream.getReader();
  try {
    for (; ; ) {
      const { done, value } = await reader.read();
      if (done) {
        break;
      }
      yield value;
    }
  } finally {
    await reader.cancel();
  }
}, "readStream");
const trackStream = /* @__PURE__ */ __name((stream, chunkSize, onProgress, onFinish) => {
  const iterator = readBytes(stream, chunkSize);
  let bytes = 0;
  let done;
  let _onFinish = /* @__PURE__ */ __name((e2) => {
    if (!done) {
      done = true;
      onFinish && onFinish(e2);
    }
  }, "_onFinish");
  return new ReadableStream({
    async pull(controller) {
      try {
        const { done: done2, value } = await iterator.next();
        if (done2) {
          _onFinish();
          controller.close();
          return;
        }
        let len = value.byteLength;
        if (onProgress) {
          let loadedBytes = bytes += len;
          onProgress(loadedBytes);
        }
        controller.enqueue(new Uint8Array(value));
      } catch (err) {
        _onFinish(err);
        throw err;
      }
    },
    cancel(reason) {
      _onFinish(reason);
      return iterator.return();
    }
  }, {
    highWaterMark: 2
  });
}, "trackStream");
const isFetchSupported = typeof fetch === "function" && typeof Request === "function" && typeof Response === "function";
const isReadableStreamSupported = isFetchSupported && typeof ReadableStream === "function";
const encodeText = isFetchSupported && (typeof TextEncoder === "function" ? /* @__PURE__ */ ((encoder) => (str) => encoder.encode(str))(new TextEncoder()) : async (str) => new Uint8Array(await new Response(str).arrayBuffer()));
const test$1 = /* @__PURE__ */ __name((fn, ...args) => {
  try {
    return !!fn(...args);
  } catch (e2) {
    return false;
  }
}, "test$1");
const supportsRequestStream = isReadableStreamSupported && test$1(() => {
  let duplexAccessed = false;
  const hasContentType = new Request(platform.origin, {
    body: new ReadableStream(),
    method: "POST",
    get duplex() {
      duplexAccessed = true;
      return "half";
    }
  }).headers.has("Content-Type");
  return duplexAccessed && !hasContentType;
});
const DEFAULT_CHUNK_SIZE = 64 * 1024;
const supportsResponseStream = isReadableStreamSupported && test$1(() => utils$2.isReadableStream(new Response("").body));
const resolvers = {
  stream: supportsResponseStream && ((res) => res.body)
};
isFetchSupported && ((res) => {
  ["text", "arrayBuffer", "blob", "formData", "stream"].forEach((type) => {
    !resolvers[type] && (resolvers[type] = utils$2.isFunction(res[type]) ? (res2) => res2[type]() : (_2, config2) => {
      throw new AxiosError$1(`Response type '${type}' is not supported`, AxiosError$1.ERR_NOT_SUPPORT, config2);
    });
  });
})(new Response());
const getBodyLength = /* @__PURE__ */ __name(async (body) => {
  if (body == null) {
    return 0;
  }
  if (utils$2.isBlob(body)) {
    return body.size;
  }
  if (utils$2.isSpecCompliantForm(body)) {
    const _request = new Request(platform.origin, {
      method: "POST",
      body
    });
    return (await _request.arrayBuffer()).byteLength;
  }
  if (utils$2.isArrayBufferView(body) || utils$2.isArrayBuffer(body)) {
    return body.byteLength;
  }
  if (utils$2.isURLSearchParams(body)) {
    body = body + "";
  }
  if (utils$2.isString(body)) {
    return (await encodeText(body)).byteLength;
  }
}, "getBodyLength");
const resolveBodyLength = /* @__PURE__ */ __name(async (headers, body) => {
  const length = utils$2.toFiniteNumber(headers.getContentLength());
  return length == null ? getBodyLength(body) : length;
}, "resolveBodyLength");
const fetchAdapter = isFetchSupported && (async (config2) => {
  let {
    url,
    method,
    data,
    signal,
    cancelToken,
    timeout,
    onDownloadProgress,
    onUploadProgress,
    responseType,
    headers,
    withCredentials = "same-origin",
    fetchOptions
  } = resolveConfig(config2);
  responseType = responseType ? (responseType + "").toLowerCase() : "text";
  let composedSignal = composeSignals([signal, cancelToken && cancelToken.toAbortSignal()], timeout);
  let request;
  const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => {
    composedSignal.unsubscribe();
  });
  let requestContentLength;
  try {
    if (onUploadProgress && supportsRequestStream && method !== "get" && method !== "head" && (requestContentLength = await resolveBodyLength(headers, data)) !== 0) {
      let _request = new Request(url, {
        method: "POST",
        body: data,
        duplex: "half"
      });
      let contentTypeHeader;
      if (utils$2.isFormData(data) && (contentTypeHeader = _request.headers.get("content-type"))) {
        headers.setContentType(contentTypeHeader);
      }
      if (_request.body) {
        const [onProgress, flush2] = progressEventDecorator(
          requestContentLength,
          progressEventReducer(asyncDecorator(onUploadProgress))
        );
        data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush2);
      }
    }
    if (!utils$2.isString(withCredentials)) {
      withCredentials = withCredentials ? "include" : "omit";
    }
    const isCredentialsSupported = "credentials" in Request.prototype;
    request = new Request(url, {
      ...fetchOptions,
      signal: composedSignal,
      method: method.toUpperCase(),
      headers: headers.normalize().toJSON(),
      body: data,
      duplex: "half",
      credentials: isCredentialsSupported ? withCredentials : void 0
    });
    let response = await fetch(request);
    const isStreamResponse = supportsResponseStream && (responseType === "stream" || responseType === "response");
    if (supportsResponseStream && (onDownloadProgress || isStreamResponse && unsubscribe)) {
      const options2 = {};
      ["status", "statusText", "headers"].forEach((prop2) => {
        options2[prop2] = response[prop2];
      });
      const responseContentLength = utils$2.toFiniteNumber(response.headers.get("content-length"));
      const [onProgress, flush2] = onDownloadProgress && progressEventDecorator(
        responseContentLength,
        progressEventReducer(asyncDecorator(onDownloadProgress), true)
      ) || [];
      response = new Response(
        trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => {
          flush2 && flush2();
          unsubscribe && unsubscribe();
        }),
        options2
      );
    }
    responseType = responseType || "text";
    let responseData = await resolvers[utils$2.findKey(resolvers, responseType) || "text"](response, config2);
    !isStreamResponse && unsubscribe && unsubscribe();
    return await new Promise((resolve2, reject) => {
      settle(resolve2, reject, {
        data: responseData,
        headers: AxiosHeaders$1.from(response.headers),
        status: response.status,
        statusText: response.statusText,
        config: config2,
        request
      });
    });
  } catch (err) {
    unsubscribe && unsubscribe();
    if (err && err.name === "TypeError" && /fetch/i.test(err.message)) {
      throw Object.assign(
        new AxiosError$1("Network Error", AxiosError$1.ERR_NETWORK, config2, request),
        {
          cause: err.cause || err
        }
      );
    }
    throw AxiosError$1.from(err, err && err.code, config2, request);
  }
});
const knownAdapters = {
  http: httpAdapter,
  xhr: xhrAdapter,
  fetch: fetchAdapter
};
utils$2.forEach(knownAdapters, (fn, value) => {
  if (fn) {
    try {
      Object.defineProperty(fn, "name", { value });
    } catch (e2) {
    }
    Object.defineProperty(fn, "adapterName", { value });
  }
});
const renderReason = /* @__PURE__ */ __name((reason) => `- ${reason}`, "renderReason");
const isResolvedHandle = /* @__PURE__ */ __name((adapter2) => utils$2.isFunction(adapter2) || adapter2 === null || adapter2 === false, "isResolvedHandle");
const adapters = {
  getAdapter: /* @__PURE__ */ __name((adapters2) => {
    adapters2 = utils$2.isArray(adapters2) ? adapters2 : [adapters2];
    const { length } = adapters2;
    let nameOrAdapter;
    let adapter2;
    const rejectedReasons = {};
    for (let i2 = 0; i2 < length; i2++) {
      nameOrAdapter = adapters2[i2];
      let id2;
      adapter2 = nameOrAdapter;
      if (!isResolvedHandle(nameOrAdapter)) {
        adapter2 = knownAdapters[(id2 = String(nameOrAdapter)).toLowerCase()];
        if (adapter2 === void 0) {
          throw new AxiosError$1(`Unknown adapter '${id2}'`);
        }
      }
      if (adapter2) {
        break;
      }
      rejectedReasons[id2 || "#" + i2] = adapter2;
    }
    if (!adapter2) {
      const reasons = Object.entries(rejectedReasons).map(
        ([id2, state]) => `adapter ${id2} ` + (state === false ? "is not supported by the environment" : "is not available in the build")
      );
      let s2 = length ? reasons.length > 1 ? "since :\n" + reasons.map(renderReason).join("\n") : " " + renderReason(reasons[0]) : "as no adapter specified";
      throw new AxiosError$1(
        `There is no suitable adapter to dispatch the request ` + s2,
        "ERR_NOT_SUPPORT"
      );
    }
    return adapter2;
  }, "getAdapter"),
  adapters: knownAdapters
};
"use strict";
function throwIfCancellationRequested(config2) {
  if (config2.cancelToken) {
    config2.cancelToken.throwIfRequested();
  }
  if (config2.signal && config2.signal.aborted) {
    throw new CanceledError$1(null, config2);
  }
}
__name(throwIfCancellationRequested, "throwIfCancellationRequested");
function dispatchRequest(config2) {
  throwIfCancellationRequested(config2);
  config2.headers = AxiosHeaders$1.from(config2.headers);
  config2.data = transformData.call(
    config2,
    config2.transformRequest
  );
  if (["post", "put", "patch"].indexOf(config2.method) !== -1) {
    config2.headers.setContentType("application/x-www-form-urlencoded", false);
  }
  const adapter2 = adapters.getAdapter(config2.adapter || defaults$1.adapter);
  return adapter2(config2).then(/* @__PURE__ */ __name(function onAdapterResolution(response) {
    throwIfCancellationRequested(config2);
    response.data = transformData.call(
      config2,
      config2.transformResponse,
      response
    );
    response.headers = AxiosHeaders$1.from(response.headers);
    return response;
  }, "onAdapterResolution"), /* @__PURE__ */ __name(function onAdapterRejection(reason) {
    if (!isCancel$1(reason)) {
      throwIfCancellationRequested(config2);
      if (reason && reason.response) {
        reason.response.data = transformData.call(
          config2,
          config2.transformResponse,
          reason.response
        );
        reason.response.headers = AxiosHeaders$1.from(reason.response.headers);
      }
    }
    return Promise.reject(reason);
  }, "onAdapterRejection"));
}
__name(dispatchRequest, "dispatchRequest");
const VERSION$1 = "1.8.2";
"use strict";
const validators$1 = {};
["object", "boolean", "number", "function", "string", "symbol"].forEach((type, i2) => {
  validators$1[type] = /* @__PURE__ */ __name(function validator2(thing) {
    return typeof thing === type || "a" + (i2 < 1 ? "n " : " ") + type;
  }, "validator");
});
const deprecatedWarnings = {};
validators$1.transitional = /* @__PURE__ */ __name(function transitional(validator2, version2, message) {
  function formatMessage(opt, desc) {
    return "[Axios v" + VERSION$1 + "] Transitional option '" + opt + "'" + desc + (message ? ". " + message : "");
  }
  __name(formatMessage, "formatMessage");
  return (value, opt, opts) => {
    if (validator2 === false) {
      throw new AxiosError$1(
        formatMessage(opt, " has been removed" + (version2 ? " in " + version2 : "")),
        AxiosError$1.ERR_DEPRECATED
      );
    }
    if (version2 && !deprecatedWarnings[opt]) {
      deprecatedWarnings[opt] = true;
      console.warn(
        formatMessage(
          opt,
          " has been deprecated since v" + version2 + " and will be removed in the near future"
        )
      );
    }
    return validator2 ? validator2(value, opt, opts) : true;
  };
}, "transitional");
validators$1.spelling = /* @__PURE__ */ __name(function spelling(correctSpelling) {
  return (value, opt) => {
    console.warn(`${opt} is likely a misspelling of ${correctSpelling}`);
    return true;
  };
}, "spelling");
function assertOptions(options2, schema2, allowUnknown) {
  if (typeof options2 !== "object") {
    throw new AxiosError$1("options must be an object", AxiosError$1.ERR_BAD_OPTION_VALUE);
  }
  const keys2 = Object.keys(options2);
  let i2 = keys2.length;
  while (i2-- > 0) {
    const opt = keys2[i2];
    const validator2 = schema2[opt];
    if (validator2) {
      const value = options2[opt];
      const result = value === void 0 || validator2(value, opt, options2);
      if (result !== true) {
        throw new AxiosError$1("option " + opt + " must be " + result, AxiosError$1.ERR_BAD_OPTION_VALUE);
      }
      continue;
    }
    if (allowUnknown !== true) {
      throw new AxiosError$1("Unknown option " + opt, AxiosError$1.ERR_BAD_OPTION);
    }
  }
}
__name(assertOptions, "assertOptions");
const validator = {
  assertOptions,
  validators: validators$1
};
"use strict";
const validators = validator.validators;
let Axios$1 = class Axios2 {
  static {
    __name(this, "Axios");
  }
  constructor(instanceConfig) {
    this.defaults = instanceConfig;
    this.interceptors = {
      request: new InterceptorManager(),
      response: new InterceptorManager()
    };
  }
  /**
   * Dispatch a request
   *
   * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)
   * @param {?Object} config
   *
   * @returns {Promise} The Promise to be fulfilled
   */
  async request(configOrUrl, config2) {
    try {
      return await this._request(configOrUrl, config2);
    } catch (err) {
      if (err instanceof Error) {
        let dummy = {};
        Error.captureStackTrace ? Error.captureStackTrace(dummy) : dummy = new Error();
        const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, "") : "";
        try {
          if (!err.stack) {
            err.stack = stack;
          } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ""))) {
            err.stack += "\n" + stack;
          }
        } catch (e2) {
        }
      }
      throw err;
    }
  }
  _request(configOrUrl, config2) {
    if (typeof configOrUrl === "string") {
      config2 = config2 || {};
      config2.url = configOrUrl;
    } else {
      config2 = configOrUrl || {};
    }
    config2 = mergeConfig$1(this.defaults, config2);
    const { transitional: transitional2, paramsSerializer, headers } = config2;
    if (transitional2 !== void 0) {
      validator.assertOptions(transitional2, {
        silentJSONParsing: validators.transitional(validators.boolean),
        forcedJSONParsing: validators.transitional(validators.boolean),
        clarifyTimeoutError: validators.transitional(validators.boolean)
      }, false);
    }
    if (paramsSerializer != null) {
      if (utils$2.isFunction(paramsSerializer)) {
        config2.paramsSerializer = {
          serialize: paramsSerializer
        };
      } else {
        validator.assertOptions(paramsSerializer, {
          encode: validators.function,
          serialize: validators.function
        }, true);
      }
    }
    if (config2.allowAbsoluteUrls !== void 0) {
    } else if (this.defaults.allowAbsoluteUrls !== void 0) {
      config2.allowAbsoluteUrls = this.defaults.allowAbsoluteUrls;
    } else {
      config2.allowAbsoluteUrls = true;
    }
    validator.assertOptions(config2, {
      baseUrl: validators.spelling("baseURL"),
      withXsrfToken: validators.spelling("withXSRFToken")
    }, true);
    config2.method = (config2.method || this.defaults.method || "get").toLowerCase();
    let contextHeaders = headers && utils$2.merge(
      headers.common,
      headers[config2.method]
    );
    headers && utils$2.forEach(
      ["delete", "get", "head", "post", "put", "patch", "common"],
      (method) => {
        delete headers[method];
      }
    );
    config2.headers = AxiosHeaders$1.concat(contextHeaders, headers);
    const requestInterceptorChain = [];
    let synchronousRequestInterceptors = true;
    this.interceptors.request.forEach(/* @__PURE__ */ __name(function unshiftRequestInterceptors(interceptor) {
      if (typeof interceptor.runWhen === "function" && interceptor.runWhen(config2) === false) {
        return;
      }
      synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
      requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
    }, "unshiftRequestInterceptors"));
    const responseInterceptorChain = [];
    this.interceptors.response.forEach(/* @__PURE__ */ __name(function pushResponseInterceptors(interceptor) {
      responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
    }, "pushResponseInterceptors"));
    let promise;
    let i2 = 0;
    let len;
    if (!synchronousRequestInterceptors) {
      const chain = [dispatchRequest.bind(this), void 0];
      chain.unshift.apply(chain, requestInterceptorChain);
      chain.push.apply(chain, responseInterceptorChain);
      len = chain.length;
      promise = Promise.resolve(config2);
      while (i2 < len) {
        promise = promise.then(chain[i2++], chain[i2++]);
      }
      return promise;
    }
    len = requestInterceptorChain.length;
    let newConfig = config2;
    i2 = 0;
    while (i2 < len) {
      const onFulfilled = requestInterceptorChain[i2++];
      const onRejected = requestInterceptorChain[i2++];
      try {
        newConfig = onFulfilled(newConfig);
      } catch (error2) {
        onRejected.call(this, error2);
        break;
      }
    }
    try {
      promise = dispatchRequest.call(this, newConfig);
    } catch (error2) {
      return Promise.reject(error2);
    }
    i2 = 0;
    len = responseInterceptorChain.length;
    while (i2 < len) {
      promise = promise.then(responseInterceptorChain[i2++], responseInterceptorChain[i2++]);
    }
    return promise;
  }
  getUri(config2) {
    config2 = mergeConfig$1(this.defaults, config2);
    const fullPath = buildFullPath(config2.baseURL, config2.url, config2.allowAbsoluteUrls);
    return buildURL(fullPath, config2.params, config2.paramsSerializer);
  }
};
utils$2.forEach(["delete", "get", "head", "options"], /* @__PURE__ */ __name(function forEachMethodNoData(method) {
  Axios$1.prototype[method] = function(url, config2) {
    return this.request(mergeConfig$1(config2 || {}, {
      method,
      url,
      data: (config2 || {}).data
    }));
  };
}, "forEachMethodNoData"));
utils$2.forEach(["post", "put", "patch"], /* @__PURE__ */ __name(function forEachMethodWithData(method) {
  function generateHTTPMethod(isForm) {
    return /* @__PURE__ */ __name(function httpMethod(url, data, config2) {
      return this.request(mergeConfig$1(config2 || {}, {
        method,
        headers: isForm ? {
          "Content-Type": "multipart/form-data"
        } : {},
        url,
        data
      }));
    }, "httpMethod");
  }
  __name(generateHTTPMethod, "generateHTTPMethod");
  Axios$1.prototype[method] = generateHTTPMethod();
  Axios$1.prototype[method + "Form"] = generateHTTPMethod(true);
}, "forEachMethodWithData"));
"use strict";
let CancelToken$1 = class CancelToken2 {
  static {
    __name(this, "CancelToken");
  }
  constructor(executor) {
    if (typeof executor !== "function") {
      throw new TypeError("executor must be a function.");
    }
    let resolvePromise;
    this.promise = new Promise(/* @__PURE__ */ __name(function promiseExecutor(resolve2) {
      resolvePromise = resolve2;
    }, "promiseExecutor"));
    const token = this;
    this.promise.then((cancel) => {
      if (!token._listeners) return;
      let i2 = token._listeners.length;
      while (i2-- > 0) {
        token._listeners[i2](cancel);
      }
      token._listeners = null;
    });
    this.promise.then = (onfulfilled) => {
      let _resolve;
      const promise = new Promise((resolve2) => {
        token.subscribe(resolve2);
        _resolve = resolve2;
      }).then(onfulfilled);
      promise.cancel = /* @__PURE__ */ __name(function reject() {
        token.unsubscribe(_resolve);
      }, "reject");
      return promise;
    };
    executor(/* @__PURE__ */ __name(function cancel(message, config2, request) {
      if (token.reason) {
        return;
      }
      token.reason = new CanceledError$1(message, config2, request);
      resolvePromise(token.reason);
    }, "cancel"));
  }
  /**
   * Throws a `CanceledError` if cancellation has been requested.
   */
  throwIfRequested() {
    if (this.reason) {
      throw this.reason;
    }
  }
  /**
   * Subscribe to the cancel signal
   */
  subscribe(listener) {
    if (this.reason) {
      listener(this.reason);
      return;
    }
    if (this._listeners) {
      this._listeners.push(listener);
    } else {
      this._listeners = [listener];
    }
  }
  /**
   * Unsubscribe from the cancel signal
   */
  unsubscribe(listener) {
    if (!this._listeners) {
      return;
    }
    const index2 = this._listeners.indexOf(listener);
    if (index2 !== -1) {
      this._listeners.splice(index2, 1);
    }
  }
  toAbortSignal() {
    const controller = new AbortController();
    const abort = /* @__PURE__ */ __name((err) => {
      controller.abort(err);
    }, "abort");
    this.subscribe(abort);
    controller.signal.unsubscribe = () => this.unsubscribe(abort);
    return controller.signal;
  }
  /**
   * Returns an object that contains a new `CancelToken` and a function that, when called,
   * cancels the `CancelToken`.
   */
  static source() {
    let cancel;
    const token = new CancelToken2(/* @__PURE__ */ __name(function executor(c2) {
      cancel = c2;
    }, "executor"));
    return {
      token,
      cancel
    };
  }
};
"use strict";
function spread$1(callback) {
  return /* @__PURE__ */ __name(function wrap2(arr) {
    return callback.apply(null, arr);
  }, "wrap");
}
__name(spread$1, "spread$1");
"use strict";
function isAxiosError$1(payload) {
  return utils$2.isObject(payload) && payload.isAxiosError === true;
}
__name(isAxiosError$1, "isAxiosError$1");
const HttpStatusCode$1 = {
  Continue: 100,
  SwitchingProtocols: 101,
  Processing: 102,
  EarlyHints: 103,
  Ok: 200,
  Created: 201,
  Accepted: 202,
  NonAuthoritativeInformation: 203,
  NoContent: 204,
  ResetContent: 205,
  PartialContent: 206,
  MultiStatus: 207,
  AlreadyReported: 208,
  ImUsed: 226,
  MultipleChoices: 300,
  MovedPermanently: 301,
  Found: 302,
  SeeOther: 303,
  NotModified: 304,
  UseProxy: 305,
  Unused: 306,
  TemporaryRedirect: 307,
  PermanentRedirect: 308,
  BadRequest: 400,
  Unauthorized: 401,
  PaymentRequired: 402,
  Forbidden: 403,
  NotFound: 404,
  MethodNotAllowed: 405,
  NotAcceptable: 406,
  ProxyAuthenticationRequired: 407,
  RequestTimeout: 408,
  Conflict: 409,
  Gone: 410,
  LengthRequired: 411,
  PreconditionFailed: 412,
  PayloadTooLarge: 413,
  UriTooLong: 414,
  UnsupportedMediaType: 415,
  RangeNotSatisfiable: 416,
  ExpectationFailed: 417,
  ImATeapot: 418,
  MisdirectedRequest: 421,
  UnprocessableEntity: 422,
  Locked: 423,
  FailedDependency: 424,
  TooEarly: 425,
  UpgradeRequired: 426,
  PreconditionRequired: 428,
  TooManyRequests: 429,
  RequestHeaderFieldsTooLarge: 431,
  UnavailableForLegalReasons: 451,
  InternalServerError: 500,
  NotImplemented: 501,
  BadGateway: 502,
  ServiceUnavailable: 503,
  GatewayTimeout: 504,
  HttpVersionNotSupported: 505,
  VariantAlsoNegotiates: 506,
  InsufficientStorage: 507,
  LoopDetected: 508,
  NotExtended: 510,
  NetworkAuthenticationRequired: 511
};
Object.entries(HttpStatusCode$1).forEach(([key, value]) => {
  HttpStatusCode$1[value] = key;
});
"use strict";
function createInstance(defaultConfig) {
  const context = new Axios$1(defaultConfig);
  const instance = bind$3(Axios$1.prototype.request, context);
  utils$2.extend(instance, Axios$1.prototype, context, { allOwnKeys: true });
  utils$2.extend(instance, context, null, { allOwnKeys: true });
  instance.create = /* @__PURE__ */ __name(function create2(instanceConfig) {
    return createInstance(mergeConfig$1(defaultConfig, instanceConfig));
  }, "create");
  return instance;
}
__name(createInstance, "createInstance");
const axios = createInstance(defaults$1);
axios.Axios = Axios$1;
axios.CanceledError = CanceledError$1;
axios.CancelToken = CancelToken$1;
axios.isCancel = isCancel$1;
axios.VERSION = VERSION$1;
axios.toFormData = toFormData$1;
axios.AxiosError = AxiosError$1;
axios.Cancel = axios.CanceledError;
axios.all = /* @__PURE__ */ __name(function all2(promises) {
  return Promise.all(promises);
}, "all");
axios.spread = spread$1;
axios.isAxiosError = isAxiosError$1;
axios.mergeConfig = mergeConfig$1;
axios.AxiosHeaders = AxiosHeaders$1;
axios.formToJSON = (thing) => formDataToJSON(utils$2.isHTMLForm(thing) ? new FormData(thing) : thing);
axios.getAdapter = adapters.getAdapter;
axios.HttpStatusCode = HttpStatusCode$1;
axios.default = axios;
const {
  Axios,
  AxiosError,
  CanceledError,
  isCancel,
  CancelToken,
  VERSION,
  all,
  Cancel,
  isAxiosError,
  spread,
  toFormData,
  AxiosHeaders,
  HttpStatusCode,
  formToJSON,
  getAdapter,
  mergeConfig
} = axios;
var util;
(function(util2) {
  util2.assertEqual = (val) => val;
  function assertIs(_arg) {
  }
  __name(assertIs, "assertIs");
  util2.assertIs = assertIs;
  function assertNever(_x) {
    throw new Error();
  }
  __name(assertNever, "assertNever");
  util2.assertNever = assertNever;
  util2.arrayToEnum = (items) => {
    const obj = {};
    for (const item of items) {
      obj[item] = item;
    }
    return obj;
  };
  util2.getValidEnumValues = (obj) => {
    const validKeys = util2.objectKeys(obj).filter((k2) => typeof obj[obj[k2]] !== "number");
    const filtered = {};
    for (const k2 of validKeys) {
      filtered[k2] = obj[k2];
    }
    return util2.objectValues(filtered);
  };
  util2.objectValues = (obj) => {
    return util2.objectKeys(obj).map(function(e2) {
      return obj[e2];
    });
  };
  util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
    const keys2 = [];
    for (const key in object) {
      if (Object.prototype.hasOwnProperty.call(object, key)) {
        keys2.push(key);
      }
    }
    return keys2;
  };
  util2.find = (arr, checker) => {
    for (const item of arr) {
      if (checker(item))
        return item;
    }
    return void 0;
  };
  util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val;
  function joinValues(array, separator = " | ") {
    return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
  }
  __name(joinValues, "joinValues");
  util2.joinValues = joinValues;
  util2.jsonStringifyReplacer = (_2, value) => {
    if (typeof value === "bigint") {
      return value.toString();
    }
    return value;
  };
})(util || (util = {}));
var objectUtil;
(function(objectUtil2) {
  objectUtil2.mergeShapes = (first2, second) => {
    return {
      ...first2,
      ...second
      // second overwrites first
    };
  };
})(objectUtil || (objectUtil = {}));
const ZodParsedType = util.arrayToEnum([
  "string",
  "nan",
  "number",
  "integer",
  "float",
  "boolean",
  "date",
  "bigint",
  "symbol",
  "function",
  "undefined",
  "null",
  "array",
  "object",
  "unknown",
  "promise",
  "void",
  "never",
  "map",
  "set"
]);
const getParsedType = /* @__PURE__ */ __name((data) => {
  const t2 = typeof data;
  switch (t2) {
    case "undefined":
      return ZodParsedType.undefined;
    case "string":
      return ZodParsedType.string;
    case "number":
      return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
    case "boolean":
      return ZodParsedType.boolean;
    case "function":
      return ZodParsedType.function;
    case "bigint":
      return ZodParsedType.bigint;
    case "symbol":
      return ZodParsedType.symbol;
    case "object":
      if (Array.isArray(data)) {
        return ZodParsedType.array;
      }
      if (data === null) {
        return ZodParsedType.null;
      }
      if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
        return ZodParsedType.promise;
      }
      if (typeof Map !== "undefined" && data instanceof Map) {
        return ZodParsedType.map;
      }
      if (typeof Set !== "undefined" && data instanceof Set) {
        return ZodParsedType.set;
      }
      if (typeof Date !== "undefined" && data instanceof Date) {
        return ZodParsedType.date;
      }
      return ZodParsedType.object;
    default:
      return ZodParsedType.unknown;
  }
}, "getParsedType");
const ZodIssueCode = util.arrayToEnum([
  "invalid_type",
  "invalid_literal",
  "custom",
  "invalid_union",
  "invalid_union_discriminator",
  "invalid_enum_value",
  "unrecognized_keys",
  "invalid_arguments",
  "invalid_return_type",
  "invalid_date",
  "invalid_string",
  "too_small",
  "too_big",
  "invalid_intersection_types",
  "not_multiple_of",
  "not_finite"
]);
const quotelessJson = /* @__PURE__ */ __name((obj) => {
  const json = JSON.stringify(obj, null, 2);
  return json.replace(/"([^"]+)":/g, "$1:");
}, "quotelessJson");
class ZodError extends Error {
  static {
    __name(this, "ZodError");
  }
  get errors() {
    return this.issues;
  }
  constructor(issues) {
    super();
    this.issues = [];
    this.addIssue = (sub) => {
      this.issues = [...this.issues, sub];
    };
    this.addIssues = (subs = []) => {
      this.issues = [...this.issues, ...subs];
    };
    const actualProto = new.target.prototype;
    if (Object.setPrototypeOf) {
      Object.setPrototypeOf(this, actualProto);
    } else {
      this.__proto__ = actualProto;
    }
    this.name = "ZodError";
    this.issues = issues;
  }
  format(_mapper) {
    const mapper = _mapper || function(issue) {
      return issue.message;
    };
    const fieldErrors = { _errors: [] };
    const processError = /* @__PURE__ */ __name((error2) => {
      for (const issue of error2.issues) {
        if (issue.code === "invalid_union") {
          issue.unionErrors.map(processError);
        } else if (issue.code === "invalid_return_type") {
          processError(issue.returnTypeError);
        } else if (issue.code === "invalid_arguments") {
          processError(issue.argumentsError);
        } else if (issue.path.length === 0) {
          fieldErrors._errors.push(mapper(issue));
        } else {
          let curr = fieldErrors;
          let i2 = 0;
          while (i2 < issue.path.length) {
            const el = issue.path[i2];
            const terminal = i2 === issue.path.length - 1;
            if (!terminal) {
              curr[el] = curr[el] || { _errors: [] };
            } else {
              curr[el] = curr[el] || { _errors: [] };
              curr[el]._errors.push(mapper(issue));
            }
            curr = curr[el];
            i2++;
          }
        }
      }
    }, "processError");
    processError(this);
    return fieldErrors;
  }
  static assert(value) {
    if (!(value instanceof ZodError)) {
      throw new Error(`Not a ZodError: ${value}`);
    }
  }
  toString() {
    return this.message;
  }
  get message() {
    return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
  }
  get isEmpty() {
    return this.issues.length === 0;
  }
  flatten(mapper = (issue) => issue.message) {
    const fieldErrors = {};
    const formErrors = [];
    for (const sub of this.issues) {
      if (sub.path.length > 0) {
        fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
        fieldErrors[sub.path[0]].push(mapper(sub));
      } else {
        formErrors.push(mapper(sub));
      }
    }
    return { formErrors, fieldErrors };
  }
  get formErrors() {
    return this.flatten();
  }
}
ZodError.create = (issues) => {
  const error2 = new ZodError(issues);
  return error2;
};
const errorMap$1 = /* @__PURE__ */ __name((issue, _ctx) => {
  let message;
  switch (issue.code) {
    case ZodIssueCode.invalid_type:
      if (issue.received === ZodParsedType.undefined) {
        message = "Required";
      } else {
        message = `Expected ${issue.expected}, received ${issue.received}`;
      }
      break;
    case ZodIssueCode.invalid_literal:
      message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
      break;
    case ZodIssueCode.unrecognized_keys:
      message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
      break;
    case ZodIssueCode.invalid_union:
      message = `Invalid input`;
      break;
    case ZodIssueCode.invalid_union_discriminator:
      message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
      break;
    case ZodIssueCode.invalid_enum_value:
      message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
      break;
    case ZodIssueCode.invalid_arguments:
      message = `Invalid function arguments`;
      break;
    case ZodIssueCode.invalid_return_type:
      message = `Invalid function return type`;
      break;
    case ZodIssueCode.invalid_date:
      message = `Invalid date`;
      break;
    case ZodIssueCode.invalid_string:
      if (typeof issue.validation === "object") {
        if ("includes" in issue.validation) {
          message = `Invalid input: must include "${issue.validation.includes}"`;
          if (typeof issue.validation.position === "number") {
            message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
          }
        } else if ("startsWith" in issue.validation) {
          message = `Invalid input: must start with "${issue.validation.startsWith}"`;
        } else if ("endsWith" in issue.validation) {
          message = `Invalid input: must end with "${issue.validation.endsWith}"`;
        } else {
          util.assertNever(issue.validation);
        }
      } else if (issue.validation !== "regex") {
        message = `Invalid ${issue.validation}`;
      } else {
        message = "Invalid";
      }
      break;
    case ZodIssueCode.too_small:
      if (issue.type === "array")
        message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
      else if (issue.type === "string")
        message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
      else if (issue.type === "number")
        message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
      else if (issue.type === "date")
        message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
      else
        message = "Invalid input";
      break;
    case ZodIssueCode.too_big:
      if (issue.type === "array")
        message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
      else if (issue.type === "string")
        message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
      else if (issue.type === "number")
        message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
      else if (issue.type === "bigint")
        message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
      else if (issue.type === "date")
        message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
      else
        message = "Invalid input";
      break;
    case ZodIssueCode.custom:
      message = `Invalid input`;
      break;
    case ZodIssueCode.invalid_intersection_types:
      message = `Intersection results could not be merged`;
      break;
    case ZodIssueCode.not_multiple_of:
      message = `Number must be a multiple of ${issue.multipleOf}`;
      break;
    case ZodIssueCode.not_finite:
      message = "Number must be finite";
      break;
    default:
      message = _ctx.defaultError;
      util.assertNever(issue);
  }
  return { message };
}, "errorMap$1");
let overrideErrorMap = errorMap$1;
function setErrorMap(map3) {
  overrideErrorMap = map3;
}
__name(setErrorMap, "setErrorMap");
function getErrorMap() {
  return overrideErrorMap;
}
__name(getErrorMap, "getErrorMap");
const makeIssue = /* @__PURE__ */ __name((params) => {
  const { data, path, errorMaps, issueData } = params;
  const fullPath = [...path, ...issueData.path || []];
  const fullIssue = {
    ...issueData,
    path: fullPath
  };
  if (issueData.message !== void 0) {
    return {
      ...issueData,
      path: fullPath,
      message: issueData.message
    };
  }
  let errorMessage = "";
  const maps = errorMaps.filter((m2) => !!m2).slice().reverse();
  for (const map3 of maps) {
    errorMessage = map3(fullIssue, { data, defaultError: errorMessage }).message;
  }
  return {
    ...issueData,
    path: fullPath,
    message: errorMessage
  };
}, "makeIssue");
const EMPTY_PATH = [];
function addIssueToContext(ctx, issueData) {
  const overrideMap = getErrorMap();
  const issue = makeIssue({
    issueData,
    data: ctx.data,
    path: ctx.path,
    errorMaps: [
      ctx.common.contextualErrorMap,
      // contextual error map is first priority
      ctx.schemaErrorMap,
      // then schema-bound map if available
      overrideMap,
      // then global override map
      overrideMap === errorMap$1 ? void 0 : errorMap$1
      // then global default map
    ].filter((x2) => !!x2)
  });
  ctx.common.issues.push(issue);
}
__name(addIssueToContext, "addIssueToContext");
class ParseStatus {
  static {
    __name(this, "ParseStatus");
  }
  constructor() {
    this.value = "valid";
  }
  dirty() {
    if (this.value === "valid")
      this.value = "dirty";
  }
  abort() {
    if (this.value !== "aborted")
      this.value = "aborted";
  }
  static mergeArray(status, results) {
    const arrayValue = [];
    for (const s2 of results) {
      if (s2.status === "aborted")
        return INVALID;
      if (s2.status === "dirty")
        status.dirty();
      arrayValue.push(s2.value);
    }
    return { status: status.value, value: arrayValue };
  }
  static async mergeObjectAsync(status, pairs) {
    const syncPairs = [];
    for (const pair of pairs) {
      const key = await pair.key;
      const value = await pair.value;
      syncPairs.push({
        key,
        value
      });
    }
    return ParseStatus.mergeObjectSync(status, syncPairs);
  }
  static mergeObjectSync(status, pairs) {
    const finalObject = {};
    for (const pair of pairs) {
      const { key, value } = pair;
      if (key.status === "aborted")
        return INVALID;
      if (value.status === "aborted")
        return INVALID;
      if (key.status === "dirty")
        status.dirty();
      if (value.status === "dirty")
        status.dirty();
      if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
        finalObject[key.value] = value.value;
      }
    }
    return { status: status.value, value: finalObject };
  }
}
const INVALID = Object.freeze({
  status: "aborted"
});
const DIRTY = /* @__PURE__ */ __name((value) => ({ status: "dirty", value }), "DIRTY");
const OK = /* @__PURE__ */ __name((value) => ({ status: "valid", value }), "OK");
const isAborted = /* @__PURE__ */ __name((x2) => x2.status === "aborted", "isAborted");
const isDirty = /* @__PURE__ */ __name((x2) => x2.status === "dirty", "isDirty");
const isValid = /* @__PURE__ */ __name((x2) => x2.status === "valid", "isValid");
const isAsync = /* @__PURE__ */ __name((x2) => typeof Promise !== "undefined" && x2 instanceof Promise, "isAsync");
function __classPrivateFieldGet(receiver, state, kind, f2) {
  if (kind === "a" && !f2) throw new TypeError("Private accessor was defined without a getter");
  if (typeof state === "function" ? receiver !== state || !f2 : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return kind === "m" ? f2 : kind === "a" ? f2.call(receiver) : f2 ? f2.value : state.get(receiver);
}
__name(__classPrivateFieldGet, "__classPrivateFieldGet");
function __classPrivateFieldSet(receiver, state, value, kind, f2) {
  if (kind === "m") throw new TypeError("Private method is not writable");
  if (kind === "a" && !f2) throw new TypeError("Private accessor was defined without a setter");
  if (typeof state === "function" ? receiver !== state || !f2 : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
  return kind === "a" ? f2.call(receiver, value) : f2 ? f2.value = value : state.set(receiver, value), value;
}
__name(__classPrivateFieldSet, "__classPrivateFieldSet");
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 errorUtil;
(function(errorUtil2) {
  errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
  errorUtil2.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message;
})(errorUtil || (errorUtil = {}));
var _ZodEnum_cache, _ZodNativeEnum_cache;
class ParseInputLazyPath {
  static {
    __name(this, "ParseInputLazyPath");
  }
  constructor(parent2, value, path, key) {
    this._cachedPath = [];
    this.parent = parent2;
    this.data = value;
    this._path = path;
    this._key = key;
  }
  get path() {
    if (!this._cachedPath.length) {
      if (this._key instanceof Array) {
        this._cachedPath.push(...this._path, ...this._key);
      } else {
        this._cachedPath.push(...this._path, this._key);
      }
    }
    return this._cachedPath;
  }
}
const handleResult = /* @__PURE__ */ __name((ctx, result) => {
  if (isValid(result)) {
    return { success: true, data: result.value };
  } else {
    if (!ctx.common.issues.length) {
      throw new Error("Validation failed but no issues detected.");
    }
    return {
      success: false,
      get error() {
        if (this._error)
          return this._error;
        const error2 = new ZodError(ctx.common.issues);
        this._error = error2;
        return this._error;
      }
    };
  }
}, "handleResult");
function processCreateParams(params) {
  if (!params)
    return {};
  const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
  if (errorMap2 && (invalid_type_error || required_error)) {
    throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
  }
  if (errorMap2)
    return { errorMap: errorMap2, description };
  const customMap = /* @__PURE__ */ __name((iss, ctx) => {
    var _a2, _b;
    const { message } = params;
    if (iss.code === "invalid_enum_value") {
      return { message: message !== null && message !== void 0 ? message : ctx.defaultError };
    }
    if (typeof ctx.data === "undefined") {
      return { message: (_a2 = message !== null && message !== void 0 ? message : required_error) !== null && _a2 !== void 0 ? _a2 : ctx.defaultError };
    }
    if (iss.code !== "invalid_type")
      return { message: ctx.defaultError };
    return { message: (_b = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b !== void 0 ? _b : ctx.defaultError };
  }, "customMap");
  return { errorMap: customMap, description };
}
__name(processCreateParams, "processCreateParams");
class ZodType {
  static {
    __name(this, "ZodType");
  }
  get description() {
    return this._def.description;
  }
  _getType(input) {
    return getParsedType(input.data);
  }
  _getOrReturnCtx(input, ctx) {
    return ctx || {
      common: input.parent.common,
      data: input.data,
      parsedType: getParsedType(input.data),
      schemaErrorMap: this._def.errorMap,
      path: input.path,
      parent: input.parent
    };
  }
  _processInputParams(input) {
    return {
      status: new ParseStatus(),
      ctx: {
        common: input.parent.common,
        data: input.data,
        parsedType: getParsedType(input.data),
        schemaErrorMap: this._def.errorMap,
        path: input.path,
        parent: input.parent
      }
    };
  }
  _parseSync(input) {
    const result = this._parse(input);
    if (isAsync(result)) {
      throw new Error("Synchronous parse encountered promise.");
    }
    return result;
  }
  _parseAsync(input) {
    const result = this._parse(input);
    return Promise.resolve(result);
  }
  parse(data, params) {
    const result = this.safeParse(data, params);
    if (result.success)
      return result.data;
    throw result.error;
  }
  safeParse(data, params) {
    var _a2;
    const ctx = {
      common: {
        issues: [],
        async: (_a2 = params === null || params === void 0 ? void 0 : params.async) !== null && _a2 !== void 0 ? _a2 : false,
        contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap
      },
      path: (params === null || params === void 0 ? void 0 : params.path) || [],
      schemaErrorMap: this._def.errorMap,
      parent: null,
      data,
      parsedType: getParsedType(data)
    };
    const result = this._parseSync({ data, path: ctx.path, parent: ctx });
    return handleResult(ctx, result);
  }
  "~validate"(data) {
    var _a2, _b;
    const ctx = {
      common: {
        issues: [],
        async: !!this["~standard"].async
      },
      path: [],
      schemaErrorMap: this._def.errorMap,
      parent: null,
      data,
      parsedType: getParsedType(data)
    };
    if (!this["~standard"].async) {
      try {
        const result = this._parseSync({ data, path: [], parent: ctx });
        return isValid(result) ? {
          value: result.value
        } : {
          issues: ctx.common.issues
        };
      } catch (err) {
        if ((_b = (_a2 = err === null || err === void 0 ? void 0 : err.message) === null || _a2 === void 0 ? void 0 : _a2.toLowerCase()) === null || _b === void 0 ? void 0 : _b.includes("encountered")) {
          this["~standard"].async = true;
        }
        ctx.common = {
          issues: [],
          async: true
        };
      }
    }
    return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
      value: result.value
    } : {
      issues: ctx.common.issues
    });
  }
  async parseAsync(data, params) {
    const result = await this.safeParseAsync(data, params);
    if (result.success)
      return result.data;
    throw result.error;
  }
  async safeParseAsync(data, params) {
    const ctx = {
      common: {
        issues: [],
        contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,
        async: true
      },
      path: (params === null || params === void 0 ? void 0 : params.path) || [],
      schemaErrorMap: this._def.errorMap,
      parent: null,
      data,
      parsedType: getParsedType(data)
    };
    const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
    const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
    return handleResult(ctx, result);
  }
  refine(check, message) {
    const getIssueProperties = /* @__PURE__ */ __name((val) => {
      if (typeof message === "string" || typeof message === "undefined") {
        return { message };
      } else if (typeof message === "function") {
        return message(val);
      } else {
        return message;
      }
    }, "getIssueProperties");
    return this._refinement((val, ctx) => {
      const result = check(val);
      const setError = /* @__PURE__ */ __name(() => ctx.addIssue({
        code: ZodIssueCode.custom,
        ...getIssueProperties(val)
      }), "setError");
      if (typeof Promise !== "undefined" && result instanceof Promise) {
        return result.then((data) => {
          if (!data) {
            setError();
            return false;
          } else {
            return true;
          }
        });
      }
      if (!result) {
        setError();
        return false;
      } else {
        return true;
      }
    });
  }
  refinement(check, refinementData) {
    return this._refinement((val, ctx) => {
      if (!check(val)) {
        ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
        return false;
      } else {
        return true;
      }
    });
  }
  _refinement(refinement) {
    return new ZodEffects({
      schema: this,
      typeName: ZodFirstPartyTypeKind.ZodEffects,
      effect: { type: "refinement", refinement }
    });
  }
  superRefine(refinement) {
    return this._refinement(refinement);
  }
  constructor(def) {
    this.spa = this.safeParseAsync;
    this._def = def;
    this.parse = this.parse.bind(this);
    this.safeParse = this.safeParse.bind(this);
    this.parseAsync = this.parseAsync.bind(this);
    this.safeParseAsync = this.safeParseAsync.bind(this);
    this.spa = this.spa.bind(this);
    this.refine = this.refine.bind(this);
    this.refinement = this.refinement.bind(this);
    this.superRefine = this.superRefine.bind(this);
    this.optional = this.optional.bind(this);
    this.nullable = this.nullable.bind(this);
    this.nullish = this.nullish.bind(this);
    this.array = this.array.bind(this);
    this.promise = this.promise.bind(this);
    this.or = this.or.bind(this);
    this.and = this.and.bind(this);
    this.transform = this.transform.bind(this);
    this.brand = this.brand.bind(this);
    this.default = this.default.bind(this);
    this.catch = this.catch.bind(this);
    this.describe = this.describe.bind(this);
    this.pipe = this.pipe.bind(this);
    this.readonly = this.readonly.bind(this);
    this.isNullable = this.isNullable.bind(this);
    this.isOptional = this.isOptional.bind(this);
    this["~standard"] = {
      version: 1,
      vendor: "zod",
      validate: /* @__PURE__ */ __name((data) => this["~validate"](data), "validate")
    };
  }
  optional() {
    return ZodOptional.create(this, this._def);
  }
  nullable() {
    return ZodNullable.create(this, this._def);
  }
  nullish() {
    return this.nullable().optional();
  }
  array() {
    return ZodArray.create(this);
  }
  promise() {
    return ZodPromise.create(this, this._def);
  }
  or(option) {
    return ZodUnion.create([this, option], this._def);
  }
  and(incoming) {
    return ZodIntersection.create(this, incoming, this._def);
  }
  transform(transform) {
    return new ZodEffects({
      ...processCreateParams(this._def),
      schema: this,
      typeName: ZodFirstPartyTypeKind.ZodEffects,
      effect: { type: "transform", transform }
    });
  }
  default(def) {
    const defaultValueFunc = typeof def === "function" ? def : () => def;
    return new ZodDefault({
      ...processCreateParams(this._def),
      innerType: this,
      defaultValue: defaultValueFunc,
      typeName: ZodFirstPartyTypeKind.ZodDefault
    });
  }
  brand() {
    return new ZodBranded({
      typeName: ZodFirstPartyTypeKind.ZodBranded,
      type: this,
      ...processCreateParams(this._def)
    });
  }
  catch(def) {
    const catchValueFunc = typeof def === "function" ? def : () => def;
    return new ZodCatch({
      ...processCreateParams(this._def),
      innerType: this,
      catchValue: catchValueFunc,
      typeName: ZodFirstPartyTypeKind.ZodCatch
    });
  }
  describe(description) {
    const This = this.constructor;
    return new This({
      ...this._def,
      description
    });
  }
  pipe(target) {
    return ZodPipeline.create(this, target);
  }
  readonly() {
    return ZodReadonly.create(this);
  }
  isOptional() {
    return this.safeParse(void 0).success;
  }
  isNullable() {
    return this.safeParse(null).success;
  }
}
const cuidRegex = /^c[^\s-]{8,}$/i;
const cuid2Regex = /^[0-9a-z]+$/;
const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
const uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
const nanoidRegex = /^[a-z0-9_-]{21}$/i;
const jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
const durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
let emojiRegex;
const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
const ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;
const ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
const ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
const base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
const base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
const dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
const dateRegex = new RegExp(`^${dateRegexSource}$`);
function timeRegexSource(args) {
  let regex2 = `([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d`;
  if (args.precision) {
    regex2 = `${regex2}\\.\\d{${args.precision}}`;
  } else if (args.precision == null) {
    regex2 = `${regex2}(\\.\\d+)?`;
  }
  return regex2;
}
__name(timeRegexSource, "timeRegexSource");
function timeRegex(args) {
  return new RegExp(`^${timeRegexSource(args)}$`);
}
__name(timeRegex, "timeRegex");
function datetimeRegex(args) {
  let regex2 = `${dateRegexSource}T${timeRegexSource(args)}`;
  const opts = [];
  opts.push(args.local ? `Z?` : `Z`);
  if (args.offset)
    opts.push(`([+-]\\d{2}:?\\d{2})`);
  regex2 = `${regex2}(${opts.join("|")})`;
  return new RegExp(`^${regex2}$`);
}
__name(datetimeRegex, "datetimeRegex");
function isValidIP(ip, version2) {
  if ((version2 === "v4" || !version2) && ipv4Regex.test(ip)) {
    return true;
  }
  if ((version2 === "v6" || !version2) && ipv6Regex.test(ip)) {
    return true;
  }
  return false;
}
__name(isValidIP, "isValidIP");
function isValidJWT(jwt, alg) {
  if (!jwtRegex.test(jwt))
    return false;
  try {
    const [header] = jwt.split(".");
    const base642 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
    const decoded = JSON.parse(atob(base642));
    if (typeof decoded !== "object" || decoded === null)
      return false;
    if (!decoded.typ || !decoded.alg)
      return false;
    if (alg && decoded.alg !== alg)
      return false;
    return true;
  } catch (_a2) {
    return false;
  }
}
__name(isValidJWT, "isValidJWT");
function isValidCidr(ip, version2) {
  if ((version2 === "v4" || !version2) && ipv4CidrRegex.test(ip)) {
    return true;
  }
  if ((version2 === "v6" || !version2) && ipv6CidrRegex.test(ip)) {
    return true;
  }
  return false;
}
__name(isValidCidr, "isValidCidr");
class ZodString extends ZodType {
  static {
    __name(this, "ZodString");
  }
  _parse(input) {
    if (this._def.coerce) {
      input.data = String(input.data);
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.string) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.string,
        received: ctx2.parsedType
      });
      return INVALID;
    }
    const status = new ParseStatus();
    let ctx = void 0;
    for (const check of this._def.checks) {
      if (check.kind === "min") {
        if (input.data.length < check.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_small,
            minimum: check.value,
            type: "string",
            inclusive: true,
            exact: false,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "max") {
        if (input.data.length > check.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_big,
            maximum: check.value,
            type: "string",
            inclusive: true,
            exact: false,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "length") {
        const tooBig = input.data.length > check.value;
        const tooSmall = input.data.length < check.value;
        if (tooBig || tooSmall) {
          ctx = this._getOrReturnCtx(input, ctx);
          if (tooBig) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_big,
              maximum: check.value,
              type: "string",
              inclusive: true,
              exact: true,
              message: check.message
            });
          } else if (tooSmall) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_small,
              minimum: check.value,
              type: "string",
              inclusive: true,
              exact: true,
              message: check.message
            });
          }
          status.dirty();
        }
      } else if (check.kind === "email") {
        if (!emailRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "email",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "emoji") {
        if (!emojiRegex) {
          emojiRegex = new RegExp(_emojiRegex, "u");
        }
        if (!emojiRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "emoji",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "uuid") {
        if (!uuidRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "uuid",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "nanoid") {
        if (!nanoidRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "nanoid",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "cuid") {
        if (!cuidRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "cuid",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "cuid2") {
        if (!cuid2Regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "cuid2",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "ulid") {
        if (!ulidRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "ulid",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "url") {
        try {
          new URL(input.data);
        } catch (_a2) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "url",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "regex") {
        check.regex.lastIndex = 0;
        const testResult = check.regex.test(input.data);
        if (!testResult) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "regex",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "trim") {
        input.data = input.data.trim();
      } else if (check.kind === "includes") {
        if (!input.data.includes(check.value, check.position)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: { includes: check.value, position: check.position },
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "toLowerCase") {
        input.data = input.data.toLowerCase();
      } else if (check.kind === "toUpperCase") {
        input.data = input.data.toUpperCase();
      } else if (check.kind === "startsWith") {
        if (!input.data.startsWith(check.value)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: { startsWith: check.value },
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "endsWith") {
        if (!input.data.endsWith(check.value)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: { endsWith: check.value },
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "datetime") {
        const regex2 = datetimeRegex(check);
        if (!regex2.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: "datetime",
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "date") {
        const regex2 = dateRegex;
        if (!regex2.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: "date",
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "time") {
        const regex2 = timeRegex(check);
        if (!regex2.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: "time",
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "duration") {
        if (!durationRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "duration",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "ip") {
        if (!isValidIP(input.data, check.version)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "ip",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "jwt") {
        if (!isValidJWT(input.data, check.alg)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "jwt",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "cidr") {
        if (!isValidCidr(input.data, check.version)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "cidr",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "base64") {
        if (!base64Regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "base64",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "base64url") {
        if (!base64urlRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "base64url",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else {
        util.assertNever(check);
      }
    }
    return { status: status.value, value: input.data };
  }
  _regex(regex2, validation2, message) {
    return this.refinement((data) => regex2.test(data), {
      validation: validation2,
      code: ZodIssueCode.invalid_string,
      ...errorUtil.errToObj(message)
    });
  }
  _addCheck(check) {
    return new ZodString({
      ...this._def,
      checks: [...this._def.checks, check]
    });
  }
  email(message) {
    return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
  }
  url(message) {
    return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
  }
  emoji(message) {
    return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
  }
  uuid(message) {
    return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
  }
  nanoid(message) {
    return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
  }
  cuid(message) {
    return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
  }
  cuid2(message) {
    return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
  }
  ulid(message) {
    return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
  }
  base64(message) {
    return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
  }
  base64url(message) {
    return this._addCheck({
      kind: "base64url",
      ...errorUtil.errToObj(message)
    });
  }
  jwt(options2) {
    return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options2) });
  }
  ip(options2) {
    return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options2) });
  }
  cidr(options2) {
    return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options2) });
  }
  datetime(options2) {
    var _a2, _b;
    if (typeof options2 === "string") {
      return this._addCheck({
        kind: "datetime",
        precision: null,
        offset: false,
        local: false,
        message: options2
      });
    }
    return this._addCheck({
      kind: "datetime",
      precision: typeof (options2 === null || options2 === void 0 ? void 0 : options2.precision) === "undefined" ? null : options2 === null || options2 === void 0 ? void 0 : options2.precision,
      offset: (_a2 = options2 === null || options2 === void 0 ? void 0 : options2.offset) !== null && _a2 !== void 0 ? _a2 : false,
      local: (_b = options2 === null || options2 === void 0 ? void 0 : options2.local) !== null && _b !== void 0 ? _b : false,
      ...errorUtil.errToObj(options2 === null || options2 === void 0 ? void 0 : options2.message)
    });
  }
  date(message) {
    return this._addCheck({ kind: "date", message });
  }
  time(options2) {
    if (typeof options2 === "string") {
      return this._addCheck({
        kind: "time",
        precision: null,
        message: options2
      });
    }
    return this._addCheck({
      kind: "time",
      precision: typeof (options2 === null || options2 === void 0 ? void 0 : options2.precision) === "undefined" ? null : options2 === null || options2 === void 0 ? void 0 : options2.precision,
      ...errorUtil.errToObj(options2 === null || options2 === void 0 ? void 0 : options2.message)
    });
  }
  duration(message) {
    return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
  }
  regex(regex2, message) {
    return this._addCheck({
      kind: "regex",
      regex: regex2,
      ...errorUtil.errToObj(message)
    });
  }
  includes(value, options2) {
    return this._addCheck({
      kind: "includes",
      value,
      position: options2 === null || options2 === void 0 ? void 0 : options2.position,
      ...errorUtil.errToObj(options2 === null || options2 === void 0 ? void 0 : options2.message)
    });
  }
  startsWith(value, message) {
    return this._addCheck({
      kind: "startsWith",
      value,
      ...errorUtil.errToObj(message)
    });
  }
  endsWith(value, message) {
    return this._addCheck({
      kind: "endsWith",
      value,
      ...errorUtil.errToObj(message)
    });
  }
  min(minLength, message) {
    return this._addCheck({
      kind: "min",
      value: minLength,
      ...errorUtil.errToObj(message)
    });
  }
  max(maxLength, message) {
    return this._addCheck({
      kind: "max",
      value: maxLength,
      ...errorUtil.errToObj(message)
    });
  }
  length(len, message) {
    return this._addCheck({
      kind: "length",
      value: len,
      ...errorUtil.errToObj(message)
    });
  }
  /**
   * Equivalent to `.min(1)`
   */
  nonempty(message) {
    return this.min(1, errorUtil.errToObj(message));
  }
  trim() {
    return new ZodString({
      ...this._def,
      checks: [...this._def.checks, { kind: "trim" }]
    });
  }
  toLowerCase() {
    return new ZodString({
      ...this._def,
      checks: [...this._def.checks, { kind: "toLowerCase" }]
    });
  }
  toUpperCase() {
    return new ZodString({
      ...this._def,
      checks: [...this._def.checks, { kind: "toUpperCase" }]
    });
  }
  get isDatetime() {
    return !!this._def.checks.find((ch) => ch.kind === "datetime");
  }
  get isDate() {
    return !!this._def.checks.find((ch) => ch.kind === "date");
  }
  get isTime() {
    return !!this._def.checks.find((ch) => ch.kind === "time");
  }
  get isDuration() {
    return !!this._def.checks.find((ch) => ch.kind === "duration");
  }
  get isEmail() {
    return !!this._def.checks.find((ch) => ch.kind === "email");
  }
  get isURL() {
    return !!this._def.checks.find((ch) => ch.kind === "url");
  }
  get isEmoji() {
    return !!this._def.checks.find((ch) => ch.kind === "emoji");
  }
  get isUUID() {
    return !!this._def.checks.find((ch) => ch.kind === "uuid");
  }
  get isNANOID() {
    return !!this._def.checks.find((ch) => ch.kind === "nanoid");
  }
  get isCUID() {
    return !!this._def.checks.find((ch) => ch.kind === "cuid");
  }
  get isCUID2() {
    return !!this._def.checks.find((ch) => ch.kind === "cuid2");
  }
  get isULID() {
    return !!this._def.checks.find((ch) => ch.kind === "ulid");
  }
  get isIP() {
    return !!this._def.checks.find((ch) => ch.kind === "ip");
  }
  get isCIDR() {
    return !!this._def.checks.find((ch) => ch.kind === "cidr");
  }
  get isBase64() {
    return !!this._def.checks.find((ch) => ch.kind === "base64");
  }
  get isBase64url() {
    return !!this._def.checks.find((ch) => ch.kind === "base64url");
  }
  get minLength() {
    let min = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "min") {
        if (min === null || ch.value > min)
          min = ch.value;
      }
    }
    return min;
  }
  get maxLength() {
    let max = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "max") {
        if (max === null || ch.value < max)
          max = ch.value;
      }
    }
    return max;
  }
}
ZodString.create = (params) => {
  var _a2;
  return new ZodString({
    checks: [],
    typeName: ZodFirstPartyTypeKind.ZodString,
    coerce: (_a2 = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a2 !== void 0 ? _a2 : false,
    ...processCreateParams(params)
  });
};
function floatSafeRemainder(val, step) {
  const valDecCount = (val.toString().split(".")[1] || "").length;
  const stepDecCount = (step.toString().split(".")[1] || "").length;
  const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
  const valInt = parseInt(val.toFixed(decCount).replace(".", ""));
  const stepInt = parseInt(step.toFixed(decCount).replace(".", ""));
  return valInt % stepInt / Math.pow(10, decCount);
}
__name(floatSafeRemainder, "floatSafeRemainder");
class ZodNumber extends ZodType {
  static {
    __name(this, "ZodNumber");
  }
  constructor() {
    super(...arguments);
    this.min = this.gte;
    this.max = this.lte;
    this.step = this.multipleOf;
  }
  _parse(input) {
    if (this._def.coerce) {
      input.data = Number(input.data);
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.number) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.number,
        received: ctx2.parsedType
      });
      return INVALID;
    }
    let ctx = void 0;
    const status = new ParseStatus();
    for (const check of this._def.checks) {
      if (check.kind === "int") {
        if (!util.isInteger(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: "integer",
            received: "float",
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "min") {
        const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
        if (tooSmall) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_small,
            minimum: check.value,
            type: "number",
            inclusive: check.inclusive,
            exact: false,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "max") {
        const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
        if (tooBig) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_big,
            maximum: check.value,
            type: "number",
            inclusive: check.inclusive,
            exact: false,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "multipleOf") {
        if (floatSafeRemainder(input.data, check.value) !== 0) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.not_multiple_of,
            multipleOf: check.value,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "finite") {
        if (!Number.isFinite(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.not_finite,
            message: check.message
          });
          status.dirty();
        }
      } else {
        util.assertNever(check);
      }
    }
    return { status: status.value, value: input.data };
  }
  gte(value, message) {
    return this.setLimit("min", value, true, errorUtil.toString(message));
  }
  gt(value, message) {
    return this.setLimit("min", value, false, errorUtil.toString(message));
  }
  lte(value, message) {
    return this.setLimit("max", value, true, errorUtil.toString(message));
  }
  lt(value, message) {
    return this.setLimit("max", value, false, errorUtil.toString(message));
  }
  setLimit(kind, value, inclusive, message) {
    return new ZodNumber({
      ...this._def,
      checks: [
        ...this._def.checks,
        {
          kind,
          value,
          inclusive,
          message: errorUtil.toString(message)
        }
      ]
    });
  }
  _addCheck(check) {
    return new ZodNumber({
      ...this._def,
      checks: [...this._def.checks, check]
    });
  }
  int(message) {
    return this._addCheck({
      kind: "int",
      message: errorUtil.toString(message)
    });
  }
  positive(message) {
    return this._addCheck({
      kind: "min",
      value: 0,
      inclusive: false,
      message: errorUtil.toString(message)
    });
  }
  negative(message) {
    return this._addCheck({
      kind: "max",
      value: 0,
      inclusive: false,
      message: errorUtil.toString(message)
    });
  }
  nonpositive(message) {
    return this._addCheck({
      kind: "max",
      value: 0,
      inclusive: true,
      message: errorUtil.toString(message)
    });
  }
  nonnegative(message) {
    return this._addCheck({
      kind: "min",
      value: 0,
      inclusive: true,
      message: errorUtil.toString(message)
    });
  }
  multipleOf(value, message) {
    return this._addCheck({
      kind: "multipleOf",
      value,
      message: errorUtil.toString(message)
    });
  }
  finite(message) {
    return this._addCheck({
      kind: "finite",
      message: errorUtil.toString(message)
    });
  }
  safe(message) {
    return this._addCheck({
      kind: "min",
      inclusive: true,
      value: Number.MIN_SAFE_INTEGER,
      message: errorUtil.toString(message)
    })._addCheck({
      kind: "max",
      inclusive: true,
      value: Number.MAX_SAFE_INTEGER,
      message: errorUtil.toString(message)
    });
  }
  get minValue() {
    let min = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "min") {
        if (min === null || ch.value > min)
          min = ch.value;
      }
    }
    return min;
  }
  get maxValue() {
    let max = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "max") {
        if (max === null || ch.value < max)
          max = ch.value;
      }
    }
    return max;
  }
  get isInt() {
    return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
  }
  get isFinite() {
    let max = null, min = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
        return true;
      } else if (ch.kind === "min") {
        if (min === null || ch.value > min)
          min = ch.value;
      } else if (ch.kind === "max") {
        if (max === null || ch.value < max)
          max = ch.value;
      }
    }
    return Number.isFinite(min) && Number.isFinite(max);
  }
}
ZodNumber.create = (params) => {
  return new ZodNumber({
    checks: [],
    typeName: ZodFirstPartyTypeKind.ZodNumber,
    coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
    ...processCreateParams(params)
  });
};
class ZodBigInt extends ZodType {
  static {
    __name(this, "ZodBigInt");
  }
  constructor() {
    super(...arguments);
    this.min = this.gte;
    this.max = this.lte;
  }
  _parse(input) {
    if (this._def.coerce) {
      try {
        input.data = BigInt(input.data);
      } catch (_a2) {
        return this._getInvalidInput(input);
      }
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.bigint) {
      return this._getInvalidInput(input);
    }
    let ctx = void 0;
    const status = new ParseStatus();
    for (const check of this._def.checks) {
      if (check.kind === "min") {
        const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
        if (tooSmall) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_small,
            type: "bigint",
            minimum: check.value,
            inclusive: check.inclusive,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "max") {
        const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
        if (tooBig) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_big,
            type: "bigint",
            maximum: check.value,
            inclusive: check.inclusive,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "multipleOf") {
        if (input.data % check.value !== BigInt(0)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.not_multiple_of,
            multipleOf: check.value,
            message: check.message
          });
          status.dirty();
        }
      } else {
        util.assertNever(check);
      }
    }
    return { status: status.value, value: input.data };
  }
  _getInvalidInput(input) {
    const ctx = this._getOrReturnCtx(input);
    addIssueToContext(ctx, {
      code: ZodIssueCode.invalid_type,
      expected: ZodParsedType.bigint,
      received: ctx.parsedType
    });
    return INVALID;
  }
  gte(value, message) {
    return this.setLimit("min", value, true, errorUtil.toString(message));
  }
  gt(value, message) {
    return this.setLimit("min", value, false, errorUtil.toString(message));
  }
  lte(value, message) {
    return this.setLimit("max", value, true, errorUtil.toString(message));
  }
  lt(value, message) {
    return this.setLimit("max", value, false, errorUtil.toString(message));
  }
  setLimit(kind, value, inclusive, message) {
    return new ZodBigInt({
      ...this._def,
      checks: [
        ...this._def.checks,
        {
          kind,
          value,
          inclusive,
          message: errorUtil.toString(message)
        }
      ]
    });
  }
  _addCheck(check) {
    return new ZodBigInt({
      ...this._def,
      checks: [...this._def.checks, check]
    });
  }
  positive(message) {
    return this._addCheck({
      kind: "min",
      value: BigInt(0),
      inclusive: false,
      message: errorUtil.toString(message)
    });
  }
  negative(message) {
    return this._addCheck({
      kind: "max",
      value: BigInt(0),
      inclusive: false,
      message: errorUtil.toString(message)
    });
  }
  nonpositive(message) {
    return this._addCheck({
      kind: "max",
      value: BigInt(0),
      inclusive: true,
      message: errorUtil.toString(message)
    });
  }
  nonnegative(message) {
    return this._addCheck({
      kind: "min",
      value: BigInt(0),
      inclusive: true,
      message: errorUtil.toString(message)
    });
  }
  multipleOf(value, message) {
    return this._addCheck({
      kind: "multipleOf",
      value,
      message: errorUtil.toString(message)
    });
  }
  get minValue() {
    let min = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "min") {
        if (min === null || ch.value > min)
          min = ch.value;
      }
    }
    return min;
  }
  get maxValue() {
    let max = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "max") {
        if (max === null || ch.value < max)
          max = ch.value;
      }
    }
    return max;
  }
}
ZodBigInt.create = (params) => {
  var _a2;
  return new ZodBigInt({
    checks: [],
    typeName: ZodFirstPartyTypeKind.ZodBigInt,
    coerce: (_a2 = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a2 !== void 0 ? _a2 : false,
    ...processCreateParams(params)
  });
};
class ZodBoolean extends ZodType {
  static {
    __name(this, "ZodBoolean");
  }
  _parse(input) {
    if (this._def.coerce) {
      input.data = Boolean(input.data);
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.boolean) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.boolean,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
}
ZodBoolean.create = (params) => {
  return new ZodBoolean({
    typeName: ZodFirstPartyTypeKind.ZodBoolean,
    coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
    ...processCreateParams(params)
  });
};
class ZodDate extends ZodType {
  static {
    __name(this, "ZodDate");
  }
  _parse(input) {
    if (this._def.coerce) {
      input.data = new Date(input.data);
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.date) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.date,
        received: ctx2.parsedType
      });
      return INVALID;
    }
    if (isNaN(input.data.getTime())) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_date
      });
      return INVALID;
    }
    const status = new ParseStatus();
    let ctx = void 0;
    for (const check of this._def.checks) {
      if (check.kind === "min") {
        if (input.data.getTime() < check.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_small,
            message: check.message,
            inclusive: true,
            exact: false,
            minimum: check.value,
            type: "date"
          });
          status.dirty();
        }
      } else if (check.kind === "max") {
        if (input.data.getTime() > check.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_big,
            message: check.message,
            inclusive: true,
            exact: false,
            maximum: check.value,
            type: "date"
          });
          status.dirty();
        }
      } else {
        util.assertNever(check);
      }
    }
    return {
      status: status.value,
      value: new Date(input.data.getTime())
    };
  }
  _addCheck(check) {
    return new ZodDate({
      ...this._def,
      checks: [...this._def.checks, check]
    });
  }
  min(minDate, message) {
    return this._addCheck({
      kind: "min",
      value: minDate.getTime(),
      message: errorUtil.toString(message)
    });
  }
  max(maxDate, message) {
    return this._addCheck({
      kind: "max",
      value: maxDate.getTime(),
      message: errorUtil.toString(message)
    });
  }
  get minDate() {
    let min = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "min") {
        if (min === null || ch.value > min)
          min = ch.value;
      }
    }
    return min != null ? new Date(min) : null;
  }
  get maxDate() {
    let max = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "max") {
        if (max === null || ch.value < max)
          max = ch.value;
      }
    }
    return max != null ? new Date(max) : null;
  }
}
ZodDate.create = (params) => {
  return new ZodDate({
    checks: [],
    coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
    typeName: ZodFirstPartyTypeKind.ZodDate,
    ...processCreateParams(params)
  });
};
class ZodSymbol extends ZodType {
  static {
    __name(this, "ZodSymbol");
  }
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.symbol) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.symbol,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
}
ZodSymbol.create = (params) => {
  return new ZodSymbol({
    typeName: ZodFirstPartyTypeKind.ZodSymbol,
    ...processCreateParams(params)
  });
};
class ZodUndefined extends ZodType {
  static {
    __name(this, "ZodUndefined");
  }
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.undefined) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.undefined,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
}
ZodUndefined.create = (params) => {
  return new ZodUndefined({
    typeName: ZodFirstPartyTypeKind.ZodUndefined,
    ...processCreateParams(params)
  });
};
class ZodNull extends ZodType {
  static {
    __name(this, "ZodNull");
  }
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.null) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.null,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
}
ZodNull.create = (params) => {
  return new ZodNull({
    typeName: ZodFirstPartyTypeKind.ZodNull,
    ...processCreateParams(params)
  });
};
class ZodAny extends ZodType {
  static {
    __name(this, "ZodAny");
  }
  constructor() {
    super(...arguments);
    this._any = true;
  }
  _parse(input) {
    return OK(input.data);
  }
}
ZodAny.create = (params) => {
  return new ZodAny({
    typeName: ZodFirstPartyTypeKind.ZodAny,
    ...processCreateParams(params)
  });
};
class ZodUnknown extends ZodType {
  static {
    __name(this, "ZodUnknown");
  }
  constructor() {
    super(...arguments);
    this._unknown = true;
  }
  _parse(input) {
    return OK(input.data);
  }
}
ZodUnknown.create = (params) => {
  return new ZodUnknown({
    typeName: ZodFirstPartyTypeKind.ZodUnknown,
    ...processCreateParams(params)
  });
};
class ZodNever extends ZodType {
  static {
    __name(this, "ZodNever");
  }
  _parse(input) {
    const ctx = this._getOrReturnCtx(input);
    addIssueToContext(ctx, {
      code: ZodIssueCode.invalid_type,
      expected: ZodParsedType.never,
      received: ctx.parsedType
    });
    return INVALID;
  }
}
ZodNever.create = (params) => {
  return new ZodNever({
    typeName: ZodFirstPartyTypeKind.ZodNever,
    ...processCreateParams(params)
  });
};
class ZodVoid extends ZodType {
  static {
    __name(this, "ZodVoid");
  }
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.undefined) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.void,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
}
ZodVoid.create = (params) => {
  return new ZodVoid({
    typeName: ZodFirstPartyTypeKind.ZodVoid,
    ...processCreateParams(params)
  });
};
class ZodArray extends ZodType {
  static {
    __name(this, "ZodArray");
  }
  _parse(input) {
    const { ctx, status } = this._processInputParams(input);
    const def = this._def;
    if (ctx.parsedType !== ZodParsedType.array) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.array,
        received: ctx.parsedType
      });
      return INVALID;
    }
    if (def.exactLength !== null) {
      const tooBig = ctx.data.length > def.exactLength.value;
      const tooSmall = ctx.data.length < def.exactLength.value;
      if (tooBig || tooSmall) {
        addIssueToContext(ctx, {
          code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
          minimum: tooSmall ? def.exactLength.value : void 0,
          maximum: tooBig ? def.exactLength.value : void 0,
          type: "array",
          inclusive: true,
          exact: true,
          message: def.exactLength.message
        });
        status.dirty();
      }
    }
    if (def.minLength !== null) {
      if (ctx.data.length < def.minLength.value) {
        addIssueToContext(ctx, {
          code: ZodIssueCode.too_small,
          minimum: def.minLength.value,
          type: "array",
          inclusive: true,
          exact: false,
          message: def.minLength.message
        });
        status.dirty();
      }
    }
    if (def.maxLength !== null) {
      if (ctx.data.length > def.maxLength.value) {
        addIssueToContext(ctx, {
          code: ZodIssueCode.too_big,
          maximum: def.maxLength.value,
          type: "array",
          inclusive: true,
          exact: false,
          message: def.maxLength.message
        });
        status.dirty();
      }
    }
    if (ctx.common.async) {
      return Promise.all([...ctx.data].map((item, i2) => {
        return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i2));
      })).then((result2) => {
        return ParseStatus.mergeArray(status, result2);
      });
    }
    const result = [...ctx.data].map((item, i2) => {
      return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i2));
    });
    return ParseStatus.mergeArray(status, result);
  }
  get element() {
    return this._def.type;
  }
  min(minLength, message) {
    return new ZodArray({
      ...this._def,
      minLength: { value: minLength, message: errorUtil.toString(message) }
    });
  }
  max(maxLength, message) {
    return new ZodArray({
      ...this._def,
      maxLength: { value: maxLength, message: errorUtil.toString(message) }
    });
  }
  length(len, message) {
    return new ZodArray({
      ...this._def,
      exactLength: { value: len, message: errorUtil.toString(message) }
    });
  }
  nonempty(message) {
    return this.min(1, message);
  }
}
ZodArray.create = (schema2, params) => {
  return new ZodArray({
    type: schema2,
    minLength: null,
    maxLength: null,
    exactLength: null,
    typeName: ZodFirstPartyTypeKind.ZodArray,
    ...processCreateParams(params)
  });
};
function deepPartialify(schema2) {
  if (schema2 instanceof ZodObject) {
    const newShape = {};
    for (const key in schema2.shape) {
      const fieldSchema = schema2.shape[key];
      newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
    }
    return new ZodObject({
      ...schema2._def,
      shape: /* @__PURE__ */ __name(() => newShape, "shape")
    });
  } else if (schema2 instanceof ZodArray) {
    return new ZodArray({
      ...schema2._def,
      type: deepPartialify(schema2.element)
    });
  } else if (schema2 instanceof ZodOptional) {
    return ZodOptional.create(deepPartialify(schema2.unwrap()));
  } else if (schema2 instanceof ZodNullable) {
    return ZodNullable.create(deepPartialify(schema2.unwrap()));
  } else if (schema2 instanceof ZodTuple) {
    return ZodTuple.create(schema2.items.map((item) => deepPartialify(item)));
  } else {
    return schema2;
  }
}
__name(deepPartialify, "deepPartialify");
class ZodObject extends ZodType {
  static {
    __name(this, "ZodObject");
  }
  constructor() {
    super(...arguments);
    this._cached = null;
    this.nonstrict = this.passthrough;
    this.augment = this.extend;
  }
  _getCached() {
    if (this._cached !== null)
      return this._cached;
    const shape = this._def.shape();
    const keys2 = util.objectKeys(shape);
    return this._cached = { shape, keys: keys2 };
  }
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.object) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.object,
        received: ctx2.parsedType
      });
      return INVALID;
    }
    const { status, ctx } = this._processInputParams(input);
    const { shape, keys: shapeKeys } = this._getCached();
    const extraKeys = [];
    if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
      for (const key in ctx.data) {
        if (!shapeKeys.includes(key)) {
          extraKeys.push(key);
        }
      }
    }
    const pairs = [];
    for (const key of shapeKeys) {
      const keyValidator = shape[key];
      const value = ctx.data[key];
      pairs.push({
        key: { status: "valid", value: key },
        value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
        alwaysSet: key in ctx.data
      });
    }
    if (this._def.catchall instanceof ZodNever) {
      const unknownKeys = this._def.unknownKeys;
      if (unknownKeys === "passthrough") {
        for (const key of extraKeys) {
          pairs.push({
            key: { status: "valid", value: key },
            value: { status: "valid", value: ctx.data[key] }
          });
        }
      } else if (unknownKeys === "strict") {
        if (extraKeys.length > 0) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.unrecognized_keys,
            keys: extraKeys
          });
          status.dirty();
        }
      } else if (unknownKeys === "strip") ;
      else {
        throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
      }
    } else {
      const catchall = this._def.catchall;
      for (const key of extraKeys) {
        const value = ctx.data[key];
        pairs.push({
          key: { status: "valid", value: key },
          value: catchall._parse(
            new ParseInputLazyPath(ctx, value, ctx.path, key)
            //, ctx.child(key), value, getParsedType(value)
          ),
          alwaysSet: key in ctx.data
        });
      }
    }
    if (ctx.common.async) {
      return Promise.resolve().then(async () => {
        const syncPairs = [];
        for (const pair of pairs) {
          const key = await pair.key;
          const value = await pair.value;
          syncPairs.push({
            key,
            value,
            alwaysSet: pair.alwaysSet
          });
        }
        return syncPairs;
      }).then((syncPairs) => {
        return ParseStatus.mergeObjectSync(status, syncPairs);
      });
    } else {
      return ParseStatus.mergeObjectSync(status, pairs);
    }
  }
  get shape() {
    return this._def.shape();
  }
  strict(message) {
    errorUtil.errToObj;
    return new ZodObject({
      ...this._def,
      unknownKeys: "strict",
      ...message !== void 0 ? {
        errorMap: /* @__PURE__ */ __name((issue, ctx) => {
          var _a2, _b, _c, _d;
          const defaultError = (_c = (_b = (_a2 = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a2, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError;
          if (issue.code === "unrecognized_keys")
            return {
              message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError
            };
          return {
            message: defaultError
          };
        }, "errorMap")
      } : {}
    });
  }
  strip() {
    return new ZodObject({
      ...this._def,
      unknownKeys: "strip"
    });
  }
  passthrough() {
    return new ZodObject({
      ...this._def,
      unknownKeys: "passthrough"
    });
  }
  // const AugmentFactory =
  //   <Def extends ZodObjectDef>(def: Def) =>
  //   <Augmentation extends ZodRawShape>(
  //     augmentation: Augmentation
  //   ): ZodObject<
  //     extendShape<ReturnType<Def["shape"]>, Augmentation>,
  //     Def["unknownKeys"],
  //     Def["catchall"]
  //   > => {
  //     return new ZodObject({
  //       ...def,
  //       shape: () => ({
  //         ...def.shape(),
  //         ...augmentation,
  //       }),
  //     }) as any;
  //   };
  extend(augmentation) {
    return new ZodObject({
      ...this._def,
      shape: /* @__PURE__ */ __name(() => ({
        ...this._def.shape(),
        ...augmentation
      }), "shape")
    });
  }
  /**
   * Prior to zod@1.0.12 there was a bug in the
   * inferred type of merged objects. Please
   * upgrade if you are experiencing issues.
   */
  merge(merging) {
    const merged = new ZodObject({
      unknownKeys: merging._def.unknownKeys,
      catchall: merging._def.catchall,
      shape: /* @__PURE__ */ __name(() => ({
        ...this._def.shape(),
        ...merging._def.shape()
      }), "shape"),
      typeName: ZodFirstPartyTypeKind.ZodObject
    });
    return merged;
  }
  // merge<
  //   Incoming extends AnyZodObject,
  //   Augmentation extends Incoming["shape"],
  //   NewOutput extends {
  //     [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
  //       ? Augmentation[k]["_output"]
  //       : k extends keyof Output
  //       ? Output[k]
  //       : never;
  //   },
  //   NewInput extends {
  //     [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
  //       ? Augmentation[k]["_input"]
  //       : k extends keyof Input
  //       ? Input[k]
  //       : never;
  //   }
  // >(
  //   merging: Incoming
  // ): ZodObject<
  //   extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
  //   Incoming["_def"]["unknownKeys"],
  //   Incoming["_def"]["catchall"],
  //   NewOutput,
  //   NewInput
  // > {
  //   const merged: any = new ZodObject({
  //     unknownKeys: merging._def.unknownKeys,
  //     catchall: merging._def.catchall,
  //     shape: () =>
  //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
  //     typeName: ZodFirstPartyTypeKind.ZodObject,
  //   }) as any;
  //   return merged;
  // }
  setKey(key, schema2) {
    return this.augment({ [key]: schema2 });
  }
  // merge<Incoming extends AnyZodObject>(
  //   merging: Incoming
  // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
  // ZodObject<
  //   extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
  //   Incoming["_def"]["unknownKeys"],
  //   Incoming["_def"]["catchall"]
  // > {
  //   // const mergedShape = objectUtil.mergeShapes(
  //   //   this._def.shape(),
  //   //   merging._def.shape()
  //   // );
  //   const merged: any = new ZodObject({
  //     unknownKeys: merging._def.unknownKeys,
  //     catchall: merging._def.catchall,
  //     shape: () =>
  //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
  //     typeName: ZodFirstPartyTypeKind.ZodObject,
  //   }) as any;
  //   return merged;
  // }
  catchall(index2) {
    return new ZodObject({
      ...this._def,
      catchall: index2
    });
  }
  pick(mask) {
    const shape = {};
    util.objectKeys(mask).forEach((key) => {
      if (mask[key] && this.shape[key]) {
        shape[key] = this.shape[key];
      }
    });
    return new ZodObject({
      ...this._def,
      shape: /* @__PURE__ */ __name(() => shape, "shape")
    });
  }
  omit(mask) {
    const shape = {};
    util.objectKeys(this.shape).forEach((key) => {
      if (!mask[key]) {
        shape[key] = this.shape[key];
      }
    });
    return new ZodObject({
      ...this._def,
      shape: /* @__PURE__ */ __name(() => shape, "shape")
    });
  }
  /**
   * @deprecated
   */
  deepPartial() {
    return deepPartialify(this);
  }
  partial(mask) {
    const newShape = {};
    util.objectKeys(this.shape).forEach((key) => {
      const fieldSchema = this.shape[key];
      if (mask && !mask[key]) {
        newShape[key] = fieldSchema;
      } else {
        newShape[key] = fieldSchema.optional();
      }
    });
    return new ZodObject({
      ...this._def,
      shape: /* @__PURE__ */ __name(() => newShape, "shape")
    });
  }
  required(mask) {
    const newShape = {};
    util.objectKeys(this.shape).forEach((key) => {
      if (mask && !mask[key]) {
        newShape[key] = this.shape[key];
      } else {
        const fieldSchema = this.shape[key];
        let newField = fieldSchema;
        while (newField instanceof ZodOptional) {
          newField = newField._def.innerType;
        }
        newShape[key] = newField;
      }
    });
    return new ZodObject({
      ...this._def,
      shape: /* @__PURE__ */ __name(() => newShape, "shape")
    });
  }
  keyof() {
    return createZodEnum(util.objectKeys(this.shape));
  }
}
ZodObject.create = (shape, params) => {
  return new ZodObject({
    shape: /* @__PURE__ */ __name(() => shape, "shape"),
    unknownKeys: "strip",
    catchall: ZodNever.create(),
    typeName: ZodFirstPartyTypeKind.ZodObject,
    ...processCreateParams(params)
  });
};
ZodObject.strictCreate = (shape, params) => {
  return new ZodObject({
    shape: /* @__PURE__ */ __name(() => shape, "shape"),
    unknownKeys: "strict",
    catchall: ZodNever.create(),
    typeName: ZodFirstPartyTypeKind.ZodObject,
    ...processCreateParams(params)
  });
};
ZodObject.lazycreate = (shape, params) => {
  return new ZodObject({
    shape,
    unknownKeys: "strip",
    catchall: ZodNever.create(),
    typeName: ZodFirstPartyTypeKind.ZodObject,
    ...processCreateParams(params)
  });
};
class ZodUnion extends ZodType {
  static {
    __name(this, "ZodUnion");
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    const options2 = this._def.options;
    function handleResults(results) {
      for (const result of results) {
        if (result.result.status === "valid") {
          return result.result;
        }
      }
      for (const result of results) {
        if (result.result.status === "dirty") {
          ctx.common.issues.push(...result.ctx.common.issues);
          return result.result;
        }
      }
      const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_union,
        unionErrors
      });
      return INVALID;
    }
    __name(handleResults, "handleResults");
    if (ctx.common.async) {
      return Promise.all(options2.map(async (option) => {
        const childCtx = {
          ...ctx,
          common: {
            ...ctx.common,
            issues: []
          },
          parent: null
        };
        return {
          result: await option._parseAsync({
            data: ctx.data,
            path: ctx.path,
            parent: childCtx
          }),
          ctx: childCtx
        };
      })).then(handleResults);
    } else {
      let dirty = void 0;
      const issues = [];
      for (const option of options2) {
        const childCtx = {
          ...ctx,
          common: {
            ...ctx.common,
            issues: []
          },
          parent: null
        };
        const result = option._parseSync({
          data: ctx.data,
          path: ctx.path,
          parent: childCtx
        });
        if (result.status === "valid") {
          return result;
        } else if (result.status === "dirty" && !dirty) {
          dirty = { result, ctx: childCtx };
        }
        if (childCtx.common.issues.length) {
          issues.push(childCtx.common.issues);
        }
      }
      if (dirty) {
        ctx.common.issues.push(...dirty.ctx.common.issues);
        return dirty.result;
      }
      const unionErrors = issues.map((issues2) => new ZodError(issues2));
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_union,
        unionErrors
      });
      return INVALID;
    }
  }
  get options() {
    return this._def.options;
  }
}
ZodUnion.create = (types, params) => {
  return new ZodUnion({
    options: types,
    typeName: ZodFirstPartyTypeKind.ZodUnion,
    ...processCreateParams(params)
  });
};
const getDiscriminator = /* @__PURE__ */ __name((type) => {
  if (type instanceof ZodLazy) {
    return getDiscriminator(type.schema);
  } else if (type instanceof ZodEffects) {
    return getDiscriminator(type.innerType());
  } else if (type instanceof ZodLiteral) {
    return [type.value];
  } else if (type instanceof ZodEnum) {
    return type.options;
  } else if (type instanceof ZodNativeEnum) {
    return util.objectValues(type.enum);
  } else if (type instanceof ZodDefault) {
    return getDiscriminator(type._def.innerType);
  } else if (type instanceof ZodUndefined) {
    return [void 0];
  } else if (type instanceof ZodNull) {
    return [null];
  } else if (type instanceof ZodOptional) {
    return [void 0, ...getDiscriminator(type.unwrap())];
  } else if (type instanceof ZodNullable) {
    return [null, ...getDiscriminator(type.unwrap())];
  } else if (type instanceof ZodBranded) {
    return getDiscriminator(type.unwrap());
  } else if (type instanceof ZodReadonly) {
    return getDiscriminator(type.unwrap());
  } else if (type instanceof ZodCatch) {
    return getDiscriminator(type._def.innerType);
  } else {
    return [];
  }
}, "getDiscriminator");
class ZodDiscriminatedUnion extends ZodType {
  static {
    __name(this, "ZodDiscriminatedUnion");
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.object) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.object,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const discriminator = this.discriminator;
    const discriminatorValue = ctx.data[discriminator];
    const option = this.optionsMap.get(discriminatorValue);
    if (!option) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_union_discriminator,
        options: Array.from(this.optionsMap.keys()),
        path: [discriminator]
      });
      return INVALID;
    }
    if (ctx.common.async) {
      return option._parseAsync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      });
    } else {
      return option._parseSync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      });
    }
  }
  get discriminator() {
    return this._def.discriminator;
  }
  get options() {
    return this._def.options;
  }
  get optionsMap() {
    return this._def.optionsMap;
  }
  /**
   * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
   * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
   * have a different value for each object in the union.
   * @param discriminator the name of the discriminator property
   * @param types an array of object schemas
   * @param params
   */
  static create(discriminator, options2, params) {
    const optionsMap = /* @__PURE__ */ new Map();
    for (const type of options2) {
      const discriminatorValues = getDiscriminator(type.shape[discriminator]);
      if (!discriminatorValues.length) {
        throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
      }
      for (const value of discriminatorValues) {
        if (optionsMap.has(value)) {
          throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
        }
        optionsMap.set(value, type);
      }
    }
    return new ZodDiscriminatedUnion({
      typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
      discriminator,
      options: options2,
      optionsMap,
      ...processCreateParams(params)
    });
  }
}
function mergeValues(a2, b2) {
  const aType = getParsedType(a2);
  const bType = getParsedType(b2);
  if (a2 === b2) {
    return { valid: true, data: a2 };
  } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
    const bKeys = util.objectKeys(b2);
    const sharedKeys = util.objectKeys(a2).filter((key) => bKeys.indexOf(key) !== -1);
    const newObj = { ...a2, ...b2 };
    for (const key of sharedKeys) {
      const sharedValue = mergeValues(a2[key], b2[key]);
      if (!sharedValue.valid) {
        return { valid: false };
      }
      newObj[key] = sharedValue.data;
    }
    return { valid: true, data: newObj };
  } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
    if (a2.length !== b2.length) {
      return { valid: false };
    }
    const newArray = [];
    for (let index2 = 0; index2 < a2.length; index2++) {
      const itemA = a2[index2];
      const itemB = b2[index2];
      const sharedValue = mergeValues(itemA, itemB);
      if (!sharedValue.valid) {
        return { valid: false };
      }
      newArray.push(sharedValue.data);
    }
    return { valid: true, data: newArray };
  } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a2 === +b2) {
    return { valid: true, data: a2 };
  } else {
    return { valid: false };
  }
}
__name(mergeValues, "mergeValues");
class ZodIntersection extends ZodType {
  static {
    __name(this, "ZodIntersection");
  }
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    const handleParsed = /* @__PURE__ */ __name((parsedLeft, parsedRight) => {
      if (isAborted(parsedLeft) || isAborted(parsedRight)) {
        return INVALID;
      }
      const merged = mergeValues(parsedLeft.value, parsedRight.value);
      if (!merged.valid) {
        addIssueToContext(ctx, {
          code: ZodIssueCode.invalid_intersection_types
        });
        return INVALID;
      }
      if (isDirty(parsedLeft) || isDirty(parsedRight)) {
        status.dirty();
      }
      return { status: status.value, value: merged.data };
    }, "handleParsed");
    if (ctx.common.async) {
      return Promise.all([
        this._def.left._parseAsync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        }),
        this._def.right._parseAsync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        })
      ]).then(([left, right]) => handleParsed(left, right));
    } else {
      return handleParsed(this._def.left._parseSync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      }), this._def.right._parseSync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      }));
    }
  }
}
ZodIntersection.create = (left, right, params) => {
  return new ZodIntersection({
    left,
    right,
    typeName: ZodFirstPartyTypeKind.ZodIntersection,
    ...processCreateParams(params)
  });
};
class ZodTuple extends ZodType {
  static {
    __name(this, "ZodTuple");
  }
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.array) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.array,
        received: ctx.parsedType
      });
      return INVALID;
    }
    if (ctx.data.length < this._def.items.length) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.too_small,
        minimum: this._def.items.length,
        inclusive: true,
        exact: false,
        type: "array"
      });
      return INVALID;
    }
    const rest = this._def.rest;
    if (!rest && ctx.data.length > this._def.items.length) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.too_big,
        maximum: this._def.items.length,
        inclusive: true,
        exact: false,
        type: "array"
      });
      status.dirty();
    }
    const items = [...ctx.data].map((item, itemIndex) => {
      const schema2 = this._def.items[itemIndex] || this._def.rest;
      if (!schema2)
        return null;
      return schema2._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
    }).filter((x2) => !!x2);
    if (ctx.common.async) {
      return Promise.all(items).then((results) => {
        return ParseStatus.mergeArray(status, results);
      });
    } else {
      return ParseStatus.mergeArray(status, items);
    }
  }
  get items() {
    return this._def.items;
  }
  rest(rest) {
    return new ZodTuple({
      ...this._def,
      rest
    });
  }
}
ZodTuple.create = (schemas, params) => {
  if (!Array.isArray(schemas)) {
    throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
  }
  return new ZodTuple({
    items: schemas,
    typeName: ZodFirstPartyTypeKind.ZodTuple,
    rest: null,
    ...processCreateParams(params)
  });
};
class ZodRecord extends ZodType {
  static {
    __name(this, "ZodRecord");
  }
  get keySchema() {
    return this._def.keyType;
  }
  get valueSchema() {
    return this._def.valueType;
  }
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.object) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.object,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const pairs = [];
    const keyType = this._def.keyType;
    const valueType = this._def.valueType;
    for (const key in ctx.data) {
      pairs.push({
        key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
        value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
        alwaysSet: key in ctx.data
      });
    }
    if (ctx.common.async) {
      return ParseStatus.mergeObjectAsync(status, pairs);
    } else {
      return ParseStatus.mergeObjectSync(status, pairs);
    }
  }
  get element() {
    return this._def.valueType;
  }
  static create(first2, second, third) {
    if (second instanceof ZodType) {
      return new ZodRecord({
        keyType: first2,
        valueType: second,
        typeName: ZodFirstPartyTypeKind.ZodRecord,
        ...processCreateParams(third)
      });
    }
    return new ZodRecord({
      keyType: ZodString.create(),
      valueType: first2,
      typeName: ZodFirstPartyTypeKind.ZodRecord,
      ...processCreateParams(second)
    });
  }
}
class ZodMap extends ZodType {
  static {
    __name(this, "ZodMap");
  }
  get keySchema() {
    return this._def.keyType;
  }
  get valueSchema() {
    return this._def.valueType;
  }
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.map) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.map,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const keyType = this._def.keyType;
    const valueType = this._def.valueType;
    const pairs = [...ctx.data.entries()].map(([key, value], index2) => {
      return {
        key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index2, "key"])),
        value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index2, "value"]))
      };
    });
    if (ctx.common.async) {
      const finalMap = /* @__PURE__ */ new Map();
      return Promise.resolve().then(async () => {
        for (const pair of pairs) {
          const key = await pair.key;
          const value = await pair.value;
          if (key.status === "aborted" || value.status === "aborted") {
            return INVALID;
          }
          if (key.status === "dirty" || value.status === "dirty") {
            status.dirty();
          }
          finalMap.set(key.value, value.value);
        }
        return { status: status.value, value: finalMap };
      });
    } else {
      const finalMap = /* @__PURE__ */ new Map();
      for (const pair of pairs) {
        const key = pair.key;
        const value = pair.value;
        if (key.status === "aborted" || value.status === "aborted") {
          return INVALID;
        }
        if (key.status === "dirty" || value.status === "dirty") {
          status.dirty();
        }
        finalMap.set(key.value, value.value);
      }
      return { status: status.value, value: finalMap };
    }
  }
}
ZodMap.create = (keyType, valueType, params) => {
  return new ZodMap({
    valueType,
    keyType,
    typeName: ZodFirstPartyTypeKind.ZodMap,
    ...processCreateParams(params)
  });
};
class ZodSet extends ZodType {
  static {
    __name(this, "ZodSet");
  }
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.set) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.set,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const def = this._def;
    if (def.minSize !== null) {
      if (ctx.data.size < def.minSize.value) {
        addIssueToContext(ctx, {
          code: ZodIssueCode.too_small,
          minimum: def.minSize.value,
          type: "set",
          inclusive: true,
          exact: false,
          message: def.minSize.message
        });
        status.dirty();
      }
    }
    if (def.maxSize !== null) {
      if (ctx.data.size > def.maxSize.value) {
        addIssueToContext(ctx, {
          code: ZodIssueCode.too_big,
          maximum: def.maxSize.value,
          type: "set",
          inclusive: true,
          exact: false,
          message: def.maxSize.message
        });
        status.dirty();
      }
    }
    const valueType = this._def.valueType;
    function finalizeSet(elements2) {
      const parsedSet = /* @__PURE__ */ new Set();
      for (const element of elements2) {
        if (element.status === "aborted")
          return INVALID;
        if (element.status === "dirty")
          status.dirty();
        parsedSet.add(element.value);
      }
      return { status: status.value, value: parsedSet };
    }
    __name(finalizeSet, "finalizeSet");
    const elements = [...ctx.data.values()].map((item, i2) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i2)));
    if (ctx.common.async) {
      return Promise.all(elements).then((elements2) => finalizeSet(elements2));
    } else {
      return finalizeSet(elements);
    }
  }
  min(minSize, message) {
    return new ZodSet({
      ...this._def,
      minSize: { value: minSize, message: errorUtil.toString(message) }
    });
  }
  max(maxSize, message) {
    return new ZodSet({
      ...this._def,
      maxSize: { value: maxSize, message: errorUtil.toString(message) }
    });
  }
  size(size, message) {
    return this.min(size, message).max(size, message);
  }
  nonempty(message) {
    return this.min(1, message);
  }
}
ZodSet.create = (valueType, params) => {
  return new ZodSet({
    valueType,
    minSize: null,
    maxSize: null,
    typeName: ZodFirstPartyTypeKind.ZodSet,
    ...processCreateParams(params)
  });
};
class ZodFunction extends ZodType {
  static {
    __name(this, "ZodFunction");
  }
  constructor() {
    super(...arguments);
    this.validate = this.implement;
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.function) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.function,
        received: ctx.parsedType
      });
      return INVALID;
    }
    function makeArgsIssue(args, error2) {
      return makeIssue({
        data: args,
        path: ctx.path,
        errorMaps: [
          ctx.common.contextualErrorMap,
          ctx.schemaErrorMap,
          getErrorMap(),
          errorMap$1
        ].filter((x2) => !!x2),
        issueData: {
          code: ZodIssueCode.invalid_arguments,
          argumentsError: error2
        }
      });
    }
    __name(makeArgsIssue, "makeArgsIssue");
    function makeReturnsIssue(returns, error2) {
      return makeIssue({
        data: returns,
        path: ctx.path,
        errorMaps: [
          ctx.common.contextualErrorMap,
          ctx.schemaErrorMap,
          getErrorMap(),
          errorMap$1
        ].filter((x2) => !!x2),
        issueData: {
          code: ZodIssueCode.invalid_return_type,
          returnTypeError: error2
        }
      });
    }
    __name(makeReturnsIssue, "makeReturnsIssue");
    const params = { errorMap: ctx.common.contextualErrorMap };
    const fn = ctx.data;
    if (this._def.returns instanceof ZodPromise) {
      const me2 = this;
      return OK(async function(...args) {
        const error2 = new ZodError([]);
        const parsedArgs = await me2._def.args.parseAsync(args, params).catch((e2) => {
          error2.addIssue(makeArgsIssue(args, e2));
          throw error2;
        });
        const result = await Reflect.apply(fn, this, parsedArgs);
        const parsedReturns = await me2._def.returns._def.type.parseAsync(result, params).catch((e2) => {
          error2.addIssue(makeReturnsIssue(result, e2));
          throw error2;
        });
        return parsedReturns;
      });
    } else {
      const me2 = this;
      return OK(function(...args) {
        const parsedArgs = me2._def.args.safeParse(args, params);
        if (!parsedArgs.success) {
          throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
        }
        const result = Reflect.apply(fn, this, parsedArgs.data);
        const parsedReturns = me2._def.returns.safeParse(result, params);
        if (!parsedReturns.success) {
          throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
        }
        return parsedReturns.data;
      });
    }
  }
  parameters() {
    return this._def.args;
  }
  returnType() {
    return this._def.returns;
  }
  args(...items) {
    return new ZodFunction({
      ...this._def,
      args: ZodTuple.create(items).rest(ZodUnknown.create())
    });
  }
  returns(returnType) {
    return new ZodFunction({
      ...this._def,
      returns: returnType
    });
  }
  implement(func) {
    const validatedFunc = this.parse(func);
    return validatedFunc;
  }
  strictImplement(func) {
    const validatedFunc = this.parse(func);
    return validatedFunc;
  }
  static create(args, returns, params) {
    return new ZodFunction({
      args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
      returns: returns || ZodUnknown.create(),
      typeName: ZodFirstPartyTypeKind.ZodFunction,
      ...processCreateParams(params)
    });
  }
}
class ZodLazy extends ZodType {
  static {
    __name(this, "ZodLazy");
  }
  get schema() {
    return this._def.getter();
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    const lazySchema = this._def.getter();
    return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
  }
}
ZodLazy.create = (getter, params) => {
  return new ZodLazy({
    getter,
    typeName: ZodFirstPartyTypeKind.ZodLazy,
    ...processCreateParams(params)
  });
};
class ZodLiteral extends ZodType {
  static {
    __name(this, "ZodLiteral");
  }
  _parse(input) {
    if (input.data !== this._def.value) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        received: ctx.data,
        code: ZodIssueCode.invalid_literal,
        expected: this._def.value
      });
      return INVALID;
    }
    return { status: "valid", value: input.data };
  }
  get value() {
    return this._def.value;
  }
}
ZodLiteral.create = (value, params) => {
  return new ZodLiteral({
    value,
    typeName: ZodFirstPartyTypeKind.ZodLiteral,
    ...processCreateParams(params)
  });
};
function createZodEnum(values, params) {
  return new ZodEnum({
    values,
    typeName: ZodFirstPartyTypeKind.ZodEnum,
    ...processCreateParams(params)
  });
}
__name(createZodEnum, "createZodEnum");
class ZodEnum extends ZodType {
  static {
    __name(this, "ZodEnum");
  }
  constructor() {
    super(...arguments);
    _ZodEnum_cache.set(this, void 0);
  }
  _parse(input) {
    if (typeof input.data !== "string") {
      const ctx = this._getOrReturnCtx(input);
      const expectedValues = this._def.values;
      addIssueToContext(ctx, {
        expected: util.joinValues(expectedValues),
        received: ctx.parsedType,
        code: ZodIssueCode.invalid_type
      });
      return INVALID;
    }
    if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f")) {
      __classPrivateFieldSet(this, _ZodEnum_cache, new Set(this._def.values), "f");
    }
    if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f").has(input.data)) {
      const ctx = this._getOrReturnCtx(input);
      const expectedValues = this._def.values;
      addIssueToContext(ctx, {
        received: ctx.data,
        code: ZodIssueCode.invalid_enum_value,
        options: expectedValues
      });
      return INVALID;
    }
    return OK(input.data);
  }
  get options() {
    return this._def.values;
  }
  get enum() {
    const enumValues = {};
    for (const val of this._def.values) {
      enumValues[val] = val;
    }
    return enumValues;
  }
  get Values() {
    const enumValues = {};
    for (const val of this._def.values) {
      enumValues[val] = val;
    }
    return enumValues;
  }
  get Enum() {
    const enumValues = {};
    for (const val of this._def.values) {
      enumValues[val] = val;
    }
    return enumValues;
  }
  extract(values, newDef = this._def) {
    return ZodEnum.create(values, {
      ...this._def,
      ...newDef
    });
  }
  exclude(values, newDef = this._def) {
    return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
      ...this._def,
      ...newDef
    });
  }
}
_ZodEnum_cache = /* @__PURE__ */ new WeakMap();
ZodEnum.create = createZodEnum;
class ZodNativeEnum extends ZodType {
  static {
    __name(this, "ZodNativeEnum");
  }
  constructor() {
    super(...arguments);
    _ZodNativeEnum_cache.set(this, void 0);
  }
  _parse(input) {
    const nativeEnumValues = util.getValidEnumValues(this._def.values);
    const ctx = this._getOrReturnCtx(input);
    if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
      const expectedValues = util.objectValues(nativeEnumValues);
      addIssueToContext(ctx, {
        expected: util.joinValues(expectedValues),
        received: ctx.parsedType,
        code: ZodIssueCode.invalid_type
      });
      return INVALID;
    }
    if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f")) {
      __classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(util.getValidEnumValues(this._def.values)), "f");
    }
    if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f").has(input.data)) {
      const expectedValues = util.objectValues(nativeEnumValues);
      addIssueToContext(ctx, {
        received: ctx.data,
        code: ZodIssueCode.invalid_enum_value,
        options: expectedValues
      });
      return INVALID;
    }
    return OK(input.data);
  }
  get enum() {
    return this._def.values;
  }
}
_ZodNativeEnum_cache = /* @__PURE__ */ new WeakMap();
ZodNativeEnum.create = (values, params) => {
  return new ZodNativeEnum({
    values,
    typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
    ...processCreateParams(params)
  });
};
class ZodPromise extends ZodType {
  static {
    __name(this, "ZodPromise");
  }
  unwrap() {
    return this._def.type;
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.promise,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
    return OK(promisified.then((data) => {
      return this._def.type.parseAsync(data, {
        path: ctx.path,
        errorMap: ctx.common.contextualErrorMap
      });
    }));
  }
}
ZodPromise.create = (schema2, params) => {
  return new ZodPromise({
    type: schema2,
    typeName: ZodFirstPartyTypeKind.ZodPromise,
    ...processCreateParams(params)
  });
};
class ZodEffects extends ZodType {
  static {
    __name(this, "ZodEffects");
  }
  innerType() {
    return this._def.schema;
  }
  sourceType() {
    return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
  }
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    const effect = this._def.effect || null;
    const checkCtx = {
      addIssue: /* @__PURE__ */ __name((arg) => {
        addIssueToContext(ctx, arg);
        if (arg.fatal) {
          status.abort();
        } else {
          status.dirty();
        }
      }, "addIssue"),
      get path() {
        return ctx.path;
      }
    };
    checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
    if (effect.type === "preprocess") {
      const processed = effect.transform(ctx.data, checkCtx);
      if (ctx.common.async) {
        return Promise.resolve(processed).then(async (processed2) => {
          if (status.value === "aborted")
            return INVALID;
          const result = await this._def.schema._parseAsync({
            data: processed2,
            path: ctx.path,
            parent: ctx
          });
          if (result.status === "aborted")
            return INVALID;
          if (result.status === "dirty")
            return DIRTY(result.value);
          if (status.value === "dirty")
            return DIRTY(result.value);
          return result;
        });
      } else {
        if (status.value === "aborted")
          return INVALID;
        const result = this._def.schema._parseSync({
          data: processed,
          path: ctx.path,
          parent: ctx
        });
        if (result.status === "aborted")
          return INVALID;
        if (result.status === "dirty")
          return DIRTY(result.value);
        if (status.value === "dirty")
          return DIRTY(result.value);
        return result;
      }
    }
    if (effect.type === "refinement") {
      const executeRefinement = /* @__PURE__ */ __name((acc) => {
        const result = effect.refinement(acc, checkCtx);
        if (ctx.common.async) {
          return Promise.resolve(result);
        }
        if (result instanceof Promise) {
          throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
        }
        return acc;
      }, "executeRefinement");
      if (ctx.common.async === false) {
        const inner = this._def.schema._parseSync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        });
        if (inner.status === "aborted")
          return INVALID;
        if (inner.status === "dirty")
          status.dirty();
        executeRefinement(inner.value);
        return { status: status.value, value: inner.value };
      } else {
        return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
          if (inner.status === "aborted")
            return INVALID;
          if (inner.status === "dirty")
            status.dirty();
          return executeRefinement(inner.value).then(() => {
            return { status: status.value, value: inner.value };
          });
        });
      }
    }
    if (effect.type === "transform") {
      if (ctx.common.async === false) {
        const base2 = this._def.schema._parseSync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        });
        if (!isValid(base2))
          return base2;
        const result = effect.transform(base2.value, checkCtx);
        if (result instanceof Promise) {
          throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
        }
        return { status: status.value, value: result };
      } else {
        return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base2) => {
          if (!isValid(base2))
            return base2;
          return Promise.resolve(effect.transform(base2.value, checkCtx)).then((result) => ({ status: status.value, value: result }));
        });
      }
    }
    util.assertNever(effect);
  }
}
ZodEffects.create = (schema2, effect, params) => {
  return new ZodEffects({
    schema: schema2,
    typeName: ZodFirstPartyTypeKind.ZodEffects,
    effect,
    ...processCreateParams(params)
  });
};
ZodEffects.createWithPreprocess = (preprocess, schema2, params) => {
  return new ZodEffects({
    schema: schema2,
    effect: { type: "preprocess", transform: preprocess },
    typeName: ZodFirstPartyTypeKind.ZodEffects,
    ...processCreateParams(params)
  });
};
class ZodOptional extends ZodType {
  static {
    __name(this, "ZodOptional");
  }
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType === ZodParsedType.undefined) {
      return OK(void 0);
    }
    return this._def.innerType._parse(input);
  }
  unwrap() {
    return this._def.innerType;
  }
}
ZodOptional.create = (type, params) => {
  return new ZodOptional({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodOptional,
    ...processCreateParams(params)
  });
};
class ZodNullable extends ZodType {
  static {
    __name(this, "ZodNullable");
  }
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType === ZodParsedType.null) {
      return OK(null);
    }
    return this._def.innerType._parse(input);
  }
  unwrap() {
    return this._def.innerType;
  }
}
ZodNullable.create = (type, params) => {
  return new ZodNullable({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodNullable,
    ...processCreateParams(params)
  });
};
class ZodDefault extends ZodType {
  static {
    __name(this, "ZodDefault");
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    let data = ctx.data;
    if (ctx.parsedType === ZodParsedType.undefined) {
      data = this._def.defaultValue();
    }
    return this._def.innerType._parse({
      data,
      path: ctx.path,
      parent: ctx
    });
  }
  removeDefault() {
    return this._def.innerType;
  }
}
ZodDefault.create = (type, params) => {
  return new ZodDefault({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodDefault,
    defaultValue: typeof params.default === "function" ? params.default : () => params.default,
    ...processCreateParams(params)
  });
};
class ZodCatch extends ZodType {
  static {
    __name(this, "ZodCatch");
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    const newCtx = {
      ...ctx,
      common: {
        ...ctx.common,
        issues: []
      }
    };
    const result = this._def.innerType._parse({
      data: newCtx.data,
      path: newCtx.path,
      parent: {
        ...newCtx
      }
    });
    if (isAsync(result)) {
      return result.then((result2) => {
        return {
          status: "valid",
          value: result2.status === "valid" ? result2.value : this._def.catchValue({
            get error() {
              return new ZodError(newCtx.common.issues);
            },
            input: newCtx.data
          })
        };
      });
    } else {
      return {
        status: "valid",
        value: result.status === "valid" ? result.value : this._def.catchValue({
          get error() {
            return new ZodError(newCtx.common.issues);
          },
          input: newCtx.data
        })
      };
    }
  }
  removeCatch() {
    return this._def.innerType;
  }
}
ZodCatch.create = (type, params) => {
  return new ZodCatch({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodCatch,
    catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
    ...processCreateParams(params)
  });
};
class ZodNaN extends ZodType {
  static {
    __name(this, "ZodNaN");
  }
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.nan) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.nan,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return { status: "valid", value: input.data };
  }
}
ZodNaN.create = (params) => {
  return new ZodNaN({
    typeName: ZodFirstPartyTypeKind.ZodNaN,
    ...processCreateParams(params)
  });
};
const BRAND = Symbol("zod_brand");
class ZodBranded extends ZodType {
  static {
    __name(this, "ZodBranded");
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    const data = ctx.data;
    return this._def.type._parse({
      data,
      path: ctx.path,
      parent: ctx
    });
  }
  unwrap() {
    return this._def.type;
  }
}
class ZodPipeline extends ZodType {
  static {
    __name(this, "ZodPipeline");
  }
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.common.async) {
      const handleAsync = /* @__PURE__ */ __name(async () => {
        const inResult = await this._def.in._parseAsync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        });
        if (inResult.status === "aborted")
          return INVALID;
        if (inResult.status === "dirty") {
          status.dirty();
          return DIRTY(inResult.value);
        } else {
          return this._def.out._parseAsync({
            data: inResult.value,
            path: ctx.path,
            parent: ctx
          });
        }
      }, "handleAsync");
      return handleAsync();
    } else {
      const inResult = this._def.in._parseSync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      });
      if (inResult.status === "aborted")
        return INVALID;
      if (inResult.status === "dirty") {
        status.dirty();
        return {
          status: "dirty",
          value: inResult.value
        };
      } else {
        return this._def.out._parseSync({
          data: inResult.value,
          path: ctx.path,
          parent: ctx
        });
      }
    }
  }
  static create(a2, b2) {
    return new ZodPipeline({
      in: a2,
      out: b2,
      typeName: ZodFirstPartyTypeKind.ZodPipeline
    });
  }
}
class ZodReadonly extends ZodType {
  static {
    __name(this, "ZodReadonly");
  }
  _parse(input) {
    const result = this._def.innerType._parse(input);
    const freeze = /* @__PURE__ */ __name((data) => {
      if (isValid(data)) {
        data.value = Object.freeze(data.value);
      }
      return data;
    }, "freeze");
    return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
  }
  unwrap() {
    return this._def.innerType;
  }
}
ZodReadonly.create = (type, params) => {
  return new ZodReadonly({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodReadonly,
    ...processCreateParams(params)
  });
};
function custom(check, params = {}, fatal2) {
  if (check)
    return ZodAny.create().superRefine((data, ctx) => {
      var _a2, _b;
      if (!check(data)) {
        const p2 = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
        const _fatal = (_b = (_a2 = p2.fatal) !== null && _a2 !== void 0 ? _a2 : fatal2) !== null && _b !== void 0 ? _b : true;
        const p22 = typeof p2 === "string" ? { message: p2 } : p2;
        ctx.addIssue({ code: "custom", ...p22, fatal: _fatal });
      }
    });
  return ZodAny.create();
}
__name(custom, "custom");
const late = {
  object: ZodObject.lazycreate
};
var ZodFirstPartyTypeKind;
(function(ZodFirstPartyTypeKind2) {
  ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
  ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
  ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
  ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
  ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
  ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
  ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
  ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
  ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
  ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
  ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
  ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
  ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
  ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
  ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
  ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
  ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
  ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
  ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
  ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
  ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
  ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
  ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
  ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
  ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
  ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
  ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
  ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
  ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
  ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
  ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
  ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
  ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
  ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
  ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
  ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
const instanceOfType = /* @__PURE__ */ __name((cls, params = {
  message: `Input not instance of ${cls.name}`
}) => custom((data) => data instanceof cls, params), "instanceOfType");
const stringType = ZodString.create;
const numberType = ZodNumber.create;
const nanType = ZodNaN.create;
const bigIntType = ZodBigInt.create;
const booleanType = ZodBoolean.create;
const dateType = ZodDate.create;
const symbolType = ZodSymbol.create;
const undefinedType = ZodUndefined.create;
const nullType = ZodNull.create;
const anyType = ZodAny.create;
const unknownType = ZodUnknown.create;
const neverType = ZodNever.create;
const voidType = ZodVoid.create;
const arrayType = ZodArray.create;
const objectType = ZodObject.create;
const strictObjectType = ZodObject.strictCreate;
const unionType = ZodUnion.create;
const discriminatedUnionType = ZodDiscriminatedUnion.create;
const intersectionType = ZodIntersection.create;
const tupleType = ZodTuple.create;
const recordType = ZodRecord.create;
const mapType = ZodMap.create;
const setType = ZodSet.create;
const functionType = ZodFunction.create;
const lazyType = ZodLazy.create;
const literalType = ZodLiteral.create;
const enumType = ZodEnum.create;
const nativeEnumType = ZodNativeEnum.create;
const promiseType = ZodPromise.create;
const effectsType = ZodEffects.create;
const optionalType = ZodOptional.create;
const nullableType = ZodNullable.create;
const preprocessType = ZodEffects.createWithPreprocess;
const pipelineType = ZodPipeline.create;
const ostring = /* @__PURE__ */ __name(() => stringType().optional(), "ostring");
const onumber = /* @__PURE__ */ __name(() => numberType().optional(), "onumber");
const oboolean = /* @__PURE__ */ __name(() => booleanType().optional(), "oboolean");
const coerce = {
  string: /* @__PURE__ */ __name((arg) => ZodString.create({ ...arg, coerce: true }), "string"),
  number: /* @__PURE__ */ __name((arg) => ZodNumber.create({ ...arg, coerce: true }), "number"),
  boolean: /* @__PURE__ */ __name((arg) => ZodBoolean.create({
    ...arg,
    coerce: true
  }), "boolean"),
  bigint: /* @__PURE__ */ __name((arg) => ZodBigInt.create({ ...arg, coerce: true }), "bigint"),
  date: /* @__PURE__ */ __name((arg) => ZodDate.create({ ...arg, coerce: true }), "date")
};
const NEVER = INVALID;
var z = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  defaultErrorMap: errorMap$1,
  setErrorMap,
  getErrorMap,
  makeIssue,
  EMPTY_PATH,
  addIssueToContext,
  ParseStatus,
  INVALID,
  DIRTY,
  OK,
  isAborted,
  isDirty,
  isValid,
  isAsync,
  get util() {
    return util;
  },
  get objectUtil() {
    return objectUtil;
  },
  ZodParsedType,
  getParsedType,
  ZodType,
  datetimeRegex,
  ZodString,
  ZodNumber,
  ZodBigInt,
  ZodBoolean,
  ZodDate,
  ZodSymbol,
  ZodUndefined,
  ZodNull,
  ZodAny,
  ZodUnknown,
  ZodNever,
  ZodVoid,
  ZodArray,
  ZodObject,
  ZodUnion,
  ZodDiscriminatedUnion,
  ZodIntersection,
  ZodTuple,
  ZodRecord,
  ZodMap,
  ZodSet,
  ZodFunction,
  ZodLazy,
  ZodLiteral,
  ZodEnum,
  ZodNativeEnum,
  ZodPromise,
  ZodEffects,
  ZodTransformer: ZodEffects,
  ZodOptional,
  ZodNullable,
  ZodDefault,
  ZodCatch,
  ZodNaN,
  BRAND,
  ZodBranded,
  ZodPipeline,
  ZodReadonly,
  custom,
  Schema: ZodType,
  ZodSchema: ZodType,
  late,
  get ZodFirstPartyTypeKind() {
    return ZodFirstPartyTypeKind;
  },
  coerce,
  any: anyType,
  array: arrayType,
  bigint: bigIntType,
  boolean: booleanType,
  date: dateType,
  discriminatedUnion: discriminatedUnionType,
  effect: effectsType,
  "enum": enumType,
  "function": functionType,
  "instanceof": instanceOfType,
  intersection: intersectionType,
  lazy: lazyType,
  literal: literalType,
  map: mapType,
  nan: nanType,
  nativeEnum: nativeEnumType,
  never: neverType,
  "null": nullType,
  nullable: nullableType,
  number: numberType,
  object: objectType,
  oboolean,
  onumber,
  optional: optionalType,
  ostring,
  pipeline: pipelineType,
  preprocess: preprocessType,
  promise: promiseType,
  record: recordType,
  set: setType,
  strictObject: strictObjectType,
  string: stringType,
  symbol: symbolType,
  transformer: effectsType,
  tuple: tupleType,
  "undefined": undefinedType,
  union: unionType,
  unknown: unknownType,
  "void": voidType,
  NEVER,
  ZodIssueCode,
  quotelessJson,
  ZodError
});
function isZodErrorLike(err) {
  return err instanceof Error && err.name === "ZodError" && "issues" in err && Array.isArray(err.issues);
}
__name(isZodErrorLike, "isZodErrorLike");
var ValidationError = class extends Error {
  static {
    __name(this, "ValidationError");
  }
  name;
  details;
  constructor(message, options2) {
    super(message, options2);
    this.name = "ZodValidationError";
    this.details = getIssuesFromErrorOptions(options2);
  }
  toString() {
    return this.message;
  }
};
function getIssuesFromErrorOptions(options2) {
  if (options2) {
    const cause = options2.cause;
    if (isZodErrorLike(cause)) {
      return cause.issues;
    }
  }
  return [];
}
__name(getIssuesFromErrorOptions, "getIssuesFromErrorOptions");
function isValidationError(err) {
  return err instanceof ValidationError;
}
__name(isValidationError, "isValidationError");
function isValidationErrorLike(err) {
  return err instanceof Error && err.name === "ZodValidationError";
}
__name(isValidationErrorLike, "isValidationErrorLike");
var ISSUE_SEPARATOR = "; ";
var MAX_ISSUES_IN_MESSAGE = 99;
var PREFIX = "Validation error";
var PREFIX_SEPARATOR = ": ";
var UNION_SEPARATOR = ", or ";
function prefixMessage(message, prefix, prefixSeparator) {
  if (prefix !== null) {
    if (message.length > 0) {
      return [prefix, message].join(prefixSeparator);
    }
    return prefix;
  }
  if (message.length > 0) {
    return message;
  }
  return PREFIX;
}
__name(prefixMessage, "prefixMessage");
var identifierRegex = /[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*/u;
function joinPath(path) {
  if (path.length === 1) {
    return path[0].toString();
  }
  return path.reduce((acc, item) => {
    if (typeof item === "number") {
      return acc + "[" + item.toString() + "]";
    }
    if (item.includes('"')) {
      return acc + '["' + escapeQuotes(item) + '"]';
    }
    if (!identifierRegex.test(item)) {
      return acc + '["' + item + '"]';
    }
    const separator = acc.length === 0 ? "" : ".";
    return acc + separator + item;
  }, "");
}
__name(joinPath, "joinPath");
function escapeQuotes(str) {
  return str.replace(/"/g, '\\"');
}
__name(escapeQuotes, "escapeQuotes");
function isNonEmptyArray(value) {
  return value.length !== 0;
}
__name(isNonEmptyArray, "isNonEmptyArray");
function getMessageFromZodIssue(props) {
  const { issue, issueSeparator, unionSeparator, includePath } = props;
  if (issue.code === "invalid_union") {
    return issue.unionErrors.reduce((acc, zodError) => {
      const newIssues = zodError.issues.map(
        (issue2) => getMessageFromZodIssue({
          issue: issue2,
          issueSeparator,
          unionSeparator,
          includePath
        })
      ).join(issueSeparator);
      if (!acc.includes(newIssues)) {
        acc.push(newIssues);
      }
      return acc;
    }, []).join(unionSeparator);
  }
  if (issue.code === "invalid_arguments") {
    return [
      issue.message,
      ...issue.argumentsError.issues.map(
        (issue2) => getMessageFromZodIssue({
          issue: issue2,
          issueSeparator,
          unionSeparator,
          includePath
        })
      )
    ].join(issueSeparator);
  }
  if (issue.code === "invalid_return_type") {
    return [
      issue.message,
      ...issue.returnTypeError.issues.map(
        (issue2) => getMessageFromZodIssue({
          issue: issue2,
          issueSeparator,
          unionSeparator,
          includePath
        })
      )
    ].join(issueSeparator);
  }
  if (includePath && isNonEmptyArray(issue.path)) {
    if (issue.path.length === 1) {
      const identifier = issue.path[0];
      if (typeof identifier === "number") {
        return `${issue.message} at index ${identifier}`;
      }
    }
    return `${issue.message} at "${joinPath(issue.path)}"`;
  }
  return issue.message;
}
__name(getMessageFromZodIssue, "getMessageFromZodIssue");
function fromZodIssue(issue, options2 = {}) {
  const {
    issueSeparator = ISSUE_SEPARATOR,
    unionSeparator = UNION_SEPARATOR,
    prefixSeparator = PREFIX_SEPARATOR,
    prefix = PREFIX,
    includePath = true
  } = options2;
  const reason = getMessageFromZodIssue({
    issue,
    issueSeparator,
    unionSeparator,
    includePath
  });
  const message = prefixMessage(reason, prefix, prefixSeparator);
  return new ValidationError(message, { cause: new ZodError([issue]) });
}
__name(fromZodIssue, "fromZodIssue");
var errorMap = /* @__PURE__ */ __name((issue, ctx) => {
  const error2 = fromZodIssue({
    ...issue,
    // fallback to the default error message
    // when issue does not have a message
    message: issue.message ?? ctx.defaultError
  });
  return {
    message: error2.message
  };
}, "errorMap");
function fromZodError(zodError, options2 = {}) {
  if (!isZodErrorLike(zodError)) {
    throw new TypeError(
      `Invalid zodError param; expected instance of ZodError. Did you mean to use the "${fromError.name}" method instead?`
    );
  }
  return fromZodErrorWithoutRuntimeCheck(zodError, options2);
}
__name(fromZodError, "fromZodError");
function fromZodErrorWithoutRuntimeCheck(zodError, options2 = {}) {
  const {
    maxIssuesInMessage = MAX_ISSUES_IN_MESSAGE,
    issueSeparator = ISSUE_SEPARATOR,
    unionSeparator = UNION_SEPARATOR,
    prefixSeparator = PREFIX_SEPARATOR,
    prefix = PREFIX,
    includePath = true
  } = options2;
  const zodIssues = zodError.errors;
  const reason = zodIssues.length === 0 ? zodError.message : zodIssues.slice(0, maxIssuesInMessage).map(
    (issue) => getMessageFromZodIssue({
      issue,
      issueSeparator,
      unionSeparator,
      includePath
    })
  ).join(issueSeparator);
  const message = prefixMessage(reason, prefix, prefixSeparator);
  return new ValidationError(message, { cause: zodError });
}
__name(fromZodErrorWithoutRuntimeCheck, "fromZodErrorWithoutRuntimeCheck");
var toValidationError = /* @__PURE__ */ __name((options2 = {}) => (err) => {
  if (isZodErrorLike(err)) {
    return fromZodErrorWithoutRuntimeCheck(err, options2);
  }
  if (err instanceof Error) {
    return new ValidationError(err.message, { cause: err });
  }
  return new ValidationError("Unknown error");
}, "toValidationError");
function fromError(err, options2 = {}) {
  return toValidationError(options2)(err);
}
__name(fromError, "fromError");
const zComboOption = z.union([z.string(), z.number()]);
const zRemoteWidgetConfig = z.object({
  route: z.string().url().or(z.string().startsWith("/")),
  refresh: z.number().gte(128).safe().or(z.number().lte(0).safe()).optional(),
  response_key: z.string().optional(),
  query_params: z.record(z.string(), z.string()).optional(),
  refresh_button: z.boolean().optional(),
  control_after_refresh: z.enum(["first", "last"]).optional(),
  timeout: z.number().gte(0).optional(),
  max_retries: z.number().gte(0).optional()
});
const zMultiSelectOption = z.object({
  placeholder: z.string().optional(),
  chip: z.boolean().optional()
});
const zBaseInputOptions = z.object({
  default: z.any().optional(),
  defaultInput: z.boolean().optional(),
  forceInput: z.boolean().optional(),
  tooltip: z.string().optional(),
  hidden: z.boolean().optional(),
  advanced: z.boolean().optional(),
  widgetType: z.string().optional(),
  /** Backend-only properties. */
  rawLink: z.boolean().optional(),
  lazy: z.boolean().optional()
}).passthrough();
const zNumericInputOptions = zBaseInputOptions.extend({
  min: z.number().optional(),
  max: z.number().optional(),
  step: z.number().optional(),
  /** Note: Many node authors are using INT/FLOAT to pass list of INT/FLOAT. */
  default: z.union([z.number(), z.array(z.number())]).optional(),
  display: z.enum(["slider", "number", "knob"]).optional()
});
const zIntInputOptions = zNumericInputOptions.extend({
  /**
   * If true, a linked widget will be added to the node to select the mode
   * of `control_after_generate`.
   */
  control_after_generate: z.boolean().optional()
});
const zFloatInputOptions = zNumericInputOptions.extend({
  round: z.union([z.number(), z.literal(false)]).optional()
});
const zBooleanInputOptions = zBaseInputOptions.extend({
  label_on: z.string().optional(),
  label_off: z.string().optional(),
  default: z.boolean().optional()
});
const zStringInputOptions = zBaseInputOptions.extend({
  default: z.string().optional(),
  multiline: z.boolean().optional(),
  dynamicPrompts: z.boolean().optional(),
  // Multiline-only fields
  defaultVal: z.string().optional(),
  placeholder: z.string().optional()
});
const zComboInputOptions = zBaseInputOptions.extend({
  control_after_generate: z.boolean().optional(),
  image_upload: z.boolean().optional(),
  image_folder: z.enum(["input", "output", "temp"]).optional(),
  allow_batch: z.boolean().optional(),
  video_upload: z.boolean().optional(),
  animated_image_upload: z.boolean().optional(),
  options: z.array(zComboOption).optional(),
  remote: zRemoteWidgetConfig.optional(),
  /** Whether the widget is a multi-select widget. */
  multi_select: zMultiSelectOption.optional()
});
const zIntInputSpec$1 = z.tuple([z.literal("INT"), zIntInputOptions.optional()]);
const zFloatInputSpec$1 = z.tuple([
  z.literal("FLOAT"),
  zFloatInputOptions.optional()
]);
const zBooleanInputSpec$1 = z.tuple([
  z.literal("BOOLEAN"),
  zBooleanInputOptions.optional()
]);
const zStringInputSpec$1 = z.tuple([
  z.literal("STRING"),
  zStringInputOptions.optional()
]);
const zComboInputSpec$1 = z.tuple([
  z.array(zComboOption),
  zComboInputOptions.optional()
]);
const zComboInputSpecV2 = z.tuple([
  z.literal("COMBO"),
  zComboInputOptions.optional()
]);
function isComboInputSpecV1(inputSpec) {
  return Array.isArray(inputSpec[0]);
}
__name(isComboInputSpecV1, "isComboInputSpecV1");
function isIntInputSpec$1(inputSpec) {
  return inputSpec[0] === "INT";
}
__name(isIntInputSpec$1, "isIntInputSpec$1");
function isFloatInputSpec$1(inputSpec) {
  return inputSpec[0] === "FLOAT";
}
__name(isFloatInputSpec$1, "isFloatInputSpec$1");
function isBooleanInputSpec$1(inputSpec) {
  return inputSpec[0] === "BOOLEAN";
}
__name(isBooleanInputSpec$1, "isBooleanInputSpec$1");
function isStringInputSpec$1(inputSpec) {
  return inputSpec[0] === "STRING";
}
__name(isStringInputSpec$1, "isStringInputSpec$1");
function isComboInputSpecV2(inputSpec) {
  return inputSpec[0] === "COMBO";
}
__name(isComboInputSpecV2, "isComboInputSpecV2");
function isCustomInputSpec(inputSpec) {
  return typeof inputSpec[0] === "string" && !excludedLiterals.has(inputSpec[0]);
}
__name(isCustomInputSpec, "isCustomInputSpec");
function isComboInputSpec$1(inputSpec) {
  return isComboInputSpecV1(inputSpec) || isComboInputSpecV2(inputSpec);
}
__name(isComboInputSpec$1, "isComboInputSpec$1");
function getInputSpecType(inputSpec) {
  return isComboInputSpec$1(inputSpec) ? "COMBO" : inputSpec[0];
}
__name(getInputSpecType, "getInputSpecType");
function getComboSpecComboOptions(inputSpec) {
  return (isComboInputSpecV2(inputSpec) ? inputSpec[1]?.options : inputSpec[0]) ?? [];
}
__name(getComboSpecComboOptions, "getComboSpecComboOptions");
const excludedLiterals = /* @__PURE__ */ new Set(["INT", "FLOAT", "BOOLEAN", "STRING", "COMBO"]);
const zCustomInputSpec$1 = z.tuple([
  z.string().refine((value) => !excludedLiterals.has(value)),
  zBaseInputOptions.optional()
]);
const zInputSpec$1 = z.union([
  zIntInputSpec$1,
  zFloatInputSpec$1,
  zBooleanInputSpec$1,
  zStringInputSpec$1,
  zComboInputSpec$1,
  zComboInputSpecV2,
  zCustomInputSpec$1
]);
const zComfyInputsSpec = z.object({
  required: z.record(zInputSpec$1).optional(),
  optional: z.record(zInputSpec$1).optional(),
  // Frontend repo is not using it, but some custom nodes are using the
  // hidden field to pass various values.
  hidden: z.record(z.any()).optional()
});
const zComfyNodeDataType = z.string();
const zComfyComboOutput = z.array(zComboOption);
const zComfyOutputTypesSpec = z.array(
  z.union([zComfyNodeDataType, zComfyComboOutput])
);
const zComfyNodeDef$1 = z.object({
  input: zComfyInputsSpec.optional(),
  output: zComfyOutputTypesSpec.optional(),
  output_is_list: z.array(z.boolean()).optional(),
  output_name: z.array(z.string()).optional(),
  output_tooltips: z.array(z.string()).optional(),
  name: z.string(),
  display_name: z.string(),
  description: z.string(),
  category: z.string(),
  output_node: z.boolean(),
  python_module: z.string(),
  deprecated: z.boolean().optional(),
  experimental: z.boolean().optional(),
  /**
   * Whether the node is an API node. Running API nodes requires login to
   * Comfy Org account.
   * https://www.comfy.org/faq
   */
  api_node: z.boolean().optional()
});
function validateComfyNodeDef(data, onError = console.warn) {
  const result = zComfyNodeDef$1.safeParse(data);
  if (!result.success) {
    const zodError = fromZodError(result.error);
    onError(
      `Invalid ComfyNodeDef: ${JSON.stringify(data)}
${zodError.message}`
    );
    return null;
  }
  return result.data;
}
__name(validateComfyNodeDef, "validateComfyNodeDef");
class UnauthorizedError extends Error {
  static {
    __name(this, "UnauthorizedError");
  }
}
class PromptExecutionError extends Error {
  static {
    __name(this, "PromptExecutionError");
  }
  response;
  constructor(response) {
    super("Prompt execution failed");
    this.response = response;
  }
  toString() {
    let message = "";
    if (typeof this.response.error === "string") {
      message += this.response.error;
    } else if (this.response.error) {
      message += this.response.error.message + ": " + this.response.error.details;
    }
    for (const [_2, nodeError] of Object.entries(
      this.response.node_errors ?? []
    )) {
      message += "\n" + nodeError.class_type + ":";
      for (const errorReason of nodeError.errors) {
        message += "\n    - " + errorReason.message + ": " + errorReason.details;
      }
    }
    return message;
  }
}
class ComfyApi extends EventTarget {
  static {
    __name(this, "ComfyApi");
  }
  #registered = /* @__PURE__ */ new Set();
  api_host;
  api_base;
  /**
   * The client id from the initial session storage.
   */
  initialClientId;
  /**
   * The current client id from websocket status updates.
   */
  clientId;
  /**
   * The current user id.
   */
  user;
  socket = null;
  reportedUnknownMessageTypes = /* @__PURE__ */ new Set();
  /**
   * The auth token for the comfy org account if the user is logged in.
   * This is only used for {@link queuePrompt} now. It is not directly
   * passed as parameter to the function because some custom nodes are hijacking
   * {@link queuePrompt} improperly, which causes extra parameters to be lost
   * in the function call chain.
   *
   * Ref: https://cs.comfy.org/search?q=context:global+%22api.queuePrompt+%3D%22&patternType=keyword&sm=0
   *
   * TODO: Move this field to parameter of {@link queuePrompt} once all
   * custom nodes are patched.
   */
  authToken;
  /**
   * The API key for the comfy org account if the user logged in via API key.
   */
  apiKey;
  constructor() {
    super();
    this.user = "";
    this.api_host = location.host;
    this.api_base = location.pathname.split("/").slice(0, -1).join("/");
    console.log("Running on", this.api_host);
    this.initialClientId = sessionStorage.getItem("clientId");
  }
  internalURL(route) {
    return this.api_base + "/internal" + route;
  }
  apiURL(route) {
    return this.api_base + "/api" + route;
  }
  fileURL(route) {
    return this.api_base + route;
  }
  fetchApi(route, options2) {
    if (!options2) {
      options2 = {};
    }
    if (!options2.headers) {
      options2.headers = {};
    }
    if (!options2.cache) {
      options2.cache = "no-cache";
    }
    if (Array.isArray(options2.headers)) {
      options2.headers.push(["Comfy-User", this.user]);
    } else if (options2.headers instanceof Headers) {
      options2.headers.set("Comfy-User", this.user);
    } else {
      options2.headers["Comfy-User"] = this.user;
    }
    return fetch(this.apiURL(route), options2);
  }
  addEventListener(type, callback, options2) {
    super.addEventListener(type, callback, options2);
    this.#registered.add(type);
  }
  removeEventListener(type, callback, options2) {
    super.removeEventListener(type, callback, options2);
  }
  dispatchCustomEvent(type, detail) {
    const event = detail === void 0 ? new CustomEvent(type) : new CustomEvent(type, { detail });
    return super.dispatchEvent(event);
  }
  /** @deprecated Use {@link dispatchCustomEvent}. */
  dispatchEvent(event) {
    return super.dispatchEvent(event);
  }
  /**
   * Poll status  for colab and other things that don't support websockets.
   */
  #pollQueue() {
    setInterval(async () => {
      try {
        const resp = await this.fetchApi("/prompt");
        const status = await resp.json();
        this.dispatchCustomEvent("status", status);
      } catch (error2) {
        this.dispatchCustomEvent("status", null);
      }
    }, 1e3);
  }
  /**
   * Creates and connects a WebSocket for realtime updates
   * @param {boolean} isReconnect If the socket is connection is a reconnect attempt
   */
  #createSocket(isReconnect) {
    if (this.socket) {
      return;
    }
    let opened = false;
    let existingSession = window.name;
    if (existingSession) {
      existingSession = "?clientId=" + existingSession;
    }
    this.socket = new WebSocket(
      `ws${window.location.protocol === "https:" ? "s" : ""}://${this.api_host}${this.api_base}/ws${existingSession}`
    );
    this.socket.binaryType = "arraybuffer";
    this.socket.addEventListener("open", () => {
      opened = true;
      if (isReconnect) {
        this.dispatchCustomEvent("reconnected");
      }
    });
    this.socket.addEventListener("error", () => {
      if (this.socket) this.socket.close();
      if (!isReconnect && !opened) {
        this.#pollQueue();
      }
    });
    this.socket.addEventListener("close", () => {
      setTimeout(() => {
        this.socket = null;
        this.#createSocket(true);
      }, 300);
      if (opened) {
        this.dispatchCustomEvent("status", null);
        this.dispatchCustomEvent("reconnecting");
      }
    });
    this.socket.addEventListener("message", (event) => {
      try {
        if (event.data instanceof ArrayBuffer) {
          const view = new DataView(event.data);
          const eventType = view.getUint32(0);
          let imageMime;
          switch (eventType) {
            case 3:
              const decoder = new TextDecoder();
              const data = event.data.slice(4);
              const nodeIdLength = view.getUint32(4);
              this.dispatchCustomEvent("progress_text", {
                nodeId: decoder.decode(data.slice(4, 4 + nodeIdLength)),
                text: decoder.decode(data.slice(4 + nodeIdLength))
              });
              break;
            case 1:
              const imageType = view.getUint32(4);
              const imageData = event.data.slice(8);
              switch (imageType) {
                case 2:
                  imageMime = "image/png";
                  break;
                case 1:
                default:
                  imageMime = "image/jpeg";
                  break;
              }
              const imageBlob = new Blob([imageData], {
                type: imageMime
              });
              this.dispatchCustomEvent("b_preview", imageBlob);
              break;
            default:
              throw new Error(
                `Unknown binary websocket message of type ${eventType}`
              );
          }
        } else {
          const msg = JSON.parse(event.data);
          switch (msg.type) {
            case "status":
              if (msg.data.sid) {
                const clientId = msg.data.sid;
                this.clientId = clientId;
                window.name = clientId;
                sessionStorage.setItem("clientId", clientId);
              }
              this.dispatchCustomEvent("status", msg.data.status ?? null);
              break;
            case "executing":
              this.dispatchCustomEvent(
                "executing",
                msg.data.display_node || msg.data.node
              );
              break;
            case "execution_start":
            case "execution_error":
            case "execution_interrupted":
            case "execution_cached":
            case "execution_success":
            case "progress":
            case "executed":
            case "graphChanged":
            case "promptQueued":
            case "logs":
            case "b_preview":
              this.dispatchCustomEvent(msg.type, msg.data);
              break;
            default:
              if (this.#registered.has(msg.type)) {
                super.dispatchEvent(
                  new CustomEvent(msg.type, { detail: msg.data })
                );
              } else if (!this.reportedUnknownMessageTypes.has(msg.type)) {
                this.reportedUnknownMessageTypes.add(msg.type);
                throw new Error(`Unknown message type ${msg.type}`);
              }
          }
        }
      } catch (error2) {
        console.warn("Unhandled message:", event.data, error2);
      }
    });
  }
  /**
   * Initialises sockets and realtime updates
   */
  init() {
    this.#createSocket();
  }
  /**
   * Gets a list of extension urls
   */
  async getExtensions() {
    const resp = await this.fetchApi("/extensions", { cache: "no-store" });
    return await resp.json();
  }
  /**
   * Gets the available workflow templates from custom nodes.
   * @returns A map of custom_node names and associated template workflow names.
   */
  async getWorkflowTemplates() {
    const res = await this.fetchApi("/workflow_templates");
    return await res.json();
  }
  /**
   * Gets the index of core workflow templates.
   */
  async getCoreWorkflowTemplates() {
    const res = await axios.get(this.fileURL("/templates/index.json"));
    const contentType = res.headers["content-type"];
    return contentType?.includes("application/json") ? res.data : [];
  }
  /**
   * Gets a list of embedding names
   */
  async getEmbeddings() {
    const resp = await this.fetchApi("/embeddings", { cache: "no-store" });
    return await resp.json();
  }
  /**
   * Loads node object definitions for the graph
   * @returns The node definitions
   */
  async getNodeDefs({ validate = false } = {}) {
    const resp = await this.fetchApi("/object_info", { cache: "no-store" });
    const objectInfoUnsafe = await resp.json();
    if (!validate) {
      return objectInfoUnsafe;
    }
    const objectInfo = {};
    for (const key in objectInfoUnsafe) {
      const validatedDef = validateComfyNodeDef(
        objectInfoUnsafe[key],
        /* onError=*/
        (errorMessage) => {
          console.warn(
            `Skipping invalid node definition: ${key}. See debug log for more information.`
          );
          console.debug(errorMessage);
        }
      );
      if (validatedDef !== null) {
        objectInfo[key] = validatedDef;
      }
    }
    return objectInfo;
  }
  /**
   * Queues a prompt to be executed
   * @param {number} number The index at which to queue the prompt, passing -1 will insert the prompt at the front of the queue
   * @param {object} prompt The prompt data to queue
   * @throws {PromptExecutionError} If the prompt fails to execute
   */
  async queuePrompt(number, data) {
    const { output: prompt, workflow } = data;
    const body = {
      client_id: this.clientId ?? "",
      // TODO: Unify clientId access
      prompt,
      extra_data: {
        auth_token_comfy_org: this.authToken,
        api_key_comfy_org: this.apiKey,
        extra_pnginfo: { workflow }
      }
    };
    if (number === -1) {
      body.front = true;
    } else if (number != 0) {
      body.number = number;
    }
    const res = await this.fetchApi("/prompt", {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify(body)
    });
    if (res.status !== 200) {
      throw new PromptExecutionError(await res.json());
    }
    return await res.json();
  }
  /**
   * Gets a list of model folder keys (eg ['checkpoints', 'loras', ...])
   * @returns The list of model folder keys
   */
  async getModelFolders() {
    const res = await this.fetchApi(`/experiment/models`);
    if (res.status === 404) {
      return [];
    }
    const folderBlacklist = ["configs", "custom_nodes"];
    return (await res.json()).filter(
      (folder) => !folderBlacklist.includes(folder)
    );
  }
  /**
   * Gets a list of models in the specified folder
   * @param {string} folder The folder to list models from, such as 'checkpoints'
   * @returns The list of model filenames within the specified folder
   */
  async getModels(folder) {
    const res = await this.fetchApi(`/experiment/models/${folder}`);
    if (res.status === 404) {
      return [];
    }
    return await res.json();
  }
  /**
   * Gets the metadata for a model
   * @param {string} folder The folder containing the model
   * @param {string} model The model to get metadata for
   * @returns The metadata for the model
   */
  async viewMetadata(folder, model) {
    const res = await this.fetchApi(
      `/view_metadata/${folder}?filename=${encodeURIComponent(model)}`
    );
    const rawResponse = await res.text();
    if (!rawResponse) {
      return null;
    }
    try {
      return JSON.parse(rawResponse);
    } catch (error2) {
      console.error(
        "Error viewing metadata",
        res.status,
        res.statusText,
        rawResponse,
        error2
      );
      return null;
    }
  }
  /**
   * Loads a list of items (queue or history)
   * @param {string} type The type of items to load, queue or history
   * @returns The items of the specified type grouped by their status
   */
  async getItems(type) {
    if (type === "queue") {
      return this.getQueue();
    }
    return this.getHistory();
  }
  /**
   * Gets the current state of the queue
   * @returns The currently running and queued items
   */
  async getQueue() {
    try {
      const res = await this.fetchApi("/queue");
      const data = await res.json();
      return {
        // Running action uses a different endpoint for cancelling
        Running: data.queue_running.map((prompt) => ({
          taskType: "Running",
          prompt,
          remove: { name: "Cancel", cb: /* @__PURE__ */ __name(() => api.interrupt(), "cb") }
        })),
        Pending: data.queue_pending.map((prompt) => ({
          taskType: "Pending",
          prompt
        }))
      };
    } catch (error2) {
      console.error(error2);
      return { Running: [], Pending: [] };
    }
  }
  /**
   * Gets the prompt execution history
   * @returns Prompt history including node outputs
   */
  async getHistory(max_items = 200) {
    try {
      const res = await this.fetchApi(`/history?max_items=${max_items}`);
      const json = await res.json();
      return {
        History: Object.values(json).map((item) => ({
          ...item,
          taskType: "History"
        }))
      };
    } catch (error2) {
      console.error(error2);
      return { History: [] };
    }
  }
  /**
   * Gets system & device stats
   * @returns System stats such as python version, OS, per device info
   */
  async getSystemStats() {
    const res = await this.fetchApi("/system_stats");
    return await res.json();
  }
  /**
   * Sends a POST request to the API
   * @param {*} type The endpoint to post to
   * @param {*} body Optional POST data
   */
  async #postItem(type, body) {
    try {
      await this.fetchApi("/" + type, {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: body ? JSON.stringify(body) : void 0
      });
    } catch (error2) {
      console.error(error2);
    }
  }
  /**
   * Deletes an item from the specified list
   * @param {string} type The type of item to delete, queue or history
   * @param {number} id The id of the item to delete
   */
  async deleteItem(type, id2) {
    await this.#postItem(type, { delete: [id2] });
  }
  /**
   * Clears the specified list
   * @param {string} type The type of list to clear, queue or history
   */
  async clearItems(type) {
    await this.#postItem(type, { clear: true });
  }
  /**
   * Interrupts the execution of the running prompt
   */
  async interrupt() {
    await this.#postItem("interrupt", null);
  }
  /**
   * Gets user configuration data and where data should be stored
   */
  async getUserConfig() {
    return (await this.fetchApi("/users")).json();
  }
  /**
   * Creates a new user
   * @param { string } username
   * @returns The fetch response
   */
  createUser(username) {
    return this.fetchApi("/users", {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({ username })
    });
  }
  /**
   * Gets all setting values for the current user
   * @returns { Promise<string, unknown> } A dictionary of id -> value
   */
  async getSettings() {
    const resp = await this.fetchApi("/settings");
    if (resp.status == 401) {
      throw new UnauthorizedError(resp.statusText);
    }
    return await resp.json();
  }
  /**
   * Gets a setting for the current user
   * @param { string } id The id of the setting to fetch
   * @returns { Promise<unknown> } The setting value
   */
  async getSetting(id2) {
    return (await this.fetchApi(`/settings/${encodeURIComponent(id2)}`)).json();
  }
  /**
   * Stores a dictionary of settings for the current user
   */
  async storeSettings(settings) {
    return this.fetchApi(`/settings`, {
      method: "POST",
      body: JSON.stringify(settings)
    });
  }
  /**
   * Stores a setting for the current user
   */
  async storeSetting(id2, value) {
    return this.fetchApi(`/settings/${encodeURIComponent(id2)}`, {
      method: "POST",
      body: JSON.stringify(value)
    });
  }
  /**
   * Gets a user data file for the current user
   */
  async getUserData(file, options2) {
    return this.fetchApi(`/userdata/${encodeURIComponent(file)}`, options2);
  }
  /**
   * Stores a user data file for the current user
   * @param { string } file The name of the userdata file to save
   * @param { unknown } data The data to save to the file
   * @param { RequestInit & { stringify?: boolean, throwOnError?: boolean } } [options]
   * @returns { Promise<Response> }
   */
  async storeUserData(file, data, options2 = {
    overwrite: true,
    stringify: true,
    throwOnError: true,
    full_info: false
  }) {
    const resp = await this.fetchApi(
      `/userdata/${encodeURIComponent(file)}?overwrite=${options2.overwrite}&full_info=${options2.full_info}`,
      {
        method: "POST",
        body: options2?.stringify ? JSON.stringify(data) : data,
        ...options2
      }
    );
    if (resp.status !== 200 && options2.throwOnError !== false) {
      throw new Error(
        `Error storing user data file '${file}': ${resp.status} ${(await resp).statusText}`
      );
    }
    return resp;
  }
  /**
   * Deletes a user data file for the current user
   * @param { string } file The name of the userdata file to delete
   */
  async deleteUserData(file) {
    const resp = await this.fetchApi(`/userdata/${encodeURIComponent(file)}`, {
      method: "DELETE"
    });
    return resp;
  }
  /**
   * Move a user data file for the current user
   * @param { string } source The userdata file to move
   * @param { string } dest The destination for the file
   */
  async moveUserData(source, dest, options2 = { overwrite: false }) {
    const resp = await this.fetchApi(
      `/userdata/${encodeURIComponent(source)}/move/${encodeURIComponent(dest)}?overwrite=${options2?.overwrite}`,
      {
        method: "POST"
      }
    );
    return resp;
  }
  async listUserDataFullInfo(dir) {
    const resp = await this.fetchApi(
      `/userdata?dir=${encodeURIComponent(dir)}&recurse=true&split=false&full_info=true`
    );
    if (resp.status === 404) return [];
    if (resp.status !== 200) {
      throw new Error(
        `Error getting user data list '${dir}': ${resp.status} ${resp.statusText}`
      );
    }
    return resp.json();
  }
  async getLogs() {
    return (await axios.get(this.internalURL("/logs"))).data;
  }
  async getRawLogs() {
    return (await axios.get(this.internalURL("/logs/raw"))).data;
  }
  async subscribeLogs(enabled) {
    return await axios.patch(this.internalURL("/logs/subscribe"), {
      enabled,
      clientId: this.clientId
    });
  }
  async getFolderPaths() {
    return (await axios.get(this.internalURL("/folder_paths"))).data;
  }
  /**
   * Gets the custom nodes i18n data from the server.
   *
   * @returns The custom nodes i18n data
   */
  async getCustomNodesI18n() {
    return (await axios.get(this.apiURL("/i18n"))).data;
  }
}
const api = new ComfyApi();
window.comfyAPI = window.comfyAPI || {};
window.comfyAPI.api = window.comfyAPI.api || {};
window.comfyAPI.api.UnauthorizedError = UnauthorizedError;
window.comfyAPI.api.PromptExecutionError = PromptExecutionError;
window.comfyAPI.api.ComfyApi = ComfyApi;
window.comfyAPI.api.api = api;
const useUserStore = /* @__PURE__ */ defineStore("user", () => {
  const userConfig = ref$3(null);
  const currentUserId = ref$3(null);
  const isMultiUserServer = computed(
    () => userConfig.value && "users" in userConfig.value
  );
  const needsLogin = computed(
    () => !currentUserId.value && isMultiUserServer.value
  );
  const users = computed(
    () => Object.entries(userConfig.value?.users ?? {}).map(([userId, username]) => ({
      userId,
      username
    }))
  );
  const currentUser = computed(
    () => users.value.find((user) => user.userId === currentUserId.value) ?? null
  );
  const initialized = computed(() => userConfig.value !== null);
  async function initialize() {
    userConfig.value = await api.getUserConfig();
    currentUserId.value = localStorage["Comfy.userId"];
  }
  __name(initialize, "initialize");
  async function createUser(username) {
    const resp = await api.createUser(username);
    const data = await resp.json();
    if (resp.status >= 300) {
      throw new Error(
        data.error ?? "Error creating user: " + resp.status + " " + resp.statusText
      );
    }
    return {
      userId: data,
      username
    };
  }
  __name(createUser, "createUser");
  async function login({
    userId,
    username
  }) {
    currentUserId.value = userId;
    localStorage["Comfy.userId"] = userId;
    localStorage["Comfy.userName"] = username;
  }
  __name(login, "login");
  watchEffect(() => {
    if (isMultiUserServer.value && currentUserId.value) {
      api.user = currentUserId.value;
    }
  });
  async function logout() {
    delete localStorage["Comfy.userId"];
    delete localStorage["Comfy.userName"];
  }
  __name(logout, "logout");
  return {
    users,
    currentUser,
    isMultiUserServer,
    needsLogin,
    initialized,
    initialize,
    createUser,
    login,
    logout
  };
});
function isElectron() {
  return "electronAPI" in window && window.electronAPI !== void 0;
}
__name(isElectron, "isElectron");
function electronAPI() {
  return window.electronAPI;
}
__name(electronAPI, "electronAPI");
function showNativeSystemMenu() {
  electronAPI()?.showContextMenu();
}
__name(showNativeSystemMenu, "showNativeSystemMenu");
function isNativeWindow() {
  return isElectron() && !!window.navigator.windowControlsOverlay?.visible;
}
__name(isNativeWindow, "isNativeWindow");
const isFileProtocol = window.location.protocol === "file:";
const basePath = isElectron() ? "/" : window.location.pathname;
const guardElectronAccess = /* @__PURE__ */ __name((_to, _from, next) => {
  if (isElectron()) {
    next();
  } else {
    next("/");
  }
}, "guardElectronAccess");
const router = createRouter({
  history: isFileProtocol ? createWebHashHistory() : (
    // Base path must be specified to ensure correct relative paths
    // Example: For URL 'http://localhost:7801/ComfyBackendDirect',
    // we need this base path or assets will incorrectly resolve from 'http://localhost:7801/'
    createWebHistory(basePath)
  ),
  routes: [
    {
      path: "/",
      component: _sfc_main$1T,
      children: [
        {
          path: "",
          name: "GraphView",
          component: /* @__PURE__ */ __name(() => __vitePreload(() => import("./GraphView-D1V4EJXE.js"), true ? __vite__mapDeps([0,1,2,3,4,5,6,7]) : void 0, import.meta.url), "component"),
          beforeEnter: /* @__PURE__ */ __name(async (_to, _from, next) => {
            const userStore = useUserStore();
            await userStore.initialize();
            if (userStore.needsLogin) {
              next("/user-select");
            } else {
              next();
            }
          }, "beforeEnter")
        },
        {
          path: "user-select",
          name: "UserSelectView",
          component: /* @__PURE__ */ __name(() => __vitePreload(() => import("./UserSelectView-D47mThhN.js"), true ? __vite__mapDeps([8,1,2,9,3]) : void 0, import.meta.url), "component")
        },
        {
          path: "server-start",
          name: "ServerStartView",
          component: /* @__PURE__ */ __name(() => __vitePreload(() => import("./ServerStartView-DBkhOGrG.js"), true ? __vite__mapDeps([10,1,2,3,9,11]) : void 0, import.meta.url), "component"),
          beforeEnter: guardElectronAccess
        },
        {
          path: "install",
          name: "InstallView",
          component: /* @__PURE__ */ __name(() => __vitePreload(() => import("./InstallView-n1yIGren.js"), true ? __vite__mapDeps([12,1,2,3,13,9,14]) : void 0, import.meta.url), "component"),
          beforeEnter: guardElectronAccess
        },
        {
          path: "welcome",
          name: "WelcomeView",
          component: /* @__PURE__ */ __name(() => __vitePreload(() => import("./WelcomeView-D5JBR5jL.js"), true ? __vite__mapDeps([15,1,2,9,3,16]) : void 0, import.meta.url), "component"),
          beforeEnter: guardElectronAccess
        },
        {
          path: "not-supported",
          name: "NotSupportedView",
          component: /* @__PURE__ */ __name(() => __vitePreload(() => import("./NotSupportedView-D9DpH9zy.js"), true ? __vite__mapDeps([17,1,2,9,3,18]) : void 0, import.meta.url), "component"),
          beforeEnter: guardElectronAccess
        },
        {
          path: "download-git",
          name: "DownloadGitView",
          component: /* @__PURE__ */ __name(() => __vitePreload(() => import("./DownloadGitView-CI2P920b.js"), true ? __vite__mapDeps([19,1,2,9,3]) : void 0, import.meta.url), "component"),
          beforeEnter: guardElectronAccess
        },
        {
          path: "manual-configuration",
          name: "ManualConfigurationView",
          component: /* @__PURE__ */ __name(() => __vitePreload(() => import("./ManualConfigurationView-6hm2NmAw.js"), true ? __vite__mapDeps([20,1,2,3,9,21]) : void 0, import.meta.url), "component"),
          beforeEnter: guardElectronAccess
        },
        {
          path: "/metrics-consent",
          name: "MetricsConsentView",
          component: /* @__PURE__ */ __name(() => __vitePreload(() => import("./MetricsConsentView-C4pUTn28.js"), true ? __vite__mapDeps([22,9,1,2,3]) : void 0, import.meta.url), "component"),
          beforeEnter: guardElectronAccess
        },
        {
          path: "desktop-start",
          name: "DesktopStartView",
          component: /* @__PURE__ */ __name(() => __vitePreload(() => import("./DesktopStartView-DQVeDhKD.js"), true ? __vite__mapDeps([23,1,2,9,3]) : void 0, import.meta.url), "component"),
          beforeEnter: guardElectronAccess
        },
        {
          path: "maintenance",
          name: "MaintenanceView",
          component: /* @__PURE__ */ __name(() => __vitePreload(() => import("./MaintenanceView-CmPBr2TJ.js"), true ? __vite__mapDeps([24,1,2,25,9,3,26]) : void 0, import.meta.url), "component"),
          beforeEnter: guardElectronAccess
        },
        {
          path: "desktop-update",
          name: "DesktopUpdateView",
          component: /* @__PURE__ */ __name(() => __vitePreload(() => import("./DesktopUpdateView-D0MR0yAS.js"), true ? __vite__mapDeps([27,1,2,25,9,3,28]) : void 0, import.meta.url), "component"),
          beforeEnter: guardElectronAccess
        }
      ]
    }
  ],
  scrollBehavior(_to, _from, savedPosition) {
    if (savedPosition) {
      return savedPosition;
    } else {
      return { top: 0 };
    }
  }
});
var BaseComponentStyle$1 = BaseStyle$1.extend({
  name: "common"
});
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;
}
__name(getDefaultExportFromCjs, "getDefaultExportFromCjs");
function getDefaultExportFromNamespaceIfPresent(n2) {
  return n2 && Object.prototype.hasOwnProperty.call(n2, "default") ? n2["default"] : n2;
}
__name(getDefaultExportFromNamespaceIfPresent, "getDefaultExportFromNamespaceIfPresent");
function getDefaultExportFromNamespaceIfNotNamed(n2) {
  return n2 && Object.prototype.hasOwnProperty.call(n2, "default") && Object.keys(n2).length === 1 ? n2["default"] : n2;
}
__name(getDefaultExportFromNamespaceIfNotNamed, "getDefaultExportFromNamespaceIfNotNamed");
function getAugmentedNamespace(n2) {
  if (n2.__esModule) return n2;
  var f2 = n2.default;
  if (typeof f2 == "function") {
    var a2 = /* @__PURE__ */ __name(function a3() {
      if (this instanceof a3) {
        return Reflect.construct(f2, arguments, this.constructor);
      }
      return f2.apply(this, arguments);
    }, "a");
    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: /* @__PURE__ */ __name(function() {
        return n2[k2];
      }, "get")
    });
  });
  return a2;
}
__name(getAugmentedNamespace, "getAugmentedNamespace");
var lodash$1 = { 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
 */
var lodash = lodash$1.exports;
(function(module2, exports) {
  ;
  (function() {
    var undefined$1;
    var VERSION2 = "4.17.21";
    var LARGE_ARRAY_SIZE2 = 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_UNDEFINED2 = "__lodash_hash_undefined__";
    var MAX_MEMOIZE_SIZE = 500;
    var PLACEHOLDER = "__lodash_placeholder__";
    var CLONE_DEEP_FLAG2 = 1, CLONE_FLAT_FLAG2 = 2, CLONE_SYMBOLS_FLAG2 = 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 INFINITY2 = 1 / 0, MAX_SAFE_INTEGER2 = 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 argsTag2 = "[object Arguments]", arrayTag2 = "[object Array]", asyncTag2 = "[object AsyncFunction]", boolTag2 = "[object Boolean]", dateTag2 = "[object Date]", domExcTag = "[object DOMException]", errorTag2 = "[object Error]", funcTag2 = "[object Function]", genTag2 = "[object GeneratorFunction]", mapTag2 = "[object Map]", numberTag2 = "[object Number]", nullTag2 = "[object Null]", objectTag2 = "[object Object]", promiseTag2 = "[object Promise]", proxyTag2 = "[object Proxy]", regexpTag2 = "[object RegExp]", setTag2 = "[object Set]", stringTag2 = "[object String]", symbolTag2 = "[object Symbol]", undefinedTag2 = "[object Undefined]", weakMapTag2 = "[object WeakMap]", weakSetTag = "[object WeakSet]";
    var arrayBufferTag2 = "[object ArrayBuffer]", dataViewTag2 = "[object DataView]", float32Tag2 = "[object Float32Array]", float64Tag2 = "[object Float64Array]", int8Tag2 = "[object Int8Array]", int16Tag2 = "[object Int16Array]", int32Tag2 = "[object Int32Array]", uint8Tag2 = "[object Uint8Array]", uint8ClampedTag2 = "[object Uint8ClampedArray]", uint16Tag2 = "[object Uint16Array]", uint32Tag2 = "[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 reRegExpChar2 = /[\\^$.*+?()[\]{}|]/g, reHasRegExpChar = RegExp(reRegExpChar2.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 reFlags2 = /\w*$/;
    var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
    var reIsBinary = /^0b[01]+$/i;
    var reIsHostCtor2 = /^\[object .+?Constructor\]$/;
    var reIsOctal = /^0o[0-7]+$/i;
    var reIsUint2 = /^(?: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 typedArrayTags2 = {};
    typedArrayTags2[float32Tag2] = typedArrayTags2[float64Tag2] = typedArrayTags2[int8Tag2] = typedArrayTags2[int16Tag2] = typedArrayTags2[int32Tag2] = typedArrayTags2[uint8Tag2] = typedArrayTags2[uint8ClampedTag2] = typedArrayTags2[uint16Tag2] = typedArrayTags2[uint32Tag2] = true;
    typedArrayTags2[argsTag2] = typedArrayTags2[arrayTag2] = typedArrayTags2[arrayBufferTag2] = typedArrayTags2[boolTag2] = typedArrayTags2[dataViewTag2] = typedArrayTags2[dateTag2] = typedArrayTags2[errorTag2] = typedArrayTags2[funcTag2] = typedArrayTags2[mapTag2] = typedArrayTags2[numberTag2] = typedArrayTags2[objectTag2] = typedArrayTags2[regexpTag2] = typedArrayTags2[setTag2] = typedArrayTags2[stringTag2] = typedArrayTags2[weakMapTag2] = false;
    var cloneableTags2 = {};
    cloneableTags2[argsTag2] = cloneableTags2[arrayTag2] = cloneableTags2[arrayBufferTag2] = cloneableTags2[dataViewTag2] = cloneableTags2[boolTag2] = cloneableTags2[dateTag2] = cloneableTags2[float32Tag2] = cloneableTags2[float64Tag2] = cloneableTags2[int8Tag2] = cloneableTags2[int16Tag2] = cloneableTags2[int32Tag2] = cloneableTags2[mapTag2] = cloneableTags2[numberTag2] = cloneableTags2[objectTag2] = cloneableTags2[regexpTag2] = cloneableTags2[setTag2] = cloneableTags2[stringTag2] = cloneableTags2[symbolTag2] = cloneableTags2[uint8Tag2] = cloneableTags2[uint8ClampedTag2] = cloneableTags2[uint16Tag2] = cloneableTags2[uint32Tag2] = true;
    cloneableTags2[errorTag2] = cloneableTags2[funcTag2] = cloneableTags2[weakMapTag2] = 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",
      "Œ": "Oe",
      "œ": "oe",
      "ŉ": "'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 freeGlobal2 = typeof commonjsGlobal == "object" && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
    var freeSelf2 = typeof self == "object" && self && self.Object === Object && self;
    var root2 = freeGlobal2 || freeSelf2 || Function("return this")();
    var freeExports = exports && !exports.nodeType && exports;
    var freeModule = freeExports && true && module2 && !module2.nodeType && module2;
    var moduleExports = freeModule && freeModule.exports === freeExports;
    var freeProcess = moduleExports && freeGlobal2.process;
    var nodeUtil2 = 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 = nodeUtil2 && nodeUtil2.isArrayBuffer, nodeIsDate = nodeUtil2 && nodeUtil2.isDate, nodeIsMap2 = nodeUtil2 && nodeUtil2.isMap, nodeIsRegExp = nodeUtil2 && nodeUtil2.isRegExp, nodeIsSet2 = nodeUtil2 && nodeUtil2.isSet, nodeIsTypedArray2 = nodeUtil2 && nodeUtil2.isTypedArray;
    function apply2(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);
    }
    __name(apply2, "apply");
    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;
    }
    __name(arrayAggregator, "arrayAggregator");
    function arrayEach2(array, iteratee) {
      var index2 = -1, length = array == null ? 0 : array.length;
      while (++index2 < length) {
        if (iteratee(array[index2], index2, array) === false) {
          break;
        }
      }
      return array;
    }
    __name(arrayEach2, "arrayEach");
    function arrayEachRight(array, iteratee) {
      var length = array == null ? 0 : array.length;
      while (length--) {
        if (iteratee(array[length], length, array) === false) {
          break;
        }
      }
      return array;
    }
    __name(arrayEachRight, "arrayEachRight");
    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;
    }
    __name(arrayEvery, "arrayEvery");
    function arrayFilter2(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;
    }
    __name(arrayFilter2, "arrayFilter");
    function arrayIncludes(array, value) {
      var length = array == null ? 0 : array.length;
      return !!length && baseIndexOf(array, value, 0) > -1;
    }
    __name(arrayIncludes, "arrayIncludes");
    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;
    }
    __name(arrayIncludesWith, "arrayIncludesWith");
    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;
    }
    __name(arrayMap, "arrayMap");
    function arrayPush2(array, values) {
      var index2 = -1, length = values.length, offset = array.length;
      while (++index2 < length) {
        array[offset + index2] = values[index2];
      }
      return array;
    }
    __name(arrayPush2, "arrayPush");
    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;
    }
    __name(arrayReduce, "arrayReduce");
    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;
    }
    __name(arrayReduceRight, "arrayReduceRight");
    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;
    }
    __name(arraySome, "arraySome");
    var asciiSize = baseProperty("length");
    function asciiToArray(string) {
      return string.split("");
    }
    __name(asciiToArray, "asciiToArray");
    function asciiWords(string) {
      return string.match(reAsciiWord) || [];
    }
    __name(asciiWords, "asciiWords");
    function baseFindKey(collection2, predicate, eachFunc) {
      var result;
      eachFunc(collection2, function(value, key, collection3) {
        if (predicate(value, key, collection3)) {
          result = key;
          return false;
        }
      });
      return result;
    }
    __name(baseFindKey, "baseFindKey");
    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;
    }
    __name(baseFindIndex, "baseFindIndex");
    function baseIndexOf(array, value, fromIndex) {
      return value === value ? strictIndexOf(array, value, fromIndex) : baseFindIndex(array, baseIsNaN, fromIndex);
    }
    __name(baseIndexOf, "baseIndexOf");
    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;
    }
    __name(baseIndexOfWith, "baseIndexOfWith");
    function baseIsNaN(value) {
      return value !== value;
    }
    __name(baseIsNaN, "baseIsNaN");
    function baseMean(array, iteratee) {
      var length = array == null ? 0 : array.length;
      return length ? baseSum(array, iteratee) / length : NAN;
    }
    __name(baseMean, "baseMean");
    function baseProperty(key) {
      return function(object) {
        return object == null ? undefined$1 : object[key];
      };
    }
    __name(baseProperty, "baseProperty");
    function basePropertyOf(object) {
      return function(key) {
        return object == null ? undefined$1 : object[key];
      };
    }
    __name(basePropertyOf, "basePropertyOf");
    function baseReduce(collection2, iteratee, accumulator, initAccum, eachFunc) {
      eachFunc(collection2, function(value, index2, collection3) {
        accumulator = initAccum ? (initAccum = false, value) : iteratee(accumulator, value, index2, collection3);
      });
      return accumulator;
    }
    __name(baseReduce, "baseReduce");
    function baseSortBy(array, comparer) {
      var length = array.length;
      array.sort(comparer);
      while (length--) {
        array[length] = array[length].value;
      }
      return array;
    }
    __name(baseSortBy, "baseSortBy");
    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;
    }
    __name(baseSum, "baseSum");
    function baseTimes2(n2, iteratee) {
      var index2 = -1, result = Array(n2);
      while (++index2 < n2) {
        result[index2] = iteratee(index2);
      }
      return result;
    }
    __name(baseTimes2, "baseTimes");
    function baseToPairs(object, props) {
      return arrayMap(props, function(key) {
        return [key, object[key]];
      });
    }
    __name(baseToPairs, "baseToPairs");
    function baseTrim(string) {
      return string ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, "") : string;
    }
    __name(baseTrim, "baseTrim");
    function baseUnary2(func) {
      return function(value) {
        return func(value);
      };
    }
    __name(baseUnary2, "baseUnary");
    function baseValues(object, props) {
      return arrayMap(props, function(key) {
        return object[key];
      });
    }
    __name(baseValues, "baseValues");
    function cacheHas(cache, key) {
      return cache.has(key);
    }
    __name(cacheHas, "cacheHas");
    function charsStartIndex(strSymbols, chrSymbols) {
      var index2 = -1, length = strSymbols.length;
      while (++index2 < length && baseIndexOf(chrSymbols, strSymbols[index2], 0) > -1) {
      }
      return index2;
    }
    __name(charsStartIndex, "charsStartIndex");
    function charsEndIndex(strSymbols, chrSymbols) {
      var index2 = strSymbols.length;
      while (index2-- && baseIndexOf(chrSymbols, strSymbols[index2], 0) > -1) {
      }
      return index2;
    }
    __name(charsEndIndex, "charsEndIndex");
    function countHolders(array, placeholder) {
      var length = array.length, result = 0;
      while (length--) {
        if (array[length] === placeholder) {
          ++result;
        }
      }
      return result;
    }
    __name(countHolders, "countHolders");
    var deburrLetter = basePropertyOf(deburredLetters);
    var escapeHtmlChar = basePropertyOf(htmlEscapes);
    function escapeStringChar(chr) {
      return "\\" + stringEscapes[chr];
    }
    __name(escapeStringChar, "escapeStringChar");
    function getValue2(object, key) {
      return object == null ? undefined$1 : object[key];
    }
    __name(getValue2, "getValue");
    function hasUnicode(string) {
      return reHasUnicode.test(string);
    }
    __name(hasUnicode, "hasUnicode");
    function hasUnicodeWord(string) {
      return reHasUnicodeWord.test(string);
    }
    __name(hasUnicodeWord, "hasUnicodeWord");
    function iteratorToArray(iterator) {
      var data, result = [];
      while (!(data = iterator.next()).done) {
        result.push(data.value);
      }
      return result;
    }
    __name(iteratorToArray, "iteratorToArray");
    function mapToArray(map3) {
      var index2 = -1, result = Array(map3.size);
      map3.forEach(function(value, key) {
        result[++index2] = [key, value];
      });
      return result;
    }
    __name(mapToArray, "mapToArray");
    function overArg2(func, transform) {
      return function(arg) {
        return func(transform(arg));
      };
    }
    __name(overArg2, "overArg");
    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;
    }
    __name(replaceHolders, "replaceHolders");
    function setToArray(set3) {
      var index2 = -1, result = Array(set3.size);
      set3.forEach(function(value) {
        result[++index2] = value;
      });
      return result;
    }
    __name(setToArray, "setToArray");
    function setToPairs(set3) {
      var index2 = -1, result = Array(set3.size);
      set3.forEach(function(value) {
        result[++index2] = [value, value];
      });
      return result;
    }
    __name(setToPairs, "setToPairs");
    function strictIndexOf(array, value, fromIndex) {
      var index2 = fromIndex - 1, length = array.length;
      while (++index2 < length) {
        if (array[index2] === value) {
          return index2;
        }
      }
      return -1;
    }
    __name(strictIndexOf, "strictIndexOf");
    function strictLastIndexOf(array, value, fromIndex) {
      var index2 = fromIndex + 1;
      while (index2--) {
        if (array[index2] === value) {
          return index2;
        }
      }
      return index2;
    }
    __name(strictLastIndexOf, "strictLastIndexOf");
    function stringSize(string) {
      return hasUnicode(string) ? unicodeSize(string) : asciiSize(string);
    }
    __name(stringSize, "stringSize");
    function stringToArray2(string) {
      return hasUnicode(string) ? unicodeToArray(string) : asciiToArray(string);
    }
    __name(stringToArray2, "stringToArray");
    function trimmedEndIndex(string) {
      var index2 = string.length;
      while (index2-- && reWhitespace.test(string.charAt(index2))) {
      }
      return index2;
    }
    __name(trimmedEndIndex, "trimmedEndIndex");
    var unescapeHtmlChar = basePropertyOf(htmlUnescapes);
    function unicodeSize(string) {
      var result = reUnicode.lastIndex = 0;
      while (reUnicode.test(string)) {
        ++result;
      }
      return result;
    }
    __name(unicodeSize, "unicodeSize");
    function unicodeToArray(string) {
      return string.match(reUnicode) || [];
    }
    __name(unicodeToArray, "unicodeToArray");
    function unicodeWords(string) {
      return string.match(reUnicodeWord) || [];
    }
    __name(unicodeWords, "unicodeWords");
    var runInContext = /* @__PURE__ */ __name(function runInContext2(context) {
      context = context == null ? root2 : _2.defaults(root2.Object(), context, _2.pick(root2, 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 arrayProto2 = Array2.prototype, funcProto2 = Function2.prototype, objectProto2 = Object2.prototype;
      var coreJsData2 = context["__core-js_shared__"];
      var funcToString2 = funcProto2.toString;
      var hasOwnProperty2 = objectProto2.hasOwnProperty;
      var idCounter = 0;
      var maskSrcKey2 = function() {
        var uid = /[^.]+$/.exec(coreJsData2 && coreJsData2.keys && coreJsData2.keys.IE_PROTO || "");
        return uid ? "Symbol(src)_1." + uid : "";
      }();
      var nativeObjectToString2 = objectProto2.toString;
      var objectCtorString = funcToString2.call(Object2);
      var oldDash = root2._;
      var reIsNative2 = RegExp2(
        "^" + funcToString2.call(hasOwnProperty2).replace(reRegExpChar2, "\\$&").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, getPrototype2 = overArg2(Object2.getPrototypeOf, Object2), objectCreate2 = Object2.create, propertyIsEnumerable2 = objectProto2.propertyIsEnumerable, splice2 = arrayProto2.splice, spreadableSymbol = Symbol2 ? Symbol2.isConcatSpreadable : undefined$1, symIterator = Symbol2 ? Symbol2.iterator : undefined$1, symToStringTag2 = Symbol2 ? Symbol2.toStringTag : undefined$1;
      var defineProperty2 = function() {
        try {
          var func = getNative2(Object2, "defineProperty");
          func({}, "", {});
          return func;
        } catch (e2) {
        }
      }();
      var ctxClearTimeout = context.clearTimeout !== root2.clearTimeout && context.clearTimeout, ctxNow = Date2 && Date2.now !== root2.Date.now && Date2.now, ctxSetTimeout = context.setTimeout !== root2.setTimeout && context.setTimeout;
      var nativeCeil = Math2.ceil, nativeFloor = Math2.floor, nativeGetSymbols2 = Object2.getOwnPropertySymbols, nativeIsBuffer = Buffer2 ? Buffer2.isBuffer : undefined$1, nativeIsFinite = context.isFinite, nativeJoin = arrayProto2.join, nativeKeys2 = overArg2(Object2.keys, Object2), nativeMax = Math2.max, nativeMin = Math2.min, nativeNow = Date2.now, nativeParseInt = context.parseInt, nativeRandom = Math2.random, nativeReverse = arrayProto2.reverse;
      var DataView2 = getNative2(context, "DataView"), Map2 = getNative2(context, "Map"), Promise2 = getNative2(context, "Promise"), Set2 = getNative2(context, "Set"), WeakMap2 = getNative2(context, "WeakMap"), nativeCreate2 = getNative2(Object2, "create");
      var metaMap = WeakMap2 && new WeakMap2();
      var realNames = {};
      var dataViewCtorString2 = toSource2(DataView2), mapCtorString2 = toSource2(Map2), promiseCtorString2 = toSource2(Promise2), setCtorString2 = toSource2(Set2), weakMapCtorString2 = toSource2(WeakMap2);
      var symbolProto2 = Symbol2 ? Symbol2.prototype : undefined$1, symbolValueOf2 = symbolProto2 ? symbolProto2.valueOf : undefined$1, symbolToString = symbolProto2 ? symbolProto2.toString : undefined$1;
      function lodash2(value) {
        if (isObjectLike2(value) && !isArray2(value) && !(value instanceof LazyWrapper)) {
          if (value instanceof LodashWrapper) {
            return value;
          }
          if (hasOwnProperty2.call(value, "__wrapped__")) {
            return wrapperClone(value);
          }
        }
        return new LodashWrapper(value);
      }
      __name(lodash2, "lodash");
      var baseCreate2 = /* @__PURE__ */ function() {
        function object() {
        }
        __name(object, "object");
        return function(proto) {
          if (!isObject2(proto)) {
            return {};
          }
          if (objectCreate2) {
            return objectCreate2(proto);
          }
          object.prototype = proto;
          var result2 = new object();
          object.prototype = undefined$1;
          return result2;
        };
      }();
      function baseLodash() {
      }
      __name(baseLodash, "baseLodash");
      function LodashWrapper(value, chainAll) {
        this.__wrapped__ = value;
        this.__actions__ = [];
        this.__chain__ = !!chainAll;
        this.__index__ = 0;
        this.__values__ = undefined$1;
      }
      __name(LodashWrapper, "LodashWrapper");
      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 = baseCreate2(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__ = [];
      }
      __name(LazyWrapper, "LazyWrapper");
      function lazyClone() {
        var result2 = new LazyWrapper(this.__wrapped__);
        result2.__actions__ = copyArray2(this.__actions__);
        result2.__dir__ = this.__dir__;
        result2.__filtered__ = this.__filtered__;
        result2.__iteratees__ = copyArray2(this.__iteratees__);
        result2.__takeCount__ = this.__takeCount__;
        result2.__views__ = copyArray2(this.__views__);
        return result2;
      }
      __name(lazyClone, "lazyClone");
      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;
      }
      __name(lazyReverse, "lazyReverse");
      function lazyValue() {
        var array = this.__wrapped__.value(), dir = this.__dir__, isArr = isArray2(array), isRight = dir < 0, arrLength = isArr ? array.length : 0, view = getView(0, arrLength, this.__views__), start2 = view.start, end = view.end, length = end - start2, index2 = isRight ? end : start2 - 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, computed2 = iteratee2(value);
              if (type == LAZY_MAP_FLAG) {
                value = computed2;
              } else if (!computed2) {
                if (type == LAZY_FILTER_FLAG) {
                  continue outer;
                } else {
                  break outer;
                }
              }
            }
            result2[resIndex++] = value;
          }
        return result2;
      }
      __name(lazyValue, "lazyValue");
      LazyWrapper.prototype = baseCreate2(baseLodash.prototype);
      LazyWrapper.prototype.constructor = LazyWrapper;
      function Hash2(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]);
        }
      }
      __name(Hash2, "Hash");
      function hashClear2() {
        this.__data__ = nativeCreate2 ? nativeCreate2(null) : {};
        this.size = 0;
      }
      __name(hashClear2, "hashClear");
      function hashDelete2(key) {
        var result2 = this.has(key) && delete this.__data__[key];
        this.size -= result2 ? 1 : 0;
        return result2;
      }
      __name(hashDelete2, "hashDelete");
      function hashGet2(key) {
        var data = this.__data__;
        if (nativeCreate2) {
          var result2 = data[key];
          return result2 === HASH_UNDEFINED2 ? undefined$1 : result2;
        }
        return hasOwnProperty2.call(data, key) ? data[key] : undefined$1;
      }
      __name(hashGet2, "hashGet");
      function hashHas2(key) {
        var data = this.__data__;
        return nativeCreate2 ? data[key] !== undefined$1 : hasOwnProperty2.call(data, key);
      }
      __name(hashHas2, "hashHas");
      function hashSet2(key, value) {
        var data = this.__data__;
        this.size += this.has(key) ? 0 : 1;
        data[key] = nativeCreate2 && value === undefined$1 ? HASH_UNDEFINED2 : value;
        return this;
      }
      __name(hashSet2, "hashSet");
      Hash2.prototype.clear = hashClear2;
      Hash2.prototype["delete"] = hashDelete2;
      Hash2.prototype.get = hashGet2;
      Hash2.prototype.has = hashHas2;
      Hash2.prototype.set = hashSet2;
      function ListCache2(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]);
        }
      }
      __name(ListCache2, "ListCache");
      function listCacheClear2() {
        this.__data__ = [];
        this.size = 0;
      }
      __name(listCacheClear2, "listCacheClear");
      function listCacheDelete2(key) {
        var data = this.__data__, index2 = assocIndexOf2(data, key);
        if (index2 < 0) {
          return false;
        }
        var lastIndex = data.length - 1;
        if (index2 == lastIndex) {
          data.pop();
        } else {
          splice2.call(data, index2, 1);
        }
        --this.size;
        return true;
      }
      __name(listCacheDelete2, "listCacheDelete");
      function listCacheGet2(key) {
        var data = this.__data__, index2 = assocIndexOf2(data, key);
        return index2 < 0 ? undefined$1 : data[index2][1];
      }
      __name(listCacheGet2, "listCacheGet");
      function listCacheHas2(key) {
        return assocIndexOf2(this.__data__, key) > -1;
      }
      __name(listCacheHas2, "listCacheHas");
      function listCacheSet2(key, value) {
        var data = this.__data__, index2 = assocIndexOf2(data, key);
        if (index2 < 0) {
          ++this.size;
          data.push([key, value]);
        } else {
          data[index2][1] = value;
        }
        return this;
      }
      __name(listCacheSet2, "listCacheSet");
      ListCache2.prototype.clear = listCacheClear2;
      ListCache2.prototype["delete"] = listCacheDelete2;
      ListCache2.prototype.get = listCacheGet2;
      ListCache2.prototype.has = listCacheHas2;
      ListCache2.prototype.set = listCacheSet2;
      function MapCache2(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]);
        }
      }
      __name(MapCache2, "MapCache");
      function mapCacheClear2() {
        this.size = 0;
        this.__data__ = {
          "hash": new Hash2(),
          "map": new (Map2 || ListCache2)(),
          "string": new Hash2()
        };
      }
      __name(mapCacheClear2, "mapCacheClear");
      function mapCacheDelete2(key) {
        var result2 = getMapData2(this, key)["delete"](key);
        this.size -= result2 ? 1 : 0;
        return result2;
      }
      __name(mapCacheDelete2, "mapCacheDelete");
      function mapCacheGet2(key) {
        return getMapData2(this, key).get(key);
      }
      __name(mapCacheGet2, "mapCacheGet");
      function mapCacheHas2(key) {
        return getMapData2(this, key).has(key);
      }
      __name(mapCacheHas2, "mapCacheHas");
      function mapCacheSet2(key, value) {
        var data = getMapData2(this, key), size2 = data.size;
        data.set(key, value);
        this.size += data.size == size2 ? 0 : 1;
        return this;
      }
      __name(mapCacheSet2, "mapCacheSet");
      MapCache2.prototype.clear = mapCacheClear2;
      MapCache2.prototype["delete"] = mapCacheDelete2;
      MapCache2.prototype.get = mapCacheGet2;
      MapCache2.prototype.has = mapCacheHas2;
      MapCache2.prototype.set = mapCacheSet2;
      function SetCache(values2) {
        var index2 = -1, length = values2 == null ? 0 : values2.length;
        this.__data__ = new MapCache2();
        while (++index2 < length) {
          this.add(values2[index2]);
        }
      }
      __name(SetCache, "SetCache");
      function setCacheAdd(value) {
        this.__data__.set(value, HASH_UNDEFINED2);
        return this;
      }
      __name(setCacheAdd, "setCacheAdd");
      function setCacheHas(value) {
        return this.__data__.has(value);
      }
      __name(setCacheHas, "setCacheHas");
      SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
      SetCache.prototype.has = setCacheHas;
      function Stack2(entries) {
        var data = this.__data__ = new ListCache2(entries);
        this.size = data.size;
      }
      __name(Stack2, "Stack");
      function stackClear2() {
        this.__data__ = new ListCache2();
        this.size = 0;
      }
      __name(stackClear2, "stackClear");
      function stackDelete2(key) {
        var data = this.__data__, result2 = data["delete"](key);
        this.size = data.size;
        return result2;
      }
      __name(stackDelete2, "stackDelete");
      function stackGet2(key) {
        return this.__data__.get(key);
      }
      __name(stackGet2, "stackGet");
      function stackHas2(key) {
        return this.__data__.has(key);
      }
      __name(stackHas2, "stackHas");
      function stackSet2(key, value) {
        var data = this.__data__;
        if (data instanceof ListCache2) {
          var pairs = data.__data__;
          if (!Map2 || pairs.length < LARGE_ARRAY_SIZE2 - 1) {
            pairs.push([key, value]);
            this.size = ++data.size;
            return this;
          }
          data = this.__data__ = new MapCache2(pairs);
        }
        data.set(key, value);
        this.size = data.size;
        return this;
      }
      __name(stackSet2, "stackSet");
      Stack2.prototype.clear = stackClear2;
      Stack2.prototype["delete"] = stackDelete2;
      Stack2.prototype.get = stackGet2;
      Stack2.prototype.has = stackHas2;
      Stack2.prototype.set = stackSet2;
      function arrayLikeKeys2(value, inherited) {
        var isArr = isArray2(value), isArg = !isArr && isArguments2(value), isBuff = !isArr && !isArg && isBuffer2(value), isType = !isArr && !isArg && !isBuff && isTypedArray2(value), skipIndexes = isArr || isArg || isBuff || isType, result2 = skipIndexes ? baseTimes2(value.length, String2) : [], length = result2.length;
        for (var key in value) {
          if ((inherited || hasOwnProperty2.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.
          isIndex2(key, length)))) {
            result2.push(key);
          }
        }
        return result2;
      }
      __name(arrayLikeKeys2, "arrayLikeKeys");
      function arraySample(array) {
        var length = array.length;
        return length ? array[baseRandom(0, length - 1)] : undefined$1;
      }
      __name(arraySample, "arraySample");
      function arraySampleSize(array, n2) {
        return shuffleSelf(copyArray2(array), baseClamp(n2, 0, array.length));
      }
      __name(arraySampleSize, "arraySampleSize");
      function arrayShuffle(array) {
        return shuffleSelf(copyArray2(array));
      }
      __name(arrayShuffle, "arrayShuffle");
      function assignMergeValue(object, key, value) {
        if (value !== undefined$1 && !eq2(object[key], value) || value === undefined$1 && !(key in object)) {
          baseAssignValue2(object, key, value);
        }
      }
      __name(assignMergeValue, "assignMergeValue");
      function assignValue2(object, key, value) {
        var objValue = object[key];
        if (!(hasOwnProperty2.call(object, key) && eq2(objValue, value)) || value === undefined$1 && !(key in object)) {
          baseAssignValue2(object, key, value);
        }
      }
      __name(assignValue2, "assignValue");
      function assocIndexOf2(array, key) {
        var length = array.length;
        while (length--) {
          if (eq2(array[length][0], key)) {
            return length;
          }
        }
        return -1;
      }
      __name(assocIndexOf2, "assocIndexOf");
      function baseAggregator(collection2, setter, iteratee2, accumulator) {
        baseEach(collection2, function(value, key, collection3) {
          setter(accumulator, value, iteratee2(value), collection3);
        });
        return accumulator;
      }
      __name(baseAggregator, "baseAggregator");
      function baseAssign2(object, source) {
        return object && copyObject2(source, keys2(source), object);
      }
      __name(baseAssign2, "baseAssign");
      function baseAssignIn2(object, source) {
        return object && copyObject2(source, keysIn2(source), object);
      }
      __name(baseAssignIn2, "baseAssignIn");
      function baseAssignValue2(object, key, value) {
        if (key == "__proto__" && defineProperty2) {
          defineProperty2(object, key, {
            "configurable": true,
            "enumerable": true,
            "value": value,
            "writable": true
          });
        } else {
          object[key] = value;
        }
      }
      __name(baseAssignValue2, "baseAssignValue");
      function baseAt(object, paths) {
        var index2 = -1, length = paths.length, result2 = Array2(length), skip = object == null;
        while (++index2 < length) {
          result2[index2] = skip ? undefined$1 : get3(object, paths[index2]);
        }
        return result2;
      }
      __name(baseAt, "baseAt");
      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;
      }
      __name(baseClamp, "baseClamp");
      function baseClone2(value, bitmask, customizer, key, object, stack) {
        var result2, isDeep = bitmask & CLONE_DEEP_FLAG2, isFlat = bitmask & CLONE_FLAT_FLAG2, isFull = bitmask & CLONE_SYMBOLS_FLAG2;
        if (customizer) {
          result2 = object ? customizer(value, key, object, stack) : customizer(value);
        }
        if (result2 !== undefined$1) {
          return result2;
        }
        if (!isObject2(value)) {
          return value;
        }
        var isArr = isArray2(value);
        if (isArr) {
          result2 = initCloneArray2(value);
          if (!isDeep) {
            return copyArray2(value, result2);
          }
        } else {
          var tag = getTag2(value), isFunc = tag == funcTag2 || tag == genTag2;
          if (isBuffer2(value)) {
            return cloneBuffer2(value, isDeep);
          }
          if (tag == objectTag2 || tag == argsTag2 || isFunc && !object) {
            result2 = isFlat || isFunc ? {} : initCloneObject2(value);
            if (!isDeep) {
              return isFlat ? copySymbolsIn2(value, baseAssignIn2(result2, value)) : copySymbols2(value, baseAssign2(result2, value));
            }
          } else {
            if (!cloneableTags2[tag]) {
              return object ? value : {};
            }
            result2 = initCloneByTag2(value, tag, isDeep);
          }
        }
        stack || (stack = new Stack2());
        var stacked = stack.get(value);
        if (stacked) {
          return stacked;
        }
        stack.set(value, result2);
        if (isSet2(value)) {
          value.forEach(function(subValue) {
            result2.add(baseClone2(subValue, bitmask, customizer, subValue, value, stack));
          });
        } else if (isMap2(value)) {
          value.forEach(function(subValue, key2) {
            result2.set(key2, baseClone2(subValue, bitmask, customizer, key2, value, stack));
          });
        }
        var keysFunc = isFull ? isFlat ? getAllKeysIn2 : getAllKeys2 : isFlat ? keysIn2 : keys2;
        var props = isArr ? undefined$1 : keysFunc(value);
        arrayEach2(props || value, function(subValue, key2) {
          if (props) {
            key2 = subValue;
            subValue = value[key2];
          }
          assignValue2(result2, key2, baseClone2(subValue, bitmask, customizer, key2, value, stack));
        });
        return result2;
      }
      __name(baseClone2, "baseClone");
      function baseConforms(source) {
        var props = keys2(source);
        return function(object) {
          return baseConformsTo(object, source, props);
        };
      }
      __name(baseConforms, "baseConforms");
      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;
      }
      __name(baseConformsTo, "baseConformsTo");
      function baseDelay(func, wait, args) {
        if (typeof func != "function") {
          throw new TypeError2(FUNC_ERROR_TEXT);
        }
        return setTimeout2(function() {
          func.apply(undefined$1, args);
        }, wait);
      }
      __name(baseDelay, "baseDelay");
      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, baseUnary2(iteratee2));
        }
        if (comparator) {
          includes2 = arrayIncludesWith;
          isCommon = false;
        } else if (values2.length >= LARGE_ARRAY_SIZE2) {
          includes2 = cacheHas;
          isCommon = false;
          values2 = new SetCache(values2);
        }
        outer:
          while (++index2 < length) {
            var value = array[index2], computed2 = iteratee2 == null ? value : iteratee2(value);
            value = comparator || value !== 0 ? value : 0;
            if (isCommon && computed2 === computed2) {
              var valuesIndex = valuesLength;
              while (valuesIndex--) {
                if (values2[valuesIndex] === computed2) {
                  continue outer;
                }
              }
              result2.push(value);
            } else if (!includes2(values2, computed2, comparator)) {
              result2.push(value);
            }
          }
        return result2;
      }
      __name(baseDifference, "baseDifference");
      var baseEach = createBaseEach(baseForOwn);
      var baseEachRight = createBaseEach(baseForOwnRight, true);
      function baseEvery(collection2, predicate) {
        var result2 = true;
        baseEach(collection2, function(value, index2, collection3) {
          result2 = !!predicate(value, index2, collection3);
          return result2;
        });
        return result2;
      }
      __name(baseEvery, "baseEvery");
      function baseExtremum(array, iteratee2, comparator) {
        var index2 = -1, length = array.length;
        while (++index2 < length) {
          var value = array[index2], current = iteratee2(value);
          if (current != null && (computed2 === undefined$1 ? current === current && !isSymbol(current) : comparator(current, computed2))) {
            var computed2 = current, result2 = value;
          }
        }
        return result2;
      }
      __name(baseExtremum, "baseExtremum");
      function baseFill(array, value, start2, end) {
        var length = array.length;
        start2 = toInteger(start2);
        if (start2 < 0) {
          start2 = -start2 > length ? 0 : length + start2;
        }
        end = end === undefined$1 || end > length ? length : toInteger(end);
        if (end < 0) {
          end += length;
        }
        end = start2 > end ? 0 : toLength(end);
        while (start2 < end) {
          array[start2++] = value;
        }
        return array;
      }
      __name(baseFill, "baseFill");
      function baseFilter(collection2, predicate) {
        var result2 = [];
        baseEach(collection2, function(value, index2, collection3) {
          if (predicate(value, index2, collection3)) {
            result2.push(value);
          }
        });
        return result2;
      }
      __name(baseFilter, "baseFilter");
      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 {
              arrayPush2(result2, value);
            }
          } else if (!isStrict) {
            result2[result2.length] = value;
          }
        }
        return result2;
      }
      __name(baseFlatten, "baseFlatten");
      var baseFor = createBaseFor();
      var baseForRight = createBaseFor(true);
      function baseForOwn(object, iteratee2) {
        return object && baseFor(object, iteratee2, keys2);
      }
      __name(baseForOwn, "baseForOwn");
      function baseForOwnRight(object, iteratee2) {
        return object && baseForRight(object, iteratee2, keys2);
      }
      __name(baseForOwnRight, "baseForOwnRight");
      function baseFunctions(object, props) {
        return arrayFilter2(props, function(key) {
          return isFunction2(object[key]);
        });
      }
      __name(baseFunctions, "baseFunctions");
      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;
      }
      __name(baseGet, "baseGet");
      function baseGetAllKeys2(object, keysFunc, symbolsFunc) {
        var result2 = keysFunc(object);
        return isArray2(object) ? result2 : arrayPush2(result2, symbolsFunc(object));
      }
      __name(baseGetAllKeys2, "baseGetAllKeys");
      function baseGetTag2(value) {
        if (value == null) {
          return value === undefined$1 ? undefinedTag2 : nullTag2;
        }
        return symToStringTag2 && symToStringTag2 in Object2(value) ? getRawTag2(value) : objectToString2(value);
      }
      __name(baseGetTag2, "baseGetTag");
      function baseGt(value, other) {
        return value > other;
      }
      __name(baseGt, "baseGt");
      function baseHas(object, key) {
        return object != null && hasOwnProperty2.call(object, key);
      }
      __name(baseHas, "baseHas");
      function baseHasIn(object, key) {
        return object != null && key in Object2(object);
      }
      __name(baseHasIn, "baseHasIn");
      function baseInRange(number, start2, end) {
        return number >= nativeMin(start2, end) && number < nativeMax(start2, end);
      }
      __name(baseInRange, "baseInRange");
      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, baseUnary2(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, seen2 = caches[0];
        outer:
          while (++index2 < length && result2.length < maxLength) {
            var value = array[index2], computed2 = iteratee2 ? iteratee2(value) : value;
            value = comparator || value !== 0 ? value : 0;
            if (!(seen2 ? cacheHas(seen2, computed2) : includes2(result2, computed2, comparator))) {
              othIndex = othLength;
              while (--othIndex) {
                var cache = caches[othIndex];
                if (!(cache ? cacheHas(cache, computed2) : includes2(arrays[othIndex], computed2, comparator))) {
                  continue outer;
                }
              }
              if (seen2) {
                seen2.push(computed2);
              }
              result2.push(value);
            }
          }
        return result2;
      }
      __name(baseIntersection, "baseIntersection");
      function baseInverter(object, setter, iteratee2, accumulator) {
        baseForOwn(object, function(value, key, object2) {
          setter(accumulator, iteratee2(value), key, object2);
        });
        return accumulator;
      }
      __name(baseInverter, "baseInverter");
      function baseInvoke(object, path, args) {
        path = castPath(path, object);
        object = parent2(object, path);
        var func = object == null ? object : object[toKey(last(path))];
        return func == null ? undefined$1 : apply2(func, object, args);
      }
      __name(baseInvoke, "baseInvoke");
      function baseIsArguments2(value) {
        return isObjectLike2(value) && baseGetTag2(value) == argsTag2;
      }
      __name(baseIsArguments2, "baseIsArguments");
      function baseIsArrayBuffer(value) {
        return isObjectLike2(value) && baseGetTag2(value) == arrayBufferTag2;
      }
      __name(baseIsArrayBuffer, "baseIsArrayBuffer");
      function baseIsDate(value) {
        return isObjectLike2(value) && baseGetTag2(value) == dateTag2;
      }
      __name(baseIsDate, "baseIsDate");
      function baseIsEqual(value, other, bitmask, customizer, stack) {
        if (value === other) {
          return true;
        }
        if (value == null || other == null || !isObjectLike2(value) && !isObjectLike2(other)) {
          return value !== value && other !== other;
        }
        return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
      }
      __name(baseIsEqual, "baseIsEqual");
      function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
        var objIsArr = isArray2(object), othIsArr = isArray2(other), objTag = objIsArr ? arrayTag2 : getTag2(object), othTag = othIsArr ? arrayTag2 : getTag2(other);
        objTag = objTag == argsTag2 ? objectTag2 : objTag;
        othTag = othTag == argsTag2 ? objectTag2 : othTag;
        var objIsObj = objTag == objectTag2, othIsObj = othTag == objectTag2, isSameTag = objTag == othTag;
        if (isSameTag && isBuffer2(object)) {
          if (!isBuffer2(other)) {
            return false;
          }
          objIsArr = true;
          objIsObj = false;
        }
        if (isSameTag && !objIsObj) {
          stack || (stack = new Stack2());
          return objIsArr || isTypedArray2(object) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
        }
        if (!(bitmask & COMPARE_PARTIAL_FLAG)) {
          var objIsWrapped = objIsObj && hasOwnProperty2.call(object, "__wrapped__"), othIsWrapped = othIsObj && hasOwnProperty2.call(other, "__wrapped__");
          if (objIsWrapped || othIsWrapped) {
            var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other;
            stack || (stack = new Stack2());
            return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
          }
        }
        if (!isSameTag) {
          return false;
        }
        stack || (stack = new Stack2());
        return equalObjects(object, other, bitmask, customizer, equalFunc, stack);
      }
      __name(baseIsEqualDeep, "baseIsEqualDeep");
      function baseIsMap2(value) {
        return isObjectLike2(value) && getTag2(value) == mapTag2;
      }
      __name(baseIsMap2, "baseIsMap");
      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 Stack2();
            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;
      }
      __name(baseIsMatch, "baseIsMatch");
      function baseIsNative2(value) {
        if (!isObject2(value) || isMasked2(value)) {
          return false;
        }
        var pattern = isFunction2(value) ? reIsNative2 : reIsHostCtor2;
        return pattern.test(toSource2(value));
      }
      __name(baseIsNative2, "baseIsNative");
      function baseIsRegExp(value) {
        return isObjectLike2(value) && baseGetTag2(value) == regexpTag2;
      }
      __name(baseIsRegExp, "baseIsRegExp");
      function baseIsSet2(value) {
        return isObjectLike2(value) && getTag2(value) == setTag2;
      }
      __name(baseIsSet2, "baseIsSet");
      function baseIsTypedArray2(value) {
        return isObjectLike2(value) && isLength2(value.length) && !!typedArrayTags2[baseGetTag2(value)];
      }
      __name(baseIsTypedArray2, "baseIsTypedArray");
      function baseIteratee(value) {
        if (typeof value == "function") {
          return value;
        }
        if (value == null) {
          return identity2;
        }
        if (typeof value == "object") {
          return isArray2(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value);
        }
        return property(value);
      }
      __name(baseIteratee, "baseIteratee");
      function baseKeys2(object) {
        if (!isPrototype2(object)) {
          return nativeKeys2(object);
        }
        var result2 = [];
        for (var key in Object2(object)) {
          if (hasOwnProperty2.call(object, key) && key != "constructor") {
            result2.push(key);
          }
        }
        return result2;
      }
      __name(baseKeys2, "baseKeys");
      function baseKeysIn2(object) {
        if (!isObject2(object)) {
          return nativeKeysIn2(object);
        }
        var isProto = isPrototype2(object), result2 = [];
        for (var key in object) {
          if (!(key == "constructor" && (isProto || !hasOwnProperty2.call(object, key)))) {
            result2.push(key);
          }
        }
        return result2;
      }
      __name(baseKeysIn2, "baseKeysIn");
      function baseLt(value, other) {
        return value < other;
      }
      __name(baseLt, "baseLt");
      function baseMap(collection2, iteratee2) {
        var index2 = -1, result2 = isArrayLike2(collection2) ? Array2(collection2.length) : [];
        baseEach(collection2, function(value, key, collection3) {
          result2[++index2] = iteratee2(value, key, collection3);
        });
        return result2;
      }
      __name(baseMap, "baseMap");
      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);
        };
      }
      __name(baseMatches, "baseMatches");
      function baseMatchesProperty(path, srcValue) {
        if (isKey(path) && isStrictComparable(srcValue)) {
          return matchesStrictComparable(toKey(path), srcValue);
        }
        return function(object) {
          var objValue = get3(object, path);
          return objValue === undefined$1 && objValue === srcValue ? hasIn(object, path) : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);
        };
      }
      __name(baseMatchesProperty, "baseMatchesProperty");
      function baseMerge(object, source, srcIndex, customizer, stack) {
        if (object === source) {
          return;
        }
        baseFor(source, function(srcValue, key) {
          stack || (stack = new Stack2());
          if (isObject2(srcValue)) {
            baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);
          } else {
            var newValue2 = customizer ? customizer(safeGet2(object, key), srcValue, key + "", object, source, stack) : undefined$1;
            if (newValue2 === undefined$1) {
              newValue2 = srcValue;
            }
            assignMergeValue(object, key, newValue2);
          }
        }, keysIn2);
      }
      __name(baseMerge, "baseMerge");
      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 newValue2 = customizer ? customizer(objValue, srcValue, key + "", object, source, stack) : undefined$1;
        var isCommon = newValue2 === undefined$1;
        if (isCommon) {
          var isArr = isArray2(srcValue), isBuff = !isArr && isBuffer2(srcValue), isTyped = !isArr && !isBuff && isTypedArray2(srcValue);
          newValue2 = srcValue;
          if (isArr || isBuff || isTyped) {
            if (isArray2(objValue)) {
              newValue2 = objValue;
            } else if (isArrayLikeObject(objValue)) {
              newValue2 = copyArray2(objValue);
            } else if (isBuff) {
              isCommon = false;
              newValue2 = cloneBuffer2(srcValue, true);
            } else if (isTyped) {
              isCommon = false;
              newValue2 = cloneTypedArray2(srcValue, true);
            } else {
              newValue2 = [];
            }
          } else if (isPlainObject2(srcValue) || isArguments2(srcValue)) {
            newValue2 = objValue;
            if (isArguments2(objValue)) {
              newValue2 = toPlainObject(objValue);
            } else if (!isObject2(objValue) || isFunction2(objValue)) {
              newValue2 = initCloneObject2(srcValue);
            }
          } else {
            isCommon = false;
          }
        }
        if (isCommon) {
          stack.set(srcValue, newValue2);
          mergeFunc(newValue2, srcValue, srcIndex, customizer, stack);
          stack["delete"](srcValue);
        }
        assignMergeValue(object, key, newValue2);
      }
      __name(baseMergeDeep, "baseMergeDeep");
      function baseNth(array, n2) {
        var length = array.length;
        if (!length) {
          return;
        }
        n2 += n2 < 0 ? length : 0;
        return isIndex2(n2, length) ? array[n2] : undefined$1;
      }
      __name(baseNth, "baseNth");
      function baseOrderBy(collection2, iteratees, orders) {
        if (iteratees.length) {
          iteratees = arrayMap(iteratees, function(iteratee2) {
            if (isArray2(iteratee2)) {
              return function(value) {
                return baseGet(value, iteratee2.length === 1 ? iteratee2[0] : iteratee2);
              };
            }
            return iteratee2;
          });
        } else {
          iteratees = [identity2];
        }
        var index2 = -1;
        iteratees = arrayMap(iteratees, baseUnary2(getIteratee()));
        var result2 = baseMap(collection2, function(value, key, collection3) {
          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);
        });
      }
      __name(baseOrderBy, "baseOrderBy");
      function basePick(object, paths) {
        return basePickBy(object, paths, function(value, path) {
          return hasIn(object, path);
        });
      }
      __name(basePick, "basePick");
      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;
      }
      __name(basePickBy, "basePickBy");
      function basePropertyDeep(path) {
        return function(object) {
          return baseGet(object, path);
        };
      }
      __name(basePropertyDeep, "basePropertyDeep");
      function basePullAll(array, values2, iteratee2, comparator) {
        var indexOf2 = comparator ? baseIndexOfWith : baseIndexOf, index2 = -1, length = values2.length, seen2 = array;
        if (array === values2) {
          values2 = copyArray2(values2);
        }
        if (iteratee2) {
          seen2 = arrayMap(array, baseUnary2(iteratee2));
        }
        while (++index2 < length) {
          var fromIndex = 0, value = values2[index2], computed2 = iteratee2 ? iteratee2(value) : value;
          while ((fromIndex = indexOf2(seen2, computed2, fromIndex, comparator)) > -1) {
            if (seen2 !== array) {
              splice2.call(seen2, fromIndex, 1);
            }
            splice2.call(array, fromIndex, 1);
          }
        }
        return array;
      }
      __name(basePullAll, "basePullAll");
      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 (isIndex2(index2)) {
              splice2.call(array, index2, 1);
            } else {
              baseUnset(array, index2);
            }
          }
        }
        return array;
      }
      __name(basePullAt, "basePullAt");
      function baseRandom(lower, upper) {
        return lower + nativeFloor(nativeRandom() * (upper - lower + 1));
      }
      __name(baseRandom, "baseRandom");
      function baseRange(start2, end, step, fromRight) {
        var index2 = -1, length = nativeMax(nativeCeil((end - start2) / (step || 1)), 0), result2 = Array2(length);
        while (length--) {
          result2[fromRight ? length : ++index2] = start2;
          start2 += step;
        }
        return result2;
      }
      __name(baseRange, "baseRange");
      function baseRepeat(string, n2) {
        var result2 = "";
        if (!string || n2 < 1 || n2 > MAX_SAFE_INTEGER2) {
          return result2;
        }
        do {
          if (n2 % 2) {
            result2 += string;
          }
          n2 = nativeFloor(n2 / 2);
          if (n2) {
            string += string;
          }
        } while (n2);
        return result2;
      }
      __name(baseRepeat, "baseRepeat");
      function baseRest(func, start2) {
        return setToString(overRest(func, start2, identity2), func + "");
      }
      __name(baseRest, "baseRest");
      function baseSample(collection2) {
        return arraySample(values(collection2));
      }
      __name(baseSample, "baseSample");
      function baseSampleSize(collection2, n2) {
        var array = values(collection2);
        return shuffleSelf(array, baseClamp(n2, 0, array.length));
      }
      __name(baseSampleSize, "baseSampleSize");
      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]), newValue2 = value;
          if (key === "__proto__" || key === "constructor" || key === "prototype") {
            return object;
          }
          if (index2 != lastIndex) {
            var objValue = nested[key];
            newValue2 = customizer ? customizer(objValue, key, nested) : undefined$1;
            if (newValue2 === undefined$1) {
              newValue2 = isObject2(objValue) ? objValue : isIndex2(path[index2 + 1]) ? [] : {};
            }
          }
          assignValue2(nested, key, newValue2);
          nested = nested[key];
        }
        return object;
      }
      __name(baseSet, "baseSet");
      var baseSetData = !metaMap ? identity2 : function(func, data) {
        metaMap.set(func, data);
        return func;
      };
      var baseSetToString = !defineProperty2 ? identity2 : function(func, string) {
        return defineProperty2(func, "toString", {
          "configurable": true,
          "enumerable": false,
          "value": constant(string),
          "writable": true
        });
      };
      function baseShuffle(collection2) {
        return shuffleSelf(values(collection2));
      }
      __name(baseShuffle, "baseShuffle");
      function baseSlice(array, start2, end) {
        var index2 = -1, length = array.length;
        if (start2 < 0) {
          start2 = -start2 > length ? 0 : length + start2;
        }
        end = end > length ? length : end;
        if (end < 0) {
          end += length;
        }
        length = start2 > end ? 0 : end - start2 >>> 0;
        start2 >>>= 0;
        var result2 = Array2(length);
        while (++index2 < length) {
          result2[index2] = array[index2 + start2];
        }
        return result2;
      }
      __name(baseSlice, "baseSlice");
      function baseSome(collection2, predicate) {
        var result2;
        baseEach(collection2, function(value, index2, collection3) {
          result2 = predicate(value, index2, collection3);
          return !result2;
        });
        return !!result2;
      }
      __name(baseSome, "baseSome");
      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, computed2 = array[mid];
            if (computed2 !== null && !isSymbol(computed2) && (retHighest ? computed2 <= value : computed2 < value)) {
              low = mid + 1;
            } else {
              high = mid;
            }
          }
          return high;
        }
        return baseSortedIndexBy(array, value, identity2, retHighest);
      }
      __name(baseSortedIndex, "baseSortedIndex");
      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), computed2 = iteratee2(array[mid]), othIsDefined = computed2 !== undefined$1, othIsNull = computed2 === null, othIsReflexive = computed2 === computed2, othIsSymbol = isSymbol(computed2);
          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 ? computed2 <= value : computed2 < value;
          }
          if (setLow) {
            low = mid + 1;
          } else {
            high = mid;
          }
        }
        return nativeMin(high, MAX_ARRAY_INDEX);
      }
      __name(baseSortedIndexBy, "baseSortedIndexBy");
      function baseSortedUniq(array, iteratee2) {
        var index2 = -1, length = array.length, resIndex = 0, result2 = [];
        while (++index2 < length) {
          var value = array[index2], computed2 = iteratee2 ? iteratee2(value) : value;
          if (!index2 || !eq2(computed2, seen2)) {
            var seen2 = computed2;
            result2[resIndex++] = value === 0 ? 0 : value;
          }
        }
        return result2;
      }
      __name(baseSortedUniq, "baseSortedUniq");
      function baseToNumber(value) {
        if (typeof value == "number") {
          return value;
        }
        if (isSymbol(value)) {
          return NAN;
        }
        return +value;
      }
      __name(baseToNumber, "baseToNumber");
      function baseToString2(value) {
        if (typeof value == "string") {
          return value;
        }
        if (isArray2(value)) {
          return arrayMap(value, baseToString2) + "";
        }
        if (isSymbol(value)) {
          return symbolToString ? symbolToString.call(value) : "";
        }
        var result2 = value + "";
        return result2 == "0" && 1 / value == -INFINITY2 ? "-0" : result2;
      }
      __name(baseToString2, "baseToString");
      function baseUniq(array, iteratee2, comparator) {
        var index2 = -1, includes2 = arrayIncludes, length = array.length, isCommon = true, result2 = [], seen2 = result2;
        if (comparator) {
          isCommon = false;
          includes2 = arrayIncludesWith;
        } else if (length >= LARGE_ARRAY_SIZE2) {
          var set4 = iteratee2 ? null : createSet(array);
          if (set4) {
            return setToArray(set4);
          }
          isCommon = false;
          includes2 = cacheHas;
          seen2 = new SetCache();
        } else {
          seen2 = iteratee2 ? [] : result2;
        }
        outer:
          while (++index2 < length) {
            var value = array[index2], computed2 = iteratee2 ? iteratee2(value) : value;
            value = comparator || value !== 0 ? value : 0;
            if (isCommon && computed2 === computed2) {
              var seenIndex = seen2.length;
              while (seenIndex--) {
                if (seen2[seenIndex] === computed2) {
                  continue outer;
                }
              }
              if (iteratee2) {
                seen2.push(computed2);
              }
              result2.push(value);
            } else if (!includes2(seen2, computed2, comparator)) {
              if (seen2 !== result2) {
                seen2.push(computed2);
              }
              result2.push(value);
            }
          }
        return result2;
      }
      __name(baseUniq, "baseUniq");
      function baseUnset(object, path) {
        path = castPath(path, object);
        object = parent2(object, path);
        return object == null || delete object[toKey(last(path))];
      }
      __name(baseUnset, "baseUnset");
      function baseUpdate(object, path, updater, customizer) {
        return baseSet(object, path, updater(baseGet(object, path)), customizer);
      }
      __name(baseUpdate, "baseUpdate");
      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);
      }
      __name(baseWhile, "baseWhile");
      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, arrayPush2([result3], action.args));
        }, result2);
      }
      __name(baseWrapperValue, "baseWrapperValue");
      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);
      }
      __name(baseXor, "baseXor");
      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;
      }
      __name(baseZipObject, "baseZipObject");
      function castArrayLikeObject(value) {
        return isArrayLikeObject(value) ? value : [];
      }
      __name(castArrayLikeObject, "castArrayLikeObject");
      function castFunction(value) {
        return typeof value == "function" ? value : identity2;
      }
      __name(castFunction, "castFunction");
      function castPath(value, object) {
        if (isArray2(value)) {
          return value;
        }
        return isKey(value, object) ? [value] : stringToPath(toString3(value));
      }
      __name(castPath, "castPath");
      var castRest = baseRest;
      function castSlice(array, start2, end) {
        var length = array.length;
        end = end === undefined$1 ? length : end;
        return !start2 && end >= length ? array : baseSlice(array, start2, end);
      }
      __name(castSlice, "castSlice");
      var clearTimeout2 = ctxClearTimeout || function(id2) {
        return root2.clearTimeout(id2);
      };
      function cloneBuffer2(buffer, isDeep) {
        if (isDeep) {
          return buffer.slice();
        }
        var length = buffer.length, result2 = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
        buffer.copy(result2);
        return result2;
      }
      __name(cloneBuffer2, "cloneBuffer");
      function cloneArrayBuffer2(arrayBuffer) {
        var result2 = new arrayBuffer.constructor(arrayBuffer.byteLength);
        new Uint8Array2(result2).set(new Uint8Array2(arrayBuffer));
        return result2;
      }
      __name(cloneArrayBuffer2, "cloneArrayBuffer");
      function cloneDataView2(dataView, isDeep) {
        var buffer = isDeep ? cloneArrayBuffer2(dataView.buffer) : dataView.buffer;
        return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
      }
      __name(cloneDataView2, "cloneDataView");
      function cloneRegExp2(regexp2) {
        var result2 = new regexp2.constructor(regexp2.source, reFlags2.exec(regexp2));
        result2.lastIndex = regexp2.lastIndex;
        return result2;
      }
      __name(cloneRegExp2, "cloneRegExp");
      function cloneSymbol2(symbol) {
        return symbolValueOf2 ? Object2(symbolValueOf2.call(symbol)) : {};
      }
      __name(cloneSymbol2, "cloneSymbol");
      function cloneTypedArray2(typedArray, isDeep) {
        var buffer = isDeep ? cloneArrayBuffer2(typedArray.buffer) : typedArray.buffer;
        return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
      }
      __name(cloneTypedArray2, "cloneTypedArray");
      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;
      }
      __name(compareAscending, "compareAscending");
      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;
      }
      __name(compareMultiple, "compareMultiple");
      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;
      }
      __name(composeArgs, "composeArgs");
      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;
      }
      __name(composeArgsRight, "composeArgsRight");
      function copyArray2(source, array) {
        var index2 = -1, length = source.length;
        array || (array = Array2(length));
        while (++index2 < length) {
          array[index2] = source[index2];
        }
        return array;
      }
      __name(copyArray2, "copyArray");
      function copyObject2(source, props, object, customizer) {
        var isNew = !object;
        object || (object = {});
        var index2 = -1, length = props.length;
        while (++index2 < length) {
          var key = props[index2];
          var newValue2 = customizer ? customizer(object[key], source[key], key, object, source) : undefined$1;
          if (newValue2 === undefined$1) {
            newValue2 = source[key];
          }
          if (isNew) {
            baseAssignValue2(object, key, newValue2);
          } else {
            assignValue2(object, key, newValue2);
          }
        }
        return object;
      }
      __name(copyObject2, "copyObject");
      function copySymbols2(source, object) {
        return copyObject2(source, getSymbols2(source), object);
      }
      __name(copySymbols2, "copySymbols");
      function copySymbolsIn2(source, object) {
        return copyObject2(source, getSymbolsIn2(source), object);
      }
      __name(copySymbolsIn2, "copySymbolsIn");
      function createAggregator(setter, initializer) {
        return function(collection2, iteratee2) {
          var func = isArray2(collection2) ? arrayAggregator : baseAggregator, accumulator = initializer ? initializer() : {};
          return func(collection2, setter, getIteratee(iteratee2, 2), accumulator);
        };
      }
      __name(createAggregator, "createAggregator");
      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;
        });
      }
      __name(createAssigner, "createAssigner");
      function createBaseEach(eachFunc, fromRight) {
        return function(collection2, iteratee2) {
          if (collection2 == null) {
            return collection2;
          }
          if (!isArrayLike2(collection2)) {
            return eachFunc(collection2, iteratee2);
          }
          var length = collection2.length, index2 = fromRight ? length : -1, iterable = Object2(collection2);
          while (fromRight ? index2-- : ++index2 < length) {
            if (iteratee2(iterable[index2], index2, iterable) === false) {
              break;
            }
          }
          return collection2;
        };
      }
      __name(createBaseEach, "createBaseEach");
      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;
        };
      }
      __name(createBaseFor, "createBaseFor");
      function createBind(func, bitmask, thisArg) {
        var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func);
        function wrapper() {
          var fn = this && this !== root2 && this instanceof wrapper ? Ctor : func;
          return fn.apply(isBind ? thisArg : this, arguments);
        }
        __name(wrapper, "wrapper");
        return wrapper;
      }
      __name(createBind, "createBind");
      function createCaseFirst(methodName) {
        return function(string) {
          string = toString3(string);
          var strSymbols = hasUnicode(string) ? stringToArray2(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;
        };
      }
      __name(createCaseFirst, "createCaseFirst");
      function createCompounder(callback) {
        return function(string) {
          return arrayReduce(words(deburr(string).replace(reApos, "")), callback, "");
        };
      }
      __name(createCompounder, "createCompounder");
      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 = baseCreate2(Ctor.prototype), result2 = Ctor.apply(thisBinding, args);
          return isObject2(result2) ? result2 : thisBinding;
        };
      }
      __name(createCtor, "createCtor");
      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 fn = this && this !== root2 && this instanceof wrapper ? Ctor : func;
          return apply2(fn, this, args);
        }
        __name(wrapper, "wrapper");
        return wrapper;
      }
      __name(createCurry, "createCurry");
      function createFind(findIndexFunc) {
        return function(collection2, predicate, fromIndex) {
          var iterable = Object2(collection2);
          if (!isArrayLike2(collection2)) {
            var iteratee2 = getIteratee(predicate, 3);
            collection2 = keys2(collection2);
            predicate = /* @__PURE__ */ __name(function(key) {
              return iteratee2(iterable[key], key, iterable);
            }, "predicate");
          }
          var index2 = findIndexFunc(collection2, predicate, fromIndex);
          return index2 > -1 ? iterable[iteratee2 ? collection2[index2] : index2] : undefined$1;
        };
      }
      __name(createFind, "createFind");
      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 && isArray2(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;
          };
        });
      }
      __name(createFlow, "createFlow");
      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, fn = 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 !== root2 && this instanceof wrapper) {
            fn = Ctor || createCtor(fn);
          }
          return fn.apply(thisBinding, args);
        }
        __name(wrapper, "wrapper");
        return wrapper;
      }
      __name(createHybrid, "createHybrid");
      function createInverter(setter, toIteratee) {
        return function(object, iteratee2) {
          return baseInverter(object, setter, toIteratee(iteratee2), {});
        };
      }
      __name(createInverter, "createInverter");
      function createMathOperation(operator, defaultValue) {
        return function(value, other) {
          var result2;
          if (value === undefined$1 && other === undefined$1) {
            return defaultValue;
          }
          if (value !== undefined$1) {
            result2 = value;
          }
          if (other !== undefined$1) {
            if (result2 === undefined$1) {
              return other;
            }
            if (typeof value == "string" || typeof other == "string") {
              value = baseToString2(value);
              other = baseToString2(other);
            } else {
              value = baseToNumber(value);
              other = baseToNumber(other);
            }
            result2 = operator(value, other);
          }
          return result2;
        };
      }
      __name(createMathOperation, "createMathOperation");
      function createOver(arrayFunc) {
        return flatRest(function(iteratees) {
          iteratees = arrayMap(iteratees, baseUnary2(getIteratee()));
          return baseRest(function(args) {
            var thisArg = this;
            return arrayFunc(iteratees, function(iteratee2) {
              return apply2(iteratee2, thisArg, args);
            });
          });
        });
      }
      __name(createOver, "createOver");
      function createPadding(length, chars2) {
        chars2 = chars2 === undefined$1 ? " " : baseToString2(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(stringToArray2(result2), 0, length).join("") : result2.slice(0, length);
      }
      __name(createPadding, "createPadding");
      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), fn = this && this !== root2 && this instanceof wrapper ? Ctor : func;
          while (++leftIndex < leftLength) {
            args[leftIndex] = partials[leftIndex];
          }
          while (argsLength--) {
            args[leftIndex++] = arguments[++argsIndex];
          }
          return apply2(fn, isBind ? thisArg : this, args);
        }
        __name(wrapper, "wrapper");
        return wrapper;
      }
      __name(createPartial, "createPartial");
      function createRange(fromRight) {
        return function(start2, end, step) {
          if (step && typeof step != "number" && isIterateeCall(start2, end, step)) {
            end = step = undefined$1;
          }
          start2 = toFinite(start2);
          if (end === undefined$1) {
            end = start2;
            start2 = 0;
          } else {
            end = toFinite(end);
          }
          step = step === undefined$1 ? start2 < end ? 1 : -1 : toFinite(step);
          return baseRange(start2, end, step, fromRight);
        };
      }
      __name(createRange, "createRange");
      function createRelationalOperation(operator) {
        return function(value, other) {
          if (!(typeof value == "string" && typeof other == "string")) {
            value = toNumber2(value);
            other = toNumber2(other);
          }
          return operator(value, other);
        };
      }
      __name(createRelationalOperation, "createRelationalOperation");
      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);
      }
      __name(createRecurry, "createRecurry");
      function createRound(methodName) {
        var func = Math2[methodName];
        return function(number, precision) {
          number = toNumber2(number);
          precision = precision == null ? 0 : nativeMin(toInteger(precision), 292);
          if (precision && nativeIsFinite(number)) {
            var pair = (toString3(number) + "e").split("e"), value = func(pair[0] + "e" + (+pair[1] + precision));
            pair = (toString3(value) + "e").split("e");
            return +(pair[0] + "e" + (+pair[1] - precision));
          }
          return func(number);
        };
      }
      __name(createRound, "createRound");
      var createSet = !(Set2 && 1 / setToArray(new Set2([, -0]))[1] == INFINITY2) ? noop2 : function(values2) {
        return new Set2(values2);
      };
      function createToPairs(keysFunc) {
        return function(object) {
          var tag = getTag2(object);
          if (tag == mapTag2) {
            return mapToArray(object);
          }
          if (tag == setTag2) {
            return setToPairs(object);
          }
          return baseToPairs(object, keysFunc(object));
        };
      }
      __name(createToPairs, "createToPairs");
      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);
      }
      __name(createWrap, "createWrap");
      function customDefaultsAssignIn(objValue, srcValue, key, object) {
        if (objValue === undefined$1 || eq2(objValue, objectProto2[key]) && !hasOwnProperty2.call(object, key)) {
          return srcValue;
        }
        return objValue;
      }
      __name(customDefaultsAssignIn, "customDefaultsAssignIn");
      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;
      }
      __name(customDefaultsMerge, "customDefaultsMerge");
      function customOmitClone(value) {
        return isPlainObject2(value) ? undefined$1 : value;
      }
      __name(customOmitClone, "customOmitClone");
      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, seen2 = 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 (seen2) {
            if (!arraySome(other, function(othValue2, othIndex) {
              if (!cacheHas(seen2, othIndex) && (arrValue === othValue2 || equalFunc(arrValue, othValue2, bitmask, customizer, stack))) {
                return seen2.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;
      }
      __name(equalArrays, "equalArrays");
      function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
        switch (tag) {
          case dataViewTag2:
            if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) {
              return false;
            }
            object = object.buffer;
            other = other.buffer;
          case arrayBufferTag2:
            if (object.byteLength != other.byteLength || !equalFunc(new Uint8Array2(object), new Uint8Array2(other))) {
              return false;
            }
            return true;
          case boolTag2:
          case dateTag2:
          case numberTag2:
            return eq2(+object, +other);
          case errorTag2:
            return object.name == other.name && object.message == other.message;
          case regexpTag2:
          case stringTag2:
            return object == other + "";
          case mapTag2:
            var convert = mapToArray;
          case setTag2:
            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 symbolTag2:
            if (symbolValueOf2) {
              return symbolValueOf2.call(object) == symbolValueOf2.call(other);
            }
        }
        return false;
      }
      __name(equalByTag, "equalByTag");
      function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
        var isPartial = bitmask & COMPARE_PARTIAL_FLAG, objProps = getAllKeys2(object), objLength = objProps.length, othProps = getAllKeys2(other), othLength = othProps.length;
        if (objLength != othLength && !isPartial) {
          return false;
        }
        var index2 = objLength;
        while (index2--) {
          var key = objProps[index2];
          if (!(isPartial ? key in other : hasOwnProperty2.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;
      }
      __name(equalObjects, "equalObjects");
      function flatRest(func) {
        return setToString(overRest(func, undefined$1, flatten2), func + "");
      }
      __name(flatRest, "flatRest");
      function getAllKeys2(object) {
        return baseGetAllKeys2(object, keys2, getSymbols2);
      }
      __name(getAllKeys2, "getAllKeys");
      function getAllKeysIn2(object) {
        return baseGetAllKeys2(object, keysIn2, getSymbolsIn2);
      }
      __name(getAllKeysIn2, "getAllKeysIn");
      var getData = !metaMap ? noop2 : function(func) {
        return metaMap.get(func);
      };
      function getFuncName(func) {
        var result2 = func.name + "", array = realNames[result2], length = hasOwnProperty2.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;
      }
      __name(getFuncName, "getFuncName");
      function getHolder(func) {
        var object = hasOwnProperty2.call(lodash2, "placeholder") ? lodash2 : func;
        return object.placeholder;
      }
      __name(getHolder, "getHolder");
      function getIteratee() {
        var result2 = lodash2.iteratee || iteratee;
        result2 = result2 === iteratee ? baseIteratee : result2;
        return arguments.length ? result2(arguments[0], arguments[1]) : result2;
      }
      __name(getIteratee, "getIteratee");
      function getMapData2(map4, key) {
        var data = map4.__data__;
        return isKeyable2(key) ? data[typeof key == "string" ? "string" : "hash"] : data.map;
      }
      __name(getMapData2, "getMapData");
      function getMatchData(object) {
        var result2 = keys2(object), length = result2.length;
        while (length--) {
          var key = result2[length], value = object[key];
          result2[length] = [key, value, isStrictComparable(value)];
        }
        return result2;
      }
      __name(getMatchData, "getMatchData");
      function getNative2(object, key) {
        var value = getValue2(object, key);
        return baseIsNative2(value) ? value : undefined$1;
      }
      __name(getNative2, "getNative");
      function getRawTag2(value) {
        var isOwn = hasOwnProperty2.call(value, symToStringTag2), tag = value[symToStringTag2];
        try {
          value[symToStringTag2] = undefined$1;
          var unmasked = true;
        } catch (e2) {
        }
        var result2 = nativeObjectToString2.call(value);
        if (unmasked) {
          if (isOwn) {
            value[symToStringTag2] = tag;
          } else {
            delete value[symToStringTag2];
          }
        }
        return result2;
      }
      __name(getRawTag2, "getRawTag");
      var getSymbols2 = !nativeGetSymbols2 ? stubArray2 : function(object) {
        if (object == null) {
          return [];
        }
        object = Object2(object);
        return arrayFilter2(nativeGetSymbols2(object), function(symbol) {
          return propertyIsEnumerable2.call(object, symbol);
        });
      };
      var getSymbolsIn2 = !nativeGetSymbols2 ? stubArray2 : function(object) {
        var result2 = [];
        while (object) {
          arrayPush2(result2, getSymbols2(object));
          object = getPrototype2(object);
        }
        return result2;
      };
      var getTag2 = baseGetTag2;
      if (DataView2 && getTag2(new DataView2(new ArrayBuffer(1))) != dataViewTag2 || Map2 && getTag2(new Map2()) != mapTag2 || Promise2 && getTag2(Promise2.resolve()) != promiseTag2 || Set2 && getTag2(new Set2()) != setTag2 || WeakMap2 && getTag2(new WeakMap2()) != weakMapTag2) {
        getTag2 = /* @__PURE__ */ __name(function(value) {
          var result2 = baseGetTag2(value), Ctor = result2 == objectTag2 ? value.constructor : undefined$1, ctorString = Ctor ? toSource2(Ctor) : "";
          if (ctorString) {
            switch (ctorString) {
              case dataViewCtorString2:
                return dataViewTag2;
              case mapCtorString2:
                return mapTag2;
              case promiseCtorString2:
                return promiseTag2;
              case setCtorString2:
                return setTag2;
              case weakMapCtorString2:
                return weakMapTag2;
            }
          }
          return result2;
        }, "getTag");
      }
      function getView(start2, end, transforms) {
        var index2 = -1, length = transforms.length;
        while (++index2 < length) {
          var data = transforms[index2], size2 = data.size;
          switch (data.type) {
            case "drop":
              start2 += size2;
              break;
            case "dropRight":
              end -= size2;
              break;
            case "take":
              end = nativeMin(end, start2 + size2);
              break;
            case "takeRight":
              start2 = nativeMax(start2, end - size2);
              break;
          }
        }
        return { "start": start2, "end": end };
      }
      __name(getView, "getView");
      function getWrapDetails(source) {
        var match2 = source.match(reWrapDetails);
        return match2 ? match2[1].split(reSplitDetails) : [];
      }
      __name(getWrapDetails, "getWrapDetails");
      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 && isLength2(length) && isIndex2(key, length) && (isArray2(object) || isArguments2(object));
      }
      __name(hasPath, "hasPath");
      function initCloneArray2(array) {
        var length = array.length, result2 = new array.constructor(length);
        if (length && typeof array[0] == "string" && hasOwnProperty2.call(array, "index")) {
          result2.index = array.index;
          result2.input = array.input;
        }
        return result2;
      }
      __name(initCloneArray2, "initCloneArray");
      function initCloneObject2(object) {
        return typeof object.constructor == "function" && !isPrototype2(object) ? baseCreate2(getPrototype2(object)) : {};
      }
      __name(initCloneObject2, "initCloneObject");
      function initCloneByTag2(object, tag, isDeep) {
        var Ctor = object.constructor;
        switch (tag) {
          case arrayBufferTag2:
            return cloneArrayBuffer2(object);
          case boolTag2:
          case dateTag2:
            return new Ctor(+object);
          case dataViewTag2:
            return cloneDataView2(object, isDeep);
          case float32Tag2:
          case float64Tag2:
          case int8Tag2:
          case int16Tag2:
          case int32Tag2:
          case uint8Tag2:
          case uint8ClampedTag2:
          case uint16Tag2:
          case uint32Tag2:
            return cloneTypedArray2(object, isDeep);
          case mapTag2:
            return new Ctor();
          case numberTag2:
          case stringTag2:
            return new Ctor(object);
          case regexpTag2:
            return cloneRegExp2(object);
          case setTag2:
            return new Ctor();
          case symbolTag2:
            return cloneSymbol2(object);
        }
      }
      __name(initCloneByTag2, "initCloneByTag");
      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");
      }
      __name(insertWrapDetails, "insertWrapDetails");
      function isFlattenable(value) {
        return isArray2(value) || isArguments2(value) || !!(spreadableSymbol && value && value[spreadableSymbol]);
      }
      __name(isFlattenable, "isFlattenable");
      function isIndex2(value, length) {
        var type = typeof value;
        length = length == null ? MAX_SAFE_INTEGER2 : length;
        return !!length && (type == "number" || type != "symbol" && reIsUint2.test(value)) && (value > -1 && value % 1 == 0 && value < length);
      }
      __name(isIndex2, "isIndex");
      function isIterateeCall(value, index2, object) {
        if (!isObject2(object)) {
          return false;
        }
        var type = typeof index2;
        if (type == "number" ? isArrayLike2(object) && isIndex2(index2, object.length) : type == "string" && index2 in object) {
          return eq2(object[index2], value);
        }
        return false;
      }
      __name(isIterateeCall, "isIterateeCall");
      function isKey(value, object) {
        if (isArray2(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);
      }
      __name(isKey, "isKey");
      function isKeyable2(value) {
        var type = typeof value;
        return type == "string" || type == "number" || type == "symbol" || type == "boolean" ? value !== "__proto__" : value === null;
      }
      __name(isKeyable2, "isKeyable");
      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];
      }
      __name(isLaziable, "isLaziable");
      function isMasked2(func) {
        return !!maskSrcKey2 && maskSrcKey2 in func;
      }
      __name(isMasked2, "isMasked");
      var isMaskable = coreJsData2 ? isFunction2 : stubFalse2;
      function isPrototype2(value) {
        var Ctor = value && value.constructor, proto = typeof Ctor == "function" && Ctor.prototype || objectProto2;
        return value === proto;
      }
      __name(isPrototype2, "isPrototype");
      function isStrictComparable(value) {
        return value === value && !isObject2(value);
      }
      __name(isStrictComparable, "isStrictComparable");
      function matchesStrictComparable(key, srcValue) {
        return function(object) {
          if (object == null) {
            return false;
          }
          return object[key] === srcValue && (srcValue !== undefined$1 || key in Object2(object));
        };
      }
      __name(matchesStrictComparable, "matchesStrictComparable");
      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;
      }
      __name(memoizeCapped, "memoizeCapped");
      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;
      }
      __name(mergeData, "mergeData");
      function nativeKeysIn2(object) {
        var result2 = [];
        if (object != null) {
          for (var key in Object2(object)) {
            result2.push(key);
          }
        }
        return result2;
      }
      __name(nativeKeysIn2, "nativeKeysIn");
      function objectToString2(value) {
        return nativeObjectToString2.call(value);
      }
      __name(objectToString2, "objectToString");
      function overRest(func, start2, transform2) {
        start2 = nativeMax(start2 === undefined$1 ? func.length - 1 : start2, 0);
        return function() {
          var args = arguments, index2 = -1, length = nativeMax(args.length - start2, 0), array = Array2(length);
          while (++index2 < length) {
            array[index2] = args[start2 + index2];
          }
          index2 = -1;
          var otherArgs = Array2(start2 + 1);
          while (++index2 < start2) {
            otherArgs[index2] = args[index2];
          }
          otherArgs[start2] = transform2(array);
          return apply2(func, this, otherArgs);
        };
      }
      __name(overRest, "overRest");
      function parent2(object, path) {
        return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1));
      }
      __name(parent2, "parent");
      function reorder(array, indexes) {
        var arrLength = array.length, length = nativeMin(indexes.length, arrLength), oldArray = copyArray2(array);
        while (length--) {
          var index2 = indexes[length];
          array[length] = isIndex2(index2, arrLength) ? oldArray[index2] : undefined$1;
        }
        return array;
      }
      __name(reorder, "reorder");
      function safeGet2(object, key) {
        if (key === "constructor" && typeof object[key] === "function") {
          return;
        }
        if (key == "__proto__") {
          return;
        }
        return object[key];
      }
      __name(safeGet2, "safeGet");
      var setData = shortOut(baseSetData);
      var setTimeout2 = ctxSetTimeout || function(func, wait) {
        return root2.setTimeout(func, wait);
      };
      var setToString = shortOut(baseSetToString);
      function setWrapToString(wrapper, reference2, bitmask) {
        var source = reference2 + "";
        return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask)));
      }
      __name(setWrapToString, "setWrapToString");
      function shortOut(func) {
        var count2 = 0, lastCalled = 0;
        return function() {
          var stamp = nativeNow(), remaining = HOT_SPAN - (stamp - lastCalled);
          lastCalled = stamp;
          if (remaining > 0) {
            if (++count2 >= HOT_COUNT) {
              return arguments[0];
            }
          } else {
            count2 = 0;
          }
          return func.apply(undefined$1, arguments);
        };
      }
      __name(shortOut, "shortOut");
      function shuffleSelf(array, size2) {
        var index2 = -1, length = array.length, lastIndex = length - 1;
        size2 = size2 === undefined$1 ? length : size2;
        while (++index2 < size2) {
          var rand2 = baseRandom(index2, lastIndex), value = array[rand2];
          array[rand2] = array[index2];
          array[index2] = value;
        }
        array.length = size2;
        return array;
      }
      __name(shuffleSelf, "shuffleSelf");
      var stringToPath = memoizeCapped(function(string) {
        var result2 = [];
        if (string.charCodeAt(0) === 46) {
          result2.push("");
        }
        string.replace(rePropName, function(match2, number, quote, subString) {
          result2.push(quote ? subString.replace(reEscapeChar, "$1") : number || match2);
        });
        return result2;
      });
      function toKey(value) {
        if (typeof value == "string" || isSymbol(value)) {
          return value;
        }
        var result2 = value + "";
        return result2 == "0" && 1 / value == -INFINITY2 ? "-0" : result2;
      }
      __name(toKey, "toKey");
      function toSource2(func) {
        if (func != null) {
          try {
            return funcToString2.call(func);
          } catch (e2) {
          }
          try {
            return func + "";
          } catch (e2) {
          }
        }
        return "";
      }
      __name(toSource2, "toSource");
      function updateWrapDetails(details, bitmask) {
        arrayEach2(wrapFlags, function(pair) {
          var value = "_." + pair[0];
          if (bitmask & pair[1] && !arrayIncludes(details, value)) {
            details.push(value);
          }
        });
        return details.sort();
      }
      __name(updateWrapDetails, "updateWrapDetails");
      function wrapperClone(wrapper) {
        if (wrapper instanceof LazyWrapper) {
          return wrapper.clone();
        }
        var result2 = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__);
        result2.__actions__ = copyArray2(wrapper.__actions__);
        result2.__index__ = wrapper.__index__;
        result2.__values__ = wrapper.__values__;
        return result2;
      }
      __name(wrapperClone, "wrapperClone");
      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;
      }
      __name(chunk, "chunk");
      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;
      }
      __name(compact, "compact");
      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 arrayPush2(isArray2(array) ? copyArray2(array) : [array], baseFlatten(args, 1));
      }
      __name(concat, "concat");
      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);
      }
      __name(drop, "drop");
      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);
      }
      __name(dropRight, "dropRight");
      function dropRightWhile(array, predicate) {
        return array && array.length ? baseWhile(array, getIteratee(predicate, 3), true, true) : [];
      }
      __name(dropRightWhile, "dropRightWhile");
      function dropWhile(array, predicate) {
        return array && array.length ? baseWhile(array, getIteratee(predicate, 3), true) : [];
      }
      __name(dropWhile, "dropWhile");
      function fill2(array, value, start2, end) {
        var length = array == null ? 0 : array.length;
        if (!length) {
          return [];
        }
        if (start2 && typeof start2 != "number" && isIterateeCall(array, value, start2)) {
          start2 = 0;
          end = length;
        }
        return baseFill(array, value, start2, end);
      }
      __name(fill2, "fill");
      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);
      }
      __name(findIndex, "findIndex");
      function findLastIndex2(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);
      }
      __name(findLastIndex2, "findLastIndex");
      function flatten2(array) {
        var length = array == null ? 0 : array.length;
        return length ? baseFlatten(array, 1) : [];
      }
      __name(flatten2, "flatten");
      function flattenDeep(array) {
        var length = array == null ? 0 : array.length;
        return length ? baseFlatten(array, INFINITY2) : [];
      }
      __name(flattenDeep, "flattenDeep");
      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);
      }
      __name(flattenDepth, "flattenDepth");
      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;
      }
      __name(fromPairs, "fromPairs");
      function head(array) {
        return array && array.length ? array[0] : undefined$1;
      }
      __name(head, "head");
      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);
      }
      __name(indexOf, "indexOf");
      function initial(array) {
        var length = array == null ? 0 : array.length;
        return length ? baseSlice(array, 0, -1) : [];
      }
      __name(initial, "initial");
      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 join2(array, separator) {
        return array == null ? "" : nativeJoin.call(array, separator);
      }
      __name(join2, "join");
      function last(array) {
        var length = array == null ? 0 : array.length;
        return length ? array[length - 1] : undefined$1;
      }
      __name(last, "last");
      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);
      }
      __name(lastIndexOf, "lastIndexOf");
      function nth(array, n2) {
        return array && array.length ? baseNth(array, toInteger(n2)) : undefined$1;
      }
      __name(nth, "nth");
      var pull = baseRest(pullAll);
      function pullAll(array, values2) {
        return array && array.length && values2 && values2.length ? basePullAll(array, values2) : array;
      }
      __name(pullAll, "pullAll");
      function pullAllBy(array, values2, iteratee2) {
        return array && array.length && values2 && values2.length ? basePullAll(array, values2, getIteratee(iteratee2, 2)) : array;
      }
      __name(pullAllBy, "pullAllBy");
      function pullAllWith(array, values2, comparator) {
        return array && array.length && values2 && values2.length ? basePullAll(array, values2, undefined$1, comparator) : array;
      }
      __name(pullAllWith, "pullAllWith");
      var pullAt = flatRest(function(array, indexes) {
        var length = array == null ? 0 : array.length, result2 = baseAt(array, indexes);
        basePullAt(array, arrayMap(indexes, function(index2) {
          return isIndex2(index2, length) ? +index2 : index2;
        }).sort(compareAscending));
        return result2;
      });
      function remove2(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;
      }
      __name(remove2, "remove");
      function reverse2(array) {
        return array == null ? array : nativeReverse.call(array);
      }
      __name(reverse2, "reverse");
      function slice2(array, start2, end) {
        var length = array == null ? 0 : array.length;
        if (!length) {
          return [];
        }
        if (end && typeof end != "number" && isIterateeCall(array, start2, end)) {
          start2 = 0;
          end = length;
        } else {
          start2 = start2 == null ? 0 : toInteger(start2);
          end = end === undefined$1 ? length : toInteger(end);
        }
        return baseSlice(array, start2, end);
      }
      __name(slice2, "slice");
      function sortedIndex(array, value) {
        return baseSortedIndex(array, value);
      }
      __name(sortedIndex, "sortedIndex");
      function sortedIndexBy(array, value, iteratee2) {
        return baseSortedIndexBy(array, value, getIteratee(iteratee2, 2));
      }
      __name(sortedIndexBy, "sortedIndexBy");
      function sortedIndexOf(array, value) {
        var length = array == null ? 0 : array.length;
        if (length) {
          var index2 = baseSortedIndex(array, value);
          if (index2 < length && eq2(array[index2], value)) {
            return index2;
          }
        }
        return -1;
      }
      __name(sortedIndexOf, "sortedIndexOf");
      function sortedLastIndex(array, value) {
        return baseSortedIndex(array, value, true);
      }
      __name(sortedLastIndex, "sortedLastIndex");
      function sortedLastIndexBy(array, value, iteratee2) {
        return baseSortedIndexBy(array, value, getIteratee(iteratee2, 2), true);
      }
      __name(sortedLastIndexBy, "sortedLastIndexBy");
      function sortedLastIndexOf(array, value) {
        var length = array == null ? 0 : array.length;
        if (length) {
          var index2 = baseSortedIndex(array, value, true) - 1;
          if (eq2(array[index2], value)) {
            return index2;
          }
        }
        return -1;
      }
      __name(sortedLastIndexOf, "sortedLastIndexOf");
      function sortedUniq(array) {
        return array && array.length ? baseSortedUniq(array) : [];
      }
      __name(sortedUniq, "sortedUniq");
      function sortedUniqBy(array, iteratee2) {
        return array && array.length ? baseSortedUniq(array, getIteratee(iteratee2, 2)) : [];
      }
      __name(sortedUniqBy, "sortedUniqBy");
      function tail(array) {
        var length = array == null ? 0 : array.length;
        return length ? baseSlice(array, 1, length) : [];
      }
      __name(tail, "tail");
      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);
      }
      __name(take, "take");
      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);
      }
      __name(takeRight, "takeRight");
      function takeRightWhile(array, predicate) {
        return array && array.length ? baseWhile(array, getIteratee(predicate, 3), false, true) : [];
      }
      __name(takeRightWhile, "takeRightWhile");
      function takeWhile(array, predicate) {
        return array && array.length ? baseWhile(array, getIteratee(predicate, 3)) : [];
      }
      __name(takeWhile, "takeWhile");
      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 uniq2(array) {
        return array && array.length ? baseUniq(array) : [];
      }
      __name(uniq2, "uniq");
      function uniqBy(array, iteratee2) {
        return array && array.length ? baseUniq(array, getIteratee(iteratee2, 2)) : [];
      }
      __name(uniqBy, "uniqBy");
      function uniqWith(array, comparator) {
        comparator = typeof comparator == "function" ? comparator : undefined$1;
        return array && array.length ? baseUniq(array, undefined$1, comparator) : [];
      }
      __name(uniqWith, "uniqWith");
      function unzip(array) {
        if (!(array && array.length)) {
          return [];
        }
        var length = 0;
        array = arrayFilter2(array, function(group) {
          if (isArrayLikeObject(group)) {
            length = nativeMax(group.length, length);
            return true;
          }
        });
        return baseTimes2(length, function(index2) {
          return arrayMap(array, baseProperty(index2));
        });
      }
      __name(unzip, "unzip");
      function unzipWith(array, iteratee2) {
        if (!(array && array.length)) {
          return [];
        }
        var result2 = unzip(array);
        if (iteratee2 == null) {
          return result2;
        }
        return arrayMap(result2, function(group) {
          return apply2(iteratee2, undefined$1, group);
        });
      }
      __name(unzipWith, "unzipWith");
      var without = baseRest(function(array, values2) {
        return isArrayLikeObject(array) ? baseDifference(array, values2) : [];
      });
      var xor = baseRest(function(arrays) {
        return baseXor(arrayFilter2(arrays, isArrayLikeObject));
      });
      var xorBy = baseRest(function(arrays) {
        var iteratee2 = last(arrays);
        if (isArrayLikeObject(iteratee2)) {
          iteratee2 = undefined$1;
        }
        return baseXor(arrayFilter2(arrays, isArrayLikeObject), getIteratee(iteratee2, 2));
      });
      var xorWith = baseRest(function(arrays) {
        var comparator = last(arrays);
        comparator = typeof comparator == "function" ? comparator : undefined$1;
        return baseXor(arrayFilter2(arrays, isArrayLikeObject), undefined$1, comparator);
      });
      var zip = baseRest(unzip);
      function zipObject(props, values2) {
        return baseZipObject(props || [], values2 || [], assignValue2);
      }
      __name(zipObject, "zipObject");
      function zipObjectDeep(props, values2) {
        return baseZipObject(props || [], values2 || [], baseSet);
      }
      __name(zipObjectDeep, "zipObjectDeep");
      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;
      }
      __name(chain, "chain");
      function tap(value, interceptor) {
        interceptor(value);
        return value;
      }
      __name(tap, "tap");
      function thru(value, interceptor) {
        return interceptor(value);
      }
      __name(thru, "thru");
      var wrapperAt = flatRest(function(paths) {
        var length = paths.length, start2 = length ? paths[0] : 0, value = this.__wrapped__, interceptor = /* @__PURE__ */ __name(function(object) {
          return baseAt(object, paths);
        }, "interceptor");
        if (length > 1 || this.__actions__.length || !(value instanceof LazyWrapper) || !isIndex2(start2)) {
          return this.thru(interceptor);
        }
        value = value.slice(start2, +start2 + (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);
      }
      __name(wrapperChain, "wrapperChain");
      function wrapperCommit() {
        return new LodashWrapper(this.value(), this.__chain__);
      }
      __name(wrapperCommit, "wrapperCommit");
      function wrapperNext() {
        if (this.__values__ === undefined$1) {
          this.__values__ = toArray2(this.value());
        }
        var done = this.__index__ >= this.__values__.length, value = done ? undefined$1 : this.__values__[this.__index__++];
        return { "done": done, "value": value };
      }
      __name(wrapperNext, "wrapperNext");
      function wrapperToIterator() {
        return this;
      }
      __name(wrapperToIterator, "wrapperToIterator");
      function wrapperPlant(value) {
        var result2, parent3 = this;
        while (parent3 instanceof baseLodash) {
          var clone3 = wrapperClone(parent3);
          clone3.__index__ = 0;
          clone3.__values__ = undefined$1;
          if (result2) {
            previous.__wrapped__ = clone3;
          } else {
            result2 = clone3;
          }
          var previous = clone3;
          parent3 = parent3.__wrapped__;
        }
        previous.__wrapped__ = value;
        return result2;
      }
      __name(wrapperPlant, "wrapperPlant");
      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": [reverse2],
            "thisArg": undefined$1
          });
          return new LodashWrapper(wrapped, this.__chain__);
        }
        return this.thru(reverse2);
      }
      __name(wrapperReverse, "wrapperReverse");
      function wrapperValue() {
        return baseWrapperValue(this.__wrapped__, this.__actions__);
      }
      __name(wrapperValue, "wrapperValue");
      var countBy = createAggregator(function(result2, value, key) {
        if (hasOwnProperty2.call(result2, key)) {
          ++result2[key];
        } else {
          baseAssignValue2(result2, key, 1);
        }
      });
      function every(collection2, predicate, guard) {
        var func = isArray2(collection2) ? arrayEvery : baseEvery;
        if (guard && isIterateeCall(collection2, predicate, guard)) {
          predicate = undefined$1;
        }
        return func(collection2, getIteratee(predicate, 3));
      }
      __name(every, "every");
      function filter3(collection2, predicate) {
        var func = isArray2(collection2) ? arrayFilter2 : baseFilter;
        return func(collection2, getIteratee(predicate, 3));
      }
      __name(filter3, "filter");
      var find2 = createFind(findIndex);
      var findLast2 = createFind(findLastIndex2);
      function flatMap(collection2, iteratee2) {
        return baseFlatten(map3(collection2, iteratee2), 1);
      }
      __name(flatMap, "flatMap");
      function flatMapDeep(collection2, iteratee2) {
        return baseFlatten(map3(collection2, iteratee2), INFINITY2);
      }
      __name(flatMapDeep, "flatMapDeep");
      function flatMapDepth(collection2, iteratee2, depth) {
        depth = depth === undefined$1 ? 1 : toInteger(depth);
        return baseFlatten(map3(collection2, iteratee2), depth);
      }
      __name(flatMapDepth, "flatMapDepth");
      function forEach3(collection2, iteratee2) {
        var func = isArray2(collection2) ? arrayEach2 : baseEach;
        return func(collection2, getIteratee(iteratee2, 3));
      }
      __name(forEach3, "forEach");
      function forEachRight(collection2, iteratee2) {
        var func = isArray2(collection2) ? arrayEachRight : baseEachRight;
        return func(collection2, getIteratee(iteratee2, 3));
      }
      __name(forEachRight, "forEachRight");
      var groupBy = createAggregator(function(result2, value, key) {
        if (hasOwnProperty2.call(result2, key)) {
          result2[key].push(value);
        } else {
          baseAssignValue2(result2, key, [value]);
        }
      });
      function includes(collection2, value, fromIndex, guard) {
        collection2 = isArrayLike2(collection2) ? collection2 : values(collection2);
        fromIndex = fromIndex && !guard ? toInteger(fromIndex) : 0;
        var length = collection2.length;
        if (fromIndex < 0) {
          fromIndex = nativeMax(length + fromIndex, 0);
        }
        return isString2(collection2) ? fromIndex <= length && collection2.indexOf(value, fromIndex) > -1 : !!length && baseIndexOf(collection2, value, fromIndex) > -1;
      }
      __name(includes, "includes");
      var invokeMap = baseRest(function(collection2, path, args) {
        var index2 = -1, isFunc = typeof path == "function", result2 = isArrayLike2(collection2) ? Array2(collection2.length) : [];
        baseEach(collection2, function(value) {
          result2[++index2] = isFunc ? apply2(path, value, args) : baseInvoke(value, path, args);
        });
        return result2;
      });
      var keyBy = createAggregator(function(result2, value, key) {
        baseAssignValue2(result2, key, value);
      });
      function map3(collection2, iteratee2) {
        var func = isArray2(collection2) ? arrayMap : baseMap;
        return func(collection2, getIteratee(iteratee2, 3));
      }
      __name(map3, "map");
      function orderBy2(collection2, iteratees, orders, guard) {
        if (collection2 == null) {
          return [];
        }
        if (!isArray2(iteratees)) {
          iteratees = iteratees == null ? [] : [iteratees];
        }
        orders = guard ? undefined$1 : orders;
        if (!isArray2(orders)) {
          orders = orders == null ? [] : [orders];
        }
        return baseOrderBy(collection2, iteratees, orders);
      }
      __name(orderBy2, "orderBy");
      var partition = createAggregator(function(result2, value, key) {
        result2[key ? 0 : 1].push(value);
      }, function() {
        return [[], []];
      });
      function reduce(collection2, iteratee2, accumulator) {
        var func = isArray2(collection2) ? arrayReduce : baseReduce, initAccum = arguments.length < 3;
        return func(collection2, getIteratee(iteratee2, 4), accumulator, initAccum, baseEach);
      }
      __name(reduce, "reduce");
      function reduceRight(collection2, iteratee2, accumulator) {
        var func = isArray2(collection2) ? arrayReduceRight : baseReduce, initAccum = arguments.length < 3;
        return func(collection2, getIteratee(iteratee2, 4), accumulator, initAccum, baseEachRight);
      }
      __name(reduceRight, "reduceRight");
      function reject(collection2, predicate) {
        var func = isArray2(collection2) ? arrayFilter2 : baseFilter;
        return func(collection2, negate(getIteratee(predicate, 3)));
      }
      __name(reject, "reject");
      function sample(collection2) {
        var func = isArray2(collection2) ? arraySample : baseSample;
        return func(collection2);
      }
      __name(sample, "sample");
      function sampleSize(collection2, n2, guard) {
        if (guard ? isIterateeCall(collection2, n2, guard) : n2 === undefined$1) {
          n2 = 1;
        } else {
          n2 = toInteger(n2);
        }
        var func = isArray2(collection2) ? arraySampleSize : baseSampleSize;
        return func(collection2, n2);
      }
      __name(sampleSize, "sampleSize");
      function shuffle2(collection2) {
        var func = isArray2(collection2) ? arrayShuffle : baseShuffle;
        return func(collection2);
      }
      __name(shuffle2, "shuffle");
      function size(collection2) {
        if (collection2 == null) {
          return 0;
        }
        if (isArrayLike2(collection2)) {
          return isString2(collection2) ? stringSize(collection2) : collection2.length;
        }
        var tag = getTag2(collection2);
        if (tag == mapTag2 || tag == setTag2) {
          return collection2.size;
        }
        return baseKeys2(collection2).length;
      }
      __name(size, "size");
      function some(collection2, predicate, guard) {
        var func = isArray2(collection2) ? arraySome : baseSome;
        if (guard && isIterateeCall(collection2, predicate, guard)) {
          predicate = undefined$1;
        }
        return func(collection2, getIteratee(predicate, 3));
      }
      __name(some, "some");
      var sortBy = baseRest(function(collection2, iteratees) {
        if (collection2 == null) {
          return [];
        }
        var length = iteratees.length;
        if (length > 1 && isIterateeCall(collection2, iteratees[0], iteratees[1])) {
          iteratees = [];
        } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) {
          iteratees = [iteratees[0]];
        }
        return baseOrderBy(collection2, baseFlatten(iteratees, 1), []);
      });
      var now2 = ctxNow || function() {
        return root2.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);
          }
        };
      }
      __name(after, "after");
      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);
      }
      __name(ary, "ary");
      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;
        };
      }
      __name(before, "before");
      var bind2 = baseRest(function(func, thisArg, partials) {
        var bitmask = WRAP_BIND_FLAG;
        if (partials.length) {
          var holders = replaceHolders(partials, getHolder(bind2));
          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;
      }
      __name(curry, "curry");
      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;
      }
      __name(curryRight, "curryRight");
      function debounce2(func, wait, options2) {
        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 = toNumber2(wait) || 0;
        if (isObject2(options2)) {
          leading = !!options2.leading;
          maxing = "maxWait" in options2;
          maxWait = maxing ? nativeMax(toNumber2(options2.maxWait) || 0, wait) : maxWait;
          trailing = "trailing" in options2 ? !!options2.trailing : trailing;
        }
        function invokeFunc(time) {
          var args = lastArgs, thisArg = lastThis;
          lastArgs = lastThis = undefined$1;
          lastInvokeTime = time;
          result2 = func.apply(thisArg, args);
          return result2;
        }
        __name(invokeFunc, "invokeFunc");
        function leadingEdge(time) {
          lastInvokeTime = time;
          timerId = setTimeout2(timerExpired, wait);
          return leading ? invokeFunc(time) : result2;
        }
        __name(leadingEdge, "leadingEdge");
        function remainingWait(time) {
          var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, timeWaiting = wait - timeSinceLastCall;
          return maxing ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting;
        }
        __name(remainingWait, "remainingWait");
        function shouldInvoke(time) {
          var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime;
          return lastCallTime === undefined$1 || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
        }
        __name(shouldInvoke, "shouldInvoke");
        function timerExpired() {
          var time = now2();
          if (shouldInvoke(time)) {
            return trailingEdge(time);
          }
          timerId = setTimeout2(timerExpired, remainingWait(time));
        }
        __name(timerExpired, "timerExpired");
        function trailingEdge(time) {
          timerId = undefined$1;
          if (trailing && lastArgs) {
            return invokeFunc(time);
          }
          lastArgs = lastThis = undefined$1;
          return result2;
        }
        __name(trailingEdge, "trailingEdge");
        function cancel() {
          if (timerId !== undefined$1) {
            clearTimeout2(timerId);
          }
          lastInvokeTime = 0;
          lastArgs = lastCallTime = lastThis = timerId = undefined$1;
        }
        __name(cancel, "cancel");
        function flush2() {
          return timerId === undefined$1 ? result2 : trailingEdge(now2());
        }
        __name(flush2, "flush");
        function debounced() {
          var time = now2(), 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;
        }
        __name(debounced, "debounced");
        debounced.cancel = cancel;
        debounced.flush = flush2;
        return debounced;
      }
      __name(debounce2, "debounce");
      var defer = baseRest(function(func, args) {
        return baseDelay(func, 1, args);
      });
      var delay = baseRest(function(func, wait, args) {
        return baseDelay(func, toNumber2(wait) || 0, args);
      });
      function flip(func) {
        return createWrap(func, WRAP_FLIP_FLAG);
      }
      __name(flip, "flip");
      function memoize(func, resolver) {
        if (typeof func != "function" || resolver != null && typeof resolver != "function") {
          throw new TypeError2(FUNC_ERROR_TEXT);
        }
        var memoized = /* @__PURE__ */ __name(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");
        memoized.cache = new (memoize.Cache || MapCache2)();
        return memoized;
      }
      __name(memoize, "memoize");
      memoize.Cache = MapCache2;
      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);
        };
      }
      __name(negate, "negate");
      function once2(func) {
        return before(2, func);
      }
      __name(once2, "once");
      var overArgs = castRest(function(func, transforms) {
        transforms = transforms.length == 1 && isArray2(transforms[0]) ? arrayMap(transforms[0], baseUnary2(getIteratee())) : arrayMap(baseFlatten(transforms, 1), baseUnary2(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 apply2(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, start2) {
        if (typeof func != "function") {
          throw new TypeError2(FUNC_ERROR_TEXT);
        }
        start2 = start2 === undefined$1 ? start2 : toInteger(start2);
        return baseRest(func, start2);
      }
      __name(rest, "rest");
      function spread2(func, start2) {
        if (typeof func != "function") {
          throw new TypeError2(FUNC_ERROR_TEXT);
        }
        start2 = start2 == null ? 0 : nativeMax(toInteger(start2), 0);
        return baseRest(function(args) {
          var array = args[start2], otherArgs = castSlice(args, 0, start2);
          if (array) {
            arrayPush2(otherArgs, array);
          }
          return apply2(func, this, otherArgs);
        });
      }
      __name(spread2, "spread");
      function throttle2(func, wait, options2) {
        var leading = true, trailing = true;
        if (typeof func != "function") {
          throw new TypeError2(FUNC_ERROR_TEXT);
        }
        if (isObject2(options2)) {
          leading = "leading" in options2 ? !!options2.leading : leading;
          trailing = "trailing" in options2 ? !!options2.trailing : trailing;
        }
        return debounce2(func, wait, {
          "leading": leading,
          "maxWait": wait,
          "trailing": trailing
        });
      }
      __name(throttle2, "throttle");
      function unary(func) {
        return ary(func, 1);
      }
      __name(unary, "unary");
      function wrap2(value, wrapper) {
        return partial(castFunction(wrapper), value);
      }
      __name(wrap2, "wrap");
      function castArray() {
        if (!arguments.length) {
          return [];
        }
        var value = arguments[0];
        return isArray2(value) ? value : [value];
      }
      __name(castArray, "castArray");
      function clone2(value) {
        return baseClone2(value, CLONE_SYMBOLS_FLAG2);
      }
      __name(clone2, "clone");
      function cloneWith(value, customizer) {
        customizer = typeof customizer == "function" ? customizer : undefined$1;
        return baseClone2(value, CLONE_SYMBOLS_FLAG2, customizer);
      }
      __name(cloneWith, "cloneWith");
      function cloneDeep2(value) {
        return baseClone2(value, CLONE_DEEP_FLAG2 | CLONE_SYMBOLS_FLAG2);
      }
      __name(cloneDeep2, "cloneDeep");
      function cloneDeepWith(value, customizer) {
        customizer = typeof customizer == "function" ? customizer : undefined$1;
        return baseClone2(value, CLONE_DEEP_FLAG2 | CLONE_SYMBOLS_FLAG2, customizer);
      }
      __name(cloneDeepWith, "cloneDeepWith");
      function conformsTo(object, source) {
        return source == null || baseConformsTo(object, source, keys2(source));
      }
      __name(conformsTo, "conformsTo");
      function eq2(value, other) {
        return value === other || value !== value && other !== other;
      }
      __name(eq2, "eq");
      var gt2 = createRelationalOperation(baseGt);
      var gte = createRelationalOperation(function(value, other) {
        return value >= other;
      });
      var isArguments2 = baseIsArguments2(/* @__PURE__ */ function() {
        return arguments;
      }()) ? baseIsArguments2 : function(value) {
        return isObjectLike2(value) && hasOwnProperty2.call(value, "callee") && !propertyIsEnumerable2.call(value, "callee");
      };
      var isArray2 = Array2.isArray;
      var isArrayBuffer2 = nodeIsArrayBuffer ? baseUnary2(nodeIsArrayBuffer) : baseIsArrayBuffer;
      function isArrayLike2(value) {
        return value != null && isLength2(value.length) && !isFunction2(value);
      }
      __name(isArrayLike2, "isArrayLike");
      function isArrayLikeObject(value) {
        return isObjectLike2(value) && isArrayLike2(value);
      }
      __name(isArrayLikeObject, "isArrayLikeObject");
      function isBoolean2(value) {
        return value === true || value === false || isObjectLike2(value) && baseGetTag2(value) == boolTag2;
      }
      __name(isBoolean2, "isBoolean");
      var isBuffer2 = nativeIsBuffer || stubFalse2;
      var isDate2 = nodeIsDate ? baseUnary2(nodeIsDate) : baseIsDate;
      function isElement2(value) {
        return isObjectLike2(value) && value.nodeType === 1 && !isPlainObject2(value);
      }
      __name(isElement2, "isElement");
      function isEmpty3(value) {
        if (value == null) {
          return true;
        }
        if (isArrayLike2(value) && (isArray2(value) || typeof value == "string" || typeof value.splice == "function" || isBuffer2(value) || isTypedArray2(value) || isArguments2(value))) {
          return !value.length;
        }
        var tag = getTag2(value);
        if (tag == mapTag2 || tag == setTag2) {
          return !value.size;
        }
        if (isPrototype2(value)) {
          return !baseKeys2(value).length;
        }
        for (var key in value) {
          if (hasOwnProperty2.call(value, key)) {
            return false;
          }
        }
        return true;
      }
      __name(isEmpty3, "isEmpty");
      function isEqual(value, other) {
        return baseIsEqual(value, other);
      }
      __name(isEqual, "isEqual");
      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;
      }
      __name(isEqualWith, "isEqualWith");
      function isError2(value) {
        if (!isObjectLike2(value)) {
          return false;
        }
        var tag = baseGetTag2(value);
        return tag == errorTag2 || tag == domExcTag || typeof value.message == "string" && typeof value.name == "string" && !isPlainObject2(value);
      }
      __name(isError2, "isError");
      function isFinite2(value) {
        return typeof value == "number" && nativeIsFinite(value);
      }
      __name(isFinite2, "isFinite");
      function isFunction2(value) {
        if (!isObject2(value)) {
          return false;
        }
        var tag = baseGetTag2(value);
        return tag == funcTag2 || tag == genTag2 || tag == asyncTag2 || tag == proxyTag2;
      }
      __name(isFunction2, "isFunction");
      function isInteger2(value) {
        return typeof value == "number" && value == toInteger(value);
      }
      __name(isInteger2, "isInteger");
      function isLength2(value) {
        return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER2;
      }
      __name(isLength2, "isLength");
      function isObject2(value) {
        var type = typeof value;
        return value != null && (type == "object" || type == "function");
      }
      __name(isObject2, "isObject");
      function isObjectLike2(value) {
        return value != null && typeof value == "object";
      }
      __name(isObjectLike2, "isObjectLike");
      var isMap2 = nodeIsMap2 ? baseUnary2(nodeIsMap2) : baseIsMap2;
      function isMatch(object, source) {
        return object === source || baseIsMatch(object, source, getMatchData(source));
      }
      __name(isMatch, "isMatch");
      function isMatchWith(object, source, customizer) {
        customizer = typeof customizer == "function" ? customizer : undefined$1;
        return baseIsMatch(object, source, getMatchData(source), customizer);
      }
      __name(isMatchWith, "isMatchWith");
      function isNaN2(value) {
        return isNumber2(value) && value != +value;
      }
      __name(isNaN2, "isNaN");
      function isNative(value) {
        if (isMaskable(value)) {
          throw new Error2(CORE_ERROR_TEXT);
        }
        return baseIsNative2(value);
      }
      __name(isNative, "isNative");
      function isNull(value) {
        return value === null;
      }
      __name(isNull, "isNull");
      function isNil(value) {
        return value == null;
      }
      __name(isNil, "isNil");
      function isNumber2(value) {
        return typeof value == "number" || isObjectLike2(value) && baseGetTag2(value) == numberTag2;
      }
      __name(isNumber2, "isNumber");
      function isPlainObject2(value) {
        if (!isObjectLike2(value) || baseGetTag2(value) != objectTag2) {
          return false;
        }
        var proto = getPrototype2(value);
        if (proto === null) {
          return true;
        }
        var Ctor = hasOwnProperty2.call(proto, "constructor") && proto.constructor;
        return typeof Ctor == "function" && Ctor instanceof Ctor && funcToString2.call(Ctor) == objectCtorString;
      }
      __name(isPlainObject2, "isPlainObject");
      var isRegExp2 = nodeIsRegExp ? baseUnary2(nodeIsRegExp) : baseIsRegExp;
      function isSafeInteger2(value) {
        return isInteger2(value) && value >= -MAX_SAFE_INTEGER2 && value <= MAX_SAFE_INTEGER2;
      }
      __name(isSafeInteger2, "isSafeInteger");
      var isSet2 = nodeIsSet2 ? baseUnary2(nodeIsSet2) : baseIsSet2;
      function isString2(value) {
        return typeof value == "string" || !isArray2(value) && isObjectLike2(value) && baseGetTag2(value) == stringTag2;
      }
      __name(isString2, "isString");
      function isSymbol(value) {
        return typeof value == "symbol" || isObjectLike2(value) && baseGetTag2(value) == symbolTag2;
      }
      __name(isSymbol, "isSymbol");
      var isTypedArray2 = nodeIsTypedArray2 ? baseUnary2(nodeIsTypedArray2) : baseIsTypedArray2;
      function isUndefined2(value) {
        return value === undefined$1;
      }
      __name(isUndefined2, "isUndefined");
      function isWeakMap(value) {
        return isObjectLike2(value) && getTag2(value) == weakMapTag2;
      }
      __name(isWeakMap, "isWeakMap");
      function isWeakSet(value) {
        return isObjectLike2(value) && baseGetTag2(value) == weakSetTag;
      }
      __name(isWeakSet, "isWeakSet");
      var lt2 = createRelationalOperation(baseLt);
      var lte = createRelationalOperation(function(value, other) {
        return value <= other;
      });
      function toArray2(value) {
        if (!value) {
          return [];
        }
        if (isArrayLike2(value)) {
          return isString2(value) ? stringToArray2(value) : copyArray2(value);
        }
        if (symIterator && value[symIterator]) {
          return iteratorToArray(value[symIterator]());
        }
        var tag = getTag2(value), func = tag == mapTag2 ? mapToArray : tag == setTag2 ? setToArray : values;
        return func(value);
      }
      __name(toArray2, "toArray");
      function toFinite(value) {
        if (!value) {
          return value === 0 ? value : 0;
        }
        value = toNumber2(value);
        if (value === INFINITY2 || value === -INFINITY2) {
          var sign = value < 0 ? -1 : 1;
          return sign * MAX_INTEGER;
        }
        return value === value ? value : 0;
      }
      __name(toFinite, "toFinite");
      function toInteger(value) {
        var result2 = toFinite(value), remainder = result2 % 1;
        return result2 === result2 ? remainder ? result2 - remainder : result2 : 0;
      }
      __name(toInteger, "toInteger");
      function toLength(value) {
        return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0;
      }
      __name(toLength, "toLength");
      function toNumber2(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;
      }
      __name(toNumber2, "toNumber");
      function toPlainObject(value) {
        return copyObject2(value, keysIn2(value));
      }
      __name(toPlainObject, "toPlainObject");
      function toSafeInteger(value) {
        return value ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER2, MAX_SAFE_INTEGER2) : value === 0 ? value : 0;
      }
      __name(toSafeInteger, "toSafeInteger");
      function toString3(value) {
        return value == null ? "" : baseToString2(value);
      }
      __name(toString3, "toString");
      var assign2 = createAssigner(function(object, source) {
        if (isPrototype2(source) || isArrayLike2(source)) {
          copyObject2(source, keys2(source), object);
          return;
        }
        for (var key in source) {
          if (hasOwnProperty2.call(source, key)) {
            assignValue2(object, key, source[key]);
          }
        }
      });
      var assignIn = createAssigner(function(object, source) {
        copyObject2(source, keysIn2(source), object);
      });
      var assignInWith = createAssigner(function(object, source, srcIndex, customizer) {
        copyObject2(source, keysIn2(source), object, customizer);
      });
      var assignWith = createAssigner(function(object, source, srcIndex, customizer) {
        copyObject2(source, keys2(source), object, customizer);
      });
      var at2 = flatRest(baseAt);
      function create2(prototype2, properties) {
        var result2 = baseCreate2(prototype2);
        return properties == null ? result2 : baseAssign2(result2, properties);
      }
      __name(create2, "create");
      var defaults2 = 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 = keysIn2(source);
          var propsIndex = -1;
          var propsLength = props.length;
          while (++propsIndex < propsLength) {
            var key = props[propsIndex];
            var value = object[key];
            if (value === undefined$1 || eq2(value, objectProto2[key]) && !hasOwnProperty2.call(object, key)) {
              object[key] = source[key];
            }
          }
        }
        return object;
      });
      var defaultsDeep = baseRest(function(args) {
        args.push(undefined$1, customDefaultsMerge);
        return apply2(mergeWith, undefined$1, args);
      });
      function findKey2(object, predicate) {
        return baseFindKey(object, getIteratee(predicate, 3), baseForOwn);
      }
      __name(findKey2, "findKey");
      function findLastKey(object, predicate) {
        return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight);
      }
      __name(findLastKey, "findLastKey");
      function forIn(object, iteratee2) {
        return object == null ? object : baseFor(object, getIteratee(iteratee2, 3), keysIn2);
      }
      __name(forIn, "forIn");
      function forInRight(object, iteratee2) {
        return object == null ? object : baseForRight(object, getIteratee(iteratee2, 3), keysIn2);
      }
      __name(forInRight, "forInRight");
      function forOwn(object, iteratee2) {
        return object && baseForOwn(object, getIteratee(iteratee2, 3));
      }
      __name(forOwn, "forOwn");
      function forOwnRight(object, iteratee2) {
        return object && baseForOwnRight(object, getIteratee(iteratee2, 3));
      }
      __name(forOwnRight, "forOwnRight");
      function functions(object) {
        return object == null ? [] : baseFunctions(object, keys2(object));
      }
      __name(functions, "functions");
      function functionsIn(object) {
        return object == null ? [] : baseFunctions(object, keysIn2(object));
      }
      __name(functionsIn, "functionsIn");
      function get3(object, path, defaultValue) {
        var result2 = object == null ? undefined$1 : baseGet(object, path);
        return result2 === undefined$1 ? defaultValue : result2;
      }
      __name(get3, "get");
      function has2(object, path) {
        return object != null && hasPath(object, path, baseHas);
      }
      __name(has2, "has");
      function hasIn(object, path) {
        return object != null && hasPath(object, path, baseHasIn);
      }
      __name(hasIn, "hasIn");
      var invert = createInverter(function(result2, value, key) {
        if (value != null && typeof value.toString != "function") {
          value = nativeObjectToString2.call(value);
        }
        result2[value] = key;
      }, constant(identity2));
      var invertBy = createInverter(function(result2, value, key) {
        if (value != null && typeof value.toString != "function") {
          value = nativeObjectToString2.call(value);
        }
        if (hasOwnProperty2.call(result2, value)) {
          result2[value].push(key);
        } else {
          result2[value] = [key];
        }
      }, getIteratee);
      var invoke2 = baseRest(baseInvoke);
      function keys2(object) {
        return isArrayLike2(object) ? arrayLikeKeys2(object) : baseKeys2(object);
      }
      __name(keys2, "keys");
      function keysIn2(object) {
        return isArrayLike2(object) ? arrayLikeKeys2(object, true) : baseKeysIn2(object);
      }
      __name(keysIn2, "keysIn");
      function mapKeys(object, iteratee2) {
        var result2 = {};
        iteratee2 = getIteratee(iteratee2, 3);
        baseForOwn(object, function(value, key, object2) {
          baseAssignValue2(result2, iteratee2(value, key, object2), value);
        });
        return result2;
      }
      __name(mapKeys, "mapKeys");
      function mapValues(object, iteratee2) {
        var result2 = {};
        iteratee2 = getIteratee(iteratee2, 3);
        baseForOwn(object, function(value, key, object2) {
          baseAssignValue2(result2, key, iteratee2(value, key, object2));
        });
        return result2;
      }
      __name(mapValues, "mapValues");
      var merge2 = createAssigner(function(object, source, srcIndex) {
        baseMerge(object, source, srcIndex);
      });
      var mergeWith = createAssigner(function(object, source, srcIndex, customizer) {
        baseMerge(object, source, srcIndex, customizer);
      });
      var omit2 = 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;
        });
        copyObject2(object, getAllKeysIn2(object), result2);
        if (isDeep) {
          result2 = baseClone2(result2, CLONE_DEEP_FLAG2 | CLONE_FLAT_FLAG2 | CLONE_SYMBOLS_FLAG2, customOmitClone);
        }
        var length = paths.length;
        while (length--) {
          baseUnset(result2, paths[length]);
        }
        return result2;
      });
      function omitBy(object, predicate) {
        return pickBy(object, negate(getIteratee(predicate)));
      }
      __name(omitBy, "omitBy");
      var pick = flatRest(function(object, paths) {
        return object == null ? {} : basePick(object, paths);
      });
      function pickBy(object, predicate) {
        if (object == null) {
          return {};
        }
        var props = arrayMap(getAllKeysIn2(object), function(prop2) {
          return [prop2];
        });
        predicate = getIteratee(predicate);
        return basePickBy(object, props, function(value, path) {
          return predicate(value, path[0]);
        });
      }
      __name(pickBy, "pickBy");
      function result(object, path, defaultValue) {
        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 = defaultValue;
          }
          object = isFunction2(value) ? value.call(object) : value;
        }
        return object;
      }
      __name(result, "result");
      function set3(object, path, value) {
        return object == null ? object : baseSet(object, path, value);
      }
      __name(set3, "set");
      function setWith(object, path, value, customizer) {
        customizer = typeof customizer == "function" ? customizer : undefined$1;
        return object == null ? object : baseSet(object, path, value, customizer);
      }
      __name(setWith, "setWith");
      var toPairs = createToPairs(keys2);
      var toPairsIn = createToPairs(keysIn2);
      function transform(object, iteratee2, accumulator) {
        var isArr = isArray2(object), isArrLike = isArr || isBuffer2(object) || isTypedArray2(object);
        iteratee2 = getIteratee(iteratee2, 4);
        if (accumulator == null) {
          var Ctor = object && object.constructor;
          if (isArrLike) {
            accumulator = isArr ? new Ctor() : [];
          } else if (isObject2(object)) {
            accumulator = isFunction2(Ctor) ? baseCreate2(getPrototype2(object)) : {};
          } else {
            accumulator = {};
          }
        }
        (isArrLike ? arrayEach2 : baseForOwn)(object, function(value, index2, object2) {
          return iteratee2(accumulator, value, index2, object2);
        });
        return accumulator;
      }
      __name(transform, "transform");
      function unset(object, path) {
        return object == null ? true : baseUnset(object, path);
      }
      __name(unset, "unset");
      function update2(object, path, updater) {
        return object == null ? object : baseUpdate(object, path, castFunction(updater));
      }
      __name(update2, "update");
      function updateWith(object, path, updater, customizer) {
        customizer = typeof customizer == "function" ? customizer : undefined$1;
        return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer);
      }
      __name(updateWith, "updateWith");
      function values(object) {
        return object == null ? [] : baseValues(object, keys2(object));
      }
      __name(values, "values");
      function valuesIn(object) {
        return object == null ? [] : baseValues(object, keysIn2(object));
      }
      __name(valuesIn, "valuesIn");
      function clamp2(number, lower, upper) {
        if (upper === undefined$1) {
          upper = lower;
          lower = undefined$1;
        }
        if (upper !== undefined$1) {
          upper = toNumber2(upper);
          upper = upper === upper ? upper : 0;
        }
        if (lower !== undefined$1) {
          lower = toNumber2(lower);
          lower = lower === lower ? lower : 0;
        }
        return baseClamp(toNumber2(number), lower, upper);
      }
      __name(clamp2, "clamp");
      function inRange(number, start2, end) {
        start2 = toFinite(start2);
        if (end === undefined$1) {
          end = start2;
          start2 = 0;
        } else {
          end = toFinite(end);
        }
        number = toNumber2(number);
        return baseInRange(number, start2, end);
      }
      __name(inRange, "inRange");
      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 rand2 = nativeRandom();
          return nativeMin(lower + rand2 * (upper - lower + freeParseFloat("1e-" + ((rand2 + "").length - 1))), upper);
        }
        return baseRandom(lower, upper);
      }
      __name(random, "random");
      var camelCase = createCompounder(function(result2, word, index2) {
        word = word.toLowerCase();
        return result2 + (index2 ? capitalize(word) : word);
      });
      function capitalize(string) {
        return upperFirst(toString3(string).toLowerCase());
      }
      __name(capitalize, "capitalize");
      function deburr(string) {
        string = toString3(string);
        return string && string.replace(reLatin, deburrLetter).replace(reComboMark, "");
      }
      __name(deburr, "deburr");
      function endsWith2(string, target, position) {
        string = toString3(string);
        target = baseToString2(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;
      }
      __name(endsWith2, "endsWith");
      function escape2(string) {
        string = toString3(string);
        return string && reHasUnescapedHtml.test(string) ? string.replace(reUnescapedHtml, escapeHtmlChar) : string;
      }
      __name(escape2, "escape");
      function escapeRegExp(string) {
        string = toString3(string);
        return string && reHasRegExpChar.test(string) ? string.replace(reRegExpChar2, "\\$&") : string;
      }
      __name(escapeRegExp, "escapeRegExp");
      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 pad2(string, length, chars2) {
        string = toString3(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);
      }
      __name(pad2, "pad");
      function padEnd(string, length, chars2) {
        string = toString3(string);
        length = toInteger(length);
        var strLength = length ? stringSize(string) : 0;
        return length && strLength < length ? string + createPadding(length - strLength, chars2) : string;
      }
      __name(padEnd, "padEnd");
      function padStart(string, length, chars2) {
        string = toString3(string);
        length = toInteger(length);
        var strLength = length ? stringSize(string) : 0;
        return length && strLength < length ? createPadding(length - strLength, chars2) + string : string;
      }
      __name(padStart, "padStart");
      function parseInt2(string, radix, guard) {
        if (guard || radix == null) {
          radix = 0;
        } else if (radix) {
          radix = +radix;
        }
        return nativeParseInt(toString3(string).replace(reTrimStart, ""), radix || 0);
      }
      __name(parseInt2, "parseInt");
      function repeat2(string, n2, guard) {
        if (guard ? isIterateeCall(string, n2, guard) : n2 === undefined$1) {
          n2 = 1;
        } else {
          n2 = toInteger(n2);
        }
        return baseRepeat(toString3(string), n2);
      }
      __name(repeat2, "repeat");
      function replace2() {
        var args = arguments, string = toString3(args[0]);
        return args.length < 3 ? string : string.replace(args[1], args[2]);
      }
      __name(replace2, "replace");
      var snakeCase = createCompounder(function(result2, word, index2) {
        return result2 + (index2 ? "_" : "") + word.toLowerCase();
      });
      function split2(string, separator, limit2) {
        if (limit2 && typeof limit2 != "number" && isIterateeCall(string, separator, limit2)) {
          separator = limit2 = undefined$1;
        }
        limit2 = limit2 === undefined$1 ? MAX_ARRAY_LENGTH : limit2 >>> 0;
        if (!limit2) {
          return [];
        }
        string = toString3(string);
        if (string && (typeof separator == "string" || separator != null && !isRegExp2(separator))) {
          separator = baseToString2(separator);
          if (!separator && hasUnicode(string)) {
            return castSlice(stringToArray2(string), 0, limit2);
          }
        }
        return string.split(separator, limit2);
      }
      __name(split2, "split");
      var startCase = createCompounder(function(result2, word, index2) {
        return result2 + (index2 ? " " : "") + upperFirst(word);
      });
      function startsWith(string, target, position) {
        string = toString3(string);
        position = position == null ? 0 : baseClamp(toInteger(position), 0, string.length);
        target = baseToString2(target);
        return string.slice(position, position + target.length) == target;
      }
      __name(startsWith, "startsWith");
      function template(string, options2, guard) {
        var settings = lodash2.templateSettings;
        if (guard && isIterateeCall(string, options2, guard)) {
          options2 = undefined$1;
        }
        string = toString3(string);
        options2 = assignInWith({}, options2, settings, customDefaultsAssignIn);
        var imports = assignInWith({}, options2.imports, settings.imports, customDefaultsAssignIn), importsKeys = keys2(imports), importsValues = baseValues(imports, importsKeys);
        var isEscaping, isEvaluating, index2 = 0, interpolate = options2.interpolate || reNoMatch, source = "__p += '";
        var reDelimiters = RegExp2(
          (options2.escape || reNoMatch).source + "|" + interpolate.source + "|" + (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + "|" + (options2.evaluate || reNoMatch).source + "|$",
          "g"
        );
        var sourceURL = "//# sourceURL=" + (hasOwnProperty2.call(options2, "sourceURL") ? (options2.sourceURL + "").replace(/\s/g, " ") : "lodash.templateSources[" + ++templateCounter + "]") + "\n";
        string.replace(reDelimiters, function(match2, 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 + match2.length;
          return match2;
        });
        source += "';\n";
        var variable = hasOwnProperty2.call(options2, "variable") && options2.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 (isError2(result2)) {
          throw result2;
        }
        return result2;
      }
      __name(template, "template");
      function toLower(value) {
        return toString3(value).toLowerCase();
      }
      __name(toLower, "toLower");
      function toUpper(value) {
        return toString3(value).toUpperCase();
      }
      __name(toUpper, "toUpper");
      function trim2(string, chars2, guard) {
        string = toString3(string);
        if (string && (guard || chars2 === undefined$1)) {
          return baseTrim(string);
        }
        if (!string || !(chars2 = baseToString2(chars2))) {
          return string;
        }
        var strSymbols = stringToArray2(string), chrSymbols = stringToArray2(chars2), start2 = charsStartIndex(strSymbols, chrSymbols), end = charsEndIndex(strSymbols, chrSymbols) + 1;
        return castSlice(strSymbols, start2, end).join("");
      }
      __name(trim2, "trim");
      function trimEnd2(string, chars2, guard) {
        string = toString3(string);
        if (string && (guard || chars2 === undefined$1)) {
          return string.slice(0, trimmedEndIndex(string) + 1);
        }
        if (!string || !(chars2 = baseToString2(chars2))) {
          return string;
        }
        var strSymbols = stringToArray2(string), end = charsEndIndex(strSymbols, stringToArray2(chars2)) + 1;
        return castSlice(strSymbols, 0, end).join("");
      }
      __name(trimEnd2, "trimEnd");
      function trimStart2(string, chars2, guard) {
        string = toString3(string);
        if (string && (guard || chars2 === undefined$1)) {
          return string.replace(reTrimStart, "");
        }
        if (!string || !(chars2 = baseToString2(chars2))) {
          return string;
        }
        var strSymbols = stringToArray2(string), start2 = charsStartIndex(strSymbols, stringToArray2(chars2));
        return castSlice(strSymbols, start2).join("");
      }
      __name(trimStart2, "trimStart");
      function truncate2(string, options2) {
        var length = DEFAULT_TRUNC_LENGTH, omission = DEFAULT_TRUNC_OMISSION;
        if (isObject2(options2)) {
          var separator = "separator" in options2 ? options2.separator : separator;
          length = "length" in options2 ? toInteger(options2.length) : length;
          omission = "omission" in options2 ? baseToString2(options2.omission) : omission;
        }
        string = toString3(string);
        var strLength = string.length;
        if (hasUnicode(string)) {
          var strSymbols = stringToArray2(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 (isRegExp2(separator)) {
          if (string.slice(end).search(separator)) {
            var match2, substring = result2;
            if (!separator.global) {
              separator = RegExp2(separator.source, toString3(reFlags2.exec(separator)) + "g");
            }
            separator.lastIndex = 0;
            while (match2 = separator.exec(substring)) {
              var newEnd = match2.index;
            }
            result2 = result2.slice(0, newEnd === undefined$1 ? end : newEnd);
          }
        } else if (string.indexOf(baseToString2(separator), end) != end) {
          var index2 = result2.lastIndexOf(separator);
          if (index2 > -1) {
            result2 = result2.slice(0, index2);
          }
        }
        return result2 + omission;
      }
      __name(truncate2, "truncate");
      function unescape2(string) {
        string = toString3(string);
        return string && reHasEscapedHtml.test(string) ? string.replace(reEscapedHtml, unescapeHtmlChar) : string;
      }
      __name(unescape2, "unescape");
      var upperCase = createCompounder(function(result2, word, index2) {
        return result2 + (index2 ? " " : "") + word.toUpperCase();
      });
      var upperFirst = createCaseFirst("toUpperCase");
      function words(string, pattern, guard) {
        string = toString3(string);
        pattern = guard ? undefined$1 : pattern;
        if (pattern === undefined$1) {
          return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string);
        }
        return string.match(pattern) || [];
      }
      __name(words, "words");
      var attempt = baseRest(function(func, args) {
        try {
          return apply2(func, undefined$1, args);
        } catch (e2) {
          return isError2(e2) ? e2 : new Error2(e2);
        }
      });
      var bindAll2 = flatRest(function(object, methodNames) {
        arrayEach2(methodNames, function(key) {
          key = toKey(key);
          baseAssignValue2(object, key, bind2(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 (apply2(pair[0], this, args)) {
              return apply2(pair[1], this, args);
            }
          }
        });
      }
      __name(cond, "cond");
      function conforms(source) {
        return baseConforms(baseClone2(source, CLONE_DEEP_FLAG2));
      }
      __name(conforms, "conforms");
      function constant(value) {
        return function() {
          return value;
        };
      }
      __name(constant, "constant");
      function defaultTo(value, defaultValue) {
        return value == null || value !== value ? defaultValue : value;
      }
      __name(defaultTo, "defaultTo");
      var flow = createFlow();
      var flowRight = createFlow(true);
      function identity2(value) {
        return value;
      }
      __name(identity2, "identity");
      function iteratee(func) {
        return baseIteratee(typeof func == "function" ? func : baseClone2(func, CLONE_DEEP_FLAG2));
      }
      __name(iteratee, "iteratee");
      function matches2(source) {
        return baseMatches(baseClone2(source, CLONE_DEEP_FLAG2));
      }
      __name(matches2, "matches");
      function matchesProperty(path, srcValue) {
        return baseMatchesProperty(path, baseClone2(srcValue, CLONE_DEEP_FLAG2));
      }
      __name(matchesProperty, "matchesProperty");
      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, options2) {
        var props = keys2(source), methodNames = baseFunctions(source, props);
        if (options2 == null && !(isObject2(source) && (methodNames.length || !props.length))) {
          options2 = source;
          source = object;
          object = this;
          methodNames = baseFunctions(source, keys2(source));
        }
        var chain2 = !(isObject2(options2) && "chain" in options2) || !!options2.chain, isFunc = isFunction2(object);
        arrayEach2(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__ = copyArray2(this.__actions__);
                actions.push({ "func": func, "args": arguments, "thisArg": object });
                result2.__chain__ = chainAll;
                return result2;
              }
              return func.apply(object, arrayPush2([this.value()], arguments));
            };
          }
        });
        return object;
      }
      __name(mixin, "mixin");
      function noConflict() {
        if (root2._ === this) {
          root2._ = oldDash;
        }
        return this;
      }
      __name(noConflict, "noConflict");
      function noop2() {
      }
      __name(noop2, "noop");
      function nthArg(n2) {
        n2 = toInteger(n2);
        return baseRest(function(args) {
          return baseNth(args, n2);
        });
      }
      __name(nthArg, "nthArg");
      var over = createOver(arrayMap);
      var overEvery = createOver(arrayEvery);
      var overSome = createOver(arraySome);
      function property(path) {
        return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);
      }
      __name(property, "property");
      function propertyOf(object) {
        return function(path) {
          return object == null ? undefined$1 : baseGet(object, path);
        };
      }
      __name(propertyOf, "propertyOf");
      var range = createRange();
      var rangeRight = createRange(true);
      function stubArray2() {
        return [];
      }
      __name(stubArray2, "stubArray");
      function stubFalse2() {
        return false;
      }
      __name(stubFalse2, "stubFalse");
      function stubObject() {
        return {};
      }
      __name(stubObject, "stubObject");
      function stubString() {
        return "";
      }
      __name(stubString, "stubString");
      function stubTrue() {
        return true;
      }
      __name(stubTrue, "stubTrue");
      function times(n2, iteratee2) {
        n2 = toInteger(n2);
        if (n2 < 1 || n2 > MAX_SAFE_INTEGER2) {
          return [];
        }
        var index2 = MAX_ARRAY_LENGTH, length = nativeMin(n2, MAX_ARRAY_LENGTH);
        iteratee2 = getIteratee(iteratee2);
        n2 -= MAX_ARRAY_LENGTH;
        var result2 = baseTimes2(length, iteratee2);
        while (++index2 < n2) {
          iteratee2(index2);
        }
        return result2;
      }
      __name(times, "times");
      function toPath(value) {
        if (isArray2(value)) {
          return arrayMap(value, toKey);
        }
        return isSymbol(value) ? [value] : copyArray2(stringToPath(toString3(value)));
      }
      __name(toPath, "toPath");
      function uniqueId(prefix) {
        var id2 = ++idCounter;
        return toString3(prefix) + id2;
      }
      __name(uniqueId, "uniqueId");
      var add3 = createMathOperation(function(augend, addend) {
        return augend + addend;
      }, 0);
      var ceil = createRound("ceil");
      var divide = createMathOperation(function(dividend, divisor) {
        return dividend / divisor;
      }, 1);
      var floor2 = createRound("floor");
      function max(array) {
        return array && array.length ? baseExtremum(array, identity2, baseGt) : undefined$1;
      }
      __name(max, "max");
      function maxBy(array, iteratee2) {
        return array && array.length ? baseExtremum(array, getIteratee(iteratee2, 2), baseGt) : undefined$1;
      }
      __name(maxBy, "maxBy");
      function mean(array) {
        return baseMean(array, identity2);
      }
      __name(mean, "mean");
      function meanBy(array, iteratee2) {
        return baseMean(array, getIteratee(iteratee2, 2));
      }
      __name(meanBy, "meanBy");
      function min(array) {
        return array && array.length ? baseExtremum(array, identity2, baseLt) : undefined$1;
      }
      __name(min, "min");
      function minBy(array, iteratee2) {
        return array && array.length ? baseExtremum(array, getIteratee(iteratee2, 2), baseLt) : undefined$1;
      }
      __name(minBy, "minBy");
      var multiply = createMathOperation(function(multiplier, multiplicand) {
        return multiplier * multiplicand;
      }, 1);
      var round = createRound("round");
      var subtract = createMathOperation(function(minuend, subtrahend) {
        return minuend - subtrahend;
      }, 0);
      function sum2(array) {
        return array && array.length ? baseSum(array, identity2) : 0;
      }
      __name(sum2, "sum");
      function sumBy(array, iteratee2) {
        return array && array.length ? baseSum(array, getIteratee(iteratee2, 2)) : 0;
      }
      __name(sumBy, "sumBy");
      lodash2.after = after;
      lodash2.ary = ary;
      lodash2.assign = assign2;
      lodash2.assignIn = assignIn;
      lodash2.assignInWith = assignInWith;
      lodash2.assignWith = assignWith;
      lodash2.at = at2;
      lodash2.before = before;
      lodash2.bind = bind2;
      lodash2.bindAll = bindAll2;
      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 = create2;
      lodash2.curry = curry;
      lodash2.curryRight = curryRight;
      lodash2.debounce = debounce2;
      lodash2.defaults = defaults2;
      lodash2.defaultsDeep = defaultsDeep;
      lodash2.defer = defer;
      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 = fill2;
      lodash2.filter = filter3;
      lodash2.flatMap = flatMap;
      lodash2.flatMapDeep = flatMapDeep;
      lodash2.flatMapDepth = flatMapDepth;
      lodash2.flatten = flatten2;
      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 = keys2;
      lodash2.keysIn = keysIn2;
      lodash2.map = map3;
      lodash2.mapKeys = mapKeys;
      lodash2.mapValues = mapValues;
      lodash2.matches = matches2;
      lodash2.matchesProperty = matchesProperty;
      lodash2.memoize = memoize;
      lodash2.merge = merge2;
      lodash2.mergeWith = mergeWith;
      lodash2.method = method;
      lodash2.methodOf = methodOf;
      lodash2.mixin = mixin;
      lodash2.negate = negate;
      lodash2.nthArg = nthArg;
      lodash2.omit = omit2;
      lodash2.omitBy = omitBy;
      lodash2.once = once2;
      lodash2.orderBy = orderBy2;
      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 = remove2;
      lodash2.rest = rest;
      lodash2.reverse = reverse2;
      lodash2.sampleSize = sampleSize;
      lodash2.set = set3;
      lodash2.setWith = setWith;
      lodash2.shuffle = shuffle2;
      lodash2.slice = slice2;
      lodash2.sortBy = sortBy;
      lodash2.sortedUniq = sortedUniq;
      lodash2.sortedUniqBy = sortedUniqBy;
      lodash2.split = split2;
      lodash2.spread = spread2;
      lodash2.tail = tail;
      lodash2.take = take;
      lodash2.takeRight = takeRight;
      lodash2.takeRightWhile = takeRightWhile;
      lodash2.takeWhile = takeWhile;
      lodash2.tap = tap;
      lodash2.throttle = throttle2;
      lodash2.thru = thru;
      lodash2.toArray = toArray2;
      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 = uniq2;
      lodash2.uniqBy = uniqBy;
      lodash2.uniqWith = uniqWith;
      lodash2.unset = unset;
      lodash2.unzip = unzip;
      lodash2.unzipWith = unzipWith;
      lodash2.update = update2;
      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 = add3;
      lodash2.attempt = attempt;
      lodash2.camelCase = camelCase;
      lodash2.capitalize = capitalize;
      lodash2.ceil = ceil;
      lodash2.clamp = clamp2;
      lodash2.clone = clone2;
      lodash2.cloneDeep = cloneDeep2;
      lodash2.cloneDeepWith = cloneDeepWith;
      lodash2.cloneWith = cloneWith;
      lodash2.conformsTo = conformsTo;
      lodash2.deburr = deburr;
      lodash2.defaultTo = defaultTo;
      lodash2.divide = divide;
      lodash2.endsWith = endsWith2;
      lodash2.eq = eq2;
      lodash2.escape = escape2;
      lodash2.escapeRegExp = escapeRegExp;
      lodash2.every = every;
      lodash2.find = find2;
      lodash2.findIndex = findIndex;
      lodash2.findKey = findKey2;
      lodash2.findLast = findLast2;
      lodash2.findLastIndex = findLastIndex2;
      lodash2.findLastKey = findLastKey;
      lodash2.floor = floor2;
      lodash2.forEach = forEach3;
      lodash2.forEachRight = forEachRight;
      lodash2.forIn = forIn;
      lodash2.forInRight = forInRight;
      lodash2.forOwn = forOwn;
      lodash2.forOwnRight = forOwnRight;
      lodash2.get = get3;
      lodash2.gt = gt2;
      lodash2.gte = gte;
      lodash2.has = has2;
      lodash2.hasIn = hasIn;
      lodash2.head = head;
      lodash2.identity = identity2;
      lodash2.includes = includes;
      lodash2.indexOf = indexOf;
      lodash2.inRange = inRange;
      lodash2.invoke = invoke2;
      lodash2.isArguments = isArguments2;
      lodash2.isArray = isArray2;
      lodash2.isArrayBuffer = isArrayBuffer2;
      lodash2.isArrayLike = isArrayLike2;
      lodash2.isArrayLikeObject = isArrayLikeObject;
      lodash2.isBoolean = isBoolean2;
      lodash2.isBuffer = isBuffer2;
      lodash2.isDate = isDate2;
      lodash2.isElement = isElement2;
      lodash2.isEmpty = isEmpty3;
      lodash2.isEqual = isEqual;
      lodash2.isEqualWith = isEqualWith;
      lodash2.isError = isError2;
      lodash2.isFinite = isFinite2;
      lodash2.isFunction = isFunction2;
      lodash2.isInteger = isInteger2;
      lodash2.isLength = isLength2;
      lodash2.isMap = isMap2;
      lodash2.isMatch = isMatch;
      lodash2.isMatchWith = isMatchWith;
      lodash2.isNaN = isNaN2;
      lodash2.isNative = isNative;
      lodash2.isNil = isNil;
      lodash2.isNull = isNull;
      lodash2.isNumber = isNumber2;
      lodash2.isObject = isObject2;
      lodash2.isObjectLike = isObjectLike2;
      lodash2.isPlainObject = isPlainObject2;
      lodash2.isRegExp = isRegExp2;
      lodash2.isSafeInteger = isSafeInteger2;
      lodash2.isSet = isSet2;
      lodash2.isString = isString2;
      lodash2.isSymbol = isSymbol;
      lodash2.isTypedArray = isTypedArray2;
      lodash2.isUndefined = isUndefined2;
      lodash2.isWeakMap = isWeakMap;
      lodash2.isWeakSet = isWeakSet;
      lodash2.join = join2;
      lodash2.kebabCase = kebabCase;
      lodash2.last = last;
      lodash2.lastIndexOf = lastIndexOf;
      lodash2.lowerCase = lowerCase;
      lodash2.lowerFirst = lowerFirst;
      lodash2.lt = lt2;
      lodash2.lte = lte;
      lodash2.max = max;
      lodash2.maxBy = maxBy;
      lodash2.mean = mean;
      lodash2.meanBy = meanBy;
      lodash2.min = min;
      lodash2.minBy = minBy;
      lodash2.stubArray = stubArray2;
      lodash2.stubFalse = stubFalse2;
      lodash2.stubObject = stubObject;
      lodash2.stubString = stubString;
      lodash2.stubTrue = stubTrue;
      lodash2.multiply = multiply;
      lodash2.nth = nth;
      lodash2.noConflict = noConflict;
      lodash2.noop = noop2;
      lodash2.now = now2;
      lodash2.pad = pad2;
      lodash2.padEnd = padEnd;
      lodash2.padStart = padStart;
      lodash2.parseInt = parseInt2;
      lodash2.random = random;
      lodash2.reduce = reduce;
      lodash2.reduceRight = reduceRight;
      lodash2.repeat = repeat2;
      lodash2.replace = replace2;
      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 = subtract;
      lodash2.sum = sum2;
      lodash2.sumBy = sumBy;
      lodash2.template = template;
      lodash2.times = times;
      lodash2.toFinite = toFinite;
      lodash2.toInteger = toInteger;
      lodash2.toLength = toLength;
      lodash2.toLower = toLower;
      lodash2.toNumber = toNumber2;
      lodash2.toSafeInteger = toSafeInteger;
      lodash2.toString = toString3;
      lodash2.toUpper = toUpper;
      lodash2.trim = trim2;
      lodash2.trimEnd = trimEnd2;
      lodash2.trimStart = trimStart2;
      lodash2.truncate = truncate2;
      lodash2.unescape = unescape2;
      lodash2.uniqueId = uniqueId;
      lodash2.upperCase = upperCase;
      lodash2.upperFirst = upperFirst;
      lodash2.each = forEach3;
      lodash2.eachRight = forEachRight;
      lodash2.first = head;
      mixin(lodash2, function() {
        var source = {};
        baseForOwn(lodash2, function(func, methodName) {
          if (!hasOwnProperty2.call(lodash2.prototype, methodName)) {
            source[methodName] = func;
          }
        });
        return source;
      }(), { "chain": false });
      lodash2.VERSION = VERSION2;
      arrayEach2(["bind", "bindKey", "curry", "curryRight", "partial", "partialRight"], function(methodName) {
        lodash2[methodName].placeholder = lodash2;
      });
      arrayEach2(["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();
        };
      });
      arrayEach2(["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;
        };
      });
      arrayEach2(["head", "last"], function(methodName, index2) {
        var takeName = "take" + (index2 ? "Right" : "");
        LazyWrapper.prototype[methodName] = function() {
          return this[takeName](1).value()[0];
        };
      });
      arrayEach2(["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(identity2);
      };
      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(start2, end) {
        start2 = toInteger(start2);
        var result2 = this;
        if (result2.__filtered__ && (start2 > 0 || end < 0)) {
          return new LazyWrapper(result2);
        }
        if (start2 < 0) {
          result2 = result2.takeRight(-start2);
        } else if (start2) {
          result2 = result2.drop(start2);
        }
        if (end !== undefined$1) {
          end = toInteger(end);
          result2 = end < 0 ? result2.dropRight(-end) : result2.take(end - start2);
        }
        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 || isArray2(value);
          var interceptor = /* @__PURE__ */ __name(function(value2) {
            var result3 = lodashFunc.apply(lodash2, arrayPush2([value2], args));
            return isTaker && chainAll ? result3[0] : result3;
          }, "interceptor");
          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;
        };
      });
      arrayEach2(["pop", "push", "shift", "sort", "splice", "unshift"], function(methodName) {
        var func = arrayProto2[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(isArray2(value) ? value : [], args);
          }
          return this[chainName](function(value2) {
            return func.apply(isArray2(value2) ? value2 : [], args);
          });
        };
      });
      baseForOwn(LazyWrapper.prototype, function(func, methodName) {
        var lodashFunc = lodash2[methodName];
        if (lodashFunc) {
          var key = lodashFunc.name + "";
          if (!hasOwnProperty2.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;
    }, "runInContext");
    var _2 = runInContext();
    if (typeof undefined$1 == "function" && typeof undefined$1.amd == "object" && undefined$1.amd) {
      root2._ = _2;
      undefined$1(function() {
        return _2;
      });
    } else if (freeModule) {
      (freeModule.exports = _2)._ = _2;
      freeExports._ = _2;
    } else {
      root2._ = _2;
    }
  }).call(commonjsGlobal);
})(lodash$1, lodash$1.exports);
var lodashExports = lodash$1.exports;
const _ = /* @__PURE__ */ getDefaultExportFromCjs(lodashExports);
const useDialogStore = /* @__PURE__ */ defineStore("dialog", () => {
  const dialogStack = ref$3([]);
  const genDialogKey = /* @__PURE__ */ __name(() => `dialog-${Math.random().toString(36).slice(2, 9)}`, "genDialogKey");
  function riseDialog(options2) {
    const dialogKey = options2.key;
    const index2 = dialogStack.value.findIndex((d2) => d2.key === dialogKey);
    if (index2 !== -1) {
      const dialogs = dialogStack.value.splice(index2, 1);
      dialogStack.value.push(...dialogs);
    }
  }
  __name(riseDialog, "riseDialog");
  function closeDialog(options2) {
    const targetDialog = options2 ? dialogStack.value.find((d2) => d2.key === options2.key) : dialogStack.value[0];
    if (!targetDialog) return;
    targetDialog.dialogComponentProps?.onClose?.();
    dialogStack.value.splice(dialogStack.value.indexOf(targetDialog), 1);
  }
  __name(closeDialog, "closeDialog");
  function createDialog(options2) {
    if (dialogStack.value.length >= 10) {
      dialogStack.value.shift();
    }
    const dialog = {
      key: options2.key,
      visible: true,
      title: options2.title,
      headerComponent: options2.headerComponent ? markRaw(options2.headerComponent) : void 0,
      footerComponent: options2.footerComponent ? markRaw(options2.footerComponent) : void 0,
      component: markRaw(options2.component),
      contentProps: { ...options2.props },
      dialogComponentProps: {
        maximizable: false,
        modal: true,
        closable: true,
        closeOnEscape: true,
        dismissableMask: true,
        ...options2.dialogComponentProps,
        maximized: false,
        onMaximize: /* @__PURE__ */ __name(() => {
          dialog.dialogComponentProps.maximized = true;
        }, "onMaximize"),
        onUnmaximize: /* @__PURE__ */ __name(() => {
          dialog.dialogComponentProps.maximized = false;
        }, "onUnmaximize"),
        onAfterHide: /* @__PURE__ */ __name(() => {
          closeDialog(dialog);
        }, "onAfterHide"),
        pt: lodashExports.merge(options2.dialogComponentProps?.pt || {}, {
          root: {
            onMousedown: /* @__PURE__ */ __name(() => {
              riseDialog(dialog);
            }, "onMousedown")
          }
        })
      }
    };
    dialogStack.value.push(dialog);
    return dialog;
  }
  __name(createDialog, "createDialog");
  function showDialog(options2) {
    const dialogKey = options2.key || genDialogKey();
    let dialog = dialogStack.value.find((d2) => d2.key === dialogKey);
    if (dialog) {
      dialog.visible = true;
      riseDialog(dialog);
    } else {
      dialog = createDialog({ ...options2, key: dialogKey });
    }
    return dialog;
  }
  __name(showDialog, "showDialog");
  return {
    dialogStack,
    riseDialog,
    showDialog,
    closeDialog
  };
});
const _hoisted_1$1v = ["id"];
const _sfc_main$1S = /* @__PURE__ */ defineComponent({
  __name: "GlobalDialog",
  setup(__props) {
    const dialogStore = useDialogStore();
    const primevue = usePrimeVue();
    const baseZIndex = computed(() => {
      return primevue?.config?.zIndex?.modal ?? 1100;
    });
    onMounted(() => {
      const mask = document.createElement("div");
      ZIndex$1.set("model", mask, baseZIndex.value);
    });
    return (_ctx, _cache) => {
      return openBlock(true), createElementBlock(Fragment$1, null, renderList(unref(dialogStore).dialogStack, (item, index2) => {
        return openBlock(), createBlock(unref(script$4), mergeProps$1({
          key: item.key,
          visible: item.visible,
          "onUpdate:visible": /* @__PURE__ */ __name(($event) => item.visible = $event, "onUpdate:visible"),
          class: "global-dialog",
          ref_for: true
        }, item.dialogComponentProps, {
          "auto-z-index": false,
          pt: item.dialogComponentProps.pt,
          "pt:mask:style": { zIndex: baseZIndex.value + index2 + 1 },
          "aria-labelledby": item.key
        }), createSlots({
          header: withCtx(() => [
            item.headerComponent ? (openBlock(), createBlock(resolveDynamicComponent(item.headerComponent), {
              key: 0,
              id: item.key
            }, null, 8, ["id"])) : (openBlock(), createElementBlock("h3", {
              key: 1,
              id: item.key
            }, toDisplayString(item.title || " "), 9, _hoisted_1$1v))
          ]),
          default: withCtx(() => [
            (openBlock(), createBlock(resolveDynamicComponent(item.component), mergeProps$1({ ref_for: true }, item.contentProps, {
              maximized: item.dialogComponentProps.maximized
            }), null, 16, ["maximized"]))
          ]),
          _: 2
        }, [
          item.footerComponent ? {
            name: "footer",
            fn: withCtx(() => [
              (openBlock(), createBlock(resolveDynamicComponent(item.footerComponent)))
            ]),
            key: "0"
          } : void 0
        ]), 1040, ["visible", "onUpdate:visible", "pt", "pt:mask:style", "aria-labelledby"]);
      }), 128);
    };
  }
});
const config$1 = {
  app_title: "ComfyUI",
  app_version: "1.20.0"
};
class InputIndicators {
  static {
    __name(this, "InputIndicators");
  }
  constructor(canvas2) {
    this.canvas = canvas2;
    this.controller = new AbortController();
    const { signal } = this.controller;
    const element = canvas2.canvas;
    const options2 = { capture: true, signal };
    element.addEventListener("pointerdown", this.#onPointerDownOrMove, options2);
    element.addEventListener("pointermove", this.#onPointerDownOrMove, options2);
    element.addEventListener("pointerup", this.#onPointerUp, options2);
    element.addEventListener("keydown", this.#onKeyDownOrUp, options2);
    document.addEventListener("keyup", this.#onKeyDownOrUp, options2);
    const origDrawFrontCanvas = canvas2.drawFrontCanvas.bind(canvas2);
    signal.addEventListener("abort", () => {
      canvas2.drawFrontCanvas = origDrawFrontCanvas;
    });
    canvas2.drawFrontCanvas = () => {
      origDrawFrontCanvas();
      this.draw();
    };
  }
  // #region config
  radius = 8;
  startAngle = 0;
  endAngle = Math.PI * 2;
  inactiveColour = "#ffffff10";
  colour1 = "#ff5f00";
  colour2 = "#00ff7c";
  colour3 = "#dea7ff";
  fontString = "bold 12px Arial";
  // #endregion
  // #region state
  enabled = true;
  shiftDown = false;
  undoDown = false;
  redoDown = false;
  ctrlDown = false;
  altDown = false;
  mouse0Down = false;
  mouse1Down = false;
  mouse2Down = false;
  x = 0;
  y = 0;
  // #endregion
  controller;
  #onPointerDownOrMove = this.onPointerDownOrMove.bind(this);
  onPointerDownOrMove(e2) {
    this.mouse0Down = (e2.buttons & 1) === 1;
    this.mouse1Down = (e2.buttons & 4) === 4;
    this.mouse2Down = (e2.buttons & 2) === 2;
    this.x = e2.clientX;
    this.y = e2.clientY;
    this.canvas.setDirty(true);
  }
  #onPointerUp = this.onPointerUp.bind(this);
  onPointerUp() {
    this.mouse0Down = false;
    this.mouse1Down = false;
    this.mouse2Down = false;
  }
  #onKeyDownOrUp = this.onKeyDownOrUp.bind(this);
  onKeyDownOrUp(e2) {
    this.ctrlDown = e2.ctrlKey;
    this.altDown = e2.altKey;
    this.shiftDown = e2.shiftKey;
    this.undoDown = e2.ctrlKey && e2.code === "KeyZ" && e2.type === "keydown";
    this.redoDown = e2.ctrlKey && e2.code === "KeyY" && e2.type === "keydown";
  }
  draw() {
    const {
      canvas: { ctx },
      radius,
      startAngle,
      endAngle,
      x: x2,
      y: y2,
      inactiveColour,
      colour1,
      colour2,
      colour3,
      fontString
    } = this;
    const { fillStyle, font } = ctx;
    const mouseDotX = x2;
    const mouseDotY = y2 - 80;
    const textX = mouseDotX;
    const textY = mouseDotY - 15;
    ctx.font = fontString;
    textMarker(textX + 0, textY, "Shift", this.shiftDown ? colour1 : inactiveColour);
    textMarker(textX + 45, textY + 20, "Alt", this.altDown ? colour2 : inactiveColour);
    textMarker(textX + 30, textY, "Control", this.ctrlDown ? colour3 : inactiveColour);
    textMarker(textX - 30, textY, "↩️", this.undoDown ? "#000" : "transparent");
    textMarker(textX + 45, textY, "↪️", this.redoDown ? "#000" : "transparent");
    ctx.beginPath();
    drawDot(mouseDotX, mouseDotY);
    drawDot(mouseDotX + 15, mouseDotY);
    drawDot(mouseDotX + 30, mouseDotY);
    ctx.fillStyle = inactiveColour;
    ctx.fill();
    const leftButtonColour = this.mouse0Down ? colour1 : inactiveColour;
    const middleButtonColour = this.mouse1Down ? colour2 : inactiveColour;
    const rightButtonColour = this.mouse2Down ? colour3 : inactiveColour;
    if (this.mouse0Down) mouseMarker(mouseDotX, mouseDotY, leftButtonColour);
    if (this.mouse1Down) mouseMarker(mouseDotX + 15, mouseDotY, middleButtonColour);
    if (this.mouse2Down) mouseMarker(mouseDotX + 30, mouseDotY, rightButtonColour);
    ctx.fillStyle = fillStyle;
    ctx.font = font;
    function textMarker(x22, y22, text2, colour) {
      ctx.fillStyle = colour;
      ctx.fillText(text2, x22, y22);
    }
    __name(textMarker, "textMarker");
    function mouseMarker(x22, y22, colour) {
      ctx.beginPath();
      ctx.fillStyle = colour;
      drawDot(x22, y22);
      ctx.fill();
    }
    __name(mouseMarker, "mouseMarker");
    function drawDot(x22, y22) {
      ctx.arc(x22, y22, radius, startAngle, endAngle);
    }
    __name(drawDot, "drawDot");
  }
  dispose() {
    this.controller?.abort();
    this.controller = void 0;
  }
  [Symbol.dispose]() {
    this.dispose();
  }
}
class ContextMenu {
  static {
    __name(this, "ContextMenu");
  }
  options;
  parentMenu;
  root;
  current_submenu;
  lock;
  controller = new AbortController();
  /**
   * @todo Interface for values requires functionality change - currently accepts
   * an array of strings, functions, objects, nulls, or undefined.
   * @param values (allows object { title: "Nice text", callback: function ... })
   * @param options [optional] Some options:\
   * - title: title to show on top of the menu
   * - callback: function to call when an option is clicked, it receives the item information
   * - ignore_item_callbacks: ignores the callback inside the item, it just calls the options.callback
   * - event: you can pass a MouseEvent, this way the ContextMenu appears in that position
   */
  constructor(values, options2) {
    options2 ||= {};
    this.options = options2;
    const parent2 = options2.parentMenu;
    if (parent2) {
      if (!(parent2 instanceof ContextMenu)) {
        console.error("parentMenu must be of class ContextMenu, ignoring it");
        options2.parentMenu = void 0;
      } else {
        this.parentMenu = parent2;
        this.parentMenu.lock = true;
        this.parentMenu.current_submenu = this;
      }
      if (parent2.options?.className === "dark") {
        options2.className = "dark";
      }
    }
    const eventClass = options2.event ? options2.event.constructor.name : null;
    if (eventClass !== "MouseEvent" && eventClass !== "CustomEvent" && eventClass !== "PointerEvent") {
      console.error(`Event passed to ContextMenu is not of type MouseEvent or CustomEvent. Ignoring it. (${eventClass})`);
      options2.event = void 0;
    }
    const root2 = document.createElement("div");
    let classes2 = "litegraph litecontextmenu litemenubar-panel";
    if (options2.className) classes2 += ` ${options2.className}`;
    root2.className = classes2;
    root2.style.minWidth = "100";
    root2.style.minHeight = "100";
    const { signal } = this.controller;
    const eventOptions = { capture: true, signal };
    if (!this.parentMenu) {
      document.addEventListener("pointerdown", (e2) => {
        if (e2.target instanceof Node && !this.containsNode(e2.target)) {
          this.close();
        }
      }, eventOptions);
    }
    root2.addEventListener("pointerup", (e2) => e2.preventDefault(), eventOptions);
    root2.addEventListener(
      "contextmenu",
      (e2) => {
        if (e2.button === 2) e2.preventDefault();
      },
      eventOptions
    );
    root2.addEventListener(
      "pointerdown",
      (e2) => {
        if (e2.button == 2) {
          this.close();
          e2.preventDefault();
        }
      },
      eventOptions
    );
    this.root = root2;
    if (options2.title) {
      const element = document.createElement("div");
      element.className = "litemenu-title";
      element.innerHTML = options2.title;
      root2.append(element);
    }
    for (let i2 = 0; i2 < values.length; i2++) {
      const value = values[i2];
      let name2 = Array.isArray(values) ? value : String(i2);
      if (typeof name2 !== "string") {
        name2 = name2 != null ? name2.content === void 0 ? String(name2) : name2.content : name2;
      }
      this.addItem(name2, value, options2);
    }
    const ownerDocument = options2.event?.target?.ownerDocument;
    const root_document = ownerDocument || document;
    if (root_document.fullscreenElement)
      root_document.fullscreenElement.append(root2);
    else
      root_document.body.append(root2);
    let left = options2.left || 0;
    let top = options2.top || 0;
    if (options2.event) {
      left = options2.event.clientX - 10;
      top = options2.event.clientY - 10;
      if (options2.title) top -= 20;
      if (parent2) {
        const rect = parent2.root.getBoundingClientRect();
        left = rect.left + rect.width;
      }
      const body_rect = document.body.getBoundingClientRect();
      const root_rect = root2.getBoundingClientRect();
      if (body_rect.height == 0)
        console.error("document.body height is 0. That is dangerous, set html,body { height: 100%; }");
      if (body_rect.width && left > body_rect.width - root_rect.width - 10)
        left = body_rect.width - root_rect.width - 10;
      if (body_rect.height && top > body_rect.height - root_rect.height - 10)
        top = body_rect.height - root_rect.height - 10;
    }
    root2.style.left = `${left}px`;
    root2.style.top = `${top}px`;
    if (LiteGraph.context_menu_scaling && options2.scale) {
      root2.style.transform = `scale(${Math.round(options2.scale * 4) * 0.25})`;
    }
  }
  /**
   * Checks if {@link node} is inside this context menu or any of its submenus
   * @param node The {@link Node} to check
   * @param visited A set of visited menus to avoid circular references
   * @returns `true` if {@link node} is inside this context menu or any of its submenus
   */
  containsNode(node2, visited = /* @__PURE__ */ new Set()) {
    if (visited.has(this)) return false;
    visited.add(this);
    return this.current_submenu?.containsNode(node2, visited) || this.root.contains(node2);
  }
  addItem(name2, value, options2) {
    options2 ||= {};
    const element = document.createElement("div");
    element.className = "litemenu-entry submenu";
    let disabled = false;
    if (value === null) {
      element.classList.add("separator");
    } else {
      const innerHtml = name2 === null ? "" : String(name2);
      if (typeof value === "string") {
        element.innerHTML = innerHtml;
      } else {
        element.innerHTML = value?.title ?? innerHtml;
        if (value.disabled) {
          disabled = true;
          element.classList.add("disabled");
          element.setAttribute("aria-disabled", "true");
        }
        if (value.submenu || value.has_submenu) {
          element.classList.add("has_submenu");
          element.setAttribute("aria-haspopup", "true");
          element.setAttribute("aria-expanded", "false");
        }
        if (value.className) element.className += ` ${value.className}`;
      }
      element.value = value;
      element.setAttribute("role", "menuitem");
      if (typeof value === "function") {
        element.dataset["value"] = String(name2);
        element.onclick_callback = value;
      } else {
        element.dataset["value"] = String(value);
      }
    }
    this.root.append(element);
    if (!disabled) element.addEventListener("click", inner_onclick);
    if (!disabled && options2.autoopen)
      element.addEventListener("pointerenter", inner_over);
    const setAriaExpanded = /* @__PURE__ */ __name(() => {
      const entries = this.root.querySelectorAll("div.litemenu-entry.has_submenu");
      if (entries) {
        for (const entry of entries) {
          entry.setAttribute("aria-expanded", "false");
        }
      }
      element.setAttribute("aria-expanded", "true");
    }, "setAriaExpanded");
    function inner_over(e2) {
      const value2 = this.value;
      if (!value2 || !value2.has_submenu) return;
      inner_onclick.call(this, e2);
      setAriaExpanded();
    }
    __name(inner_over, "inner_over");
    const that = this;
    function inner_onclick(e2) {
      const value2 = this.value;
      let close_parent = true;
      that.current_submenu?.close(e2);
      if (value2?.has_submenu || value2?.submenu) {
        setAriaExpanded();
      }
      if (options2.callback) {
        const r2 = options2.callback.call(
          this,
          value2,
          options2,
          e2,
          that,
          options2.node
        );
        if (r2 === true) close_parent = false;
      }
      if (typeof value2 === "object") {
        if (value2.callback && !options2.ignore_item_callbacks && value2.disabled !== true) {
          const r2 = value2.callback.call(
            this,
            value2,
            options2,
            e2,
            that,
            options2.extra
          );
          if (r2 === true) close_parent = false;
        }
        if (value2.submenu) {
          if (!value2.submenu.options) throw "ContextMenu submenu needs options";
          new that.constructor(value2.submenu.options, {
            callback: value2.submenu.callback,
            event: e2,
            parentMenu: that,
            ignore_item_callbacks: value2.submenu.ignore_item_callbacks,
            title: value2.submenu.title,
            extra: value2.submenu.extra,
            autoopen: options2.autoopen
          });
          close_parent = false;
        }
      }
      if (close_parent && !that.lock) that.close();
    }
    __name(inner_onclick, "inner_onclick");
    return element;
  }
  close(e2, ignore_parent_menu) {
    this.controller.abort();
    this.root.remove();
    if (this.parentMenu && !ignore_parent_menu) {
      this.parentMenu.lock = false;
      this.parentMenu.current_submenu = void 0;
      if (e2 === void 0) {
        this.parentMenu.close();
      } else if (e2 && !ContextMenu.isCursorOverElement(e2, this.parentMenu.root)) {
        ContextMenu.trigger(
          this.parentMenu.root,
          `${LiteGraph.pointerevents_method}leave`,
          e2
        );
      }
    }
    this.current_submenu?.close(e2, true);
  }
  /** @deprecated Likely unused, however code search was inconclusive (too many results to check by hand). */
  // this code is used to trigger events easily (used in the context menu mouseleave
  static trigger(element, event_name, params) {
    const evt = document.createEvent("CustomEvent");
    evt.initCustomEvent(event_name, true, true, params);
    if (element.dispatchEvent) element.dispatchEvent(evt);
    return evt;
  }
  // returns the top most menu
  getTopMenu() {
    return this.options.parentMenu ? this.options.parentMenu.getTopMenu() : this;
  }
  getFirstEvent() {
    return this.options.parentMenu ? this.options.parentMenu.getFirstEvent() : this.options.event;
  }
  /** @deprecated Unused. */
  static isCursorOverElement(event, element) {
    const left = event.clientX;
    const top = event.clientY;
    const rect = element.getBoundingClientRect();
    if (!rect) return false;
    if (top > rect.top && top < rect.top + rect.height && left > rect.left && left < rect.left + rect.width) {
      return true;
    }
    return false;
  }
}
var NodeSlotType = /* @__PURE__ */ ((NodeSlotType2) => {
  NodeSlotType2[NodeSlotType2["INPUT"] = 1] = "INPUT";
  NodeSlotType2[NodeSlotType2["OUTPUT"] = 2] = "OUTPUT";
  return NodeSlotType2;
})(NodeSlotType || {});
var RenderShape = /* @__PURE__ */ ((RenderShape2) => {
  RenderShape2[RenderShape2["BOX"] = 1] = "BOX";
  RenderShape2[RenderShape2["ROUND"] = 2] = "ROUND";
  RenderShape2[RenderShape2["CIRCLE"] = 3] = "CIRCLE";
  RenderShape2[RenderShape2["CARD"] = 4] = "CARD";
  RenderShape2[RenderShape2["ARROW"] = 5] = "ARROW";
  RenderShape2[RenderShape2["GRID"] = 6] = "GRID";
  RenderShape2[RenderShape2["HollowCircle"] = 7] = "HollowCircle";
  return RenderShape2;
})(RenderShape || {});
var CanvasItem = /* @__PURE__ */ ((CanvasItem2) => {
  CanvasItem2[CanvasItem2["Nothing"] = 0] = "Nothing";
  CanvasItem2[CanvasItem2["Node"] = 1] = "Node";
  CanvasItem2[CanvasItem2["Group"] = 2] = "Group";
  CanvasItem2[CanvasItem2["Reroute"] = 4] = "Reroute";
  CanvasItem2[CanvasItem2["Link"] = 8] = "Link";
  CanvasItem2[CanvasItem2["ResizeSe"] = 16] = "ResizeSe";
  CanvasItem2[CanvasItem2["RerouteSlot"] = 32] = "RerouteSlot";
  return CanvasItem2;
})(CanvasItem || {});
var LinkDirection = /* @__PURE__ */ ((LinkDirection2) => {
  LinkDirection2[LinkDirection2["NONE"] = 0] = "NONE";
  LinkDirection2[LinkDirection2["UP"] = 1] = "UP";
  LinkDirection2[LinkDirection2["DOWN"] = 2] = "DOWN";
  LinkDirection2[LinkDirection2["LEFT"] = 3] = "LEFT";
  LinkDirection2[LinkDirection2["RIGHT"] = 4] = "RIGHT";
  LinkDirection2[LinkDirection2["CENTER"] = 5] = "CENTER";
  return LinkDirection2;
})(LinkDirection || {});
var LinkRenderType = /* @__PURE__ */ ((LinkRenderType2) => {
  LinkRenderType2[LinkRenderType2["HIDDEN_LINK"] = -1] = "HIDDEN_LINK";
  LinkRenderType2[LinkRenderType2["STRAIGHT_LINK"] = 0] = "STRAIGHT_LINK";
  LinkRenderType2[LinkRenderType2["LINEAR_LINK"] = 1] = "LINEAR_LINK";
  LinkRenderType2[LinkRenderType2["SPLINE_LINK"] = 2] = "SPLINE_LINK";
  return LinkRenderType2;
})(LinkRenderType || {});
var LinkMarkerShape = /* @__PURE__ */ ((LinkMarkerShape2) => {
  LinkMarkerShape2[LinkMarkerShape2["None"] = 0] = "None";
  LinkMarkerShape2[LinkMarkerShape2["Circle"] = 1] = "Circle";
  LinkMarkerShape2[LinkMarkerShape2["Arrow"] = 2] = "Arrow";
  return LinkMarkerShape2;
})(LinkMarkerShape || {});
var TitleMode = /* @__PURE__ */ ((TitleMode2) => {
  TitleMode2[TitleMode2["NORMAL_TITLE"] = 0] = "NORMAL_TITLE";
  TitleMode2[TitleMode2["NO_TITLE"] = 1] = "NO_TITLE";
  TitleMode2[TitleMode2["TRANSPARENT_TITLE"] = 2] = "TRANSPARENT_TITLE";
  TitleMode2[TitleMode2["AUTOHIDE_TITLE"] = 3] = "AUTOHIDE_TITLE";
  return TitleMode2;
})(TitleMode || {});
var LGraphEventMode = /* @__PURE__ */ ((LGraphEventMode2) => {
  LGraphEventMode2[LGraphEventMode2["ALWAYS"] = 0] = "ALWAYS";
  LGraphEventMode2[LGraphEventMode2["ON_EVENT"] = 1] = "ON_EVENT";
  LGraphEventMode2[LGraphEventMode2["NEVER"] = 2] = "NEVER";
  LGraphEventMode2[LGraphEventMode2["ON_TRIGGER"] = 3] = "ON_TRIGGER";
  LGraphEventMode2[LGraphEventMode2["BYPASS"] = 4] = "BYPASS";
  return LGraphEventMode2;
})(LGraphEventMode || {});
var EaseFunction = /* @__PURE__ */ ((EaseFunction2) => {
  EaseFunction2["LINEAR"] = "linear";
  EaseFunction2["EASE_IN_QUAD"] = "easeInQuad";
  EaseFunction2["EASE_OUT_QUAD"] = "easeOutQuad";
  EaseFunction2["EASE_IN_OUT_QUAD"] = "easeInOutQuad";
  return EaseFunction2;
})(EaseFunction || {});
function distance(a2, b2) {
  return Math.sqrt(
    (b2[0] - a2[0]) * (b2[0] - a2[0]) + (b2[1] - a2[1]) * (b2[1] - a2[1])
  );
}
__name(distance, "distance");
function dist2(x1, y1, x2, y2) {
  return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
}
__name(dist2, "dist2");
function isInRectangle(x2, y2, left, top, width2, height) {
  return x2 >= left && x2 < left + width2 && y2 >= top && y2 < top + height;
}
__name(isInRectangle, "isInRectangle");
function isPointInRect(point, rect) {
  return point[0] >= rect[0] && point[0] < rect[0] + rect[2] && point[1] >= rect[1] && point[1] < rect[1] + rect[3];
}
__name(isPointInRect, "isPointInRect");
function isInRect(x2, y2, rect) {
  return x2 >= rect[0] && x2 < rect[0] + rect[2] && y2 >= rect[1] && y2 < rect[1] + rect[3];
}
__name(isInRect, "isInRect");
function isInsideRectangle(x2, y2, left, top, width2, height) {
  return left < x2 && left + width2 > x2 && top < y2 && top + height > y2;
}
__name(isInsideRectangle, "isInsideRectangle");
function overlapBounding(a2, b2) {
  const aRight = a2[0] + a2[2];
  const aBottom = a2[1] + a2[3];
  const bRight = b2[0] + b2[2];
  const bBottom = b2[1] + b2[3];
  return a2[0] > bRight || a2[1] > bBottom || aRight < b2[0] || aBottom < b2[1] ? false : true;
}
__name(overlapBounding, "overlapBounding");
function getCentre(rect) {
  return [
    rect[0] + rect[2] * 0.5,
    rect[1] + rect[3] * 0.5
  ];
}
__name(getCentre, "getCentre");
function containsCentre(a2, b2) {
  const centreX = b2[0] + b2[2] * 0.5;
  const centreY = b2[1] + b2[3] * 0.5;
  return isInRect(centreX, centreY, a2);
}
__name(containsCentre, "containsCentre");
function containsRect(a2, b2) {
  const aRight = a2[0] + a2[2];
  const aBottom = a2[1] + a2[3];
  const bRight = b2[0] + b2[2];
  const bBottom = b2[1] + b2[3];
  const identical = a2[0] === b2[0] && a2[1] === b2[1] && aRight === bRight && aBottom === bBottom;
  return !identical && a2[0] <= b2[0] && a2[1] <= b2[1] && aRight >= bRight && aBottom >= bBottom;
}
__name(containsRect, "containsRect");
function findPointOnCurve(out, a2, b2, controlA, controlB, t2 = 0.5) {
  const iT = 1 - t2;
  const c1 = iT * iT * iT;
  const c2 = 3 * (iT * iT) * t2;
  const c3 = 3 * iT * (t2 * t2);
  const c4 = t2 * t2 * t2;
  out[0] = c1 * a2[0] + c2 * controlA[0] + c3 * controlB[0] + c4 * b2[0];
  out[1] = c1 * a2[1] + c2 * controlA[1] + c3 * controlB[1] + c4 * b2[1];
}
__name(findPointOnCurve, "findPointOnCurve");
function createBounds(objects, padding = 10) {
  const bounds = new Float32Array([Infinity, Infinity, -Infinity, -Infinity]);
  for (const obj of objects) {
    const rect = obj.boundingRect;
    bounds[0] = Math.min(bounds[0], rect[0]);
    bounds[1] = Math.min(bounds[1], rect[1]);
    bounds[2] = Math.max(bounds[2], rect[0] + rect[2]);
    bounds[3] = Math.max(bounds[3], rect[1] + rect[3]);
  }
  if (!bounds.every((x2) => isFinite(x2))) return null;
  return [
    bounds[0] - padding,
    bounds[1] - padding,
    bounds[2] - bounds[0] + 2 * padding,
    bounds[3] - bounds[1] + 2 * padding
  ];
}
__name(createBounds, "createBounds");
function snapPoint(pos, snapTo) {
  if (!snapTo) return false;
  pos[0] = snapTo * Math.round(pos[0] / snapTo);
  pos[1] = snapTo * Math.round(pos[1] / snapTo);
  return true;
}
__name(snapPoint, "snapPoint");
function clamp(value, min, max) {
  return value < min ? min : value > max ? max : value;
}
__name(clamp, "clamp");
class CurveEditor {
  static {
    __name(this, "CurveEditor");
  }
  points;
  selected;
  nearest;
  size;
  must_update;
  margin;
  _nearest;
  constructor(points) {
    this.points = points;
    this.selected = -1;
    this.nearest = -1;
    this.size = null;
    this.must_update = true;
    this.margin = 5;
  }
  static sampleCurve(f2, points) {
    if (!points) return;
    for (let i2 = 0; i2 < points.length - 1; ++i2) {
      const p2 = points[i2];
      const pn = points[i2 + 1];
      if (pn[0] < f2) continue;
      const r2 = pn[0] - p2[0];
      if (Math.abs(r2) < 1e-5) return p2[1];
      const local_f = (f2 - p2[0]) / r2;
      return p2[1] * (1 - local_f) + pn[1] * local_f;
    }
    return 0;
  }
  draw(ctx, size, graphcanvas, background_color, line_color, inactive = false) {
    const points = this.points;
    if (!points) return;
    this.size = size;
    const w2 = size[0] - this.margin * 2;
    const h2 = size[1] - this.margin * 2;
    line_color = line_color || "#666";
    ctx.save();
    ctx.translate(this.margin, this.margin);
    if (background_color) {
      ctx.fillStyle = "#111";
      ctx.fillRect(0, 0, w2, h2);
      ctx.fillStyle = "#222";
      ctx.fillRect(w2 * 0.5, 0, 1, h2);
      ctx.strokeStyle = "#333";
      ctx.strokeRect(0, 0, w2, h2);
    }
    ctx.strokeStyle = line_color;
    if (inactive) ctx.globalAlpha = 0.5;
    ctx.beginPath();
    for (const p2 of points) {
      ctx.lineTo(p2[0] * w2, (1 - p2[1]) * h2);
    }
    ctx.stroke();
    ctx.globalAlpha = 1;
    if (!inactive) {
      for (const [i2, p2] of points.entries()) {
        ctx.fillStyle = this.selected == i2 ? "#FFF" : this.nearest == i2 ? "#DDD" : "#AAA";
        ctx.beginPath();
        ctx.arc(p2[0] * w2, (1 - p2[1]) * h2, 2, 0, Math.PI * 2);
        ctx.fill();
      }
    }
    ctx.restore();
  }
  // localpos is mouse in curve editor space
  onMouseDown(localpos, graphcanvas) {
    const points = this.points;
    if (!points) return;
    if (localpos[1] < 0) return;
    if (this.size == null) throw new Error("CurveEditor.size was null or undefined.");
    const w2 = this.size[0] - this.margin * 2;
    const h2 = this.size[1] - this.margin * 2;
    const x2 = localpos[0] - this.margin;
    const y2 = localpos[1] - this.margin;
    const pos = [x2, y2];
    const max_dist = 30 / graphcanvas.ds.scale;
    this.selected = this.getCloserPoint(pos, max_dist);
    if (this.selected == -1) {
      const point = [x2 / w2, 1 - y2 / h2];
      points.push(point);
      points.sort(function(a2, b2) {
        return a2[0] - b2[0];
      });
      this.selected = points.indexOf(point);
      this.must_update = true;
    }
    if (this.selected != -1) return true;
  }
  onMouseMove(localpos, graphcanvas) {
    const points = this.points;
    if (!points) return;
    const s2 = this.selected;
    if (s2 < 0) return;
    if (this.size == null) throw new Error("CurveEditor.size was null or undefined.");
    const x2 = (localpos[0] - this.margin) / (this.size[0] - this.margin * 2);
    const y2 = (localpos[1] - this.margin) / (this.size[1] - this.margin * 2);
    const curvepos = [
      localpos[0] - this.margin,
      localpos[1] - this.margin
    ];
    const max_dist = 30 / graphcanvas.ds.scale;
    this._nearest = this.getCloserPoint(curvepos, max_dist);
    const point = points[s2];
    if (point) {
      const is_edge_point = s2 == 0 || s2 == points.length - 1;
      if (!is_edge_point && (localpos[0] < -10 || localpos[0] > this.size[0] + 10 || localpos[1] < -10 || localpos[1] > this.size[1] + 10)) {
        points.splice(s2, 1);
        this.selected = -1;
        return;
      }
      if (!is_edge_point) point[0] = clamp(x2, 0, 1);
      else point[0] = s2 == 0 ? 0 : 1;
      point[1] = 1 - clamp(y2, 0, 1);
      points.sort(function(a2, b2) {
        return a2[0] - b2[0];
      });
      this.selected = points.indexOf(point);
      this.must_update = true;
    }
  }
  // Former params: localpos, graphcanvas
  onMouseUp() {
    this.selected = -1;
    return false;
  }
  getCloserPoint(pos, max_dist) {
    const points = this.points;
    if (!points) return -1;
    max_dist = max_dist || 30;
    if (this.size == null) throw new Error("CurveEditor.size was null or undefined.");
    const w2 = this.size[0] - this.margin * 2;
    const h2 = this.size[1] - this.margin * 2;
    const num = points.length;
    const p2 = [0, 0];
    let min_dist = 1e6;
    let closest = -1;
    for (let i2 = 0; i2 < num; ++i2) {
      const p3 = points[i2];
      p2[0] = p3[0] * w2;
      p2[1] = (1 - p3[1]) * h2;
      const dist3 = distance(pos, p2);
      if (dist3 > min_dist || dist3 > max_dist) continue;
      closest = i2;
      min_dist = dist3;
    }
    return closest;
  }
}
class DragAndScale {
  static {
    __name(this, "DragAndScale");
  }
  /**
   * The state of this DragAndScale instance.
   *
   * Implemented as a POCO that can be proxied without side-effects.
   */
  state;
  /** Maximum scale (zoom in) */
  max_scale;
  /** Minimum scale (zoom out) */
  min_scale;
  enabled;
  last_mouse;
  element;
  visible_area;
  dragging;
  viewport;
  get offset() {
    return this.state.offset;
  }
  set offset(value) {
    this.state.offset = value;
  }
  get scale() {
    return this.state.scale;
  }
  set scale(value) {
    this.state.scale = value;
  }
  constructor(element) {
    this.state = {
      offset: new Float32Array([0, 0]),
      scale: 1
    };
    this.max_scale = 10;
    this.min_scale = 0.1;
    this.enabled = true;
    this.last_mouse = [0, 0];
    this.visible_area = new Rectangle();
    this.element = element;
  }
  computeVisibleArea(viewport) {
    if (!this.element) {
      this.visible_area[0] = this.visible_area[1] = this.visible_area[2] = this.visible_area[3] = 0;
      return;
    }
    let width2 = this.element.width;
    let height = this.element.height;
    let startx = -this.offset[0];
    let starty = -this.offset[1];
    if (viewport) {
      startx += viewport[0] / this.scale;
      starty += viewport[1] / this.scale;
      width2 = viewport[2];
      height = viewport[3];
    }
    const endx = startx + width2 / this.scale;
    const endy = starty + height / this.scale;
    this.visible_area[0] = startx;
    this.visible_area[1] = starty;
    this.visible_area[2] = endx - startx;
    this.visible_area[3] = endy - starty;
  }
  toCanvasContext(ctx) {
    ctx.scale(this.scale, this.scale);
    ctx.translate(this.offset[0], this.offset[1]);
  }
  convertOffsetToCanvas(pos) {
    return [
      (pos[0] + this.offset[0]) * this.scale,
      (pos[1] + this.offset[1]) * this.scale
    ];
  }
  convertCanvasToOffset(pos, out) {
    out = out || [0, 0];
    out[0] = pos[0] / this.scale - this.offset[0];
    out[1] = pos[1] / this.scale - this.offset[1];
    return out;
  }
  /** @deprecated Has not been kept up to date */
  mouseDrag(x2, y2) {
    this.offset[0] += x2 / this.scale;
    this.offset[1] += y2 / this.scale;
    this.onredraw?.(this);
  }
  changeScale(value, zooming_center, roundToScaleOne = true) {
    if (value < this.min_scale) {
      value = this.min_scale;
    } else if (value > this.max_scale) {
      value = this.max_scale;
    }
    if (value == this.scale) return;
    const rect = this.element.getBoundingClientRect();
    if (!rect) return;
    zooming_center = zooming_center ?? [rect.width * 0.5, rect.height * 0.5];
    const normalizedCenter = [
      zooming_center[0] - rect.x,
      zooming_center[1] - rect.y
    ];
    const center = this.convertCanvasToOffset(normalizedCenter);
    this.scale = value;
    if (roundToScaleOne && Math.abs(this.scale - 1) < 0.01) this.scale = 1;
    const new_center = this.convertCanvasToOffset(normalizedCenter);
    const delta_offset = [
      new_center[0] - center[0],
      new_center[1] - center[1]
    ];
    this.offset[0] += delta_offset[0];
    this.offset[1] += delta_offset[1];
    this.onredraw?.(this);
  }
  changeDeltaScale(value, zooming_center) {
    this.changeScale(this.scale * value, zooming_center);
  }
  /**
   * Fits the view to the specified bounds.
   * @param bounds The bounds to fit the view to, defined by a rectangle.
   */
  fitToBounds(bounds, { zoom = 0.75 } = {}) {
    const cw = this.element.width / window.devicePixelRatio;
    const ch = this.element.height / window.devicePixelRatio;
    let targetScale = this.scale;
    if (zoom > 0) {
      const targetScaleX = zoom * cw / Math.max(bounds[2], 300);
      const targetScaleY = zoom * ch / Math.max(bounds[3], 300);
      targetScale = Math.min(targetScaleX, targetScaleY, this.max_scale);
    }
    const scaledWidth = cw / targetScale;
    const scaledHeight = ch / targetScale;
    const targetX = -bounds[0] - bounds[2] * 0.5 + scaledWidth * 0.5;
    const targetY = -bounds[1] - bounds[3] * 0.5 + scaledHeight * 0.5;
    this.offset[0] = targetX;
    this.offset[1] = targetY;
    this.scale = targetScale;
  }
  /**
   * Starts an animation to fit the view around the specified selection of nodes.
   * @param bounds The bounds to animate the view to, defined by a rectangle.
   */
  animateToBounds(bounds, setDirty, {
    duration = 350,
    zoom = 0.75,
    easing = EaseFunction.EASE_IN_OUT_QUAD
  } = {}) {
    if (!(duration > 0)) throw new RangeError("Duration must be greater than 0");
    const easeFunctions = {
      linear: /* @__PURE__ */ __name((t2) => t2, "linear"),
      easeInQuad: /* @__PURE__ */ __name((t2) => t2 * t2, "easeInQuad"),
      easeOutQuad: /* @__PURE__ */ __name((t2) => t2 * (2 - t2), "easeOutQuad"),
      easeInOutQuad: /* @__PURE__ */ __name((t2) => t2 < 0.5 ? 2 * t2 * t2 : -1 + (4 - 2 * t2) * t2, "easeInOutQuad")
    };
    const easeFunction = easeFunctions[easing] ?? easeFunctions.linear;
    const startTimestamp = performance.now();
    const cw = this.element.width / window.devicePixelRatio;
    const ch = this.element.height / window.devicePixelRatio;
    const startX = this.offset[0];
    const startY = this.offset[1];
    const startX2 = startX - cw / this.scale;
    const startY2 = startY - ch / this.scale;
    const startScale = this.scale;
    let targetScale = startScale;
    if (zoom > 0) {
      const targetScaleX = zoom * cw / Math.max(bounds[2], 300);
      const targetScaleY = zoom * ch / Math.max(bounds[3], 300);
      targetScale = Math.min(targetScaleX, targetScaleY, this.max_scale);
    }
    const scaledWidth = cw / targetScale;
    const scaledHeight = ch / targetScale;
    const targetX = -bounds[0] - bounds[2] * 0.5 + scaledWidth * 0.5;
    const targetY = -bounds[1] - bounds[3] * 0.5 + scaledHeight * 0.5;
    const targetX2 = targetX - scaledWidth;
    const targetY2 = targetY - scaledHeight;
    const animate = /* @__PURE__ */ __name((timestamp2) => {
      const elapsed = timestamp2 - startTimestamp;
      const progress = Math.min(elapsed / duration, 1);
      const easedProgress = easeFunction(progress);
      const currentX = startX + (targetX - startX) * easedProgress;
      const currentY = startY + (targetY - startY) * easedProgress;
      this.offset[0] = currentX;
      this.offset[1] = currentY;
      if (zoom > 0) {
        const currentX2 = startX2 + (targetX2 - startX2) * easedProgress;
        const currentY2 = startY2 + (targetY2 - startY2) * easedProgress;
        const currentWidth = Math.abs(currentX2 - currentX);
        const currentHeight = Math.abs(currentY2 - currentY);
        this.scale = Math.min(cw / currentWidth, ch / currentHeight);
      }
      setDirty();
      if (progress < 1) {
        animationId = requestAnimationFrame(animate);
      } else {
        cancelAnimationFrame(animationId);
      }
    }, "animate");
    let animationId = requestAnimationFrame(animate);
  }
  reset() {
    this.scale = 1;
    this.offset[0] = 0;
    this.offset[1] = 0;
  }
}
const ELLIPSIS = "…";
const TWO_DOT_LEADER = "‥";
const ONE_DOT_LEADER = "․";
var SlotType = /* @__PURE__ */ ((SlotType2) => {
  SlotType2["Array"] = "array";
  SlotType2[SlotType2["Event"] = -1] = "Event";
  return SlotType2;
})(SlotType || {});
var SlotShape = ((SlotShape2) => {
  SlotShape2[SlotShape2["Box"] = RenderShape.BOX] = "Box";
  SlotShape2[SlotShape2["Arrow"] = RenderShape.ARROW] = "Arrow";
  SlotShape2[SlotShape2["Grid"] = RenderShape.GRID] = "Grid";
  SlotShape2[SlotShape2["Circle"] = RenderShape.CIRCLE] = "Circle";
  SlotShape2[SlotShape2["HollowCircle"] = RenderShape.HollowCircle] = "HollowCircle";
  return SlotShape2;
})(SlotShape || {});
var SlotDirection = ((SlotDirection2) => {
  SlotDirection2[SlotDirection2["Up"] = LinkDirection.UP] = "Up";
  SlotDirection2[SlotDirection2["Right"] = LinkDirection.RIGHT] = "Right";
  SlotDirection2[SlotDirection2["Down"] = LinkDirection.DOWN] = "Down";
  SlotDirection2[SlotDirection2["Left"] = LinkDirection.LEFT] = "Left";
  return SlotDirection2;
})(SlotDirection || {});
var LabelPosition = /* @__PURE__ */ ((LabelPosition2) => {
  LabelPosition2["Left"] = "left";
  LabelPosition2["Right"] = "right";
  return LabelPosition2;
})(LabelPosition || {});
function strokeShape(ctx, area, {
  shape = RenderShape.BOX,
  round_radius,
  title_height,
  title_mode = TitleMode.NORMAL_TITLE,
  color: color2,
  padding = 6,
  collapsed = false,
  lineWidth: thickness = 1
} = {}) {
  round_radius ??= LiteGraph.ROUND_RADIUS;
  color2 ??= LiteGraph.NODE_BOX_OUTLINE_COLOR;
  if (title_mode === TitleMode.TRANSPARENT_TITLE) {
    const height2 = title_height ?? LiteGraph.NODE_TITLE_HEIGHT;
    area[1] -= height2;
    area[3] += height2;
  }
  const { lineWidth, strokeStyle } = ctx;
  ctx.lineWidth = thickness;
  ctx.globalAlpha = 0.8;
  ctx.strokeStyle = color2;
  ctx.beginPath();
  const [x2, y2, width2, height] = area;
  switch (shape) {
    case RenderShape.BOX: {
      ctx.rect(
        x2 - padding,
        y2 - padding,
        width2 + 2 * padding,
        height + 2 * padding
      );
      break;
    }
    case RenderShape.ROUND:
    case RenderShape.CARD: {
      const radius = round_radius + padding;
      const isCollapsed = shape === RenderShape.CARD && collapsed;
      const cornerRadii = isCollapsed || shape === RenderShape.ROUND ? [radius] : [radius, 2, radius, 2];
      ctx.roundRect(
        x2 - padding,
        y2 - padding,
        width2 + 2 * padding,
        height + 2 * padding,
        cornerRadii
      );
      break;
    }
    case RenderShape.CIRCLE: {
      const centerX = x2 + width2 / 2;
      const centerY = y2 + height / 2;
      const radius = Math.max(width2, height) / 2 + padding;
      ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
      break;
    }
  }
  ctx.stroke();
  ctx.lineWidth = lineWidth;
  ctx.strokeStyle = strokeStyle;
  ctx.globalAlpha = 1;
}
__name(strokeShape, "strokeShape");
function truncateTextToWidth(ctx, text2, maxWidth) {
  if (!(maxWidth > 0)) return "";
  const fullWidth = ctx.measureText(text2).width;
  if (fullWidth <= maxWidth) return text2;
  const ellipsisWidth = ctx.measureText(ELLIPSIS).width * 0.75;
  if (ellipsisWidth > maxWidth) {
    const twoDotsWidth = ctx.measureText(TWO_DOT_LEADER).width * 0.75;
    if (twoDotsWidth < maxWidth) return TWO_DOT_LEADER;
    const oneDotWidth = ctx.measureText(ONE_DOT_LEADER).width * 0.75;
    return oneDotWidth < maxWidth ? ONE_DOT_LEADER : "";
  }
  let min = 0;
  let max = text2.length;
  let bestLen = 0;
  while (min <= max) {
    const mid = Math.floor((min + max) * 0.5);
    if (mid === 0) {
      min = mid + 1;
      continue;
    }
    const sub = text2.substring(0, mid);
    const currentWidth = ctx.measureText(sub).width + ellipsisWidth;
    if (currentWidth <= maxWidth) {
      bestLen = mid;
      min = mid + 1;
    } else {
      max = mid - 1;
    }
  }
  return bestLen === 0 ? ELLIPSIS : text2.substring(0, bestLen) + ELLIPSIS;
}
__name(truncateTextToWidth, "truncateTextToWidth");
function drawTextInArea({ ctx, text: text2, area, align = "left" }) {
  const { left, right, bottom, width: width2, centreX } = area;
  const fullWidth = ctx.measureText(text2).width;
  if (fullWidth <= width2) {
    ctx.textAlign = align;
    const x2 = align === "left" ? left : align === "right" ? right : centreX;
    ctx.fillText(text2, x2, bottom);
    return;
  }
  const truncated = truncateTextToWidth(ctx, text2, width2);
  if (truncated.length === 0) return;
  ctx.textAlign = "left";
  ctx.fillText(truncated.slice(0, -1), left, bottom);
  ctx.rect(left, bottom, width2, 1);
  ctx.textAlign = "right";
  const ellipsis = truncated.at(-1);
  ctx.fillText(ellipsis, right, bottom, ctx.measureText(ellipsis).width * 0.75);
}
__name(drawTextInArea, "drawTextInArea");
const zeroUuid = "00000000-0000-0000-0000-000000000000";
const randomStorage = new Uint32Array(31);
function createUuidv4() {
  if (typeof crypto?.randomUUID === "function") return crypto.randomUUID();
  if (typeof crypto?.getRandomValues === "function") {
    const random = crypto.getRandomValues(randomStorage);
    let i2 = 0;
    return "10000000-1000-4000-8000-100000000000".replaceAll(/[018]/g, (a2) => (Number(a2) ^ random[i2++] * 3725290298461914e-24 >> Number(a2) * 0.25).toString(16));
  }
  return "10000000-1000-4000-8000-100000000000".replaceAll(/[018]/g, (a2) => (Number(a2) ^ Math.random() * 16 >> Number(a2) * 0.25).toString(16));
}
__name(createUuidv4, "createUuidv4");
class CustomEventTarget extends EventTarget {
  static {
    __name(this, "CustomEventTarget");
  }
  dispatch(type, detail) {
    const event = new CustomEvent(type, { detail, cancelable: true });
    return super.dispatchEvent(event);
  }
  addEventListener(type, listener, options2) {
    super.addEventListener(type, listener, options2);
  }
  removeEventListener(type, listener, options2) {
    super.removeEventListener(type, listener, options2);
  }
  /** @deprecated Use {@link dispatch}. */
  dispatchEvent(event) {
    return super.dispatchEvent(event);
  }
}
class LLink {
  static {
    __name(this, "LLink");
  }
  /** Link ID */
  id;
  parentId;
  type;
  /** Output node ID */
  origin_id;
  /** Output slot index */
  origin_slot;
  /** Input node ID */
  target_id;
  /** Input slot index */
  target_slot;
  data;
  _data;
  /** Centre point of the link, calculated during render only - can be inaccurate */
  _pos;
  /** @todo Clean up - never implemented in comfy. */
  _last_time;
  /** The last canvas 2D path that was used to render this link */
  path;
  /** @inheritdoc */
  _centreAngle;
  /** @inheritdoc */
  _dragging;
  #color;
  /** Custom colour for this link only */
  get color() {
    return this.#color;
  }
  set color(value) {
    this.#color = value === "" ? null : value;
  }
  get isFloatingOutput() {
    return this.origin_id === -1 && this.origin_slot === -1;
  }
  get isFloatingInput() {
    return this.target_id === -1 && this.target_slot === -1;
  }
  get isFloating() {
    return this.isFloatingOutput || this.isFloatingInput;
  }
  constructor(id2, type, origin_id, origin_slot, target_id, target_slot, parentId) {
    this.id = id2;
    this.type = type;
    this.origin_id = origin_id;
    this.origin_slot = origin_slot;
    this.target_id = target_id;
    this.target_slot = target_slot;
    this.parentId = parentId;
    this._data = null;
    this._pos = new Float32Array(2);
  }
  /** @deprecated Use {@link LLink.create} */
  static createFromArray(data) {
    return new LLink(data[0], data[5], data[1], data[2], data[3], data[4]);
  }
  /**
   * LLink static factory: creates a new LLink from the provided data.
   * @param data Serialised LLink data to create the link from
   * @returns A new LLink
   */
  static create(data) {
    return new LLink(
      data.id,
      data.type,
      data.origin_id,
      data.origin_slot,
      data.target_id,
      data.target_slot,
      data.parentId
    );
  }
  /**
   * Gets all reroutes from the output slot to this segment.  If this segment is a reroute, it will not be included.
   * @returns An ordered array of all reroutes from the node output to
   * this reroute or the reroute before it.  Otherwise, an empty array.
   */
  static getReroutes(network, linkSegment) {
    if (!linkSegment.parentId) return [];
    return network.reroutes.get(linkSegment.parentId)?.getReroutes() ?? [];
  }
  static getFirstReroute(network, linkSegment) {
    return LLink.getReroutes(network, linkSegment).at(0);
  }
  /**
   * Finds the reroute in the chain after the provided reroute ID.
   * @param network The network this link belongs to
   * @param linkSegment The starting point of the search (input side).
   * Typically the LLink object itself, but can be any link segment.
   * @param rerouteId The matching reroute will have this set as its {@link parentId}.
   * @returns The reroute that was found, `undefined` if no reroute was found, or `null` if an infinite loop was detected.
   */
  static findNextReroute(network, linkSegment, rerouteId) {
    if (!linkSegment.parentId) return;
    return network.reroutes.get(linkSegment.parentId)?.findNextReroute(rerouteId);
  }
  /**
   * Gets the origin node of a link.
   * @param network The network to search
   * @param linkId The ID of the link to get the origin node of
   * @returns The origin node of the link, or `undefined` if the link is not found or the origin node is not found
   */
  static getOriginNode(network, linkId) {
    const id2 = network.links.get(linkId)?.origin_id;
    return network.getNodeById(id2) ?? void 0;
  }
  /**
   * Gets the target node of a link.
   * @param network The network to search
   * @param linkId The ID of the link to get the target node of
   * @returns The target node of the link, or `undefined` if the link is not found or the target node is not found
   */
  static getTargetNode(network, linkId) {
    const id2 = network.links.get(linkId)?.target_id;
    return network.getNodeById(id2) ?? void 0;
  }
  /**
   * Resolves a link ID to the link, node, and slot objects.
   * @param linkId The {@link id} of the link to resolve
   * @param network The link network to search
   * @returns An object containing the input and output nodes, as well as the input and output slots.
   * @remarks This method is heavier than others; it will always resolve all objects.
   * Whilst the performance difference should in most cases be negligible,
   * it is recommended to use simpler methods where appropriate.
   */
  static resolve(linkId, network) {
    return network.getLink(linkId)?.resolve(network);
  }
  /**
   * Resolves a list of link IDs to the link, node, and slot objects.
   * Discards invalid link IDs.
   * @param linkIds An iterable of link {@link id}s to resolve
   * @param network The link network to search
   * @returns An array of resolved connections.  If a link is not found, it is not included in the array.
   * @see {@link LLink.resolve}
   */
  static resolveMany(linkIds, network) {
    const resolved = [];
    for (const id2 of linkIds) {
      const r2 = network.getLink(id2)?.resolve(network);
      if (r2) resolved.push(r2);
    }
    return resolved;
  }
  /**
   * Resolves the primitive ID values stored in the link to the referenced objects.
   * @param network The link network to search
   * @returns An object containing the input and output nodes, as well as the input and output slots.
   * @remarks This method is heavier than others; it will always resolve all objects.
   * Whilst the performance difference should in most cases be negligible,
   * it is recommended to use simpler methods where appropriate.
   */
  resolve(network) {
    const inputNode = this.target_id === -1 ? void 0 : network.getNodeById(this.target_id) ?? void 0;
    const outputNode = this.origin_id === -1 ? void 0 : network.getNodeById(this.origin_id) ?? void 0;
    const input = inputNode?.inputs[this.target_slot];
    const output = outputNode?.outputs[this.origin_slot];
    return { inputNode, outputNode, input, output, link: this };
  }
  configure(o2) {
    if (Array.isArray(o2)) {
      this.id = o2[0];
      this.origin_id = o2[1];
      this.origin_slot = o2[2];
      this.target_id = o2[3];
      this.target_slot = o2[4];
      this.type = o2[5];
    } else {
      this.id = o2.id;
      this.type = o2.type;
      this.origin_id = o2.origin_id;
      this.origin_slot = o2.origin_slot;
      this.target_id = o2.target_id;
      this.target_slot = o2.target_slot;
      this.parentId = o2.parentId;
    }
  }
  /**
   * Checks if the specified node id and output index are this link's origin (output side).
   * @param nodeId ID of the node to check
   * @param outputIndex The array index of the node output
   * @returns `true` if the origin matches, otherwise `false`.
   */
  hasOrigin(nodeId, outputIndex) {
    return this.origin_id === nodeId && this.origin_slot === outputIndex;
  }
  /**
   * Checks if the specified node id and input index are this link's target (input side).
   * @param nodeId ID of the node to check
   * @param inputIndex The array index of the node input
   * @returns `true` if the target matches, otherwise `false`.
   */
  hasTarget(nodeId, inputIndex) {
    return this.target_id === nodeId && this.target_slot === inputIndex;
  }
  /**
   * Creates a floating link from this link.
   * @param slotType The side of the link that is still connected
   * @param parentId The parent reroute ID of the link
   * @returns A new LLink that is floating
   */
  toFloating(slotType, parentId) {
    const exported = this.asSerialisable();
    exported.id = -1;
    exported.parentId = parentId;
    if (slotType === "input") {
      exported.origin_id = -1;
      exported.origin_slot = -1;
    } else {
      exported.target_id = -1;
      exported.target_slot = -1;
    }
    return LLink.create(exported);
  }
  /**
   * Disconnects a link and removes it from the graph, cleaning up any reroutes that are no longer used
   * @param network The container (LGraph) where reroutes should be updated
   * @param keepReroutes If `undefined`, reroutes will be automatically removed if no links remain.
   * If `input` or `output`, reroutes will not be automatically removed, and retain a connection to the input or output, respectively.
   */
  disconnect(network, keepReroutes) {
    const reroutes = LLink.getReroutes(network, this);
    const lastReroute = reroutes.at(-1);
    const outputFloating = keepReroutes === "output" && lastReroute?.linkIds.size === 1 && lastReroute.floatingLinkIds.size === 0;
    if (outputFloating || keepReroutes === "input" && lastReroute) {
      const newLink = LLink.create(this);
      newLink.id = -1;
      if (keepReroutes === "input") {
        newLink.origin_id = -1;
        newLink.origin_slot = -1;
        lastReroute.floating = { slotType: "input" };
      } else {
        newLink.target_id = -1;
        newLink.target_slot = -1;
        lastReroute.floating = { slotType: "output" };
      }
      network.addFloatingLink(newLink);
    }
    for (const reroute of reroutes) {
      reroute.linkIds.delete(this.id);
      if (!keepReroutes && !reroute.totalLinks) {
        network.reroutes.delete(reroute.id);
      }
    }
    network.links.delete(this.id);
  }
  /**
   * @deprecated Prefer {@link LLink.asSerialisable} (returns an object, not an array)
   * @returns An array representing this LLink
   */
  serialize() {
    return [
      this.id,
      this.origin_id,
      this.origin_slot,
      this.target_id,
      this.target_slot,
      this.type
    ];
  }
  asSerialisable() {
    const copy2 = {
      id: this.id,
      origin_id: this.origin_id,
      origin_slot: this.origin_slot,
      target_id: this.target_id,
      target_slot: this.target_slot,
      type: this.type
    };
    if (this.parentId) copy2.parentId = this.parentId;
    return copy2;
  }
}
class FloatingRenderLink {
  static {
    __name(this, "FloatingRenderLink");
  }
  constructor(network, link2, toType, fromReroute, dragDirection = LinkDirection.CENTER) {
    this.network = network;
    this.link = link2;
    this.toType = toType;
    this.fromReroute = fromReroute;
    this.dragDirection = dragDirection;
    const {
      origin_id: outputNodeId,
      target_id: inputNodeId,
      origin_slot: outputIndex,
      target_slot: inputIndex
    } = link2;
    if (outputNodeId !== -1) {
      const outputNode = network.getNodeById(outputNodeId) ?? void 0;
      if (!outputNode) throw new Error(`Creating DraggingRenderLink for link [${link2.id}] failed: Output node [${outputNodeId}] not found.`);
      const outputSlot = outputNode?.outputs.at(outputIndex);
      if (!outputSlot) throw new Error(`Creating DraggingRenderLink for link [${link2.id}] failed: Output slot [${outputIndex}] not found.`);
      this.outputNodeId = outputNodeId;
      this.outputNode = outputNode;
      this.outputSlot = outputSlot;
      this.outputIndex = outputIndex;
      this.outputPos = outputNode.getOutputPos(outputIndex);
      this.node = outputNode;
      this.fromSlot = outputSlot;
      this.fromPos = fromReroute?.pos ?? this.outputPos;
      this.fromDirection = LinkDirection.LEFT;
      this.dragDirection = LinkDirection.RIGHT;
      this.fromSlotIndex = outputIndex;
    } else {
      const inputNode = network.getNodeById(inputNodeId) ?? void 0;
      if (!inputNode) throw new Error(`Creating DraggingRenderLink for link [${link2.id}] failed: Input node [${inputNodeId}] not found.`);
      const inputSlot = inputNode?.inputs.at(inputIndex);
      if (!inputSlot) throw new Error(`Creating DraggingRenderLink for link [${link2.id}] failed: Input slot [${inputIndex}] not found.`);
      this.inputNodeId = inputNodeId;
      this.inputNode = inputNode;
      this.inputSlot = inputSlot;
      this.inputIndex = inputIndex;
      this.inputPos = inputNode.getInputPos(inputIndex);
      this.node = inputNode;
      this.fromSlot = inputSlot;
      this.fromDirection = LinkDirection.RIGHT;
      this.fromSlotIndex = inputIndex;
    }
    this.fromPos = fromReroute.pos;
  }
  node;
  fromSlot;
  fromPos;
  fromDirection;
  fromSlotIndex;
  outputNodeId = -1;
  outputNode;
  outputSlot;
  outputIndex = -1;
  outputPos;
  inputNodeId = -1;
  inputNode;
  inputSlot;
  inputIndex = -1;
  inputPos;
  canConnectToInput() {
    return this.toType === "input";
  }
  canConnectToOutput() {
    return this.toType === "output";
  }
  canConnectToReroute(reroute) {
    if (this.toType === "input") {
      if (reroute.origin_id === this.inputNode?.id) return false;
    } else {
      if (reroute.origin_id === this.outputNode?.id) return false;
    }
    return true;
  }
  connectToInput(node2, input, _events) {
    const floatingLink = this.link;
    floatingLink.target_id = node2.id;
    floatingLink.target_slot = node2.inputs.indexOf(input);
    node2.disconnectInput(node2.inputs.indexOf(input));
    this.fromSlot._floatingLinks?.delete(floatingLink);
    input._floatingLinks ??= /* @__PURE__ */ new Set();
    input._floatingLinks.add(floatingLink);
  }
  connectToOutput(node2, output, _events) {
    const floatingLink = this.link;
    floatingLink.origin_id = node2.id;
    floatingLink.origin_slot = node2.outputs.indexOf(output);
    this.fromSlot._floatingLinks?.delete(floatingLink);
    output._floatingLinks ??= /* @__PURE__ */ new Set();
    output._floatingLinks.add(floatingLink);
  }
  connectToRerouteInput(reroute, { node: inputNode, input }, events2) {
    const floatingLink = this.link;
    floatingLink.target_id = inputNode.id;
    floatingLink.target_slot = inputNode.inputs.indexOf(input);
    this.fromSlot._floatingLinks?.delete(floatingLink);
    input._floatingLinks ??= /* @__PURE__ */ new Set();
    input._floatingLinks.add(floatingLink);
    events2.dispatch("input-moved", this);
  }
  connectToRerouteOutput(reroute, outputNode, output, events2) {
    const floatingLink = this.link;
    floatingLink.origin_id = outputNode.id;
    floatingLink.origin_slot = outputNode.outputs.indexOf(output);
    this.fromSlot._floatingLinks?.delete(floatingLink);
    output._floatingLinks ??= /* @__PURE__ */ new Set();
    output._floatingLinks.add(floatingLink);
    events2.dispatch("output-moved", this);
  }
}
class MovingLinkBase {
  static {
    __name(this, "MovingLinkBase");
  }
  constructor(network, link2, toType, fromReroute, dragDirection = LinkDirection.CENTER) {
    this.network = network;
    this.link = link2;
    this.toType = toType;
    this.fromReroute = fromReroute;
    this.dragDirection = dragDirection;
    const {
      origin_id: outputNodeId,
      target_id: inputNodeId,
      origin_slot: outputIndex,
      target_slot: inputIndex
    } = link2;
    const outputNode = network.getNodeById(outputNodeId) ?? void 0;
    if (!outputNode) throw new Error(`Creating MovingRenderLink for link [${link2.id}] failed: Output node [${outputNodeId}] not found.`);
    const outputSlot = outputNode.outputs.at(outputIndex);
    if (!outputSlot) throw new Error(`Creating MovingRenderLink for link [${link2.id}] failed: Output slot [${outputIndex}] not found.`);
    this.outputNodeId = outputNodeId;
    this.outputNode = outputNode;
    this.outputSlot = outputSlot;
    this.outputIndex = outputIndex;
    this.outputPos = outputNode.getOutputPos(outputIndex);
    const inputNode = network.getNodeById(inputNodeId) ?? void 0;
    if (!inputNode) throw new Error(`Creating DraggingRenderLink for link [${link2.id}] failed: Input node [${inputNodeId}] not found.`);
    const inputSlot = inputNode.inputs.at(inputIndex);
    if (!inputSlot) throw new Error(`Creating DraggingRenderLink for link [${link2.id}] failed: Input slot [${inputIndex}] not found.`);
    this.inputNodeId = inputNodeId;
    this.inputNode = inputNode;
    this.inputSlot = inputSlot;
    this.inputIndex = inputIndex;
    this.inputPos = inputNode.getInputPos(inputIndex);
  }
  outputNodeId;
  outputNode;
  outputSlot;
  outputIndex;
  outputPos;
  inputNodeId;
  inputNode;
  inputSlot;
  inputIndex;
  inputPos;
}
class MovingInputLink extends MovingLinkBase {
  static {
    __name(this, "MovingInputLink");
  }
  toType = "input";
  node;
  fromSlot;
  fromPos;
  fromDirection;
  fromSlotIndex;
  constructor(network, link2, fromReroute, dragDirection = LinkDirection.CENTER) {
    super(network, link2, "input", fromReroute, dragDirection);
    this.node = this.outputNode;
    this.fromSlot = this.outputSlot;
    this.fromPos = fromReroute?.pos ?? this.outputPos;
    this.fromDirection = LinkDirection.NONE;
    this.fromSlotIndex = this.outputIndex;
  }
  canConnectToInput(inputNode, input) {
    return this.node.canConnectTo(inputNode, input, this.outputSlot);
  }
  canConnectToOutput() {
    return false;
  }
  canConnectToReroute(reroute) {
    return reroute.origin_id !== this.inputNode.id;
  }
  connectToInput(inputNode, input, events2) {
    if (input === this.inputSlot) return;
    this.inputNode.disconnectInput(this.inputIndex, true);
    const link2 = this.outputNode.connectSlots(this.outputSlot, inputNode, input, this.fromReroute?.id);
    if (link2) events2.dispatch("input-moved", this);
    return link2;
  }
  connectToOutput() {
    throw new Error("MovingInputLink cannot connect to an output.");
  }
  connectToRerouteInput(reroute, { node: inputNode, input, link: existingLink }, events2, originalReroutes) {
    const { outputNode, outputSlot, fromReroute } = this;
    for (const reroute2 of originalReroutes) {
      if (reroute2.id === this.link.parentId) break;
      if (reroute2.totalLinks === 1) reroute2.remove();
    }
    reroute.parentId = fromReroute?.id;
    const newLink = outputNode.connectSlots(outputSlot, inputNode, input, existingLink.parentId);
    if (newLink) events2.dispatch("input-moved", this);
  }
  connectToRerouteOutput() {
    throw new Error("MovingInputLink cannot connect to an output.");
  }
  disconnect() {
    return this.inputNode.disconnectInput(this.inputIndex, true);
  }
}
class MovingOutputLink extends MovingLinkBase {
  static {
    __name(this, "MovingOutputLink");
  }
  toType = "output";
  node;
  fromSlot;
  fromPos;
  fromDirection;
  fromSlotIndex;
  constructor(network, link2, fromReroute, dragDirection = LinkDirection.CENTER) {
    super(network, link2, "output", fromReroute, dragDirection);
    this.node = this.inputNode;
    this.fromSlot = this.inputSlot;
    this.fromPos = fromReroute?.pos ?? this.inputPos;
    this.fromDirection = LinkDirection.LEFT;
    this.fromSlotIndex = this.inputIndex;
  }
  canConnectToInput() {
    return false;
  }
  canConnectToOutput(outputNode, output) {
    return outputNode.canConnectTo(this.node, this.inputSlot, output);
  }
  canConnectToReroute(reroute) {
    return reroute.origin_id !== this.outputNode.id;
  }
  connectToInput() {
    throw new Error("MovingOutputLink cannot connect to an input.");
  }
  connectToOutput(outputNode, output, events2) {
    if (output === this.outputSlot) return;
    const link2 = outputNode.connectSlots(output, this.inputNode, this.inputSlot, this.link.parentId);
    if (link2) events2.dispatch("output-moved", this);
    return link2;
  }
  connectToRerouteInput() {
    throw new Error("MovingOutputLink cannot connect to an input.");
  }
  connectToRerouteOutput(reroute, outputNode, output, events2) {
    const { inputNode, inputSlot, fromReroute } = this;
    const floatingTerminus = reroute?.floating?.slotType === "output";
    if (fromReroute) {
      fromReroute.parentId = reroute.id;
    } else {
      this.link.parentId = reroute.id;
    }
    outputNode.connectSlots(output, inputNode, inputSlot, this.link.parentId);
    if (floatingTerminus) reroute.removeAllFloatingLinks();
    events2.dispatch("output-moved", this);
  }
  disconnect() {
    return this.outputNode.disconnectOutput(this.outputIndex, this.inputNode);
  }
}
class ToInputRenderLink {
  static {
    __name(this, "ToInputRenderLink");
  }
  constructor(network, node2, fromSlot, fromReroute, dragDirection = LinkDirection.CENTER) {
    this.network = network;
    this.node = node2;
    this.fromSlot = fromSlot;
    this.fromReroute = fromReroute;
    this.dragDirection = dragDirection;
    const outputIndex = node2.outputs.indexOf(fromSlot);
    if (outputIndex === -1) throw new Error(`Creating render link for node [${this.node.id}] failed: Slot index not found.`);
    this.fromSlotIndex = outputIndex;
    this.fromPos = fromReroute ? fromReroute.pos : this.node.getOutputPos(outputIndex);
  }
  toType = "input";
  fromPos;
  fromSlotIndex;
  fromDirection = LinkDirection.RIGHT;
  canConnectToInput(inputNode, input) {
    return this.node.canConnectTo(inputNode, input, this.fromSlot);
  }
  canConnectToOutput() {
    return false;
  }
  connectToInput(node2, input, events2) {
    const { node: outputNode, fromSlot, fromReroute } = this;
    if (node2 === outputNode) return;
    const newLink = outputNode.connectSlots(fromSlot, node2, input, fromReroute?.id);
    events2.dispatch("link-created", newLink);
  }
  connectToRerouteInput(reroute, {
    node: inputNode,
    input,
    link: link2
  }, events2, originalReroutes) {
    const { node: outputNode, fromSlot, fromReroute } = this;
    const floatingTerminus = fromReroute?.floating?.slotType === "output";
    reroute.parentId = fromReroute?.id;
    const newLink = outputNode.connectSlots(fromSlot, inputNode, input, link2.parentId);
    if (floatingTerminus) fromReroute.removeAllFloatingLinks();
    for (const reroute2 of originalReroutes) {
      if (reroute2.id === fromReroute?.id) break;
      reroute2.removeLink(link2);
      if (reroute2.totalLinks === 0) {
        if (link2.isFloating) {
          reroute2.remove();
        } else {
          const cl = link2.toFloating("output", reroute2.id);
          this.network.addFloatingLink(cl);
          reroute2.floating = { slotType: "output" };
        }
      }
    }
    events2.dispatch("link-created", newLink);
  }
  connectToOutput() {
    throw new Error("ToInputRenderLink cannot connect to an output.");
  }
  connectToRerouteOutput() {
    throw new Error("ToInputRenderLink cannot connect to an output.");
  }
}
class ToOutputRenderLink {
  static {
    __name(this, "ToOutputRenderLink");
  }
  constructor(network, node2, fromSlot, fromReroute, dragDirection = LinkDirection.CENTER) {
    this.network = network;
    this.node = node2;
    this.fromSlot = fromSlot;
    this.fromReroute = fromReroute;
    this.dragDirection = dragDirection;
    const inputIndex = node2.inputs.indexOf(fromSlot);
    if (inputIndex === -1) throw new Error(`Creating render link for node [${this.node.id}] failed: Slot index not found.`);
    this.fromSlotIndex = inputIndex;
    this.fromPos = fromReroute ? fromReroute.pos : this.node.getInputPos(inputIndex);
  }
  toType = "output";
  fromPos;
  fromSlotIndex;
  fromDirection = LinkDirection.LEFT;
  canConnectToInput() {
    return false;
  }
  canConnectToOutput(outputNode, output) {
    return this.node.canConnectTo(outputNode, this.fromSlot, output);
  }
  canConnectToReroute(reroute) {
    if (reroute.origin_id === this.node.id) return false;
    return true;
  }
  connectToOutput(node2, output, events2) {
    const { node: inputNode, fromSlot, fromReroute } = this;
    if (!inputNode) return;
    const newLink = node2.connectSlots(output, inputNode, fromSlot, fromReroute?.id);
    events2.dispatch("link-created", newLink);
  }
  connectToRerouteOutput(reroute, outputNode, output, events2) {
    const { node: inputNode, fromSlot } = this;
    const newLink = outputNode.connectSlots(output, inputNode, fromSlot, reroute?.id);
    events2.dispatch("link-created", newLink);
  }
  connectToInput() {
    throw new Error("ToOutputRenderLink cannot connect to an input.");
  }
  connectToRerouteInput() {
    throw new Error("ToOutputRenderLink cannot connect to an input.");
  }
}
class ToOutputFromRerouteLink extends ToOutputRenderLink {
  static {
    __name(this, "ToOutputFromRerouteLink");
  }
  constructor(network, node2, fromSlot, fromReroute, linkConnector) {
    super(network, node2, fromSlot, fromReroute);
    this.fromReroute = fromReroute;
    this.linkConnector = linkConnector;
  }
  canConnectToReroute() {
    return false;
  }
  connectToOutput(node2, output) {
    const nuRenderLink = new ToInputRenderLink(this.network, node2, output);
    this.linkConnector._connectOutputToReroute(this.fromReroute, nuRenderLink);
  }
}
class LinkConnector {
  static {
    __name(this, "LinkConnector");
  }
  /**
   * Link connection state POJO. Source of truth for state of link drag operations.
   *
   * Can be replaced or proxied to allow notifications.
   * Is always dereferenced at the start of an operation.
   */
  state = {
    connectingTo: void 0,
    multi: false,
    draggingExistingLinks: false,
    snapLinksPos: void 0
  };
  events = new CustomEventTarget();
  /** Contains information for rendering purposes only. */
  renderLinks = [];
  /** Existing links that are being moved **to** a new input slot. */
  inputLinks = [];
  /** Existing links that are being moved **to** a new output slot. */
  outputLinks = [];
  /** Existing floating links that are being moved to a new slot. */
  floatingLinks = [];
  hiddenReroutes = /* @__PURE__ */ new Set();
  /** The widget beneath the pointer, if it is a valid connection target. */
  overWidget;
  /** The type (returned by downstream callback) for {@link overWidget} */
  overWidgetType;
  /** The reroute beneath the pointer, if it is a valid connection target. */
  overReroute;
  #setConnectingLinks;
  constructor(setConnectingLinks) {
    this.#setConnectingLinks = setConnectingLinks;
  }
  get isConnecting() {
    return this.state.connectingTo !== void 0;
  }
  get draggingExistingLinks() {
    return this.state.draggingExistingLinks;
  }
  /** Drag an existing link to a different input. */
  moveInputLink(network, input) {
    if (this.isConnecting) throw new Error("Already dragging links.");
    const { state, inputLinks, renderLinks } = this;
    const linkId = input.link;
    if (linkId == null) {
      const floatingLink = input._floatingLinks?.values().next().value;
      if (floatingLink?.parentId == null) return;
      try {
        const reroute = network.reroutes.get(floatingLink.parentId);
        if (!reroute) throw new Error(`Invalid reroute id: [${floatingLink.parentId}] for floating link id: [${floatingLink.id}].`);
        const renderLink = new FloatingRenderLink(network, floatingLink, "input", reroute);
        const mayContinue = this.events.dispatch("before-move-input", renderLink);
        if (mayContinue === false) return;
        renderLinks.push(renderLink);
      } catch (error2) {
        console.warn(`Could not create render link for link id: [${floatingLink.id}].`, floatingLink, error2);
      }
      floatingLink._dragging = true;
      this.floatingLinks.push(floatingLink);
    } else {
      const link2 = network.links.get(linkId);
      if (!link2) return;
      try {
        const reroute = network.getReroute(link2.parentId);
        const renderLink = new MovingInputLink(network, link2, reroute);
        const mayContinue = this.events.dispatch("before-move-input", renderLink);
        if (mayContinue === false) return;
        renderLinks.push(renderLink);
        this.listenUntilReset("input-moved", (e2) => {
          e2.detail.link.disconnect(network, "output");
        });
      } catch (error2) {
        console.warn(`Could not create render link for link id: [${link2.id}].`, link2, error2);
        return;
      }
      link2._dragging = true;
      inputLinks.push(link2);
    }
    state.connectingTo = "input";
    state.draggingExistingLinks = true;
    this.#setLegacyLinks(false);
  }
  /** Drag all links from an output to a new output. */
  moveOutputLink(network, output) {
    if (this.isConnecting) throw new Error("Already dragging links.");
    const { state, renderLinks } = this;
    if (output._floatingLinks?.size) {
      for (const floatingLink of output._floatingLinks.values()) {
        try {
          const reroute = LLink.getFirstReroute(network, floatingLink);
          if (!reroute) throw new Error(`Invalid reroute id: [${floatingLink.parentId}] for floating link id: [${floatingLink.id}].`);
          const renderLink = new FloatingRenderLink(network, floatingLink, "output", reroute);
          const mayContinue = this.events.dispatch("before-move-output", renderLink);
          if (mayContinue === false) continue;
          renderLinks.push(renderLink);
          this.floatingLinks.push(floatingLink);
        } catch (error2) {
          console.warn(`Could not create render link for link id: [${floatingLink.id}].`, floatingLink, error2);
        }
      }
    }
    if (output.links?.length) {
      for (const linkId of output.links) {
        const link2 = network.links.get(linkId);
        if (!link2) continue;
        const firstReroute = LLink.getFirstReroute(network, link2);
        if (firstReroute) {
          firstReroute._dragging = true;
          this.hiddenReroutes.add(firstReroute);
        } else {
          link2._dragging = true;
        }
        this.outputLinks.push(link2);
        try {
          const renderLink = new MovingOutputLink(network, link2, firstReroute, LinkDirection.RIGHT);
          const mayContinue = this.events.dispatch("before-move-output", renderLink);
          if (mayContinue === false) continue;
          renderLinks.push(renderLink);
        } catch (error2) {
          console.warn(`Could not create render link for link id: [${link2.id}].`, link2, error2);
          continue;
        }
      }
    }
    if (renderLinks.length === 0) return;
    state.draggingExistingLinks = true;
    state.multi = true;
    state.connectingTo = "output";
    this.#setLegacyLinks(true);
  }
  /**
   * Drags a new link from an output slot to an input slot.
   * @param network The network that the link being connected belongs to
   * @param node The node the link is being dragged from
   * @param output The output slot that the link is being dragged from
   */
  dragNewFromOutput(network, node2, output, fromReroute) {
    if (this.isConnecting) throw new Error("Already dragging links.");
    const { state } = this;
    const renderLink = new ToInputRenderLink(network, node2, output, fromReroute);
    this.renderLinks.push(renderLink);
    state.connectingTo = "input";
    this.#setLegacyLinks(false);
  }
  /**
   * Drags a new link from an input slot to an output slot.
   * @param network The network that the link being connected belongs to
   * @param node The node the link is being dragged from
   * @param input The input slot that the link is being dragged from
   */
  dragNewFromInput(network, node2, input, fromReroute) {
    if (this.isConnecting) throw new Error("Already dragging links.");
    const { state } = this;
    const renderLink = new ToOutputRenderLink(network, node2, input, fromReroute);
    this.renderLinks.push(renderLink);
    state.connectingTo = "output";
    this.#setLegacyLinks(true);
  }
  /**
   * Drags a new link from a reroute to an input slot.
   * @param network The network that the link being connected belongs to
   * @param reroute The reroute that the link is being dragged from
   */
  dragFromReroute(network, reroute) {
    if (this.isConnecting) throw new Error("Already dragging links.");
    const link2 = reroute.firstLink ?? reroute.firstFloatingLink;
    if (!link2) {
      console.warn("No link found for reroute.");
      return;
    }
    const outputNode = network.getNodeById(link2.origin_id);
    if (!outputNode) {
      console.warn("No output node found for link.", link2);
      return;
    }
    const outputSlot = outputNode.outputs.at(link2.origin_slot);
    if (!outputSlot) {
      console.warn("No output slot found for link.", link2);
      return;
    }
    const renderLink = new ToInputRenderLink(network, outputNode, outputSlot, reroute);
    renderLink.fromDirection = LinkDirection.NONE;
    this.renderLinks.push(renderLink);
    this.state.connectingTo = "input";
    this.#setLegacyLinks(false);
  }
  /**
   * Drags a new link from a reroute to an output slot.
   * @param network The network that the link being connected belongs to
   * @param reroute The reroute that the link is being dragged from
   */
  dragFromRerouteToOutput(network, reroute) {
    if (this.isConnecting) throw new Error("Already dragging links.");
    const link2 = reroute.firstLink ?? reroute.firstFloatingLink;
    if (!link2) {
      console.warn("No link found for reroute.");
      return;
    }
    const inputNode = network.getNodeById(link2.target_id);
    if (!inputNode) {
      console.warn("No input node found for link.", link2);
      return;
    }
    const inputSlot = inputNode.inputs.at(link2.target_slot);
    if (!inputSlot) {
      console.warn("No input slot found for link.", link2);
      return;
    }
    const renderLink = new ToOutputFromRerouteLink(network, inputNode, inputSlot, reroute, this);
    renderLink.fromDirection = LinkDirection.LEFT;
    this.renderLinks.push(renderLink);
    this.state.connectingTo = "output";
    this.#setLegacyLinks(true);
  }
  dragFromLinkSegment(network, linkSegment) {
    if (this.isConnecting) throw new Error("Already dragging links.");
    const { state } = this;
    if (linkSegment.origin_id == null || linkSegment.origin_slot == null) return;
    const node2 = network.getNodeById(linkSegment.origin_id);
    if (!node2) return;
    const slot = node2.outputs.at(linkSegment.origin_slot);
    if (!slot) return;
    const reroute = network.getReroute(linkSegment.parentId);
    const renderLink = new ToInputRenderLink(network, node2, slot, reroute);
    renderLink.fromDirection = LinkDirection.NONE;
    this.renderLinks.push(renderLink);
    state.connectingTo = "input";
    this.#setLegacyLinks(false);
  }
  /**
   * Connects the links being droppe
   * @param event Contains the drop location, in canvas space
   */
  dropLinks(locator, event) {
    if (!this.isConnecting) {
      console.warn("Attempted to drop links when not connecting to anything.");
      return;
    }
    const { renderLinks } = this;
    const mayContinue = this.events.dispatch("before-drop-links", { renderLinks, event });
    if (mayContinue === false) return;
    const { canvasX, canvasY } = event;
    const node2 = locator.getNodeOnPos(canvasX, canvasY) ?? void 0;
    if (node2) {
      this.dropOnNode(node2, event);
    } else {
      const reroute = locator.getRerouteOnPos(canvasX, canvasY);
      if (reroute && this.isRerouteValidDrop(reroute)) {
        this.dropOnReroute(reroute, event);
      } else {
        this.dropOnNothing(event);
      }
    }
    this.events.dispatch("after-drop-links", { renderLinks, event });
  }
  dropOnNode(node2, event) {
    const { renderLinks, state } = this;
    const { connectingTo } = state;
    const { canvasX, canvasY } = event;
    if (renderLinks.every((link2) => link2.node === node2)) return;
    if (connectingTo === "output") {
      const output = node2.getOutputOnPos([canvasX, canvasY]);
      if (output) {
        this.#dropOnOutput(node2, output);
      } else {
        this.connectToNode(node2, event);
      }
    } else if (connectingTo === "input") {
      const input = node2.getInputOnPos([canvasX, canvasY]);
      const inputOrSocket = input ?? node2.getSlotFromWidget(this.overWidget);
      if (inputOrSocket) {
        this.#dropOnInput(node2, inputOrSocket);
      } else {
        this.connectToNode(node2, event);
      }
    }
  }
  dropOnReroute(reroute, event) {
    const mayContinue = this.events.dispatch("dropped-on-reroute", { reroute, event });
    if (mayContinue === false) return;
    if (this.state.connectingTo === "input") {
      if (this.renderLinks.length !== 1) throw new Error(`Attempted to connect ${this.renderLinks.length} input links to a reroute.`);
      const renderLink = this.renderLinks[0];
      this._connectOutputToReroute(reroute, renderLink);
      return;
    }
    for (const link2 of this.renderLinks) {
      if (link2.toType !== "output") continue;
      const result = reroute.findSourceOutput();
      if (!result) continue;
      const { node: node2, output } = result;
      if (!link2.canConnectToOutput(node2, output)) continue;
      link2.connectToRerouteOutput(reroute, node2, output, this.events);
    }
  }
  /** @internal Temporary workaround - requires refactor. */
  _connectOutputToReroute(reroute, renderLink) {
    const results = reroute.findTargetInputs();
    if (!results?.length) return;
    const maybeReroutes = reroute.getReroutes();
    if (maybeReroutes === null) throw new Error("Reroute loop detected.");
    const originalReroutes = maybeReroutes.slice(0, -1).reverse();
    if (renderLink instanceof ToInputRenderLink) {
      const { node: node2, fromSlot, fromSlotIndex, fromReroute } = renderLink;
      reroute.setFloatingLinkOrigin(node2, fromSlot, fromSlotIndex);
      if (fromReroute != null) {
        for (const originalReroute of originalReroutes) {
          if (originalReroute.id === fromReroute.id) break;
          for (const linkId of reroute.floatingLinkIds) {
            originalReroute.floatingLinkIds.delete(linkId);
          }
        }
      }
    }
    const filtered = results.filter((result) => renderLink.toType === "input" && canConnectInputLinkToReroute(renderLink, result.node, result.input, reroute));
    for (const result of filtered) {
      renderLink.connectToRerouteInput(reroute, result, this.events, originalReroutes);
    }
    return;
  }
  dropOnNothing(event) {
    const mayContinue = this.events.dispatch("dropped-on-canvas", event);
    if (mayContinue === false) return;
    this.disconnectLinks();
  }
  /**
   * Disconnects all moving links.
   * @remarks This is called when the links are dropped on the canvas.
   * May be called by consumers to e.g. drag links into a bin / void.
   */
  disconnectLinks() {
    for (const link2 of this.renderLinks) {
      if (link2 instanceof MovingLinkBase) {
        link2.disconnect();
      }
    }
  }
  /**
   * Connects the links being dropped onto a node to the first matching slot.
   * @param node The node that the links are being dropped on
   * @param event Contains the drop location, in canvas space
   */
  connectToNode(node2, event) {
    const { state: { connectingTo } } = this;
    const mayContinue = this.events.dispatch("dropped-on-node", { node: node2, event });
    if (mayContinue === false) return;
    const firstLink = this.renderLinks[0];
    if (!firstLink) return;
    if (connectingTo === "output") {
      const output = node2.findOutputByType(firstLink.fromSlot.type)?.slot;
      if (!output) {
        console.warn(`Could not find slot for link type: [${firstLink.fromSlot.type}].`);
        return;
      }
      this.#dropOnOutput(node2, output);
    } else if (connectingTo === "input") {
      const input = node2.findInputByType(firstLink.fromSlot.type)?.slot;
      if (!input) {
        console.warn(`Could not find slot for link type: [${firstLink.fromSlot.type}].`);
        return;
      }
      this.#dropOnInput(node2, input);
    }
  }
  #dropOnInput(node2, input) {
    for (const link2 of this.renderLinks) {
      if (!link2.canConnectToInput(node2, input)) continue;
      link2.connectToInput(node2, input, this.events);
    }
  }
  #dropOnOutput(node2, output) {
    for (const link2 of this.renderLinks) {
      if (!link2.canConnectToOutput(node2, output)) {
        if (link2 instanceof MovingOutputLink && link2.link.parentId !== void 0) {
          link2.outputNode.connectSlots(link2.outputSlot, link2.inputNode, link2.inputSlot, void 0);
        }
        continue;
      }
      link2.connectToOutput(node2, output, this.events);
    }
  }
  isInputValidDrop(node2, input) {
    return this.renderLinks.some((link2) => link2.canConnectToInput(node2, input));
  }
  isNodeValidDrop(node2) {
    if (this.state.connectingTo === "output") {
      return node2.outputs.some((output) => this.renderLinks.some((link2) => link2.canConnectToOutput(node2, output)));
    }
    return node2.inputs.some((input) => this.renderLinks.some((link2) => link2.canConnectToInput(node2, input)));
  }
  /**
   * Checks if a reroute is a valid drop target for any of the links being connected.
   * @param reroute The reroute that would be dropped on.
   * @returns `true` if any of the current links being connected are valid for the given reroute.
   */
  isRerouteValidDrop(reroute) {
    if (this.state.connectingTo === "input") {
      const results = reroute.findTargetInputs();
      if (!results?.length) return false;
      for (const { node: node2, input } of results) {
        for (const renderLink of this.renderLinks) {
          if (renderLink.toType !== "input") continue;
          if (canConnectInputLinkToReroute(renderLink, node2, input, reroute)) return true;
        }
      }
    } else {
      const result = reroute.findSourceOutput();
      if (!result) return false;
      const { node: node2, output } = result;
      for (const renderLink of this.renderLinks) {
        if (renderLink.toType !== "output") continue;
        if (!renderLink.canConnectToReroute(reroute)) continue;
        if (renderLink.canConnectToOutput(node2, output)) return true;
      }
    }
    return false;
  }
  /** Sets connecting_links, used by some extensions still. */
  #setLegacyLinks(fromSlotIsInput) {
    const links = this.renderLinks.map((link2) => {
      const input = fromSlotIsInput ? link2.fromSlot : null;
      const output = fromSlotIsInput ? null : link2.fromSlot;
      const afterRerouteId = link2 instanceof MovingLinkBase ? link2.link?.parentId : link2.fromReroute?.id;
      return {
        node: link2.node,
        slot: link2.fromSlotIndex,
        input,
        output,
        pos: link2.fromPos,
        afterRerouteId
      };
    });
    this.#setConnectingLinks(links);
  }
  /**
   * Exports the current state of the link connector.
   * @param network The network that the links being connected belong to.
   * @returns A POJO with the state of the link connector, links being connected, and their network.
   * @remarks Other than {@link network}, all properties are shallow cloned.
   */
  export(network) {
    return {
      renderLinks: [...this.renderLinks],
      inputLinks: [...this.inputLinks],
      outputLinks: [...this.outputLinks],
      floatingLinks: [...this.floatingLinks],
      state: { ...this.state },
      network
    };
  }
  /**
   * Adds an event listener that will be automatically removed when the reset event is fired.
   * @param eventName The event to listen for.
   * @param listener The listener to call when the event is fired.
   */
  listenUntilReset(eventName, listener, options2) {
    this.events.addEventListener(eventName, listener, options2);
    this.events.addEventListener("reset", () => this.events.removeEventListener(eventName, listener), { once: true });
  }
  /**
   * Resets everything to its initial state.
   *
   * Effectively cancels moving or connecting links.
   */
  reset(force = false) {
    const mayContinue = this.events.dispatch("reset", force);
    if (mayContinue === false) return;
    const { state, outputLinks, inputLinks, hiddenReroutes, renderLinks, floatingLinks } = this;
    if (!force && state.connectingTo === void 0) return;
    state.connectingTo = void 0;
    for (const link2 of outputLinks) delete link2._dragging;
    for (const link2 of inputLinks) delete link2._dragging;
    for (const link2 of floatingLinks) delete link2._dragging;
    for (const reroute of hiddenReroutes) delete reroute._dragging;
    renderLinks.length = 0;
    inputLinks.length = 0;
    outputLinks.length = 0;
    floatingLinks.length = 0;
    hiddenReroutes.clear();
    state.multi = false;
    state.draggingExistingLinks = false;
    state.snapLinksPos = void 0;
  }
}
function canConnectInputLinkToReroute(link2, inputNode, input, reroute) {
  const { fromReroute } = link2;
  if (!link2.canConnectToInput(inputNode, input) || // Would result in no change
  fromReroute?.id === reroute.id || // Cannot connect from child to parent reroute
  fromReroute?.getReroutes()?.includes(reroute)) {
    return false;
  }
  if (link2 instanceof ToInputRenderLink) {
    if (reroute.parentId == null) {
      if (reroute.firstLink?.hasOrigin(link2.node.id, link2.fromSlotIndex)) return false;
    } else if (link2.fromReroute?.id === reroute.parentId) {
      return false;
    }
  }
  return true;
}
__name(canConnectInputLinkToReroute, "canConnectInputLinkToReroute");
function getNodeInputOnPos(node2, x2, y2) {
  const { inputs } = node2;
  if (!inputs) return;
  for (const [index2, input] of inputs.entries()) {
    const pos = node2.getInputPos(index2);
    const nameLength = input.label?.length ?? input.localized_name?.length ?? input.name?.length;
    const width2 = 20 + (nameLength || 3) * 7;
    if (isInRectangle(
      x2,
      y2,
      pos[0] - 10,
      pos[1] - 10,
      width2,
      20
    )) {
      return { index: index2, input, pos };
    }
  }
}
__name(getNodeInputOnPos, "getNodeInputOnPos");
function getNodeOutputOnPos(node2, x2, y2) {
  const { outputs } = node2;
  if (!outputs) return;
  for (const [index2, output] of outputs.entries()) {
    const pos = node2.getOutputPos(index2);
    if (isInRectangle(
      x2,
      y2,
      pos[0] - 10,
      pos[1] - 10,
      40,
      20
    )) {
      return { index: index2, output, pos };
    }
  }
}
__name(getNodeOutputOnPos, "getNodeOutputOnPos");
function isOverNodeInput(node2, canvasx, canvasy, slot_pos) {
  const result = getNodeInputOnPos(node2, canvasx, canvasy);
  if (!result) return -1;
  if (slot_pos) {
    slot_pos[0] = result.pos[0];
    slot_pos[1] = result.pos[1];
  }
  return result.index;
}
__name(isOverNodeInput, "isOverNodeInput");
function isOverNodeOutput(node2, canvasx, canvasy, slot_pos) {
  const result = getNodeOutputOnPos(node2, canvasx, canvasy);
  if (!result) return -1;
  if (slot_pos) {
    slot_pos[0] = result.pos[0];
    slot_pos[1] = result.pos[1];
  }
  return result.index;
}
__name(isOverNodeOutput, "isOverNodeOutput");
class CanvasPointer {
  static {
    __name(this, "CanvasPointer");
  }
  /** Maximum time in milliseconds to ignore click drift */
  static bufferTime = 150;
  /** Maximum gap between pointerup and pointerdown events to be considered as a double click */
  static doubleClickTime = 300;
  /** Maximum offset from click location */
  static get maxClickDrift() {
    return this.#maxClickDrift;
  }
  static set maxClickDrift(value) {
    this.#maxClickDrift = value;
    this.#maxClickDrift2 = value * value;
  }
  static #maxClickDrift = 6;
  /** {@link maxClickDrift} squared.  Used to calculate click drift without `sqrt`. */
  static #maxClickDrift2 = this.#maxClickDrift ** 2;
  /** The element this PointerState should capture input against when dragging. */
  element;
  /** Pointer ID used by drag capture. */
  pointerId;
  /** Set to true when if the pointer moves far enough after a down event, before the corresponding up event is fired. */
  dragStarted = false;
  /** The {@link eUp} from the last successful click */
  eLastDown;
  /** Used downstream for touch event support. */
  isDouble = false;
  /** Used downstream for touch event support. */
  isDown = false;
  /**
   * If `true`, {@link eDown}, {@link eMove}, and {@link eUp} will be set to
   * `undefined` when {@link reset} is called.
   *
   * Default: `true`
   */
  clearEventsOnReset = true;
  /** The last pointerdown event for the primary button */
  eDown;
  /** The last pointermove event for the primary button */
  eMove;
  /** The last pointerup event for the primary button */
  eUp;
  /**
   * Run-once callback, called at the end of any click or drag, whether or not it was successful in any way.
   *
   * The setter of this callback will call the existing value before replacing it.
   * Therefore, simply setting this value twice will execute the first callback.
   */
  get finally() {
    return this.#finally;
  }
  set finally(value) {
    try {
      this.#finally?.();
    } finally {
      this.#finally = value;
    }
  }
  #finally;
  constructor(element) {
    this.element = element;
  }
  /**
   * Callback for `pointerdown` events.  To be used as the event handler (or called by it).
   * @param e The `pointerdown` event
   */
  down(e2) {
    this.reset();
    this.eDown = e2;
    this.pointerId = e2.pointerId;
    this.element.setPointerCapture(e2.pointerId);
  }
  /**
   * Callback for `pointermove` events.  To be used as the event handler (or called by it).
   * @param e The `pointermove` event
   */
  move(e2) {
    const { eDown } = this;
    if (!eDown) return;
    if (!e2.buttons) {
      this.reset();
      return;
    }
    if (!(e2.buttons & eDown.buttons)) {
      this.#completeClick(e2);
      this.reset();
      return;
    }
    this.eMove = e2;
    this.onDrag?.(e2);
    if (this.dragStarted) return;
    const longerThanBufferTime = e2.timeStamp - eDown.timeStamp > CanvasPointer.bufferTime;
    if (longerThanBufferTime || !this.#hasSamePosition(e2, eDown)) {
      this.#setDragStarted(e2);
    }
  }
  /**
   * Callback for `pointerup` events.  To be used as the event handler (or called by it).
   * @param e The `pointerup` event
   */
  up(e2) {
    if (e2.button !== this.eDown?.button) return false;
    this.#completeClick(e2);
    const { dragStarted } = this;
    this.reset();
    return !dragStarted;
  }
  #completeClick(e2) {
    const { eDown } = this;
    if (!eDown) return;
    this.eUp = e2;
    if (this.dragStarted) {
      this.onDragEnd?.(e2);
    } else if (!this.#hasSamePosition(e2, eDown)) {
      this.#setDragStarted();
      this.onDragEnd?.(e2);
    } else if (this.onDoubleClick && this.#isDoubleClick()) {
      this.onDoubleClick(e2);
      this.eLastDown = void 0;
    } else {
      this.onClick?.(e2);
      this.eLastDown = eDown;
    }
  }
  /**
   * Checks if two events occurred near each other - not further apart than the maximum click drift.
   * @param a The first event to compare
   * @param b The second event to compare
   * @param tolerance2 The maximum distance (squared) before the positions are considered different
   * @returns `true` if the two events were no more than {@link maxClickDrift} apart, otherwise `false`
   */
  #hasSamePosition(a2, b2, tolerance2 = CanvasPointer.#maxClickDrift2) {
    const drift = dist2(a2.clientX, a2.clientY, b2.clientX, b2.clientY);
    return drift <= tolerance2;
  }
  /**
   * Checks whether the pointer is currently past the max click drift threshold.
   * @returns `true` if the latest pointer event is past the the click drift threshold
   */
  #isDoubleClick() {
    const { eDown, eLastDown } = this;
    if (!eDown || !eLastDown) return false;
    const tolerance2 = (3 * CanvasPointer.#maxClickDrift) ** 2;
    const diff2 = eDown.timeStamp - eLastDown.timeStamp;
    return diff2 > 0 && diff2 < CanvasPointer.doubleClickTime && this.#hasSamePosition(eDown, eLastDown, tolerance2);
  }
  #setDragStarted(eMove) {
    this.dragStarted = true;
    this.onDragStart?.(this, eMove);
    delete this.onDragStart;
  }
  /**
   * Resets the state of this {@link CanvasPointer} instance.
   *
   * The {@link finally} callback is first executed, then all callbacks and intra-click
   * state is cleared.
   */
  reset() {
    this.finally = void 0;
    delete this.onClick;
    delete this.onDoubleClick;
    delete this.onDragStart;
    delete this.onDrag;
    delete this.onDragEnd;
    this.isDown = false;
    this.isDouble = false;
    this.dragStarted = false;
    if (this.clearEventsOnReset) {
      this.eDown = void 0;
      this.eMove = void 0;
      this.eUp = void 0;
    }
    const { element, pointerId } = this;
    this.pointerId = void 0;
    if (typeof pointerId === "number" && element.hasPointerCapture(pointerId)) {
      element.releasePointerCapture(pointerId);
    }
  }
}
class NullGraphError extends Error {
  static {
    __name(this, "NullGraphError");
  }
  constructor(message = "Attempted to access LGraph reference that was null or undefined.", cause) {
    super(message, { cause });
    this.name = "NullGraphError";
  }
}
class LGraphIcon {
  static {
    __name(this, "LGraphIcon");
  }
  unicode;
  fontFamily;
  color;
  bgColor;
  fontSize;
  circlePadding;
  xOffset;
  yOffset;
  constructor({
    unicode,
    fontFamily = "PrimeIcons",
    color: color2 = "#e6c200",
    bgColor,
    fontSize = 16,
    circlePadding = 2,
    xOffset = 0,
    yOffset = 0
  }) {
    this.unicode = unicode;
    this.fontFamily = fontFamily;
    this.color = color2;
    this.bgColor = bgColor;
    this.fontSize = fontSize;
    this.circlePadding = circlePadding;
    this.xOffset = xOffset;
    this.yOffset = yOffset;
  }
  draw(ctx, x2, y2) {
    x2 += this.xOffset;
    y2 += this.yOffset;
    const { font, textBaseline, textAlign, fillStyle } = ctx;
    ctx.font = `${this.fontSize}px '${this.fontFamily}'`;
    ctx.textBaseline = "middle";
    ctx.textAlign = "center";
    const iconRadius = this.fontSize / 2 + this.circlePadding;
    if (this.bgColor) {
      ctx.beginPath();
      ctx.arc(x2 + iconRadius, y2, iconRadius, 0, 2 * Math.PI);
      ctx.fillStyle = this.bgColor;
      ctx.fill();
    }
    ctx.fillStyle = this.color;
    ctx.fillText(this.unicode, x2 + iconRadius, y2);
    ctx.font = font;
    ctx.textBaseline = textBaseline;
    ctx.textAlign = textAlign;
    ctx.fillStyle = fillStyle;
  }
}
var BadgePosition = /* @__PURE__ */ ((BadgePosition2) => {
  BadgePosition2["TopLeft"] = "top-left";
  BadgePosition2["TopRight"] = "top-right";
  return BadgePosition2;
})(BadgePosition || {});
class LGraphBadge {
  static {
    __name(this, "LGraphBadge");
  }
  text;
  fgColor;
  bgColor;
  fontSize;
  padding;
  height;
  cornerRadius;
  icon;
  xOffset;
  yOffset;
  constructor({
    text: text2,
    fgColor = "white",
    bgColor = "#0F1F0F",
    fontSize = 12,
    padding = 6,
    height = 20,
    cornerRadius = 5,
    iconOptions,
    xOffset = 0,
    yOffset = 0
  }) {
    this.text = text2;
    this.fgColor = fgColor;
    this.bgColor = bgColor;
    this.fontSize = fontSize;
    this.padding = padding;
    this.height = height;
    this.cornerRadius = cornerRadius;
    if (iconOptions) {
      this.icon = new LGraphIcon(iconOptions);
    }
    this.xOffset = xOffset;
    this.yOffset = yOffset;
  }
  get visible() {
    return this.text.length > 0 || !!this.icon;
  }
  getWidth(ctx) {
    if (!this.visible) return 0;
    const { font } = ctx;
    let iconWidth = 0;
    if (this.icon) {
      ctx.font = `${this.icon.fontSize}px '${this.icon.fontFamily}'`;
      iconWidth = ctx.measureText(this.icon.unicode).width + this.padding;
    }
    ctx.font = `${this.fontSize}px sans-serif`;
    const textWidth = this.text ? ctx.measureText(this.text).width : 0;
    ctx.font = font;
    return iconWidth + textWidth + this.padding * 2;
  }
  draw(ctx, x2, y2) {
    if (!this.visible) return;
    x2 += this.xOffset;
    y2 += this.yOffset;
    const { font, fillStyle, textBaseline, textAlign } = ctx;
    ctx.font = `${this.fontSize}px sans-serif`;
    const badgeWidth = this.getWidth(ctx);
    const badgeX = 0;
    ctx.fillStyle = this.bgColor;
    ctx.beginPath();
    if (ctx.roundRect) {
      ctx.roundRect(x2 + badgeX, y2, badgeWidth, this.height, this.cornerRadius);
    } else {
      ctx.rect(x2 + badgeX, y2, badgeWidth, this.height);
    }
    ctx.fill();
    let drawX = x2 + badgeX + this.padding;
    const centerY = y2 + this.height / 2;
    if (this.icon) {
      this.icon.draw(ctx, drawX, centerY);
      drawX += this.icon.fontSize + this.padding / 2 + 4;
    }
    if (this.text) {
      ctx.fillStyle = this.fgColor;
      ctx.textBaseline = "middle";
      ctx.textAlign = "left";
      ctx.fillText(this.text, drawX, centerY + 1);
    }
    ctx.font = font;
    ctx.fillStyle = fillStyle;
    ctx.textBaseline = textBaseline;
    ctx.textAlign = textAlign;
  }
}
class SlotBase {
  static {
    __name(this, "SlotBase");
  }
  name;
  localized_name;
  label;
  type;
  dir;
  removable;
  shape;
  color_off;
  color_on;
  locked;
  nameLocked;
  widget;
  _floatingLinks;
  hasErrors;
  boundingRect;
  constructor(name2, type, boundingRect) {
    this.name = name2;
    this.type = type;
    this.boundingRect = boundingRect;
  }
  renderingColor(colorContext) {
    return this.isConnected ? this.color_on || colorContext.getConnectedColor(this.type) : this.color_off || colorContext.getDisconnectedColor(this.type);
  }
}
class NodeSlot extends SlotBase {
  static {
    __name(this, "NodeSlot");
  }
  pos;
  /** The offset from the parent node to the centre point of this slot. */
  get #centreOffset() {
    const nodePos = this.node.pos;
    const { boundingRect } = this;
    const diameter = boundingRect[3];
    return getCentre([
      boundingRect[0] - nodePos[0],
      boundingRect[1] - nodePos[1],
      diameter,
      diameter
    ]);
  }
  #node;
  get node() {
    return this.#node;
  }
  get highlightColor() {
    return LiteGraph.NODE_TEXT_HIGHLIGHT_COLOR ?? LiteGraph.NODE_SELECTED_TITLE_COLOR ?? LiteGraph.NODE_TEXT_COLOR;
  }
  constructor(slot, node2) {
    super(slot.name, slot.type, slot.boundingRect ?? [0, 0, 0, 0]);
    Object.assign(this, slot);
    this.#node = node2;
  }
  /**
   * The label to display in the UI.
   */
  get renderingLabel() {
    return this.label || this.localized_name || this.name || "";
  }
  draw(ctx, {
    colorContext,
    labelPosition = LabelPosition.Right,
    lowQuality = false,
    highlight = false,
    doStroke = false
  }) {
    const originalFillStyle = ctx.fillStyle;
    const originalStrokeStyle = ctx.strokeStyle;
    const originalLineWidth = ctx.lineWidth;
    const labelColor = highlight ? this.highlightColor : LiteGraph.NODE_TEXT_COLOR;
    const pos = this.#centreOffset;
    const slot_type = this.type;
    const slot_shape = slot_type === SlotType.Array ? SlotShape.Grid : this.shape;
    ctx.beginPath();
    let doFill = true;
    ctx.fillStyle = this.renderingColor(colorContext);
    ctx.lineWidth = 1;
    if (slot_type === SlotType.Event || slot_shape === SlotShape.Box) {
      ctx.rect(pos[0] - 6 + 0.5, pos[1] - 5 + 0.5, 14, 10);
    } else if (slot_shape === SlotShape.Arrow) {
      ctx.moveTo(pos[0] + 8, pos[1] + 0.5);
      ctx.lineTo(pos[0] - 4, pos[1] + 6 + 0.5);
      ctx.lineTo(pos[0] - 4, pos[1] - 6 + 0.5);
      ctx.closePath();
    } else if (slot_shape === SlotShape.Grid) {
      const gridSize = 3;
      const cellSize = 2;
      const spacing = 3;
      for (let x2 = 0; x2 < gridSize; x2++) {
        for (let y2 = 0; y2 < gridSize; y2++) {
          ctx.rect(
            pos[0] - 4 + x2 * spacing,
            pos[1] - 4 + y2 * spacing,
            cellSize,
            cellSize
          );
        }
      }
      doStroke = false;
    } else {
      if (lowQuality) {
        ctx.rect(pos[0] - 4, pos[1] - 4, 8, 8);
      } else {
        let radius;
        if (slot_shape === SlotShape.HollowCircle) {
          doFill = false;
          doStroke = true;
          ctx.lineWidth = 3;
          ctx.strokeStyle = ctx.fillStyle;
          radius = highlight ? 4 : 3;
        } else {
          radius = highlight ? 5 : 4;
        }
        ctx.arc(pos[0], pos[1], radius, 0, Math.PI * 2);
      }
    }
    if (doFill) ctx.fill();
    if (!lowQuality && doStroke) ctx.stroke();
    const hideLabel = lowQuality || this.isWidgetInputSlot;
    if (!hideLabel) {
      const text2 = this.renderingLabel;
      if (text2) {
        ctx.fillStyle = labelColor;
        if (labelPosition === LabelPosition.Right) {
          if (this.dir == LinkDirection.UP) {
            ctx.fillText(text2, pos[0], pos[1] - 10);
          } else {
            ctx.fillText(text2, pos[0] + 10, pos[1] + 5);
          }
        } else {
          if (this.dir == LinkDirection.DOWN) {
            ctx.fillText(text2, pos[0], pos[1] - 8);
          } else {
            ctx.fillText(text2, pos[0] - 10, pos[1] + 5);
          }
        }
      }
    }
    if (this.hasErrors) {
      ctx.lineWidth = 2;
      ctx.strokeStyle = "red";
      ctx.beginPath();
      ctx.arc(pos[0], pos[1], 12, 0, Math.PI * 2);
      ctx.stroke();
    }
    ctx.fillStyle = originalFillStyle;
    ctx.strokeStyle = originalStrokeStyle;
    ctx.lineWidth = originalLineWidth;
  }
  drawCollapsed(ctx) {
    const [x2, y2] = this.collapsedPos;
    const { fillStyle } = ctx;
    ctx.fillStyle = "#686";
    ctx.beginPath();
    if (this.type === SlotType.Event || this.shape === RenderShape.BOX) {
      ctx.rect(x2 - 7 + 0.5, y2 - 4, 14, 8);
    } else if (this.shape === RenderShape.ARROW) {
      const isInput = this instanceof NodeInputSlot;
      if (isInput) {
        ctx.moveTo(x2 + 8, y2);
        ctx.lineTo(x2 - 4, y2 - 4);
        ctx.lineTo(x2 - 4, y2 + 4);
      } else {
        ctx.moveTo(x2 + 6, y2);
        ctx.lineTo(x2 - 6, y2 - 4);
        ctx.lineTo(x2 - 6, y2 + 4);
      }
      ctx.closePath();
    } else {
      ctx.arc(x2, y2, 4, 0, Math.PI * 2);
    }
    ctx.fill();
    ctx.fillStyle = fillStyle;
  }
}
class NodeInputSlot extends NodeSlot {
  static {
    __name(this, "NodeInputSlot");
  }
  link;
  get isWidgetInputSlot() {
    return !!this.widget;
  }
  get collapsedPos() {
    return [0, LiteGraph.NODE_TITLE_HEIGHT * -0.5];
  }
  constructor(slot, node2) {
    super(slot, node2);
    this.link = slot.link;
  }
  get isConnected() {
    return this.link != null;
  }
  isValidTarget(fromSlot) {
    return "links" in fromSlot && LiteGraph.isValidConnection(this.type, fromSlot.type);
  }
  draw(ctx, options2) {
    const { textAlign } = ctx;
    ctx.textAlign = "left";
    super.draw(ctx, {
      ...options2,
      labelPosition: LabelPosition.Right,
      doStroke: false
    });
    ctx.textAlign = textAlign;
  }
}
class NodeOutputSlot extends NodeSlot {
  static {
    __name(this, "NodeOutputSlot");
  }
  #node;
  links;
  _data;
  slot_index;
  get isWidgetInputSlot() {
    return false;
  }
  get collapsedPos() {
    return [
      this.#node._collapsed_width ?? LiteGraph.NODE_COLLAPSED_WIDTH,
      LiteGraph.NODE_TITLE_HEIGHT * -0.5
    ];
  }
  constructor(slot, node2) {
    super(slot, node2);
    this.links = slot.links;
    this._data = slot._data;
    this.slot_index = slot.slot_index;
    this.#node = node2;
  }
  isValidTarget(fromSlot) {
    return "link" in fromSlot && LiteGraph.isValidConnection(this.type, fromSlot.type);
  }
  get isConnected() {
    return this.links != null && this.links.length > 0;
  }
  draw(ctx, options2) {
    const { textAlign, strokeStyle } = ctx;
    ctx.textAlign = "right";
    ctx.strokeStyle = "black";
    super.draw(ctx, {
      ...options2,
      labelPosition: LabelPosition.Left,
      doStroke: true
    });
    ctx.textAlign = textAlign;
    ctx.strokeStyle = strokeStyle;
  }
}
function shallowCloneCommonProps(slot) {
  const { color_off, color_on, dir, label, localized_name, locked, name: name2, nameLocked, removable, shape, type } = slot;
  return { color_off, color_on, dir, label, localized_name, locked, name: name2, nameLocked, removable, shape, type };
}
__name(shallowCloneCommonProps, "shallowCloneCommonProps");
function inputAsSerialisable(slot) {
  const { link: link2 } = slot;
  const widgetOrPos = slot.widget ? { widget: { name: slot.widget.name } } : { pos: slot.pos };
  return {
    ...shallowCloneCommonProps(slot),
    ...widgetOrPos,
    link: link2
  };
}
__name(inputAsSerialisable, "inputAsSerialisable");
function outputAsSerialisable(slot) {
  const { pos, slot_index, links, widget } = slot;
  const outputWidget = widget ? { widget: { name: widget.name } } : null;
  return {
    ...shallowCloneCommonProps(slot),
    ...outputWidget,
    pos,
    slot_index,
    links
  };
}
__name(outputAsSerialisable, "outputAsSerialisable");
function isINodeInputSlot(slot) {
  return "link" in slot;
}
__name(isINodeInputSlot, "isINodeInputSlot");
function isWidgetInputSlot(slot) {
  return !!slot.widget;
}
__name(isWidgetInputSlot, "isWidgetInputSlot");
function stringOrEmpty(value) {
  return value == null ? "" : String(value);
}
__name(stringOrEmpty, "stringOrEmpty");
function parseSlotTypes(type) {
  return type == "" || type == "0" ? ["*"] : String(type).toLowerCase().split(",");
}
__name(parseSlotTypes, "parseSlotTypes");
function getAllNestedItems(items) {
  const allItems = /* @__PURE__ */ new Set();
  if (items) {
    for (const item of items) addRecursively(item, allItems);
  }
  return allItems;
  function addRecursively(item, flatSet) {
    if (flatSet.has(item) || item.pinned) return;
    flatSet.add(item);
    if (item.children) {
      for (const child2 of item.children) addRecursively(child2, flatSet);
    }
  }
  __name(addRecursively, "addRecursively");
}
__name(getAllNestedItems, "getAllNestedItems");
function findFirstNode(items) {
  for (const item of items) {
    if (item instanceof LGraphNode) return item;
  }
}
__name(findFirstNode, "findFirstNode");
function findFreeSlotOfType(slots, type) {
  if (!slots?.length) return;
  let occupiedSlot;
  let wildSlot;
  let occupiedWildSlot;
  const validTypes = parseSlotTypes(type);
  for (const [index2, slot] of slots.entries()) {
    const slotTypes = parseSlotTypes(slot.type);
    for (const validType of validTypes) {
      for (const slotType of slotTypes) {
        if (slotType === validType) {
          if (slot.link == null && !slot.links?.length) {
            return { index: index2, slot };
          }
          occupiedSlot ??= { index: index2, slot };
        } else if (!wildSlot && (validType === "*" || slotType === "*")) {
          if (slot.link == null && !slot.links?.length) {
            wildSlot = { index: index2, slot };
          } else {
            occupiedWildSlot ??= { index: index2, slot };
          }
        }
      }
    }
  }
  return wildSlot ?? occupiedSlot ?? occupiedWildSlot;
}
__name(findFreeSlotOfType, "findFreeSlotOfType");
function distributeSpace(totalSpace, requests) {
  if (requests.length === 0) return [];
  const totalMinSize = requests.reduce((sum2, req) => sum2 + req.minSize, 0);
  if (totalSpace < totalMinSize) {
    return requests.map((req) => req.minSize);
  }
  let allocations = requests.map((req) => ({
    computedSize: req.minSize,
    maxSize: req.maxSize ?? Infinity,
    remaining: (req.maxSize ?? Infinity) - req.minSize
  }));
  let remainingSpace = totalSpace - totalMinSize;
  while (remainingSpace > 0 && allocations.some((alloc) => alloc.remaining > 0)) {
    const growableItems = allocations.filter(
      (alloc) => alloc.remaining > 0
    ).length;
    if (growableItems === 0) break;
    const sharePerItem = remainingSpace / growableItems;
    let spaceUsedThisRound = 0;
    allocations = allocations.map((alloc) => {
      if (alloc.remaining <= 0) return alloc;
      const growth = Math.min(sharePerItem, alloc.remaining);
      spaceUsedThisRound += growth;
      return {
        ...alloc,
        computedSize: alloc.computedSize + growth,
        remaining: alloc.remaining - growth
      };
    });
    remainingSpace -= spaceUsedThisRound;
    if (spaceUsedThisRound === 0) break;
  }
  return allocations.map(({ computedSize }) => computedSize);
}
__name(distributeSpace, "distributeSpace");
function toClass(cls, ...args) {
  return args[0] instanceof cls ? args[0] : new cls(...args);
}
__name(toClass, "toClass");
function isColorable(obj) {
  return typeof obj === "object" && obj !== null && "setColorOption" in obj && "getColorOption" in obj;
}
__name(isColorable, "isColorable");
class Rectangle extends Float64Array {
  static {
    __name(this, "Rectangle");
  }
  #pos;
  #size;
  constructor(x2 = 0, y2 = 0, width2 = 0, height = 0) {
    super(4);
    this[0] = x2;
    this[1] = y2;
    this[2] = width2;
    this[3] = height;
  }
  subarray(begin = 0, end) {
    const byteOffset = begin << 3;
    const length = end === void 0 ? end : end - begin;
    return new Float64Array(this.buffer, byteOffset, length);
  }
  /**
   * A reference to the position of the top-left corner of this rectangle.
   *
   * Updating the values of the returned object will update this rectangle.
   */
  get pos() {
    this.#pos ??= this.subarray(0, 2);
    return this.#pos;
  }
  set pos(value) {
    this[0] = value[0];
    this[1] = value[1];
  }
  /**
   * A reference to the size of this rectangle.
   *
   * Updating the values of the returned object will update this rectangle.
   */
  get size() {
    this.#size ??= this.subarray(2, 4);
    return this.#size;
  }
  set size(value) {
    this[2] = value[0];
    this[3] = value[1];
  }
  // #region Property accessors
  /** The x co-ordinate of the top-left corner of this rectangle. */
  get x() {
    return this[0];
  }
  set x(value) {
    this[0] = value;
  }
  /** The y co-ordinate of the top-left corner of this rectangle. */
  get y() {
    return this[1];
  }
  set y(value) {
    this[1] = value;
  }
  /** The width of this rectangle. */
  get width() {
    return this[2];
  }
  set width(value) {
    this[2] = value;
  }
  /** The height of this rectangle. */
  get height() {
    return this[3];
  }
  set height(value) {
    this[3] = value;
  }
  /** The x co-ordinate of the left edge of this rectangle. */
  get left() {
    return this[0];
  }
  set left(value) {
    this[0] = value;
  }
  /** The y co-ordinate of the top edge of this rectangle. */
  get top() {
    return this[1];
  }
  set top(value) {
    this[1] = value;
  }
  /** The x co-ordinate of the right edge of this rectangle. */
  get right() {
    return this[0] + this[2];
  }
  set right(value) {
    this[0] = value - this[2];
  }
  /** The y co-ordinate of the bottom edge of this rectangle. */
  get bottom() {
    return this[1] + this[3];
  }
  set bottom(value) {
    this[1] = value - this[3];
  }
  /** The x co-ordinate of the centre of this rectangle. */
  get centreX() {
    return this[0] + this[2] * 0.5;
  }
  /** The y co-ordinate of the centre of this rectangle. */
  get centreY() {
    return this[1] + this[3] * 0.5;
  }
  // #endregion Property accessors
  /**
   * Updates the rectangle to the values of {@link rect}.
   * @param rect The rectangle to update to.
   */
  updateTo(rect) {
    this[0] = rect[0];
    this[1] = rect[1];
    this[2] = rect[2];
    this[3] = rect[3];
  }
  /**
   * Checks if the point [{@link x}, {@link y}] is inside this rectangle.
   * @param x The x-coordinate to check
   * @param y The y-coordinate to check
   * @returns `true` if the point is inside this rectangle, otherwise `false`.
   */
  containsXy(x2, y2) {
    const { x: left, y: top, width: width2, height } = this;
    return left <= x2 && top <= y2 && left + width2 >= x2 && top + height >= y2;
  }
  /**
   * Checks if {@link point} is inside this rectangle.
   * @param point The point to check
   * @returns `true` if {@link point} is inside this rectangle, otherwise `false`.
   */
  containsPoint(point) {
    return this.x <= point[0] && this.y <= point[1] && this.x + this.width >= point[0] && this.y + this.height >= point[1];
  }
  /**
   * Checks if {@link rect} is inside this rectangle.
   * @param rect The rectangle to check
   * @returns `true` if {@link rect} is inside this rectangle, otherwise `false`.
   */
  containsRect(rect) {
    return this.x <= rect[0] && this.y <= rect[1] && this.x + this.width >= rect[0] + rect[2] && this.y + this.height >= rect[1] + rect[3];
  }
  /**
   * Checks if {@link rect} overlaps with this rectangle.
   * @param rect The rectangle to check
   * @returns `true` if {@link rect} overlaps with this rectangle, otherwise `false`.
   */
  overlaps(rect) {
    return this.x < rect[0] + rect[2] && this.y < rect[1] + rect[3] && this.x + this.width > rect[0] && this.y + this.height > rect[1];
  }
  /** @returns The centre point of this rectangle, as a new {@link Point}. */
  getCentre() {
    return [this.centreX, this.centreY];
  }
  /** @returns The area of this rectangle. */
  getArea() {
    return this.width * this.height;
  }
  /** @returns The perimeter of this rectangle. */
  getPerimeter() {
    return 2 * (this.width + this.height);
  }
  /** @returns The top-left corner of this rectangle, as a new {@link Point}. */
  getTopLeft() {
    return [this[0], this[1]];
  }
  /** @returns The bottom-right corner of this rectangle, as a new {@link Point}. */
  getBottomRight() {
    return [this.right, this.bottom];
  }
  /** @returns The width and height of this rectangle, as a new {@link Size}. */
  getSize() {
    return [this[2], this[3]];
  }
  /** @returns The offset from the top-left of this rectangle to the point [{@link x}, {@link y}], as a new {@link Point}. */
  getOffsetTo([x2, y2]) {
    return [x2 - this[0], y2 - this[1]];
  }
  /** @returns The offset from the point [{@link x}, {@link y}] to the top-left of this rectangle, as a new {@link Point}. */
  getOffsetFrom([x2, y2]) {
    return [this[0] - x2, this[1] - y2];
  }
  /** Sets the width without moving the right edge (changes position) */
  setWidthRightAnchored(width2) {
    const currentWidth = this[2];
    this[2] = width2;
    this[0] += currentWidth - width2;
  }
  /** Sets the height without moving the bottom edge (changes position) */
  setHeightBottomAnchored(height) {
    const currentHeight = this[3];
    this[3] = height;
    this[1] += currentHeight - height;
  }
  /** Alias of {@link export}. */
  toArray() {
    return this.export();
  }
  /** @returns A new, untyped array (serializable) containing the values of this rectangle. */
  export() {
    return [this[0], this[1], this[2], this[3]];
  }
  /** Draws a debug outline of this rectangle. */
  _drawDebug(ctx, colour = "red") {
    const { strokeStyle, lineWidth } = ctx;
    try {
      ctx.strokeStyle = colour;
      ctx.lineWidth = 0.5;
      ctx.beginPath();
      ctx.strokeRect(this[0], this[1], this[2], this[3]);
    } finally {
      ctx.strokeStyle = strokeStyle;
      ctx.lineWidth = lineWidth;
    }
  }
}
class BaseWidget {
  static {
    __name(this, "BaseWidget");
  }
  /** From node edge to widget edge */
  static margin = 15;
  /** From widget edge to tip of arrow button */
  static arrowMargin = 6;
  /** Arrow button width */
  static arrowWidth = 10;
  /** Absolute minimum display width of widget values */
  static minValueWidth = 42;
  /** Minimum gap between label and value */
  static labelValueGap = 5;
  #node;
  /** The node that this widget belongs to. */
  get node() {
    return this.#node;
  }
  linkedWidgets;
  name;
  options;
  label;
  type;
  y = 0;
  last_y;
  width;
  disabled;
  computedDisabled;
  hidden;
  advanced;
  tooltip;
  element;
  #value;
  get value() {
    return this.#value;
  }
  set value(value) {
    this.#value = value;
  }
  constructor(widget, node2) {
    this.#node = node2 ?? widget.node;
    this.name = widget.name;
    this.options = widget.options;
    this.type = widget.type;
    const { node: _2, outline_color, background_color, height, text_color, secondary_text_color, disabledTextColor, displayName, displayValue, labelBaseline, ...safeValues } = widget;
    Object.assign(this, safeValues);
  }
  get outline_color() {
    return this.advanced ? LiteGraph.WIDGET_ADVANCED_OUTLINE_COLOR : LiteGraph.WIDGET_OUTLINE_COLOR;
  }
  get background_color() {
    return LiteGraph.WIDGET_BGCOLOR;
  }
  get height() {
    return LiteGraph.NODE_WIDGET_HEIGHT;
  }
  get text_color() {
    return LiteGraph.WIDGET_TEXT_COLOR;
  }
  get secondary_text_color() {
    return LiteGraph.WIDGET_SECONDARY_TEXT_COLOR;
  }
  get disabledTextColor() {
    return LiteGraph.WIDGET_DISABLED_TEXT_COLOR;
  }
  get displayName() {
    return this.label || this.name;
  }
  // TODO: Resolve this workaround. Ref: https://github.com/Comfy-Org/litegraph.js/issues/1022
  get _displayValue() {
    return String(this.value);
  }
  get labelBaseline() {
    return this.y + this.height * 0.7;
  }
  /**
   * Draws the standard widget shape - elongated capsule. The path of the widget shape is not
   * cleared, and may be used for further drawing.
   * @param ctx The canvas context
   * @param options The options for drawing the widget
   * @remarks Leaves {@link ctx} dirty.
   */
  drawWidgetShape(ctx, { width: width2, showText }) {
    const { height, y: y2 } = this;
    const { margin } = BaseWidget;
    ctx.textAlign = "left";
    ctx.strokeStyle = this.outline_color;
    ctx.fillStyle = this.background_color;
    ctx.beginPath();
    if (showText) {
      ctx.roundRect(margin, y2, width2 - margin * 2, height, [height * 0.5]);
    } else {
      ctx.rect(margin, y2, width2 - margin * 2, height);
    }
    ctx.fill();
    if (showText && !this.computedDisabled) ctx.stroke();
  }
  /**
   * A shared routine for drawing a label and value as text, truncated
   * if they exceed the available width.
   */
  drawTruncatingText({
    ctx,
    width: width2,
    leftPadding = 5,
    rightPadding = 20
  }) {
    const { height, y: y2 } = this;
    const { margin } = BaseWidget;
    const { displayName, _displayValue } = this;
    const labelWidth = ctx.measureText(displayName).width;
    const valueWidth = ctx.measureText(_displayValue).width;
    const gap = BaseWidget.labelValueGap;
    const x2 = margin * 2 + leftPadding;
    const totalWidth = width2 - x2 - 2 * margin - rightPadding;
    const requiredWidth = labelWidth + gap + valueWidth;
    const area = new Rectangle(x2, y2, totalWidth, height * 0.7);
    ctx.fillStyle = this.secondary_text_color;
    if (requiredWidth <= totalWidth) {
      drawTextInArea({ ctx, text: displayName, area, align: "left" });
    } else if (LiteGraph.truncateWidgetTextEvenly) {
      const scale = (totalWidth - gap) / (requiredWidth - gap);
      area.width = labelWidth * scale;
      drawTextInArea({ ctx, text: displayName, area, align: "left" });
      area.right = x2 + totalWidth;
      area.setWidthRightAnchored(valueWidth * scale);
    } else if (LiteGraph.truncateWidgetValuesFirst) {
      const cappedLabelWidth = Math.min(labelWidth, totalWidth);
      area.width = cappedLabelWidth;
      drawTextInArea({ ctx, text: displayName, area, align: "left" });
      area.right = x2 + totalWidth;
      area.setWidthRightAnchored(Math.max(totalWidth - gap - cappedLabelWidth, 0));
    } else {
      const cappedValueWidth = Math.min(valueWidth, totalWidth);
      area.width = Math.max(totalWidth - gap - cappedValueWidth, 0);
      drawTextInArea({ ctx, text: displayName, area, align: "left" });
      area.right = x2 + totalWidth;
      area.setWidthRightAnchored(cappedValueWidth);
    }
    ctx.fillStyle = this.text_color;
    drawTextInArea({ ctx, text: _displayValue, area, align: "right" });
  }
  /**
   * Sets the value of the widget
   * @param value The value to set
   * @param options The options for setting the value
   */
  setValue(value, { e: e2, node: node2, canvas: canvas2 }) {
    const oldValue = this.value;
    if (value === this.value) return;
    const v2 = this.type === "number" ? Number(value) : value;
    this.value = v2;
    if (this.options?.property && node2.properties[this.options.property] !== void 0) {
      node2.setProperty(this.options.property, v2);
    }
    const pos = canvas2.graph_mouse;
    this.callback?.(this.value, canvas2, node2, pos, e2);
    node2.onWidgetChanged?.(this.name ?? "", v2, oldValue, this);
    if (node2.graph) node2.graph._version++;
  }
}
let BooleanWidget$1 = class BooleanWidget2 extends BaseWidget {
  static {
    __name(this, "BooleanWidget");
  }
  type = "toggle";
  drawWidget(ctx, {
    width: width2,
    showText = true
  }) {
    const { height, y: y2 } = this;
    const { margin } = BaseWidget;
    this.drawWidgetShape(ctx, { width: width2, showText });
    ctx.fillStyle = this.value ? "#89A" : "#333";
    ctx.beginPath();
    ctx.arc(
      width2 - margin * 2,
      y2 + height * 0.5,
      height * 0.36,
      0,
      Math.PI * 2
    );
    ctx.fill();
    if (showText) {
      this.drawLabel(ctx, margin * 2);
      this.drawValue(ctx, width2 - 40);
    }
  }
  drawLabel(ctx, x2) {
    ctx.fillStyle = this.secondary_text_color;
    const { displayName } = this;
    if (displayName) ctx.fillText(displayName, x2, this.labelBaseline);
  }
  drawValue(ctx, x2) {
    ctx.fillStyle = this.value ? this.text_color : this.secondary_text_color;
    ctx.textAlign = "right";
    const value = this.value ? this.options.on || "true" : this.options.off || "false";
    ctx.fillText(value, x2, this.labelBaseline);
  }
  onClick(options2) {
    this.setValue(!this.value, options2);
  }
};
class ButtonWidget extends BaseWidget {
  static {
    __name(this, "ButtonWidget");
  }
  type = "button";
  clicked;
  constructor(widget, node2) {
    super(widget, node2);
    this.clicked ??= false;
  }
  /**
   * Draws the widget
   * @param ctx The canvas context
   * @param options The options for drawing the widget
   */
  drawWidget(ctx, {
    width: width2,
    showText = true
  }) {
    const { fillStyle, strokeStyle, textAlign } = ctx;
    const { height, y: y2 } = this;
    const { margin } = BaseWidget;
    ctx.fillStyle = this.background_color;
    if (this.clicked) {
      ctx.fillStyle = "#AAA";
      this.clicked = false;
    }
    ctx.fillRect(margin, y2, width2 - margin * 2, height);
    if (showText && !this.computedDisabled) {
      ctx.strokeStyle = this.outline_color;
      ctx.strokeRect(margin, y2, width2 - margin * 2, height);
    }
    if (showText) this.drawLabel(ctx, width2 * 0.5);
    Object.assign(ctx, { textAlign, strokeStyle, fillStyle });
  }
  drawLabel(ctx, x2) {
    ctx.textAlign = "center";
    ctx.fillStyle = this.text_color;
    ctx.fillText(this.displayName, x2, this.y + this.height * 0.7);
  }
  onClick({ e: e2, node: node2, canvas: canvas2 }) {
    const pos = canvas2.graph_mouse;
    this.clicked = true;
    canvas2.setDirty(true);
    this.callback?.(this, canvas2, node2, pos, e2);
  }
}
const UNIQUE_MESSAGE_LIMIT = 1e4;
const sentWarnings = /* @__PURE__ */ new Set();
function warnDeprecated(message, source) {
  if (!LiteGraph.alwaysRepeatWarnings) {
    if (sentWarnings.has(message)) return;
    if (sentWarnings.size > UNIQUE_MESSAGE_LIMIT) return;
    sentWarnings.add(message);
  }
  for (const callback of LiteGraph.onDeprecationWarning) {
    callback(message, source);
  }
}
__name(warnDeprecated, "warnDeprecated");
class BaseSteppedWidget extends BaseWidget {
  static {
    __name(this, "BaseSteppedWidget");
  }
  /**
   * Draw the arrow buttons for the widget
   * @param ctx The canvas rendering context
   * @param width The width of the widget
   */
  drawArrowButtons(ctx, width2) {
    const { height, text_color, disabledTextColor, y: y2 } = this;
    const { arrowMargin, arrowWidth, margin } = BaseWidget;
    const arrowTipX = margin + arrowMargin;
    const arrowInnerX = arrowTipX + arrowWidth;
    ctx.fillStyle = this.canDecrement() ? text_color : disabledTextColor;
    ctx.beginPath();
    ctx.moveTo(arrowInnerX, y2 + 5);
    ctx.lineTo(arrowTipX, y2 + height * 0.5);
    ctx.lineTo(arrowInnerX, y2 + height - 5);
    ctx.fill();
    ctx.fillStyle = this.canIncrement() ? text_color : disabledTextColor;
    ctx.beginPath();
    ctx.moveTo(width2 - arrowInnerX, y2 + 5);
    ctx.lineTo(width2 - arrowTipX, y2 + height * 0.5);
    ctx.lineTo(width2 - arrowInnerX, y2 + height - 5);
    ctx.fill();
  }
  drawWidget(ctx, options2) {
    const { fillStyle, strokeStyle, textAlign } = ctx;
    this.drawWidgetShape(ctx, options2);
    if (options2.showText) {
      if (!this.computedDisabled) this.drawArrowButtons(ctx, options2.width);
      this.drawTruncatingText({ ctx, width: options2.width });
    }
    Object.assign(ctx, { textAlign, strokeStyle, fillStyle });
  }
}
function toArray(values) {
  return Array.isArray(values) ? values : Object.keys(values);
}
__name(toArray, "toArray");
class ComboWidget extends BaseSteppedWidget {
  static {
    __name(this, "ComboWidget");
  }
  type = "combo";
  get _displayValue() {
    const { values: rawValues } = this.options;
    if (rawValues) {
      const values = typeof rawValues === "function" ? rawValues() : rawValues;
      if (values && !Array.isArray(values)) {
        return values[this.value];
      }
    }
    return typeof this.value === "number" ? String(this.value) : this.value;
  }
  #getValues(node2) {
    const { values } = this.options;
    if (values == null) throw new Error("[ComboWidget]: values is required");
    return typeof values === "function" ? values(this, node2) : values;
  }
  /**
   * Checks if the value is {@link Array.at at} the given index in the combo list.
   * @param increment `true` if checking the use of the increment button, `false` for decrement
   * @returns `true` if the value is at the given index, otherwise `false`.
   */
  #canUseButton(increment2) {
    const { values } = this.options;
    if (typeof values === "function") return false;
    const valuesArray = toArray(values);
    if (!(valuesArray.length > 1)) return false;
    const firstValue = valuesArray.at(0);
    const lastValue = valuesArray.at(-1);
    if (firstValue === lastValue) return true;
    return this.value !== (increment2 ? lastValue : firstValue);
  }
  /**
   * Returns `true` if the current value is not the last value in the list.
   * Handles edge case where the value is both the first and last item in the list.
   */
  canIncrement() {
    return this.#canUseButton(true);
  }
  canDecrement() {
    return this.#canUseButton(false);
  }
  incrementValue(options2) {
    this.#tryChangeValue(1, options2);
  }
  decrementValue(options2) {
    this.#tryChangeValue(-1, options2);
  }
  #tryChangeValue(delta2, options2) {
    const values = this.#getValues(options2.node);
    const indexedValues = toArray(values);
    options2.canvas.last_mouseclick = 0;
    const foundIndex = typeof values === "object" ? indexedValues.indexOf(String(this.value)) + delta2 : indexedValues.indexOf(this.value) + delta2;
    const index2 = clamp(foundIndex, 0, indexedValues.length - 1);
    const value = Array.isArray(values) ? values[index2] : index2;
    this.setValue(value, options2);
  }
  onClick({ e: e2, node: node2, canvas: canvas2 }) {
    const x2 = e2.canvasX - node2.pos[0];
    const width2 = this.width || node2.size[0];
    if (typeof this.options.values === "function") {
      warnDeprecated("Using a function for values is deprecated. Use an array of unique values instead.");
    }
    if (x2 < 40) return this.decrementValue({ e: e2, node: node2, canvas: canvas2 });
    if (x2 > width2 - 40) return this.incrementValue({ e: e2, node: node2, canvas: canvas2 });
    const values = this.#getValues(node2);
    const values_list = toArray(values);
    const text_values = values != values_list ? Object.values(values) : values;
    new LiteGraph.ContextMenu(text_values, {
      scale: Math.max(1, canvas2.ds.scale),
      event: e2,
      className: "dark",
      callback: /* @__PURE__ */ __name((value) => {
        this.setValue(
          values != values_list ? text_values.indexOf(value) : value,
          { e: e2, node: node2, canvas: canvas2 }
        );
      }, "callback")
    });
  }
}
function getWidgetStep(options2) {
  return options2.step2 || (options2.step || 10) * 0.1;
}
__name(getWidgetStep, "getWidgetStep");
class KnobWidget extends BaseWidget {
  static {
    __name(this, "KnobWidget");
  }
  type = "knob";
  /**
   * Compute the layout size of the widget.
   * @returns The layout size of the widget.
   */
  computeLayoutSize() {
    return {
      minHeight: 60,
      minWidth: 20,
      maxHeight: 1e6,
      maxWidth: 1e6
    };
  }
  get height() {
    return this.computedHeight || super.height;
  }
  drawWidget(ctx, {
    width: width2,
    showText = true
  }) {
    const { fillStyle, strokeStyle, textAlign } = ctx;
    const { y: y2 } = this;
    const { margin } = BaseWidget;
    const { gradient_stops = "rgb(14, 182, 201); rgb(0, 216, 72)" } = this.options;
    const effective_height = this.computedHeight || this.height;
    const size_modifier = Math.min(this.computedHeight || this.height, this.width || 20) / 20;
    const arc_center = { x: width2 / 2, y: effective_height / 2 + y2 };
    ctx.lineWidth = (Math.min(width2, effective_height) - margin * size_modifier) / 6;
    const arc_size = (Math.min(width2, effective_height) - margin * size_modifier - ctx.lineWidth) / 2;
    {
      const gradient2 = ctx.createRadialGradient(
        arc_center.x,
        arc_center.y,
        arc_size + ctx.lineWidth,
        0,
        0,
        arc_size + ctx.lineWidth
      );
      gradient2.addColorStop(0, "rgb(29, 29, 29)");
      gradient2.addColorStop(1, "rgb(116, 116, 116)");
      ctx.fillStyle = gradient2;
    }
    ctx.beginPath();
    {
      ctx.arc(
        arc_center.x,
        arc_center.y,
        arc_size + ctx.lineWidth / 2,
        0,
        Math.PI * 2,
        false
      );
      ctx.fill();
      ctx.closePath();
    }
    const arc2 = {
      start_angle: Math.PI * 0.6,
      end_angle: Math.PI * 2.4
    };
    ctx.beginPath();
    {
      const gradient2 = ctx.createRadialGradient(
        arc_center.x,
        arc_center.y,
        arc_size + ctx.lineWidth,
        0,
        0,
        arc_size + ctx.lineWidth
      );
      gradient2.addColorStop(0, "rgb(99, 99, 99)");
      gradient2.addColorStop(1, "rgb(36, 36, 36)");
      ctx.strokeStyle = gradient2;
    }
    ctx.arc(
      arc_center.x,
      arc_center.y,
      arc_size,
      arc2.start_angle,
      arc2.end_angle,
      false
    );
    ctx.stroke();
    ctx.closePath();
    const range = this.options.max - this.options.min;
    let nvalue = (this.value - this.options.min) / range;
    nvalue = clamp(nvalue, 0, 1);
    ctx.beginPath();
    const gradient = ctx.createConicGradient(
      arc2.start_angle,
      arc_center.x,
      arc_center.y
    );
    const gs = gradient_stops.split(";");
    for (const [index2, stop2] of gs.entries()) {
      gradient.addColorStop(index2, stop2.trim());
    }
    ctx.strokeStyle = gradient;
    const value_end_angle = (arc2.end_angle - arc2.start_angle) * nvalue + arc2.start_angle;
    ctx.arc(
      arc_center.x,
      arc_center.y,
      arc_size,
      arc2.start_angle,
      value_end_angle,
      false
    );
    ctx.stroke();
    ctx.closePath();
    if (showText && !this.computedDisabled) {
      ctx.strokeStyle = this.outline_color;
      ctx.beginPath();
      ctx.strokeStyle = this.outline_color;
      ctx.arc(
        arc_center.x,
        arc_center.y,
        arc_size + ctx.lineWidth / 2,
        0,
        Math.PI * 2,
        false
      );
      ctx.lineWidth = 1;
      ctx.stroke();
      ctx.closePath();
    }
    if (showText) {
      ctx.textAlign = "center";
      ctx.fillStyle = this.text_color;
      const fixedValue = Number(this.value).toFixed(this.options.precision ?? 3);
      ctx.fillText(
        `${this.label || this.name}
${fixedValue}`,
        width2 * 0.5,
        y2 + effective_height * 0.5
      );
    }
    Object.assign(ctx, { textAlign, strokeStyle, fillStyle });
  }
  onClick() {
    this.current_drag_offset = 0;
  }
  current_drag_offset = 0;
  onDrag(options2) {
    if (this.options.read_only) return;
    const { e: e2 } = options2;
    const step = getWidgetStep(this.options);
    const range = this.options.max - this.options.min;
    const range_10_percent = range / 10;
    const range_1_percent = range / 100;
    const step_for = {
      shift: range_10_percent > step ? range_10_percent - range_10_percent % step : step,
      delta_y: range_1_percent > step ? range_1_percent - range_1_percent % step : step
      // 1% increments
    };
    const use_y = Math.abs(e2.movementY) > Math.abs(e2.movementX);
    const delta2 = use_y ? -e2.movementY : e2.movementX;
    const drag_threshold = 15;
    this.current_drag_offset += delta2;
    let adjustment = 0;
    if (this.current_drag_offset > drag_threshold) {
      adjustment += 1;
      this.current_drag_offset -= drag_threshold;
    } else if (this.current_drag_offset < -15) {
      adjustment -= 1;
      this.current_drag_offset += drag_threshold;
    }
    const step_with_shift_modifier = e2.shiftKey ? step_for.shift : use_y ? step_for.delta_y : step;
    const deltaValue = adjustment * step_with_shift_modifier;
    const newValue2 = clamp(
      this.value + deltaValue,
      this.options.min,
      this.options.max
    );
    if (newValue2 !== this.value) {
      this.setValue(newValue2, options2);
    }
  }
}
class LegacyWidget extends BaseWidget {
  static {
    __name(this, "LegacyWidget");
  }
  drawWidget(ctx, options2) {
    const H2 = LiteGraph.NODE_WIDGET_HEIGHT;
    this.draw?.(ctx, this.node, options2.width, this.y, H2, !!options2.showText);
  }
  onClick() {
    console.warn("Custom widget wrapper onClick was just called. Handling for third party widgets is done via LGraphCanvas - the mouse callback.");
  }
}
class NumberWidget extends BaseSteppedWidget {
  static {
    __name(this, "NumberWidget");
  }
  type = "number";
  get _displayValue() {
    return Number(this.value).toFixed(
      this.options.precision !== void 0 ? this.options.precision : 3
    );
  }
  canIncrement() {
    const { max } = this.options;
    return max == null || this.value < max;
  }
  canDecrement() {
    const { min } = this.options;
    return min == null || this.value > min;
  }
  incrementValue(options2) {
    this.setValue(this.value + getWidgetStep(this.options), options2);
  }
  decrementValue(options2) {
    this.setValue(this.value - getWidgetStep(this.options), options2);
  }
  setValue(value, options2) {
    let newValue2 = value;
    if (this.options.min != null && newValue2 < this.options.min) {
      newValue2 = this.options.min;
    }
    if (this.options.max != null && newValue2 > this.options.max) {
      newValue2 = this.options.max;
    }
    super.setValue(newValue2, options2);
  }
  onClick({ e, node, canvas }) {
    const x = e.canvasX - node.pos[0];
    const width = this.width || node.size[0];
    const delta = x < 40 ? -1 : x > width - 40 ? 1 : 0;
    if (delta) {
      this.setValue(this.value + delta * getWidgetStep(this.options), { e, node, canvas });
      return;
    }
    canvas.prompt("Value", this.value, (v) => {
      if (/^[\d\s()*+/-]+|\d+\.\d+$/.test(v)) {
        try {
          v = eval(v);
        } catch {
        }
      }
      const newValue = Number(v);
      if (!isNaN(newValue)) {
        this.setValue(newValue, { e, node, canvas });
      }
    }, e);
  }
  /**
   * Handles drag events for the number widget
   * @param options The options for handling the drag event
   */
  onDrag({ e: e2, node: node2, canvas: canvas2 }) {
    const width2 = this.width || node2.width;
    const x2 = e2.canvasX - node2.pos[0];
    const delta2 = x2 < 40 ? -1 : x2 > width2 - 40 ? 1 : 0;
    if (delta2 && (x2 > -3 && x2 < width2 + 3)) return;
    this.setValue(this.value + (e2.deltaX ?? 0) * getWidgetStep(this.options), { e: e2, node: node2, canvas: canvas2 });
  }
}
class SliderWidget extends BaseWidget {
  static {
    __name(this, "SliderWidget");
  }
  type = "slider";
  marker;
  /**
   * Draws the widget
   * @param ctx The canvas context
   * @param options The options for drawing the widget
   */
  drawWidget(ctx, {
    width: width2,
    showText = true
  }) {
    const { fillStyle, strokeStyle, textAlign } = ctx;
    const { height, y: y2 } = this;
    const { margin } = BaseWidget;
    ctx.fillStyle = this.background_color;
    ctx.fillRect(margin, y2, width2 - margin * 2, height);
    const range = this.options.max - this.options.min;
    let nvalue = (this.value - this.options.min) / range;
    nvalue = clamp(nvalue, 0, 1);
    ctx.fillStyle = this.options.slider_color ?? "#678";
    ctx.fillRect(margin, y2, nvalue * (width2 - margin * 2), height);
    if (showText && !this.computedDisabled) {
      ctx.strokeStyle = this.outline_color;
      ctx.strokeRect(margin, y2, width2 - margin * 2, height);
    }
    if (this.marker != null) {
      let marker_nvalue = (this.marker - this.options.min) / range;
      marker_nvalue = clamp(marker_nvalue, 0, 1);
      ctx.fillStyle = this.options.marker_color ?? "#AA9";
      ctx.fillRect(
        margin + marker_nvalue * (width2 - margin * 2),
        y2,
        2,
        height
      );
    }
    if (showText) {
      ctx.textAlign = "center";
      ctx.fillStyle = this.text_color;
      const fixedValue = Number(this.value).toFixed(this.options.precision ?? 3);
      ctx.fillText(
        `${this.label || this.name}  ${fixedValue}`,
        width2 * 0.5,
        y2 + height * 0.7
      );
    }
    Object.assign(ctx, { textAlign, strokeStyle, fillStyle });
  }
  /**
   * Handles click events for the slider widget
   */
  onClick(options2) {
    if (this.options.read_only) return;
    const { e: e2, node: node2 } = options2;
    const width2 = this.width || node2.size[0];
    const x2 = e2.canvasX - node2.pos[0];
    const slideFactor = clamp((x2 - 15) / (width2 - 30), 0, 1);
    const newValue2 = this.options.min + (this.options.max - this.options.min) * slideFactor;
    if (newValue2 !== this.value) {
      this.setValue(newValue2, options2);
    }
  }
  /**
   * Handles drag events for the slider widget
   */
  onDrag(options2) {
    if (this.options.read_only) return false;
    const { e: e2, node: node2 } = options2;
    const width2 = this.width || node2.size[0];
    const x2 = e2.canvasX - node2.pos[0];
    const slideFactor = clamp((x2 - 15) / (width2 - 30), 0, 1);
    const newValue2 = this.options.min + (this.options.max - this.options.min) * slideFactor;
    if (newValue2 !== this.value) {
      this.setValue(newValue2, options2);
    }
  }
}
class TextWidget extends BaseWidget {
  static {
    __name(this, "TextWidget");
  }
  constructor(widget, node2) {
    super(widget, node2);
    this.type ??= "string";
    this.value = widget.value?.toString() ?? "";
  }
  /**
   * Draws the widget
   * @param ctx The canvas context
   * @param options The options for drawing the widget
   */
  drawWidget(ctx, {
    width: width2,
    showText = true
  }) {
    const { fillStyle, strokeStyle, textAlign } = ctx;
    this.drawWidgetShape(ctx, { width: width2, showText });
    if (showText) {
      this.drawTruncatingText({ ctx, width: width2, leftPadding: 0, rightPadding: 0 });
    }
    Object.assign(ctx, { textAlign, strokeStyle, fillStyle });
  }
  onClick({ e: e2, node: node2, canvas: canvas2 }) {
    canvas2.prompt(
      "Value",
      this.value,
      (v2) => {
        if (v2 !== null) {
          this.setValue(v2, { e: e2, node: node2, canvas: canvas2 });
        }
      },
      e2,
      this.options?.multiline ?? false
    );
  }
}
function toConcreteWidget(widget, node2, wrapLegacyWidgets = true) {
  const narrowedWidget = widget;
  switch (narrowedWidget.type) {
    case "button":
      return toClass(ButtonWidget, narrowedWidget, node2);
    case "toggle":
      return toClass(BooleanWidget$1, narrowedWidget, node2);
    case "slider":
      return toClass(SliderWidget, narrowedWidget, node2);
    case "knob":
      return toClass(KnobWidget, narrowedWidget, node2);
    case "combo":
      return toClass(ComboWidget, narrowedWidget, node2);
    case "number":
      return toClass(NumberWidget, narrowedWidget, node2);
    case "string":
      return toClass(TextWidget, narrowedWidget, node2);
    case "text":
      return toClass(TextWidget, narrowedWidget, node2);
    default: {
      if (wrapLegacyWidgets) return toClass(LegacyWidget, widget, node2);
    }
  }
}
__name(toConcreteWidget, "toConcreteWidget");
function isComboWidget(widget) {
  return widget.type === "combo";
}
__name(isComboWidget, "isComboWidget");
class LGraphNode {
  static {
    __name(this, "LGraphNode");
  }
  // Static properties used by dynamic child classes
  static title;
  static MAX_CONSOLE;
  static type;
  static category;
  static filter;
  static skip_list;
  /** Default setting for {@link LGraphNode.connectInputToOutput}. @see {@link INodeFlags.keepAllLinksOnBypass} */
  static keepAllLinksOnBypass = false;
  /** The title text of the node. */
  title;
  /**
   * The font style used to render the node's title text.
   */
  get titleFontStyle() {
    return `${LiteGraph.NODE_TEXT_SIZE}px ${LiteGraph.NODE_FONT}`;
  }
  get innerFontStyle() {
    return `normal ${LiteGraph.NODE_SUBTEXT_SIZE}px ${LiteGraph.NODE_FONT}`;
  }
  graph = null;
  id;
  type = "";
  inputs = [];
  outputs = [];
  #concreteInputs = [];
  #concreteOutputs = [];
  properties = {};
  properties_info = [];
  flags = {};
  widgets;
  /**
   * The amount of space available for widgets to grow into.
   * @see {@link layoutWidgets}
   */
  freeWidgetSpace;
  locked;
  /** Execution order, automatically computed during run @see {@link LGraph.computeExecutionOrder} */
  order = 0;
  mode = LGraphEventMode.ALWAYS;
  last_serialization;
  serialize_widgets;
  /**
   * The overridden fg color used to render the node.
   * @see {@link renderingColor}
   */
  color;
  /**
   * The overridden bg color used to render the node.
   * @see {@link renderingBgColor}
   */
  bgcolor;
  /**
   * The overridden box color used to render the node.
   * @see {@link renderingBoxColor}
   */
  boxcolor;
  /** The fg color used to render the node. */
  get renderingColor() {
    return this.color || this.constructor.color || LiteGraph.NODE_DEFAULT_COLOR;
  }
  /** The bg color used to render the node. */
  get renderingBgColor() {
    return this.bgcolor || this.constructor.bgcolor || LiteGraph.NODE_DEFAULT_BGCOLOR;
  }
  /** The box color used to render the node. */
  get renderingBoxColor() {
    if (this.boxcolor) return this.boxcolor;
    if (LiteGraph.node_box_coloured_when_on) {
      if (this.action_triggered) return "#FFF";
      if (this.execute_triggered) return "#AAA";
    }
    if (LiteGraph.node_box_coloured_by_mode) {
      const modeColour = LiteGraph.NODE_MODES_COLORS[this.mode ?? LGraphEventMode.ALWAYS];
      if (modeColour) return modeColour;
    }
    return LiteGraph.NODE_DEFAULT_BOXCOLOR;
  }
  /** @inheritdoc {@link IColorable.setColorOption} */
  setColorOption(colorOption) {
    if (colorOption == null) {
      delete this.color;
      delete this.bgcolor;
    } else {
      this.color = colorOption.color;
      this.bgcolor = colorOption.bgcolor;
    }
  }
  /** @inheritdoc {@link IColorable.getColorOption} */
  getColorOption() {
    return Object.values(LGraphCanvas.node_colors).find(
      (colorOption) => colorOption.color === this.color && colorOption.bgcolor === this.bgcolor
    ) ?? null;
  }
  /**
   * The stroke styles that should be applied to the node.
   */
  strokeStyles;
  /**
   * The progress of node execution. Used to render a progress bar. Value between 0 and 1.
   */
  progress;
  exec_version;
  action_call;
  execute_triggered;
  action_triggered;
  widgets_up;
  widgets_start_y;
  lostFocusAt;
  gotFocusAt;
  badges = [];
  badgePosition = BadgePosition.TopLeft;
  /**
   * The width of the node when collapsed.
   * Updated by {@link LGraphCanvas.drawNode}
   */
  _collapsed_width;
  console;
  _level;
  _shape;
  mouseOver;
  redraw_on_mouse;
  resizable;
  clonable;
  _relative_id;
  clip_area;
  ignore_remove;
  has_errors;
  removable;
  block_delete;
  selected;
  showAdvanced;
  /** @inheritdoc {@link renderArea} */
  #renderArea = new Float32Array(4);
  /**
   * Rect describing the node area, including shadows and any protrusions.
   * Determines if the node is visible.  Calculated once at the start of every frame.
   */
  get renderArea() {
    return this.#renderArea;
  }
  /** @inheritdoc {@link boundingRect} */
  #boundingRect = new Float32Array(4);
  /**
   * Cached node position & area as `x, y, width, height`.  Includes changes made by {@link onBounding}, if present.
   *
   * Determines the node hitbox and other rendering effects.  Calculated once at the start of every frame.
   */
  get boundingRect() {
    return this.#boundingRect;
  }
  /** {@link pos} and {@link size} values are backed by this {@link Rect}. */
  _posSize = new Float32Array(4);
  _pos = this._posSize.subarray(0, 2);
  _size = this._posSize.subarray(2, 4);
  get pos() {
    return this._pos;
  }
  /** Node position does not necessarily correlate to the top-left corner. */
  set pos(value) {
    if (!value || value.length < 2) return;
    this._pos[0] = value[0];
    this._pos[1] = value[1];
  }
  get size() {
    return this._size;
  }
  set size(value) {
    if (!value || value.length < 2) return;
    this._size[0] = value[0];
    this._size[1] = value[1];
  }
  /**
   * The size of the node used for rendering.
   */
  get renderingSize() {
    return this.flags.collapsed ? [this._collapsed_width ?? 0, 0] : this._size;
  }
  get shape() {
    return this._shape;
  }
  set shape(v2) {
    switch (v2) {
      case "default":
        delete this._shape;
        break;
      case "box":
        this._shape = RenderShape.BOX;
        break;
      case "round":
        this._shape = RenderShape.ROUND;
        break;
      case "circle":
        this._shape = RenderShape.CIRCLE;
        break;
      case "card":
        this._shape = RenderShape.CARD;
        break;
      default:
        this._shape = v2;
    }
  }
  /**
   * The shape of the node used for rendering. @see {@link RenderShape}
   */
  get renderingShape() {
    return this._shape || this.constructor.shape || LiteGraph.NODE_DEFAULT_SHAPE;
  }
  get is_selected() {
    return this.selected;
  }
  set is_selected(value) {
    this.selected = value;
  }
  get title_mode() {
    return this.constructor.title_mode ?? TitleMode.NORMAL_TITLE;
  }
  #getErrorStrokeStyle() {
    if (this.has_errors) {
      return {
        padding: 12,
        lineWidth: 10,
        color: LiteGraph.NODE_ERROR_COLOUR
      };
    }
  }
  #getSelectedStrokeStyle() {
    if (this.selected) {
      return {
        padding: this.has_errors ? 20 : void 0
      };
    }
  }
  constructor(title, type) {
    this.id = LiteGraph.use_uuids ? LiteGraph.uuidv4() : -1;
    this.title = title || "Unnamed";
    this.type = type ?? "";
    this.size = [LiteGraph.NODE_WIDTH, 60];
    this.pos = [10, 10];
    this.strokeStyles = {
      error: this.#getErrorStrokeStyle,
      selected: this.#getSelectedStrokeStyle
    };
  }
  /**
   * configure a node from an object containing the serialized info
   */
  configure(info) {
    if (this.graph) {
      this.graph._version++;
    }
    for (const j2 in info) {
      if (j2 == "properties") {
        for (const k2 in info.properties) {
          this.properties[k2] = info.properties[k2];
          this.onPropertyChanged?.(k2, info.properties[k2]);
        }
        continue;
      }
      if (info[j2] == null) {
        continue;
      } else if (typeof info[j2] == "object") {
        if (this[j2]?.configure) {
          this[j2]?.configure(info[j2]);
        } else {
          this[j2] = LiteGraph.cloneObject(info[j2], this[j2]);
        }
      } else {
        this[j2] = info[j2];
      }
    }
    if (!info.title) {
      this.title = this.constructor.title;
    }
    this.inputs ??= [];
    this.inputs = this.inputs.map((input) => toClass(NodeInputSlot, input, this));
    for (const [i2, input] of this.inputs.entries()) {
      const link2 = this.graph && input.link != null ? this.graph._links.get(input.link) : null;
      this.onConnectionsChange?.(NodeSlotType.INPUT, i2, true, link2, input);
      this.onInputAdded?.(input);
    }
    this.outputs ??= [];
    this.outputs = this.outputs.map((output) => toClass(NodeOutputSlot, output, this));
    for (const [i2, output] of this.outputs.entries()) {
      if (!output.links) continue;
      for (const linkId of output.links) {
        const link2 = this.graph ? this.graph._links.get(linkId) : null;
        this.onConnectionsChange?.(NodeSlotType.OUTPUT, i2, true, link2, output);
      }
      this.onOutputAdded?.(output);
    }
    if (this.widgets) {
      for (const w2 of this.widgets) {
        if (!w2) continue;
        if (w2.options?.property && this.properties[w2.options.property] != void 0)
          w2.value = JSON.parse(JSON.stringify(this.properties[w2.options.property]));
      }
      if (info.widgets_values) {
        const widgetsWithValue = this.widgets.filter((w2) => w2.serialize !== false);
        for (let i2 = 0; i2 < info.widgets_values.length; ++i2) {
          const widget = widgetsWithValue[i2];
          if (widget) {
            widget.value = info.widgets_values[i2];
          }
        }
      }
    }
    if (this.pinned) this.resizable = false;
    this.onConfigure?.(info);
  }
  /**
   * serialize the content
   */
  serialize() {
    const o2 = {
      id: this.id,
      type: this.type,
      pos: [this.pos[0], this.pos[1]],
      size: [this.size[0], this.size[1]],
      flags: LiteGraph.cloneObject(this.flags),
      order: this.order,
      mode: this.mode,
      showAdvanced: this.showAdvanced
    };
    if (this.constructor === LGraphNode && this.last_serialization)
      return this.last_serialization;
    if (this.inputs) o2.inputs = this.inputs.map((input) => inputAsSerialisable(input));
    if (this.outputs) o2.outputs = this.outputs.map((output) => outputAsSerialisable(output));
    if (this.title && this.title != this.constructor.title) o2.title = this.title;
    if (this.properties) o2.properties = LiteGraph.cloneObject(this.properties);
    const { widgets } = this;
    if (widgets && this.serialize_widgets) {
      o2.widgets_values = [];
      for (const [i2, widget] of widgets.entries()) {
        if (widget.serialize === false) continue;
        o2.widgets_values[i2] = widget ? widget.value : null;
      }
    }
    if (!o2.type) o2.type = this.constructor.type;
    if (this.color) o2.color = this.color;
    if (this.bgcolor) o2.bgcolor = this.bgcolor;
    if (this.boxcolor) o2.boxcolor = this.boxcolor;
    if (this.shape) o2.shape = this.shape;
    if (this.onSerialize?.(o2)) console.warn("node onSerialize shouldnt return anything, data should be stored in the object pass in the first parameter");
    return o2;
  }
  /* Creates a clone of this node */
  clone() {
    if (this.type == null) return null;
    const node2 = LiteGraph.createNode(this.type);
    if (!node2) return null;
    const data = LiteGraph.cloneObject(this.serialize());
    const { inputs, outputs } = data;
    if (inputs) {
      for (const input of inputs) {
        input.link = null;
      }
    }
    if (outputs) {
      for (const { links } of outputs) {
        if (links) links.length = 0;
      }
    }
    delete data.id;
    if (LiteGraph.use_uuids) data.id = LiteGraph.uuidv4();
    node2.configure(data);
    return node2;
  }
  /**
   * serialize and stringify
   */
  toString() {
    return JSON.stringify(this.serialize());
  }
  /**
   * get the title string
   */
  getTitle() {
    return this.title || this.constructor.title;
  }
  /**
   * sets the value of a property
   * @param name
   * @param value
   */
  setProperty(name2, value) {
    this.properties ||= {};
    if (value === this.properties[name2]) return;
    const prev_value = this.properties[name2];
    this.properties[name2] = value;
    if (this.onPropertyChanged?.(name2, value, prev_value) === false)
      this.properties[name2] = prev_value;
    if (this.widgets) {
      for (const w2 of this.widgets) {
        if (!w2) continue;
        if (w2.options.property == name2) {
          w2.value = value;
          break;
        }
      }
    }
  }
  /**
   * sets the output data
   * @param slot
   * @param data
   */
  setOutputData(slot, data) {
    const { outputs } = this;
    if (!outputs) return;
    if (slot == -1 || slot >= outputs.length) return;
    const output_info = outputs[slot];
    if (!output_info) return;
    output_info._data = data;
    if (!this.graph) throw new NullGraphError();
    const { links } = outputs[slot];
    if (links) {
      for (const id2 of links) {
        const link2 = this.graph._links.get(id2);
        if (link2) link2.data = data;
      }
    }
  }
  /**
   * sets the output data type, useful when you want to be able to overwrite the data type
   */
  setOutputDataType(slot, type) {
    const { outputs } = this;
    if (!outputs || (slot == -1 || slot >= outputs.length)) return;
    const output_info = outputs[slot];
    if (!output_info) return;
    output_info.type = type;
    if (!this.graph) throw new NullGraphError();
    const { links } = outputs[slot];
    if (links) {
      for (const id2 of links) {
        const link2 = this.graph._links.get(id2);
        if (link2) link2.type = type;
      }
    }
  }
  /**
   * Retrieves the input data (data traveling through the connection) from one slot
   * @param slot
   * @param force_update if set to true it will force the connected node of this slot to output data into this link
   * @returns data or if it is not connected returns undefined
   */
  getInputData(slot, force_update) {
    if (!this.inputs) return;
    if (slot >= this.inputs.length || this.inputs[slot].link == null) return;
    if (!this.graph) throw new NullGraphError();
    const link_id = this.inputs[slot].link;
    const link2 = this.graph._links.get(link_id);
    if (!link2) return null;
    if (!force_update) return link2.data;
    const node2 = this.graph.getNodeById(link2.origin_id);
    if (!node2) return link2.data;
    if (node2.updateOutputData) {
      node2.updateOutputData(link2.origin_slot);
    } else {
      node2.onExecute?.();
    }
    return link2.data;
  }
  /**
   * Retrieves the input data type (in case this supports multiple input types)
   * @param slot
   * @returns datatype in string format
   */
  getInputDataType(slot) {
    if (!this.inputs) return null;
    if (slot >= this.inputs.length || this.inputs[slot].link == null) return null;
    if (!this.graph) throw new NullGraphError();
    const link_id = this.inputs[slot].link;
    const link2 = this.graph._links.get(link_id);
    if (!link2) return null;
    const node2 = this.graph.getNodeById(link2.origin_id);
    if (!node2) return link2.type;
    const output_info = node2.outputs[link2.origin_slot];
    return output_info ? output_info.type : null;
  }
  /**
   * Retrieves the input data from one slot using its name instead of slot number
   * @param slot_name
   * @param force_update if set to true it will force the connected node of this slot to output data into this link
   * @returns data or if it is not connected returns null
   */
  getInputDataByName(slot_name, force_update) {
    const slot = this.findInputSlot(slot_name);
    return slot == -1 ? null : this.getInputData(slot, force_update);
  }
  /**
   * tells you if there is a connection in one input slot
   * @param slot The 0-based index of the input to check
   * @returns `true` if the input slot has a link ID (does not perform validation)
   */
  isInputConnected(slot) {
    if (!this.inputs) return false;
    return slot < this.inputs.length && this.inputs[slot].link != null;
  }
  /**
   * tells you info about an input connection (which node, type, etc)
   * @returns object or null { link: id, name: string, type: string or 0 }
   */
  getInputInfo(slot) {
    return !this.inputs || !(slot < this.inputs.length) ? null : this.inputs[slot];
  }
  /**
   * Returns the link info in the connection of an input slot
   * @returns object or null
   */
  getInputLink(slot) {
    if (!this.inputs) return null;
    if (slot < this.inputs.length) {
      if (!this.graph) throw new NullGraphError();
      const input = this.inputs[slot];
      if (input.link != null) {
        return this.graph._links.get(input.link) ?? null;
      }
    }
    return null;
  }
  /**
   * returns the node connected in the input slot
   * @returns node or null
   */
  getInputNode(slot) {
    if (!this.inputs) return null;
    if (slot >= this.inputs.length) return null;
    const input = this.inputs[slot];
    if (!input || input.link === null) return null;
    if (!this.graph) throw new NullGraphError();
    const link_info = this.graph._links.get(input.link);
    if (!link_info) return null;
    return this.graph.getNodeById(link_info.origin_id);
  }
  /**
   * returns the value of an input with this name, otherwise checks if there is a property with that name
   * @returns value
   */
  getInputOrProperty(name2) {
    const { inputs } = this;
    if (!inputs?.length) {
      return this.properties ? this.properties[name2] : null;
    }
    if (!this.graph) throw new NullGraphError();
    for (const input of inputs) {
      if (name2 == input.name && input.link != null) {
        const link2 = this.graph._links.get(input.link);
        if (link2) return link2.data;
      }
    }
    return this.properties[name2];
  }
  /**
   * tells you the last output data that went in that slot
   * @returns object or null
   */
  getOutputData(slot) {
    if (!this.outputs) return null;
    if (slot >= this.outputs.length) return null;
    const info = this.outputs[slot];
    return info._data;
  }
  /**
   * tells you info about an output connection (which node, type, etc)
   * @returns object or null { name: string, type: string, links: [ ids of links in number ] }
   */
  getOutputInfo(slot) {
    return !this.outputs || !(slot < this.outputs.length) ? null : this.outputs[slot];
  }
  /**
   * tells you if there is a connection in one output slot
   */
  isOutputConnected(slot) {
    if (!this.outputs) return false;
    return slot < this.outputs.length && Number(this.outputs[slot].links?.length) > 0;
  }
  /**
   * tells you if there is any connection in the output slots
   */
  isAnyOutputConnected() {
    const { outputs } = this;
    if (!outputs) return false;
    for (const output of outputs) {
      if (output.links?.length) return true;
    }
    return false;
  }
  /**
   * retrieves all the nodes connected to this output slot
   */
  getOutputNodes(slot) {
    const { outputs } = this;
    if (!outputs || outputs.length == 0) return null;
    if (slot >= outputs.length) return null;
    const { links } = outputs[slot];
    if (!links || links.length == 0) return null;
    if (!this.graph) throw new NullGraphError();
    const r2 = [];
    for (const id2 of links) {
      const link2 = this.graph._links.get(id2);
      if (link2) {
        const target_node = this.graph.getNodeById(link2.target_id);
        if (target_node) {
          r2.push(target_node);
        }
      }
    }
    return r2;
  }
  addOnTriggerInput() {
    const trigS = this.findInputSlot("onTrigger");
    if (trigS == -1) {
      this.addInput("onTrigger", LiteGraph.EVENT, {
        nameLocked: true
      });
      return this.findInputSlot("onTrigger");
    }
    return trigS;
  }
  addOnExecutedOutput() {
    const trigS = this.findOutputSlot("onExecuted");
    if (trigS == -1) {
      this.addOutput("onExecuted", LiteGraph.ACTION, {
        nameLocked: true
      });
      return this.findOutputSlot("onExecuted");
    }
    return trigS;
  }
  onAfterExecuteNode(param, options2) {
    const trigS = this.findOutputSlot("onExecuted");
    if (trigS != -1) {
      this.triggerSlot(trigS, param, null, options2);
    }
  }
  changeMode(modeTo) {
    switch (modeTo) {
      case LGraphEventMode.ON_EVENT:
        break;
      case LGraphEventMode.ON_TRIGGER:
        this.addOnTriggerInput();
        this.addOnExecutedOutput();
        break;
      case LGraphEventMode.NEVER:
        break;
      case LGraphEventMode.ALWAYS:
        break;
      case LiteGraph.ON_REQUEST:
        break;
      default:
        return false;
    }
    this.mode = modeTo;
    return true;
  }
  /**
   * Triggers the node code execution, place a boolean/counter to mark the node as being executed
   */
  doExecute(param, options2) {
    options2 = options2 || {};
    if (this.onExecute) {
      options2.action_call ||= `${this.id}_exec_${Math.floor(Math.random() * 9999)}`;
      if (!this.graph) throw new NullGraphError();
      this.graph.nodes_executing[this.id] = true;
      this.onExecute(param, options2);
      this.graph.nodes_executing[this.id] = false;
      this.exec_version = this.graph.iteration;
      if (options2?.action_call) {
        this.action_call = options2.action_call;
        this.graph.nodes_executedAction[this.id] = options2.action_call;
      }
    }
    this.execute_triggered = 2;
    this.onAfterExecuteNode?.(param, options2);
  }
  /**
   * Triggers an action, wrapped by logics to control execution flow
   * @param action name
   */
  actionDo(action, param, options2) {
    options2 = options2 || {};
    if (this.onAction) {
      options2.action_call ||= `${this.id}_${action || "action"}_${Math.floor(Math.random() * 9999)}`;
      if (!this.graph) throw new NullGraphError();
      this.graph.nodes_actioning[this.id] = action || "actioning";
      this.onAction(action, param, options2);
      this.graph.nodes_actioning[this.id] = false;
      if (options2?.action_call) {
        this.action_call = options2.action_call;
        this.graph.nodes_executedAction[this.id] = options2.action_call;
      }
    }
    this.action_triggered = 2;
    this.onAfterExecuteNode?.(param, options2);
  }
  /**
   * Triggers an event in this node, this will trigger any output with the same name
   * @param action name ( "on_play", ... ) if action is equivalent to false then the event is send to all
   */
  trigger(action, param, options2) {
    const { outputs } = this;
    if (!outputs || !outputs.length) {
      return;
    }
    if (this.graph) this.graph._last_trigger_time = LiteGraph.getTime();
    for (const [i2, output] of outputs.entries()) {
      if (!output || output.type !== LiteGraph.EVENT || action && output.name != action) {
        continue;
      }
      this.triggerSlot(i2, param, null, options2);
    }
  }
  /**
   * Triggers a slot event in this node: cycle output slots and launch execute/action on connected nodes
   * @param slot the index of the output slot
   * @param link_id [optional] in case you want to trigger and specific output link in a slot
   */
  triggerSlot(slot, param, link_id, options2) {
    options2 = options2 || {};
    if (!this.outputs) return;
    if (slot == null) {
      console.error("slot must be a number");
      return;
    }
    if (typeof slot !== "number")
      console.warn("slot must be a number, use node.trigger('name') if you want to use a string");
    const output = this.outputs[slot];
    if (!output) return;
    const links = output.links;
    if (!links || !links.length) return;
    if (!this.graph) throw new NullGraphError();
    this.graph._last_trigger_time = LiteGraph.getTime();
    for (const id2 of links) {
      if (link_id != null && link_id != id2) continue;
      const link_info = this.graph._links.get(id2);
      if (!link_info) continue;
      link_info._last_time = LiteGraph.getTime();
      const node2 = this.graph.getNodeById(link_info.target_id);
      if (!node2) continue;
      if (node2.mode === LGraphEventMode.ON_TRIGGER) {
        if (!options2.action_call)
          options2.action_call = `${this.id}_trigg_${Math.floor(Math.random() * 9999)}`;
        node2.doExecute?.(param, options2);
      } else if (node2.onAction) {
        if (!options2.action_call)
          options2.action_call = `${this.id}_act_${Math.floor(Math.random() * 9999)}`;
        const target_connection = node2.inputs[link_info.target_slot];
        node2.actionDo(target_connection.name, param, options2);
      }
    }
  }
  /**
   * clears the trigger slot animation
   * @param slot the index of the output slot
   * @param link_id [optional] in case you want to trigger and specific output link in a slot
   */
  clearTriggeredSlot(slot, link_id) {
    if (!this.outputs) return;
    const output = this.outputs[slot];
    if (!output) return;
    const links = output.links;
    if (!links || !links.length) return;
    if (!this.graph) throw new NullGraphError();
    for (const id2 of links) {
      if (link_id != null && link_id != id2) continue;
      const link_info = this.graph._links.get(id2);
      if (!link_info) continue;
      link_info._last_time = 0;
    }
  }
  /**
   * changes node size and triggers callback
   */
  setSize(size) {
    this.size = size;
    this.onResize?.(this.size);
  }
  /**
   * Expands the node size to fit its content.
   */
  expandToFitContent() {
    const newSize = this.computeSize();
    this.setSize([
      Math.max(this.size[0], newSize[0]),
      Math.max(this.size[1], newSize[1])
    ]);
  }
  /**
   * add a new property to this node
   * @param type string defining the output type ("vec3","number",...)
   * @param extra_info this can be used to have special properties of the property (like values, etc)
   */
  addProperty(name2, default_value, type, extra_info) {
    const o2 = { name: name2, type, default_value };
    if (extra_info) Object.assign(o2, extra_info);
    this.properties_info ||= [];
    this.properties_info.push(o2);
    this.properties ||= {};
    this.properties[name2] = default_value;
    return o2;
  }
  /**
   * add a new output slot to use in this node
   * @param type string defining the output type ("vec3","number",...)
   * @param extra_info this can be used to have special properties of an output (label, special color, position, etc)
   */
  addOutput(name2, type, extra_info) {
    const output = Object.assign(
      new NodeOutputSlot({ name: name2, type, links: null }, this),
      extra_info
    );
    this.outputs ||= [];
    this.outputs.push(output);
    this.onOutputAdded?.(output);
    if (LiteGraph.auto_load_slot_types)
      LiteGraph.registerNodeAndSlotType(this, type, true);
    this.expandToFitContent();
    this.setDirtyCanvas(true, true);
    return output;
  }
  /**
   * remove an existing output slot
   */
  removeOutput(slot) {
    this.disconnectOutput(slot);
    const { outputs } = this;
    outputs.splice(slot, 1);
    for (let i2 = slot; i2 < outputs.length; ++i2) {
      const output = outputs[i2];
      if (!output || !output.links) continue;
      for (const linkId of output.links) {
        if (!this.graph) throw new NullGraphError();
        const link2 = this.graph._links.get(linkId);
        if (link2) link2.origin_slot--;
      }
    }
    this.onOutputRemoved?.(slot);
    this.setDirtyCanvas(true, true);
  }
  /**
   * add a new input slot to use in this node
   * @param type string defining the input type ("vec3","number",...), it its a generic one use 0
   * @param extra_info this can be used to have special properties of an input (label, color, position, etc)
   */
  addInput(name2, type, extra_info) {
    type ||= 0;
    const input = Object.assign(
      new NodeInputSlot({ name: name2, type, link: null }, this),
      extra_info
    );
    this.inputs ||= [];
    this.inputs.push(input);
    this.expandToFitContent();
    this.onInputAdded?.(input);
    LiteGraph.registerNodeAndSlotType(this, type);
    this.setDirtyCanvas(true, true);
    return input;
  }
  /**
   * remove an existing input slot
   */
  removeInput(slot) {
    this.disconnectInput(slot, true);
    const { inputs } = this;
    const slot_info = inputs.splice(slot, 1);
    for (let i2 = slot; i2 < inputs.length; ++i2) {
      const input = inputs[i2];
      if (!input?.link) continue;
      if (!this.graph) throw new NullGraphError();
      const link2 = this.graph._links.get(input.link);
      if (link2) link2.target_slot--;
    }
    this.onInputRemoved?.(slot, slot_info[0]);
    this.setDirtyCanvas(true, true);
  }
  /**
   * computes the minimum size of a node according to its inputs and output slots
   * @returns the total size
   */
  computeSize(out) {
    const ctorSize = this.constructor.size;
    if (ctorSize) return [ctorSize[0], ctorSize[1]];
    const { inputs, outputs, widgets } = this;
    let rows = Math.max(
      inputs ? inputs.filter((input) => !isWidgetInputSlot(input)).length : 1,
      outputs ? outputs.length : 1
    );
    const size = out || new Float32Array([0, 0]);
    rows = Math.max(rows, 1);
    const font_size = LiteGraph.NODE_TEXT_SIZE;
    const padLeft = LiteGraph.NODE_TITLE_HEIGHT;
    const padRight = padLeft * 0.33;
    const title_width = padLeft + compute_text_size(this.title, this.titleFontStyle) + padRight;
    let input_width = 0;
    let widgetWidth = 0;
    let output_width = 0;
    if (inputs) {
      for (const input of inputs) {
        const text2 = input.label || input.localized_name || input.name || "";
        const text_width = compute_text_size(text2, this.innerFontStyle);
        if (isWidgetInputSlot(input)) {
          const widget = this.getWidgetFromSlot(input);
          if (widget && !this.isWidgetVisible(widget)) continue;
          if (text_width > widgetWidth) widgetWidth = text_width;
        } else {
          if (text_width > input_width) input_width = text_width;
        }
      }
    }
    if (outputs) {
      for (const output of outputs) {
        const text2 = output.label || output.localized_name || output.name || "";
        const text_width = compute_text_size(text2, this.innerFontStyle);
        if (output_width < text_width)
          output_width = text_width;
      }
    }
    const minWidth = LiteGraph.NODE_WIDTH * (widgets?.length ? 1.5 : 1);
    const centrePadding = input_width && output_width ? 5 : 0;
    const slotsWidth = input_width + output_width + 2 * LiteGraph.NODE_SLOT_HEIGHT + centrePadding;
    const widgetMargin = BaseWidget.margin + BaseWidget.arrowMargin + BaseWidget.arrowWidth;
    const widgetPadding = BaseWidget.minValueWidth + 2 * widgetMargin;
    if (widgetWidth) widgetWidth += widgetPadding;
    size[0] = Math.max(slotsWidth, widgetWidth, title_width, minWidth);
    size[1] = (this.constructor.slot_start_y || 0) + rows * LiteGraph.NODE_SLOT_HEIGHT;
    let widgets_height = 0;
    if (widgets?.length) {
      for (const widget of widgets) {
        if (!this.isWidgetVisible(widget)) continue;
        let widget_height = 0;
        if (widget.computeSize) {
          widget_height += widget.computeSize(size[0])[1];
        } else if (widget.computeLayoutSize) {
          const { minHeight, minWidth: minWidth2 } = widget.computeLayoutSize(this);
          const widgetWidth2 = minWidth2 + widgetPadding;
          if (widgetWidth2 > size[0]) size[0] = widgetWidth2;
          widget_height += minHeight;
        } else {
          widget_height += LiteGraph.NODE_WIDGET_HEIGHT;
        }
        widgets_height += widget_height + 4;
      }
      widgets_height += 8;
    }
    if (this.widgets_up)
      size[1] = Math.max(size[1], widgets_height);
    else if (this.widgets_start_y != null)
      size[1] = Math.max(size[1], widgets_height + this.widgets_start_y);
    else
      size[1] += widgets_height;
    function compute_text_size(text2, fontStyle) {
      return LGraphCanvas._measureText?.(text2, fontStyle) ?? font_size * (text2?.length ?? 0) * 0.6;
    }
    __name(compute_text_size, "compute_text_size");
    if (this.constructor.min_height && size[1] < this.constructor.min_height) {
      size[1] = this.constructor.min_height;
    }
    size[1] += 6;
    return size;
  }
  inResizeCorner(canvasX, canvasY) {
    const rows = this.outputs ? this.outputs.length : 1;
    const outputs_offset = (this.constructor.slot_start_y || 0) + rows * LiteGraph.NODE_SLOT_HEIGHT;
    return isInRectangle(
      canvasX,
      canvasY,
      this.pos[0] + this.size[0] - 15,
      this.pos[1] + Math.max(this.size[1] - 15, outputs_offset),
      20,
      20
    );
  }
  /**
   * returns all the info available about a property of this node.
   * @param property name of the property
   * @returns the object with all the available info
   */
  getPropertyInfo(property) {
    let info = null;
    const { properties_info } = this;
    if (properties_info) {
      for (const propInfo of properties_info) {
        if (propInfo.name == property) {
          info = propInfo;
          break;
        }
      }
    }
    if (this.constructor[`@${property}`]) info = this.constructor[`@${property}`];
    if (this.constructor.widgets_info?.[property])
      info = this.constructor.widgets_info[property];
    if (!info && this.onGetPropertyInfo) {
      info = this.onGetPropertyInfo(property);
    }
    info ||= {};
    info.type ||= typeof this.properties[property];
    if (info.widget == "combo") info.type = "enum";
    return info;
  }
  /**
   * Defines a widget inside the node, it will be rendered on top of the node, you can control lots of properties
   * @param type the widget type
   * @param name the text to show on the widget
   * @param value the default value
   * @param callback function to call when it changes (optionally, it can be the name of the property to modify)
   * @param options the object that contains special properties of this widget
   * @returns the created widget object
   */
  addWidget(type, name2, value, callback, options2) {
    this.widgets ||= [];
    if (!options2 && callback && typeof callback === "object") {
      options2 = callback;
      callback = null;
    }
    options2 ||= {};
    if (typeof options2 === "string")
      options2 = { property: options2 };
    if (callback && typeof callback === "string") {
      options2.property = callback;
      callback = null;
    }
    const w2 = {
      // @ts-expect-error
      type: type.toLowerCase(),
      name: name2,
      value,
      callback: typeof callback !== "function" ? void 0 : callback,
      options: options2,
      y: 0
    };
    if (w2.options.y !== void 0) {
      w2.y = w2.options.y;
    }
    if (!callback && !w2.options.callback && !w2.options.property) {
      console.warn("LiteGraph addWidget(...) without a callback or property assigned");
    }
    if (type == "combo" && !w2.options.values) {
      throw "LiteGraph addWidget('combo',...) requires to pass values in options: { values:['red','blue'] }";
    }
    const widget = this.addCustomWidget(w2);
    this.expandToFitContent();
    return widget;
  }
  addCustomWidget(custom_widget) {
    this.widgets ||= [];
    const widget = toConcreteWidget(custom_widget, this, false) ?? custom_widget;
    this.widgets.push(widget);
    return widget;
  }
  move(deltaX, deltaY) {
    if (this.pinned) return;
    this.pos[0] += deltaX;
    this.pos[1] += deltaY;
  }
  /**
   * Internal method to measure the node for rendering.  Prefer {@link boundingRect} where possible.
   *
   * Populates {@link out} with the results in graph space.
   * Populates {@link _collapsed_width} with the collapsed width if the node is collapsed.
   * Adjusts for title and collapsed status, but does not call {@link onBounding}.
   * @param out `x, y, width, height` are written to this array.
   * @param ctx The canvas context to use for measuring text.
   */
  measure(out, ctx) {
    const titleMode = this.title_mode;
    const renderTitle = titleMode != TitleMode.TRANSPARENT_TITLE && titleMode != TitleMode.NO_TITLE;
    const titleHeight = renderTitle ? LiteGraph.NODE_TITLE_HEIGHT : 0;
    out[0] = this.pos[0];
    out[1] = this.pos[1] + -titleHeight;
    if (!this.flags?.collapsed) {
      out[2] = this.size[0];
      out[3] = this.size[1] + titleHeight;
    } else {
      ctx.font = this.innerFontStyle;
      this._collapsed_width = Math.min(
        this.size[0],
        ctx.measureText(this.getTitle() ?? "").width + LiteGraph.NODE_TITLE_HEIGHT * 2
      );
      out[2] = this._collapsed_width || LiteGraph.NODE_COLLAPSED_WIDTH;
      out[3] = LiteGraph.NODE_TITLE_HEIGHT;
    }
  }
  /**
   * returns the bounding of the object, used for rendering purposes
   * @param out {Float32Array[4]?} [optional] a place to store the output, to free garbage
   * @param includeExternal {boolean?} [optional] set to true to
   * include the shadow and connection points in the bounding calculation
   * @returns the bounding box in format of [topleft_cornerx, topleft_cornery, width, height]
   */
  getBounding(out, includeExternal) {
    out ||= new Float32Array(4);
    const rect = includeExternal ? this.renderArea : this.boundingRect;
    out[0] = rect[0];
    out[1] = rect[1];
    out[2] = rect[2];
    out[3] = rect[3];
    return out;
  }
  /**
   * Calculates the render area of this node, populating both {@link boundingRect} and {@link renderArea}.
   * Called automatically at the start of every frame.
   */
  updateArea(ctx) {
    const bounds = this.#boundingRect;
    this.measure(bounds, ctx);
    this.onBounding?.(bounds);
    const renderArea = this.#renderArea;
    renderArea.set(bounds);
    renderArea[0] -= 4;
    renderArea[1] -= 4;
    renderArea[2] += 6 + 4;
    renderArea[3] += 5 + 4;
  }
  /**
   * checks if a point is inside the shape of a node
   */
  isPointInside(x2, y2) {
    return isInRect(x2, y2, this.boundingRect);
  }
  /**
   * Checks if the provided point is inside this node's collapse button area.
   * @param x X co-ordinate to check
   * @param y Y co-ordinate to check
   * @returns true if the x,y point is in the collapse button area, otherwise false
   */
  isPointInCollapse(x2, y2) {
    const squareLength = LiteGraph.NODE_TITLE_HEIGHT;
    return isInRectangle(
      x2,
      y2,
      this.pos[0],
      this.pos[1] - squareLength,
      squareLength,
      squareLength
    );
  }
  /**
   * Returns the input slot at the given position. Uses full 20 height, and approximates the label length.
   * @param pos The graph co-ordinates to check
   * @returns The input slot at the given position if found, otherwise `undefined`.
   */
  getInputOnPos(pos) {
    return getNodeInputOnPos(this, pos[0], pos[1])?.input;
  }
  /**
   * Returns the output slot at the given position. Uses full 20x20 box for the slot.
   * @param pos The graph co-ordinates to check
   * @returns The output slot at the given position if found, otherwise `undefined`.
   */
  getOutputOnPos(pos) {
    return getNodeOutputOnPos(this, pos[0], pos[1])?.output;
  }
  /**
   * Returns the input or output slot at the given position.
   *
   * Tries {@link getNodeInputOnPos} first, then {@link getNodeOutputOnPos}.
   * @param pos The graph co-ordinates to check
   * @returns The input or output slot at the given position if found, otherwise `undefined`.
   */
  getSlotOnPos(pos) {
    if (!isPointInRect(pos, this.boundingRect)) return;
    return this.getInputOnPos(pos) ?? this.getOutputOnPos(pos);
  }
  /**
   * @deprecated Use {@link getSlotOnPos} instead.
   * checks if a point is inside a node slot, and returns info about which slot
   * @param x
   * @param y
   * @returns if found the object contains { input|output: slot object, slot: number, link_pos: [x,y] }
   */
  getSlotInPosition(x2, y2) {
    const { inputs, outputs } = this;
    if (inputs) {
      for (const [i2, input] of inputs.entries()) {
        const pos = this.getInputPos(i2);
        if (isInRectangle(x2, y2, pos[0] - 10, pos[1] - 10, 20, 20)) {
          return { input, slot: i2, link_pos: pos };
        }
      }
    }
    if (outputs) {
      for (const [i2, output] of outputs.entries()) {
        const pos = this.getOutputPos(i2);
        if (isInRectangle(x2, y2, pos[0] - 10, pos[1] - 10, 20, 20)) {
          return { output, slot: i2, link_pos: pos };
        }
      }
    }
    return null;
  }
  /**
   * Gets the widget on this node at the given co-ordinates.
   * @param canvasX X co-ordinate in graph space
   * @param canvasY Y co-ordinate in graph space
   * @returns The widget found, otherwise `null`
   */
  getWidgetOnPos(canvasX, canvasY, includeDisabled = false) {
    const { widgets, pos, size } = this;
    if (!widgets?.length) return;
    const x2 = canvasX - pos[0];
    const y2 = canvasY - pos[1];
    const nodeWidth = size[0];
    for (const widget of widgets) {
      if (widget.computedDisabled && !includeDisabled || !this.isWidgetVisible(widget)) {
        continue;
      }
      const h2 = widget.computedHeight ?? widget.computeSize?.(nodeWidth)[1] ?? LiteGraph.NODE_WIDGET_HEIGHT;
      const w2 = widget.width || nodeWidth;
      if (widget.last_y !== void 0 && isInRectangle(x2, y2, 6, widget.last_y, w2 - 12, h2)) {
        return widget;
      }
    }
  }
  findInputSlot(name2, returnObj = false) {
    const { inputs } = this;
    if (!inputs) return -1;
    for (const [i2, input] of inputs.entries()) {
      if (name2 == input.name) {
        return !returnObj ? i2 : input;
      }
    }
    return -1;
  }
  findOutputSlot(name2, returnObj = false) {
    const { outputs } = this;
    if (!outputs) return -1;
    for (const [i2, output] of outputs.entries()) {
      if (name2 == output.name) {
        return !returnObj ? i2 : output;
      }
    }
    return -1;
  }
  findInputSlotFree(optsIn) {
    return this.#findFreeSlot(this.inputs, optsIn);
  }
  findOutputSlotFree(optsIn) {
    return this.#findFreeSlot(this.outputs, optsIn);
  }
  /**
   * Finds the next free slot
   * @param slots The slots to search, i.e. this.inputs or this.outputs
   */
  #findFreeSlot(slots, options2) {
    const defaults2 = {
      returnObj: false,
      typesNotAccepted: []
    };
    const opts = Object.assign(defaults2, options2 || {});
    const length = slots?.length;
    if (!(length > 0)) return -1;
    for (let i2 = 0; i2 < length; ++i2) {
      const slot = slots[i2];
      if (!slot || slot.link || slot.links?.length) continue;
      if (opts.typesNotAccepted?.includes?.(slot.type)) continue;
      return !opts.returnObj ? i2 : slot;
    }
    return -1;
  }
  findInputSlotByType(type, returnObj, preferFreeSlot, doNotUseOccupied) {
    return this.#findSlotByType(
      this.inputs,
      type,
      returnObj,
      preferFreeSlot,
      doNotUseOccupied
    );
  }
  findOutputSlotByType(type, returnObj, preferFreeSlot, doNotUseOccupied) {
    return this.#findSlotByType(
      this.outputs,
      type,
      returnObj,
      preferFreeSlot,
      doNotUseOccupied
    );
  }
  findSlotByType(input, type, returnObj, preferFreeSlot, doNotUseOccupied) {
    return input ? this.#findSlotByType(
      this.inputs,
      type,
      returnObj,
      preferFreeSlot,
      doNotUseOccupied
    ) : this.#findSlotByType(
      this.outputs,
      type,
      returnObj,
      preferFreeSlot,
      doNotUseOccupied
    );
  }
  /**
   * Finds a matching slot from those provided, returning the slot itself or its index in {@link slots}.
   * @param slots Slots to search (this.inputs or this.outputs)
   * @param type Type of slot to look for
   * @param returnObj If true, returns the slot itself.  Otherwise, the index.
   * @param preferFreeSlot Prefer a free slot, but if none are found, fall back to an occupied slot.
   * @param doNotUseOccupied Do not fall back to occupied slots.
   * @see {findSlotByType}
   * @see {findOutputSlotByType}
   * @see {findInputSlotByType}
   * @returns If a match is found, the slot if returnObj is true, otherwise the index.  If no matches are found, -1
   */
  #findSlotByType(slots, type, returnObj, preferFreeSlot, doNotUseOccupied) {
    const length = slots?.length;
    if (!length) return -1;
    if (type == "" || type == "*") type = 0;
    const sourceTypes = String(type).toLowerCase().split(",");
    let occupiedSlot = null;
    for (let i2 = 0; i2 < length; ++i2) {
      const slot = slots[i2];
      const destTypes = slot.type == "0" || slot.type == "*" ? ["0"] : String(slot.type).toLowerCase().split(",");
      for (const sourceType of sourceTypes) {
        const source = sourceType == "_event_" ? LiteGraph.EVENT : sourceType;
        for (const destType of destTypes) {
          const dest = destType == "_event_" ? LiteGraph.EVENT : destType;
          if (source == dest || source === "*" || dest === "*") {
            if (preferFreeSlot && (slot.links?.length || slot.link != null)) {
              occupiedSlot ??= returnObj ? slot : i2;
              continue;
            }
            return returnObj ? slot : i2;
          }
        }
      }
    }
    return doNotUseOccupied ? -1 : occupiedSlot ?? -1;
  }
  /**
   * Determines the slot index to connect to when attempting to connect by type.
   * @param findInputs If true, searches for an input.  Otherwise, an output.
   * @param node The node at the other end of the connection.
   * @param slotType The type of slot at the other end of the connection.
   * @param options Search restrictions to adhere to.
   * @see {connectByType}
   * @see {connectByTypeOutput}
   */
  findConnectByTypeSlot(findInputs, node2, slotType, options2) {
    if (options2 && typeof options2 === "object") {
      if ("firstFreeIfInputGeneralInCase" in options2) options2.wildcardToTyped = !!options2.firstFreeIfInputGeneralInCase;
      if ("firstFreeIfOutputGeneralInCase" in options2) options2.wildcardToTyped = !!options2.firstFreeIfOutputGeneralInCase;
      if ("generalTypeInCase" in options2) options2.typedToWildcard = !!options2.generalTypeInCase;
    }
    const optsDef = {
      createEventInCase: true,
      wildcardToTyped: true,
      typedToWildcard: true
    };
    const opts = Object.assign(optsDef, options2);
    if (!this.graph) throw new NullGraphError();
    if (node2 && typeof node2 === "number") {
      const nodeById = this.graph.getNodeById(node2);
      if (!nodeById) return;
      node2 = nodeById;
    }
    const slot = node2.findSlotByType(findInputs, slotType, false, true);
    if (slot >= 0 && slot !== null) return slot;
    if (opts.createEventInCase && slotType == LiteGraph.EVENT) {
      if (findInputs) return -1;
      if (LiteGraph.do_add_triggers_slots) return node2.addOnExecutedOutput();
    }
    if (opts.typedToWildcard) {
      const generalSlot = node2.findSlotByType(findInputs, 0, false, true, true);
      if (generalSlot >= 0) return generalSlot;
    }
    if (opts.wildcardToTyped && (slotType == 0 || slotType == "*" || slotType == "")) {
      const opt = { typesNotAccepted: [LiteGraph.EVENT] };
      const nonEventSlot = findInputs ? node2.findInputSlotFree(opt) : node2.findOutputSlotFree(opt);
      if (nonEventSlot >= 0) return nonEventSlot;
    }
  }
  /**
   * Finds the first free output slot with any of the comma-delimited types in {@link type}.
   *
   * If no slots are free, falls back in order to:
   * - The first free wildcard slot
   * - The first occupied slot
   * - The first occupied wildcard slot
   * @param type The {@link ISlotType type} of slot to find
   * @returns The index and slot if found, otherwise `undefined`.
   */
  findOutputByType(type) {
    return findFreeSlotOfType(this.outputs, type);
  }
  /**
   * Finds the first free input slot with any of the comma-delimited types in {@link type}.
   *
   * If no slots are free, falls back in order to:
   * - The first free wildcard slot
   * - The first occupied slot
   * - The first occupied wildcard slot
   * @param type The {@link ISlotType type} of slot to find
   * @returns The index and slot if found, otherwise `undefined`.
   */
  findInputByType(type) {
    return findFreeSlotOfType(this.inputs, type);
  }
  /**
   * connect this node output to the input of another node BY TYPE
   * @param slot (could be the number of the slot or the string with the name of the slot)
   * @param target_node the target node
   * @param target_slotType the input slot type of the target node
   * @returns the link_info is created, otherwise null
   */
  connectByType(slot, target_node, target_slotType, optsIn) {
    const slotIndex = this.findConnectByTypeSlot(
      true,
      target_node,
      target_slotType,
      optsIn
    );
    if (slotIndex !== void 0)
      return this.connect(slot, target_node, slotIndex, optsIn?.afterRerouteId);
    console.debug("[connectByType]: no way to connect type:", target_slotType, "to node:", target_node);
    return null;
  }
  /**
   * connect this node input to the output of another node BY TYPE
   * @param slot (could be the number of the slot or the string with the name of the slot)
   * @param source_node the target node
   * @param source_slotType the output slot type of the target node
   * @returns the link_info is created, otherwise null
   */
  connectByTypeOutput(slot, source_node, source_slotType, optsIn) {
    if (typeof optsIn === "object") {
      if ("firstFreeIfInputGeneralInCase" in optsIn) optsIn.wildcardToTyped = !!optsIn.firstFreeIfInputGeneralInCase;
      if ("generalTypeInCase" in optsIn) optsIn.typedToWildcard = !!optsIn.generalTypeInCase;
    }
    const slotIndex = this.findConnectByTypeSlot(
      false,
      source_node,
      source_slotType,
      optsIn
    );
    if (slotIndex !== void 0)
      return source_node.connect(slotIndex, this, slot, optsIn?.afterRerouteId);
    console.debug("[connectByType]: no way to connect type:", source_slotType, "to node:", source_node);
    return null;
  }
  canConnectTo(node2, toSlot, fromSlot) {
    return this.id !== node2.id && LiteGraph.isValidConnection(fromSlot.type, toSlot.type);
  }
  /**
   * Connect an output of this node to an input of another node
   * @param slot (could be the number of the slot or the string with the name of the slot)
   * @param target_node the target node
   * @param target_slot the input slot of the target node (could be the number of the slot or the string with the name of the slot, or -1 to connect a trigger)
   * @returns the link_info is created, otherwise null
   */
  connect(slot, target_node, target_slot, afterRerouteId) {
    let targetIndex;
    const { graph, outputs } = this;
    if (!graph) {
      console.log("Connect: Error, node doesn't belong to any graph. Nodes must be added first to a graph before connecting them.");
      return null;
    }
    if (typeof slot === "string") {
      slot = this.findOutputSlot(slot);
      if (slot == -1) {
        if (LiteGraph.debug) console.log(`Connect: Error, no slot of name ${slot}`);
        return null;
      }
    } else if (!outputs || slot >= outputs.length) {
      if (LiteGraph.debug) console.log("Connect: Error, slot number not found");
      return null;
    }
    if (target_node && typeof target_node === "number") {
      const nodeById = graph.getNodeById(target_node);
      if (!nodeById) throw "target node is null";
      target_node = nodeById;
    }
    if (!target_node) throw "target node is null";
    if (target_node == this) return null;
    if (typeof target_slot === "string") {
      targetIndex = target_node.findInputSlot(target_slot);
      if (targetIndex == -1) {
        if (LiteGraph.debug) console.log(`Connect: Error, no slot of name ${targetIndex}`);
        return null;
      }
    } else if (target_slot === LiteGraph.EVENT) {
      if (LiteGraph.do_add_triggers_slots) {
        target_node.changeMode(LGraphEventMode.ON_TRIGGER);
        targetIndex = target_node.findInputSlot("onTrigger");
      } else {
        return null;
      }
    } else if (typeof target_slot === "number") {
      targetIndex = target_slot;
    } else {
      targetIndex = 0;
    }
    if (target_node.onBeforeConnectInput) {
      const requestedIndex = target_node.onBeforeConnectInput(targetIndex, target_slot);
      targetIndex = typeof requestedIndex === "number" ? requestedIndex : null;
    }
    if (targetIndex === null || !target_node.inputs || targetIndex >= target_node.inputs.length) {
      if (LiteGraph.debug) console.log("Connect: Error, slot number not found");
      return null;
    }
    const input = target_node.inputs[targetIndex];
    const output = outputs[slot];
    if (!output) return null;
    if (output.links?.length) {
      if (output.type === LiteGraph.EVENT && !LiteGraph.allow_multi_output_for_events) {
        graph.beforeChange();
        this.disconnectOutput(slot, false, { doProcessChange: false });
      }
    }
    const link2 = this.connectSlots(output, target_node, input, afterRerouteId);
    return link2 ?? null;
  }
  /**
   * Connect two slots between two nodes
   * @param output The output slot to connect
   * @param inputNode The node that the input slot is on
   * @param input The input slot to connect
   * @param afterRerouteId The reroute ID to use for the link
   * @returns The link that was created, or null if the connection was blocked
   */
  connectSlots(output, inputNode, input, afterRerouteId) {
    const { graph } = this;
    if (!graph) throw new NullGraphError();
    const outputIndex = this.outputs.indexOf(output);
    if (outputIndex === -1) {
      console.warn("connectSlots: output not found");
      return;
    }
    const inputIndex = inputNode.inputs.indexOf(input);
    if (inputIndex === -1) {
      console.warn("connectSlots: input not found");
      return;
    }
    if (!LiteGraph.isValidConnection(output.type, input.type)) {
      this.setDirtyCanvas(false, true);
      return null;
    }
    if (inputNode.onConnectInput?.(inputIndex, output.type, output, this, outputIndex) === false)
      return null;
    if (this.onConnectOutput?.(outputIndex, input.type, input, inputNode, inputIndex) === false)
      return null;
    if (inputNode.inputs[inputIndex]?.link != null) {
      graph.beforeChange();
      inputNode.disconnectInput(inputIndex, true);
    }
    const link2 = new LLink(
      ++graph.state.lastLinkId,
      input.type || output.type,
      this.id,
      outputIndex,
      inputNode.id,
      inputIndex,
      afterRerouteId
    );
    graph._links.set(link2.id, link2);
    output.links ??= [];
    output.links.push(link2.id);
    inputNode.inputs[inputIndex].link = link2.id;
    const reroutes = LLink.getReroutes(graph, link2);
    for (const reroute of reroutes) {
      reroute.linkIds.add(link2.id);
      if (reroute.floating) delete reroute.floating;
      reroute._dragging = void 0;
    }
    const lastReroute = reroutes.at(-1);
    if (lastReroute) {
      for (const linkId of lastReroute.floatingLinkIds) {
        const link22 = graph.floatingLinks.get(linkId);
        if (link22?.parentId === lastReroute.id) {
          graph.removeFloatingLink(link22);
        }
      }
    }
    graph._version++;
    this.onConnectionsChange?.(
      NodeSlotType.OUTPUT,
      outputIndex,
      true,
      link2,
      output
    );
    inputNode.onConnectionsChange?.(
      NodeSlotType.INPUT,
      inputIndex,
      true,
      link2,
      input
    );
    this.setDirtyCanvas(false, true);
    graph.afterChange();
    graph.connectionChange(this);
    return link2;
  }
  connectFloatingReroute(pos, slot, afterRerouteId) {
    const { graph, id: id2 } = this;
    if (!graph) throw new NullGraphError();
    const inputIndex = this.inputs.indexOf(slot);
    const outputIndex = this.outputs.indexOf(slot);
    if (inputIndex === -1 && outputIndex === -1) throw new Error("Invalid slot");
    const slotType = outputIndex === -1 ? "input" : "output";
    const reroute = graph.setReroute({
      pos,
      parentId: afterRerouteId,
      linkIds: [],
      floating: { slotType }
    });
    const parentReroute = graph.getReroute(afterRerouteId);
    const fromLastFloatingReroute = parentReroute?.floating?.slotType === "output";
    if (afterRerouteId == null || !fromLastFloatingReroute) {
      const link22 = new LLink(
        -1,
        slot.type,
        outputIndex === -1 ? -1 : id2,
        outputIndex,
        inputIndex === -1 ? -1 : id2,
        inputIndex
      );
      link22.parentId = reroute.id;
      graph.addFloatingLink(link22);
      return reroute;
    }
    if (!parentReroute) throw new Error("[connectFloatingReroute] Parent reroute not found");
    const link2 = parentReroute.getFloatingLinks("output")?.[0];
    if (!link2) throw new Error("[connectFloatingReroute] Floating link not found");
    reroute.floatingLinkIds.add(link2.id);
    link2.parentId = reroute.id;
    delete parentReroute.floating;
    return reroute;
  }
  /**
   * disconnect one output to an specific node
   * @param slot (could be the number of the slot or the string with the name of the slot)
   * @param target_node the target node to which this slot is connected [Optional,
   * if not target_node is specified all nodes will be disconnected]
   * @returns if it was disconnected successfully
   */
  disconnectOutput(slot, target_node) {
    if (typeof slot === "string") {
      slot = this.findOutputSlot(slot);
      if (slot == -1) {
        if (LiteGraph.debug) console.log(`Connect: Error, no slot of name ${slot}`);
        return false;
      }
    } else if (!this.outputs || slot >= this.outputs.length) {
      if (LiteGraph.debug) console.log("Connect: Error, slot number not found");
      return false;
    }
    const output = this.outputs[slot];
    if (!output) return false;
    if (output._floatingLinks) {
      for (const link2 of output._floatingLinks) {
        if (link2.hasOrigin(this.id, slot)) {
          this.graph?.removeFloatingLink(link2);
        }
      }
    }
    if (!output.links || output.links.length == 0) return false;
    const { links } = output;
    const graph = this.graph;
    if (!graph) throw new NullGraphError();
    if (target_node) {
      const target = typeof target_node === "number" ? graph.getNodeById(target_node) : target_node;
      if (!target) throw "Target Node not found";
      for (const [i2, link_id] of links.entries()) {
        const link_info = graph._links.get(link_id);
        if (link_info?.target_id != target.id) continue;
        links.splice(i2, 1);
        const input = target.inputs[link_info.target_slot];
        input.link = null;
        link_info.disconnect(graph, "input");
        graph._version++;
        target.onConnectionsChange?.(
          NodeSlotType.INPUT,
          link_info.target_slot,
          false,
          link_info,
          input
        );
        this.onConnectionsChange?.(
          NodeSlotType.OUTPUT,
          slot,
          false,
          link_info,
          output
        );
        break;
      }
    } else {
      for (const link_id of links) {
        const link_info = graph._links.get(link_id);
        if (!link_info) continue;
        const target = graph.getNodeById(link_info.target_id);
        graph._version++;
        if (target) {
          const input = target.inputs[link_info.target_slot];
          input.link = null;
          target.onConnectionsChange?.(
            NodeSlotType.INPUT,
            link_info.target_slot,
            false,
            link_info,
            input
          );
        }
        link_info.disconnect(graph, "input");
        this.onConnectionsChange?.(
          NodeSlotType.OUTPUT,
          slot,
          false,
          link_info,
          output
        );
      }
      output.links = null;
    }
    this.setDirtyCanvas(false, true);
    graph.connectionChange(this);
    return true;
  }
  /**
   * Disconnect one input
   * @param slot Input slot index, or the name of the slot
   * @param keepReroutes If `true`, reroutes will not be garbage collected.
   * @returns true if disconnected successfully or already disconnected, otherwise false
   */
  disconnectInput(slot, keepReroutes) {
    if (typeof slot === "string") {
      slot = this.findInputSlot(slot);
      if (slot == -1) {
        if (LiteGraph.debug) console.log(`Connect: Error, no slot of name ${slot}`);
        return false;
      }
    } else if (!this.inputs || slot >= this.inputs.length) {
      if (LiteGraph.debug) {
        console.log("Connect: Error, slot number not found");
      }
      return false;
    }
    const input = this.inputs[slot];
    if (!input) return false;
    const { graph } = this;
    if (!graph) throw new NullGraphError();
    if (input._floatingLinks?.size) {
      for (const link2 of input._floatingLinks) {
        graph.removeFloatingLink(link2);
      }
    }
    const link_id = this.inputs[slot].link;
    if (link_id != null) {
      this.inputs[slot].link = null;
      const link_info = graph._links.get(link_id);
      if (link_info) {
        const target_node = graph.getNodeById(link_info.origin_id);
        if (!target_node) return false;
        const output = target_node.outputs[link_info.origin_slot];
        if (!output?.links?.length) return false;
        let i2 = 0;
        for (const l2 = output.links.length; i2 < l2; i2++) {
          if (output.links[i2] == link_id) {
            output.links.splice(i2, 1);
            break;
          }
        }
        link_info.disconnect(graph, keepReroutes ? "output" : void 0);
        if (graph) graph._version++;
        this.onConnectionsChange?.(
          NodeSlotType.INPUT,
          slot,
          false,
          link_info,
          input
        );
        target_node.onConnectionsChange?.(
          NodeSlotType.OUTPUT,
          i2,
          false,
          link_info,
          output
        );
      }
    }
    this.setDirtyCanvas(false, true);
    graph?.connectionChange(this);
    return true;
  }
  /**
   * @deprecated Use {@link getInputPos} or {@link getOutputPos} instead.
   * returns the center of a connection point in canvas coords
   * @param is_input true if if a input slot, false if it is an output
   * @param slot_number (could be the number of the slot or the string with the name of the slot)
   * @param out [optional] a place to store the output, to free garbage
   * @returns the position
   */
  getConnectionPos(is_input, slot_number, out) {
    out ||= new Float32Array(2);
    const { pos: [nodeX, nodeY], inputs, outputs } = this;
    if (this.flags.collapsed) {
      const w2 = this._collapsed_width || LiteGraph.NODE_COLLAPSED_WIDTH;
      out[0] = is_input ? nodeX : nodeX + w2;
      out[1] = nodeY - LiteGraph.NODE_TITLE_HEIGHT * 0.5;
      return out;
    }
    if (is_input && slot_number == -1) {
      out[0] = nodeX + LiteGraph.NODE_TITLE_HEIGHT * 0.5;
      out[1] = nodeY + LiteGraph.NODE_TITLE_HEIGHT * 0.5;
      return out;
    }
    const inputPos = inputs?.[slot_number]?.pos;
    const outputPos = outputs?.[slot_number]?.pos;
    if (is_input && inputPos) {
      out[0] = nodeX + inputPos[0];
      out[1] = nodeY + inputPos[1];
      return out;
    } else if (!is_input && outputPos) {
      out[0] = nodeX + outputPos[0];
      out[1] = nodeY + outputPos[1];
      return out;
    }
    const offset = LiteGraph.NODE_SLOT_HEIGHT * 0.5;
    const slotIndex = is_input ? this.#defaultVerticalInputs.indexOf(this.inputs[slot_number]) : this.#defaultVerticalOutputs.indexOf(this.outputs[slot_number]);
    out[0] = is_input ? nodeX + offset : nodeX + this.size[0] + 1 - offset;
    out[1] = nodeY + (slotIndex + 0.7) * LiteGraph.NODE_SLOT_HEIGHT + (this.constructor.slot_start_y || 0);
    return out;
  }
  /**
   * @internal The inputs that are not positioned with absolute coordinates.
   */
  get #defaultVerticalInputs() {
    return this.inputs.filter(
      (slot) => !slot.pos && !(this.widgets?.length && isWidgetInputSlot(slot))
    );
  }
  /**
   * @internal The outputs that are not positioned with absolute coordinates.
   */
  get #defaultVerticalOutputs() {
    return this.outputs.filter((slot) => !slot.pos);
  }
  /**
   * Gets the position of an input slot, in graph co-ordinates.
   *
   * This method is preferred over the legacy {@link getConnectionPos} method.
   * @param slot Input slot index
   * @returns Position of the input slot
   */
  getInputPos(slot) {
    return this.getInputSlotPos(this.inputs[slot]);
  }
  /**
   * Gets the position of an input slot, in graph co-ordinates.
   * @param input The actual node input object
   * @returns Position of the centre of the input slot in graph co-ordinates.
   */
  getInputSlotPos(input) {
    const { pos: [nodeX, nodeY] } = this;
    if (this.flags.collapsed) {
      const halfTitle = LiteGraph.NODE_TITLE_HEIGHT * 0.5;
      return [nodeX, nodeY - halfTitle];
    }
    const { pos } = input;
    if (pos) return [nodeX + pos[0], nodeY + pos[1]];
    const offsetX = LiteGraph.NODE_SLOT_HEIGHT * 0.5;
    const nodeOffsetY = this.constructor.slot_start_y || 0;
    const slotIndex = this.#defaultVerticalInputs.indexOf(input);
    const slotY = (slotIndex + 0.7) * LiteGraph.NODE_SLOT_HEIGHT;
    return [nodeX + offsetX, nodeY + slotY + nodeOffsetY];
  }
  /**
   * Gets the position of an output slot, in graph co-ordinates.
   *
   * This method is preferred over the legacy {@link getConnectionPos} method.
   * @param slot Output slot index
   * @returns Position of the output slot
   */
  getOutputPos(slot) {
    const { pos: [nodeX, nodeY], outputs, size: [width2] } = this;
    if (this.flags.collapsed) {
      const width22 = this._collapsed_width || LiteGraph.NODE_COLLAPSED_WIDTH;
      const halfTitle = LiteGraph.NODE_TITLE_HEIGHT * 0.5;
      return [nodeX + width22, nodeY - halfTitle];
    }
    const outputPos = outputs?.[slot]?.pos;
    if (outputPos) return [nodeX + outputPos[0], nodeY + outputPos[1]];
    const offsetX = LiteGraph.NODE_SLOT_HEIGHT * 0.5;
    const nodeOffsetY = this.constructor.slot_start_y || 0;
    const slotIndex = this.#defaultVerticalOutputs.indexOf(this.outputs[slot]);
    const slotY = (slotIndex + 0.7) * LiteGraph.NODE_SLOT_HEIGHT;
    return [nodeX + width2 + 1 - offsetX, nodeY + slotY + nodeOffsetY];
  }
  /** @inheritdoc */
  snapToGrid(snapTo) {
    return this.pinned ? false : snapPoint(this.pos, snapTo);
  }
  /** @see {@link snapToGrid} */
  alignToGrid() {
    this.snapToGrid(LiteGraph.CANVAS_GRID_SIZE);
  }
  /* Console output */
  trace(msg) {
    this.console ||= [];
    this.console.push(msg);
    if (this.console.length > LGraphNode.MAX_CONSOLE)
      this.console.shift();
  }
  /* Forces to redraw or the main canvas (LGraphNode) or the bg canvas (links) */
  setDirtyCanvas(dirty_foreground, dirty_background) {
    this.graph?.canvasAction((c2) => c2.setDirty(dirty_foreground, dirty_background));
  }
  loadImage(url) {
    const img = new Image();
    img.src = LiteGraph.node_images_path + url;
    img.ready = false;
    const dirty = /* @__PURE__ */ __name(() => this.setDirtyCanvas(true), "dirty");
    img.addEventListener("load", function() {
      this.ready = true;
      dirty();
    });
    return img;
  }
  /* Allows to get onMouseMove and onMouseUp events even if the mouse is out of focus */
  captureInput(v2) {
    if (!this.graph || !this.graph.list_of_graphcanvas) return;
    const list2 = this.graph.list_of_graphcanvas;
    for (const c2 of list2) {
      if (!v2 && c2.node_capturing_input != this) continue;
      c2.node_capturing_input = v2 ? this : null;
    }
  }
  get collapsed() {
    return !!this.flags.collapsed;
  }
  get collapsible() {
    return !this.pinned && this.constructor.collapsable !== false;
  }
  /**
   * Toggle node collapse (makes it smaller on the canvas)
   */
  collapse(force) {
    if (!this.collapsible && !force) return;
    if (!this.graph) throw new NullGraphError();
    this.graph._version++;
    this.flags.collapsed = !this.flags.collapsed;
    this.setDirtyCanvas(true, true);
  }
  /**
   * Toggles advanced mode of the node, showing advanced widgets
   */
  toggleAdvanced() {
    if (!this.widgets?.some((w2) => w2.advanced)) return;
    if (!this.graph) throw new NullGraphError();
    this.graph._version++;
    this.showAdvanced = !this.showAdvanced;
    this.expandToFitContent();
    this.setDirtyCanvas(true, true);
  }
  get pinned() {
    return !!this.flags.pinned;
  }
  /**
   * Prevents the node being accidentally moved or resized by mouse interaction.
   * Toggles pinned state if no value is provided.
   */
  pin(v2) {
    if (!this.graph) throw new NullGraphError();
    this.graph._version++;
    this.flags.pinned = v2 ?? !this.flags.pinned;
    this.resizable = !this.pinned;
    if (!this.pinned) delete this.flags.pinned;
  }
  unpin() {
    this.pin(false);
  }
  localToScreen(x2, y2, dragAndScale) {
    return [
      (x2 + this.pos[0]) * dragAndScale.scale + dragAndScale.offset[0],
      (y2 + this.pos[1]) * dragAndScale.scale + dragAndScale.offset[1]
    ];
  }
  get width() {
    return this.collapsed ? this._collapsed_width || LiteGraph.NODE_COLLAPSED_WIDTH : this.size[0];
  }
  /**
   * Returns the height of the node, including the title bar.
   */
  get height() {
    return LiteGraph.NODE_TITLE_HEIGHT + this.bodyHeight;
  }
  /**
   * Returns the height of the node, excluding the title bar.
   */
  get bodyHeight() {
    return this.collapsed ? 0 : this.size[1];
  }
  drawBadges(ctx, { gap = 2 } = {}) {
    const badgeInstances = this.badges.map((badge) => badge instanceof LGraphBadge ? badge : badge());
    const isLeftAligned = this.badgePosition === BadgePosition.TopLeft;
    let currentX = isLeftAligned ? 0 : this.width - badgeInstances.reduce((acc, badge) => acc + badge.getWidth(ctx) + gap, 0);
    const y2 = -(LiteGraph.NODE_TITLE_HEIGHT + gap);
    for (const badge of badgeInstances) {
      badge.draw(ctx, currentX, y2 - badge.height);
      currentX += badge.getWidth(ctx) + gap;
    }
  }
  /**
   * Renders the node's title bar background
   */
  drawTitleBarBackground(ctx, {
    scale,
    title_height = LiteGraph.NODE_TITLE_HEIGHT,
    low_quality = false
  }) {
    const fgcolor = this.renderingColor;
    const shape = this.renderingShape;
    const size = this.renderingSize;
    if (this.onDrawTitleBar) {
      this.onDrawTitleBar(ctx, title_height, size, scale, fgcolor);
      return;
    }
    if (this.title_mode === TitleMode.TRANSPARENT_TITLE) {
      return;
    }
    if (this.collapsed) {
      ctx.shadowColor = LiteGraph.DEFAULT_SHADOW_COLOR;
    }
    ctx.fillStyle = this.constructor.title_color || fgcolor;
    ctx.beginPath();
    if (shape == RenderShape.BOX || low_quality) {
      ctx.rect(0, -title_height, size[0], title_height);
    } else if (shape == RenderShape.ROUND || shape == RenderShape.CARD) {
      ctx.roundRect(
        0,
        -title_height,
        size[0],
        title_height,
        this.collapsed ? [LiteGraph.ROUND_RADIUS] : [LiteGraph.ROUND_RADIUS, LiteGraph.ROUND_RADIUS, 0, 0]
      );
    }
    ctx.fill();
    ctx.shadowColor = "transparent";
  }
  /**
   * Renders the node's title box, i.e. the dot in front of the title text that
   * when clicked toggles the node's collapsed state. The term `title box` comes
   * from the original LiteGraph implementation.
   */
  drawTitleBox(ctx, {
    scale,
    low_quality = false,
    title_height = LiteGraph.NODE_TITLE_HEIGHT,
    box_size = 10
  }) {
    const size = this.renderingSize;
    const shape = this.renderingShape;
    if (this.onDrawTitleBox) {
      this.onDrawTitleBox(ctx, title_height, size, scale);
      return;
    }
    if ([RenderShape.ROUND, RenderShape.CIRCLE, RenderShape.CARD].includes(shape)) {
      if (low_quality) {
        ctx.fillStyle = "black";
        ctx.beginPath();
        ctx.arc(
          title_height * 0.5,
          title_height * -0.5,
          box_size * 0.5 + 1,
          0,
          Math.PI * 2
        );
        ctx.fill();
      }
      ctx.fillStyle = this.renderingBoxColor;
      if (low_quality) {
        ctx.fillRect(
          title_height * 0.5 - box_size * 0.5,
          title_height * -0.5 - box_size * 0.5,
          box_size,
          box_size
        );
      } else {
        ctx.beginPath();
        ctx.arc(
          title_height * 0.5,
          title_height * -0.5,
          box_size * 0.5,
          0,
          Math.PI * 2
        );
        ctx.fill();
      }
    } else {
      if (low_quality) {
        ctx.fillStyle = "black";
        ctx.fillRect(
          (title_height - box_size) * 0.5 - 1,
          (title_height + box_size) * -0.5 - 1,
          box_size + 2,
          box_size + 2
        );
      }
      ctx.fillStyle = this.renderingBoxColor;
      ctx.fillRect(
        (title_height - box_size) * 0.5,
        (title_height + box_size) * -0.5,
        box_size,
        box_size
      );
    }
  }
  /**
   * Renders the node's title text.
   */
  drawTitleText(ctx, {
    scale,
    default_title_color,
    low_quality = false,
    title_height = LiteGraph.NODE_TITLE_HEIGHT
  }) {
    const size = this.renderingSize;
    const selected = this.selected;
    if (this.onDrawTitleText) {
      this.onDrawTitleText(
        ctx,
        title_height,
        size,
        scale,
        this.titleFontStyle,
        selected
      );
      return;
    }
    if (low_quality) {
      return;
    }
    ctx.font = this.titleFontStyle;
    const rawTitle = this.getTitle() ?? `❌ ${this.type}`;
    const title = String(rawTitle) + (this.pinned ? "📌" : "");
    if (title) {
      if (selected) {
        ctx.fillStyle = LiteGraph.NODE_SELECTED_TITLE_COLOR;
      } else {
        ctx.fillStyle = this.constructor.title_text_color || default_title_color;
      }
      if (this.collapsed) {
        ctx.textAlign = "left";
        ctx.fillText(
          // avoid urls too long
          title.substr(0, 20),
          title_height,
          LiteGraph.NODE_TITLE_TEXT_Y - title_height
        );
        ctx.textAlign = "left";
      } else {
        ctx.textAlign = "left";
        ctx.fillText(
          title,
          title_height,
          LiteGraph.NODE_TITLE_TEXT_Y - title_height
        );
      }
    }
  }
  /**
   * Attempts to gracefully bypass this node in all of its connections by reconnecting all links.
   *
   * Each input is checked against each output.  This is done on a matching index basis, i.e. input 3 -> output 3.
   * If there are any input links remaining,
   * and {@link flags}.{@link INodeFlags.keepAllLinksOnBypass keepAllLinksOnBypass} is `true`,
   * each input will check for outputs that match, and take the first one that matches
   * `true`: Try the index matching first, then every input to every output.
   * `false`: Only matches indexes, e.g. input 3 to output 3.
   *
   * If {@link flags}.{@link INodeFlags.keepAllLinksOnBypass keepAllLinksOnBypass} is `undefined`, it will fall back to
   * the static {@link keepAllLinksOnBypass}.
   * @returns `true` if any new links were established, otherwise `false`.
   * @todo Decision: Change API to return array of new links instead?
   */
  connectInputToOutput() {
    const { inputs, outputs, graph } = this;
    if (!inputs || !outputs) return;
    if (!graph) throw new NullGraphError();
    const { _links } = graph;
    let madeAnyConnections = false;
    for (const [index2, input] of inputs.entries()) {
      if (input.link == null) continue;
      const output = outputs[index2];
      if (!output || !LiteGraph.isValidConnection(input.type, output.type)) continue;
      const inLink = _links.get(input.link);
      if (!inLink) continue;
      const inNode = graph.getNodeById(inLink?.origin_id);
      if (!inNode) continue;
      bypassAllLinks(output, inNode, inLink, graph);
    }
    if (!(this.flags.keepAllLinksOnBypass ?? LGraphNode.keepAllLinksOnBypass))
      return madeAnyConnections;
    for (const input of inputs) {
      if (input.link == null) continue;
      const inLink = _links.get(input.link);
      if (!inLink) continue;
      const inNode = graph.getNodeById(inLink?.origin_id);
      if (!inNode) continue;
      for (const output of outputs) {
        if (!LiteGraph.isValidConnection(input.type, output.type)) continue;
        bypassAllLinks(output, inNode, inLink, graph);
        break;
      }
    }
    return madeAnyConnections;
    function bypassAllLinks(output, inNode, inLink, graph2) {
      const outLinks = output.links?.map((x2) => _links.get(x2)).filter((x2) => !!x2);
      if (!outLinks?.length) return;
      for (const outLink of outLinks) {
        const outNode = graph2.getNodeById(outLink.target_id);
        if (!outNode) continue;
        const result = inNode.connect(
          inLink.origin_slot,
          outNode,
          outLink.target_slot,
          inLink.parentId
        );
        madeAnyConnections ||= !!result;
      }
    }
    __name(bypassAllLinks, "bypassAllLinks");
  }
  /**
   * Returns `true` if the widget is visible, otherwise `false`.
   */
  isWidgetVisible(widget) {
    const isHidden2 = this.collapsed || widget.hidden || widget.advanced && !this.showAdvanced;
    return !isHidden2;
  }
  drawWidgets(ctx, {
    lowQuality = false,
    editorAlpha = 1
  }) {
    if (!this.widgets) return;
    const nodeWidth = this.size[0];
    const { widgets } = this;
    const H2 = LiteGraph.NODE_WIDGET_HEIGHT;
    const showText = !lowQuality;
    ctx.save();
    ctx.globalAlpha = editorAlpha;
    for (const widget of widgets) {
      if (!this.isWidgetVisible(widget)) continue;
      const { y: y2 } = widget;
      const outlineColour = widget.advanced ? LiteGraph.WIDGET_ADVANCED_OUTLINE_COLOR : LiteGraph.WIDGET_OUTLINE_COLOR;
      widget.last_y = y2;
      widget.computedDisabled = widget.disabled || this.getSlotFromWidget(widget)?.link != null;
      ctx.strokeStyle = outlineColour;
      ctx.fillStyle = "#222";
      ctx.textAlign = "left";
      if (widget.computedDisabled) ctx.globalAlpha *= 0.5;
      const width2 = widget.width || nodeWidth;
      const widgetInstance = toConcreteWidget(widget, this, false);
      if (widgetInstance) {
        widgetInstance.drawWidget(ctx, { width: width2, showText });
      } else {
        widget.draw?.(ctx, this, width2, y2, H2, lowQuality);
      }
      ctx.globalAlpha = editorAlpha;
    }
    ctx.restore();
  }
  /**
   * When {@link LGraphNode.collapsed} is `true`, this method draws the node's collapsed slots.
   */
  drawCollapsedSlots(ctx) {
    for (const slot of this.#concreteInputs) {
      if (slot.link != null) {
        slot.drawCollapsed(ctx);
        break;
      }
    }
    for (const slot of this.#concreteOutputs) {
      if (slot.links?.length) {
        slot.drawCollapsed(ctx);
        break;
      }
    }
  }
  get slots() {
    return [...this.inputs, ...this.outputs];
  }
  #measureSlot(slot, slotIndex, isInput) {
    const pos = isInput ? this.getInputPos(slotIndex) : this.getOutputPos(slotIndex);
    slot.boundingRect[0] = pos[0] - LiteGraph.NODE_SLOT_HEIGHT * 0.5;
    slot.boundingRect[1] = pos[1] - LiteGraph.NODE_SLOT_HEIGHT * 0.5;
    slot.boundingRect[2] = slot.isWidgetInputSlot ? BaseWidget.margin : LiteGraph.NODE_SLOT_HEIGHT;
    slot.boundingRect[3] = LiteGraph.NODE_SLOT_HEIGHT;
  }
  #measureSlots() {
    const slots = [];
    for (const [slotIndex, slot] of this.#concreteInputs.entries()) {
      if (this.widgets?.length && isWidgetInputSlot(slot)) continue;
      this.#measureSlot(slot, slotIndex, true);
      slots.push(slot);
    }
    for (const [slotIndex, slot] of this.#concreteOutputs.entries()) {
      this.#measureSlot(slot, slotIndex, false);
      slots.push(slot);
    }
    return slots.length ? createBounds(slots, 0) : null;
  }
  #getMouseOverSlot(slot) {
    const isInput = isINodeInputSlot(slot);
    const mouseOverId = this.mouseOver?.[isInput ? "inputId" : "outputId"] ?? -1;
    if (mouseOverId === -1) {
      return null;
    }
    return isInput ? this.inputs[mouseOverId] : this.outputs[mouseOverId];
  }
  #isMouseOverSlot(slot) {
    return this.#getMouseOverSlot(slot) === slot;
  }
  #isMouseOverWidget(widget) {
    if (!widget) return false;
    return this.mouseOver?.overWidget === widget;
  }
  /**
   * Returns the input slot that is associated with the given widget.
   */
  getSlotFromWidget(widget) {
    if (widget) return this.inputs.find((slot) => isWidgetInputSlot(slot) && slot.widget.name === widget.name);
  }
  /**
   * Returns the widget that is associated with the given input slot.
   */
  getWidgetFromSlot(slot) {
    if (!isWidgetInputSlot(slot)) return;
    return this.widgets?.find((w2) => w2.name === slot.widget.name);
  }
  /**
   * Draws the node's input and output slots.
   */
  drawSlots(ctx, {
    fromSlot,
    colorContext,
    editorAlpha,
    lowQuality
  }) {
    for (const slot of [...this.#concreteInputs, ...this.#concreteOutputs]) {
      const isValidTarget = fromSlot && slot.isValidTarget(fromSlot);
      const isMouseOverSlot = this.#isMouseOverSlot(slot);
      const isValid2 = !fromSlot || isValidTarget;
      const highlight = isValid2 && isMouseOverSlot;
      if (isMouseOverSlot || isValidTarget || !slot.isWidgetInputSlot || this.#isMouseOverWidget(this.getWidgetFromSlot(slot)) || slot.isConnected) {
        ctx.globalAlpha = isValid2 ? editorAlpha : 0.4 * editorAlpha;
        slot.draw(ctx, {
          colorContext,
          lowQuality,
          highlight
        });
      }
    }
  }
  /**
   * Arranges the node's widgets vertically.
   * Sets following properties on each widget:
   * -  {@link IBaseWidget.computedHeight}
   * -  {@link IBaseWidget.y}
   * @param widgetStartY The y-coordinate of the first widget
   */
  #arrangeWidgets(widgetStartY) {
    if (!this.widgets || !this.widgets.length) return;
    const bodyHeight = this.bodyHeight;
    const startY = this.widgets_start_y ?? (this.widgets_up ? 0 : widgetStartY) + 2;
    let freeSpace = bodyHeight - startY;
    let fixedWidgetHeight = 0;
    const growableWidgets = [];
    for (const w2 of this.widgets) {
      if (w2.computeSize) {
        const height = w2.computeSize()[1] + 4;
        w2.computedHeight = height;
        fixedWidgetHeight += height;
      } else if (w2.computeLayoutSize) {
        const { minHeight, maxHeight } = w2.computeLayoutSize(this);
        growableWidgets.push({
          minHeight,
          prefHeight: maxHeight,
          w: w2
        });
      } else {
        const height = LiteGraph.NODE_WIDGET_HEIGHT + 4;
        w2.computedHeight = height;
        fixedWidgetHeight += height;
      }
    }
    freeSpace -= fixedWidgetHeight;
    this.freeWidgetSpace = freeSpace;
    const spaceRequests = growableWidgets.map((d2) => ({
      minSize: d2.minHeight,
      maxSize: d2.prefHeight
    }));
    const allocations = distributeSpace(Math.max(0, freeSpace), spaceRequests);
    for (const [i2, d2] of growableWidgets.entries()) {
      d2.w.computedHeight = allocations[i2];
    }
    let y2 = startY;
    for (const w2 of this.widgets) {
      w2.y = y2;
      y2 += w2.computedHeight ?? 0;
    }
    if (!this.graph) throw new NullGraphError();
    if (y2 > bodyHeight) {
      this.setSize([this.size[0], y2]);
      this.graph.setDirtyCanvas(false, true);
    }
  }
  /**
   * Arranges the layout of the node's widget input slots.
   */
  #arrangeWidgetInputSlots() {
    if (!this.widgets) return;
    const slotByWidgetName = /* @__PURE__ */ new Map();
    for (const [i2, slot] of this.inputs.entries()) {
      if (!isWidgetInputSlot(slot)) continue;
      slotByWidgetName.set(slot.widget.name, { ...slot, index: i2 });
    }
    if (!slotByWidgetName.size) return;
    for (const widget of this.widgets) {
      const slot = slotByWidgetName.get(widget.name);
      if (!slot) continue;
      const actualSlot = this.#concreteInputs[slot.index];
      const offset = LiteGraph.NODE_SLOT_HEIGHT * 0.5;
      actualSlot.pos = [offset, widget.y + offset];
      this.#measureSlot(actualSlot, slot.index, true);
    }
  }
  /**
   * @internal Sets the internal concrete slot arrays, ensuring they are instances of
   * {@link NodeInputSlot} or {@link NodeOutputSlot}.
   *
   * A temporary workaround until duck-typed inputs and outputs
   * have been removed from the ecosystem.
   */
  _setConcreteSlots() {
    this.#concreteInputs = this.inputs.map((slot) => toClass(NodeInputSlot, slot, this));
    this.#concreteOutputs = this.outputs.map((slot) => toClass(NodeOutputSlot, slot, this));
  }
  /**
   * Arranges node elements in preparation for rendering (slots & widgets).
   */
  arrange() {
    const slotsBounds = this.#measureSlots();
    const widgetStartY = slotsBounds ? slotsBounds[1] + slotsBounds[3] - this.pos[1] : 0;
    this.#arrangeWidgets(widgetStartY);
    this.#arrangeWidgetInputSlots();
  }
  /**
   * Draws a progress bar on the node.
   * @param ctx The canvas context to draw on
   */
  drawProgressBar(ctx) {
    if (!this.progress) return;
    const originalFillStyle = ctx.fillStyle;
    ctx.fillStyle = "green";
    ctx.fillRect(
      0,
      0,
      this.width * this.progress,
      6
    );
    ctx.fillStyle = originalFillStyle;
  }
}
class LGraphGroup {
  static {
    __name(this, "LGraphGroup");
  }
  static minWidth = 140;
  static minHeight = 80;
  static resizeLength = 10;
  static padding = 4;
  static defaultColour = "#335";
  id;
  color;
  title;
  font;
  font_size = LiteGraph.DEFAULT_GROUP_FONT || 24;
  _bounding = new Float32Array([
    10,
    10,
    LGraphGroup.minWidth,
    LGraphGroup.minHeight
  ]);
  _pos = this._bounding.subarray(0, 2);
  _size = this._bounding.subarray(2, 4);
  /** @deprecated See {@link _children} */
  _nodes = [];
  _children = /* @__PURE__ */ new Set();
  graph;
  flags = {};
  selected;
  constructor(title, id2) {
    this.id = id2 ?? -1;
    this.title = title || "Group";
    const { pale_blue } = LGraphCanvas.node_colors;
    this.color = pale_blue ? pale_blue.groupcolor : "#AAA";
  }
  /** @inheritdoc {@link IColorable.setColorOption} */
  setColorOption(colorOption) {
    if (colorOption == null) {
      delete this.color;
    } else {
      this.color = colorOption.groupcolor;
    }
  }
  /** @inheritdoc {@link IColorable.getColorOption} */
  getColorOption() {
    return Object.values(LGraphCanvas.node_colors).find(
      (colorOption) => colorOption.groupcolor === this.color
    ) ?? null;
  }
  /** Position of the group, as x,y co-ordinates in graph space */
  get pos() {
    return this._pos;
  }
  set pos(v2) {
    if (!v2 || v2.length < 2) return;
    this._pos[0] = v2[0];
    this._pos[1] = v2[1];
  }
  /** Size of the group, as width,height in graph units */
  get size() {
    return this._size;
  }
  set size(v2) {
    if (!v2 || v2.length < 2) return;
    this._size[0] = Math.max(LGraphGroup.minWidth, v2[0]);
    this._size[1] = Math.max(LGraphGroup.minHeight, v2[1]);
  }
  get boundingRect() {
    return this._bounding;
  }
  get nodes() {
    return this._nodes;
  }
  get titleHeight() {
    return this.font_size * 1.4;
  }
  get children() {
    return this._children;
  }
  get pinned() {
    return !!this.flags.pinned;
  }
  /**
   * Prevents the group being accidentally moved or resized by mouse interaction.
   * Toggles pinned state if no value is provided.
   */
  pin(value) {
    const newState = value === void 0 ? !this.pinned : value;
    if (newState) this.flags.pinned = true;
    else delete this.flags.pinned;
  }
  unpin() {
    this.pin(false);
  }
  configure(o2) {
    this.id = o2.id;
    this.title = o2.title;
    this._bounding.set(o2.bounding);
    this.color = o2.color;
    this.flags = o2.flags || this.flags;
    if (o2.font_size) this.font_size = o2.font_size;
  }
  serialize() {
    const b2 = this._bounding;
    return {
      id: this.id,
      title: this.title,
      bounding: [...b2],
      color: this.color,
      font_size: this.font_size,
      flags: this.flags
    };
  }
  /**
   * Draws the group on the canvas
   * @param graphCanvas
   * @param ctx
   */
  draw(graphCanvas, ctx) {
    const { padding, resizeLength, defaultColour } = LGraphGroup;
    const font_size = this.font_size || LiteGraph.DEFAULT_GROUP_FONT_SIZE;
    const [x2, y2] = this._pos;
    const [width2, height] = this._size;
    const color2 = this.color || defaultColour;
    ctx.globalAlpha = 0.25 * graphCanvas.editor_alpha;
    ctx.fillStyle = color2;
    ctx.strokeStyle = color2;
    ctx.beginPath();
    ctx.rect(x2 + 0.5, y2 + 0.5, width2, font_size * 1.4);
    ctx.fill();
    ctx.fillStyle = color2;
    ctx.strokeStyle = color2;
    ctx.beginPath();
    ctx.rect(x2 + 0.5, y2 + 0.5, width2, height);
    ctx.fill();
    ctx.globalAlpha = graphCanvas.editor_alpha;
    ctx.stroke();
    ctx.beginPath();
    ctx.moveTo(x2 + width2, y2 + height);
    ctx.lineTo(x2 + width2 - resizeLength, y2 + height);
    ctx.lineTo(x2 + width2, y2 + height - resizeLength);
    ctx.fill();
    ctx.font = `${font_size}px ${LiteGraph.GROUP_FONT}`;
    ctx.textAlign = "left";
    ctx.fillText(this.title + (this.pinned ? "📌" : ""), x2 + padding, y2 + font_size);
    if (LiteGraph.highlight_selected_group && this.selected) {
      strokeShape(ctx, this._bounding, {
        title_height: this.titleHeight,
        padding
      });
    }
  }
  resize(width2, height) {
    if (this.pinned) return false;
    this._size[0] = Math.max(LGraphGroup.minWidth, width2);
    this._size[1] = Math.max(LGraphGroup.minHeight, height);
    return true;
  }
  move(deltaX, deltaY, skipChildren = false) {
    if (this.pinned) return;
    this._pos[0] += deltaX;
    this._pos[1] += deltaY;
    if (skipChildren === true) return;
    for (const item of this._children) {
      item.move(deltaX, deltaY);
    }
  }
  /** @inheritdoc */
  snapToGrid(snapTo) {
    return this.pinned ? false : snapPoint(this.pos, snapTo);
  }
  recomputeInsideNodes() {
    if (!this.graph) throw new NullGraphError();
    const { nodes, reroutes, groups } = this.graph;
    const children = this._children;
    this._nodes.length = 0;
    children.clear();
    for (const node2 of nodes) {
      if (containsCentre(this._bounding, node2.boundingRect)) {
        this._nodes.push(node2);
        children.add(node2);
      }
    }
    for (const reroute of reroutes.values()) {
      if (isPointInRect(reroute.pos, this._bounding))
        children.add(reroute);
    }
    for (const group of groups) {
      if (containsRect(this._bounding, group._bounding))
        children.add(group);
    }
    groups.sort((a2, b2) => {
      if (a2 === this) {
        return children.has(b2) ? -1 : 0;
      } else if (b2 === this) {
        return children.has(a2) ? 1 : 0;
      } else {
        return 0;
      }
    });
  }
  /**
   * Resizes and moves the group to neatly fit all given {@link objects}.
   * @param objects All objects that should be inside the group
   * @param padding Value in graph units to add to all sides of the group.  Default: 10
   */
  resizeTo(objects, padding = 10) {
    const boundingBox = createBounds(objects, padding);
    if (boundingBox === null) return;
    this.pos[0] = boundingBox[0];
    this.pos[1] = boundingBox[1] - this.titleHeight;
    this.size[0] = boundingBox[2];
    this.size[1] = boundingBox[3] + this.titleHeight;
  }
  /**
   * Add nodes to the group and adjust the group's position and size accordingly
   * @param nodes The nodes to add to the group
   * @param padding The padding around the group
   */
  addNodes(nodes, padding = 10) {
    if (!this._nodes && nodes.length === 0) return;
    this.resizeTo([...this.children, ...this._nodes, ...nodes], padding);
  }
  getMenuOptions() {
    return [
      {
        content: this.pinned ? "Unpin" : "Pin",
        callback: /* @__PURE__ */ __name(() => {
          if (this.pinned) this.unpin();
          else this.pin();
          this.setDirtyCanvas(false, true);
        }, "callback")
      },
      null,
      { content: "Title", callback: LGraphCanvas.onShowPropertyEditor },
      {
        content: "Color",
        has_submenu: true,
        callback: LGraphCanvas.onMenuNodeColors
      },
      {
        content: "Font size",
        property: "font_size",
        type: "Number",
        callback: LGraphCanvas.onShowPropertyEditor
      },
      null,
      { content: "Remove", callback: LGraphCanvas.onMenuNodeRemove }
    ];
  }
  isPointInTitlebar(x2, y2) {
    const b2 = this.boundingRect;
    return isInRectangle(x2, y2, b2[0], b2[1], b2[2], this.titleHeight);
  }
  isInResize(x2, y2) {
    const b2 = this.boundingRect;
    const right = b2[0] + b2[2];
    const bottom = b2[1] + b2[3];
    return x2 < right && y2 < bottom && x2 - right + (y2 - bottom) > -LGraphGroup.resizeLength;
  }
  isPointInside = LGraphNode.prototype.isPointInside;
  setDirtyCanvas = LGraphNode.prototype.setDirtyCanvas;
}
class Reroute {
  static {
    __name(this, "Reroute");
  }
  /**
   * Initialises a new link reroute object.
   * @param id Unique identifier for this reroute
   * @param network The network of links this reroute belongs to.  Internally converted to a WeakRef.
   * @param pos Position in graph coordinates
   * @param linkIds Link IDs ({@link LLink.id}) of all links that use this reroute
   */
  constructor(id2, network, pos, parentId, linkIds, floatingLinkIds) {
    this.id = id2;
    this.#network = new WeakRef(network);
    this.parentId = parentId;
    if (pos) this.pos = pos;
    this.linkIds = new Set(linkIds);
    this.floatingLinkIds = new Set(floatingLinkIds);
  }
  static radius = 10;
  /** Maximum distance from reroutes to their bezier curve control points. */
  static maxSplineOffset = 80;
  static drawIdBadge = false;
  static slotRadius = 5;
  /** Distance from reroute centre to slot centre. */
  static get slotOffset() {
    const gap = Reroute.slotRadius * 0.33;
    return Reroute.radius + gap + Reroute.slotRadius;
  }
  #malloc = new Float32Array(8);
  /** The network this reroute belongs to.  Contains all valid links and reroutes. */
  #network;
  #parentId;
  get parentId() {
    return this.#parentId;
  }
  /** Ignores attempts to create an infinite loop. @inheritdoc */
  set parentId(value) {
    if (value === this.id) return;
    if (this.getReroutes() === null) return;
    this.#parentId = value;
  }
  get parent() {
    return this.#network.deref()?.getReroute(this.#parentId);
  }
  /** This property is only defined on the last reroute of a floating reroute chain (closest to input end). */
  floating;
  #pos = this.#malloc.subarray(0, 2);
  /** @inheritdoc */
  get pos() {
    return this.#pos;
  }
  set pos(value) {
    if (!(value?.length >= 2))
      throw new TypeError("Reroute.pos is an x,y point, and expects an indexable with at least two values.");
    this.#pos[0] = value[0];
    this.#pos[1] = value[1];
  }
  /** @inheritdoc */
  get boundingRect() {
    const { radius } = Reroute;
    const [x2, y2] = this.#pos;
    return [x2 - radius, y2 - radius, 2 * radius, 2 * radius];
  }
  /**
   * Slightly over-sized rectangle, guaranteed to contain the entire surface area for hover detection.
   * Eliminates most hover positions using an extremely cheap check.
   */
  get #hoverArea() {
    const xOffset = 2 * Reroute.slotOffset;
    const yOffset = 2 * Math.max(Reroute.radius, Reroute.slotRadius);
    const [x2, y2] = this.#pos;
    return [x2 - xOffset, y2 - yOffset, 2 * xOffset, 2 * yOffset];
  }
  /** The total number of links & floating links using this reroute */
  get totalLinks() {
    return this.linkIds.size + this.floatingLinkIds.size;
  }
  /** @inheritdoc */
  selected;
  /** The ID ({@link LLink.id}) of every link using this reroute */
  linkIds;
  /** The ID ({@link LLink.id}) of every floating link using this reroute */
  floatingLinkIds;
  /** Cached cos */
  cos = 0;
  sin = 0;
  /** Bezier curve control point for the "target" (input) side of the link */
  controlPoint = this.#malloc.subarray(4, 6);
  /** @inheritdoc */
  path;
  /** @inheritdoc */
  _centreAngle;
  /** @inheritdoc */
  _pos = this.#malloc.subarray(6, 8);
  /** @inheritdoc */
  _dragging;
  /** Colour of the first link that rendered this reroute */
  _colour;
  /** Colour of the first link that rendered this reroute */
  get colour() {
    return this._colour ?? "#18184d";
  }
  /**
   * Used to ensure reroute angles are only executed once per frame.
   * @todo Calculate on change instead.
   */
  #lastRenderTime = -Infinity;
  #inputSlot = new RerouteSlot(this, true);
  #outputSlot = new RerouteSlot(this, false);
  get isSlotHovered() {
    return this.isInputHovered || this.isOutputHovered;
  }
  get isInputHovered() {
    return this.#inputSlot.hovering;
  }
  get isOutputHovered() {
    return this.#outputSlot.hovering;
  }
  get firstLink() {
    const linkId = this.linkIds.values().next().value;
    return linkId === void 0 ? void 0 : this.#network.deref()?.links.get(linkId);
  }
  get firstFloatingLink() {
    const linkId = this.floatingLinkIds.values().next().value;
    return linkId === void 0 ? void 0 : this.#network.deref()?.floatingLinks.get(linkId);
  }
  /** @inheritdoc */
  get origin_id() {
    return this.firstLink?.origin_id;
  }
  /** @inheritdoc */
  get origin_slot() {
    return this.firstLink?.origin_slot;
  }
  /**
   * Applies a new parentId to the reroute, and optinoally a new position and linkId.
   * Primarily used for deserialisation.
   * @param parentId The ID of the reroute prior to this reroute, or
   * `undefined` if it is the first reroute connected to a nodes output
   * @param pos The position of this reroute
   * @param linkIds All link IDs that pass through this reroute
   */
  update(parentId, pos, linkIds, floating) {
    this.parentId = parentId;
    if (pos) this.pos = pos;
    if (linkIds) this.linkIds = new Set(linkIds);
    this.floating = floating;
  }
  /**
   * Validates the linkIds this reroute has.  Removes broken links.
   * @param links Collection of valid links
   * @returns true if any links remain after validation
   */
  validateLinks(links, floatingLinks) {
    const { linkIds, floatingLinkIds } = this;
    for (const linkId of linkIds) {
      if (!links.has(linkId)) linkIds.delete(linkId);
    }
    for (const linkId of floatingLinkIds) {
      if (!floatingLinks.has(linkId)) floatingLinkIds.delete(linkId);
    }
    return linkIds.size > 0 || floatingLinkIds.size > 0;
  }
  /**
   * Retrieves an ordered array of all reroutes from the node output.
   * @param visited Internal.  A set of reroutes that this function
   * has already visited whilst recursing up the chain.
   * @returns An ordered array of all reroutes from the node output to this reroute, inclusive.
   * `null` if an infinite loop is detected.
   * `undefined` if the reroute chain or {@link LinkNetwork} are invalid.
   */
  getReroutes(visited = /* @__PURE__ */ new Set()) {
    if (this.#parentId === void 0) return [this];
    if (visited.has(this)) return null;
    visited.add(this);
    const parent2 = this.#network.deref()?.reroutes.get(this.#parentId);
    if (!parent2) {
      this.#parentId = void 0;
      return [this];
    }
    const reroutes = parent2.getReroutes(visited);
    reroutes?.push(this);
    return reroutes;
  }
  /**
   * Internal.  Called by {@link LLink.findNextReroute}.  Not intended for use by itself.
   * @param withParentId The rerouteId to look for
   * @param visited A set of reroutes that have already been visited
   * @returns The reroute that was found, `undefined` if no reroute was found, or `null` if an infinite loop was detected.
   */
  findNextReroute(withParentId, visited = /* @__PURE__ */ new Set()) {
    if (this.#parentId === withParentId) return this;
    if (visited.has(this)) return null;
    visited.add(this);
    if (this.#parentId === void 0) return;
    return this.#network.deref()?.reroutes.get(this.#parentId)?.findNextReroute(withParentId, visited);
  }
  /**
   * Finds the output node and output slot of the first link passing through this reroute.
   * @returns The output node and output slot of the first link passing through this reroute, or `undefined` if no link is found.
   */
  findSourceOutput() {
    const link2 = this.firstLink ?? this.firstFloatingLink;
    if (!link2) return;
    const node2 = this.#network.deref()?.getNodeById(link2.origin_id);
    if (!node2) return;
    return {
      node: node2,
      output: node2.outputs[link2.origin_slot]
    };
  }
  /**
   * Finds the inputs and nodes of (floating) links passing through this reroute.
   * @returns An array of objects containing the node and input slot of each link passing through this reroute.
   */
  findTargetInputs() {
    const network = this.#network.deref();
    if (!network) return;
    const results = [];
    addAllResults(network, this.linkIds, network.links);
    addAllResults(network, this.floatingLinkIds, network.floatingLinks);
    return results;
    function addAllResults(network2, linkIds, links) {
      for (const linkId of linkIds) {
        const link2 = links.get(linkId);
        if (!link2) continue;
        const node2 = network2.getNodeById(link2.target_id);
        const input = node2?.inputs[link2.target_slot];
        if (!input) continue;
        results.push({ node: node2, input, link: link2 });
      }
    }
    __name(addAllResults, "addAllResults");
  }
  /**
   * Retrieves all floating links passing through this reroute.
   * @param from Filters the links by the currently connected link side.
   * @returns An array of floating links
   */
  getFloatingLinks(from2) {
    const floatingLinks = this.#network.deref()?.floatingLinks;
    if (!floatingLinks) return;
    const idProp = from2 === "input" ? "origin_id" : "target_id";
    const out = [];
    for (const linkId of this.floatingLinkIds) {
      const link2 = floatingLinks.get(linkId);
      if (link2?.[idProp] === -1) out.push(link2);
    }
    return out;
  }
  /**
   * Changes the origin node/output of all floating links that pass through this reroute.
   * @param node The new origin node
   * @param output The new origin output slot
   * @param index The slot index of {@link output}
   */
  setFloatingLinkOrigin(node2, output, index2) {
    const network = this.#network.deref();
    const floatingOutLinks = this.getFloatingLinks("output");
    if (!floatingOutLinks) throw new Error("[setFloatingLinkOrigin]: Invalid network.");
    if (!floatingOutLinks.length) return;
    output._floatingLinks ??= /* @__PURE__ */ new Set();
    for (const link2 of floatingOutLinks) {
      output._floatingLinks.add(link2);
      network?.getNodeById(link2.origin_id)?.outputs[link2.origin_slot]?._floatingLinks?.delete(link2);
      link2.origin_id = node2.id;
      link2.origin_slot = index2;
    }
  }
  /** @inheritdoc */
  move(deltaX, deltaY) {
    this.#pos[0] += deltaX;
    this.#pos[1] += deltaY;
  }
  /** @inheritdoc */
  snapToGrid(snapTo) {
    if (!snapTo) return false;
    const { pos } = this;
    pos[0] = snapTo * Math.round(pos[0] / snapTo);
    pos[1] = snapTo * Math.round(pos[1] / snapTo);
    return true;
  }
  removeAllFloatingLinks() {
    for (const linkId of this.floatingLinkIds) {
      this.removeFloatingLink(linkId);
    }
  }
  removeFloatingLink(linkId) {
    const network = this.#network.deref();
    if (!network) return;
    const floatingLink = network.floatingLinks.get(linkId);
    if (!floatingLink) {
      console.warn(`[Reroute.removeFloatingLink] Floating link not found: ${linkId}, ignoring and discarding ID.`);
      this.floatingLinkIds.delete(linkId);
      return;
    }
    network.removeFloatingLink(floatingLink);
  }
  /**
   * Removes a link or floating link from this reroute, by matching link object instance equality.
   * @param link The link to remove.
   * @remarks Does not remove the link from the network.
   */
  removeLink(link2) {
    const network = this.#network.deref();
    if (!network) return;
    const floatingLink = network.floatingLinks.get(link2.id);
    if (link2 === floatingLink) {
      this.floatingLinkIds.delete(link2.id);
    } else {
      this.linkIds.delete(link2.id);
    }
  }
  remove() {
    const network = this.#network.deref();
    if (!network) return;
    network.removeReroute(this.id);
  }
  calculateAngle(lastRenderTime, network, linkStart) {
    if (!(lastRenderTime > this.#lastRenderTime)) return;
    this.#lastRenderTime = lastRenderTime;
    const { id: id2, pos: thisPos } = this;
    const angles = [];
    let sum2 = 0;
    calculateAngles(this.linkIds, network.links);
    calculateAngles(this.floatingLinkIds, network.floatingLinks);
    if (!angles.length) {
      this.cos = 0;
      this.sin = 0;
      this.controlPoint[0] = 0;
      this.controlPoint[1] = 0;
      return;
    }
    sum2 /= angles.length;
    const originToReroute = Math.atan2(
      this.#pos[1] - linkStart[1],
      this.#pos[0] - linkStart[0]
    );
    let diff2 = (originToReroute - sum2) * 0.5;
    if (Math.abs(diff2) > Math.PI * 0.5) diff2 += Math.PI;
    const dist3 = Math.min(Reroute.maxSplineOffset, distance(linkStart, this.#pos) * 0.25);
    const originDiff = originToReroute - diff2;
    const cos = Math.cos(originDiff);
    const sin = Math.sin(originDiff);
    this.cos = cos;
    this.sin = sin;
    this.controlPoint[0] = dist3 * -cos;
    this.controlPoint[1] = dist3 * -sin;
    function calculateAngles(linkIds, links) {
      for (const linkId of linkIds) {
        const link2 = links.get(linkId);
        const pos = getNextPos(network, link2, id2);
        if (!pos) continue;
        const angle = getDirection(thisPos, pos);
        angles.push(angle);
        sum2 += angle;
      }
    }
    __name(calculateAngles, "calculateAngles");
  }
  /**
   * Renders the reroute on the canvas.
   * @param ctx Canvas context to draw on
   * @param backgroundPattern The canvas background pattern; used to make floating reroutes appear washed out.
   * @remarks Leaves {@link ctx}.fillStyle, strokeStyle, and lineWidth dirty (perf.).
   */
  draw(ctx, backgroundPattern) {
    const { globalAlpha } = ctx;
    const { pos } = this;
    ctx.beginPath();
    ctx.arc(pos[0], pos[1], Reroute.radius, 0, 2 * Math.PI);
    if (this.linkIds.size === 0) {
      ctx.fillStyle = backgroundPattern ?? "#797979";
      ctx.fill();
      ctx.globalAlpha = globalAlpha * 0.33;
    }
    ctx.fillStyle = this.colour;
    ctx.lineWidth = Reroute.radius * 0.1;
    ctx.strokeStyle = "rgb(0,0,0,0.5)";
    ctx.fill();
    ctx.stroke();
    ctx.fillStyle = "#ffffff55";
    ctx.strokeStyle = "rgb(0,0,0,0.3)";
    ctx.beginPath();
    ctx.arc(pos[0], pos[1], Reroute.radius * 0.8, 0, 2 * Math.PI);
    ctx.fill();
    ctx.stroke();
    if (this.selected) {
      ctx.strokeStyle = "#fff";
      ctx.beginPath();
      ctx.arc(pos[0], pos[1], Reroute.radius * 1.2, 0, 2 * Math.PI);
      ctx.stroke();
    }
    if (Reroute.drawIdBadge) {
      const idBadge = new LGraphBadge({ text: this.id.toString() });
      const x2 = pos[0] - idBadge.getWidth(ctx) * 0.5;
      const y2 = pos[1] - idBadge.height - Reroute.radius - 2;
      idBadge.draw(ctx, x2, y2);
    }
    ctx.globalAlpha = globalAlpha;
  }
  /**
   * Draws the input and output slots on the canvas, if the slots are visible.
   * @param ctx The canvas context to draw on.
   */
  drawSlots(ctx) {
    this.#inputSlot.draw(ctx);
    this.#outputSlot.draw(ctx);
  }
  drawHighlight(ctx, colour) {
    const { pos } = this;
    const { strokeStyle, lineWidth } = ctx;
    ctx.strokeStyle = colour;
    ctx.lineWidth = 1;
    ctx.beginPath();
    ctx.arc(pos[0], pos[1], Reroute.radius * 1.5, 0, 2 * Math.PI);
    ctx.stroke();
    ctx.strokeStyle = strokeStyle;
    ctx.lineWidth = lineWidth;
  }
  /**
   * Updates visibility of the input and output slots, based on the position of the pointer.
   * @param pos The position of the pointer.
   * @returns `true` if any changes require a redraw.
   */
  updateVisibility(pos) {
    const input = this.#inputSlot;
    const output = this.#outputSlot;
    input.dirty = false;
    output.dirty = false;
    const { firstFloatingLink } = this;
    const hasLink = !!this.firstLink;
    const showInput = hasLink || firstFloatingLink?.isFloatingOutput;
    const showOutput = hasLink || firstFloatingLink?.isFloatingInput;
    const showEither = showInput || showOutput;
    if (showEither && isPointInRect(pos, this.#hoverArea)) {
      const outlineOnly = this.#contains(pos);
      if (showInput) input.update(pos, outlineOnly);
      if (showOutput) output.update(pos, outlineOnly);
    } else {
      this.hideSlots();
    }
    return input.dirty || output.dirty;
  }
  /** Prevents rendering of the input and output slots. */
  hideSlots() {
    this.#inputSlot.hide();
    this.#outputSlot.hide();
  }
  /**
   * Precisely determines if {@link pos} is inside this reroute.
   * @param pos The position to check (canvas space)
   * @returns `true` if {@link pos} is within the reroute's radius.
   */
  containsPoint(pos) {
    return isPointInRect(pos, this.#hoverArea) && this.#contains(pos);
  }
  #contains(pos) {
    return distance(this.pos, pos) <= Reroute.radius;
  }
  /** @inheritdoc */
  asSerialisable() {
    const { id: id2, parentId, pos, linkIds } = this;
    return {
      id: id2,
      parentId,
      pos: [pos[0], pos[1]],
      linkIds: [...linkIds],
      floating: this.floating ? { slotType: this.floating.slotType } : void 0
    };
  }
}
class RerouteSlot {
  static {
    __name(this, "RerouteSlot");
  }
  /** The reroute that the slot belongs to. */
  #reroute;
  #offsetMultiplier;
  /** Centre point of this slot. */
  get pos() {
    const [x2, y2] = this.#reroute.pos;
    return [x2 + Reroute.slotOffset * this.#offsetMultiplier, y2];
  }
  /** Whether any changes require a redraw. */
  dirty = false;
  #hovering = false;
  /** Whether the pointer is hovering over the slot itself. */
  get hovering() {
    return this.#hovering;
  }
  set hovering(value) {
    if (!Object.is(this.#hovering, value)) {
      this.#hovering = value;
      this.dirty = true;
    }
  }
  #showOutline = false;
  /** Whether the slot outline / faint background is visible. */
  get showOutline() {
    return this.#showOutline;
  }
  set showOutline(value) {
    if (!Object.is(this.#showOutline, value)) {
      this.#showOutline = value;
      this.dirty = true;
    }
  }
  constructor(reroute, isInput) {
    this.#reroute = reroute;
    this.#offsetMultiplier = isInput ? -1 : 1;
  }
  /**
   * Updates the slot's visibility based on the position of the pointer.
   * @param pos The position of the pointer.
   * @param outlineOnly If `true`, slot will display with the faded outline only ({@link showOutline}).
   */
  update(pos, outlineOnly) {
    if (outlineOnly) {
      this.hovering = false;
      this.showOutline = true;
    } else {
      const dist3 = distance(this.pos, pos);
      this.hovering = dist3 <= 2 * Reroute.slotRadius;
      this.showOutline = dist3 <= 5 * Reroute.slotRadius;
    }
  }
  /** Hides the slot. */
  hide() {
    this.hovering = false;
    this.showOutline = false;
  }
  /**
   * Draws the slot on the canvas.
   * @param ctx The canvas context to draw on.
   */
  draw(ctx) {
    const { fillStyle, strokeStyle, lineWidth } = ctx;
    const { showOutline, hovering, pos: [x2, y2] } = this;
    if (!showOutline) return;
    try {
      ctx.fillStyle = hovering ? this.#reroute.colour : "rgba(127,127,127,0.3)";
      ctx.strokeStyle = "rgb(0,0,0,0.5)";
      ctx.lineWidth = 1;
      ctx.beginPath();
      ctx.arc(x2, y2, Reroute.slotRadius, 0, 2 * Math.PI);
      ctx.fill();
      ctx.stroke();
    } finally {
      ctx.fillStyle = fillStyle;
      ctx.strokeStyle = strokeStyle;
      ctx.lineWidth = lineWidth;
    }
  }
}
function getNextPos(network, link2, id2) {
  if (!link2) return;
  const linkPos = LLink.findNextReroute(network, link2, id2)?.pos;
  if (linkPos) return linkPos;
  if (link2.target_id === -1 || link2.target_slot === -1) return;
  return network.getNodeById(link2.target_id)?.getInputPos(link2.target_slot);
}
__name(getNextPos, "getNextPos");
function getDirection(fromPos, toPos) {
  return Math.atan2(toPos[1] - fromPos[1], toPos[0] - fromPos[0]);
}
__name(getDirection, "getDirection");
function getBoundaryNodes(nodes) {
  const valid = nodes?.find((x2) => x2);
  if (!valid) return null;
  let top = valid;
  let right = valid;
  let bottom = valid;
  let left = valid;
  for (const node2 of nodes) {
    if (!node2) continue;
    const [x2, y2] = node2.pos;
    const [width2, height] = node2.size;
    if (y2 < top.pos[1]) top = node2;
    if (x2 + width2 > right.pos[0] + right.size[0]) right = node2;
    if (y2 + height > bottom.pos[1] + bottom.size[1]) bottom = node2;
    if (x2 < left.pos[0]) left = node2;
  }
  return {
    top,
    right,
    bottom,
    left
  };
}
__name(getBoundaryNodes, "getBoundaryNodes");
function distributeNodes(nodes, horizontal) {
  const nodeCount = nodes?.length;
  if (!(nodeCount > 1)) return;
  const index2 = horizontal ? 0 : 1;
  let total = 0;
  let highest = -Infinity;
  for (const node2 of nodes) {
    total += node2.size[index2];
    const high = node2.pos[index2] + node2.size[index2];
    if (high > highest) highest = high;
  }
  const sorted = [...nodes].sort((a2, b2) => a2.pos[index2] - b2.pos[index2]);
  const lowest = sorted[0].pos[index2];
  const gap = (highest - lowest - total) / (nodeCount - 1);
  let startAt2 = lowest;
  for (let i2 = 0; i2 < nodeCount; i2++) {
    const node2 = sorted[i2];
    node2.pos[index2] = startAt2 + gap * i2;
    startAt2 += node2.size[index2];
  }
}
__name(distributeNodes, "distributeNodes");
function alignNodes(nodes, direction, align_to) {
  if (!nodes) return;
  const boundary = align_to === void 0 ? getBoundaryNodes(nodes) : { top: align_to, right: align_to, bottom: align_to, left: align_to };
  if (boundary === null) return;
  for (const node2 of nodes) {
    switch (direction) {
      case "right":
        node2.pos[0] = boundary.right.pos[0] + boundary.right.size[0] - node2.size[0];
        break;
      case "left":
        node2.pos[0] = boundary.left.pos[0];
        break;
      case "top":
        node2.pos[1] = boundary.top.pos[1];
        break;
      case "bottom":
        node2.pos[1] = boundary.bottom.pos[1] + boundary.bottom.size[1] - node2.size[1];
        break;
    }
  }
}
__name(alignNodes, "alignNodes");
class LGraphCanvas {
  static {
    __name(this, "LGraphCanvas");
  }
  // Optimised buffers used during rendering
  static #temp = new Float32Array(4);
  static #temp_vec2 = new Float32Array(2);
  static #tmp_area = new Float32Array(4);
  static #margin_area = new Float32Array(4);
  static #link_bounding = new Float32Array(4);
  static #lTempA = new Float32Array(2);
  static #lTempB = new Float32Array(2);
  static #lTempC = new Float32Array(2);
  static DEFAULT_BACKGROUND_IMAGE = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAIAAAD/gAIDAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAQBJREFUeNrs1rEKwjAUhlETUkj3vP9rdmr1Ysammk2w5wdxuLgcMHyptfawuZX4pJSWZTnfnu/lnIe/jNNxHHGNn//HNbbv+4dr6V+11uF527arU7+u63qfa/bnmh8sWLBgwYJlqRf8MEptXPBXJXa37BSl3ixYsGDBMliwFLyCV/DeLIMFCxYsWLBMwSt4Be/NggXLYMGCBUvBK3iNruC9WbBgwYJlsGApeAWv4L1ZBgsWLFiwYJmCV/AK3psFC5bBggULloJX8BpdwXuzYMGCBctgwVLwCl7Be7MMFixYsGDBsu8FH1FaSmExVfAxBa/gvVmwYMGCZbBg/W4vAQYA5tRF9QYlv/QAAAAASUVORK5CYII=";
  static DEFAULT_EVENT_LINK_COLOR = "#A86";
  /** Link type to colour dictionary. */
  static link_type_colors = {
    "-1": LGraphCanvas.DEFAULT_EVENT_LINK_COLOR,
    "number": "#AAA",
    "node": "#DCA"
  };
  static gradients = {};
  static search_limit = -1;
  static node_colors = {
    red: { color: "#322", bgcolor: "#533", groupcolor: "#A88" },
    brown: { color: "#332922", bgcolor: "#593930", groupcolor: "#b06634" },
    green: { color: "#232", bgcolor: "#353", groupcolor: "#8A8" },
    blue: { color: "#223", bgcolor: "#335", groupcolor: "#88A" },
    pale_blue: {
      color: "#2a363b",
      bgcolor: "#3f5159",
      groupcolor: "#3f789e"
    },
    cyan: { color: "#233", bgcolor: "#355", groupcolor: "#8AA" },
    purple: { color: "#323", bgcolor: "#535", groupcolor: "#a1309b" },
    yellow: { color: "#432", bgcolor: "#653", groupcolor: "#b58b2a" },
    black: { color: "#222", bgcolor: "#000", groupcolor: "#444" }
  };
  /**
   * @internal Exclusively a workaround for design limitation in {@link LGraphNode.computeSize}.
   */
  static _measureText;
  /**
   * The state of this canvas, e.g. whether it is being dragged, or read-only.
   *
   * Implemented as a POCO that can be proxied without side-effects.
   */
  state = {
    draggingItems: false,
    draggingCanvas: false,
    readOnly: false,
    hoveringOver: CanvasItem.Nothing,
    shouldSetCursor: true
  };
  #updateCursorStyle() {
    if (!this.state.shouldSetCursor) return;
    let cursor = "default";
    if (this.state.draggingCanvas) {
      cursor = "grabbing";
    } else if (this.state.readOnly) {
      cursor = "grab";
    } else if (this.state.hoveringOver & CanvasItem.ResizeSe) {
      cursor = "se-resize";
    } else if (this.state.hoveringOver & CanvasItem.Node) {
      cursor = "crosshair";
    } else if (this.state.hoveringOver & CanvasItem.Reroute) {
      cursor = "grab";
    } else if (this.state.hoveringOver & CanvasItem.RerouteSlot) {
      cursor = "crosshair";
    }
    this.canvas.style.cursor = cursor;
  }
  // Whether the canvas was previously being dragged prior to pressing space key.
  // null if space key is not pressed.
  _previously_dragging_canvas = null;
  // #region Legacy accessors
  /** @deprecated @inheritdoc {@link LGraphCanvasState.readOnly} */
  get read_only() {
    return this.state.readOnly;
  }
  set read_only(value) {
    this.state.readOnly = value;
    this.#updateCursorStyle();
  }
  get isDragging() {
    return this.state.draggingItems;
  }
  set isDragging(value) {
    this.state.draggingItems = value;
  }
  get hoveringOver() {
    return this.state.hoveringOver;
  }
  set hoveringOver(value) {
    this.state.hoveringOver = value;
    this.#updateCursorStyle();
  }
  /** @deprecated Replace all references with {@link pointer}.{@link CanvasPointer.isDown isDown}. */
  get pointer_is_down() {
    return this.pointer.isDown;
  }
  /** @deprecated Replace all references with {@link pointer}.{@link CanvasPointer.isDouble isDouble}. */
  get pointer_is_double() {
    return this.pointer.isDouble;
  }
  /** @deprecated @inheritdoc {@link LGraphCanvasState.draggingCanvas} */
  get dragging_canvas() {
    return this.state.draggingCanvas;
  }
  set dragging_canvas(value) {
    this.state.draggingCanvas = value;
    this.#updateCursorStyle();
  }
  /**
   * @deprecated Use {@link LGraphNode.titleFontStyle} instead.
   */
  get title_text_font() {
    return `${LiteGraph.NODE_TEXT_SIZE}px ${LiteGraph.NODE_FONT}`;
  }
  // #endregion Legacy accessors
  get inner_text_font() {
    return `normal ${LiteGraph.NODE_SUBTEXT_SIZE}px ${LiteGraph.NODE_FONT}`;
  }
  #maximumFrameGap = 0;
  /** Maximum frames per second to render. 0: unlimited. Default: 0 */
  get maximumFps() {
    return this.#maximumFrameGap > Number.EPSILON ? this.#maximumFrameGap / 1e3 : 0;
  }
  set maximumFps(value) {
    this.#maximumFrameGap = value > Number.EPSILON ? 1e3 / value : 0;
  }
  /**
   * @deprecated Use {@link LiteGraphGlobal.ROUND_RADIUS} instead.
   */
  get round_radius() {
    return LiteGraph.ROUND_RADIUS;
  }
  /**
   * @deprecated Use {@link LiteGraphGlobal.ROUND_RADIUS} instead.
   */
  set round_radius(value) {
    LiteGraph.ROUND_RADIUS = value;
  }
  /**
   * Render low quality when zoomed out.
   */
  get low_quality() {
    return this.ds.scale < this.low_quality_zoom_threshold;
  }
  options;
  background_image;
  ds;
  pointer;
  zoom_modify_alpha;
  zoom_speed;
  node_title_color;
  default_link_color;
  default_connection_color;
  default_connection_color_byType;
  default_connection_color_byTypeOff;
  /** Gets link colours. Extremely basic impl. until the legacy object dictionaries are removed. */
  colourGetter = {
    getConnectedColor: /* @__PURE__ */ __name((type) => this.default_connection_color_byType[type] || this.default_connection_color.output_on, "getConnectedColor"),
    getDisconnectedColor: /* @__PURE__ */ __name((type) => this.default_connection_color_byTypeOff[type] || this.default_connection_color_byType[type] || this.default_connection_color.output_off, "getDisconnectedColor")
  };
  highquality_render;
  use_gradients;
  editor_alpha;
  pause_rendering;
  clear_background;
  clear_background_color;
  render_only_selected;
  show_info;
  allow_dragcanvas;
  allow_dragnodes;
  allow_interaction;
  multi_select;
  allow_searchbox;
  allow_reconnect_links;
  align_to_grid;
  drag_mode;
  dragging_rectangle;
  filter;
  set_canvas_dirty_on_mouse_event;
  always_render_background;
  render_shadows;
  render_canvas_border;
  render_connections_shadows;
  render_connections_border;
  render_curved_connections;
  render_connection_arrows;
  render_collapsed_slots;
  render_execution_order;
  render_link_tooltip;
  /** Shape of the markers shown at the midpoint of links.  Default: Circle */
  linkMarkerShape = LinkMarkerShape.Circle;
  links_render_mode;
  /** Zoom threshold for low quality rendering. Zoom below this threshold will render low quality. */
  low_quality_zoom_threshold = 0.6;
  /** mouse in canvas coordinates, where 0,0 is the top-left corner of the blue rectangle */
  mouse;
  /** mouse in graph coordinates, where 0,0 is the top-left corner of the blue rectangle */
  graph_mouse;
  /** @deprecated LEGACY: REMOVE THIS, USE {@link graph_mouse} INSTEAD */
  canvas_mouse;
  /** to personalize the search box */
  onSearchBox;
  onSearchBoxSelection;
  onMouse;
  /** to render background objects (behind nodes and connections) in the canvas affected by transform */
  onDrawBackground;
  /** to render foreground objects (above nodes and connections) in the canvas affected by transform */
  onDrawForeground;
  connections_width;
  /** The current node being drawn by {@link drawNode}.  This should NOT be used to determine the currently selected node.  See {@link selectedItems} */
  current_node;
  /** used for widgets */
  node_widget;
  /** The link to draw a tooltip for. */
  over_link_center;
  last_mouse_position;
  /** The visible area of this canvas.  Tightly coupled with {@link ds}. */
  visible_area;
  /** Contains all links and reroutes that were rendered.  Repopulated every render cycle. */
  renderedPaths = /* @__PURE__ */ new Set();
  /** @deprecated Replaced by {@link renderedPaths}, but length is set to 0 by some extensions. */
  visible_links = [];
  /** @deprecated This array is populated and cleared to support legacy extensions. The contents are ignored by Litegraph. */
  connecting_links;
  linkConnector = new LinkConnector((links) => this.connecting_links = links);
  /** The viewport of this canvas.  Tightly coupled with {@link ds}. */
  viewport;
  autoresize;
  static active_canvas;
  frame = 0;
  last_draw_time = 0;
  render_time = 0;
  fps = 0;
  /** @deprecated See {@link LGraphCanvas.selectedItems} */
  selected_nodes = {};
  /** All selected nodes, groups, and reroutes */
  selectedItems = /* @__PURE__ */ new Set();
  /** The group currently being resized. */
  resizingGroup = null;
  /** @deprecated See {@link LGraphCanvas.selectedItems} */
  selected_group = null;
  /** The nodes that are currently visible on the canvas. */
  visible_nodes = [];
  /**
   * The IDs of the nodes that are currently visible on the canvas. More
   * performant than {@link visible_nodes} for visibility checks.
   */
  #visible_node_ids = /* @__PURE__ */ new Set();
  node_over;
  node_capturing_input;
  highlighted_links = {};
  #visibleReroutes = /* @__PURE__ */ new Set();
  dirty_canvas = true;
  dirty_bgcanvas = true;
  /** A map of nodes that require selective-redraw */
  dirty_nodes = /* @__PURE__ */ new Map();
  dirty_area;
  /** @deprecated Unused */
  node_in_panel;
  last_mouse = [0, 0];
  last_mouseclick = 0;
  graph;
  canvas;
  bgcanvas;
  ctx;
  _events_binded;
  bgctx;
  is_rendering;
  /** @deprecated Panels */
  block_click;
  /** @deprecated Panels */
  last_click_position;
  resizing_node;
  /** @deprecated See {@link LGraphCanvas.resizingGroup} */
  selected_group_resizing;
  /** @deprecated See {@link pointer}.{@link CanvasPointer.dragStarted dragStarted} */
  last_mouse_dragging;
  onMouseDown;
  _highlight_pos;
  _highlight_input;
  // TODO: Check if panels are used
  /** @deprecated Panels */
  node_panel;
  /** @deprecated Panels */
  options_panel;
  _bg_img;
  _pattern;
  _pattern_img;
  // TODO: This looks like another panel thing
  prompt_box;
  search_box;
  /** @deprecated Panels */
  SELECTED_NODE;
  /** @deprecated Panels */
  NODEPANEL_IS_OPEN;
  /** Once per frame check of snap to grid value.  @todo Update on change. */
  #snapToGrid;
  /** Set on keydown, keyup. @todo */
  #shiftDown = false;
  /** If true, enable drag zoom. Ctrl+Shift+Drag Up/Down: zoom canvas. */
  dragZoomEnabled = false;
  /** The start position of the drag zoom. */
  #dragZoomStart = null;
  static active_node;
  onClear;
  /** called after moving a node @deprecated Does not handle multi-node move, and can return the wrong node. */
  onNodeMoved;
  /** @deprecated Called with the deprecated {@link selected_nodes} when the selection changes. Replacement not yet impl. */
  onSelectionChange;
  /** called when rendering a tooltip */
  onDrawLinkTooltip;
  /** to render foreground objects not affected by transform (for GUIs) */
  onDrawOverlay;
  onRenderBackground;
  onNodeDblClicked;
  onShowNodePanel;
  onNodeSelected;
  onNodeDeselected;
  onRender;
  /**
   * Creates a new instance of LGraphCanvas.
   * @param canvas The canvas HTML element (or its id) to use, or null / undefined to leave blank.
   * @param graph The graph that owns this canvas.
   * @param options
   */
  constructor(canvas2, graph, options2) {
    options2 ||= {};
    this.options = options2;
    this.background_image = LGraphCanvas.DEFAULT_BACKGROUND_IMAGE;
    this.ds = new DragAndScale(canvas2);
    this.pointer = new CanvasPointer(canvas2);
    this.linkConnector.events.addEventListener("reset", () => {
      this.connecting_links = null;
    });
    this.linkConnector.events.addEventListener("dropped-on-canvas", (customEvent) => {
      if (!this.connecting_links) return;
      const e2 = customEvent.detail;
      this.emitEvent({
        subType: "empty-release",
        originalEvent: e2,
        linkReleaseContext: { links: this.connecting_links }
      });
      const firstLink = this.linkConnector.renderLinks[0];
      if (LiteGraph.release_link_on_empty_shows_menu) {
        const linkReleaseContext = this.linkConnector.state.connectingTo === "input" ? {
          node_from: firstLink.node,
          slot_from: firstLink.fromSlot,
          type_filter_in: firstLink.fromSlot.type
        } : {
          node_to: firstLink.node,
          slot_from: firstLink.fromSlot,
          type_filter_out: firstLink.fromSlot.type
        };
        const afterRerouteId = firstLink.fromReroute?.id;
        if ("shiftKey" in e2 && e2.shiftKey) {
          if (this.allow_searchbox) {
            this.showSearchBox(e2, linkReleaseContext);
          }
        } else if (this.linkConnector.state.connectingTo === "input") {
          this.showConnectionMenu({ nodeFrom: firstLink.node, slotFrom: firstLink.fromSlot, e: e2, afterRerouteId });
        } else {
          this.showConnectionMenu({ nodeTo: firstLink.node, slotTo: firstLink.fromSlot, e: e2, afterRerouteId });
        }
      }
    });
    this.zoom_modify_alpha = true;
    this.zoom_speed = 1.1;
    this.node_title_color = LiteGraph.NODE_TITLE_COLOR;
    this.default_link_color = LiteGraph.LINK_COLOR;
    this.default_connection_color = {
      input_off: "#778",
      input_on: "#7F7",
      output_off: "#778",
      output_on: "#7F7"
    };
    this.default_connection_color_byType = {
      /* number: "#7F7",
            string: "#77F",
            boolean: "#F77", */
    };
    this.default_connection_color_byTypeOff = {
      /* number: "#474",
            string: "#447",
            boolean: "#744", */
    };
    this.highquality_render = true;
    this.use_gradients = false;
    this.editor_alpha = 1;
    this.pause_rendering = false;
    this.clear_background = true;
    this.clear_background_color = "#222";
    this.render_only_selected = true;
    this.show_info = true;
    this.allow_dragcanvas = true;
    this.allow_dragnodes = true;
    this.allow_interaction = true;
    this.multi_select = false;
    this.allow_searchbox = true;
    this.allow_reconnect_links = true;
    this.align_to_grid = false;
    this.drag_mode = false;
    this.dragging_rectangle = null;
    this.filter = null;
    this.set_canvas_dirty_on_mouse_event = true;
    this.always_render_background = false;
    this.render_shadows = true;
    this.render_canvas_border = true;
    this.render_connections_shadows = false;
    this.render_connections_border = true;
    this.render_curved_connections = false;
    this.render_connection_arrows = false;
    this.render_collapsed_slots = true;
    this.render_execution_order = false;
    this.render_link_tooltip = true;
    this.links_render_mode = LinkRenderType.SPLINE_LINK;
    this.mouse = [0, 0];
    this.graph_mouse = [0, 0];
    this.canvas_mouse = this.graph_mouse;
    this.connections_width = 3;
    this.current_node = null;
    this.node_widget = null;
    this.last_mouse_position = [0, 0];
    this.visible_area = this.ds.visible_area;
    this.connecting_links = null;
    this.viewport = options2.viewport || null;
    this.graph = graph;
    graph?.attachCanvas(this);
    this.canvas = void 0;
    this.bgcanvas = void 0;
    this.ctx = void 0;
    this.setCanvas(canvas2, options2.skip_events);
    this.clear();
    LGraphCanvas._measureText = (text2, fontStyle = this.inner_text_font) => {
      const { ctx } = this;
      const { font } = ctx;
      try {
        ctx.font = fontStyle;
        return ctx.measureText(text2).width;
      } finally {
        ctx.font = font;
      }
    };
    if (!options2.skip_render) {
      this.startRendering();
    }
    this.autoresize = options2.autoresize;
  }
  static onGroupAdd(info, entry, mouse_event) {
    const canvas2 = LGraphCanvas.active_canvas;
    const group = new LiteGraph.LGraphGroup();
    group.pos = canvas2.convertEventToCanvasOffset(mouse_event);
    if (!canvas2.graph) throw new NullGraphError();
    canvas2.graph.add(group);
  }
  /**
   * @deprecated Functionality moved to {@link getBoundaryNodes}.  The new function returns null on failure, instead of an object with all null properties.
   * Determines the furthest nodes in each direction
   * @param nodes the nodes to from which boundary nodes will be extracted
   * @returns
   */
  static getBoundaryNodes(nodes) {
    const _nodes = Array.isArray(nodes) ? nodes : Object.values(nodes);
    return getBoundaryNodes(_nodes) ?? {
      top: null,
      right: null,
      bottom: null,
      left: null
    };
  }
  /**
   * @deprecated Functionality moved to {@link alignNodes}.  The new function does not set dirty canvas.
   * @param nodes a list of nodes
   * @param direction Direction to align the nodes
   * @param align_to Node to align to (if null, align to the furthest node in the given direction)
   */
  static alignNodes(nodes, direction, align_to) {
    alignNodes(Object.values(nodes), direction, align_to);
    LGraphCanvas.active_canvas.setDirty(true, true);
  }
  static onNodeAlign(value, options2, event, prev_menu, node2) {
    new LiteGraph.ContextMenu(["Top", "Bottom", "Left", "Right"], {
      event,
      callback: inner_clicked,
      parentMenu: prev_menu
    });
    function inner_clicked(value2) {
      alignNodes(
        Object.values(LGraphCanvas.active_canvas.selected_nodes),
        value2.toLowerCase(),
        node2
      );
      LGraphCanvas.active_canvas.setDirty(true, true);
    }
    __name(inner_clicked, "inner_clicked");
  }
  static onGroupAlign(value, options2, event, prev_menu) {
    new LiteGraph.ContextMenu(["Top", "Bottom", "Left", "Right"], {
      event,
      callback: inner_clicked,
      parentMenu: prev_menu
    });
    function inner_clicked(value2) {
      alignNodes(
        Object.values(LGraphCanvas.active_canvas.selected_nodes),
        value2.toLowerCase()
      );
      LGraphCanvas.active_canvas.setDirty(true, true);
    }
    __name(inner_clicked, "inner_clicked");
  }
  static createDistributeMenu(value, options2, event, prev_menu) {
    new LiteGraph.ContextMenu(["Vertically", "Horizontally"], {
      event,
      callback: inner_clicked,
      parentMenu: prev_menu
    });
    function inner_clicked(value2) {
      const canvas2 = LGraphCanvas.active_canvas;
      distributeNodes(Object.values(canvas2.selected_nodes), value2 === "Horizontally");
      canvas2.setDirty(true, true);
    }
    __name(inner_clicked, "inner_clicked");
  }
  static onMenuAdd(value, options2, e2, prev_menu, callback) {
    const canvas2 = LGraphCanvas.active_canvas;
    const ref_window = canvas2.getCanvasWindow();
    const { graph } = canvas2;
    if (!graph) return;
    inner_onMenuAdded("", prev_menu);
    return false;
    function inner_onMenuAdded(base_category, prev_menu2) {
      if (!graph) return;
      const categories = LiteGraph.getNodeTypesCategories(canvas2.filter || graph.filter).filter((category) => category.startsWith(base_category));
      const entries = [];
      for (const category of categories) {
        if (!category) continue;
        const base_category_regex = new RegExp(`^(${base_category})`);
        const category_name = category.replace(base_category_regex, "").split("/", 1)[0];
        const category_path = base_category === "" ? `${category_name}/` : `${base_category}${category_name}/`;
        let name2 = category_name;
        if (name2.includes("::")) name2 = name2.split("::", 2)[1];
        const index2 = entries.findIndex((entry) => entry.value === category_path);
        if (index2 === -1) {
          entries.push({
            value: category_path,
            content: name2,
            has_submenu: true,
            callback: /* @__PURE__ */ __name(function(value2, event, mouseEvent, contextMenu2) {
              inner_onMenuAdded(value2.value, contextMenu2);
            }, "callback")
          });
        }
      }
      const nodes = LiteGraph.getNodeTypesInCategory(
        base_category.slice(0, -1),
        canvas2.filter || graph.filter
      );
      for (const node2 of nodes) {
        if (node2.skip_list) continue;
        const entry = {
          value: node2.type,
          content: node2.title,
          has_submenu: false,
          callback: /* @__PURE__ */ __name(function(value2, event, mouseEvent, contextMenu2) {
            if (!canvas2.graph) throw new NullGraphError();
            const first_event = contextMenu2.getFirstEvent();
            canvas2.graph.beforeChange();
            const node22 = LiteGraph.createNode(value2.value);
            if (node22) {
              if (!first_event) throw new TypeError("Context menu event was null. This should not occur in normal usage.");
              node22.pos = canvas2.convertEventToCanvasOffset(first_event);
              canvas2.graph.add(node22);
            } else {
              console.warn("Failed to create node of type:", value2.value);
            }
            callback?.(node22);
            canvas2.graph.afterChange();
          }, "callback")
        };
        entries.push(entry);
      }
      new LiteGraph.ContextMenu(entries, { event: e2, parentMenu: prev_menu2 }, ref_window);
    }
    __name(inner_onMenuAdded, "inner_onMenuAdded");
  }
  static onMenuCollapseAll() {
  }
  static onMenuNodeEdit() {
  }
  /** @param _options Parameter is never used */
  static showMenuNodeOptionalOutputs(v2, _options, e2, prev_menu, node2) {
    if (!node2) return;
    const canvas2 = LGraphCanvas.active_canvas;
    let entries = [];
    if (LiteGraph.do_add_triggers_slots && node2.findOutputSlot("onExecuted") == -1) {
      entries.push({ content: "On Executed", value: ["onExecuted", LiteGraph.EVENT, { nameLocked: true }], className: "event" });
    }
    const retEntries = node2.onMenuNodeOutputs?.(entries);
    if (retEntries) entries = retEntries;
    if (!entries.length) return;
    new LiteGraph.ContextMenu(
      entries,
      {
        event: e2,
        callback: inner_clicked,
        parentMenu: prev_menu,
        node: node2
      }
    );
    function inner_clicked(v22, e22, prev) {
      if (!node2) return;
      if (v22.callback) v22.callback.call(this, node2, v22, e22, prev);
      if (!v22.value) return;
      const value = v22.value[1];
      if (value && (typeof value === "object" || Array.isArray(value))) {
        const entries2 = [];
        for (const i2 in value) {
          entries2.push({ content: i2, value: value[i2] });
        }
        new LiteGraph.ContextMenu(entries2, {
          event: e22,
          callback: inner_clicked,
          parentMenu: prev_menu,
          node: node2
        });
        return false;
      }
      const { graph } = node2;
      if (!graph) throw new NullGraphError();
      graph.beforeChange();
      node2.addOutput(v22.value[0], v22.value[1], v22.value[2]);
      node2.onNodeOutputAdd?.(v22.value);
      canvas2.setDirty(true, true);
      graph.afterChange();
    }
    __name(inner_clicked, "inner_clicked");
    return false;
  }
  /** @param value Parameter is never used */
  static onShowMenuNodeProperties(value, options2, e2, prev_menu, node2) {
    if (!node2 || !node2.properties) return;
    const canvas2 = LGraphCanvas.active_canvas;
    const ref_window = canvas2.getCanvasWindow();
    const entries = [];
    for (const i2 in node2.properties) {
      value = node2.properties[i2] !== void 0 ? node2.properties[i2] : " ";
      if (typeof value == "object")
        value = JSON.stringify(value);
      const info = node2.getPropertyInfo(i2);
      if (info.type == "enum" || info.type == "combo")
        value = LGraphCanvas.getPropertyPrintableValue(value, info.values);
      value = LGraphCanvas.decodeHTML(stringOrEmpty(value));
      entries.push({
        content: `<span class='property_name'>${info.label || i2}</span><span class='property_value'>${value}</span>`,
        value: i2
      });
    }
    if (!entries.length) {
      return;
    }
    new LiteGraph.ContextMenu(
      entries,
      {
        event: e2,
        callback: inner_clicked,
        parentMenu: prev_menu,
        allow_html: true,
        node: node2
      },
      // @ts-expect-error Unused
      ref_window
    );
    function inner_clicked(v2) {
      if (!node2) return;
      const rect = this.getBoundingClientRect();
      canvas2.showEditPropertyValue(node2, v2.value, {
        position: [rect.left, rect.top]
      });
    }
    __name(inner_clicked, "inner_clicked");
    return false;
  }
  /** @deprecated */
  static decodeHTML(str) {
    const e2 = document.createElement("div");
    e2.textContent = str;
    return e2.innerHTML;
  }
  static onMenuResizeNode(value, options2, e2, menu2, node2) {
    if (!node2) return;
    const fApplyMultiNode = /* @__PURE__ */ __name(function(node22) {
      node22.setSize(node22.computeSize());
    }, "fApplyMultiNode");
    const canvas2 = LGraphCanvas.active_canvas;
    if (!canvas2.selected_nodes || Object.keys(canvas2.selected_nodes).length <= 1) {
      fApplyMultiNode(node2);
    } else {
      for (const i2 in canvas2.selected_nodes) {
        fApplyMultiNode(canvas2.selected_nodes[i2]);
      }
    }
    canvas2.setDirty(true, true);
  }
  // TODO refactor :: this is used fot title but not for properties!
  static onShowPropertyEditor(item, options2, e2, menu2, node2) {
    const property = item.property || "title";
    const value = node2[property];
    const title = document.createElement("span");
    title.className = "name";
    title.textContent = property;
    const input = document.createElement("input");
    Object.assign(input, { type: "text", className: "value", autofocus: true });
    const button = document.createElement("button");
    button.textContent = "OK";
    const dialog = Object.assign(document.createElement("div"), {
      is_modified: false,
      className: "graphdialog",
      close: /* @__PURE__ */ __name(() => dialog.remove(), "close")
    });
    dialog.append(title, input, button);
    input.value = String(value);
    input.addEventListener("blur", function() {
      this.focus();
    });
    input.addEventListener("keydown", (e22) => {
      dialog.is_modified = true;
      if (e22.key == "Escape") {
        dialog.close();
      } else if (e22.key == "Enter") {
        inner();
      } else if (!e22.target || !("localName" in e22.target) || e22.target.localName != "textarea") {
        return;
      }
      e22.preventDefault();
      e22.stopPropagation();
    });
    const canvas2 = LGraphCanvas.active_canvas;
    const canvasEl = canvas2.canvas;
    const rect = canvasEl.getBoundingClientRect();
    const offsetx = rect ? -20 - rect.left : -20;
    const offsety = rect ? -20 - rect.top : -20;
    if (e2) {
      dialog.style.left = `${e2.clientX + offsetx}px`;
      dialog.style.top = `${e2.clientY + offsety}px`;
    } else {
      dialog.style.left = `${canvasEl.width * 0.5 + offsetx}px`;
      dialog.style.top = `${canvasEl.height * 0.5 + offsety}px`;
    }
    button.addEventListener("click", inner);
    if (canvasEl.parentNode == null) throw new TypeError("canvasEl.parentNode was null");
    canvasEl.parentNode.append(dialog);
    input.focus();
    let dialogCloseTimer;
    dialog.addEventListener("mouseleave", function() {
      if (LiteGraph.dialog_close_on_mouse_leave) {
        if (!dialog.is_modified && LiteGraph.dialog_close_on_mouse_leave) {
          dialogCloseTimer = setTimeout(
            dialog.close,
            LiteGraph.dialog_close_on_mouse_leave_delay
          );
        }
      }
    });
    dialog.addEventListener("mouseenter", function() {
      if (LiteGraph.dialog_close_on_mouse_leave) {
        if (dialogCloseTimer) clearTimeout(dialogCloseTimer);
      }
    });
    function inner() {
      if (input) setValue(input.value);
    }
    __name(inner, "inner");
    function setValue(value2) {
      if (item.type == "Number") {
        value2 = Number(value2);
      } else if (item.type == "Boolean") {
        value2 = Boolean(value2);
      }
      node2[property] = value2;
      dialog.remove();
      canvas2.setDirty(true, true);
    }
    __name(setValue, "setValue");
  }
  static getPropertyPrintableValue(value, values) {
    if (!values) return String(value);
    if (Array.isArray(values)) {
      return String(value);
    }
    if (typeof values === "object") {
      let desc_value = "";
      for (const k2 in values) {
        if (values[k2] != value) continue;
        desc_value = k2;
        break;
      }
      return `${String(value)} (${desc_value})`;
    }
  }
  static onMenuNodeCollapse(value, options2, e2, menu2, node2) {
    if (!node2.graph) throw new NullGraphError();
    node2.graph.beforeChange();
    const fApplyMultiNode = /* @__PURE__ */ __name(function(node22) {
      node22.collapse();
    }, "fApplyMultiNode");
    const graphcanvas = LGraphCanvas.active_canvas;
    if (!graphcanvas.selected_nodes || Object.keys(graphcanvas.selected_nodes).length <= 1) {
      fApplyMultiNode(node2);
    } else {
      for (const i2 in graphcanvas.selected_nodes) {
        fApplyMultiNode(graphcanvas.selected_nodes[i2]);
      }
    }
    node2.graph.afterChange();
  }
  static onMenuToggleAdvanced(value, options2, e2, menu2, node2) {
    if (!node2.graph) throw new NullGraphError();
    node2.graph.beforeChange();
    const fApplyMultiNode = /* @__PURE__ */ __name(function(node22) {
      node22.toggleAdvanced();
    }, "fApplyMultiNode");
    const graphcanvas = LGraphCanvas.active_canvas;
    if (!graphcanvas.selected_nodes || Object.keys(graphcanvas.selected_nodes).length <= 1) {
      fApplyMultiNode(node2);
    } else {
      for (const i2 in graphcanvas.selected_nodes) {
        fApplyMultiNode(graphcanvas.selected_nodes[i2]);
      }
    }
    node2.graph.afterChange();
  }
  static onMenuNodeMode(value, options2, e2, menu2, node2) {
    new LiteGraph.ContextMenu(
      LiteGraph.NODE_MODES,
      { event: e2, callback: inner_clicked, parentMenu: menu2, node: node2 }
    );
    function inner_clicked(v2) {
      if (!node2) return;
      const kV = Object.values(LiteGraph.NODE_MODES).indexOf(v2);
      const fApplyMultiNode = /* @__PURE__ */ __name(function(node22) {
        if (kV !== -1 && LiteGraph.NODE_MODES[kV]) {
          node22.changeMode(kV);
        } else {
          console.warn(`unexpected mode: ${v2}`);
          node22.changeMode(LGraphEventMode.ALWAYS);
        }
      }, "fApplyMultiNode");
      const graphcanvas = LGraphCanvas.active_canvas;
      if (!graphcanvas.selected_nodes || Object.keys(graphcanvas.selected_nodes).length <= 1) {
        fApplyMultiNode(node2);
      } else {
        for (const i2 in graphcanvas.selected_nodes) {
          fApplyMultiNode(graphcanvas.selected_nodes[i2]);
        }
      }
    }
    __name(inner_clicked, "inner_clicked");
    return false;
  }
  /** @param value Parameter is never used */
  static onMenuNodeColors(value, options2, e2, menu2, node2) {
    if (!node2) throw "no node for color";
    const values = [];
    values.push({
      value: null,
      content: "<span style='display: block; padding-left: 4px;'>No color</span>"
    });
    for (const i2 in LGraphCanvas.node_colors) {
      const color2 = LGraphCanvas.node_colors[i2];
      value = {
        value: i2,
        content: `<span style='display: block; color: #999; padding-left: 4px; border-left: 8px solid ${color2.color}; background-color:${color2.bgcolor}'>${i2}</span>`
      };
      values.push(value);
    }
    new LiteGraph.ContextMenu(values, {
      event: e2,
      callback: inner_clicked,
      parentMenu: menu2,
      node: node2
    });
    function inner_clicked(v2) {
      if (!node2) return;
      const fApplyColor = /* @__PURE__ */ __name(function(item) {
        const colorOption = v2.value ? LGraphCanvas.node_colors[v2.value] : null;
        item.setColorOption(colorOption);
      }, "fApplyColor");
      const canvas2 = LGraphCanvas.active_canvas;
      if (!canvas2.selected_nodes || Object.keys(canvas2.selected_nodes).length <= 1) {
        fApplyColor(node2);
      } else {
        for (const i2 in canvas2.selected_nodes) {
          fApplyColor(canvas2.selected_nodes[i2]);
        }
      }
      canvas2.setDirty(true, true);
    }
    __name(inner_clicked, "inner_clicked");
    return false;
  }
  static onMenuNodeShapes(value, options2, e2, menu2, node2) {
    if (!node2) throw "no node passed";
    new LiteGraph.ContextMenu(LiteGraph.VALID_SHAPES, {
      event: e2,
      callback: inner_clicked,
      parentMenu: menu2,
      node: node2
    });
    function inner_clicked(v2) {
      if (!node2) return;
      if (!node2.graph) throw new NullGraphError();
      node2.graph.beforeChange();
      const fApplyMultiNode = /* @__PURE__ */ __name(function(node22) {
        node22.shape = v2;
      }, "fApplyMultiNode");
      const canvas2 = LGraphCanvas.active_canvas;
      if (!canvas2.selected_nodes || Object.keys(canvas2.selected_nodes).length <= 1) {
        fApplyMultiNode(node2);
      } else {
        for (const i2 in canvas2.selected_nodes) {
          fApplyMultiNode(canvas2.selected_nodes[i2]);
        }
      }
      node2.graph.afterChange();
      canvas2.setDirty(true);
    }
    __name(inner_clicked, "inner_clicked");
    return false;
  }
  static onMenuNodeRemove() {
    LGraphCanvas.active_canvas.deleteSelected();
  }
  static onMenuNodeClone(value, options2, e2, menu2, node2) {
    const { graph } = node2;
    if (!graph) throw new NullGraphError();
    graph.beforeChange();
    const newSelected = /* @__PURE__ */ new Set();
    const fApplyMultiNode = /* @__PURE__ */ __name(function(node22, newNodes) {
      if (node22.clonable === false) return;
      const newnode = node22.clone();
      if (!newnode) return;
      newnode.pos = [node22.pos[0] + 5, node22.pos[1] + 5];
      if (!node22.graph) throw new NullGraphError();
      node22.graph.add(newnode);
      newNodes.add(newnode);
    }, "fApplyMultiNode");
    const canvas2 = LGraphCanvas.active_canvas;
    if (!canvas2.selected_nodes || Object.keys(canvas2.selected_nodes).length <= 1) {
      fApplyMultiNode(node2, newSelected);
    } else {
      for (const i2 in canvas2.selected_nodes) {
        fApplyMultiNode(canvas2.selected_nodes[i2], newSelected);
      }
    }
    if (newSelected.size) {
      canvas2.selectNodes([...newSelected]);
    }
    graph.afterChange();
    canvas2.setDirty(true, true);
  }
  /**
   * clears all the data inside
   *
   */
  clear() {
    this.frame = 0;
    this.last_draw_time = 0;
    this.render_time = 0;
    this.fps = 0;
    this.dragging_rectangle = null;
    this.selected_nodes = {};
    this.selected_group = null;
    this.selectedItems.clear();
    this.onSelectionChange?.(this.selected_nodes);
    this.visible_nodes = [];
    this.node_over = void 0;
    this.node_capturing_input = null;
    this.connecting_links = null;
    this.highlighted_links = {};
    this.dragging_canvas = false;
    this.#dirty();
    this.dirty_area = null;
    this.node_in_panel = null;
    this.node_widget = null;
    this.last_mouse = [0, 0];
    this.last_mouseclick = 0;
    this.pointer.reset();
    this.visible_area.set([0, 0, 0, 0]);
    this.onClear?.();
  }
  /**
   * Assigns a new graph to this canvas.
   */
  setGraph(newGraph) {
    const { graph } = this;
    if (newGraph === graph) return;
    const options2 = {
      bubbles: true,
      detail: { newGraph, oldGraph: graph }
    };
    this.clear();
    newGraph.attachCanvas(this);
    this.canvas.dispatchEvent(new CustomEvent("litegraph:set-graph", options2));
    this.#dirty();
  }
  /**
   * @returns the visually active graph (in case there are more in the stack)
   */
  getCurrentGraph() {
    return this.graph;
  }
  /**
   * Finds the canvas if required, throwing on failure.
   * @param canvas Canvas element, or its element ID
   * @returns The canvas element
   * @throws If {@link canvas} is an element ID that does not belong to a valid HTML canvas element
   */
  #validateCanvas(canvas2) {
    if (typeof canvas2 === "string") {
      const el = document.getElementById(canvas2);
      if (!(el instanceof HTMLCanvasElement)) throw "Error validating LiteGraph canvas: Canvas element not found";
      return el;
    }
    return canvas2;
  }
  /**
   * Sets the current HTML canvas element.
   * Calls bindEvents to add input event listeners, and (re)creates the background canvas.
   * @param canvas The canvas element to assign, or its HTML element ID.  If null or undefined, the current reference is cleared.
   * @param skip_events If true, events on the previous canvas will not be removed.  Has no effect on the first invocation.
   */
  setCanvas(canvas2, skip_events) {
    const element = this.#validateCanvas(canvas2);
    if (element === this.canvas) return;
    if (!element && this.canvas && !skip_events) this.unbindEvents();
    this.canvas = element;
    this.ds.element = element;
    this.pointer.element = element;
    if (!element) return;
    element.className += " lgraphcanvas";
    element.data = this;
    this.bgcanvas = document.createElement("canvas");
    this.bgcanvas.width = this.canvas.width;
    this.bgcanvas.height = this.canvas.height;
    const ctx = element.getContext?.("2d");
    if (ctx == null) {
      if (element.localName != "canvas") {
        throw `Element supplied for LGraphCanvas must be a <canvas> element, you passed a ${element.localName}`;
      }
      throw "This browser doesn't support Canvas";
    }
    this.ctx = ctx;
    if (!skip_events) this.bindEvents();
  }
  /** Captures an event and prevents default - returns false. */
  _doNothing(e2) {
    e2.preventDefault();
    return false;
  }
  /** Captures an event and prevents default - returns true. */
  _doReturnTrue(e2) {
    e2.preventDefault();
    return true;
  }
  /**
   * binds mouse, keyboard, touch and drag events to the canvas
   */
  bindEvents() {
    if (this._events_binded) {
      console.warn("LGraphCanvas: events already binded");
      return;
    }
    const { canvas: canvas2 } = this;
    const { document: document2 } = this.getCanvasWindow();
    this._mousedown_callback = this.processMouseDown.bind(this);
    this._mousewheel_callback = this.processMouseWheel.bind(this);
    this._mousemove_callback = this.processMouseMove.bind(this);
    this._mouseup_callback = this.processMouseUp.bind(this);
    this._mouseout_callback = this.processMouseOut.bind(this);
    this._mousecancel_callback = this.processMouseCancel.bind(this);
    canvas2.addEventListener("pointerdown", this._mousedown_callback, true);
    canvas2.addEventListener("wheel", this._mousewheel_callback, false);
    canvas2.addEventListener("pointerup", this._mouseup_callback, true);
    canvas2.addEventListener("pointermove", this._mousemove_callback);
    canvas2.addEventListener("pointerout", this._mouseout_callback);
    canvas2.addEventListener("pointercancel", this._mousecancel_callback, true);
    canvas2.addEventListener("contextmenu", this._doNothing);
    this._key_callback = this.processKey.bind(this);
    canvas2.addEventListener("keydown", this._key_callback, true);
    document2.addEventListener("keyup", this._key_callback, true);
    canvas2.addEventListener("dragover", this._doNothing, false);
    canvas2.addEventListener("dragend", this._doNothing, false);
    canvas2.addEventListener("dragenter", this._doReturnTrue, false);
    this._events_binded = true;
  }
  /**
   * unbinds mouse events from the canvas
   */
  unbindEvents() {
    if (!this._events_binded) {
      console.warn("LGraphCanvas: no events binded");
      return;
    }
    const { document: document2 } = this.getCanvasWindow();
    const { canvas: canvas2 } = this;
    canvas2.removeEventListener("pointercancel", this._mousecancel_callback);
    canvas2.removeEventListener("pointerout", this._mouseout_callback);
    canvas2.removeEventListener("pointermove", this._mousemove_callback);
    canvas2.removeEventListener("pointerup", this._mouseup_callback);
    canvas2.removeEventListener("pointerdown", this._mousedown_callback);
    canvas2.removeEventListener("wheel", this._mousewheel_callback);
    canvas2.removeEventListener("keydown", this._key_callback);
    document2.removeEventListener("keyup", this._key_callback);
    canvas2.removeEventListener("contextmenu", this._doNothing);
    canvas2.removeEventListener("dragenter", this._doReturnTrue);
    this._mousedown_callback = void 0;
    this._mousewheel_callback = void 0;
    this._key_callback = void 0;
    this._events_binded = false;
  }
  /**
   * Ensures the canvas will be redrawn on the next frame by setting the dirty flag(s).
   * Without parameters, this function does nothing.
   * @todo Impl. `setDirty()` or similar as shorthand to redraw everything.
   * @param fgcanvas If true, marks the foreground canvas as dirty (nodes and anything drawn on top of them).  Default: false
   * @param bgcanvas If true, mark the background canvas as dirty (background, groups, links).  Default: false
   */
  setDirty(fgcanvas, bgcanvas) {
    if (fgcanvas) this.dirty_canvas = true;
    if (bgcanvas) this.dirty_bgcanvas = true;
  }
  /** Marks the entire canvas as dirty. */
  #dirty() {
    this.dirty_canvas = true;
    this.dirty_bgcanvas = true;
  }
  #linkConnectorDrop() {
    const { graph, linkConnector, pointer } = this;
    if (!graph) throw new NullGraphError();
    pointer.onDragEnd = (upEvent) => linkConnector.dropLinks(graph, upEvent);
    pointer.finally = () => {
      this.linkConnector.reset(true);
      this.#dirty();
    };
  }
  /**
   * Used to attach the canvas in a popup
   * @returns returns the window where the canvas is attached (the DOM root node)
   */
  getCanvasWindow() {
    if (!this.canvas) return window;
    const doc2 = this.canvas.ownerDocument;
    return doc2.defaultView || doc2.parentWindow;
  }
  /**
   * starts rendering the content of the canvas when needed
   *
   */
  startRendering() {
    if (this.is_rendering) return;
    this.is_rendering = true;
    renderFrame.call(this);
    function renderFrame() {
      if (!this.pause_rendering) {
        this.draw();
      }
      const window2 = this.getCanvasWindow();
      if (this.is_rendering) {
        if (this.#maximumFrameGap > 0) {
          const gap = this.#maximumFrameGap - (LiteGraph.getTime() - this.last_draw_time);
          setTimeout(renderFrame.bind(this), Math.max(1, gap));
        } else {
          window2.requestAnimationFrame(renderFrame.bind(this));
        }
      }
    }
    __name(renderFrame, "renderFrame");
  }
  /**
   * stops rendering the content of the canvas (to save resources)
   *
   */
  stopRendering() {
    this.is_rendering = false;
  }
  /* LiteGraphCanvas input */
  // used to block future mouse events (because of im gui)
  blockClick() {
    this.block_click = true;
    this.last_mouseclick = 0;
  }
  /**
   * Gets the widget at the current cursor position.
   * @param node Optional node to check for widgets under cursor
   * @returns The widget located at the current cursor position, if any is found.
   * @deprecated Use {@link LGraphNode.getWidgetOnPos} instead.
   * ```ts
   * const [x, y] = canvas.graph_mouse
   * const widget = canvas.node_over?.getWidgetOnPos(x, y, true)
   * ```
   */
  getWidgetAtCursor(node2) {
    node2 ??= this.node_over;
    return node2?.getWidgetOnPos(this.graph_mouse[0], this.graph_mouse[1], true);
  }
  /**
   * Clears highlight and mouse-over information from nodes that should not have it.
   *
   * Intended to be called when the pointer moves away from a node.
   * @param node The node that the mouse is now over
   * @param e MouseEvent that is triggering this
   */
  updateMouseOverNodes(node2, e2) {
    if (!this.graph) throw new NullGraphError();
    const nodes = this.graph._nodes;
    for (const otherNode of nodes) {
      if (otherNode.mouseOver && node2 != otherNode) {
        otherNode.mouseOver = void 0;
        this._highlight_input = void 0;
        this._highlight_pos = void 0;
        this.linkConnector.overWidget = void 0;
        otherNode.lostFocusAt = LiteGraph.getTime();
        this.node_over?.onMouseLeave?.(e2);
        this.node_over = void 0;
        this.dirty_canvas = true;
      }
    }
  }
  processMouseDown(e2) {
    if (this.dragZoomEnabled && e2.ctrlKey && e2.shiftKey && !e2.altKey && e2.buttons) {
      this.#dragZoomStart = { pos: [e2.x, e2.y], scale: this.ds.scale };
      return;
    }
    const { graph, pointer } = this;
    this.adjustMouseEvent(e2);
    if (e2.isPrimary) pointer.down(e2);
    if (this.set_canvas_dirty_on_mouse_event) this.dirty_canvas = true;
    if (!graph) return;
    const ref_window = this.getCanvasWindow();
    LGraphCanvas.active_canvas = this;
    const x2 = e2.clientX;
    const y2 = e2.clientY;
    this.ds.viewport = this.viewport;
    const is_inside = !this.viewport || isInRect(x2, y2, this.viewport);
    if (!is_inside) return;
    const node2 = graph.getNodeOnPos(e2.canvasX, e2.canvasY, this.visible_nodes) ?? void 0;
    this.mouse[0] = x2;
    this.mouse[1] = y2;
    this.graph_mouse[0] = e2.canvasX;
    this.graph_mouse[1] = e2.canvasY;
    this.last_click_position = [this.mouse[0], this.mouse[1]];
    pointer.isDouble = pointer.isDown && e2.isPrimary;
    pointer.isDown = true;
    this.canvas.focus();
    LiteGraph.closeAllContextMenus(ref_window);
    if (this.onMouse?.(e2) == true) return;
    if (e2.button === 0 && !pointer.isDouble) {
      this.#processPrimaryButton(e2, node2);
    } else if (e2.button === 1) {
      this.#processMiddleButton(e2, node2);
    } else if ((e2.button === 2 || pointer.isDouble) && this.allow_interaction && !this.read_only) {
      if (node2) {
        this.processSelect(node2, e2, true);
      } else if (this.links_render_mode !== LinkRenderType.HIDDEN_LINK) {
        const reroute = graph.getRerouteOnPos(e2.canvasX, e2.canvasY, this.#visibleReroutes);
        if (reroute) {
          if (e2.altKey) {
            pointer.onClick = (upEvent) => {
              if (upEvent.altKey) {
                if (reroute.selected) {
                  this.deselect(reroute);
                  this.onSelectionChange?.(this.selected_nodes);
                }
                reroute.remove();
              }
            };
          } else {
            this.processSelect(reroute, e2, true);
          }
        }
      }
      pointer.onClick ??= () => this.processContextMenu(node2, e2);
    }
    this.last_mouse = [x2, y2];
    this.last_mouseclick = LiteGraph.getTime();
    this.last_mouse_dragging = true;
    graph.change();
    if (!ref_window.document.activeElement || ref_window.document.activeElement.nodeName.toLowerCase() != "input" && ref_window.document.activeElement.nodeName.toLowerCase() != "textarea") {
      e2.preventDefault();
    }
    e2.stopPropagation();
    this.onMouseDown?.(e2);
  }
  #processPrimaryButton(e2, node2) {
    const { pointer, graph, linkConnector } = this;
    if (!graph) throw new NullGraphError();
    const x2 = e2.canvasX;
    const y2 = e2.canvasY;
    const ctrlOrMeta = e2.ctrlKey || e2.metaKey;
    if (ctrlOrMeta && !e2.altKey) {
      const dragRect = new Float32Array(4);
      dragRect[0] = x2;
      dragRect[1] = y2;
      dragRect[2] = 1;
      dragRect[3] = 1;
      pointer.onClick = (eUp) => {
        const clickedItem = node2 ?? graph.getRerouteOnPos(eUp.canvasX, eUp.canvasY, this.#visibleReroutes) ?? graph.getGroupTitlebarOnPos(eUp.canvasX, eUp.canvasY);
        this.processSelect(clickedItem, eUp);
      };
      pointer.onDragStart = () => this.dragging_rectangle = dragRect;
      pointer.onDragEnd = (upEvent) => this.#handleMultiSelect(upEvent, dragRect);
      pointer.finally = () => this.dragging_rectangle = null;
      return;
    }
    if (this.read_only) {
      pointer.finally = () => this.dragging_canvas = false;
      this.dragging_canvas = true;
      return;
    }
    if (LiteGraph.alt_drag_do_clone_nodes && e2.altKey && !e2.ctrlKey && node2 && this.allow_interaction) {
      const node_data = node2.clone()?.serialize();
      if (node_data?.type != null) {
        const cloned = LiteGraph.createNode(node_data.type);
        if (cloned) {
          cloned.configure(node_data);
          cloned.pos[0] += 5;
          cloned.pos[1] += 5;
          if (this.allow_dragnodes) {
            pointer.onDragStart = (pointer2) => {
              graph.add(cloned, false);
              this.#startDraggingItems(cloned, pointer2);
            };
            pointer.onDragEnd = (e22) => this.#processDraggedItems(e22);
          } else {
            graph.beforeChange();
            graph.add(cloned, false);
            graph.afterChange();
          }
          return;
        }
      }
    }
    if (node2 && (this.allow_interaction || node2.flags.allow_interaction)) {
      this.#processNodeClick(e2, ctrlOrMeta, node2);
    } else {
      if (this.links_render_mode !== LinkRenderType.HIDDEN_LINK) {
        for (const reroute of this.#visibleReroutes) {
          const overReroute = reroute.containsPoint([x2, y2]);
          if (!reroute.isSlotHovered && !overReroute) continue;
          if (overReroute) {
            pointer.onClick = () => this.processSelect(reroute, e2);
            if (!e2.shiftKey) {
              pointer.onDragStart = (pointer2) => this.#startDraggingItems(reroute, pointer2, true);
              pointer.onDragEnd = (e22) => this.#processDraggedItems(e22);
            }
          }
          if (reroute.isOutputHovered || overReroute && e2.shiftKey) {
            linkConnector.dragFromReroute(graph, reroute);
            this.#linkConnectorDrop();
          }
          if (reroute.isInputHovered) {
            linkConnector.dragFromRerouteToOutput(graph, reroute);
            this.#linkConnectorDrop();
          }
          reroute.hideSlots();
          this.dirty_bgcanvas = true;
          return;
        }
      }
      const { lineWidth } = this.ctx;
      this.ctx.lineWidth = this.connections_width + 7;
      const dpi = window?.devicePixelRatio || 1;
      for (const linkSegment of this.renderedPaths) {
        const centre = linkSegment._pos;
        if (!centre) continue;
        if ((e2.shiftKey || e2.altKey) && linkSegment.path && this.ctx.isPointInStroke(linkSegment.path, x2 * dpi, y2 * dpi)) {
          this.ctx.lineWidth = lineWidth;
          if (e2.shiftKey && !e2.altKey) {
            linkConnector.dragFromLinkSegment(graph, linkSegment);
            this.#linkConnectorDrop();
            return;
          } else if (e2.altKey && !e2.shiftKey) {
            const newReroute = graph.createReroute([x2, y2], linkSegment);
            pointer.onDragStart = (pointer2) => this.#startDraggingItems(newReroute, pointer2);
            pointer.onDragEnd = (e22) => this.#processDraggedItems(e22);
            return;
          }
        } else if (isInRectangle(x2, y2, centre[0] - 4, centre[1] - 4, 8, 8)) {
          this.ctx.lineWidth = lineWidth;
          pointer.onClick = () => this.showLinkMenu(linkSegment, e2);
          pointer.onDragStart = () => this.dragging_canvas = true;
          pointer.finally = () => this.dragging_canvas = false;
          this.over_link_center = void 0;
          return;
        }
      }
      this.ctx.lineWidth = lineWidth;
      const group = graph.getGroupOnPos(x2, y2);
      this.selected_group = group ?? null;
      if (group) {
        if (group.isInResize(x2, y2)) {
          const b2 = group.boundingRect;
          const offsetX = x2 - (b2[0] + b2[2]);
          const offsetY = y2 - (b2[1] + b2[3]);
          pointer.onDragStart = () => this.resizingGroup = group;
          pointer.onDrag = (eMove) => {
            if (this.read_only) return;
            const pos = [
              eMove.canvasX - group.pos[0] - offsetX,
              eMove.canvasY - group.pos[1] - offsetY
            ];
            if (this.#snapToGrid) snapPoint(pos, this.#snapToGrid);
            const resized = group.resize(pos[0], pos[1]);
            if (resized) this.dirty_bgcanvas = true;
          };
          pointer.finally = () => this.resizingGroup = null;
        } else {
          const f2 = group.font_size || LiteGraph.DEFAULT_GROUP_FONT_SIZE;
          const headerHeight = f2 * 1.4;
          if (isInRectangle(
            x2,
            y2,
            group.pos[0],
            group.pos[1],
            group.size[0],
            headerHeight
          )) {
            pointer.onClick = () => this.processSelect(group, e2);
            pointer.onDragStart = (pointer2) => {
              group.recomputeInsideNodes();
              this.#startDraggingItems(group, pointer2, true);
            };
            pointer.onDragEnd = (e22) => this.#processDraggedItems(e22);
          }
        }
        pointer.onDoubleClick = () => {
          this.emitEvent({
            subType: "group-double-click",
            originalEvent: e2,
            group
          });
        };
      } else {
        pointer.onDoubleClick = () => {
          if (this.allow_searchbox) {
            this.showSearchBox(e2);
            e2.preventDefault();
          }
          this.emitEvent({
            subType: "empty-double-click",
            originalEvent: e2
          });
        };
      }
    }
    if (!pointer.onDragStart && !pointer.onClick && !pointer.onDrag && this.allow_dragcanvas) {
      pointer.onClick = () => this.processSelect(null, e2);
      pointer.finally = () => this.dragging_canvas = false;
      this.dragging_canvas = true;
    }
  }
  /**
   * Processes a pointerdown event inside the bounds of a node.  Part of {@link processMouseDown}.
   * @param e The pointerdown event
   * @param ctrlOrMeta Ctrl or meta key is pressed
   * @param node The node to process a click event for
   */
  #processNodeClick(e2, ctrlOrMeta, node2) {
    const { pointer, graph, linkConnector } = this;
    if (!graph) throw new NullGraphError();
    const x2 = e2.canvasX;
    const y2 = e2.canvasY;
    pointer.onClick = () => this.processSelect(node2, e2);
    if (!node2.flags.pinned) {
      this.bringToFront(node2);
    }
    const inCollapse = node2.isPointInCollapse(x2, y2);
    if (inCollapse) {
      pointer.onClick = () => {
        node2.collapse();
        this.setDirty(true, true);
      };
    } else if (!node2.flags.collapsed) {
      if (node2.resizable !== false && node2.inResizeCorner(x2, y2)) {
        const b2 = node2.boundingRect;
        const offsetX = x2 - (b2[0] + b2[2]);
        const offsetY = y2 - (b2[1] + b2[3]);
        pointer.onDragStart = () => {
          graph.beforeChange();
          this.resizing_node = node2;
        };
        pointer.onDrag = (eMove) => {
          if (this.read_only) return;
          const pos2 = [
            eMove.canvasX - node2.pos[0] - offsetX,
            eMove.canvasY - node2.pos[1] - offsetY
          ];
          if (this.#snapToGrid) snapPoint(pos2, this.#snapToGrid);
          const min = node2.computeSize();
          pos2[0] = Math.max(min[0], pos2[0]);
          pos2[1] = Math.max(min[1], pos2[1]);
          node2.setSize(pos2);
          this.#dirty();
        };
        pointer.onDragEnd = () => {
          this.#dirty();
          graph.afterChange(this.resizing_node);
        };
        pointer.finally = () => this.resizing_node = null;
        this.canvas.style.cursor = "se-resize";
        return;
      }
      const { inputs, outputs } = node2;
      if (outputs) {
        for (const [i2, output] of outputs.entries()) {
          const link_pos = node2.getOutputPos(i2);
          if (isInRectangle(x2, y2, link_pos[0] - 15, link_pos[1] - 10, 30, 20)) {
            if (e2.shiftKey && (output.links?.length || output._floatingLinks?.size)) {
              linkConnector.moveOutputLink(graph, output);
              this.#linkConnectorDrop();
              return;
            }
            linkConnector.dragNewFromOutput(graph, node2, output);
            this.#linkConnectorDrop();
            if (LiteGraph.shift_click_do_break_link_from) {
              if (e2.shiftKey) {
                node2.disconnectOutput(i2);
              }
            } else if (LiteGraph.ctrl_alt_click_do_break_link) {
              if (ctrlOrMeta && e2.altKey && !e2.shiftKey) {
                node2.disconnectOutput(i2);
              }
            }
            pointer.onDoubleClick = () => node2.onOutputDblClick?.(i2, e2);
            pointer.onClick = () => node2.onOutputClick?.(i2, e2);
            return;
          }
        }
      }
      if (inputs) {
        for (const [i2, input] of inputs.entries()) {
          const link_pos = node2.getInputPos(i2);
          const isInSlot = input instanceof NodeInputSlot ? isInRect(x2, y2, input.boundingRect) : isInRectangle(x2, y2, link_pos[0] - 15, link_pos[1] - 10, 30, 20);
          if (isInSlot) {
            pointer.onDoubleClick = () => node2.onInputDblClick?.(i2, e2);
            pointer.onClick = () => node2.onInputClick?.(i2, e2);
            const shouldBreakLink = LiteGraph.ctrl_alt_click_do_break_link && ctrlOrMeta && e2.altKey && !e2.shiftKey;
            if (input.link !== null || input._floatingLinks?.size) {
              if (shouldBreakLink || LiteGraph.click_do_break_link_to) {
                node2.disconnectInput(i2, true);
              } else if (e2.shiftKey || this.allow_reconnect_links) {
                linkConnector.moveInputLink(graph, input);
              }
            }
            if (!linkConnector.isConnecting) {
              linkConnector.dragNewFromInput(graph, node2, input);
            }
            this.#linkConnectorDrop();
            this.dirty_bgcanvas = true;
            return;
          }
        }
      }
    }
    const pos = [x2 - node2.pos[0], y2 - node2.pos[1]];
    const widget = node2.getWidgetOnPos(x2, y2);
    if (widget) {
      this.#processWidgetClick(e2, node2, widget);
      this.node_widget = [node2, widget];
    } else {
      pointer.onDoubleClick = () => {
        if (pos[1] < 0 && !inCollapse) {
          node2.onNodeTitleDblClick?.(e2, pos, this);
        }
        node2.onDblClick?.(e2, pos, this);
        this.emitEvent({
          subType: "node-double-click",
          originalEvent: e2,
          node: node2
        });
        this.processNodeDblClicked(node2);
      };
      if (node2.onMouseDown?.(e2, pos, this) || !this.allow_dragnodes)
        return;
      pointer.onDragStart = (pointer2) => this.#startDraggingItems(node2, pointer2, true);
      pointer.onDragEnd = (e22) => this.#processDraggedItems(e22);
    }
    this.dirty_canvas = true;
  }
  #processWidgetClick(e2, node2, widget) {
    const { pointer } = this;
    if (typeof widget.onPointerDown === "function") {
      const handled = widget.onPointerDown(pointer, node2, this);
      if (handled) return;
    }
    const oldValue = widget.value;
    const pos = this.graph_mouse;
    const x2 = pos[0] - node2.pos[0];
    const y2 = pos[1] - node2.pos[1];
    const widgetInstance = toConcreteWidget(widget, node2, false);
    if (widgetInstance) {
      pointer.onClick = () => widgetInstance.onClick({
        e: e2,
        node: node2,
        canvas: this
      });
      pointer.onDrag = (eMove) => widgetInstance.onDrag?.({
        e: eMove,
        node: node2,
        canvas: this
      });
    } else if (widget.mouse) {
      const result = widget.mouse(e2, [x2, y2], node2);
      if (result != null) this.dirty_canvas = result;
    }
    if (oldValue != widget.value) {
      node2.onWidgetChanged?.(widget.name, widget.value, oldValue, widget);
      if (!node2.graph) throw new NullGraphError();
      node2.graph._version++;
    }
    pointer.finally = () => {
      if (widget.mouse) {
        const { eUp } = pointer;
        if (!eUp) return;
        const { canvasX, canvasY } = eUp;
        widget.mouse(eUp, [canvasX - node2.pos[0], canvasY - node2.pos[1]], node2);
      }
      this.node_widget = null;
    };
  }
  /**
   * Pointer middle button click processing.  Part of {@link processMouseDown}.
   * @param e The pointerdown event
   * @param node The node to process a click event for
   */
  #processMiddleButton(e2, node2) {
    const { pointer } = this;
    if (LiteGraph.middle_click_slot_add_default_node && node2 && this.allow_interaction && !this.read_only && !this.connecting_links && !node2.flags.collapsed) {
      let mClikSlot = false;
      let mClikSlot_index = false;
      let mClikSlot_isOut = false;
      const { inputs, outputs } = node2;
      if (outputs) {
        for (const [i2, output] of outputs.entries()) {
          const link_pos = node2.getOutputPos(i2);
          if (isInRectangle(e2.canvasX, e2.canvasY, link_pos[0] - 15, link_pos[1] - 10, 30, 20)) {
            mClikSlot = output;
            mClikSlot_index = i2;
            mClikSlot_isOut = true;
            break;
          }
        }
      }
      if (inputs) {
        for (const [i2, input] of inputs.entries()) {
          const link_pos = node2.getInputPos(i2);
          if (isInRectangle(e2.canvasX, e2.canvasY, link_pos[0] - 15, link_pos[1] - 10, 30, 20)) {
            mClikSlot = input;
            mClikSlot_index = i2;
            mClikSlot_isOut = false;
            break;
          }
        }
      }
      if (mClikSlot && mClikSlot_index !== false) {
        const alphaPosY = 0.5 - (mClikSlot_index + 1) / (mClikSlot_isOut ? outputs.length : inputs.length);
        const node_bounding = node2.getBounding();
        const posRef = [
          !mClikSlot_isOut ? node_bounding[0] : node_bounding[0] + node_bounding[2],
          e2.canvasY - 80
        ];
        pointer.onClick = () => this.createDefaultNodeForSlot({
          nodeFrom: !mClikSlot_isOut ? null : node2,
          slotFrom: !mClikSlot_isOut ? null : mClikSlot_index,
          nodeTo: !mClikSlot_isOut ? node2 : null,
          slotTo: !mClikSlot_isOut ? mClikSlot_index : null,
          position: posRef,
          nodeType: "AUTO",
          posAdd: [!mClikSlot_isOut ? -30 : 30, -alphaPosY * 130],
          posSizeFix: [!mClikSlot_isOut ? -1 : 0, 0]
        });
      }
    }
    if (this.allow_dragcanvas) {
      pointer.onDragStart = () => this.dragging_canvas = true;
      pointer.finally = () => this.dragging_canvas = false;
    }
  }
  #processDragZoom(e2) {
    if (!e2.buttons) {
      this.#dragZoomStart = null;
      return;
    }
    const start2 = this.#dragZoomStart;
    if (!start2) throw new TypeError("Drag-zoom state object was null");
    if (!this.graph) throw new NullGraphError();
    const deltaY = e2.y - start2.pos[1];
    const startScale = start2.scale;
    const scale = startScale - deltaY / 100;
    this.ds.changeScale(scale, start2.pos);
    this.graph.change();
  }
  /**
   * Called when a mouse move event has to be processed
   */
  processMouseMove(e2) {
    if (this.dragZoomEnabled && e2.ctrlKey && e2.shiftKey && this.#dragZoomStart) {
      this.#processDragZoom(e2);
      return;
    }
    if (this.autoresize) this.resize();
    if (this.set_canvas_dirty_on_mouse_event) this.dirty_canvas = true;
    const { graph, resizingGroup, linkConnector } = this;
    if (!graph) return;
    LGraphCanvas.active_canvas = this;
    this.adjustMouseEvent(e2);
    const mouse = [e2.clientX, e2.clientY];
    this.mouse[0] = mouse[0];
    this.mouse[1] = mouse[1];
    const delta2 = [
      mouse[0] - this.last_mouse[0],
      mouse[1] - this.last_mouse[1]
    ];
    this.last_mouse = mouse;
    this.graph_mouse[0] = e2.canvasX;
    this.graph_mouse[1] = e2.canvasY;
    if (e2.isPrimary) this.pointer.move(e2);
    if (this.block_click) {
      e2.preventDefault();
      return;
    }
    e2.dragging = this.last_mouse_dragging;
    if (this.node_widget) {
      const [node22, widget] = this.node_widget;
      if (widget?.mouse) {
        const x2 = e2.canvasX - node22.pos[0];
        const y2 = e2.canvasY - node22.pos[1];
        const result = widget.mouse(e2, [x2, y2], node22);
        if (result != null) this.dirty_canvas = result;
      }
    }
    let underPointer = CanvasItem.Nothing;
    const node2 = graph.getNodeOnPos(
      e2.canvasX,
      e2.canvasY,
      this.visible_nodes
    );
    const dragRect = this.dragging_rectangle;
    if (dragRect) {
      dragRect[2] = e2.canvasX - dragRect[0];
      dragRect[3] = e2.canvasY - dragRect[1];
      this.dirty_canvas = true;
    } else if (resizingGroup) {
      underPointer |= CanvasItem.ResizeSe | CanvasItem.Group;
    } else if (this.dragging_canvas) {
      this.ds.offset[0] += delta2[0] / this.ds.scale;
      this.ds.offset[1] += delta2[1] / this.ds.scale;
      this.#dirty();
    } else if ((this.allow_interaction || node2?.flags.allow_interaction) && !this.read_only) {
      if (linkConnector.isConnecting) this.dirty_canvas = true;
      this.updateMouseOverNodes(node2, e2);
      if (node2) {
        underPointer |= CanvasItem.Node;
        if (node2.redraw_on_mouse) this.dirty_canvas = true;
        const pos = [0, 0];
        const inputId = isOverNodeInput(node2, e2.canvasX, e2.canvasY, pos);
        const outputId = isOverNodeOutput(node2, e2.canvasX, e2.canvasY, pos);
        const overWidget = node2.getWidgetOnPos(e2.canvasX, e2.canvasY, true) ?? void 0;
        if (!node2.mouseOver) {
          node2.mouseOver = {};
          this.node_over = node2;
          this.dirty_canvas = true;
          for (const reroute of this.#visibleReroutes) {
            reroute.hideSlots();
            this.dirty_bgcanvas = true;
          }
          node2.onMouseEnter?.(e2);
        }
        node2.onMouseMove?.(e2, [e2.canvasX - node2.pos[0], e2.canvasY - node2.pos[1]], this);
        const { mouseOver } = node2;
        if (mouseOver.inputId !== inputId || mouseOver.outputId !== outputId || mouseOver.overWidget !== overWidget) {
          mouseOver.inputId = inputId;
          mouseOver.outputId = outputId;
          mouseOver.overWidget = overWidget;
          linkConnector.overWidget = void 0;
          if (linkConnector.isConnecting) {
            const firstLink = linkConnector.renderLinks.at(0);
            let highlightPos;
            let highlightInput;
            if (!firstLink || !linkConnector.isNodeValidDrop(node2)) ;
            else if (linkConnector.state.connectingTo === "input") {
              if (overWidget) {
                const slot = node2.getSlotFromWidget(overWidget);
                if (slot && linkConnector.isInputValidDrop(node2, slot)) {
                  highlightInput = slot;
                  highlightPos = node2.getInputSlotPos(slot);
                  linkConnector.overWidget = overWidget;
                }
              }
              if (!linkConnector.overWidget) {
                if (inputId === -1 && outputId === -1) {
                  const result = node2.findInputByType(firstLink.fromSlot.type);
                  if (result) {
                    highlightInput = result.slot;
                    highlightPos = node2.getInputSlotPos(result.slot);
                  }
                } else if (inputId != -1 && node2.inputs[inputId] && LiteGraph.isValidConnection(firstLink.fromSlot.type, node2.inputs[inputId].type)) {
                  highlightPos = pos;
                  highlightInput = node2.inputs[inputId];
                }
                if (highlightInput) {
                  const widget = node2.getWidgetFromSlot(highlightInput);
                  if (widget) linkConnector.overWidget = widget;
                }
              }
            } else if (linkConnector.state.connectingTo === "output") {
              if (inputId === -1 && outputId === -1) {
                const result = node2.findOutputByType(firstLink.fromSlot.type);
                if (result) {
                  highlightPos = node2.getOutputPos(result.index);
                }
              } else {
                if (outputId != -1 && node2.outputs[outputId] && LiteGraph.isValidConnection(firstLink.fromSlot.type, node2.outputs[outputId].type)) {
                  highlightPos = pos;
                }
              }
            }
            this._highlight_pos = highlightPos;
            this._highlight_input = highlightInput;
          }
          this.dirty_canvas = true;
        }
        if (node2.inResizeCorner(e2.canvasX, e2.canvasY)) {
          underPointer |= CanvasItem.ResizeSe;
        }
      } else {
        underPointer = this.#updateReroutes(underPointer);
        const segment = this.#getLinkCentreOnPos(e2);
        if (this.over_link_center !== segment) {
          underPointer |= CanvasItem.Link;
          this.over_link_center = segment;
          this.dirty_bgcanvas = true;
        }
        if (this.canvas) {
          const group = graph.getGroupOnPos(e2.canvasX, e2.canvasY);
          if (group && !e2.ctrlKey && !this.read_only && group.isInResize(e2.canvasX, e2.canvasY)) {
            underPointer |= CanvasItem.ResizeSe;
          }
        }
      }
      if (this.node_capturing_input && this.node_capturing_input != node2) {
        this.node_capturing_input.onMouseMove?.(
          e2,
          [
            e2.canvasX - this.node_capturing_input.pos[0],
            e2.canvasY - this.node_capturing_input.pos[1]
          ],
          this
        );
      }
      if (this.isDragging) {
        const selected = this.selectedItems;
        const allItems = e2.ctrlKey ? selected : getAllNestedItems(selected);
        const deltaX = delta2[0] / this.ds.scale;
        const deltaY = delta2[1] / this.ds.scale;
        for (const item of allItems) {
          item.move(deltaX, deltaY, true);
        }
        this.#dirty();
      }
      if (this.resizing_node) underPointer |= CanvasItem.ResizeSe;
    }
    this.hoveringOver = underPointer;
    e2.preventDefault();
    return;
  }
  /**
   * Updates the hover / snap state of all visible reroutes.
   * @returns The original value of {@link underPointer}, with any found reroute items added.
   */
  #updateReroutes(underPointer) {
    const { graph, pointer, linkConnector } = this;
    if (!graph) throw new NullGraphError();
    if (!pointer.isDown) {
      let anyChanges = false;
      for (const reroute of this.#visibleReroutes) {
        anyChanges ||= reroute.updateVisibility(this.graph_mouse);
        if (reroute.isSlotHovered) underPointer |= CanvasItem.RerouteSlot;
      }
      if (anyChanges) this.dirty_bgcanvas = true;
    } else if (linkConnector.isConnecting) {
      for (const reroute of this.#visibleReroutes) {
        if (reroute.containsPoint(this.graph_mouse)) {
          if (linkConnector.isRerouteValidDrop(reroute)) {
            linkConnector.overReroute = reroute;
            this._highlight_pos = reroute.pos;
          }
          return underPointer |= CanvasItem.RerouteSlot;
        }
      }
    }
    this._highlight_pos &&= void 0;
    linkConnector.overReroute &&= void 0;
    return underPointer;
  }
  /**
   * Start dragging an item, optionally including all other selected items.
   *
   * ** This function sets the {@link CanvasPointer.finally}() callback. **
   * @param item The item that the drag event started on
   * @param pointer The pointer event that initiated the drag, e.g. pointerdown
   * @param sticky If `true`, the item is added to the selection - see {@link processSelect}
   */
  #startDraggingItems(item, pointer, sticky = false) {
    this.emitBeforeChange();
    this.graph?.beforeChange();
    pointer.finally = () => {
      this.isDragging = false;
      this.graph?.afterChange();
      this.emitAfterChange();
    };
    this.processSelect(item, pointer.eDown, sticky);
    this.isDragging = true;
  }
  /**
   * Handles shared clean up and placement after items have been dragged.
   * @param e The event that completed the drag, e.g. pointerup, pointermove
   */
  #processDraggedItems(e2) {
    const { graph } = this;
    if (e2.shiftKey || LiteGraph.alwaysSnapToGrid)
      graph?.snapToGrid(this.selectedItems);
    this.dirty_canvas = true;
    this.dirty_bgcanvas = true;
    this.onNodeMoved?.(findFirstNode(this.selectedItems));
  }
  /**
   * Called when a mouse up event has to be processed
   */
  processMouseUp(e2) {
    if (e2.isPrimary === false) return;
    const { graph, pointer } = this;
    if (!graph) return;
    LGraphCanvas.active_canvas = this;
    this.adjustMouseEvent(e2);
    const now2 = LiteGraph.getTime();
    e2.click_time = now2 - this.last_mouseclick;
    const isClick = pointer.up(e2);
    if (isClick === true) {
      pointer.isDown = false;
      pointer.isDouble = false;
      this.connecting_links = null;
      this.dragging_canvas = false;
      graph.change();
      e2.stopPropagation();
      e2.preventDefault();
      return;
    }
    this.last_mouse_dragging = false;
    this.last_click_position = null;
    this.block_click &&= false;
    if (e2.button === 0) {
      this.selected_group = null;
      this.isDragging = false;
      const x2 = e2.canvasX;
      const y2 = e2.canvasY;
      if (!this.linkConnector.isConnecting) {
        this.dirty_canvas = true;
        this.node_over?.onMouseUp?.(e2, [x2 - this.node_over.pos[0], y2 - this.node_over.pos[1]], this);
        this.node_capturing_input?.onMouseUp?.(e2, [
          x2 - this.node_capturing_input.pos[0],
          y2 - this.node_capturing_input.pos[1]
        ]);
      }
    } else if (e2.button === 1) {
      this.dirty_canvas = true;
      this.dragging_canvas = false;
    } else if (e2.button === 2) {
      this.dirty_canvas = true;
    }
    pointer.isDown = false;
    pointer.isDouble = false;
    graph.change();
    e2.stopPropagation();
    e2.preventDefault();
    return;
  }
  /**
   * Called when the mouse moves off the canvas.  Clears all node hover states.
   * @param e
   */
  processMouseOut(e2) {
    this.adjustMouseEvent(e2);
    this.updateMouseOverNodes(null, e2);
  }
  processMouseCancel() {
    console.warn("Pointer cancel!");
    this.pointer.reset();
  }
  /**
   * Called when a mouse wheel event has to be processed
   */
  processMouseWheel(e2) {
    if (!this.graph || !this.allow_dragcanvas) return;
    const delta2 = e2.wheelDeltaY ?? e2.detail * -60;
    this.adjustMouseEvent(e2);
    const pos = [e2.clientX, e2.clientY];
    if (this.viewport && !isPointInRect(pos, this.viewport)) return;
    let { scale } = this.ds;
    if (LiteGraph.macTrackpadGestures && (!LiteGraph.macGesturesRequireMac || navigator.userAgent.includes("Mac"))) {
      if (e2.ctrlKey && !Number.isInteger(e2.deltaY)) {
        scale *= 1 + e2.deltaY * (1 - this.zoom_speed) * 0.18;
        this.ds.changeScale(scale, [e2.clientX, e2.clientY], false);
      } else {
        this.ds.offset[0] -= e2.deltaX * 1.18 * (1 / scale);
        this.ds.offset[1] -= e2.deltaY * 1.18 * (1 / scale);
      }
    } else {
      if (delta2 > 0) {
        scale *= this.zoom_speed;
      } else if (delta2 < 0) {
        scale *= 1 / this.zoom_speed;
      }
      this.ds.changeScale(scale, [e2.clientX, e2.clientY]);
    }
    this.graph.change();
    e2.preventDefault();
    return;
  }
  #noItemsSelected() {
    const event = new CustomEvent("litegraph:no-items-selected", { bubbles: true });
    this.canvas.dispatchEvent(event);
  }
  /**
   * process a key event
   */
  processKey(e2) {
    this.#shiftDown = e2.shiftKey;
    const { graph } = this;
    if (!graph) return;
    let block_default = false;
    if (e2.target.localName == "input") return;
    if (e2.type == "keydown") {
      if (e2.key === " ") {
        this.read_only = true;
        if (this._previously_dragging_canvas === null) {
          this._previously_dragging_canvas = this.dragging_canvas;
        }
        this.dragging_canvas = this.pointer.isDown;
        block_default = true;
      } else if (e2.key === "Escape") {
        if (this.linkConnector.isConnecting) {
          this.linkConnector.reset();
          this.#dirty();
          e2.preventDefault();
          return;
        }
        this.node_panel?.close();
        this.options_panel?.close();
        block_default = true;
      } else if (e2.keyCode === 65 && e2.ctrlKey) {
        this.selectItems();
        block_default = true;
      } else if (e2.keyCode === 67 && (e2.metaKey || e2.ctrlKey) && !e2.shiftKey) {
        if (this.selected_nodes) {
          this.copyToClipboard();
          block_default = true;
        }
      } else if (e2.keyCode === 86 && (e2.metaKey || e2.ctrlKey)) {
        this.pasteFromClipboard({ connectInputs: e2.shiftKey });
      } else if (e2.key === "Delete" || e2.key === "Backspace") {
        if (e2.target.localName != "input" && e2.target.localName != "textarea") {
          if (this.selectedItems.size === 0) {
            this.#noItemsSelected();
            return;
          }
          this.deleteSelected();
          block_default = true;
        }
      }
      for (const node2 of Object.values(this.selected_nodes)) {
        node2.onKeyDown?.(e2);
      }
    } else if (e2.type == "keyup") {
      if (e2.key === " ") {
        this.read_only = false;
        this.dragging_canvas = (this._previously_dragging_canvas ?? false) && this.pointer.isDown;
        this._previously_dragging_canvas = null;
      }
      for (const node2 of Object.values(this.selected_nodes)) {
        node2.onKeyUp?.(e2);
      }
    }
    graph.change();
    if (block_default) {
      e2.preventDefault();
      e2.stopImmediatePropagation();
    }
  }
  /**
   * Copies canvas items to an internal, app-specific clipboard backed by local storage.
   * When called without parameters, it copies {@link selectedItems}.
   * @param items The items to copy.  If nullish, all selected items are copied.
   */
  copyToClipboard(items) {
    const serialisable = {
      nodes: [],
      groups: [],
      reroutes: [],
      links: []
    };
    for (const item of items ?? this.selectedItems) {
      if (item instanceof LGraphNode) {
        if (item.clonable === false) continue;
        const cloned = item.clone()?.serialize();
        if (!cloned) continue;
        cloned.id = item.id;
        serialisable.nodes.push(cloned);
        if (item.inputs) {
          for (const { link: linkId } of item.inputs) {
            if (linkId == null) continue;
            const link2 = this.graph?._links.get(linkId)?.asSerialisable();
            if (link2) serialisable.links.push(link2);
          }
        }
      } else if (item instanceof LGraphGroup) {
        serialisable.groups.push(item.serialize());
      } else if (item instanceof Reroute) {
        serialisable.reroutes.push(item.asSerialisable());
      }
    }
    localStorage.setItem(
      "litegrapheditor_clipboard",
      JSON.stringify(serialisable)
    );
  }
  emitEvent(detail) {
    this.canvas.dispatchEvent(
      new CustomEvent("litegraph:canvas", {
        bubbles: true,
        detail
      })
    );
  }
  /** @todo Refactor to where it belongs - e.g. Deleting / creating nodes is not actually canvas event. */
  emitBeforeChange() {
    this.emitEvent({
      subType: "before-change"
    });
  }
  /** @todo See {@link emitBeforeChange} */
  emitAfterChange() {
    this.emitEvent({
      subType: "after-change"
    });
  }
  /**
   * Pastes the items from the canvas "clipbaord" - a local storage variable.
   */
  _pasteFromClipboard(options2 = {}) {
    const {
      connectInputs = false,
      position = this.graph_mouse
    } = options2;
    if (!LiteGraph.ctrl_shift_v_paste_connect_unselected_outputs && connectInputs) return;
    const data = localStorage.getItem("litegrapheditor_clipboard");
    if (!data) return;
    const { graph } = this;
    if (!graph) throw new NullGraphError();
    graph.beforeChange();
    const parsed = JSON.parse(data);
    parsed.nodes ??= [];
    parsed.groups ??= [];
    parsed.reroutes ??= [];
    parsed.links ??= [];
    let offsetX = Infinity;
    let offsetY = Infinity;
    for (const item of [...parsed.nodes, ...parsed.reroutes]) {
      if (item.pos == null) throw new TypeError("Invalid node encounterd on paste.  `pos` was null.");
      if (item.pos[0] < offsetX) offsetX = item.pos[0];
      if (item.pos[1] < offsetY) offsetY = item.pos[1];
    }
    if (parsed.groups) {
      for (const group of parsed.groups) {
        if (group.bounding[0] < offsetX) offsetX = group.bounding[0];
        if (group.bounding[1] < offsetY) offsetY = group.bounding[1];
      }
    }
    const results = {
      created: [],
      nodes: /* @__PURE__ */ new Map(),
      links: /* @__PURE__ */ new Map(),
      reroutes: /* @__PURE__ */ new Map()
    };
    const { created: created2, nodes, links, reroutes } = results;
    for (const info of parsed.groups) {
      info.id = -1;
      const group = new LGraphGroup();
      group.configure(info);
      graph.add(group);
      created2.push(group);
    }
    for (const info of parsed.nodes) {
      const node2 = info.type == null ? null : LiteGraph.createNode(info.type);
      if (!node2) {
        continue;
      }
      nodes.set(info.id, node2);
      info.id = -1;
      node2.configure(info);
      graph.add(node2);
      created2.push(node2);
    }
    for (const info of parsed.reroutes) {
      const { id: id2, ...rerouteInfo } = info;
      const reroute = graph.setReroute(rerouteInfo);
      created2.push(reroute);
      reroutes.set(id2, reroute);
    }
    for (const reroute of reroutes.values()) {
      if (reroute.parentId == null) continue;
      const mapped = reroutes.get(reroute.parentId);
      if (mapped) reroute.parentId = mapped.id;
    }
    for (const info of parsed.links) {
      let outNode = nodes.get(info.origin_id);
      let afterRerouteId;
      if (info.parentId != null) afterRerouteId = reroutes.get(info.parentId)?.id;
      if (connectInputs && LiteGraph.ctrl_shift_v_paste_connect_unselected_outputs) {
        outNode ??= graph.getNodeById(info.origin_id);
        afterRerouteId ??= info.parentId;
      }
      const inNode = nodes.get(info.target_id);
      if (inNode) {
        const link2 = outNode?.connect(
          info.origin_slot,
          inNode,
          info.target_slot,
          afterRerouteId
        );
        if (link2) links.set(info.id, link2);
      }
    }
    for (const reroute of reroutes.values()) {
      const ids = [...reroute.linkIds].map((x2) => links.get(x2)?.id ?? x2);
      reroute.update(reroute.parentId, void 0, ids, reroute.floating);
      if (!reroute.validateLinks(graph.links, graph.floatingLinks)) {
        graph.removeReroute(reroute.id);
      }
    }
    for (const item of created2) {
      item.pos[0] += position[0] - offsetX;
      item.pos[1] += position[1] - offsetY;
    }
    this.selectItems(created2);
    graph.afterChange();
    return results;
  }
  pasteFromClipboard(options2 = {}) {
    this.emitBeforeChange();
    try {
      this._pasteFromClipboard(options2);
    } finally {
      this.emitAfterChange();
    }
  }
  processNodeDblClicked(n2) {
    this.onShowNodePanel?.(n2);
    this.onNodeDblClicked?.(n2);
    this.setDirty(true);
  }
  #handleMultiSelect(e2, dragRect) {
    const { graph, selectedItems } = this;
    if (!graph) throw new NullGraphError();
    const w2 = Math.abs(dragRect[2]);
    const h2 = Math.abs(dragRect[3]);
    if (dragRect[2] < 0) dragRect[0] -= w2;
    if (dragRect[3] < 0) dragRect[1] -= h2;
    dragRect[2] = w2;
    dragRect[3] = h2;
    const isSelected = /* @__PURE__ */ new Set();
    const notSelected = [];
    for (const nodeX of graph._nodes) {
      if (overlapBounding(dragRect, nodeX.boundingRect)) {
        addPositionable(nodeX);
      }
    }
    for (const group of graph.groups) {
      if (!containsRect(dragRect, group._bounding)) continue;
      group.recomputeInsideNodes();
      addPositionable(group);
    }
    for (const reroute of graph.reroutes.values()) {
      if (!isPointInRect(reroute.pos, dragRect)) continue;
      selectedItems.add(reroute);
      reroute.selected = true;
      addPositionable(reroute);
    }
    if (e2.shiftKey) {
      for (const item of notSelected) this.select(item);
    } else if (e2.altKey) {
      for (const item of isSelected) this.deselect(item);
    } else {
      for (const item of selectedItems.values()) {
        if (!isSelected.has(item)) this.deselect(item);
      }
      for (const item of notSelected) this.select(item);
    }
    this.onSelectionChange?.(this.selected_nodes);
    function addPositionable(item) {
      if (!item.selected || !selectedItems.has(item)) notSelected.push(item);
      else isSelected.add(item);
    }
    __name(addPositionable, "addPositionable");
  }
  /**
   * Determines whether to select or deselect an item that has received a pointer event.  Will deselect other nodes if
   * @param item Canvas item to select/deselect
   * @param e The MouseEvent to handle
   * @param sticky Prevents deselecting individual nodes (as used by aux/right-click)
   * @remarks
   * Accessibility: anyone using {@link mutli_select} always deselects when clicking empty space.
   */
  processSelect(item, e2, sticky = false) {
    const addModifier = e2?.shiftKey;
    const subtractModifier = e2 != null && (e2.metaKey || e2.ctrlKey);
    const eitherModifier = addModifier || subtractModifier;
    const modifySelection = eitherModifier || this.multi_select;
    if (!item) {
      if (!eitherModifier || this.multi_select) this.deselectAll();
    } else if (!item.selected || !this.selectedItems.has(item)) {
      if (!modifySelection) this.deselectAll(item);
      this.select(item);
    } else if (modifySelection && !sticky) {
      this.deselect(item);
    } else if (!sticky) {
      this.deselectAll(item);
    } else {
      return;
    }
    this.onSelectionChange?.(this.selected_nodes);
    this.setDirty(true);
  }
  /**
   * Selects a {@link Positionable} item.
   * @param item The canvas item to add to the selection.
   */
  select(item) {
    if (item.selected && this.selectedItems.has(item)) return;
    item.selected = true;
    this.selectedItems.add(item);
    if (!(item instanceof LGraphNode)) return;
    item.onSelected?.();
    this.selected_nodes[item.id] = item;
    this.onNodeSelected?.(item);
    if (item.inputs) {
      for (const input of item.inputs) {
        if (input.link == null) continue;
        this.highlighted_links[input.link] = true;
      }
    }
    if (item.outputs) {
      for (const id2 of item.outputs.flatMap((x2) => x2.links)) {
        if (id2 == null) continue;
        this.highlighted_links[id2] = true;
      }
    }
  }
  /**
   * Deselects a {@link Positionable} item.
   * @param item The canvas item to remove from the selection.
   */
  deselect(item) {
    if (!item.selected && !this.selectedItems.has(item)) return;
    item.selected = false;
    this.selectedItems.delete(item);
    if (!(item instanceof LGraphNode)) return;
    item.onDeselected?.();
    delete this.selected_nodes[item.id];
    this.onNodeDeselected?.(item);
    const { graph } = this;
    if (!graph) return;
    if (item.inputs) {
      for (const input of item.inputs) {
        if (input.link == null) continue;
        const node2 = LLink.getOriginNode(graph, input.link);
        if (node2 && this.selectedItems.has(node2)) continue;
        delete this.highlighted_links[input.link];
      }
    }
    if (item.outputs) {
      for (const id2 of item.outputs.flatMap((x2) => x2.links)) {
        if (id2 == null) continue;
        const node2 = LLink.getTargetNode(graph, id2);
        if (node2 && this.selectedItems.has(node2)) continue;
        delete this.highlighted_links[id2];
      }
    }
  }
  /** @deprecated See {@link LGraphCanvas.processSelect} */
  processNodeSelected(item, e2) {
    this.processSelect(
      item,
      e2,
      e2 && (e2.shiftKey || e2.metaKey || e2.ctrlKey || this.multi_select)
    );
  }
  /** @deprecated See {@link LGraphCanvas.select} */
  selectNode(node2, add_to_current_selection) {
    if (node2 == null) {
      this.deselectAll();
    } else {
      this.selectNodes([node2], add_to_current_selection);
    }
  }
  get empty() {
    if (!this.graph) throw new NullGraphError();
    return this.graph.empty;
  }
  get positionableItems() {
    if (!this.graph) throw new NullGraphError();
    return this.graph.positionableItems();
  }
  /**
   * Selects several items.
   * @param items Items to select - if falsy, all items on the canvas will be selected
   * @param add_to_current_selection If set, the items will be added to the current selection instead of replacing it
   */
  selectItems(items, add_to_current_selection) {
    const itemsToSelect = items ?? this.positionableItems;
    if (!add_to_current_selection) this.deselectAll();
    for (const item of itemsToSelect) this.select(item);
    this.onSelectionChange?.(this.selected_nodes);
    this.setDirty(true);
  }
  /**
   * selects several nodes (or adds them to the current selection)
   * @deprecated See {@link LGraphCanvas.selectItems}
   */
  selectNodes(nodes, add_to_current_selection) {
    this.selectItems(nodes, add_to_current_selection);
  }
  /** @deprecated See {@link LGraphCanvas.deselect} */
  deselectNode(node2) {
    this.deselect(node2);
  }
  /**
   * Deselects all items on the canvas.
   * @param keepSelected If set, this item will not be removed from the selection.
   */
  deselectAll(keepSelected) {
    if (!this.graph) return;
    const selected = this.selectedItems;
    if (!selected.size) return;
    let wasSelected;
    for (const sel of selected) {
      if (sel === keepSelected) {
        wasSelected = sel;
        continue;
      }
      sel.onDeselected?.();
      sel.selected = false;
    }
    selected.clear();
    if (wasSelected) selected.add(wasSelected);
    this.setDirty(true);
    const oldNode = keepSelected?.id == null ? null : this.selected_nodes[keepSelected.id];
    this.selected_nodes = {};
    this.current_node = null;
    this.highlighted_links = {};
    if (keepSelected instanceof LGraphNode) {
      if (oldNode) this.selected_nodes[oldNode.id] = oldNode;
      if (keepSelected.inputs) {
        for (const input of keepSelected.inputs) {
          if (input.link == null) continue;
          this.highlighted_links[input.link] = true;
        }
      }
      if (keepSelected.outputs) {
        for (const id2 of keepSelected.outputs.flatMap((x2) => x2.links)) {
          if (id2 == null) continue;
          this.highlighted_links[id2] = true;
        }
      }
    }
    this.onSelectionChange?.(this.selected_nodes);
  }
  /** @deprecated See {@link LGraphCanvas.deselectAll} */
  deselectAllNodes() {
    this.deselectAll();
  }
  /**
   * Deletes all selected items from the graph.
   * @todo Refactor deletion task to LGraph.  Selection is a canvas property, delete is a graph action.
   */
  deleteSelected() {
    const { graph } = this;
    if (!graph) throw new NullGraphError();
    this.emitBeforeChange();
    graph.beforeChange();
    for (const item of this.selectedItems) {
      if (item instanceof LGraphNode) {
        const node2 = item;
        if (node2.block_delete) continue;
        node2.connectInputToOutput();
        graph.remove(node2);
        this.onNodeDeselected?.(node2);
      } else if (item instanceof LGraphGroup) {
        graph.remove(item);
      } else if (item instanceof Reroute) {
        graph.removeReroute(item.id);
      }
    }
    this.selected_nodes = {};
    this.selectedItems.clear();
    this.current_node = null;
    this.highlighted_links = {};
    this.onSelectionChange?.(this.selected_nodes);
    this.setDirty(true);
    graph.afterChange();
    this.emitAfterChange();
  }
  /**
   * deletes all nodes in the current selection from the graph
   * @deprecated See {@link LGraphCanvas.deleteSelected}
   */
  deleteSelectedNodes() {
    this.deleteSelected();
  }
  /**
   * centers the camera on a given node
   */
  centerOnNode(node2) {
    const dpi = window?.devicePixelRatio || 1;
    this.ds.offset[0] = -node2.pos[0] - node2.size[0] * 0.5 + this.canvas.width * 0.5 / (this.ds.scale * dpi);
    this.ds.offset[1] = -node2.pos[1] - node2.size[1] * 0.5 + this.canvas.height * 0.5 / (this.ds.scale * dpi);
    this.setDirty(true, true);
  }
  /**
   * adds some useful properties to a mouse event, like the position in graph coordinates
   */
  adjustMouseEvent(e2) {
    let clientX_rel = e2.clientX;
    let clientY_rel = e2.clientY;
    if (this.canvas) {
      const b2 = this.canvas.getBoundingClientRect();
      clientX_rel -= b2.left;
      clientY_rel -= b2.top;
    }
    e2.safeOffsetX = clientX_rel;
    e2.safeOffsetY = clientY_rel;
    if (e2.deltaX === void 0)
      e2.deltaX = clientX_rel - this.last_mouse_position[0];
    if (e2.deltaY === void 0)
      e2.deltaY = clientY_rel - this.last_mouse_position[1];
    this.last_mouse_position[0] = clientX_rel;
    this.last_mouse_position[1] = clientY_rel;
    e2.canvasX = clientX_rel / this.ds.scale - this.ds.offset[0];
    e2.canvasY = clientY_rel / this.ds.scale - this.ds.offset[1];
  }
  /**
   * changes the zoom level of the graph (default is 1), you can pass also a place used to pivot the zoom
   */
  setZoom(value, zooming_center) {
    this.ds.changeScale(value, zooming_center);
    this.#dirty();
  }
  /**
   * converts a coordinate from graph coordinates to canvas2D coordinates
   */
  convertOffsetToCanvas(pos, out) {
    return this.ds.convertOffsetToCanvas(pos, out);
  }
  /**
   * converts a coordinate from Canvas2D coordinates to graph space
   */
  convertCanvasToOffset(pos, out) {
    return this.ds.convertCanvasToOffset(pos, out);
  }
  // converts event coordinates from canvas2D to graph coordinates
  convertEventToCanvasOffset(e2) {
    const rect = this.canvas.getBoundingClientRect();
    return this.convertCanvasToOffset([
      e2.clientX - rect.left,
      e2.clientY - rect.top
    ]);
  }
  /**
   * brings a node to front (above all other nodes)
   */
  bringToFront(node2) {
    const { graph } = this;
    if (!graph) throw new NullGraphError();
    const i2 = graph._nodes.indexOf(node2);
    if (i2 == -1) return;
    graph._nodes.splice(i2, 1);
    graph._nodes.push(node2);
  }
  /**
   * sends a node to the back (below all other nodes)
   */
  sendToBack(node2) {
    const { graph } = this;
    if (!graph) throw new NullGraphError();
    const i2 = graph._nodes.indexOf(node2);
    if (i2 == -1) return;
    graph._nodes.splice(i2, 1);
    graph._nodes.unshift(node2);
  }
  /**
   * Determines which nodes are visible and populates {@link out} with the results.
   * @param nodes The list of nodes to check - if falsy, all nodes in the graph will be checked
   * @param out Array to write visible nodes into - if falsy, a new array is created instead
   * @returns Array passed ({@link out}), or a new array containing all visible nodes
   */
  computeVisibleNodes(nodes, out) {
    const visible_nodes = out || [];
    visible_nodes.length = 0;
    if (!this.graph) throw new NullGraphError();
    const _nodes = nodes || this.graph._nodes;
    for (const node2 of _nodes) {
      node2.updateArea(this.ctx);
      if (!overlapBounding(this.visible_area, node2.renderArea)) continue;
      visible_nodes.push(node2);
    }
    return visible_nodes;
  }
  /**
   * Checks if a node is visible on the canvas.
   * @param node The node to check
   * @returns `true` if the node is visible, otherwise `false`
   */
  isNodeVisible(node2) {
    return this.#visible_node_ids.has(node2.id);
  }
  /**
   * renders the whole canvas content, by rendering in two separated canvas, one containing the background grid and the connections, and one containing the nodes)
   */
  draw(force_canvas, force_bgcanvas) {
    if (!this.canvas || this.canvas.width == 0 || this.canvas.height == 0) return;
    const now2 = LiteGraph.getTime();
    this.render_time = (now2 - this.last_draw_time) * 1e-3;
    this.last_draw_time = now2;
    if (this.graph) this.ds.computeVisibleArea(this.viewport);
    if (this.dirty_canvas || force_canvas) {
      this.computeVisibleNodes(void 0, this.visible_nodes);
      this.#visible_node_ids = new Set(this.visible_nodes.map((node2) => node2.id));
    }
    if (this.dirty_bgcanvas || force_bgcanvas || this.always_render_background || this.graph?._last_trigger_time && now2 - this.graph._last_trigger_time < 1e3) {
      this.drawBackCanvas();
    }
    if (this.dirty_canvas || force_canvas) this.drawFrontCanvas();
    this.fps = this.render_time ? 1 / this.render_time : 0;
    this.frame++;
  }
  /**
   * draws the front canvas (the one containing all the nodes)
   */
  drawFrontCanvas() {
    this.dirty_canvas = false;
    const { ctx, canvas: canvas2, linkConnector } = this;
    if (ctx.start2D && !this.viewport) {
      ctx.start2D();
      ctx.restore();
      ctx.setTransform(1, 0, 0, 1, 0, 0);
    }
    const area = this.viewport || this.dirty_area;
    if (area) {
      ctx.save();
      ctx.beginPath();
      ctx.rect(area[0], area[1], area[2], area[3]);
      ctx.clip();
    }
    this.#snapToGrid = this.#shiftDown || LiteGraph.alwaysSnapToGrid ? this.graph?.getSnapToGridSize() : void 0;
    if (this.clear_background) {
      if (area) ctx.clearRect(area[0], area[1], area[2], area[3]);
      else ctx.clearRect(0, 0, canvas2.width, canvas2.height);
    }
    if (this.bgcanvas == this.canvas) {
      this.drawBackCanvas();
    } else {
      const scale = window.devicePixelRatio;
      ctx.drawImage(
        this.bgcanvas,
        0,
        0,
        this.bgcanvas.width / scale,
        this.bgcanvas.height / scale
      );
    }
    this.onRender?.(canvas2, ctx);
    if (this.show_info) {
      this.renderInfo(ctx, area ? area[0] : 0, area ? area[1] : 0);
    }
    if (this.graph) {
      ctx.save();
      this.ds.toCanvasContext(ctx);
      const { visible_nodes } = this;
      const drawSnapGuides = this.#snapToGrid && this.isDragging;
      for (const node2 of visible_nodes) {
        ctx.save();
        if (drawSnapGuides && this.selectedItems.has(node2))
          this.drawSnapGuide(ctx, node2);
        ctx.translate(node2.pos[0], node2.pos[1]);
        this.drawNode(node2, ctx);
        ctx.restore();
      }
      if (this.render_execution_order) {
        this.drawExecutionOrder(ctx);
      }
      if (this.graph.config.links_ontop) {
        this.drawConnections(ctx);
      }
      if (linkConnector.isConnecting) {
        const { renderLinks } = linkConnector;
        const highlightPos = this.#getHighlightPosition();
        ctx.lineWidth = this.connections_width;
        for (const renderLink of renderLinks) {
          const { fromSlot, fromPos: pos, fromDirection, dragDirection } = renderLink;
          const connShape = fromSlot.shape;
          const connType = fromSlot.type;
          const colour = connType === LiteGraph.EVENT ? LiteGraph.EVENT_LINK_COLOR : LiteGraph.CONNECTING_LINK_COLOR;
          this.renderLink(
            ctx,
            pos,
            highlightPos,
            null,
            false,
            null,
            colour,
            fromDirection,
            dragDirection
          );
          ctx.beginPath();
          if (connType === LiteGraph.EVENT || connShape === RenderShape.BOX) {
            ctx.rect(pos[0] - 6 + 0.5, pos[1] - 5 + 0.5, 14, 10);
            ctx.rect(
              highlightPos[0] - 6 + 0.5,
              highlightPos[1] - 5 + 0.5,
              14,
              10
            );
          } else if (connShape === RenderShape.ARROW) {
            ctx.moveTo(pos[0] + 8, pos[1] + 0.5);
            ctx.lineTo(pos[0] - 4, pos[1] + 6 + 0.5);
            ctx.lineTo(pos[0] - 4, pos[1] - 6 + 0.5);
            ctx.closePath();
          } else {
            ctx.arc(pos[0], pos[1], 4, 0, Math.PI * 2);
            ctx.arc(highlightPos[0], highlightPos[1], 4, 0, Math.PI * 2);
          }
          ctx.fill();
        }
        this.#renderSnapHighlight(ctx, highlightPos);
      }
      if (this.dragging_rectangle) {
        const { eDown, eMove } = this.pointer;
        ctx.strokeStyle = "#FFF";
        if (eDown && eMove) {
          const transform = ctx.getTransform();
          const ratio = Math.max(1, window.devicePixelRatio);
          ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
          const x2 = eDown.safeOffsetX;
          const y2 = eDown.safeOffsetY;
          ctx.strokeRect(x2, y2, eMove.safeOffsetX - x2, eMove.safeOffsetY - y2);
          ctx.setTransform(transform);
        } else {
          const [x2, y2, w2, h2] = this.dragging_rectangle;
          ctx.strokeRect(x2, y2, w2, h2);
        }
      }
      if (!this.isDragging && this.over_link_center && this.render_link_tooltip) {
        this.drawLinkTooltip(ctx, this.over_link_center);
      } else {
        this.onDrawLinkTooltip?.(ctx, null);
      }
      this.onDrawForeground?.(ctx, this.visible_area);
      ctx.restore();
    }
    this.onDrawOverlay?.(ctx);
    if (area) ctx.restore();
  }
  /** @returns If the pointer is over a link centre marker, the link segment it belongs to.  Otherwise, `undefined`.  */
  #getLinkCentreOnPos(e2) {
    for (const linkSegment of this.renderedPaths) {
      const centre = linkSegment._pos;
      if (!centre) continue;
      if (isInRectangle(e2.canvasX, e2.canvasY, centre[0] - 4, centre[1] - 4, 8, 8)) {
        return linkSegment;
      }
    }
  }
  /** Get the target snap / highlight point in graph space */
  #getHighlightPosition() {
    return LiteGraph.snaps_for_comfy ? this.linkConnector.state.snapLinksPos ?? this._highlight_pos ?? this.graph_mouse : this.graph_mouse;
  }
  /**
   * Renders indicators showing where a link will connect if released.
   * Partial border over target node and a highlight over the slot itself.
   * @param ctx Canvas 2D context
   */
  #renderSnapHighlight(ctx, highlightPos) {
    const linkConnectorSnap = !!this.linkConnector.state.snapLinksPos;
    if (!this._highlight_pos && !linkConnectorSnap) return;
    ctx.fillStyle = "#ffcc00";
    ctx.beginPath();
    const shape = this._highlight_input?.shape;
    if (shape === RenderShape.ARROW) {
      ctx.moveTo(highlightPos[0] + 8, highlightPos[1] + 0.5);
      ctx.lineTo(highlightPos[0] - 4, highlightPos[1] + 6 + 0.5);
      ctx.lineTo(highlightPos[0] - 4, highlightPos[1] - 6 + 0.5);
      ctx.closePath();
    } else {
      ctx.arc(highlightPos[0], highlightPos[1], 6, 0, Math.PI * 2);
    }
    ctx.fill();
    const { linkConnector } = this;
    const { overReroute, overWidget } = linkConnector;
    if (!LiteGraph.snap_highlights_node || !linkConnector.isConnecting || linkConnectorSnap) return;
    overReroute?.drawHighlight(ctx, "#ffcc00aa");
    const node2 = this.node_over;
    if (!node2) return;
    const { strokeStyle, lineWidth } = ctx;
    const area = node2.boundingRect;
    const gap = 3;
    const radius = LiteGraph.ROUND_RADIUS + gap;
    const x2 = area[0] - gap;
    const y2 = area[1] - gap;
    const width2 = area[2] + gap * 2;
    const height = area[3] + gap * 2;
    ctx.beginPath();
    ctx.roundRect(x2, y2, width2, height, radius);
    const start2 = linkConnector.state.connectingTo === "output" ? 0 : 1;
    const inverter = start2 ? -1 : 1;
    const hx = highlightPos[0];
    const hy = highlightPos[1];
    const gRadius = width2 < height ? width2 : width2 * Math.max(height / width2, 0.5);
    const gradient = ctx.createRadialGradient(hx, hy, 0, hx, hy, gRadius);
    gradient.addColorStop(1, "#00000000");
    gradient.addColorStop(0, "#ffcc00aa");
    const linearGradient = ctx.createLinearGradient(x2, y2, x2 + width2, y2);
    linearGradient.addColorStop(0.5, "#00000000");
    linearGradient.addColorStop(start2 + 0.67 * inverter, "#ddeeff33");
    linearGradient.addColorStop(start2 + inverter, "#ffcc0055");
    ctx.setLineDash([radius, radius * 1e-3]);
    ctx.lineWidth = 1;
    ctx.strokeStyle = linearGradient;
    ctx.stroke();
    if (overWidget) {
      const { computedHeight } = overWidget;
      ctx.beginPath();
      const { pos: [nodeX, nodeY] } = node2;
      const height2 = LiteGraph.NODE_WIDGET_HEIGHT;
      if (overWidget.type.startsWith("custom") && computedHeight != null && computedHeight > height2 * 2) {
        ctx.rect(
          nodeX + 9,
          nodeY + overWidget.y + 9,
          (overWidget.width ?? area[2]) - 18,
          computedHeight - 18
        );
      } else {
        ctx.roundRect(
          nodeX + BaseWidget.margin,
          nodeY + overWidget.y,
          overWidget.width ?? area[2],
          height2,
          height2 * 0.5
        );
      }
      ctx.stroke();
    }
    ctx.strokeStyle = gradient;
    ctx.stroke();
    ctx.setLineDash([]);
    ctx.lineWidth = lineWidth;
    ctx.strokeStyle = strokeStyle;
  }
  /**
   * draws some useful stats in the corner of the canvas
   */
  renderInfo(ctx, x2, y2) {
    x2 = x2 || 10;
    y2 = y2 || this.canvas.offsetHeight - 80;
    ctx.save();
    ctx.translate(x2, y2);
    ctx.font = `10px ${LiteGraph.DEFAULT_FONT}`;
    ctx.fillStyle = "#888";
    ctx.textAlign = "left";
    if (this.graph) {
      ctx.fillText(`T: ${this.graph.globaltime.toFixed(2)}s`, 5, 13 * 1);
      ctx.fillText(`I: ${this.graph.iteration}`, 5, 13 * 2);
      ctx.fillText(`N: ${this.graph._nodes.length} [${this.visible_nodes.length}]`, 5, 13 * 3);
      ctx.fillText(`V: ${this.graph._version}`, 5, 13 * 4);
      ctx.fillText(`FPS:${this.fps.toFixed(2)}`, 5, 13 * 5);
    } else {
      ctx.fillText("No graph selected", 5, 13 * 1);
    }
    ctx.restore();
  }
  /**
   * draws the back canvas (the one containing the background and the connections)
   */
  drawBackCanvas() {
    const canvas2 = this.bgcanvas;
    if (canvas2.width != this.canvas.width || canvas2.height != this.canvas.height) {
      canvas2.width = this.canvas.width;
      canvas2.height = this.canvas.height;
    }
    if (!this.bgctx) {
      this.bgctx = this.bgcanvas.getContext("2d");
    }
    const ctx = this.bgctx;
    if (!ctx) throw new TypeError("Background canvas context was null.");
    const viewport = this.viewport || [0, 0, ctx.canvas.width, ctx.canvas.height];
    if (this.clear_background) {
      ctx.clearRect(viewport[0], viewport[1], viewport[2], viewport[3]);
    }
    const bg_already_painted = this.onRenderBackground ? this.onRenderBackground(canvas2, ctx) : false;
    if (!this.viewport) {
      const scale = window.devicePixelRatio;
      ctx.restore();
      ctx.setTransform(scale, 0, 0, scale, 0, 0);
    }
    if (this.graph) {
      ctx.save();
      this.ds.toCanvasContext(ctx);
      if (this.ds.scale < 1.5 && !bg_already_painted && this.clear_background_color) {
        ctx.fillStyle = this.clear_background_color;
        ctx.fillRect(
          this.visible_area[0],
          this.visible_area[1],
          this.visible_area[2],
          this.visible_area[3]
        );
      }
      if (this.background_image && this.ds.scale > 0.5 && !bg_already_painted) {
        if (this.zoom_modify_alpha) {
          ctx.globalAlpha = (1 - 0.5 / this.ds.scale) * this.editor_alpha;
        } else {
          ctx.globalAlpha = this.editor_alpha;
        }
        ctx.imageSmoothingEnabled = false;
        if (!this._bg_img || this._bg_img.name != this.background_image) {
          this._bg_img = new Image();
          this._bg_img.name = this.background_image;
          this._bg_img.src = this.background_image;
          const that = this;
          this._bg_img.addEventListener("load", function() {
            that.draw(true, true);
          });
        }
        let pattern = this._pattern;
        if (pattern == null && this._bg_img.width > 0) {
          pattern = ctx.createPattern(this._bg_img, "repeat") ?? void 0;
          this._pattern_img = this._bg_img;
          this._pattern = pattern;
        }
        if (pattern) {
          ctx.fillStyle = pattern;
          ctx.fillRect(
            this.visible_area[0],
            this.visible_area[1],
            this.visible_area[2],
            this.visible_area[3]
          );
          ctx.fillStyle = "transparent";
        }
        ctx.globalAlpha = 1;
        ctx.imageSmoothingEnabled = true;
      }
      if (this.graph._groups.length) {
        this.drawGroups(canvas2, ctx);
      }
      this.onDrawBackground?.(ctx, this.visible_area);
      if (this.render_canvas_border) {
        ctx.strokeStyle = "#235";
        ctx.strokeRect(0, 0, canvas2.width, canvas2.height);
      }
      if (this.render_connections_shadows) {
        ctx.shadowColor = "#000";
        ctx.shadowOffsetX = 0;
        ctx.shadowOffsetY = 0;
        ctx.shadowBlur = 6;
      } else {
        ctx.shadowColor = "rgba(0,0,0,0)";
      }
      this.drawConnections(ctx);
      ctx.shadowColor = "rgba(0,0,0,0)";
      ctx.restore();
    }
    this.dirty_bgcanvas = false;
    this.dirty_canvas = true;
  }
  /**
   * draws the given node inside the canvas
   */
  drawNode(node2, ctx) {
    this.current_node = node2;
    const color2 = node2.renderingColor;
    const bgcolor = node2.renderingBgColor;
    const { low_quality, editor_alpha } = this;
    ctx.globalAlpha = editor_alpha;
    if (this.render_shadows && !low_quality) {
      ctx.shadowColor = LiteGraph.DEFAULT_SHADOW_COLOR;
      ctx.shadowOffsetX = 2 * this.ds.scale;
      ctx.shadowOffsetY = 2 * this.ds.scale;
      ctx.shadowBlur = 3 * this.ds.scale;
    } else {
      ctx.shadowColor = "transparent";
    }
    if (node2.flags.collapsed && node2.onDrawCollapsed?.(ctx, this) == true)
      return;
    const shape = node2._shape || RenderShape.BOX;
    const size = LGraphCanvas.#temp_vec2;
    size.set(node2.renderingSize);
    if (node2.collapsed) {
      ctx.font = this.inner_text_font;
    }
    if (node2.clip_area) {
      ctx.save();
      ctx.beginPath();
      if (shape == RenderShape.BOX) {
        ctx.rect(0, 0, size[0], size[1]);
      } else if (shape == RenderShape.ROUND) {
        ctx.roundRect(0, 0, size[0], size[1], [10]);
      } else if (shape == RenderShape.CIRCLE) {
        ctx.arc(size[0] * 0.5, size[1] * 0.5, size[0] * 0.5, 0, Math.PI * 2);
      }
      ctx.clip();
    }
    this.drawNodeShape(
      node2,
      ctx,
      size,
      color2,
      bgcolor,
      !!node2.selected
    );
    if (!low_quality) {
      node2.drawBadges(ctx);
    }
    ctx.shadowColor = "transparent";
    ctx.strokeStyle = LiteGraph.NODE_BOX_OUTLINE_COLOR;
    node2.onDrawForeground?.(ctx, this, this.canvas);
    ctx.font = this.inner_text_font;
    node2._setConcreteSlots();
    if (!node2.collapsed) {
      node2.arrange();
      node2.drawSlots(ctx, {
        fromSlot: this.linkConnector.renderLinks[0]?.fromSlot,
        colorContext: this.colourGetter,
        editorAlpha: this.editor_alpha,
        lowQuality: this.low_quality
      });
      ctx.textAlign = "left";
      ctx.globalAlpha = 1;
      this.drawNodeWidgets(node2, null, ctx);
    } else if (this.render_collapsed_slots) {
      node2.drawCollapsedSlots(ctx);
    }
    if (node2.clip_area) {
      ctx.restore();
    }
    ctx.globalAlpha = 1;
  }
  /**
   * Draws the link mouseover effect and tooltip.
   * @param ctx Canvas 2D context to draw on
   * @param link The link to render the mouseover effect for
   * @remarks
   * Called against {@link LGraphCanvas.over_link_center}.
   * @todo Split tooltip from hover, so it can be drawn / eased separately
   */
  drawLinkTooltip(ctx, link2) {
    const pos = link2._pos;
    ctx.fillStyle = "black";
    ctx.beginPath();
    if (this.linkMarkerShape === LinkMarkerShape.Arrow) {
      const transform = ctx.getTransform();
      ctx.translate(pos[0], pos[1]);
      if (Number.isFinite(link2._centreAngle)) ctx.rotate(link2._centreAngle);
      ctx.moveTo(-2, -3);
      ctx.lineTo(4, 0);
      ctx.lineTo(-2, 3);
      ctx.setTransform(transform);
    } else if (this.linkMarkerShape == null || this.linkMarkerShape === LinkMarkerShape.Circle) {
      ctx.arc(pos[0], pos[1], 3, 0, Math.PI * 2);
    }
    ctx.fill();
    const { data } = link2;
    if (data == null) return;
    if (this.onDrawLinkTooltip?.(ctx, link2, this) == true) return;
    let text2 = null;
    if (typeof data === "number")
      text2 = data.toFixed(2);
    else if (typeof data === "string")
      text2 = `"${data}"`;
    else if (typeof data === "boolean")
      text2 = String(data);
    else if (data.toToolTip)
      text2 = data.toToolTip();
    else
      text2 = `[${data.constructor.name}]`;
    if (text2 == null) return;
    text2 = text2.substring(0, 30);
    ctx.font = "14px Courier New";
    const info = ctx.measureText(text2);
    const w2 = info.width + 20;
    const h2 = 24;
    ctx.shadowColor = "black";
    ctx.shadowOffsetX = 2;
    ctx.shadowOffsetY = 2;
    ctx.shadowBlur = 3;
    ctx.fillStyle = "#454";
    ctx.beginPath();
    ctx.roundRect(pos[0] - w2 * 0.5, pos[1] - 15 - h2, w2, h2, [3]);
    ctx.moveTo(pos[0] - 10, pos[1] - 15);
    ctx.lineTo(pos[0] + 10, pos[1] - 15);
    ctx.lineTo(pos[0], pos[1] - 5);
    ctx.fill();
    ctx.shadowColor = "transparent";
    ctx.textAlign = "center";
    ctx.fillStyle = "#CEC";
    ctx.fillText(text2, pos[0], pos[1] - 15 - h2 * 0.3);
  }
  /**
   * Draws the shape of the given node on the canvas
   * @param node The node to draw
   * @param ctx 2D canvas rendering context used to draw
   * @param size Size of the background to draw, in graph units.  Differs from node size if collapsed, etc.
   * @param fgcolor Foreground colour - used for text
   * @param bgcolor Background colour of the node
   * @param _selected Whether to render the node as selected.  Likely to be removed in future, as current usage is simply the selected property of the node.
   */
  drawNodeShape(node2, ctx, size, fgcolor, bgcolor, _selected) {
    ctx.strokeStyle = fgcolor;
    ctx.fillStyle = bgcolor;
    const title_height = LiteGraph.NODE_TITLE_HEIGHT;
    const { low_quality } = this;
    const { collapsed } = node2.flags;
    const shape = node2.renderingShape;
    const { title_mode } = node2;
    const render_title = title_mode == TitleMode.TRANSPARENT_TITLE || title_mode == TitleMode.NO_TITLE ? false : true;
    const area = LGraphCanvas.#tmp_area;
    area.set(node2.boundingRect);
    area[0] -= node2.pos[0];
    area[1] -= node2.pos[1];
    const old_alpha = ctx.globalAlpha;
    ctx.beginPath();
    if (shape == RenderShape.BOX || low_quality) {
      ctx.rect(area[0], area[1], area[2], area[3]);
    } else if (shape == RenderShape.ROUND || shape == RenderShape.CARD) {
      ctx.roundRect(
        area[0],
        area[1],
        area[2],
        area[3],
        shape == RenderShape.CARD ? [LiteGraph.ROUND_RADIUS, LiteGraph.ROUND_RADIUS, 0, 0] : [LiteGraph.ROUND_RADIUS]
      );
    } else if (shape == RenderShape.CIRCLE) {
      ctx.arc(size[0] * 0.5, size[1] * 0.5, size[0] * 0.5, 0, Math.PI * 2);
    }
    ctx.fill();
    if (!collapsed && render_title) {
      ctx.shadowColor = "transparent";
      ctx.fillStyle = "rgba(0,0,0,0.2)";
      ctx.fillRect(0, -1, area[2], 2);
    }
    ctx.shadowColor = "transparent";
    node2.onDrawBackground?.(ctx);
    if (render_title || title_mode == TitleMode.TRANSPARENT_TITLE) {
      node2.drawTitleBarBackground(ctx, {
        scale: this.ds.scale,
        low_quality
      });
      node2.drawTitleBox(ctx, {
        scale: this.ds.scale,
        low_quality,
        box_size: 10
      });
      ctx.globalAlpha = old_alpha;
      node2.drawTitleText(ctx, {
        scale: this.ds.scale,
        default_title_color: this.node_title_color,
        low_quality
      });
      node2.onDrawTitle?.(ctx);
    }
    for (const getStyle of Object.values(node2.strokeStyles)) {
      const strokeStyle = getStyle.call(node2);
      if (strokeStyle) {
        strokeShape(ctx, area, {
          shape,
          title_height,
          title_mode,
          collapsed,
          ...strokeStyle
        });
      }
    }
    node2.drawProgressBar(ctx);
    if (node2.execute_triggered != null && node2.execute_triggered > 0) node2.execute_triggered--;
    if (node2.action_triggered != null && node2.action_triggered > 0) node2.action_triggered--;
  }
  /**
   * Draws a snap guide for a {@link Positionable} item.
   *
   * Initial design was a simple white rectangle representing the location the
   * item would land if dropped.
   * @param ctx The 2D canvas context to draw on
   * @param item The item to draw a snap guide for
   * @param shape The shape of the snap guide to draw
   * @todo Update to align snapping with boundingRect
   * @todo Shapes
   */
  drawSnapGuide(ctx, item, shape = RenderShape.ROUND) {
    const snapGuide = LGraphCanvas.#temp;
    snapGuide.set(item.boundingRect);
    const { pos } = item;
    const offsetX = pos[0] - snapGuide[0];
    const offsetY = pos[1] - snapGuide[1];
    snapGuide[0] += offsetX;
    snapGuide[1] += offsetY;
    if (this.#snapToGrid) snapPoint(snapGuide, this.#snapToGrid);
    snapGuide[0] -= offsetX;
    snapGuide[1] -= offsetY;
    const { globalAlpha } = ctx;
    ctx.globalAlpha = 1;
    ctx.beginPath();
    const [x2, y2, w2, h2] = snapGuide;
    if (shape === RenderShape.CIRCLE) {
      const midX = x2 + w2 * 0.5;
      const midY = y2 + h2 * 0.5;
      const radius = Math.min(w2 * 0.5, h2 * 0.5);
      ctx.arc(midX, midY, radius, 0, Math.PI * 2);
    } else {
      ctx.rect(x2, y2, w2, h2);
    }
    ctx.lineWidth = 0.5;
    ctx.strokeStyle = "#FFFFFF66";
    ctx.fillStyle = "#FFFFFF22";
    ctx.fill();
    ctx.stroke();
    ctx.globalAlpha = globalAlpha;
  }
  drawConnections(ctx) {
    this.renderedPaths.clear();
    if (this.links_render_mode === LinkRenderType.HIDDEN_LINK) return;
    const { graph } = this;
    if (!graph) throw new NullGraphError();
    const visibleReroutes = [];
    const now2 = LiteGraph.getTime();
    const { visible_area } = this;
    LGraphCanvas.#margin_area[0] = visible_area[0] - 20;
    LGraphCanvas.#margin_area[1] = visible_area[1] - 20;
    LGraphCanvas.#margin_area[2] = visible_area[2] + 40;
    LGraphCanvas.#margin_area[3] = visible_area[3] + 40;
    ctx.lineWidth = this.connections_width;
    ctx.fillStyle = "#AAA";
    ctx.strokeStyle = "#AAA";
    ctx.globalAlpha = this.editor_alpha;
    const nodes = graph._nodes;
    for (const node2 of nodes) {
      const { inputs } = node2;
      if (!inputs?.length) continue;
      for (const [i2, input] of inputs.entries()) {
        if (!input || input.link == null) continue;
        const link_id = input.link;
        const link2 = graph._links.get(link_id);
        if (!link2) continue;
        const endPos = node2.getInputPos(i2);
        const start_node = graph.getNodeById(link2.origin_id);
        if (start_node == null) continue;
        const outputId = link2.origin_slot;
        const startPos = outputId === -1 ? [start_node.pos[0] + 10, start_node.pos[1] + 10] : start_node.getOutputPos(outputId);
        const output = start_node.outputs[outputId];
        if (!output) continue;
        this.#renderAllLinkSegments(ctx, link2, startPos, endPos, visibleReroutes, now2, output.dir, input.dir);
      }
    }
    if (graph.floatingLinks.size > 0) {
      this.#renderFloatingLinks(ctx, graph, visibleReroutes, now2);
    }
    const rerouteSet = this.#visibleReroutes;
    rerouteSet.clear();
    visibleReroutes.sort((a2, b2) => a2.linkIds.size - b2.linkIds.size);
    for (const reroute of visibleReroutes) {
      rerouteSet.add(reroute);
      if (this.#snapToGrid && this.isDragging && this.selectedItems.has(reroute)) {
        this.drawSnapGuide(ctx, reroute, RenderShape.CIRCLE);
      }
      reroute.draw(ctx, this._pattern);
      if (!this.pointer.isDown) reroute.drawSlots(ctx);
    }
    ctx.globalAlpha = 1;
  }
  #renderFloatingLinks(ctx, graph, visibleReroutes, now2) {
    const { globalAlpha } = ctx;
    ctx.globalAlpha = globalAlpha * 0.33;
    for (const link2 of graph.floatingLinks.values()) {
      const reroutes = LLink.getReroutes(graph, link2);
      const firstReroute = reroutes[0];
      const reroute = reroutes.at(-1);
      if (!firstReroute || !reroute?.floating) continue;
      if (reroute.floating.slotType === "input") {
        const node2 = graph.getNodeById(link2.target_id);
        if (!node2) continue;
        const startPos = firstReroute.pos;
        const endPos = node2.getInputPos(link2.target_slot);
        const endDirection = node2.inputs[link2.target_slot]?.dir;
        firstReroute._dragging = true;
        this.#renderAllLinkSegments(ctx, link2, startPos, endPos, visibleReroutes, now2, LinkDirection.CENTER, endDirection, true);
      } else {
        const node2 = graph.getNodeById(link2.origin_id);
        if (!node2) continue;
        const startPos = node2.getOutputPos(link2.origin_slot);
        const endPos = reroute.pos;
        const startDirection = node2.outputs[link2.origin_slot]?.dir;
        link2._dragging = true;
        this.#renderAllLinkSegments(ctx, link2, startPos, endPos, visibleReroutes, now2, startDirection, LinkDirection.CENTER, true);
      }
    }
    ctx.globalAlpha = globalAlpha;
  }
  #renderAllLinkSegments(ctx, link2, startPos, endPos, visibleReroutes, now2, startDirection, endDirection, disabled = false) {
    const { graph, renderedPaths } = this;
    if (!graph) return;
    const reroutes = LLink.getReroutes(graph, link2);
    const points = [
      startPos,
      ...reroutes.map((x2) => x2.pos),
      endPos
    ];
    const pointsX = points.map((x2) => x2[0]);
    const pointsY = points.map((x2) => x2[1]);
    LGraphCanvas.#link_bounding[0] = Math.min(...pointsX);
    LGraphCanvas.#link_bounding[1] = Math.min(...pointsY);
    LGraphCanvas.#link_bounding[2] = Math.max(...pointsX) - LGraphCanvas.#link_bounding[0];
    LGraphCanvas.#link_bounding[3] = Math.max(...pointsY) - LGraphCanvas.#link_bounding[1];
    if (!overlapBounding(LGraphCanvas.#link_bounding, LGraphCanvas.#margin_area))
      return;
    const start_dir = startDirection || LinkDirection.RIGHT;
    const end_dir = endDirection || LinkDirection.LEFT;
    if (reroutes.length) {
      let startControl;
      const l2 = reroutes.length;
      for (let j2 = 0; j2 < l2; j2++) {
        const reroute = reroutes[j2];
        if (!renderedPaths.has(reroute)) {
          renderedPaths.add(reroute);
          visibleReroutes.push(reroute);
          reroute._colour = link2.color || LGraphCanvas.link_type_colors[link2.type] || this.default_link_color;
          const prevReroute = graph.getReroute(reroute.parentId);
          const rerouteStartPos = prevReroute?.pos ?? startPos;
          reroute.calculateAngle(this.last_draw_time, graph, rerouteStartPos);
          if (!reroute._dragging) {
            this.renderLink(
              ctx,
              rerouteStartPos,
              reroute.pos,
              link2,
              false,
              0,
              null,
              startControl === void 0 ? start_dir : LinkDirection.CENTER,
              LinkDirection.CENTER,
              {
                startControl,
                endControl: reroute.controlPoint,
                reroute,
                disabled
              }
            );
          }
        }
        if (!startControl && reroutes.at(-1)?.floating?.slotType === "input") {
          startControl = [0, 0];
        } else {
          const nextPos = reroutes[j2 + 1]?.pos ?? endPos;
          const dist3 = Math.min(Reroute.maxSplineOffset, distance(reroute.pos, nextPos) * 0.25);
          startControl = [dist3 * reroute.cos, dist3 * reroute.sin];
        }
      }
      if (link2._dragging) return;
      const segmentStartPos = points.at(-2) ?? startPos;
      this.renderLink(
        ctx,
        segmentStartPos,
        endPos,
        link2,
        false,
        0,
        null,
        LinkDirection.CENTER,
        end_dir,
        { startControl, disabled }
      );
    } else if (!link2._dragging) {
      this.renderLink(
        ctx,
        startPos,
        endPos,
        link2,
        false,
        0,
        null,
        start_dir,
        end_dir
      );
    }
    renderedPaths.add(link2);
    if (link2?._last_time && now2 - link2._last_time < 1e3) {
      const f2 = 2 - (now2 - link2._last_time) * 2e-3;
      const tmp = ctx.globalAlpha;
      ctx.globalAlpha = tmp * f2;
      this.renderLink(
        ctx,
        startPos,
        endPos,
        link2,
        true,
        f2,
        "white",
        start_dir,
        end_dir
      );
      ctx.globalAlpha = tmp;
    }
  }
  /**
   * draws a link between two points
   * @param ctx Canvas 2D rendering context
   * @param a start pos
   * @param b end pos
   * @param link the link object with all the link info
   * @param skip_border ignore the shadow of the link
   * @param flow show flow animation (for events)
   * @param color the color for the link
   * @param start_dir the direction enum
   * @param end_dir the direction enum
   */
  renderLink(ctx, a2, b2, link2, skip_border, flow, color2, start_dir, end_dir, {
    startControl,
    endControl,
    reroute,
    num_sublines = 1,
    disabled = false
  } = {}) {
    const linkColour = link2 != null && this.highlighted_links[link2.id] ? "#FFF" : color2 || link2?.color || link2?.type != null && LGraphCanvas.link_type_colors[link2.type] || this.default_link_color;
    const startDir = start_dir || LinkDirection.RIGHT;
    const endDir = end_dir || LinkDirection.LEFT;
    const dist3 = this.links_render_mode == LinkRenderType.SPLINE_LINK && (!endControl || !startControl) ? distance(a2, b2) : 0;
    if (this.render_connections_border && !this.low_quality) {
      ctx.lineWidth = this.connections_width + 4;
    }
    ctx.lineJoin = "round";
    num_sublines ||= 1;
    if (num_sublines > 1) ctx.lineWidth = 0.5;
    const path = new Path2D();
    const linkSegment = reroute ?? link2;
    if (linkSegment) linkSegment.path = path;
    const innerA = LGraphCanvas.#lTempA;
    const innerB = LGraphCanvas.#lTempB;
    const pos = linkSegment?._pos ?? [0, 0];
    for (let i2 = 0; i2 < num_sublines; i2++) {
      const offsety = (i2 - (num_sublines - 1) * 0.5) * 5;
      innerA[0] = a2[0];
      innerA[1] = a2[1];
      innerB[0] = b2[0];
      innerB[1] = b2[1];
      if (this.links_render_mode == LinkRenderType.SPLINE_LINK) {
        if (endControl) {
          innerB[0] = b2[0] + endControl[0];
          innerB[1] = b2[1] + endControl[1];
        } else {
          this.#addSplineOffset(innerB, endDir, dist3);
        }
        if (startControl) {
          innerA[0] = a2[0] + startControl[0];
          innerA[1] = a2[1] + startControl[1];
        } else {
          this.#addSplineOffset(innerA, startDir, dist3);
        }
        path.moveTo(a2[0], a2[1] + offsety);
        path.bezierCurveTo(
          innerA[0],
          innerA[1] + offsety,
          innerB[0],
          innerB[1] + offsety,
          b2[0],
          b2[1] + offsety
        );
        findPointOnCurve(pos, a2, b2, innerA, innerB, 0.5);
        if (linkSegment && this.linkMarkerShape === LinkMarkerShape.Arrow) {
          const justPastCentre = LGraphCanvas.#lTempC;
          findPointOnCurve(justPastCentre, a2, b2, innerA, innerB, 0.51);
          linkSegment._centreAngle = Math.atan2(
            justPastCentre[1] - pos[1],
            justPastCentre[0] - pos[0]
          );
        }
      } else {
        const l2 = this.links_render_mode == LinkRenderType.LINEAR_LINK ? 15 : 10;
        switch (startDir) {
          case LinkDirection.LEFT:
            innerA[0] += -l2;
            break;
          case LinkDirection.RIGHT:
            innerA[0] += l2;
            break;
          case LinkDirection.UP:
            innerA[1] += -l2;
            break;
          case LinkDirection.DOWN:
            innerA[1] += l2;
            break;
        }
        switch (endDir) {
          case LinkDirection.LEFT:
            innerB[0] += -l2;
            break;
          case LinkDirection.RIGHT:
            innerB[0] += l2;
            break;
          case LinkDirection.UP:
            innerB[1] += -l2;
            break;
          case LinkDirection.DOWN:
            innerB[1] += l2;
            break;
        }
        if (this.links_render_mode == LinkRenderType.LINEAR_LINK) {
          path.moveTo(a2[0], a2[1] + offsety);
          path.lineTo(innerA[0], innerA[1] + offsety);
          path.lineTo(innerB[0], innerB[1] + offsety);
          path.lineTo(b2[0], b2[1] + offsety);
          pos[0] = (innerA[0] + innerB[0]) * 0.5;
          pos[1] = (innerA[1] + innerB[1]) * 0.5;
          if (linkSegment && this.linkMarkerShape === LinkMarkerShape.Arrow) {
            linkSegment._centreAngle = Math.atan2(
              innerB[1] - innerA[1],
              innerB[0] - innerA[0]
            );
          }
        } else if (this.links_render_mode == LinkRenderType.STRAIGHT_LINK) {
          const midX = (innerA[0] + innerB[0]) * 0.5;
          path.moveTo(a2[0], a2[1]);
          path.lineTo(innerA[0], innerA[1]);
          path.lineTo(midX, innerA[1]);
          path.lineTo(midX, innerB[1]);
          path.lineTo(innerB[0], innerB[1]);
          path.lineTo(b2[0], b2[1]);
          pos[0] = midX;
          pos[1] = (innerA[1] + innerB[1]) * 0.5;
          if (linkSegment && this.linkMarkerShape === LinkMarkerShape.Arrow) {
            const diff2 = innerB[1] - innerA[1];
            if (Math.abs(diff2) < 4) linkSegment._centreAngle = 0;
            else if (diff2 > 0) linkSegment._centreAngle = Math.PI * 0.5;
            else linkSegment._centreAngle = -(Math.PI * 0.5);
          }
        } else {
          return;
        }
      }
    }
    if (this.render_connections_border && !this.low_quality && !skip_border) {
      ctx.strokeStyle = "rgba(0,0,0,0.5)";
      ctx.stroke(path);
    }
    ctx.lineWidth = this.connections_width;
    ctx.fillStyle = ctx.strokeStyle = linkColour;
    ctx.stroke(path);
    if (this.ds.scale >= 0.6 && this.highquality_render && linkSegment) {
      if (this.render_connection_arrows) {
        const posA = this.computeConnectionPoint(a2, b2, 0.25, startDir, endDir);
        const posB = this.computeConnectionPoint(a2, b2, 0.26, startDir, endDir);
        const posC = this.computeConnectionPoint(a2, b2, 0.75, startDir, endDir);
        const posD = this.computeConnectionPoint(a2, b2, 0.76, startDir, endDir);
        let angleA = 0;
        let angleB = 0;
        if (this.render_curved_connections) {
          angleA = -Math.atan2(posB[0] - posA[0], posB[1] - posA[1]);
          angleB = -Math.atan2(posD[0] - posC[0], posD[1] - posC[1]);
        } else {
          angleB = angleA = b2[1] > a2[1] ? 0 : Math.PI;
        }
        const transform = ctx.getTransform();
        ctx.translate(posA[0], posA[1]);
        ctx.rotate(angleA);
        ctx.beginPath();
        ctx.moveTo(-5, -3);
        ctx.lineTo(0, 7);
        ctx.lineTo(5, -3);
        ctx.fill();
        ctx.setTransform(transform);
        ctx.translate(posC[0], posC[1]);
        ctx.rotate(angleB);
        ctx.beginPath();
        ctx.moveTo(-5, -3);
        ctx.lineTo(0, 7);
        ctx.lineTo(5, -3);
        ctx.fill();
        ctx.setTransform(transform);
      }
      ctx.beginPath();
      if (this.linkMarkerShape === LinkMarkerShape.Arrow) {
        const transform = ctx.getTransform();
        ctx.translate(pos[0], pos[1]);
        if (linkSegment._centreAngle) ctx.rotate(linkSegment._centreAngle);
        ctx.moveTo(-3.2, -5);
        ctx.lineTo(7, 0);
        ctx.lineTo(-3.2, 5);
        ctx.setTransform(transform);
      } else if (this.linkMarkerShape == null || this.linkMarkerShape === LinkMarkerShape.Circle) {
        ctx.arc(pos[0], pos[1], 5, 0, Math.PI * 2);
      }
      if (disabled) {
        const { fillStyle, globalAlpha } = ctx;
        ctx.fillStyle = this._pattern ?? "#797979";
        ctx.globalAlpha = 0.75;
        ctx.fill();
        ctx.globalAlpha = globalAlpha;
        ctx.fillStyle = fillStyle;
      }
      ctx.fill();
    }
    if (flow) {
      ctx.fillStyle = linkColour;
      for (let i2 = 0; i2 < 5; ++i2) {
        const f2 = (LiteGraph.getTime() * 1e-3 + i2 * 0.2) % 1;
        const flowPos = this.computeConnectionPoint(a2, b2, f2, startDir, endDir);
        ctx.beginPath();
        ctx.arc(flowPos[0], flowPos[1], 5, 0, 2 * Math.PI);
        ctx.fill();
      }
    }
  }
  /**
   * Finds a point along a spline represented by a to b, with spline endpoint directions dictacted by start_dir and end_dir.
   * @param a Start point
   * @param b End point
   * @param t Time: distance between points (e.g 0.25 is 25% along the line)
   * @param start_dir Spline start direction
   * @param end_dir Spline end direction
   * @returns The point at {@link t} distance along the spline a-b.
   */
  computeConnectionPoint(a2, b2, t2, start_dir, end_dir) {
    start_dir ||= LinkDirection.RIGHT;
    end_dir ||= LinkDirection.LEFT;
    const dist3 = distance(a2, b2);
    const pa = [a2[0], a2[1]];
    const pb = [b2[0], b2[1]];
    this.#addSplineOffset(pa, start_dir, dist3);
    this.#addSplineOffset(pb, end_dir, dist3);
    const c1 = (1 - t2) * (1 - t2) * (1 - t2);
    const c2 = 3 * ((1 - t2) * (1 - t2)) * t2;
    const c3 = 3 * (1 - t2) * (t2 * t2);
    const c4 = t2 * t2 * t2;
    const x2 = c1 * a2[0] + c2 * pa[0] + c3 * pb[0] + c4 * b2[0];
    const y2 = c1 * a2[1] + c2 * pa[1] + c3 * pb[1] + c4 * b2[1];
    return [x2, y2];
  }
  /**
   * Modifies an existing point, adding a single-axis offset.
   * @param point The point to add the offset to
   * @param direction The direction to add the offset in
   * @param dist Distance to offset
   * @param factor Distance is mulitplied by this value.  Default: 0.25
   */
  #addSplineOffset(point, direction, dist3, factor = 0.25) {
    switch (direction) {
      case LinkDirection.LEFT:
        point[0] += dist3 * -factor;
        break;
      case LinkDirection.RIGHT:
        point[0] += dist3 * factor;
        break;
      case LinkDirection.UP:
        point[1] += dist3 * -factor;
        break;
      case LinkDirection.DOWN:
        point[1] += dist3 * factor;
        break;
    }
  }
  drawExecutionOrder(ctx) {
    ctx.shadowColor = "transparent";
    ctx.globalAlpha = 0.25;
    ctx.textAlign = "center";
    ctx.strokeStyle = "white";
    ctx.globalAlpha = 0.75;
    const { visible_nodes } = this;
    for (const node2 of visible_nodes) {
      ctx.fillStyle = "black";
      ctx.fillRect(
        node2.pos[0] - LiteGraph.NODE_TITLE_HEIGHT,
        node2.pos[1] - LiteGraph.NODE_TITLE_HEIGHT,
        LiteGraph.NODE_TITLE_HEIGHT,
        LiteGraph.NODE_TITLE_HEIGHT
      );
      if (node2.order == 0) {
        ctx.strokeRect(
          node2.pos[0] - LiteGraph.NODE_TITLE_HEIGHT + 0.5,
          node2.pos[1] - LiteGraph.NODE_TITLE_HEIGHT + 0.5,
          LiteGraph.NODE_TITLE_HEIGHT,
          LiteGraph.NODE_TITLE_HEIGHT
        );
      }
      ctx.fillStyle = "#FFF";
      ctx.fillText(
        stringOrEmpty(node2.order),
        node2.pos[0] + LiteGraph.NODE_TITLE_HEIGHT * -0.5,
        node2.pos[1] - 6
      );
    }
    ctx.globalAlpha = 1;
  }
  /**
   * draws the widgets stored inside a node
   * @deprecated Use {@link LGraphNode.drawWidgets} instead.
   * @remarks Currently there are extensions hijacking this function, so we cannot remove it.
   */
  drawNodeWidgets(node2, _posY, ctx) {
    node2.drawWidgets(ctx, {
      lowQuality: this.low_quality,
      editorAlpha: this.editor_alpha
    });
  }
  /**
   * draws every group area in the background
   */
  drawGroups(canvas2, ctx) {
    if (!this.graph) return;
    const groups = this.graph._groups;
    ctx.save();
    ctx.globalAlpha = 0.5 * this.editor_alpha;
    const drawSnapGuides = this.#snapToGrid && this.isDragging;
    for (const group of groups) {
      if (!overlapBounding(this.visible_area, group._bounding)) {
        continue;
      }
      if (drawSnapGuides && this.selectedItems.has(group))
        this.drawSnapGuide(ctx, group);
      group.draw(this, ctx);
    }
    ctx.restore();
  }
  /**
   * resizes the canvas to a given size, if no size is passed, then it tries to fill the parentNode
   * @todo Remove or rewrite
   */
  resize(width2, height) {
    if (!width2 && !height) {
      const parent2 = this.canvas.parentElement;
      if (!parent2) throw new TypeError("Attempted to resize canvas, but parent element was null.");
      width2 = parent2.offsetWidth;
      height = parent2.offsetHeight;
    }
    if (this.canvas.width == width2 && this.canvas.height == height) return;
    this.canvas.width = width2 ?? 0;
    this.canvas.height = height ?? 0;
    this.bgcanvas.width = this.canvas.width;
    this.bgcanvas.height = this.canvas.height;
    this.setDirty(true, true);
  }
  onNodeSelectionChange() {
  }
  /**
   * Determines the furthest nodes in each direction for the currently selected nodes
   */
  boundaryNodesForSelection() {
    return LGraphCanvas.getBoundaryNodes(this.selected_nodes);
  }
  showLinkMenu(segment, e2) {
    const { graph } = this;
    if (!graph) throw new NullGraphError();
    const title = "data" in segment && segment.data != null ? segment.data.constructor.name : void 0;
    const { origin_id, origin_slot } = segment;
    if (origin_id == null || origin_slot == null) {
      new LiteGraph.ContextMenu(["Link has no origin"], {
        event: e2,
        title
      });
      return false;
    }
    const node_left = graph.getNodeById(origin_id);
    const fromType = node_left?.outputs?.[origin_slot]?.type;
    const options2 = ["Add Node", "Add Reroute", null, "Delete", null];
    const menu2 = new LiteGraph.ContextMenu(options2, {
      event: e2,
      title,
      callback: inner_clicked.bind(this)
    });
    return false;
    function inner_clicked(v2, options22, e22) {
      if (!graph) throw new NullGraphError();
      switch (v2) {
        case "Add Node":
          LGraphCanvas.onMenuAdd(null, null, e22, menu2, (node2) => {
            if (!node2?.inputs?.length || !node2?.outputs?.length || origin_slot == null) return;
            const options3 = { afterRerouteId: segment.parentId };
            if (node_left?.connectByType(origin_slot, node2, fromType ?? "*", options3)) {
              node2.pos[0] -= node2.size[0] * 0.5;
            }
          });
          break;
        case "Add Reroute": {
          try {
            this.emitBeforeChange();
            this.adjustMouseEvent(e22);
            graph.createReroute(segment._pos, segment);
            this.setDirty(false, true);
          } catch (error2) {
            console.error(error2);
          } finally {
            this.emitAfterChange();
          }
          break;
        }
        case "Delete":
          graph.removeLink(segment.id);
          break;
      }
    }
    __name(inner_clicked, "inner_clicked");
  }
  createDefaultNodeForSlot(optPass) {
    const opts = Object.assign({
      nodeFrom: null,
      slotFrom: null,
      nodeTo: null,
      slotTo: null,
      position: [0, 0],
      nodeType: void 0,
      posAdd: [0, 0],
      posSizeFix: [0, 0]
    }, optPass);
    const { afterRerouteId } = opts;
    const isFrom = opts.nodeFrom && opts.slotFrom !== null;
    const isTo = !isFrom && opts.nodeTo && opts.slotTo !== null;
    if (!isFrom && !isTo) {
      console.warn(`No data passed to createDefaultNodeForSlot`, opts.nodeFrom, opts.slotFrom, opts.nodeTo, opts.slotTo);
      return false;
    }
    if (!opts.nodeType) {
      console.warn("No type to createDefaultNodeForSlot");
      return false;
    }
    const nodeX = isFrom ? opts.nodeFrom : opts.nodeTo;
    if (!nodeX) throw new TypeError("nodeX was null when creating default node for slot.");
    let slotX = isFrom ? opts.slotFrom : opts.slotTo;
    let iSlotConn = false;
    switch (typeof slotX) {
      case "string":
        iSlotConn = isFrom ? nodeX.findOutputSlot(slotX, false) : nodeX.findInputSlot(slotX, false);
        slotX = isFrom ? nodeX.outputs[slotX] : nodeX.inputs[slotX];
        break;
      case "object":
        if (slotX === null) {
          console.warn("Cant get slot information", slotX);
          return false;
        }
        iSlotConn = isFrom ? nodeX.findOutputSlot(slotX.name) : nodeX.findInputSlot(slotX.name);
        break;
      case "number":
        iSlotConn = slotX;
        slotX = isFrom ? nodeX.outputs[slotX] : nodeX.inputs[slotX];
        break;
      case "undefined":
      default:
        console.warn("Cant get slot information", slotX);
        return false;
    }
    const fromSlotType = slotX.type == LiteGraph.EVENT ? "_event_" : slotX.type;
    const slotTypesDefault = isFrom ? LiteGraph.slot_types_default_out : LiteGraph.slot_types_default_in;
    if (slotTypesDefault?.[fromSlotType]) {
      let nodeNewType = false;
      if (typeof slotTypesDefault[fromSlotType] == "object") {
        for (const typeX in slotTypesDefault[fromSlotType]) {
          if (opts.nodeType == slotTypesDefault[fromSlotType][typeX] || opts.nodeType == "AUTO") {
            nodeNewType = slotTypesDefault[fromSlotType][typeX];
            break;
          }
        }
      } else if (opts.nodeType == slotTypesDefault[fromSlotType] || opts.nodeType == "AUTO") {
        nodeNewType = slotTypesDefault[fromSlotType];
      }
      if (nodeNewType) {
        let nodeNewOpts = false;
        if (typeof nodeNewType == "object" && nodeNewType.node) {
          nodeNewOpts = nodeNewType;
          nodeNewType = nodeNewType.node;
        }
        const newNode = LiteGraph.createNode(nodeNewType);
        if (newNode) {
          if (nodeNewOpts) {
            if (nodeNewOpts.properties) {
              for (const i2 in nodeNewOpts.properties) {
                newNode.addProperty(i2, nodeNewOpts.properties[i2]);
              }
            }
            if (nodeNewOpts.inputs) {
              newNode.inputs = [];
              for (const i2 in nodeNewOpts.inputs) {
                newNode.addOutput(
                  nodeNewOpts.inputs[i2][0],
                  nodeNewOpts.inputs[i2][1]
                );
              }
            }
            if (nodeNewOpts.outputs) {
              newNode.outputs = [];
              for (const i2 in nodeNewOpts.outputs) {
                newNode.addOutput(
                  nodeNewOpts.outputs[i2][0],
                  nodeNewOpts.outputs[i2][1]
                );
              }
            }
            if (nodeNewOpts.title) {
              newNode.title = nodeNewOpts.title;
            }
            if (nodeNewOpts.json) {
              newNode.configure(nodeNewOpts.json);
            }
          }
          if (!this.graph) throw new NullGraphError();
          this.graph.add(newNode);
          newNode.pos = [
            opts.position[0] + opts.posAdd[0] + (opts.posSizeFix[0] ? opts.posSizeFix[0] * newNode.size[0] : 0),
            opts.position[1] + opts.posAdd[1] + (opts.posSizeFix[1] ? opts.posSizeFix[1] * newNode.size[1] : 0)
          ];
          const detail = { node: newNode, opts };
          const mayConnectLinks = this.canvas.dispatchEvent(new CustomEvent("connect-new-default-node", { detail, cancelable: true }));
          if (!mayConnectLinks) return true;
          if (isFrom) {
            if (!opts.nodeFrom) throw new TypeError("createDefaultNodeForSlot - nodeFrom was null");
            opts.nodeFrom.connectByType(iSlotConn, newNode, fromSlotType, { afterRerouteId });
          } else {
            if (!opts.nodeTo) throw new TypeError("createDefaultNodeForSlot - nodeTo was null");
            opts.nodeTo.connectByTypeOutput(iSlotConn, newNode, fromSlotType, { afterRerouteId });
          }
          return true;
        }
        console.log(`failed creating ${nodeNewType}`);
      }
    }
    return false;
  }
  showConnectionMenu(optPass) {
    const opts = Object.assign({
      nodeFrom: null,
      slotFrom: null,
      nodeTo: null,
      slotTo: null,
      e: void 0,
      allow_searchbox: this.allow_searchbox,
      showSearchBox: this.showSearchBox
    }, optPass || {});
    const dirty = /* @__PURE__ */ __name(() => this.#dirty(), "dirty");
    const that = this;
    const { graph } = this;
    const { afterRerouteId } = opts;
    const isFrom = opts.nodeFrom && opts.slotFrom;
    const isTo = !isFrom && opts.nodeTo && opts.slotTo;
    if (!isFrom && !isTo) {
      console.warn("No data passed to showConnectionMenu");
      return;
    }
    const nodeX = isFrom ? opts.nodeFrom : opts.nodeTo;
    if (!nodeX) throw new TypeError("nodeX was null when creating default node for slot.");
    let slotX = isFrom ? opts.slotFrom : opts.slotTo;
    let iSlotConn;
    switch (typeof slotX) {
      case "string":
        iSlotConn = isFrom ? nodeX.findOutputSlot(slotX, false) : nodeX.findInputSlot(slotX, false);
        slotX = isFrom ? nodeX.outputs[slotX] : nodeX.inputs[slotX];
        break;
      case "object":
        if (slotX === null) {
          console.warn("Cant get slot information", slotX);
          return;
        }
        iSlotConn = isFrom ? nodeX.findOutputSlot(slotX.name) : nodeX.findInputSlot(slotX.name);
        break;
      case "number":
        iSlotConn = slotX;
        slotX = isFrom ? nodeX.outputs[slotX] : nodeX.inputs[slotX];
        break;
      default:
        console.warn("Cant get slot information", slotX);
        return;
    }
    const options2 = ["Add Node", "Add Reroute", null];
    if (opts.allow_searchbox) {
      options2.push("Search", null);
    }
    const fromSlotType = slotX.type == LiteGraph.EVENT ? "_event_" : slotX.type;
    const slotTypesDefault = isFrom ? LiteGraph.slot_types_default_out : LiteGraph.slot_types_default_in;
    if (slotTypesDefault?.[fromSlotType]) {
      if (typeof slotTypesDefault[fromSlotType] == "object") {
        for (const typeX in slotTypesDefault[fromSlotType]) {
          options2.push(slotTypesDefault[fromSlotType][typeX]);
        }
      } else {
        options2.push(slotTypesDefault[fromSlotType]);
      }
    }
    const menu2 = new LiteGraph.ContextMenu(options2, {
      event: opts.e,
      extra: slotX,
      title: (slotX && slotX.name != "" ? slotX.name + (fromSlotType ? " | " : "") : "") + (slotX && fromSlotType ? fromSlotType : ""),
      callback: inner_clicked
    });
    return menu2;
    function inner_clicked(v2, options22, e2) {
      switch (v2) {
        case "Add Node":
          LGraphCanvas.onMenuAdd(null, null, e2, menu2, function(node2) {
            if (!node2) return;
            if (isFrom) {
              opts.nodeFrom?.connectByType(iSlotConn, node2, fromSlotType, { afterRerouteId });
            } else {
              opts.nodeTo?.connectByTypeOutput(iSlotConn, node2, fromSlotType, { afterRerouteId });
            }
          });
          break;
        case "Add Reroute": {
          const node2 = isFrom ? opts.nodeFrom : opts.nodeTo;
          const slot = options22.extra;
          if (!graph) throw new NullGraphError();
          if (!node2) throw new TypeError("Cannot add reroute: node was null");
          if (!slot) throw new TypeError("Cannot add reroute: slot was null");
          if (!opts.e) throw new TypeError("Cannot add reroute: CanvasPointerEvent was null");
          const reroute = node2.connectFloatingReroute([opts.e.canvasX, opts.e.canvasY], slot, afterRerouteId);
          if (!reroute) throw new Error("Failed to create reroute");
          dirty();
          break;
        }
        case "Search":
          if (isFrom) {
            opts.showSearchBox(e2, { node_from: opts.nodeFrom, slot_from: slotX, type_filter_in: fromSlotType });
          } else {
            opts.showSearchBox(e2, { node_to: opts.nodeTo, slot_from: slotX, type_filter_out: fromSlotType });
          }
          break;
        default: {
          const customProps = {
            position: [opts.e?.canvasX ?? 0, opts.e?.canvasY ?? 0],
            nodeType: v2,
            afterRerouteId
          };
          const options3 = Object.assign(opts, customProps);
          that.createDefaultNodeForSlot(options3);
          break;
        }
      }
    }
    __name(inner_clicked, "inner_clicked");
  }
  // refactor: there are different dialogs, some uses createDialog some dont
  prompt(title, value, callback, event, multiline) {
    const that = this;
    title = title || "";
    const customProperties = {
      is_modified: false,
      className: "graphdialog rounded",
      innerHTML: multiline ? "<span class='name'></span> <textarea autofocus class='value'></textarea><button class='rounded'>OK</button>" : "<span class='name'></span> <input autofocus type='text' class='value'/><button class='rounded'>OK</button>",
      close() {
        that.prompt_box = null;
        if (dialog.parentNode) {
          dialog.remove();
        }
      }
    };
    const div = document.createElement("div");
    const dialog = Object.assign(div, customProperties);
    const graphcanvas = LGraphCanvas.active_canvas;
    const { canvas: canvas2 } = graphcanvas;
    if (!canvas2.parentNode) throw new TypeError("canvas element parentNode was null when opening a prompt.");
    canvas2.parentNode.append(dialog);
    if (this.ds.scale > 1) dialog.style.transform = `scale(${this.ds.scale})`;
    let dialogCloseTimer;
    let prevent_timeout = 0;
    LiteGraph.pointerListenerAdd(dialog, "leave", function() {
      if (prevent_timeout) return;
      if (LiteGraph.dialog_close_on_mouse_leave) {
        if (!dialog.is_modified && LiteGraph.dialog_close_on_mouse_leave) {
          dialogCloseTimer = setTimeout(
            dialog.close,
            LiteGraph.dialog_close_on_mouse_leave_delay
          );
        }
      }
    });
    LiteGraph.pointerListenerAdd(dialog, "enter", function() {
      if (LiteGraph.dialog_close_on_mouse_leave && dialogCloseTimer)
        clearTimeout(dialogCloseTimer);
    });
    const selInDia = dialog.querySelectorAll("select");
    if (selInDia) {
      for (const selIn of selInDia) {
        selIn.addEventListener("click", function() {
          prevent_timeout++;
        });
        selIn.addEventListener("blur", function() {
          prevent_timeout = 0;
        });
        selIn.addEventListener("change", function() {
          prevent_timeout = -1;
        });
      }
    }
    this.prompt_box?.close();
    this.prompt_box = dialog;
    const name_element = dialog.querySelector(".name");
    if (!name_element) throw new TypeError("name_element was null");
    name_element.textContent = title;
    const value_element = dialog.querySelector(".value");
    if (!value_element) throw new TypeError("value_element was null");
    value_element.value = value;
    value_element.select();
    const input = value_element;
    input.addEventListener("keydown", function(e2) {
      dialog.is_modified = true;
      if (e2.key == "Escape") {
        dialog.close();
      } else if (e2.key == "Enter" && e2.target.localName != "textarea") {
        if (callback) {
          callback(this.value);
        }
        dialog.close();
      } else {
        return;
      }
      e2.preventDefault();
      e2.stopPropagation();
    });
    const button = dialog.querySelector("button");
    if (!button) throw new TypeError("button was null when opening prompt");
    button.addEventListener("click", function() {
      callback?.(input.value);
      that.setDirty(true);
      dialog.close();
    });
    const rect = canvas2.getBoundingClientRect();
    let offsetx = -20;
    let offsety = -20;
    if (rect) {
      offsetx -= rect.left;
      offsety -= rect.top;
    }
    if (event) {
      dialog.style.left = `${event.clientX + offsetx}px`;
      dialog.style.top = `${event.clientY + offsety}px`;
    } else {
      dialog.style.left = `${canvas2.width * 0.5 + offsetx}px`;
      dialog.style.top = `${canvas2.height * 0.5 + offsety}px`;
    }
    setTimeout(function() {
      input.focus();
      const clickTime = Date.now();
      function handleOutsideClick(e2) {
        if (e2.target === canvas2 && Date.now() - clickTime > 256) {
          dialog.close();
          canvas2.parentElement?.removeEventListener("click", handleOutsideClick);
          canvas2.parentElement?.removeEventListener("touchend", handleOutsideClick);
        }
      }
      __name(handleOutsideClick, "handleOutsideClick");
      canvas2.parentElement?.addEventListener("click", handleOutsideClick);
      canvas2.parentElement?.addEventListener("touchend", handleOutsideClick);
    }, 10);
    return dialog;
  }
  showSearchBox(event, searchOptions) {
    const options2 = {
      slot_from: null,
      node_from: null,
      node_to: null,
      // TODO check for registered_slot_[in/out]_types not empty
      // this will be checked for functionality enabled : filter on slot type, in and out
      do_type_filter: LiteGraph.search_filter_enabled,
      // these are default: pass to set initially set values
      // @ts-expect-error
      type_filter_in: false,
      type_filter_out: false,
      show_general_if_none_on_typefilter: true,
      show_general_after_typefiltered: true,
      hide_on_mouse_leave: LiteGraph.search_hide_on_mouse_leave,
      show_all_if_empty: true,
      show_all_on_open: LiteGraph.search_show_all_on_open
    };
    Object.assign(options2, searchOptions);
    const that = this;
    const graphcanvas = LGraphCanvas.active_canvas;
    const { canvas: canvas2 } = graphcanvas;
    const root_document = canvas2.ownerDocument || document;
    const div = document.createElement("div");
    const dialog = Object.assign(div, {
      close() {
        that.search_box = void 0;
        this.blur();
        canvas2.focus();
        root_document.body.style.overflow = "";
        setTimeout(() => canvas2.focus(), 20);
        dialog.remove();
      }
    });
    dialog.className = "litegraph litesearchbox graphdialog rounded";
    dialog.innerHTML = "<span class='name'>Search</span> <input autofocus type='text' class='value rounded'/>";
    if (options2.do_type_filter) {
      dialog.innerHTML += "<select class='slot_in_type_filter'><option value=''></option></select>";
      dialog.innerHTML += "<select class='slot_out_type_filter'><option value=''></option></select>";
    }
    const helper = document.createElement("div");
    helper.className = "helper";
    dialog.append(helper);
    if (root_document.fullscreenElement) {
      root_document.fullscreenElement.append(dialog);
    } else {
      root_document.body.append(dialog);
      root_document.body.style.overflow = "hidden";
    }
    let selIn;
    let selOut;
    if (options2.do_type_filter) {
      selIn = dialog.querySelector(".slot_in_type_filter");
      selOut = dialog.querySelector(".slot_out_type_filter");
    }
    if (this.ds.scale > 1) {
      dialog.style.transform = `scale(${this.ds.scale})`;
    }
    if (options2.hide_on_mouse_leave) {
      let prevent_timeout = false;
      let timeout_close = null;
      LiteGraph.pointerListenerAdd(dialog, "enter", function() {
        if (timeout_close) {
          clearTimeout(timeout_close);
          timeout_close = null;
        }
      });
      dialog.addEventListener("pointerleave", function() {
        if (prevent_timeout) return;
        const hideDelay = options2.hide_on_mouse_leave;
        const delay = typeof hideDelay === "number" ? hideDelay : 500;
        timeout_close = setTimeout(dialog.close, delay);
      });
      if (options2.do_type_filter) {
        if (!selIn) throw new TypeError("selIn was null when showing search box");
        if (!selOut) throw new TypeError("selOut was null when showing search box");
        selIn.addEventListener("click", function() {
          prevent_timeout++;
        });
        selIn.addEventListener("blur", function() {
          prevent_timeout = 0;
        });
        selIn.addEventListener("change", function() {
          prevent_timeout = -1;
        });
        selOut.addEventListener("click", function() {
          prevent_timeout++;
        });
        selOut.addEventListener("blur", function() {
          prevent_timeout = 0;
        });
        selOut.addEventListener("change", function() {
          prevent_timeout = -1;
        });
      }
    }
    that.search_box?.close();
    that.search_box = dialog;
    let first2 = null;
    let timeout = null;
    let selected = null;
    const maybeInput = dialog.querySelector("input");
    if (!maybeInput) throw new TypeError("Could not create search input box.");
    const input = maybeInput;
    if (input) {
      input.addEventListener("blur", function() {
        this.focus();
      });
      input.addEventListener("keydown", function(e2) {
        if (e2.key == "ArrowUp") {
          changeSelection(false);
        } else if (e2.key == "ArrowDown") {
          changeSelection(true);
        } else if (e2.key == "Escape") {
          dialog.close();
        } else if (e2.key == "Enter") {
          if (selected instanceof HTMLElement) {
            select(unescape(String(selected.dataset["type"])));
          } else if (first2) {
            select(first2);
          } else {
            dialog.close();
          }
        } else {
          if (timeout) {
            clearInterval(timeout);
          }
          timeout = setTimeout(refreshHelper, 10);
          return;
        }
        e2.preventDefault();
        e2.stopPropagation();
        e2.stopImmediatePropagation();
        return true;
      });
    }
    if (options2.do_type_filter) {
      if (selIn) {
        const aSlots = LiteGraph.slot_types_in;
        const nSlots = aSlots.length;
        if (options2.type_filter_in == LiteGraph.EVENT || options2.type_filter_in == LiteGraph.ACTION) {
          options2.type_filter_in = "_event_";
        }
        for (let iK = 0; iK < nSlots; iK++) {
          const opt = document.createElement("option");
          opt.value = aSlots[iK];
          opt.innerHTML = aSlots[iK];
          selIn.append(opt);
          if (
            // @ts-expect-error
            options2.type_filter_in !== false && String(options2.type_filter_in).toLowerCase() == String(aSlots[iK]).toLowerCase()
          ) {
            opt.selected = true;
          }
        }
        selIn.addEventListener("change", function() {
          refreshHelper();
        });
      }
      if (selOut) {
        const aSlots = LiteGraph.slot_types_out;
        if (options2.type_filter_out == LiteGraph.EVENT || options2.type_filter_out == LiteGraph.ACTION) {
          options2.type_filter_out = "_event_";
        }
        for (const aSlot of aSlots) {
          const opt = document.createElement("option");
          opt.value = aSlot;
          opt.innerHTML = aSlot;
          selOut.append(opt);
          if (options2.type_filter_out !== false && String(options2.type_filter_out).toLowerCase() == String(aSlot).toLowerCase()) {
            opt.selected = true;
          }
        }
        selOut.addEventListener("change", function() {
          refreshHelper();
        });
      }
    }
    const rect = canvas2.getBoundingClientRect();
    const left = (event ? event.clientX : rect.left + rect.width * 0.5) - 80;
    const top = (event ? event.clientY : rect.top + rect.height * 0.5) - 20;
    dialog.style.left = `${left}px`;
    dialog.style.top = `${top}px`;
    if (event.layerY > rect.height - 200) {
      helper.style.maxHeight = `${rect.height - event.layerY - 20}px`;
    }
    requestAnimationFrame(function() {
      input.focus();
    });
    if (options2.show_all_on_open) refreshHelper();
    function select(name2) {
      if (name2) {
        if (that.onSearchBoxSelection) {
          that.onSearchBoxSelection(name2, event, graphcanvas);
        } else {
          if (!graphcanvas.graph) throw new NullGraphError();
          graphcanvas.graph.beforeChange();
          const node2 = LiteGraph.createNode(name2);
          if (node2) {
            node2.pos = graphcanvas.convertEventToCanvasOffset(event);
            graphcanvas.graph.add(node2, false);
          }
          if (options2.node_from) {
            let iS = false;
            switch (typeof options2.slot_from) {
              case "string":
                iS = options2.node_from.findOutputSlot(options2.slot_from);
                break;
              case "object":
                if (options2.slot_from == null) throw new TypeError("options.slot_from was null when showing search box");
                iS = options2.slot_from.name ? options2.node_from.findOutputSlot(options2.slot_from.name) : -1;
                if (iS == -1 && options2.slot_from.slot_index !== void 0) iS = options2.slot_from.slot_index;
                break;
              case "number":
                iS = options2.slot_from;
                break;
              default:
                iS = 0;
            }
            if (options2.node_from.outputs[iS] !== void 0) {
              if (iS !== false && iS > -1) {
                if (node2 == null) throw new TypeError("options.slot_from was null when showing search box");
                options2.node_from.connectByType(iS, node2, options2.node_from.outputs[iS].type);
              }
            }
          }
          if (options2.node_to) {
            let iS = false;
            switch (typeof options2.slot_from) {
              case "string":
                iS = options2.node_to.findInputSlot(options2.slot_from);
                break;
              case "object":
                if (options2.slot_from == null) throw new TypeError("options.slot_from was null when showing search box");
                iS = options2.slot_from.name ? options2.node_to.findInputSlot(options2.slot_from.name) : -1;
                if (iS == -1 && options2.slot_from.slot_index !== void 0) iS = options2.slot_from.slot_index;
                break;
              case "number":
                iS = options2.slot_from;
                break;
              default:
                iS = 0;
            }
            if (options2.node_to.inputs[iS] !== void 0) {
              if (iS !== false && iS > -1) {
                if (node2 == null) throw new TypeError("options.slot_from was null when showing search box");
                options2.node_to.connectByTypeOutput(iS, node2, options2.node_to.inputs[iS].type);
              }
            }
          }
          graphcanvas.graph.afterChange();
        }
      }
      dialog.close();
    }
    __name(select, "select");
    function changeSelection(forward) {
      const prev = selected;
      if (!selected) {
        selected = forward ? helper.childNodes[0] : helper.childNodes[helper.childNodes.length];
      } else if (selected instanceof Element) {
        selected.classList.remove("selected");
        selected = forward ? selected.nextSibling : selected.previousSibling;
        selected ||= prev;
      }
      if (selected instanceof Element) {
        selected.classList.add("selected");
        selected.scrollIntoView({ block: "end", behavior: "smooth" });
      }
    }
    __name(changeSelection, "changeSelection");
    function refreshHelper() {
      timeout = null;
      let str = input.value;
      first2 = null;
      helper.innerHTML = "";
      if (!str && !options2.show_all_if_empty) return;
      if (that.onSearchBox) {
        const list2 = that.onSearchBox(helper, str, graphcanvas);
        if (list2) {
          for (const item of list2) {
            addResult(item);
          }
        }
      } else {
        let inner_test_filter = /* @__PURE__ */ __name(function(type, optsIn) {
          optsIn = optsIn || {};
          const optsDef = {
            skipFilter: false,
            inTypeOverride: false,
            outTypeOverride: false
          };
          const opts = Object.assign(optsDef, optsIn);
          const ctor = LiteGraph.registered_node_types[type];
          if (filter3 && ctor.filter != filter3) return false;
          if ((!options2.show_all_if_empty || str) && !type.toLowerCase().includes(str) && (!ctor.title || !ctor.title.toLowerCase().includes(str))) {
            return false;
          }
          if (options2.do_type_filter && !opts.skipFilter) {
            const sType = type;
            let sV = opts.inTypeOverride !== false ? opts.inTypeOverride : sIn.value;
            if (sIn && sV && LiteGraph.registered_slot_in_types[sV]?.nodes) {
              const doesInc = LiteGraph.registered_slot_in_types[sV].nodes.includes(sType);
              if (doesInc === false) return false;
            }
            sV = sOut.value;
            if (opts.outTypeOverride !== false) sV = opts.outTypeOverride;
            if (sOut && sV && LiteGraph.registered_slot_out_types[sV]?.nodes) {
              const doesInc = LiteGraph.registered_slot_out_types[sV].nodes.includes(sType);
              if (doesInc === false) return false;
            }
          }
          return true;
        }, "inner_test_filter");
        let c2 = 0;
        str = str.toLowerCase();
        if (!graphcanvas.graph) throw new NullGraphError();
        const filter3 = graphcanvas.filter || graphcanvas.graph.filter;
        let sIn = false;
        let sOut = false;
        if (options2.do_type_filter && that.search_box) {
          sIn = that.search_box.querySelector(".slot_in_type_filter");
          sOut = that.search_box.querySelector(".slot_out_type_filter");
        }
        const keys2 = Object.keys(LiteGraph.registered_node_types);
        const filtered = keys2.filter((x2) => inner_test_filter(x2));
        for (const item of filtered) {
          addResult(item);
          if (LGraphCanvas.search_limit !== -1 && c2++ > LGraphCanvas.search_limit)
            break;
        }
        if (options2.show_general_after_typefiltered && (sIn.value || sOut.value)) {
          filtered_extra = [];
          for (const i2 in LiteGraph.registered_node_types) {
            if (inner_test_filter(i2, {
              inTypeOverride: sIn && sIn.value ? "*" : false,
              outTypeOverride: sOut && sOut.value ? "*" : false
            })) {
              filtered_extra.push(i2);
            }
          }
          for (const extraItem of filtered_extra) {
            addResult(extraItem, "generic_type");
            if (LGraphCanvas.search_limit !== -1 && c2++ > LGraphCanvas.search_limit)
              break;
          }
        }
        if ((sIn.value || sOut.value) && helper.childNodes.length == 0 && options2.show_general_if_none_on_typefilter) {
          filtered_extra = [];
          for (const i2 in LiteGraph.registered_node_types) {
            if (inner_test_filter(i2, { skipFilter: true }))
              filtered_extra.push(i2);
          }
          for (const extraItem of filtered_extra) {
            addResult(extraItem, "not_in_filter");
            if (LGraphCanvas.search_limit !== -1 && c2++ > LGraphCanvas.search_limit)
              break;
          }
        }
      }
      function addResult(type, className) {
        const help = document.createElement("div");
        first2 ||= type;
        const nodeType = LiteGraph.registered_node_types[type];
        if (nodeType?.title) {
          help.textContent = nodeType?.title;
          const typeEl = document.createElement("span");
          typeEl.className = "litegraph lite-search-item-type";
          typeEl.textContent = type;
          help.append(typeEl);
        } else {
          help.textContent = type;
        }
        help.dataset["type"] = escape(type);
        help.className = "litegraph lite-search-item";
        if (className) {
          help.className += ` ${className}`;
        }
        help.addEventListener("click", function() {
          select(unescape(String(this.dataset["type"])));
        });
        helper.append(help);
      }
      __name(addResult, "addResult");
    }
    __name(refreshHelper, "refreshHelper");
    return dialog;
  }
  showEditPropertyValue(node2, property, options2) {
    if (!node2 || node2.properties[property] === void 0) return;
    options2 = options2 || {};
    const info = node2.getPropertyInfo(property);
    const { type } = info;
    let input_html = "";
    if (type == "string" || type == "number" || type == "array" || type == "object") {
      input_html = "<input autofocus type='text' class='value'/>";
    } else if ((type == "enum" || type == "combo") && info.values) {
      input_html = "<select autofocus type='text' class='value'>";
      for (const i2 in info.values) {
        const v2 = Array.isArray(info.values) ? info.values[i2] : i2;
        const selected = v2 == node2.properties[property] ? "selected" : "";
        input_html += `<option value='${v2}' ${selected}>${info.values[i2]}</option>`;
      }
      input_html += "</select>";
    } else if (type == "boolean" || type == "toggle") {
      const checked = node2.properties[property] ? "checked" : "";
      input_html = `<input autofocus type='checkbox' class='value' ${checked}/>`;
    } else {
      console.warn(`unknown type: ${type}`);
      return;
    }
    const dialog = this.createDialog(
      `<span class='name'>${info.label || property}</span>${input_html}<button>OK</button>`,
      options2
    );
    let input;
    if ((type == "enum" || type == "combo") && info.values) {
      input = dialog.querySelector("select");
      input?.addEventListener("change", function(e2) {
        dialog.modified();
        setValue(e2.target?.value);
      });
    } else if (type == "boolean" || type == "toggle") {
      input = dialog.querySelector("input");
      input?.addEventListener("click", function() {
        dialog.modified();
        setValue(!!input.checked);
      });
    } else {
      input = dialog.querySelector("input");
      if (input) {
        input.addEventListener("blur", function() {
          this.focus();
        });
        let v2 = node2.properties[property] !== void 0 ? node2.properties[property] : "";
        if (type !== "string") {
          v2 = JSON.stringify(v2);
        }
        input.value = v2;
        input.addEventListener("keydown", function(e2) {
          if (e2.key == "Escape") {
            dialog.close();
          } else if (e2.key == "Enter") {
            inner();
          } else {
            dialog.modified();
            return;
          }
          e2.preventDefault();
          e2.stopPropagation();
        });
      }
    }
    input?.focus();
    const button = dialog.querySelector("button");
    if (!button) throw new TypeError("Show edit property value button was null.");
    button.addEventListener("click", inner);
    function inner() {
      setValue(input?.value);
    }
    __name(inner, "inner");
    const dirty = /* @__PURE__ */ __name(() => this.#dirty(), "dirty");
    function setValue(value) {
      if (info?.values && typeof info.values === "object" && info.values[value] != void 0) {
        value = info.values[value];
      }
      if (typeof node2.properties[property] == "number") {
        value = Number(value);
      }
      if (type == "array" || type == "object") {
        value = JSON.parse(value);
      }
      node2.properties[property] = value;
      if (node2.graph) {
        node2.graph._version++;
      }
      node2.onPropertyChanged?.(property, value);
      options2.onclose?.();
      dialog.close();
      dirty();
    }
    __name(setValue, "setValue");
    return dialog;
  }
  // TODO refactor, theer are different dialog, some uses createDialog, some dont
  createDialog(html, options2) {
    const def_options = {
      checkForInput: false,
      closeOnLeave: true,
      closeOnLeave_checkModified: true
    };
    options2 = Object.assign(def_options, options2 || {});
    const customProperties = {
      className: "graphdialog",
      innerHTML: html,
      is_modified: false,
      modified() {
        this.is_modified = true;
      },
      close() {
        this.remove();
      }
    };
    const div = document.createElement("div");
    const dialog = Object.assign(div, customProperties);
    const rect = this.canvas.getBoundingClientRect();
    let offsetx = -20;
    let offsety = -20;
    if (rect) {
      offsetx -= rect.left;
      offsety -= rect.top;
    }
    if (options2.position) {
      offsetx += options2.position[0];
      offsety += options2.position[1];
    } else if (options2.event) {
      offsetx += options2.event.clientX;
      offsety += options2.event.clientY;
    } else {
      offsetx += this.canvas.width * 0.5;
      offsety += this.canvas.height * 0.5;
    }
    dialog.style.left = `${offsetx}px`;
    dialog.style.top = `${offsety}px`;
    if (!this.canvas.parentNode) throw new TypeError("Canvas parent element was null.");
    this.canvas.parentNode.append(dialog);
    if (options2.checkForInput) {
      const aI = dialog.querySelectorAll("input");
      if (aI) {
        for (const iX of aI) {
          iX.addEventListener("keydown", function(e2) {
            dialog.modified();
            if (e2.key == "Escape") {
              dialog.close();
            } else if (e2.key != "Enter") {
              return;
            }
            e2.preventDefault();
            e2.stopPropagation();
          });
          iX.focus();
        }
      }
    }
    let dialogCloseTimer;
    let prevent_timeout = 0;
    dialog.addEventListener("mouseleave", function() {
      if (prevent_timeout) return;
      if (!dialog.is_modified && LiteGraph.dialog_close_on_mouse_leave) {
        dialogCloseTimer = setTimeout(
          dialog.close,
          LiteGraph.dialog_close_on_mouse_leave_delay
        );
      }
    });
    dialog.addEventListener("mouseenter", function() {
      if (options2.closeOnLeave || LiteGraph.dialog_close_on_mouse_leave) {
        if (dialogCloseTimer) clearTimeout(dialogCloseTimer);
      }
    });
    const selInDia = dialog.querySelectorAll("select");
    if (selInDia) {
      for (const selIn of selInDia) {
        selIn.addEventListener("click", function() {
          prevent_timeout++;
        });
        selIn.addEventListener("blur", function() {
          prevent_timeout = 0;
        });
        selIn.addEventListener("change", function() {
          prevent_timeout = -1;
        });
      }
    }
    return dialog;
  }
  createPanel(title, options2) {
    options2 = options2 || {};
    const ref_window = options2.window || window;
    const root2 = document.createElement("div");
    root2.className = "litegraph dialog";
    root2.innerHTML = "<div class='dialog-header'><span class='dialog-title'></span></div><div class='dialog-content'></div><div style='display:none;' class='dialog-alt-content'></div><div class='dialog-footer'></div>";
    root2.header = root2.querySelector(".dialog-header");
    if (options2.width)
      root2.style.width = options2.width + (typeof options2.width === "number" ? "px" : "");
    if (options2.height)
      root2.style.height = options2.height + (typeof options2.height === "number" ? "px" : "");
    if (options2.closable) {
      const close2 = document.createElement("span");
      close2.innerHTML = "&#10005;";
      close2.classList.add("close");
      close2.addEventListener("click", function() {
        root2.close();
      });
      root2.header.append(close2);
    }
    root2.title_element = root2.querySelector(".dialog-title");
    root2.title_element.textContent = title;
    root2.content = root2.querySelector(".dialog-content");
    root2.alt_content = root2.querySelector(".dialog-alt-content");
    root2.footer = root2.querySelector(".dialog-footer");
    root2.close = function() {
      if (typeof root2.onClose == "function") root2.onClose();
      root2.remove();
      this.remove();
    };
    root2.toggleAltContent = function(force) {
      let vTo;
      let vAlt;
      if (force !== void 0) {
        vTo = force ? "block" : "none";
        vAlt = force ? "none" : "block";
      } else {
        vTo = root2.alt_content.style.display != "block" ? "block" : "none";
        vAlt = root2.alt_content.style.display != "block" ? "none" : "block";
      }
      root2.alt_content.style.display = vTo;
      root2.content.style.display = vAlt;
    };
    root2.toggleFooterVisibility = function(force) {
      let vTo;
      if (force !== void 0) {
        vTo = force ? "block" : "none";
      } else {
        vTo = root2.footer.style.display != "block" ? "block" : "none";
      }
      root2.footer.style.display = vTo;
    };
    root2.clear = function() {
      this.content.innerHTML = "";
    };
    root2.addHTML = function(code2, classname, on_footer) {
      const elem = document.createElement("div");
      if (classname) elem.className = classname;
      elem.innerHTML = code2;
      if (on_footer) root2.footer.append(elem);
      else root2.content.append(elem);
      return elem;
    };
    root2.addButton = function(name2, callback, options22) {
      const elem = document.createElement("button");
      elem.textContent = name2;
      elem.options = options22;
      elem.classList.add("btn");
      elem.addEventListener("click", callback);
      root2.footer.append(elem);
      return elem;
    };
    root2.addSeparator = function() {
      const elem = document.createElement("div");
      elem.className = "separator";
      root2.content.append(elem);
    };
    root2.addWidget = function(type, name2, value, options22, callback) {
      options22 = options22 || {};
      let str_value = String(value);
      type = type.toLowerCase();
      if (type == "number" && typeof value === "number") str_value = value.toFixed(3);
      const elem = document.createElement("div");
      elem.className = "property";
      elem.innerHTML = "<span class='property_name'></span><span class='property_value'></span>";
      const nameSpan = elem.querySelector(".property_name");
      if (!nameSpan) throw new TypeError("Property name element was null.");
      nameSpan.textContent = options22.label || name2;
      const value_element = elem.querySelector(".property_value");
      if (!value_element) throw new TypeError("Property name element was null.");
      value_element.textContent = str_value;
      elem.dataset["property"] = name2;
      elem.dataset["type"] = options22.type || type;
      elem.options = options22;
      elem.value = value;
      if (type == "code") {
        elem.addEventListener("click", function() {
          root2.inner_showCodePad(this.dataset["property"]);
        });
      } else if (type == "boolean") {
        elem.classList.add("boolean");
        if (value) elem.classList.add("bool-on");
        elem.addEventListener("click", () => {
          const propname = elem.dataset["property"];
          elem.value = !elem.value;
          elem.classList.toggle("bool-on");
          if (!value_element) throw new TypeError("Property name element was null.");
          value_element.textContent = elem.value ? "true" : "false";
          innerChange(propname, elem.value);
        });
      } else if (type == "string" || type == "number") {
        if (!value_element) throw new TypeError("Property name element was null.");
        value_element.setAttribute("contenteditable", "true");
        value_element.addEventListener("keydown", function(e2) {
          if (e2.code == "Enter" && (type != "string" || !e2.shiftKey)) {
            e2.preventDefault();
            this.blur();
          }
        });
        value_element.addEventListener("blur", function() {
          let v2 = this.textContent;
          const propname = this.parentElement?.dataset["property"];
          const proptype = this.parentElement?.dataset["type"];
          if (proptype == "number") v2 = Number(v2);
          innerChange(propname, v2);
        });
      } else if (type == "enum" || type == "combo") {
        const str_value2 = LGraphCanvas.getPropertyPrintableValue(value, options22.values);
        if (!value_element) throw new TypeError("Property name element was null.");
        value_element.textContent = str_value2 ?? "";
        value_element.addEventListener("click", function(event) {
          const values = options22.values || [];
          const propname = this.parentElement?.dataset["property"];
          const inner_clicked = /* @__PURE__ */ __name((v2) => {
            this.textContent = v2;
            innerChange(propname, v2);
            return false;
          }, "inner_clicked");
          new LiteGraph.ContextMenu(
            values,
            {
              event,
              className: "dark",
              callback: inner_clicked
            },
            // @ts-expect-error
            ref_window
          );
        });
      }
      root2.content.append(elem);
      function innerChange(name22, value2) {
        options22.callback?.(name22, value2, options22);
        callback?.(name22, value2, options22);
      }
      __name(innerChange, "innerChange");
      return elem;
    };
    if (typeof root2.onOpen == "function") root2.onOpen();
    return root2;
  }
  closePanels() {
    document.querySelector("#node-panel")?.close?.();
    document.querySelector("#option-panel")?.close?.();
  }
  showShowNodePanel(node2) {
    this.SELECTED_NODE = node2;
    this.closePanels();
    const ref_window = this.getCanvasWindow();
    const panel = this.createPanel(node2.title || "", {
      closable: true,
      window: ref_window,
      onOpen: /* @__PURE__ */ __name(() => {
        this.NODEPANEL_IS_OPEN = true;
      }, "onOpen"),
      onClose: /* @__PURE__ */ __name(() => {
        this.NODEPANEL_IS_OPEN = false;
        this.node_panel = null;
      }, "onClose")
    });
    this.node_panel = panel;
    panel.id = "node-panel";
    panel.node = node2;
    panel.classList.add("settings");
    const inner_refresh = /* @__PURE__ */ __name(() => {
      panel.content.innerHTML = "";
      panel.addHTML(`<span class='node_type'>${node2.type}</span><span class='node_desc'>${node2.constructor.desc || ""}</span><span class='separator'></span>`);
      panel.addHTML("<h3>Properties</h3>");
      const fUpdate = /* @__PURE__ */ __name((name2, value) => {
        if (!this.graph) throw new NullGraphError();
        this.graph.beforeChange(node2);
        switch (name2) {
          case "Title":
            if (typeof value !== "string") throw new TypeError("Attempting to set title to non-string value.");
            node2.title = value;
            break;
          case "Mode": {
            if (typeof value !== "string") throw new TypeError("Attempting to set mode to non-string value.");
            const kV = Object.values(LiteGraph.NODE_MODES).indexOf(value);
            if (kV !== -1 && LiteGraph.NODE_MODES[kV]) {
              node2.changeMode(kV);
            } else {
              console.warn(`unexpected mode: ${value}`);
            }
            break;
          }
          case "Color":
            if (typeof value !== "string") throw new TypeError("Attempting to set colour to non-string value.");
            if (LGraphCanvas.node_colors[value]) {
              node2.color = LGraphCanvas.node_colors[value].color;
              node2.bgcolor = LGraphCanvas.node_colors[value].bgcolor;
            } else {
              console.warn(`unexpected color: ${value}`);
            }
            break;
          default:
            node2.setProperty(name2, value);
            break;
        }
        this.graph.afterChange();
        this.dirty_canvas = true;
      }, "fUpdate");
      panel.addWidget("string", "Title", node2.title, {}, fUpdate);
      const mode = node2.mode == null ? void 0 : LiteGraph.NODE_MODES[node2.mode];
      panel.addWidget("combo", "Mode", mode, { values: LiteGraph.NODE_MODES }, fUpdate);
      const nodeCol = node2.color !== void 0 ? Object.keys(LGraphCanvas.node_colors).filter(function(nK) {
        return LGraphCanvas.node_colors[nK].color == node2.color;
      }) : "";
      panel.addWidget("combo", "Color", nodeCol, { values: Object.keys(LGraphCanvas.node_colors) }, fUpdate);
      for (const pName in node2.properties) {
        const value = node2.properties[pName];
        const info = node2.getPropertyInfo(pName);
        if (node2.onAddPropertyToPanel?.(pName, panel)) continue;
        panel.addWidget(info.widget || info.type, pName, value, info, fUpdate);
      }
      panel.addSeparator();
      node2.onShowCustomPanelInfo?.(panel);
      panel.footer.innerHTML = "";
      panel.addButton("Delete", function() {
        if (node2.block_delete) return;
        if (!node2.graph) throw new NullGraphError();
        node2.graph.remove(node2);
        panel.close();
      }).classList.add("delete");
    }, "inner_refresh");
    panel.inner_showCodePad = function(propname) {
      panel.classList.remove("settings");
      panel.classList.add("centered");
      panel.alt_content.innerHTML = "<textarea class='code'></textarea>";
      const textarea = panel.alt_content.querySelector("textarea");
      const fDoneWith = /* @__PURE__ */ __name(function() {
        panel.toggleAltContent(false);
        panel.toggleFooterVisibility(true);
        textarea.remove();
        panel.classList.add("settings");
        panel.classList.remove("centered");
        inner_refresh();
      }, "fDoneWith");
      textarea.value = String(node2.properties[propname]);
      textarea.addEventListener("keydown", function(e2) {
        if (e2.code == "Enter" && e2.ctrlKey) {
          node2.setProperty(propname, textarea.value);
          fDoneWith();
        }
      });
      panel.toggleAltContent(true);
      panel.toggleFooterVisibility(false);
      textarea.style.height = "calc(100% - 40px)";
      const assign2 = panel.addButton("Assign", function() {
        node2.setProperty(propname, textarea.value);
        fDoneWith();
      });
      panel.alt_content.append(assign2);
      const button = panel.addButton("Close", fDoneWith);
      button.style.float = "right";
      panel.alt_content.append(button);
    };
    inner_refresh();
    if (!this.canvas.parentNode) throw new TypeError("showNodePanel - this.canvas.parentNode was null");
    this.canvas.parentNode.append(panel);
  }
  checkPanels() {
    if (!this.canvas) return;
    if (!this.canvas.parentNode) throw new TypeError("checkPanels - this.canvas.parentNode was null");
    const panels = this.canvas.parentNode.querySelectorAll(".litegraph.dialog");
    for (const panel of panels) {
      if (!panel.node) continue;
      if (!panel.node.graph || panel.graph != this.graph) panel.close();
    }
  }
  getCanvasMenuOptions() {
    let options2;
    if (this.getMenuOptions) {
      options2 = this.getMenuOptions();
    } else {
      options2 = [
        {
          content: "Add Node",
          has_submenu: true,
          callback: LGraphCanvas.onMenuAdd
        },
        { content: "Add Group", callback: LGraphCanvas.onGroupAdd }
        // { content: "Arrange", callback: that.graph.arrange },
        // {content:"Collapse All", callback: LGraphCanvas.onMenuCollapseAll }
      ];
      if (Object.keys(this.selected_nodes).length > 1) {
        options2.push({
          content: "Align",
          has_submenu: true,
          callback: LGraphCanvas.onGroupAlign
        });
      }
    }
    const extra = this.getExtraMenuOptions?.(this, options2);
    return Array.isArray(extra) ? options2.concat(extra) : options2;
  }
  // called by processContextMenu to extract the menu list
  getNodeMenuOptions(node2) {
    let options2;
    if (node2.getMenuOptions) {
      options2 = node2.getMenuOptions(this);
    } else {
      options2 = [
        {
          content: "Inputs",
          has_submenu: true,
          disabled: true
        },
        {
          content: "Outputs",
          has_submenu: true,
          disabled: true,
          callback: LGraphCanvas.showMenuNodeOptionalOutputs
        },
        null,
        {
          content: "Properties",
          has_submenu: true,
          callback: LGraphCanvas.onShowMenuNodeProperties
        },
        {
          content: "Properties Panel",
          callback: /* @__PURE__ */ __name(function(item, options22, e2, menu2, node22) {
            LGraphCanvas.active_canvas.showShowNodePanel(node22);
          }, "callback")
        },
        null,
        {
          content: "Title",
          callback: LGraphCanvas.onShowPropertyEditor
        },
        {
          content: "Mode",
          has_submenu: true,
          callback: LGraphCanvas.onMenuNodeMode
        }
      ];
      if (node2.resizable !== false) {
        options2.push({
          content: "Resize",
          callback: LGraphCanvas.onMenuResizeNode
        });
      }
      if (node2.collapsible) {
        options2.push({
          content: node2.collapsed ? "Expand" : "Collapse",
          callback: LGraphCanvas.onMenuNodeCollapse
        });
      }
      if (node2.widgets?.some((w2) => w2.advanced)) {
        options2.push({
          content: node2.showAdvanced ? "Hide Advanced" : "Show Advanced",
          callback: LGraphCanvas.onMenuToggleAdvanced
        });
      }
      options2.push(
        {
          content: node2.pinned ? "Unpin" : "Pin",
          callback: /* @__PURE__ */ __name(() => {
            for (const i2 in this.selected_nodes) {
              const node22 = this.selected_nodes[i2];
              node22.pin();
            }
            this.setDirty(true, true);
          }, "callback")
        },
        {
          content: "Colors",
          has_submenu: true,
          callback: LGraphCanvas.onMenuNodeColors
        },
        {
          content: "Shapes",
          has_submenu: true,
          callback: LGraphCanvas.onMenuNodeShapes
        },
        null
      );
    }
    const extra = node2.getExtraMenuOptions?.(this, options2);
    if (Array.isArray(extra) && extra.length > 0) {
      extra.push(null);
      options2 = extra.concat(options2);
    }
    if (node2.clonable !== false) {
      options2.push({
        content: "Clone",
        callback: LGraphCanvas.onMenuNodeClone
      });
    }
    if (Object.keys(this.selected_nodes).length > 1) {
      options2.push({
        content: "Align Selected To",
        has_submenu: true,
        callback: LGraphCanvas.onNodeAlign
      }, {
        content: "Distribute Nodes",
        has_submenu: true,
        callback: LGraphCanvas.createDistributeMenu
      });
    }
    options2.push(null, {
      content: "Remove",
      disabled: !(node2.removable !== false && !node2.block_delete),
      callback: LGraphCanvas.onMenuNodeRemove
    });
    node2.graph?.onGetNodeMenuOptions?.(options2, node2);
    return options2;
  }
  /** @deprecated */
  getGroupMenuOptions(group) {
    console.warn("LGraphCanvas.getGroupMenuOptions is deprecated, use LGraphGroup.getMenuOptions instead");
    return group.getMenuOptions();
  }
  processContextMenu(node2, event) {
    const canvas2 = LGraphCanvas.active_canvas;
    const ref_window = canvas2.getCanvasWindow();
    let menu_info;
    const options2 = {
      event,
      callback: inner_option_clicked,
      extra: node2
    };
    if (node2) {
      options2.title = node2.type ?? void 0;
      LGraphCanvas.active_node = node2;
      const slot = node2.getSlotInPosition(event.canvasX, event.canvasY);
      if (slot) {
        menu_info = [];
        if (node2.getSlotMenuOptions) {
          menu_info = node2.getSlotMenuOptions(slot);
        } else {
          if (slot.output?.links?.length || slot.input?.link != null) {
            menu_info.push({ content: "Disconnect Links", slot });
          }
          const _slot = slot.input || slot.output;
          if (!_slot) throw new TypeError("Both in put and output slots were null when processing context menu.");
          if (_slot.removable) {
            menu_info.push(
              _slot.locked ? "Cannot remove" : { content: "Remove Slot", slot }
            );
          }
          if (!_slot.nameLocked && !("link" in _slot && _slot.widget)) {
            menu_info.push({ content: "Rename Slot", slot });
          }
          if (node2.getExtraSlotMenuOptions) {
            menu_info.push(...node2.getExtraSlotMenuOptions(slot));
          }
        }
        options2.title = (slot.input ? slot.input.type : slot.output.type) || "*";
        if (slot.input && slot.input.type == LiteGraph.ACTION)
          options2.title = "Action";
        if (slot.output && slot.output.type == LiteGraph.EVENT)
          options2.title = "Event";
      } else {
        menu_info = this.getNodeMenuOptions(node2);
      }
    } else {
      menu_info = this.getCanvasMenuOptions();
      if (!this.graph) throw new NullGraphError();
      if (this.links_render_mode !== LinkRenderType.HIDDEN_LINK) {
        const reroute = this.graph.getRerouteOnPos(event.canvasX, event.canvasY, this.#visibleReroutes);
        if (reroute) {
          menu_info.unshift({
            content: "Delete Reroute",
            callback: /* @__PURE__ */ __name(() => {
              if (!this.graph) throw new NullGraphError();
              this.graph.removeReroute(reroute.id);
            }, "callback")
          }, null);
        }
      }
      const group = this.graph.getGroupOnPos(
        event.canvasX,
        event.canvasY
      );
      if (group) {
        menu_info.push(null, {
          content: "Edit Group",
          has_submenu: true,
          submenu: {
            title: "Group",
            extra: group,
            options: group.getMenuOptions()
          }
        });
      }
    }
    if (!menu_info) return;
    new LiteGraph.ContextMenu(menu_info, options2, ref_window);
    const createDialog = /* @__PURE__ */ __name((options22) => this.createDialog(
      "<span class='name'>Name</span><input autofocus type='text'/><button>OK</button>",
      options22
    ), "createDialog");
    const setDirty = /* @__PURE__ */ __name(() => this.setDirty(true), "setDirty");
    function inner_option_clicked(v2, options22) {
      if (!v2) return;
      if (v2.content == "Remove Slot") {
        if (!node2?.graph) throw new NullGraphError();
        const info = v2.slot;
        if (!info) throw new TypeError("Found-slot info was null when processing context menu.");
        node2.graph.beforeChange();
        if (info.input) {
          node2.removeInput(info.slot);
        } else if (info.output) {
          node2.removeOutput(info.slot);
        }
        node2.graph.afterChange();
        return;
      } else if (v2.content == "Disconnect Links") {
        if (!node2?.graph) throw new NullGraphError();
        const info = v2.slot;
        if (!info) throw new TypeError("Found-slot info was null when processing context menu.");
        node2.graph.beforeChange();
        if (info.output) {
          node2.disconnectOutput(info.slot);
        } else if (info.input) {
          node2.disconnectInput(info.slot, true);
        }
        node2.graph.afterChange();
        return;
      } else if (v2.content == "Rename Slot") {
        if (!node2) throw new TypeError("`node` was null when processing the context menu.");
        const info = v2.slot;
        if (!info) throw new TypeError("Found-slot info was null when processing context menu.");
        const slot_info = info.input ? node2.getInputInfo(info.slot) : node2.getOutputInfo(info.slot);
        const dialog = createDialog(options22);
        const input = dialog.querySelector("input");
        if (input && slot_info) {
          input.value = slot_info.label || "";
        }
        const inner = /* @__PURE__ */ __name(function() {
          if (!node2.graph) throw new NullGraphError();
          node2.graph.beforeChange();
          if (input?.value) {
            if (slot_info) {
              slot_info.label = input.value;
            }
            setDirty();
          }
          dialog.close();
          node2.graph.afterChange();
        }, "inner");
        dialog.querySelector("button")?.addEventListener("click", inner);
        if (!input) throw new TypeError("Input element was null when processing context menu.");
        input.addEventListener("keydown", function(e2) {
          dialog.is_modified = true;
          if (e2.key == "Escape") {
            dialog.close();
          } else if (e2.key == "Enter") {
            inner();
          } else if (e2.target.localName != "textarea") {
            return;
          }
          e2.preventDefault();
          e2.stopPropagation();
        });
        input.focus();
      }
    }
    __name(inner_option_clicked, "inner_option_clicked");
  }
  /**
   * Starts an animation to fit the view around the specified selection of nodes.
   * @param bounds The bounds to animate the view to, defined by a rectangle.
   */
  animateToBounds(bounds, options2 = {}) {
    const setDirty = /* @__PURE__ */ __name(() => this.setDirty(true, true), "setDirty");
    this.ds.animateToBounds(bounds, setDirty, options2);
  }
  /**
   * Fits the view to the selected nodes with animation.
   * If nothing is selected, the view is fitted around all items in the graph.
   */
  fitViewToSelectionAnimated(options2 = {}) {
    const items = this.selectedItems.size ? Array.from(this.selectedItems) : this.positionableItems;
    const bounds = createBounds(items);
    if (!bounds) throw new TypeError("Attempted to fit to view but could not calculate bounds.");
    const setDirty = /* @__PURE__ */ __name(() => this.setDirty(true, true), "setDirty");
    this.ds.animateToBounds(bounds, setDirty, options2);
  }
}
class MapProxyHandler {
  static {
    __name(this, "MapProxyHandler");
  }
  getOwnPropertyDescriptor(target, p2) {
    const value = this.get(target, p2);
    if (value) {
      return {
        configurable: true,
        enumerable: true,
        value
      };
    }
  }
  has(target, p2) {
    if (typeof p2 === "symbol") return false;
    const int = parseInt(p2, 10);
    return target.has(!isNaN(int) ? int : p2);
  }
  ownKeys(target) {
    return [...target.keys()].map(String);
  }
  get(target, p2) {
    if (p2 in target) return Reflect.get(target, p2, target);
    if (typeof p2 === "symbol") return;
    const int = parseInt(p2, 10);
    return target.get(!isNaN(int) ? int : p2);
  }
  set(target, p2, newValue2) {
    if (typeof p2 === "symbol") return false;
    const int = parseInt(p2, 10);
    target.set(!isNaN(int) ? int : p2, newValue2);
    return true;
  }
  deleteProperty(target, p2) {
    return target.delete(p2);
  }
  static bindAllMethods(map3) {
    map3.clear = map3.clear.bind(map3);
    map3.delete = map3.delete.bind(map3);
    map3.forEach = map3.forEach.bind(map3);
    map3.get = map3.get.bind(map3);
    map3.has = map3.has.bind(map3);
    map3.set = map3.set.bind(map3);
    map3.entries = map3.entries.bind(map3);
    map3.keys = map3.keys.bind(map3);
    map3.values = map3.values.bind(map3);
    map3[Symbol.iterator] = map3[Symbol.iterator].bind(map3);
  }
}
class LGraph {
  static {
    __name(this, "LGraph");
  }
  static serialisedSchemaVersion = 1;
  static STATUS_STOPPED = 1;
  static STATUS_RUNNING = 2;
  id = zeroUuid;
  revision = 0;
  _version = -1;
  /** The backing store for links.  Keys are wrapped in String() */
  _links = /* @__PURE__ */ new Map();
  /**
   * Indexed property access is deprecated.
   * Backwards compatibility with a Proxy has been added, but will eventually be removed.
   *
   * Use {@link Map} methods:
   * ```
   * const linkId = 123
   * const link = graph.links.get(linkId)
   * // Deprecated: const link = graph.links[linkId]
   * ```
   */
  links;
  list_of_graphcanvas;
  status = LGraph.STATUS_STOPPED;
  state = {
    lastGroupId: 0,
    lastNodeId: 0,
    lastLinkId: 0,
    lastRerouteId: 0
  };
  _nodes = [];
  _nodes_by_id = {};
  _nodes_in_order = [];
  _nodes_executable = null;
  _groups = [];
  iteration = 0;
  globaltime = 0;
  /** @deprecated Unused */
  runningtime = 0;
  fixedtime = 0;
  fixedtime_lapse = 0.01;
  elapsed_time = 0.01;
  last_update_time = 0;
  starttime = 0;
  catch_errors = true;
  execution_timer_id;
  errors_in_execution;
  /** @deprecated Unused */
  execution_time;
  _last_trigger_time;
  filter;
  /** Must contain serialisable values, e.g. primitive types */
  config = {};
  vars = {};
  nodes_executing = [];
  nodes_actioning = [];
  nodes_executedAction = [];
  extra = {};
  /** @deprecated Deserialising a workflow sets this unused property. */
  version;
  /** @returns Whether the graph has no items */
  get empty() {
    return this._nodes.length + this._groups.length + this.reroutes.size === 0;
  }
  /** @returns All items on the canvas that can be selected */
  *positionableItems() {
    for (const node2 of this._nodes) yield node2;
    for (const group of this._groups) yield group;
    for (const reroute of this.reroutes.values()) yield reroute;
    return;
  }
  /** Internal only.  Not required for serialisation; calculated on deserialise. */
  #lastFloatingLinkId = 0;
  #floatingLinks = /* @__PURE__ */ new Map();
  get floatingLinks() {
    return this.#floatingLinks;
  }
  #reroutes = /* @__PURE__ */ new Map();
  /** All reroutes in this graph. */
  get reroutes() {
    return this.#reroutes;
  }
  get rootGraph() {
    return this;
  }
  get isRootGraph() {
    return this.rootGraph === this;
  }
  /** @deprecated See {@link state}.{@link LGraphState.lastNodeId lastNodeId} */
  get last_node_id() {
    return this.state.lastNodeId;
  }
  set last_node_id(value) {
    this.state.lastNodeId = value;
  }
  /** @deprecated See {@link state}.{@link LGraphState.lastLinkId lastLinkId} */
  get last_link_id() {
    return this.state.lastLinkId;
  }
  set last_link_id(value) {
    this.state.lastLinkId = value;
  }
  _input_nodes;
  /**
   * See {@link LGraph}
   * @param o data from previous serialization [optional]
   */
  constructor(o2) {
    if (LiteGraph.debug) console.log("Graph created");
    const links = this._links;
    MapProxyHandler.bindAllMethods(links);
    const handler5 = new MapProxyHandler();
    this.links = new Proxy(links, handler5);
    this.list_of_graphcanvas = null;
    this.clear();
    if (o2) this.configure(o2);
  }
  /**
   * Removes all nodes from this graph
   */
  clear() {
    this.stop();
    this.status = LGraph.STATUS_STOPPED;
    this.id = zeroUuid;
    this.revision = 0;
    this.state = {
      lastGroupId: 0,
      lastNodeId: 0,
      lastLinkId: 0,
      lastRerouteId: 0
    };
    this._version = -1;
    if (this._nodes) {
      for (const _node of this._nodes) {
        _node.onRemoved?.();
      }
    }
    this._nodes = [];
    this._nodes_by_id = {};
    this._nodes_in_order = [];
    this._nodes_executable = null;
    this._links.clear();
    this.reroutes.clear();
    this.#floatingLinks.clear();
    this.#lastFloatingLinkId = 0;
    this._groups = [];
    this.iteration = 0;
    this.config = {};
    this.vars = {};
    this.extra = {};
    this.globaltime = 0;
    this.runningtime = 0;
    this.fixedtime = 0;
    this.fixedtime_lapse = 0.01;
    this.elapsed_time = 0.01;
    this.last_update_time = 0;
    this.starttime = 0;
    this.catch_errors = true;
    this.nodes_executing = [];
    this.nodes_actioning = [];
    this.nodes_executedAction = [];
    this.change();
    this.canvasAction((c2) => c2.clear());
  }
  get nodes() {
    return this._nodes;
  }
  get groups() {
    return this._groups;
  }
  /**
   * Attach Canvas to this graph
   */
  attachCanvas(canvas2) {
    if (!(canvas2 instanceof LGraphCanvas)) {
      throw new TypeError("attachCanvas expects an LGraphCanvas instance");
    }
    this.list_of_graphcanvas ??= [];
    if (!this.list_of_graphcanvas.includes(canvas2)) {
      this.list_of_graphcanvas.push(canvas2);
    }
    if (canvas2.graph === this) return;
    canvas2.graph?.detachCanvas(canvas2);
    canvas2.graph = this;
  }
  /**
   * Detach Canvas from this graph
   */
  detachCanvas(canvas2) {
    canvas2.graph = null;
    const canvases = this.list_of_graphcanvas;
    if (canvases) {
      const pos = canvases.indexOf(canvas2);
      if (pos !== -1) canvases.splice(pos, 1);
    }
  }
  /**
   * @deprecated Will be removed in 0.9
   * Starts running this graph every interval milliseconds.
   * @param interval amount of milliseconds between executions, if 0 then it renders to the monitor refresh rate
   */
  start(interval) {
    if (this.status == LGraph.STATUS_RUNNING) return;
    this.status = LGraph.STATUS_RUNNING;
    this.onPlayEvent?.();
    this.sendEventToAllNodes("onStart");
    this.starttime = LiteGraph.getTime();
    this.last_update_time = this.starttime;
    interval ||= 0;
    if (interval == 0 && typeof window != "undefined" && window.requestAnimationFrame) {
      const on_frame = /* @__PURE__ */ __name(() => {
        if (this.execution_timer_id != -1) return;
        window.requestAnimationFrame(on_frame);
        this.onBeforeStep?.();
        this.runStep(1, !this.catch_errors);
        this.onAfterStep?.();
      }, "on_frame");
      this.execution_timer_id = -1;
      on_frame();
    } else {
      this.execution_timer_id = setInterval(() => {
        this.onBeforeStep?.();
        this.runStep(1, !this.catch_errors);
        this.onAfterStep?.();
      }, interval);
    }
  }
  /**
   * @deprecated Will be removed in 0.9
   * Stops the execution loop of the graph
   */
  stop() {
    if (this.status == LGraph.STATUS_STOPPED) return;
    this.status = LGraph.STATUS_STOPPED;
    this.onStopEvent?.();
    if (this.execution_timer_id != null) {
      if (this.execution_timer_id != -1) {
        clearInterval(this.execution_timer_id);
      }
      this.execution_timer_id = null;
    }
    this.sendEventToAllNodes("onStop");
  }
  /**
   * Run N steps (cycles) of the graph
   * @param num number of steps to run, default is 1
   * @param do_not_catch_errors [optional] if you want to try/catch errors
   * @param limit max number of nodes to execute (used to execute from start to a node)
   */
  runStep(num, do_not_catch_errors, limit2) {
    num = num || 1;
    const start2 = LiteGraph.getTime();
    this.globaltime = 1e-3 * (start2 - this.starttime);
    const nodes = this._nodes_executable || this._nodes;
    if (!nodes) return;
    limit2 = limit2 || nodes.length;
    if (do_not_catch_errors) {
      for (let i2 = 0; i2 < num; i2++) {
        for (let j2 = 0; j2 < limit2; ++j2) {
          const node2 = nodes[j2];
          if (node2.mode == LGraphEventMode.ALWAYS && node2.onExecute) {
            node2.doExecute?.();
          }
        }
        this.fixedtime += this.fixedtime_lapse;
        this.onExecuteStep?.();
      }
      this.onAfterExecute?.();
    } else {
      try {
        for (let i2 = 0; i2 < num; i2++) {
          for (let j2 = 0; j2 < limit2; ++j2) {
            const node2 = nodes[j2];
            if (node2.mode == LGraphEventMode.ALWAYS) {
              node2.onExecute?.();
            }
          }
          this.fixedtime += this.fixedtime_lapse;
          this.onExecuteStep?.();
        }
        this.onAfterExecute?.();
        this.errors_in_execution = false;
      } catch (error2) {
        this.errors_in_execution = true;
        if (LiteGraph.throw_errors) throw error2;
        if (LiteGraph.debug) console.log("Error during execution:", error2);
        this.stop();
      }
    }
    const now2 = LiteGraph.getTime();
    let elapsed = now2 - start2;
    if (elapsed == 0) elapsed = 1;
    this.execution_time = 1e-3 * elapsed;
    this.globaltime += 1e-3 * elapsed;
    this.iteration += 1;
    this.elapsed_time = (now2 - this.last_update_time) * 1e-3;
    this.last_update_time = now2;
    this.nodes_executing = [];
    this.nodes_actioning = [];
    this.nodes_executedAction = [];
  }
  /**
   * Updates the graph execution order according to relevance of the nodes (nodes with only outputs have more relevance than
   * nodes with only inputs.
   */
  updateExecutionOrder() {
    this._nodes_in_order = this.computeExecutionOrder(false);
    this._nodes_executable = [];
    for (const node2 of this._nodes_in_order) {
      if (node2.onExecute) {
        this._nodes_executable.push(node2);
      }
    }
  }
  // This is more internal, it computes the executable nodes in order and returns it
  computeExecutionOrder(only_onExecute, set_level) {
    const L2 = [];
    const S2 = [];
    const M2 = {};
    const visited_links = {};
    const remaining_links = {};
    for (const node2 of this._nodes) {
      if (only_onExecute && !node2.onExecute) {
        continue;
      }
      M2[node2.id] = node2;
      let num = 0;
      if (node2.inputs) {
        for (const input of node2.inputs) {
          if (input?.link != null) {
            num += 1;
          }
        }
      }
      if (num == 0) {
        S2.push(node2);
        if (set_level) node2._level = 1;
      } else {
        if (set_level) node2._level = 0;
        remaining_links[node2.id] = num;
      }
    }
    while (true) {
      const node2 = S2.shift();
      if (node2 === void 0) break;
      L2.push(node2);
      delete M2[node2.id];
      if (!node2.outputs) continue;
      for (const output of node2.outputs) {
        if (output?.links == null || output.links.length == 0)
          continue;
        for (const link_id of output.links) {
          const link2 = this._links.get(link_id);
          if (!link2) continue;
          if (visited_links[link2.id]) continue;
          const target_node = this.getNodeById(link2.target_id);
          if (target_node == null) {
            visited_links[link2.id] = true;
            continue;
          }
          if (set_level) {
            node2._level ??= 0;
            if (!target_node._level || target_node._level <= node2._level) {
              target_node._level = node2._level + 1;
            }
          }
          visited_links[link2.id] = true;
          remaining_links[target_node.id] -= 1;
          if (remaining_links[target_node.id] == 0) S2.push(target_node);
        }
      }
    }
    for (const i2 in M2) {
      L2.push(M2[i2]);
    }
    if (L2.length != this._nodes.length && LiteGraph.debug)
      console.warn("something went wrong, nodes missing");
    function setOrder(nodes) {
      const l2 = nodes.length;
      for (let i2 = 0; i2 < l2; ++i2) {
        nodes[i2].order = i2;
      }
    }
    __name(setOrder, "setOrder");
    setOrder(L2);
    L2.sort(function(A2, B2) {
      const Ap = A2.constructor.priority || A2.priority || 0;
      const Bp = B2.constructor.priority || B2.priority || 0;
      return Ap == Bp ? A2.order - B2.order : Ap - Bp;
    });
    setOrder(L2);
    return L2;
  }
  /**
   * Positions every node in a more readable manner
   */
  arrange(margin, layout) {
    margin = margin || 100;
    const nodes = this.computeExecutionOrder(false, true);
    const columns = [];
    for (const node2 of nodes) {
      const col = node2._level || 1;
      columns[col] ||= [];
      columns[col].push(node2);
    }
    let x2 = margin;
    for (const column of columns) {
      if (!column) continue;
      let max_size = 100;
      let y2 = margin + LiteGraph.NODE_TITLE_HEIGHT;
      for (const node2 of column) {
        node2.pos[0] = layout == LiteGraph.VERTICAL_LAYOUT ? y2 : x2;
        node2.pos[1] = layout == LiteGraph.VERTICAL_LAYOUT ? x2 : y2;
        const max_size_index = layout == LiteGraph.VERTICAL_LAYOUT ? 1 : 0;
        if (node2.size[max_size_index] > max_size) {
          max_size = node2.size[max_size_index];
        }
        const node_size_index = layout == LiteGraph.VERTICAL_LAYOUT ? 0 : 1;
        y2 += node2.size[node_size_index] + margin + LiteGraph.NODE_TITLE_HEIGHT;
      }
      x2 += max_size + margin;
    }
    this.setDirtyCanvas(true, true);
  }
  /**
   * Returns the amount of time the graph has been running in milliseconds
   * @returns number of milliseconds the graph has been running
   */
  getTime() {
    return this.globaltime;
  }
  /**
   * Returns the amount of time accumulated using the fixedtime_lapse var.
   * This is used in context where the time increments should be constant
   * @returns number of milliseconds the graph has been running
   */
  getFixedTime() {
    return this.fixedtime;
  }
  /**
   * Returns the amount of time it took to compute the latest iteration.
   * Take into account that this number could be not correct
   * if the nodes are using graphical actions
   * @returns number of milliseconds it took the last cycle
   */
  getElapsedTime() {
    return this.elapsed_time;
  }
  /**
   * @deprecated Will be removed in 0.9
   * Sends an event to all the nodes, useful to trigger stuff
   * @param eventname the name of the event (function to be called)
   * @param params parameters in array format
   */
  sendEventToAllNodes(eventname, params, mode) {
    mode = mode || LGraphEventMode.ALWAYS;
    const nodes = this._nodes_in_order || this._nodes;
    if (!nodes) return;
    for (const node2 of nodes) {
      if (!node2[eventname] || node2.mode != mode) continue;
      if (params === void 0) {
        node2[eventname]();
      } else if (params && params.constructor === Array) {
        node2[eventname].apply(node2, params);
      } else {
        node2[eventname](params);
      }
    }
  }
  /**
   * Runs an action on every canvas registered to this graph.
   * @param action Action to run for every canvas
   */
  canvasAction(action) {
    const canvases = this.list_of_graphcanvas;
    if (!canvases) return;
    for (const canvas2 of canvases) action(canvas2);
  }
  /** @deprecated See {@link LGraph.canvasAction} */
  sendActionToCanvas(action, params) {
    const { list_of_graphcanvas } = this;
    if (!list_of_graphcanvas) return;
    for (const c2 of list_of_graphcanvas) {
      c2[action]?.apply(c2, params);
    }
  }
  /**
   * Adds a new node instance to this graph
   * @param node the instance of the node
   */
  add(node2, skip_compute_order) {
    if (!node2) return;
    const { state } = this;
    if (LiteGraph.alwaysSnapToGrid) {
      const snapTo = this.getSnapToGridSize();
      if (snapTo) node2.snapToGrid(snapTo);
    }
    if (node2 instanceof LGraphGroup) {
      if (node2.id == null || node2.id === -1) node2.id = ++state.lastGroupId;
      if (node2.id > state.lastGroupId) state.lastGroupId = node2.id;
      this._groups.push(node2);
      this.setDirtyCanvas(true);
      this.change();
      node2.graph = this;
      this._version++;
      return;
    }
    if (node2.id != -1 && this._nodes_by_id[node2.id] != null) {
      console.warn(
        "LiteGraph: there is already a node with this ID, changing it"
      );
      node2.id = LiteGraph.use_uuids ? LiteGraph.uuidv4() : ++state.lastNodeId;
    }
    if (this._nodes.length >= LiteGraph.MAX_NUMBER_OF_NODES) {
      throw "LiteGraph: max number of nodes in a graph reached";
    }
    if (LiteGraph.use_uuids) {
      if (node2.id == null || node2.id == -1)
        node2.id = LiteGraph.uuidv4();
    } else {
      if (node2.id == null || node2.id == -1) {
        node2.id = ++state.lastNodeId;
      } else if (typeof node2.id === "number" && state.lastNodeId < node2.id) {
        state.lastNodeId = node2.id;
      }
    }
    node2.graph = this;
    this._version++;
    this._nodes.push(node2);
    this._nodes_by_id[node2.id] = node2;
    node2.onAdded?.(this);
    if (this.config.align_to_grid) node2.alignToGrid();
    if (!skip_compute_order) this.updateExecutionOrder();
    this.onNodeAdded?.(node2);
    this.setDirtyCanvas(true);
    this.change();
    return node2;
  }
  /**
   * Removes a node from the graph
   * @param node the instance of the node
   */
  remove(node2) {
    if (node2 instanceof LGraphGroup) {
      const index2 = this._groups.indexOf(node2);
      if (index2 != -1) {
        this._groups.splice(index2, 1);
      }
      node2.graph = void 0;
      this._version++;
      this.setDirtyCanvas(true, true);
      this.change();
      return;
    }
    if (this._nodes_by_id[node2.id] == null) {
      console.warn("LiteGraph: node not found", node2);
      return;
    }
    if (node2.ignore_remove) {
      console.warn("LiteGraph: node cannot be removed", node2);
      return;
    }
    this.beforeChange();
    const { inputs, outputs } = node2;
    if (inputs) {
      for (const [i2, slot] of inputs.entries()) {
        if (slot.link != null) node2.disconnectInput(i2, true);
      }
    }
    if (outputs) {
      for (const [i2, slot] of outputs.entries()) {
        if (slot.links?.length) node2.disconnectOutput(i2);
      }
    }
    for (const link2 of this.floatingLinks.values()) {
      if (link2.origin_id === node2.id || link2.target_id === node2.id) {
        this.removeFloatingLink(link2);
      }
    }
    node2.onRemoved?.();
    node2.graph = null;
    this._version++;
    const { list_of_graphcanvas } = this;
    if (list_of_graphcanvas) {
      for (const canvas2 of list_of_graphcanvas) {
        if (canvas2.selected_nodes[node2.id])
          delete canvas2.selected_nodes[node2.id];
      }
    }
    const pos = this._nodes.indexOf(node2);
    if (pos != -1) this._nodes.splice(pos, 1);
    delete this._nodes_by_id[node2.id];
    this.onNodeRemoved?.(node2);
    this.canvasAction((c2) => c2.checkPanels());
    this.setDirtyCanvas(true, true);
    this.afterChange();
    this.change();
    this.updateExecutionOrder();
  }
  /**
   * Returns a node by its id.
   */
  getNodeById(id2) {
    return id2 != null ? this._nodes_by_id[id2] : null;
  }
  /**
   * Returns a list of nodes that matches a class
   * @param classObject the class itself (not an string)
   * @returns a list with all the nodes of this type
   */
  // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
  findNodesByClass(classObject, result) {
    result = result || [];
    result.length = 0;
    const { _nodes } = this;
    for (const node2 of _nodes) {
      if (node2.constructor === classObject)
        result.push(node2);
    }
    return result;
  }
  /**
   * Returns a list of nodes that matches a type
   * @param type the name of the node type
   * @returns a list with all the nodes of this type
   */
  findNodesByType(type, result) {
    const matchType = type.toLowerCase();
    result = result || [];
    result.length = 0;
    const { _nodes } = this;
    for (const node2 of _nodes) {
      if (node2.type?.toLowerCase() == matchType)
        result.push(node2);
    }
    return result;
  }
  /**
   * Returns the first node that matches a name in its title
   * @param title the name of the node to search
   * @returns the node or null
   */
  findNodeByTitle(title) {
    const { _nodes } = this;
    for (const node2 of _nodes) {
      if (node2.title == title)
        return node2;
    }
    return null;
  }
  /**
   * Returns a list of nodes that matches a name
   * @param title the name of the node to search
   * @returns a list with all the nodes with this name
   */
  findNodesByTitle(title) {
    const result = [];
    const { _nodes } = this;
    for (const node2 of _nodes) {
      if (node2.title == title)
        result.push(node2);
    }
    return result;
  }
  /**
   * Returns the top-most node in this position of the canvas
   * @param x the x coordinate in canvas space
   * @param y the y coordinate in canvas space
   * @param nodeList a list with all the nodes to search from, by default is all the nodes in the graph
   * @returns the node at this position or null
   */
  getNodeOnPos(x2, y2, nodeList) {
    const nodes = nodeList || this._nodes;
    let i2 = nodes.length;
    while (--i2 >= 0) {
      const node2 = nodes[i2];
      if (node2.isPointInside(x2, y2)) return node2;
    }
    return null;
  }
  /**
   * Returns the top-most group in that position
   * @param x The x coordinate in canvas space
   * @param y The y coordinate in canvas space
   * @returns The group or null
   */
  getGroupOnPos(x2, y2) {
    return this._groups.toReversed().find((g2) => g2.isPointInside(x2, y2));
  }
  /**
   * Returns the top-most group with a titlebar in the provided position.
   * @param x The x coordinate in canvas space
   * @param y The y coordinate in canvas space
   * @returns The group or null
   */
  getGroupTitlebarOnPos(x2, y2) {
    return this._groups.toReversed().find((g2) => g2.isPointInTitlebar(x2, y2));
  }
  /**
   * Finds a reroute a the given graph point
   * @param x X co-ordinate in graph space
   * @param y Y co-ordinate in graph space
   * @returns The first reroute under the given co-ordinates, or undefined
   */
  getRerouteOnPos(x2, y2, reroutes) {
    for (const reroute of reroutes ?? this.reroutes.values()) {
      if (reroute.containsPoint([x2, y2])) return reroute;
    }
  }
  /**
   * Snaps the provided items to a grid.
   *
   * Item positions are reounded to the nearest multiple of {@link LiteGraph.CANVAS_GRID_SIZE}.
   *
   * When {@link LiteGraph.alwaysSnapToGrid} is enabled
   * and the grid size is falsy, a default of 1 is used.
   * @param items The items to be snapped to the grid
   * @todo Currently only snaps nodes.
   */
  snapToGrid(items) {
    const snapTo = this.getSnapToGridSize();
    if (!snapTo) return;
    for (const item of getAllNestedItems(items)) {
      if (!item.pinned) item.snapToGrid(snapTo);
    }
  }
  /**
   * Finds the size of the grid that items should be snapped to when moved.
   * @returns The size of the grid that items should be snapped to
   */
  getSnapToGridSize() {
    return LiteGraph.alwaysSnapToGrid ? LiteGraph.CANVAS_GRID_SIZE || 1 : LiteGraph.CANVAS_GRID_SIZE;
  }
  /**
   * @deprecated Will be removed in 0.9
   * Checks that the node type matches the node type registered,
   * used when replacing a nodetype by a newer version during execution
   * this replaces the ones using the old version with the new version
   */
  checkNodeTypes() {
    const { _nodes } = this;
    for (const [i2, node2] of _nodes.entries()) {
      const ctor = LiteGraph.registered_node_types[node2.type];
      if (node2.constructor == ctor) continue;
      console.log("node being replaced by newer version:", node2.type);
      const newnode = LiteGraph.createNode(node2.type);
      if (!newnode) continue;
      _nodes[i2] = newnode;
      newnode.configure(node2.serialize());
      newnode.graph = this;
      this._nodes_by_id[newnode.id] = newnode;
      if (node2.inputs) newnode.inputs = [...node2.inputs];
      if (node2.outputs) newnode.outputs = [...node2.outputs];
    }
    this.updateExecutionOrder();
  }
  // ********** GLOBALS *****************
  trigger(action, param) {
    this.onTrigger?.(action, param);
  }
  /** @todo Clean up - never implemented. */
  triggerInput(name2, value) {
    const nodes = this.findNodesByTitle(name2);
    for (const node2 of nodes) {
      node2.onTrigger(value);
    }
  }
  /** @todo Clean up - never implemented. */
  setCallback(name2, func) {
    const nodes = this.findNodesByTitle(name2);
    for (const node2 of nodes) {
      node2.setTrigger(func);
    }
  }
  // used for undo, called before any change is made to the graph
  beforeChange(info) {
    this.onBeforeChange?.(this, info);
    this.canvasAction((c2) => c2.onBeforeChange?.(this));
  }
  // used to resend actions, called after any change is made to the graph
  afterChange(info) {
    this.onAfterChange?.(this, info);
    this.canvasAction((c2) => c2.onAfterChange?.(this));
  }
  connectionChange(node2) {
    this.updateExecutionOrder();
    this.onConnectionChange?.(node2);
    this._version++;
    this.canvasAction((c2) => c2.onConnectionChange?.());
  }
  /**
   * clears the triggered slot animation in all links (stop visual animation)
   */
  clearTriggeredSlots() {
    for (const link_info of this._links.values()) {
      if (!link_info) continue;
      if (link_info._last_time) link_info._last_time = 0;
    }
  }
  /* Called when something visually changed (not the graph!) */
  change() {
    if (LiteGraph.debug) {
      console.log("Graph changed");
    }
    this.canvasAction((c2) => c2.setDirty(true, true));
    this.on_change?.(this);
  }
  setDirtyCanvas(fg, bg) {
    this.canvasAction((c2) => c2.setDirty(fg, bg));
  }
  addFloatingLink(link2) {
    if (link2.id === -1) {
      link2.id = ++this.#lastFloatingLinkId;
    }
    this.#floatingLinks.set(link2.id, link2);
    const slot = link2.target_id !== -1 ? this.getNodeById(link2.target_id)?.inputs?.[link2.target_slot] : this.getNodeById(link2.origin_id)?.outputs?.[link2.origin_slot];
    if (slot) {
      slot._floatingLinks ??= /* @__PURE__ */ new Set();
      slot._floatingLinks.add(link2);
    } else {
      console.warn(`Adding invalid floating link: target/slot: [${link2.target_id}/${link2.target_slot}] origin/slot: [${link2.origin_id}/${link2.origin_slot}]`);
    }
    const reroutes = LLink.getReroutes(this, link2);
    for (const reroute of reroutes) {
      reroute.floatingLinkIds.add(link2.id);
    }
    return link2;
  }
  removeFloatingLink(link2) {
    this.#floatingLinks.delete(link2.id);
    const slot = link2.target_id !== -1 ? this.getNodeById(link2.target_id)?.inputs?.[link2.target_slot] : this.getNodeById(link2.origin_id)?.outputs?.[link2.origin_slot];
    if (slot) {
      slot._floatingLinks?.delete(link2);
    }
    const reroutes = LLink.getReroutes(this, link2);
    for (const reroute of reroutes) {
      reroute.floatingLinkIds.delete(link2.id);
      if (reroute.floatingLinkIds.size === 0) {
        delete reroute.floating;
      }
      if (reroute.totalLinks === 0) this.removeReroute(reroute.id);
    }
  }
  getLink(id2) {
    return id2 == null ? void 0 : this._links.get(id2);
  }
  getReroute(id2) {
    return id2 == null ? void 0 : this.reroutes.get(id2);
  }
  /**
   * Configures a reroute on the graph where ID is already known (probably deserialisation).
   * Creates the object if it does not exist.
   * @param serialisedReroute See {@link SerialisableReroute}
   */
  setReroute({ id: id2, parentId, pos, linkIds, floating }) {
    id2 ??= ++this.state.lastRerouteId;
    if (id2 > this.state.lastRerouteId) this.state.lastRerouteId = id2;
    const reroute = this.reroutes.get(id2) ?? new Reroute(id2, this);
    reroute.update(parentId, pos, linkIds, floating);
    this.reroutes.set(id2, reroute);
    return reroute;
  }
  /**
   * Creates a new reroute and adds it to the graph.
   * @param pos Position in graph space
   * @param before The existing link segment (reroute, link) that will be after this reroute,
   * going from the node output to input.
   * @returns The newly created reroute - typically ignored.
   */
  createReroute(pos, before) {
    const rerouteId = ++this.state.lastRerouteId;
    const linkIds = before instanceof Reroute ? before.linkIds : [before.id];
    const floatingLinkIds = before instanceof Reroute ? before.floatingLinkIds : [before.id];
    const reroute = new Reroute(rerouteId, this, pos, before.parentId, linkIds, floatingLinkIds);
    this.reroutes.set(rerouteId, reroute);
    for (const linkId of linkIds) {
      const link2 = this._links.get(linkId);
      if (!link2) continue;
      if (link2.parentId === before.parentId) link2.parentId = rerouteId;
      const reroutes = LLink.getReroutes(this, link2);
      for (const x2 of reroutes.filter((x22) => x22.parentId === before.parentId)) {
        x2.parentId = rerouteId;
      }
    }
    for (const linkId of floatingLinkIds) {
      const link2 = this.floatingLinks.get(linkId);
      if (!link2) continue;
      if (link2.parentId === before.parentId) link2.parentId = rerouteId;
      const reroutes = LLink.getReroutes(this, link2);
      for (const x2 of reroutes.filter((x22) => x22.parentId === before.parentId)) {
        x2.parentId = rerouteId;
      }
    }
    return reroute;
  }
  /**
   * Removes a reroute from the graph
   * @param id ID of reroute to remove
   */
  removeReroute(id2) {
    const { reroutes } = this;
    const reroute = reroutes.get(id2);
    if (!reroute) return;
    const { parentId, linkIds, floatingLinkIds } = reroute;
    for (const reroute2 of reroutes.values()) {
      if (reroute2.parentId === id2) reroute2.parentId = parentId;
    }
    for (const linkId of linkIds) {
      const link2 = this._links.get(linkId);
      if (link2 && link2.parentId === id2) link2.parentId = parentId;
    }
    for (const linkId of floatingLinkIds) {
      const link2 = this.floatingLinks.get(linkId);
      if (!link2) {
        console.warn(`Removed reroute had floating link ID that did not exist [${linkId}]`);
        continue;
      }
      const floatingReroutes = LLink.getReroutes(this, link2);
      const lastReroute = floatingReroutes.at(-1);
      const secondLastReroute = floatingReroutes.at(-2);
      if (reroute !== lastReroute) {
        continue;
      } else if (secondLastReroute?.totalLinks !== 1) {
        this.removeFloatingLink(link2);
      } else if (link2.parentId === id2) {
        link2.parentId = parentId;
        secondLastReroute.floating = reroute.floating;
      }
    }
    reroutes.delete(id2);
    this.setDirtyCanvas(false, true);
  }
  /**
   * Destroys a link
   */
  removeLink(link_id) {
    const link2 = this._links.get(link_id);
    if (!link2) return;
    const node2 = this.getNodeById(link2.target_id);
    node2?.disconnectInput(link2.target_slot, false);
    link2.disconnect(this);
  }
  /**
   * Creates a Object containing all the info about this graph, it can be serialized
   * @deprecated Use {@link asSerialisable}, which returns the newer schema version.
   * @returns value of the node
   */
  serialize(option) {
    const { config: config2, state, groups, nodes, reroutes, extra, floatingLinks } = this.asSerialisable(option);
    const linkArray = [...this._links.values()];
    const links = linkArray.map((x2) => x2.serialize());
    if (reroutes?.length) {
      extra.linkExtensions = linkArray.filter((x2) => x2.parentId !== void 0).map((x2) => ({ id: x2.id, parentId: x2.parentId }));
    }
    extra.reroutes = reroutes?.length ? reroutes : void 0;
    return {
      id: this.id,
      revision: this.revision,
      last_node_id: state.lastNodeId,
      last_link_id: state.lastLinkId,
      nodes,
      links,
      floatingLinks,
      groups,
      config: config2,
      extra,
      version: LiteGraph.VERSION
    };
  }
  /** @returns The drag and scale state of the first attached canvas, otherwise `undefined`. */
  #getDragAndScale() {
    const ds = this.list_of_graphcanvas?.at(0)?.ds;
    if (ds) return { scale: ds.scale, offset: ds.offset };
  }
  /**
   * Prepares a shallow copy of this object for immediate serialisation or structuredCloning.
   * The return value should be discarded immediately.
   * @param options Serialise options = currently `sortNodes: boolean`, whether to sort nodes by ID.
   * @returns A shallow copy of parts of this graph, with shallow copies of its serialisable objects.
   * Mutating the properties of the return object may result in changes to your graph.
   * It is intended for use with {@link structuredClone} or {@link JSON.stringify}.
   */
  asSerialisable(options2) {
    const { id: id2, revision, config: config2, state } = this;
    const nodeList = !LiteGraph.use_uuids && options2?.sortNodes ? [...this._nodes].sort((a2, b2) => a2.id - b2.id) : this._nodes;
    const nodes = nodeList.map((node2) => node2.serialize());
    const groups = this._groups.map((x2) => x2.serialize());
    const links = this._links.size ? [...this._links.values()].map((x2) => x2.asSerialisable()) : void 0;
    const floatingLinks = this.floatingLinks.size ? [...this.floatingLinks.values()].map((x2) => x2.asSerialisable()) : void 0;
    const reroutes = this.reroutes.size ? [...this.reroutes.values()].map((x2) => x2.asSerialisable()) : void 0;
    const extra = { ...this.extra };
    if (LiteGraph.saveViewportWithGraph) extra.ds = this.#getDragAndScale();
    if (!extra.ds) delete extra.ds;
    const data = {
      id: id2,
      revision,
      version: LGraph.serialisedSchemaVersion,
      config: config2,
      state,
      groups,
      nodes,
      links,
      floatingLinks,
      reroutes,
      extra
    };
    this.onSerialize?.(data);
    return data;
  }
  /**
   * Configure a graph from a JSON string
   * @param data The deserialised object to configure this graph from
   * @param keep_old If `true`, the graph will not be cleared prior to
   * adding the configuration.
   */
  configure(data, keep_old) {
    if (!data) return;
    if (!keep_old) this.clear();
    if (data.id) this.id = data.id;
    else if (this.id === zeroUuid) this.id = createUuidv4();
    let reroutes;
    if (data.version === 0.4) {
      const { extra } = data;
      if (Array.isArray(data.links)) {
        for (const linkData of data.links) {
          const link2 = LLink.createFromArray(linkData);
          this._links.set(link2.id, link2);
        }
      }
      if (Array.isArray(extra?.linkExtensions)) {
        for (const linkEx of extra.linkExtensions) {
          const link2 = this._links.get(linkEx.id);
          if (link2) link2.parentId = linkEx.parentId;
        }
      }
      reroutes = extra?.reroutes;
    } else {
      if (data.state) {
        const { lastGroupId, lastLinkId, lastNodeId, lastRerouteId } = data.state;
        const { state } = this;
        if (lastGroupId != null) state.lastGroupId = lastGroupId;
        if (lastLinkId != null) state.lastLinkId = lastLinkId;
        if (lastNodeId != null) state.lastNodeId = lastNodeId;
        if (lastRerouteId != null) state.lastRerouteId = lastRerouteId;
      }
      if (Array.isArray(data.links)) {
        for (const linkData of data.links) {
          const link2 = LLink.create(linkData);
          this._links.set(link2.id, link2);
        }
      }
      reroutes = data.reroutes;
    }
    if (Array.isArray(reroutes)) {
      for (const rerouteData of reroutes) {
        this.setReroute(rerouteData);
      }
    }
    const nodesData = data.nodes;
    for (const i2 in data) {
      if (["nodes", "groups", "links", "state", "reroutes", "floatingLinks", "id"].includes(i2)) {
        continue;
      }
      this[i2] = data[i2];
    }
    let error2 = false;
    this._nodes = [];
    if (nodesData) {
      for (const n_info of nodesData) {
        let node2 = LiteGraph.createNode(String(n_info.type), n_info.title);
        if (!node2) {
          if (LiteGraph.debug) console.log("Node not found or has errors:", n_info.type);
          node2 = new LGraphNode("");
          node2.last_serialization = n_info;
          node2.has_errors = true;
          error2 = true;
        }
        node2.id = n_info.id;
        this.add(node2, true);
      }
      for (const n_info of nodesData) {
        const node2 = this.getNodeById(n_info.id);
        node2?.configure(n_info);
      }
    }
    if (Array.isArray(data.floatingLinks)) {
      for (const linkData of data.floatingLinks) {
        const floatingLink = LLink.create(linkData);
        this.addFloatingLink(floatingLink);
        if (floatingLink.id > this.#lastFloatingLinkId) this.#lastFloatingLinkId = floatingLink.id;
      }
    }
    for (const reroute of this.reroutes.values()) {
      if (!reroute.validateLinks(this._links, this.floatingLinks)) {
        this.reroutes.delete(reroute.id);
      }
    }
    this._groups.length = 0;
    const groupData = data.groups;
    if (groupData) {
      for (const data2 of groupData) {
        const group = new LiteGraph.LGraphGroup();
        group.configure(data2);
        this.add(group);
      }
    }
    this.updateExecutionOrder();
    this.extra = data.extra || {};
    delete this.extra.linkExtensions;
    this.onConfigure?.(data);
    this._version++;
    this.setDirtyCanvas(true, true);
    return error2;
  }
  load(url, callback) {
    const that = this;
    if (url instanceof Blob || url instanceof File) {
      const reader = new FileReader();
      reader.addEventListener("load", function(event) {
        const result = stringOrEmpty(event.target?.result);
        const data = JSON.parse(result);
        that.configure(data);
        callback?.();
      });
      reader.readAsText(url);
      return;
    }
    const req = new XMLHttpRequest();
    req.open("GET", url, true);
    req.send(null);
    req.addEventListener("load", function() {
      if (req.status !== 200) {
        console.error("Error loading graph:", req.status, req.response);
        return;
      }
      const data = JSON.parse(req.response);
      that.configure(data);
      callback?.();
    });
    req.addEventListener("error", (err) => {
      console.error("Error loading graph:", err);
    });
  }
}
class LiteGraphGlobal {
  static {
    __name(this, "LiteGraphGlobal");
  }
  // Enums
  SlotShape = SlotShape;
  SlotDirection = SlotDirection;
  SlotType = SlotType;
  LabelPosition = LabelPosition;
  /** Used in serialised graphs at one point. */
  VERSION = 0.4;
  CANVAS_GRID_SIZE = 10;
  NODE_TITLE_HEIGHT = 30;
  NODE_TITLE_TEXT_Y = 20;
  NODE_SLOT_HEIGHT = 20;
  NODE_WIDGET_HEIGHT = 20;
  NODE_WIDTH = 140;
  NODE_MIN_WIDTH = 50;
  NODE_COLLAPSED_RADIUS = 10;
  NODE_COLLAPSED_WIDTH = 80;
  NODE_TITLE_COLOR = "#999";
  NODE_SELECTED_TITLE_COLOR = "#FFF";
  NODE_TEXT_SIZE = 14;
  NODE_TEXT_COLOR = "#AAA";
  NODE_TEXT_HIGHLIGHT_COLOR = "#EEE";
  NODE_SUBTEXT_SIZE = 12;
  NODE_DEFAULT_COLOR = "#333";
  NODE_DEFAULT_BGCOLOR = "#353535";
  NODE_DEFAULT_BOXCOLOR = "#666";
  NODE_DEFAULT_SHAPE = RenderShape.ROUND;
  NODE_BOX_OUTLINE_COLOR = "#FFF";
  NODE_ERROR_COLOUR = "#E00";
  NODE_FONT = "Arial";
  DEFAULT_FONT = "Arial";
  DEFAULT_SHADOW_COLOR = "rgba(0,0,0,0.5)";
  DEFAULT_GROUP_FONT = 24;
  DEFAULT_GROUP_FONT_SIZE;
  GROUP_FONT = "Arial";
  WIDGET_BGCOLOR = "#222";
  WIDGET_OUTLINE_COLOR = "#666";
  WIDGET_ADVANCED_OUTLINE_COLOR = "rgba(56, 139, 253, 0.8)";
  WIDGET_TEXT_COLOR = "#DDD";
  WIDGET_SECONDARY_TEXT_COLOR = "#999";
  WIDGET_DISABLED_TEXT_COLOR = "#666";
  LINK_COLOR = "#9A9";
  EVENT_LINK_COLOR = "#A86";
  CONNECTING_LINK_COLOR = "#AFA";
  /** avoid infinite loops */
  MAX_NUMBER_OF_NODES = 1e4;
  /** default node position */
  DEFAULT_POSITION = [100, 100];
  /** ,"circle" */
  VALID_SHAPES = ["default", "box", "round", "card"];
  ROUND_RADIUS = 8;
  // shapes are used for nodes but also for slots
  BOX_SHAPE = RenderShape.BOX;
  ROUND_SHAPE = RenderShape.ROUND;
  CIRCLE_SHAPE = RenderShape.CIRCLE;
  CARD_SHAPE = RenderShape.CARD;
  ARROW_SHAPE = RenderShape.ARROW;
  /** intended for slot arrays */
  GRID_SHAPE = RenderShape.GRID;
  // enums
  INPUT = NodeSlotType.INPUT;
  OUTPUT = NodeSlotType.OUTPUT;
  // TODO: -1 can lead to ambiguity in JS; these should be updated to a more explicit constant or Symbol.
  /** for outputs */
  EVENT = -1;
  /** for inputs */
  ACTION = -1;
  /** helper, will add "On Request" and more in the future */
  NODE_MODES = ["Always", "On Event", "Never", "On Trigger"];
  /** use with node_box_coloured_by_mode */
  NODE_MODES_COLORS = ["#666", "#422", "#333", "#224", "#626"];
  ALWAYS = LGraphEventMode.ALWAYS;
  ON_EVENT = LGraphEventMode.ON_EVENT;
  NEVER = LGraphEventMode.NEVER;
  ON_TRIGGER = LGraphEventMode.ON_TRIGGER;
  UP = LinkDirection.UP;
  DOWN = LinkDirection.DOWN;
  LEFT = LinkDirection.LEFT;
  RIGHT = LinkDirection.RIGHT;
  CENTER = LinkDirection.CENTER;
  /** helper */
  LINK_RENDER_MODES = ["Straight", "Linear", "Spline"];
  HIDDEN_LINK = LinkRenderType.HIDDEN_LINK;
  STRAIGHT_LINK = LinkRenderType.STRAIGHT_LINK;
  LINEAR_LINK = LinkRenderType.LINEAR_LINK;
  SPLINE_LINK = LinkRenderType.SPLINE_LINK;
  NORMAL_TITLE = TitleMode.NORMAL_TITLE;
  NO_TITLE = TitleMode.NO_TITLE;
  TRANSPARENT_TITLE = TitleMode.TRANSPARENT_TITLE;
  AUTOHIDE_TITLE = TitleMode.AUTOHIDE_TITLE;
  /** arrange nodes vertically */
  VERTICAL_LAYOUT = "vertical";
  /** used to redirect calls */
  proxy = null;
  node_images_path = "";
  debug = false;
  catch_exceptions = true;
  throw_errors = true;
  /** if set to true some nodes like Formula would be allowed to evaluate code that comes from unsafe sources (like node configuration), which could lead to exploits */
  allow_scripts = false;
  /** nodetypes by string */
  registered_node_types = {};
  /** @deprecated used for dropping files in the canvas.  It appears the code that enables this was removed, but the object remains and is references by built-in drag drop. */
  node_types_by_file_extension = {};
  /** node types by classname */
  Nodes = {};
  /** used to store vars between graphs */
  Globals = {};
  /** @deprecated Unused and will be deleted. */
  searchbox_extras = {};
  /** [true!] this make the nodes box (top left circle) coloured when triggered (execute/action), visual feedback */
  node_box_coloured_when_on = false;
  /** [true!] nodebox based on node mode, visual feedback */
  node_box_coloured_by_mode = false;
  /** [false on mobile] better true if not touch device, TODO add an helper/listener to close if false */
  dialog_close_on_mouse_leave = false;
  dialog_close_on_mouse_leave_delay = 500;
  /** [false!] prefer false if results too easy to break links - implement with ALT or TODO custom keys */
  shift_click_do_break_link_from = false;
  /** [false!]prefer false, way too easy to break links */
  click_do_break_link_to = false;
  /** [true!] who accidentally ctrl-alt-clicks on an in/output? nobody! that's who! */
  ctrl_alt_click_do_break_link = true;
  /** [true!] snaps links when dragging connections over valid targets */
  snaps_for_comfy = true;
  /** [true!] renders a partial border to highlight when a dragged link is snapped to a node */
  snap_highlights_node = true;
  /**
   * If `true`, items always snap to the grid - modifier keys are ignored.
   * When {@link snapToGrid} is falsy, a value of `1` is used.
   * Default: `false`
   */
  alwaysSnapToGrid;
  /**
   * When set to a positive number, when nodes are moved their positions will
   * be rounded to the nearest multiple of this value.  Half up.
   * Default: `undefined`
   * @todo Not implemented - see {@link LiteGraph.CANVAS_GRID_SIZE}
   */
  snapToGrid;
  /** [false on mobile] better true if not touch device, TODO add an helper/listener to close if false */
  search_hide_on_mouse_leave = true;
  /**
   * [true!] enable filtering slots type in the search widget
   * !requires auto_load_slot_types or manual set registered_slot_[in/out]_types and slot_types_[in/out]
   */
  search_filter_enabled = false;
  /** [true!] opens the results list when opening the search widget */
  search_show_all_on_open = true;
  /**
   * [if want false, use true, run, get vars values to be statically set, than disable]
   * nodes types and nodeclass association with node types need to be calculated,
   * if dont want this, calculate once and set registered_slot_[in/out]_types and slot_types_[in/out]
   */
  auto_load_slot_types = false;
  // set these values if not using auto_load_slot_types
  /** slot types for nodeclass */
  registered_slot_in_types = {};
  /** slot types for nodeclass */
  registered_slot_out_types = {};
  /** slot types IN */
  slot_types_in = [];
  /** slot types OUT */
  slot_types_out = [];
  /**
   * specify for each IN slot type a(/many) default node(s), use single string, array, or object
   * (with node, title, parameters, ..) like for search
   */
  slot_types_default_in = {};
  /**
   * specify for each OUT slot type a(/many) default node(s), use single string, array, or object
   * (with node, title, parameters, ..) like for search
   */
  slot_types_default_out = {};
  /** [true!] very handy, ALT click to clone and drag the new node */
  alt_drag_do_clone_nodes = false;
  /**
   * [true!] will create and connect event slots when using action/events connections,
   * !WILL CHANGE node mode when using onTrigger (enable mode colors), onExecuted does not need this
   */
  do_add_triggers_slots = false;
  /** [false!] being events, it is strongly reccomended to use them sequentially, one by one */
  allow_multi_output_for_events = true;
  /** [true!] allows to create and connect a ndoe clicking with the third button (wheel) */
  middle_click_slot_add_default_node = false;
  /** [true!] dragging a link to empty space will open a menu, add from list, search or defaults */
  release_link_on_empty_shows_menu = false;
  /** "mouse"|"pointer" use mouse for retrocompatibility issues? (none found @ now) */
  pointerevents_method = "pointer";
  /**
   * [true!] allows ctrl + shift + v to paste nodes with the outputs of the unselected nodes connected
   * with the inputs of the newly pasted nodes
   */
  ctrl_shift_v_paste_connect_unselected_outputs = true;
  // if true, all newly created nodes/links will use string UUIDs for their id fields instead of integers.
  // use this if you must have node IDs that are unique across all graphs and subgraphs.
  use_uuids = false;
  // Whether to highlight the bounding box of selected groups
  highlight_selected_group = true;
  /** Whether to scale context with the graph when zooming in.  Zooming out never makes context menus smaller. */
  context_menu_scaling = false;
  /**
   * Debugging flag. Repeats deprecation warnings every time they are reported.
   * May impact performance.
   */
  alwaysRepeatWarnings = false;
  /**
   * Array of callbacks to execute when Litegraph first reports a deprecated API being used.
   * @see alwaysRepeatWarnings By default, will not repeat identical messages.
   */
  onDeprecationWarning = [console.warn];
  /**
   * If `true`, mouse wheel events will be interpreted as trackpad gestures.
   * Tested on MacBook M4 Pro.
   * @default false
   * @see macGesturesRequireMac
   */
  macTrackpadGestures = false;
  /**
   * If both this setting and {@link macTrackpadGestures} are `true`, trackpad gestures will
   * only be enabled when the browser user agent includes "Mac".
   * @default true
   * @see macTrackpadGestures
   */
  macGesturesRequireMac = true;
  /**
   * If `true`, widget labels and values will both be truncated (proportionally to size),
   * until they fit within the widget.
   *
   * Otherwise, the label will be truncated completely before the value is truncated.
   * @default false
   */
  truncateWidgetTextEvenly = false;
  /**
   * If `true`, widget values will be completely truncated when shrinking a widget,
   * before truncating widget labels.  {@link truncateWidgetTextEvenly} must be `false`.
   * @default false
   */
  truncateWidgetValuesFirst = false;
  /**
   * If `true`, the current viewport scale & offset of the first attached canvas will be included with the graph when exporting.
   * @default true
   */
  saveViewportWithGraph = true;
  // TODO: Remove legacy accessors
  LGraph = LGraph;
  LLink = LLink;
  LGraphNode = LGraphNode;
  LGraphGroup = LGraphGroup;
  DragAndScale = DragAndScale;
  LGraphCanvas = LGraphCanvas;
  ContextMenu = ContextMenu;
  CurveEditor = CurveEditor;
  Reroute = Reroute;
  InputIndicators = InputIndicators;
  /**
   * Register a node class so it can be listed when the user wants to create a new one
   * @param type name of the node and path
   * @param base_class class containing the structure of a node
   */
  registerNodeType(type, base_class) {
    if (!base_class.prototype)
      throw "Cannot register a simple object, it must be a class with a prototype";
    base_class.type = type;
    if (this.debug) console.log("Node registered:", type);
    const classname = base_class.name;
    const pos = type.lastIndexOf("/");
    base_class.category = type.substring(0, pos);
    base_class.title ||= classname;
    for (const i2 in LGraphNode.prototype) {
      base_class.prototype[i2] ||= LGraphNode.prototype[i2];
    }
    const prev = this.registered_node_types[type];
    if (prev && this.debug) {
      console.log("replacing node type:", type);
    }
    this.registered_node_types[type] = base_class;
    if (base_class.constructor.name) this.Nodes[classname] = base_class;
    this.onNodeTypeRegistered?.(type, base_class);
    if (prev) this.onNodeTypeReplaced?.(type, base_class, prev);
    if (base_class.prototype.onPropertyChange)
      console.warn(`LiteGraph node class ${type} has onPropertyChange method, it must be called onPropertyChanged with d at the end`);
    if (this.auto_load_slot_types) new base_class(base_class.title || "tmpnode");
  }
  /**
   * removes a node type from the system
   * @param type name of the node or the node constructor itself
   */
  unregisterNodeType(type) {
    const base_class = typeof type === "string" ? this.registered_node_types[type] : type;
    if (!base_class) throw `node type not found: ${String(type)}`;
    delete this.registered_node_types[String(base_class.type)];
    const name2 = base_class.constructor.name;
    if (name2) delete this.Nodes[name2];
  }
  /**
   * Save a slot type and his node
   * @param type name of the node or the node constructor itself
   * @param slot_type name of the slot type (variable type), eg. string, number, array, boolean, ..
   */
  registerNodeAndSlotType(type, slot_type, out) {
    out ||= false;
    const base_class = typeof type === "string" && this.registered_node_types[type] !== "anonymous" ? this.registered_node_types[type] : type;
    const class_type = base_class.constructor.type;
    let allTypes = [];
    if (typeof slot_type === "string") {
      allTypes = slot_type.split(",");
    } else if (slot_type == this.EVENT || slot_type == this.ACTION) {
      allTypes = ["_event_"];
    } else {
      allTypes = ["*"];
    }
    for (let slotType of allTypes) {
      if (slotType === "") slotType = "*";
      const register2 = out ? this.registered_slot_out_types : this.registered_slot_in_types;
      register2[slotType] ??= { nodes: [] };
      const { nodes } = register2[slotType];
      if (!nodes.includes(class_type)) nodes.push(class_type);
      const types = out ? this.slot_types_out : this.slot_types_in;
      const type2 = slotType.toLowerCase();
      if (!types.includes(type2)) {
        types.push(type2);
        types.sort();
      }
    }
  }
  /**
   * Removes all previously registered node's types
   */
  clearRegisteredTypes() {
    this.registered_node_types = {};
    this.node_types_by_file_extension = {};
    this.Nodes = {};
    this.searchbox_extras = {};
  }
  /**
   * Create a node of a given type with a name. The node is not attached to any graph yet.
   * @param type full name of the node class. p.e. "math/sin"
   * @param title a name to distinguish from other nodes
   * @param options to set options
   */
  createNode(type, title, options2) {
    const base_class = this.registered_node_types[type];
    if (!base_class) {
      if (this.debug) console.log(`GraphNode type "${type}" not registered.`);
      return null;
    }
    title = title || base_class.title || type;
    let node2 = null;
    if (this.catch_exceptions) {
      try {
        node2 = new base_class(title);
      } catch (error2) {
        console.error(error2);
        return null;
      }
    } else {
      node2 = new base_class(title);
    }
    node2.type = type;
    if (!node2.title && title) node2.title = title;
    node2.properties ||= {};
    node2.properties_info ||= [];
    node2.flags ||= {};
    node2.size ||= node2.computeSize();
    node2.pos ||= [this.DEFAULT_POSITION[0], this.DEFAULT_POSITION[1]];
    node2.mode ||= LGraphEventMode.ALWAYS;
    if (options2) {
      for (const i2 in options2) {
        node2[i2] = options2[i2];
      }
    }
    node2.onNodeCreated?.();
    return node2;
  }
  /**
   * Returns a registered node type with a given name
   * @param type full name of the node class. p.e. "math/sin"
   * @returns the node class
   */
  getNodeType(type) {
    return this.registered_node_types[type];
  }
  /**
   * Returns a list of node types matching one category
   * @param category category name
   * @returns array with all the node classes
   */
  getNodeTypesInCategory(category, filter3) {
    const r2 = [];
    for (const i2 in this.registered_node_types) {
      const type = this.registered_node_types[i2];
      if (type.filter != filter3) continue;
      if (category == "") {
        if (type.category == null) r2.push(type);
      } else if (type.category == category) {
        r2.push(type);
      }
    }
    return r2;
  }
  /**
   * Returns a list with all the node type categories
   * @param filter only nodes with ctor.filter equal can be shown
   * @returns array with all the names of the categories
   */
  getNodeTypesCategories(filter3) {
    const categories = { "": 1 };
    for (const i2 in this.registered_node_types) {
      const type = this.registered_node_types[i2];
      if (type.category && !type.skip_list) {
        if (type.filter != filter3) continue;
        categories[type.category] = 1;
      }
    }
    const result = [];
    for (const i2 in categories) {
      result.push(i2);
    }
    return result;
  }
  // debug purposes: reloads all the js scripts that matches a wildcard
  reloadNodes(folder_wildcard) {
    const tmp = document.getElementsByTagName("script");
    const script_files = [];
    for (const element of tmp) {
      script_files.push(element);
    }
    const docHeadObj = document.getElementsByTagName("head")[0];
    folder_wildcard = document.location.href + folder_wildcard;
    for (const script_file of script_files) {
      const src = script_file.src;
      if (!src || src.substr(0, folder_wildcard.length) != folder_wildcard)
        continue;
      try {
        if (this.debug) console.log("Reloading:", src);
        const dynamicScript = document.createElement("script");
        dynamicScript.type = "text/javascript";
        dynamicScript.src = src;
        docHeadObj.append(dynamicScript);
        script_file.remove();
      } catch (error2) {
        if (this.throw_errors) throw error2;
        if (this.debug) console.log("Error while reloading", src);
      }
    }
    if (this.debug) console.log("Nodes reloaded");
  }
  // separated just to improve if it doesn't work
  /** @deprecated Prefer {@link structuredClone} */
  cloneObject(obj, target) {
    if (obj == null) return null;
    const r2 = JSON.parse(JSON.stringify(obj));
    if (!target) return r2;
    for (const i2 in r2) {
      target[i2] = r2[i2];
    }
    return target;
  }
  /** @see {@link createUuidv4} @inheritdoc */
  uuidv4 = createUuidv4;
  /**
   * Returns if the types of two slots are compatible (taking into account wildcards, etc)
   * @param type_a output
   * @param type_b input
   * @returns true if they can be connected
   */
  isValidConnection(type_a, type_b) {
    if (type_a == "" || type_a === "*") type_a = 0;
    if (type_b == "" || type_b === "*") type_b = 0;
    if (!type_a || !type_b || type_a == type_b || type_a == this.EVENT && type_b == this.ACTION) {
      return true;
    }
    type_a = String(type_a);
    type_b = String(type_b);
    type_a = type_a.toLowerCase();
    type_b = type_b.toLowerCase();
    if (!type_a.includes(",") && !type_b.includes(","))
      return type_a == type_b;
    const supported_types_a = type_a.split(",");
    const supported_types_b = type_b.split(",");
    for (const a2 of supported_types_a) {
      for (const b2 of supported_types_b) {
        if (this.isValidConnection(a2, b2))
          return true;
      }
    }
    return false;
  }
  // used to create nodes from wrapping functions
  getParameterNames(func) {
    return String(func).replaceAll(/\/\/.*$/gm, "").replaceAll(/\s+/g, "").replaceAll(/\/\*[^*/]*\*\//g, "").split("){", 1)[0].replace(/^[^(]*\(/, "").replaceAll(/=[^,]+/g, "").split(",").filter(Boolean);
  }
  /* helper for interaction: pointer, touch, mouse Listeners
    used by LGraphCanvas DragAndScale ContextMenu */
  pointerListenerAdd(oDOM, sEvIn, fCall, capture = false) {
    if (!oDOM || !oDOM.addEventListener || !sEvIn || typeof fCall !== "function") return;
    let sMethod = this.pointerevents_method;
    let sEvent = sEvIn;
    if (sMethod == "pointer" && !window.PointerEvent) {
      console.warn("sMethod=='pointer' && !window.PointerEvent");
      console.log(`Converting pointer[${sEvent}] : down move up cancel enter TO touchstart touchmove touchend, etc ..`);
      switch (sEvent) {
        case "down": {
          sMethod = "touch";
          sEvent = "start";
          break;
        }
        case "move": {
          sMethod = "touch";
          break;
        }
        case "up": {
          sMethod = "touch";
          sEvent = "end";
          break;
        }
        case "cancel": {
          sMethod = "touch";
          break;
        }
        case "enter": {
          console.log("debug: Should I send a move event?");
          break;
        }
        default: {
          console.warn(`PointerEvent not available in this browser ? The event ${sEvent} would not be called`);
        }
      }
    }
    switch (sEvent) {
      case "down":
      case "up":
      case "move":
      case "over":
      case "out":
      case "enter": {
        oDOM.addEventListener(sMethod + sEvent, fCall, capture);
      }
      case "leave":
      case "cancel":
      case "gotpointercapture":
      case "lostpointercapture": {
        if (sMethod != "mouse") {
          return oDOM.addEventListener(sMethod + sEvent, fCall, capture);
        }
      }
      default:
        return oDOM.addEventListener(sEvent, fCall, capture);
    }
  }
  pointerListenerRemove(oDOM, sEvent, fCall, capture = false) {
    if (!oDOM || !oDOM.removeEventListener || !sEvent || typeof fCall !== "function") return;
    switch (sEvent) {
      case "down":
      case "up":
      case "move":
      case "over":
      case "out":
      case "enter": {
        if (this.pointerevents_method == "pointer" || this.pointerevents_method == "mouse") {
          oDOM.removeEventListener(this.pointerevents_method + sEvent, fCall, capture);
        }
      }
      case "leave":
      case "cancel":
      case "gotpointercapture":
      case "lostpointercapture": {
        if (this.pointerevents_method == "pointer") {
          return oDOM.removeEventListener(this.pointerevents_method + sEvent, fCall, capture);
        }
      }
      default:
        return oDOM.removeEventListener(sEvent, fCall, capture);
    }
  }
  getTime() {
    return performance.now();
  }
  distance = distance;
  colorToString(c2) {
    return `rgba(${Math.round(c2[0] * 255).toFixed()},${Math.round(c2[1] * 255).toFixed()},${Math.round(c2[2] * 255).toFixed()},${c2.length == 4 ? c2[3].toFixed(2) : "1.0"})`;
  }
  isInsideRectangle = isInsideRectangle;
  // [minx,miny,maxx,maxy]
  growBounding(bounding, x2, y2) {
    if (x2 < bounding[0]) {
      bounding[0] = x2;
    } else if (x2 > bounding[2]) {
      bounding[2] = x2;
    }
    if (y2 < bounding[1]) {
      bounding[1] = y2;
    } else if (y2 > bounding[3]) {
      bounding[3] = y2;
    }
  }
  overlapBounding = overlapBounding;
  // point inside bounding box
  isInsideBounding(p2, bb) {
    if (p2[0] < bb[0][0] || p2[1] < bb[0][1] || p2[0] > bb[1][0] || p2[1] > bb[1][1]) {
      return false;
    }
    return true;
  }
  // Convert a hex value to its decimal value - the inputted hex must be in the
  // format of a hex triplet - the kind we use for HTML colours. The function
  // will return an array with three values.
  hex2num(hex) {
    if (hex.charAt(0) == "#") {
      hex = hex.slice(1);
    }
    hex = hex.toUpperCase();
    const hex_alphabets = "0123456789ABCDEF";
    const value = new Array(3);
    let k2 = 0;
    let int1, int2;
    for (let i2 = 0; i2 < 6; i2 += 2) {
      int1 = hex_alphabets.indexOf(hex.charAt(i2));
      int2 = hex_alphabets.indexOf(hex.charAt(i2 + 1));
      value[k2] = int1 * 16 + int2;
      k2++;
    }
    return value;
  }
  // Give a array with three values as the argument and the function will return
  // the corresponding hex triplet.
  num2hex(triplet) {
    const hex_alphabets = "0123456789ABCDEF";
    let hex = "#";
    let int1, int2;
    for (let i2 = 0; i2 < 3; i2++) {
      int1 = triplet[i2] / 16;
      int2 = triplet[i2] % 16;
      hex += hex_alphabets.charAt(int1) + hex_alphabets.charAt(int2);
    }
    return hex;
  }
  closeAllContextMenus(ref_window = window) {
    const elements = [...ref_window.document.querySelectorAll(".litecontextmenu")];
    if (!elements.length) return;
    for (const element of elements) {
      if ("close" in element && typeof element.close === "function") {
        element.close();
      } else {
        element.remove();
      }
    }
  }
  extendClass(target, origin2) {
    for (const i2 in origin2) {
      if (target.hasOwnProperty(i2)) continue;
      target[i2] = origin2[i2];
    }
    if (origin2.prototype) {
      for (const i2 in origin2.prototype) {
        if (!origin2.prototype.hasOwnProperty(i2)) continue;
        if (target.prototype.hasOwnProperty(i2)) continue;
        if (origin2.prototype.__lookupGetter__(i2)) {
          target.prototype.__defineGetter__(
            i2,
            origin2.prototype.__lookupGetter__(i2)
          );
        } else {
          target.prototype[i2] = origin2.prototype[i2];
        }
        if (origin2.prototype.__lookupSetter__(i2)) {
          target.prototype.__defineSetter__(
            i2,
            origin2.prototype.__lookupSetter__(i2)
          );
        }
      }
    }
  }
}
Symbol.dispose ??= Symbol("Symbol.dispose");
Symbol.asyncDispose ??= Symbol("Symbol.asyncDispose");
function loadPolyfills() {
  if (typeof window != "undefined" && window.CanvasRenderingContext2D && !window.CanvasRenderingContext2D.prototype.roundRect) {
    window.CanvasRenderingContext2D.prototype.roundRect = function(x2, y2, w2, h2, radius, radius_low) {
      let top_left_radius = 0;
      let top_right_radius = 0;
      let bottom_left_radius = 0;
      let bottom_right_radius = 0;
      if (radius === 0) {
        this.rect(x2, y2, w2, h2);
        return;
      }
      if (radius_low === void 0) radius_low = radius;
      if (Array.isArray(radius)) {
        if (radius.length == 1) {
          top_left_radius = top_right_radius = bottom_left_radius = bottom_right_radius = radius[0];
        } else if (radius.length == 2) {
          top_left_radius = bottom_right_radius = radius[0];
          top_right_radius = bottom_left_radius = radius[1];
        } else if (radius.length == 4) {
          top_left_radius = radius[0];
          top_right_radius = radius[1];
          bottom_left_radius = radius[2];
          bottom_right_radius = radius[3];
        } else {
          return;
        }
      } else {
        top_left_radius = radius || 0;
        top_right_radius = radius || 0;
        const low = !Array.isArray(radius_low) && radius_low ? radius_low : 0;
        bottom_left_radius = low;
        bottom_right_radius = low;
      }
      this.moveTo(x2 + top_left_radius, y2);
      this.lineTo(x2 + w2 - top_right_radius, y2);
      this.quadraticCurveTo(x2 + w2, y2, x2 + w2, y2 + top_right_radius);
      this.lineTo(x2 + w2, y2 + h2 - bottom_right_radius);
      this.quadraticCurveTo(
        x2 + w2,
        y2 + h2,
        x2 + w2 - bottom_right_radius,
        y2 + h2
      );
      this.lineTo(x2 + bottom_right_radius, y2 + h2);
      this.quadraticCurveTo(x2, y2 + h2, x2, y2 + h2 - bottom_left_radius);
      this.lineTo(x2, y2 + bottom_left_radius);
      this.quadraticCurveTo(x2, y2, x2 + top_left_radius, y2);
    };
  }
  if (typeof window != "undefined" && !window["requestAnimationFrame"]) {
    window.requestAnimationFrame = // @ts-expect-error Legacy code
    window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function(callback) {
      window.setTimeout(callback, 1e3 / 60);
    };
  }
}
__name(loadPolyfills, "loadPolyfills");
const LiteGraph = new LiteGraphGlobal();
loadPolyfills();
const Comfy_BrowseTemplates$6 = {
  label: "Browse Templates"
};
const Comfy_Canvas_DeleteSelectedItems$6 = {
  label: "Delete Selected Items"
};
const Comfy_Canvas_FitView$6 = {
  label: "Fit view to selected nodes"
};
const Comfy_Canvas_ResetView$6 = {
  label: "Reset View"
};
const Comfy_Canvas_Resize$6 = {
  label: "Resize Selected Nodes"
};
const Comfy_Canvas_ToggleLinkVisibility$6 = {
  label: "Canvas Toggle Link Visibility"
};
const Comfy_Canvas_ToggleLock$6 = {
  label: "Canvas Toggle Lock"
};
const Comfy_Canvas_ToggleSelected_Pin$6 = {
  label: "Pin/Unpin Selected Items"
};
const Comfy_Canvas_ToggleSelectedNodes_Bypass$6 = {
  label: "Bypass/Unbypass Selected Nodes"
};
const Comfy_Canvas_ToggleSelectedNodes_Collapse$6 = {
  label: "Collapse/Expand Selected Nodes"
};
const Comfy_Canvas_ToggleSelectedNodes_Mute$6 = {
  label: "Mute/Unmute Selected Nodes"
};
const Comfy_Canvas_ToggleSelectedNodes_Pin$6 = {
  label: "Pin/Unpin Selected Nodes"
};
const Comfy_Canvas_ZoomIn$6 = {
  label: "Zoom In"
};
const Comfy_Canvas_ZoomOut$6 = {
  label: "Zoom Out"
};
const Comfy_ClearPendingTasks$6 = {
  label: "Clear Pending Tasks"
};
const Comfy_ClearWorkflow$6 = {
  label: "Clear Workflow"
};
const Comfy_ContactSupport$6 = {
  label: "Contact Support"
};
const Comfy_DuplicateWorkflow$6 = {
  label: "Duplicate Current Workflow"
};
const Comfy_ExportWorkflow$6 = {
  label: "Export Workflow"
};
const Comfy_ExportWorkflowAPI$6 = {
  label: "Export Workflow (API Format)"
};
const Comfy_Feedback$6 = {
  label: "Give Feedback"
};
const Comfy_Graph_FitGroupToContents$6 = {
  label: "Fit Group To Contents"
};
const Comfy_Graph_GroupSelectedNodes$6 = {
  label: "Group Selected Nodes"
};
const Comfy_GroupNode_ConvertSelectedNodesToGroupNode$6 = {
  label: "Convert selected nodes to group node"
};
const Comfy_GroupNode_ManageGroupNodes$6 = {
  label: "Manage group nodes"
};
const Comfy_GroupNode_UngroupSelectedGroupNodes$6 = {
  label: "Ungroup selected group nodes"
};
const Comfy_Help_AboutComfyUI$6 = {
  label: "Open About ComfyUI"
};
const Comfy_Help_OpenComfyOrgDiscord$6 = {
  label: "Open Comfy-Org Discord"
};
const Comfy_Help_OpenComfyUIDocs$6 = {
  label: "Open ComfyUI Docs"
};
const Comfy_Help_OpenComfyUIForum$6 = {
  label: "Open ComfyUI Forum"
};
const Comfy_Help_OpenComfyUIIssues$6 = {
  label: "Open ComfyUI Issues"
};
const Comfy_Interrupt$6 = {
  label: "Interrupt"
};
const Comfy_LoadDefaultWorkflow$6 = {
  label: "Load Default Workflow"
};
const Comfy_Manager_CustomNodesManager$6 = {
  label: "Custom Nodes Manager"
};
const Comfy_Manager_ToggleManagerProgressDialog$6 = {
  label: "Toggle Progress Dialog"
};
const Comfy_NewBlankWorkflow$6 = {
  label: "New Blank Workflow"
};
const Comfy_OpenClipspace$6 = {
  label: "Clipspace"
};
const Comfy_OpenWorkflow$6 = {
  label: "Open Workflow"
};
const Comfy_QueuePrompt$6 = {
  label: "Queue Prompt"
};
const Comfy_QueuePromptFront$6 = {
  label: "Queue Prompt (Front)"
};
const Comfy_QueueSelectedOutputNodes$6 = {
  label: "Queue Selected Output Nodes"
};
const Comfy_Redo$6 = {
  label: "Redo"
};
const Comfy_RefreshNodeDefinitions$6 = {
  label: "Refresh Node Definitions"
};
const Comfy_SaveWorkflow$6 = {
  label: "Save Workflow"
};
const Comfy_SaveWorkflowAs$6 = {
  label: "Save Workflow As"
};
const Comfy_ShowSettingsDialog$6 = {
  label: "Show Settings Dialog"
};
const Comfy_ToggleTheme$6 = {
  label: "Toggle Theme (Dark/Light)"
};
const Comfy_Undo$6 = {
  label: "Undo"
};
const Comfy_User_OpenSignInDialog$6 = {
  label: "Open Sign In Dialog"
};
const Comfy_User_SignOut$6 = {
  label: "Sign Out"
};
const Workspace_CloseWorkflow$6 = {
  label: "Close Current Workflow"
};
const Workspace_NextOpenedWorkflow$6 = {
  label: "Next Opened Workflow"
};
const Workspace_PreviousOpenedWorkflow$6 = {
  label: "Previous Opened Workflow"
};
const Workspace_SearchBox_Toggle$6 = {
  label: "Toggle Search Box"
};
const Workspace_ToggleBottomPanel$6 = {
  label: "Toggle Bottom Panel"
};
const Workspace_ToggleFocusMode$6 = {
  label: "Toggle Focus Mode"
};
const Workspace_ToggleSidebarTab_queue$6 = {
  label: "Toggle Queue Sidebar",
  tooltip: "Queue"
};
const Workspace_ToggleSidebarTab_workflows$6 = {
  label: "Toggle Workflows Sidebar",
  tooltip: "Workflows"
};
const enCommands = {
  "Comfy-Desktop_CheckForUpdates": {
    label: "Check for Updates"
  },
  "Comfy-Desktop_Folders_OpenCustomNodesFolder": {
    label: "Open Custom Nodes Folder"
  },
  "Comfy-Desktop_Folders_OpenInputsFolder": {
    label: "Open Inputs Folder"
  },
  "Comfy-Desktop_Folders_OpenLogsFolder": {
    label: "Open Logs Folder"
  },
  "Comfy-Desktop_Folders_OpenModelConfig": {
    label: "Open extra_model_paths.yaml"
  },
  "Comfy-Desktop_Folders_OpenModelsFolder": {
    label: "Open Models Folder"
  },
  "Comfy-Desktop_Folders_OpenOutputsFolder": {
    label: "Open Outputs Folder"
  },
  "Comfy-Desktop_OpenDevTools": {
    label: "Open DevTools"
  },
  "Comfy-Desktop_OpenUserGuide": {
    label: "Desktop User Guide"
  },
  "Comfy-Desktop_Quit": {
    label: "Quit"
  },
  "Comfy-Desktop_Reinstall": {
    label: "Reinstall"
  },
  "Comfy-Desktop_Restart": {
    label: "Restart"
  },
  Comfy_BrowseTemplates: Comfy_BrowseTemplates$6,
  Comfy_Canvas_DeleteSelectedItems: Comfy_Canvas_DeleteSelectedItems$6,
  Comfy_Canvas_FitView: Comfy_Canvas_FitView$6,
  Comfy_Canvas_ResetView: Comfy_Canvas_ResetView$6,
  Comfy_Canvas_Resize: Comfy_Canvas_Resize$6,
  Comfy_Canvas_ToggleLinkVisibility: Comfy_Canvas_ToggleLinkVisibility$6,
  Comfy_Canvas_ToggleLock: Comfy_Canvas_ToggleLock$6,
  Comfy_Canvas_ToggleSelected_Pin: Comfy_Canvas_ToggleSelected_Pin$6,
  Comfy_Canvas_ToggleSelectedNodes_Bypass: Comfy_Canvas_ToggleSelectedNodes_Bypass$6,
  Comfy_Canvas_ToggleSelectedNodes_Collapse: Comfy_Canvas_ToggleSelectedNodes_Collapse$6,
  Comfy_Canvas_ToggleSelectedNodes_Mute: Comfy_Canvas_ToggleSelectedNodes_Mute$6,
  Comfy_Canvas_ToggleSelectedNodes_Pin: Comfy_Canvas_ToggleSelectedNodes_Pin$6,
  Comfy_Canvas_ZoomIn: Comfy_Canvas_ZoomIn$6,
  Comfy_Canvas_ZoomOut: Comfy_Canvas_ZoomOut$6,
  Comfy_ClearPendingTasks: Comfy_ClearPendingTasks$6,
  Comfy_ClearWorkflow: Comfy_ClearWorkflow$6,
  Comfy_ContactSupport: Comfy_ContactSupport$6,
  Comfy_DuplicateWorkflow: Comfy_DuplicateWorkflow$6,
  Comfy_ExportWorkflow: Comfy_ExportWorkflow$6,
  Comfy_ExportWorkflowAPI: Comfy_ExportWorkflowAPI$6,
  Comfy_Feedback: Comfy_Feedback$6,
  Comfy_Graph_FitGroupToContents: Comfy_Graph_FitGroupToContents$6,
  Comfy_Graph_GroupSelectedNodes: Comfy_Graph_GroupSelectedNodes$6,
  Comfy_GroupNode_ConvertSelectedNodesToGroupNode: Comfy_GroupNode_ConvertSelectedNodesToGroupNode$6,
  Comfy_GroupNode_ManageGroupNodes: Comfy_GroupNode_ManageGroupNodes$6,
  Comfy_GroupNode_UngroupSelectedGroupNodes: Comfy_GroupNode_UngroupSelectedGroupNodes$6,
  Comfy_Help_AboutComfyUI: Comfy_Help_AboutComfyUI$6,
  Comfy_Help_OpenComfyOrgDiscord: Comfy_Help_OpenComfyOrgDiscord$6,
  Comfy_Help_OpenComfyUIDocs: Comfy_Help_OpenComfyUIDocs$6,
  Comfy_Help_OpenComfyUIForum: Comfy_Help_OpenComfyUIForum$6,
  Comfy_Help_OpenComfyUIIssues: Comfy_Help_OpenComfyUIIssues$6,
  Comfy_Interrupt: Comfy_Interrupt$6,
  Comfy_LoadDefaultWorkflow: Comfy_LoadDefaultWorkflow$6,
  Comfy_Manager_CustomNodesManager: Comfy_Manager_CustomNodesManager$6,
  Comfy_Manager_ToggleManagerProgressDialog: Comfy_Manager_ToggleManagerProgressDialog$6,
  Comfy_NewBlankWorkflow: Comfy_NewBlankWorkflow$6,
  Comfy_OpenClipspace: Comfy_OpenClipspace$6,
  Comfy_OpenWorkflow: Comfy_OpenWorkflow$6,
  Comfy_QueuePrompt: Comfy_QueuePrompt$6,
  Comfy_QueuePromptFront: Comfy_QueuePromptFront$6,
  Comfy_QueueSelectedOutputNodes: Comfy_QueueSelectedOutputNodes$6,
  Comfy_Redo: Comfy_Redo$6,
  Comfy_RefreshNodeDefinitions: Comfy_RefreshNodeDefinitions$6,
  Comfy_SaveWorkflow: Comfy_SaveWorkflow$6,
  Comfy_SaveWorkflowAs: Comfy_SaveWorkflowAs$6,
  Comfy_ShowSettingsDialog: Comfy_ShowSettingsDialog$6,
  Comfy_ToggleTheme: Comfy_ToggleTheme$6,
  Comfy_Undo: Comfy_Undo$6,
  Comfy_User_OpenSignInDialog: Comfy_User_OpenSignInDialog$6,
  Comfy_User_SignOut: Comfy_User_SignOut$6,
  Workspace_CloseWorkflow: Workspace_CloseWorkflow$6,
  Workspace_NextOpenedWorkflow: Workspace_NextOpenedWorkflow$6,
  Workspace_PreviousOpenedWorkflow: Workspace_PreviousOpenedWorkflow$6,
  Workspace_SearchBox_Toggle: Workspace_SearchBox_Toggle$6,
  Workspace_ToggleBottomPanel: Workspace_ToggleBottomPanel$6,
  "Workspace_ToggleBottomPanelTab_command-terminal": {
    label: "Toggle Terminal Bottom Panel"
  },
  "Workspace_ToggleBottomPanelTab_logs-terminal": {
    label: "Toggle Logs Bottom Panel"
  },
  Workspace_ToggleFocusMode: Workspace_ToggleFocusMode$6,
  "Workspace_ToggleSidebarTab_model-library": {
    label: "Toggle Model Library Sidebar",
    tooltip: "Model Library"
  },
  "Workspace_ToggleSidebarTab_node-library": {
    label: "Toggle Node Library Sidebar",
    tooltip: "Node Library"
  },
  Workspace_ToggleSidebarTab_queue: Workspace_ToggleSidebarTab_queue$6,
  Workspace_ToggleSidebarTab_workflows: Workspace_ToggleSidebarTab_workflows$6
};
const g$6 = {
  user: "User",
  currentUser: "Current user",
  empty: "Empty",
  noWorkflowsFound: "No workflows found.",
  comingSoon: "Coming Soon",
  firstTimeUIMessage: 'This is the first time you use the new UI. Choose "Menu > Use New Menu > Disabled" to restore the old UI.',
  download: "Download",
  "import": "Import",
  loadAllFolders: "Load All Folders",
  refresh: "Refresh",
  terminal: "Terminal",
  logs: "Logs",
  videoFailedToLoad: "Video failed to load",
  extensionName: "Extension Name",
  reloadToApplyChanges: "Reload to apply changes",
  insert: "Insert",
  systemInfo: "System Info",
  devices: "Devices",
  about: "About",
  add: "Add",
  confirm: "Confirm",
  confirmed: "Confirmed",
  reset: "Reset",
  resetAll: "Reset All",
  resetAllKeybindingsTooltip: "Reset all keybindings to default",
  customizeFolder: "Customize Folder",
  icon: "Icon",
  color: "Color",
  error: "Error",
  loading: "Loading",
  findIssues: "Find Issues",
  reportIssue: "Send Report",
  reportIssueTooltip: "Submit the error report to Comfy Org",
  reportSent: "Report Submitted",
  copyToClipboard: "Copy to Clipboard",
  openNewIssue: "Open New Issue",
  showReport: "Show Report",
  imageFailedToLoad: "Image failed to load",
  reconnecting: "Reconnecting",
  reconnected: "Reconnected",
  "delete": "Delete",
  rename: "Rename",
  save: "Save",
  saving: "Saving",
  no: "No",
  cancel: "Cancel",
  close: "Close",
  back: "Back",
  next: "Next",
  install: "Install",
  installing: "Installing",
  overwrite: "Overwrite",
  customize: "Customize",
  experimental: "BETA",
  deprecated: "DEPR",
  loadWorkflow: "Load Workflow",
  goToNode: "Go to Node",
  settings: "Settings",
  searchWorkflows: "Search Workflows",
  searchSettings: "Search Settings",
  searchNodes: "Search Nodes",
  searchModels: "Search Models",
  searchKeybindings: "Search Keybindings",
  searchExtensions: "Search Extensions",
  noResultsFound: "No Results Found",
  searchFailedMessage: "We couldn't find any settings matching your search. Try adjusting your search terms.",
  noTasksFound: "No Tasks Found",
  noTasksFoundMessage: "There are no tasks in the queue.",
  newFolder: "New Folder",
  enableAll: "Enable All",
  disableAll: "Disable All",
  command: "Command",
  keybinding: "Keybinding",
  upload: "Upload",
  "export": "Export",
  workflow: "Workflow",
  success: "Success",
  ok: "OK",
  feedback: "Feedback",
  "continue": "Continue",
  control_after_generate: "control after generate",
  control_before_generate: "control before generate",
  choose_file_to_upload: "choose file to upload",
  capture: "capture",
  nodes: "Nodes",
  community: "Community",
  all: "All",
  update: "Update",
  updated: "Updated",
  resultsCount: "Found {count} Results",
  status: "Status",
  description: "Description",
  name: "Name",
  category: "Category",
  sort: "Sort",
  source: "Source",
  filter: "Filter",
  apply: "Apply",
  enabled: "Enabled",
  installed: "Installed",
  restart: "Restart",
  missing: "Missing",
  inProgress: "In progress",
  completed: "Completed",
  interrupted: "Interrupted",
  enabling: "Enabling",
  disabling: "Disabling",
  updating: "Updating",
  migrate: "Migrate",
  updateAvailable: "Update Available",
  login: "Login",
  learnMore: "Learn more",
  amount: "Amount",
  unknownError: "Unknown error",
  title: "Title"
};
const manager$6 = {
  title: "Custom Nodes Manager",
  failed: "Failed ({count})",
  noNodesFound: "No nodes found",
  noNodesFoundDescription: "The pack's nodes either could not be parsed, or the pack is a frontend extension only and doesn't have any nodes.",
  installationQueue: "Installation Queue",
  changingVersion: "Changing version from {from} to {to}",
  dependencies: "Dependencies",
  inWorkflow: "In Workflow",
  infoPanelEmpty: "Click an item to see the info",
  restartToApplyChanges: "To apply changes, please restart ComfyUI",
  loadingVersions: "Loading versions...",
  selectVersion: "Select Version",
  downloads: "Downloads",
  repository: "Repository",
  uninstall: "Uninstall",
  uninstalling: "Uninstalling",
  update: "Update",
  uninstallSelected: "Uninstall Selected",
  updatingAllPacks: "Updating all packages",
  license: "License",
  nightlyVersion: "Nightly",
  latestVersion: "Latest",
  createdBy: "Created By",
  totalNodes: "Total Nodes",
  discoverCommunityContent: "Discover community-made Node Packs, Extensions, and more...",
  errorConnecting: "Error connecting to the Comfy Node Registry.",
  noResultsFound: "No results found matching your search.",
  tryDifferentSearch: "Please try a different search query.",
  tryAgainLater: "Please try again later.",
  nodePack: "Node Pack",
  searchPlaceholder: "Search",
  version: "Version",
  lastUpdated: "Last Updated",
  noDescription: "No description available",
  installSelected: "Install Selected",
  packsSelected: "Packs Selected",
  status: {
    active: "Active",
    pending: "Pending",
    flagged: "Flagged",
    deleted: "Deleted",
    banned: "Banned",
    unknown: "Unknown"
  },
  sort: {
    downloads: "Most Popular",
    publisher: "Publisher",
    created: "Newest",
    updated: "Updated Recently"
  },
  filter: {
    nodePack: "Node Pack",
    enabled: "Enabled",
    disabled: "Disabled"
  }
};
const issueReport$6 = {
  submitErrorReport: "Submit Error Report (Optional)",
  provideEmail: "Give us your email (optional)",
  provideAdditionalDetails: "Provide additional details (optional)",
  stackTrace: "Stack Trace",
  systemStats: "System Stats",
  contactFollowUp: "Contact me for follow up",
  notifyResolve: "Notify me when resolved",
  helpFix: "Help Fix This",
  rating: "Rating",
  feedbackTitle: "Help us improve ComfyUI by providing feedback",
  contactSupportTitle: "Contact Support",
  contactSupportDescription: "Please fill in the form below with your report",
  selectIssue: "Select the issue",
  whatDoYouNeedHelpWith: "What do you need help with?",
  whatCanWeInclude: "Specify what to include in the report",
  describeTheProblem: "Describe the problem",
  email: "Email",
  helpTypes: {
    billingPayments: "Billing / Payments",
    loginAccessIssues: "Login / Access Issues",
    giveFeedback: "Give Feedback",
    bugReport: "Bug Report",
    somethingElse: "Something Else"
  },
  validation: {
    maxLength: "Message too long",
    invalidEmail: "Please enter a valid email address",
    selectIssueType: "Please select an issue type"
  }
};
const color$6 = {
  noColor: "No Color",
  "default": "Default",
  blue: "Blue",
  green: "Green",
  red: "Red",
  pink: "Pink",
  yellow: "Yellow",
  brown: "Brown",
  pale_blue: "Pale Blue",
  cyan: "Cyan",
  purple: "Purple",
  black: "Black",
  custom: "Custom"
};
const contextMenu$6 = {
  Inputs: "Inputs",
  Outputs: "Outputs",
  Properties: "Properties",
  "Properties Panel": "Properties Panel",
  Title: "Title",
  Mode: "Mode",
  Resize: "Resize",
  Collapse: "Collapse",
  Expand: "Expand",
  Pin: "Pin",
  Unpin: "Unpin",
  Clone: "Clone",
  Remove: "Remove",
  Colors: "Colors",
  Shapes: "Shapes",
  Bypass: "Bypass",
  "Copy (Clipspace)": "Copy (Clipspace)",
  "Add Node": "Add Node",
  "Add Group": "Add Group",
  "Convert to Group Node": "Convert to Group Node",
  "Manage Group Nodes": "Manage Group Nodes",
  "Add Group For Selected Nodes": "Add Group For Selected Nodes",
  "Save Selected as Template": "Save Selected as Template",
  "Node Templates": "Node Templates",
  Manage: "Manage",
  Search: "Search"
};
const icon$6 = {
  bookmark: "Bookmark",
  folder: "Folder",
  star: "Star",
  heart: "Heart",
  file: "File",
  inbox: "Inbox",
  box: "Box",
  briefcase: "Briefcase",
  "exclamation-triangle": "Warning"
};
const welcome$6 = {
  title: "Welcome to ComfyUI",
  getStarted: "Get Started"
};
const userSelect$6 = {
  newUser: "New user",
  enterUsername: "Enter a username",
  existingUser: "Existing user",
  selectUser: "Select a user",
  next: "Next"
};
const notSupported$6 = {
  title: "Your device is not supported",
  message: "Only following devices are supported:",
  learnMore: "Learn More",
  reportIssue: "Report Issue",
  supportedDevices: {
    macos: "MacOS (M1 or later)",
    windows: "Windows (Nvidia GPU with CUDA support)"
  },
  "continue": "Continue",
  continueTooltip: "I am sure my device is supported"
};
const downloadGit$6 = {
  title: "Download git",
  message: "Unable to locate git.  A working copy of git is required for normal operation.",
  instructions: "Please download and install the latest version for your operating system.  The Download git button below opens the git-scm.com downloads page.",
  warning: "If you are sure you do not need git installed, or there has been a mistake, you may click Skip to byapss this check.  Attempting to run ComfyUI without a working copy of git is not currently supported.",
  gitWebsite: "Download git",
  skip: "Skip"
};
const install$6 = {
  installLocation: "Install Location",
  migration: "Migration",
  desktopSettings: "Desktop Settings",
  chooseInstallationLocation: "Choose Installation Location",
  systemLocations: "System Locations",
  failedToSelectDirectory: "Failed to select directory",
  pathValidationFailed: "Failed to validate path",
  pathExists: "Directory already exists - please ensure you have backed up all data",
  cannotWrite: "Unable to write to the selected path",
  insufficientFreeSpace: "Insufficient space - minimum free space",
  isOneDrive: "OneDrive is not supported. Please install ComfyUI in another location.",
  nonDefaultDrive: "Please install ComfyUI on your system drive (eg. C:\\). Drives with different file systems may cause unpredicable issues. Models and other files can be stored on other drives after installation.",
  parentMissing: "Path does not exist - create the containing directory first",
  unhandledError: "Unknown error",
  installLocationDescription: "Select the directory for ComfyUI's user data. A python environment will be installed to the selected location.",
  installLocationTooltip: "ComfyUI's user data directory. Stores:\n- Python Environment\n- Models\n- Custom nodes\n",
  appDataLocationTooltip: "ComfyUI's app data directory. Stores:\n- Logs\n- Server configs",
  appPathLocationTooltip: "ComfyUI's app asset directory. Stores the ComfyUI code and assets",
  migrateFromExistingInstallation: "Migrate from Existing Installation",
  migrationSourcePathDescription: "If you have an existing ComfyUI installation, we can copy/link your existing user files and models to the new installation. Your existing ComfyUI installation will not be affected.",
  selectItemsToMigrate: "Select Items to Migrate",
  migrationOptional: "Migration is optional. If you don't have an existing installation, you can skip this step.",
  desktopAppSettings: "Desktop App Settings",
  desktopAppSettingsDescription: "Configure how ComfyUI behaves on your desktop. You can change these settings later.",
  gpu: "GPU",
  gpuSelection: {
    selectGpu: "Select GPU",
    selectGpuDescription: "Select the type of GPU you have",
    cpuMode: "CPU Mode",
    cpuModeDescription: "CPU mode is intended for developers and rare edge cases only.",
    cpuModeDescription2: "If you are not absolutely certain you need this, please ignore this box and select your GPU above.",
    enableCpuMode: "Enable CPU Mode",
    nvidiaDescription: "NVIDIA devices are directly supported using pytorch CUDA builds.",
    mpsDescription: "Apple Metal Performance Shaders are supported using pytorch nightly.",
    customSkipsPython: "This option skips the normal python setup.",
    customComfyNeedsPython: "ComfyUI will not work until python is setup",
    customManualVenv: "Manually configure python venv",
    customInstallRequirements: "Install all requirements and dependencies (e.g. custom torch)",
    customMayNotWork: "This is entirely unsupported, and may simply not work"
  },
  manualConfiguration: {
    title: "Manual Configuration",
    requirements: "Requirements",
    createVenv: "You will need to create a virtual environment in the following directory",
    virtualEnvironmentPath: "Virtual environment path",
    restartWhenFinished: "When you have finished configuring the virtual environment, please restart ComfyUI."
  },
  settings: {
    autoUpdate: "Automatic Updates",
    allowMetrics: "Usage Metrics",
    errorUpdatingConsent: "Error Updating Consent",
    errorUpdatingConsentDetail: "Failed to update metrics consent settings",
    autoUpdateDescription: "Automatically download updates when they become available. You will be notified before updates are installed.",
    allowMetricsDescription: "Help improve ComfyUI by sending anonymous usage metrics. No personal information or workflow content will be collected.",
    learnMoreAboutData: "Learn more about data collection",
    dataCollectionDialog: {
      title: "About Data Collection",
      whatWeCollect: "What we collect:",
      whatWeDoNotCollect: "What we don't collect:",
      collect: {
        errorReports: "Error message and stack trace",
        systemInfo: "Hardware, OS type, and app version",
        userJourneyEvents: "User journey events"
      },
      doNotCollect: {
        personalInformation: "Personal information",
        fileSystemInformation: "File system information",
        workflowContents: "Workflow contents",
        customNodeConfigurations: "Custom node configurations"
      },
      viewFullPolicy: "View full policy"
    },
    pythonMirrorPlaceholder: "Enter Python mirror URL",
    pypiMirrorPlaceholder: "Enter PyPI mirror URL",
    checkingMirrors: "Checking network access to python mirrors...",
    mirrorsReachable: "Network access to python mirrors is good",
    mirrorsUnreachable: "Network access to some python mirrors is bad",
    mirrorSettings: "Mirror Settings"
  },
  customNodes: "Custom Nodes",
  customNodesDescription: "Reinstall custom nodes from existing ComfyUI installations.",
  helpImprove: "Please help improve ComfyUI",
  moreInfo: "For more info, please read our",
  privacyPolicy: "privacy policy",
  metricsEnabled: "Metrics Enabled",
  metricsDisabled: "Metrics Disabled",
  updateConsent: "You previously opted in to reporting crashes. We are now tracking event-based metrics to help identify bugs and improve the app. No personal identifiable information is collected."
};
const serverStart$6 = {
  troubleshoot: "Troubleshoot",
  reportIssue: "Report Issue",
  openLogs: "Open Logs",
  showTerminal: "Show Terminal",
  process: {
    "initial-state": "Loading...",
    "python-setup": "Setting up Python Environment...",
    "starting-server": "Starting ComfyUI server...",
    ready: "Finishing...",
    error: "Unable to start ComfyUI Desktop"
  }
};
const serverConfig$6 = {
  modifiedConfigs: "You have modified the following server configurations. Restart to apply changes.",
  revertChanges: "Revert Changes",
  restart: "Restart"
};
const sideToolbar$6 = {
  themeToggle: "Toggle Theme",
  logout: "Logout",
  queue: "Queue",
  nodeLibrary: "Node Library",
  workflows: "Workflows",
  browseTemplates: "Browse example templates",
  openWorkflow: "Open workflow in local file system",
  newBlankWorkflow: "Create a new blank workflow",
  nodeLibraryTab: {
    sortOrder: "Sort Order"
  },
  modelLibrary: "Model Library",
  downloads: "Downloads",
  queueTab: {
    showFlatList: "Show Flat List",
    backToAllTasks: "Back to All Tasks",
    containImagePreview: "Fill Image Preview",
    coverImagePreview: "Fit Image Preview",
    clearPendingTasks: "Clear Pending Tasks",
    filter: "Filter Outputs",
    filters: {
      hideCached: "Hide Cached",
      hideCanceled: "Hide Canceled"
    }
  },
  workflowTab: {
    confirmDeleteTitle: "Delete workflow?",
    confirmDelete: "Are you sure you want to delete this workflow?",
    deleted: "Workflow deleted",
    deleteFailedTitle: "Delete failed",
    deleteFailed: "Attempt to delete the workflow failed.",
    dirtyCloseTitle: "Save Changes?",
    dirtyClose: "The files below have been changed.  Would you like to save them before closing?",
    dirtyCloseHint: "Hold Shift to close without prompt",
    confirmOverwriteTitle: "Overwrite existing file?",
    confirmOverwrite: "The file below already exists. Would you like to overwrite it?",
    workflowTreeType: {
      browse: "Browse",
      bookmarks: "Bookmarks",
      open: "Open"
    }
  }
};
const menu$6 = {
  hideMenu: "Hide Menu",
  showMenu: "Show Menu",
  batchCount: "Batch Count",
  batchCountTooltip: "The number of times the workflow generation should be queued",
  autoQueue: "Auto Queue",
  disabled: "Disabled",
  disabledTooltip: "The workflow will not be automatically queued",
  instant: "Instant",
  instantTooltip: "The workflow will be queued instantly after a generation finishes",
  onChange: "On Change",
  onChangeTooltip: "The workflow will be queued once a change is made",
  runWorkflow: "Run workflow (Shift to queue at front)",
  runWorkflowFront: "Run workflow (Queue at front)",
  run: "Run",
  execute: "Execute",
  interrupt: "Cancel current run",
  refresh: "Refresh node definitions",
  clipspace: "Open Clipspace",
  resetView: "Reset canvas view",
  clear: "Clear workflow",
  toggleBottomPanel: "Toggle Bottom Panel"
};
const tabMenu$6 = {
  duplicateTab: "Duplicate Tab",
  closeTab: "Close Tab",
  closeTabsToLeft: "Close Tabs to Left",
  closeTabsToRight: "Close Tabs to Right",
  closeOtherTabs: "Close Other Tabs",
  addToBookmarks: "Add to Bookmarks",
  removeFromBookmarks: "Remove from Bookmarks"
};
const templateWorkflows$6 = {
  title: "Get Started with a Template",
  category: {
    "ComfyUI Examples": "ComfyUI Examples",
    "Custom Nodes": "Custom Nodes",
    Basics: "Basics",
    Flux: "Flux",
    ControlNet: "ControlNet",
    Upscaling: "Upscaling",
    Video: "Video",
    Image: "Image",
    "Area Composition": "Area Composition",
    "3D": "3D",
    Audio: "Audio",
    "Image API": "Image API",
    "Video API": "Video API"
  },
  templateDescription: {
    Basics: {
      "default": "Generate images from text descriptions.",
      image2image: "Transform existing images using text prompts.",
      lora: "Apply LoRA models for specialized styles or subjects.",
      inpaint_example: "Edit specific parts of images seamlessly.",
      inpain_model_outpainting: "Extend images beyond their original boundaries.",
      embedding_example: "Use textual inversion for consistent styles.",
      gligen_textbox_example: "Specify the location and size of objects.",
      lora_multiple: "Combine multiple LoRA models for unique results."
    },
    Flux: {
      flux_dev_checkpoint_example: "Create images using Flux development models.",
      flux_schnell: "Generate images quickly with Flux Schnell.",
      flux_fill_inpaint_example: "Fill in missing parts of images.",
      flux_fill_outpaint_example: "Extend images using Flux outpainting.",
      flux_canny_model_example: "Generate images from edge detection.",
      flux_depth_lora_example: "Create images with depth-aware LoRA.",
      flux_redux_model_example: "Transfer style from a reference image to guide image generation with Flux."
    },
    Image: {
      hidream_i1_dev: "Generate images with HiDream I1 Dev.",
      hidream_i1_fast: "Generate images quickly with HiDream I1.",
      hidream_i1_full: "Generate images with HiDream I1.",
      hidream_e1_full: "Edit images with HiDream E1.",
      sd3_5_simple_example: "Generate images with SD 3.5.",
      sd3_5_large_canny_controlnet_example: "Use edge detection to guide image generation with SD 3.5.",
      sd3_5_large_depth: "Create depth-aware images with SD 3.5.",
      sd3_5_large_blur: "Generate images from blurred reference images with SD 3.5.",
      sdxl_simple_example: "Create high-quality images with SDXL.",
      sdxl_refiner_prompt_example: "Enhance SDXL outputs with refiners.",
      sdxl_revision_text_prompts: "Transfer concepts from reference images to guide image generation with SDXL.",
      sdxl_revision_zero_positive: "Add text prompts alongside reference images to guide image generation with SDXL.",
      sdxlturbo_example: "Generate images in a single step with SDXL Turbo."
    },
    Video: {
      text_to_video_wan: "Quickly Generate videos from text descriptions.",
      image_to_video_wan: "Quickly Generate videos from images.",
      wan2_1_fun_inp: "Create videos from start and end frames.",
      wan2_1_fun_control: "Guide video generation with pose, depth, edge controls and more.",
      wan2_1_flf2v_720_f16: "Generate video through controlling the first and last frames.",
      ltxv_text_to_video: "Generate videos from text descriptions.",
      ltxv_image_to_video: "Convert still images into videos.",
      mochi_text_to_video_example: "Create videos with Mochi model.",
      hunyuan_video_text_to_video: "Generate videos using Hunyuan model.",
      image_to_video: "Transform images into animated videos.",
      txt_to_image_to_video: "Generate images from text and then convert them into videos."
    },
    "Image API": {
      api_openai_image_1_t2i: "Use GPT Image 1 API to generate images from text descriptions.",
      api_openai_image_1_i2i: "Use GPT Image 1 API to generate images from images.",
      api_openai_image_1_inpaint: "Use GPT Image 1 API to inpaint images.",
      api_openai_image_1_multi_inputs: "Use GPT Image 1 API with multiple inputs to generate images.",
      "api-openai-dall-e-2-t2i": "Use Dall-E 2 API to generate images from text descriptions.",
      "api-openai-dall-e-2-inpaint": "Use Dall-E 2 API to inpaint images.",
      "api-openai-dall-e-3-t2i": "Use Dall-E 3 API to generate images from text descriptions.",
      api_bfl_flux_pro_t2i: "Create images with FLUX.1 [pro]'s excellent prompt following, visual quality, image detail and output diversity.",
      api_stability_sd3_t2i: "Generate high quality images with excellent prompt adherence. Perfect for professional use cases at 1 megapixel resolution.",
      api_ideogram_v3_t2i: "Generate images with high-quality image-prompt alignment, photorealism, and text rendering. Create professional-quality logos, promotional posters, landing page concepts, product photography, and more. Effortlessly craft sophisticated spatial compositions with intricate backgrounds, precise and nuanced lighting and colors, and lifelike environmental detail.",
      api_luma_photon_i2i: "Guide image generation using a combination of images and prompt.",
      api_luma_photon_style_ref: "Apply and blend style references with exact control. Luma Photon captures the essence of each reference image, letting you combine distinct visual elements while maintaining professional quality.",
      api_recraft_image_gen_with_color_control: "Create a custom palette to reuse for multiple images or hand-pick colors for each photo. Match your brand's color palette and craft visuals that are distinctly yours.",
      api_recraft_image_gen_with_style_control: "Control style with visual examples, align positioning, and fine-tune objects. Store and share styles for perfect brand consistency.",
      api_recraft_vector_gen: "Go from a text prompt to vector image with Recraft's AI vector generator. Produce the best-quality vector art for logos, posters, icon sets, ads, banners and mockups. Perfect your designs with sharp, high-quality SVG files. Create branded vector illustrations for your app or website in seconds."
    },
    "Video API": {
      api_luma_i2v: "Take static images and instantly create magical high quality animations.",
      api_kling_i2v: "Create videos with great prompt adherence for actions, expressions, and camera movements. Now supporting complex prompts with sequential actions for you to be the director of your scene.",
      api_veo2_i2v: "Use Google Veo2 API to generate videos from images.",
      api_hailuo_minimax_i2v: "Create refined videos from images and text, including CGI integration and trendy photo effects like viral AI hugging. Choose from a variety of video styles and themes to match your creative vision.",
      api_pika_scene: "Use multiple images as ingredients and generate videos that incorporate all of them.",
      api_pixverse_template_i2v: "Transforms static images into dynamic videos with motion and effects.",
      api_pixverse_t2v: "Generate videos with accurate prompt interpretation and stunning video dynamics."
    },
    Upscaling: {
      hiresfix_latent_workflow: "Enhance image quality in latent space.",
      esrgan_example: "Use upscale models to enhance image quality.",
      hiresfix_esrgan_workflow: "Use upscale models during intermediate steps.",
      latent_upscale_different_prompt_model: "Upscale and change prompt across passes."
    },
    ControlNet: {
      controlnet_example: "Control image generation with reference images.",
      "2_pass_pose_worship": "Generate images from pose references.",
      depth_controlnet: "Create images with depth-aware generation.",
      depth_t2i_adapter: "Quickly generate depth-aware images with a T2I adapter.",
      mixing_controlnets: "Combine multiple ControlNet models together."
    },
    "Area Composition": {
      area_composition: "Control image composition with areas.",
      area_composition_reversed: "Reverse area composition workflow.",
      area_composition_square_area_for_subject: "Create consistent subject placement."
    },
    "3D": {
      "hunyuan3d-non-multiview-train": "Use Hunyuan3D 2.0 to generate models from a single view.",
      "hunyuan-3d-multiview-elf": " Use Hunyuan3D 2mv to generate models from multiple views.",
      "hunyuan-3d-turbo": "Use Hunyuan3D 2mv turbo to generate models from multiple views.",
      stable_zero123_example: "Generate 3D views from single images."
    },
    Audio: {
      stable_audio_example: "Generate audio from text descriptions."
    }
  },
  template: {
    Flux: {
      flux_dev_checkpoint_example: "Flux Dev",
      flux_schnell: "Flux Schnell",
      flux_fill_inpaint_example: "Flux Inpaint",
      flux_fill_outpaint_example: "Flux Outpaint",
      flux_canny_model_example: "Flux Canny Model",
      flux_redux_model_example: "Flux Redux Model",
      flux_depth_lora_example: "Flux Depth Lora"
    },
    Basics: {
      "default": "Image Generation",
      image2image: "Image to Image",
      embedding_example: "Embedding",
      gligen_textbox_example: "Gligen Textbox",
      lora: "Lora",
      lora_multiple: "Lora Multiple",
      inpaint_example: "Inpaint",
      inpain_model_outpainting: "Outpaint"
    },
    ControlNet: {
      controlnet_example: "Scribble ControlNet",
      "2_pass_pose_worship": "Pose ControlNet 2 Pass",
      depth_controlnet: "Depth ControlNet",
      depth_t2i_adapter: "Depth T2I Adapter",
      mixing_controlnets: "Mixing ControlNets"
    },
    Upscaling: {
      esrgan_example: "ESRGAN",
      hiresfix_latent_workflow: "Upscale",
      hiresfix_esrgan_workflow: "HiresFix ESRGAN Workflow",
      latent_upscale_different_prompt_model: "Latent Upscale Different Prompt Model"
    },
    Video: {
      text_to_video_wan: "Wan 2.1 Text to Video",
      image_to_video_wan: "Wan 2.1 Image to Video",
      image_to_video: "SVD Image to Video",
      txt_to_image_to_video: "SVD Text to Image to Video",
      ltxv_image_to_video: "LTXV Image to Video",
      ltxv_text_to_video: "LTXV Text to Video",
      mochi_text_to_video_example: "Mochi Text to Video",
      hunyuan_video_text_to_video: "Hunyuan Video Text to Video",
      wan2_1_fun_inp: "Wan 2.1 Inpainting",
      wan2_1_fun_control: "Wan 2.1 ControlNet"
    },
    "Image API": {
      api_openai_image_1_t2i: "OpenAI Image-1 Text to Image",
      api_openai_image_1_i2i: "OpenAI Image-1 Image to Image",
      api_openai_image_1_inpaint: "OpenAI Image-1 Inpaint",
      api_openai_image_1_multi_inputs: "OpenAI Image-1 Multi Inputs",
      "api-openai-dall-e-2-t2i": "Dall-E 2 Text to Image",
      "api-openai-dall-e-2-inpaint": "Dall-E 2 Inpaint",
      "api-openai-dall-e-3-t2i": "Dall-E 3 Text to Image",
      api_bfl_flux_pro_t2i: "BFL Flux 1.1[pro] Ultra Text to Image",
      api_stability_sd3_t2i: "Stability AI Stable Image Ultra Text to Image",
      api_ideogram_v3_t2i: "Ideogram V3 Text to Image",
      api_luma_photon_i2i: "Luma Photon Image to Image",
      api_luma_photon_style_ref: "Luma Photon Style Reference",
      api_recraft_image_gen_with_color_control: "Recraft Color Control Image Generation",
      api_recraft_image_gen_with_style_control: "Recraft Style Control Image Generation",
      api_recraft_vector_gen: "Recraft Vector Generation"
    },
    "Video API": {
      api_luma_i2v: "Luma Image to Video",
      api_kling_i2v: "Kling Image to Video",
      api_veo2_i2v: "Veo2 Image to Video",
      api_hailuo_minimax_i2v: "MiniMax Image to Video",
      api_pika_scene: "Pika Scenes: Images to Video",
      api_pixverse_template_i2v: "PixVerse Template Effects: Image to Video",
      api_pixverse_t2v: "PixVerse Text to Video"
    },
    Image: {
      sd3_5_simple_example: "SD3.5 Simple",
      sd3_5_large_canny_controlnet_example: "SD3.5 Large Canny ControlNet",
      sd3_5_large_depth: "SD3.5 Large Depth",
      sd3_5_large_blur: "SD3.5 Large Blur",
      sdxl_simple_example: "SDXL Simple",
      sdxl_refiner_prompt_example: "SDXL Refiner Prompt",
      sdxl_revision_text_prompts: "SDXL Revision Text Prompts",
      sdxl_revision_zero_positive: "SDXL Revision Zero Positive",
      sdxlturbo_example: "SDXL Turbo",
      hidream_i1_dev: "HiDream I1 Dev",
      hidream_i1_fast: "HiDream I1 Fast",
      hidream_i1_full: "HiDream I1 Full"
    },
    "Area Composition": {
      area_composition: "Area Composition",
      area_composition_reversed: "Area Composition Reversed",
      area_composition_square_area_for_subject: "Area Composition Square Area for Subject"
    },
    "3D": {
      stable_zero123_example: "Stable Zero123",
      "hunyuan3d-non-multiview-train": "Hunyuan3D 2.0",
      "hunyuan-3d-multiview-elf": "Hunyuan3D 2.0 MV",
      "hunyuan-3d-turbo": "Hunyuan3D 2.0 MV Turbo"
    },
    Audio: {
      stable_audio_example: "Stable Audio"
    }
  }
};
const graphCanvasMenu$6 = {
  zoomIn: "Zoom In",
  zoomOut: "Zoom Out",
  resetView: "Reset View",
  fitView: "Fit View",
  selectMode: "Select Mode",
  panMode: "Pan Mode",
  toggleLinkVisibility: "Toggle Link Visibility"
};
const groupNode$6 = {
  create: "Create group node",
  enterName: "Enter name"
};
const nodeTemplates$6 = {
  saveAsTemplate: "Save as template",
  enterName: "Enter name"
};
const workflowService$6 = {
  exportWorkflow: "Export Workflow",
  enterFilename: "Enter the filename",
  saveWorkflow: "Save workflow"
};
const electronFileDownload$6 = {
  inProgress: "In Progress",
  pause: "Pause Download",
  paused: "Paused",
  resume: "Resume Download",
  cancel: "Cancel Download",
  cancelled: "Cancelled"
};
const maskEditor$6 = {
  Invert: "Invert",
  Clear: "Clear",
  "Brush Settings": "Brush Settings",
  "Brush Shape": "Brush Shape",
  Thickness: "Thickness",
  Opacity: "Opacity",
  Hardness: "Hardness",
  "Smoothing Precision": "Smoothing Precision",
  "Reset to Default": "Reset to Default",
  "Paint Bucket Settings": "Paint Bucket Settings",
  Tolerance: "Tolerance",
  "Fill Opacity": "Fill Opacity",
  "Color Select Settings": "Color Select Settings",
  "Selection Opacity": "Selection Opacity",
  "Live Preview": "Live Preview",
  "Apply to Whole Image": "Apply to Whole Image",
  Method: "Method",
  "Stop at mask": "Stop at mask",
  "Mask Tolerance": "Mask Tolerance",
  Layers: "Layers",
  "Mask Layer": "Mask Layer",
  "Mask Opacity": "Mask Opacity",
  "Image Layer": "Image Layer"
};
const menuLabels$6 = {
  Workflow: "Workflow",
  Edit: "Edit",
  Help: "Help",
  "Check for Updates": "Check for Updates",
  "Open Custom Nodes Folder": "Open Custom Nodes Folder",
  "Open Inputs Folder": "Open Inputs Folder",
  "Open Logs Folder": "Open Logs Folder",
  "Open extra_model_paths_yaml": "Open extra_model_paths.yaml",
  "Open Models Folder": "Open Models Folder",
  "Open Outputs Folder": "Open Outputs Folder",
  "Open DevTools": "Open DevTools",
  "Desktop User Guide": "Desktop User Guide",
  Quit: "Quit",
  Reinstall: "Reinstall",
  Restart: "Restart",
  "Browse Templates": "Browse Templates",
  "Delete Selected Items": "Delete Selected Items",
  "Fit view to selected nodes": "Fit view to selected nodes",
  "Reset View": "Reset View",
  "Resize Selected Nodes": "Resize Selected Nodes",
  "Canvas Toggle Link Visibility": "Canvas Toggle Link Visibility",
  "Canvas Toggle Lock": "Canvas Toggle Lock",
  "Pin/Unpin Selected Items": "Pin/Unpin Selected Items",
  "Bypass/Unbypass Selected Nodes": "Bypass/Unbypass Selected Nodes",
  "Collapse/Expand Selected Nodes": "Collapse/Expand Selected Nodes",
  "Mute/Unmute Selected Nodes": "Mute/Unmute Selected Nodes",
  "Pin/Unpin Selected Nodes": "Pin/Unpin Selected Nodes",
  "Zoom In": "Zoom In",
  "Zoom Out": "Zoom Out",
  "Clear Pending Tasks": "Clear Pending Tasks",
  "Clear Workflow": "Clear Workflow",
  "Contact Support": "Contact Support",
  "Duplicate Current Workflow": "Duplicate Current Workflow",
  Export: "Export",
  "Export (API)": "Export (API)",
  "Give Feedback": "Give Feedback",
  "Fit Group To Contents": "Fit Group To Contents",
  "Group Selected Nodes": "Group Selected Nodes",
  "Convert selected nodes to group node": "Convert selected nodes to group node",
  "Manage group nodes": "Manage group nodes",
  "Ungroup selected group nodes": "Ungroup selected group nodes",
  "About ComfyUI": "About ComfyUI",
  "Comfy-Org Discord": "Comfy-Org Discord",
  "ComfyUI Docs": "ComfyUI Docs",
  "ComfyUI Forum": "ComfyUI Forum",
  "ComfyUI Issues": "ComfyUI Issues",
  Interrupt: "Interrupt",
  "Load Default Workflow": "Load Default Workflow",
  "Custom Nodes Manager": "Custom Nodes Manager",
  "Toggle Progress Dialog": "Toggle Progress Dialog",
  New: "New",
  Clipspace: "Clipspace",
  Open: "Open",
  "Queue Prompt": "Queue Prompt",
  "Queue Prompt (Front)": "Queue Prompt (Front)",
  "Queue Selected Output Nodes": "Queue Selected Output Nodes",
  Redo: "Redo",
  "Refresh Node Definitions": "Refresh Node Definitions",
  Save: "Save",
  "Save As": "Save As",
  "Show Settings Dialog": "Show Settings Dialog",
  "Toggle Theme (Dark/Light)": "Toggle Theme (Dark/Light)",
  Undo: "Undo",
  "Open Sign In Dialog": "Open Sign In Dialog",
  "Sign Out": "Sign Out",
  "Close Current Workflow": "Close Current Workflow",
  "Next Opened Workflow": "Next Opened Workflow",
  "Previous Opened Workflow": "Previous Opened Workflow",
  "Toggle Search Box": "Toggle Search Box",
  "Toggle Bottom Panel": "Toggle Bottom Panel",
  "Toggle Terminal Bottom Panel": "Toggle Terminal Bottom Panel",
  "Toggle Logs Bottom Panel": "Toggle Logs Bottom Panel",
  "Toggle Focus Mode": "Toggle Focus Mode",
  "Toggle Model Library Sidebar": "Toggle Model Library Sidebar",
  "Toggle Node Library Sidebar": "Toggle Node Library Sidebar",
  "Toggle Queue Sidebar": "Toggle Queue Sidebar",
  "Toggle Workflows Sidebar": "Toggle Workflows Sidebar"
};
const desktopMenu$6 = {
  reinstall: "Reinstall",
  confirmReinstall: "This will clear your extra_models_config.yaml file,\nand begin installation again.\n\nAre you sure?",
  quit: "Quit",
  confirmQuit: "There are unsaved workflows open; any unsaved changes will be lost.  Ignore this and quit?"
};
const settingsCategories$6 = {
  "Comfy-Desktop": "Comfy-Desktop",
  General: "General",
  Appearance: "Appearance",
  ColorPalette: "Color Palette",
  Comfy: "Comfy",
  Workflow: "Workflow",
  DevMode: "Dev Mode",
  LiteGraph: "Lite Graph",
  "Node Widget": "Node Widget",
  Node: "Node",
  Extension: "Extension",
  Canvas: "Canvas",
  Link: "Link",
  Group: "Group",
  Menu: "Menu",
  Keybinding: "Keybinding",
  LinkRelease: "Link Release",
  Graph: "Graph",
  Locale: "Locale",
  "Mask Editor": "Mask Editor",
  BrushAdjustment: "Brush Adjustment",
  NewEditor: "New Editor",
  ModelLibrary: "Model Library",
  NodeLibrary: "Node Library",
  "Node Search Box": "Node Search Box",
  Pointer: "Pointer",
  Queue: "Queue",
  QueueButton: "Queue Button",
  RerouteBeta: "Reroute Beta",
  Server: "Server",
  Settings: "Settings",
  Sidebar: "Sidebar",
  "Tree Explorer": "Tree Explorer",
  Validation: "Validation",
  Window: "Window",
  "Server-Config": "Server-Config",
  About: "About",
  EditTokenWeight: "Edit Token Weight",
  CustomColorPalettes: "Custom Color Palettes",
  UV: "UV",
  ContextMenu: "Context Menu",
  Reroute: "Reroute",
  "Load 3D": "Load 3D",
  Camera: "Camera",
  Scene: "Scene",
  "3D": "3D",
  Light: "Light",
  User: "User",
  Credits: "Credits"
};
const serverConfigItems$6 = {
  listen: {
    name: "Host: The IP address to listen on"
  },
  port: {
    name: "Port: The port to listen on"
  },
  "tls-keyfile": {
    name: "TLS Key File: Path to TLS key file for HTTPS"
  },
  "tls-certfile": {
    name: "TLS Certificate File: Path to TLS certificate file for HTTPS"
  },
  "enable-cors-header": {
    name: 'Enable CORS header: Use "*" for all origins or specify domain'
  },
  "max-upload-size": {
    name: "Maximum upload size (MB)"
  },
  "cuda-device": {
    name: "CUDA device index to use"
  },
  "cuda-malloc": {
    name: "Use CUDA malloc for memory allocation"
  },
  "global-precision": {
    name: "Global floating point precision",
    tooltip: "Global floating point precision"
  },
  "unet-precision": {
    name: "UNET precision",
    tooltip: "UNET precision"
  },
  "vae-precision": {
    name: "VAE precision",
    tooltip: "VAE precision"
  },
  "cpu-vae": {
    name: "Run VAE on CPU"
  },
  "text-encoder-precision": {
    name: "Text Encoder precision",
    tooltip: "Text Encoder precision"
  },
  "force-channels-last": {
    name: "Force channels-last memory format"
  },
  directml: {
    name: "DirectML device index"
  },
  "disable-ipex-optimize": {
    name: "Disable IPEX optimization"
  },
  "preview-method": {
    name: "Method used for latent previews"
  },
  "preview-size": {
    name: "Size of preview images"
  },
  "cache-classic": {
    name: "Use classic cache system"
  },
  "cache-lru": {
    name: "Use LRU caching with a maximum of N node results cached.",
    tooltip: "May use more RAM/VRAM."
  },
  "cross-attention-method": {
    name: "Cross attention method"
  },
  "disable-xformers": {
    name: "Disable xFormers optimization"
  },
  "force-upcast-attention": {
    name: "Force attention upcast"
  },
  "dont-upcast-attention": {
    name: "Prevent attention upcast"
  },
  "vram-management": {
    name: "VRAM management mode"
  },
  "reserve-vram": {
    name: "Reserved VRAM (GB)",
    tooltip: "Set the amount of vram in GB you want to reserve for use by your OS/other software. By default some amount is reverved depending on your OS."
  },
  "default-hashing-function": {
    name: "Default hashing function for model files"
  },
  "disable-smart-memory": {
    name: "Disable smart memory management",
    tooltip: "Force ComfyUI to aggressively offload to regular ram instead of keeping models in vram when it can."
  },
  deterministic: {
    name: "Make pytorch use slower deterministic algorithms when it can.",
    tooltip: "Note that this might not make images deterministic in all cases."
  },
  fast: {
    name: "Enable some untested and potentially quality deteriorating optimizations."
  },
  "dont-print-server": {
    name: "Don't print server output to console."
  },
  "disable-metadata": {
    name: "Disable saving prompt metadata in files."
  },
  "disable-all-custom-nodes": {
    name: "Disable loading all custom nodes."
  },
  "log-level": {
    name: "Logging verbosity level"
  },
  "input-directory": {
    name: "Input directory"
  },
  "output-directory": {
    name: "Output directory"
  }
};
const serverConfigCategories$6 = {
  Network: "Network",
  CUDA: "CUDA",
  Inference: "Inference",
  Memory: "Memory",
  Preview: "Preview",
  Cache: "Cache",
  Attention: "Attention",
  General: "General",
  Directories: "Directories"
};
const nodeCategories$6 = {
  _for_testing: "_for_testing",
  custom_sampling: "custom_sampling",
  noise: "noise",
  sampling: "sampling",
  schedulers: "schedulers",
  guiders: "guiders",
  image: "image",
  preprocessors: "preprocessors",
  advanced: "advanced",
  guidance: "guidance",
  loaders: "loaders",
  model_merging: "model_merging",
  attention_experiments: "attention_experiments",
  conditioning: "conditioning",
  flux: "flux",
  hooks: "hooks",
  combine: "combine",
  "cond single": "cond single",
  controlnet: "controlnet",
  inpaint: "inpaint",
  scheduling: "scheduling",
  create: "create",
  video: "video",
  mask: "mask",
  deprecated: "deprecated",
  latent: "latent",
  audio: "audio",
  "3d": "3d",
  ltxv: "ltxv",
  sd3: "sd3",
  sigmas: "sigmas",
  "api node": "api node",
  BFL: "BFL",
  model_patches: "model_patches",
  unet: "unet",
  gligen: "gligen",
  video_models: "video_models",
  Ideogram: "Ideogram",
  v1: "v1",
  v2: "v2",
  v3: "v3",
  postprocessing: "postprocessing",
  transform: "transform",
  batch: "batch",
  upscaling: "upscaling",
  instructpix2pix: "instructpix2pix",
  compositing: "compositing",
  Kling: "Kling",
  samplers: "samplers",
  operations: "operations",
  lotus: "lotus",
  Luma: "Luma",
  MiniMax: "MiniMax",
  debug: "debug",
  model: "model",
  model_specific: "model_specific",
  OpenAI: "OpenAI",
  "cond pair": "cond pair",
  photomaker: "photomaker",
  Pika: "Pika",
  PixVerse: "PixVerse",
  utils: "utils",
  primitive: "primitive",
  Recraft: "Recraft",
  animation: "animation",
  api: "api",
  upscale_diffusion: "upscale_diffusion",
  clip: "clip",
  "Stability AI": "Stability AI",
  stable_cascade: "stable_cascade",
  "3d_models": "3d_models",
  style_model: "style_model",
  sd: "sd",
  Veo: "Veo"
};
const dataTypes$6 = {
  "*": "*",
  AUDIO: "AUDIO",
  BOOLEAN: "BOOLEAN",
  CAMERA_CONTROL: "CAMERA_CONTROL",
  CLIP: "CLIP",
  CLIP_VISION: "CLIP_VISION",
  CLIP_VISION_OUTPUT: "CLIP_VISION_OUTPUT",
  COMBO: "COMBO",
  CONDITIONING: "CONDITIONING",
  CONTROL_NET: "CONTROL_NET",
  FLOAT: "FLOAT",
  FLOATS: "FLOATS",
  GLIGEN: "GLIGEN",
  GUIDER: "GUIDER",
  HOOK_KEYFRAMES: "HOOK_KEYFRAMES",
  HOOKS: "HOOKS",
  IMAGE: "IMAGE",
  INT: "INT",
  LATENT: "LATENT",
  LATENT_OPERATION: "LATENT_OPERATION",
  LOAD_3D: "LOAD_3D",
  LOAD_3D_ANIMATION: "LOAD_3D_ANIMATION",
  LOAD3D_CAMERA: "LOAD3D_CAMERA",
  LUMA_CONCEPTS: "LUMA_CONCEPTS",
  LUMA_REF: "LUMA_REF",
  MASK: "MASK",
  MESH: "MESH",
  MODEL: "MODEL",
  NOISE: "NOISE",
  PHOTOMAKER: "PHOTOMAKER",
  PIXVERSE_TEMPLATE: "PIXVERSE_TEMPLATE",
  RECRAFT_COLOR: "RECRAFT_COLOR",
  RECRAFT_CONTROLS: "RECRAFT_CONTROLS",
  RECRAFT_V3_STYLE: "RECRAFT_V3_STYLE",
  SAMPLER: "SAMPLER",
  SIGMAS: "SIGMAS",
  STRING: "STRING",
  STYLE_MODEL: "STYLE_MODEL",
  SVG: "SVG",
  TIMESTEPS_RANGE: "TIMESTEPS_RANGE",
  UPSCALE_MODEL: "UPSCALE_MODEL",
  VAE: "VAE",
  VIDEO: "VIDEO",
  VOXEL: "VOXEL",
  WEBCAM: "WEBCAM"
};
const maintenance$6 = {
  title: "Maintenance",
  allOk: "No issues were detected.",
  status: "Status",
  detected: "Detected",
  refreshing: "Refreshing",
  None: "None",
  OK: "OK",
  Skipped: "Skipped",
  showManual: "Show maintenance tasks",
  confirmTitle: "Are you sure?",
  terminalDefaultMessage: "When you run a troubleshooting command, any output will be shown here.",
  consoleLogs: "Console Logs",
  error: {
    toastTitle: "Task error",
    taskFailed: "Task failed to run.",
    cannotContinue: "Unable to continue - errors remain",
    defaultDescription: "An error occurred while running a maintenance task."
  }
};
const missingModelsDialog$6 = {
  doNotAskAgain: "Don't show this again",
  missingModels: "Missing Models",
  missingModelsMessage: "When loading the graph, the following models were not found"
};
const errorDialog$6 = {
  defaultTitle: "An error occurred",
  loadWorkflowTitle: "Loading aborted due to error reloading workflow data",
  noStackTrace: "No stacktrace available",
  extensionFileHint: "This may be due to the following script",
  promptExecutionError: "Prompt execution failed"
};
const apiNodesSignInDialog$6 = {
  title: "Sign In Required to Use API Nodes",
  message: "This workflow contains API Nodes, which require you to be signed in to your account in order to run."
};
const apiNodesCostBreakdown$6 = {
  title: "API Node(s)",
  costPerRun: "Cost per run",
  totalCost: "Total Cost"
};
const desktopUpdate$6 = {
  title: "Updating ComfyUI Desktop",
  description: "ComfyUI Desktop is installing new dependencies.  This may take a few minutes.",
  terminalDefaultMessage: "Any console output from the update will be shown here.",
  updateFoundTitle: "Update Found (v{version})",
  updateAvailableMessage: "An update is available. Do you want to restart and update now?",
  noUpdateFound: "No update found",
  errorCheckingUpdate: "Error checking for updates",
  errorInstallingUpdate: "Error installing update"
};
const clipboard$6 = {
  successMessage: "Copied to clipboard",
  errorMessage: "Failed to copy to clipboard",
  errorNotSupported: "Clipboard API not supported in your browser"
};
const load3d$6 = {
  switchCamera: "Switch Camera",
  showGrid: "Show Grid",
  backgroundColor: "Background Color",
  lightIntensity: "Light Intensity",
  fov: "FOV",
  previewOutput: "Preview Output",
  uploadBackgroundImage: "Upload Background Image",
  removeBackgroundImage: "Remove Background Image",
  loadingModel: "Loading 3D Model...",
  upDirection: "Up Direction",
  materialMode: "Material Mode",
  scene: "Scene",
  model: "Model",
  camera: "Camera",
  light: "Light",
  switchingMaterialMode: "Switching Material Mode...",
  edgeThreshold: "Edge Threshold",
  "export": "Export",
  exportModel: "Export Model",
  exportingModel: "Exporting model...",
  uploadTexture: "Upload Texture",
  applyingTexture: "Applying Texture...",
  materialModes: {
    normal: "Normal",
    wireframe: "Wireframe",
    original: "Original",
    depth: "Depth",
    lineart: "Lineart"
  },
  startRecording: "Start Recording",
  stopRecording: "Stop Recording",
  exportRecording: "Export Recording",
  clearRecording: "Clear Recording",
  resizeNodeMatchOutput: "Resize Node to match output"
};
const toastMessages$6 = {
  nothingToQueue: "Nothing to queue",
  pleaseSelectOutputNodes: "Please select output nodes",
  no3dScene: "No 3D scene to apply texture",
  failedToApplyTexture: "Failed to apply texture",
  no3dSceneToExport: "No 3D scene to export",
  failedToExportModel: "Failed to export model as {format}",
  fileLoadError: "Unable to find workflow in {fileName}",
  dropFileError: "Unable to process dropped item: {error}",
  interrupted: "Execution has been interrupted",
  pendingTasksDeleted: "Pending tasks deleted",
  nothingToGroup: "Nothing to group",
  pleaseSelectNodesToGroup: "Please select the nodes (or other groups) to create a group for",
  emptyCanvas: "Empty canvas",
  fileUploadFailed: "File upload failed",
  unableToGetModelFilePath: "Unable to get model file path",
  couldNotDetermineFileType: "Could not determine file type",
  errorLoadingModel: "Error loading model",
  failedToDownloadFile: "Failed to download file",
  updateRequested: "Update requested",
  nodeDefinitionsUpdated: "Node definitions updated",
  errorSaveSetting: "Error saving setting {id}: {err}",
  errorCopyImage: "Error copying image: {error}",
  noTemplatesToExport: "No templates to export",
  failedToFetchLogs: "Failed to fetch server logs",
  migrateToLitegraphReroute: "Reroute nodes will be removed in future versions. Click to migrate to litegraph-native reroute.",
  userNotAuthenticated: "User not authenticated",
  failedToFetchBalance: "Failed to fetch balance: {error}",
  failedToCreateCustomer: "Failed to create customer: {error}",
  failedToInitiateCreditPurchase: "Failed to initiate credit purchase: {error}",
  failedToAccessBillingPortal: "Failed to access billing portal: {error}",
  failedToPurchaseCredits: "Failed to purchase credits: {error}",
  unauthorizedDomain: "Your domain {domain} is not authorized to use this service. Please contact {email} to add your domain to the whitelist.",
  useApiKeyTip: "Tip: Can't access normal login? Use the Comfy API Key option."
};
const auth$6 = {
  apiKey: {
    title: "API Key",
    label: "API Key",
    description: "Use your Comfy API key to enable API Nodes",
    placeholder: "Enter your API Key",
    error: "Invalid API Key",
    storageFailed: "Failed to store API Key",
    storageFailedDetail: "Please try again.",
    stored: "API Key stored",
    storedDetail: "Your API Key has been stored successfully",
    cleared: "API Key cleared",
    clearedDetail: "Your API Key has been cleared successfully",
    invalid: "Invalid API Key",
    invalidDetail: "Please enter a valid API Key",
    helpText: "Need an API key?",
    generateKey: "Get one here",
    whitelistInfo: "About non-whitelisted sites"
  },
  login: {
    title: "Log in to your account",
    useApiKey: "Comfy API Key",
    signInOrSignUp: "Sign In / Sign Up",
    forgotPasswordError: "Failed to send password reset email",
    passwordResetSent: "Password reset email sent",
    passwordResetSentDetail: "Please check your email for a link to reset your password.",
    newUser: "New here?",
    userAvatar: "User Avatar",
    signUp: "Sign up",
    emailLabel: "Email",
    emailPlaceholder: "Enter your email",
    passwordLabel: "Password",
    passwordPlaceholder: "Enter your password",
    confirmPasswordLabel: "Confirm Password",
    confirmPasswordPlaceholder: "Enter the same password again",
    forgotPassword: "Forgot password?",
    loginButton: "Log in",
    orContinueWith: "Or continue with",
    loginWithGoogle: "Log in with Google",
    loginWithGithub: "Log in with Github",
    termsText: 'By clicking "Next" or "Sign Up", you agree to our',
    termsLink: "Terms of Use",
    andText: "and",
    privacyLink: "Privacy Policy",
    success: "Login successful",
    failed: "Login failed",
    insecureContextWarning: "This connection is insecure (HTTP) - your credentials may be intercepted by attackers if you proceed to login.",
    questionsContactPrefix: "Questions? Contact us at",
    noAssociatedUser: "There is no Comfy user associated with the provided API key"
  },
  signup: {
    title: "Create an account",
    alreadyHaveAccount: "Already have an account?",
    emailLabel: "Email",
    emailPlaceholder: "Enter your email",
    passwordLabel: "Password",
    passwordPlaceholder: "Enter new password",
    signUpButton: "Sign up",
    signIn: "Sign in",
    signUpWithGoogle: "Sign up with Google",
    signUpWithGithub: "Sign up with Github",
    regionRestrictionChina: "In accordance with local regulatory requirements, our services are temporarily unavailable to users located in China.",
    personalDataConsentLabel: "I agree to the processing of my personal data."
  },
  signOut: {
    signOut: "Log Out",
    success: "Signed out successfully",
    successDetail: "You have been signed out of your account."
  },
  passwordUpdate: {
    success: "Password Updated",
    successDetail: "Your password has been updated successfully"
  }
};
const validation$6 = {
  invalidEmail: "Invalid email address",
  required: "Required",
  minLength: "Must be at least {length} characters",
  maxLength: "Must be no more than {length} characters",
  prefix: "Must start with {prefix}",
  length: "Must be {length} characters",
  password: {
    requirements: "Password requirements",
    minLength: "Must be between 8 and 32 characters",
    uppercase: "Must contain at least one uppercase letter",
    lowercase: "Must contain at least one lowercase letter",
    number: "Must contain at least one number",
    special: "Must contain at least one special character",
    match: "Passwords must match"
  },
  personalDataConsentRequired: "You must agree to the processing of your personal data."
};
const credits$6 = {
  credits: "Credits",
  yourCreditBalance: "Your credit balance",
  purchaseCredits: "Purchase Credits",
  invoiceHistory: "Invoice History",
  apiPricing: "API Pricing",
  faqs: "FAQs",
  messageSupport: "Message Support",
  lastUpdated: "Last updated",
  topUp: {
    insufficientTitle: "Insufficient Credits",
    insufficientMessage: "You don't have enough credits to run this workflow.",
    quickPurchase: "Quick Purchase",
    maxAmount: "(Max. $1,000 USD)",
    buyNow: "Buy now",
    seeDetails: "See details",
    topUp: "Top Up"
  }
};
const userSettings$6 = {
  title: "User Settings",
  name: "Name",
  email: "Email",
  provider: "Sign-in Provider",
  notSet: "Not set",
  updatePassword: "Update Password"
};
const apiNodesNews$6 = {
  introducing: "Introducing",
  subtitle: "Access all the popular paid models natively in ComfyUI",
  steps: {
    step1: {
      title: "Login/Create an account:",
      subtitle: "Settings > User > Login"
    },
    step2: {
      title: "Purchase credits:",
      subtitle: "Settings > Credits > Buy Credits"
    },
    step3: {
      title: "Locate new API Nodes under 'API Node' section and add to the canvas"
    },
    step4: {
      title: "Run!"
    }
  }
};
const selectionToolbox$6 = {
  executeButton: {
    tooltip: "Execute to selected output nodes (Highlighted with orange border)",
    disabledTooltip: "No output nodes selected"
  }
};
const en = {
  g: g$6,
  manager: manager$6,
  issueReport: issueReport$6,
  color: color$6,
  contextMenu: contextMenu$6,
  icon: icon$6,
  welcome: welcome$6,
  userSelect: userSelect$6,
  notSupported: notSupported$6,
  downloadGit: downloadGit$6,
  install: install$6,
  serverStart: serverStart$6,
  serverConfig: serverConfig$6,
  sideToolbar: sideToolbar$6,
  menu: menu$6,
  tabMenu: tabMenu$6,
  templateWorkflows: templateWorkflows$6,
  graphCanvasMenu: graphCanvasMenu$6,
  groupNode: groupNode$6,
  nodeTemplates: nodeTemplates$6,
  workflowService: workflowService$6,
  electronFileDownload: electronFileDownload$6,
  maskEditor: maskEditor$6,
  menuLabels: menuLabels$6,
  desktopMenu: desktopMenu$6,
  settingsCategories: settingsCategories$6,
  serverConfigItems: serverConfigItems$6,
  serverConfigCategories: serverConfigCategories$6,
  nodeCategories: nodeCategories$6,
  dataTypes: dataTypes$6,
  maintenance: maintenance$6,
  missingModelsDialog: missingModelsDialog$6,
  errorDialog: errorDialog$6,
  apiNodesSignInDialog: apiNodesSignInDialog$6,
  apiNodesCostBreakdown: apiNodesCostBreakdown$6,
  desktopUpdate: desktopUpdate$6,
  clipboard: clipboard$6,
  load3d: load3d$6,
  toastMessages: toastMessages$6,
  auth: auth$6,
  validation: validation$6,
  credits: credits$6,
  userSettings: userSettings$6,
  apiNodesNews: apiNodesNews$6,
  selectionToolbox: selectionToolbox$6
};
const AddNoise$6 = {
  display_name: "AddNoise",
  inputs: {
    model: {
      name: "model"
    },
    noise: {
      name: "noise"
    },
    sigmas: {
      name: "sigmas"
    },
    latent_image: {
      name: "latent_image"
    }
  }
};
const AlignYourStepsScheduler$6 = {
  display_name: "AlignYourStepsScheduler",
  inputs: {
    model_type: {
      name: "model_type"
    },
    steps: {
      name: "steps"
    },
    denoise: {
      name: "denoise"
    }
  }
};
const BasicGuider$6 = {
  display_name: "BasicGuider",
  inputs: {
    model: {
      name: "model"
    },
    conditioning: {
      name: "conditioning"
    }
  }
};
const BasicScheduler$6 = {
  display_name: "BasicScheduler",
  inputs: {
    model: {
      name: "model"
    },
    scheduler: {
      name: "scheduler"
    },
    steps: {
      name: "steps"
    },
    denoise: {
      name: "denoise"
    }
  }
};
const BetaSamplingScheduler$6 = {
  display_name: "BetaSamplingScheduler",
  inputs: {
    model: {
      name: "model"
    },
    steps: {
      name: "steps"
    },
    alpha: {
      name: "alpha"
    },
    beta: {
      name: "beta"
    }
  }
};
const Canny$6 = {
  display_name: "Canny",
  inputs: {
    image: {
      name: "image"
    },
    low_threshold: {
      name: "low_threshold"
    },
    high_threshold: {
      name: "high_threshold"
    }
  }
};
const CFGGuider$6 = {
  display_name: "CFGGuider",
  inputs: {
    model: {
      name: "model"
    },
    positive: {
      name: "positive"
    },
    negative: {
      name: "negative"
    },
    cfg: {
      name: "cfg"
    }
  }
};
const CFGZeroStar$6 = {
  display_name: "CFGZeroStar",
  inputs: {
    model: {
      name: "model"
    }
  },
  outputs: {
    "0": {
      name: "patched_model"
    }
  }
};
const CheckpointLoader$6 = {
  display_name: "Load Checkpoint With Config (DEPRECATED)",
  inputs: {
    config_name: {
      name: "config_name"
    },
    ckpt_name: {
      name: "ckpt_name"
    }
  }
};
const CheckpointLoaderSimple$6 = {
  display_name: "Load Checkpoint",
  description: "Loads a diffusion model checkpoint, diffusion models are used to denoise latents.",
  inputs: {
    ckpt_name: {
      name: "ckpt_name",
      tooltip: "The name of the checkpoint (model) to load."
    }
  },
  outputs: {
    "0": {
      tooltip: "The model used for denoising latents."
    },
    "1": {
      tooltip: "The CLIP model used for encoding text prompts."
    },
    "2": {
      tooltip: "The VAE model used for encoding and decoding images to and from latent space."
    }
  }
};
const CheckpointSave$6 = {
  display_name: "Save Checkpoint",
  inputs: {
    model: {
      name: "model"
    },
    clip: {
      name: "clip"
    },
    vae: {
      name: "vae"
    },
    filename_prefix: {
      name: "filename_prefix"
    }
  }
};
const CLIPAttentionMultiply$6 = {
  display_name: "CLIPAttentionMultiply",
  inputs: {
    clip: {
      name: "clip"
    },
    q: {
      name: "q"
    },
    k: {
      name: "k"
    },
    v: {
      name: "v"
    },
    out: {
      name: "out"
    }
  }
};
const CLIPLoader$6 = {
  display_name: "Load CLIP",
  description: "[Recipes]\n\nstable_diffusion: clip-l\nstable_cascade: clip-g\nsd3: t5 xxl/ clip-g / clip-l\nstable_audio: t5 base\nmochi: t5 xxl\ncosmos: old t5 xxl\nlumina2: gemma 2 2B\nwan: umt5 xxl\n hidream: llama-3.1 (Recommend) or t5",
  inputs: {
    clip_name: {
      name: "clip_name"
    },
    type: {
      name: "type"
    },
    device: {
      name: "device"
    }
  }
};
const CLIPMergeAdd$6 = {
  display_name: "CLIPMergeAdd",
  inputs: {
    clip1: {
      name: "clip1"
    },
    clip2: {
      name: "clip2"
    }
  }
};
const CLIPMergeSimple$6 = {
  display_name: "CLIPMergeSimple",
  inputs: {
    clip1: {
      name: "clip1"
    },
    clip2: {
      name: "clip2"
    },
    ratio: {
      name: "ratio"
    }
  }
};
const CLIPMergeSubtract$6 = {
  display_name: "CLIPMergeSubtract",
  inputs: {
    clip1: {
      name: "clip1"
    },
    clip2: {
      name: "clip2"
    },
    multiplier: {
      name: "multiplier"
    }
  }
};
const CLIPSave$6 = {
  display_name: "CLIPSave",
  inputs: {
    clip: {
      name: "clip"
    },
    filename_prefix: {
      name: "filename_prefix"
    }
  }
};
const CLIPSetLastLayer$6 = {
  display_name: "CLIP Set Last Layer",
  inputs: {
    clip: {
      name: "clip"
    },
    stop_at_clip_layer: {
      name: "stop_at_clip_layer"
    }
  }
};
const CLIPTextEncode$6 = {
  display_name: "CLIP Text Encode (Prompt)",
  description: "Encodes a text prompt using a CLIP model into an embedding that can be used to guide the diffusion model towards generating specific images.",
  inputs: {
    text: {
      name: "text",
      tooltip: "The text to be encoded."
    },
    clip: {
      name: "clip",
      tooltip: "The CLIP model used for encoding the text."
    }
  },
  outputs: {
    "0": {
      tooltip: "A conditioning containing the embedded text used to guide the diffusion model."
    }
  }
};
const CLIPTextEncodeControlnet$6 = {
  display_name: "CLIPTextEncodeControlnet",
  inputs: {
    clip: {
      name: "clip"
    },
    conditioning: {
      name: "conditioning"
    },
    text: {
      name: "text"
    }
  }
};
const CLIPTextEncodeFlux$6 = {
  display_name: "CLIPTextEncodeFlux",
  inputs: {
    clip: {
      name: "clip"
    },
    clip_l: {
      name: "clip_l"
    },
    t5xxl: {
      name: "t5xxl"
    },
    guidance: {
      name: "guidance"
    }
  }
};
const CLIPTextEncodeHiDream$6 = {
  display_name: "CLIPTextEncodeHiDream",
  inputs: {
    clip: {
      name: "clip"
    },
    clip_l: {
      name: "clip_l"
    },
    clip_g: {
      name: "clip_g"
    },
    t5xxl: {
      name: "t5xxl"
    },
    llama: {
      name: "llama"
    }
  }
};
const CLIPTextEncodeHunyuanDiT$6 = {
  display_name: "CLIPTextEncodeHunyuanDiT",
  inputs: {
    clip: {
      name: "clip"
    },
    bert: {
      name: "bert"
    },
    mt5xl: {
      name: "mt5xl"
    }
  }
};
const CLIPTextEncodeLumina2$6 = {
  display_name: "CLIP Text Encode for Lumina2",
  description: "Encodes a system prompt and a user prompt using a CLIP model into an embedding that can be used to guide the diffusion model towards generating specific images.",
  inputs: {
    system_prompt: {
      name: "system_prompt",
      tooltip: "Lumina2 provide two types of system prompts:Superior: You are an assistant designed to generate superior images with the superior degree of image-text alignment based on textual prompts or user prompts. Alignment: You are an assistant designed to generate high-quality images with the highest degree of image-text alignment based on textual prompts."
    },
    user_prompt: {
      name: "user_prompt",
      tooltip: "The text to be encoded."
    },
    clip: {
      name: "clip",
      tooltip: "The CLIP model used for encoding the text."
    }
  },
  outputs: {
    "0": {
      tooltip: "A conditioning containing the embedded text used to guide the diffusion model."
    }
  }
};
const CLIPTextEncodePixArtAlpha$6 = {
  display_name: "CLIPTextEncodePixArtAlpha",
  description: "Encodes text and sets the resolution conditioning for PixArt Alpha. Does not apply to PixArt Sigma.",
  inputs: {
    width: {
      name: "width"
    },
    height: {
      name: "height"
    },
    text: {
      name: "text"
    },
    clip: {
      name: "clip"
    }
  }
};
const CLIPTextEncodeSD3$6 = {
  display_name: "CLIPTextEncodeSD3",
  inputs: {
    clip: {
      name: "clip"
    },
    clip_l: {
      name: "clip_l"
    },
    clip_g: {
      name: "clip_g"
    },
    t5xxl: {
      name: "t5xxl"
    },
    empty_padding: {
      name: "empty_padding"
    }
  }
};
const CLIPTextEncodeSDXL$6 = {
  display_name: "CLIPTextEncodeSDXL",
  inputs: {
    clip: {
      name: "clip"
    },
    width: {
      name: "width"
    },
    height: {
      name: "height"
    },
    crop_w: {
      name: "crop_w"
    },
    crop_h: {
      name: "crop_h"
    },
    target_width: {
      name: "target_width"
    },
    target_height: {
      name: "target_height"
    },
    text_g: {
      name: "text_g"
    },
    text_l: {
      name: "text_l"
    }
  }
};
const CLIPTextEncodeSDXLRefiner$6 = {
  display_name: "CLIPTextEncodeSDXLRefiner",
  inputs: {
    ascore: {
      name: "ascore"
    },
    width: {
      name: "width"
    },
    height: {
      name: "height"
    },
    text: {
      name: "text"
    },
    clip: {
      name: "clip"
    }
  }
};
const CLIPVisionEncode$6 = {
  display_name: "CLIP Vision Encode",
  inputs: {
    clip_vision: {
      name: "clip_vision"
    },
    image: {
      name: "image"
    },
    crop: {
      name: "crop"
    }
  }
};
const CLIPVisionLoader$6 = {
  display_name: "Load CLIP Vision",
  inputs: {
    clip_name: {
      name: "clip_name"
    }
  }
};
const CombineHooks2$6 = {
  display_name: "Combine Hooks [2]",
  inputs: {
    hooks_A: {
      name: "hooks_A"
    },
    hooks_B: {
      name: "hooks_B"
    }
  }
};
const CombineHooks4$6 = {
  display_name: "Combine Hooks [4]",
  inputs: {
    hooks_A: {
      name: "hooks_A"
    },
    hooks_B: {
      name: "hooks_B"
    },
    hooks_C: {
      name: "hooks_C"
    },
    hooks_D: {
      name: "hooks_D"
    }
  }
};
const CombineHooks8$6 = {
  display_name: "Combine Hooks [8]",
  inputs: {
    hooks_A: {
      name: "hooks_A"
    },
    hooks_B: {
      name: "hooks_B"
    },
    hooks_C: {
      name: "hooks_C"
    },
    hooks_D: {
      name: "hooks_D"
    },
    hooks_E: {
      name: "hooks_E"
    },
    hooks_F: {
      name: "hooks_F"
    },
    hooks_G: {
      name: "hooks_G"
    },
    hooks_H: {
      name: "hooks_H"
    }
  }
};
const ConditioningAverage$6 = {
  display_name: "ConditioningAverage",
  inputs: {
    conditioning_to: {
      name: "conditioning_to"
    },
    conditioning_from: {
      name: "conditioning_from"
    },
    conditioning_to_strength: {
      name: "conditioning_to_strength"
    }
  }
};
const ConditioningCombine$6 = {
  display_name: "Conditioning (Combine)",
  inputs: {
    conditioning_1: {
      name: "conditioning_1"
    },
    conditioning_2: {
      name: "conditioning_2"
    }
  }
};
const ConditioningConcat$6 = {
  display_name: "Conditioning (Concat)",
  inputs: {
    conditioning_to: {
      name: "conditioning_to"
    },
    conditioning_from: {
      name: "conditioning_from"
    }
  }
};
const ConditioningSetArea$6 = {
  display_name: "Conditioning (Set Area)",
  inputs: {
    conditioning: {
      name: "conditioning"
    },
    width: {
      name: "width"
    },
    height: {
      name: "height"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    },
    strength: {
      name: "strength"
    }
  }
};
const ConditioningSetAreaPercentage$6 = {
  display_name: "Conditioning (Set Area with Percentage)",
  inputs: {
    conditioning: {
      name: "conditioning"
    },
    width: {
      name: "width"
    },
    height: {
      name: "height"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    },
    strength: {
      name: "strength"
    }
  }
};
const ConditioningSetAreaPercentageVideo$6 = {
  display_name: "ConditioningSetAreaPercentageVideo",
  inputs: {
    conditioning: {
      name: "conditioning"
    },
    width: {
      name: "width"
    },
    height: {
      name: "height"
    },
    temporal: {
      name: "temporal"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    },
    z: {
      name: "z"
    },
    strength: {
      name: "strength"
    }
  }
};
const ConditioningSetAreaStrength$6 = {
  display_name: "ConditioningSetAreaStrength",
  inputs: {
    conditioning: {
      name: "conditioning"
    },
    strength: {
      name: "strength"
    }
  }
};
const ConditioningSetDefaultCombine$6 = {
  display_name: "Cond Set Default Combine",
  inputs: {
    cond: {
      name: "cond"
    },
    cond_DEFAULT: {
      name: "cond_DEFAULT"
    },
    hooks: {
      name: "hooks"
    }
  }
};
const ConditioningSetMask$6 = {
  display_name: "Conditioning (Set Mask)",
  inputs: {
    conditioning: {
      name: "conditioning"
    },
    mask: {
      name: "mask"
    },
    strength: {
      name: "strength"
    },
    set_cond_area: {
      name: "set_cond_area"
    }
  }
};
const ConditioningSetProperties$6 = {
  display_name: "Cond Set Props",
  inputs: {
    cond_NEW: {
      name: "cond_NEW"
    },
    strength: {
      name: "strength"
    },
    set_cond_area: {
      name: "set_cond_area"
    },
    mask: {
      name: "mask"
    },
    hooks: {
      name: "hooks"
    },
    timesteps: {
      name: "timesteps"
    }
  }
};
const ConditioningSetPropertiesAndCombine$6 = {
  display_name: "Cond Set Props Combine",
  inputs: {
    cond: {
      name: "cond"
    },
    cond_NEW: {
      name: "cond_NEW"
    },
    strength: {
      name: "strength"
    },
    set_cond_area: {
      name: "set_cond_area"
    },
    mask: {
      name: "mask"
    },
    hooks: {
      name: "hooks"
    },
    timesteps: {
      name: "timesteps"
    }
  }
};
const ConditioningSetTimestepRange$6 = {
  display_name: "ConditioningSetTimestepRange",
  inputs: {
    conditioning: {
      name: "conditioning"
    },
    start: {
      name: "start"
    },
    end: {
      name: "end"
    }
  }
};
const ConditioningStableAudio$6 = {
  display_name: "ConditioningStableAudio",
  inputs: {
    positive: {
      name: "positive"
    },
    negative: {
      name: "negative"
    },
    seconds_start: {
      name: "seconds_start"
    },
    seconds_total: {
      name: "seconds_total"
    }
  },
  outputs: {
    "0": {
      name: "positive"
    },
    "1": {
      name: "negative"
    }
  }
};
const ConditioningTimestepsRange$6 = {
  display_name: "Timesteps Range",
  inputs: {
    start_percent: {
      name: "start_percent"
    },
    end_percent: {
      name: "end_percent"
    }
  },
  outputs: {
    "1": {
      name: "BEFORE_RANGE"
    },
    "2": {
      name: "AFTER_RANGE"
    }
  }
};
const ConditioningZeroOut$6 = {
  display_name: "ConditioningZeroOut",
  inputs: {
    conditioning: {
      name: "conditioning"
    }
  }
};
const ControlNetApply$6 = {
  display_name: "Apply ControlNet (OLD)",
  inputs: {
    conditioning: {
      name: "conditioning"
    },
    control_net: {
      name: "control_net"
    },
    image: {
      name: "image"
    },
    strength: {
      name: "strength"
    }
  }
};
const ControlNetApplyAdvanced$6 = {
  display_name: "Apply ControlNet",
  inputs: {
    positive: {
      name: "positive"
    },
    negative: {
      name: "negative"
    },
    control_net: {
      name: "control_net"
    },
    image: {
      name: "image"
    },
    strength: {
      name: "strength"
    },
    start_percent: {
      name: "start_percent"
    },
    end_percent: {
      name: "end_percent"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "positive"
    },
    "1": {
      name: "negative"
    }
  }
};
const ControlNetApplySD3$6 = {
  display_name: "Apply Controlnet with VAE",
  inputs: {
    positive: {
      name: "positive"
    },
    negative: {
      name: "negative"
    },
    control_net: {
      name: "control_net"
    },
    vae: {
      name: "vae"
    },
    image: {
      name: "image"
    },
    strength: {
      name: "strength"
    },
    start_percent: {
      name: "start_percent"
    },
    end_percent: {
      name: "end_percent"
    }
  },
  outputs: {
    "0": {
      name: "positive"
    },
    "1": {
      name: "negative"
    }
  }
};
const ControlNetInpaintingAliMamaApply$6 = {
  display_name: "ControlNetInpaintingAliMamaApply",
  inputs: {
    positive: {
      name: "positive"
    },
    negative: {
      name: "negative"
    },
    control_net: {
      name: "control_net"
    },
    vae: {
      name: "vae"
    },
    image: {
      name: "image"
    },
    mask: {
      name: "mask"
    },
    strength: {
      name: "strength"
    },
    start_percent: {
      name: "start_percent"
    },
    end_percent: {
      name: "end_percent"
    }
  },
  outputs: {
    "0": {
      name: "positive"
    },
    "1": {
      name: "negative"
    }
  }
};
const ControlNetLoader$6 = {
  display_name: "Load ControlNet Model",
  inputs: {
    control_net_name: {
      name: "control_net_name"
    }
  }
};
const CosmosImageToVideoLatent$6 = {
  display_name: "CosmosImageToVideoLatent",
  inputs: {
    vae: {
      name: "vae"
    },
    width: {
      name: "width"
    },
    height: {
      name: "height"
    },
    length: {
      name: "length"
    },
    batch_size: {
      name: "batch_size"
    },
    start_image: {
      name: "start_image"
    },
    end_image: {
      name: "end_image"
    }
  }
};
const CreateHookKeyframe$6 = {
  display_name: "Create Hook Keyframe",
  inputs: {
    strength_mult: {
      name: "strength_mult"
    },
    start_percent: {
      name: "start_percent"
    },
    prev_hook_kf: {
      name: "prev_hook_kf"
    }
  },
  outputs: {
    "0": {
      name: "HOOK_KF"
    }
  }
};
const CreateHookKeyframesFromFloats$6 = {
  display_name: "Create Hook Keyframes From Floats",
  inputs: {
    floats_strength: {
      name: "floats_strength"
    },
    start_percent: {
      name: "start_percent"
    },
    end_percent: {
      name: "end_percent"
    },
    print_keyframes: {
      name: "print_keyframes"
    },
    prev_hook_kf: {
      name: "prev_hook_kf"
    }
  },
  outputs: {
    "0": {
      name: "HOOK_KF"
    }
  }
};
const CreateHookKeyframesInterpolated$6 = {
  display_name: "Create Hook Keyframes Interp.",
  inputs: {
    strength_start: {
      name: "strength_start"
    },
    strength_end: {
      name: "strength_end"
    },
    interpolation: {
      name: "interpolation"
    },
    start_percent: {
      name: "start_percent"
    },
    end_percent: {
      name: "end_percent"
    },
    keyframes_count: {
      name: "keyframes_count"
    },
    print_keyframes: {
      name: "print_keyframes"
    },
    prev_hook_kf: {
      name: "prev_hook_kf"
    }
  },
  outputs: {
    "0": {
      name: "HOOK_KF"
    }
  }
};
const CreateHookLora$6 = {
  display_name: "Create Hook LoRA",
  inputs: {
    lora_name: {
      name: "lora_name"
    },
    strength_model: {
      name: "strength_model"
    },
    strength_clip: {
      name: "strength_clip"
    },
    prev_hooks: {
      name: "prev_hooks"
    }
  }
};
const CreateHookLoraModelOnly$6 = {
  display_name: "Create Hook LoRA (MO)",
  inputs: {
    lora_name: {
      name: "lora_name"
    },
    strength_model: {
      name: "strength_model"
    },
    prev_hooks: {
      name: "prev_hooks"
    }
  }
};
const CreateHookModelAsLora$6 = {
  display_name: "Create Hook Model as LoRA",
  inputs: {
    ckpt_name: {
      name: "ckpt_name"
    },
    strength_model: {
      name: "strength_model"
    },
    strength_clip: {
      name: "strength_clip"
    },
    prev_hooks: {
      name: "prev_hooks"
    }
  }
};
const CreateHookModelAsLoraModelOnly$6 = {
  display_name: "Create Hook Model as LoRA (MO)",
  inputs: {
    ckpt_name: {
      name: "ckpt_name"
    },
    strength_model: {
      name: "strength_model"
    },
    prev_hooks: {
      name: "prev_hooks"
    }
  }
};
const CreateVideo$6 = {
  display_name: "Create Video",
  description: "Create a video from images.",
  inputs: {
    images: {
      name: "images",
      tooltip: "The images to create a video from."
    },
    fps: {
      name: "fps"
    },
    audio: {
      name: "audio",
      tooltip: "The audio to add to the video."
    }
  }
};
const CropMask$6 = {
  display_name: "CropMask",
  inputs: {
    mask: {
      name: "mask"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    },
    width: {
      name: "width"
    },
    height: {
      name: "height"
    }
  }
};
const DiffControlNetLoader$6 = {
  display_name: "Load ControlNet Model (diff)",
  inputs: {
    model: {
      name: "model"
    },
    control_net_name: {
      name: "control_net_name"
    }
  }
};
const DifferentialDiffusion$6 = {
  display_name: "Differential Diffusion",
  inputs: {
    model: {
      name: "model"
    }
  }
};
const DiffusersLoader$6 = {
  display_name: "DiffusersLoader",
  inputs: {
    model_path: {
      name: "model_path"
    }
  }
};
const DisableNoise$6 = {
  display_name: "DisableNoise"
};
const DualCFGGuider$6 = {
  display_name: "DualCFGGuider",
  inputs: {
    model: {
      name: "model"
    },
    cond1: {
      name: "cond1"
    },
    cond2: {
      name: "cond2"
    },
    negative: {
      name: "negative"
    },
    cfg_conds: {
      name: "cfg_conds"
    },
    cfg_cond2_negative: {
      name: "cfg_cond2_negative"
    }
  }
};
const DualCLIPLoader$6 = {
  display_name: "DualCLIPLoader",
  description: "[Recipes]\n\nsdxl: clip-l, clip-g\nsd3: clip-l, clip-g / clip-l, t5 / clip-g, t5\nflux: clip-l, t5\nhidream: at least one of t5 or llama, recommended t5 and llama",
  inputs: {
    clip_name1: {
      name: "clip_name1"
    },
    clip_name2: {
      name: "clip_name2"
    },
    type: {
      name: "type"
    },
    device: {
      name: "device"
    }
  }
};
const EmptyCosmosLatentVideo$6 = {
  display_name: "EmptyCosmosLatentVideo",
  inputs: {
    width: {
      name: "width"
    },
    height: {
      name: "height"
    },
    length: {
      name: "length"
    },
    batch_size: {
      name: "batch_size"
    }
  }
};
const EmptyHunyuanLatentVideo$6 = {
  display_name: "EmptyHunyuanLatentVideo",
  inputs: {
    width: {
      name: "width"
    },
    height: {
      name: "height"
    },
    length: {
      name: "length"
    },
    batch_size: {
      name: "batch_size"
    }
  }
};
const EmptyImage$6 = {
  display_name: "EmptyImage",
  inputs: {
    width: {
      name: "width"
    },
    height: {
      name: "height"
    },
    batch_size: {
      name: "batch_size"
    },
    color: {
      name: "color"
    }
  }
};
const EmptyLatentAudio$6 = {
  display_name: "EmptyLatentAudio",
  inputs: {
    seconds: {
      name: "seconds"
    },
    batch_size: {
      name: "batch_size",
      tooltip: "The number of latent images in the batch."
    }
  }
};
const EmptyLatentHunyuan3Dv2$6 = {
  display_name: "EmptyLatentHunyuan3Dv2",
  inputs: {
    resolution: {
      name: "resolution"
    },
    batch_size: {
      name: "batch_size",
      tooltip: "The number of latent images in the batch."
    }
  }
};
const EmptyLatentImage$6 = {
  display_name: "Empty Latent Image",
  description: "Create a new batch of empty latent images to be denoised via sampling.",
  inputs: {
    width: {
      name: "width",
      tooltip: "The width of the latent images in pixels."
    },
    height: {
      name: "height",
      tooltip: "The height of the latent images in pixels."
    },
    batch_size: {
      name: "batch_size",
      tooltip: "The number of latent images in the batch."
    }
  },
  outputs: {
    "0": {
      tooltip: "The empty latent image batch."
    }
  }
};
const EmptyLTXVLatentVideo$6 = {
  display_name: "EmptyLTXVLatentVideo",
  inputs: {
    width: {
      name: "width"
    },
    height: {
      name: "height"
    },
    length: {
      name: "length"
    },
    batch_size: {
      name: "batch_size"
    }
  }
};
const EmptyMochiLatentVideo$6 = {
  display_name: "EmptyMochiLatentVideo",
  inputs: {
    width: {
      name: "width"
    },
    height: {
      name: "height"
    },
    length: {
      name: "length"
    },
    batch_size: {
      name: "batch_size"
    }
  }
};
const EmptySD3LatentImage$6 = {
  display_name: "EmptySD3LatentImage",
  inputs: {
    width: {
      name: "width"
    },
    height: {
      name: "height"
    },
    batch_size: {
      name: "batch_size"
    }
  }
};
const ExponentialScheduler$6 = {
  display_name: "ExponentialScheduler",
  inputs: {
    steps: {
      name: "steps"
    },
    sigma_max: {
      name: "sigma_max"
    },
    sigma_min: {
      name: "sigma_min"
    }
  }
};
const ExtendIntermediateSigmas$6 = {
  display_name: "ExtendIntermediateSigmas",
  inputs: {
    sigmas: {
      name: "sigmas"
    },
    steps: {
      name: "steps"
    },
    start_at_sigma: {
      name: "start_at_sigma"
    },
    end_at_sigma: {
      name: "end_at_sigma"
    },
    spacing: {
      name: "spacing"
    }
  }
};
const FeatherMask$6 = {
  display_name: "FeatherMask",
  inputs: {
    mask: {
      name: "mask"
    },
    left: {
      name: "left"
    },
    top: {
      name: "top"
    },
    right: {
      name: "right"
    },
    bottom: {
      name: "bottom"
    }
  }
};
const FlipSigmas$6 = {
  display_name: "FlipSigmas",
  inputs: {
    sigmas: {
      name: "sigmas"
    }
  }
};
const FluxDisableGuidance$6 = {
  display_name: "FluxDisableGuidance",
  description: "This node completely disables the guidance embed on Flux and Flux like models",
  inputs: {
    conditioning: {
      name: "conditioning"
    }
  }
};
const FluxGuidance$6 = {
  display_name: "FluxGuidance",
  inputs: {
    conditioning: {
      name: "conditioning"
    },
    guidance: {
      name: "guidance"
    }
  }
};
const FluxProCannyNode$6 = {
  display_name: "Flux.1 Canny Control Image",
  description: "Generate image using a control image (canny).",
  inputs: {
    control_image: {
      name: "control_image"
    },
    prompt: {
      name: "prompt",
      tooltip: "Prompt for the image generation"
    },
    prompt_upsampling: {
      name: "prompt_upsampling",
      tooltip: "Whether to perform upsampling on the prompt. If active, automatically modifies the prompt for more creative generation, but results are nondeterministic (same seed will not produce exactly the same result)."
    },
    canny_low_threshold: {
      name: "canny_low_threshold",
      tooltip: "Low threshold for Canny edge detection; ignored if skip_processing is True"
    },
    canny_high_threshold: {
      name: "canny_high_threshold",
      tooltip: "High threshold for Canny edge detection; ignored if skip_processing is True"
    },
    skip_preprocessing: {
      name: "skip_preprocessing",
      tooltip: "Whether to skip preprocessing; set to True if control_image already is canny-fied, False if it is a raw image."
    },
    guidance: {
      name: "guidance",
      tooltip: "Guidance strength for the image generation process"
    },
    steps: {
      name: "steps",
      tooltip: "Number of steps for the image generation process"
    },
    seed: {
      name: "seed",
      tooltip: "The random seed used for creating the noise."
    },
    control_after_generate: {
      name: "control after generate"
    }
  }
};
const FluxProDepthNode$6 = {
  display_name: "Flux.1 Depth Control Image",
  description: "Generate image using a control image (depth).",
  inputs: {
    control_image: {
      name: "control_image"
    },
    prompt: {
      name: "prompt",
      tooltip: "Prompt for the image generation"
    },
    prompt_upsampling: {
      name: "prompt_upsampling",
      tooltip: "Whether to perform upsampling on the prompt. If active, automatically modifies the prompt for more creative generation, but results are nondeterministic (same seed will not produce exactly the same result)."
    },
    skip_preprocessing: {
      name: "skip_preprocessing",
      tooltip: "Whether to skip preprocessing; set to True if control_image already is depth-ified, False if it is a raw image."
    },
    guidance: {
      name: "guidance",
      tooltip: "Guidance strength for the image generation process"
    },
    steps: {
      name: "steps",
      tooltip: "Number of steps for the image generation process"
    },
    seed: {
      name: "seed",
      tooltip: "The random seed used for creating the noise."
    },
    control_after_generate: {
      name: "control after generate"
    }
  }
};
const FluxProExpandNode$6 = {
  display_name: "Flux.1 Expand Image",
  description: "Outpaints image based on prompt.",
  inputs: {
    image: {
      name: "image"
    },
    prompt: {
      name: "prompt",
      tooltip: "Prompt for the image generation"
    },
    prompt_upsampling: {
      name: "prompt_upsampling",
      tooltip: "Whether to perform upsampling on the prompt. If active, automatically modifies the prompt for more creative generation, but results are nondeterministic (same seed will not produce exactly the same result)."
    },
    top: {
      name: "top",
      tooltip: "Number of pixels to expand at the top of the image"
    },
    bottom: {
      name: "bottom",
      tooltip: "Number of pixels to expand at the bottom of the image"
    },
    left: {
      name: "left",
      tooltip: "Number of pixels to expand at the left side of the image"
    },
    right: {
      name: "right",
      tooltip: "Number of pixels to expand at the right side of the image"
    },
    guidance: {
      name: "guidance",
      tooltip: "Guidance strength for the image generation process"
    },
    steps: {
      name: "steps",
      tooltip: "Number of steps for the image generation process"
    },
    seed: {
      name: "seed",
      tooltip: "The random seed used for creating the noise."
    },
    control_after_generate: {
      name: "control after generate"
    }
  }
};
const FluxProFillNode$6 = {
  display_name: "Flux.1 Fill Image",
  description: "Inpaints image based on mask and prompt.",
  inputs: {
    image: {
      name: "image"
    },
    mask: {
      name: "mask"
    },
    prompt: {
      name: "prompt",
      tooltip: "Prompt for the image generation"
    },
    prompt_upsampling: {
      name: "prompt_upsampling",
      tooltip: "Whether to perform upsampling on the prompt. If active, automatically modifies the prompt for more creative generation, but results are nondeterministic (same seed will not produce exactly the same result)."
    },
    guidance: {
      name: "guidance",
      tooltip: "Guidance strength for the image generation process"
    },
    steps: {
      name: "steps",
      tooltip: "Number of steps for the image generation process"
    },
    seed: {
      name: "seed",
      tooltip: "The random seed used for creating the noise."
    },
    control_after_generate: {
      name: "control after generate"
    }
  }
};
const FluxProUltraImageNode$6 = {
  display_name: "Flux 1.1 [pro] Ultra Image",
  description: "Generates images using Flux Pro 1.1 Ultra via api based on prompt and resolution.",
  inputs: {
    prompt: {
      name: "prompt",
      tooltip: "Prompt for the image generation"
    },
    prompt_upsampling: {
      name: "prompt_upsampling",
      tooltip: "Whether to perform upsampling on the prompt. If active, automatically modifies the prompt for more creative generation, but results are nondeterministic (same seed will not produce exactly the same result)."
    },
    seed: {
      name: "seed",
      tooltip: "The random seed used for creating the noise."
    },
    aspect_ratio: {
      name: "aspect_ratio",
      tooltip: "Aspect ratio of image; must be between 1:4 and 4:1."
    },
    raw: {
      name: "raw",
      tooltip: "When True, generate less processed, more natural-looking images."
    },
    image_prompt: {
      name: "image_prompt"
    },
    image_prompt_strength: {
      name: "image_prompt_strength",
      tooltip: "Blend between the prompt and the image prompt."
    },
    control_after_generate: {
      name: "control after generate"
    }
  }
};
const FreeU$6 = {
  display_name: "FreeU",
  inputs: {
    model: {
      name: "model"
    },
    b1: {
      name: "b1"
    },
    b2: {
      name: "b2"
    },
    s1: {
      name: "s1"
    },
    s2: {
      name: "s2"
    }
  }
};
const FreeU_V2$6 = {
  display_name: "FreeU_V2",
  inputs: {
    model: {
      name: "model"
    },
    b1: {
      name: "b1"
    },
    b2: {
      name: "b2"
    },
    s1: {
      name: "s1"
    },
    s2: {
      name: "s2"
    }
  }
};
const FreSca$6 = {
  display_name: "FreSca",
  description: "Applies frequency-dependent scaling to the guidance",
  inputs: {
    model: {
      name: "model"
    },
    scale_low: {
      name: "scale_low",
      tooltip: "Scaling factor for low-frequency components"
    },
    scale_high: {
      name: "scale_high",
      tooltip: "Scaling factor for high-frequency components"
    },
    freq_cutoff: {
      name: "freq_cutoff",
      tooltip: "Number of frequency indices around center to consider as low-frequency"
    }
  }
};
const GetVideoComponents$6 = {
  display_name: "Get Video Components",
  description: "Extracts all components from a video: frames, audio, and framerate.",
  inputs: {
    video: {
      name: "video",
      tooltip: "The video to extract components from."
    }
  },
  outputs: {
    "0": {
      name: "images"
    },
    "1": {
      name: "audio"
    },
    "2": {
      name: "fps"
    }
  }
};
const GITSScheduler$6 = {
  display_name: "GITSScheduler",
  inputs: {
    coeff: {
      name: "coeff"
    },
    steps: {
      name: "steps"
    },
    denoise: {
      name: "denoise"
    }
  }
};
const GLIGENLoader$6 = {
  display_name: "GLIGENLoader",
  inputs: {
    gligen_name: {
      name: "gligen_name"
    }
  }
};
const GLIGENTextBoxApply$6 = {
  display_name: "GLIGENTextBoxApply",
  inputs: {
    conditioning_to: {
      name: "conditioning_to"
    },
    clip: {
      name: "clip"
    },
    gligen_textbox_model: {
      name: "gligen_textbox_model"
    },
    text: {
      name: "text"
    },
    width: {
      name: "width"
    },
    height: {
      name: "height"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const GrowMask$6 = {
  display_name: "GrowMask",
  inputs: {
    mask: {
      name: "mask"
    },
    expand: {
      name: "expand"
    },
    tapered_corners: {
      name: "tapered_corners"
    }
  }
};
const Hunyuan3Dv2Conditioning$6 = {
  display_name: "Hunyuan3Dv2Conditioning",
  inputs: {
    clip_vision_output: {
      name: "clip_vision_output"
    }
  },
  outputs: {
    "0": {
      name: "positive"
    },
    "1": {
      name: "negative"
    }
  }
};
const Hunyuan3Dv2ConditioningMultiView$6 = {
  display_name: "Hunyuan3Dv2ConditioningMultiView",
  inputs: {
    front: {
      name: "front"
    },
    left: {
      name: "left"
    },
    back: {
      name: "back"
    },
    right: {
      name: "right"
    }
  },
  outputs: {
    "0": {
      name: "positive"
    },
    "1": {
      name: "negative"
    }
  }
};
const HunyuanImageToVideo$6 = {
  display_name: "HunyuanImageToVideo",
  inputs: {
    positive: {
      name: "positive"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "width"
    },
    height: {
      name: "height"
    },
    length: {
      name: "length"
    },
    batch_size: {
      name: "batch_size"
    },
    guidance_type: {
      name: "guidance_type"
    },
    start_image: {
      name: "start_image"
    }
  },
  outputs: {
    "0": {
      name: "positive"
    },
    "1": {
      name: "latent"
    }
  }
};
const HypernetworkLoader$6 = {
  display_name: "HypernetworkLoader",
  inputs: {
    model: {
      name: "model"
    },
    hypernetwork_name: {
      name: "hypernetwork_name"
    },
    strength: {
      name: "strength"
    }
  }
};
const HyperTile$6 = {
  display_name: "HyperTile",
  inputs: {
    model: {
      name: "model"
    },
    tile_size: {
      name: "tile_size"
    },
    swap_size: {
      name: "swap_size"
    },
    max_depth: {
      name: "max_depth"
    },
    scale_depth: {
      name: "scale_depth"
    }
  }
};
const IdeogramV1$6 = {
  display_name: "Ideogram V1",
  description: "Generates images synchronously using the Ideogram V1 model.\n\nImages links are available for a limited period of time; if you would like to keep the image, you must download it.",
  inputs: {
    prompt: {
      name: "prompt",
      tooltip: "Prompt for the image generation"
    },
    turbo: {
      name: "turbo",
      tooltip: "Whether to use turbo mode (faster generation, potentially lower quality)"
    },
    aspect_ratio: {
      name: "aspect_ratio",
      tooltip: "The aspect ratio for image generation."
    },
    magic_prompt_option: {
      name: "magic_prompt_option",
      tooltip: "Determine if MagicPrompt should be used in generation"
    },
    seed: {
      name: "seed"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Description of what to exclude from the image"
    },
    num_images: {
      name: "num_images"
    },
    control_after_generate: {
      name: "control after generate"
    }
  }
};
const IdeogramV2$6 = {
  display_name: "Ideogram V2",
  description: "Generates images synchronously using the Ideogram V2 model.\n\nImages links are available for a limited period of time; if you would like to keep the image, you must download it.",
  inputs: {
    prompt: {
      name: "prompt",
      tooltip: "Prompt for the image generation"
    },
    turbo: {
      name: "turbo",
      tooltip: "Whether to use turbo mode (faster generation, potentially lower quality)"
    },
    aspect_ratio: {
      name: "aspect_ratio",
      tooltip: "The aspect ratio for image generation. Ignored if resolution is not set to AUTO."
    },
    resolution: {
      name: "resolution",
      tooltip: "The resolution for image generation. If not set to AUTO, this overrides the aspect_ratio setting."
    },
    magic_prompt_option: {
      name: "magic_prompt_option",
      tooltip: "Determine if MagicPrompt should be used in generation"
    },
    seed: {
      name: "seed"
    },
    style_type: {
      name: "style_type",
      tooltip: "Style type for generation (V2 only)"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Description of what to exclude from the image"
    },
    num_images: {
      name: "num_images"
    },
    control_after_generate: {
      name: "control after generate"
    }
  }
};
const IdeogramV3$6 = {
  display_name: "Ideogram V3",
  description: "Generates images synchronously using the Ideogram V3 model.\n\nSupports both regular image generation from text prompts and image editing with mask.\nImages links are available for a limited period of time; if you would like to keep the image, you must download it.",
  inputs: {
    prompt: {
      name: "prompt",
      tooltip: "Prompt for the image generation or editing"
    },
    image: {
      name: "image",
      tooltip: "Optional reference image for image editing."
    },
    mask: {
      name: "mask",
      tooltip: "Optional mask for inpainting (white areas will be replaced)"
    },
    aspect_ratio: {
      name: "aspect_ratio",
      tooltip: "The aspect ratio for image generation. Ignored if resolution is not set to Auto."
    },
    resolution: {
      name: "resolution",
      tooltip: "The resolution for image generation. If not set to Auto, this overrides the aspect_ratio setting."
    },
    magic_prompt_option: {
      name: "magic_prompt_option",
      tooltip: "Determine if MagicPrompt should be used in generation"
    },
    seed: {
      name: "seed"
    },
    num_images: {
      name: "num_images"
    },
    rendering_speed: {
      name: "rendering_speed",
      tooltip: "Controls the trade-off between generation speed and quality"
    },
    control_after_generate: {
      name: "control after generate"
    }
  }
};
const ImageBatch$6 = {
  display_name: "Batch Images",
  inputs: {
    image1: {
      name: "image1"
    },
    image2: {
      name: "image2"
    }
  }
};
const ImageBlend$6 = {
  display_name: "Image Blend",
  inputs: {
    image1: {
      name: "image1"
    },
    image2: {
      name: "image2"
    },
    blend_factor: {
      name: "blend_factor"
    },
    blend_mode: {
      name: "blend_mode"
    }
  }
};
const ImageBlur$6 = {
  display_name: "Image Blur",
  inputs: {
    image: {
      name: "image"
    },
    blur_radius: {
      name: "blur_radius"
    },
    sigma: {
      name: "sigma"
    }
  }
};
const ImageColorToMask$6 = {
  display_name: "ImageColorToMask",
  inputs: {
    image: {
      name: "image"
    },
    color: {
      name: "color"
    }
  }
};
const ImageCompositeMasked$6 = {
  display_name: "ImageCompositeMasked",
  inputs: {
    destination: {
      name: "destination"
    },
    source: {
      name: "source"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    },
    resize_source: {
      name: "resize_source"
    },
    mask: {
      name: "mask"
    }
  }
};
const ImageCrop$6 = {
  display_name: "Image Crop",
  inputs: {
    image: {
      name: "image"
    },
    width: {
      name: "width"
    },
    height: {
      name: "height"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const ImageFromBatch$6 = {
  display_name: "ImageFromBatch",
  inputs: {
    image: {
      name: "image"
    },
    batch_index: {
      name: "batch_index"
    },
    length: {
      name: "length"
    }
  }
};
const ImageInvert$6 = {
  display_name: "Invert Image",
  inputs: {
    image: {
      name: "image"
    }
  }
};
const ImageOnlyCheckpointLoader$6 = {
  display_name: "Image Only Checkpoint Loader (img2vid model)",
  inputs: {
    ckpt_name: {
      name: "ckpt_name"
    }
  }
};
const ImageOnlyCheckpointSave$6 = {
  display_name: "ImageOnlyCheckpointSave",
  inputs: {
    model: {
      name: "model"
    },
    clip_vision: {
      name: "clip_vision"
    },
    vae: {
      name: "vae"
    },
    filename_prefix: {
      name: "filename_prefix"
    }
  }
};
const ImagePadForOutpaint$6 = {
  display_name: "Pad Image for Outpainting",
  inputs: {
    image: {
      name: "image"
    },
    left: {
      name: "left"
    },
    top: {
      name: "top"
    },
    right: {
      name: "right"
    },
    bottom: {
      name: "bottom"
    },
    feathering: {
      name: "feathering"
    }
  }
};
const ImageQuantize$6 = {
  display_name: "Image Quantize",
  inputs: {
    image: {
      name: "image"
    },
    colors: {
      name: "colors"
    },
    dither: {
      name: "dither"
    }
  }
};
const ImageRGBToYUV$6 = {
  display_name: "ImageRGBToYUV",
  inputs: {
    image: {
      name: "image"
    }
  },
  outputs: {
    "0": {
      name: "Y"
    },
    "1": {
      name: "U"
    },
    "2": {
      name: "V"
    }
  }
};
const ImageScale$6 = {
  display_name: "Upscale Image",
  inputs: {
    image: {
      name: "image"
    },
    upscale_method: {
      name: "upscale_method"
    },
    width: {
      name: "width"
    },
    height: {
      name: "height"
    },
    crop: {
      name: "crop"
    }
  }
};
const ImageScaleBy$6 = {
  display_name: "Upscale Image By",
  inputs: {
    image: {
      name: "image"
    },
    upscale_method: {
      name: "upscale_method"
    },
    scale_by: {
      name: "scale_by"
    }
  }
};
const ImageScaleToTotalPixels$6 = {
  display_name: "Scale Image to Total Pixels",
  inputs: {
    image: {
      name: "image"
    },
    upscale_method: {
      name: "upscale_method"
    },
    megapixels: {
      name: "megapixels"
    }
  }
};
const ImageSharpen$6 = {
  display_name: "Image Sharpen",
  inputs: {
    image: {
      name: "image"
    },
    sharpen_radius: {
      name: "sharpen_radius"
    },
    sigma: {
      name: "sigma"
    },
    alpha: {
      name: "alpha"
    }
  }
};
const ImageToMask$6 = {
  display_name: "Convert Image to Mask",
  inputs: {
    image: {
      name: "image"
    },
    channel: {
      name: "channel"
    }
  }
};
const ImageUpscaleWithModel$6 = {
  display_name: "Upscale Image (using Model)",
  inputs: {
    upscale_model: {
      name: "upscale_model"
    },
    image: {
      name: "image"
    }
  }
};
const ImageYUVToRGB$6 = {
  display_name: "ImageYUVToRGB",
  inputs: {
    Y: {
      name: "Y"
    },
    U: {
      name: "U"
    },
    V: {
      name: "V"
    }
  }
};
const InpaintModelConditioning$6 = {
  display_name: "InpaintModelConditioning",
  inputs: {
    positive: {
      name: "positive"
    },
    negative: {
      name: "negative"
    },
    vae: {
      name: "vae"
    },
    pixels: {
      name: "pixels"
    },
    mask: {
      name: "mask"
    },
    noise_mask: {
      name: "noise_mask",
      tooltip: "Add a noise mask to the latent so sampling will only happen within the mask. Might improve results or completely break things depending on the model."
    }
  },
  outputs: {
    "0": {
      name: "positive"
    },
    "1": {
      name: "negative"
    },
    "2": {
      name: "latent"
    }
  }
};
const InstructPixToPixConditioning$6 = {
  display_name: "InstructPixToPixConditioning",
  inputs: {
    positive: {
      name: "positive"
    },
    negative: {
      name: "negative"
    },
    vae: {
      name: "vae"
    },
    pixels: {
      name: "pixels"
    }
  },
  outputs: {
    "0": {
      name: "positive"
    },
    "1": {
      name: "negative"
    },
    "2": {
      name: "latent"
    }
  }
};
const InvertMask$6 = {
  display_name: "InvertMask",
  inputs: {
    mask: {
      name: "mask"
    }
  }
};
const JoinImageWithAlpha$6 = {
  display_name: "Join Image with Alpha",
  inputs: {
    image: {
      name: "image"
    },
    alpha: {
      name: "alpha"
    }
  }
};
const KarrasScheduler$6 = {
  display_name: "KarrasScheduler",
  inputs: {
    steps: {
      name: "steps"
    },
    sigma_max: {
      name: "sigma_max"
    },
    sigma_min: {
      name: "sigma_min"
    },
    rho: {
      name: "rho"
    }
  }
};
const KlingCameraControlI2VNode$6 = {
  display_name: "Kling Image to Video (Camera Control)",
  description: "Transform still images into cinematic videos with professional camera movements that simulate real-world cinematography. Control virtual camera actions including zoom, rotation, pan, tilt, and first-person view, while maintaining focus on your original image.",
  inputs: {
    start_frame: {
      name: "start_frame",
      tooltip: "Reference Image - URL or Base64 encoded string, cannot exceed 10MB, resolution not less than 300*300px, aspect ratio between 1:2.5 ~ 2.5:1. Base64 should not include data:image prefix."
    },
    prompt: {
      name: "prompt",
      tooltip: "Positive text prompt"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Negative text prompt"
    },
    cfg_scale: {
      name: "cfg_scale"
    },
    aspect_ratio: {
      name: "aspect_ratio"
    },
    camera_control: {
      name: "camera_control",
      tooltip: "Can be created using the Kling Camera Controls node. Controls the camera movement and motion during the video generation."
    }
  },
  outputs: {
    "1": {
      name: "video_id"
    },
    "2": {
      name: "duration"
    }
  }
};
const KlingCameraControls$6 = {
  display_name: "Kling Camera Controls",
  description: "Allows specifying configuration options for Kling Camera Controls and motion control effects.",
  inputs: {
    camera_control_type: {
      name: "camera_control_type"
    },
    horizontal_movement: {
      name: "horizontal_movement",
      tooltip: "Controls camera's movement along horizontal axis (x-axis). Negative indicates left, positive indicates right"
    },
    vertical_movement: {
      name: "vertical_movement",
      tooltip: "Controls camera's movement along vertical axis (y-axis). Negative indicates downward, positive indicates upward."
    },
    pan: {
      name: "pan",
      tooltip: "Controls camera's rotation in vertical plane (x-axis). Negative indicates downward rotation, positive indicates upward rotation."
    },
    tilt: {
      name: "tilt",
      tooltip: "Controls camera's rotation in horizontal plane (y-axis). Negative indicates left rotation, positive indicates right rotation."
    },
    roll: {
      name: "roll",
      tooltip: "Controls camera's rolling amount (z-axis). Negative indicates counterclockwise, positive indicates clockwise."
    },
    zoom: {
      name: "zoom",
      tooltip: "Controls change in camera's focal length. Negative indicates narrower field of view, positive indicates wider field of view."
    }
  },
  outputs: {
    "0": {
      name: "camera_control"
    }
  }
};
const KlingCameraControlT2VNode$6 = {
  display_name: "Kling Text to Video (Camera Control)",
  description: "Transform text into cinematic videos with professional camera movements that simulate real-world cinematography. Control virtual camera actions including zoom, rotation, pan, tilt, and first-person view, while maintaining focus on your original text.",
  inputs: {
    prompt: {
      name: "prompt",
      tooltip: "Positive text prompt"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Negative text prompt"
    },
    cfg_scale: {
      name: "cfg_scale"
    },
    aspect_ratio: {
      name: "aspect_ratio"
    },
    camera_control: {
      name: "camera_control",
      tooltip: "Can be created using the Kling Camera Controls node. Controls the camera movement and motion during the video generation."
    }
  },
  outputs: {
    "1": {
      name: "video_id"
    },
    "2": {
      name: "duration"
    }
  }
};
const KlingDualCharacterVideoEffectNode$6 = {
  display_name: "Kling Dual Character Video Effects",
  description: "Achieve different special effects when generating a video based on the effect_scene. First image will be positioned on left side, second on right side of the composite.",
  inputs: {
    image_left: {
      name: "image_left",
      tooltip: "Left side image"
    },
    image_right: {
      name: "image_right",
      tooltip: "Right side image"
    },
    effect_scene: {
      name: "effect_scene"
    },
    model_name: {
      name: "model_name"
    },
    mode: {
      name: "mode"
    },
    duration: {
      name: "duration"
    }
  },
  outputs: {
    "1": {
      name: "duration"
    }
  }
};
const KlingImage2VideoNode$6 = {
  display_name: "Kling Image to Video",
  description: "Kling Image to Video Node",
  inputs: {
    start_frame: {
      name: "start_frame",
      tooltip: "Reference Image - URL or Base64 encoded string, cannot exceed 10MB, resolution not less than 300*300px, aspect ratio between 1:2.5 ~ 2.5:1. Base64 should not include data:image prefix."
    },
    prompt: {
      name: "prompt",
      tooltip: "Positive text prompt"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Negative text prompt"
    },
    model_name: {
      name: "model_name"
    },
    cfg_scale: {
      name: "cfg_scale"
    },
    mode: {
      name: "mode"
    },
    aspect_ratio: {
      name: "aspect_ratio"
    },
    duration: {
      name: "duration"
    }
  },
  outputs: {
    "1": {
      name: "video_id"
    },
    "2": {
      name: "duration"
    }
  }
};
const KlingImageGenerationNode$6 = {
  display_name: "Kling Image Generation",
  description: "Kling Image Generation Node. Generate an image from a text prompt with an optional reference image.",
  inputs: {
    prompt: {
      name: "prompt",
      tooltip: "Positive text prompt"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Negative text prompt"
    },
    image_type: {
      name: "image_type"
    },
    image_fidelity: {
      name: "image_fidelity",
      tooltip: "Reference intensity for user-uploaded images"
    },
    human_fidelity: {
      name: "human_fidelity",
      tooltip: "Subject reference similarity"
    },
    model_name: {
      name: "model_name"
    },
    aspect_ratio: {
      name: "aspect_ratio"
    },
    n: {
      name: "n",
      tooltip: "Number of generated images"
    },
    image: {
      name: "image"
    }
  }
};
const KlingLipSyncAudioToVideoNode$6 = {
  display_name: "Kling Lip Sync Video with Audio",
  description: "Kling Lip Sync Audio to Video Node. Syncs mouth movements in a video file to the audio content of an audio file.",
  inputs: {
    video: {
      name: "video"
    },
    audio: {
      name: "audio"
    },
    voice_language: {
      name: "voice_language"
    }
  },
  outputs: {
    "1": {
      name: "video_id"
    },
    "2": {
      name: "duration"
    }
  }
};
const KlingLipSyncTextToVideoNode$6 = {
  display_name: "Kling Lip Sync Video with Text",
  description: "Kling Lip Sync Text to Video Node. Syncs mouth movements in a video file to a text prompt.",
  inputs: {
    video: {
      name: "video"
    },
    text: {
      name: "text",
      tooltip: "Text Content for Lip-Sync Video Generation. Required when mode is text2video. Maximum length is 120 characters."
    },
    voice: {
      name: "voice"
    },
    voice_speed: {
      name: "voice_speed",
      tooltip: "Speech Rate. Valid range: 0.8~2.0, accurate to one decimal place."
    }
  },
  outputs: {
    "1": {
      name: "video_id"
    },
    "2": {
      name: "duration"
    }
  }
};
const KlingSingleImageVideoEffectNode$6 = {
  display_name: "Kling Video Effects",
  description: "Achieve different special effects when generating a video based on the effect_scene.",
  inputs: {
    image: {
      name: "image",
      tooltip: " Reference Image. URL or Base64 encoded string (without data:image prefix). File size cannot exceed 10MB, resolution not less than 300*300px, aspect ratio between 1:2.5 ~ 2.5:1"
    },
    effect_scene: {
      name: "effect_scene"
    },
    model_name: {
      name: "model_name"
    },
    duration: {
      name: "duration"
    }
  },
  outputs: {
    "1": {
      name: "video_id"
    },
    "2": {
      name: "duration"
    }
  }
};
const KlingStartEndFrameNode$6 = {
  display_name: "Kling Start-End Frame to Video",
  description: "Generate a video sequence that transitions between your provided start and end images. The node creates all frames in between, producing a smooth transformation from the first frame to the last.",
  inputs: {
    start_frame: {
      name: "start_frame",
      tooltip: "Reference Image - URL or Base64 encoded string, cannot exceed 10MB, resolution not less than 300*300px, aspect ratio between 1:2.5 ~ 2.5:1. Base64 should not include data:image prefix."
    },
    end_frame: {
      name: "end_frame",
      tooltip: "Reference Image - End frame control. URL or Base64 encoded string, cannot exceed 10MB, resolution not less than 300*300px. Base64 should not include data:image prefix."
    },
    prompt: {
      name: "prompt",
      tooltip: "Positive text prompt"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Negative text prompt"
    },
    cfg_scale: {
      name: "cfg_scale"
    },
    aspect_ratio: {
      name: "aspect_ratio"
    },
    mode: {
      name: "mode",
      tooltip: "The configuration to use for the video generation following the format: mode / duration / model_name."
    }
  },
  outputs: {
    "1": {
      name: "video_id"
    },
    "2": {
      name: "duration"
    }
  }
};
const KlingTextToVideoNode$6 = {
  display_name: "Kling Text to Video",
  description: "Kling Text to Video Node",
  inputs: {
    prompt: {
      name: "prompt",
      tooltip: "Positive text prompt"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Negative text prompt"
    },
    cfg_scale: {
      name: "cfg_scale"
    },
    aspect_ratio: {
      name: "aspect_ratio"
    },
    mode: {
      name: "mode",
      tooltip: "The configuration to use for the video generation following the format: mode / duration / model_name."
    }
  },
  outputs: {
    "1": {
      name: "video_id"
    },
    "2": {
      name: "duration"
    }
  }
};
const KlingVideoExtendNode$6 = {
  display_name: "Kling Video Extend",
  description: "Kling Video Extend Node. Extend videos made by other Kling nodes. The video_id is created by using other Kling Nodes.",
  inputs: {
    prompt: {
      name: "prompt",
      tooltip: "Positive text prompt for guiding the video extension"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Negative text prompt for elements to avoid in the extended video"
    },
    cfg_scale: {
      name: "cfg_scale"
    },
    video_id: {
      name: "video_id",
      tooltip: "The ID of the video to be extended. Supports videos generated by text-to-video, image-to-video, and previous video extension operations. Cannot exceed 3 minutes total duration after extension."
    }
  },
  outputs: {
    "1": {
      name: "video_id"
    },
    "2": {
      name: "duration"
    }
  }
};
const KlingVirtualTryOnNode$6 = {
  display_name: "Kling Virtual Try On",
  description: "Kling Virtual Try On Node. Input a human image and a cloth image to try on the cloth on the human.",
  inputs: {
    human_image: {
      name: "human_image"
    },
    cloth_image: {
      name: "cloth_image"
    },
    model_name: {
      name: "model_name"
    }
  }
};
const KSampler$6 = {
  display_name: "KSampler",
  description: "Uses the provided model, positive and negative conditioning to denoise the latent image.",
  inputs: {
    model: {
      name: "model",
      tooltip: "The model used for denoising the input latent."
    },
    seed: {
      name: "seed",
      tooltip: "The random seed used for creating the noise."
    },
    steps: {
      name: "steps",
      tooltip: "The number of steps used in the denoising process."
    },
    cfg: {
      name: "cfg",
      tooltip: "The Classifier-Free Guidance scale balances creativity and adherence to the prompt. Higher values result in images more closely matching the prompt however too high values will negatively impact quality."
    },
    sampler_name: {
      name: "sampler_name",
      tooltip: "The algorithm used when sampling, this can affect the quality, speed, and style of the generated output."
    },
    scheduler: {
      name: "scheduler",
      tooltip: "The scheduler controls how noise is gradually removed to form the image."
    },
    positive: {
      name: "positive",
      tooltip: "The conditioning describing the attributes you want to include in the image."
    },
    negative: {
      name: "negative",
      tooltip: "The conditioning describing the attributes you want to exclude from the image."
    },
    latent_image: {
      name: "latent_image",
      tooltip: "The latent image to denoise."
    },
    denoise: {
      name: "denoise",
      tooltip: "The amount of denoising applied, lower values will maintain the structure of the initial image allowing for image to image sampling."
    },
    control_after_generate: {
      name: "control after generate"
    }
  },
  outputs: {
    "0": {
      tooltip: "The denoised latent."
    }
  }
};
const KSamplerAdvanced$6 = {
  display_name: "KSampler (Advanced)",
  inputs: {
    model: {
      name: "model"
    },
    add_noise: {
      name: "add_noise"
    },
    noise_seed: {
      name: "noise_seed"
    },
    steps: {
      name: "steps"
    },
    cfg: {
      name: "cfg"
    },
    sampler_name: {
      name: "sampler_name"
    },
    scheduler: {
      name: "scheduler"
    },
    positive: {
      name: "positive"
    },
    negative: {
      name: "negative"
    },
    latent_image: {
      name: "latent_image"
    },
    start_at_step: {
      name: "start_at_step"
    },
    end_at_step: {
      name: "end_at_step"
    },
    return_with_leftover_noise: {
      name: "return_with_leftover_noise"
    },
    control_after_generate: {
      name: "control after generate"
    }
  }
};
const KSamplerSelect$6 = {
  display_name: "KSamplerSelect",
  inputs: {
    sampler_name: {
      name: "sampler_name"
    }
  }
};
const LaplaceScheduler$6 = {
  display_name: "LaplaceScheduler",
  inputs: {
    steps: {
      name: "steps"
    },
    sigma_max: {
      name: "sigma_max"
    },
    sigma_min: {
      name: "sigma_min"
    },
    mu: {
      name: "mu"
    },
    beta: {
      name: "beta"
    }
  }
};
const LatentAdd$6 = {
  display_name: "LatentAdd",
  inputs: {
    samples1: {
      name: "samples1"
    },
    samples2: {
      name: "samples2"
    }
  }
};
const LatentApplyOperation$6 = {
  display_name: "LatentApplyOperation",
  inputs: {
    samples: {
      name: "samples"
    },
    operation: {
      name: "operation"
    }
  }
};
const LatentApplyOperationCFG$6 = {
  display_name: "LatentApplyOperationCFG",
  inputs: {
    model: {
      name: "model"
    },
    operation: {
      name: "operation"
    }
  }
};
const LatentBatch$6 = {
  display_name: "LatentBatch",
  inputs: {
    samples1: {
      name: "samples1"
    },
    samples2: {
      name: "samples2"
    }
  }
};
const LatentBatchSeedBehavior$6 = {
  display_name: "LatentBatchSeedBehavior",
  inputs: {
    samples: {
      name: "samples"
    },
    seed_behavior: {
      name: "seed_behavior"
    }
  }
};
const LatentBlend$6 = {
  display_name: "Latent Blend",
  inputs: {
    samples1: {
      name: "samples1"
    },
    samples2: {
      name: "samples2"
    },
    blend_factor: {
      name: "blend_factor"
    }
  }
};
const LatentComposite$6 = {
  display_name: "Latent Composite",
  inputs: {
    samples_to: {
      name: "samples_to"
    },
    samples_from: {
      name: "samples_from"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    },
    feather: {
      name: "feather"
    }
  }
};
const LatentCompositeMasked$6 = {
  display_name: "LatentCompositeMasked",
  inputs: {
    destination: {
      name: "destination"
    },
    source: {
      name: "source"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    },
    resize_source: {
      name: "resize_source"
    },
    mask: {
      name: "mask"
    }
  }
};
const LatentCrop$6 = {
  display_name: "Crop Latent",
  inputs: {
    samples: {
      name: "samples"
    },
    width: {
      name: "width"
    },
    height: {
      name: "height"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const LatentFlip$6 = {
  display_name: "Flip Latent",
  inputs: {
    samples: {
      name: "samples"
    },
    flip_method: {
      name: "flip_method"
    }
  }
};
const LatentFromBatch$6 = {
  display_name: "Latent From Batch",
  inputs: {
    samples: {
      name: "samples"
    },
    batch_index: {
      name: "batch_index"
    },
    length: {
      name: "length"
    }
  }
};
const LatentInterpolate$6 = {
  display_name: "LatentInterpolate",
  inputs: {
    samples1: {
      name: "samples1"
    },
    samples2: {
      name: "samples2"
    },
    ratio: {
      name: "ratio"
    }
  }
};
const LatentMultiply$6 = {
  display_name: "LatentMultiply",
  inputs: {
    samples: {
      name: "samples"
    },
    multiplier: {
      name: "multiplier"
    }
  }
};
const LatentOperationSharpen$6 = {
  display_name: "LatentOperationSharpen",
  inputs: {
    sharpen_radius: {
      name: "sharpen_radius"
    },
    sigma: {
      name: "sigma"
    },
    alpha: {
      name: "alpha"
    }
  }
};
const LatentOperationTonemapReinhard$6 = {
  display_name: "LatentOperationTonemapReinhard",
  inputs: {
    multiplier: {
      name: "multiplier"
    }
  }
};
const LatentRotate$6 = {
  display_name: "Rotate Latent",
  inputs: {
    samples: {
      name: "samples"
    },
    rotation: {
      name: "rotation"
    }
  }
};
const LatentSubtract$6 = {
  display_name: "LatentSubtract",
  inputs: {
    samples1: {
      name: "samples1"
    },
    samples2: {
      name: "samples2"
    }
  }
};
const LatentUpscale$6 = {
  display_name: "Upscale Latent",
  inputs: {
    samples: {
      name: "samples"
    },
    upscale_method: {
      name: "upscale_method"
    },
    width: {
      name: "width"
    },
    height: {
      name: "height"
    },
    crop: {
      name: "crop"
    }
  }
};
const LatentUpscaleBy$6 = {
  display_name: "Upscale Latent By",
  inputs: {
    samples: {
      name: "samples"
    },
    upscale_method: {
      name: "upscale_method"
    },
    scale_by: {
      name: "scale_by"
    }
  }
};
const Load3D$6 = {
  display_name: "Load 3D",
  inputs: {
    model_file: {
      name: "model_file"
    },
    image: {
      name: "image"
    },
    width: {
      name: "width"
    },
    height: {
      name: "height"
    },
    clear: {},
    "upload 3d model": {}
  },
  outputs: {
    "0": {
      name: "image"
    },
    "1": {
      name: "mask"
    },
    "2": {
      name: "mesh_path"
    },
    "3": {
      name: "normal"
    },
    "4": {
      name: "lineart"
    },
    "5": {
      name: "camera_info"
    }
  }
};
const Load3DAnimation$6 = {
  display_name: "Load 3D - Animation",
  inputs: {
    model_file: {
      name: "model_file"
    },
    image: {
      name: "image"
    },
    width: {
      name: "width"
    },
    height: {
      name: "height"
    },
    clear: {},
    "upload 3d model": {}
  },
  outputs: {
    "0": {
      name: "image"
    },
    "1": {
      name: "mask"
    },
    "2": {
      name: "mesh_path"
    },
    "3": {
      name: "normal"
    },
    "4": {
      name: "camera_info"
    }
  }
};
const LoadAudio$6 = {
  display_name: "LoadAudio",
  inputs: {
    audio: {
      name: "audio"
    },
    audioUI: {
      name: "audioUI"
    },
    upload: {
      name: "choose file to upload"
    }
  }
};
const LoadImage$6 = {
  display_name: "Load Image",
  inputs: {
    image: {
      name: "image"
    },
    upload: {
      name: "choose file to upload"
    }
  }
};
const LoadImageMask$6 = {
  display_name: "Load Image (as Mask)",
  inputs: {
    image: {
      name: "image"
    },
    channel: {
      name: "channel"
    },
    upload: {
      name: "choose file to upload"
    }
  }
};
const LoadImageOutput$6 = {
  display_name: "Load Image (from Outputs)",
  description: "Load an image from the output folder. When the refresh button is clicked, the node will update the image list and automatically select the first image, allowing for easy iteration.",
  inputs: {
    image: {
      name: "image"
    },
    refresh: {},
    upload: {
      name: "choose file to upload"
    }
  }
};
const LoadLatent$6 = {
  display_name: "LoadLatent",
  inputs: {
    latent: {
      name: "latent"
    }
  }
};
const LoadVideo$6 = {
  display_name: "Load Video",
  inputs: {
    file: {
      name: "file"
    },
    upload: {
      name: "choose file to upload"
    }
  }
};
const LoraLoader$6 = {
  display_name: "Load LoRA",
  description: "LoRAs are used to modify diffusion and CLIP models, altering the way in which latents are denoised such as applying styles. Multiple LoRA nodes can be linked together.",
  inputs: {
    model: {
      name: "model",
      tooltip: "The diffusion model the LoRA will be applied to."
    },
    clip: {
      name: "clip",
      tooltip: "The CLIP model the LoRA will be applied to."
    },
    lora_name: {
      name: "lora_name",
      tooltip: "The name of the LoRA."
    },
    strength_model: {
      name: "strength_model",
      tooltip: "How strongly to modify the diffusion model. This value can be negative."
    },
    strength_clip: {
      name: "strength_clip",
      tooltip: "How strongly to modify the CLIP model. This value can be negative."
    }
  },
  outputs: {
    "0": {
      tooltip: "The modified diffusion model."
    },
    "1": {
      tooltip: "The modified CLIP model."
    }
  }
};
const LoraLoaderModelOnly$6 = {
  display_name: "LoraLoaderModelOnly",
  description: "LoRAs are used to modify diffusion and CLIP models, altering the way in which latents are denoised such as applying styles. Multiple LoRA nodes can be linked together.",
  inputs: {
    model: {
      name: "model"
    },
    lora_name: {
      name: "lora_name"
    },
    strength_model: {
      name: "strength_model"
    }
  },
  outputs: {
    "0": {
      tooltip: "The modified diffusion model."
    }
  }
};
const LoraSave$6 = {
  display_name: "Extract and Save Lora",
  inputs: {
    filename_prefix: {
      name: "filename_prefix"
    },
    rank: {
      name: "rank"
    },
    lora_type: {
      name: "lora_type"
    },
    bias_diff: {
      name: "bias_diff"
    },
    model_diff: {
      name: "model_diff",
      tooltip: "The ModelSubtract output to be converted to a lora."
    },
    text_encoder_diff: {
      name: "text_encoder_diff",
      tooltip: "The CLIPSubtract output to be converted to a lora."
    }
  }
};
const LotusConditioning$6 = {
  display_name: "LotusConditioning",
  outputs: {
    "0": {
      name: "conditioning"
    }
  }
};
const LTXVAddGuide$6 = {
  display_name: "LTXVAddGuide",
  inputs: {
    positive: {
      name: "positive"
    },
    negative: {
      name: "negative"
    },
    vae: {
      name: "vae"
    },
    latent: {
      name: "latent"
    },
    image: {
      name: "image",
      tooltip: "Image or video to condition the latent video on. Must be 8*n + 1 frames.If the video is not 8*n + 1 frames, it will be cropped to the nearest 8*n + 1 frames."
    },
    frame_idx: {
      name: "frame_idx",
      tooltip: "Frame index to start the conditioning at. For single-frame images or videos with 1-8 frames, any frame_idx value is acceptable. For videos with 9+ frames, frame_idx must be divisible by 8, otherwise it will be rounded down to the nearest multiple of 8. Negative values are counted from the end of the video."
    },
    strength: {
      name: "strength"
    }
  },
  outputs: {
    "0": {
      name: "positive"
    },
    "1": {
      name: "negative"
    },
    "2": {
      name: "latent"
    }
  }
};
const LTXVConditioning$6 = {
  display_name: "LTXVConditioning",
  inputs: {
    positive: {
      name: "positive"
    },
    negative: {
      name: "negative"
    },
    frame_rate: {
      name: "frame_rate"
    }
  },
  outputs: {
    "0": {
      name: "positive"
    },
    "1": {
      name: "negative"
    }
  }
};
const LTXVCropGuides$6 = {
  display_name: "LTXVCropGuides",
  inputs: {
    positive: {
      name: "positive"
    },
    negative: {
      name: "negative"
    },
    latent: {
      name: "latent"
    }
  },
  outputs: {
    "0": {
      name: "positive"
    },
    "1": {
      name: "negative"
    },
    "2": {
      name: "latent"
    }
  }
};
const LTXVImgToVideo$6 = {
  display_name: "LTXVImgToVideo",
  inputs: {
    positive: {
      name: "positive"
    },
    negative: {
      name: "negative"
    },
    vae: {
      name: "vae"
    },
    image: {
      name: "image"
    },
    width: {
      name: "width"
    },
    height: {
      name: "height"
    },
    length: {
      name: "length"
    },
    batch_size: {
      name: "batch_size"
    },
    strength: {
      name: "strength"
    }
  },
  outputs: {
    "0": {
      name: "positive"
    },
    "1": {
      name: "negative"
    },
    "2": {
      name: "latent"
    }
  }
};
const LTXVPreprocess$6 = {
  display_name: "LTXVPreprocess",
  inputs: {
    image: {
      name: "image"
    },
    img_compression: {
      name: "img_compression",
      tooltip: "Amount of compression to apply on image."
    }
  },
  outputs: {
    "0": {
      name: "output_image"
    }
  }
};
const LTXVScheduler$6 = {
  display_name: "LTXVScheduler",
  inputs: {
    steps: {
      name: "steps"
    },
    max_shift: {
      name: "max_shift"
    },
    base_shift: {
      name: "base_shift"
    },
    stretch: {
      name: "stretch",
      tooltip: "Stretch the sigmas to be in the range [terminal, 1]."
    },
    terminal: {
      name: "terminal",
      tooltip: "The terminal value of the sigmas after stretching."
    },
    latent: {
      name: "latent"
    }
  }
};
const LumaConceptsNode$6 = {
  display_name: "Luma Concepts",
  description: "Holds one or more Camera Concepts for use with Luma Text to Video and Luma Image to Video nodes.",
  inputs: {
    concept1: {
      name: "concept1"
    },
    concept2: {
      name: "concept2"
    },
    concept3: {
      name: "concept3"
    },
    concept4: {
      name: "concept4"
    },
    luma_concepts: {
      name: "luma_concepts",
      tooltip: "Optional Camera Concepts to add to the ones chosen here."
    }
  },
  outputs: {
    "0": {
      name: "luma_concepts"
    }
  }
};
const LumaImageModifyNode$6 = {
  display_name: "Luma Image to Image",
  description: "Modifies images synchronously based on prompt and aspect ratio.",
  inputs: {
    image: {
      name: "image"
    },
    prompt: {
      name: "prompt",
      tooltip: "Prompt for the image generation"
    },
    image_weight: {
      name: "image_weight",
      tooltip: "Weight of the image; the closer to 1.0, the less the image will be modified."
    },
    model: {
      name: "model"
    },
    seed: {
      name: "seed",
      tooltip: "Seed to determine if node should re-run; actual results are nondeterministic regardless of seed."
    },
    control_after_generate: {
      name: "control after generate"
    }
  }
};
const LumaImageNode$6 = {
  display_name: "Luma Text to Image",
  description: "Generates images synchronously based on prompt and aspect ratio.",
  inputs: {
    prompt: {
      name: "prompt",
      tooltip: "Prompt for the image generation"
    },
    model: {
      name: "model"
    },
    aspect_ratio: {
      name: "aspect_ratio"
    },
    seed: {
      name: "seed",
      tooltip: "Seed to determine if node should re-run; actual results are nondeterministic regardless of seed."
    },
    style_image_weight: {
      name: "style_image_weight",
      tooltip: "Weight of style image. Ignored if no style_image provided."
    },
    image_luma_ref: {
      name: "image_luma_ref",
      tooltip: "Luma Reference node connection to influence generation with input images; up to 4 images can be considered."
    },
    style_image: {
      name: "style_image",
      tooltip: "Style reference image; only 1 image will be used."
    },
    character_image: {
      name: "character_image",
      tooltip: "Character reference images; can be a batch of multiple, up to 4 images can be considered."
    },
    control_after_generate: {
      name: "control after generate"
    }
  }
};
const LumaImageToVideoNode$6 = {
  display_name: "Luma Image to Video",
  description: "Generates videos synchronously based on prompt, input images, and output_size.",
  inputs: {
    prompt: {
      name: "prompt",
      tooltip: "Prompt for the video generation"
    },
    model: {
      name: "model"
    },
    resolution: {
      name: "resolution"
    },
    duration: {
      name: "duration"
    },
    loop: {
      name: "loop"
    },
    seed: {
      name: "seed",
      tooltip: "Seed to determine if node should re-run; actual results are nondeterministic regardless of seed."
    },
    first_image: {
      name: "first_image",
      tooltip: "First frame of generated video."
    },
    last_image: {
      name: "last_image",
      tooltip: "Last frame of generated video."
    },
    luma_concepts: {
      name: "luma_concepts",
      tooltip: "Optional Camera Concepts to dictate camera motion via the Luma Concepts node."
    },
    control_after_generate: {
      name: "control after generate"
    }
  }
};
const LumaReferenceNode$6 = {
  display_name: "Luma Reference",
  description: "Holds an image and weight for use with Luma Generate Image node.",
  inputs: {
    image: {
      name: "image",
      tooltip: "Image to use as reference."
    },
    weight: {
      name: "weight",
      tooltip: "Weight of image reference."
    },
    luma_ref: {
      name: "luma_ref"
    }
  },
  outputs: {
    "0": {
      name: "luma_ref"
    }
  }
};
const LumaVideoNode$6 = {
  display_name: "Luma Text to Video",
  description: "Generates videos synchronously based on prompt and output_size.",
  inputs: {
    prompt: {
      name: "prompt",
      tooltip: "Prompt for the video generation"
    },
    model: {
      name: "model"
    },
    aspect_ratio: {
      name: "aspect_ratio"
    },
    resolution: {
      name: "resolution"
    },
    duration: {
      name: "duration"
    },
    loop: {
      name: "loop"
    },
    seed: {
      name: "seed",
      tooltip: "Seed to determine if node should re-run; actual results are nondeterministic regardless of seed."
    },
    luma_concepts: {
      name: "luma_concepts",
      tooltip: "Optional Camera Concepts to dictate camera motion via the Luma Concepts node."
    },
    control_after_generate: {
      name: "control after generate"
    }
  }
};
const Mahiro$6 = {
  display_name: "Mahiro is so cute that she deserves a better guidance function!! (。・ω・。)",
  description: "Modify the guidance to scale more on the 'direction' of the positive prompt rather than the difference between the negative prompt.",
  inputs: {
    model: {
      name: "model"
    }
  },
  outputs: {
    "0": {
      name: "patched_model"
    }
  }
};
const MaskComposite$6 = {
  display_name: "MaskComposite",
  inputs: {
    destination: {
      name: "destination"
    },
    source: {
      name: "source"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    },
    operation: {
      name: "operation"
    }
  }
};
const MaskPreview$6 = {
  display_name: "MaskPreview",
  description: "Saves the input images to your ComfyUI output directory.",
  inputs: {
    mask: {
      name: "mask"
    }
  }
};
const MaskToImage$6 = {
  display_name: "Convert Mask to Image",
  inputs: {
    mask: {
      name: "mask"
    }
  }
};
const MinimaxImageToVideoNode$6 = {
  display_name: "MiniMax Image to Video",
  description: "Generates videos from an image and prompts using MiniMax's API",
  inputs: {
    image: {
      name: "image",
      tooltip: "Image to use as first frame of video generation"
    },
    prompt_text: {
      name: "prompt_text",
      tooltip: "Text prompt to guide the video generation"
    },
    model: {
      name: "model",
      tooltip: "Model to use for video generation"
    },
    seed: {
      name: "seed",
      tooltip: "The random seed used for creating the noise."
    },
    control_after_generate: {
      name: "control after generate"
    }
  }
};
const MinimaxTextToVideoNode$6 = {
  display_name: "MiniMax Text to Video",
  description: "Generates videos from prompts using MiniMax's API",
  inputs: {
    prompt_text: {
      name: "prompt_text",
      tooltip: "Text prompt to guide the video generation"
    },
    model: {
      name: "model",
      tooltip: "Model to use for video generation"
    },
    seed: {
      name: "seed",
      tooltip: "The random seed used for creating the noise."
    },
    control_after_generate: {
      name: "control after generate"
    }
  }
};
const ModelComputeDtype$6 = {
  display_name: "ModelComputeDtype",
  inputs: {
    model: {
      name: "model"
    },
    dtype: {
      name: "dtype"
    }
  }
};
const ModelMergeAdd$6 = {
  display_name: "ModelMergeAdd",
  inputs: {
    model1: {
      name: "model1"
    },
    model2: {
      name: "model2"
    }
  }
};
const ModelMergeAuraflow$6 = {
  display_name: "ModelMergeAuraflow",
  inputs: {
    model1: {
      name: "model1"
    },
    model2: {
      name: "model2"
    },
    init_x_linear_: {
      name: "init_x_linear."
    },
    positional_encoding: {
      name: "positional_encoding"
    },
    cond_seq_linear_: {
      name: "cond_seq_linear."
    },
    register_tokens: {
      name: "register_tokens"
    },
    t_embedder_: {
      name: "t_embedder."
    },
    double_layers_0_: {
      name: "double_layers.0."
    },
    double_layers_1_: {
      name: "double_layers.1."
    },
    double_layers_2_: {
      name: "double_layers.2."
    },
    double_layers_3_: {
      name: "double_layers.3."
    },
    single_layers_0_: {
      name: "single_layers.0."
    },
    single_layers_1_: {
      name: "single_layers.1."
    },
    single_layers_2_: {
      name: "single_layers.2."
    },
    single_layers_3_: {
      name: "single_layers.3."
    },
    single_layers_4_: {
      name: "single_layers.4."
    },
    single_layers_5_: {
      name: "single_layers.5."
    },
    single_layers_6_: {
      name: "single_layers.6."
    },
    single_layers_7_: {
      name: "single_layers.7."
    },
    single_layers_8_: {
      name: "single_layers.8."
    },
    single_layers_9_: {
      name: "single_layers.9."
    },
    single_layers_10_: {
      name: "single_layers.10."
    },
    single_layers_11_: {
      name: "single_layers.11."
    },
    single_layers_12_: {
      name: "single_layers.12."
    },
    single_layers_13_: {
      name: "single_layers.13."
    },
    single_layers_14_: {
      name: "single_layers.14."
    },
    single_layers_15_: {
      name: "single_layers.15."
    },
    single_layers_16_: {
      name: "single_layers.16."
    },
    single_layers_17_: {
      name: "single_layers.17."
    },
    single_layers_18_: {
      name: "single_layers.18."
    },
    single_layers_19_: {
      name: "single_layers.19."
    },
    single_layers_20_: {
      name: "single_layers.20."
    },
    single_layers_21_: {
      name: "single_layers.21."
    },
    single_layers_22_: {
      name: "single_layers.22."
    },
    single_layers_23_: {
      name: "single_layers.23."
    },
    single_layers_24_: {
      name: "single_layers.24."
    },
    single_layers_25_: {
      name: "single_layers.25."
    },
    single_layers_26_: {
      name: "single_layers.26."
    },
    single_layers_27_: {
      name: "single_layers.27."
    },
    single_layers_28_: {
      name: "single_layers.28."
    },
    single_layers_29_: {
      name: "single_layers.29."
    },
    single_layers_30_: {
      name: "single_layers.30."
    },
    single_layers_31_: {
      name: "single_layers.31."
    },
    modF_: {
      name: "modF."
    },
    final_linear_: {
      name: "final_linear."
    }
  }
};
const ModelMergeBlocks$6 = {
  display_name: "ModelMergeBlocks",
  inputs: {
    model1: {
      name: "model1"
    },
    model2: {
      name: "model2"
    },
    input: {
      name: "input"
    },
    middle: {
      name: "middle"
    },
    out: {
      name: "out"
    }
  }
};
const ModelMergeCosmos14B$6 = {
  display_name: "ModelMergeCosmos14B",
  inputs: {
    model1: {
      name: "model1"
    },
    model2: {
      name: "model2"
    },
    pos_embedder_: {
      name: "pos_embedder."
    },
    extra_pos_embedder_: {
      name: "extra_pos_embedder."
    },
    x_embedder_: {
      name: "x_embedder."
    },
    t_embedder_: {
      name: "t_embedder."
    },
    affline_norm_: {
      name: "affline_norm."
    },
    blocks_block0_: {
      name: "blocks.block0."
    },
    blocks_block1_: {
      name: "blocks.block1."
    },
    blocks_block2_: {
      name: "blocks.block2."
    },
    blocks_block3_: {
      name: "blocks.block3."
    },
    blocks_block4_: {
      name: "blocks.block4."
    },
    blocks_block5_: {
      name: "blocks.block5."
    },
    blocks_block6_: {
      name: "blocks.block6."
    },
    blocks_block7_: {
      name: "blocks.block7."
    },
    blocks_block8_: {
      name: "blocks.block8."
    },
    blocks_block9_: {
      name: "blocks.block9."
    },
    blocks_block10_: {
      name: "blocks.block10."
    },
    blocks_block11_: {
      name: "blocks.block11."
    },
    blocks_block12_: {
      name: "blocks.block12."
    },
    blocks_block13_: {
      name: "blocks.block13."
    },
    blocks_block14_: {
      name: "blocks.block14."
    },
    blocks_block15_: {
      name: "blocks.block15."
    },
    blocks_block16_: {
      name: "blocks.block16."
    },
    blocks_block17_: {
      name: "blocks.block17."
    },
    blocks_block18_: {
      name: "blocks.block18."
    },
    blocks_block19_: {
      name: "blocks.block19."
    },
    blocks_block20_: {
      name: "blocks.block20."
    },
    blocks_block21_: {
      name: "blocks.block21."
    },
    blocks_block22_: {
      name: "blocks.block22."
    },
    blocks_block23_: {
      name: "blocks.block23."
    },
    blocks_block24_: {
      name: "blocks.block24."
    },
    blocks_block25_: {
      name: "blocks.block25."
    },
    blocks_block26_: {
      name: "blocks.block26."
    },
    blocks_block27_: {
      name: "blocks.block27."
    },
    blocks_block28_: {
      name: "blocks.block28."
    },
    blocks_block29_: {
      name: "blocks.block29."
    },
    blocks_block30_: {
      name: "blocks.block30."
    },
    blocks_block31_: {
      name: "blocks.block31."
    },
    blocks_block32_: {
      name: "blocks.block32."
    },
    blocks_block33_: {
      name: "blocks.block33."
    },
    blocks_block34_: {
      name: "blocks.block34."
    },
    blocks_block35_: {
      name: "blocks.block35."
    },
    final_layer_: {
      name: "final_layer."
    }
  }
};
const ModelMergeCosmos7B$6 = {
  display_name: "ModelMergeCosmos7B",
  inputs: {
    model1: {
      name: "model1"
    },
    model2: {
      name: "model2"
    },
    pos_embedder_: {
      name: "pos_embedder."
    },
    extra_pos_embedder_: {
      name: "extra_pos_embedder."
    },
    x_embedder_: {
      name: "x_embedder."
    },
    t_embedder_: {
      name: "t_embedder."
    },
    affline_norm_: {
      name: "affline_norm."
    },
    blocks_block0_: {
      name: "blocks.block0."
    },
    blocks_block1_: {
      name: "blocks.block1."
    },
    blocks_block2_: {
      name: "blocks.block2."
    },
    blocks_block3_: {
      name: "blocks.block3."
    },
    blocks_block4_: {
      name: "blocks.block4."
    },
    blocks_block5_: {
      name: "blocks.block5."
    },
    blocks_block6_: {
      name: "blocks.block6."
    },
    blocks_block7_: {
      name: "blocks.block7."
    },
    blocks_block8_: {
      name: "blocks.block8."
    },
    blocks_block9_: {
      name: "blocks.block9."
    },
    blocks_block10_: {
      name: "blocks.block10."
    },
    blocks_block11_: {
      name: "blocks.block11."
    },
    blocks_block12_: {
      name: "blocks.block12."
    },
    blocks_block13_: {
      name: "blocks.block13."
    },
    blocks_block14_: {
      name: "blocks.block14."
    },
    blocks_block15_: {
      name: "blocks.block15."
    },
    blocks_block16_: {
      name: "blocks.block16."
    },
    blocks_block17_: {
      name: "blocks.block17."
    },
    blocks_block18_: {
      name: "blocks.block18."
    },
    blocks_block19_: {
      name: "blocks.block19."
    },
    blocks_block20_: {
      name: "blocks.block20."
    },
    blocks_block21_: {
      name: "blocks.block21."
    },
    blocks_block22_: {
      name: "blocks.block22."
    },
    blocks_block23_: {
      name: "blocks.block23."
    },
    blocks_block24_: {
      name: "blocks.block24."
    },
    blocks_block25_: {
      name: "blocks.block25."
    },
    blocks_block26_: {
      name: "blocks.block26."
    },
    blocks_block27_: {
      name: "blocks.block27."
    },
    final_layer_: {
      name: "final_layer."
    }
  }
};
const ModelMergeFlux1$6 = {
  display_name: "ModelMergeFlux1",
  inputs: {
    model1: {
      name: "model1"
    },
    model2: {
      name: "model2"
    },
    img_in_: {
      name: "img_in."
    },
    time_in_: {
      name: "time_in."
    },
    guidance_in: {
      name: "guidance_in"
    },
    vector_in_: {
      name: "vector_in."
    },
    txt_in_: {
      name: "txt_in."
    },
    double_blocks_0_: {
      name: "double_blocks.0."
    },
    double_blocks_1_: {
      name: "double_blocks.1."
    },
    double_blocks_2_: {
      name: "double_blocks.2."
    },
    double_blocks_3_: {
      name: "double_blocks.3."
    },
    double_blocks_4_: {
      name: "double_blocks.4."
    },
    double_blocks_5_: {
      name: "double_blocks.5."
    },
    double_blocks_6_: {
      name: "double_blocks.6."
    },
    double_blocks_7_: {
      name: "double_blocks.7."
    },
    double_blocks_8_: {
      name: "double_blocks.8."
    },
    double_blocks_9_: {
      name: "double_blocks.9."
    },
    double_blocks_10_: {
      name: "double_blocks.10."
    },
    double_blocks_11_: {
      name: "double_blocks.11."
    },
    double_blocks_12_: {
      name: "double_blocks.12."
    },
    double_blocks_13_: {
      name: "double_blocks.13."
    },
    double_blocks_14_: {
      name: "double_blocks.14."
    },
    double_blocks_15_: {
      name: "double_blocks.15."
    },
    double_blocks_16_: {
      name: "double_blocks.16."
    },
    double_blocks_17_: {
      name: "double_blocks.17."
    },
    double_blocks_18_: {
      name: "double_blocks.18."
    },
    single_blocks_0_: {
      name: "single_blocks.0."
    },
    single_blocks_1_: {
      name: "single_blocks.1."
    },
    single_blocks_2_: {
      name: "single_blocks.2."
    },
    single_blocks_3_: {
      name: "single_blocks.3."
    },
    single_blocks_4_: {
      name: "single_blocks.4."
    },
    single_blocks_5_: {
      name: "single_blocks.5."
    },
    single_blocks_6_: {
      name: "single_blocks.6."
    },
    single_blocks_7_: {
      name: "single_blocks.7."
    },
    single_blocks_8_: {
      name: "single_blocks.8."
    },
    single_blocks_9_: {
      name: "single_blocks.9."
    },
    single_blocks_10_: {
      name: "single_blocks.10."
    },
    single_blocks_11_: {
      name: "single_blocks.11."
    },
    single_blocks_12_: {
      name: "single_blocks.12."
    },
    single_blocks_13_: {
      name: "single_blocks.13."
    },
    single_blocks_14_: {
      name: "single_blocks.14."
    },
    single_blocks_15_: {
      name: "single_blocks.15."
    },
    single_blocks_16_: {
      name: "single_blocks.16."
    },
    single_blocks_17_: {
      name: "single_blocks.17."
    },
    single_blocks_18_: {
      name: "single_blocks.18."
    },
    single_blocks_19_: {
      name: "single_blocks.19."
    },
    single_blocks_20_: {
      name: "single_blocks.20."
    },
    single_blocks_21_: {
      name: "single_blocks.21."
    },
    single_blocks_22_: {
      name: "single_blocks.22."
    },
    single_blocks_23_: {
      name: "single_blocks.23."
    },
    single_blocks_24_: {
      name: "single_blocks.24."
    },
    single_blocks_25_: {
      name: "single_blocks.25."
    },
    single_blocks_26_: {
      name: "single_blocks.26."
    },
    single_blocks_27_: {
      name: "single_blocks.27."
    },
    single_blocks_28_: {
      name: "single_blocks.28."
    },
    single_blocks_29_: {
      name: "single_blocks.29."
    },
    single_blocks_30_: {
      name: "single_blocks.30."
    },
    single_blocks_31_: {
      name: "single_blocks.31."
    },
    single_blocks_32_: {
      name: "single_blocks.32."
    },
    single_blocks_33_: {
      name: "single_blocks.33."
    },
    single_blocks_34_: {
      name: "single_blocks.34."
    },
    single_blocks_35_: {
      name: "single_blocks.35."
    },
    single_blocks_36_: {
      name: "single_blocks.36."
    },
    single_blocks_37_: {
      name: "single_blocks.37."
    },
    final_layer_: {
      name: "final_layer."
    }
  }
};
const ModelMergeLTXV$6 = {
  display_name: "ModelMergeLTXV",
  inputs: {
    model1: {
      name: "model1"
    },
    model2: {
      name: "model2"
    },
    patchify_proj_: {
      name: "patchify_proj."
    },
    adaln_single_: {
      name: "adaln_single."
    },
    caption_projection_: {
      name: "caption_projection."
    },
    transformer_blocks_0_: {
      name: "transformer_blocks.0."
    },
    transformer_blocks_1_: {
      name: "transformer_blocks.1."
    },
    transformer_blocks_2_: {
      name: "transformer_blocks.2."
    },
    transformer_blocks_3_: {
      name: "transformer_blocks.3."
    },
    transformer_blocks_4_: {
      name: "transformer_blocks.4."
    },
    transformer_blocks_5_: {
      name: "transformer_blocks.5."
    },
    transformer_blocks_6_: {
      name: "transformer_blocks.6."
    },
    transformer_blocks_7_: {
      name: "transformer_blocks.7."
    },
    transformer_blocks_8_: {
      name: "transformer_blocks.8."
    },
    transformer_blocks_9_: {
      name: "transformer_blocks.9."
    },
    transformer_blocks_10_: {
      name: "transformer_blocks.10."
    },
    transformer_blocks_11_: {
      name: "transformer_blocks.11."
    },
    transformer_blocks_12_: {
      name: "transformer_blocks.12."
    },
    transformer_blocks_13_: {
      name: "transformer_blocks.13."
    },
    transformer_blocks_14_: {
      name: "transformer_blocks.14."
    },
    transformer_blocks_15_: {
      name: "transformer_blocks.15."
    },
    transformer_blocks_16_: {
      name: "transformer_blocks.16."
    },
    transformer_blocks_17_: {
      name: "transformer_blocks.17."
    },
    transformer_blocks_18_: {
      name: "transformer_blocks.18."
    },
    transformer_blocks_19_: {
      name: "transformer_blocks.19."
    },
    transformer_blocks_20_: {
      name: "transformer_blocks.20."
    },
    transformer_blocks_21_: {
      name: "transformer_blocks.21."
    },
    transformer_blocks_22_: {
      name: "transformer_blocks.22."
    },
    transformer_blocks_23_: {
      name: "transformer_blocks.23."
    },
    transformer_blocks_24_: {
      name: "transformer_blocks.24."
    },
    transformer_blocks_25_: {
      name: "transformer_blocks.25."
    },
    transformer_blocks_26_: {
      name: "transformer_blocks.26."
    },
    transformer_blocks_27_: {
      name: "transformer_blocks.27."
    },
    scale_shift_table: {
      name: "scale_shift_table"
    },
    proj_out_: {
      name: "proj_out."
    }
  }
};
const ModelMergeMochiPreview$6 = {
  display_name: "ModelMergeMochiPreview",
  inputs: {
    model1: {
      name: "model1"
    },
    model2: {
      name: "model2"
    },
    pos_frequencies_: {
      name: "pos_frequencies."
    },
    t_embedder_: {
      name: "t_embedder."
    },
    t5_y_embedder_: {
      name: "t5_y_embedder."
    },
    t5_yproj_: {
      name: "t5_yproj."
    },
    blocks_0_: {
      name: "blocks.0."
    },
    blocks_1_: {
      name: "blocks.1."
    },
    blocks_2_: {
      name: "blocks.2."
    },
    blocks_3_: {
      name: "blocks.3."
    },
    blocks_4_: {
      name: "blocks.4."
    },
    blocks_5_: {
      name: "blocks.5."
    },
    blocks_6_: {
      name: "blocks.6."
    },
    blocks_7_: {
      name: "blocks.7."
    },
    blocks_8_: {
      name: "blocks.8."
    },
    blocks_9_: {
      name: "blocks.9."
    },
    blocks_10_: {
      name: "blocks.10."
    },
    blocks_11_: {
      name: "blocks.11."
    },
    blocks_12_: {
      name: "blocks.12."
    },
    blocks_13_: {
      name: "blocks.13."
    },
    blocks_14_: {
      name: "blocks.14."
    },
    blocks_15_: {
      name: "blocks.15."
    },
    blocks_16_: {
      name: "blocks.16."
    },
    blocks_17_: {
      name: "blocks.17."
    },
    blocks_18_: {
      name: "blocks.18."
    },
    blocks_19_: {
      name: "blocks.19."
    },
    blocks_20_: {
      name: "blocks.20."
    },
    blocks_21_: {
      name: "blocks.21."
    },
    blocks_22_: {
      name: "blocks.22."
    },
    blocks_23_: {
      name: "blocks.23."
    },
    blocks_24_: {
      name: "blocks.24."
    },
    blocks_25_: {
      name: "blocks.25."
    },
    blocks_26_: {
      name: "blocks.26."
    },
    blocks_27_: {
      name: "blocks.27."
    },
    blocks_28_: {
      name: "blocks.28."
    },
    blocks_29_: {
      name: "blocks.29."
    },
    blocks_30_: {
      name: "blocks.30."
    },
    blocks_31_: {
      name: "blocks.31."
    },
    blocks_32_: {
      name: "blocks.32."
    },
    blocks_33_: {
      name: "blocks.33."
    },
    blocks_34_: {
      name: "blocks.34."
    },
    blocks_35_: {
      name: "blocks.35."
    },
    blocks_36_: {
      name: "blocks.36."
    },
    blocks_37_: {
      name: "blocks.37."
    },
    blocks_38_: {
      name: "blocks.38."
    },
    blocks_39_: {
      name: "blocks.39."
    },
    blocks_40_: {
      name: "blocks.40."
    },
    blocks_41_: {
      name: "blocks.41."
    },
    blocks_42_: {
      name: "blocks.42."
    },
    blocks_43_: {
      name: "blocks.43."
    },
    blocks_44_: {
      name: "blocks.44."
    },
    blocks_45_: {
      name: "blocks.45."
    },
    blocks_46_: {
      name: "blocks.46."
    },
    blocks_47_: {
      name: "blocks.47."
    },
    final_layer_: {
      name: "final_layer."
    }
  }
};
const ModelMergeSD1$6 = {
  display_name: "ModelMergeSD1",
  inputs: {
    model1: {
      name: "model1"
    },
    model2: {
      name: "model2"
    },
    time_embed_: {
      name: "time_embed."
    },
    label_emb_: {
      name: "label_emb."
    },
    input_blocks_0_: {
      name: "input_blocks.0."
    },
    input_blocks_1_: {
      name: "input_blocks.1."
    },
    input_blocks_2_: {
      name: "input_blocks.2."
    },
    input_blocks_3_: {
      name: "input_blocks.3."
    },
    input_blocks_4_: {
      name: "input_blocks.4."
    },
    input_blocks_5_: {
      name: "input_blocks.5."
    },
    input_blocks_6_: {
      name: "input_blocks.6."
    },
    input_blocks_7_: {
      name: "input_blocks.7."
    },
    input_blocks_8_: {
      name: "input_blocks.8."
    },
    input_blocks_9_: {
      name: "input_blocks.9."
    },
    input_blocks_10_: {
      name: "input_blocks.10."
    },
    input_blocks_11_: {
      name: "input_blocks.11."
    },
    middle_block_0_: {
      name: "middle_block.0."
    },
    middle_block_1_: {
      name: "middle_block.1."
    },
    middle_block_2_: {
      name: "middle_block.2."
    },
    output_blocks_0_: {
      name: "output_blocks.0."
    },
    output_blocks_1_: {
      name: "output_blocks.1."
    },
    output_blocks_2_: {
      name: "output_blocks.2."
    },
    output_blocks_3_: {
      name: "output_blocks.3."
    },
    output_blocks_4_: {
      name: "output_blocks.4."
    },
    output_blocks_5_: {
      name: "output_blocks.5."
    },
    output_blocks_6_: {
      name: "output_blocks.6."
    },
    output_blocks_7_: {
      name: "output_blocks.7."
    },
    output_blocks_8_: {
      name: "output_blocks.8."
    },
    output_blocks_9_: {
      name: "output_blocks.9."
    },
    output_blocks_10_: {
      name: "output_blocks.10."
    },
    output_blocks_11_: {
      name: "output_blocks.11."
    },
    out_: {
      name: "out."
    }
  }
};
const ModelMergeSD2$6 = {
  display_name: "ModelMergeSD2",
  inputs: {
    model1: {
      name: "model1"
    },
    model2: {
      name: "model2"
    },
    time_embed_: {
      name: "time_embed."
    },
    label_emb_: {
      name: "label_emb."
    },
    input_blocks_0_: {
      name: "input_blocks.0."
    },
    input_blocks_1_: {
      name: "input_blocks.1."
    },
    input_blocks_2_: {
      name: "input_blocks.2."
    },
    input_blocks_3_: {
      name: "input_blocks.3."
    },
    input_blocks_4_: {
      name: "input_blocks.4."
    },
    input_blocks_5_: {
      name: "input_blocks.5."
    },
    input_blocks_6_: {
      name: "input_blocks.6."
    },
    input_blocks_7_: {
      name: "input_blocks.7."
    },
    input_blocks_8_: {
      name: "input_blocks.8."
    },
    input_blocks_9_: {
      name: "input_blocks.9."
    },
    input_blocks_10_: {
      name: "input_blocks.10."
    },
    input_blocks_11_: {
      name: "input_blocks.11."
    },
    middle_block_0_: {
      name: "middle_block.0."
    },
    middle_block_1_: {
      name: "middle_block.1."
    },
    middle_block_2_: {
      name: "middle_block.2."
    },
    output_blocks_0_: {
      name: "output_blocks.0."
    },
    output_blocks_1_: {
      name: "output_blocks.1."
    },
    output_blocks_2_: {
      name: "output_blocks.2."
    },
    output_blocks_3_: {
      name: "output_blocks.3."
    },
    output_blocks_4_: {
      name: "output_blocks.4."
    },
    output_blocks_5_: {
      name: "output_blocks.5."
    },
    output_blocks_6_: {
      name: "output_blocks.6."
    },
    output_blocks_7_: {
      name: "output_blocks.7."
    },
    output_blocks_8_: {
      name: "output_blocks.8."
    },
    output_blocks_9_: {
      name: "output_blocks.9."
    },
    output_blocks_10_: {
      name: "output_blocks.10."
    },
    output_blocks_11_: {
      name: "output_blocks.11."
    },
    out_: {
      name: "out."
    }
  }
};
const ModelMergeSD3_2B$6 = {
  display_name: "ModelMergeSD3_2B",
  inputs: {
    model1: {
      name: "model1"
    },
    model2: {
      name: "model2"
    },
    pos_embed_: {
      name: "pos_embed."
    },
    x_embedder_: {
      name: "x_embedder."
    },
    context_embedder_: {
      name: "context_embedder."
    },
    y_embedder_: {
      name: "y_embedder."
    },
    t_embedder_: {
      name: "t_embedder."
    },
    joint_blocks_0_: {
      name: "joint_blocks.0."
    },
    joint_blocks_1_: {
      name: "joint_blocks.1."
    },
    joint_blocks_2_: {
      name: "joint_blocks.2."
    },
    joint_blocks_3_: {
      name: "joint_blocks.3."
    },
    joint_blocks_4_: {
      name: "joint_blocks.4."
    },
    joint_blocks_5_: {
      name: "joint_blocks.5."
    },
    joint_blocks_6_: {
      name: "joint_blocks.6."
    },
    joint_blocks_7_: {
      name: "joint_blocks.7."
    },
    joint_blocks_8_: {
      name: "joint_blocks.8."
    },
    joint_blocks_9_: {
      name: "joint_blocks.9."
    },
    joint_blocks_10_: {
      name: "joint_blocks.10."
    },
    joint_blocks_11_: {
      name: "joint_blocks.11."
    },
    joint_blocks_12_: {
      name: "joint_blocks.12."
    },
    joint_blocks_13_: {
      name: "joint_blocks.13."
    },
    joint_blocks_14_: {
      name: "joint_blocks.14."
    },
    joint_blocks_15_: {
      name: "joint_blocks.15."
    },
    joint_blocks_16_: {
      name: "joint_blocks.16."
    },
    joint_blocks_17_: {
      name: "joint_blocks.17."
    },
    joint_blocks_18_: {
      name: "joint_blocks.18."
    },
    joint_blocks_19_: {
      name: "joint_blocks.19."
    },
    joint_blocks_20_: {
      name: "joint_blocks.20."
    },
    joint_blocks_21_: {
      name: "joint_blocks.21."
    },
    joint_blocks_22_: {
      name: "joint_blocks.22."
    },
    joint_blocks_23_: {
      name: "joint_blocks.23."
    },
    final_layer_: {
      name: "final_layer."
    }
  }
};
const ModelMergeSD35_Large$6 = {
  display_name: "ModelMergeSD35_Large",
  inputs: {
    model1: {
      name: "model1"
    },
    model2: {
      name: "model2"
    },
    pos_embed_: {
      name: "pos_embed."
    },
    x_embedder_: {
      name: "x_embedder."
    },
    context_embedder_: {
      name: "context_embedder."
    },
    y_embedder_: {
      name: "y_embedder."
    },
    t_embedder_: {
      name: "t_embedder."
    },
    joint_blocks_0_: {
      name: "joint_blocks.0."
    },
    joint_blocks_1_: {
      name: "joint_blocks.1."
    },
    joint_blocks_2_: {
      name: "joint_blocks.2."
    },
    joint_blocks_3_: {
      name: "joint_blocks.3."
    },
    joint_blocks_4_: {
      name: "joint_blocks.4."
    },
    joint_blocks_5_: {
      name: "joint_blocks.5."
    },
    joint_blocks_6_: {
      name: "joint_blocks.6."
    },
    joint_blocks_7_: {
      name: "joint_blocks.7."
    },
    joint_blocks_8_: {
      name: "joint_blocks.8."
    },
    joint_blocks_9_: {
      name: "joint_blocks.9."
    },
    joint_blocks_10_: {
      name: "joint_blocks.10."
    },
    joint_blocks_11_: {
      name: "joint_blocks.11."
    },
    joint_blocks_12_: {
      name: "joint_blocks.12."
    },
    joint_blocks_13_: {
      name: "joint_blocks.13."
    },
    joint_blocks_14_: {
      name: "joint_blocks.14."
    },
    joint_blocks_15_: {
      name: "joint_blocks.15."
    },
    joint_blocks_16_: {
      name: "joint_blocks.16."
    },
    joint_blocks_17_: {
      name: "joint_blocks.17."
    },
    joint_blocks_18_: {
      name: "joint_blocks.18."
    },
    joint_blocks_19_: {
      name: "joint_blocks.19."
    },
    joint_blocks_20_: {
      name: "joint_blocks.20."
    },
    joint_blocks_21_: {
      name: "joint_blocks.21."
    },
    joint_blocks_22_: {
      name: "joint_blocks.22."
    },
    joint_blocks_23_: {
      name: "joint_blocks.23."
    },
    joint_blocks_24_: {
      name: "joint_blocks.24."
    },
    joint_blocks_25_: {
      name: "joint_blocks.25."
    },
    joint_blocks_26_: {
      name: "joint_blocks.26."
    },
    joint_blocks_27_: {
      name: "joint_blocks.27."
    },
    joint_blocks_28_: {
      name: "joint_blocks.28."
    },
    joint_blocks_29_: {
      name: "joint_blocks.29."
    },
    joint_blocks_30_: {
      name: "joint_blocks.30."
    },
    joint_blocks_31_: {
      name: "joint_blocks.31."
    },
    joint_blocks_32_: {
      name: "joint_blocks.32."
    },
    joint_blocks_33_: {
      name: "joint_blocks.33."
    },
    joint_blocks_34_: {
      name: "joint_blocks.34."
    },
    joint_blocks_35_: {
      name: "joint_blocks.35."
    },
    joint_blocks_36_: {
      name: "joint_blocks.36."
    },
    joint_blocks_37_: {
      name: "joint_blocks.37."
    },
    final_layer_: {
      name: "final_layer."
    }
  }
};
const ModelMergeSDXL$6 = {
  display_name: "ModelMergeSDXL",
  inputs: {
    model1: {
      name: "model1"
    },
    model2: {
      name: "model2"
    },
    time_embed_: {
      name: "time_embed."
    },
    label_emb_: {
      name: "label_emb."
    },
    input_blocks_0: {
      name: "input_blocks.0"
    },
    input_blocks_1: {
      name: "input_blocks.1"
    },
    input_blocks_2: {
      name: "input_blocks.2"
    },
    input_blocks_3: {
      name: "input_blocks.3"
    },
    input_blocks_4: {
      name: "input_blocks.4"
    },
    input_blocks_5: {
      name: "input_blocks.5"
    },
    input_blocks_6: {
      name: "input_blocks.6"
    },
    input_blocks_7: {
      name: "input_blocks.7"
    },
    input_blocks_8: {
      name: "input_blocks.8"
    },
    middle_block_0: {
      name: "middle_block.0"
    },
    middle_block_1: {
      name: "middle_block.1"
    },
    middle_block_2: {
      name: "middle_block.2"
    },
    output_blocks_0: {
      name: "output_blocks.0"
    },
    output_blocks_1: {
      name: "output_blocks.1"
    },
    output_blocks_2: {
      name: "output_blocks.2"
    },
    output_blocks_3: {
      name: "output_blocks.3"
    },
    output_blocks_4: {
      name: "output_blocks.4"
    },
    output_blocks_5: {
      name: "output_blocks.5"
    },
    output_blocks_6: {
      name: "output_blocks.6"
    },
    output_blocks_7: {
      name: "output_blocks.7"
    },
    output_blocks_8: {
      name: "output_blocks.8"
    },
    out_: {
      name: "out."
    }
  }
};
const ModelMergeSimple$6 = {
  display_name: "ModelMergeSimple",
  inputs: {
    model1: {
      name: "model1"
    },
    model2: {
      name: "model2"
    },
    ratio: {
      name: "ratio"
    }
  }
};
const ModelMergeSubtract$6 = {
  display_name: "ModelMergeSubtract",
  inputs: {
    model1: {
      name: "model1"
    },
    model2: {
      name: "model2"
    },
    multiplier: {
      name: "multiplier"
    }
  }
};
const ModelMergeWAN2_1$6 = {
  display_name: "ModelMergeWAN2_1",
  description: "1.3B model has 30 blocks, 14B model has 40 blocks. Image to video model has the extra img_emb.",
  inputs: {
    model1: {
      name: "model1"
    },
    model2: {
      name: "model2"
    },
    patch_embedding_: {
      name: "patch_embedding."
    },
    time_embedding_: {
      name: "time_embedding."
    },
    time_projection_: {
      name: "time_projection."
    },
    text_embedding_: {
      name: "text_embedding."
    },
    img_emb_: {
      name: "img_emb."
    },
    blocks_0_: {
      name: "blocks.0."
    },
    blocks_1_: {
      name: "blocks.1."
    },
    blocks_2_: {
      name: "blocks.2."
    },
    blocks_3_: {
      name: "blocks.3."
    },
    blocks_4_: {
      name: "blocks.4."
    },
    blocks_5_: {
      name: "blocks.5."
    },
    blocks_6_: {
      name: "blocks.6."
    },
    blocks_7_: {
      name: "blocks.7."
    },
    blocks_8_: {
      name: "blocks.8."
    },
    blocks_9_: {
      name: "blocks.9."
    },
    blocks_10_: {
      name: "blocks.10."
    },
    blocks_11_: {
      name: "blocks.11."
    },
    blocks_12_: {
      name: "blocks.12."
    },
    blocks_13_: {
      name: "blocks.13."
    },
    blocks_14_: {
      name: "blocks.14."
    },
    blocks_15_: {
      name: "blocks.15."
    },
    blocks_16_: {
      name: "blocks.16."
    },
    blocks_17_: {
      name: "blocks.17."
    },
    blocks_18_: {
      name: "blocks.18."
    },
    blocks_19_: {
      name: "blocks.19."
    },
    blocks_20_: {
      name: "blocks.20."
    },
    blocks_21_: {
      name: "blocks.21."
    },
    blocks_22_: {
      name: "blocks.22."
    },
    blocks_23_: {
      name: "blocks.23."
    },
    blocks_24_: {
      name: "blocks.24."
    },
    blocks_25_: {
      name: "blocks.25."
    },
    blocks_26_: {
      name: "blocks.26."
    },
    blocks_27_: {
      name: "blocks.27."
    },
    blocks_28_: {
      name: "blocks.28."
    },
    blocks_29_: {
      name: "blocks.29."
    },
    blocks_30_: {
      name: "blocks.30."
    },
    blocks_31_: {
      name: "blocks.31."
    },
    blocks_32_: {
      name: "blocks.32."
    },
    blocks_33_: {
      name: "blocks.33."
    },
    blocks_34_: {
      name: "blocks.34."
    },
    blocks_35_: {
      name: "blocks.35."
    },
    blocks_36_: {
      name: "blocks.36."
    },
    blocks_37_: {
      name: "blocks.37."
    },
    blocks_38_: {
      name: "blocks.38."
    },
    blocks_39_: {
      name: "blocks.39."
    },
    head_: {
      name: "head."
    }
  }
};
const ModelSamplingAuraFlow$6 = {
  display_name: "ModelSamplingAuraFlow",
  inputs: {
    model: {
      name: "model"
    },
    shift: {
      name: "shift"
    }
  }
};
const ModelSamplingContinuousEDM$6 = {
  display_name: "ModelSamplingContinuousEDM",
  inputs: {
    model: {
      name: "model"
    },
    sampling: {
      name: "sampling"
    },
    sigma_max: {
      name: "sigma_max"
    },
    sigma_min: {
      name: "sigma_min"
    }
  }
};
const ModelSamplingContinuousV$6 = {
  display_name: "ModelSamplingContinuousV",
  inputs: {
    model: {
      name: "model"
    },
    sampling: {
      name: "sampling"
    },
    sigma_max: {
      name: "sigma_max"
    },
    sigma_min: {
      name: "sigma_min"
    }
  }
};
const ModelSamplingDiscrete$6 = {
  display_name: "ModelSamplingDiscrete",
  inputs: {
    model: {
      name: "model"
    },
    sampling: {
      name: "sampling"
    },
    zsnr: {
      name: "zsnr"
    }
  }
};
const ModelSamplingFlux$6 = {
  display_name: "ModelSamplingFlux",
  inputs: {
    model: {
      name: "model"
    },
    max_shift: {
      name: "max_shift"
    },
    base_shift: {
      name: "base_shift"
    },
    width: {
      name: "width"
    },
    height: {
      name: "height"
    }
  }
};
const ModelSamplingLTXV$6 = {
  display_name: "ModelSamplingLTXV",
  inputs: {
    model: {
      name: "model"
    },
    max_shift: {
      name: "max_shift"
    },
    base_shift: {
      name: "base_shift"
    },
    latent: {
      name: "latent"
    }
  }
};
const ModelSamplingSD3$6 = {
  display_name: "ModelSamplingSD3",
  inputs: {
    model: {
      name: "model"
    },
    shift: {
      name: "shift"
    }
  }
};
const ModelSamplingStableCascade$6 = {
  display_name: "ModelSamplingStableCascade",
  inputs: {
    model: {
      name: "model"
    },
    shift: {
      name: "shift"
    }
  }
};
const ModelSave$6 = {
  display_name: "ModelSave",
  inputs: {
    model: {
      name: "model"
    },
    filename_prefix: {
      name: "filename_prefix"
    }
  }
};
const Morphology$6 = {
  display_name: "ImageMorphology",
  inputs: {
    image: {
      name: "image"
    },
    operation: {
      name: "operation"
    },
    kernel_size: {
      name: "kernel_size"
    }
  }
};
const OpenAIDalle2$6 = {
  display_name: "OpenAI DALL·E 2",
  description: "Generates images synchronously via OpenAI's DALL·E 2 endpoint.",
  inputs: {
    prompt: {
      name: "prompt",
      tooltip: "Text prompt for DALL·E"
    },
    seed: {
      name: "seed",
      tooltip: "not implemented yet in backend"
    },
    size: {
      name: "size",
      tooltip: "Image size"
    },
    n: {
      name: "n",
      tooltip: "How many images to generate"
    },
    image: {
      name: "image",
      tooltip: "Optional reference image for image editing."
    },
    mask: {
      name: "mask",
      tooltip: "Optional mask for inpainting (white areas will be replaced)"
    },
    control_after_generate: {
      name: "control after generate"
    }
  }
};
const OpenAIDalle3$6 = {
  display_name: "OpenAI DALL·E 3",
  description: "Generates images synchronously via OpenAI's DALL·E 3 endpoint.",
  inputs: {
    prompt: {
      name: "prompt",
      tooltip: "Text prompt for DALL·E"
    },
    seed: {
      name: "seed",
      tooltip: "not implemented yet in backend"
    },
    quality: {
      name: "quality",
      tooltip: "Image quality"
    },
    style: {
      name: "style",
      tooltip: "Vivid causes the model to lean towards generating hyper-real and dramatic images. Natural causes the model to produce more natural, less hyper-real looking images."
    },
    size: {
      name: "size",
      tooltip: "Image size"
    },
    control_after_generate: {
      name: "control after generate"
    }
  }
};
const OpenAIGPTImage1$6 = {
  display_name: "OpenAI GPT Image 1",
  description: "Generates images synchronously via OpenAI's GPT Image 1 endpoint.",
  inputs: {
    prompt: {
      name: "prompt",
      tooltip: "Text prompt for GPT Image 1"
    },
    seed: {
      name: "seed",
      tooltip: "not implemented yet in backend"
    },
    quality: {
      name: "quality",
      tooltip: "Image quality, affects cost and generation time."
    },
    background: {
      name: "background",
      tooltip: "Return image with or without background"
    },
    size: {
      name: "size",
      tooltip: "Image size"
    },
    n: {
      name: "n",
      tooltip: "How many images to generate"
    },
    image: {
      name: "image",
      tooltip: "Optional reference image for image editing."
    },
    mask: {
      name: "mask",
      tooltip: "Optional mask for inpainting (white areas will be replaced)"
    },
    control_after_generate: {
      name: "control after generate"
    }
  }
};
const OptimalStepsScheduler$6 = {
  display_name: "OptimalStepsScheduler",
  inputs: {
    model_type: {
      name: "model_type"
    },
    steps: {
      name: "steps"
    },
    denoise: {
      name: "denoise"
    }
  }
};
const PairConditioningCombine$6 = {
  display_name: "Cond Pair Combine",
  inputs: {
    positive_A: {
      name: "positive_A"
    },
    negative_A: {
      name: "negative_A"
    },
    positive_B: {
      name: "positive_B"
    },
    negative_B: {
      name: "negative_B"
    }
  },
  outputs: {
    "0": {
      name: "positive"
    },
    "1": {
      name: "negative"
    }
  }
};
const PairConditioningSetDefaultCombine$6 = {
  display_name: "Cond Pair Set Default Combine",
  inputs: {
    positive: {
      name: "positive"
    },
    negative: {
      name: "negative"
    },
    positive_DEFAULT: {
      name: "positive_DEFAULT"
    },
    negative_DEFAULT: {
      name: "negative_DEFAULT"
    },
    hooks: {
      name: "hooks"
    }
  },
  outputs: {
    "0": {
      name: "positive"
    },
    "1": {
      name: "negative"
    }
  }
};
const PairConditioningSetProperties$6 = {
  display_name: "Cond Pair Set Props",
  inputs: {
    positive_NEW: {
      name: "positive_NEW"
    },
    negative_NEW: {
      name: "negative_NEW"
    },
    strength: {
      name: "strength"
    },
    set_cond_area: {
      name: "set_cond_area"
    },
    mask: {
      name: "mask"
    },
    hooks: {
      name: "hooks"
    },
    timesteps: {
      name: "timesteps"
    }
  },
  outputs: {
    "0": {
      name: "positive"
    },
    "1": {
      name: "negative"
    }
  }
};
const PairConditioningSetPropertiesAndCombine$6 = {
  display_name: "Cond Pair Set Props Combine",
  inputs: {
    positive: {
      name: "positive"
    },
    negative: {
      name: "negative"
    },
    positive_NEW: {
      name: "positive_NEW"
    },
    negative_NEW: {
      name: "negative_NEW"
    },
    strength: {
      name: "strength"
    },
    set_cond_area: {
      name: "set_cond_area"
    },
    mask: {
      name: "mask"
    },
    hooks: {
      name: "hooks"
    },
    timesteps: {
      name: "timesteps"
    }
  },
  outputs: {
    "0": {
      name: "positive"
    },
    "1": {
      name: "negative"
    }
  }
};
const PatchModelAddDownscale$6 = {
  display_name: "PatchModelAddDownscale (Kohya Deep Shrink)",
  inputs: {
    model: {
      name: "model"
    },
    block_number: {
      name: "block_number"
    },
    downscale_factor: {
      name: "downscale_factor"
    },
    start_percent: {
      name: "start_percent"
    },
    end_percent: {
      name: "end_percent"
    },
    downscale_after_skip: {
      name: "downscale_after_skip"
    },
    downscale_method: {
      name: "downscale_method"
    },
    upscale_method: {
      name: "upscale_method"
    }
  }
};
const PerpNeg$6 = {
  display_name: "Perp-Neg (DEPRECATED by PerpNegGuider)",
  inputs: {
    model: {
      name: "model"
    },
    empty_conditioning: {
      name: "empty_conditioning"
    },
    neg_scale: {
      name: "neg_scale"
    }
  }
};
const PerpNegGuider$6 = {
  display_name: "PerpNegGuider",
  inputs: {
    model: {
      name: "model"
    },
    positive: {
      name: "positive"
    },
    negative: {
      name: "negative"
    },
    empty_conditioning: {
      name: "empty_conditioning"
    },
    cfg: {
      name: "cfg"
    },
    neg_scale: {
      name: "neg_scale"
    }
  }
};
const PerturbedAttentionGuidance$6 = {
  display_name: "PerturbedAttentionGuidance",
  inputs: {
    model: {
      name: "model"
    },
    scale: {
      name: "scale"
    }
  }
};
const PhotoMakerEncode$6 = {
  display_name: "PhotoMakerEncode",
  inputs: {
    photomaker: {
      name: "photomaker"
    },
    image: {
      name: "image"
    },
    clip: {
      name: "clip"
    },
    text: {
      name: "text"
    }
  }
};
const PhotoMakerLoader$6 = {
  display_name: "PhotoMakerLoader",
  inputs: {
    photomaker_model_name: {
      name: "photomaker_model_name"
    }
  }
};
const Pikadditions$6 = {
  display_name: "Pikadditions (Video Object Insertion)",
  description: "Add any object or image into your video. Upload a video and specify what you’d like to add to create a seamlessly integrated result.",
  inputs: {
    video: {
      name: "video",
      tooltip: "The video to add an image to."
    },
    image: {
      name: "image",
      tooltip: "The image to add to the video."
    },
    prompt_text: {
      name: "prompt_text"
    },
    negative_prompt: {
      name: "negative_prompt"
    },
    seed: {
      name: "seed"
    },
    control_after_generate: {
      name: "control after generate"
    }
  }
};
const Pikaffects$6 = {
  display_name: "Pikaffects (Video Effects)",
  description: "Generate a video with a specific Pikaffect. Supported Pikaffects: Cake-ify, Crumble, Crush, Decapitate, Deflate, Dissolve, Explode, Eye-pop, Inflate, Levitate, Melt, Peel, Poke, Squish, Ta-da, Tear",
  inputs: {
    image: {
      name: "image",
      tooltip: "The reference image to apply the Pikaffect to."
    },
    pikaffect: {
      name: "pikaffect"
    },
    prompt_text: {
      name: "prompt_text"
    },
    negative_prompt: {
      name: "negative_prompt"
    },
    seed: {
      name: "seed"
    },
    control_after_generate: {
      name: "control after generate"
    }
  }
};
const PikaImageToVideoNode2_2$6 = {
  display_name: "Pika Image to Video",
  description: "Sends an image and prompt to the Pika API v2.2 to generate a video.",
  inputs: {
    image: {
      name: "image",
      tooltip: "The image to convert to video"
    },
    prompt_text: {
      name: "prompt_text"
    },
    negative_prompt: {
      name: "negative_prompt"
    },
    seed: {
      name: "seed"
    },
    resolution: {
      name: "resolution"
    },
    duration: {
      name: "duration"
    },
    control_after_generate: {
      name: "control after generate"
    }
  }
};
const PikaScenesV2_2$6 = {
  display_name: "Pika Scenes (Video Image Composition)",
  description: "Combine your images to create a video with the objects in them. Upload multiple images as ingredients and generate a high-quality video that incorporates all of them.",
  inputs: {
    prompt_text: {
      name: "prompt_text"
    },
    negative_prompt: {
      name: "negative_prompt"
    },
    seed: {
      name: "seed"
    },
    resolution: {
      name: "resolution"
    },
    duration: {
      name: "duration"
    },
    ingredients_mode: {
      name: "ingredients_mode"
    },
    aspect_ratio: {
      name: "aspect_ratio",
      tooltip: "Aspect ratio (width / height)"
    },
    image_ingredient_1: {
      name: "image_ingredient_1",
      tooltip: "Image that will be used as ingredient to create a video."
    },
    image_ingredient_2: {
      name: "image_ingredient_2",
      tooltip: "Image that will be used as ingredient to create a video."
    },
    image_ingredient_3: {
      name: "image_ingredient_3",
      tooltip: "Image that will be used as ingredient to create a video."
    },
    image_ingredient_4: {
      name: "image_ingredient_4",
      tooltip: "Image that will be used as ingredient to create a video."
    },
    image_ingredient_5: {
      name: "image_ingredient_5",
      tooltip: "Image that will be used as ingredient to create a video."
    },
    control_after_generate: {
      name: "control after generate"
    }
  }
};
const PikaStartEndFrameNode2_2$6 = {
  display_name: "Pika Start and End Frame to Video",
  description: "Generate a video by combining your first and last frame. Upload two images to define the start and end points, and let the AI create a smooth transition between them.",
  inputs: {
    image_start: {
      name: "image_start",
      tooltip: "The first image to combine."
    },
    image_end: {
      name: "image_end",
      tooltip: "The last image to combine."
    },
    prompt_text: {
      name: "prompt_text"
    },
    negative_prompt: {
      name: "negative_prompt"
    },
    seed: {
      name: "seed"
    },
    resolution: {
      name: "resolution"
    },
    duration: {
      name: "duration"
    },
    control_after_generate: {
      name: "control after generate"
    }
  }
};
const Pikaswaps$6 = {
  display_name: "Pika Swaps (Video Object Replacement)",
  description: "Swap out any object or region of your video with a new image or object. Define areas to replace either with a mask or coordinates.",
  inputs: {
    video: {
      name: "video",
      tooltip: "The video to swap an object in."
    },
    image: {
      name: "image",
      tooltip: "The image used to replace the masked object in the video."
    },
    mask: {
      name: "mask",
      tooltip: "Use the mask to define areas in the video to replace"
    },
    prompt_text: {
      name: "prompt_text"
    },
    negative_prompt: {
      name: "negative_prompt"
    },
    seed: {
      name: "seed"
    },
    control_after_generate: {
      name: "control after generate"
    }
  }
};
const PikaTextToVideoNode2_2$6 = {
  display_name: "Pika Text to Video",
  description: "Sends a text prompt to the Pika API v2.2 to generate a video.",
  inputs: {
    prompt_text: {
      name: "prompt_text"
    },
    negative_prompt: {
      name: "negative_prompt"
    },
    seed: {
      name: "seed"
    },
    resolution: {
      name: "resolution"
    },
    duration: {
      name: "duration"
    },
    aspect_ratio: {
      name: "aspect_ratio",
      tooltip: "Aspect ratio (width / height)"
    },
    control_after_generate: {
      name: "control after generate"
    }
  }
};
const PixverseImageToVideoNode$6 = {
  display_name: "PixVerse Image to Video",
  description: "Generates videos synchronously based on prompt and output_size.",
  inputs: {
    image: {
      name: "image"
    },
    prompt: {
      name: "prompt",
      tooltip: "Prompt for the video generation"
    },
    quality: {
      name: "quality"
    },
    duration_seconds: {
      name: "duration_seconds"
    },
    motion_mode: {
      name: "motion_mode"
    },
    seed: {
      name: "seed",
      tooltip: "Seed for video generation."
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "An optional text description of undesired elements on an image."
    },
    pixverse_template: {
      name: "pixverse_template",
      tooltip: "An optional template to influence style of generation, created by the PixVerse Template node."
    },
    control_after_generate: {
      name: "control after generate"
    }
  }
};
const PixverseTemplateNode$6 = {
  display_name: "PixVerse Template",
  inputs: {
    template: {
      name: "template"
    }
  },
  outputs: {
    "0": {
      name: "pixverse_template"
    }
  }
};
const PixverseTextToVideoNode$6 = {
  display_name: "PixVerse Text to Video",
  description: "Generates videos synchronously based on prompt and output_size.",
  inputs: {
    prompt: {
      name: "prompt",
      tooltip: "Prompt for the video generation"
    },
    aspect_ratio: {
      name: "aspect_ratio"
    },
    quality: {
      name: "quality"
    },
    duration_seconds: {
      name: "duration_seconds"
    },
    motion_mode: {
      name: "motion_mode"
    },
    seed: {
      name: "seed",
      tooltip: "Seed for video generation."
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "An optional text description of undesired elements on an image."
    },
    pixverse_template: {
      name: "pixverse_template",
      tooltip: "An optional template to influence style of generation, created by the PixVerse Template node."
    },
    control_after_generate: {
      name: "control after generate"
    }
  }
};
const PixverseTransitionVideoNode$6 = {
  display_name: "PixVerse Transition Video",
  description: "Generates videos synchronously based on prompt and output_size.",
  inputs: {
    first_frame: {
      name: "first_frame"
    },
    last_frame: {
      name: "last_frame"
    },
    prompt: {
      name: "prompt",
      tooltip: "Prompt for the video generation"
    },
    quality: {
      name: "quality"
    },
    duration_seconds: {
      name: "duration_seconds"
    },
    motion_mode: {
      name: "motion_mode"
    },
    seed: {
      name: "seed",
      tooltip: "Seed for video generation."
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "An optional text description of undesired elements on an image."
    },
    control_after_generate: {
      name: "control after generate"
    }
  }
};
const PolyexponentialScheduler$6 = {
  display_name: "PolyexponentialScheduler",
  inputs: {
    steps: {
      name: "steps"
    },
    sigma_max: {
      name: "sigma_max"
    },
    sigma_min: {
      name: "sigma_min"
    },
    rho: {
      name: "rho"
    }
  }
};
const PorterDuffImageComposite$6 = {
  display_name: "Porter-Duff Image Composite",
  inputs: {
    source: {
      name: "source"
    },
    source_alpha: {
      name: "source_alpha"
    },
    destination: {
      name: "destination"
    },
    destination_alpha: {
      name: "destination_alpha"
    },
    mode: {
      name: "mode"
    }
  }
};
const Preview3D$6 = {
  display_name: "Preview 3D",
  inputs: {
    model_file: {
      name: "model_file"
    },
    camera_info: {
      name: "camera_info"
    },
    image: {
      name: "image"
    }
  }
};
const Preview3DAnimation$6 = {
  display_name: "Preview 3D - Animation",
  inputs: {
    model_file: {
      name: "model_file"
    },
    camera_info: {
      name: "camera_info"
    },
    image: {
      name: "image"
    }
  }
};
const PreviewAny$6 = {
  display_name: "Preview Any",
  inputs: {
    source: {
      name: "source"
    },
    preview: {}
  }
};
const PreviewAudio$6 = {
  display_name: "PreviewAudio",
  inputs: {
    audio: {
      name: "audio"
    },
    audioUI: {
      name: "audioUI"
    }
  }
};
const PreviewImage$6 = {
  display_name: "Preview Image",
  description: "Saves the input images to your ComfyUI output directory.",
  inputs: {
    images: {
      name: "images"
    }
  }
};
const PrimitiveBoolean$6 = {
  display_name: "Boolean",
  inputs: {
    value: {
      name: "value"
    }
  }
};
const PrimitiveFloat$6 = {
  display_name: "Float",
  inputs: {
    value: {
      name: "value"
    }
  }
};
const PrimitiveInt$6 = {
  display_name: "Int",
  inputs: {
    value: {
      name: "value"
    },
    control_after_generate: {
      name: "control after generate"
    }
  }
};
const PrimitiveString$6 = {
  display_name: "String",
  inputs: {
    value: {
      name: "value"
    }
  }
};
const PrimitiveStringMultiline$6 = {
  display_name: "String (Multiline)",
  inputs: {
    value: {
      name: "value"
    }
  }
};
const QuadrupleCLIPLoader$6 = {
  display_name: "QuadrupleCLIPLoader",
  description: "[Recipes]\n\nhidream: long clip-l, long clip-g, t5xxl, llama_8b_3.1_instruct",
  inputs: {
    clip_name1: {
      name: "clip_name1"
    },
    clip_name2: {
      name: "clip_name2"
    },
    clip_name3: {
      name: "clip_name3"
    },
    clip_name4: {
      name: "clip_name4"
    }
  }
};
const RandomNoise$6 = {
  display_name: "RandomNoise",
  inputs: {
    noise_seed: {
      name: "noise_seed"
    },
    control_after_generate: {
      name: "control after generate"
    }
  }
};
const RebatchImages$6 = {
  display_name: "Rebatch Images",
  inputs: {
    images: {
      name: "images"
    },
    batch_size: {
      name: "batch_size"
    }
  }
};
const RebatchLatents$6 = {
  display_name: "Rebatch Latents",
  inputs: {
    latents: {
      name: "latents"
    },
    batch_size: {
      name: "batch_size"
    }
  }
};
const RecraftColorRGB$6 = {
  display_name: "Recraft Color RGB",
  description: "Create Recraft Color by choosing specific RGB values.",
  inputs: {
    r: {
      name: "r",
      tooltip: "Red value of color."
    },
    g: {
      name: "g",
      tooltip: "Green value of color."
    },
    b: {
      name: "b",
      tooltip: "Blue value of color."
    },
    recraft_color: {
      name: "recraft_color"
    }
  },
  outputs: {
    "0": {
      name: "recraft_color"
    }
  }
};
const RecraftControls$6 = {
  display_name: "Recraft Controls",
  description: "Create Recraft Controls for customizing Recraft generation.",
  inputs: {
    colors: {
      name: "colors"
    },
    background_color: {
      name: "background_color"
    }
  },
  outputs: {
    "0": {
      name: "recraft_controls"
    }
  }
};
const RecraftCreativeUpscaleNode$6 = {
  display_name: "Recraft Creative Upscale Image",
  description: "Upscale image synchronously.\nEnhances a given raster image using ‘creative upscale’ tool, boosting resolution with a focus on refining small details and faces.",
  inputs: {
    image: {
      name: "image"
    }
  }
};
const RecraftCrispUpscaleNode$6 = {
  display_name: "Recraft Crisp Upscale Image",
  description: "Upscale image synchronously.\nEnhances a given raster image using ‘crisp upscale’ tool, increasing image resolution, making the image sharper and cleaner.",
  inputs: {
    image: {
      name: "image"
    }
  }
};
const RecraftImageInpaintingNode$6 = {
  display_name: "Recraft Image Inpainting",
  description: "Modify image based on prompt and mask.",
  inputs: {
    image: {
      name: "image"
    },
    mask: {
      name: "mask"
    },
    prompt: {
      name: "prompt",
      tooltip: "Prompt for the image generation."
    },
    n: {
      name: "n",
      tooltip: "The number of images to generate."
    },
    seed: {
      name: "seed",
      tooltip: "Seed to determine if node should re-run; actual results are nondeterministic regardless of seed."
    },
    recraft_style: {
      name: "recraft_style"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "An optional text description of undesired elements on an image."
    },
    control_after_generate: {
      name: "control after generate"
    }
  }
};
const RecraftImageToImageNode$6 = {
  display_name: "Recraft Image to Image",
  description: "Modify image based on prompt and strength.",
  inputs: {
    image: {
      name: "image"
    },
    prompt: {
      name: "prompt",
      tooltip: "Prompt for the image generation."
    },
    n: {
      name: "n",
      tooltip: "The number of images to generate."
    },
    strength: {
      name: "strength",
      tooltip: "Defines the difference with the original image, should lie in [0, 1], where 0 means almost identical, and 1 means miserable similarity."
    },
    seed: {
      name: "seed",
      tooltip: "Seed to determine if node should re-run; actual results are nondeterministic regardless of seed."
    },
    recraft_style: {
      name: "recraft_style"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "An optional text description of undesired elements on an image."
    },
    recraft_controls: {
      name: "recraft_controls",
      tooltip: "Optional additional controls over the generation via the Recraft Controls node."
    },
    control_after_generate: {
      name: "control after generate"
    }
  }
};
const RecraftRemoveBackgroundNode$6 = {
  display_name: "Recraft Remove Background",
  description: "Remove background from image, and return processed image and mask.",
  inputs: {
    image: {
      name: "image"
    }
  }
};
const RecraftReplaceBackgroundNode$6 = {
  display_name: "Recraft Replace Background",
  description: "Replace background on image, based on provided prompt.",
  inputs: {
    image: {
      name: "image"
    },
    prompt: {
      name: "prompt",
      tooltip: "Prompt for the image generation."
    },
    n: {
      name: "n",
      tooltip: "The number of images to generate."
    },
    seed: {
      name: "seed",
      tooltip: "Seed to determine if node should re-run; actual results are nondeterministic regardless of seed."
    },
    recraft_style: {
      name: "recraft_style"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "An optional text description of undesired elements on an image."
    },
    control_after_generate: {
      name: "control after generate"
    }
  }
};
const RecraftStyleV3DigitalIllustration$6 = {
  display_name: "Recraft Style - Digital Illustration",
  description: "Select realistic_image style and optional substyle.",
  inputs: {
    substyle: {
      name: "substyle"
    }
  },
  outputs: {
    "0": {
      name: "recraft_style"
    }
  }
};
const RecraftStyleV3InfiniteStyleLibrary$6 = {
  display_name: "Recraft Style - Infinite Style Library",
  description: "Select style based on preexisting UUID from Recraft's Infinite Style Library.",
  inputs: {
    style_id: {
      name: "style_id",
      tooltip: "UUID of style from Infinite Style Library."
    }
  },
  outputs: {
    "0": {
      name: "recraft_style"
    }
  }
};
const RecraftStyleV3LogoRaster$6 = {
  display_name: "Recraft Style - Logo Raster",
  description: "Select realistic_image style and optional substyle.",
  inputs: {
    substyle: {
      name: "substyle"
    }
  },
  outputs: {
    "0": {
      name: "recraft_style"
    }
  }
};
const RecraftStyleV3RealisticImage$6 = {
  display_name: "Recraft Style - Realistic Image",
  description: "Select realistic_image style and optional substyle.",
  inputs: {
    substyle: {
      name: "substyle"
    }
  },
  outputs: {
    "0": {
      name: "recraft_style"
    }
  }
};
const RecraftTextToImageNode$6 = {
  display_name: "Recraft Text to Image",
  description: "Generates images synchronously based on prompt and resolution.",
  inputs: {
    prompt: {
      name: "prompt",
      tooltip: "Prompt for the image generation."
    },
    size: {
      name: "size",
      tooltip: "The size of the generated image."
    },
    n: {
      name: "n",
      tooltip: "The number of images to generate."
    },
    seed: {
      name: "seed",
      tooltip: "Seed to determine if node should re-run; actual results are nondeterministic regardless of seed."
    },
    recraft_style: {
      name: "recraft_style"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "An optional text description of undesired elements on an image."
    },
    recraft_controls: {
      name: "recraft_controls",
      tooltip: "Optional additional controls over the generation via the Recraft Controls node."
    },
    control_after_generate: {
      name: "control after generate"
    }
  }
};
const RecraftTextToVectorNode$6 = {
  display_name: "Recraft Text to Vector",
  description: "Generates SVG synchronously based on prompt and resolution.",
  inputs: {
    prompt: {
      name: "prompt",
      tooltip: "Prompt for the image generation."
    },
    substyle: {
      name: "substyle"
    },
    size: {
      name: "size",
      tooltip: "The size of the generated image."
    },
    n: {
      name: "n",
      tooltip: "The number of images to generate."
    },
    seed: {
      name: "seed",
      tooltip: "Seed to determine if node should re-run; actual results are nondeterministic regardless of seed."
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "An optional text description of undesired elements on an image."
    },
    recraft_controls: {
      name: "recraft_controls",
      tooltip: "Optional additional controls over the generation via the Recraft Controls node."
    },
    control_after_generate: {
      name: "control after generate"
    }
  }
};
const RecraftVectorizeImageNode$6 = {
  display_name: "Recraft Vectorize Image",
  description: "Generates SVG synchronously from an input image.",
  inputs: {
    image: {
      name: "image"
    }
  }
};
const RenormCFG$6 = {
  display_name: "RenormCFG",
  inputs: {
    model: {
      name: "model"
    },
    cfg_trunc: {
      name: "cfg_trunc"
    },
    renorm_cfg: {
      name: "renorm_cfg"
    }
  }
};
const RepeatImageBatch$6 = {
  display_name: "RepeatImageBatch",
  inputs: {
    image: {
      name: "image"
    },
    amount: {
      name: "amount"
    }
  }
};
const RepeatLatentBatch$6 = {
  display_name: "Repeat Latent Batch",
  inputs: {
    samples: {
      name: "samples"
    },
    amount: {
      name: "amount"
    }
  }
};
const RescaleCFG$6 = {
  display_name: "RescaleCFG",
  inputs: {
    model: {
      name: "model"
    },
    multiplier: {
      name: "multiplier"
    }
  }
};
const SamplerCustom$6 = {
  display_name: "SamplerCustom",
  inputs: {
    model: {
      name: "model"
    },
    add_noise: {
      name: "add_noise"
    },
    noise_seed: {
      name: "noise_seed"
    },
    cfg: {
      name: "cfg"
    },
    positive: {
      name: "positive"
    },
    negative: {
      name: "negative"
    },
    sampler: {
      name: "sampler"
    },
    sigmas: {
      name: "sigmas"
    },
    latent_image: {
      name: "latent_image"
    },
    control_after_generate: {
      name: "control after generate"
    }
  },
  outputs: {
    "0": {
      name: "output"
    },
    "1": {
      name: "denoised_output"
    }
  }
};
const SamplerCustomAdvanced$6 = {
  display_name: "SamplerCustomAdvanced",
  inputs: {
    noise: {
      name: "noise"
    },
    guider: {
      name: "guider"
    },
    sampler: {
      name: "sampler"
    },
    sigmas: {
      name: "sigmas"
    },
    latent_image: {
      name: "latent_image"
    }
  },
  outputs: {
    "0": {
      name: "output"
    },
    "1": {
      name: "denoised_output"
    }
  }
};
const SamplerDPMAdaptative$6 = {
  display_name: "SamplerDPMAdaptative",
  inputs: {
    order: {
      name: "order"
    },
    rtol: {
      name: "rtol"
    },
    atol: {
      name: "atol"
    },
    h_init: {
      name: "h_init"
    },
    pcoeff: {
      name: "pcoeff"
    },
    icoeff: {
      name: "icoeff"
    },
    dcoeff: {
      name: "dcoeff"
    },
    accept_safety: {
      name: "accept_safety"
    },
    eta: {
      name: "eta"
    },
    s_noise: {
      name: "s_noise"
    }
  }
};
const SamplerDPMPP_2M_SDE$6 = {
  display_name: "SamplerDPMPP_2M_SDE",
  inputs: {
    solver_type: {
      name: "solver_type"
    },
    eta: {
      name: "eta"
    },
    s_noise: {
      name: "s_noise"
    },
    noise_device: {
      name: "noise_device"
    }
  }
};
const SamplerDPMPP_2S_Ancestral$6 = {
  display_name: "SamplerDPMPP_2S_Ancestral",
  inputs: {
    eta: {
      name: "eta"
    },
    s_noise: {
      name: "s_noise"
    }
  }
};
const SamplerDPMPP_3M_SDE$6 = {
  display_name: "SamplerDPMPP_3M_SDE",
  inputs: {
    eta: {
      name: "eta"
    },
    s_noise: {
      name: "s_noise"
    },
    noise_device: {
      name: "noise_device"
    }
  }
};
const SamplerDPMPP_SDE$6 = {
  display_name: "SamplerDPMPP_SDE",
  inputs: {
    eta: {
      name: "eta"
    },
    s_noise: {
      name: "s_noise"
    },
    r: {
      name: "r"
    },
    noise_device: {
      name: "noise_device"
    }
  }
};
const SamplerEulerAncestral$6 = {
  display_name: "SamplerEulerAncestral",
  inputs: {
    eta: {
      name: "eta"
    },
    s_noise: {
      name: "s_noise"
    }
  }
};
const SamplerEulerAncestralCFGPP$6 = {
  display_name: "SamplerEulerAncestralCFG++",
  inputs: {
    eta: {
      name: "eta"
    },
    s_noise: {
      name: "s_noise"
    }
  }
};
const SamplerEulerCFGpp$6 = {
  display_name: "SamplerEulerCFG++",
  inputs: {
    version: {
      name: "version"
    }
  }
};
const SamplerLCMUpscale$6 = {
  display_name: "SamplerLCMUpscale",
  inputs: {
    scale_ratio: {
      name: "scale_ratio"
    },
    scale_steps: {
      name: "scale_steps"
    },
    upscale_method: {
      name: "upscale_method"
    }
  }
};
const SamplerLMS$6 = {
  display_name: "SamplerLMS",
  inputs: {
    order: {
      name: "order"
    }
  }
};
const SaveAnimatedPNG$6 = {
  display_name: "SaveAnimatedPNG",
  inputs: {
    images: {
      name: "images"
    },
    filename_prefix: {
      name: "filename_prefix"
    },
    fps: {
      name: "fps"
    },
    compress_level: {
      name: "compress_level"
    }
  }
};
const SaveAnimatedWEBP$6 = {
  display_name: "SaveAnimatedWEBP",
  inputs: {
    images: {
      name: "images"
    },
    filename_prefix: {
      name: "filename_prefix"
    },
    fps: {
      name: "fps"
    },
    lossless: {
      name: "lossless"
    },
    quality: {
      name: "quality"
    },
    method: {
      name: "method"
    }
  }
};
const SaveAudio$6 = {
  display_name: "SaveAudio",
  inputs: {
    audio: {
      name: "audio"
    },
    filename_prefix: {
      name: "filename_prefix"
    },
    audioUI: {
      name: "audioUI"
    }
  }
};
const SaveGLB$6 = {
  display_name: "SaveGLB",
  inputs: {
    mesh: {
      name: "mesh"
    },
    filename_prefix: {
      name: "filename_prefix"
    },
    image: {
      name: "image"
    }
  }
};
const SaveImage$6 = {
  display_name: "Save Image",
  description: "Saves the input images to your ComfyUI output directory.",
  inputs: {
    images: {
      name: "images",
      tooltip: "The images to save."
    },
    filename_prefix: {
      name: "filename_prefix",
      tooltip: "The prefix for the file to save. This may include formatting information such as %date:yyyy-MM-dd% or %Empty Latent Image.width% to include values from nodes."
    }
  }
};
const SaveImageWebsocket$6 = {
  display_name: "SaveImageWebsocket",
  inputs: {
    images: {
      name: "images"
    }
  }
};
const SaveLatent$6 = {
  display_name: "SaveLatent",
  inputs: {
    samples: {
      name: "samples"
    },
    filename_prefix: {
      name: "filename_prefix"
    }
  }
};
const SaveSVG$6 = {
  display_name: "Save SVG",
  description: "Save SVG files on disk.",
  inputs: {
    svg: {
      name: "svg"
    },
    filename_prefix: {
      name: "filename_prefix",
      tooltip: "The prefix for the file to save. This may include formatting information such as %date:yyyy-MM-dd% or %Empty Latent Image.width% to include values from nodes."
    }
  }
};
const SaveVideo$6 = {
  display_name: "Save Video",
  description: "Saves the input images to your ComfyUI output directory.",
  inputs: {
    video: {
      name: "video",
      tooltip: "The video to save."
    },
    filename_prefix: {
      name: "filename_prefix",
      tooltip: "The prefix for the file to save. This may include formatting information such as %date:yyyy-MM-dd% or %Empty Latent Image.width% to include values from nodes."
    },
    format: {
      name: "format",
      tooltip: "The format to save the video as."
    },
    codec: {
      name: "codec",
      tooltip: "The codec to use for the video."
    }
  }
};
const SaveWEBM$6 = {
  display_name: "SaveWEBM",
  inputs: {
    images: {
      name: "images"
    },
    filename_prefix: {
      name: "filename_prefix"
    },
    codec: {
      name: "codec"
    },
    fps: {
      name: "fps"
    },
    crf: {
      name: "crf",
      tooltip: "Higher crf means lower quality with a smaller file size, lower crf means higher quality higher filesize."
    }
  }
};
const SD_4XUpscale_Conditioning$6 = {
  display_name: "SD_4XUpscale_Conditioning",
  inputs: {
    images: {
      name: "images"
    },
    positive: {
      name: "positive"
    },
    negative: {
      name: "negative"
    },
    scale_ratio: {
      name: "scale_ratio"
    },
    noise_augmentation: {
      name: "noise_augmentation"
    }
  },
  outputs: {
    "0": {
      name: "positive"
    },
    "1": {
      name: "negative"
    },
    "2": {
      name: "latent"
    }
  }
};
const SDTurboScheduler$6 = {
  display_name: "SDTurboScheduler",
  inputs: {
    model: {
      name: "model"
    },
    steps: {
      name: "steps"
    },
    denoise: {
      name: "denoise"
    }
  }
};
const SelfAttentionGuidance$6 = {
  display_name: "Self-Attention Guidance",
  inputs: {
    model: {
      name: "model"
    },
    scale: {
      name: "scale"
    },
    blur_sigma: {
      name: "blur_sigma"
    }
  }
};
const SetClipHooks$6 = {
  display_name: "Set CLIP Hooks",
  inputs: {
    clip: {
      name: "clip"
    },
    apply_to_conds: {
      name: "apply_to_conds"
    },
    schedule_clip: {
      name: "schedule_clip"
    },
    hooks: {
      name: "hooks"
    }
  }
};
const SetFirstSigma$6 = {
  display_name: "SetFirstSigma",
  inputs: {
    sigmas: {
      name: "sigmas"
    },
    sigma: {
      name: "sigma"
    }
  }
};
const SetHookKeyframes$6 = {
  display_name: "Set Hook Keyframes",
  inputs: {
    hooks: {
      name: "hooks"
    },
    hook_kf: {
      name: "hook_kf"
    }
  }
};
const SetLatentNoiseMask$6 = {
  display_name: "Set Latent Noise Mask",
  inputs: {
    samples: {
      name: "samples"
    },
    mask: {
      name: "mask"
    }
  }
};
const SetUnionControlNetType$6 = {
  display_name: "SetUnionControlNetType",
  inputs: {
    control_net: {
      name: "control_net"
    },
    type: {
      name: "type"
    }
  }
};
const SkipLayerGuidanceDiT$6 = {
  display_name: "SkipLayerGuidanceDiT",
  description: "Generic version of SkipLayerGuidance node that can be used on every DiT model.",
  inputs: {
    model: {
      name: "model"
    },
    double_layers: {
      name: "double_layers"
    },
    single_layers: {
      name: "single_layers"
    },
    scale: {
      name: "scale"
    },
    start_percent: {
      name: "start_percent"
    },
    end_percent: {
      name: "end_percent"
    },
    rescaling_scale: {
      name: "rescaling_scale"
    }
  }
};
const SkipLayerGuidanceSD3$6 = {
  display_name: "SkipLayerGuidanceSD3",
  description: "Generic version of SkipLayerGuidance node that can be used on every DiT model.",
  inputs: {
    model: {
      name: "model"
    },
    layers: {
      name: "layers"
    },
    scale: {
      name: "scale"
    },
    start_percent: {
      name: "start_percent"
    },
    end_percent: {
      name: "end_percent"
    }
  }
};
const SolidMask$6 = {
  display_name: "SolidMask",
  inputs: {
    value: {
      name: "value"
    },
    width: {
      name: "width"
    },
    height: {
      name: "height"
    }
  }
};
const SplitImageWithAlpha$6 = {
  display_name: "Split Image with Alpha",
  inputs: {
    image: {
      name: "image"
    }
  }
};
const SplitSigmas$6 = {
  display_name: "SplitSigmas",
  inputs: {
    sigmas: {
      name: "sigmas"
    },
    step: {
      name: "step"
    }
  },
  outputs: {
    "0": {
      name: "high_sigmas"
    },
    "1": {
      name: "low_sigmas"
    }
  }
};
const SplitSigmasDenoise$6 = {
  display_name: "SplitSigmasDenoise",
  inputs: {
    sigmas: {
      name: "sigmas"
    },
    denoise: {
      name: "denoise"
    }
  },
  outputs: {
    "0": {
      name: "high_sigmas"
    },
    "1": {
      name: "low_sigmas"
    }
  }
};
const StabilityStableImageSD_3_5Node$6 = {
  display_name: "Stability AI Stable Diffusion 3.5 Image",
  description: "Generates images synchronously based on prompt and resolution.",
  inputs: {
    prompt: {
      name: "prompt",
      tooltip: "What you wish to see in the output image. A strong, descriptive prompt that clearly defines elements, colors, and subjects will lead to better results."
    },
    model: {
      name: "model"
    },
    aspect_ratio: {
      name: "aspect_ratio",
      tooltip: "Aspect ratio of generated image."
    },
    style_preset: {
      name: "style_preset",
      tooltip: "Optional desired style of generated image."
    },
    cfg_scale: {
      name: "cfg_scale",
      tooltip: "How strictly the diffusion process adheres to the prompt text (higher values keep your image closer to your prompt)"
    },
    seed: {
      name: "seed",
      tooltip: "The random seed used for creating the noise."
    },
    image: {
      name: "image"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Keywords of what you do not wish to see in the output image. This is an advanced feature."
    },
    image_denoise: {
      name: "image_denoise",
      tooltip: "Denoise of input image; 0.0 yields image identical to input, 1.0 is as if no image was provided at all."
    },
    control_after_generate: {
      name: "control after generate"
    }
  }
};
const StabilityStableImageUltraNode$6 = {
  display_name: "Stability AI Stable Image Ultra",
  description: "Generates images synchronously based on prompt and resolution.",
  inputs: {
    prompt: {
      name: "prompt",
      tooltip: "What you wish to see in the output image. A strong, descriptive prompt that clearly definesWhat you wish to see in the output image. A strong, descriptive prompt that clearly defineselements, colors, and subjects will lead to better results. To control the weight of a given word use the format `(word:weight)`,where `word` is the word you'd like to control the weight of and `weight`is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`would convey a sky that was blue and green, but more green than blue."
    },
    aspect_ratio: {
      name: "aspect_ratio",
      tooltip: "Aspect ratio of generated image."
    },
    style_preset: {
      name: "style_preset",
      tooltip: "Optional desired style of generated image."
    },
    seed: {
      name: "seed",
      tooltip: "The random seed used for creating the noise."
    },
    image: {
      name: "image"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "A blurb of text describing what you do not wish to see in the output image. This is an advanced feature."
    },
    image_denoise: {
      name: "image_denoise",
      tooltip: "Denoise of input image; 0.0 yields image identical to input, 1.0 is as if no image was provided at all."
    },
    control_after_generate: {
      name: "control after generate"
    }
  }
};
const StabilityUpscaleConservativeNode$6 = {
  display_name: "Stability AI Upscale Conservative",
  description: "Upscale image with minimal alterations to 4K resolution.",
  inputs: {
    image: {
      name: "image"
    },
    prompt: {
      name: "prompt",
      tooltip: "What you wish to see in the output image. A strong, descriptive prompt that clearly defines elements, colors, and subjects will lead to better results."
    },
    creativity: {
      name: "creativity",
      tooltip: "Controls the likelihood of creating additional details not heavily conditioned by the init image."
    },
    seed: {
      name: "seed",
      tooltip: "The random seed used for creating the noise."
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Keywords of what you do not wish to see in the output image. This is an advanced feature."
    },
    control_after_generate: {
      name: "control after generate"
    }
  }
};
const StabilityUpscaleCreativeNode$6 = {
  display_name: "Stability AI Upscale Creative",
  description: "Upscale image with minimal alterations to 4K resolution.",
  inputs: {
    image: {
      name: "image"
    },
    prompt: {
      name: "prompt",
      tooltip: "What you wish to see in the output image. A strong, descriptive prompt that clearly defines elements, colors, and subjects will lead to better results."
    },
    creativity: {
      name: "creativity",
      tooltip: "Controls the likelihood of creating additional details not heavily conditioned by the init image."
    },
    style_preset: {
      name: "style_preset",
      tooltip: "Optional desired style of generated image."
    },
    seed: {
      name: "seed",
      tooltip: "The random seed used for creating the noise."
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Keywords of what you do not wish to see in the output image. This is an advanced feature."
    },
    control_after_generate: {
      name: "control after generate"
    }
  }
};
const StabilityUpscaleFastNode$6 = {
  display_name: "Stability AI Upscale Fast",
  description: "Quickly upscales an image via Stability API call to 4x its original size; intended for upscaling low-quality/compressed images.",
  inputs: {
    image: {
      name: "image"
    }
  }
};
const StableCascade_EmptyLatentImage$6 = {
  display_name: "StableCascade_EmptyLatentImage",
  inputs: {
    width: {
      name: "width"
    },
    height: {
      name: "height"
    },
    compression: {
      name: "compression"
    },
    batch_size: {
      name: "batch_size"
    }
  },
  outputs: {
    "0": {
      name: "stage_c"
    },
    "1": {
      name: "stage_b"
    }
  }
};
const StableCascade_StageB_Conditioning$6 = {
  display_name: "StableCascade_StageB_Conditioning",
  inputs: {
    conditioning: {
      name: "conditioning"
    },
    stage_c: {
      name: "stage_c"
    }
  }
};
const StableCascade_StageC_VAEEncode$6 = {
  display_name: "StableCascade_StageC_VAEEncode",
  inputs: {
    image: {
      name: "image"
    },
    vae: {
      name: "vae"
    },
    compression: {
      name: "compression"
    }
  },
  outputs: {
    "0": {
      name: "stage_c"
    },
    "1": {
      name: "stage_b"
    }
  }
};
const StableCascade_SuperResolutionControlnet$6 = {
  display_name: "StableCascade_SuperResolutionControlnet",
  inputs: {
    image: {
      name: "image"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "controlnet_input"
    },
    "1": {
      name: "stage_c"
    },
    "2": {
      name: "stage_b"
    }
  }
};
const StableZero123_Conditioning$6 = {
  display_name: "StableZero123_Conditioning",
  inputs: {
    clip_vision: {
      name: "clip_vision"
    },
    init_image: {
      name: "init_image"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "width"
    },
    height: {
      name: "height"
    },
    batch_size: {
      name: "batch_size"
    },
    elevation: {
      name: "elevation"
    },
    azimuth: {
      name: "azimuth"
    }
  },
  outputs: {
    "0": {
      name: "positive"
    },
    "1": {
      name: "negative"
    },
    "2": {
      name: "latent"
    }
  }
};
const StableZero123_Conditioning_Batched$6 = {
  display_name: "StableZero123_Conditioning_Batched",
  inputs: {
    clip_vision: {
      name: "clip_vision"
    },
    init_image: {
      name: "init_image"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "width"
    },
    height: {
      name: "height"
    },
    batch_size: {
      name: "batch_size"
    },
    elevation: {
      name: "elevation"
    },
    azimuth: {
      name: "azimuth"
    },
    elevation_batch_increment: {
      name: "elevation_batch_increment"
    },
    azimuth_batch_increment: {
      name: "azimuth_batch_increment"
    }
  },
  outputs: {
    "0": {
      name: "positive"
    },
    "1": {
      name: "negative"
    },
    "2": {
      name: "latent"
    }
  }
};
const StyleModelApply$6 = {
  display_name: "Apply Style Model",
  inputs: {
    conditioning: {
      name: "conditioning"
    },
    style_model: {
      name: "style_model"
    },
    clip_vision_output: {
      name: "clip_vision_output"
    },
    strength: {
      name: "strength"
    },
    strength_type: {
      name: "strength_type"
    }
  }
};
const StyleModelLoader$6 = {
  display_name: "Load Style Model",
  inputs: {
    style_model_name: {
      name: "style_model_name"
    }
  }
};
const SV3D_Conditioning$6 = {
  display_name: "SV3D_Conditioning",
  inputs: {
    clip_vision: {
      name: "clip_vision"
    },
    init_image: {
      name: "init_image"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "width"
    },
    height: {
      name: "height"
    },
    video_frames: {
      name: "video_frames"
    },
    elevation: {
      name: "elevation"
    }
  },
  outputs: {
    "0": {
      name: "positive"
    },
    "1": {
      name: "negative"
    },
    "2": {
      name: "latent"
    }
  }
};
const SVD_img2vid_Conditioning$6 = {
  display_name: "SVD_img2vid_Conditioning",
  inputs: {
    clip_vision: {
      name: "clip_vision"
    },
    init_image: {
      name: "init_image"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "width"
    },
    height: {
      name: "height"
    },
    video_frames: {
      name: "video_frames"
    },
    motion_bucket_id: {
      name: "motion_bucket_id"
    },
    fps: {
      name: "fps"
    },
    augmentation_level: {
      name: "augmentation_level"
    }
  },
  outputs: {
    "0": {
      name: "positive"
    },
    "1": {
      name: "negative"
    },
    "2": {
      name: "latent"
    }
  }
};
const T5TokenizerOptions$6 = {
  display_name: "T5TokenizerOptions",
  inputs: {
    clip: {
      name: "clip"
    },
    min_padding: {
      name: "min_padding"
    },
    min_length: {
      name: "min_length"
    }
  }
};
const TextEncodeHunyuanVideo_ImageToVideo$6 = {
  display_name: "TextEncodeHunyuanVideo_ImageToVideo",
  inputs: {
    clip: {
      name: "clip"
    },
    clip_vision_output: {
      name: "clip_vision_output"
    },
    prompt: {
      name: "prompt"
    },
    image_interleave: {
      name: "image_interleave",
      tooltip: "How much the image influences things vs the text prompt. Higher number means more influence from the text prompt."
    }
  }
};
const ThresholdMask$6 = {
  display_name: "ThresholdMask",
  inputs: {
    mask: {
      name: "mask"
    },
    value: {
      name: "value"
    }
  }
};
const TomePatchModel$6 = {
  display_name: "TomePatchModel",
  inputs: {
    model: {
      name: "model"
    },
    ratio: {
      name: "ratio"
    }
  }
};
const TorchCompileModel$6 = {
  display_name: "TorchCompileModel",
  inputs: {
    model: {
      name: "model"
    },
    backend: {
      name: "backend"
    }
  }
};
const TrimVideoLatent$6 = {
  display_name: "TrimVideoLatent",
  inputs: {
    samples: {
      name: "samples"
    },
    trim_amount: {
      name: "trim_amount"
    }
  }
};
const TripleCLIPLoader$6 = {
  display_name: "TripleCLIPLoader",
  description: "[Recipes]\n\nsd3: clip-l, clip-g, t5",
  inputs: {
    clip_name1: {
      name: "clip_name1"
    },
    clip_name2: {
      name: "clip_name2"
    },
    clip_name3: {
      name: "clip_name3"
    }
  }
};
const unCLIPCheckpointLoader$6 = {
  display_name: "unCLIPCheckpointLoader",
  inputs: {
    ckpt_name: {
      name: "ckpt_name"
    }
  }
};
const unCLIPConditioning$6 = {
  display_name: "unCLIPConditioning",
  inputs: {
    conditioning: {
      name: "conditioning"
    },
    clip_vision_output: {
      name: "clip_vision_output"
    },
    strength: {
      name: "strength"
    },
    noise_augmentation: {
      name: "noise_augmentation"
    }
  }
};
const UNetCrossAttentionMultiply$6 = {
  display_name: "UNetCrossAttentionMultiply",
  inputs: {
    model: {
      name: "model"
    },
    q: {
      name: "q"
    },
    k: {
      name: "k"
    },
    v: {
      name: "v"
    },
    out: {
      name: "out"
    }
  }
};
const UNETLoader$6 = {
  display_name: "Load Diffusion Model",
  inputs: {
    unet_name: {
      name: "unet_name"
    },
    weight_dtype: {
      name: "weight_dtype"
    }
  }
};
const UNetSelfAttentionMultiply$6 = {
  display_name: "UNetSelfAttentionMultiply",
  inputs: {
    model: {
      name: "model"
    },
    q: {
      name: "q"
    },
    k: {
      name: "k"
    },
    v: {
      name: "v"
    },
    out: {
      name: "out"
    }
  }
};
const UNetTemporalAttentionMultiply$6 = {
  display_name: "UNetTemporalAttentionMultiply",
  inputs: {
    model: {
      name: "model"
    },
    self_structural: {
      name: "self_structural"
    },
    self_temporal: {
      name: "self_temporal"
    },
    cross_structural: {
      name: "cross_structural"
    },
    cross_temporal: {
      name: "cross_temporal"
    }
  }
};
const UpscaleModelLoader$6 = {
  display_name: "Load Upscale Model",
  inputs: {
    model_name: {
      name: "model_name"
    }
  }
};
const VAEDecode$6 = {
  display_name: "VAE Decode",
  description: "Decodes latent images back into pixel space images.",
  inputs: {
    samples: {
      name: "samples",
      tooltip: "The latent to be decoded."
    },
    vae: {
      name: "vae",
      tooltip: "The VAE model used for decoding the latent."
    }
  },
  outputs: {
    "0": {
      tooltip: "The decoded image."
    }
  }
};
const VAEDecodeAudio$6 = {
  display_name: "VAEDecodeAudio",
  inputs: {
    samples: {
      name: "samples"
    },
    vae: {
      name: "vae"
    }
  }
};
const VAEDecodeHunyuan3D$6 = {
  display_name: "VAEDecodeHunyuan3D",
  inputs: {
    samples: {
      name: "samples"
    },
    vae: {
      name: "vae"
    },
    num_chunks: {
      name: "num_chunks"
    },
    octree_resolution: {
      name: "octree_resolution"
    }
  }
};
const VAEDecodeTiled$6 = {
  display_name: "VAE Decode (Tiled)",
  inputs: {
    samples: {
      name: "samples"
    },
    vae: {
      name: "vae"
    },
    tile_size: {
      name: "tile_size"
    },
    overlap: {
      name: "overlap"
    },
    temporal_size: {
      name: "temporal_size",
      tooltip: "Only used for video VAEs: Amount of frames to decode at a time."
    },
    temporal_overlap: {
      name: "temporal_overlap",
      tooltip: "Only used for video VAEs: Amount of frames to overlap."
    }
  }
};
const VAEEncode$6 = {
  display_name: "VAE Encode",
  inputs: {
    pixels: {
      name: "pixels"
    },
    vae: {
      name: "vae"
    }
  }
};
const VAEEncodeAudio$6 = {
  display_name: "VAEEncodeAudio",
  inputs: {
    audio: {
      name: "audio"
    },
    vae: {
      name: "vae"
    }
  }
};
const VAEEncodeForInpaint$6 = {
  display_name: "VAE Encode (for Inpainting)",
  inputs: {
    pixels: {
      name: "pixels"
    },
    vae: {
      name: "vae"
    },
    mask: {
      name: "mask"
    },
    grow_mask_by: {
      name: "grow_mask_by"
    }
  }
};
const VAEEncodeTiled$6 = {
  display_name: "VAE Encode (Tiled)",
  inputs: {
    pixels: {
      name: "pixels"
    },
    vae: {
      name: "vae"
    },
    tile_size: {
      name: "tile_size"
    },
    overlap: {
      name: "overlap"
    },
    temporal_size: {
      name: "temporal_size",
      tooltip: "Only used for video VAEs: Amount of frames to encode at a time."
    },
    temporal_overlap: {
      name: "temporal_overlap",
      tooltip: "Only used for video VAEs: Amount of frames to overlap."
    }
  }
};
const VAELoader$6 = {
  display_name: "Load VAE",
  inputs: {
    vae_name: {
      name: "vae_name"
    }
  }
};
const VAESave$6 = {
  display_name: "VAESave",
  inputs: {
    vae: {
      name: "vae"
    },
    filename_prefix: {
      name: "filename_prefix"
    }
  }
};
const VeoVideoGenerationNode$6 = {
  display_name: "Google Veo2 Video Generation",
  description: "Generates videos from text prompts using Google's Veo API",
  inputs: {
    prompt: {
      name: "prompt",
      tooltip: "Text description of the video"
    },
    aspect_ratio: {
      name: "aspect_ratio",
      tooltip: "Aspect ratio of the output video"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Negative text prompt to guide what to avoid in the video"
    },
    duration_seconds: {
      name: "duration_seconds",
      tooltip: "Duration of the output video in seconds"
    },
    enhance_prompt: {
      name: "enhance_prompt",
      tooltip: "Whether to enhance the prompt with AI assistance"
    },
    person_generation: {
      name: "person_generation",
      tooltip: "Whether to allow generating people in the video"
    },
    seed: {
      name: "seed",
      tooltip: "Seed for video generation (0 for random)"
    },
    image: {
      name: "image",
      tooltip: "Optional reference image to guide video generation"
    },
    control_after_generate: {
      name: "control after generate"
    }
  }
};
const VideoLinearCFGGuidance$6 = {
  display_name: "VideoLinearCFGGuidance",
  inputs: {
    model: {
      name: "model"
    },
    min_cfg: {
      name: "min_cfg"
    }
  }
};
const VideoTriangleCFGGuidance$6 = {
  display_name: "VideoTriangleCFGGuidance",
  inputs: {
    model: {
      name: "model"
    },
    min_cfg: {
      name: "min_cfg"
    }
  }
};
const VoxelToMesh$6 = {
  display_name: "VoxelToMesh",
  inputs: {
    voxel: {
      name: "voxel"
    },
    algorithm: {
      name: "algorithm"
    },
    threshold: {
      name: "threshold"
    }
  }
};
const VoxelToMeshBasic$6 = {
  display_name: "VoxelToMeshBasic",
  inputs: {
    voxel: {
      name: "voxel"
    },
    threshold: {
      name: "threshold"
    }
  }
};
const VPScheduler$6 = {
  display_name: "VPScheduler",
  inputs: {
    steps: {
      name: "steps"
    },
    beta_d: {
      name: "beta_d"
    },
    beta_min: {
      name: "beta_min"
    },
    eps_s: {
      name: "eps_s"
    }
  }
};
const WanFirstLastFrameToVideo$6 = {
  display_name: "WanFirstLastFrameToVideo",
  inputs: {
    positive: {
      name: "positive"
    },
    negative: {
      name: "negative"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "width"
    },
    height: {
      name: "height"
    },
    length: {
      name: "length"
    },
    batch_size: {
      name: "batch_size"
    },
    clip_vision_start_image: {
      name: "clip_vision_start_image"
    },
    clip_vision_end_image: {
      name: "clip_vision_end_image"
    },
    start_image: {
      name: "start_image"
    },
    end_image: {
      name: "end_image"
    }
  },
  outputs: {
    "0": {
      name: "positive"
    },
    "1": {
      name: "negative"
    },
    "2": {
      name: "latent"
    }
  }
};
const WanFunControlToVideo$6 = {
  display_name: "WanFunControlToVideo",
  inputs: {
    positive: {
      name: "positive"
    },
    negative: {
      name: "negative"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "width"
    },
    height: {
      name: "height"
    },
    length: {
      name: "length"
    },
    batch_size: {
      name: "batch_size"
    },
    clip_vision_output: {
      name: "clip_vision_output"
    },
    start_image: {
      name: "start_image"
    },
    control_video: {
      name: "control_video"
    }
  },
  outputs: {
    "0": {
      name: "positive"
    },
    "1": {
      name: "negative"
    },
    "2": {
      name: "latent"
    }
  }
};
const WanFunInpaintToVideo$6 = {
  display_name: "WanFunInpaintToVideo",
  inputs: {
    positive: {
      name: "positive"
    },
    negative: {
      name: "negative"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "width"
    },
    height: {
      name: "height"
    },
    length: {
      name: "length"
    },
    batch_size: {
      name: "batch_size"
    },
    clip_vision_output: {
      name: "clip_vision_output"
    },
    start_image: {
      name: "start_image"
    },
    end_image: {
      name: "end_image"
    }
  },
  outputs: {
    "0": {
      name: "positive"
    },
    "1": {
      name: "negative"
    },
    "2": {
      name: "latent"
    }
  }
};
const WanImageToVideo$6 = {
  display_name: "WanImageToVideo",
  inputs: {
    positive: {
      name: "positive"
    },
    negative: {
      name: "negative"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "width"
    },
    height: {
      name: "height"
    },
    length: {
      name: "length"
    },
    batch_size: {
      name: "batch_size"
    },
    clip_vision_output: {
      name: "clip_vision_output"
    },
    start_image: {
      name: "start_image"
    }
  },
  outputs: {
    "0": {
      name: "positive"
    },
    "1": {
      name: "negative"
    },
    "2": {
      name: "latent"
    }
  }
};
const WanVaceToVideo$6 = {
  display_name: "WanVaceToVideo",
  inputs: {
    positive: {
      name: "positive"
    },
    negative: {
      name: "negative"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "width"
    },
    height: {
      name: "height"
    },
    length: {
      name: "length"
    },
    batch_size: {
      name: "batch_size"
    },
    strength: {
      name: "strength"
    },
    control_video: {
      name: "control_video"
    },
    control_masks: {
      name: "control_masks"
    },
    reference_image: {
      name: "reference_image"
    }
  },
  outputs: {
    "0": {
      name: "positive"
    },
    "1": {
      name: "negative"
    },
    "2": {
      name: "latent"
    },
    "3": {
      name: "trim_latent"
    }
  }
};
const WebcamCapture$6 = {
  display_name: "Webcam Capture",
  inputs: {
    image: {
      name: "image"
    },
    width: {
      name: "width"
    },
    height: {
      name: "height"
    },
    capture_on_queue: {
      name: "capture_on_queue"
    },
    "waiting for camera___": {}
  }
};
const enNodes = {
  AddNoise: AddNoise$6,
  AlignYourStepsScheduler: AlignYourStepsScheduler$6,
  BasicGuider: BasicGuider$6,
  BasicScheduler: BasicScheduler$6,
  BetaSamplingScheduler: BetaSamplingScheduler$6,
  Canny: Canny$6,
  CFGGuider: CFGGuider$6,
  CFGZeroStar: CFGZeroStar$6,
  CheckpointLoader: CheckpointLoader$6,
  CheckpointLoaderSimple: CheckpointLoaderSimple$6,
  CheckpointSave: CheckpointSave$6,
  CLIPAttentionMultiply: CLIPAttentionMultiply$6,
  CLIPLoader: CLIPLoader$6,
  CLIPMergeAdd: CLIPMergeAdd$6,
  CLIPMergeSimple: CLIPMergeSimple$6,
  CLIPMergeSubtract: CLIPMergeSubtract$6,
  CLIPSave: CLIPSave$6,
  CLIPSetLastLayer: CLIPSetLastLayer$6,
  CLIPTextEncode: CLIPTextEncode$6,
  CLIPTextEncodeControlnet: CLIPTextEncodeControlnet$6,
  CLIPTextEncodeFlux: CLIPTextEncodeFlux$6,
  CLIPTextEncodeHiDream: CLIPTextEncodeHiDream$6,
  CLIPTextEncodeHunyuanDiT: CLIPTextEncodeHunyuanDiT$6,
  CLIPTextEncodeLumina2: CLIPTextEncodeLumina2$6,
  CLIPTextEncodePixArtAlpha: CLIPTextEncodePixArtAlpha$6,
  CLIPTextEncodeSD3: CLIPTextEncodeSD3$6,
  CLIPTextEncodeSDXL: CLIPTextEncodeSDXL$6,
  CLIPTextEncodeSDXLRefiner: CLIPTextEncodeSDXLRefiner$6,
  CLIPVisionEncode: CLIPVisionEncode$6,
  CLIPVisionLoader: CLIPVisionLoader$6,
  CombineHooks2: CombineHooks2$6,
  CombineHooks4: CombineHooks4$6,
  CombineHooks8: CombineHooks8$6,
  ConditioningAverage: ConditioningAverage$6,
  ConditioningCombine: ConditioningCombine$6,
  ConditioningConcat: ConditioningConcat$6,
  ConditioningSetArea: ConditioningSetArea$6,
  ConditioningSetAreaPercentage: ConditioningSetAreaPercentage$6,
  ConditioningSetAreaPercentageVideo: ConditioningSetAreaPercentageVideo$6,
  ConditioningSetAreaStrength: ConditioningSetAreaStrength$6,
  ConditioningSetDefaultCombine: ConditioningSetDefaultCombine$6,
  ConditioningSetMask: ConditioningSetMask$6,
  ConditioningSetProperties: ConditioningSetProperties$6,
  ConditioningSetPropertiesAndCombine: ConditioningSetPropertiesAndCombine$6,
  ConditioningSetTimestepRange: ConditioningSetTimestepRange$6,
  ConditioningStableAudio: ConditioningStableAudio$6,
  ConditioningTimestepsRange: ConditioningTimestepsRange$6,
  ConditioningZeroOut: ConditioningZeroOut$6,
  ControlNetApply: ControlNetApply$6,
  ControlNetApplyAdvanced: ControlNetApplyAdvanced$6,
  ControlNetApplySD3: ControlNetApplySD3$6,
  ControlNetInpaintingAliMamaApply: ControlNetInpaintingAliMamaApply$6,
  ControlNetLoader: ControlNetLoader$6,
  CosmosImageToVideoLatent: CosmosImageToVideoLatent$6,
  CreateHookKeyframe: CreateHookKeyframe$6,
  CreateHookKeyframesFromFloats: CreateHookKeyframesFromFloats$6,
  CreateHookKeyframesInterpolated: CreateHookKeyframesInterpolated$6,
  CreateHookLora: CreateHookLora$6,
  CreateHookLoraModelOnly: CreateHookLoraModelOnly$6,
  CreateHookModelAsLora: CreateHookModelAsLora$6,
  CreateHookModelAsLoraModelOnly: CreateHookModelAsLoraModelOnly$6,
  CreateVideo: CreateVideo$6,
  CropMask: CropMask$6,
  DiffControlNetLoader: DiffControlNetLoader$6,
  DifferentialDiffusion: DifferentialDiffusion$6,
  DiffusersLoader: DiffusersLoader$6,
  DisableNoise: DisableNoise$6,
  DualCFGGuider: DualCFGGuider$6,
  DualCLIPLoader: DualCLIPLoader$6,
  EmptyCosmosLatentVideo: EmptyCosmosLatentVideo$6,
  EmptyHunyuanLatentVideo: EmptyHunyuanLatentVideo$6,
  EmptyImage: EmptyImage$6,
  EmptyLatentAudio: EmptyLatentAudio$6,
  EmptyLatentHunyuan3Dv2: EmptyLatentHunyuan3Dv2$6,
  EmptyLatentImage: EmptyLatentImage$6,
  EmptyLTXVLatentVideo: EmptyLTXVLatentVideo$6,
  EmptyMochiLatentVideo: EmptyMochiLatentVideo$6,
  EmptySD3LatentImage: EmptySD3LatentImage$6,
  ExponentialScheduler: ExponentialScheduler$6,
  ExtendIntermediateSigmas: ExtendIntermediateSigmas$6,
  FeatherMask: FeatherMask$6,
  FlipSigmas: FlipSigmas$6,
  FluxDisableGuidance: FluxDisableGuidance$6,
  FluxGuidance: FluxGuidance$6,
  FluxProCannyNode: FluxProCannyNode$6,
  FluxProDepthNode: FluxProDepthNode$6,
  FluxProExpandNode: FluxProExpandNode$6,
  FluxProFillNode: FluxProFillNode$6,
  FluxProUltraImageNode: FluxProUltraImageNode$6,
  FreeU: FreeU$6,
  FreeU_V2: FreeU_V2$6,
  FreSca: FreSca$6,
  GetVideoComponents: GetVideoComponents$6,
  GITSScheduler: GITSScheduler$6,
  GLIGENLoader: GLIGENLoader$6,
  GLIGENTextBoxApply: GLIGENTextBoxApply$6,
  GrowMask: GrowMask$6,
  Hunyuan3Dv2Conditioning: Hunyuan3Dv2Conditioning$6,
  Hunyuan3Dv2ConditioningMultiView: Hunyuan3Dv2ConditioningMultiView$6,
  HunyuanImageToVideo: HunyuanImageToVideo$6,
  HypernetworkLoader: HypernetworkLoader$6,
  HyperTile: HyperTile$6,
  IdeogramV1: IdeogramV1$6,
  IdeogramV2: IdeogramV2$6,
  IdeogramV3: IdeogramV3$6,
  ImageBatch: ImageBatch$6,
  ImageBlend: ImageBlend$6,
  ImageBlur: ImageBlur$6,
  ImageColorToMask: ImageColorToMask$6,
  ImageCompositeMasked: ImageCompositeMasked$6,
  ImageCrop: ImageCrop$6,
  ImageFromBatch: ImageFromBatch$6,
  ImageInvert: ImageInvert$6,
  ImageOnlyCheckpointLoader: ImageOnlyCheckpointLoader$6,
  ImageOnlyCheckpointSave: ImageOnlyCheckpointSave$6,
  ImagePadForOutpaint: ImagePadForOutpaint$6,
  ImageQuantize: ImageQuantize$6,
  ImageRGBToYUV: ImageRGBToYUV$6,
  ImageScale: ImageScale$6,
  ImageScaleBy: ImageScaleBy$6,
  ImageScaleToTotalPixels: ImageScaleToTotalPixels$6,
  ImageSharpen: ImageSharpen$6,
  ImageToMask: ImageToMask$6,
  ImageUpscaleWithModel: ImageUpscaleWithModel$6,
  ImageYUVToRGB: ImageYUVToRGB$6,
  InpaintModelConditioning: InpaintModelConditioning$6,
  InstructPixToPixConditioning: InstructPixToPixConditioning$6,
  InvertMask: InvertMask$6,
  JoinImageWithAlpha: JoinImageWithAlpha$6,
  KarrasScheduler: KarrasScheduler$6,
  KlingCameraControlI2VNode: KlingCameraControlI2VNode$6,
  KlingCameraControls: KlingCameraControls$6,
  KlingCameraControlT2VNode: KlingCameraControlT2VNode$6,
  KlingDualCharacterVideoEffectNode: KlingDualCharacterVideoEffectNode$6,
  KlingImage2VideoNode: KlingImage2VideoNode$6,
  KlingImageGenerationNode: KlingImageGenerationNode$6,
  KlingLipSyncAudioToVideoNode: KlingLipSyncAudioToVideoNode$6,
  KlingLipSyncTextToVideoNode: KlingLipSyncTextToVideoNode$6,
  KlingSingleImageVideoEffectNode: KlingSingleImageVideoEffectNode$6,
  KlingStartEndFrameNode: KlingStartEndFrameNode$6,
  KlingTextToVideoNode: KlingTextToVideoNode$6,
  KlingVideoExtendNode: KlingVideoExtendNode$6,
  KlingVirtualTryOnNode: KlingVirtualTryOnNode$6,
  KSampler: KSampler$6,
  KSamplerAdvanced: KSamplerAdvanced$6,
  KSamplerSelect: KSamplerSelect$6,
  LaplaceScheduler: LaplaceScheduler$6,
  LatentAdd: LatentAdd$6,
  LatentApplyOperation: LatentApplyOperation$6,
  LatentApplyOperationCFG: LatentApplyOperationCFG$6,
  LatentBatch: LatentBatch$6,
  LatentBatchSeedBehavior: LatentBatchSeedBehavior$6,
  LatentBlend: LatentBlend$6,
  LatentComposite: LatentComposite$6,
  LatentCompositeMasked: LatentCompositeMasked$6,
  LatentCrop: LatentCrop$6,
  LatentFlip: LatentFlip$6,
  LatentFromBatch: LatentFromBatch$6,
  LatentInterpolate: LatentInterpolate$6,
  LatentMultiply: LatentMultiply$6,
  LatentOperationSharpen: LatentOperationSharpen$6,
  LatentOperationTonemapReinhard: LatentOperationTonemapReinhard$6,
  LatentRotate: LatentRotate$6,
  LatentSubtract: LatentSubtract$6,
  LatentUpscale: LatentUpscale$6,
  LatentUpscaleBy: LatentUpscaleBy$6,
  Load3D: Load3D$6,
  Load3DAnimation: Load3DAnimation$6,
  LoadAudio: LoadAudio$6,
  LoadImage: LoadImage$6,
  LoadImageMask: LoadImageMask$6,
  LoadImageOutput: LoadImageOutput$6,
  LoadLatent: LoadLatent$6,
  LoadVideo: LoadVideo$6,
  LoraLoader: LoraLoader$6,
  LoraLoaderModelOnly: LoraLoaderModelOnly$6,
  LoraSave: LoraSave$6,
  LotusConditioning: LotusConditioning$6,
  LTXVAddGuide: LTXVAddGuide$6,
  LTXVConditioning: LTXVConditioning$6,
  LTXVCropGuides: LTXVCropGuides$6,
  LTXVImgToVideo: LTXVImgToVideo$6,
  LTXVPreprocess: LTXVPreprocess$6,
  LTXVScheduler: LTXVScheduler$6,
  LumaConceptsNode: LumaConceptsNode$6,
  LumaImageModifyNode: LumaImageModifyNode$6,
  LumaImageNode: LumaImageNode$6,
  LumaImageToVideoNode: LumaImageToVideoNode$6,
  LumaReferenceNode: LumaReferenceNode$6,
  LumaVideoNode: LumaVideoNode$6,
  Mahiro: Mahiro$6,
  MaskComposite: MaskComposite$6,
  MaskPreview: MaskPreview$6,
  MaskToImage: MaskToImage$6,
  MinimaxImageToVideoNode: MinimaxImageToVideoNode$6,
  MinimaxTextToVideoNode: MinimaxTextToVideoNode$6,
  ModelComputeDtype: ModelComputeDtype$6,
  ModelMergeAdd: ModelMergeAdd$6,
  ModelMergeAuraflow: ModelMergeAuraflow$6,
  ModelMergeBlocks: ModelMergeBlocks$6,
  ModelMergeCosmos14B: ModelMergeCosmos14B$6,
  ModelMergeCosmos7B: ModelMergeCosmos7B$6,
  ModelMergeFlux1: ModelMergeFlux1$6,
  ModelMergeLTXV: ModelMergeLTXV$6,
  ModelMergeMochiPreview: ModelMergeMochiPreview$6,
  ModelMergeSD1: ModelMergeSD1$6,
  ModelMergeSD2: ModelMergeSD2$6,
  ModelMergeSD3_2B: ModelMergeSD3_2B$6,
  ModelMergeSD35_Large: ModelMergeSD35_Large$6,
  ModelMergeSDXL: ModelMergeSDXL$6,
  ModelMergeSimple: ModelMergeSimple$6,
  ModelMergeSubtract: ModelMergeSubtract$6,
  ModelMergeWAN2_1: ModelMergeWAN2_1$6,
  ModelSamplingAuraFlow: ModelSamplingAuraFlow$6,
  ModelSamplingContinuousEDM: ModelSamplingContinuousEDM$6,
  ModelSamplingContinuousV: ModelSamplingContinuousV$6,
  ModelSamplingDiscrete: ModelSamplingDiscrete$6,
  ModelSamplingFlux: ModelSamplingFlux$6,
  ModelSamplingLTXV: ModelSamplingLTXV$6,
  ModelSamplingSD3: ModelSamplingSD3$6,
  ModelSamplingStableCascade: ModelSamplingStableCascade$6,
  ModelSave: ModelSave$6,
  Morphology: Morphology$6,
  OpenAIDalle2: OpenAIDalle2$6,
  OpenAIDalle3: OpenAIDalle3$6,
  OpenAIGPTImage1: OpenAIGPTImage1$6,
  OptimalStepsScheduler: OptimalStepsScheduler$6,
  PairConditioningCombine: PairConditioningCombine$6,
  PairConditioningSetDefaultCombine: PairConditioningSetDefaultCombine$6,
  PairConditioningSetProperties: PairConditioningSetProperties$6,
  PairConditioningSetPropertiesAndCombine: PairConditioningSetPropertiesAndCombine$6,
  PatchModelAddDownscale: PatchModelAddDownscale$6,
  PerpNeg: PerpNeg$6,
  PerpNegGuider: PerpNegGuider$6,
  PerturbedAttentionGuidance: PerturbedAttentionGuidance$6,
  PhotoMakerEncode: PhotoMakerEncode$6,
  PhotoMakerLoader: PhotoMakerLoader$6,
  Pikadditions: Pikadditions$6,
  Pikaffects: Pikaffects$6,
  PikaImageToVideoNode2_2: PikaImageToVideoNode2_2$6,
  PikaScenesV2_2: PikaScenesV2_2$6,
  PikaStartEndFrameNode2_2: PikaStartEndFrameNode2_2$6,
  Pikaswaps: Pikaswaps$6,
  PikaTextToVideoNode2_2: PikaTextToVideoNode2_2$6,
  PixverseImageToVideoNode: PixverseImageToVideoNode$6,
  PixverseTemplateNode: PixverseTemplateNode$6,
  PixverseTextToVideoNode: PixverseTextToVideoNode$6,
  PixverseTransitionVideoNode: PixverseTransitionVideoNode$6,
  PolyexponentialScheduler: PolyexponentialScheduler$6,
  PorterDuffImageComposite: PorterDuffImageComposite$6,
  Preview3D: Preview3D$6,
  Preview3DAnimation: Preview3DAnimation$6,
  PreviewAny: PreviewAny$6,
  PreviewAudio: PreviewAudio$6,
  PreviewImage: PreviewImage$6,
  PrimitiveBoolean: PrimitiveBoolean$6,
  PrimitiveFloat: PrimitiveFloat$6,
  PrimitiveInt: PrimitiveInt$6,
  PrimitiveString: PrimitiveString$6,
  PrimitiveStringMultiline: PrimitiveStringMultiline$6,
  QuadrupleCLIPLoader: QuadrupleCLIPLoader$6,
  RandomNoise: RandomNoise$6,
  RebatchImages: RebatchImages$6,
  RebatchLatents: RebatchLatents$6,
  RecraftColorRGB: RecraftColorRGB$6,
  RecraftControls: RecraftControls$6,
  RecraftCreativeUpscaleNode: RecraftCreativeUpscaleNode$6,
  RecraftCrispUpscaleNode: RecraftCrispUpscaleNode$6,
  RecraftImageInpaintingNode: RecraftImageInpaintingNode$6,
  RecraftImageToImageNode: RecraftImageToImageNode$6,
  RecraftRemoveBackgroundNode: RecraftRemoveBackgroundNode$6,
  RecraftReplaceBackgroundNode: RecraftReplaceBackgroundNode$6,
  RecraftStyleV3DigitalIllustration: RecraftStyleV3DigitalIllustration$6,
  RecraftStyleV3InfiniteStyleLibrary: RecraftStyleV3InfiniteStyleLibrary$6,
  RecraftStyleV3LogoRaster: RecraftStyleV3LogoRaster$6,
  RecraftStyleV3RealisticImage: RecraftStyleV3RealisticImage$6,
  RecraftTextToImageNode: RecraftTextToImageNode$6,
  RecraftTextToVectorNode: RecraftTextToVectorNode$6,
  RecraftVectorizeImageNode: RecraftVectorizeImageNode$6,
  RenormCFG: RenormCFG$6,
  RepeatImageBatch: RepeatImageBatch$6,
  RepeatLatentBatch: RepeatLatentBatch$6,
  RescaleCFG: RescaleCFG$6,
  SamplerCustom: SamplerCustom$6,
  SamplerCustomAdvanced: SamplerCustomAdvanced$6,
  SamplerDPMAdaptative: SamplerDPMAdaptative$6,
  SamplerDPMPP_2M_SDE: SamplerDPMPP_2M_SDE$6,
  SamplerDPMPP_2S_Ancestral: SamplerDPMPP_2S_Ancestral$6,
  SamplerDPMPP_3M_SDE: SamplerDPMPP_3M_SDE$6,
  SamplerDPMPP_SDE: SamplerDPMPP_SDE$6,
  SamplerEulerAncestral: SamplerEulerAncestral$6,
  SamplerEulerAncestralCFGPP: SamplerEulerAncestralCFGPP$6,
  SamplerEulerCFGpp: SamplerEulerCFGpp$6,
  SamplerLCMUpscale: SamplerLCMUpscale$6,
  SamplerLMS: SamplerLMS$6,
  SaveAnimatedPNG: SaveAnimatedPNG$6,
  SaveAnimatedWEBP: SaveAnimatedWEBP$6,
  SaveAudio: SaveAudio$6,
  SaveGLB: SaveGLB$6,
  SaveImage: SaveImage$6,
  SaveImageWebsocket: SaveImageWebsocket$6,
  SaveLatent: SaveLatent$6,
  SaveSVG: SaveSVG$6,
  SaveVideo: SaveVideo$6,
  SaveWEBM: SaveWEBM$6,
  SD_4XUpscale_Conditioning: SD_4XUpscale_Conditioning$6,
  SDTurboScheduler: SDTurboScheduler$6,
  SelfAttentionGuidance: SelfAttentionGuidance$6,
  SetClipHooks: SetClipHooks$6,
  SetFirstSigma: SetFirstSigma$6,
  SetHookKeyframes: SetHookKeyframes$6,
  SetLatentNoiseMask: SetLatentNoiseMask$6,
  SetUnionControlNetType: SetUnionControlNetType$6,
  SkipLayerGuidanceDiT: SkipLayerGuidanceDiT$6,
  SkipLayerGuidanceSD3: SkipLayerGuidanceSD3$6,
  SolidMask: SolidMask$6,
  SplitImageWithAlpha: SplitImageWithAlpha$6,
  SplitSigmas: SplitSigmas$6,
  SplitSigmasDenoise: SplitSigmasDenoise$6,
  StabilityStableImageSD_3_5Node: StabilityStableImageSD_3_5Node$6,
  StabilityStableImageUltraNode: StabilityStableImageUltraNode$6,
  StabilityUpscaleConservativeNode: StabilityUpscaleConservativeNode$6,
  StabilityUpscaleCreativeNode: StabilityUpscaleCreativeNode$6,
  StabilityUpscaleFastNode: StabilityUpscaleFastNode$6,
  StableCascade_EmptyLatentImage: StableCascade_EmptyLatentImage$6,
  StableCascade_StageB_Conditioning: StableCascade_StageB_Conditioning$6,
  StableCascade_StageC_VAEEncode: StableCascade_StageC_VAEEncode$6,
  StableCascade_SuperResolutionControlnet: StableCascade_SuperResolutionControlnet$6,
  StableZero123_Conditioning: StableZero123_Conditioning$6,
  StableZero123_Conditioning_Batched: StableZero123_Conditioning_Batched$6,
  StyleModelApply: StyleModelApply$6,
  StyleModelLoader: StyleModelLoader$6,
  SV3D_Conditioning: SV3D_Conditioning$6,
  SVD_img2vid_Conditioning: SVD_img2vid_Conditioning$6,
  T5TokenizerOptions: T5TokenizerOptions$6,
  TextEncodeHunyuanVideo_ImageToVideo: TextEncodeHunyuanVideo_ImageToVideo$6,
  ThresholdMask: ThresholdMask$6,
  TomePatchModel: TomePatchModel$6,
  TorchCompileModel: TorchCompileModel$6,
  TrimVideoLatent: TrimVideoLatent$6,
  TripleCLIPLoader: TripleCLIPLoader$6,
  unCLIPCheckpointLoader: unCLIPCheckpointLoader$6,
  unCLIPConditioning: unCLIPConditioning$6,
  UNetCrossAttentionMultiply: UNetCrossAttentionMultiply$6,
  UNETLoader: UNETLoader$6,
  UNetSelfAttentionMultiply: UNetSelfAttentionMultiply$6,
  UNetTemporalAttentionMultiply: UNetTemporalAttentionMultiply$6,
  UpscaleModelLoader: UpscaleModelLoader$6,
  VAEDecode: VAEDecode$6,
  VAEDecodeAudio: VAEDecodeAudio$6,
  VAEDecodeHunyuan3D: VAEDecodeHunyuan3D$6,
  VAEDecodeTiled: VAEDecodeTiled$6,
  VAEEncode: VAEEncode$6,
  VAEEncodeAudio: VAEEncodeAudio$6,
  VAEEncodeForInpaint: VAEEncodeForInpaint$6,
  VAEEncodeTiled: VAEEncodeTiled$6,
  VAELoader: VAELoader$6,
  VAESave: VAESave$6,
  VeoVideoGenerationNode: VeoVideoGenerationNode$6,
  VideoLinearCFGGuidance: VideoLinearCFGGuidance$6,
  VideoTriangleCFGGuidance: VideoTriangleCFGGuidance$6,
  VoxelToMesh: VoxelToMesh$6,
  VoxelToMeshBasic: VoxelToMeshBasic$6,
  VPScheduler: VPScheduler$6,
  WanFirstLastFrameToVideo: WanFirstLastFrameToVideo$6,
  WanFunControlToVideo: WanFunControlToVideo$6,
  WanFunInpaintToVideo: WanFunInpaintToVideo$6,
  WanImageToVideo: WanImageToVideo$6,
  WanVaceToVideo: WanVaceToVideo$6,
  WebcamCapture: WebcamCapture$6
};
const Comfy_Canvas_SelectionToolbox$6 = {
  name: "Show selection toolbox"
};
const Comfy_ConfirmClear$6 = {
  name: "Require confirmation when clearing workflow"
};
const Comfy_DevMode$6 = {
  name: "Enable dev mode options (API save, etc.)"
};
const Comfy_DisableFloatRounding$6 = {
  name: "Disable default float widget rounding.",
  tooltip: "(requires page reload) Cannot disable round when round is set by the node in the backend."
};
const Comfy_DisableSliders$6 = {
  name: "Disable node widget sliders"
};
const Comfy_DOMClippingEnabled$6 = {
  name: "Enable DOM element clipping (enabling may reduce performance)"
};
const Comfy_EditAttention_Delta$6 = {
  name: "Ctrl+up/down precision"
};
const Comfy_EnableTooltips$6 = {
  name: "Enable Tooltips"
};
const Comfy_EnableWorkflowViewRestore$6 = {
  name: "Save and restore canvas position and zoom level in workflows"
};
const Comfy_FloatRoundingPrecision$6 = {
  name: "Float widget rounding decimal places [0 = auto].",
  tooltip: "(requires page reload)"
};
const Comfy_Graph_CanvasInfo$6 = {
  name: "Show canvas info on bottom left corner (fps, etc.)"
};
const Comfy_Graph_CanvasMenu$6 = {
  name: "Show graph canvas menu"
};
const Comfy_Graph_CtrlShiftZoom$6 = {
  name: "Enable fast-zoom shortcut (Ctrl + Shift + Drag)"
};
const Comfy_Graph_LinkMarkers$6 = {
  name: "Link midpoint markers",
  options: {
    None: "None",
    Circle: "Circle",
    Arrow: "Arrow"
  }
};
const Comfy_Graph_ZoomSpeed$6 = {
  name: "Canvas zoom speed"
};
const Comfy_Group_DoubleClickTitleToEdit$6 = {
  name: "Double click group title to edit"
};
const Comfy_GroupSelectedNodes_Padding$6 = {
  name: "Group selected nodes padding"
};
const Comfy_LinkRelease_Action$6 = {
  name: "Action on link release (No modifier)",
  options: {
    "context menu": "context menu",
    "search box": "search box",
    "no action": "no action"
  }
};
const Comfy_LinkRelease_ActionShift$6 = {
  name: "Action on link release (Shift)",
  options: {
    "context menu": "context menu",
    "search box": "search box",
    "no action": "no action"
  }
};
const Comfy_LinkRenderMode$6 = {
  name: "Link Render Mode",
  options: {
    Straight: "Straight",
    Linear: "Linear",
    Spline: "Spline",
    Hidden: "Hidden"
  }
};
const Comfy_Load3D_BackgroundColor$6 = {
  name: "Initial Background Color",
  tooltip: "Controls the default background color of the 3D scene. This setting determines the background appearance when a new 3D widget is created, but can be adjusted individually for each widget after creation."
};
const Comfy_Load3D_CameraType$6 = {
  name: "Initial Camera Type",
  tooltip: "Controls whether the camera is perspective or orthographic by default when a new 3D widget is created. This default can still be toggled individually for each widget after creation.",
  options: {
    perspective: "perspective",
    orthographic: "orthographic"
  }
};
const Comfy_Load3D_LightAdjustmentIncrement$6 = {
  name: "Light Adjustment Increment",
  tooltip: "Controls the increment size when adjusting light intensity in 3D scenes. A smaller step value allows for finer control over lighting adjustments, while a larger value results in more noticeable changes per adjustment."
};
const Comfy_Load3D_LightIntensity$6 = {
  name: "Initial Light Intensity",
  tooltip: "Sets the default brightness level of lighting in the 3D scene. This value determines how intensely lights illuminate objects when a new 3D widget is created, but can be adjusted individually for each widget after creation."
};
const Comfy_Load3D_LightIntensityMaximum$6 = {
  name: "Light Intensity Maximum",
  tooltip: "Sets the maximum allowable light intensity value for 3D scenes. This defines the upper brightness limit that can be set when adjusting lighting in any 3D widget."
};
const Comfy_Load3D_LightIntensityMinimum$6 = {
  name: "Light Intensity Minimum",
  tooltip: "Sets the minimum allowable light intensity value for 3D scenes. This defines the lower brightness limit that can be set when adjusting lighting in any 3D widget."
};
const Comfy_Load3D_ShowGrid$6 = {
  name: "Initial Grid Visibility",
  tooltip: "Controls whether the grid is visible by default when a new 3D widget is created. This default can still be toggled individually for each widget after creation."
};
const Comfy_Load3D_ShowPreview$6 = {
  name: "Initial Preview Visibility",
  tooltip: "Controls whether the preview screen is visible by default when a new 3D widget is created. This default can still be toggled individually for each widget after creation."
};
const Comfy_Locale$6 = {
  name: "Language"
};
const Comfy_MaskEditor_BrushAdjustmentSpeed$6 = {
  name: "Brush adjustment speed multiplier",
  tooltip: "Controls how quickly the brush size and hardness change when adjusting. Higher values mean faster changes."
};
const Comfy_MaskEditor_UseDominantAxis$6 = {
  name: "Lock brush adjustment to dominant axis",
  tooltip: "When enabled, brush adjustments will only affect size OR hardness based on which direction you move more"
};
const Comfy_MaskEditor_UseNewEditor$6 = {
  name: "Use new mask editor",
  tooltip: "Switch to the new mask editor interface"
};
const Comfy_ModelLibrary_AutoLoadAll$6 = {
  name: "Automatically load all model folders",
  tooltip: "If true, all folders will load as soon as you open the model library (this may cause delays while it loads). If false, root level model folders will only load once you click on them."
};
const Comfy_ModelLibrary_NameFormat$6 = {
  name: "What name to display in the model library tree view",
  tooltip: 'Select "filename" to render a simplified view of the raw filename (without directory or ".safetensors" extension) in the model list. Select "title" to display the configurable model metadata title.',
  options: {
    filename: "filename",
    title: "title"
  }
};
const Comfy_Node_AllowImageSizeDraw$6 = {
  name: "Show width × height below the image preview"
};
const Comfy_Node_AutoSnapLinkToSlot$6 = {
  name: "Auto snap link to node slot",
  tooltip: "When dragging a link over a node, the link automatically snap to a viable input slot on the node"
};
const Comfy_Node_BypassAllLinksOnDelete$6 = {
  name: "Keep all links when deleting nodes",
  tooltip: "When deleting a node, attempt to reconnect all of its input and output links (bypassing the deleted node)"
};
const Comfy_Node_DoubleClickTitleToEdit$6 = {
  name: "Double click node title to edit"
};
const Comfy_Node_MiddleClickRerouteNode$6 = {
  name: "Middle-click creates a new Reroute node"
};
const Comfy_Node_Opacity$6 = {
  name: "Node opacity"
};
const Comfy_Node_ShowDeprecated$6 = {
  name: "Show deprecated nodes in search",
  tooltip: "Deprecated nodes are hidden by default in the UI, but remain functional in existing workflows that use them."
};
const Comfy_Node_ShowExperimental$6 = {
  name: "Show experimental nodes in search",
  tooltip: "Experimental nodes are marked as such in the UI and may be subject to significant changes or removal in future versions. Use with caution in production workflows"
};
const Comfy_Node_SnapHighlightsNode$6 = {
  name: "Snap highlights node",
  tooltip: "When dragging a link over a node with viable input slot, highlight the node"
};
const Comfy_NodeBadge_NodeIdBadgeMode$6 = {
  name: "Node ID badge mode",
  options: {
    None: "None",
    "Show all": "Show all"
  }
};
const Comfy_NodeBadge_NodeLifeCycleBadgeMode$6 = {
  name: "Node life cycle badge mode",
  options: {
    None: "None",
    "Show all": "Show all"
  }
};
const Comfy_NodeBadge_NodeSourceBadgeMode$6 = {
  name: "Node source badge mode",
  options: {
    None: "None",
    "Show all": "Show all",
    "Hide built-in": "Hide built-in"
  }
};
const Comfy_NodeSearchBoxImpl$6 = {
  name: "Node search box implementation",
  options: {
    "default": "default",
    "litegraph (legacy)": "litegraph (legacy)"
  }
};
const Comfy_NodeSearchBoxImpl_NodePreview$6 = {
  name: "Node preview",
  tooltip: "Only applies to the default implementation"
};
const Comfy_NodeSearchBoxImpl_ShowCategory$6 = {
  name: "Show node category in search results",
  tooltip: "Only applies to the default implementation"
};
const Comfy_NodeSearchBoxImpl_ShowIdName$6 = {
  name: "Show node id name in search results",
  tooltip: "Only applies to the default implementation"
};
const Comfy_NodeSearchBoxImpl_ShowNodeFrequency$6 = {
  name: "Show node frequency in search results",
  tooltip: "Only applies to the default implementation"
};
const Comfy_NodeSuggestions_number$6 = {
  name: "Number of nodes suggestions",
  tooltip: "Only for litegraph searchbox/context menu"
};
const Comfy_Pointer_ClickBufferTime$6 = {
  name: "Pointer click drift delay",
  tooltip: "After pressing a pointer button down, this is the maximum time (in milliseconds) that pointer movement can be ignored for.\n\nHelps prevent objects from being unintentionally nudged if the pointer is moved whilst clicking."
};
const Comfy_Pointer_ClickDrift$6 = {
  name: "Pointer click drift (maximum distance)",
  tooltip: "If the pointer moves more than this distance while holding a button down, it is considered dragging (rather than clicking).\n\nHelps prevent objects from being unintentionally nudged if the pointer is moved whilst clicking."
};
const Comfy_Pointer_DoubleClickTime$6 = {
  name: "Double click interval (maximum)",
  tooltip: "The maximum time in milliseconds between the two clicks of a double-click.  Increasing this value may assist if double-clicks are sometimes not registered."
};
const Comfy_PreviewFormat$6 = {
  name: "Preview image format",
  tooltip: "When displaying a preview in the image widget, convert it to a lightweight image, e.g. webp, jpeg, webp;50, etc."
};
const Comfy_PromptFilename$6 = {
  name: "Prompt for filename when saving workflow"
};
const Comfy_Queue_MaxHistoryItems$6 = {
  name: "Queue history size",
  tooltip: "The maximum number of tasks that show in the queue history."
};
const Comfy_QueueButton_BatchCountLimit$6 = {
  name: "Batch count limit",
  tooltip: "The maximum number of tasks added to the queue at one button click"
};
const Comfy_Sidebar_Location$6 = {
  name: "Sidebar location",
  options: {
    left: "left",
    right: "right"
  }
};
const Comfy_Sidebar_Size$6 = {
  name: "Sidebar size",
  options: {
    normal: "normal",
    small: "small"
  }
};
const Comfy_Sidebar_UnifiedWidth$6 = {
  name: "Unified sidebar width"
};
const Comfy_SnapToGrid_GridSize$6 = {
  name: "Snap to grid size",
  tooltip: "When dragging and resizing nodes while holding shift they will be aligned to the grid, this controls the size of that grid."
};
const Comfy_TextareaWidget_FontSize$6 = {
  name: "Textarea widget font size"
};
const Comfy_TextareaWidget_Spellcheck$6 = {
  name: "Textarea widget spellcheck"
};
const Comfy_TreeExplorer_ItemPadding$6 = {
  name: "Tree explorer item padding"
};
const Comfy_UseNewMenu$6 = {
  name: "Use new menu",
  options: {
    Disabled: "Disabled",
    Top: "Top",
    Bottom: "Bottom"
  }
};
const Comfy_Validation_NodeDefs$6 = {
  name: "Validate node definitions (slow)",
  tooltip: "Recommended for node developers. This will validate all node definitions on startup."
};
const Comfy_Validation_Workflows$6 = {
  name: "Validate workflows"
};
const Comfy_WidgetControlMode$6 = {
  name: "Widget control mode",
  tooltip: "Controls when widget values are updated (randomize/increment/decrement), either before the prompt is queued or after.",
  options: {
    before: "before",
    after: "after"
  }
};
const Comfy_Window_UnloadConfirmation$6 = {
  name: "Show confirmation when closing window"
};
const Comfy_Workflow_AutoSave$6 = {
  name: "Auto Save",
  options: {
    off: "off",
    "after delay": "after delay"
  }
};
const Comfy_Workflow_AutoSaveDelay$6 = {
  name: "Auto Save Delay (ms)",
  tooltip: 'Only applies if Auto Save is set to "after delay".'
};
const Comfy_Workflow_ConfirmDelete$6 = {
  name: "Show confirmation when deleting workflows"
};
const Comfy_Workflow_Persist$6 = {
  name: "Persist workflow state and restore on page (re)load"
};
const Comfy_Workflow_ShowMissingModelsWarning$6 = {
  name: "Show missing models warning"
};
const Comfy_Workflow_ShowMissingNodesWarning$6 = {
  name: "Show missing nodes warning"
};
const Comfy_Workflow_SortNodeIdOnSave$6 = {
  name: "Sort node IDs when saving workflow"
};
const Comfy_Workflow_WorkflowTabsPosition$6 = {
  name: "Opened workflows position",
  options: {
    Sidebar: "Sidebar",
    Topbar: "Topbar",
    "Topbar (2nd-row)": "Topbar (2nd-row)"
  }
};
const LiteGraph_Canvas_LowQualityRenderingZoomThreshold$6 = {
  name: "Low quality rendering zoom threshold",
  tooltip: "Render low quality shapes when zoomed out"
};
const LiteGraph_Canvas_MaximumFps$6 = {
  name: "Maximum FPS",
  tooltip: "The maximum frames per second that the canvas is allowed to render. Caps GPU usage at the cost of smoothness. If 0, the screen refresh rate is used. Default: 0"
};
const LiteGraph_ContextMenu_Scaling$6 = {
  name: "Scale node combo widget menus (lists) when zoomed in"
};
const LiteGraph_Node_DefaultPadding$6 = {
  name: "Always shrink new nodes",
  tooltip: "Resize nodes to the smallest possible size when created. When disabled, a newly added node will be widened slightly to show widget values."
};
const LiteGraph_Node_TooltipDelay$6 = {
  name: "Tooltip Delay"
};
const LiteGraph_Pointer_TrackpadGestures$6 = {
  name: "Enable trackpad gestures",
  tooltip: "This setting enables trackpad mode for the canvas, allowing pinch-to-zoom and panning with two fingers."
};
const LiteGraph_Reroute_SplineOffset$6 = {
  name: "Reroute spline offset",
  tooltip: "The bezier control point offset from the reroute centre point"
};
const pysssss_SnapToGrid$6 = {
  name: "Always snap to grid"
};
const enSettings = {
  "Comfy-Desktop_AutoUpdate": {
    name: "Automatically check for updates"
  },
  "Comfy-Desktop_SendStatistics": {
    name: "Send anonymous usage metrics"
  },
  "Comfy-Desktop_UV_PypiInstallMirror": {
    name: "Pypi Install Mirror",
    tooltip: "Default pip install mirror"
  },
  "Comfy-Desktop_UV_PythonInstallMirror": {
    name: "Python Install Mirror",
    tooltip: "Managed Python installations are downloaded from the Astral python-build-standalone project. This variable can be set to a mirror URL to use a different source for Python installations. The provided URL will replace https://github.com/astral-sh/python-build-standalone/releases/download in, e.g., https://github.com/astral-sh/python-build-standalone/releases/download/20240713/cpython-3.12.4%2B20240713-aarch64-apple-darwin-install_only.tar.gz. Distributions can be read from a local directory by using the file:// URL scheme."
  },
  "Comfy-Desktop_UV_TorchInstallMirror": {
    name: "Torch Install Mirror",
    tooltip: "Pip install mirror for pytorch"
  },
  "Comfy-Desktop_WindowStyle": {
    name: "Window Style",
    tooltip: "Custom: Replace the system title bar with ComfyUI's Top menu",
    options: {
      "default": "default",
      custom: "custom"
    }
  },
  Comfy_Canvas_SelectionToolbox: Comfy_Canvas_SelectionToolbox$6,
  Comfy_ConfirmClear: Comfy_ConfirmClear$6,
  Comfy_DevMode: Comfy_DevMode$6,
  Comfy_DisableFloatRounding: Comfy_DisableFloatRounding$6,
  Comfy_DisableSliders: Comfy_DisableSliders$6,
  Comfy_DOMClippingEnabled: Comfy_DOMClippingEnabled$6,
  Comfy_EditAttention_Delta: Comfy_EditAttention_Delta$6,
  Comfy_EnableTooltips: Comfy_EnableTooltips$6,
  Comfy_EnableWorkflowViewRestore: Comfy_EnableWorkflowViewRestore$6,
  Comfy_FloatRoundingPrecision: Comfy_FloatRoundingPrecision$6,
  Comfy_Graph_CanvasInfo: Comfy_Graph_CanvasInfo$6,
  Comfy_Graph_CanvasMenu: Comfy_Graph_CanvasMenu$6,
  Comfy_Graph_CtrlShiftZoom: Comfy_Graph_CtrlShiftZoom$6,
  Comfy_Graph_LinkMarkers: Comfy_Graph_LinkMarkers$6,
  Comfy_Graph_ZoomSpeed: Comfy_Graph_ZoomSpeed$6,
  Comfy_Group_DoubleClickTitleToEdit: Comfy_Group_DoubleClickTitleToEdit$6,
  Comfy_GroupSelectedNodes_Padding: Comfy_GroupSelectedNodes_Padding$6,
  Comfy_LinkRelease_Action: Comfy_LinkRelease_Action$6,
  Comfy_LinkRelease_ActionShift: Comfy_LinkRelease_ActionShift$6,
  Comfy_LinkRenderMode: Comfy_LinkRenderMode$6,
  Comfy_Load3D_BackgroundColor: Comfy_Load3D_BackgroundColor$6,
  Comfy_Load3D_CameraType: Comfy_Load3D_CameraType$6,
  Comfy_Load3D_LightAdjustmentIncrement: Comfy_Load3D_LightAdjustmentIncrement$6,
  Comfy_Load3D_LightIntensity: Comfy_Load3D_LightIntensity$6,
  Comfy_Load3D_LightIntensityMaximum: Comfy_Load3D_LightIntensityMaximum$6,
  Comfy_Load3D_LightIntensityMinimum: Comfy_Load3D_LightIntensityMinimum$6,
  Comfy_Load3D_ShowGrid: Comfy_Load3D_ShowGrid$6,
  Comfy_Load3D_ShowPreview: Comfy_Load3D_ShowPreview$6,
  Comfy_Locale: Comfy_Locale$6,
  Comfy_MaskEditor_BrushAdjustmentSpeed: Comfy_MaskEditor_BrushAdjustmentSpeed$6,
  Comfy_MaskEditor_UseDominantAxis: Comfy_MaskEditor_UseDominantAxis$6,
  Comfy_MaskEditor_UseNewEditor: Comfy_MaskEditor_UseNewEditor$6,
  Comfy_ModelLibrary_AutoLoadAll: Comfy_ModelLibrary_AutoLoadAll$6,
  Comfy_ModelLibrary_NameFormat: Comfy_ModelLibrary_NameFormat$6,
  Comfy_Node_AllowImageSizeDraw: Comfy_Node_AllowImageSizeDraw$6,
  Comfy_Node_AutoSnapLinkToSlot: Comfy_Node_AutoSnapLinkToSlot$6,
  Comfy_Node_BypassAllLinksOnDelete: Comfy_Node_BypassAllLinksOnDelete$6,
  Comfy_Node_DoubleClickTitleToEdit: Comfy_Node_DoubleClickTitleToEdit$6,
  Comfy_Node_MiddleClickRerouteNode: Comfy_Node_MiddleClickRerouteNode$6,
  Comfy_Node_Opacity: Comfy_Node_Opacity$6,
  Comfy_Node_ShowDeprecated: Comfy_Node_ShowDeprecated$6,
  Comfy_Node_ShowExperimental: Comfy_Node_ShowExperimental$6,
  Comfy_Node_SnapHighlightsNode: Comfy_Node_SnapHighlightsNode$6,
  Comfy_NodeBadge_NodeIdBadgeMode: Comfy_NodeBadge_NodeIdBadgeMode$6,
  Comfy_NodeBadge_NodeLifeCycleBadgeMode: Comfy_NodeBadge_NodeLifeCycleBadgeMode$6,
  Comfy_NodeBadge_NodeSourceBadgeMode: Comfy_NodeBadge_NodeSourceBadgeMode$6,
  Comfy_NodeSearchBoxImpl: Comfy_NodeSearchBoxImpl$6,
  Comfy_NodeSearchBoxImpl_NodePreview: Comfy_NodeSearchBoxImpl_NodePreview$6,
  Comfy_NodeSearchBoxImpl_ShowCategory: Comfy_NodeSearchBoxImpl_ShowCategory$6,
  Comfy_NodeSearchBoxImpl_ShowIdName: Comfy_NodeSearchBoxImpl_ShowIdName$6,
  Comfy_NodeSearchBoxImpl_ShowNodeFrequency: Comfy_NodeSearchBoxImpl_ShowNodeFrequency$6,
  Comfy_NodeSuggestions_number: Comfy_NodeSuggestions_number$6,
  Comfy_Pointer_ClickBufferTime: Comfy_Pointer_ClickBufferTime$6,
  Comfy_Pointer_ClickDrift: Comfy_Pointer_ClickDrift$6,
  Comfy_Pointer_DoubleClickTime: Comfy_Pointer_DoubleClickTime$6,
  Comfy_PreviewFormat: Comfy_PreviewFormat$6,
  Comfy_PromptFilename: Comfy_PromptFilename$6,
  Comfy_Queue_MaxHistoryItems: Comfy_Queue_MaxHistoryItems$6,
  Comfy_QueueButton_BatchCountLimit: Comfy_QueueButton_BatchCountLimit$6,
  Comfy_Sidebar_Location: Comfy_Sidebar_Location$6,
  Comfy_Sidebar_Size: Comfy_Sidebar_Size$6,
  Comfy_Sidebar_UnifiedWidth: Comfy_Sidebar_UnifiedWidth$6,
  Comfy_SnapToGrid_GridSize: Comfy_SnapToGrid_GridSize$6,
  Comfy_TextareaWidget_FontSize: Comfy_TextareaWidget_FontSize$6,
  Comfy_TextareaWidget_Spellcheck: Comfy_TextareaWidget_Spellcheck$6,
  Comfy_TreeExplorer_ItemPadding: Comfy_TreeExplorer_ItemPadding$6,
  Comfy_UseNewMenu: Comfy_UseNewMenu$6,
  Comfy_Validation_NodeDefs: Comfy_Validation_NodeDefs$6,
  Comfy_Validation_Workflows: Comfy_Validation_Workflows$6,
  Comfy_WidgetControlMode: Comfy_WidgetControlMode$6,
  Comfy_Window_UnloadConfirmation: Comfy_Window_UnloadConfirmation$6,
  Comfy_Workflow_AutoSave: Comfy_Workflow_AutoSave$6,
  Comfy_Workflow_AutoSaveDelay: Comfy_Workflow_AutoSaveDelay$6,
  Comfy_Workflow_ConfirmDelete: Comfy_Workflow_ConfirmDelete$6,
  Comfy_Workflow_Persist: Comfy_Workflow_Persist$6,
  Comfy_Workflow_ShowMissingModelsWarning: Comfy_Workflow_ShowMissingModelsWarning$6,
  Comfy_Workflow_ShowMissingNodesWarning: Comfy_Workflow_ShowMissingNodesWarning$6,
  Comfy_Workflow_SortNodeIdOnSave: Comfy_Workflow_SortNodeIdOnSave$6,
  Comfy_Workflow_WorkflowTabsPosition: Comfy_Workflow_WorkflowTabsPosition$6,
  LiteGraph_Canvas_LowQualityRenderingZoomThreshold: LiteGraph_Canvas_LowQualityRenderingZoomThreshold$6,
  LiteGraph_Canvas_MaximumFps: LiteGraph_Canvas_MaximumFps$6,
  LiteGraph_ContextMenu_Scaling: LiteGraph_ContextMenu_Scaling$6,
  LiteGraph_Node_DefaultPadding: LiteGraph_Node_DefaultPadding$6,
  LiteGraph_Node_TooltipDelay: LiteGraph_Node_TooltipDelay$6,
  LiteGraph_Pointer_TrackpadGestures: LiteGraph_Pointer_TrackpadGestures$6,
  LiteGraph_Reroute_SplineOffset: LiteGraph_Reroute_SplineOffset$6,
  pysssss_SnapToGrid: pysssss_SnapToGrid$6
};
const Comfy_BrowseTemplates$5 = {
  label: "Explorar plantillas"
};
const Comfy_Canvas_DeleteSelectedItems$5 = {
  label: "Eliminar elementos seleccionados"
};
const Comfy_Canvas_FitView$5 = {
  label: "Ajustar vista a los nodos seleccionados"
};
const Comfy_Canvas_ResetView$5 = {
  label: "Restablecer vista"
};
const Comfy_Canvas_Resize$5 = {
  label: "Redimensionar Nodos Seleccionados"
};
const Comfy_Canvas_ToggleLinkVisibility$5 = {
  label: "Alternar visibilidad de enlace en lienzo"
};
const Comfy_Canvas_ToggleLock$5 = {
  label: "Alternar bloqueo en lienzo"
};
const Comfy_Canvas_ToggleSelectedNodes_Bypass$5 = {
  label: "Omitir/No omitir nodos seleccionados"
};
const Comfy_Canvas_ToggleSelectedNodes_Collapse$5 = {
  label: "Colapsar/Expandir nodos seleccionados"
};
const Comfy_Canvas_ToggleSelectedNodes_Mute$5 = {
  label: "Silenciar/Activar sonido de nodos seleccionados"
};
const Comfy_Canvas_ToggleSelectedNodes_Pin$5 = {
  label: "Anclar/Desanclar nodos seleccionados"
};
const Comfy_Canvas_ToggleSelected_Pin$5 = {
  label: "Anclar/Desanclar elementos seleccionados"
};
const Comfy_Canvas_ZoomIn$5 = {
  label: "Acercar"
};
const Comfy_Canvas_ZoomOut$5 = {
  label: "Alejar"
};
const Comfy_ClearPendingTasks$5 = {
  label: "Borrar tareas pendientes"
};
const Comfy_ClearWorkflow$5 = {
  label: "Borrar flujo de trabajo"
};
const Comfy_ContactSupport$5 = {
  label: "Contactar soporte"
};
const Comfy_DuplicateWorkflow$5 = {
  label: "Duplicar flujo de trabajo actual"
};
const Comfy_ExportWorkflow$5 = {
  label: "Exportar flujo de trabajo"
};
const Comfy_ExportWorkflowAPI$5 = {
  label: "Exportar flujo de trabajo (formato API)"
};
const Comfy_Feedback$5 = {
  label: "Dar retroalimentación"
};
const Comfy_Graph_FitGroupToContents$5 = {
  label: "Ajustar grupo al contenido"
};
const Comfy_Graph_GroupSelectedNodes$5 = {
  label: "Agrupar nodos seleccionados"
};
const Comfy_GroupNode_ConvertSelectedNodesToGroupNode$5 = {
  label: "Convertir nodos seleccionados en nodo de grupo"
};
const Comfy_GroupNode_ManageGroupNodes$5 = {
  label: "Administrar nodos de grupo"
};
const Comfy_GroupNode_UngroupSelectedGroupNodes$5 = {
  label: "Desagrupar nodos de grupo seleccionados"
};
const Comfy_Help_AboutComfyUI$5 = {
  label: "Abrir Acerca de ComfyUI"
};
const Comfy_Help_OpenComfyOrgDiscord$5 = {
  label: "Abrir Comfy-Org Discord"
};
const Comfy_Help_OpenComfyUIDocs$5 = {
  label: "Abrir documentación de ComfyUI"
};
const Comfy_Help_OpenComfyUIForum$5 = {
  label: "Abrir foro de ComfyUI"
};
const Comfy_Help_OpenComfyUIIssues$5 = {
  label: "Abrir problemas de ComfyUI"
};
const Comfy_Interrupt$5 = {
  label: "Interrumpir"
};
const Comfy_LoadDefaultWorkflow$5 = {
  label: "Cargar flujo de trabajo predeterminado"
};
const Comfy_Manager_CustomNodesManager$5 = {
  label: "Administrador de nodos personalizados"
};
const Comfy_Manager_ToggleManagerProgressDialog$5 = {
  label: "Alternar diálogo de progreso del administrador"
};
const Comfy_NewBlankWorkflow$5 = {
  label: "Nuevo flujo de trabajo en blanco"
};
const Comfy_OpenClipspace$5 = {
  label: "Abrir espacio de clips"
};
const Comfy_OpenWorkflow$5 = {
  label: "Abrir Flujo de Trabajo"
};
const Comfy_QueuePrompt$5 = {
  label: "Prompt de Cola"
};
const Comfy_QueuePromptFront$5 = {
  label: "Prompt de Cola (Frente)"
};
const Comfy_QueueSelectedOutputNodes$5 = {
  label: "Encolar nodos de salida seleccionados"
};
const Comfy_Redo$5 = {
  label: "Rehacer"
};
const Comfy_RefreshNodeDefinitions$5 = {
  label: "Actualizar Definiciones de Nodo"
};
const Comfy_SaveWorkflow$5 = {
  label: "Guardar Flujo de Trabajo"
};
const Comfy_SaveWorkflowAs$5 = {
  label: "Guardar Flujo de Trabajo Como"
};
const Comfy_ShowSettingsDialog$5 = {
  label: "Mostrar Diálogo de Configuraciones"
};
const Comfy_ToggleTheme$5 = {
  label: "Cambiar Tema (Oscuro/Claro)"
};
const Comfy_Undo$5 = {
  label: "Deshacer"
};
const Comfy_User_OpenSignInDialog$5 = {
  label: "Abrir diálogo de inicio de sesión"
};
const Comfy_User_SignOut$5 = {
  label: "Cerrar sesión"
};
const Workspace_CloseWorkflow$5 = {
  label: "Cerrar Flujo de Trabajo Actual"
};
const Workspace_NextOpenedWorkflow$5 = {
  label: "Siguiente Flujo de Trabajo Abierto"
};
const Workspace_PreviousOpenedWorkflow$5 = {
  label: "Flujo de Trabajo Abierto Anterior"
};
const Workspace_SearchBox_Toggle$5 = {
  label: "Alternar Caja de Búsqueda"
};
const Workspace_ToggleBottomPanel$5 = {
  label: "Alternar Panel Inferior"
};
const Workspace_ToggleFocusMode$5 = {
  label: "Alternar Modo de Enfoque"
};
const Workspace_ToggleSidebarTab_queue$5 = {
  label: "Alternar Barra Lateral de Cola",
  tooltip: "Cola"
};
const Workspace_ToggleSidebarTab_workflows$5 = {
  label: "Alternar Barra Lateral de Flujos de Trabajo",
  tooltip: "Flujos de Trabajo"
};
const esCommands = {
  "Comfy-Desktop_CheckForUpdates": {
    label: "Buscar actualizaciones"
  },
  "Comfy-Desktop_Folders_OpenCustomNodesFolder": {
    label: "Abrir carpeta de nodos personalizados"
  },
  "Comfy-Desktop_Folders_OpenInputsFolder": {
    label: "Abrir carpeta de entradas"
  },
  "Comfy-Desktop_Folders_OpenLogsFolder": {
    label: "Abrir carpeta de registros"
  },
  "Comfy-Desktop_Folders_OpenModelConfig": {
    label: "Abrir extra_model_paths.yaml"
  },
  "Comfy-Desktop_Folders_OpenModelsFolder": {
    label: "Abrir carpeta de modelos"
  },
  "Comfy-Desktop_Folders_OpenOutputsFolder": {
    label: "Abrir carpeta de salidas"
  },
  "Comfy-Desktop_OpenDevTools": {
    label: "Abrir herramientas de desarrollo"
  },
  "Comfy-Desktop_OpenUserGuide": {
    label: "Guía de usuario de escritorio"
  },
  "Comfy-Desktop_Quit": {
    label: "Salir"
  },
  "Comfy-Desktop_Reinstall": {
    label: "Reinstalar"
  },
  "Comfy-Desktop_Restart": {
    label: "Reiniciar"
  },
  Comfy_BrowseTemplates: Comfy_BrowseTemplates$5,
  Comfy_Canvas_DeleteSelectedItems: Comfy_Canvas_DeleteSelectedItems$5,
  Comfy_Canvas_FitView: Comfy_Canvas_FitView$5,
  Comfy_Canvas_ResetView: Comfy_Canvas_ResetView$5,
  Comfy_Canvas_Resize: Comfy_Canvas_Resize$5,
  Comfy_Canvas_ToggleLinkVisibility: Comfy_Canvas_ToggleLinkVisibility$5,
  Comfy_Canvas_ToggleLock: Comfy_Canvas_ToggleLock$5,
  Comfy_Canvas_ToggleSelectedNodes_Bypass: Comfy_Canvas_ToggleSelectedNodes_Bypass$5,
  Comfy_Canvas_ToggleSelectedNodes_Collapse: Comfy_Canvas_ToggleSelectedNodes_Collapse$5,
  Comfy_Canvas_ToggleSelectedNodes_Mute: Comfy_Canvas_ToggleSelectedNodes_Mute$5,
  Comfy_Canvas_ToggleSelectedNodes_Pin: Comfy_Canvas_ToggleSelectedNodes_Pin$5,
  Comfy_Canvas_ToggleSelected_Pin: Comfy_Canvas_ToggleSelected_Pin$5,
  Comfy_Canvas_ZoomIn: Comfy_Canvas_ZoomIn$5,
  Comfy_Canvas_ZoomOut: Comfy_Canvas_ZoomOut$5,
  Comfy_ClearPendingTasks: Comfy_ClearPendingTasks$5,
  Comfy_ClearWorkflow: Comfy_ClearWorkflow$5,
  Comfy_ContactSupport: Comfy_ContactSupport$5,
  Comfy_DuplicateWorkflow: Comfy_DuplicateWorkflow$5,
  Comfy_ExportWorkflow: Comfy_ExportWorkflow$5,
  Comfy_ExportWorkflowAPI: Comfy_ExportWorkflowAPI$5,
  Comfy_Feedback: Comfy_Feedback$5,
  Comfy_Graph_FitGroupToContents: Comfy_Graph_FitGroupToContents$5,
  Comfy_Graph_GroupSelectedNodes: Comfy_Graph_GroupSelectedNodes$5,
  Comfy_GroupNode_ConvertSelectedNodesToGroupNode: Comfy_GroupNode_ConvertSelectedNodesToGroupNode$5,
  Comfy_GroupNode_ManageGroupNodes: Comfy_GroupNode_ManageGroupNodes$5,
  Comfy_GroupNode_UngroupSelectedGroupNodes: Comfy_GroupNode_UngroupSelectedGroupNodes$5,
  Comfy_Help_AboutComfyUI: Comfy_Help_AboutComfyUI$5,
  Comfy_Help_OpenComfyOrgDiscord: Comfy_Help_OpenComfyOrgDiscord$5,
  Comfy_Help_OpenComfyUIDocs: Comfy_Help_OpenComfyUIDocs$5,
  Comfy_Help_OpenComfyUIForum: Comfy_Help_OpenComfyUIForum$5,
  Comfy_Help_OpenComfyUIIssues: Comfy_Help_OpenComfyUIIssues$5,
  Comfy_Interrupt: Comfy_Interrupt$5,
  Comfy_LoadDefaultWorkflow: Comfy_LoadDefaultWorkflow$5,
  Comfy_Manager_CustomNodesManager: Comfy_Manager_CustomNodesManager$5,
  Comfy_Manager_ToggleManagerProgressDialog: Comfy_Manager_ToggleManagerProgressDialog$5,
  Comfy_NewBlankWorkflow: Comfy_NewBlankWorkflow$5,
  Comfy_OpenClipspace: Comfy_OpenClipspace$5,
  Comfy_OpenWorkflow: Comfy_OpenWorkflow$5,
  Comfy_QueuePrompt: Comfy_QueuePrompt$5,
  Comfy_QueuePromptFront: Comfy_QueuePromptFront$5,
  Comfy_QueueSelectedOutputNodes: Comfy_QueueSelectedOutputNodes$5,
  Comfy_Redo: Comfy_Redo$5,
  Comfy_RefreshNodeDefinitions: Comfy_RefreshNodeDefinitions$5,
  Comfy_SaveWorkflow: Comfy_SaveWorkflow$5,
  Comfy_SaveWorkflowAs: Comfy_SaveWorkflowAs$5,
  Comfy_ShowSettingsDialog: Comfy_ShowSettingsDialog$5,
  Comfy_ToggleTheme: Comfy_ToggleTheme$5,
  Comfy_Undo: Comfy_Undo$5,
  Comfy_User_OpenSignInDialog: Comfy_User_OpenSignInDialog$5,
  Comfy_User_SignOut: Comfy_User_SignOut$5,
  Workspace_CloseWorkflow: Workspace_CloseWorkflow$5,
  Workspace_NextOpenedWorkflow: Workspace_NextOpenedWorkflow$5,
  Workspace_PreviousOpenedWorkflow: Workspace_PreviousOpenedWorkflow$5,
  Workspace_SearchBox_Toggle: Workspace_SearchBox_Toggle$5,
  Workspace_ToggleBottomPanel: Workspace_ToggleBottomPanel$5,
  "Workspace_ToggleBottomPanelTab_command-terminal": {
    label: "Alternar Panel Inferior de Terminal"
  },
  "Workspace_ToggleBottomPanelTab_logs-terminal": {
    label: "Alternar Panel Inferior de Registros"
  },
  Workspace_ToggleFocusMode: Workspace_ToggleFocusMode$5,
  "Workspace_ToggleSidebarTab_model-library": {
    label: "Alternar Barra Lateral de Biblioteca de Modelos",
    tooltip: "Biblioteca de Modelos"
  },
  "Workspace_ToggleSidebarTab_node-library": {
    label: "Alternar Barra Lateral de Biblioteca de Nodos",
    tooltip: "Biblioteca de Nodos"
  },
  Workspace_ToggleSidebarTab_queue: Workspace_ToggleSidebarTab_queue$5,
  Workspace_ToggleSidebarTab_workflows: Workspace_ToggleSidebarTab_workflows$5
};
const apiNodesCostBreakdown$5 = {
  costPerRun: "Costo por ejecución",
  title: "Nodo(s) de API",
  totalCost: "Costo total"
};
const apiNodesNews$5 = {
  introducing: "Presentamos",
  steps: {
    step1: {
      subtitle: "Configuración > Usuario > Iniciar sesión",
      title: "Inicia sesión/Crea una cuenta:"
    },
    step2: {
      subtitle: "Configuración > Créditos > Comprar créditos",
      title: "Compra créditos:"
    },
    step3: {
      title: "Ubica los nuevos nodos API en la sección 'API Node' y agrégalos al lienzo"
    },
    step4: {
      title: "¡Ejecuta!"
    }
  },
  subtitle: "Todos los modelos externos ahora disponibles en ComfyUI"
};
const apiNodesSignInDialog$5 = {
  message: "Este flujo de trabajo contiene nodos de API, que requieren que inicies sesión en tu cuenta para poder ejecutar.",
  title: "Se requiere iniciar sesión para usar los nodos de API"
};
const auth$5 = {
  apiKey: {
    cleared: "Clave API eliminada",
    clearedDetail: "Tu clave API se ha eliminado correctamente",
    description: "Usa tu clave API de Comfy para habilitar los nodos de API",
    error: "Clave API no válida",
    generateKey: "Consíguela aquí",
    helpText: "¿Necesitas una clave API?",
    invalid: "Clave API no válida",
    invalidDetail: "Por favor, introduce una clave API válida",
    label: "Clave API",
    placeholder: "Introduce tu clave API",
    storageFailed: "No se pudo guardar la clave API",
    storageFailedDetail: "Por favor, inténtalo de nuevo.",
    stored: "Clave API guardada",
    storedDetail: "Tu clave API se ha guardado correctamente",
    title: "Clave API",
    whitelistInfo: "Acerca de los sitios no incluidos en la lista blanca"
  },
  login: {
    andText: "y",
    confirmPasswordLabel: "Confirmar contraseña",
    confirmPasswordPlaceholder: "Ingresa la misma contraseña nuevamente",
    emailLabel: "Correo electrónico",
    emailPlaceholder: "Ingresa tu correo electrónico",
    failed: "Inicio de sesión fallido",
    forgotPassword: "¿Olvidaste tu contraseña?",
    forgotPasswordError: "No se pudo enviar el correo electrónico para restablecer la contraseña",
    insecureContextWarning: "Esta conexión no es segura (HTTP): tus credenciales pueden ser interceptadas por atacantes si continúas con el inicio de sesión.",
    loginButton: "Iniciar sesión",
    loginWithGithub: "Iniciar sesión con Github",
    loginWithGoogle: "Iniciar sesión con Google",
    newUser: "¿Eres nuevo aquí?",
    noAssociatedUser: "No hay ningún usuario de Comfy asociado con la clave API proporcionada",
    orContinueWith: "O continuar con",
    passwordLabel: "Contraseña",
    passwordPlaceholder: "Ingresa tu contraseña",
    passwordResetSent: "Correo electrónico de restablecimiento de contraseña enviado",
    passwordResetSentDetail: "Por favor, revisa tu correo electrónico para encontrar un enlace para restablecer tu contraseña.",
    privacyLink: "Política de privacidad",
    questionsContactPrefix: "¿Preguntas? Contáctanos en",
    signInOrSignUp: "Iniciar sesión / Registrarse",
    signUp: "Regístrate",
    success: "Inicio de sesión exitoso",
    termsLink: "Términos de uso",
    termsText: 'Al hacer clic en "Siguiente" o "Registrarse", aceptas nuestros',
    title: "Inicia sesión en tu cuenta",
    useApiKey: "Clave API de Comfy",
    userAvatar: "Avatar de usuario"
  },
  passwordUpdate: {
    success: "Contraseña actualizada",
    successDetail: "Tu contraseña se ha actualizado correctamente"
  },
  signOut: {
    signOut: "Cerrar sesión",
    success: "Sesión cerrada correctamente",
    successDetail: "Has cerrado sesión en tu cuenta."
  },
  signup: {
    alreadyHaveAccount: "¿Ya tienes una cuenta?",
    emailLabel: "Correo electrónico",
    emailPlaceholder: "Ingresa tu correo electrónico",
    passwordLabel: "Contraseña",
    passwordPlaceholder: "Ingresa una nueva contraseña",
    personalDataConsentLabel: "Acepto el tratamiento de mis datos personales.",
    regionRestrictionChina: "De acuerdo con los requisitos regulatorios locales, nuestros servicios no están disponibles actualmente para usuarios ubicados en China continental.",
    signIn: "Iniciar sesión",
    signUpButton: "Registrarse",
    signUpWithGithub: "Registrarse con Github",
    signUpWithGoogle: "Registrarse con Google",
    title: "Crea una cuenta"
  }
};
const clipboard$5 = {
  errorMessage: "Error al copiar al portapapeles",
  errorNotSupported: "API del portapapeles no soportada en su navegador",
  successMessage: "Copiado al portapapeles"
};
const color$5 = {
  black: "Negro",
  blue: "Azul",
  brown: "Marrón",
  custom: "Personalizado",
  cyan: "Cian",
  "default": "Predeterminado",
  green: "Verde",
  noColor: "Sin Color",
  pale_blue: "Azul Pálido",
  pink: "Rosa",
  purple: "Morado",
  red: "Rojo",
  yellow: "Amarillo"
};
const contextMenu$5 = {
  "Add Group": "Agregar Grupo",
  "Add Group For Selected Nodes": "Agregar Grupo para Nodos Seleccionados",
  "Add Node": "Agregar Nodo",
  Bypass: "Omitir",
  Clone: "Clonar",
  Collapse: "Colapsar",
  Colors: "Colores",
  "Convert to Group Node": "Convertir en Nodo de Grupo",
  "Copy (Clipspace)": "Copiar (Espacio de Clip)",
  Expand: "Expandir",
  Inputs: "Entradas",
  Manage: "Administrar",
  "Manage Group Nodes": "Administrar Nodos de Grupo",
  Mode: "Modo",
  "Node Templates": "Plantillas de Nodos",
  Outputs: "Salidas",
  Pin: "Anclar",
  Properties: "Propiedades",
  "Properties Panel": "Panel de Propiedades",
  Remove: "Eliminar",
  Resize: "Redimensionar",
  "Save Selected as Template": "Guardar Seleccionado como Plantilla",
  Search: "Buscar",
  Shapes: "Formas",
  Title: "Título",
  Unpin: "Desanclar"
};
const credits$5 = {
  apiPricing: "Precios de la API",
  credits: "Créditos",
  faqs: "Preguntas frecuentes",
  invoiceHistory: "Historial de facturas",
  lastUpdated: "Última actualización",
  messageSupport: "Contactar soporte",
  purchaseCredits: "Comprar créditos",
  topUp: {
    buyNow: "Comprar ahora",
    insufficientMessage: "No tienes suficientes créditos para ejecutar este flujo de trabajo.",
    insufficientTitle: "Créditos insuficientes",
    maxAmount: "(Máx. $1,000 USD)",
    quickPurchase: "Compra rápida",
    seeDetails: "Ver detalles",
    topUp: "Recargar"
  },
  yourCreditBalance: "Tu saldo de créditos"
};
const dataTypes$5 = {
  "*": "*",
  AUDIO: "AUDIO",
  BOOLEAN: "BOOLEANO",
  CAMERA_CONTROL: "CONTROL DE CÁMARA",
  CLIP: "CLIP",
  CLIP_VISION: "CLIP_VISION",
  CLIP_VISION_OUTPUT: "SALIDA_CLIP_VISION",
  COMBO: "COMBO",
  CONDITIONING: "ACONDICIONAMIENTO",
  CONTROL_NET: "RED_DE_CONTROL",
  FLOAT: "FLOTANTE",
  FLOATS: "FLOTANTES",
  GLIGEN: "GLIGEN",
  GUIDER: "GUÍA",
  HOOKS: "GANCHOS",
  HOOK_KEYFRAMES: "GANCHO_FOTOGRAMAS_CLAVE",
  IMAGE: "IMAGEN",
  INT: "ENTERO",
  LATENT: "LATENTE",
  LATENT_OPERATION: "OPERACIÓN_LATENTE",
  LOAD3D_CAMERA: "CARGAR CÁMARA 3D",
  LOAD_3D: "CARGAR_3D",
  LOAD_3D_ANIMATION: "CARGAR_ANIMACIÓN_3D",
  LUMA_CONCEPTS: "CONCEPTOS LUMA",
  LUMA_REF: "REFERENCIA LUMA",
  MASK: "MASK",
  MESH: "MALLA",
  MODEL: "MODELO",
  NOISE: "RUIDO",
  PHOTOMAKER: "PHOTOMAKER",
  PIXVERSE_TEMPLATE: "PLANTILLA PIXVERSE",
  RECRAFT_COLOR: "COLOR RECRAFT",
  RECRAFT_CONTROLS: "CONTROLES RECRAFT",
  RECRAFT_V3_STYLE: "ESTILO RECRAFT V3",
  SAMPLER: "MUESTREADOR",
  SIGMAS: "SIGMAS",
  STRING: "CADENA",
  STYLE_MODEL: "MODELO_DE_ESTILO",
  SVG: "SVG",
  TIMESTEPS_RANGE: "RANGO_DE_PASOS_DE_TIEMPO",
  UPSCALE_MODEL: "MODELO_DE_ESCALADO",
  VAE: "VAE",
  VIDEO: "VÍDEO",
  VOXEL: "VOXEL",
  WEBCAM: "WEBCAM"
};
const desktopMenu$5 = {
  confirmQuit: "Hay flujos de trabajo abiertos sin guardar; se perderán los cambios no guardados. ¿Ignorar esto y salir?",
  confirmReinstall: "Esto borrará su archivo extra_models_config.yaml,\ny comenzará la instalación nuevamente.\n\n¿Estás seguro?",
  quit: "Salir",
  reinstall: "Reinstalar"
};
const desktopUpdate$5 = {
  description: "ComfyUI Desktop está instalando nuevas dependencias. Esto puede tardar unos minutos.",
  errorCheckingUpdate: "Error al buscar actualizaciones",
  errorInstallingUpdate: "Error al instalar la actualización",
  noUpdateFound: "No se encontró ninguna actualización",
  terminalDefaultMessage: "Cualquier salida de consola de la actualización se mostrará aquí.",
  title: "Actualizando ComfyUI Desktop",
  updateAvailableMessage: "Hay una actualización disponible. ¿Quieres reiniciar y actualizar ahora?",
  updateFoundTitle: "Actualización encontrada (v{version})"
};
const downloadGit$5 = {
  gitWebsite: "Descargar git",
  instructions: "Por favor, descarga e instala la última versión para tu sistema operativo. El botón Descargar git de abajo abre la página de descargas de git-scm.com.",
  message: "No se puede localizar git. Se requiere una copia funcional de git para el funcionamiento normal.",
  skip: "Saltar",
  title: "Descargar git",
  warning: "Si estás seguro de que no necesitas instalar git, o ha habido un error, puedes hacer clic en Saltar para eludir esta comprobación. Intentar ejecutar ComfyUI sin una copia funcional de git no está actualmente soportado."
};
const electronFileDownload$5 = {
  cancel: "Cancelar descarga",
  cancelled: "Cancelado",
  inProgress: "En progreso",
  pause: "Pausar descarga",
  paused: "Pausado",
  resume: "Reanudar descarga"
};
const errorDialog$5 = {
  defaultTitle: "Ocurrió un error",
  extensionFileHint: "Esto puede deberse al siguiente script",
  loadWorkflowTitle: "La carga se interrumpió debido a un error al recargar los datos del flujo de trabajo",
  noStackTrace: "No hay seguimiento de pila disponible",
  promptExecutionError: "La ejecución del prompt falló"
};
const g$5 = {
  about: "Acerca de",
  add: "Añadir",
  all: "Todo",
  amount: "Cantidad",
  apply: "Aplicar",
  back: "Atrás",
  cancel: "Cancelar",
  capture: "captura",
  category: "Categoría",
  choose_file_to_upload: "elige archivo para subir",
  close: "Cerrar",
  color: "Color",
  comingSoon: "Próximamente",
  command: "Comando",
  community: "Comunidad",
  completed: "Completado",
  confirm: "Confirmar",
  confirmed: "Confirmado",
  "continue": "Continuar",
  control_after_generate: "control después de generar",
  control_before_generate: "control antes de generar",
  copyToClipboard: "Copiar al portapapeles",
  currentUser: "Usuario actual",
  customize: "Personalizar",
  customizeFolder: "Personalizar carpeta",
  "delete": "Eliminar",
  deprecated: "DEPR",
  description: "Descripción",
  devices: "Dispositivos",
  disableAll: "Deshabilitar todo",
  disabling: "Deshabilitando",
  download: "Descargar",
  empty: "Vacío",
  enableAll: "Habilitar todo",
  enabled: "Habilitado",
  enabling: "Habilitando",
  error: "Error",
  experimental: "BETA",
  "export": "Exportar",
  extensionName: "Nombre de la extensión",
  feedback: "Retroalimentación",
  filter: "Filtrar",
  findIssues: "Encontrar problemas",
  firstTimeUIMessage: 'Esta es la primera vez que usas la nueva interfaz. Elige "Menú > Usar nuevo menú > Desactivado" para restaurar la antigua interfaz.',
  goToNode: "Ir al nodo",
  icon: "Icono",
  imageFailedToLoad: "Falló la carga de la imagen",
  "import": "Importar",
  inProgress: "En progreso",
  insert: "Insertar",
  install: "Instalar",
  installed: "Instalado",
  installing: "Instalando",
  interrupted: "Interrumpido",
  keybinding: "Combinación de teclas",
  learnMore: "Aprende más",
  loadAllFolders: "Cargar todas las carpetas",
  loadWorkflow: "Cargar flujo de trabajo",
  loading: "Cargando",
  login: "Iniciar sesión",
  logs: "Registros",
  migrate: "Migrar",
  missing: "Faltante",
  name: "Nombre",
  newFolder: "Nueva carpeta",
  next: "Siguiente",
  no: "No",
  noResultsFound: "No se encontraron resultados",
  noTasksFound: "No se encontraron tareas",
  noTasksFoundMessage: "No hay tareas en la cola.",
  noWorkflowsFound: "No se encontraron flujos de trabajo.",
  nodes: "Nodos",
  ok: "OK",
  openNewIssue: "Abrir nuevo problema",
  overwrite: "Sobrescribir",
  reconnected: "Reconectado",
  reconnecting: "Reconectando",
  refresh: "Actualizar",
  reloadToApplyChanges: "Recargar para aplicar cambios",
  rename: "Renombrar",
  reportIssue: "Enviar informe",
  reportIssueTooltip: "Enviar el informe de error a Comfy Org",
  reportSent: "Informe enviado",
  reset: "Reiniciar",
  resetAll: "Restablecer todo",
  resetAllKeybindingsTooltip: "Restablecer todas las teclas de acceso rápido a la configuración predeterminada",
  restart: "Reiniciar",
  resultsCount: "Encontrados {count} resultados",
  save: "Guardar",
  saving: "Guardando",
  searchExtensions: "Buscar extensiones",
  searchFailedMessage: "No pudimos encontrar ninguna configuración que coincida con tu búsqueda. Intenta ajustar tus términos de búsqueda.",
  searchKeybindings: "Buscar combinaciones de teclas",
  searchModels: "Buscar modelos",
  searchNodes: "Buscar nodos",
  searchSettings: "Buscar configuraciones",
  searchWorkflows: "Buscar flujos de trabajo",
  settings: "Configuraciones",
  showReport: "Mostrar informe",
  sort: "Ordenar",
  source: "Fuente",
  status: "Estado",
  success: "Éxito",
  systemInfo: "Información del sistema",
  terminal: "Terminal",
  title: "Título",
  unknownError: "Error desconocido",
  update: "Actualizar",
  updateAvailable: "Actualización Disponible",
  updated: "Actualizado",
  updating: "Actualizando",
  upload: "Subir",
  user: "Usuario",
  videoFailedToLoad: "Falló la carga del video",
  workflow: "Flujo de trabajo"
};
const graphCanvasMenu$5 = {
  fitView: "Ajustar vista",
  panMode: "Modo de desplazamiento",
  resetView: "Restablecer vista",
  selectMode: "Modo de selección",
  toggleLinkVisibility: "Alternar visibilidad de enlace",
  zoomIn: "Acercar",
  zoomOut: "Alejar"
};
const groupNode$5 = {
  create: "Crear nodo de grupo",
  enterName: "Introduzca el nombre"
};
const icon$5 = {
  bookmark: "Marcador",
  box: "Caja",
  briefcase: "Maletín",
  "exclamation-triangle": "Advertencia",
  file: "Archivo",
  folder: "Carpeta",
  heart: "Corazón",
  inbox: "Bandeja de entrada",
  star: "Estrella"
};
const install$5 = {
  appDataLocationTooltip: "Directorio de datos de la aplicación ComfyUI. Almacena:\n- Registros\n- Configuraciones del servidor",
  appPathLocationTooltip: "Directorio de activos de la aplicación ComfyUI. Almacena el código y los activos de ComfyUI",
  cannotWrite: "No se puede escribir en la ruta seleccionada",
  chooseInstallationLocation: "Elegir Ubicación de Instalación",
  customNodes: "Nodos Personalizados",
  customNodesDescription: "Reinstala los nodos personalizados de las instalaciones existentes de ComfyUI.",
  desktopAppSettings: "Configuraciones de la Aplicación de Escritorio",
  desktopAppSettingsDescription: "Configura cómo se comporta ComfyUI en tu escritorio. Puedes cambiar estas configuraciones más tarde.",
  desktopSettings: "Configuraciones de Escritorio",
  failedToSelectDirectory: "Falló al seleccionar el directorio",
  gpu: "GPU",
  gpuSelection: {
    cpuMode: "Modo CPU",
    cpuModeDescription: "El modo CPU está destinado para desarrolladores y casos extremos raros solamente.",
    cpuModeDescription2: "Si no estás absolutamente seguro de que necesitas esto, por favor ignora esta casilla y selecciona tu GPU arriba.",
    customComfyNeedsPython: "ComfyUI no funcionará hasta que python esté configurado",
    customInstallRequirements: "Instalar todos los requisitos y dependencias (ej. torch personalizado)",
    customManualVenv: "Configurar manualmente el entorno virtual de python",
    customMayNotWork: "Esto no está soportado en absoluto, y simplemente puede que no funcione",
    customSkipsPython: "Esta opción omite la configuración normal de python.",
    enableCpuMode: "Habilitar Modo CPU",
    mpsDescription: "Los Shaders de Rendimiento de Metal de Apple son soportados usando pytorch nightly.",
    nvidiaDescription: "Los dispositivos NVIDIA son directamente soportados usando compilaciones de pytorch CUDA.",
    selectGpu: "Seleccionar GPU",
    selectGpuDescription: "Selecciona el tipo de GPU que tienes"
  },
  helpImprove: "Por favor ayuda a mejorar ComfyUI",
  installLocation: "Ubicación de Instalación",
  installLocationDescription: "Selecciona el directorio para los datos de usuario de ComfyUI. Un entorno de python será instalado en la ubicación seleccionada.",
  installLocationTooltip: "Directorio de datos de usuario de ComfyUI. Almacena:\n- Entorno Python\n- Modelos\n- Nodos personalizados\n",
  insufficientFreeSpace: "Espacio insuficiente - espacio libre mínimo",
  isOneDrive: "OneDrive no es compatible. Por favor instala ComfyUI en otra ubicación.",
  manualConfiguration: {
    createVenv: "Necesitarás crear un entorno virtual en el siguiente directorio",
    requirements: "Requisitos",
    restartWhenFinished: "Cuando hayas terminado de configurar el entorno virtual, por favor reinicia ComfyUI.",
    title: "Configuración Manual",
    virtualEnvironmentPath: "Ruta del entorno virtual"
  },
  metricsDisabled: "Métricas Deshabilitadas",
  metricsEnabled: "Métricas Habilitadas",
  migrateFromExistingInstallation: "Migrar desde una Instalación Existente",
  migration: "Migración",
  migrationOptional: "La migración es opcional. Si no tienes una instalación existente, puedes saltarte este paso.",
  migrationSourcePathDescription: "Si tienes una instalación existente de ComfyUI, podemos copiar/enlazar tus archivos de usuario existentes y modelos a la nueva instalación. Tu instalación existente de ComfyUI no será afectada.",
  moreInfo: "Para más información, por favor lee nuestra",
  nonDefaultDrive: "Por favor instala ComfyUI en tu unidad de sistema (ej. C:\\). Las unidades con diferentes sistemas de archivos pueden causar problemas impredecibles. Los modelos y otros archivos pueden ser almacenados en otras unidades después de la instalación.",
  parentMissing: "La ruta no existe - crea el directorio contenedor primero",
  pathExists: "El directorio ya existe - por favor asegúrate de haber respaldado todos los datos",
  pathValidationFailed: "Falló la validación de la ruta",
  privacyPolicy: "política de privacidad",
  selectItemsToMigrate: "Selecciona los Elementos a Migrar",
  settings: {
    allowMetrics: "Métricas de Uso",
    allowMetricsDescription: "Ayuda a mejorar ComfyUI enviando métricas de uso anónimas. No se recogerá ninguna información personal o contenido de flujo de trabajo.",
    autoUpdate: "Actualizaciones Automáticas",
    autoUpdateDescription: "Descarga automáticamente las actualizaciones cuando estén disponibles. Se te notificará antes de que las actualizaciones sean instaladas.",
    checkingMirrors: "Comprobando el acceso a la red a los espejos de python...",
    dataCollectionDialog: {
      collect: {
        errorReports: "Mensaje de error y rastreo de pila",
        systemInfo: "Hardware, tipo de SO y versión de la aplicación",
        userJourneyEvents: "Eventos de trayectoria del usuario"
      },
      doNotCollect: {
        customNodeConfigurations: "Configuraciones de nodo personalizadas",
        fileSystemInformation: "Información del sistema de archivos",
        personalInformation: "Información personal",
        workflowContents: "Contenidos de flujo de trabajo"
      },
      title: "Acerca de la Recolección de Datos",
      viewFullPolicy: "Ver política completa",
      whatWeCollect: "Lo que recogemos:",
      whatWeDoNotCollect: "Lo que no recogemos:"
    },
    errorUpdatingConsent: "Error Actualizando Consentimiento",
    errorUpdatingConsentDetail: "Falló al actualizar la configuración de consentimiento de métricas",
    learnMoreAboutData: "Aprende más sobre la recolección de datos",
    mirrorSettings: "Configuraciones de Espejo",
    mirrorsReachable: "El acceso a la red a los espejos de python es bueno",
    mirrorsUnreachable: "El acceso a la red a algunos espejos de python es malo",
    pypiMirrorPlaceholder: "Ingresa la URL del espejo de PyPI",
    pythonMirrorPlaceholder: "Ingresa la URL del espejo de Python"
  },
  systemLocations: "Ubicaciones del Sistema",
  unhandledError: "Error desconocido",
  updateConsent: "Anteriormente optaste por reportar fallos. Ahora estamos rastreando métricas basadas en eventos para ayudar a identificar errores y mejorar la aplicación. No se recoge ninguna información personal identificable."
};
const issueReport$5 = {
  contactFollowUp: "Contáctame para seguimiento",
  contactSupportDescription: "Por favor, complete el siguiente formulario con su reporte",
  contactSupportTitle: "Contactar Soporte",
  describeTheProblem: "Describa el problema",
  email: "Correo electrónico",
  feedbackTitle: "Ayúdanos a mejorar ComfyUI proporcionando comentarios",
  helpFix: "Ayuda a Solucionar Esto",
  helpTypes: {
    billingPayments: "Facturación / Pagos",
    bugReport: "Reporte de error",
    giveFeedback: "Enviar comentarios",
    loginAccessIssues: "Problemas de inicio de sesión / acceso",
    somethingElse: "Otro"
  },
  notifyResolve: "Notifícame cuando se resuelva",
  provideAdditionalDetails: "Proporciona detalles adicionales (opcional)",
  provideEmail: "Danos tu correo electrónico (opcional)",
  rating: "Calificación",
  selectIssue: "Seleccione el problema",
  stackTrace: "Rastreo de Pila",
  submitErrorReport: "Enviar Reporte de Error (Opcional)",
  systemStats: "Estadísticas del Sistema",
  validation: {
    invalidEmail: "Por favor ingresa una dirección de correo electrónico válida",
    maxLength: "Mensaje demasiado largo",
    selectIssueType: "Por favor, seleccione un tipo de problema"
  },
  whatCanWeInclude: "Especifique qué incluir en el reporte",
  whatDoYouNeedHelpWith: "¿Con qué necesita ayuda?"
};
const load3d$5 = {
  applyingTexture: "Aplicando textura...",
  backgroundColor: "Color de fondo",
  camera: "Cámara",
  clearRecording: "Borrar grabación",
  edgeThreshold: "Umbral de borde",
  "export": "Exportar",
  exportModel: "Exportar modelo",
  exportRecording: "Exportar grabación",
  exportingModel: "Exportando modelo...",
  fov: "FOV",
  light: "Luz",
  lightIntensity: "Intensidad de luz",
  loadingModel: "Cargando modelo 3D...",
  materialMode: "Modo de material",
  materialModes: {
    depth: "Profundidad",
    lineart: "Dibujo lineal",
    normal: "Normal",
    original: "Original",
    wireframe: "Malla"
  },
  model: "Modelo",
  previewOutput: "Vista previa de salida",
  removeBackgroundImage: "Eliminar imagen de fondo",
  resizeNodeMatchOutput: "Redimensionar nodo para coincidir con la salida",
  scene: "Escena",
  showGrid: "Mostrar cuadrícula",
  startRecording: "Iniciar grabación",
  stopRecording: "Detener grabación",
  switchCamera: "Cambiar cámara",
  switchingMaterialMode: "Cambiando modo de material...",
  upDirection: "Dirección hacia arriba",
  uploadBackgroundImage: "Subir imagen de fondo",
  uploadTexture: "Subir textura"
};
const maintenance$5 = {
  None: "Ninguno",
  OK: "OK",
  Skipped: "Omitido",
  allOk: "No se detectaron problemas.",
  confirmTitle: "¿Estás seguro?",
  consoleLogs: "Registros de la consola",
  detected: "Detectado",
  error: {
    cannotContinue: "No se puede continuar - quedan errores",
    defaultDescription: "Ocurrió un error mientras se ejecutaba una tarea de mantenimiento.",
    taskFailed: "La tarea falló al ejecutarse.",
    toastTitle: "Error de tarea"
  },
  refreshing: "Actualizando",
  showManual: "Mostrar tareas de mantenimiento",
  status: "Estado",
  terminalDefaultMessage: "Cuando ejecutes un comando de solución de problemas, cualquier salida se mostrará aquí.",
  title: "Mantenimiento"
};
const manager$5 = {
  changingVersion: "Cambiando versión de {from} a {to}",
  createdBy: "Creado Por",
  dependencies: "Dependencias",
  discoverCommunityContent: "Descubre paquetes de nodos, extensiones y más creados por la comunidad...",
  downloads: "Descargas",
  errorConnecting: "Error al conectar con el Registro de Nodos Comfy.",
  failed: "Falló ({count})",
  filter: {
    disabled: "Deshabilitado",
    enabled: "Habilitado",
    nodePack: "Paquete de Nodos"
  },
  inWorkflow: "En Flujo de Trabajo",
  infoPanelEmpty: "Haz clic en un elemento para ver la información",
  installSelected: "Instalar Seleccionado",
  installationQueue: "Cola de Instalación",
  lastUpdated: "Última Actualización",
  latestVersion: "Última",
  license: "Licencia",
  loadingVersions: "Cargando versiones...",
  nightlyVersion: "Nocturna",
  noDescription: "No hay descripción disponible",
  noNodesFound: "No se encontraron nodos",
  noNodesFoundDescription: "Los nodos del paquete no se pudieron analizar, o el paquete es solo una extensión de frontend y no tiene ningún nodo.",
  noResultsFound: "No se encontraron resultados que coincidan con tu búsqueda.",
  nodePack: "Paquete de Nodos",
  packsSelected: "Paquetes Seleccionados",
  repository: "Repositorio",
  restartToApplyChanges: "Para aplicar los cambios, por favor reinicia ComfyUI",
  searchPlaceholder: "Buscar",
  selectVersion: "Seleccionar Versión",
  sort: {
    created: "Más reciente",
    downloads: "Más Popular",
    publisher: "Editor",
    updated: "Actualizado recientemente"
  },
  status: {
    active: "Activo",
    banned: "Prohibido",
    deleted: "Eliminado",
    flagged: "Marcado",
    pending: "Pendiente",
    unknown: "Desconocido"
  },
  title: "Administrador de Nodos Personalizados",
  totalNodes: "Total de Nodos",
  tryAgainLater: "Por favor intenta de nuevo más tarde.",
  tryDifferentSearch: "Por favor intenta con una consulta de búsqueda diferente.",
  uninstall: "Desinstalar",
  uninstallSelected: "Desinstalar Seleccionado",
  uninstalling: "Desinstalando",
  update: "Actualizar",
  updatingAllPacks: "Actualizando todos los paquetes",
  version: "Versión"
};
const maskEditor$5 = {
  "Apply to Whole Image": "Aplicar a toda la imagen",
  "Brush Settings": "Configuración de pincel",
  "Brush Shape": "Forma de pincel",
  Clear: "Borrar",
  "Color Select Settings": "Configuración de selección de color",
  "Fill Opacity": "Opacidad de relleno",
  Hardness: "Dureza",
  "Image Layer": "Capa de imagen",
  Invert: "Invertir",
  Layers: "Capas",
  "Live Preview": "Vista previa en vivo",
  "Mask Layer": "Capa de máscara",
  "Mask Opacity": "Opacidad de máscara",
  "Mask Tolerance": "Tolerancia de máscara",
  Method: "Método",
  Opacity: "Opacidad",
  "Paint Bucket Settings": "Configuración de cubo de pintura",
  "Reset to Default": "Restablecer a predeterminado",
  "Selection Opacity": "Opacidad de selección",
  "Smoothing Precision": "Precisión de suavizado",
  "Stop at mask": "Detener en máscara",
  Thickness: "Grosor",
  Tolerance: "Tolerancia"
};
const menu$5 = {
  autoQueue: "Cola automática",
  batchCount: "Conteo de lotes",
  batchCountTooltip: "El número de veces que la generación del flujo de trabajo debe ser encolada",
  clear: "Limpiar flujo de trabajo",
  clipspace: "Abrir Clipspace",
  disabled: "Deshabilitado",
  disabledTooltip: "El flujo de trabajo no se encolará automáticamente",
  execute: "Ejecutar",
  hideMenu: "Ocultar menú",
  instant: "Instantáneo",
  instantTooltip: "El flujo de trabajo se encolará instantáneamente después de que finalice una generación",
  interrupt: "Cancelar ejecución actual",
  onChange: "Al cambiar",
  onChangeTooltip: "El flujo de trabajo se encolará una vez que se haga un cambio",
  refresh: "Actualizar definiciones de nodos",
  resetView: "Restablecer vista del lienzo",
  run: "Ejecutar",
  runWorkflow: "Ejecutar flujo de trabajo (Shift para encolar al frente)",
  runWorkflowFront: "Ejecutar flujo de trabajo (Encolar al frente)",
  showMenu: "Mostrar menú",
  toggleBottomPanel: "Alternar panel inferior"
};
const menuLabels$5 = {
  "About ComfyUI": "Acerca de ComfyUI",
  "Browse Templates": "Explorar plantillas",
  "Bypass/Unbypass Selected Nodes": "Evitar/No evitar nodos seleccionados",
  "Canvas Toggle Link Visibility": "Alternar visibilidad de enlace en lienzo",
  "Canvas Toggle Lock": "Alternar bloqueo en lienzo",
  "Check for Updates": "Buscar actualizaciones",
  "Clear Pending Tasks": "Borrar tareas pendientes",
  "Clear Workflow": "Borrar flujo de trabajo",
  Clipspace: "Espacio de clip",
  "Close Current Workflow": "Cerrar flujo de trabajo actual",
  "Collapse/Expand Selected Nodes": "Contraer/Expandir nodos seleccionados",
  "Comfy-Org Discord": "Discord de Comfy-Org",
  "ComfyUI Docs": "Documentos de ComfyUI",
  "ComfyUI Forum": "Foro de ComfyUI",
  "ComfyUI Issues": "Problemas de ComfyUI",
  "Contact Support": "Contactar soporte",
  "Convert selected nodes to group node": "Convertir nodos seleccionados en nodo de grupo",
  "Custom Nodes Manager": "Gestor de nodos personalizados",
  "Delete Selected Items": "Eliminar elementos seleccionados",
  "Desktop User Guide": "Guía de usuario de escritorio",
  "Duplicate Current Workflow": "Duplicar flujo de trabajo actual",
  Edit: "Editar",
  Export: "Exportar",
  "Export (API)": "Exportar (API)",
  "Fit Group To Contents": "Ajustar grupo a contenidos",
  "Fit view to selected nodes": "Ajustar vista a los nodos seleccionados",
  "Give Feedback": "Dar retroalimentación",
  "Group Selected Nodes": "Agrupar nodos seleccionados",
  Help: "Ayuda",
  Interrupt: "Interrumpir",
  "Load Default Workflow": "Cargar flujo de trabajo predeterminado",
  "Manage group nodes": "Gestionar nodos de grupo",
  "Mute/Unmute Selected Nodes": "Silenciar/Activar sonido de nodos seleccionados",
  New: "Nuevo",
  "Next Opened Workflow": "Siguiente flujo de trabajo abierto",
  Open: "Abrir",
  "Open Custom Nodes Folder": "Abrir carpeta de nodos personalizados",
  "Open DevTools": "Abrir DevTools",
  "Open Inputs Folder": "Abrir carpeta de entradas",
  "Open Logs Folder": "Abrir carpeta de registros",
  "Open Models Folder": "Abrir carpeta de modelos",
  "Open Outputs Folder": "Abrir carpeta de salidas",
  "Open Sign In Dialog": "Abrir diálogo de inicio de sesión",
  "Open extra_model_paths_yaml": "Abrir extra_model_paths.yaml",
  "Pin/Unpin Selected Items": "Anclar/Desanclar elementos seleccionados",
  "Pin/Unpin Selected Nodes": "Anclar/Desanclar nodos seleccionados",
  "Previous Opened Workflow": "Flujo de trabajo abierto anterior",
  "Queue Prompt": "Indicador de cola",
  "Queue Prompt (Front)": "Indicador de cola (Frente)",
  "Queue Selected Output Nodes": "Encolar nodos de salida seleccionados",
  Quit: "Salir",
  Redo: "Rehacer",
  "Refresh Node Definitions": "Actualizar definiciones de nodo",
  Reinstall: "Reinstalar",
  "Reset View": "Restablecer vista",
  "Resize Selected Nodes": "Redimensionar Nodos Seleccionados",
  Restart: "Reiniciar",
  Save: "Guardar",
  "Save As": "Guardar como",
  "Show Settings Dialog": "Mostrar diálogo de configuración",
  "Sign Out": "Cerrar sesión",
  "Toggle Bottom Panel": "Alternar panel inferior",
  "Toggle Focus Mode": "Alternar modo de enfoque",
  "Toggle Logs Bottom Panel": "Alternar panel inferior de registros",
  "Toggle Model Library Sidebar": "Alternar barra lateral de biblioteca de modelos",
  "Toggle Node Library Sidebar": "Alternar barra lateral de biblioteca de nodos",
  "Toggle Progress Dialog": "Alternar diálogo de progreso",
  "Toggle Queue Sidebar": "Alternar barra lateral de cola",
  "Toggle Search Box": "Alternar caja de búsqueda",
  "Toggle Terminal Bottom Panel": "Alternar panel inferior de terminal",
  "Toggle Theme (Dark/Light)": "Alternar tema (Oscuro/Claro)",
  "Toggle Workflows Sidebar": "Alternar barra lateral de flujos de trabajo",
  Undo: "Deshacer",
  "Ungroup selected group nodes": "Desagrupar nodos de grupo seleccionados",
  Workflow: "Flujo de trabajo",
  "Zoom In": "Acercar",
  "Zoom Out": "Alejar"
};
const missingModelsDialog$5 = {
  doNotAskAgain: "No mostrar esto de nuevo",
  missingModels: "Modelos faltantes",
  missingModelsMessage: "Al cargar el gráfico, no se encontraron los siguientes modelos"
};
const nodeCategories$5 = {
  "3d": "3d",
  "3d_models": "modelos_3d",
  BFL: "BFL",
  Ideogram: "Ideogram",
  Kling: "Kling",
  Luma: "Luma",
  MiniMax: "MiniMax",
  OpenAI: "OpenAI",
  Pika: "Pika",
  PixVerse: "PixVerse",
  Recraft: "Recraft",
  "Stability AI": "Stability AI",
  Veo: "Veo",
  _for_testing: "_para_pruebas",
  advanced: "avanzado",
  animation: "animación",
  api: "api",
  "api node": "nodo api",
  attention_experiments: "experimentos_de_atención",
  audio: "audio",
  batch: "lote",
  clip: "clip",
  combine: "combinar",
  compositing: "composición",
  "cond pair": "par_cond",
  "cond single": "cond único",
  conditioning: "acondicionamiento",
  controlnet: "controlnet",
  create: "crear",
  custom_sampling: "muestreo_personalizado",
  debug: "depurar",
  deprecated: "obsoleto",
  flux: "flux",
  gligen: "gligen",
  guidance: "orientación",
  guiders: "guías",
  hooks: "ganchos",
  image: "imagen",
  inpaint: "pintar",
  instructpix2pix: "instruirpix2pix",
  latent: "latent",
  loaders: "cargadores",
  lotus: "lotus",
  ltxv: "ltxv",
  mask: "mask",
  model: "modelo",
  model_merging: "fusión_de_modelos",
  model_patches: "parches_de_modelo",
  model_specific: "modelo_específico",
  noise: "ruido",
  operations: "operaciones",
  photomaker: "photomaker",
  postprocessing: "postprocesamiento",
  preprocessors: "preprocesadores",
  primitive: "primitivo",
  samplers: "muestreadores",
  sampling: "muestreo",
  schedulers: "programadores",
  scheduling: "programación",
  sd: "sd",
  sd3: "sd3",
  sigmas: "sigmas",
  stable_cascade: "stable_cascade",
  style_model: "modelo_de_estilo",
  transform: "transformar",
  unet: "unet",
  upscale_diffusion: "difusión_de_escalado",
  upscaling: "escalado",
  utils: "utilidades",
  v1: "v1",
  v2: "v2",
  v3: "v3",
  video: "video",
  video_models: "modelos_de_video"
};
const nodeTemplates$5 = {
  enterName: "Introduzca el nombre",
  saveAsTemplate: "Guardar como plantilla"
};
const notSupported$5 = {
  "continue": "Continuar",
  continueTooltip: "Estoy seguro de que mi dispositivo es compatible",
  learnMore: "Aprender más",
  message: "Solo los siguientes dispositivos son compatibles:",
  reportIssue: "Reportar problema",
  supportedDevices: {
    macos: "MacOS (M1 o posterior)",
    windows: "Windows (GPU Nvidia con soporte CUDA)"
  },
  title: "Tu dispositivo no es compatible"
};
const selectionToolbox$5 = {
  executeButton: {
    disabledTooltip: "No hay nodos de salida seleccionados",
    tooltip: "Ejecutar en los nodos de salida seleccionados (resaltados con borde naranja)"
  }
};
const serverConfig$5 = {
  modifiedConfigs: "Has modificado las siguientes configuraciones del servidor. Reinicia para aplicar los cambios.",
  restart: "Reiniciar",
  revertChanges: "Revertir cambios"
};
const serverConfigCategories$5 = {
  Attention: "Atención",
  CUDA: "CUDA",
  Cache: "Caché",
  Directories: "Directorios",
  General: "General",
  Inference: "Inferencia",
  Memory: "Memoria",
  Network: "Red",
  Preview: "Vista previa"
};
const serverConfigItems$5 = {
  "cache-classic": {
    name: "Usar el sistema de caché clásico"
  },
  "cache-lru": {
    name: "Usar la caché LRU con un máximo de N resultados de nodo en caché.",
    tooltip: "Puede usar más RAM/VRAM."
  },
  "cpu-vae": {
    name: "Ejecutar VAE en CPU"
  },
  "cross-attention-method": {
    name: "Método de atención cruzada"
  },
  "cuda-device": {
    name: "Índice de dispositivo CUDA para usar"
  },
  "cuda-malloc": {
    name: "Usar CUDA malloc para la asignación de memoria"
  },
  "default-hashing-function": {
    name: "Función de hashing predeterminada para archivos de modelo"
  },
  deterministic: {
    name: "Hacer que pytorch use algoritmos deterministas más lentos cuando puede.",
    tooltip: "Tenga en cuenta que esto puede no hacer que las imágenes sean deterministas en todos los casos."
  },
  directml: {
    name: "Índice de dispositivo DirectML"
  },
  "disable-all-custom-nodes": {
    name: "Desactivar la carga de todos los nodos personalizados."
  },
  "disable-ipex-optimize": {
    name: "Desactivar la optimización de IPEX"
  },
  "disable-metadata": {
    name: "Desactivar el guardado de metadatos de solicitud en archivos."
  },
  "disable-smart-memory": {
    name: "Desactivar la gestión inteligente de memoria",
    tooltip: "Forzar a ComfyUI a descargar agresivamente a la ram regular en lugar de mantener los modelos en vram cuando puede."
  },
  "disable-xformers": {
    name: "Desactivar la optimización de xFormers"
  },
  "dont-print-server": {
    name: "No imprimir la salida del servidor en la consola."
  },
  "dont-upcast-attention": {
    name: "Prevenir la atención de upcast"
  },
  "enable-cors-header": {
    name: 'Habilitar encabezado CORS: Use "*" para todos los orígenes o especifique el dominio'
  },
  fast: {
    name: "Habilitar algunas optimizaciones no probadas y potencialmente deteriorantes de la calidad."
  },
  "force-channels-last": {
    name: "Forzar el formato de memoria de los canales al final"
  },
  "force-upcast-attention": {
    name: "Forzar la atención de upcast"
  },
  "global-precision": {
    name: "Precisión global de punto flotante",
    tooltip: "Precisión global de punto flotante"
  },
  "input-directory": {
    name: "Directorio de entrada"
  },
  listen: {
    name: "Host: La dirección IP para escuchar"
  },
  "log-level": {
    name: "Nivel de verbosidad de registro"
  },
  "max-upload-size": {
    name: "Tamaño máximo de carga (MB)"
  },
  "output-directory": {
    name: "Directorio de salida"
  },
  port: {
    name: "Puerto: El puerto para escuchar"
  },
  "preview-method": {
    name: "Método utilizado para las vistas previas latentes"
  },
  "preview-size": {
    name: "Tamaño de las imágenes de vista previa"
  },
  "reserve-vram": {
    name: "VRAM reservada (GB)",
    tooltip: "Establezca la cantidad de vram en GB que desea reservar para su uso por su sistema operativo/otro software. Por defecto, se reserva cierta cantidad dependiendo de su sistema operativo."
  },
  "text-encoder-precision": {
    name: "Precisión del codificador de texto",
    tooltip: "Precisión del codificador de texto"
  },
  "tls-certfile": {
    name: "Archivo de certificado TLS: Ruta al archivo de certificado TLS para HTTPS"
  },
  "tls-keyfile": {
    name: "Archivo de clave TLS: Ruta al archivo de clave TLS para HTTPS"
  },
  "unet-precision": {
    name: "Precisión de UNET",
    tooltip: "Precisión de UNET"
  },
  "vae-precision": {
    name: "Precisión de VAE",
    tooltip: "Precisión de VAE"
  },
  "vram-management": {
    name: "Modo de gestión de VRAM"
  }
};
const serverStart$5 = {
  openLogs: "Abrir registros",
  process: {
    error: "No se puede iniciar ComfyUI Desktop",
    "initial-state": "Cargando...",
    "python-setup": "Configurando el entorno de Python...",
    ready: "Finalizando...",
    "starting-server": "Iniciando el servidor ComfyUI..."
  },
  reportIssue: "Reportar problema",
  showTerminal: "Mostrar terminal",
  troubleshoot: "Solucionar problemas"
};
const settingsCategories$5 = {
  "3D": "3D",
  About: "Acerca de",
  Appearance: "Apariencia",
  BrushAdjustment: "Ajuste de Pincel",
  Camera: "Cámara",
  Canvas: "Lienzo",
  ColorPalette: "Paleta de Colores",
  Comfy: "Comfy",
  "Comfy-Desktop": "Comfy-Desktop",
  ContextMenu: "Menú Contextual",
  Credits: "Créditos",
  CustomColorPalettes: "Paletas de Colores Personalizadas",
  DevMode: "Modo de Desarrollo",
  EditTokenWeight: "Editar Peso del Token",
  Extension: "Extensión",
  General: "General",
  Graph: "Gráfico",
  Group: "Grupo",
  Keybinding: "Asignación de Teclas",
  Light: "Claro",
  Link: "Enlace",
  LinkRelease: "Liberación de Enlace",
  LiteGraph: "Lite Graph",
  "Load 3D": "Cargar 3D",
  Locale: "Localización",
  "Mask Editor": "Editor de Máscara",
  Menu: "Menú",
  ModelLibrary: "Biblioteca de Modelos",
  NewEditor: "Nuevo Editor",
  Node: "Nodo",
  "Node Search Box": "Caja de Búsqueda de Nodo",
  "Node Widget": "Widget de Nodo",
  NodeLibrary: "Biblioteca de Nodos",
  Pointer: "Puntero",
  Queue: "Cola",
  QueueButton: "Botón de Cola",
  Reroute: "Reenrutar",
  RerouteBeta: "Reroute Beta",
  Scene: "Escena",
  Server: "Servidor",
  "Server-Config": "Configuración del Servidor",
  Settings: "Configuraciones",
  Sidebar: "Barra Lateral",
  "Tree Explorer": "Explorador de Árbol",
  UV: "UV",
  User: "Usuario",
  Validation: "Validación",
  Window: "Ventana",
  Workflow: "Flujo de Trabajo"
};
const sideToolbar$5 = {
  browseTemplates: "Explorar plantillas de ejemplo",
  downloads: "Descargas",
  logout: "Cerrar sesión",
  modelLibrary: "Biblioteca de modelos",
  newBlankWorkflow: "Crear un nuevo flujo de trabajo en blanco",
  nodeLibrary: "Biblioteca de nodos",
  nodeLibraryTab: {
    sortOrder: "Orden de clasificación"
  },
  openWorkflow: "Abrir flujo de trabajo en el sistema de archivos local",
  queue: "Cola",
  queueTab: {
    backToAllTasks: "Volver a todas las tareas",
    clearPendingTasks: "Borrar tareas pendientes",
    containImagePreview: "Llenar vista previa de la imagen",
    coverImagePreview: "Ajustar vista previa de la imagen",
    filter: "Filtrar salidas",
    filters: {
      hideCached: "Ocultar en caché",
      hideCanceled: "Ocultar cancelados"
    },
    showFlatList: "Mostrar lista plana"
  },
  themeToggle: "Cambiar tema",
  workflowTab: {
    confirmDelete: "¿Estás seguro de que quieres eliminar este flujo de trabajo?",
    confirmDeleteTitle: "¿Eliminar flujo de trabajo?",
    confirmOverwrite: "El archivo a continuación ya existe. ¿Te gustaría sobrescribirlo?",
    confirmOverwriteTitle: "¿Sobrescribir archivo existente?",
    deleteFailed: "El intento de eliminar el flujo de trabajo ha fallado.",
    deleteFailedTitle: "Eliminación fallida",
    deleted: "Flujo de trabajo eliminado",
    dirtyClose: "Los archivos a continuación han sido modificados. ¿Te gustaría guardarlos antes de cerrar?",
    dirtyCloseHint: "Mantén presionada la tecla Shift para cerrar sin preguntar",
    dirtyCloseTitle: "¿Guardar cambios?",
    workflowTreeType: {
      bookmarks: "Marcadores",
      browse: "Explorar",
      open: "Abrir"
    }
  },
  workflows: "Flujos de trabajo"
};
const tabMenu$5 = {
  addToBookmarks: "Agregar a marcadores",
  closeOtherTabs: "Cerrar otras pestañas",
  closeTab: "Cerrar pestaña",
  closeTabsToLeft: "Cerrar pestañas a la izquierda",
  closeTabsToRight: "Cerrar pestañas a la derecha",
  duplicateTab: "Duplicar pestaña",
  removeFromBookmarks: "Eliminar de marcadores"
};
const templateWorkflows$5 = {
  category: {
    "3D": "3D",
    "Area Composition": "Composición de Área",
    Audio: "Audio",
    Basics: "Básicos",
    "ComfyUI Examples": "Ejemplos de ComfyUI",
    ControlNet: "ControlNet",
    "Custom Nodes": "Nodos Personalizados",
    Flux: "Flux",
    Image: "Imagen",
    "Image API": "API de Imagen",
    Upscaling: "Ampliación",
    Video: "Video",
    "Video API": "API de Video"
  },
  template: {
    "3D": {
      "hunyuan-3d-multiview-elf": "Hunyuan3D 2.0 MV",
      "hunyuan-3d-turbo": "Hunyuan3D 2.0 MV Turbo",
      "hunyuan3d-non-multiview-train": "Hunyuan3D 2.0",
      stable_zero123_example: "Estable Zero123"
    },
    "Area Composition": {
      area_composition: "Composición de Área",
      area_composition_reversed: "Composición de Área Invertida",
      area_composition_square_area_for_subject: "Composición de Área Cuadrada para el Sujeto"
    },
    Audio: {
      stable_audio_example: "Audio Estable"
    },
    Basics: {
      "default": "Generación de Imagen",
      embedding_example: "Incrustación",
      gligen_textbox_example: "Caja de Texto Gligen",
      image2image: "Imagen a Imagen",
      inpain_model_outpainting: "Outpaint",
      inpaint_example: "Inpaint",
      lora: "Lora",
      lora_multiple: "Lora Múltiple"
    },
    ControlNet: {
      "2_pass_pose_worship": "ControlNet de Pose 2 Pasadas",
      controlnet_example: "ControlNet de Garabato",
      depth_controlnet: "ControlNet de Profundidad",
      depth_t2i_adapter: "Adaptador de Profundidad T2I",
      mixing_controlnets: "Mezcla de ControlNets"
    },
    Flux: {
      flux_canny_model_example: "Flux Canny Model",
      flux_depth_lora_example: "Flux Depth Lora",
      flux_dev_checkpoint_example: "Flux Dev",
      flux_fill_inpaint_example: "Flux Inpaint",
      flux_fill_outpaint_example: "Flux Outpaint",
      flux_redux_model_example: "Flux Redux Model",
      flux_schnell: "Flux Schnell"
    },
    Image: {
      hidream_i1_dev: "HiDream I1 Dev",
      hidream_i1_fast: "HiDream I1 Rápido",
      hidream_i1_full: "HiDream I1 Completo",
      sd3_5_large_blur: "SD3.5 Grande Desenfoque",
      sd3_5_large_canny_controlnet_example: "SD3.5 Grande Canny ControlNet",
      sd3_5_large_depth: "SD3.5 Grande Profundidad",
      sd3_5_simple_example: "SD3.5 Simple",
      sdxl_refiner_prompt_example: "SDXL Refinador de Solicitud",
      sdxl_revision_text_prompts: "SDXL Revisión de Solicitud de Texto",
      sdxl_revision_zero_positive: "SDXL Revisión Cero Positivo",
      sdxl_simple_example: "SDXL Simple",
      sdxlturbo_example: "SDXL Turbo"
    },
    "Image API": {
      "api-openai-dall-e-2-inpaint": "Dall-E 2 Rellenar",
      "api-openai-dall-e-2-t2i": "Dall-E 2 Texto a Imagen",
      "api-openai-dall-e-3-t2i": "Dall-E 3 Texto a Imagen",
      api_bfl_flux_pro_t2i: "BFL Flux 1.1[pro] Ultra Texto a Imagen",
      api_ideogram_v3_t2i: "Ideogram V3 Texto a Imagen",
      api_luma_photon_i2i: "Luma Photon Imagen a Imagen",
      api_luma_photon_style_ref: "Luma Photon Referencia de Estilo",
      api_openai_image_1_i2i: "OpenAI Image-1 Imagen a Imagen",
      api_openai_image_1_inpaint: "OpenAI Image-1 Rellenar",
      api_openai_image_1_multi_inputs: "OpenAI Image-1 Múltiples Entradas",
      api_openai_image_1_t2i: "OpenAI Image-1 Texto a Imagen",
      api_recraft_image_gen_with_color_control: "Recraft Generación de Imagen con Control de Color",
      api_recraft_image_gen_with_style_control: "Recraft Generación de Imagen con Control de Estilo",
      api_recraft_vector_gen: "Recraft Generación de Vectores",
      api_stability_sd3_t2i: "Stability AI Stable Image Ultra Texto a Imagen"
    },
    Upscaling: {
      esrgan_example: "ESRGAN",
      hiresfix_esrgan_workflow: "Flujo de Trabajo HiresFix ESRGAN",
      hiresfix_latent_workflow: "Ampliación",
      latent_upscale_different_prompt_model: "Ampliación Latente Modelo de Solicitud Diferente"
    },
    Video: {
      hunyuan_video_text_to_video: "Hunyuan Video Texto a Video",
      image_to_video: "SVD Imagen a Video",
      image_to_video_wan: "Wan 2.1 Imagen a Video",
      ltxv_image_to_video: "LTXV Imagen a Video",
      ltxv_text_to_video: "LTXV Texto a Video",
      mochi_text_to_video_example: "Mochi Texto a Video",
      text_to_video_wan: "Wan 2.1 Texto a Video",
      txt_to_image_to_video: "SVD Texto a Imagen a Video",
      wan2_1_fun_control: "Wan 2.1 ControlNet",
      wan2_1_fun_inp: "Wan 2.1 Relleno"
    },
    "Video API": {
      api_hailuo_minimax_i2v: "MiniMax Imagen a Video",
      api_kling_i2v: "Kling Imagen a Video",
      api_luma_i2v: "Luma Imagen a Video",
      api_pika_scene: "Pika Escenas: Imágenes a Video",
      api_pixverse_t2v: "PixVerse Texto a Video",
      api_pixverse_template_i2v: "PixVerse Template Effects: Imagen a Video",
      api_veo2_i2v: "Veo2 Imagen a Video"
    }
  },
  templateDescription: {
    "3D": {
      "hunyuan-3d-multiview-elf": "Usa Hunyuan3D 2mv para generar modelos desde múltiples vistas.",
      "hunyuan-3d-turbo": "Usa Hunyuan3D 2mv turbo para generar modelos desde múltiples vistas.",
      "hunyuan3d-non-multiview-train": "Usa Hunyuan3D 2.0 para generar modelos desde una sola vista.",
      stable_zero123_example: "Genera vistas 3D a partir de imágenes individuales."
    },
    "Area Composition": {
      area_composition: "Controla la composición de la imagen por áreas.",
      area_composition_reversed: "Invierte el flujo de composición por áreas.",
      area_composition_square_area_for_subject: "Crea una colocación consistente del sujeto."
    },
    Audio: {
      stable_audio_example: "Genera audio a partir de descripciones de texto."
    },
    Basics: {
      "default": "Genera imágenes a partir de descripciones de texto.",
      embedding_example: "Utiliza inversión textual para estilos consistentes.",
      gligen_textbox_example: "Especifica la ubicación y el tamaño de los objetos.",
      image2image: "Transforma imágenes existentes usando indicaciones de texto.",
      inpain_model_outpainting: "Extiende imágenes más allá de sus límites originales.",
      inpaint_example: "Edita partes específicas de imágenes de manera fluida.",
      lora: "Aplica modelos LoRA para estilos o temas especializados.",
      lora_multiple: "Combina múltiples modelos LoRA para resultados únicos."
    },
    ControlNet: {
      "2_pass_pose_worship": "Genera imágenes a partir de referencias de pose.",
      controlnet_example: "Controla la generación de imágenes con imágenes de referencia.",
      depth_controlnet: "Crea imágenes con generación consciente de profundidad.",
      depth_t2i_adapter: "Genera rápidamente imágenes conscientes de profundidad con un adaptador T2I.",
      mixing_controlnets: "Combina múltiples modelos ControlNet juntos."
    },
    Flux: {
      flux_canny_model_example: "Genera imágenes a partir de detección de bordes.",
      flux_depth_lora_example: "Crea imágenes con LoRA consciente de profundidad.",
      flux_dev_checkpoint_example: "Crea imágenes usando modelos de desarrollo de Flux.",
      flux_fill_inpaint_example: "Rellena partes faltantes de imágenes.",
      flux_fill_outpaint_example: "Extiende imágenes usando outpainting de Flux.",
      flux_redux_model_example: "Transfiere el estilo de una imagen de referencia para guiar la generación de imágenes con Flux.",
      flux_schnell: "Genera imágenes rápidamente con Flux Schnell."
    },
    Image: {
      hidream_e1_full: "Edita imágenes con HiDream E1.",
      hidream_i1_dev: "Genera imágenes con HiDream I1 Dev.",
      hidream_i1_fast: "Genera imágenes rápidamente con HiDream I1.",
      hidream_i1_full: "Genera imágenes con HiDream I1.",
      sd3_5_large_blur: "Genera imágenes a partir de imágenes de referencia borrosas con SD 3.5.",
      sd3_5_large_canny_controlnet_example: "Usa detección de bordes para guiar la generación de imágenes con SD 3.5.",
      sd3_5_large_depth: "Crea imágenes conscientes de profundidad con SD 3.5.",
      sd3_5_simple_example: "Genera imágenes con SD 3.5.",
      sdxl_refiner_prompt_example: "Mejora los resultados de SDXL con refinadores.",
      sdxl_revision_text_prompts: "Transfiere conceptos de imágenes de referencia para guiar la generación de imágenes con SDXL.",
      sdxl_revision_zero_positive: "Agrega indicaciones de texto junto a imágenes de referencia para guiar la generación de imágenes con SDXL.",
      sdxl_simple_example: "Crea imágenes de alta calidad con SDXL.",
      sdxlturbo_example: "Genera imágenes en un solo paso con SDXL Turbo."
    },
    "Image API": {
      "api-openai-dall-e-2-inpaint": "Usa la API Dall-E 2 para hacer inpainting en imágenes.",
      "api-openai-dall-e-2-t2i": "Usa la API Dall-E 2 para generar imágenes a partir de descripciones de texto.",
      "api-openai-dall-e-3-t2i": "Usa la API Dall-E 3 para generar imágenes a partir de descripciones de texto.",
      api_bfl_flux_pro_t2i: "Crea imágenes con FLUX.1 [pro] y su excelente seguimiento de indicaciones, calidad visual, detalle de imagen y diversidad de resultados.",
      api_ideogram_v3_t2i: "Genera imágenes con alineación de indicaciones de alta calidad, fotorrealismo y renderizado de texto. Crea logotipos de calidad profesional, carteles promocionales, conceptos de páginas de destino, fotografía de productos y más. Crea composiciones espaciales sofisticadas con fondos intrincados, iluminación y colores precisos y matizados, y detalles ambientales realistas.",
      api_luma_photon_i2i: "Guía la generación de imágenes usando una combinación de imágenes e indicaciones.",
      api_luma_photon_style_ref: "Aplica y combina referencias de estilo con control exacto. Luma Photon captura la esencia de cada imagen de referencia, permitiéndote combinar elementos visuales distintos manteniendo calidad profesional.",
      api_openai_image_1_i2i: "Usa la API GPT Image 1 para generar imágenes a partir de imágenes.",
      api_openai_image_1_inpaint: "Usa la API GPT Image 1 para hacer inpainting en imágenes.",
      api_openai_image_1_multi_inputs: "Usa la API GPT Image 1 con múltiples entradas para generar imágenes.",
      api_openai_image_1_t2i: "Usa la API GPT Image 1 para generar imágenes a partir de descripciones de texto.",
      api_recraft_image_gen_with_color_control: "Crea una paleta personalizada para reutilizar en múltiples imágenes o selecciona colores para cada foto. Haz coincidir la paleta de tu marca y crea imágenes visuales que sean distintivamente tuyas.",
      api_recraft_image_gen_with_style_control: "Controla el estilo con ejemplos visuales, alinea la posición y ajusta objetos. Guarda y comparte estilos para una consistencia perfecta de marca.",
      api_recraft_vector_gen: "Pasa de una indicación de texto a una imagen vectorial con el generador de vectores IA de Recraft. Produce arte vectorial de la mejor calidad para logotipos, carteles, conjuntos de iconos, anuncios, banners y maquetas. Perfecciona tus diseños con archivos SVG nítidos y de alta calidad. Crea ilustraciones vectoriales de marca para tu app o sitio web en segundos.",
      api_stability_sd3_t2i: "Genera imágenes de alta calidad con excelente adherencia a las indicaciones. Perfecto para casos de uso profesional a resolución de 1 megapíxel."
    },
    Upscaling: {
      esrgan_example: "Usa modelos de escalado para mejorar la calidad de imagen.",
      hiresfix_esrgan_workflow: "Usa modelos de escalado durante pasos intermedios.",
      hiresfix_latent_workflow: "Mejora la calidad de imagen en el espacio latente.",
      latent_upscale_different_prompt_model: "Escala y cambia la indicación entre pasadas."
    },
    Video: {
      hunyuan_video_text_to_video: "Genera videos usando el modelo Hunyuan.",
      image_to_video: "Transforma imágenes en videos animados.",
      image_to_video_wan: "Genera videos rápidamente a partir de imágenes.",
      ltxv_image_to_video: "Convierte imágenes fijas en videos.",
      ltxv_text_to_video: "Genera videos a partir de descripciones de texto.",
      mochi_text_to_video_example: "Crea videos con el modelo Mochi.",
      text_to_video_wan: "Genera videos rápidamente a partir de descripciones de texto.",
      txt_to_image_to_video: "Genera imágenes a partir de texto y luego conviértelas en videos.",
      wan2_1_flf2v_720_f16: "Genera video controlando el primer y último fotograma.",
      wan2_1_fun_control: "Guía la generación de video con pose, profundidad, controles de bordes y más.",
      wan2_1_fun_inp: "Crea videos a partir de fotogramas iniciales y finales."
    },
    "Video API": {
      api_hailuo_minimax_i2v: "Crea videos refinados a partir de imágenes y texto, incluyendo integración CGI y efectos fotográficos de tendencia como abrazos virales de IA. Elige entre una variedad de estilos y temas de video para que coincidan con tu visión creativa.",
      api_kling_i2v: "Crea videos con gran adherencia a las indicaciones para acciones, expresiones y movimientos de cámara. Ahora soporta indicaciones complejas con acciones secuenciales para que seas el director de tu escena.",
      api_luma_i2v: "Convierte imágenes estáticas en animaciones mágicas de alta calidad al instante.",
      api_pika_scene: "Usa múltiples imágenes como ingredientes y genera videos que las incorporen todas.",
      api_pixverse_t2v: "Genera videos con interpretación precisa de indicaciones y una dinámica visual impresionante.",
      api_pixverse_template_i2v: "Transforma imágenes estáticas en videos dinámicos con movimiento y efectos.",
      api_veo2_i2v: "Usa la API Google Veo2 para generar videos a partir de imágenes."
    }
  },
  title: "Comienza con una Plantilla"
};
const toastMessages$5 = {
  couldNotDetermineFileType: "No se pudo determinar el tipo de archivo",
  dropFileError: "No se puede procesar el elemento soltado: {error}",
  emptyCanvas: "Lienzo vacío",
  errorCopyImage: "Error al copiar la imagen: {error}",
  errorLoadingModel: "Error al cargar el modelo",
  errorSaveSetting: "Error al guardar la configuración {id}: {err}",
  failedToAccessBillingPortal: "No se pudo acceder al portal de facturación: {error}",
  failedToApplyTexture: "Error al aplicar textura",
  failedToCreateCustomer: "No se pudo crear el cliente: {error}",
  failedToDownloadFile: "Error al descargar el archivo",
  failedToExportModel: "Error al exportar modelo como {format}",
  failedToFetchBalance: "No se pudo obtener el saldo: {error}",
  failedToFetchLogs: "Error al obtener los registros del servidor",
  failedToInitiateCreditPurchase: "No se pudo iniciar la compra de créditos: {error}",
  failedToPurchaseCredits: "No se pudo comprar créditos: {error}",
  fileLoadError: "No se puede encontrar el flujo de trabajo en {fileName}",
  fileUploadFailed: "Error al subir el archivo",
  interrupted: "La ejecución ha sido interrumpida",
  migrateToLitegraphReroute: "Los nodos de reroute se eliminarán en futuras versiones. Haz clic para migrar a reroute nativo de litegraph.",
  no3dScene: "No hay escena 3D para aplicar textura",
  no3dSceneToExport: "No hay escena 3D para exportar",
  noTemplatesToExport: "No hay plantillas para exportar",
  nodeDefinitionsUpdated: "Definiciones de nodos actualizadas",
  nothingToGroup: "Nada para agrupar",
  nothingToQueue: "Nada para poner en cola",
  pendingTasksDeleted: "Tareas pendientes eliminadas",
  pleaseSelectNodesToGroup: "Por favor, seleccione los nodos (u otros grupos) para crear un grupo para",
  pleaseSelectOutputNodes: "Por favor, selecciona los nodos de salida",
  unableToGetModelFilePath: "No se puede obtener la ruta del archivo del modelo",
  unauthorizedDomain: "Tu dominio {domain} no está autorizado para usar este servicio. Por favor, contacta a {email} para agregar tu dominio a la lista blanca.",
  updateRequested: "Actualización solicitada",
  useApiKeyTip: "Consejo: ¿No puedes acceder al inicio de sesión normal? Usa la opción de clave API de Comfy.",
  userNotAuthenticated: "Usuario no autenticado"
};
const userSelect$5 = {
  enterUsername: "Introduce un nombre de usuario",
  existingUser: "Usuario existente",
  newUser: "Nuevo usuario",
  next: "Siguiente",
  selectUser: "Selecciona un usuario"
};
const userSettings$5 = {
  email: "Correo electrónico",
  name: "Nombre",
  notSet: "No establecido",
  provider: "Método de inicio de sesión",
  title: "Configuración de usuario",
  updatePassword: "Actualizar contraseña"
};
const validation$5 = {
  invalidEmail: "Dirección de correo electrónico inválida",
  length: "Debe tener {length} caracteres",
  maxLength: "No debe tener más de {length} caracteres",
  minLength: "Debe tener al menos {length} caracteres",
  password: {
    lowercase: "Debe contener al menos una letra minúscula",
    match: "Las contraseñas deben coincidir",
    minLength: "Debe tener entre 8 y 32 caracteres",
    number: "Debe contener al menos un número",
    requirements: "Requisitos de la contraseña",
    special: "Debe contener al menos un carácter especial",
    uppercase: "Debe contener al menos una letra mayúscula"
  },
  personalDataConsentRequired: "Debes aceptar el procesamiento de tus datos personales.",
  prefix: "Debe comenzar con {prefix}",
  required: "Requerido"
};
const welcome$5 = {
  getStarted: "Empezar",
  title: "Bienvenido a ComfyUI"
};
const workflowService$5 = {
  enterFilename: "Introduzca el nombre del archivo",
  exportWorkflow: "Exportar flujo de trabajo",
  saveWorkflow: "Guardar flujo de trabajo"
};
const es = {
  apiNodesCostBreakdown: apiNodesCostBreakdown$5,
  apiNodesNews: apiNodesNews$5,
  apiNodesSignInDialog: apiNodesSignInDialog$5,
  auth: auth$5,
  clipboard: clipboard$5,
  color: color$5,
  contextMenu: contextMenu$5,
  credits: credits$5,
  dataTypes: dataTypes$5,
  desktopMenu: desktopMenu$5,
  desktopUpdate: desktopUpdate$5,
  downloadGit: downloadGit$5,
  electronFileDownload: electronFileDownload$5,
  errorDialog: errorDialog$5,
  g: g$5,
  graphCanvasMenu: graphCanvasMenu$5,
  groupNode: groupNode$5,
  icon: icon$5,
  install: install$5,
  issueReport: issueReport$5,
  load3d: load3d$5,
  maintenance: maintenance$5,
  manager: manager$5,
  maskEditor: maskEditor$5,
  menu: menu$5,
  menuLabels: menuLabels$5,
  missingModelsDialog: missingModelsDialog$5,
  nodeCategories: nodeCategories$5,
  nodeTemplates: nodeTemplates$5,
  notSupported: notSupported$5,
  selectionToolbox: selectionToolbox$5,
  serverConfig: serverConfig$5,
  serverConfigCategories: serverConfigCategories$5,
  serverConfigItems: serverConfigItems$5,
  serverStart: serverStart$5,
  settingsCategories: settingsCategories$5,
  sideToolbar: sideToolbar$5,
  tabMenu: tabMenu$5,
  templateWorkflows: templateWorkflows$5,
  toastMessages: toastMessages$5,
  userSelect: userSelect$5,
  userSettings: userSettings$5,
  validation: validation$5,
  welcome: welcome$5,
  workflowService: workflowService$5
};
const AddNoise$5 = {
  display_name: "AñadirRuido",
  inputs: {
    latent_image: {
      name: "imagen_latente"
    },
    model: {
      name: "modelo"
    },
    noise: {
      name: "ruido"
    },
    sigmas: {
      name: "sigmas"
    }
  }
};
const AlignYourStepsScheduler$5 = {
  display_name: "ProgramadorAlineaTusPasos",
  inputs: {
    denoise: {
      name: "desruido"
    },
    model_type: {
      name: "tipo_modelo"
    },
    steps: {
      name: "pasos"
    }
  }
};
const BasicGuider$5 = {
  display_name: "GuíaBásica",
  inputs: {
    conditioning: {
      name: "acondicionamiento"
    },
    model: {
      name: "modelo"
    }
  }
};
const BasicScheduler$5 = {
  display_name: "ProgramadorBásico",
  inputs: {
    denoise: {
      name: "desruido"
    },
    model: {
      name: "modelo"
    },
    scheduler: {
      name: "programador"
    },
    steps: {
      name: "pasos"
    }
  }
};
const BetaSamplingScheduler$5 = {
  display_name: "ProgramadorMuestreoBeta",
  inputs: {
    alpha: {
      name: "alfa"
    },
    beta: {
      name: "beta"
    },
    model: {
      name: "modelo"
    },
    steps: {
      name: "pasos"
    }
  }
};
const CFGGuider$5 = {
  display_name: "GuíaCFG",
  inputs: {
    cfg: {
      name: "cfg"
    },
    model: {
      name: "modelo"
    },
    negative: {
      name: "negativo"
    },
    positive: {
      name: "positivo"
    }
  }
};
const CFGZeroStar$5 = {
  display_name: "CFGZeroStar",
  inputs: {
    model: {
      name: "modelo"
    }
  },
  outputs: {
    "0": {
      name: "modelo_modificado"
    }
  }
};
const CLIPAttentionMultiply$5 = {
  display_name: "MultiplicarAtenciónCLIP",
  inputs: {
    clip: {
      name: "clip"
    },
    k: {
      name: "k"
    },
    out: {
      name: "salida"
    },
    q: {
      name: "q"
    },
    v: {
      name: "v"
    }
  }
};
const CLIPLoader$5 = {
  description: "[Recetas]\n\nstable_diffusion: clip-l\nstable_cascade: clip-g\nsd3: t5 xxl/ clip-g / clip-l\nstable_audio: t5 base\nmochi: t5 xxl\ncosmos: old t5 xxl\nlumina2: gemma 2 2B\nwan: umt5 xxl",
  display_name: "Cargar CLIP",
  inputs: {
    clip_name: {
      name: "nombre_clip"
    },
    device: {
      name: "dispositivo"
    },
    type: {
      name: "tipo"
    }
  }
};
const CLIPMergeAdd$5 = {
  display_name: "CLIPMergeAdd",
  inputs: {
    clip1: {
      name: "clip1"
    },
    clip2: {
      name: "clip2"
    }
  }
};
const CLIPMergeSimple$5 = {
  display_name: "CLIPMergeSimple",
  inputs: {
    clip1: {
      name: "clip1"
    },
    clip2: {
      name: "clip2"
    },
    ratio: {
      name: "ratio"
    }
  }
};
const CLIPMergeSubtract$5 = {
  display_name: "CLIPMergeSubtract",
  inputs: {
    clip1: {
      name: "clip1"
    },
    clip2: {
      name: "clip2"
    },
    multiplier: {
      name: "multiplicador"
    }
  }
};
const CLIPSave$5 = {
  display_name: "Guardar CLIP",
  inputs: {
    clip: {
      name: "clip"
    },
    filename_prefix: {
      name: "prefijo_nombre_archivo"
    }
  }
};
const CLIPSetLastLayer$5 = {
  display_name: "Establecer Última Capa de CLIP",
  inputs: {
    clip: {
      name: "clip"
    },
    stop_at_clip_layer: {
      name: "detener_en_capa_clip"
    }
  }
};
const CLIPTextEncode$5 = {
  description: "Codifica un prompt de texto utilizando un modelo CLIP en un embedding que se puede usar para guiar el modelo de difusión hacia la generación de imágenes específicas.",
  display_name: "Codificar Texto CLIP (Prompt)",
  inputs: {
    clip: {
      name: "clip",
      tooltip: "El modelo CLIP utilizado para codificar el texto."
    },
    text: {
      name: "texto",
      tooltip: "El texto a codificar."
    }
  },
  outputs: {
    "0": {
      tooltip: "Una condición que contiene el texto incrustado utilizado para guiar el modelo de difusión."
    }
  }
};
const CLIPTextEncodeControlnet$5 = {
  display_name: "CodificarTextoCLIPControlnet",
  inputs: {
    clip: {
      name: "clip"
    },
    conditioning: {
      name: "condicionamiento"
    },
    text: {
      name: "texto"
    }
  }
};
const CLIPTextEncodeFlux$5 = {
  display_name: "CodificarTextoCLIPFlux",
  inputs: {
    clip: {
      name: "clip"
    },
    clip_l: {
      name: "clip_l"
    },
    guidance: {
      name: "orientación"
    },
    t5xxl: {
      name: "t5xxl"
    }
  }
};
const CLIPTextEncodeHiDream$5 = {
  display_name: "CLIPTextEncodeHiDream",
  inputs: {
    clip: {
      name: "clip"
    },
    clip_g: {
      name: "clip_g"
    },
    clip_l: {
      name: "clip_l"
    },
    llama: {
      name: "llama"
    },
    t5xxl: {
      name: "t5xxl"
    }
  }
};
const CLIPTextEncodeHunyuanDiT$5 = {
  display_name: "CodificarTextoCLIPHunyuanDiT",
  inputs: {
    bert: {
      name: "bert"
    },
    clip: {
      name: "clip"
    },
    mt5xl: {
      name: "mt5xl"
    }
  }
};
const CLIPTextEncodeLumina2$5 = {
  description: "Codifica un mensaje del sistema y un mensaje del usuario utilizando un modelo CLIP en un embedding que se puede usar para guiar el modelo de difusión hacia la generación de imágenes específicas.",
  display_name: "CLIP Text Encode para Lumina2",
  inputs: {
    clip: {
      name: "clip",
      tooltip: "El modelo CLIP utilizado para codificar el texto."
    },
    system_prompt: {
      name: "system_prompt",
      tooltip: "Lumina2 proporciona dos tipos de mensajes del sistema: Superior: Eres un asistente diseñado para generar imágenes superiores con el grado superior de alineación imagen-texto basado en mensajes textuales o mensajes del usuario. Alineación: Eres un asistente diseñado para generar imágenes de alta calidad con el mayor grado de alineación imagen-texto basado en mensajes textuales."
    },
    user_prompt: {
      name: "user_prompt",
      tooltip: "El texto a codificar."
    }
  },
  outputs: {
    "0": {
      tooltip: "Una condición que contiene el texto incrustado utilizado para guiar el modelo de difusión."
    }
  }
};
const CLIPTextEncodePixArtAlpha$5 = {
  description: "Codifica el texto y establece la condición de resolución para PixArt Alpha. No se aplica a PixArt Sigma.",
  display_name: "CLIPTextEncodePixArtAlpha",
  inputs: {
    clip: {
      name: "clip"
    },
    height: {
      name: "height"
    },
    text: {
      name: "text"
    },
    width: {
      name: "width"
    }
  }
};
const CLIPTextEncodeSD3$5 = {
  display_name: "CLIPTextEncodeSD3",
  inputs: {
    clip: {
      name: "clip"
    },
    clip_g: {
      name: "clip_g"
    },
    clip_l: {
      name: "clip_l"
    },
    empty_padding: {
      name: "empty_padding"
    },
    t5xxl: {
      name: "t5xxl"
    }
  }
};
const CLIPTextEncodeSDXL$5 = {
  display_name: "CLIPTextEncodeSDXL",
  inputs: {
    clip: {
      name: "clip"
    },
    crop_h: {
      name: "crop_h"
    },
    crop_w: {
      name: "crop_w"
    },
    height: {
      name: "height"
    },
    target_height: {
      name: "target_height"
    },
    target_width: {
      name: "target_width"
    },
    text_g: {
      name: "text_g"
    },
    text_l: {
      name: "text_l"
    },
    width: {
      name: "width"
    }
  }
};
const CLIPTextEncodeSDXLRefiner$5 = {
  display_name: "CLIPTextEncodeSDXLRefiner",
  inputs: {
    ascore: {
      name: "ascore"
    },
    clip: {
      name: "clip"
    },
    height: {
      name: "height"
    },
    text: {
      name: "text"
    },
    width: {
      name: "width"
    }
  }
};
const CLIPVisionEncode$5 = {
  display_name: "CLIP Vision Encode",
  inputs: {
    clip_vision: {
      name: "clip_vision"
    },
    crop: {
      name: "crop"
    },
    image: {
      name: "image"
    }
  }
};
const CLIPVisionLoader$5 = {
  display_name: "Cargar CLIP Vision",
  inputs: {
    clip_name: {
      name: "clip_name"
    }
  }
};
const Canny$5 = {
  display_name: "Canny",
  inputs: {
    high_threshold: {
      name: "umbral_alto"
    },
    image: {
      name: "imagen"
    },
    low_threshold: {
      name: "umbral_bajo"
    }
  }
};
const CheckpointLoader$5 = {
  display_name: "Cargar Punto de Control Con Configuración (OBSOLETO)",
  inputs: {
    ckpt_name: {
      name: "nombre_ckpt"
    },
    config_name: {
      name: "nombre_configuración"
    }
  }
};
const CheckpointLoaderSimple$5 = {
  description: "Carga un punto de control del modelo de difusión, los modelos de difusión se utilizan para desruidar latentes.",
  display_name: "Cargar Punto de Control",
  inputs: {
    ckpt_name: {
      name: "nombre_ckpt",
      tooltip: "El nombre del punto de control (modelo) a cargar."
    }
  },
  outputs: {
    "0": {
      tooltip: "El modelo utilizado para desruidar latentes."
    },
    "1": {
      tooltip: "El modelo CLIP utilizado para codificar textos de prompts."
    },
    "2": {
      tooltip: "El modelo VAE utilizado para codificar y decodificar imágenes a y desde el espacio latente."
    }
  }
};
const CheckpointSave$5 = {
  display_name: "Guardar Punto de Control",
  inputs: {
    clip: {
      name: "clip"
    },
    filename_prefix: {
      name: "prefijo_nombre_archivo"
    },
    model: {
      name: "modelo"
    },
    vae: {
      name: "vae"
    }
  }
};
const CombineHooks2$5 = {
  display_name: "Combinar Hooks [2]",
  inputs: {
    hooks_A: {
      name: "hooks_A"
    },
    hooks_B: {
      name: "hooks_B"
    }
  }
};
const CombineHooks4$5 = {
  display_name: "Combine Hooks [4]",
  inputs: {
    hooks_A: {
      name: "hooks_A"
    },
    hooks_B: {
      name: "hooks_B"
    },
    hooks_C: {
      name: "hooks_C"
    },
    hooks_D: {
      name: "hooks_D"
    }
  }
};
const CombineHooks8$5 = {
  display_name: "Combine Hooks [8]",
  inputs: {
    hooks_A: {
      name: "hooks_A"
    },
    hooks_B: {
      name: "hooks_B"
    },
    hooks_C: {
      name: "hooks_C"
    },
    hooks_D: {
      name: "hooks_D"
    },
    hooks_E: {
      name: "hooks_E"
    },
    hooks_F: {
      name: "hooks_F"
    },
    hooks_G: {
      name: "hooks_G"
    },
    hooks_H: {
      name: "hooks_H"
    }
  }
};
const ConditioningAverage$5 = {
  display_name: "Promedio de Acondicionamiento",
  inputs: {
    conditioning_from: {
      name: "acondicionamiento_de"
    },
    conditioning_to: {
      name: "acondicionamiento_a"
    },
    conditioning_to_strength: {
      name: "fuerza_de_acondicionamiento_a"
    }
  }
};
const ConditioningCombine$5 = {
  display_name: "Acondicionamiento (Combinar)",
  inputs: {
    conditioning_1: {
      name: "acondicionamiento_1"
    },
    conditioning_2: {
      name: "acondicionamiento_2"
    }
  }
};
const ConditioningConcat$5 = {
  display_name: "Acondicionamiento (Concatenar)",
  inputs: {
    conditioning_from: {
      name: "acondicionamiento_de"
    },
    conditioning_to: {
      name: "acondicionamiento_a"
    }
  }
};
const ConditioningSetArea$5 = {
  display_name: "Acondicionamiento (Establecer Área)",
  inputs: {
    conditioning: {
      name: "acondicionamiento"
    },
    height: {
      name: "alto"
    },
    strength: {
      name: "fuerza"
    },
    width: {
      name: "ancho"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const ConditioningSetAreaPercentage$5 = {
  display_name: "Acondicionamiento (Establecer Área con Porcentaje)",
  inputs: {
    conditioning: {
      name: "acondicionamiento"
    },
    height: {
      name: "alto"
    },
    strength: {
      name: "fuerza"
    },
    width: {
      name: "ancho"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const ConditioningSetAreaPercentageVideo$5 = {
  display_name: "AcondicionamientoEstablecerAreaPorcentajeVideo",
  inputs: {
    conditioning: {
      name: "acondicionamiento"
    },
    height: {
      name: "alto"
    },
    strength: {
      name: "fuerza"
    },
    temporal: {
      name: "temporal"
    },
    width: {
      name: "ancho"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    },
    z: {
      name: "z"
    }
  }
};
const ConditioningSetAreaStrength$5 = {
  display_name: "AcondicionamientoEstablecerFuerzaArea",
  inputs: {
    conditioning: {
      name: "acondicionamiento"
    },
    strength: {
      name: "fuerza"
    }
  }
};
const ConditioningSetDefaultCombine$5 = {
  display_name: "Cond Establecer Combinación Predeterminada",
  inputs: {
    cond: {
      name: "cond"
    },
    cond_DEFAULT: {
      name: "cond_DEFAULT"
    },
    hooks: {
      name: "hooks"
    }
  }
};
const ConditioningSetMask$5 = {
  display_name: "Acondicionamiento (Establecer Máscara)",
  inputs: {
    conditioning: {
      name: "acondicionamiento"
    },
    mask: {
      name: "máscara"
    },
    set_cond_area: {
      name: "establecer_area_cond"
    },
    strength: {
      name: "fuerza"
    }
  }
};
const ConditioningSetProperties$5 = {
  display_name: "Establecer Propiedades Cond",
  inputs: {
    cond_NEW: {
      name: "cond_NEW"
    },
    hooks: {
      name: "ganchos"
    },
    mask: {
      name: "máscara"
    },
    set_cond_area: {
      name: "establecer_area_cond"
    },
    strength: {
      name: "fuerza"
    },
    timesteps: {
      name: "pasos_de_tiempo"
    }
  }
};
const ConditioningSetPropertiesAndCombine$5 = {
  display_name: "Establecer Propiedades Cond Combinar",
  inputs: {
    cond: {
      name: "cond"
    },
    cond_NEW: {
      name: "cond_NEW"
    },
    hooks: {
      name: "ganchos"
    },
    mask: {
      name: "máscara"
    },
    set_cond_area: {
      name: "establecer_area_cond"
    },
    strength: {
      name: "fuerza"
    },
    timesteps: {
      name: "pasos_de_tiempo"
    }
  }
};
const ConditioningSetTimestepRange$5 = {
  display_name: "Establecer Rango de Pasos de Tiempo de Acondicionamiento",
  inputs: {
    conditioning: {
      name: "acondicionamiento"
    },
    end: {
      name: "fin"
    },
    start: {
      name: "inicio"
    }
  }
};
const ConditioningStableAudio$5 = {
  display_name: "Acondicionamiento Audio Estable",
  inputs: {
    negative: {
      name: "negativo"
    },
    positive: {
      name: "positivo"
    },
    seconds_start: {
      name: "segundos_inicio"
    },
    seconds_total: {
      name: "segundos_total"
    }
  },
  outputs: {
    "0": {
      name: "positivo"
    },
    "1": {
      name: "negativo"
    }
  }
};
const ConditioningTimestepsRange$5 = {
  display_name: "Rango de Pasos de Tiempo",
  inputs: {
    end_percent: {
      name: "porcentaje_fin"
    },
    start_percent: {
      name: "porcentaje_inicio"
    }
  },
  outputs: {
    "1": {
      name: "ANTES_DE_RANGO"
    },
    "2": {
      name: "DESPUÉS_DE_RANGO"
    }
  }
};
const ConditioningZeroOut$5 = {
  display_name: "Acondicionamiento Cero",
  inputs: {
    conditioning: {
      name: "acondicionamiento"
    }
  }
};
const ControlNetApply$5 = {
  display_name: "Aplicar ControlNet (ANTIGUO)",
  inputs: {
    conditioning: {
      name: "acondicionamiento"
    },
    control_net: {
      name: "control_net"
    },
    image: {
      name: "imagen"
    },
    strength: {
      name: "fuerza"
    }
  }
};
const ControlNetApplyAdvanced$5 = {
  display_name: "Aplicar ControlNet",
  inputs: {
    control_net: {
      name: "control_net"
    },
    end_percent: {
      name: "porcentaje_fin"
    },
    image: {
      name: "imagen"
    },
    negative: {
      name: "negativo"
    },
    positive: {
      name: "positivo"
    },
    start_percent: {
      name: "porcentaje_inicio"
    },
    strength: {
      name: "fuerza"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "positivo"
    },
    "1": {
      name: "negativo"
    }
  }
};
const ControlNetApplySD3$5 = {
  display_name: "Aplicar Controlnet con VAE",
  inputs: {
    control_net: {
      name: "control_net"
    },
    end_percent: {
      name: "porcentaje_final"
    },
    image: {
      name: "imagen"
    },
    negative: {
      name: "negativo"
    },
    positive: {
      name: "positivo"
    },
    start_percent: {
      name: "porcentaje_inicio"
    },
    strength: {
      name: "fuerza"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "positivo"
    },
    "1": {
      name: "negativo"
    }
  }
};
const ControlNetInpaintingAliMamaApply$5 = {
  display_name: "ControlNetInpaintingAliMamaApply",
  inputs: {
    control_net: {
      name: "control_net"
    },
    end_percent: {
      name: "porcentaje_final"
    },
    image: {
      name: "imagen"
    },
    mask: {
      name: "máscara"
    },
    negative: {
      name: "negativo"
    },
    positive: {
      name: "positivo"
    },
    start_percent: {
      name: "porcentaje_inicio"
    },
    strength: {
      name: "fuerza"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "positivo"
    },
    "1": {
      name: "negativo"
    }
  }
};
const ControlNetLoader$5 = {
  display_name: "Cargar Modelo ControlNet",
  inputs: {
    control_net_name: {
      name: "nombre_control_net"
    }
  }
};
const CosmosImageToVideoLatent$5 = {
  display_name: "CosmosImageToVideoLatent",
  inputs: {
    batch_size: {
      name: "tamaño_lote"
    },
    end_image: {
      name: "imagen_final"
    },
    height: {
      name: "altura"
    },
    length: {
      name: "longitud"
    },
    start_image: {
      name: "imagen_inicio"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "ancho"
    }
  }
};
const CreateHookKeyframe$5 = {
  display_name: "Crear Hook Keyframe",
  inputs: {
    prev_hook_kf: {
      name: "prev_hook_kf"
    },
    start_percent: {
      name: "porcentaje_inicio"
    },
    strength_mult: {
      name: "multiplicador_fuerza"
    }
  },
  outputs: {
    "0": {
      name: "HOOK_KF"
    }
  }
};
const CreateHookKeyframesFromFloats$5 = {
  display_name: "Crear Hook Keyframes Desde Flotantes",
  inputs: {
    end_percent: {
      name: "porcentaje_final"
    },
    floats_strength: {
      name: "fuerza_flotantes"
    },
    prev_hook_kf: {
      name: "prev_hook_kf"
    },
    print_keyframes: {
      name: "imprimir_keyframes"
    },
    start_percent: {
      name: "porcentaje_inicio"
    }
  },
  outputs: {
    "0": {
      name: "HOOK_KF"
    }
  }
};
const CreateHookKeyframesInterpolated$5 = {
  display_name: "Crear Hook Keyframes Interp.",
  inputs: {
    end_percent: {
      name: "end_percent"
    },
    interpolation: {
      name: "interpolación"
    },
    keyframes_count: {
      name: "keyframes_count"
    },
    prev_hook_kf: {
      name: "prev_hook_kf"
    },
    print_keyframes: {
      name: "print_keyframes"
    },
    start_percent: {
      name: "start_percent"
    },
    strength_end: {
      name: "strength_end"
    },
    strength_start: {
      name: "strength_start"
    }
  },
  outputs: {
    "0": {
      name: "HOOK_KF"
    }
  }
};
const CreateHookLora$5 = {
  display_name: "Crear Hook LoRA",
  inputs: {
    lora_name: {
      name: "lora_name"
    },
    prev_hooks: {
      name: "prev_hooks"
    },
    strength_clip: {
      name: "strength_clip"
    },
    strength_model: {
      name: "strength_model"
    }
  }
};
const CreateHookLoraModelOnly$5 = {
  display_name: "Crear Hook LoRA (MO)",
  inputs: {
    lora_name: {
      name: "lora_name"
    },
    prev_hooks: {
      name: "prev_hooks"
    },
    strength_model: {
      name: "strength_model"
    }
  }
};
const CreateHookModelAsLora$5 = {
  display_name: "Crear Hook Model como LoRA",
  inputs: {
    ckpt_name: {
      name: "ckpt_name"
    },
    prev_hooks: {
      name: "prev_hooks"
    },
    strength_clip: {
      name: "strength_clip"
    },
    strength_model: {
      name: "strength_model"
    }
  }
};
const CreateHookModelAsLoraModelOnly$5 = {
  display_name: "Crear Hook Model como LoRA (MO)",
  inputs: {
    ckpt_name: {
      name: "ckpt_name"
    },
    prev_hooks: {
      name: "prev_hooks"
    },
    strength_model: {
      name: "strength_model"
    }
  }
};
const CreateVideo$5 = {
  description: "Crea un video a partir de imágenes.",
  display_name: "Crear video",
  inputs: {
    audio: {
      name: "audio",
      tooltip: "El audio que se añadirá al video."
    },
    fps: {
      name: "fps"
    },
    images: {
      name: "imágenes",
      tooltip: "Las imágenes de las que se creará el video."
    }
  }
};
const CropMask$5 = {
  display_name: "CropMask",
  inputs: {
    height: {
      name: "altura"
    },
    mask: {
      name: "máscara"
    },
    width: {
      name: "ancho"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const DiffControlNetLoader$5 = {
  display_name: "Cargar Modelo ControlNet (diff)",
  inputs: {
    control_net_name: {
      name: "control_net_name"
    },
    model: {
      name: "modelo"
    }
  }
};
const DifferentialDiffusion$5 = {
  display_name: "Difusión Diferencial",
  inputs: {
    model: {
      name: "modelo"
    }
  }
};
const DiffusersLoader$5 = {
  display_name: "Cargador de Difusores",
  inputs: {
    model_path: {
      name: "ruta_del_modelo"
    }
  }
};
const DisableNoise$5 = {
  display_name: "DesactivarRuido"
};
const DualCFGGuider$5 = {
  display_name: "Guía Dual CFG",
  inputs: {
    cfg_cond2_negative: {
      name: "cfg_cond2_negativo"
    },
    cfg_conds: {
      name: "cfg_conds"
    },
    cond1: {
      name: "cond1"
    },
    cond2: {
      name: "cond2"
    },
    model: {
      name: "modelo"
    },
    negative: {
      name: "negativo"
    }
  }
};
const DualCLIPLoader$5 = {
  description: "[Recetas]\n\nsdxl: clip-l, clip-g\nsd3: clip-l, clip-g / clip-l, t5 / clip-g, t5\nflux: clip-l, t5",
  display_name: "DualCLIPLoader",
  inputs: {
    clip_name1: {
      name: "clip_name1"
    },
    clip_name2: {
      name: "clip_name2"
    },
    device: {
      name: "dispositivo"
    },
    type: {
      name: "tipo"
    }
  }
};
const EmptyCosmosLatentVideo$5 = {
  display_name: "EmptyCosmosLatentVideo",
  inputs: {
    batch_size: {
      name: "tamaño_del_lote"
    },
    height: {
      name: "altura"
    },
    length: {
      name: "longitud"
    },
    width: {
      name: "ancho"
    }
  }
};
const EmptyHunyuanLatentVideo$5 = {
  display_name: "EmptyHunyuanLatentVideo",
  inputs: {
    batch_size: {
      name: "tamaño_del_lote"
    },
    height: {
      name: "altura"
    },
    length: {
      name: "longitud"
    },
    width: {
      name: "ancho"
    }
  }
};
const EmptyImage$5 = {
  display_name: "EmptyImage",
  inputs: {
    batch_size: {
      name: "tamaño_del_lote"
    },
    color: {
      name: "color"
    },
    height: {
      name: "altura"
    },
    width: {
      name: "ancho"
    }
  }
};
const EmptyLTXVLatentVideo$5 = {
  display_name: "EmptyLTXVLatentVideo",
  inputs: {
    batch_size: {
      name: "tamaño_del_lote"
    },
    height: {
      name: "altura"
    },
    length: {
      name: "longitud"
    },
    width: {
      name: "ancho"
    }
  }
};
const EmptyLatentAudio$5 = {
  display_name: "EmptyLatentAudio",
  inputs: {
    batch_size: {
      name: "tamaño_del_lote",
      tooltip: "El número de imágenes latentes en el lote."
    },
    seconds: {
      name: "segundos"
    }
  }
};
const EmptyLatentHunyuan3Dv2$5 = {
  display_name: "EmptyLatentHunyuan3Dv2",
  inputs: {
    batch_size: {
      name: "tamaño_del_lote",
      tooltip: "El número de imágenes latentes en el lote."
    },
    resolution: {
      name: "resolución"
    }
  }
};
const EmptyLatentImage$5 = {
  description: "Crea un nuevo lote de imágenes latentes vacías para ser desruidadas mediante muestreo.",
  display_name: "Imagen Latente Vacía",
  inputs: {
    batch_size: {
      name: "tamaño_del_lote",
      tooltip: "El número de imágenes latentes en el lote."
    },
    height: {
      name: "altura",
      tooltip: "La altura de las imágenes latentes en píxeles."
    },
    width: {
      name: "ancho",
      tooltip: "El ancho de las imágenes latentes en píxeles."
    }
  },
  outputs: {
    "0": {
      tooltip: "El lote de imágenes latentes vacías."
    }
  }
};
const EmptyMochiLatentVideo$5 = {
  display_name: "EmptyMochiLatentVideo",
  inputs: {
    batch_size: {
      name: "tamaño_del_lote"
    },
    height: {
      name: "altura"
    },
    length: {
      name: "longitud"
    },
    width: {
      name: "ancho"
    }
  }
};
const EmptySD3LatentImage$5 = {
  display_name: "EmptySD3LatentImage",
  inputs: {
    batch_size: {
      name: "tamaño_del_lote"
    },
    height: {
      name: "altura"
    },
    width: {
      name: "ancho"
    }
  }
};
const ExponentialScheduler$5 = {
  display_name: "ExponentialScheduler",
  inputs: {
    sigma_max: {
      name: "sigma_max"
    },
    sigma_min: {
      name: "sigma_min"
    },
    steps: {
      name: "pasos"
    }
  }
};
const ExtendIntermediateSigmas$5 = {
  display_name: "ExtendIntermediateSigmas",
  inputs: {
    end_at_sigma: {
      name: "terminar_en_sigma"
    },
    sigmas: {
      name: "sigmas"
    },
    spacing: {
      name: "espaciado"
    },
    start_at_sigma: {
      name: "comenzar_en_sigma"
    },
    steps: {
      name: "pasos"
    }
  }
};
const FeatherMask$5 = {
  display_name: "FeatherMask",
  inputs: {
    bottom: {
      name: "abajo"
    },
    left: {
      name: "izquierda"
    },
    mask: {
      name: "máscara"
    },
    right: {
      name: "derecha"
    },
    top: {
      name: "arriba"
    }
  }
};
const FlipSigmas$5 = {
  display_name: "FlipSigmas",
  inputs: {
    sigmas: {
      name: "sigmas"
    }
  }
};
const FluxDisableGuidance$5 = {
  description: "Este nodo desactiva completamente la guía incrustada en Flux y modelos similares a Flux",
  display_name: "FluxDisableGuidance",
  inputs: {
    conditioning: {
      name: "acondicionamiento"
    }
  }
};
const FluxGuidance$5 = {
  display_name: "FluxGuidance",
  inputs: {
    conditioning: {
      name: "acondicionamiento"
    },
    guidance: {
      name: "guía"
    }
  }
};
const FluxProCannyNode$5 = {
  description: "Genera una imagen usando una imagen de control (canny).",
  display_name: "Flux.1 Imagen de Control Canny",
  inputs: {
    canny_high_threshold: {
      name: "canny_high_threshold",
      tooltip: "Umbral alto para la detección de bordes Canny; se ignora si skip_processing es True"
    },
    canny_low_threshold: {
      name: "canny_low_threshold",
      tooltip: "Umbral bajo para la detección de bordes Canny; se ignora si skip_processing es True"
    },
    control_after_generate: {
      name: "control after generate"
    },
    control_image: {
      name: "control_image"
    },
    guidance: {
      name: "guidance",
      tooltip: "Fuerza de la guía para el proceso de generación de la imagen"
    },
    prompt: {
      name: "prompt",
      tooltip: "Prompt para la generación de la imagen"
    },
    prompt_upsampling: {
      name: "prompt_upsampling",
      tooltip: "Indica si se debe realizar upsampling en el prompt. Si está activo, modifica automáticamente el prompt para una generación más creativa, pero los resultados son no deterministas (la misma semilla no producirá exactamente el mismo resultado)."
    },
    seed: {
      name: "seed",
      tooltip: "La semilla aleatoria utilizada para crear el ruido."
    },
    skip_preprocessing: {
      name: "skip_preprocessing",
      tooltip: "Indica si se debe omitir el preprocesamiento; establecer en True si control_image ya está canny-fied, False si es una imagen sin procesar."
    },
    steps: {
      name: "steps",
      tooltip: "Número de pasos para el proceso de generación de la imagen"
    }
  }
};
const FluxProDepthNode$5 = {
  description: "Genera una imagen usando una imagen de control (profundidad).",
  display_name: "Flux.1 Control de Profundidad de Imagen",
  inputs: {
    control_after_generate: {
      name: "control after generate"
    },
    control_image: {
      name: "control_image"
    },
    guidance: {
      name: "guidance",
      tooltip: "Fuerza de la guía para el proceso de generación de imagen"
    },
    prompt: {
      name: "prompt",
      tooltip: "Prompt para la generación de la imagen"
    },
    prompt_upsampling: {
      name: "prompt_upsampling",
      tooltip: "Indica si se realiza upsampling en el prompt. Si está activo, modifica automáticamente el prompt para una generación más creativa, pero los resultados no son deterministas (la misma semilla no producirá exactamente el mismo resultado)."
    },
    seed: {
      name: "seed",
      tooltip: "La semilla aleatoria utilizada para crear el ruido."
    },
    skip_preprocessing: {
      name: "skip_preprocessing",
      tooltip: "Indica si se omite el preprocesamiento; establece en True si control_image ya tiene profundidad, False si es una imagen sin procesar."
    },
    steps: {
      name: "steps",
      tooltip: "Número de pasos para el proceso de generación de imagen"
    }
  }
};
const FluxProExpandNode$5 = {
  description: "Expande la imagen según el prompt.",
  display_name: "Flux.1 Expandir imagen",
  inputs: {
    bottom: {
      name: "abajo",
      tooltip: "Número de píxeles a expandir en la parte inferior de la imagen"
    },
    control_after_generate: {
      name: "control después de generar"
    },
    guidance: {
      name: "guía",
      tooltip: "Fuerza de la guía para el proceso de generación de imagen"
    },
    image: {
      name: "imagen"
    },
    left: {
      name: "izquierda",
      tooltip: "Número de píxeles a expandir en el lado izquierdo de la imagen"
    },
    prompt: {
      name: "prompt",
      tooltip: "Prompt para la generación de la imagen"
    },
    prompt_upsampling: {
      name: "reescaleado de prompt",
      tooltip: "Si se realiza reescaleado en el prompt. Si está activo, modifica automáticamente el prompt para una generación más creativa, pero los resultados son no deterministas (la misma semilla no producirá exactamente el mismo resultado)."
    },
    right: {
      name: "derecha",
      tooltip: "Número de píxeles a expandir en el lado derecho de la imagen"
    },
    seed: {
      name: "semilla",
      tooltip: "La semilla aleatoria utilizada para crear el ruido."
    },
    steps: {
      name: "pasos",
      tooltip: "Número de pasos para el proceso de generación de imagen"
    },
    top: {
      name: "arriba",
      tooltip: "Número de píxeles a expandir en la parte superior de la imagen"
    }
  }
};
const FluxProFillNode$5 = {
  description: "Rellena la imagen según la mask y el prompt.",
  display_name: "Flux.1 Rellenar Imagen",
  inputs: {
    control_after_generate: {
      name: "controlar después de generar"
    },
    guidance: {
      name: "guía",
      tooltip: "Fuerza de la guía para el proceso de generación de imagen"
    },
    image: {
      name: "imagen"
    },
    mask: {
      name: "mask"
    },
    prompt: {
      name: "prompt",
      tooltip: "Prompt para la generación de la imagen"
    },
    prompt_upsampling: {
      name: "re-muestreo de prompt",
      tooltip: "Indica si se realiza re-muestreo en el prompt. Si está activo, modifica automáticamente el prompt para una generación más creativa, pero los resultados no son deterministas (la misma semilla no producirá exactamente el mismo resultado)."
    },
    seed: {
      name: "semilla",
      tooltip: "La semilla aleatoria utilizada para crear el ruido."
    },
    steps: {
      name: "pasos",
      tooltip: "Número de pasos para el proceso de generación de imagen"
    }
  }
};
const FluxProUltraImageNode$5 = {
  description: "Genera imágenes usando Flux Pro 1.1 Ultra vía API basado en el prompt y la resolución.",
  display_name: "Flux 1.1 [pro] Ultra Image",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio",
      tooltip: "Relación de aspecto de la imagen; debe estar entre 1:4 y 4:1."
    },
    control_after_generate: {
      name: "control after generate"
    },
    image_prompt: {
      name: "image_prompt"
    },
    image_prompt_strength: {
      name: "image_prompt_strength",
      tooltip: "Mezcla entre el prompt y el image prompt."
    },
    prompt: {
      name: "prompt",
      tooltip: "Prompt para la generación de la imagen"
    },
    prompt_upsampling: {
      name: "prompt_upsampling",
      tooltip: "Indica si se realiza upsampling en el prompt. Si está activo, modifica automáticamente el prompt para una generación más creativa, pero los resultados son no deterministas (la misma semilla no producirá exactamente el mismo resultado)."
    },
    raw: {
      name: "raw",
      tooltip: "Cuando es Verdadero, genera imágenes menos procesadas y de aspecto más natural."
    },
    seed: {
      name: "seed",
      tooltip: "La semilla aleatoria utilizada para crear el ruido."
    }
  }
};
const FreSca$5 = {
  description: "Aplica un escalado dependiente de la frecuencia a la guía",
  display_name: "FreSca",
  inputs: {
    freq_cutoff: {
      name: "corte_frecuencia",
      tooltip: "Número de índices de frecuencia alrededor del centro a considerar como baja frecuencia"
    },
    model: {
      name: "modelo"
    },
    scale_high: {
      name: "escala_alta",
      tooltip: "Factor de escala para los componentes de alta frecuencia"
    },
    scale_low: {
      name: "escala_baja",
      tooltip: "Factor de escala para los componentes de baja frecuencia"
    }
  }
};
const FreeU$5 = {
  display_name: "FreeU",
  inputs: {
    b1: {
      name: "b1"
    },
    b2: {
      name: "b2"
    },
    model: {
      name: "modelo"
    },
    s1: {
      name: "s1"
    },
    s2: {
      name: "s2"
    }
  }
};
const FreeU_V2$5 = {
  display_name: "FreeU_V2",
  inputs: {
    b1: {
      name: "b1"
    },
    b2: {
      name: "b2"
    },
    model: {
      name: "modelo"
    },
    s1: {
      name: "s1"
    },
    s2: {
      name: "s2"
    }
  }
};
const GITSScheduler$5 = {
  display_name: "GITSScheduler",
  inputs: {
    coeff: {
      name: "coef"
    },
    denoise: {
      name: "denoise"
    },
    steps: {
      name: "pasos"
    }
  }
};
const GLIGENLoader$5 = {
  display_name: "GLIGENLoader",
  inputs: {
    gligen_name: {
      name: "nombre_gligen"
    }
  }
};
const GLIGENTextBoxApply$5 = {
  display_name: "GLIGENTextBoxApply",
  inputs: {
    clip: {
      name: "clip"
    },
    conditioning_to: {
      name: "acondicionamiento_a"
    },
    gligen_textbox_model: {
      name: "modelo_caja_texto_gligen"
    },
    height: {
      name: "altura"
    },
    text: {
      name: "texto"
    },
    width: {
      name: "ancho"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const GetVideoComponents$5 = {
  description: "Extrae todos los componentes de un video: fotogramas, audio y velocidad de fotogramas.",
  display_name: "Obtener componentes de video",
  inputs: {
    video: {
      name: "video",
      tooltip: "El video del que extraer los componentes."
    }
  },
  outputs: {
    "0": {
      name: "imágenes"
    },
    "1": {
      name: "audio"
    },
    "2": {
      name: "fps"
    }
  }
};
const GrowMask$5 = {
  display_name: "GrowMask",
  inputs: {
    expand: {
      name: "expandir"
    },
    mask: {
      name: "máscara"
    },
    tapered_corners: {
      name: "esquinas_afiladas"
    }
  }
};
const Hunyuan3Dv2Conditioning$5 = {
  display_name: "Hunyuan3Dv2Conditioning",
  inputs: {
    clip_vision_output: {
      name: "salida_vision_clip"
    }
  },
  outputs: {
    "0": {
      name: "positivo"
    },
    "1": {
      name: "negativo"
    }
  }
};
const Hunyuan3Dv2ConditioningMultiView$5 = {
  display_name: "Hunyuan3Dv2ConditioningMultiView",
  inputs: {
    back: {
      name: "atrás"
    },
    front: {
      name: "frente"
    },
    left: {
      name: "izquierda"
    },
    right: {
      name: "derecha"
    }
  },
  outputs: {
    "0": {
      name: "positivo"
    },
    "1": {
      name: "negativo"
    }
  }
};
const HunyuanImageToVideo$5 = {
  display_name: "HunyuanImageToVideo",
  inputs: {
    batch_size: {
      name: "tamaño_del_lote"
    },
    guidance_type: {
      name: "tipo_de_orientación"
    },
    height: {
      name: "altura"
    },
    length: {
      name: "longitud"
    },
    positive: {
      name: "positivo"
    },
    start_image: {
      name: "imagen_inicial"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "ancho"
    }
  },
  outputs: {
    "0": {
      name: "positivo"
    },
    "1": {
      name: "latente"
    }
  }
};
const HyperTile$5 = {
  display_name: "HyperTile",
  inputs: {
    max_depth: {
      name: "profundidad_máxima"
    },
    model: {
      name: "modelo"
    },
    scale_depth: {
      name: "escala_de_profundidad"
    },
    swap_size: {
      name: "tamaño_de_intercambio"
    },
    tile_size: {
      name: "tamaño_de_mosaico"
    }
  }
};
const HypernetworkLoader$5 = {
  display_name: "CargadorHypernetwork",
  inputs: {
    hypernetwork_name: {
      name: "nombre_hypernetwork"
    },
    model: {
      name: "modelo"
    },
    strength: {
      name: "fuerza"
    }
  }
};
const IdeogramV1$5 = {
  description: "Genera imágenes de forma sincrónica usando el modelo Ideogram V1.\n\nLos enlaces de las imágenes están disponibles por un período limitado; si deseas conservar la imagen, debes descargarla.",
  display_name: "Ideogram V1",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio",
      tooltip: "La relación de aspecto para la generación de la imagen."
    },
    control_after_generate: {
      name: "control after generate"
    },
    magic_prompt_option: {
      name: "magic_prompt_option",
      tooltip: "Determina si se debe usar MagicPrompt en la generación"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Descripción de lo que se debe excluir de la imagen"
    },
    num_images: {
      name: "num_images"
    },
    prompt: {
      name: "prompt",
      tooltip: "Prompt para la generación de la imagen"
    },
    seed: {
      name: "seed"
    },
    turbo: {
      name: "turbo",
      tooltip: "Indica si se debe usar el modo turbo (generación más rápida, potencialmente menor calidad)"
    }
  }
};
const IdeogramV2$5 = {
  description: "Genera imágenes de forma sincrónica usando el modelo Ideogram V2.\n\nLos enlaces de las imágenes están disponibles por un período limitado; si deseas conservar la imagen, debes descargarla.",
  display_name: "Ideogram V2",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio",
      tooltip: "La relación de aspecto para la generación de la imagen. Se ignora si la resolución no está configurada en AUTO."
    },
    control_after_generate: {
      name: "control after generate"
    },
    magic_prompt_option: {
      name: "magic_prompt_option",
      tooltip: "Determina si se debe usar MagicPrompt en la generación"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Descripción de lo que se debe excluir de la imagen"
    },
    num_images: {
      name: "num_images"
    },
    prompt: {
      name: "prompt",
      tooltip: "Prompt para la generación de la imagen"
    },
    resolution: {
      name: "resolution",
      tooltip: "La resolución para la generación de la imagen. Si no está configurada en AUTO, esto sobrescribe el ajuste de aspect_ratio."
    },
    seed: {
      name: "seed"
    },
    style_type: {
      name: "style_type",
      tooltip: "Tipo de estilo para la generación (solo V2)"
    },
    turbo: {
      name: "turbo",
      tooltip: "Indica si se debe usar el modo turbo (generación más rápida, potencialmente menor calidad)"
    }
  }
};
const IdeogramV3$5 = {
  description: "Genera imágenes de forma síncrona usando el modelo Ideogram V3.\n\nAdmite tanto la generación regular de imágenes a partir de indicaciones de texto como la edición de imágenes con mask.\nLos enlaces de las imágenes están disponibles por un período limitado; si deseas conservar la imagen, debes descargarla.",
  display_name: "Ideogram V3",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio",
      tooltip: "La relación de aspecto para la generación de imagen. Se ignora si la resolución no está en Automático."
    },
    control_after_generate: {
      name: "control after generate"
    },
    image: {
      name: "image",
      tooltip: "Imagen de referencia opcional para la edición de imagen."
    },
    magic_prompt_option: {
      name: "magic_prompt_option",
      tooltip: "Determina si MagicPrompt debe usarse en la generación"
    },
    mask: {
      name: "mask",
      tooltip: "Mask opcional para inpainting (las áreas blancas serán reemplazadas)"
    },
    num_images: {
      name: "num_images"
    },
    prompt: {
      name: "prompt",
      tooltip: "Indicación para la generación o edición de la imagen"
    },
    rendering_speed: {
      name: "rendering_speed",
      tooltip: "Controla el equilibrio entre la velocidad de generación y la calidad"
    },
    resolution: {
      name: "resolution",
      tooltip: "La resolución para la generación de imagen. Si no está en Automático, esto sobrescribe la configuración de aspect_ratio."
    },
    seed: {
      name: "seed"
    }
  }
};
const ImageBatch$5 = {
  display_name: "Lote de Imágenes",
  inputs: {
    image1: {
      name: "imagen1"
    },
    image2: {
      name: "imagen2"
    }
  }
};
const ImageBlend$5 = {
  display_name: "Mezcla de Imágenes",
  inputs: {
    blend_factor: {
      name: "factor_de_mezcla"
    },
    blend_mode: {
      name: "modo_de_mezcla"
    },
    image1: {
      name: "imagen1"
    },
    image2: {
      name: "imagen2"
    }
  }
};
const ImageBlur$5 = {
  display_name: "Desenfoque de Imagen",
  inputs: {
    blur_radius: {
      name: "radio_de_desenfoque"
    },
    image: {
      name: "imagen"
    },
    sigma: {
      name: "sigma"
    }
  }
};
const ImageColorToMask$5 = {
  display_name: "ImageColorToMask",
  inputs: {
    color: {
      name: "color"
    },
    image: {
      name: "imagen"
    }
  }
};
const ImageCompositeMasked$5 = {
  display_name: "ImageCompositeMasked",
  inputs: {
    destination: {
      name: "destino"
    },
    mask: {
      name: "máscara"
    },
    resize_source: {
      name: "redimensionar_fuente"
    },
    source: {
      name: "fuente"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const ImageCrop$5 = {
  display_name: "Recorte de Imagen",
  inputs: {
    height: {
      name: "altura"
    },
    image: {
      name: "imagen"
    },
    width: {
      name: "ancho"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const ImageFromBatch$5 = {
  display_name: "ImagenDeLote",
  inputs: {
    batch_index: {
      name: "indice_lote"
    },
    image: {
      name: "imagen"
    },
    length: {
      name: "longitud"
    }
  }
};
const ImageInvert$5 = {
  display_name: "Invertir Imagen",
  inputs: {
    image: {
      name: "imagen"
    }
  }
};
const ImageOnlyCheckpointLoader$5 = {
  display_name: "Cargador de Puntos de Control Solo de Imagen (modelo img2vid)",
  inputs: {
    ckpt_name: {
      name: "nombre_ckpt"
    }
  }
};
const ImageOnlyCheckpointSave$5 = {
  display_name: "GuardarPuntoDeControlSoloDeImagen",
  inputs: {
    clip_vision: {
      name: "clip_vision"
    },
    filename_prefix: {
      name: "prefijo_nombre_archivo"
    },
    model: {
      name: "modelo"
    },
    vae: {
      name: "vae"
    }
  }
};
const ImagePadForOutpaint$5 = {
  display_name: "Rellenar Imagen para Pintar Fuera",
  inputs: {
    bottom: {
      name: "abajo"
    },
    feathering: {
      name: "difuminado"
    },
    image: {
      name: "imagen"
    },
    left: {
      name: "izquierda"
    },
    right: {
      name: "derecha"
    },
    top: {
      name: "arriba"
    }
  }
};
const ImageQuantize$5 = {
  display_name: "Cuantizar Imagen",
  inputs: {
    colors: {
      name: "colores"
    },
    dither: {
      name: "difuminado"
    },
    image: {
      name: "imagen"
    }
  }
};
const ImageRGBToYUV$5 = {
  display_name: "ImageRGBToYUV",
  inputs: {
    image: {
      name: "imagen"
    }
  },
  outputs: {
    "0": {
      name: "Y"
    },
    "1": {
      name: "U"
    },
    "2": {
      name: "V"
    }
  }
};
const ImageScale$5 = {
  display_name: "Ampliar Imagen",
  inputs: {
    crop: {
      name: "recorte"
    },
    height: {
      name: "altura"
    },
    image: {
      name: "imagen"
    },
    upscale_method: {
      name: "metodo_ampliacion"
    },
    width: {
      name: "ancho"
    }
  }
};
const ImageScaleBy$5 = {
  display_name: "Ampliar Imagen Por",
  inputs: {
    image: {
      name: "imagen"
    },
    scale_by: {
      name: "escalar_por"
    },
    upscale_method: {
      name: "metodo_ampliacion"
    }
  }
};
const ImageScaleToTotalPixels$5 = {
  display_name: "Escalar Imagen a Total de Pixeles",
  inputs: {
    image: {
      name: "imagen"
    },
    megapixels: {
      name: "megapixeles"
    },
    upscale_method: {
      name: "metodo_ampliacion"
    }
  }
};
const ImageSharpen$5 = {
  display_name: "Afinar Imagen",
  inputs: {
    alpha: {
      name: "alfa"
    },
    image: {
      name: "imagen"
    },
    sharpen_radius: {
      name: "radio_afinado"
    },
    sigma: {
      name: "sigma"
    }
  }
};
const ImageToMask$5 = {
  display_name: "Convertir Imagen a Máscara",
  inputs: {
    channel: {
      name: "canal"
    },
    image: {
      name: "imagen"
    }
  }
};
const ImageUpscaleWithModel$5 = {
  display_name: "Ampliar Imagen (usando Modelo)",
  inputs: {
    image: {
      name: "imagen"
    },
    upscale_model: {
      name: "modelo_ampliacion"
    }
  }
};
const ImageYUVToRGB$5 = {
  display_name: "ImageYUVToRGB",
  inputs: {
    U: {
      name: "U"
    },
    V: {
      name: "V"
    },
    Y: {
      name: "Y"
    }
  }
};
const InpaintModelConditioning$5 = {
  display_name: "InpaintModelConditioning",
  inputs: {
    mask: {
      name: "máscara"
    },
    negative: {
      name: "negativo"
    },
    noise_mask: {
      name: "máscara de ruido",
      tooltip: "Agrega una máscara de ruido al latente para que el muestreo solo ocurra dentro de la máscara. Puede mejorar los resultados o romper completamente las cosas dependiendo del modelo."
    },
    pixels: {
      name: "píxeles"
    },
    positive: {
      name: "positivo"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "positivo"
    },
    "1": {
      name: "negativo"
    },
    "2": {
      name: "latente"
    }
  }
};
const InstructPixToPixConditioning$5 = {
  display_name: "InstructPixToPixConditioning",
  inputs: {
    negative: {
      name: "negativo"
    },
    pixels: {
      name: "píxeles"
    },
    positive: {
      name: "positivo"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "positivo"
    },
    "1": {
      name: "negativo"
    },
    "2": {
      name: "latente"
    }
  }
};
const InvertMask$5 = {
  display_name: "InvertirMáscara",
  inputs: {
    mask: {
      name: "máscara"
    }
  }
};
const JoinImageWithAlpha$5 = {
  display_name: "Unir Imagen con Alfa",
  inputs: {
    alpha: {
      name: "alfa"
    },
    image: {
      name: "imagen"
    }
  }
};
const KSampler$5 = {
  description: "Utiliza el modelo proporcionado, el acondicionamiento positivo y negativo para deshacer el ruido de la imagen latente.",
  display_name: "KSampler",
  inputs: {
    cfg: {
      name: "cfg",
      tooltip: "La escala de Orientación Libre de Clasificador equilibra la creatividad y la adherencia al indicador. Los valores más altos resultan en imágenes que se asemejan más al indicador, sin embargo, valores demasiado altos afectarán negativamente la calidad."
    },
    control_after_generate: {
      name: "control después de generar"
    },
    denoise: {
      name: "deshacer_ruido",
      tooltip: "La cantidad de eliminación de ruido aplicada, los valores más bajos mantendrán la estructura de la imagen inicial permitiendo el muestreo de imagen a imagen."
    },
    latent_image: {
      name: "imagen_latente",
      tooltip: "La imagen latente a deshacer el ruido."
    },
    model: {
      name: "modelo",
      tooltip: "El modelo utilizado para eliminar el ruido de la entrada latente."
    },
    negative: {
      name: "negativo",
      tooltip: "El acondicionamiento que describe los atributos que quieres excluir de la imagen."
    },
    positive: {
      name: "positivo",
      tooltip: "El acondicionamiento que describe los atributos que quieres incluir en la imagen."
    },
    sampler_name: {
      name: "nombre_muestreador",
      tooltip: "El algoritmo utilizado al muestrear, esto puede afectar la calidad, velocidad y estilo de la salida generada."
    },
    scheduler: {
      name: "programador",
      tooltip: "El programador controla cómo se elimina gradualmente el ruido para formar la imagen."
    },
    seed: {
      name: "semilla",
      tooltip: "La semilla aleatoria utilizada para crear el ruido."
    },
    steps: {
      name: "pasos",
      tooltip: "El número de pasos utilizados en el proceso de eliminación de ruido."
    }
  },
  outputs: {
    "0": {
      tooltip: "El latente deshacer el ruido."
    }
  }
};
const KSamplerAdvanced$5 = {
  display_name: "KSampler (Avanzado)",
  inputs: {
    add_noise: {
      name: "añadir_ruido"
    },
    cfg: {
      name: "cfg"
    },
    control_after_generate: {
      name: "control_después_de_generar"
    },
    end_at_step: {
      name: "terminar_en_paso"
    },
    latent_image: {
      name: "imagen_latente"
    },
    model: {
      name: "modelo"
    },
    negative: {
      name: "negativo"
    },
    noise_seed: {
      name: "semilla_de_ruido"
    },
    positive: {
      name: "positivo"
    },
    return_with_leftover_noise: {
      name: "devolver_con_ruido_sobrante"
    },
    sampler_name: {
      name: "nombre_del_muestreador"
    },
    scheduler: {
      name: "programador"
    },
    start_at_step: {
      name: "comenzar_en_paso"
    },
    steps: {
      name: "pasos"
    }
  }
};
const KSamplerSelect$5 = {
  display_name: "KSamplerSelect",
  inputs: {
    sampler_name: {
      name: "nombre_del_muestreador"
    }
  }
};
const KarrasScheduler$5 = {
  display_name: "KarrasScheduler",
  inputs: {
    rho: {
      name: "rho"
    },
    sigma_max: {
      name: "sigma_max"
    },
    sigma_min: {
      name: "sigma_min"
    },
    steps: {
      name: "pasos"
    }
  }
};
const KlingCameraControlI2VNode$5 = {
  description: "Transforma imágenes fijas en videos cinematográficos con movimientos de cámara profesionales que simulan la cinematografía del mundo real. Controla acciones de cámara virtual como zoom, rotación, paneo, inclinación y vista en primera persona, manteniendo el enfoque en tu imagen original.",
  display_name: "Kling Imagen a Video (Control de Cámara)",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio"
    },
    camera_control: {
      name: "camera_control",
      tooltip: "Puede ser creado usando el nodo Kling Camera Controls. Controla el movimiento y la acción de la cámara durante la generación del video."
    },
    cfg_scale: {
      name: "cfg_scale"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Prompt de texto negativo"
    },
    prompt: {
      name: "prompt",
      tooltip: "Prompt de texto positivo"
    },
    start_frame: {
      name: "start_frame",
      tooltip: "Imagen de referencia - URL o cadena codificada en Base64, no puede exceder los 10MB, resolución no menor a 300*300px, relación de aspecto entre 1:2.5 ~ 2.5:1. Base64 no debe incluir el prefijo data:image."
    }
  },
  outputs: {
    "1": {
      name: "video_id"
    },
    "2": {
      name: "duration"
    }
  }
};
const KlingCameraControlT2VNode$5 = {
  description: "Transforma texto en videos cinematográficos con movimientos de cámara profesionales que simulan la cinematografía del mundo real. Controla acciones de cámara virtual como zoom, rotación, paneo, inclinación y vista en primera persona, manteniendo el enfoque en tu texto original.",
  display_name: "Kling Texto a Video (Control de Cámara)",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio"
    },
    camera_control: {
      name: "camera_control",
      tooltip: "Puede ser creado usando el nodo Kling Camera Controls. Controla el movimiento y la acción de la cámara durante la generación del video."
    },
    cfg_scale: {
      name: "cfg_scale"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Prompt de texto negativo"
    },
    prompt: {
      name: "prompt",
      tooltip: "Prompt de texto positivo"
    }
  },
  outputs: {
    "1": {
      name: "video_id"
    },
    "2": {
      name: "duration"
    }
  }
};
const KlingCameraControls$5 = {
  description: "Permite especificar opciones de configuración para los Controles de Cámara Kling y efectos de control de movimiento.",
  display_name: "Controles de Cámara Kling",
  inputs: {
    camera_control_type: {
      name: "camera_control_type"
    },
    horizontal_movement: {
      name: "horizontal_movement",
      tooltip: "Controla el movimiento de la cámara a lo largo del eje horizontal (eje x). Negativo indica izquierda, positivo indica derecha."
    },
    pan: {
      name: "pan",
      tooltip: "Controla la rotación de la cámara en el plano vertical (eje x). Negativo indica rotación hacia abajo, positivo indica rotación hacia arriba."
    },
    roll: {
      name: "roll",
      tooltip: "Controla la cantidad de giro de la cámara (eje z). Negativo indica sentido antihorario, positivo indica sentido horario."
    },
    tilt: {
      name: "tilt",
      tooltip: "Controla la rotación de la cámara en el plano horizontal (eje y). Negativo indica rotación hacia la izquierda, positivo indica rotación hacia la derecha."
    },
    vertical_movement: {
      name: "vertical_movement",
      tooltip: "Controla el movimiento de la cámara a lo largo del eje vertical (eje y). Negativo indica hacia abajo, positivo indica hacia arriba."
    },
    zoom: {
      name: "zoom",
      tooltip: "Controla el cambio en la distancia focal de la cámara. Negativo indica un campo de visión más estrecho, positivo indica un campo de visión más amplio."
    }
  },
  outputs: {
    "0": {
      name: "camera_control"
    }
  }
};
const KlingDualCharacterVideoEffectNode$5 = {
  description: "Logra diferentes efectos especiales al generar un video basado en el effect_scene. La primera imagen se posicionará en el lado izquierdo y la segunda en el lado derecho de la composición.",
  display_name: "Efectos de Video de Doble Personaje Kling",
  inputs: {
    duration: {
      name: "duración"
    },
    effect_scene: {
      name: "effect_scene"
    },
    image_left: {
      name: "imagen_izquierda",
      tooltip: "Imagen del lado izquierdo"
    },
    image_right: {
      name: "imagen_derecha",
      tooltip: "Imagen del lado derecho"
    },
    mode: {
      name: "modo"
    },
    model_name: {
      name: "model_name"
    }
  },
  outputs: {
    "1": {
      name: "duración"
    }
  }
};
const KlingImage2VideoNode$5 = {
  description: "Nodo Kling Imagen a Video",
  display_name: "Kling Imagen a Video",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio"
    },
    cfg_scale: {
      name: "cfg_scale"
    },
    duration: {
      name: "duration"
    },
    mode: {
      name: "mode"
    },
    model_name: {
      name: "model_name"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Prompt de texto negativo"
    },
    prompt: {
      name: "prompt",
      tooltip: "Prompt de texto positivo"
    },
    start_frame: {
      name: "start_frame",
      tooltip: "Imagen de referencia - URL o cadena codificada en Base64, no puede exceder los 10MB, resolución no menor a 300*300px, relación de aspecto entre 1:2.5 ~ 2.5:1. El Base64 no debe incluir el prefijo data:image."
    }
  },
  outputs: {
    "1": {
      name: "video_id"
    },
    "2": {
      name: "duration"
    }
  }
};
const KlingImageGenerationNode$5 = {
  description: "Nodo de Generación de Imágenes Kling. Genera una imagen a partir de un prompt de texto con una imagen de referencia opcional.",
  display_name: "Generación de Imágenes Kling",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio"
    },
    human_fidelity: {
      name: "human_fidelity",
      tooltip: "Similitud de referencia del sujeto"
    },
    image: {
      name: "image"
    },
    image_fidelity: {
      name: "image_fidelity",
      tooltip: "Intensidad de referencia para imágenes subidas por el usuario"
    },
    image_type: {
      name: "image_type"
    },
    model_name: {
      name: "model_name"
    },
    n: {
      name: "n",
      tooltip: "Número de imágenes generadas"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Prompt de texto negativo"
    },
    prompt: {
      name: "prompt",
      tooltip: "Prompt de texto positivo"
    }
  }
};
const KlingLipSyncAudioToVideoNode$5 = {
  description: "Nodo de Sincronización Labial Kling de Audio a Video. Sincroniza los movimientos de la boca en un archivo de video con el contenido de audio de un archivo de audio.",
  display_name: "Sincronización Labial Kling: Video con Audio",
  inputs: {
    audio: {
      name: "audio"
    },
    video: {
      name: "video"
    },
    voice_language: {
      name: "idioma_de_voz"
    }
  },
  outputs: {
    "1": {
      name: "id_de_video"
    },
    "2": {
      name: "duración"
    }
  }
};
const KlingLipSyncTextToVideoNode$5 = {
  description: "Nodo Kling Lip Sync de Texto a Video. Sincroniza los movimientos de la boca en un archivo de video con un texto.",
  display_name: "Sincronización Labial Kling Video con Texto",
  inputs: {
    text: {
      name: "texto",
      tooltip: "Contenido de texto para la generación de video con sincronización labial. Requerido cuando el modo es text2video. La longitud máxima es de 120 caracteres."
    },
    video: {
      name: "video"
    },
    voice: {
      name: "voz"
    },
    voice_speed: {
      name: "velocidad_de_voz",
      tooltip: "Velocidad del habla. Rango válido: 0.8~2.0, con una cifra decimal."
    }
  },
  outputs: {
    "1": {
      name: "id_video"
    },
    "2": {
      name: "duración"
    }
  }
};
const KlingSingleImageVideoEffectNode$5 = {
  description: "Logra diferentes efectos especiales al generar un video basado en el effect_scene.",
  display_name: "Efectos de Video Kling",
  inputs: {
    duration: {
      name: "duración"
    },
    effect_scene: {
      name: "effect_scene"
    },
    image: {
      name: "imagen",
      tooltip: "Imagen de referencia. URL o cadena codificada en Base64 (sin el prefijo data:image). El tamaño del archivo no puede exceder los 10MB, la resolución no debe ser menor a 300*300px, y la relación de aspecto debe estar entre 1:2.5 y 2.5:1"
    },
    model_name: {
      name: "model_name"
    }
  },
  outputs: {
    "1": {
      name: "video_id"
    },
    "2": {
      name: "duración"
    }
  }
};
const KlingStartEndFrameNode$5 = {
  description: "Genera una secuencia de video que transiciona entre las imágenes inicial y final proporcionadas. El nodo crea todos los fotogramas intermedios, produciendo una transformación suave desde el primer fotograma hasta el último.",
  display_name: "Kling Fotograma Inicial-Final a Video",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio"
    },
    cfg_scale: {
      name: "cfg_scale"
    },
    end_frame: {
      name: "end_frame",
      tooltip: "Imagen de referencia - Control del fotograma final. URL o cadena codificada en Base64, no puede exceder los 10MB, resolución no menor a 300*300px. El Base64 no debe incluir el prefijo data:image."
    },
    mode: {
      name: "mode",
      tooltip: "La configuración a usar para la generación de video siguiendo el formato: modo / duración / nombre_del_modelo."
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Prompt de texto negativo"
    },
    prompt: {
      name: "prompt",
      tooltip: "Prompt de texto positivo"
    },
    start_frame: {
      name: "start_frame",
      tooltip: "Imagen de referencia - URL o cadena codificada en Base64, no puede exceder los 10MB, resolución no menor a 300*300px, relación de aspecto entre 1:2.5 ~ 2.5:1. El Base64 no debe incluir el prefijo data:image."
    }
  },
  outputs: {
    "1": {
      name: "video_id"
    },
    "2": {
      name: "duration"
    }
  }
};
const KlingTextToVideoNode$5 = {
  description: "Nodo Kling Texto a Video",
  display_name: "Kling Texto a Video",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio"
    },
    cfg_scale: {
      name: "cfg_scale"
    },
    mode: {
      name: "mode",
      tooltip: "La configuración a usar para la generación de video siguiendo el formato: modo / duración / nombre_del_modelo."
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Prompt de texto negativo"
    },
    prompt: {
      name: "prompt",
      tooltip: "Prompt de texto positivo"
    }
  },
  outputs: {
    "1": {
      name: "video_id"
    },
    "2": {
      name: "duration"
    }
  }
};
const KlingVideoExtendNode$5 = {
  description: "Nodo Kling Video Extend. Extiende videos creados por otros nodos Kling. El video_id se crea utilizando otros nodos Kling.",
  display_name: "Kling Video Extend",
  inputs: {
    cfg_scale: {
      name: "cfg_scale"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Prompt de texto negativo para los elementos a evitar en el video extendido"
    },
    prompt: {
      name: "prompt",
      tooltip: "Prompt de texto positivo para guiar la extensión del video"
    },
    video_id: {
      name: "video_id",
      tooltip: "El ID del video a extender. Soporta videos generados por texto a video, imagen a video y operaciones previas de extensión de video. No puede exceder los 3 minutos de duración total después de la extensión."
    }
  },
  outputs: {
    "1": {
      name: "video_id"
    },
    "2": {
      name: "duration"
    }
  }
};
const KlingVirtualTryOnNode$5 = {
  description: "Nodo Kling Virtual Try On. Ingresa una imagen de una persona y una imagen de una prenda para probar la prenda en la persona.",
  display_name: "Kling Virtual Try On",
  inputs: {
    cloth_image: {
      name: "cloth_image"
    },
    human_image: {
      name: "human_image"
    },
    model_name: {
      name: "model_name"
    }
  }
};
const LTXVAddGuide$5 = {
  display_name: "LTXVAddGuide",
  inputs: {
    frame_idx: {
      name: "indice_fotograma",
      tooltip: "Índice de fotograma para comenzar la condición. Para imágenes de un solo fotograma o videos con 1-8 fotogramas, cualquier valor de indice_fotograma es aceptable. Para videos con 9+ fotogramas, indice_fotograma debe ser divisible por 8, de lo contrario se redondeará hacia abajo al múltiplo de 8 más cercano. Los valores negativos se cuentan desde el final del video."
    },
    image: {
      name: "imagen",
      tooltip: "Imagen o video para condicionar el video latente. Debe ser 8*n + 1 fotogramas. Si el video no es 8*n + 1 fotogramas, se recortará a los 8*n + 1 fotogramas más cercanos."
    },
    latent: {
      name: "latente"
    },
    negative: {
      name: "negativo"
    },
    positive: {
      name: "positivo"
    },
    strength: {
      name: "fuerza"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "positivo"
    },
    "1": {
      name: "negativo"
    },
    "2": {
      name: "latente"
    }
  }
};
const LTXVConditioning$5 = {
  display_name: "LTXVConditioning",
  inputs: {
    frame_rate: {
      name: "tasa_fotogramas"
    },
    negative: {
      name: "negativo"
    },
    positive: {
      name: "positivo"
    }
  },
  outputs: {
    "0": {
      name: "positivo"
    },
    "1": {
      name: "negativo"
    }
  }
};
const LTXVCropGuides$5 = {
  display_name: "LTXVCropGuides",
  inputs: {
    latent: {
      name: "latente"
    },
    negative: {
      name: "negativo"
    },
    positive: {
      name: "positivo"
    }
  },
  outputs: {
    "0": {
      name: "positivo"
    },
    "1": {
      name: "negativo"
    },
    "2": {
      name: "latente"
    }
  }
};
const LTXVImgToVideo$5 = {
  display_name: "LTXVImgToVideo",
  inputs: {
    batch_size: {
      name: "tamaño_lote"
    },
    height: {
      name: "altura"
    },
    image: {
      name: "imagen"
    },
    length: {
      name: "longitud"
    },
    negative: {
      name: "negativo"
    },
    positive: {
      name: "positivo"
    },
    strength: {
      name: "fuerza"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "ancho"
    }
  },
  outputs: {
    "0": {
      name: "positivo"
    },
    "1": {
      name: "negativo"
    },
    "2": {
      name: "latente"
    }
  }
};
const LTXVPreprocess$5 = {
  display_name: "LTXVPreprocesar",
  inputs: {
    image: {
      name: "imagen"
    },
    img_compression: {
      name: "img_compresion",
      tooltip: "Cantidad de compresión para aplicar en la imagen."
    }
  },
  outputs: {
    "0": {
      name: "imagen_salida"
    }
  }
};
const LTXVScheduler$5 = {
  display_name: "LTXVProgramador",
  inputs: {
    base_shift: {
      name: "base_desplazamiento"
    },
    latent: {
      name: "latente"
    },
    max_shift: {
      name: "max_desplazamiento"
    },
    steps: {
      name: "pasos"
    },
    stretch: {
      name: "estiramiento",
      tooltip: "Estira las sigmas para estar en el rango [terminal, 1]."
    },
    terminal: {
      name: "terminal",
      tooltip: "El valor terminal de las sigmas después del estiramiento."
    }
  }
};
const LaplaceScheduler$5 = {
  display_name: "LaplaceScheduler",
  inputs: {
    beta: {
      name: "beta"
    },
    mu: {
      name: "mu"
    },
    sigma_max: {
      name: "sigma_max"
    },
    sigma_min: {
      name: "sigma_min"
    },
    steps: {
      name: "pasos"
    }
  }
};
const LatentAdd$5 = {
  display_name: "LatentAdd",
  inputs: {
    samples1: {
      name: "muestras1"
    },
    samples2: {
      name: "muestras2"
    }
  }
};
const LatentApplyOperation$5 = {
  display_name: "LatentApplyOperation",
  inputs: {
    operation: {
      name: "operación"
    },
    samples: {
      name: "muestras"
    }
  }
};
const LatentApplyOperationCFG$5 = {
  display_name: "LatentApplyOperationCFG",
  inputs: {
    model: {
      name: "modelo"
    },
    operation: {
      name: "operación"
    }
  }
};
const LatentBatch$5 = {
  display_name: "LatentBatch",
  inputs: {
    samples1: {
      name: "muestras1"
    },
    samples2: {
      name: "muestras2"
    }
  }
};
const LatentBatchSeedBehavior$5 = {
  display_name: "LatentBatchSeedBehavior",
  inputs: {
    samples: {
      name: "muestras"
    },
    seed_behavior: {
      name: "comportamiento_de_semilla"
    }
  }
};
const LatentBlend$5 = {
  display_name: "Mezcla Latente",
  inputs: {
    blend_factor: {
      name: "factor_de_mezcla"
    },
    samples1: {
      name: "muestras1"
    },
    samples2: {
      name: "muestras2"
    }
  }
};
const LatentComposite$5 = {
  display_name: "Compuesto Latente",
  inputs: {
    feather: {
      name: "pluma"
    },
    samples_from: {
      name: "muestras_de"
    },
    samples_to: {
      name: "muestras_a"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const LatentCompositeMasked$5 = {
  display_name: "CompuestoLatenteEnmascarado",
  inputs: {
    destination: {
      name: "destino"
    },
    mask: {
      name: "máscara"
    },
    resize_source: {
      name: "redimensionar_fuente"
    },
    source: {
      name: "fuente"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const LatentCrop$5 = {
  display_name: "Recortar Latente",
  inputs: {
    height: {
      name: "altura"
    },
    samples: {
      name: "muestras"
    },
    width: {
      name: "ancho"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const LatentFlip$5 = {
  display_name: "Voltear Latente",
  inputs: {
    flip_method: {
      name: "método_volteo"
    },
    samples: {
      name: "muestras"
    }
  }
};
const LatentFromBatch$5 = {
  display_name: "Latente De Lote",
  inputs: {
    batch_index: {
      name: "índice_lote"
    },
    length: {
      name: "longitud"
    },
    samples: {
      name: "muestras"
    }
  }
};
const LatentInterpolate$5 = {
  display_name: "Interpolar Latente",
  inputs: {
    ratio: {
      name: "proporción"
    },
    samples1: {
      name: "muestras1"
    },
    samples2: {
      name: "muestras2"
    }
  }
};
const LatentMultiply$5 = {
  display_name: "Multiplicar Latente",
  inputs: {
    multiplier: {
      name: "multiplicador"
    },
    samples: {
      name: "muestras"
    }
  }
};
const LatentOperationSharpen$5 = {
  display_name: "OperaciónAfiladoLatente",
  inputs: {
    alpha: {
      name: "alfa"
    },
    sharpen_radius: {
      name: "radio_afilado"
    },
    sigma: {
      name: "sigma"
    }
  }
};
const LatentOperationTonemapReinhard$5 = {
  display_name: "OperaciónTonemapReinhardLatente",
  inputs: {
    multiplier: {
      name: "multiplicador"
    }
  }
};
const LatentRotate$5 = {
  display_name: "Rotar Latente",
  inputs: {
    rotation: {
      name: "rotación"
    },
    samples: {
      name: "muestras"
    }
  }
};
const LatentSubtract$5 = {
  display_name: "Restar Latente",
  inputs: {
    samples1: {
      name: "muestras1"
    },
    samples2: {
      name: "muestras2"
    }
  }
};
const LatentUpscale$5 = {
  display_name: "Escalar Latente",
  inputs: {
    crop: {
      name: "recorte"
    },
    height: {
      name: "altura"
    },
    samples: {
      name: "muestras"
    },
    upscale_method: {
      name: "método_escala"
    },
    width: {
      name: "ancho"
    }
  }
};
const LatentUpscaleBy$5 = {
  display_name: "Escalar Latente Por",
  inputs: {
    samples: {
      name: "muestras"
    },
    scale_by: {
      name: "escalar_por"
    },
    upscale_method: {
      name: "método_escala"
    }
  }
};
const Load3D$5 = {
  display_name: "Cargar 3D",
  inputs: {
    clear: {},
    height: {
      name: "altura"
    },
    image: {
      name: "imagen"
    },
    model_file: {
      name: "archivo_modelo"
    },
    "upload 3d model": {},
    width: {
      name: "ancho"
    }
  },
  outputs: [
    null,
    null,
    null,
    {
      name: "normal"
    },
    {
      name: "lineart"
    },
    {
      name: "camera_info"
    }
  ]
};
const Load3DAnimation$5 = {
  display_name: "Cargar 3D - Animación",
  inputs: {
    clear: {},
    height: {
      name: "altura"
    },
    image: {
      name: "imagen"
    },
    model_file: {
      name: "archivo_modelo"
    },
    "upload 3d model": {},
    width: {
      name: "ancho"
    }
  },
  outputs: [
    null,
    null,
    null,
    {
      name: "normal"
    },
    {
      name: "camera_info"
    }
  ]
};
const LoadAudio$5 = {
  display_name: "CargarAudio",
  inputs: {
    audio: {
      name: "audio"
    },
    audioUI: {
      name: "audioUI"
    },
    upload: {
      name: "elige archivo para subir"
    }
  }
};
const LoadImage$5 = {
  display_name: "Cargar Imagen",
  inputs: {
    image: {
      name: "imagen"
    },
    upload: {
      name: "elige archivo para subir"
    }
  }
};
const LoadImageMask$5 = {
  display_name: "Cargar Imagen (como Máscara)",
  inputs: {
    channel: {
      name: "canal"
    },
    image: {
      name: "imagen"
    },
    upload: {
      name: "elige archivo para subir"
    }
  }
};
const LoadImageOutput$5 = {
  description: "Carga una imagen desde la carpeta de salida. Cuando se hace clic en el botón de actualizar, el nodo actualizará la lista de imágenes y seleccionará automáticamente la primera imagen, permitiendo una fácil iteración.",
  display_name: "Cargar Imagen (desde Salidas)",
  inputs: {
    image: {
      name: "imagen"
    },
    refresh: {},
    upload: {
      name: "elige archivo para subir"
    }
  }
};
const LoadLatent$5 = {
  display_name: "CargarLatente",
  inputs: {
    latent: {
      name: "latente"
    }
  }
};
const LoadVideo$5 = {
  display_name: "Cargar video",
  inputs: {
    file: {
      name: "archivo"
    },
    upload: {
      name: "elegir archivo para subir"
    }
  }
};
const LoraLoader$5 = {
  description: "Las LoRAs se utilizan para modificar los modelos de difusión y CLIP, alterando la forma en que se desruidan los latentes, como la aplicación de estilos. Se pueden vincular varios nodos de LoRA.",
  display_name: "Cargar LoRA",
  inputs: {
    clip: {
      name: "clip",
      tooltip: "El modelo CLIP al que se aplicará la LoRA."
    },
    lora_name: {
      name: "nombre_lora",
      tooltip: "El nombre de la LoRA."
    },
    model: {
      name: "modelo",
      tooltip: "El modelo de difusión al que se aplicará la LoRA."
    },
    strength_clip: {
      name: "fuerza_clip",
      tooltip: "Cuánto modificar el modelo CLIP. Este valor puede ser negativo."
    },
    strength_model: {
      name: "fuerza_modelo",
      tooltip: "Cuánto modificar el modelo de difusión. Este valor puede ser negativo."
    }
  },
  outputs: {
    "0": {
      tooltip: "El modelo de difusión modificado."
    },
    "1": {
      tooltip: "El modelo CLIP modificado."
    }
  }
};
const LoraLoaderModelOnly$5 = {
  description: "Las LoRAs se utilizan para modificar los modelos de difusión y CLIP, alterando la forma en que se desruidan los latentes, como la aplicación de estilos. Se pueden vincular varios nodos de LoRA.",
  display_name: "CargadorLoRAModeloSolo",
  inputs: {
    lora_name: {
      name: "nombre_lora"
    },
    model: {
      name: "modelo"
    },
    strength_model: {
      name: "fuerza_modelo"
    }
  },
  outputs: {
    "0": {
      tooltip: "El modelo de difusión modificado."
    }
  }
};
const LoraSave$5 = {
  display_name: "Extraer y Guardar Lora",
  inputs: {
    bias_diff: {
      name: "diferencia_sesgo"
    },
    filename_prefix: {
      name: "prefijo_nombre_archivo"
    },
    lora_type: {
      name: "tipo_lora"
    },
    model_diff: {
      name: "diferencia_modelo",
      tooltip: "La salida de ModelSubtract para ser convertida a una lora."
    },
    rank: {
      name: "rango"
    },
    text_encoder_diff: {
      name: "diferencia_codificador_texto",
      tooltip: "La salida de CLIPSubtract para ser convertida a una lora."
    }
  }
};
const LotusConditioning$5 = {
  display_name: "LotusConditioning",
  outputs: {
    "0": {
      name: "condicionamiento"
    }
  }
};
const LumaConceptsNode$5 = {
  description: "Contiene uno o más Conceptos de Cámara para usar con los nodos Luma Text to Video y Luma Image to Video.",
  display_name: "Luma Concepts",
  inputs: {
    concept1: {
      name: "concept1"
    },
    concept2: {
      name: "concept2"
    },
    concept3: {
      name: "concept3"
    },
    concept4: {
      name: "concept4"
    },
    luma_concepts: {
      name: "luma_concepts",
      tooltip: "Conceptos de Cámara opcionales para añadir a los seleccionados aquí."
    }
  },
  outputs: {
    "0": {
      name: "luma_concepts"
    }
  }
};
const LumaImageModifyNode$5 = {
  description: "Modifica imágenes de forma sincrónica según el prompt y la relación de aspecto.",
  display_name: "Luma Imagen a Imagen",
  inputs: {
    control_after_generate: {
      name: "controlar después de generar"
    },
    image: {
      name: "imagen"
    },
    image_weight: {
      name: "peso_imagen",
      tooltip: "Peso de la imagen; cuanto más cerca de 1.0, menos se modificará la imagen."
    },
    model: {
      name: "modelo"
    },
    prompt: {
      name: "prompt",
      tooltip: "Prompt para la generación de la imagen"
    },
    seed: {
      name: "semilla",
      tooltip: "Semilla para determinar si el nodo debe ejecutarse de nuevo; los resultados reales son no deterministas independientemente de la semilla."
    }
  }
};
const LumaImageNode$5 = {
  description: "Genera imágenes de forma sincrónica según el prompt y la relación de aspecto.",
  display_name: "Luma Texto a Imagen",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio"
    },
    character_image: {
      name: "character_image",
      tooltip: "Imágenes de referencia de personaje; puede ser un lote de varias, se pueden considerar hasta 4 imágenes."
    },
    control_after_generate: {
      name: "control after generate"
    },
    image_luma_ref: {
      name: "image_luma_ref",
      tooltip: "Conexión de nodo de referencia Luma para influir en la generación con imágenes de entrada; se pueden considerar hasta 4 imágenes."
    },
    model: {
      name: "model"
    },
    prompt: {
      name: "prompt",
      tooltip: "Prompt para la generación de la imagen"
    },
    seed: {
      name: "seed",
      tooltip: "Semilla para determinar si el nodo debe ejecutarse de nuevo; los resultados reales son no deterministas independientemente de la semilla."
    },
    style_image: {
      name: "style_image",
      tooltip: "Imagen de referencia de estilo; solo se usará 1 imagen."
    },
    style_image_weight: {
      name: "style_image_weight",
      tooltip: "Peso de la imagen de estilo. Se ignora si no se proporciona style_image."
    }
  }
};
const LumaImageToVideoNode$5 = {
  description: "Genera videos de forma sincrónica basados en el prompt, imágenes de entrada y output_size.",
  display_name: "Luma Image to Video",
  inputs: {
    control_after_generate: {
      name: "control después de generar"
    },
    duration: {
      name: "duración"
    },
    first_image: {
      name: "primera_imagen",
      tooltip: "Primer fotograma del video generado."
    },
    last_image: {
      name: "última_imagen",
      tooltip: "Último fotograma del video generado."
    },
    loop: {
      name: "bucle"
    },
    luma_concepts: {
      name: "luma_concepts",
      tooltip: "Conceptos de cámara opcionales para dictar el movimiento de cámara a través del nodo Luma Concepts."
    },
    model: {
      name: "model"
    },
    prompt: {
      name: "prompt",
      tooltip: "Prompt para la generación de video"
    },
    resolution: {
      name: "resolución"
    },
    seed: {
      name: "semilla",
      tooltip: "Semilla para determinar si el nodo debe ejecutarse de nuevo; los resultados reales son no deterministas independientemente de la semilla."
    }
  }
};
const LumaReferenceNode$5 = {
  description: "Contiene una imagen y un peso para usar con el nodo Luma Generate Image.",
  display_name: "Referencia Luma",
  inputs: {
    image: {
      name: "imagen",
      tooltip: "Imagen a usar como referencia."
    },
    luma_ref: {
      name: "luma_ref"
    },
    weight: {
      name: "peso",
      tooltip: "Peso de la referencia de imagen."
    }
  },
  outputs: {
    "0": {
      name: "luma_ref"
    }
  }
};
const LumaVideoNode$5 = {
  description: "Genera videos de forma sincrónica según el prompt y el tamaño de salida.",
  display_name: "Luma Texto a Video",
  inputs: {
    aspect_ratio: {
      name: "relación de aspecto"
    },
    control_after_generate: {
      name: "control después de generar"
    },
    duration: {
      name: "duración"
    },
    loop: {
      name: "bucle"
    },
    luma_concepts: {
      name: "luma_concepts",
      tooltip: "Conceptos de cámara opcionales para dictar el movimiento de cámara a través del nodo Luma Concepts."
    },
    model: {
      name: "modelo"
    },
    prompt: {
      name: "prompt",
      tooltip: "Prompt para la generación de video"
    },
    resolution: {
      name: "resolución"
    },
    seed: {
      name: "semilla",
      tooltip: "Semilla para determinar si el nodo debe ejecutarse de nuevo; los resultados reales son no deterministas independientemente de la semilla."
    }
  }
};
const Mahiro$5 = {
  description: "Modifica la guía para escalar más en la 'dirección' del indicador positivo en lugar de la diferencia entre el indicador negativo.",
  display_name: "¡Mahiro es tan linda que merece una mejor función de guía!! (。・ω・。)",
  inputs: {
    model: {
      name: "modelo"
    }
  },
  outputs: {
    "0": {
      name: "modelo_parcheado"
    }
  }
};
const MaskComposite$5 = {
  display_name: "Composición de Máscara",
  inputs: {
    destination: {
      name: "destino"
    },
    operation: {
      name: "operación"
    },
    source: {
      name: "fuente"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const MaskPreview$5 = {
  description: "Guarda las imágenes de entrada en tu directorio de salida de ComfyUI.",
  display_name: "MaskPreview",
  inputs: {
    mask: {
      name: "mask"
    }
  }
};
const MaskToImage$5 = {
  display_name: "Convertir Máscara a Imagen",
  inputs: {
    mask: {
      name: "máscara"
    }
  }
};
const MinimaxImageToVideoNode$5 = {
  description: "Genera videos a partir de una imagen y prompts usando la API de MiniMax",
  display_name: "MiniMax Imagen a Video",
  inputs: {
    control_after_generate: {
      name: "control después de generar"
    },
    image: {
      name: "imagen",
      tooltip: "Imagen a usar como primer fotograma de la generación de video"
    },
    model: {
      name: "modelo",
      tooltip: "Modelo a usar para la generación de video"
    },
    prompt_text: {
      name: "texto de prompt",
      tooltip: "Prompt de texto para guiar la generación de video"
    },
    seed: {
      name: "semilla",
      tooltip: "La semilla aleatoria utilizada para crear el ruido."
    }
  }
};
const MinimaxTextToVideoNode$5 = {
  description: "Genera videos a partir de indicaciones usando la API de MiniMax",
  display_name: "MiniMax Texto a Video",
  inputs: {
    control_after_generate: {
      name: "controlar después de generar"
    },
    model: {
      name: "modelo",
      tooltip: "Modelo a utilizar para la generación de video"
    },
    prompt_text: {
      name: "texto_de_indicación",
      tooltip: "Texto de indicación para guiar la generación del video"
    },
    seed: {
      name: "semilla",
      tooltip: "La semilla aleatoria utilizada para crear el ruido."
    }
  }
};
const ModelComputeDtype$5 = {
  display_name: "ModeloCalcularDtype",
  inputs: {
    dtype: {
      name: "dtype"
    },
    model: {
      name: "modelo"
    }
  }
};
const ModelMergeAdd$5 = {
  display_name: "ModeloFusionarAgregar",
  inputs: {
    model1: {
      name: "modelo1"
    },
    model2: {
      name: "modelo2"
    }
  }
};
const ModelMergeAuraflow$5 = {
  display_name: "ModelMergeAuraflow",
  inputs: {
    cond_seq_linear_: {
      name: "cond_seq_linear."
    },
    double_layers_0_: {
      name: "capas_dobles.0."
    },
    double_layers_1_: {
      name: "capas_dobles.1."
    },
    double_layers_2_: {
      name: "capas_dobles.2."
    },
    double_layers_3_: {
      name: "capas_dobles.3."
    },
    final_linear_: {
      name: "final_linear."
    },
    init_x_linear_: {
      name: "init_x_linear."
    },
    modF_: {
      name: "modF."
    },
    model1: {
      name: "modelo1"
    },
    model2: {
      name: "modelo2"
    },
    positional_encoding: {
      name: "codificación_posicional"
    },
    register_tokens: {
      name: "registrar_tokens"
    },
    single_layers_0_: {
      name: "capas_simples.0."
    },
    single_layers_10_: {
      name: "capas_simples.10."
    },
    single_layers_11_: {
      name: "capas_simples.11."
    },
    single_layers_12_: {
      name: "capas_simples.12."
    },
    single_layers_13_: {
      name: "capas_simples.13."
    },
    single_layers_14_: {
      name: "capas_simples.14."
    },
    single_layers_15_: {
      name: "capas_simples.15."
    },
    single_layers_16_: {
      name: "capas_simples.16."
    },
    single_layers_17_: {
      name: "capas_simples.17."
    },
    single_layers_18_: {
      name: "capas_simples.18."
    },
    single_layers_19_: {
      name: "capas_simples.19."
    },
    single_layers_1_: {
      name: "capas_simples.1."
    },
    single_layers_20_: {
      name: "capas_simples.20."
    },
    single_layers_21_: {
      name: "capas_simples.21."
    },
    single_layers_22_: {
      name: "capas_simples.22."
    },
    single_layers_23_: {
      name: "capas_simples.23."
    },
    single_layers_24_: {
      name: "capas_simples.24."
    },
    single_layers_25_: {
      name: "capas_simples.25."
    },
    single_layers_26_: {
      name: "capas_simples.26."
    },
    single_layers_27_: {
      name: "capas_simples.27."
    },
    single_layers_28_: {
      name: "capas_simples.28."
    },
    single_layers_29_: {
      name: "capas_simples.29."
    },
    single_layers_2_: {
      name: "capas_simples.2."
    },
    single_layers_30_: {
      name: "capas_simples.30."
    },
    single_layers_31_: {
      name: "capas_simples.31."
    },
    single_layers_3_: {
      name: "capas_simples.3."
    },
    single_layers_4_: {
      name: "capas_simples.4."
    },
    single_layers_5_: {
      name: "capas_simples.5."
    },
    single_layers_6_: {
      name: "capas_simples.6."
    },
    single_layers_7_: {
      name: "capas_simples.7."
    },
    single_layers_8_: {
      name: "capas_simples.8."
    },
    single_layers_9_: {
      name: "capas_simples.9."
    },
    t_embedder_: {
      name: "t_embedder."
    }
  }
};
const ModelMergeBlocks$5 = {
  display_name: "ModelMergeBlocks",
  inputs: {
    input: {
      name: "entrada"
    },
    middle: {
      name: "medio"
    },
    model1: {
      name: "modelo1"
    },
    model2: {
      name: "modelo2"
    },
    out: {
      name: "salida"
    }
  }
};
const ModelMergeCosmos14B$5 = {
  display_name: "ModelMergeCosmos14B",
  inputs: {
    affline_norm_: {
      name: "affline_norm."
    },
    blocks_block0_: {
      name: "blocks.block0."
    },
    blocks_block10_: {
      name: "blocks.block10."
    },
    blocks_block11_: {
      name: "blocks.block11."
    },
    blocks_block12_: {
      name: "blocks.block12."
    },
    blocks_block13_: {
      name: "blocks.block13."
    },
    blocks_block14_: {
      name: "blocks.block14."
    },
    blocks_block15_: {
      name: "blocks.block15."
    },
    blocks_block16_: {
      name: "blocks.block16."
    },
    blocks_block17_: {
      name: "blocks.block17."
    },
    blocks_block18_: {
      name: "blocks.block18."
    },
    blocks_block19_: {
      name: "blocks.block19."
    },
    blocks_block1_: {
      name: "blocks.block1."
    },
    blocks_block20_: {
      name: "blocks.block20."
    },
    blocks_block21_: {
      name: "blocks.block21."
    },
    blocks_block22_: {
      name: "blocks.block22."
    },
    blocks_block23_: {
      name: "blocks.block23."
    },
    blocks_block24_: {
      name: "blocks.block24."
    },
    blocks_block25_: {
      name: "blocks.block25."
    },
    blocks_block26_: {
      name: "blocks.block26."
    },
    blocks_block27_: {
      name: "blocks.block27."
    },
    blocks_block28_: {
      name: "blocks.block28."
    },
    blocks_block29_: {
      name: "blocks.block29."
    },
    blocks_block2_: {
      name: "blocks.block2."
    },
    blocks_block30_: {
      name: "blocks.block30."
    },
    blocks_block31_: {
      name: "blocks.block31."
    },
    blocks_block32_: {
      name: "blocks.block32."
    },
    blocks_block33_: {
      name: "blocks.block33."
    },
    blocks_block34_: {
      name: "blocks.block34."
    },
    blocks_block35_: {
      name: "final_layer."
    },
    blocks_block3_: {
      name: "blocks.block3."
    },
    blocks_block4_: {
      name: "blocks.block4."
    },
    blocks_block5_: {
      name: "blocks.block5."
    },
    blocks_block6_: {
      name: "blocks.block6."
    },
    blocks_block7_: {
      name: "blocks.block7."
    },
    blocks_block8_: {
      name: "blocks.block8."
    },
    blocks_block9_: {
      name: "blocks.block9."
    },
    extra_pos_embedder_: {
      name: "extra_pos_embedder."
    },
    final_layer_: {
      name: "capa_final."
    },
    model1: {
      name: "model1"
    },
    model2: {
      name: "model2"
    },
    pos_embedder_: {
      name: "pos_embedder."
    },
    t_embedder_: {
      name: "t_embedder."
    },
    x_embedder_: {
      name: "x_embedder."
    }
  }
};
const ModelMergeCosmos7B$5 = {
  display_name: "ModelMergeCosmos7B",
  inputs: {
    affline_norm_: {
      name: "affline_norm."
    },
    blocks_block0_: {
      name: "blocks.block0."
    },
    blocks_block10_: {
      name: "blocks.block10."
    },
    blocks_block11_: {
      name: "blocks.block11."
    },
    blocks_block12_: {
      name: "blocks.block12."
    },
    blocks_block13_: {
      name: "blocks.block13."
    },
    blocks_block14_: {
      name: "blocks.block14."
    },
    blocks_block15_: {
      name: "blocks.block15."
    },
    blocks_block16_: {
      name: "blocks.block16."
    },
    blocks_block17_: {
      name: "blocks.block17."
    },
    blocks_block18_: {
      name: "blocks.block18."
    },
    blocks_block19_: {
      name: "blocks.block19."
    },
    blocks_block1_: {
      name: "blocks.block1."
    },
    blocks_block20_: {
      name: "blocks.block20."
    },
    blocks_block21_: {
      name: "blocks.block21."
    },
    blocks_block22_: {
      name: "blocks.block22."
    },
    blocks_block23_: {
      name: "blocks.block23."
    },
    blocks_block24_: {
      name: "blocks.block24."
    },
    blocks_block25_: {
      name: "blocks.block25."
    },
    blocks_block26_: {
      name: "blocks.block26."
    },
    blocks_block27_: {
      name: "blocks.block27."
    },
    blocks_block2_: {
      name: "blocks.block2."
    },
    blocks_block3_: {
      name: "blocks.block3."
    },
    blocks_block4_: {
      name: "blocks.block4."
    },
    blocks_block5_: {
      name: "blocks.block5."
    },
    blocks_block6_: {
      name: "blocks.block6."
    },
    blocks_block7_: {
      name: "blocks.block7."
    },
    blocks_block8_: {
      name: "blocks.block8."
    },
    blocks_block9_: {
      name: "blocks.block9."
    },
    extra_pos_embedder_: {
      name: "extra_pos_embedder."
    },
    final_layer_: {
      name: "final_layer."
    },
    model1: {
      name: "model1"
    },
    model2: {
      name: "model2"
    },
    pos_embedder_: {
      name: "pos_embedder."
    },
    t_embedder_: {
      name: "t_embedder."
    },
    x_embedder_: {
      name: "x_embedder."
    }
  }
};
const ModelMergeFlux1$5 = {
  display_name: "ModelMergeFlux1",
  inputs: {
    double_blocks_0_: {
      name: "bloques_dobles.0."
    },
    double_blocks_10_: {
      name: "bloques_dobles.10."
    },
    double_blocks_11_: {
      name: "bloques_dobles.11."
    },
    double_blocks_12_: {
      name: "bloques_dobles.12."
    },
    double_blocks_13_: {
      name: "bloques_dobles.13."
    },
    double_blocks_14_: {
      name: "bloques_dobles.14."
    },
    double_blocks_15_: {
      name: "bloques_dobles.15."
    },
    double_blocks_16_: {
      name: "bloques_dobles.16."
    },
    double_blocks_17_: {
      name: "bloques_dobles.17."
    },
    double_blocks_18_: {
      name: "bloques_dobles.18."
    },
    double_blocks_1_: {
      name: "bloques_dobles.1."
    },
    double_blocks_2_: {
      name: "bloques_dobles.2."
    },
    double_blocks_3_: {
      name: "bloques_dobles.3."
    },
    double_blocks_4_: {
      name: "bloques_dobles.4."
    },
    double_blocks_5_: {
      name: "bloques_dobles.5."
    },
    double_blocks_6_: {
      name: "bloques_dobles.6."
    },
    double_blocks_7_: {
      name: "bloques_dobles.7."
    },
    double_blocks_8_: {
      name: "bloques_dobles.8."
    },
    double_blocks_9_: {
      name: "bloques_dobles.9."
    },
    final_layer_: {
      name: "capa_final."
    },
    guidance_in: {
      name: "orientación_in"
    },
    img_in_: {
      name: "img_in."
    },
    model1: {
      name: "model1"
    },
    model2: {
      name: "model2"
    },
    single_blocks_0_: {
      name: "bloques_simples.0."
    },
    single_blocks_10_: {
      name: "bloques_simples.10."
    },
    single_blocks_11_: {
      name: "bloques_simples.11."
    },
    single_blocks_12_: {
      name: "bloques_simples.12."
    },
    single_blocks_13_: {
      name: "bloques_simples.13."
    },
    single_blocks_14_: {
      name: "bloques_simples.14."
    },
    single_blocks_15_: {
      name: "bloques_simples.15."
    },
    single_blocks_16_: {
      name: "bloques_simples.16."
    },
    single_blocks_17_: {
      name: "bloques_simples.17."
    },
    single_blocks_18_: {
      name: "bloques_simples.18."
    },
    single_blocks_19_: {
      name: "bloques_simples.19."
    },
    single_blocks_1_: {
      name: "bloques_simples.1."
    },
    single_blocks_20_: {
      name: "bloques_simples.20."
    },
    single_blocks_21_: {
      name: "bloques_simples.21."
    },
    single_blocks_22_: {
      name: "bloques_simples.22."
    },
    single_blocks_23_: {
      name: "bloques_simples.23."
    },
    single_blocks_24_: {
      name: "bloques_simples.24."
    },
    single_blocks_25_: {
      name: "bloques_simples.25."
    },
    single_blocks_26_: {
      name: "bloques_simples.26."
    },
    single_blocks_27_: {
      name: "bloques_simples.27."
    },
    single_blocks_28_: {
      name: "bloques_simples.28."
    },
    single_blocks_29_: {
      name: "bloques_simples.29."
    },
    single_blocks_2_: {
      name: "bloques_simples.2."
    },
    single_blocks_30_: {
      name: "bloques_simples.30."
    },
    single_blocks_31_: {
      name: "bloques_simples.31."
    },
    single_blocks_32_: {
      name: "bloques_simples.32."
    },
    single_blocks_33_: {
      name: "bloques_simples.33."
    },
    single_blocks_34_: {
      name: "bloques_simples.34."
    },
    single_blocks_35_: {
      name: "bloques_simples.35."
    },
    single_blocks_36_: {
      name: "bloques_simples.36."
    },
    single_blocks_37_: {
      name: "bloques_simples.37."
    },
    single_blocks_3_: {
      name: "bloques_simples.3."
    },
    single_blocks_4_: {
      name: "bloques_simples.4."
    },
    single_blocks_5_: {
      name: "bloques_simples.5."
    },
    single_blocks_6_: {
      name: "bloques_simples.6."
    },
    single_blocks_7_: {
      name: "bloques_simples.7."
    },
    single_blocks_8_: {
      name: "bloques_simples.8."
    },
    single_blocks_9_: {
      name: "bloques_simples.9."
    },
    time_in_: {
      name: "time_in."
    },
    txt_in_: {
      name: "txt_in."
    },
    vector_in_: {
      name: "vector_in."
    }
  }
};
const ModelMergeLTXV$5 = {
  display_name: "ModelMergeLTXV",
  inputs: {
    adaln_single_: {
      name: "adaln_single."
    },
    caption_projection_: {
      name: "caption_projection."
    },
    model1: {
      name: "model1"
    },
    model2: {
      name: "model2"
    },
    patchify_proj_: {
      name: "patchify_proj."
    },
    proj_out_: {
      name: "proj_out."
    },
    scale_shift_table: {
      name: "scale_shift_table"
    },
    transformer_blocks_0_: {
      name: "transformer_blocks.0."
    },
    transformer_blocks_10_: {
      name: "transformer_blocks.10."
    },
    transformer_blocks_11_: {
      name: "transformer_blocks.11."
    },
    transformer_blocks_12_: {
      name: "transformer_blocks.12."
    },
    transformer_blocks_13_: {
      name: "transformer_blocks.13."
    },
    transformer_blocks_14_: {
      name: "transformer_blocks.14."
    },
    transformer_blocks_15_: {
      name: "transformer_blocks.15."
    },
    transformer_blocks_16_: {
      name: "transformer_blocks.16."
    },
    transformer_blocks_17_: {
      name: "transformer_blocks.17."
    },
    transformer_blocks_18_: {
      name: "transformer_blocks.18."
    },
    transformer_blocks_19_: {
      name: "transformer_blocks.19."
    },
    transformer_blocks_1_: {
      name: "transformer_blocks.1."
    },
    transformer_blocks_20_: {
      name: "transformer_blocks.20."
    },
    transformer_blocks_21_: {
      name: "transformer_blocks.21."
    },
    transformer_blocks_22_: {
      name: "transformer_blocks.22."
    },
    transformer_blocks_23_: {
      name: "transformer_blocks.23."
    },
    transformer_blocks_24_: {
      name: "transformer_blocks.24."
    },
    transformer_blocks_25_: {
      name: "transformer_blocks.25."
    },
    transformer_blocks_26_: {
      name: "transformer_blocks.26."
    },
    transformer_blocks_27_: {
      name: "transformer_blocks.27."
    },
    transformer_blocks_2_: {
      name: "transformer_blocks.2."
    },
    transformer_blocks_3_: {
      name: "transformer_blocks.3."
    },
    transformer_blocks_4_: {
      name: "transformer_blocks.4."
    },
    transformer_blocks_5_: {
      name: "transformer_blocks.5."
    },
    transformer_blocks_6_: {
      name: "transformer_blocks.6."
    },
    transformer_blocks_7_: {
      name: "transformer_blocks.7."
    },
    transformer_blocks_8_: {
      name: "transformer_blocks.8."
    },
    transformer_blocks_9_: {
      name: "transformer_blocks.9."
    }
  }
};
const ModelMergeMochiPreview$5 = {
  display_name: "ModelMergeMochiPreview",
  inputs: {
    blocks_0_: {
      name: "blocks.0."
    },
    blocks_10_: {
      name: "blocks.10."
    },
    blocks_11_: {
      name: "blocks.11."
    },
    blocks_12_: {
      name: "blocks.12."
    },
    blocks_13_: {
      name: "blocks.13."
    },
    blocks_14_: {
      name: "blocks.14."
    },
    blocks_15_: {
      name: "blocks.15."
    },
    blocks_16_: {
      name: "blocks.16."
    },
    blocks_17_: {
      name: "blocks.17."
    },
    blocks_18_: {
      name: "blocks.18."
    },
    blocks_19_: {
      name: "blocks.19."
    },
    blocks_1_: {
      name: "blocks.1."
    },
    blocks_20_: {
      name: "blocks.20."
    },
    blocks_21_: {
      name: "blocks.21."
    },
    blocks_22_: {
      name: "blocks.22."
    },
    blocks_23_: {
      name: "blocks.23."
    },
    blocks_24_: {
      name: "blocks.24."
    },
    blocks_25_: {
      name: "blocks.25."
    },
    blocks_26_: {
      name: "blocks.26."
    },
    blocks_27_: {
      name: "blocks.27."
    },
    blocks_28_: {
      name: "blocks.28."
    },
    blocks_29_: {
      name: "blocks.29."
    },
    blocks_2_: {
      name: "blocks.2."
    },
    blocks_30_: {
      name: "blocks.30."
    },
    blocks_31_: {
      name: "blocks.31."
    },
    blocks_32_: {
      name: "blocks.32."
    },
    blocks_33_: {
      name: "blocks.33."
    },
    blocks_34_: {
      name: "blocks.34."
    },
    blocks_35_: {
      name: "blocks.35."
    },
    blocks_36_: {
      name: "blocks.36."
    },
    blocks_37_: {
      name: "blocks.37."
    },
    blocks_38_: {
      name: "blocks.38."
    },
    blocks_39_: {
      name: "blocks.39."
    },
    blocks_3_: {
      name: "blocks.3."
    },
    blocks_40_: {
      name: "blocks.40."
    },
    blocks_41_: {
      name: "blocks.41."
    },
    blocks_42_: {
      name: "blocks.42."
    },
    blocks_43_: {
      name: "blocks.43."
    },
    blocks_44_: {
      name: "blocks.44."
    },
    blocks_45_: {
      name: "blocks.45."
    },
    blocks_46_: {
      name: "blocks.46."
    },
    blocks_47_: {
      name: "blocks.47."
    },
    blocks_4_: {
      name: "blocks.4."
    },
    blocks_5_: {
      name: "blocks.5."
    },
    blocks_6_: {
      name: "blocks.6."
    },
    blocks_7_: {
      name: "blocks.7."
    },
    blocks_8_: {
      name: "blocks.8."
    },
    blocks_9_: {
      name: "blocks.9."
    },
    final_layer_: {
      name: "final_layer."
    },
    model1: {
      name: "model1"
    },
    model2: {
      name: "model2"
    },
    pos_frequencies_: {
      name: "pos_frequencies."
    },
    t5_y_embedder_: {
      name: "t5_y_embedder."
    },
    t5_yproj_: {
      name: "t5_yproj."
    },
    t_embedder_: {
      name: "t_embedder."
    }
  }
};
const ModelMergeSD1$5 = {
  display_name: "ModelMergeSD1",
  inputs: {
    input_blocks_0_: {
      name: "input_blocks.0."
    },
    input_blocks_10_: {
      name: "input_blocks.10."
    },
    input_blocks_11_: {
      name: "input_blocks.11."
    },
    input_blocks_1_: {
      name: "input_blocks.1."
    },
    input_blocks_2_: {
      name: "input_blocks.2."
    },
    input_blocks_3_: {
      name: "input_blocks.3."
    },
    input_blocks_4_: {
      name: "input_blocks.4."
    },
    input_blocks_5_: {
      name: "input_blocks.5."
    },
    input_blocks_6_: {
      name: "input_blocks.6."
    },
    input_blocks_7_: {
      name: "input_blocks.7."
    },
    input_blocks_8_: {
      name: "input_blocks.8."
    },
    input_blocks_9_: {
      name: "input_blocks.9."
    },
    label_emb_: {
      name: "label_emb."
    },
    middle_block_0_: {
      name: "middle_block.0."
    },
    middle_block_1_: {
      name: "middle_block.1."
    },
    middle_block_2_: {
      name: "middle_block.2."
    },
    model1: {
      name: "model1"
    },
    model2: {
      name: "model2"
    },
    out_: {
      name: "out."
    },
    output_blocks_0_: {
      name: "output_blocks.0."
    },
    output_blocks_10_: {
      name: "output_blocks.10."
    },
    output_blocks_11_: {
      name: "output_blocks.11."
    },
    output_blocks_1_: {
      name: "output_blocks.1."
    },
    output_blocks_2_: {
      name: "output_blocks.2."
    },
    output_blocks_3_: {
      name: "output_blocks.3."
    },
    output_blocks_4_: {
      name: "output_blocks.4."
    },
    output_blocks_5_: {
      name: "output_blocks.5."
    },
    output_blocks_6_: {
      name: "output_blocks.6."
    },
    output_blocks_7_: {
      name: "output_blocks.7."
    },
    output_blocks_8_: {
      name: "output_blocks.8."
    },
    output_blocks_9_: {
      name: "output_blocks.9."
    },
    time_embed_: {
      name: "time_embed."
    }
  }
};
const ModelMergeSD2$5 = {
  display_name: "ModelMergeSD2",
  inputs: {
    input_blocks_0_: {
      name: "input_blocks.0."
    },
    input_blocks_10_: {
      name: "input_blocks.10."
    },
    input_blocks_11_: {
      name: "input_blocks.11."
    },
    input_blocks_1_: {
      name: "input_blocks.1."
    },
    input_blocks_2_: {
      name: "input_blocks.2."
    },
    input_blocks_3_: {
      name: "input_blocks.3."
    },
    input_blocks_4_: {
      name: "input_blocks.4."
    },
    input_blocks_5_: {
      name: "input_blocks.5."
    },
    input_blocks_6_: {
      name: "input_blocks.6."
    },
    input_blocks_7_: {
      name: "input_blocks.7."
    },
    input_blocks_8_: {
      name: "input_blocks.8."
    },
    input_blocks_9_: {
      name: "input_blocks.9."
    },
    label_emb_: {
      name: "label_emb."
    },
    middle_block_0_: {
      name: "middle_block.0."
    },
    middle_block_1_: {
      name: "middle_block.1."
    },
    middle_block_2_: {
      name: "middle_block.2."
    },
    model1: {
      name: "model1"
    },
    model2: {
      name: "model2"
    },
    out_: {
      name: "out."
    },
    output_blocks_0_: {
      name: "output_blocks.0."
    },
    output_blocks_10_: {
      name: "output_blocks.10."
    },
    output_blocks_11_: {
      name: "output_blocks.11."
    },
    output_blocks_1_: {
      name: "output_blocks.1."
    },
    output_blocks_2_: {
      name: "output_blocks.2."
    },
    output_blocks_3_: {
      name: "output_blocks.3."
    },
    output_blocks_4_: {
      name: "output_blocks.4."
    },
    output_blocks_5_: {
      name: "output_blocks.5."
    },
    output_blocks_6_: {
      name: "output_blocks.6."
    },
    output_blocks_7_: {
      name: "output_blocks.7."
    },
    output_blocks_8_: {
      name: "output_blocks.8."
    },
    output_blocks_9_: {
      name: "output_blocks.9."
    },
    time_embed_: {
      name: "time_embed."
    }
  }
};
const ModelMergeSD35_Large$5 = {
  display_name: "ModelMergeSD35_Large",
  inputs: {
    context_embedder_: {
      name: "context_embedder."
    },
    final_layer_: {
      name: "final_layer."
    },
    joint_blocks_0_: {
      name: "joint_blocks.0."
    },
    joint_blocks_10_: {
      name: "joint_blocks.10."
    },
    joint_blocks_11_: {
      name: "joint_blocks.11."
    },
    joint_blocks_12_: {
      name: "joint_blocks.12."
    },
    joint_blocks_13_: {
      name: "joint_blocks.13."
    },
    joint_blocks_14_: {
      name: "joint_blocks.14."
    },
    joint_blocks_15_: {
      name: "joint_blocks.15."
    },
    joint_blocks_16_: {
      name: "joint_blocks.16."
    },
    joint_blocks_17_: {
      name: "joint_blocks.17."
    },
    joint_blocks_18_: {
      name: "joint_blocks.18."
    },
    joint_blocks_19_: {
      name: "joint_blocks.19."
    },
    joint_blocks_1_: {
      name: "joint_blocks.1."
    },
    joint_blocks_20_: {
      name: "joint_blocks.20."
    },
    joint_blocks_21_: {
      name: "joint_blocks.21."
    },
    joint_blocks_22_: {
      name: "joint_blocks.22."
    },
    joint_blocks_23_: {
      name: "joint_blocks.23."
    },
    joint_blocks_24_: {
      name: "joint_blocks.24."
    },
    joint_blocks_25_: {
      name: "joint_blocks.25."
    },
    joint_blocks_26_: {
      name: "joint_blocks.26."
    },
    joint_blocks_27_: {
      name: "joint_blocks.27."
    },
    joint_blocks_28_: {
      name: "joint_blocks.28."
    },
    joint_blocks_29_: {
      name: "joint_blocks.29."
    },
    joint_blocks_2_: {
      name: "joint_blocks.2."
    },
    joint_blocks_30_: {
      name: "joint_blocks.30."
    },
    joint_blocks_31_: {
      name: "joint_blocks.31."
    },
    joint_blocks_32_: {
      name: "joint_blocks.32."
    },
    joint_blocks_33_: {
      name: "joint_blocks.33."
    },
    joint_blocks_34_: {
      name: "joint_blocks.34."
    },
    joint_blocks_35_: {
      name: "joint_blocks.35."
    },
    joint_blocks_36_: {
      name: "joint_blocks.36."
    },
    joint_blocks_37_: {
      name: "joint_blocks.37."
    },
    joint_blocks_3_: {
      name: "joint_blocks.3."
    },
    joint_blocks_4_: {
      name: "joint_blocks.4."
    },
    joint_blocks_5_: {
      name: "joint_blocks.5."
    },
    joint_blocks_6_: {
      name: "joint_blocks.6."
    },
    joint_blocks_7_: {
      name: "joint_blocks.7."
    },
    joint_blocks_8_: {
      name: "joint_blocks.8."
    },
    joint_blocks_9_: {
      name: "joint_blocks.9."
    },
    model1: {
      name: "model1"
    },
    model2: {
      name: "model2"
    },
    pos_embed_: {
      name: "pos_embed."
    },
    t_embedder_: {
      name: "t_embedder."
    },
    x_embedder_: {
      name: "x_embedder."
    },
    y_embedder_: {
      name: "y_embedder."
    }
  }
};
const ModelMergeSD3_2B$5 = {
  display_name: "ModelMergeSD3_2B",
  inputs: {
    context_embedder_: {
      name: "context_embedder."
    },
    final_layer_: {
      name: "final_layer."
    },
    joint_blocks_0_: {
      name: "joint_blocks.0."
    },
    joint_blocks_10_: {
      name: "joint_blocks.10."
    },
    joint_blocks_11_: {
      name: "joint_blocks.11."
    },
    joint_blocks_12_: {
      name: "joint_blocks.12."
    },
    joint_blocks_13_: {
      name: "joint_blocks.13."
    },
    joint_blocks_14_: {
      name: "joint_blocks.14."
    },
    joint_blocks_15_: {
      name: "joint_blocks.15."
    },
    joint_blocks_16_: {
      name: "joint_blocks.16."
    },
    joint_blocks_17_: {
      name: "joint_blocks.17."
    },
    joint_blocks_18_: {
      name: "joint_blocks.18."
    },
    joint_blocks_19_: {
      name: "joint_blocks.19."
    },
    joint_blocks_1_: {
      name: "joint_blocks.1."
    },
    joint_blocks_20_: {
      name: "joint_blocks.20."
    },
    joint_blocks_21_: {
      name: "joint_blocks.21."
    },
    joint_blocks_22_: {
      name: "joint_blocks.22."
    },
    joint_blocks_23_: {
      name: "joint_blocks.23."
    },
    joint_blocks_2_: {
      name: "joint_blocks.2."
    },
    joint_blocks_3_: {
      name: "joint_blocks.3."
    },
    joint_blocks_4_: {
      name: "joint_blocks.4."
    },
    joint_blocks_5_: {
      name: "joint_blocks.5."
    },
    joint_blocks_6_: {
      name: "joint_blocks.6."
    },
    joint_blocks_7_: {
      name: "joint_blocks.7."
    },
    joint_blocks_8_: {
      name: "joint_blocks.8."
    },
    joint_blocks_9_: {
      name: "joint_blocks.9."
    },
    model1: {
      name: "model1"
    },
    model2: {
      name: "model2"
    },
    pos_embed_: {
      name: "pos_embed."
    },
    t_embedder_: {
      name: "t_embedder."
    },
    x_embedder_: {
      name: "x_embedder."
    },
    y_embedder_: {
      name: "y_embedder."
    }
  }
};
const ModelMergeSDXL$5 = {
  display_name: "ModelMergeSDXL",
  inputs: {
    input_blocks_0: {
      name: "input_blocks.0"
    },
    input_blocks_1: {
      name: "input_blocks.1"
    },
    input_blocks_2: {
      name: "input_blocks.2"
    },
    input_blocks_3: {
      name: "input_blocks.3"
    },
    input_blocks_4: {
      name: "input_blocks.4"
    },
    input_blocks_5: {
      name: "input_blocks.5"
    },
    input_blocks_6: {
      name: "input_blocks.6"
    },
    input_blocks_7: {
      name: "input_blocks.7"
    },
    input_blocks_8: {
      name: "input_blocks.8"
    },
    label_emb_: {
      name: "label_emb."
    },
    middle_block_0: {
      name: "middle_block.0"
    },
    middle_block_1: {
      name: "middle_block.1"
    },
    middle_block_2: {
      name: "middle_block.2"
    },
    model1: {
      name: "model1"
    },
    model2: {
      name: "model2"
    },
    out_: {
      name: "out."
    },
    output_blocks_0: {
      name: "output_blocks.0"
    },
    output_blocks_1: {
      name: "output_blocks.1"
    },
    output_blocks_2: {
      name: "output_blocks.2"
    },
    output_blocks_3: {
      name: "output_blocks.3"
    },
    output_blocks_4: {
      name: "output_blocks.4"
    },
    output_blocks_5: {
      name: "output_blocks.5"
    },
    output_blocks_6: {
      name: "output_blocks.6"
    },
    output_blocks_7: {
      name: "output_blocks.7"
    },
    output_blocks_8: {
      name: "output_blocks.8"
    },
    time_embed_: {
      name: "time_embed."
    }
  }
};
const ModelMergeSimple$5 = {
  display_name: "ModelMergeSimple",
  inputs: {
    model1: {
      name: "model1"
    },
    model2: {
      name: "model2"
    },
    ratio: {
      name: "ratio"
    }
  }
};
const ModelMergeSubtract$5 = {
  display_name: "ModelMergeSubtract",
  inputs: {
    model1: {
      name: "model1"
    },
    model2: {
      name: "model2"
    },
    multiplier: {
      name: "multiplier"
    }
  }
};
const ModelMergeWAN2_1$5 = {
  description: "El modelo de 1.3B tiene 30 bloques, el modelo de 14B tiene 40 bloques. El modelo de imagen a video tiene el img_emb extra.",
  display_name: "ModelMergeWAN2_1",
  inputs: {
    blocks_0_: {
      name: "blocks.0."
    },
    blocks_10_: {
      name: "blocks.10."
    },
    blocks_11_: {
      name: "blocks.11."
    },
    blocks_12_: {
      name: "blocks.12."
    },
    blocks_13_: {
      name: "blocks.13."
    },
    blocks_14_: {
      name: "blocks.14."
    },
    blocks_15_: {
      name: "blocks.15."
    },
    blocks_16_: {
      name: "blocks.16."
    },
    blocks_17_: {
      name: "blocks.17."
    },
    blocks_18_: {
      name: "blocks.18."
    },
    blocks_19_: {
      name: "blocks.19."
    },
    blocks_1_: {
      name: "blocks.1."
    },
    blocks_20_: {
      name: "blocks.20."
    },
    blocks_21_: {
      name: "blocks.21."
    },
    blocks_22_: {
      name: "blocks.22."
    },
    blocks_23_: {
      name: "blocks.23."
    },
    blocks_24_: {
      name: "blocks.24."
    },
    blocks_25_: {
      name: "blocks.25."
    },
    blocks_26_: {
      name: "blocks.26."
    },
    blocks_27_: {
      name: "blocks.27."
    },
    blocks_28_: {
      name: "blocks.28."
    },
    blocks_29_: {
      name: "blocks.29."
    },
    blocks_2_: {
      name: "blocks.2."
    },
    blocks_30_: {
      name: "blocks.30."
    },
    blocks_31_: {
      name: "blocks.31."
    },
    blocks_32_: {
      name: "blocks.32."
    },
    blocks_33_: {
      name: "blocks.33."
    },
    blocks_34_: {
      name: "blocks.34."
    },
    blocks_35_: {
      name: "blocks.35."
    },
    blocks_36_: {
      name: "blocks.36."
    },
    blocks_37_: {
      name: "blocks.37."
    },
    blocks_38_: {
      name: "blocks.38."
    },
    blocks_39_: {
      name: "blocks.39."
    },
    blocks_3_: {
      name: "blocks.3."
    },
    blocks_4_: {
      name: "blocks.4."
    },
    blocks_5_: {
      name: "blocks.5."
    },
    blocks_6_: {
      name: "blocks.6."
    },
    blocks_7_: {
      name: "blocks.7."
    },
    blocks_8_: {
      name: "blocks.8."
    },
    blocks_9_: {
      name: "blocks.9."
    },
    head_: {
      name: "head."
    },
    img_emb_: {
      name: "img_emb."
    },
    model1: {
      name: "model1"
    },
    model2: {
      name: "model2"
    },
    patch_embedding_: {
      name: "patch_embedding."
    },
    text_embedding_: {
      name: "text_embedding."
    },
    time_embedding_: {
      name: "time_embedding."
    },
    time_projection_: {
      name: "time_projection."
    }
  }
};
const ModelSamplingAuraFlow$5 = {
  display_name: "ModelSamplingAuraFlow",
  inputs: {
    model: {
      name: "model"
    },
    shift: {
      name: "shift"
    }
  }
};
const ModelSamplingContinuousEDM$5 = {
  display_name: "ModelSamplingContinuousEDM",
  inputs: {
    model: {
      name: "model"
    },
    sampling: {
      name: "muestreo"
    },
    sigma_max: {
      name: "sigma_max"
    },
    sigma_min: {
      name: "sigma_min"
    }
  }
};
const ModelSamplingContinuousV$5 = {
  display_name: "ModelSamplingContinuousV",
  inputs: {
    model: {
      name: "model"
    },
    sampling: {
      name: "muestreo"
    },
    sigma_max: {
      name: "sigma_max"
    },
    sigma_min: {
      name: "sigma_min"
    }
  }
};
const ModelSamplingDiscrete$5 = {
  display_name: "MuestreoDeModeloDiscreto",
  inputs: {
    model: {
      name: "modelo"
    },
    sampling: {
      name: "muestreo"
    },
    zsnr: {
      name: "zsnr"
    }
  }
};
const ModelSamplingFlux$5 = {
  display_name: "MuestreoDeModeloFlux",
  inputs: {
    base_shift: {
      name: "desplazamiento_base"
    },
    height: {
      name: "altura"
    },
    max_shift: {
      name: "desplazamiento_max"
    },
    model: {
      name: "modelo"
    },
    width: {
      name: "ancho"
    }
  }
};
const ModelSamplingLTXV$5 = {
  display_name: "MuestreoDeModeloLTXV",
  inputs: {
    base_shift: {
      name: "desplazamiento_base"
    },
    latent: {
      name: "latente"
    },
    max_shift: {
      name: "desplazamiento_max"
    },
    model: {
      name: "modelo"
    }
  }
};
const ModelSamplingSD3$5 = {
  display_name: "MuestreoDeModeloSD3",
  inputs: {
    model: {
      name: "modelo"
    },
    shift: {
      name: "desplazamiento"
    }
  }
};
const ModelSamplingStableCascade$5 = {
  display_name: "MuestreoDeModeloStableCascade",
  inputs: {
    model: {
      name: "modelo"
    },
    shift: {
      name: "desplazamiento"
    }
  }
};
const ModelSave$5 = {
  display_name: "GuardarModelo",
  inputs: {
    filename_prefix: {
      name: "prefijo_nombre_archivo"
    },
    model: {
      name: "modelo"
    }
  }
};
const Morphology$5 = {
  display_name: "MorfologiaDeImagen",
  inputs: {
    image: {
      name: "imagen"
    },
    kernel_size: {
      name: "tamaño_kernel"
    },
    operation: {
      name: "operacion"
    }
  }
};
const OpenAIDalle2$5 = {
  description: "Genera imágenes de forma síncrona a través del endpoint DALL·E 2 de OpenAI.",
  display_name: "OpenAI DALL·E 2",
  inputs: {
    control_after_generate: {
      name: "controlar después de generar"
    },
    image: {
      name: "imagen",
      tooltip: "Imagen de referencia opcional para la edición de imágenes."
    },
    mask: {
      name: "mask",
      tooltip: "Máscara opcional para inpainting (las áreas blancas serán reemplazadas)"
    },
    n: {
      name: "n",
      tooltip: "Cuántas imágenes generar"
    },
    prompt: {
      name: "prompt",
      tooltip: "Texto de entrada para DALL·E"
    },
    seed: {
      name: "seed",
      tooltip: "aún no implementado en el backend"
    },
    size: {
      name: "tamaño",
      tooltip: "Tamaño de la imagen"
    }
  }
};
const OpenAIDalle3$5 = {
  description: "Genera imágenes de forma sincrónica a través del endpoint DALL·E 3 de OpenAI.",
  display_name: "OpenAI DALL·E 3",
  inputs: {
    control_after_generate: {
      name: "controlar después de generar"
    },
    prompt: {
      name: "prompt",
      tooltip: "Texto de entrada para DALL·E"
    },
    quality: {
      name: "calidad",
      tooltip: "Calidad de la imagen"
    },
    seed: {
      name: "seed",
      tooltip: "aún no implementado en el backend"
    },
    size: {
      name: "tamaño",
      tooltip: "Tamaño de la imagen"
    },
    style: {
      name: "estilo",
      tooltip: "Vívido hace que el modelo tienda a generar imágenes hiperrealistas y dramáticas. Natural hace que el modelo produzca imágenes más naturales y menos hiperrealistas."
    }
  }
};
const OpenAIGPTImage1$5 = {
  description: "Genera imágenes de forma síncrona a través del endpoint GPT Image 1 de OpenAI.",
  display_name: "OpenAI GPT Image 1",
  inputs: {
    background: {
      name: "background",
      tooltip: "Devolver imagen con o sin fondo"
    },
    control_after_generate: {
      name: "control after generate"
    },
    image: {
      name: "image",
      tooltip: "Imagen de referencia opcional para edición de imagen."
    },
    mask: {
      name: "mask",
      tooltip: "Máscara opcional para inpainting (las áreas blancas serán reemplazadas)"
    },
    n: {
      name: "n",
      tooltip: "Cuántas imágenes generar"
    },
    prompt: {
      name: "prompt",
      tooltip: "Texto de entrada para GPT Image 1"
    },
    quality: {
      name: "quality",
      tooltip: "Calidad de la imagen, afecta el costo y el tiempo de generación."
    },
    seed: {
      name: "seed",
      tooltip: "aún no implementado en el backend"
    },
    size: {
      name: "size",
      tooltip: "Tamaño de la imagen"
    }
  }
};
const OptimalStepsScheduler$5 = {
  display_name: "OptimalStepsScheduler",
  inputs: {
    denoise: {
      name: "eliminar ruido"
    },
    model_type: {
      name: "model_type"
    },
    steps: {
      name: "pasos"
    }
  }
};
const PairConditioningCombine$5 = {
  display_name: "CombinarCondPares",
  inputs: {
    negative_A: {
      name: "negativo_A"
    },
    negative_B: {
      name: "negativo_B"
    },
    positive_A: {
      name: "positivo_A"
    },
    positive_B: {
      name: "positivo_B"
    }
  },
  outputs: {
    "0": {
      name: "positivo"
    },
    "1": {
      name: "negativo"
    }
  }
};
const PairConditioningSetDefaultCombine$5 = {
  display_name: "CombinarCondParesEstablecerPorDefecto",
  inputs: {
    hooks: {
      name: "ganchos"
    },
    negative: {
      name: "negativo"
    },
    negative_DEFAULT: {
      name: "negativo_POR_DEFECTO"
    },
    positive: {
      name: "positivo"
    },
    positive_DEFAULT: {
      name: "positivo_POR_DEFECTO"
    }
  },
  outputs: {
    "0": {
      name: "positivo"
    },
    "1": {
      name: "negativo"
    }
  }
};
const PairConditioningSetProperties$5 = {
  display_name: "EstablecerPropiedadesCondPares",
  inputs: {
    hooks: {
      name: "ganchos"
    },
    mask: {
      name: "mascara"
    },
    negative_NEW: {
      name: "negativo_NUEVO"
    },
    positive_NEW: {
      name: "positivo_NUEVO"
    },
    set_cond_area: {
      name: "establecer_area_cond"
    },
    strength: {
      name: "fuerza"
    },
    timesteps: {
      name: "pasos_de_tiempo"
    }
  },
  outputs: {
    "0": {
      name: "positivo"
    },
    "1": {
      name: "negativo"
    }
  }
};
const PairConditioningSetPropertiesAndCombine$5 = {
  display_name: "Cond Pair Set Props Combine",
  inputs: {
    hooks: {
      name: "ganchos"
    },
    mask: {
      name: "máscara"
    },
    negative: {
      name: "negativo"
    },
    negative_NEW: {
      name: "negativo_NUEVO"
    },
    positive: {
      name: "positivo"
    },
    positive_NEW: {
      name: "positivo_NUEVO"
    },
    set_cond_area: {
      name: "set_area_cond"
    },
    strength: {
      name: "fuerza"
    },
    timesteps: {
      name: "pasos_de_tiempo"
    }
  },
  outputs: {
    "0": {
      name: "positivo"
    },
    "1": {
      name: "negativo"
    }
  }
};
const PatchModelAddDownscale$5 = {
  display_name: "PatchModelAddDownscale (Kohya Deep Shrink)",
  inputs: {
    block_number: {
      name: "numero_de_bloque"
    },
    downscale_after_skip: {
      name: "reducción_después_de_omitir"
    },
    downscale_factor: {
      name: "factor_de_reducción"
    },
    downscale_method: {
      name: "método_de_reducción"
    },
    end_percent: {
      name: "porcentaje_final"
    },
    model: {
      name: "modelo"
    },
    start_percent: {
      name: "porcentaje_inicial"
    },
    upscale_method: {
      name: "método_de_ampliación"
    }
  }
};
const PerpNeg$5 = {
  display_name: "Perp-Neg (DEPRECATED by PerpNegGuider)",
  inputs: {
    empty_conditioning: {
      name: "condicionamiento_vacío"
    },
    model: {
      name: "modelo"
    },
    neg_scale: {
      name: "escala_neg"
    }
  }
};
const PerpNegGuider$5 = {
  display_name: "PerpNegGuider",
  inputs: {
    cfg: {
      name: "cfg"
    },
    empty_conditioning: {
      name: "condicionamiento_vacío"
    },
    model: {
      name: "modelo"
    },
    neg_scale: {
      name: "escala_neg"
    },
    negative: {
      name: "negativo"
    },
    positive: {
      name: "positivo"
    }
  }
};
const PerturbedAttentionGuidance$5 = {
  display_name: "PerturbedAttentionGuidance",
  inputs: {
    model: {
      name: "modelo"
    },
    scale: {
      name: "escala"
    }
  }
};
const PhotoMakerEncode$5 = {
  display_name: "PhotoMakerEncode",
  inputs: {
    clip: {
      name: "clip"
    },
    image: {
      name: "imagen"
    },
    photomaker: {
      name: "photomaker"
    },
    text: {
      name: "texto"
    }
  }
};
const PhotoMakerLoader$5 = {
  display_name: "PhotoMakerLoader",
  inputs: {
    photomaker_model_name: {
      name: "nombre_del_modelo_photomaker"
    }
  }
};
const PikaImageToVideoNode2_2$5 = {
  description: "Envía una imagen y un prompt a la API de Pika v2.2 para generar un video.",
  display_name: "Pika Imagen a Video",
  inputs: {
    control_after_generate: {
      name: "control después de generar"
    },
    duration: {
      name: "duración"
    },
    image: {
      name: "imagen",
      tooltip: "La imagen a convertir en video"
    },
    negative_prompt: {
      name: "prompt negativo"
    },
    prompt_text: {
      name: "texto del prompt"
    },
    resolution: {
      name: "resolución"
    },
    seed: {
      name: "semilla"
    }
  }
};
const PikaScenesV2_2$5 = {
  description: "Combina tus imágenes para crear un video con los objetos que contienen. Sube varias imágenes como ingredientes y genera un video de alta calidad que las incorpore todas.",
  display_name: "Pika Scenes (Composición de Imágenes en Video)",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio",
      tooltip: "Relación de aspecto (ancho / alto)"
    },
    control_after_generate: {
      name: "control after generate"
    },
    duration: {
      name: "duration"
    },
    image_ingredient_1: {
      name: "image_ingredient_1",
      tooltip: "Imagen que se usará como ingrediente para crear un video."
    },
    image_ingredient_2: {
      name: "image_ingredient_2",
      tooltip: "Imagen que se usará como ingrediente para crear un video."
    },
    image_ingredient_3: {
      name: "image_ingredient_3",
      tooltip: "Imagen que se usará como ingrediente para crear un video."
    },
    image_ingredient_4: {
      name: "image_ingredient_4",
      tooltip: "Imagen que se usará como ingrediente para crear un video."
    },
    image_ingredient_5: {
      name: "image_ingredient_5",
      tooltip: "Imagen que se usará como ingrediente para crear un video."
    },
    ingredients_mode: {
      name: "ingredients_mode"
    },
    negative_prompt: {
      name: "negative_prompt"
    },
    prompt_text: {
      name: "prompt_text"
    },
    resolution: {
      name: "resolution"
    },
    seed: {
      name: "seed"
    }
  }
};
const PikaStartEndFrameNode2_2$5 = {
  description: "Genera un video combinando tu primer y último fotograma. Sube dos imágenes para definir los puntos de inicio y fin, y deja que la IA cree una transición suave entre ellas.",
  display_name: "Pika: Fotograma Inicial y Final a Video",
  inputs: {
    control_after_generate: {
      name: "control después de generar"
    },
    duration: {
      name: "duración"
    },
    image_end: {
      name: "imagen_final",
      tooltip: "La última imagen a combinar."
    },
    image_start: {
      name: "imagen_inicial",
      tooltip: "La primera imagen a combinar."
    },
    negative_prompt: {
      name: "prompt_negativo"
    },
    prompt_text: {
      name: "texto_de_prompt"
    },
    resolution: {
      name: "resolución"
    },
    seed: {
      name: "semilla"
    }
  }
};
const PikaTextToVideoNode2_2$5 = {
  description: "Envía un prompt de texto a la API de Pika v2.2 para generar un video.",
  display_name: "Pika Texto a Video",
  inputs: {
    aspect_ratio: {
      name: "relación de aspecto",
      tooltip: "Relación de aspecto (ancho / alto)"
    },
    control_after_generate: {
      name: "controlar después de generar"
    },
    duration: {
      name: "duración"
    },
    negative_prompt: {
      name: "prompt negativo"
    },
    prompt_text: {
      name: "texto del prompt"
    },
    resolution: {
      name: "resolución"
    },
    seed: {
      name: "semilla"
    }
  }
};
const Pikadditions$5 = {
  description: "Agrega cualquier objeto o imagen a tu video. Sube un video y especifica lo que deseas añadir para crear un resultado perfectamente integrado.",
  display_name: "Pikadditions (Inserción de Objetos en Video)",
  inputs: {
    control_after_generate: {
      name: "control después de generar"
    },
    image: {
      name: "imagen",
      tooltip: "La imagen que se añadirá al video."
    },
    negative_prompt: {
      name: "indicación negativa"
    },
    prompt_text: {
      name: "texto de indicación"
    },
    seed: {
      name: "semilla"
    },
    video: {
      name: "video",
      tooltip: "El video al que se añadirá una imagen."
    }
  }
};
const Pikaffects$5 = {
  description: "Genera un video con un Pikaffect específico. Pikaffects soportados: Cake-ify, Crumble, Crush, Decapitate, Deflate, Dissolve, Explode, Eye-pop, Inflate, Levitate, Melt, Peel, Poke, Squish, Ta-da, Tear",
  display_name: "Pikaffects (Efectos de Video)",
  inputs: {
    control_after_generate: {
      name: "control después de generar"
    },
    image: {
      name: "imagen",
      tooltip: "La imagen de referencia a la que se aplicará el Pikaffect."
    },
    negative_prompt: {
      name: "prompt negativo"
    },
    pikaffect: {
      name: "pikaffect"
    },
    prompt_text: {
      name: "texto de prompt"
    },
    seed: {
      name: "semilla"
    }
  }
};
const Pikaswaps$5 = {
  description: "Sustituye cualquier objeto o región de tu video con una nueva imagen u objeto. Define las áreas a reemplazar usando una máscara o coordenadas.",
  display_name: "Pika Swaps (Reemplazo de Objetos en Video)",
  inputs: {
    control_after_generate: {
      name: "control después de generar"
    },
    image: {
      name: "imagen",
      tooltip: "La imagen utilizada para reemplazar el objeto enmascarado en el video."
    },
    mask: {
      name: "máscara",
      tooltip: "Usa la máscara para definir las áreas del video a reemplazar"
    },
    negative_prompt: {
      name: "prompt negativo"
    },
    prompt_text: {
      name: "texto de prompt"
    },
    seed: {
      name: "semilla"
    },
    video: {
      name: "video",
      tooltip: "El video en el que se va a intercambiar un objeto."
    }
  }
};
const PixverseImageToVideoNode$5 = {
  description: "Genera videos de forma sincrónica según el prompt y el tamaño de salida.",
  display_name: "PixVerse Imagen a Video",
  inputs: {
    control_after_generate: {
      name: "controlar después de generar"
    },
    duration_seconds: {
      name: "duración_en_segundos"
    },
    image: {
      name: "imagen"
    },
    motion_mode: {
      name: "modo_de_movimiento"
    },
    negative_prompt: {
      name: "prompt_negativo",
      tooltip: "Una descripción opcional en texto de los elementos no deseados en una imagen."
    },
    pixverse_template: {
      name: "plantilla_pixverse",
      tooltip: "Una plantilla opcional para influir en el estilo de la generación, creada por el nodo PixVerse Template."
    },
    prompt: {
      name: "prompt",
      tooltip: "Prompt para la generación del video"
    },
    quality: {
      name: "calidad"
    },
    seed: {
      name: "semilla",
      tooltip: "Semilla para la generación del video."
    }
  }
};
const PixverseTemplateNode$5 = {
  display_name: "Plantilla de PixVerse",
  inputs: {
    template: {
      name: "plantilla"
    }
  },
  outputs: {
    "0": {
      name: "plantilla_pixverse"
    }
  }
};
const PixverseTextToVideoNode$5 = {
  description: "Genera videos de forma sincrónica basados en el prompt y el tamaño de salida.",
  display_name: "PixVerse Texto a Video",
  inputs: {
    aspect_ratio: {
      name: "relación_de_aspecto"
    },
    control_after_generate: {
      name: "controlar después de generar"
    },
    duration_seconds: {
      name: "duración_segundos"
    },
    motion_mode: {
      name: "modo_de_movimiento"
    },
    negative_prompt: {
      name: "prompt_negativo",
      tooltip: "Una descripción opcional en texto de los elementos no deseados en una imagen."
    },
    pixverse_template: {
      name: "plantilla_pixverse",
      tooltip: "Una plantilla opcional para influir en el estilo de la generación, creada por el nodo PixVerse Template."
    },
    prompt: {
      name: "prompt",
      tooltip: "Prompt para la generación de video"
    },
    quality: {
      name: "calidad"
    },
    seed: {
      name: "semilla",
      tooltip: "Semilla para la generación de video."
    }
  }
};
const PixverseTransitionVideoNode$5 = {
  description: "Genera videos de forma sincrónica según el prompt y el tamaño de salida.",
  display_name: "Video de Transición PixVerse",
  inputs: {
    control_after_generate: {
      name: "controlar después de generar"
    },
    duration_seconds: {
      name: "duración en segundos"
    },
    first_frame: {
      name: "primer fotograma"
    },
    last_frame: {
      name: "último fotograma"
    },
    motion_mode: {
      name: "modo de movimiento"
    },
    negative_prompt: {
      name: "prompt negativo",
      tooltip: "Una descripción opcional en texto de los elementos no deseados en una imagen."
    },
    prompt: {
      name: "prompt",
      tooltip: "Prompt para la generación de video"
    },
    quality: {
      name: "calidad"
    },
    seed: {
      name: "semilla",
      tooltip: "Semilla para la generación de video."
    }
  }
};
const PolyexponentialScheduler$5 = {
  display_name: "PolyexponentialScheduler",
  inputs: {
    rho: {
      name: "rho"
    },
    sigma_max: {
      name: "sigma_max"
    },
    sigma_min: {
      name: "sigma_min"
    },
    steps: {
      name: "pasos"
    }
  }
};
const PorterDuffImageComposite$5 = {
  display_name: "Composición de Imagen Porter-Duff",
  inputs: {
    destination: {
      name: "destino"
    },
    destination_alpha: {
      name: "alfa_destino"
    },
    mode: {
      name: "modo"
    },
    source: {
      name: "fuente"
    },
    source_alpha: {
      name: "alfa_fuente"
    }
  }
};
const Preview3D$5 = {
  display_name: "Vista previa 3D",
  inputs: {
    camera_info: {
      name: "camera_info"
    },
    image: {
      name: "imagen"
    },
    model_file: {
      name: "archivo_modelo"
    }
  }
};
const Preview3DAnimation$5 = {
  display_name: "Vista previa 3D - Animación",
  inputs: {
    camera_info: {
      name: "camera_info"
    },
    image: {
      name: "imagen"
    },
    model_file: {
      name: "archivo_modelo"
    }
  }
};
const PreviewAny$5 = {
  display_name: "Vista previa de cualquier",
  inputs: {
    preview: {},
    source: {
      name: "fuente"
    }
  }
};
const PreviewAudio$5 = {
  display_name: "Vista previa de audio",
  inputs: {
    audio: {
      name: "audio"
    },
    audioUI: {
      name: "interfaz_audio"
    }
  }
};
const PreviewImage$5 = {
  description: "Guarda las imágenes de entrada en tu directorio de salida de ComfyUI.",
  display_name: "Vista previa de imagen",
  inputs: {
    images: {
      name: "imagenes"
    }
  }
};
const PrimitiveBoolean$5 = {
  display_name: "Booleano",
  inputs: {
    value: {
      name: "valor"
    }
  }
};
const PrimitiveFloat$5 = {
  display_name: "Flotante",
  inputs: {
    value: {
      name: "valor"
    }
  }
};
const PrimitiveInt$5 = {
  display_name: "Int",
  inputs: {
    control_after_generate: {
      name: "controlar después de generar"
    },
    value: {
      name: "valor"
    }
  }
};
const PrimitiveString$5 = {
  display_name: "Cadena",
  inputs: {
    value: {
      name: "valor"
    }
  }
};
const PrimitiveStringMultiline$5 = {
  display_name: "Cadena (Multilínea)",
  inputs: {
    value: {
      name: "valor"
    }
  }
};
const QuadrupleCLIPLoader$5 = {
  description: "[Recetas]\n\nhidream: long clip-l, long clip-g, t5xxl, llama_8b_3.1_instruct",
  display_name: "QuadrupleCLIPLoader",
  inputs: {
    clip_name1: {
      name: "clip_name1"
    },
    clip_name2: {
      name: "clip_name2"
    },
    clip_name3: {
      name: "clip_name3"
    },
    clip_name4: {
      name: "clip_name4"
    }
  }
};
const RandomNoise$5 = {
  display_name: "Ruido aleatorio",
  inputs: {
    control_after_generate: {
      name: "control después de generar"
    },
    noise_seed: {
      name: "semilla_ruido"
    }
  }
};
const RebatchImages$5 = {
  display_name: "Reagrupar imágenes",
  inputs: {
    batch_size: {
      name: "tamaño_lote"
    },
    images: {
      name: "imagenes"
    }
  }
};
const RebatchLatents$5 = {
  display_name: "Reagrupar latentes",
  inputs: {
    batch_size: {
      name: "tamaño_lote"
    },
    latents: {
      name: "latentes"
    }
  }
};
const RecraftColorRGB$5 = {
  description: "Crea un Recraft Color eligiendo valores RGB específicos.",
  display_name: "Recraft Color RGB",
  inputs: {
    b: {
      name: "b",
      tooltip: "Valor azul del color."
    },
    g: {
      name: "g",
      tooltip: "Valor verde del color."
    },
    r: {
      name: "r",
      tooltip: "Valor rojo del color."
    },
    recraft_color: {
      name: "recraft_color"
    }
  },
  outputs: {
    "0": {
      name: "recraft_color"
    }
  }
};
const RecraftControls$5 = {
  description: "Crea Controles de Recraft para personalizar la generación de Recraft.",
  display_name: "Controles de Recraft",
  inputs: {
    background_color: {
      name: "color_de_fondo"
    },
    colors: {
      name: "colores"
    }
  },
  outputs: {
    "0": {
      name: "controles_recraft"
    }
  }
};
const RecraftCreativeUpscaleNode$5 = {
  description: "Aumenta la imagen de forma sincrónica.\nMejora una imagen ráster dada utilizando la herramienta de ‘creative upscale’, aumentando la resolución con un enfoque en refinar pequeños detalles y rostros.",
  display_name: "Recraft Creative Upscale Image",
  inputs: {
    image: {
      name: "imagen"
    }
  }
};
const RecraftCrispUpscaleNode$5 = {
  description: "Aumenta la imagen de forma sincrónica.\nMejora una imagen ráster dada usando la herramienta ‘crisp upscale’, aumentando la resolución de la imagen y haciéndola más nítida y clara.",
  display_name: "Recraft Crisp Upscale Image",
  inputs: {
    image: {
      name: "imagen"
    }
  }
};
const RecraftImageInpaintingNode$5 = {
  description: "Modifica la imagen según el prompt y la mask.",
  display_name: "Recraft Relleno de Imagen",
  inputs: {
    control_after_generate: {
      name: "control después de generar"
    },
    image: {
      name: "imagen"
    },
    mask: {
      name: "mask"
    },
    n: {
      name: "n",
      tooltip: "El número de imágenes a generar."
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Una descripción opcional en texto de los elementos no deseados en una imagen."
    },
    prompt: {
      name: "prompt",
      tooltip: "Prompt para la generación de la imagen."
    },
    recraft_style: {
      name: "recraft_style"
    },
    seed: {
      name: "semilla",
      tooltip: "Semilla para determinar si el nodo debe ejecutarse de nuevo; los resultados reales son no deterministas independientemente de la semilla."
    }
  }
};
const RecraftImageToImageNode$5 = {
  description: "Modifica la imagen según el prompt y la intensidad.",
  display_name: "Recraft Imagen a Imagen",
  inputs: {
    control_after_generate: {
      name: "control after generate"
    },
    image: {
      name: "imagen"
    },
    n: {
      name: "n",
      tooltip: "El número de imágenes a generar."
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Una descripción opcional en texto de los elementos no deseados en una imagen."
    },
    prompt: {
      name: "prompt",
      tooltip: "Prompt para la generación de la imagen."
    },
    recraft_controls: {
      name: "recraft_controls",
      tooltip: "Controles adicionales opcionales sobre la generación a través del nodo Recraft Controls."
    },
    recraft_style: {
      name: "recraft_style"
    },
    seed: {
      name: "semilla",
      tooltip: "Semilla para determinar si el nodo debe volver a ejecutarse; los resultados reales son no deterministas independientemente de la semilla."
    },
    strength: {
      name: "intensidad",
      tooltip: "Define la diferencia con la imagen original, debe estar en [0, 1], donde 0 significa casi idéntica y 1 significa muy poca similitud."
    }
  }
};
const RecraftRemoveBackgroundNode$5 = {
  description: "Elimina el fondo de la imagen y devuelve la imagen procesada y la máscara.",
  display_name: "Recraft Remove Background",
  inputs: {
    image: {
      name: "imagen"
    }
  }
};
const RecraftReplaceBackgroundNode$5 = {
  description: "Reemplaza el fondo de una imagen, basado en el prompt proporcionado.",
  display_name: "Recraft Reemplazar Fondo",
  inputs: {
    control_after_generate: {
      name: "control after generate"
    },
    image: {
      name: "imagen"
    },
    n: {
      name: "n",
      tooltip: "El número de imágenes a generar."
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Una descripción de texto opcional de los elementos no deseados en una imagen."
    },
    prompt: {
      name: "prompt",
      tooltip: "Prompt para la generación de la imagen."
    },
    recraft_style: {
      name: "recraft_style"
    },
    seed: {
      name: "semilla",
      tooltip: "Semilla para determinar si el nodo debe ejecutarse de nuevo; los resultados reales son no deterministas independientemente de la semilla."
    }
  }
};
const RecraftStyleV3DigitalIllustration$5 = {
  description: "Selecciona el estilo realistic_image y un subestilo opcional.",
  display_name: "Estilo Recraft - Ilustración Digital",
  inputs: {
    substyle: {
      name: "subestilo"
    }
  },
  outputs: {
    "0": {
      name: "estilo_recraft"
    }
  }
};
const RecraftStyleV3InfiniteStyleLibrary$5 = {
  description: "Selecciona un estilo basado en el UUID preexistente de la Biblioteca de Estilos Infinita de Recraft.",
  display_name: "Recraft Style - Biblioteca de Estilos Infinita",
  inputs: {
    style_id: {
      name: "style_id",
      tooltip: "UUID del estilo de la Biblioteca de Estilos Infinita."
    }
  },
  outputs: {
    "0": {
      name: "recraft_style"
    }
  }
};
const RecraftStyleV3LogoRaster$5 = {
  description: "Selecciona el estilo realistic_image y un subestilo opcional.",
  display_name: "Recraft Style - Logo Raster",
  inputs: {
    substyle: {
      name: "subestilo"
    }
  },
  outputs: {
    "0": {
      name: "recraft_style"
    }
  }
};
const RecraftStyleV3RealisticImage$5 = {
  description: "Selecciona el estilo realistic_image y un subestilo opcional.",
  display_name: "Recraft Style - Imagen Realista",
  inputs: {
    substyle: {
      name: "subestilo"
    }
  },
  outputs: {
    "0": {
      name: "recraft_style"
    }
  }
};
const RecraftTextToImageNode$5 = {
  description: "Genera imágenes de forma sincrónica según el prompt y la resolución.",
  display_name: "Recraft Texto a Imagen",
  inputs: {
    control_after_generate: {
      name: "controlar después de generar"
    },
    n: {
      name: "n",
      tooltip: "La cantidad de imágenes a generar."
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Una descripción opcional en texto de los elementos no deseados en una imagen."
    },
    prompt: {
      name: "prompt",
      tooltip: "Prompt para la generación de la imagen."
    },
    recraft_controls: {
      name: "recraft_controls",
      tooltip: "Controles adicionales opcionales sobre la generación a través del nodo Recraft Controls."
    },
    recraft_style: {
      name: "recraft_style"
    },
    seed: {
      name: "semilla",
      tooltip: "Semilla para determinar si el nodo debe volver a ejecutarse; los resultados reales son no deterministas independientemente de la semilla."
    },
    size: {
      name: "tamaño",
      tooltip: "El tamaño de la imagen generada."
    }
  }
};
const RecraftTextToVectorNode$5 = {
  description: "Genera SVG de forma sincrónica según el prompt y la resolución.",
  display_name: "Recraft Texto a Vector",
  inputs: {
    control_after_generate: {
      name: "control después de generar"
    },
    n: {
      name: "n",
      tooltip: "La cantidad de imágenes a generar."
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Una descripción opcional en texto de los elementos no deseados en una imagen."
    },
    prompt: {
      name: "prompt",
      tooltip: "Prompt para la generación de la imagen."
    },
    recraft_controls: {
      name: "recraft_controls",
      tooltip: "Controles adicionales opcionales sobre la generación a través del nodo Recraft Controls."
    },
    seed: {
      name: "semilla",
      tooltip: "Semilla para determinar si el nodo debe ejecutarse de nuevo; los resultados reales son no deterministas independientemente de la semilla."
    },
    size: {
      name: "tamaño",
      tooltip: "El tamaño de la imagen generada."
    },
    substyle: {
      name: "substyle"
    }
  }
};
const RecraftVectorizeImageNode$5 = {
  description: "Genera SVG de forma sincrónica a partir de una imagen de entrada.",
  display_name: "Recraft Vectorizar Imagen",
  inputs: {
    image: {
      name: "imagen"
    }
  }
};
const RenormCFG$5 = {
  display_name: "RenormCFG",
  inputs: {
    cfg_trunc: {
      name: "cfg_trunc"
    },
    model: {
      name: "modelo"
    },
    renorm_cfg: {
      name: "renorm_cfg"
    }
  }
};
const RepeatImageBatch$5 = {
  display_name: "Repetir lote de imágenes",
  inputs: {
    amount: {
      name: "cantidad"
    },
    image: {
      name: "imagen"
    }
  }
};
const RepeatLatentBatch$5 = {
  display_name: "Repetir lote latente",
  inputs: {
    amount: {
      name: "cantidad"
    },
    samples: {
      name: "muestras"
    }
  }
};
const RescaleCFG$5 = {
  display_name: "ReescalarCFG",
  inputs: {
    model: {
      name: "modelo"
    },
    multiplier: {
      name: "multiplicador"
    }
  }
};
const SDTurboScheduler$5 = {
  display_name: "SDTurboScheduler",
  inputs: {
    denoise: {
      name: "reducir_ruido"
    },
    model: {
      name: "modelo"
    },
    steps: {
      name: "pasos"
    }
  }
};
const SD_4XUpscale_Conditioning$5 = {
  display_name: "SD_4XUpscale_Conditioning",
  inputs: {
    images: {
      name: "imágenes"
    },
    negative: {
      name: "negativo"
    },
    noise_augmentation: {
      name: "aumento_ruido"
    },
    positive: {
      name: "positivo"
    },
    scale_ratio: {
      name: "relación_escala"
    }
  },
  outputs: {
    "0": {
      name: "positivo"
    },
    "1": {
      name: "negativo"
    },
    "2": {
      name: "latente"
    }
  }
};
const SV3D_Conditioning$5 = {
  display_name: "SV3D_Acondicionamiento",
  inputs: {
    clip_vision: {
      name: "clip_vision"
    },
    elevation: {
      name: "elevación"
    },
    height: {
      name: "altura"
    },
    init_image: {
      name: "imagen_inicial"
    },
    vae: {
      name: "vae"
    },
    video_frames: {
      name: "cuadros_de_video"
    },
    width: {
      name: "ancho"
    }
  },
  outputs: {
    "0": {
      name: "positivo"
    },
    "1": {
      name: "negativo"
    },
    "2": {
      name: "latente"
    }
  }
};
const SVD_img2vid_Conditioning$5 = {
  display_name: "SVD_img2vid_Acondicionamiento",
  inputs: {
    augmentation_level: {
      name: "nivel_de_aumento"
    },
    clip_vision: {
      name: "clip_vision"
    },
    fps: {
      name: "fps"
    },
    height: {
      name: "altura"
    },
    init_image: {
      name: "imagen_inicial"
    },
    motion_bucket_id: {
      name: "id_del_cubeta_de_movimiento"
    },
    vae: {
      name: "vae"
    },
    video_frames: {
      name: "cuadros_de_video"
    },
    width: {
      name: "ancho"
    }
  },
  outputs: {
    "0": {
      name: "positivo"
    },
    "1": {
      name: "negativo"
    },
    "2": {
      name: "latente"
    }
  }
};
const SamplerCustom$5 = {
  display_name: "Muestreador personalizado",
  inputs: {
    add_noise: {
      name: "añadir_ruido"
    },
    cfg: {
      name: "cfg"
    },
    control_after_generate: {
      name: "control después de generar"
    },
    latent_image: {
      name: "imagen_latente"
    },
    model: {
      name: "modelo"
    },
    negative: {
      name: "negativo"
    },
    noise_seed: {
      name: "semilla_ruido"
    },
    positive: {
      name: "positivo"
    },
    sampler: {
      name: "muestreador"
    },
    sigmas: {
      name: "sigmas"
    }
  },
  outputs: {
    "0": {
      name: "salida"
    },
    "1": {
      name: "salida_denoisada"
    }
  }
};
const SamplerCustomAdvanced$5 = {
  display_name: "SamplerCustomAdvanced",
  inputs: {
    guider: {
      name: "guía"
    },
    latent_image: {
      name: "imagen_latente"
    },
    noise: {
      name: "ruido"
    },
    sampler: {
      name: "muestreador"
    },
    sigmas: {
      name: "sigmas"
    }
  },
  outputs: {
    "0": {
      name: "salida"
    },
    "1": {
      name: "salida_denoised"
    }
  }
};
const SamplerDPMAdaptative$5 = {
  display_name: "SamplerDPMAdaptative",
  inputs: {
    accept_safety: {
      name: "aceptar_seguridad"
    },
    atol: {
      name: "atol"
    },
    dcoeff: {
      name: "dcoeff"
    },
    eta: {
      name: "eta"
    },
    h_init: {
      name: "h_init"
    },
    icoeff: {
      name: "icoeff"
    },
    order: {
      name: "orden"
    },
    pcoeff: {
      name: "pcoeff"
    },
    rtol: {
      name: "rtol"
    },
    s_noise: {
      name: "s_ruido"
    }
  }
};
const SamplerDPMPP_2M_SDE$5 = {
  display_name: "SamplerDPMPP_2M_SDE",
  inputs: {
    eta: {
      name: "eta"
    },
    noise_device: {
      name: "dispositivo_ruido"
    },
    s_noise: {
      name: "s_ruido"
    },
    solver_type: {
      name: "tipo_resolvedor"
    }
  }
};
const SamplerDPMPP_2S_Ancestral$5 = {
  display_name: "SamplerDPMPP_2S_Ancestral",
  inputs: {
    eta: {
      name: "eta"
    },
    s_noise: {
      name: "s_ruido"
    }
  }
};
const SamplerDPMPP_3M_SDE$5 = {
  display_name: "SamplerDPMPP_3M_SDE",
  inputs: {
    eta: {
      name: "eta"
    },
    noise_device: {
      name: "dispositivo_ruido"
    },
    s_noise: {
      name: "s_ruido"
    }
  }
};
const SamplerDPMPP_SDE$5 = {
  display_name: "SamplerDPMPP_SDE",
  inputs: {
    eta: {
      name: "eta"
    },
    noise_device: {
      name: "dispositivo_ruido"
    },
    r: {
      name: "r"
    },
    s_noise: {
      name: "s_ruido"
    }
  }
};
const SamplerEulerAncestral$5 = {
  display_name: "SamplerEulerAncestral",
  inputs: {
    eta: {
      name: "eta"
    },
    s_noise: {
      name: "s_ruido"
    }
  }
};
const SamplerEulerAncestralCFGPP$5 = {
  display_name: "SamplerEulerAncestralCFG++",
  inputs: {
    eta: {
      name: "eta"
    },
    s_noise: {
      name: "s_ruido"
    }
  }
};
const SamplerEulerCFGpp$5 = {
  display_name: "SamplerEulerCFG++",
  inputs: {
    version: {
      name: "versión"
    }
  }
};
const SamplerLCMUpscale$5 = {
  display_name: "SamplerLCMUpscale",
  inputs: {
    scale_ratio: {
      name: "relación_escala"
    },
    scale_steps: {
      name: "pasos_escala"
    },
    upscale_method: {
      name: "método_aumento_escala"
    }
  }
};
const SamplerLMS$5 = {
  display_name: "SamplerLMS",
  inputs: {
    order: {
      name: "orden"
    }
  }
};
const SaveAnimatedPNG$5 = {
  display_name: "GuardarPNGAnimado",
  inputs: {
    compress_level: {
      name: "nivel_compresión"
    },
    filename_prefix: {
      name: "prefijo_nombre_archivo"
    },
    fps: {
      name: "fps"
    },
    images: {
      name: "imágenes"
    }
  }
};
const SaveAnimatedWEBP$5 = {
  display_name: "GuardarWEBPAnimado",
  inputs: {
    filename_prefix: {
      name: "prefijo_nombre_archivo"
    },
    fps: {
      name: "fps"
    },
    images: {
      name: "imágenes"
    },
    lossless: {
      name: "sin_pérdidas"
    },
    method: {
      name: "método"
    },
    quality: {
      name: "calidad"
    }
  }
};
const SaveAudio$5 = {
  display_name: "GuardarAudio",
  inputs: {
    audio: {
      name: "audio"
    },
    audioUI: {
      name: "interfaz_audio"
    },
    filename_prefix: {
      name: "prefijo_nombre_archivo"
    }
  }
};
const SaveGLB$5 = {
  display_name: "GuardarGLB",
  inputs: {
    filename_prefix: {
      name: "prefijo_nombre_archivo"
    },
    image: {
      name: "imagen"
    },
    mesh: {
      name: "malla"
    }
  }
};
const SaveImage$5 = {
  description: "Guarda las imágenes de entrada en tu directorio de salida de ComfyUI.",
  display_name: "Guardar Imagen",
  inputs: {
    filename_prefix: {
      name: "prefijo_nombre_archivo",
      tooltip: "El prefijo para el archivo a guardar. Esto puede incluir información de formato como %date:yyyy-MM-dd% o %Empty Latent Image.width% para incluir valores de los nodos."
    },
    images: {
      name: "imágenes",
      tooltip: "Las imágenes a guardar."
    }
  }
};
const SaveImageWebsocket$5 = {
  display_name: "GuardarImagenWebsocket",
  inputs: {
    images: {
      name: "imágenes"
    }
  }
};
const SaveLatent$5 = {
  display_name: "GuardarLatente",
  inputs: {
    filename_prefix: {
      name: "prefijo_nombre_archivo"
    },
    samples: {
      name: "muestras"
    }
  }
};
const SaveSVG$5 = {
  description: "Guardar archivos SVG en el disco.",
  display_name: "Guardar SVG",
  inputs: {
    filename_prefix: {
      name: "prefijo_de_archivo",
      tooltip: "El prefijo para el archivo a guardar. Esto puede incluir información de formato como %date:yyyy-MM-dd% o %Empty Latent Image.width% para incluir valores de los nodos."
    },
    svg: {
      name: "svg"
    }
  }
};
const SaveVideo$5 = {
  description: "Guarda las imágenes de entrada en tu directorio de salida de ComfyUI.",
  display_name: "Guardar video",
  inputs: {
    codec: {
      name: "códec",
      tooltip: "El códec que se usará para el video."
    },
    filename_prefix: {
      name: "prefijo_nombre_archivo",
      tooltip: "El prefijo para el archivo a guardar. Esto puede incluir información de formato como %date:yyyy-MM-dd% o %Empty Latent Image.width% para incluir valores de los nodos."
    },
    format: {
      name: "formato",
      tooltip: "El formato en el que se guardará el video."
    },
    video: {
      name: "video",
      tooltip: "El video que se va a guardar."
    }
  }
};
const SaveWEBM$5 = {
  display_name: "GuardarWEBM",
  inputs: {
    codec: {
      name: "códec"
    },
    crf: {
      name: "crf",
      tooltip: "Un crf más alto significa menor calidad con un tamaño de archivo más pequeño, un crf más bajo significa mayor calidad con un tamaño de archivo más grande."
    },
    filename_prefix: {
      name: "prefijo_nombre_archivo"
    },
    fps: {
      name: "fps"
    },
    images: {
      name: "imágenes"
    }
  }
};
const SelfAttentionGuidance$5 = {
  display_name: "Orientación de Auto-Atención",
  inputs: {
    blur_sigma: {
      name: "blur_sigma"
    },
    model: {
      name: "modelo"
    },
    scale: {
      name: "escala"
    }
  }
};
const SetClipHooks$5 = {
  display_name: "Establecer Ganchos CLIP",
  inputs: {
    apply_to_conds: {
      name: "aplicar_a_conds"
    },
    clip: {
      name: "clip"
    },
    hooks: {
      name: "ganchos"
    },
    schedule_clip: {
      name: "programar_clip"
    }
  }
};
const SetFirstSigma$5 = {
  display_name: "EstablecerPrimeraSigma",
  inputs: {
    sigma: {
      name: "sigma"
    },
    sigmas: {
      name: "sigmas"
    }
  }
};
const SetHookKeyframes$5 = {
  display_name: "Establecer Fotogramas Clave de Gancho",
  inputs: {
    hook_kf: {
      name: "gancho_kf"
    },
    hooks: {
      name: "ganchos"
    }
  }
};
const SetLatentNoiseMask$5 = {
  display_name: "Establecer Máscara de Ruido Latente",
  inputs: {
    mask: {
      name: "máscara"
    },
    samples: {
      name: "muestras"
    }
  }
};
const SetUnionControlNetType$5 = {
  display_name: "EstablecerTipoDeRedDeControlUnion",
  inputs: {
    control_net: {
      name: "controlnet"
    },
    type: {
      name: "tipo"
    }
  }
};
const SkipLayerGuidanceDiT$5 = {
  description: "Versión genérica del nodo de Orientación de Capa de Salto que se puede usar en cada modelo DiT.",
  display_name: "Orientación de Capa de Salto DiT",
  inputs: {
    double_layers: {
      name: "capas_dobles"
    },
    end_percent: {
      name: "porcentaje_final"
    },
    model: {
      name: "modelo"
    },
    rescaling_scale: {
      name: "escala_reescalado"
    },
    scale: {
      name: "escala"
    },
    single_layers: {
      name: "capas_simples"
    },
    start_percent: {
      name: "porcentaje_inicio"
    }
  }
};
const SkipLayerGuidanceSD3$5 = {
  description: "Versión genérica del nodo de Orientación de Capa de Salto que se puede usar en cada modelo DiT.",
  display_name: "Orientación de Capa de Salto SD3",
  inputs: {
    end_percent: {
      name: "porcentaje_final"
    },
    layers: {
      name: "capas"
    },
    model: {
      name: "modelo"
    },
    scale: {
      name: "escala"
    },
    start_percent: {
      name: "porcentaje_inicio"
    }
  }
};
const SolidMask$5 = {
  display_name: "Máscara Sólida",
  inputs: {
    height: {
      name: "altura"
    },
    value: {
      name: "valor"
    },
    width: {
      name: "ancho"
    }
  }
};
const SplitImageWithAlpha$5 = {
  display_name: "Dividir Imagen con Alfa",
  inputs: {
    image: {
      name: "imagen"
    }
  }
};
const SplitSigmas$5 = {
  display_name: "DividirSigmas",
  inputs: {
    sigmas: {
      name: "sigmas"
    },
    step: {
      name: "paso"
    }
  },
  outputs: {
    "0": {
      name: "sigmas_altas"
    },
    "1": {
      name: "sigmas_bajas"
    }
  }
};
const SplitSigmasDenoise$5 = {
  display_name: "SplitSigmasDenoise",
  inputs: {
    denoise: {
      name: "denoise"
    },
    sigmas: {
      name: "sigmas"
    }
  },
  outputs: {
    "0": {
      name: "high_sigmas"
    },
    "1": {
      name: "low_sigmas"
    }
  }
};
const StabilityStableImageSD_3_5Node$5 = {
  description: "Genera imágenes de forma sincrónica según el prompt y la resolución.",
  display_name: "Stability AI Stable Diffusion 3.5 Imagen",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio",
      tooltip: "Relación de aspecto de la imagen generada."
    },
    cfg_scale: {
      name: "cfg_scale",
      tooltip: "Qué tan estrictamente el proceso de difusión se adhiere al texto del prompt (valores más altos mantienen la imagen más cercana a tu prompt)."
    },
    control_after_generate: {
      name: "control after generate"
    },
    image: {
      name: "image"
    },
    image_denoise: {
      name: "image_denoise",
      tooltip: "Reducción de ruido de la imagen de entrada; 0.0 produce una imagen idéntica a la entrada, 1.0 es como si no se hubiera proporcionado ninguna imagen."
    },
    model: {
      name: "model"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Palabras clave de lo que no deseas ver en la imagen de salida. Esta es una función avanzada."
    },
    prompt: {
      name: "prompt",
      tooltip: "Lo que deseas ver en la imagen de salida. Un prompt fuerte y descriptivo que defina claramente los elementos, colores y sujetos dará mejores resultados."
    },
    seed: {
      name: "seed",
      tooltip: "La semilla aleatoria utilizada para crear el ruido."
    },
    style_preset: {
      name: "style_preset",
      tooltip: "Estilo opcional deseado para la imagen generada."
    }
  }
};
const StabilityStableImageUltraNode$5 = {
  description: "Genera imágenes de forma sincrónica según el prompt y la resolución.",
  display_name: "Stability AI Stable Image Ultra",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio",
      tooltip: "Relación de aspecto de la imagen generada."
    },
    control_after_generate: {
      name: "control after generate"
    },
    image: {
      name: "image"
    },
    image_denoise: {
      name: "image_denoise",
      tooltip: "Nivel de eliminación de ruido de la imagen de entrada; 0.0 produce una imagen idéntica a la entrada, 1.0 es como si no se hubiera proporcionado ninguna imagen."
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Un texto que describe lo que no deseas ver en la imagen de salida. Esta es una función avanzada."
    },
    prompt: {
      name: "prompt",
      tooltip: "Lo que deseas ver en la imagen de salida. Un prompt fuerte y descriptivo que defina claramente los elementos, colores y sujetos dará mejores resultados. Para controlar el peso de una palabra usa el formato `(palabra:peso)`, donde `palabra` es la palabra cuyo peso deseas controlar y `peso` es un valor entre 0 y 1. Por ejemplo: `El cielo era de un (azul:0.3) y (verde:0.8) nítidos` indicará un cielo azul y verde, pero más verde que azul."
    },
    seed: {
      name: "seed",
      tooltip: "La semilla aleatoria utilizada para crear el ruido."
    },
    style_preset: {
      name: "style_preset",
      tooltip: "Estilo opcional deseado para la imagen generada."
    }
  }
};
const StabilityUpscaleConservativeNode$5 = {
  description: "Aumenta la resolución de la imagen a 4K con alteraciones mínimas.",
  display_name: "Stability AI Upscale Conservador",
  inputs: {
    control_after_generate: {
      name: "controlar después de generar"
    },
    creativity: {
      name: "creatividad",
      tooltip: "Controla la probabilidad de crear detalles adicionales que no estén fuertemente condicionados por la imagen inicial."
    },
    image: {
      name: "imagen"
    },
    negative_prompt: {
      name: "prompt negativo",
      tooltip: "Palabras clave de lo que no deseas ver en la imagen de salida. Esta es una función avanzada."
    },
    prompt: {
      name: "prompt",
      tooltip: "Lo que deseas ver en la imagen de salida. Un prompt fuerte y descriptivo que defina claramente los elementos, colores y sujetos dará mejores resultados."
    },
    seed: {
      name: "semilla",
      tooltip: "La semilla aleatoria utilizada para crear el ruido."
    }
  }
};
const StabilityUpscaleCreativeNode$5 = {
  description: "Aumenta la resolución de la imagen a 4K con alteraciones mínimas.",
  display_name: "Stability AI Upscale Creative",
  inputs: {
    control_after_generate: {
      name: "controlar después de generar"
    },
    creativity: {
      name: "creatividad",
      tooltip: "Controla la probabilidad de crear detalles adicionales que no estén fuertemente condicionados por la imagen inicial."
    },
    image: {
      name: "imagen"
    },
    negative_prompt: {
      name: "prompt negativo",
      tooltip: "Palabras clave de lo que no deseas ver en la imagen de salida. Esta es una función avanzada."
    },
    prompt: {
      name: "prompt",
      tooltip: "Lo que deseas ver en la imagen de salida. Un prompt fuerte y descriptivo que defina claramente los elementos, colores y sujetos dará mejores resultados."
    },
    seed: {
      name: "semilla",
      tooltip: "La semilla aleatoria utilizada para crear el ruido."
    },
    style_preset: {
      name: "estilo predefinido",
      tooltip: "Estilo opcional deseado para la imagen generada."
    }
  }
};
const StabilityUpscaleFastNode$5 = {
  description: "Aumenta rápidamente una imagen a 4x su tamaño original mediante una llamada a la API de Stability; pensado para mejorar imágenes de baja calidad o comprimidas.",
  display_name: "Stability AI Escalado Rápido",
  inputs: {
    image: {
      name: "imagen"
    }
  }
};
const StableCascade_EmptyLatentImage$5 = {
  display_name: "StableCascade_EmptyLatentImage",
  inputs: {
    batch_size: {
      name: "tamaño_del_lote"
    },
    compression: {
      name: "compresión"
    },
    height: {
      name: "altura"
    },
    width: {
      name: "ancho"
    }
  },
  outputs: {
    "0": {
      name: "etapa_c"
    },
    "1": {
      name: "etapa_b"
    }
  }
};
const StableCascade_StageB_Conditioning$5 = {
  display_name: "StableCascade_StageB_Conditioning",
  inputs: {
    conditioning: {
      name: "acondicionamiento"
    },
    stage_c: {
      name: "etapa_c"
    }
  }
};
const StableCascade_StageC_VAEEncode$5 = {
  display_name: "StableCascade_StageC_VAEEncode",
  inputs: {
    compression: {
      name: "compresión"
    },
    image: {
      name: "imagen"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "etapa_c"
    },
    "1": {
      name: "etapa_b"
    }
  }
};
const StableCascade_SuperResolutionControlnet$5 = {
  display_name: "StableCascade_SuperResolutionControlnet",
  inputs: {
    image: {
      name: "imagen"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "entrada_controlnet"
    },
    "1": {
      name: "etapa_c"
    },
    "2": {
      name: "etapa_b"
    }
  }
};
const StableZero123_Conditioning$5 = {
  display_name: "StableZero123_Conditioning",
  inputs: {
    azimuth: {
      name: "acimut"
    },
    batch_size: {
      name: "tamaño_del_lote"
    },
    clip_vision: {
      name: "visión_clip"
    },
    elevation: {
      name: "elevación"
    },
    height: {
      name: "altura"
    },
    init_image: {
      name: "imagen_inicial"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "ancho"
    }
  },
  outputs: {
    "0": {
      name: "positivo"
    },
    "1": {
      name: "negativo"
    },
    "2": {
      name: "latente"
    }
  }
};
const StableZero123_Conditioning_Batched$5 = {
  display_name: "StableZero123_Conditioning_Batched",
  inputs: {
    azimuth: {
      name: "acimut"
    },
    azimuth_batch_increment: {
      name: "incremento_de_lote_de_acimut"
    },
    batch_size: {
      name: "tamaño_del_lote"
    },
    clip_vision: {
      name: "clip_vision"
    },
    elevation: {
      name: "elevación"
    },
    elevation_batch_increment: {
      name: "incremento_de_lote_de_elevación"
    },
    height: {
      name: "altura"
    },
    init_image: {
      name: "imagen_inicial"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "ancho"
    }
  },
  outputs: {
    "0": {
      name: "positivo"
    },
    "1": {
      name: "negativo"
    },
    "2": {
      name: "latente"
    }
  }
};
const StyleModelApply$5 = {
  display_name: "Aplicar Modelo de Estilo",
  inputs: {
    clip_vision_output: {
      name: "salida_de_clip_vision"
    },
    conditioning: {
      name: "acondicionamiento"
    },
    strength: {
      name: "fuerza"
    },
    strength_type: {
      name: "tipo_de_fuerza"
    },
    style_model: {
      name: "modelo_de_estilo"
    }
  }
};
const StyleModelLoader$5 = {
  display_name: "Cargar Modelo de Estilo",
  inputs: {
    style_model_name: {
      name: "nombre_del_modelo_de_estilo"
    }
  }
};
const T5TokenizerOptions$5 = {
  display_name: "T5TokenizerOptions",
  inputs: {
    clip: {
      name: "clip"
    },
    min_length: {
      name: "mín_longitud"
    },
    min_padding: {
      name: "mín_relleno"
    }
  }
};
const TextEncodeHunyuanVideo_ImageToVideo$5 = {
  display_name: "TextEncodeHunyuanVideo_ImagenAVideo",
  inputs: {
    clip: {
      name: "clip"
    },
    clip_vision_output: {
      name: "salida_de_clip_vision"
    },
    image_interleave: {
      name: "entrelazado_de_imagen",
      tooltip: "Cuánto influye la imagen en las cosas frente al indicación de texto. Un número más alto significa más influencia del indicación de texto."
    },
    prompt: {
      name: "indicación"
    }
  }
};
const ThresholdMask$5 = {
  display_name: "Máscara de Umbral",
  inputs: {
    mask: {
      name: "máscara"
    },
    value: {
      name: "valor"
    }
  }
};
const TomePatchModel$5 = {
  display_name: "Modelo de Parche Tome",
  inputs: {
    model: {
      name: "modelo"
    },
    ratio: {
      name: "ratio"
    }
  }
};
const TorchCompileModel$5 = {
  display_name: "Modelo de Compilación Torch",
  inputs: {
    backend: {
      name: "backend"
    },
    model: {
      name: "modelo"
    }
  }
};
const TrimVideoLatent$5 = {
  display_name: "TrimVideoLatent",
  inputs: {
    samples: {
      name: "muestras"
    },
    trim_amount: {
      name: "cantidad_de_recorte"
    }
  }
};
const TripleCLIPLoader$5 = {
  description: "[Recetas]\n\nsd3: clip-l, clip-g, t5",
  display_name: "Cargador Triple CLIP",
  inputs: {
    clip_name1: {
      name: "nombre_clip1"
    },
    clip_name2: {
      name: "nombre_clip2"
    },
    clip_name3: {
      name: "nombre_clip3"
    }
  }
};
const UNETLoader$5 = {
  display_name: "Cargar Modelo de Difusión",
  inputs: {
    unet_name: {
      name: "nombre_unet"
    },
    weight_dtype: {
      name: "tipo_dato_peso"
    }
  }
};
const UNetCrossAttentionMultiply$5 = {
  display_name: "Multiplicación de Atención Cruzada UNet",
  inputs: {
    k: {
      name: "k"
    },
    model: {
      name: "modelo"
    },
    out: {
      name: "salida"
    },
    q: {
      name: "q"
    },
    v: {
      name: "v"
    }
  }
};
const UNetSelfAttentionMultiply$5 = {
  display_name: "Multiplicación de Auto Atención UNet",
  inputs: {
    k: {
      name: "k"
    },
    model: {
      name: "modelo"
    },
    out: {
      name: "salida"
    },
    q: {
      name: "q"
    },
    v: {
      name: "v"
    }
  }
};
const UNetTemporalAttentionMultiply$5 = {
  display_name: "Multiplicación de Atención Temporal UNet",
  inputs: {
    cross_structural: {
      name: "cruz_estructural"
    },
    cross_temporal: {
      name: "cruz_temporal"
    },
    model: {
      name: "modelo"
    },
    self_structural: {
      name: "auto_estructural"
    },
    self_temporal: {
      name: "auto_temporal"
    }
  }
};
const UpscaleModelLoader$5 = {
  display_name: "Cargar Modelo de Escala Superior",
  inputs: {
    model_name: {
      name: "nombre_modelo"
    }
  }
};
const VAEDecode$5 = {
  description: "Decodifica imágenes latentes de nuevo en imágenes de espacio de píxeles.",
  display_name: "Decodificación VAE",
  inputs: {
    samples: {
      name: "muestras",
      tooltip: "El latente a ser decodificado."
    },
    vae: {
      name: "vae",
      tooltip: "El modelo VAE utilizado para decodificar el latente."
    }
  },
  outputs: {
    "0": {
      tooltip: "La imagen decodificada."
    }
  }
};
const VAEDecodeAudio$5 = {
  display_name: "VAEDecodeAudio",
  inputs: {
    samples: {
      name: "muestras"
    },
    vae: {
      name: "vae"
    }
  }
};
const VAEDecodeHunyuan3D$5 = {
  display_name: "VAEDecodeHunyuan3D",
  inputs: {
    num_chunks: {
      name: "num_chunks"
    },
    octree_resolution: {
      name: "resolución_octree"
    },
    samples: {
      name: "muestras"
    },
    vae: {
      name: "vae"
    }
  }
};
const VAEDecodeTiled$5 = {
  display_name: "VAE Decodificar (Mosaico)",
  inputs: {
    overlap: {
      name: "superposición"
    },
    samples: {
      name: "muestras"
    },
    temporal_overlap: {
      name: "superposición_temporal",
      tooltip: "Solo se utiliza para VAEs de video: Cantidad de fotogramas para superponer."
    },
    temporal_size: {
      name: "tamaño_temporal",
      tooltip: "Solo se utiliza para VAEs de video: Cantidad de fotogramas para decodificar a la vez."
    },
    tile_size: {
      name: "tamaño_mosaico"
    },
    vae: {
      name: "vae"
    }
  }
};
const VAEEncode$5 = {
  display_name: "VAE Codificar",
  inputs: {
    pixels: {
      name: "píxeles"
    },
    vae: {
      name: "vae"
    }
  }
};
const VAEEncodeAudio$5 = {
  display_name: "VAEEncodeAudio",
  inputs: {
    audio: {
      name: "audio"
    },
    vae: {
      name: "vae"
    }
  }
};
const VAEEncodeForInpaint$5 = {
  display_name: "VAE Codificar (para Inpainting)",
  inputs: {
    grow_mask_by: {
      name: "crecer_máscara_por"
    },
    mask: {
      name: "máscara"
    },
    pixels: {
      name: "píxeles"
    },
    vae: {
      name: "vae"
    }
  }
};
const VAEEncodeTiled$5 = {
  display_name: "VAE Codificar (Mosaico)",
  inputs: {
    overlap: {
      name: "superposición"
    },
    pixels: {
      name: "píxeles"
    },
    temporal_overlap: {
      name: "superposición_temporal",
      tooltip: "Solo se utiliza para VAEs de video: Cantidad de fotogramas para superponer."
    },
    temporal_size: {
      name: "tamaño_temporal",
      tooltip: "Solo se utiliza para VAEs de video: Cantidad de fotogramas para codificar a la vez."
    },
    tile_size: {
      name: "tamaño_mosaico"
    },
    vae: {
      name: "vae"
    }
  }
};
const VAELoader$5 = {
  display_name: "Cargar VAE",
  inputs: {
    vae_name: {
      name: "nombre_vae"
    }
  }
};
const VAESave$5 = {
  display_name: "GuardarVAE",
  inputs: {
    filename_prefix: {
      name: "prefijo_nombre_archivo"
    },
    vae: {
      name: "vae"
    }
  }
};
const VPScheduler$5 = {
  display_name: "VPScheduler",
  inputs: {
    beta_d: {
      name: "beta_d"
    },
    beta_min: {
      name: "beta_min"
    },
    eps_s: {
      name: "eps_s"
    },
    steps: {
      name: "pasos"
    }
  }
};
const VeoVideoGenerationNode$5 = {
  description: "Genera videos a partir de indicaciones de texto usando la API de Veo de Google",
  display_name: "Generación de Video Google Veo2",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio",
      tooltip: "Relación de aspecto del video de salida"
    },
    control_after_generate: {
      name: "control after generate"
    },
    duration_seconds: {
      name: "duration_seconds",
      tooltip: "Duración del video de salida en segundos"
    },
    enhance_prompt: {
      name: "enhance_prompt",
      tooltip: "Si se debe mejorar la indicación con asistencia de IA"
    },
    image: {
      name: "image",
      tooltip: "Imagen de referencia opcional para guiar la generación del video"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Indicaciones negativas para guiar lo que se debe evitar en el video"
    },
    person_generation: {
      name: "person_generation",
      tooltip: "Si se permite generar personas en el video"
    },
    prompt: {
      name: "prompt",
      tooltip: "Descripción de texto del video"
    },
    seed: {
      name: "seed",
      tooltip: "Semilla para la generación de video (0 para aleatorio)"
    }
  }
};
const VideoLinearCFGGuidance$5 = {
  display_name: "OrientaciónLinealCFGVideo",
  inputs: {
    min_cfg: {
      name: "min_cfg"
    },
    model: {
      name: "modelo"
    }
  }
};
const VideoTriangleCFGGuidance$5 = {
  display_name: "OrientaciónTriangularCFGVideo",
  inputs: {
    min_cfg: {
      name: "min_cfg"
    },
    model: {
      name: "modelo"
    }
  }
};
const VoxelToMesh$5 = {
  display_name: "VoxelToMesh",
  inputs: {
    algorithm: {
      name: "algoritmo"
    },
    threshold: {
      name: "umbral"
    },
    voxel: {
      name: "voxel"
    }
  }
};
const VoxelToMeshBasic$5 = {
  display_name: "VoxelAMallaBásico",
  inputs: {
    threshold: {
      name: "umbral"
    },
    voxel: {
      name: "voxel"
    }
  }
};
const WanFirstLastFrameToVideo$5 = {
  display_name: "WanFirstLastFrameToVideo",
  inputs: {
    batch_size: {
      name: "tamaño_lote"
    },
    clip_vision_end_image: {
      name: "clip_vision_end_image"
    },
    clip_vision_start_image: {
      name: "clip_vision_start_image"
    },
    end_image: {
      name: "imagen_final"
    },
    height: {
      name: "alto"
    },
    length: {
      name: "longitud"
    },
    negative: {
      name: "negativo"
    },
    positive: {
      name: "positivo"
    },
    start_image: {
      name: "imagen_inicial"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "ancho"
    }
  },
  outputs: {
    "0": {
      name: "positivo"
    },
    "1": {
      name: "negativo"
    },
    "2": {
      name: "latente"
    }
  }
};
const WanFunControlToVideo$5 = {
  display_name: "WanFunControlToVideo",
  inputs: {
    batch_size: {
      name: "tamaño_lote"
    },
    clip_vision_output: {
      name: "clip_vision_output"
    },
    control_video: {
      name: "control_video"
    },
    height: {
      name: "alto"
    },
    length: {
      name: "longitud"
    },
    negative: {
      name: "negativo"
    },
    positive: {
      name: "positivo"
    },
    start_image: {
      name: "imagen_inicial"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "ancho"
    }
  },
  outputs: {
    "0": {
      name: "positivo"
    },
    "1": {
      name: "negativo"
    },
    "2": {
      name: "latente"
    }
  }
};
const WanFunInpaintToVideo$5 = {
  display_name: "WanFunInpaintToVideo",
  inputs: {
    batch_size: {
      name: "tamaño_de_lote"
    },
    clip_vision_output: {
      name: "clip_vision_output"
    },
    end_image: {
      name: "imagen_final"
    },
    height: {
      name: "alto"
    },
    length: {
      name: "longitud"
    },
    negative: {
      name: "negativo"
    },
    positive: {
      name: "positivo"
    },
    start_image: {
      name: "imagen_inicial"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "ancho"
    }
  },
  outputs: {
    "0": {
      name: "positivo"
    },
    "1": {
      name: "negativo"
    },
    "2": {
      name: "latente"
    }
  }
};
const WanImageToVideo$5 = {
  display_name: "WanImageToVideo",
  inputs: {
    batch_size: {
      name: "tamaño_del_lote"
    },
    clip_vision_output: {
      name: "salida_de_vision_clip"
    },
    height: {
      name: "altura"
    },
    length: {
      name: "longitud"
    },
    negative: {
      name: "negativo"
    },
    positive: {
      name: "positivo"
    },
    start_image: {
      name: "imagen_inicial"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "ancho"
    }
  },
  outputs: {
    "0": {
      name: "positivo"
    },
    "1": {
      name: "negativo"
    },
    "2": {
      name: "latente"
    }
  }
};
const WanVaceToVideo$5 = {
  display_name: "WanVaceToVideo",
  inputs: {
    batch_size: {
      name: "tamaño_lote"
    },
    control_masks: {
      name: "máscaras_de_control"
    },
    control_video: {
      name: "control_video"
    },
    height: {
      name: "alto"
    },
    length: {
      name: "longitud"
    },
    negative: {
      name: "negativo"
    },
    positive: {
      name: "positivo"
    },
    reference_image: {
      name: "imagen_de_referencia"
    },
    strength: {
      name: "fuerza"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "ancho"
    }
  },
  outputs: {
    "0": {
      name: "positivo"
    },
    "1": {
      name: "negativo"
    },
    "2": {
      name: "latente"
    },
    "3": {
      name: "latente_recortado"
    }
  }
};
const WebcamCapture$5 = {
  display_name: "Captura de Webcam",
  inputs: {
    capture_on_queue: {
      name: "captura_en_cola"
    },
    height: {
      name: "altura"
    },
    image: {
      name: "imagen"
    },
    "waiting for camera___": {},
    width: {
      name: "ancho"
    }
  }
};
const unCLIPCheckpointLoader$5 = {
  display_name: "Cargador de Puntos de Control unCLIP",
  inputs: {
    ckpt_name: {
      name: "nombre_ckpt"
    }
  }
};
const unCLIPConditioning$5 = {
  display_name: "Acondicionamiento unCLIP",
  inputs: {
    clip_vision_output: {
      name: "salida_vision_clip"
    },
    conditioning: {
      name: "acondicionamiento"
    },
    noise_augmentation: {
      name: "aumento_ruido"
    },
    strength: {
      name: "fuerza"
    }
  }
};
const esNodes = {
  AddNoise: AddNoise$5,
  AlignYourStepsScheduler: AlignYourStepsScheduler$5,
  BasicGuider: BasicGuider$5,
  BasicScheduler: BasicScheduler$5,
  BetaSamplingScheduler: BetaSamplingScheduler$5,
  CFGGuider: CFGGuider$5,
  CFGZeroStar: CFGZeroStar$5,
  CLIPAttentionMultiply: CLIPAttentionMultiply$5,
  CLIPLoader: CLIPLoader$5,
  CLIPMergeAdd: CLIPMergeAdd$5,
  CLIPMergeSimple: CLIPMergeSimple$5,
  CLIPMergeSubtract: CLIPMergeSubtract$5,
  CLIPSave: CLIPSave$5,
  CLIPSetLastLayer: CLIPSetLastLayer$5,
  CLIPTextEncode: CLIPTextEncode$5,
  CLIPTextEncodeControlnet: CLIPTextEncodeControlnet$5,
  CLIPTextEncodeFlux: CLIPTextEncodeFlux$5,
  CLIPTextEncodeHiDream: CLIPTextEncodeHiDream$5,
  CLIPTextEncodeHunyuanDiT: CLIPTextEncodeHunyuanDiT$5,
  CLIPTextEncodeLumina2: CLIPTextEncodeLumina2$5,
  CLIPTextEncodePixArtAlpha: CLIPTextEncodePixArtAlpha$5,
  CLIPTextEncodeSD3: CLIPTextEncodeSD3$5,
  CLIPTextEncodeSDXL: CLIPTextEncodeSDXL$5,
  CLIPTextEncodeSDXLRefiner: CLIPTextEncodeSDXLRefiner$5,
  CLIPVisionEncode: CLIPVisionEncode$5,
  CLIPVisionLoader: CLIPVisionLoader$5,
  Canny: Canny$5,
  CheckpointLoader: CheckpointLoader$5,
  CheckpointLoaderSimple: CheckpointLoaderSimple$5,
  CheckpointSave: CheckpointSave$5,
  CombineHooks2: CombineHooks2$5,
  CombineHooks4: CombineHooks4$5,
  CombineHooks8: CombineHooks8$5,
  ConditioningAverage: ConditioningAverage$5,
  ConditioningCombine: ConditioningCombine$5,
  ConditioningConcat: ConditioningConcat$5,
  ConditioningSetArea: ConditioningSetArea$5,
  ConditioningSetAreaPercentage: ConditioningSetAreaPercentage$5,
  ConditioningSetAreaPercentageVideo: ConditioningSetAreaPercentageVideo$5,
  ConditioningSetAreaStrength: ConditioningSetAreaStrength$5,
  ConditioningSetDefaultCombine: ConditioningSetDefaultCombine$5,
  ConditioningSetMask: ConditioningSetMask$5,
  ConditioningSetProperties: ConditioningSetProperties$5,
  ConditioningSetPropertiesAndCombine: ConditioningSetPropertiesAndCombine$5,
  ConditioningSetTimestepRange: ConditioningSetTimestepRange$5,
  ConditioningStableAudio: ConditioningStableAudio$5,
  ConditioningTimestepsRange: ConditioningTimestepsRange$5,
  ConditioningZeroOut: ConditioningZeroOut$5,
  ControlNetApply: ControlNetApply$5,
  ControlNetApplyAdvanced: ControlNetApplyAdvanced$5,
  ControlNetApplySD3: ControlNetApplySD3$5,
  ControlNetInpaintingAliMamaApply: ControlNetInpaintingAliMamaApply$5,
  ControlNetLoader: ControlNetLoader$5,
  CosmosImageToVideoLatent: CosmosImageToVideoLatent$5,
  CreateHookKeyframe: CreateHookKeyframe$5,
  CreateHookKeyframesFromFloats: CreateHookKeyframesFromFloats$5,
  CreateHookKeyframesInterpolated: CreateHookKeyframesInterpolated$5,
  CreateHookLora: CreateHookLora$5,
  CreateHookLoraModelOnly: CreateHookLoraModelOnly$5,
  CreateHookModelAsLora: CreateHookModelAsLora$5,
  CreateHookModelAsLoraModelOnly: CreateHookModelAsLoraModelOnly$5,
  CreateVideo: CreateVideo$5,
  CropMask: CropMask$5,
  DiffControlNetLoader: DiffControlNetLoader$5,
  DifferentialDiffusion: DifferentialDiffusion$5,
  DiffusersLoader: DiffusersLoader$5,
  DisableNoise: DisableNoise$5,
  DualCFGGuider: DualCFGGuider$5,
  DualCLIPLoader: DualCLIPLoader$5,
  EmptyCosmosLatentVideo: EmptyCosmosLatentVideo$5,
  EmptyHunyuanLatentVideo: EmptyHunyuanLatentVideo$5,
  EmptyImage: EmptyImage$5,
  EmptyLTXVLatentVideo: EmptyLTXVLatentVideo$5,
  EmptyLatentAudio: EmptyLatentAudio$5,
  EmptyLatentHunyuan3Dv2: EmptyLatentHunyuan3Dv2$5,
  EmptyLatentImage: EmptyLatentImage$5,
  EmptyMochiLatentVideo: EmptyMochiLatentVideo$5,
  EmptySD3LatentImage: EmptySD3LatentImage$5,
  ExponentialScheduler: ExponentialScheduler$5,
  ExtendIntermediateSigmas: ExtendIntermediateSigmas$5,
  FeatherMask: FeatherMask$5,
  FlipSigmas: FlipSigmas$5,
  FluxDisableGuidance: FluxDisableGuidance$5,
  FluxGuidance: FluxGuidance$5,
  FluxProCannyNode: FluxProCannyNode$5,
  FluxProDepthNode: FluxProDepthNode$5,
  FluxProExpandNode: FluxProExpandNode$5,
  FluxProFillNode: FluxProFillNode$5,
  FluxProUltraImageNode: FluxProUltraImageNode$5,
  FreSca: FreSca$5,
  FreeU: FreeU$5,
  FreeU_V2: FreeU_V2$5,
  GITSScheduler: GITSScheduler$5,
  GLIGENLoader: GLIGENLoader$5,
  GLIGENTextBoxApply: GLIGENTextBoxApply$5,
  GetVideoComponents: GetVideoComponents$5,
  GrowMask: GrowMask$5,
  Hunyuan3Dv2Conditioning: Hunyuan3Dv2Conditioning$5,
  Hunyuan3Dv2ConditioningMultiView: Hunyuan3Dv2ConditioningMultiView$5,
  HunyuanImageToVideo: HunyuanImageToVideo$5,
  HyperTile: HyperTile$5,
  HypernetworkLoader: HypernetworkLoader$5,
  IdeogramV1: IdeogramV1$5,
  IdeogramV2: IdeogramV2$5,
  IdeogramV3: IdeogramV3$5,
  ImageBatch: ImageBatch$5,
  ImageBlend: ImageBlend$5,
  ImageBlur: ImageBlur$5,
  ImageColorToMask: ImageColorToMask$5,
  ImageCompositeMasked: ImageCompositeMasked$5,
  ImageCrop: ImageCrop$5,
  ImageFromBatch: ImageFromBatch$5,
  ImageInvert: ImageInvert$5,
  ImageOnlyCheckpointLoader: ImageOnlyCheckpointLoader$5,
  ImageOnlyCheckpointSave: ImageOnlyCheckpointSave$5,
  ImagePadForOutpaint: ImagePadForOutpaint$5,
  ImageQuantize: ImageQuantize$5,
  ImageRGBToYUV: ImageRGBToYUV$5,
  ImageScale: ImageScale$5,
  ImageScaleBy: ImageScaleBy$5,
  ImageScaleToTotalPixels: ImageScaleToTotalPixels$5,
  ImageSharpen: ImageSharpen$5,
  ImageToMask: ImageToMask$5,
  ImageUpscaleWithModel: ImageUpscaleWithModel$5,
  ImageYUVToRGB: ImageYUVToRGB$5,
  InpaintModelConditioning: InpaintModelConditioning$5,
  InstructPixToPixConditioning: InstructPixToPixConditioning$5,
  InvertMask: InvertMask$5,
  JoinImageWithAlpha: JoinImageWithAlpha$5,
  KSampler: KSampler$5,
  KSamplerAdvanced: KSamplerAdvanced$5,
  KSamplerSelect: KSamplerSelect$5,
  KarrasScheduler: KarrasScheduler$5,
  KlingCameraControlI2VNode: KlingCameraControlI2VNode$5,
  KlingCameraControlT2VNode: KlingCameraControlT2VNode$5,
  KlingCameraControls: KlingCameraControls$5,
  KlingDualCharacterVideoEffectNode: KlingDualCharacterVideoEffectNode$5,
  KlingImage2VideoNode: KlingImage2VideoNode$5,
  KlingImageGenerationNode: KlingImageGenerationNode$5,
  KlingLipSyncAudioToVideoNode: KlingLipSyncAudioToVideoNode$5,
  KlingLipSyncTextToVideoNode: KlingLipSyncTextToVideoNode$5,
  KlingSingleImageVideoEffectNode: KlingSingleImageVideoEffectNode$5,
  KlingStartEndFrameNode: KlingStartEndFrameNode$5,
  KlingTextToVideoNode: KlingTextToVideoNode$5,
  KlingVideoExtendNode: KlingVideoExtendNode$5,
  KlingVirtualTryOnNode: KlingVirtualTryOnNode$5,
  LTXVAddGuide: LTXVAddGuide$5,
  LTXVConditioning: LTXVConditioning$5,
  LTXVCropGuides: LTXVCropGuides$5,
  LTXVImgToVideo: LTXVImgToVideo$5,
  LTXVPreprocess: LTXVPreprocess$5,
  LTXVScheduler: LTXVScheduler$5,
  LaplaceScheduler: LaplaceScheduler$5,
  LatentAdd: LatentAdd$5,
  LatentApplyOperation: LatentApplyOperation$5,
  LatentApplyOperationCFG: LatentApplyOperationCFG$5,
  LatentBatch: LatentBatch$5,
  LatentBatchSeedBehavior: LatentBatchSeedBehavior$5,
  LatentBlend: LatentBlend$5,
  LatentComposite: LatentComposite$5,
  LatentCompositeMasked: LatentCompositeMasked$5,
  LatentCrop: LatentCrop$5,
  LatentFlip: LatentFlip$5,
  LatentFromBatch: LatentFromBatch$5,
  LatentInterpolate: LatentInterpolate$5,
  LatentMultiply: LatentMultiply$5,
  LatentOperationSharpen: LatentOperationSharpen$5,
  LatentOperationTonemapReinhard: LatentOperationTonemapReinhard$5,
  LatentRotate: LatentRotate$5,
  LatentSubtract: LatentSubtract$5,
  LatentUpscale: LatentUpscale$5,
  LatentUpscaleBy: LatentUpscaleBy$5,
  Load3D: Load3D$5,
  Load3DAnimation: Load3DAnimation$5,
  LoadAudio: LoadAudio$5,
  LoadImage: LoadImage$5,
  LoadImageMask: LoadImageMask$5,
  LoadImageOutput: LoadImageOutput$5,
  LoadLatent: LoadLatent$5,
  LoadVideo: LoadVideo$5,
  LoraLoader: LoraLoader$5,
  LoraLoaderModelOnly: LoraLoaderModelOnly$5,
  LoraSave: LoraSave$5,
  LotusConditioning: LotusConditioning$5,
  LumaConceptsNode: LumaConceptsNode$5,
  LumaImageModifyNode: LumaImageModifyNode$5,
  LumaImageNode: LumaImageNode$5,
  LumaImageToVideoNode: LumaImageToVideoNode$5,
  LumaReferenceNode: LumaReferenceNode$5,
  LumaVideoNode: LumaVideoNode$5,
  Mahiro: Mahiro$5,
  MaskComposite: MaskComposite$5,
  MaskPreview: MaskPreview$5,
  MaskToImage: MaskToImage$5,
  MinimaxImageToVideoNode: MinimaxImageToVideoNode$5,
  MinimaxTextToVideoNode: MinimaxTextToVideoNode$5,
  ModelComputeDtype: ModelComputeDtype$5,
  ModelMergeAdd: ModelMergeAdd$5,
  ModelMergeAuraflow: ModelMergeAuraflow$5,
  ModelMergeBlocks: ModelMergeBlocks$5,
  ModelMergeCosmos14B: ModelMergeCosmos14B$5,
  ModelMergeCosmos7B: ModelMergeCosmos7B$5,
  ModelMergeFlux1: ModelMergeFlux1$5,
  ModelMergeLTXV: ModelMergeLTXV$5,
  ModelMergeMochiPreview: ModelMergeMochiPreview$5,
  ModelMergeSD1: ModelMergeSD1$5,
  ModelMergeSD2: ModelMergeSD2$5,
  ModelMergeSD35_Large: ModelMergeSD35_Large$5,
  ModelMergeSD3_2B: ModelMergeSD3_2B$5,
  ModelMergeSDXL: ModelMergeSDXL$5,
  ModelMergeSimple: ModelMergeSimple$5,
  ModelMergeSubtract: ModelMergeSubtract$5,
  ModelMergeWAN2_1: ModelMergeWAN2_1$5,
  ModelSamplingAuraFlow: ModelSamplingAuraFlow$5,
  ModelSamplingContinuousEDM: ModelSamplingContinuousEDM$5,
  ModelSamplingContinuousV: ModelSamplingContinuousV$5,
  ModelSamplingDiscrete: ModelSamplingDiscrete$5,
  ModelSamplingFlux: ModelSamplingFlux$5,
  ModelSamplingLTXV: ModelSamplingLTXV$5,
  ModelSamplingSD3: ModelSamplingSD3$5,
  ModelSamplingStableCascade: ModelSamplingStableCascade$5,
  ModelSave: ModelSave$5,
  Morphology: Morphology$5,
  OpenAIDalle2: OpenAIDalle2$5,
  OpenAIDalle3: OpenAIDalle3$5,
  OpenAIGPTImage1: OpenAIGPTImage1$5,
  OptimalStepsScheduler: OptimalStepsScheduler$5,
  PairConditioningCombine: PairConditioningCombine$5,
  PairConditioningSetDefaultCombine: PairConditioningSetDefaultCombine$5,
  PairConditioningSetProperties: PairConditioningSetProperties$5,
  PairConditioningSetPropertiesAndCombine: PairConditioningSetPropertiesAndCombine$5,
  PatchModelAddDownscale: PatchModelAddDownscale$5,
  PerpNeg: PerpNeg$5,
  PerpNegGuider: PerpNegGuider$5,
  PerturbedAttentionGuidance: PerturbedAttentionGuidance$5,
  PhotoMakerEncode: PhotoMakerEncode$5,
  PhotoMakerLoader: PhotoMakerLoader$5,
  PikaImageToVideoNode2_2: PikaImageToVideoNode2_2$5,
  PikaScenesV2_2: PikaScenesV2_2$5,
  PikaStartEndFrameNode2_2: PikaStartEndFrameNode2_2$5,
  PikaTextToVideoNode2_2: PikaTextToVideoNode2_2$5,
  Pikadditions: Pikadditions$5,
  Pikaffects: Pikaffects$5,
  Pikaswaps: Pikaswaps$5,
  PixverseImageToVideoNode: PixverseImageToVideoNode$5,
  PixverseTemplateNode: PixverseTemplateNode$5,
  PixverseTextToVideoNode: PixverseTextToVideoNode$5,
  PixverseTransitionVideoNode: PixverseTransitionVideoNode$5,
  PolyexponentialScheduler: PolyexponentialScheduler$5,
  PorterDuffImageComposite: PorterDuffImageComposite$5,
  Preview3D: Preview3D$5,
  Preview3DAnimation: Preview3DAnimation$5,
  PreviewAny: PreviewAny$5,
  PreviewAudio: PreviewAudio$5,
  PreviewImage: PreviewImage$5,
  PrimitiveBoolean: PrimitiveBoolean$5,
  PrimitiveFloat: PrimitiveFloat$5,
  PrimitiveInt: PrimitiveInt$5,
  PrimitiveString: PrimitiveString$5,
  PrimitiveStringMultiline: PrimitiveStringMultiline$5,
  QuadrupleCLIPLoader: QuadrupleCLIPLoader$5,
  RandomNoise: RandomNoise$5,
  RebatchImages: RebatchImages$5,
  RebatchLatents: RebatchLatents$5,
  RecraftColorRGB: RecraftColorRGB$5,
  RecraftControls: RecraftControls$5,
  RecraftCreativeUpscaleNode: RecraftCreativeUpscaleNode$5,
  RecraftCrispUpscaleNode: RecraftCrispUpscaleNode$5,
  RecraftImageInpaintingNode: RecraftImageInpaintingNode$5,
  RecraftImageToImageNode: RecraftImageToImageNode$5,
  RecraftRemoveBackgroundNode: RecraftRemoveBackgroundNode$5,
  RecraftReplaceBackgroundNode: RecraftReplaceBackgroundNode$5,
  RecraftStyleV3DigitalIllustration: RecraftStyleV3DigitalIllustration$5,
  RecraftStyleV3InfiniteStyleLibrary: RecraftStyleV3InfiniteStyleLibrary$5,
  RecraftStyleV3LogoRaster: RecraftStyleV3LogoRaster$5,
  RecraftStyleV3RealisticImage: RecraftStyleV3RealisticImage$5,
  RecraftTextToImageNode: RecraftTextToImageNode$5,
  RecraftTextToVectorNode: RecraftTextToVectorNode$5,
  RecraftVectorizeImageNode: RecraftVectorizeImageNode$5,
  RenormCFG: RenormCFG$5,
  RepeatImageBatch: RepeatImageBatch$5,
  RepeatLatentBatch: RepeatLatentBatch$5,
  RescaleCFG: RescaleCFG$5,
  SDTurboScheduler: SDTurboScheduler$5,
  SD_4XUpscale_Conditioning: SD_4XUpscale_Conditioning$5,
  SV3D_Conditioning: SV3D_Conditioning$5,
  SVD_img2vid_Conditioning: SVD_img2vid_Conditioning$5,
  SamplerCustom: SamplerCustom$5,
  SamplerCustomAdvanced: SamplerCustomAdvanced$5,
  SamplerDPMAdaptative: SamplerDPMAdaptative$5,
  SamplerDPMPP_2M_SDE: SamplerDPMPP_2M_SDE$5,
  SamplerDPMPP_2S_Ancestral: SamplerDPMPP_2S_Ancestral$5,
  SamplerDPMPP_3M_SDE: SamplerDPMPP_3M_SDE$5,
  SamplerDPMPP_SDE: SamplerDPMPP_SDE$5,
  SamplerEulerAncestral: SamplerEulerAncestral$5,
  SamplerEulerAncestralCFGPP: SamplerEulerAncestralCFGPP$5,
  SamplerEulerCFGpp: SamplerEulerCFGpp$5,
  SamplerLCMUpscale: SamplerLCMUpscale$5,
  SamplerLMS: SamplerLMS$5,
  SaveAnimatedPNG: SaveAnimatedPNG$5,
  SaveAnimatedWEBP: SaveAnimatedWEBP$5,
  SaveAudio: SaveAudio$5,
  SaveGLB: SaveGLB$5,
  SaveImage: SaveImage$5,
  SaveImageWebsocket: SaveImageWebsocket$5,
  SaveLatent: SaveLatent$5,
  SaveSVG: SaveSVG$5,
  SaveVideo: SaveVideo$5,
  SaveWEBM: SaveWEBM$5,
  SelfAttentionGuidance: SelfAttentionGuidance$5,
  SetClipHooks: SetClipHooks$5,
  SetFirstSigma: SetFirstSigma$5,
  SetHookKeyframes: SetHookKeyframes$5,
  SetLatentNoiseMask: SetLatentNoiseMask$5,
  SetUnionControlNetType: SetUnionControlNetType$5,
  SkipLayerGuidanceDiT: SkipLayerGuidanceDiT$5,
  SkipLayerGuidanceSD3: SkipLayerGuidanceSD3$5,
  SolidMask: SolidMask$5,
  SplitImageWithAlpha: SplitImageWithAlpha$5,
  SplitSigmas: SplitSigmas$5,
  SplitSigmasDenoise: SplitSigmasDenoise$5,
  StabilityStableImageSD_3_5Node: StabilityStableImageSD_3_5Node$5,
  StabilityStableImageUltraNode: StabilityStableImageUltraNode$5,
  StabilityUpscaleConservativeNode: StabilityUpscaleConservativeNode$5,
  StabilityUpscaleCreativeNode: StabilityUpscaleCreativeNode$5,
  StabilityUpscaleFastNode: StabilityUpscaleFastNode$5,
  StableCascade_EmptyLatentImage: StableCascade_EmptyLatentImage$5,
  StableCascade_StageB_Conditioning: StableCascade_StageB_Conditioning$5,
  StableCascade_StageC_VAEEncode: StableCascade_StageC_VAEEncode$5,
  StableCascade_SuperResolutionControlnet: StableCascade_SuperResolutionControlnet$5,
  StableZero123_Conditioning: StableZero123_Conditioning$5,
  StableZero123_Conditioning_Batched: StableZero123_Conditioning_Batched$5,
  StyleModelApply: StyleModelApply$5,
  StyleModelLoader: StyleModelLoader$5,
  T5TokenizerOptions: T5TokenizerOptions$5,
  TextEncodeHunyuanVideo_ImageToVideo: TextEncodeHunyuanVideo_ImageToVideo$5,
  ThresholdMask: ThresholdMask$5,
  TomePatchModel: TomePatchModel$5,
  TorchCompileModel: TorchCompileModel$5,
  TrimVideoLatent: TrimVideoLatent$5,
  TripleCLIPLoader: TripleCLIPLoader$5,
  UNETLoader: UNETLoader$5,
  UNetCrossAttentionMultiply: UNetCrossAttentionMultiply$5,
  UNetSelfAttentionMultiply: UNetSelfAttentionMultiply$5,
  UNetTemporalAttentionMultiply: UNetTemporalAttentionMultiply$5,
  UpscaleModelLoader: UpscaleModelLoader$5,
  VAEDecode: VAEDecode$5,
  VAEDecodeAudio: VAEDecodeAudio$5,
  VAEDecodeHunyuan3D: VAEDecodeHunyuan3D$5,
  VAEDecodeTiled: VAEDecodeTiled$5,
  VAEEncode: VAEEncode$5,
  VAEEncodeAudio: VAEEncodeAudio$5,
  VAEEncodeForInpaint: VAEEncodeForInpaint$5,
  VAEEncodeTiled: VAEEncodeTiled$5,
  VAELoader: VAELoader$5,
  VAESave: VAESave$5,
  VPScheduler: VPScheduler$5,
  VeoVideoGenerationNode: VeoVideoGenerationNode$5,
  VideoLinearCFGGuidance: VideoLinearCFGGuidance$5,
  VideoTriangleCFGGuidance: VideoTriangleCFGGuidance$5,
  VoxelToMesh: VoxelToMesh$5,
  VoxelToMeshBasic: VoxelToMeshBasic$5,
  WanFirstLastFrameToVideo: WanFirstLastFrameToVideo$5,
  WanFunControlToVideo: WanFunControlToVideo$5,
  WanFunInpaintToVideo: WanFunInpaintToVideo$5,
  WanImageToVideo: WanImageToVideo$5,
  WanVaceToVideo: WanVaceToVideo$5,
  WebcamCapture: WebcamCapture$5,
  unCLIPCheckpointLoader: unCLIPCheckpointLoader$5,
  unCLIPConditioning: unCLIPConditioning$5
};
const Comfy_Canvas_SelectionToolbox$5 = {
  name: "Mostrar caja de herramientas de selección"
};
const Comfy_ConfirmClear$5 = {
  name: "Requerir confirmación al borrar el flujo de trabajo"
};
const Comfy_DOMClippingEnabled$5 = {
  name: "Habilitar el recorte de elementos DOM (la habilitación puede reducir el rendimiento)"
};
const Comfy_DevMode$5 = {
  name: "Habilitar opciones de modo de desarrollo (guardar API, etc.)"
};
const Comfy_DisableFloatRounding$5 = {
  name: "Desactivar el redondeo predeterminado del widget flotante.",
  tooltip: "(requiere recargar la página) No se puede desactivar el redondeo cuando el redondeo está establecido por el nodo en el backend."
};
const Comfy_DisableSliders$5 = {
  name: "Desactivar los deslizadores del widget del nodo"
};
const Comfy_EditAttention_Delta$5 = {
  name: "Precisión Ctrl+arriba/abajo"
};
const Comfy_EnableTooltips$5 = {
  name: "Habilitar Tooltips"
};
const Comfy_EnableWorkflowViewRestore$5 = {
  name: "Guardar y restaurar la posición del lienzo y el nivel de zoom en los flujos de trabajo"
};
const Comfy_FloatRoundingPrecision$5 = {
  name: "Decimales de redondeo del widget flotante [0 = automático].",
  tooltip: "(requiere recargar la página)"
};
const Comfy_Graph_CanvasInfo$5 = {
  name: "Mostrar información del lienzo en la esquina inferior izquierda (fps, etc.)"
};
const Comfy_Graph_CanvasMenu$5 = {
  name: "Mostrar menú del lienzo del gráfico"
};
const Comfy_Graph_CtrlShiftZoom$5 = {
  name: "Habilitar atajo de zoom rápido (Ctrl + Shift + Arrastrar)"
};
const Comfy_Graph_LinkMarkers$5 = {
  name: "Marcadores de punto medio de enlace",
  options: {
    Arrow: "Flecha",
    Circle: "Círculo",
    None: "Ninguno"
  }
};
const Comfy_Graph_ZoomSpeed$5 = {
  name: "Velocidad de zoom del lienzo"
};
const Comfy_GroupSelectedNodes_Padding$5 = {
  name: "Relleno de nodos seleccionados en grupo"
};
const Comfy_Group_DoubleClickTitleToEdit$5 = {
  name: "Haga doble clic en el título del grupo para editar"
};
const Comfy_LinkRelease_Action$5 = {
  name: "Acción al soltar el enlace (Sin modificador)",
  options: {
    "context menu": "menú contextual",
    "no action": "sin acción",
    "search box": "caja de búsqueda"
  }
};
const Comfy_LinkRelease_ActionShift$5 = {
  name: "Acción al soltar el enlace (Shift)",
  options: {
    "context menu": "menú contextual",
    "no action": "sin acción",
    "search box": "caja de búsqueda"
  }
};
const Comfy_LinkRenderMode$5 = {
  name: "Modo de renderizado de enlace",
  options: {
    Hidden: "Oculto",
    Linear: "Lineal",
    Spline: "Spline",
    Straight: "Recto"
  }
};
const Comfy_Load3D_BackgroundColor$5 = {
  name: "Color de fondo inicial",
  tooltip: "Controla el color de fondo predeterminado de la escena 3D. Esta configuración determina la apariencia del fondo cuando se crea un nuevo widget 3D, pero puede ajustarse individualmente para cada widget después de su creación."
};
const Comfy_Load3D_CameraType$5 = {
  name: "Tipo de Cámara",
  options: {
    orthographic: "ortográfica",
    perspective: "perspectiva"
  },
  tooltip: "Controla si la cámara es perspectiva u ortográfica por defecto cuando se crea un nuevo widget 3D. Este valor predeterminado aún puede ser alternado individualmente para cada widget después de su creación."
};
const Comfy_Load3D_LightAdjustmentIncrement$5 = {
  name: "Incremento de ajuste de luz",
  tooltip: "Controla el tamaño del incremento al ajustar la intensidad de la luz en escenas 3D. Un valor de paso más pequeño permite un control más preciso sobre los ajustes de iluminación, mientras que un valor más grande resulta en cambios más notorios por cada ajuste."
};
const Comfy_Load3D_LightIntensity$5 = {
  name: "Intensidad Inicial de la Luz",
  tooltip: "Establece el nivel de brillo predeterminado de la iluminación en la escena 3D. Este valor determina cuán intensamente las luces iluminan los objetos cuando se crea un nuevo widget 3D, pero puede ajustarse individualmente para cada widget después de la creación."
};
const Comfy_Load3D_LightIntensityMaximum$5 = {
  name: "Intensidad Máxima de Luz",
  tooltip: "Establece el valor máximo permitido de intensidad de luz para escenas 3D. Esto define el límite superior de brillo que se puede ajustar al modificar la iluminación en cualquier widget 3D."
};
const Comfy_Load3D_LightIntensityMinimum$5 = {
  name: "Intensidad de luz mínima",
  tooltip: "Establece el valor mínimo permitido de intensidad de luz para escenas 3D. Esto define el límite inferior de brillo que se puede ajustar al modificar la iluminación en cualquier widget 3D."
};
const Comfy_Load3D_ShowGrid$5 = {
  name: "Mostrar Cuadrícula",
  tooltip: "Cambiar para mostrar cuadrícula por defecto"
};
const Comfy_Load3D_ShowPreview$5 = {
  name: "Mostrar Previsualización",
  tooltip: "Cambiar para mostrar previsualización por defecto"
};
const Comfy_Locale$5 = {
  name: "Idioma"
};
const Comfy_MaskEditor_BrushAdjustmentSpeed$5 = {
  name: "Multiplicador de velocidad de ajuste del pincel",
  tooltip: "Controla la rapidez con la que cambian el tamaño y la dureza del pincel al ajustar. Valores más altos significan cambios más rápidos."
};
const Comfy_MaskEditor_UseDominantAxis$5 = {
  name: "Bloquear ajuste del pincel al eje dominante",
  tooltip: "Cuando está habilitado, los ajustes del pincel solo afectarán el tamaño O la dureza según la dirección en la que te muevas más"
};
const Comfy_MaskEditor_UseNewEditor$5 = {
  name: "Usar nuevo editor de máscara",
  tooltip: "Cambiar a la nueva interfaz del editor de máscaras"
};
const Comfy_ModelLibrary_AutoLoadAll$5 = {
  name: "Cargar automáticamente todas las carpetas de modelos",
  tooltip: "Si es verdadero, todas las carpetas se cargarán tan pronto como abras la biblioteca de modelos (esto puede causar retrasos mientras se carga). Si es falso, las carpetas de modelos de nivel raíz solo se cargarán una vez que hagas clic en ellas."
};
const Comfy_ModelLibrary_NameFormat$5 = {
  name: "Qué nombre mostrar en la vista de árbol de la biblioteca de modelos",
  options: {
    filename: "nombre de archivo",
    title: "título"
  },
  tooltip: 'Selecciona "nombre de archivo" para renderizar una vista simplificada del nombre de archivo bruto (sin directorio o extensión ".safetensors") en la lista de modelos. Selecciona "título" para mostrar el título de metadatos del modelo configurable.'
};
const Comfy_NodeBadge_NodeIdBadgeMode$5 = {
  name: "Modo de insignia de ID de nodo",
  options: {
    None: "Ninguno",
    "Show all": "Mostrar todo"
  }
};
const Comfy_NodeBadge_NodeLifeCycleBadgeMode$5 = {
  name: "Modo de insignia de ciclo de vida del nodo",
  options: {
    None: "Ninguno",
    "Show all": "Mostrar todo"
  }
};
const Comfy_NodeBadge_NodeSourceBadgeMode$5 = {
  name: "Modo de insignia de fuente de nodo",
  options: {
    "Hide built-in": "Ocultar incorporado",
    None: "Ninguno",
    "Show all": "Mostrar todo"
  }
};
const Comfy_NodeSearchBoxImpl$5 = {
  name: "Implementación de la caja de búsqueda de nodos",
  options: {
    "default": "predeterminado",
    "litegraph (legacy)": "litegraph (legado)"
  }
};
const Comfy_NodeSearchBoxImpl_NodePreview$5 = {
  name: "Vista previa del nodo",
  tooltip: "Solo se aplica a la implementación predeterminada"
};
const Comfy_NodeSearchBoxImpl_ShowCategory$5 = {
  name: "Mostrar categoría de nodo en los resultados de búsqueda",
  tooltip: "Solo se aplica a la implementación predeterminada"
};
const Comfy_NodeSearchBoxImpl_ShowIdName$5 = {
  name: "Mostrar nombre de id de nodo en los resultados de búsqueda",
  tooltip: "Solo se aplica a la implementación predeterminada"
};
const Comfy_NodeSearchBoxImpl_ShowNodeFrequency$5 = {
  name: "Mostrar frecuencia de nodos en los resultados de búsqueda",
  tooltip: "Solo se aplica a la implementación predeterminada"
};
const Comfy_NodeSuggestions_number$5 = {
  name: "Número de sugerencias de nodos",
  tooltip: "Solo para el cuadro de búsqueda/contexto del menú de litegraph"
};
const Comfy_Node_AllowImageSizeDraw$5 = {
  name: "Mostrar ancho × altura debajo de la vista previa de la imagen"
};
const Comfy_Node_AutoSnapLinkToSlot$5 = {
  name: "Enlace de ajuste automático a la ranura del nodo",
  tooltip: "Al arrastrar un enlace sobre un nodo, el enlace se ajustará automáticamente a una ranura de entrada viable en el nodo"
};
const Comfy_Node_BypassAllLinksOnDelete$5 = {
  name: "Mantener todos los enlaces al eliminar nodos",
  tooltip: "Al eliminar un nodo, intenta reconectar todos sus enlaces de entrada y salida (eludiendo el nodo eliminado)"
};
const Comfy_Node_DoubleClickTitleToEdit$5 = {
  name: "Haz doble clic en el título del nodo para editarlo"
};
const Comfy_Node_MiddleClickRerouteNode$5 = {
  name: "El clic medio crea un nuevo nodo de reenrutamiento"
};
const Comfy_Node_Opacity$5 = {
  name: "Opacidad del nodo"
};
const Comfy_Node_ShowDeprecated$5 = {
  name: "Mostrar nodos obsoletos en la búsqueda",
  tooltip: "Los nodos obsoletos están ocultos por defecto en la interfaz de usuario, pero siguen siendo funcionales en los flujos de trabajo existentes que los utilizan."
};
const Comfy_Node_ShowExperimental$5 = {
  name: "Mostrar nodos experimentales en la búsqueda",
  tooltip: "Los nodos experimentales están marcados como tales en la interfaz de usuario y pueden estar sujetos a cambios significativos o eliminación en futuras versiones. Úselos con precaución en flujos de trabajo de producción"
};
const Comfy_Node_SnapHighlightsNode$5 = {
  name: "Destacar nodo de ajuste",
  tooltip: "Al arrastrar un enlace sobre un nodo con ranura de entrada viable, resalta el nodo"
};
const Comfy_Pointer_ClickBufferTime$5 = {
  name: "Retraso de deriva del clic del puntero",
  tooltip: "Después de presionar un botón del puntero, este es el tiempo máximo (en milisegundos) que se puede ignorar el movimiento del puntero.\n\nAyuda a prevenir que los objetos sean movidos involuntariamente si el puntero se mueve al hacer clic."
};
const Comfy_Pointer_ClickDrift$5 = {
  name: "Deriva del clic del puntero (distancia máxima)",
  tooltip: "Si el puntero se mueve más de esta distancia mientras se mantiene presionado un botón, se considera arrastrar (en lugar de hacer clic).\n\nAyuda a prevenir que los objetos sean movidos involuntariamente si el puntero se mueve al hacer clic."
};
const Comfy_Pointer_DoubleClickTime$5 = {
  name: "Intervalo de doble clic (máximo)",
  tooltip: "El tiempo máximo en milisegundos entre los dos clics de un doble clic. Aumentar este valor puede ayudar si a veces no se registran los doble clics."
};
const Comfy_PreviewFormat$5 = {
  name: "Formato de imagen de vista previa",
  tooltip: "Al mostrar una vista previa en el widget de imagen, conviértala en una imagen ligera, por ejemplo, webp, jpeg, webp;50, etc."
};
const Comfy_PromptFilename$5 = {
  name: "Solicitar nombre de archivo al guardar el flujo de trabajo"
};
const Comfy_QueueButton_BatchCountLimit$5 = {
  name: "Límite de conteo de lotes",
  tooltip: "El número máximo de tareas añadidas a la cola con un solo clic de botón"
};
const Comfy_Queue_MaxHistoryItems$5 = {
  name: "Tamaño del historial de la cola",
  tooltip: "El número máximo de tareas que se muestran en el historial de la cola."
};
const Comfy_Sidebar_Location$5 = {
  name: "Ubicación de la barra lateral",
  options: {
    left: "izquierda",
    right: "derecha"
  }
};
const Comfy_Sidebar_Size$5 = {
  name: "Tamaño de la barra lateral",
  options: {
    normal: "normal",
    small: "pequeña"
  }
};
const Comfy_Sidebar_UnifiedWidth$5 = {
  name: "Ancho unificado de la barra lateral"
};
const Comfy_SnapToGrid_GridSize$5 = {
  name: "Tamaño de la cuadrícula para ajustar",
  tooltip: "Al arrastrar y redimensionar nodos mientras se mantiene presionada la tecla shift, se alinearán a la cuadrícula, esto controla el tamaño de esa cuadrícula."
};
const Comfy_TextareaWidget_FontSize$5 = {
  name: "Tamaño de fuente del widget de área de texto"
};
const Comfy_TextareaWidget_Spellcheck$5 = {
  name: "Corrector ortográfico del widget de área de texto"
};
const Comfy_TreeExplorer_ItemPadding$5 = {
  name: "Relleno del elemento del explorador de árboles"
};
const Comfy_UseNewMenu$5 = {
  name: "Usar nuevo menú",
  options: {
    Bottom: "Abajo",
    Disabled: "Deshabilitado",
    Top: "Arriba"
  }
};
const Comfy_Validation_NodeDefs$5 = {
  name: "Validar definiciones de nodos (lento)",
  tooltip: "Recomendado para desarrolladores de nodos. Esto validará todas las definiciones de nodos al iniciar."
};
const Comfy_Validation_Workflows$5 = {
  name: "Validar flujos de trabajo"
};
const Comfy_WidgetControlMode$5 = {
  name: "Modo de control del widget",
  options: {
    after: "después",
    before: "antes"
  },
  tooltip: "Controla cuándo se actualizan los valores del widget (aleatorizar/incrementar/decrementar), ya sea antes de que se encole el aviso o después."
};
const Comfy_Window_UnloadConfirmation$5 = {
  name: "Mostrar confirmación al cerrar la ventana"
};
const Comfy_Workflow_AutoSave$5 = {
  name: "Auto Guardar",
  options: {
    "after delay": "después de retraso",
    off: "desactivado"
  }
};
const Comfy_Workflow_AutoSaveDelay$5 = {
  name: "Retraso de Auto Guardar (ms)",
  tooltip: 'Solo se aplica si Auto Guardar está configurado en "después de retraso".'
};
const Comfy_Workflow_ConfirmDelete$5 = {
  name: "Mostrar confirmación al eliminar flujos de trabajo"
};
const Comfy_Workflow_Persist$5 = {
  name: "Persistir el estado del flujo de trabajo y restaurar en la (re)carga de la página"
};
const Comfy_Workflow_ShowMissingModelsWarning$5 = {
  name: "Mostrar advertencia de modelos faltantes"
};
const Comfy_Workflow_ShowMissingNodesWarning$5 = {
  name: "Mostrar advertencia de nodos faltantes"
};
const Comfy_Workflow_SortNodeIdOnSave$5 = {
  name: "Ordenar IDs de nodos al guardar el flujo de trabajo"
};
const Comfy_Workflow_WorkflowTabsPosition$5 = {
  name: "Posición de los flujos de trabajo abiertos",
  options: {
    Sidebar: "Barra lateral",
    Topbar: "Barra superior",
    "Topbar (2nd-row)": "Barra superior (2ª fila)"
  }
};
const LiteGraph_Canvas_LowQualityRenderingZoomThreshold$5 = {
  name: "Umbral de renderizado de baja calidad al hacer zoom",
  tooltip: "Renderiza formas de baja calidad cuando se aleja"
};
const LiteGraph_Canvas_MaximumFps$5 = {
  name: "FPS máximo",
  tooltip: "La cantidad máxima de cuadros por segundo que se permite renderizar en el lienzo. Limita el uso de la GPU a costa de la suavidad. Si es 0, se utiliza la tasa de refresco de la pantalla. Predeterminado: 0"
};
const LiteGraph_ContextMenu_Scaling$5 = {
  name: "Escala los menús de widgets combinados de nodos (listas) al acercar"
};
const LiteGraph_Node_DefaultPadding$5 = {
  name: "Reducir siempre los nuevos nodos",
  tooltip: "Redimensiona los nodos al tamaño más pequeño posible al crearlos. Si está desactivado, un nodo recién añadido se ampliará ligeramente para mostrar los valores de los widgets."
};
const LiteGraph_Node_TooltipDelay$5 = {
  name: "Retraso de la información sobre herramientas"
};
const LiteGraph_Pointer_TrackpadGestures$5 = {
  name: "Habilitar gestos del trackpad",
  tooltip: "Esta configuración activa el modo trackpad para el lienzo, permitiendo hacer zoom con pellizco y desplazar con dos dedos."
};
const LiteGraph_Reroute_SplineOffset$5 = {
  name: "Desvío de la compensación de la spline",
  tooltip: "El punto de control bezier desplazado desde el punto central de reenrutamiento"
};
const pysssss_SnapToGrid$5 = {
  name: "Siempre ajustar a la cuadrícula"
};
const esSettings = {
  "Comfy-Desktop_AutoUpdate": {
    name: "Verificar actualizaciones automáticamente"
  },
  "Comfy-Desktop_SendStatistics": {
    name: "Enviar métricas de uso anónimas"
  },
  "Comfy-Desktop_UV_PypiInstallMirror": {
    name: "Espejo de instalación Pypi",
    tooltip: "Espejo de instalación pip por defecto"
  },
  "Comfy-Desktop_UV_PythonInstallMirror": {
    name: "Espejo de instalación Python",
    tooltip: "Las instalaciones de Python gestionadas se descargan del proyecto python-build-standalone de Astral. Esta variable puede establecerse en una URL de espejo para usar una fuente diferente para las instalaciones de Python. La URL proporcionada reemplazará https://github.com/astral-sh/python-build-standalone/releases/download en, por ejemplo, https://github.com/astral-sh/python-build-standalone/releases/download/20240713/cpython-3.12.4%2B20240713-aarch64-apple-darwin-install_only.tar.gz. Las distribuciones pueden leerse desde un directorio local utilizando el esquema de URL file://."
  },
  "Comfy-Desktop_UV_TorchInstallMirror": {
    name: "Espejo de instalación Torch",
    tooltip: "Espejo de instalación pip para pytorch"
  },
  "Comfy-Desktop_WindowStyle": {
    name: "Estilo de ventana",
    options: {
      custom: "personalizado",
      "default": "predeterminado"
    },
    tooltip: "Personalizado: Reemplace la barra de título del sistema con el menú superior de ComfyUI"
  },
  Comfy_Canvas_SelectionToolbox: Comfy_Canvas_SelectionToolbox$5,
  Comfy_ConfirmClear: Comfy_ConfirmClear$5,
  Comfy_DOMClippingEnabled: Comfy_DOMClippingEnabled$5,
  Comfy_DevMode: Comfy_DevMode$5,
  Comfy_DisableFloatRounding: Comfy_DisableFloatRounding$5,
  Comfy_DisableSliders: Comfy_DisableSliders$5,
  Comfy_EditAttention_Delta: Comfy_EditAttention_Delta$5,
  Comfy_EnableTooltips: Comfy_EnableTooltips$5,
  Comfy_EnableWorkflowViewRestore: Comfy_EnableWorkflowViewRestore$5,
  Comfy_FloatRoundingPrecision: Comfy_FloatRoundingPrecision$5,
  Comfy_Graph_CanvasInfo: Comfy_Graph_CanvasInfo$5,
  Comfy_Graph_CanvasMenu: Comfy_Graph_CanvasMenu$5,
  Comfy_Graph_CtrlShiftZoom: Comfy_Graph_CtrlShiftZoom$5,
  Comfy_Graph_LinkMarkers: Comfy_Graph_LinkMarkers$5,
  Comfy_Graph_ZoomSpeed: Comfy_Graph_ZoomSpeed$5,
  Comfy_GroupSelectedNodes_Padding: Comfy_GroupSelectedNodes_Padding$5,
  Comfy_Group_DoubleClickTitleToEdit: Comfy_Group_DoubleClickTitleToEdit$5,
  Comfy_LinkRelease_Action: Comfy_LinkRelease_Action$5,
  Comfy_LinkRelease_ActionShift: Comfy_LinkRelease_ActionShift$5,
  Comfy_LinkRenderMode: Comfy_LinkRenderMode$5,
  Comfy_Load3D_BackgroundColor: Comfy_Load3D_BackgroundColor$5,
  Comfy_Load3D_CameraType: Comfy_Load3D_CameraType$5,
  Comfy_Load3D_LightAdjustmentIncrement: Comfy_Load3D_LightAdjustmentIncrement$5,
  Comfy_Load3D_LightIntensity: Comfy_Load3D_LightIntensity$5,
  Comfy_Load3D_LightIntensityMaximum: Comfy_Load3D_LightIntensityMaximum$5,
  Comfy_Load3D_LightIntensityMinimum: Comfy_Load3D_LightIntensityMinimum$5,
  Comfy_Load3D_ShowGrid: Comfy_Load3D_ShowGrid$5,
  Comfy_Load3D_ShowPreview: Comfy_Load3D_ShowPreview$5,
  Comfy_Locale: Comfy_Locale$5,
  Comfy_MaskEditor_BrushAdjustmentSpeed: Comfy_MaskEditor_BrushAdjustmentSpeed$5,
  Comfy_MaskEditor_UseDominantAxis: Comfy_MaskEditor_UseDominantAxis$5,
  Comfy_MaskEditor_UseNewEditor: Comfy_MaskEditor_UseNewEditor$5,
  Comfy_ModelLibrary_AutoLoadAll: Comfy_ModelLibrary_AutoLoadAll$5,
  Comfy_ModelLibrary_NameFormat: Comfy_ModelLibrary_NameFormat$5,
  Comfy_NodeBadge_NodeIdBadgeMode: Comfy_NodeBadge_NodeIdBadgeMode$5,
  Comfy_NodeBadge_NodeLifeCycleBadgeMode: Comfy_NodeBadge_NodeLifeCycleBadgeMode$5,
  Comfy_NodeBadge_NodeSourceBadgeMode: Comfy_NodeBadge_NodeSourceBadgeMode$5,
  Comfy_NodeSearchBoxImpl: Comfy_NodeSearchBoxImpl$5,
  Comfy_NodeSearchBoxImpl_NodePreview: Comfy_NodeSearchBoxImpl_NodePreview$5,
  Comfy_NodeSearchBoxImpl_ShowCategory: Comfy_NodeSearchBoxImpl_ShowCategory$5,
  Comfy_NodeSearchBoxImpl_ShowIdName: Comfy_NodeSearchBoxImpl_ShowIdName$5,
  Comfy_NodeSearchBoxImpl_ShowNodeFrequency: Comfy_NodeSearchBoxImpl_ShowNodeFrequency$5,
  Comfy_NodeSuggestions_number: Comfy_NodeSuggestions_number$5,
  Comfy_Node_AllowImageSizeDraw: Comfy_Node_AllowImageSizeDraw$5,
  Comfy_Node_AutoSnapLinkToSlot: Comfy_Node_AutoSnapLinkToSlot$5,
  Comfy_Node_BypassAllLinksOnDelete: Comfy_Node_BypassAllLinksOnDelete$5,
  Comfy_Node_DoubleClickTitleToEdit: Comfy_Node_DoubleClickTitleToEdit$5,
  Comfy_Node_MiddleClickRerouteNode: Comfy_Node_MiddleClickRerouteNode$5,
  Comfy_Node_Opacity: Comfy_Node_Opacity$5,
  Comfy_Node_ShowDeprecated: Comfy_Node_ShowDeprecated$5,
  Comfy_Node_ShowExperimental: Comfy_Node_ShowExperimental$5,
  Comfy_Node_SnapHighlightsNode: Comfy_Node_SnapHighlightsNode$5,
  Comfy_Pointer_ClickBufferTime: Comfy_Pointer_ClickBufferTime$5,
  Comfy_Pointer_ClickDrift: Comfy_Pointer_ClickDrift$5,
  Comfy_Pointer_DoubleClickTime: Comfy_Pointer_DoubleClickTime$5,
  Comfy_PreviewFormat: Comfy_PreviewFormat$5,
  Comfy_PromptFilename: Comfy_PromptFilename$5,
  Comfy_QueueButton_BatchCountLimit: Comfy_QueueButton_BatchCountLimit$5,
  Comfy_Queue_MaxHistoryItems: Comfy_Queue_MaxHistoryItems$5,
  Comfy_Sidebar_Location: Comfy_Sidebar_Location$5,
  Comfy_Sidebar_Size: Comfy_Sidebar_Size$5,
  Comfy_Sidebar_UnifiedWidth: Comfy_Sidebar_UnifiedWidth$5,
  Comfy_SnapToGrid_GridSize: Comfy_SnapToGrid_GridSize$5,
  Comfy_TextareaWidget_FontSize: Comfy_TextareaWidget_FontSize$5,
  Comfy_TextareaWidget_Spellcheck: Comfy_TextareaWidget_Spellcheck$5,
  Comfy_TreeExplorer_ItemPadding: Comfy_TreeExplorer_ItemPadding$5,
  Comfy_UseNewMenu: Comfy_UseNewMenu$5,
  Comfy_Validation_NodeDefs: Comfy_Validation_NodeDefs$5,
  Comfy_Validation_Workflows: Comfy_Validation_Workflows$5,
  Comfy_WidgetControlMode: Comfy_WidgetControlMode$5,
  Comfy_Window_UnloadConfirmation: Comfy_Window_UnloadConfirmation$5,
  Comfy_Workflow_AutoSave: Comfy_Workflow_AutoSave$5,
  Comfy_Workflow_AutoSaveDelay: Comfy_Workflow_AutoSaveDelay$5,
  Comfy_Workflow_ConfirmDelete: Comfy_Workflow_ConfirmDelete$5,
  Comfy_Workflow_Persist: Comfy_Workflow_Persist$5,
  Comfy_Workflow_ShowMissingModelsWarning: Comfy_Workflow_ShowMissingModelsWarning$5,
  Comfy_Workflow_ShowMissingNodesWarning: Comfy_Workflow_ShowMissingNodesWarning$5,
  Comfy_Workflow_SortNodeIdOnSave: Comfy_Workflow_SortNodeIdOnSave$5,
  Comfy_Workflow_WorkflowTabsPosition: Comfy_Workflow_WorkflowTabsPosition$5,
  LiteGraph_Canvas_LowQualityRenderingZoomThreshold: LiteGraph_Canvas_LowQualityRenderingZoomThreshold$5,
  LiteGraph_Canvas_MaximumFps: LiteGraph_Canvas_MaximumFps$5,
  LiteGraph_ContextMenu_Scaling: LiteGraph_ContextMenu_Scaling$5,
  LiteGraph_Node_DefaultPadding: LiteGraph_Node_DefaultPadding$5,
  LiteGraph_Node_TooltipDelay: LiteGraph_Node_TooltipDelay$5,
  LiteGraph_Pointer_TrackpadGestures: LiteGraph_Pointer_TrackpadGestures$5,
  LiteGraph_Reroute_SplineOffset: LiteGraph_Reroute_SplineOffset$5,
  pysssss_SnapToGrid: pysssss_SnapToGrid$5
};
const Comfy_BrowseTemplates$4 = {
  label: "Parcourir les modèles"
};
const Comfy_Canvas_DeleteSelectedItems$4 = {
  label: "Supprimer les éléments sélectionnés"
};
const Comfy_Canvas_FitView$4 = {
  label: "Ajuster la vue aux nœuds sélectionnés"
};
const Comfy_Canvas_ResetView$4 = {
  label: "Réinitialiser la vue"
};
const Comfy_Canvas_Resize$4 = {
  label: "Redimensionner les nœuds sélectionnés"
};
const Comfy_Canvas_ToggleLinkVisibility$4 = {
  label: "Basculer la visibilité du lien sur le canevas"
};
const Comfy_Canvas_ToggleLock$4 = {
  label: "Basculer le verrouillage du canevas"
};
const Comfy_Canvas_ToggleSelectedNodes_Bypass$4 = {
  label: "Contourner/Ne pas contourner les nœuds sélectionnés"
};
const Comfy_Canvas_ToggleSelectedNodes_Collapse$4 = {
  label: "Réduire/Étendre les nœuds sélectionnés"
};
const Comfy_Canvas_ToggleSelectedNodes_Mute$4 = {
  label: "Mettre en sourdine/Activer le son des nœuds sélectionnés"
};
const Comfy_Canvas_ToggleSelectedNodes_Pin$4 = {
  label: "Épingler/Désépingler les nœuds sélectionnés"
};
const Comfy_Canvas_ToggleSelected_Pin$4 = {
  label: "Épingler/Désépingler les éléments sélectionnés"
};
const Comfy_Canvas_ZoomIn$4 = {
  label: "Zoom avant"
};
const Comfy_Canvas_ZoomOut$4 = {
  label: "Zoom arrière"
};
const Comfy_ClearPendingTasks$4 = {
  label: "Effacer les tâches en attente"
};
const Comfy_ClearWorkflow$4 = {
  label: "Effacer le flux de travail"
};
const Comfy_ContactSupport$4 = {
  label: "Contacter le support"
};
const Comfy_DuplicateWorkflow$4 = {
  label: "Dupliquer le flux de travail actuel"
};
const Comfy_ExportWorkflow$4 = {
  label: "Exporter le flux de travail"
};
const Comfy_ExportWorkflowAPI$4 = {
  label: "Exporter le flux de travail (format API)"
};
const Comfy_Feedback$4 = {
  label: "Retour d'information"
};
const Comfy_Graph_FitGroupToContents$4 = {
  label: "Ajuster le groupe au contenu"
};
const Comfy_Graph_GroupSelectedNodes$4 = {
  label: "Grouper les nœuds sélectionnés"
};
const Comfy_GroupNode_ConvertSelectedNodesToGroupNode$4 = {
  label: "Convertir les nœuds sélectionnés en nœud de groupe"
};
const Comfy_GroupNode_ManageGroupNodes$4 = {
  label: "Gérer les nœuds de groupe"
};
const Comfy_GroupNode_UngroupSelectedGroupNodes$4 = {
  label: "Dégrouper les nœuds de groupe sélectionnés"
};
const Comfy_Help_AboutComfyUI$4 = {
  label: "Ouvrir À propos de ComfyUI"
};
const Comfy_Help_OpenComfyOrgDiscord$4 = {
  label: "Ouvrir Comfy-Org Discord"
};
const Comfy_Help_OpenComfyUIDocs$4 = {
  label: "Ouvrir les documents ComfyUI"
};
const Comfy_Help_OpenComfyUIForum$4 = {
  label: "Ouvrir le forum Comfy-Org"
};
const Comfy_Help_OpenComfyUIIssues$4 = {
  label: "Ouvrir les problèmes ComfyUI"
};
const Comfy_Interrupt$4 = {
  label: "Interrompre"
};
const Comfy_LoadDefaultWorkflow$4 = {
  label: "Charger le flux de travail par défaut"
};
const Comfy_Manager_CustomNodesManager$4 = {
  label: "Gestionnaire de Nœuds Personnalisés"
};
const Comfy_Manager_ToggleManagerProgressDialog$4 = {
  label: "Basculer la boîte de dialogue de progression"
};
const Comfy_NewBlankWorkflow$4 = {
  label: "Nouveau flux de travail vierge"
};
const Comfy_OpenClipspace$4 = {
  label: "Espace de clip"
};
const Comfy_OpenWorkflow$4 = {
  label: "Ouvrir le flux de travail"
};
const Comfy_QueuePrompt$4 = {
  label: "Invite de file d'attente"
};
const Comfy_QueuePromptFront$4 = {
  label: "Invite de file d'attente (avant)"
};
const Comfy_QueueSelectedOutputNodes$4 = {
  label: "Mettre en file d’attente les nœuds de sortie sélectionnés"
};
const Comfy_Redo$4 = {
  label: "Refaire"
};
const Comfy_RefreshNodeDefinitions$4 = {
  label: "Actualiser les définitions de nœud"
};
const Comfy_SaveWorkflow$4 = {
  label: "Enregistrer le flux de travail"
};
const Comfy_SaveWorkflowAs$4 = {
  label: "Enregistrer le flux de travail sous"
};
const Comfy_ShowSettingsDialog$4 = {
  label: "Afficher la boîte de dialogue des paramètres"
};
const Comfy_ToggleTheme$4 = {
  label: "Changer de thème (Sombre/Clair)"
};
const Comfy_Undo$4 = {
  label: "Annuler"
};
const Comfy_User_OpenSignInDialog$4 = {
  label: "Ouvrir la boîte de dialogue de connexion"
};
const Comfy_User_SignOut$4 = {
  label: "Se déconnecter"
};
const Workspace_CloseWorkflow$4 = {
  label: "Fermer le flux de travail actuel"
};
const Workspace_NextOpenedWorkflow$4 = {
  label: "Flux de travail ouvert suivant"
};
const Workspace_PreviousOpenedWorkflow$4 = {
  label: "Flux de travail ouvert précédent"
};
const Workspace_SearchBox_Toggle$4 = {
  label: "Basculer la boîte de recherche"
};
const Workspace_ToggleBottomPanel$4 = {
  label: "Basculer le panneau inférieur"
};
const Workspace_ToggleFocusMode$4 = {
  label: "Basculer le mode focus"
};
const Workspace_ToggleSidebarTab_queue$4 = {
  label: "Basculer la barre latérale de la file d'attente",
  tooltip: "File d'attente"
};
const Workspace_ToggleSidebarTab_workflows$4 = {
  label: "Basculer la barre latérale des flux de travail",
  tooltip: "Flux de travail"
};
const frCommands = {
  "Comfy-Desktop_CheckForUpdates": {
    label: "Vérifier les mises à jour"
  },
  "Comfy-Desktop_Folders_OpenCustomNodesFolder": {
    label: "Ouvrir le dossier des nœuds personnalisés"
  },
  "Comfy-Desktop_Folders_OpenInputsFolder": {
    label: "Ouvrir le dossier des entrées"
  },
  "Comfy-Desktop_Folders_OpenLogsFolder": {
    label: "Ouvrir le dossier des journaux"
  },
  "Comfy-Desktop_Folders_OpenModelConfig": {
    label: "Ouvrir extra_model_paths.yaml"
  },
  "Comfy-Desktop_Folders_OpenModelsFolder": {
    label: "Ouvrir le dossier des modèles"
  },
  "Comfy-Desktop_Folders_OpenOutputsFolder": {
    label: "Ouvrir le dossier des sorties"
  },
  "Comfy-Desktop_OpenDevTools": {
    label: "Ouvrir les outils de développement"
  },
  "Comfy-Desktop_OpenUserGuide": {
    label: "Guide de l'utilisateur du bureau"
  },
  "Comfy-Desktop_Quit": {
    label: "Quitter"
  },
  "Comfy-Desktop_Reinstall": {
    label: "Réinstaller"
  },
  "Comfy-Desktop_Restart": {
    label: "Redémarrer"
  },
  Comfy_BrowseTemplates: Comfy_BrowseTemplates$4,
  Comfy_Canvas_DeleteSelectedItems: Comfy_Canvas_DeleteSelectedItems$4,
  Comfy_Canvas_FitView: Comfy_Canvas_FitView$4,
  Comfy_Canvas_ResetView: Comfy_Canvas_ResetView$4,
  Comfy_Canvas_Resize: Comfy_Canvas_Resize$4,
  Comfy_Canvas_ToggleLinkVisibility: Comfy_Canvas_ToggleLinkVisibility$4,
  Comfy_Canvas_ToggleLock: Comfy_Canvas_ToggleLock$4,
  Comfy_Canvas_ToggleSelectedNodes_Bypass: Comfy_Canvas_ToggleSelectedNodes_Bypass$4,
  Comfy_Canvas_ToggleSelectedNodes_Collapse: Comfy_Canvas_ToggleSelectedNodes_Collapse$4,
  Comfy_Canvas_ToggleSelectedNodes_Mute: Comfy_Canvas_ToggleSelectedNodes_Mute$4,
  Comfy_Canvas_ToggleSelectedNodes_Pin: Comfy_Canvas_ToggleSelectedNodes_Pin$4,
  Comfy_Canvas_ToggleSelected_Pin: Comfy_Canvas_ToggleSelected_Pin$4,
  Comfy_Canvas_ZoomIn: Comfy_Canvas_ZoomIn$4,
  Comfy_Canvas_ZoomOut: Comfy_Canvas_ZoomOut$4,
  Comfy_ClearPendingTasks: Comfy_ClearPendingTasks$4,
  Comfy_ClearWorkflow: Comfy_ClearWorkflow$4,
  Comfy_ContactSupport: Comfy_ContactSupport$4,
  Comfy_DuplicateWorkflow: Comfy_DuplicateWorkflow$4,
  Comfy_ExportWorkflow: Comfy_ExportWorkflow$4,
  Comfy_ExportWorkflowAPI: Comfy_ExportWorkflowAPI$4,
  Comfy_Feedback: Comfy_Feedback$4,
  Comfy_Graph_FitGroupToContents: Comfy_Graph_FitGroupToContents$4,
  Comfy_Graph_GroupSelectedNodes: Comfy_Graph_GroupSelectedNodes$4,
  Comfy_GroupNode_ConvertSelectedNodesToGroupNode: Comfy_GroupNode_ConvertSelectedNodesToGroupNode$4,
  Comfy_GroupNode_ManageGroupNodes: Comfy_GroupNode_ManageGroupNodes$4,
  Comfy_GroupNode_UngroupSelectedGroupNodes: Comfy_GroupNode_UngroupSelectedGroupNodes$4,
  Comfy_Help_AboutComfyUI: Comfy_Help_AboutComfyUI$4,
  Comfy_Help_OpenComfyOrgDiscord: Comfy_Help_OpenComfyOrgDiscord$4,
  Comfy_Help_OpenComfyUIDocs: Comfy_Help_OpenComfyUIDocs$4,
  Comfy_Help_OpenComfyUIForum: Comfy_Help_OpenComfyUIForum$4,
  Comfy_Help_OpenComfyUIIssues: Comfy_Help_OpenComfyUIIssues$4,
  Comfy_Interrupt: Comfy_Interrupt$4,
  Comfy_LoadDefaultWorkflow: Comfy_LoadDefaultWorkflow$4,
  Comfy_Manager_CustomNodesManager: Comfy_Manager_CustomNodesManager$4,
  Comfy_Manager_ToggleManagerProgressDialog: Comfy_Manager_ToggleManagerProgressDialog$4,
  Comfy_NewBlankWorkflow: Comfy_NewBlankWorkflow$4,
  Comfy_OpenClipspace: Comfy_OpenClipspace$4,
  Comfy_OpenWorkflow: Comfy_OpenWorkflow$4,
  Comfy_QueuePrompt: Comfy_QueuePrompt$4,
  Comfy_QueuePromptFront: Comfy_QueuePromptFront$4,
  Comfy_QueueSelectedOutputNodes: Comfy_QueueSelectedOutputNodes$4,
  Comfy_Redo: Comfy_Redo$4,
  Comfy_RefreshNodeDefinitions: Comfy_RefreshNodeDefinitions$4,
  Comfy_SaveWorkflow: Comfy_SaveWorkflow$4,
  Comfy_SaveWorkflowAs: Comfy_SaveWorkflowAs$4,
  Comfy_ShowSettingsDialog: Comfy_ShowSettingsDialog$4,
  Comfy_ToggleTheme: Comfy_ToggleTheme$4,
  Comfy_Undo: Comfy_Undo$4,
  Comfy_User_OpenSignInDialog: Comfy_User_OpenSignInDialog$4,
  Comfy_User_SignOut: Comfy_User_SignOut$4,
  Workspace_CloseWorkflow: Workspace_CloseWorkflow$4,
  Workspace_NextOpenedWorkflow: Workspace_NextOpenedWorkflow$4,
  Workspace_PreviousOpenedWorkflow: Workspace_PreviousOpenedWorkflow$4,
  Workspace_SearchBox_Toggle: Workspace_SearchBox_Toggle$4,
  Workspace_ToggleBottomPanel: Workspace_ToggleBottomPanel$4,
  "Workspace_ToggleBottomPanelTab_command-terminal": {
    label: "Basculer le panneau inférieur du terminal"
  },
  "Workspace_ToggleBottomPanelTab_logs-terminal": {
    label: "Basculer le panneau inférieur des journaux"
  },
  Workspace_ToggleFocusMode: Workspace_ToggleFocusMode$4,
  "Workspace_ToggleSidebarTab_model-library": {
    label: "Basculer la barre latérale de la bibliothèque de modèles",
    tooltip: "Bibliothèque de modèles"
  },
  "Workspace_ToggleSidebarTab_node-library": {
    label: "Basculer la barre latérale de la bibliothèque de nœuds",
    tooltip: "Bibliothèque de nœuds"
  },
  Workspace_ToggleSidebarTab_queue: Workspace_ToggleSidebarTab_queue$4,
  Workspace_ToggleSidebarTab_workflows: Workspace_ToggleSidebarTab_workflows$4
};
const apiNodesCostBreakdown$4 = {
  costPerRun: "Coût par exécution",
  title: "Nœud(s) API",
  totalCost: "Coût total"
};
const apiNodesNews$4 = {
  introducing: "Présentation",
  steps: {
    step1: {
      subtitle: "Paramètres > Utilisateur > Connexion",
      title: "Connectez-vous / Créez un compte :"
    },
    step2: {
      subtitle: "Paramètres > Crédits > Acheter des crédits",
      title: "Achetez des crédits :"
    },
    step3: {
      title: "Trouvez les nouveaux nœuds API dans la section 'API Node' et ajoutez-les à la toile"
    },
    step4: {
      title: "Lancez !"
    }
  },
  subtitle: "Tous les modèles externes sont désormais disponibles dans ComfyUI"
};
const apiNodesSignInDialog$4 = {
  message: "Ce flux de travail contient des nœuds API, qui nécessitent que vous soyez connecté à votre compte pour pouvoir fonctionner.",
  title: "Connexion requise pour utiliser les nœuds API"
};
const auth$4 = {
  apiKey: {
    cleared: "Clé API supprimée",
    clearedDetail: "Votre clé API a été supprimée avec succès",
    description: "Utilisez votre clé API Comfy pour activer les nœuds API",
    error: "Clé API invalide",
    generateKey: "Obtenez-en une ici",
    helpText: "Besoin d'une clé API ?",
    invalid: "Clé API invalide",
    invalidDetail: "Veuillez entrer une clé API valide",
    label: "Clé API",
    placeholder: "Entrez votre clé API",
    storageFailed: "Échec de l’enregistrement de la clé API",
    storageFailedDetail: "Veuillez réessayer.",
    stored: "Clé API enregistrée",
    storedDetail: "Votre clé API a été enregistrée avec succès",
    title: "Clé API",
    whitelistInfo: "À propos des sites non autorisés"
  },
  login: {
    andText: "et",
    confirmPasswordLabel: "Confirmer le mot de passe",
    confirmPasswordPlaceholder: "Entrez à nouveau le même mot de passe",
    emailLabel: "Email",
    emailPlaceholder: "Entrez votre email",
    failed: "Échec de la connexion",
    forgotPassword: "Mot de passe oublié?",
    forgotPasswordError: "Échec de l'envoi de l'e-mail de réinitialisation du mot de passe",
    insecureContextWarning: "Cette connexion n'est pas sécurisée (HTTP) - vos identifiants pourraient être interceptés par des attaquants si vous continuez à vous connecter.",
    loginButton: "Se connecter",
    loginWithGithub: "Se connecter avec Github",
    loginWithGoogle: "Se connecter avec Google",
    newUser: "Nouveau ici?",
    noAssociatedUser: "Aucun utilisateur Comfy n'est associé à la clé API fournie",
    orContinueWith: "Ou continuer avec",
    passwordLabel: "Mot de passe",
    passwordPlaceholder: "Entrez votre mot de passe",
    passwordResetSent: "E-mail de réinitialisation du mot de passe envoyé",
    passwordResetSentDetail: "Veuillez vérifier votre e-mail pour un lien de réinitialisation de votre mot de passe.",
    privacyLink: "Politique de confidentialité",
    questionsContactPrefix: "Des questions ? Contactez-nous à",
    signInOrSignUp: "Se connecter / S’inscrire",
    signUp: "S'inscrire",
    success: "Connexion réussie",
    termsLink: "Conditions d'utilisation",
    termsText: `En cliquant sur "Suivant" ou "S'inscrire", vous acceptez nos`,
    title: "Connectez-vous à votre compte",
    useApiKey: "Clé API Comfy",
    userAvatar: "Avatar utilisateur"
  },
  passwordUpdate: {
    success: "Mot de passe mis à jour",
    successDetail: "Votre mot de passe a été mis à jour avec succès"
  },
  signOut: {
    signOut: "Se déconnecter",
    success: "Déconnexion réussie",
    successDetail: "Vous avez été déconnecté de votre compte."
  },
  signup: {
    alreadyHaveAccount: "Vous avez déjà un compte?",
    emailLabel: "Email",
    emailPlaceholder: "Entrez votre email",
    passwordLabel: "Mot de passe",
    passwordPlaceholder: "Entrez un nouveau mot de passe",
    personalDataConsentLabel: "J'accepte le traitement de mes données personnelles.",
    regionRestrictionChina: "Conformément aux exigences réglementaires locales, nos services ne sont actuellement pas disponibles pour les utilisateurs situés en Chine continentale.",
    signIn: "Se connecter",
    signUpButton: "S'inscrire",
    signUpWithGithub: "S'inscrire avec Github",
    signUpWithGoogle: "S'inscrire avec Google",
    title: "Créer un compte"
  }
};
const clipboard$4 = {
  errorMessage: "Échec de la copie dans le presse-papiers",
  errorNotSupported: "L'API du presse-papiers n'est pas prise en charge par votre navigateur",
  successMessage: "Copié dans le presse-papiers"
};
const color$4 = {
  black: "Noir",
  blue: "Bleu",
  brown: "Marron",
  custom: "Personnalisé",
  cyan: "Cyan",
  "default": "Par défaut",
  green: "Vert",
  noColor: "Pas de couleur",
  pale_blue: "Bleu pâle",
  pink: "Rose",
  purple: "Violet",
  red: "Rouge",
  yellow: "Jaune"
};
const contextMenu$4 = {
  "Add Group": "Ajouter un Groupe",
  "Add Group For Selected Nodes": "Ajouter un Groupe pour les Nœuds Sélectionnés",
  "Add Node": "Ajouter un Nœud",
  Bypass: "Contourner",
  Clone: "Cloner",
  Collapse: "Réduire",
  Colors: "Couleurs",
  "Convert to Group Node": "Convertir en Nœud de Groupe",
  "Copy (Clipspace)": "Copier (Clipspace)",
  Expand: "Développer",
  Inputs: "Entrées",
  Manage: "Gérer",
  "Manage Group Nodes": "Gérer les Nœuds de Groupe",
  Mode: "Mode",
  "Node Templates": "Modèles de Nœuds",
  Outputs: "Sorties",
  Pin: "Épingler",
  Properties: "Propriétés",
  "Properties Panel": "Panneau des Propriétés",
  Remove: "Supprimer",
  Resize: "Redimensionner",
  "Save Selected as Template": "Enregistrer la Sélection comme Modèle",
  Search: "Recherche",
  Shapes: "Formes",
  Title: "Titre",
  Unpin: "Désépingler"
};
const credits$4 = {
  apiPricing: "Tarification de l’API",
  credits: "Crédits",
  faqs: "FAQ",
  invoiceHistory: "Historique des factures",
  lastUpdated: "Dernière mise à jour",
  messageSupport: "Contacter le support",
  purchaseCredits: "Acheter des crédits",
  topUp: {
    buyNow: "Acheter maintenant",
    insufficientMessage: "Vous n'avez pas assez de crédits pour exécuter ce workflow.",
    insufficientTitle: "Crédits insuffisants",
    maxAmount: "(Max. 1 000 $ US)",
    quickPurchase: "Achat rapide",
    seeDetails: "Voir les détails",
    topUp: "Recharger"
  },
  yourCreditBalance: "Votre solde de crédits"
};
const dataTypes$4 = {
  "*": "*",
  AUDIO: "AUDIO",
  BOOLEAN: "BOOLEAN",
  CAMERA_CONTROL: "Contrôle de la caméra",
  CLIP: "CLIP",
  CLIP_VISION: "CLIP_VISION",
  CLIP_VISION_OUTPUT: "SORTIE_CLIP_VISION",
  COMBO: "COMBO",
  CONDITIONING: "CONDITIONNEMENT",
  CONTROL_NET: "RESEAU_DE_CONTROLE",
  FLOAT: "FLOTTANT",
  FLOATS: "FLOTTANTS",
  GLIGEN: "GLIGEN",
  GUIDER: "GUIDE",
  HOOKS: "CROCHETS",
  HOOK_KEYFRAMES: "CLEFS_DE_CROCHET",
  IMAGE: "IMAGE",
  INT: "ENTIER",
  LATENT: "LATENT",
  LATENT_OPERATION: "OPERATION_LATENTE",
  LOAD3D_CAMERA: "Charger la caméra 3D",
  LOAD_3D: "CHARGER_3D",
  LOAD_3D_ANIMATION: "CHARGER_ANIMATION_3D",
  LUMA_CONCEPTS: "Concepts Luma",
  LUMA_REF: "Référence Luma",
  MASK: "MASQUE",
  MESH: "MAILLAGE",
  MODEL: "MODÈLE",
  NOISE: "BRUIT",
  PHOTOMAKER: "PHOTOMAKER",
  PIXVERSE_TEMPLATE: "Modèle Pixverse",
  RECRAFT_COLOR: "Couleur Recraft",
  RECRAFT_CONTROLS: "Contrôles Recraft",
  RECRAFT_V3_STYLE: "Style Recraft V3",
  SAMPLER: "ÉCHANTILLONNEUR",
  SIGMAS: "SIGMAS",
  STRING: "CHAÎNE",
  STYLE_MODEL: "MODÈLE_DE_STYLE",
  SVG: "SVG",
  TIMESTEPS_RANGE: "PLAGE_DES_ÉTAPES_TEMPORELLES",
  UPSCALE_MODEL: "MODÈLE_DE_MISE_À_L'ÉCHELLE",
  VAE: "VAE",
  VIDEO: "Vidéo",
  VOXEL: "VOXEL",
  WEBCAM: "WEBCAM"
};
const desktopMenu$4 = {
  confirmQuit: "Il y a des flux de travail non enregistrés ouverts; toutes les modifications non enregistrées seront perdues. Ignorer cela et quitter?",
  confirmReinstall: "Cela effacera votre fichier extra_models_config.yaml,\net commencera l'installation à nouveau.\n\nÊtes-vous sûr ?",
  quit: "Quitter",
  reinstall: "Réinstaller"
};
const desktopUpdate$4 = {
  description: "ComfyUI Desktop installe de nouvelles dépendances. Cela peut prendre quelques minutes.",
  errorCheckingUpdate: "Erreur lors de la vérification des mises à jour",
  errorInstallingUpdate: "Erreur lors de l'installation de la mise à jour",
  noUpdateFound: "Aucune mise à jour trouvée",
  terminalDefaultMessage: "Toute sortie de console de la mise à jour sera affichée ici.",
  title: "Mise à jour de ComfyUI Desktop",
  updateAvailableMessage: "Une mise à jour est disponible. Voulez-vous redémarrer et mettre à jour maintenant?",
  updateFoundTitle: "Mise à jour trouvée (v{version})"
};
const downloadGit$4 = {
  gitWebsite: "Télécharger git",
  instructions: "Veuillez télécharger et installer la dernière version pour votre système d'exploitation. Le bouton Télécharger git ci-dessous ouvre la page de téléchargement de git-scm.com.",
  message: "Impossible de localiser git. Une copie fonctionnelle de git est nécessaire pour un fonctionnement normal.",
  skip: "Passer",
  title: "Télécharger git",
  warning: "Si vous êtes sûr de ne pas avoir besoin de git installé, ou s'il y a eu une erreur, vous pouvez cliquer sur Passer pour contourner cette vérification. Essayer de faire fonctionner ComfyUI sans une copie fonctionnelle de git n'est actuellement pas pris en charge."
};
const electronFileDownload$4 = {
  cancel: "Annuler le téléchargement",
  cancelled: "Annulé",
  inProgress: "En cours",
  pause: "Pause du téléchargement",
  paused: "En pause",
  resume: "Reprendre le téléchargement"
};
const errorDialog$4 = {
  defaultTitle: "Une erreur est survenue",
  extensionFileHint: "Cela peut être dû au script suivant",
  loadWorkflowTitle: "Chargement interrompu en raison d'une erreur de rechargement des données de workflow",
  noStackTrace: "Aucune trace de pile disponible",
  promptExecutionError: "L'exécution de l'invite a échoué"
};
const g$4 = {
  about: "À propos",
  add: "Ajouter",
  all: "Tout",
  amount: "Quantité",
  apply: "Appliquer",
  back: "Retour",
  cancel: "Annuler",
  capture: "capture",
  category: "Catégorie",
  choose_file_to_upload: "choisissez le fichier à télécharger",
  close: "Fermer",
  color: "Couleur",
  comingSoon: "Bientôt disponible",
  command: "Commande",
  community: "Communauté",
  completed: "Terminé",
  confirm: "Confirmer",
  confirmed: "Confirmé",
  "continue": "Continuer",
  control_after_generate: "contrôle après génération",
  control_before_generate: "contrôle avant génération",
  copyToClipboard: "Copier dans le presse-papiers",
  currentUser: "Utilisateur actuel",
  customize: "Personnaliser",
  customizeFolder: "Personnaliser le dossier",
  "delete": "Supprimer",
  deprecated: "DEPR",
  description: "Description",
  devices: "Appareils",
  disableAll: "Désactiver tout",
  disabling: "Désactivation",
  download: "Télécharger",
  empty: "Vide",
  enableAll: "Activer tout",
  enabled: "Activé",
  enabling: "Activation",
  error: "Erreur",
  experimental: "BETA",
  "export": "Exportation",
  extensionName: "Nom de l'extension",
  feedback: "Commentaires",
  filter: "Filtrer",
  findIssues: "Trouver des problèmes",
  firstTimeUIMessage: `C'est la première fois que vous utilisez la nouvelle interface utilisateur. Choisissez "Menu > Utiliser le nouveau menu > Désactivé" pour restaurer l'ancienne interface utilisateur.`,
  goToNode: "Aller au nœud",
  icon: "Icône",
  imageFailedToLoad: "Échec du chargement de l'image",
  "import": "Importer",
  inProgress: "En cours",
  insert: "Insérer",
  install: "Installer",
  installed: "Installé",
  installing: "Installation",
  interrupted: "Interrompu",
  keybinding: "Raccourci clavier",
  learnMore: "En savoir plus",
  loadAllFolders: "Charger tous les dossiers",
  loadWorkflow: "Charger le flux de travail",
  loading: "Chargement",
  login: "Connexion",
  logs: "Journaux",
  migrate: "Migrer",
  missing: "Manquant",
  name: "Nom",
  newFolder: "Nouveau dossier",
  next: "Suivant",
  no: "Non",
  noResultsFound: "Aucun résultat trouvé",
  noTasksFound: "Aucune tâche trouvée",
  noTasksFoundMessage: "Il n'y a pas de tâches dans la file d'attente.",
  noWorkflowsFound: "Aucun flux de travail trouvé.",
  nodes: "Nœuds",
  ok: "OK",
  openNewIssue: "Ouvrir un nouveau problème",
  overwrite: "Écraser",
  reconnected: "Reconnecté",
  reconnecting: "Reconnexion",
  refresh: "Rafraîchir",
  reloadToApplyChanges: "Recharger pour appliquer les modifications",
  rename: "Renommer",
  reportIssue: "Envoyer le rapport",
  reportIssueTooltip: "Soumettre le rapport d'erreur à Comfy Org",
  reportSent: "Rapport soumis",
  reset: "Réinitialiser",
  resetAll: "Réinitialiser tout",
  resetAllKeybindingsTooltip: "Réinitialiser tous les raccourcis clavier par défaut",
  restart: "Redémarrer",
  resultsCount: "{count} Résultats Trouvés",
  save: "Enregistrer",
  saving: "Enregistrement",
  searchExtensions: "Rechercher des extensions",
  searchFailedMessage: "Nous n'avons trouvé aucun paramètre correspondant à votre recherche. Essayez d'ajuster vos termes de recherche.",
  searchKeybindings: "Rechercher des raccourcis clavier",
  searchModels: "Rechercher des modèles",
  searchNodes: "Rechercher des nœuds",
  searchSettings: "Rechercher des paramètres",
  searchWorkflows: "Rechercher des flux de travail",
  settings: "Paramètres",
  showReport: "Afficher le rapport",
  sort: "Trier",
  source: "Source",
  status: "Statut",
  success: "Succès",
  systemInfo: "Informations système",
  terminal: "Terminal",
  title: "Titre",
  unknownError: "Erreur inconnue",
  update: "Mettre à jour",
  updateAvailable: "Mise à jour disponible",
  updated: "Mis à jour",
  updating: "Mise à jour",
  upload: "Téléverser",
  user: "Utilisateur",
  videoFailedToLoad: "Échec du chargement de la vidéo",
  workflow: "Flux de travail"
};
const graphCanvasMenu$4 = {
  fitView: "Adapter la vue",
  panMode: "Mode panoramique",
  resetView: "Réinitialiser la vue",
  selectMode: "Mode sélection",
  toggleLinkVisibility: "Basculer la visibilité des liens",
  zoomIn: "Zoom avant",
  zoomOut: "Zoom arrière"
};
const groupNode$4 = {
  create: "Créer un nœud de groupe",
  enterName: "Entrer le nom"
};
const icon$4 = {
  bookmark: "Favori",
  box: "Boîte",
  briefcase: "Porte-documents",
  "exclamation-triangle": "Avertissement",
  file: "Fichier",
  folder: "Dossier",
  heart: "Cœur",
  inbox: "Boîte de réception",
  star: "Étoile"
};
const install$4 = {
  appDataLocationTooltip: "Répertoire des données de l'application ComfyUI. Stocke :\n- Logs\n- Configurations du serveur",
  appPathLocationTooltip: "Répertoire des ressources de l'application ComfyUI. Stocke le code et les ressources de ComfyUI",
  cannotWrite: "Impossible d'écrire sur le chemin sélectionné",
  chooseInstallationLocation: "Choisissez l'emplacement d'installation",
  customNodes: "Nœuds personnalisés",
  customNodesDescription: "Réinstallez les nœuds personnalisés à partir des installations existantes de ComfyUI.",
  desktopAppSettings: "Paramètres de l'application de bureau",
  desktopAppSettingsDescription: "Configurez comment ComfyUI se comporte sur votre bureau. Vous pouvez modifier ces paramètres plus tard.",
  desktopSettings: "Paramètres de bureau",
  failedToSelectDirectory: "Échec de la sélection du répertoire",
  gpu: "GPU",
  gpuSelection: {
    cpuMode: "Mode CPU",
    cpuModeDescription: "Le mode CPU est destiné aux développeurs et aux cas limites rares uniquement.",
    cpuModeDescription2: "Si vous n'êtes pas absolument certain d'en avoir besoin, veuillez ignorer cette case et sélectionnez votre GPU ci-dessus.",
    customComfyNeedsPython: "ComfyUI ne fonctionnera pas tant que python n'est pas configuré",
    customInstallRequirements: "Installez toutes les exigences et dépendances (par exemple, torch personnalisé)",
    customManualVenv: "Configurer manuellement l'environnement virtuel python",
    customMayNotWork: "Ceci n'est pas du tout pris en charge, et peut simplement ne pas fonctionner",
    customSkipsPython: "Cette option saute la configuration python normale.",
    enableCpuMode: "Activer le mode CPU",
    mpsDescription: "Les shaders de performance métallique d'Apple sont pris en charge en utilisant la version nocturne de pytorch.",
    nvidiaDescription: "Les appareils NVIDIA sont directement pris en charge en utilisant les builds CUDA de pytorch.",
    selectGpu: "Sélectionnez le GPU",
    selectGpuDescription: "Sélectionnez le type de GPU que vous avez"
  },
  helpImprove: "Veuillez aider à améliorer ComfyUI",
  installLocation: "Emplacement d'installation",
  installLocationDescription: "Sélectionnez le répertoire pour les données utilisateur de ComfyUI. Un environnement python sera installé à l'emplacement sélectionné. Veuillez vous assurer que le disque sélectionné a suffisamment d'espace (~15GB) restant.",
  installLocationTooltip: "Répertoire des données utilisateur de ComfyUI. Stocke :\n- Environnement Python\n- Modèles\n- Nœuds personnalisés\n",
  insufficientFreeSpace: "Espace insuffisant - espace libre minimum",
  isOneDrive: "L'installation dans OneDrive peut causer des problèmes. Nous recommandons fortement d'installer dans un emplacement non-OneDrive.",
  manualConfiguration: {
    createVenv: "Vous devrez créer un environnement virtuel dans le répertoire suivant",
    requirements: "Exigences",
    restartWhenFinished: "Lorsque vous avez terminé de configurer l'environnement virtuel, veuillez redémarrer ComfyUI.",
    title: "Configuration manuelle",
    virtualEnvironmentPath: "Chemin de l'environnement virtuel"
  },
  metricsDisabled: "Métriques désactivées",
  metricsEnabled: "Métriques activées",
  migrateFromExistingInstallation: "Migrer à partir d'une installation existante",
  migration: "Migration",
  migrationOptional: "La migration est facultative. Si vous n'avez pas d'installation existante, vous pouvez sauter cette étape.",
  migrationSourcePathDescription: "Si vous avez une installation existante de ComfyUI, nous pouvons copier/lier vos fichiers utilisateur et modèles existants à la nouvelle installation. Votre installation existante de ComfyUI ne sera pas affectée.",
  moreInfo: "Pour plus d'informations, veuillez lire notre",
  nonDefaultDrive: "Veuillez installer ComfyUI sur le disque système de votre ordinateur (par exemple C:\\). Les disques avec des systèmes de fichiers différents peuvent causer des problèmes imprévisibles. Les modèles et autres fichiers peuvent être stockés sur d'autres disques après l'installation.",
  parentMissing: "Le chemin n'existe pas - créez d'abord le répertoire contenant",
  pathExists: "Le répertoire existe déjà - veuillez vous assurer que vous avez sauvegardé toutes les données",
  pathValidationFailed: "Échec de la validation du chemin",
  privacyPolicy: "politique de confidentialité",
  selectItemsToMigrate: "Sélectionnez les éléments à migrer",
  settings: {
    allowMetrics: "Métriques d'utilisation",
    allowMetricsDescription: "Aidez à améliorer ComfyUI en envoyant des métriques d'utilisation anonymes. Aucune information personnelle ou contenu de flux de travail ne sera collecté.",
    autoUpdate: "Mises à jour automatiques",
    autoUpdateDescription: "Téléchargez et installez automatiquement les mises à jour lorsqu'elles deviennent disponibles. Vous serez toujours informé avant l'installation des mises à jour.",
    checkingMirrors: "Vérification de l'accès réseau aux miroirs python...",
    dataCollectionDialog: {
      collect: {
        errorReports: "Message d'erreur et trace de la pile",
        systemInfo: "Matériel, type de système d'exploitation et version de l'application",
        userJourneyEvents: "Événements du parcours utilisateur"
      },
      doNotCollect: {
        customNodeConfigurations: "Configurations de nœud personnalisées",
        fileSystemInformation: "Informations sur le système de fichiers",
        personalInformation: "Informations personnelles",
        workflowContents: "Contenus du flux de travail"
      },
      title: "À propos de la collecte de données",
      viewFullPolicy: "Voir la politique complète",
      whatWeCollect: "Ce que nous collectons :",
      whatWeDoNotCollect: "Ce que nous ne collectons pas :"
    },
    errorUpdatingConsent: "Erreur de mise à jour du consentement",
    errorUpdatingConsentDetail: "Échec de la mise à jour des paramètres de consentement aux métriques",
    learnMoreAboutData: "En savoir plus sur la collecte de données",
    mirrorSettings: "Paramètres du Miroir",
    mirrorsReachable: "L'accès réseau aux miroirs python est bon",
    mirrorsUnreachable: "L'accès au réseau à certains miroirs python est mauvais",
    pypiMirrorPlaceholder: "Entrez l'URL du miroir PyPI",
    pythonMirrorPlaceholder: "Entrez l'URL du miroir Python"
  },
  systemLocations: "Emplacements système",
  unhandledError: "Erreur inconnue",
  updateConsent: "Vous avez précédemment accepté de signaler les plantages. Nous suivons maintenant des métriques basées sur les événements pour aider à identifier les bugs et améliorer l'application. Aucune information personnelle identifiable n'est collectée."
};
const issueReport$4 = {
  contactFollowUp: "Contactez-moi pour un suivi",
  contactSupportDescription: "Veuillez remplir le formulaire ci-dessous avec votre signalement",
  contactSupportTitle: "Contacter le support",
  describeTheProblem: "Décrivez le problème",
  email: "E-mail",
  feedbackTitle: "Aidez-nous à améliorer ComfyUI en fournissant des commentaires",
  helpFix: "Aidez à résoudre cela",
  helpTypes: {
    billingPayments: "Facturation / Paiements",
    bugReport: "Signaler un bug",
    giveFeedback: "Donner un avis",
    loginAccessIssues: "Problèmes de connexion / d'accès",
    somethingElse: "Autre chose"
  },
  notifyResolve: "Prévenez-moi lorsque résolu",
  provideAdditionalDetails: "Fournir des détails supplémentaires (facultatif)",
  provideEmail: "Donnez-nous votre email (Facultatif)",
  rating: "Évaluation",
  selectIssue: "Sélectionnez le problème",
  stackTrace: "Trace de la pile",
  submitErrorReport: "Soumettre un rapport d'erreur (Facultatif)",
  systemStats: "Statistiques du système",
  validation: {
    invalidEmail: "Veuillez entrer une adresse e-mail valide",
    maxLength: "Message trop long",
    selectIssueType: "Veuillez sélectionner un type de problème"
  },
  whatCanWeInclude: "Précisez ce qu'il faut inclure dans le rapport",
  whatDoYouNeedHelpWith: "Avec quoi avez-vous besoin d'aide ?"
};
const load3d$4 = {
  applyingTexture: "Application de la texture...",
  backgroundColor: "Couleur de fond",
  camera: "Caméra",
  clearRecording: "Effacer l'enregistrement",
  edgeThreshold: "Seuil de Bordure",
  "export": "Exportation",
  exportModel: "Exportation du modèle",
  exportRecording: "Exporter l'enregistrement",
  exportingModel: "Exportation du modèle en cours...",
  fov: "FOV",
  light: "Lumière",
  lightIntensity: "Intensité de la lumière",
  loadingModel: "Chargement du modèle 3D...",
  materialMode: "Mode Matériel",
  materialModes: {
    depth: "Profondeur",
    lineart: "Dessin au trait",
    normal: "Normal",
    original: "Original",
    wireframe: "Fil de fer"
  },
  model: "Modèle",
  previewOutput: "Aperçu de la sortie",
  removeBackgroundImage: "Supprimer l'image de fond",
  resizeNodeMatchOutput: "Redimensionner le nœud pour correspondre à la sortie",
  scene: "Scène",
  showGrid: "Afficher la grille",
  startRecording: "Démarrer l'enregistrement",
  stopRecording: "Arrêter l'enregistrement",
  switchCamera: "Changer de caméra",
  switchingMaterialMode: "Changement de mode de matériau...",
  upDirection: "Direction Haut",
  uploadBackgroundImage: "Télécharger l'image de fond",
  uploadTexture: "Télécharger Texture"
};
const maintenance$4 = {
  None: "Aucun",
  OK: "OK",
  Skipped: "Ignoré",
  allOk: "Aucun problème détecté.",
  confirmTitle: "Êtes-vous sûr ?",
  consoleLogs: "Journaux de la console",
  detected: "Détecté",
  error: {
    cannotContinue: "Impossible de continuer - des erreurs subsistent",
    defaultDescription: "Une erreur s'est produite lors de l'exécution d'une tâche de maintenance.",
    taskFailed: "La tâche a échoué.",
    toastTitle: "Erreur de tâche"
  },
  refreshing: "Actualisation",
  showManual: "Afficher les tâches de maintenance",
  status: "Statut",
  terminalDefaultMessage: "Lorsque vous exécutez une commande de dépannage, toute sortie sera affichée ici.",
  title: "Maintenance"
};
const manager$4 = {
  changingVersion: "Changement de version de {from} à {to}",
  createdBy: "Créé par",
  dependencies: "Dépendances",
  discoverCommunityContent: "Découvrez les packs de nœuds, extensions et plus encore créés par la communauté...",
  downloads: "Téléchargements",
  errorConnecting: "Erreur de connexion au registre de nœuds Comfy.",
  failed: "Échoué ({count})",
  filter: {
    disabled: "Désactivé",
    enabled: "Activé",
    nodePack: "Pack de Nœuds"
  },
  inWorkflow: "Dans le flux de travail",
  infoPanelEmpty: "Cliquez sur un élément pour voir les informations",
  installSelected: "Installer sélectionné",
  installationQueue: "File d'attente d'installation",
  lastUpdated: "Dernière mise à jour",
  latestVersion: "Dernière",
  license: "Licence",
  loadingVersions: "Chargement des versions...",
  nightlyVersion: "Nocturne",
  noDescription: "Aucune description disponible",
  noNodesFound: "Aucun nœud trouvé",
  noNodesFoundDescription: "Les nœuds du pack n'ont pas pu être analysés, ou le pack est une extension frontend uniquement et n'a pas de nœuds.",
  noResultsFound: "Aucun résultat trouvé correspondant à votre recherche.",
  nodePack: "Pack de Nœuds",
  packsSelected: "Packs sélectionnés",
  repository: "Référentiel",
  restartToApplyChanges: "Pour appliquer les modifications, veuillez redémarrer ComfyUI",
  searchPlaceholder: "Recherche",
  selectVersion: "Sélectionner la version",
  sort: {
    created: "Le plus récent",
    downloads: "Le plus populaire",
    publisher: "Éditeur",
    updated: "Mis à jour récemment"
  },
  status: {
    active: "Actif",
    banned: "Banni",
    deleted: "Supprimé",
    flagged: "Signalé",
    pending: "En attente",
    unknown: "Inconnu"
  },
  title: "Gestionnaire de Nœuds Personnalisés",
  totalNodes: "Total de Nœuds",
  tryAgainLater: "Veuillez réessayer plus tard.",
  tryDifferentSearch: "Veuillez essayer une autre requête de recherche.",
  uninstall: "Désinstaller",
  uninstallSelected: "Désinstaller sélectionné",
  uninstalling: "Désinstallation",
  update: "Mettre à jour",
  updatingAllPacks: "Mise à jour de tous les paquets",
  version: "Version"
};
const maskEditor$4 = {
  "Apply to Whole Image": "Appliquer à toute l'image",
  "Brush Settings": "Paramètres de brosse",
  "Brush Shape": "Forme de brosse",
  Clear: "Effacer",
  "Color Select Settings": "Paramètres de sélection de couleur",
  "Fill Opacity": "Opacité de remplissage",
  Hardness: "Dureté",
  "Image Layer": "Couche d'image",
  Invert: "Inverser",
  Layers: "Couches",
  "Live Preview": "Aperçu en direct",
  "Mask Layer": "Couche de masque",
  "Mask Opacity": "Opacité du masque",
  "Mask Tolerance": "Tolérance du masque",
  Method: "Méthode",
  Opacity: "Opacité",
  "Paint Bucket Settings": "Paramètres du seau de peinture",
  "Reset to Default": "Réinitialiser par défaut",
  "Selection Opacity": "Opacité de sélection",
  "Smoothing Precision": "Précision de lissage",
  "Stop at mask": "Arrêter au masque",
  Thickness: "Épaisseur",
  Tolerance: "Tolérance"
};
const menu$4 = {
  autoQueue: "File d'attente automatique",
  batchCount: "Nombre de lots",
  batchCountTooltip: "Le nombre de fois que la génération du flux de travail doit être mise en file d'attente",
  clear: "Effacer le flux de travail",
  clipspace: "Ouvrir Clipspace",
  disabled: "Désactivé",
  disabledTooltip: "Le flux de travail ne sera pas mis en file d'attente automatiquement",
  execute: "Exécuter",
  hideMenu: "Masquer le menu",
  instant: "Instantané",
  instantTooltip: "Le flux de travail sera mis en file d'attente immédiatement après la fin d'une génération",
  interrupt: "Annuler l'exécution en cours",
  onChange: "Sur modification",
  onChangeTooltip: "Le flux de travail sera mis en file d'attente une fois une modification effectuée",
  refresh: "Actualiser les définitions des nœuds",
  resetView: "Réinitialiser la vue du canevas",
  run: "Exécuter",
  runWorkflow: "Exécuter le workflow (Maj pour mettre en file d'attente en premier)",
  runWorkflowFront: "Exécuter le workflow (Mettre en file d'attente en premier)",
  showMenu: "Afficher le menu",
  toggleBottomPanel: "Basculer le panneau inférieur"
};
const menuLabels$4 = {
  "About ComfyUI": "À propos de ComfyUI",
  "Browse Templates": "Parcourir les modèles",
  "Bypass/Unbypass Selected Nodes": "Contourner/Ne pas contourner les nœuds sélectionnés",
  "Canvas Toggle Link Visibility": "Basculer la visibilité du lien de la toile",
  "Canvas Toggle Lock": "Basculer le verrouillage de la toile",
  "Check for Updates": "Vérifier les mises à jour",
  "Clear Pending Tasks": "Effacer les tâches en attente",
  "Clear Workflow": "Effacer le flux de travail",
  Clipspace: "Espace de clip",
  "Close Current Workflow": "Fermer le flux de travail actuel",
  "Collapse/Expand Selected Nodes": "Réduire/Étendre les nœuds sélectionnés",
  "Comfy-Org Discord": "Discord de Comfy-Org",
  "ComfyUI Docs": "Docs de ComfyUI",
  "ComfyUI Forum": "Forum ComfyUI",
  "ComfyUI Issues": "Problèmes de ComfyUI",
  "Contact Support": "Contacter le support",
  "Convert selected nodes to group node": "Convertir les nœuds sélectionnés en nœud de groupe",
  "Custom Nodes Manager": "Gestionnaire de Nœuds Personnalisés",
  "Delete Selected Items": "Supprimer les éléments sélectionnés",
  "Desktop User Guide": "Guide de l'utilisateur de bureau",
  "Duplicate Current Workflow": "Dupliquer le flux de travail actuel",
  Edit: "Éditer",
  Export: "Exporter",
  "Export (API)": "Exporter (API)",
  "Fit Group To Contents": "Ajuster le groupe au contenu",
  "Fit view to selected nodes": "Ajuster la vue aux nœuds sélectionnés",
  "Give Feedback": "Donnez votre avis",
  "Group Selected Nodes": "Grouper les nœuds sélectionnés",
  Help: "Aide",
  Interrupt: "Interrompre",
  "Load Default Workflow": "Charger le flux de travail par défaut",
  "Manage group nodes": "Gérer les nœuds de groupe",
  "Mute/Unmute Selected Nodes": "Mettre en sourdine/Activer le son des nœuds sélectionnés",
  New: "Nouveau",
  "Next Opened Workflow": "Prochain flux de travail ouvert",
  Open: "Ouvrir",
  "Open Custom Nodes Folder": "Ouvrir le dossier des nœuds personnalisés",
  "Open DevTools": "Ouvrir DevTools",
  "Open Inputs Folder": "Ouvrir le dossier des entrées",
  "Open Logs Folder": "Ouvrir le dossier des journaux",
  "Open Models Folder": "Ouvrir le dossier des modèles",
  "Open Outputs Folder": "Ouvrir le dossier des sorties",
  "Open Sign In Dialog": "Ouvrir la boîte de dialogue de connexion",
  "Open extra_model_paths_yaml": "Ouvrir extra_model_paths.yaml",
  "Pin/Unpin Selected Items": "Épingler/Désépingler les éléments sélectionnés",
  "Pin/Unpin Selected Nodes": "Épingler/Désépingler les nœuds sélectionnés",
  "Previous Opened Workflow": "Flux de travail ouvert précédent",
  "Queue Prompt": "Invite de file d'attente",
  "Queue Prompt (Front)": "Invite de file d'attente (Front)",
  "Queue Selected Output Nodes": "Mettre en file d’attente les nœuds de sortie sélectionnés",
  Quit: "Quitter",
  Redo: "Refaire",
  "Refresh Node Definitions": "Actualiser les définitions de nœud",
  Reinstall: "Réinstaller",
  "Reset View": "Réinitialiser la vue",
  "Resize Selected Nodes": "Redimensionner les nœuds sélectionnés",
  Restart: "Redémarrer",
  Save: "Enregistrer",
  "Save As": "Enregistrer sous",
  "Show Settings Dialog": "Afficher la boîte de dialogue des paramètres",
  "Sign Out": "Se déconnecter",
  "Toggle Bottom Panel": "Basculer le panneau inférieur",
  "Toggle Focus Mode": "Basculer le mode focus",
  "Toggle Logs Bottom Panel": "Basculer le panneau inférieur des journaux",
  "Toggle Model Library Sidebar": "Basculer la barre latérale de la bibliothèque de modèles",
  "Toggle Node Library Sidebar": "Basculer la barre latérale de la bibliothèque de nœuds",
  "Toggle Progress Dialog": "Basculer la boîte de dialogue de progression",
  "Toggle Queue Sidebar": "Basculer la barre latérale de la file d'attente",
  "Toggle Search Box": "Basculer la boîte de recherche",
  "Toggle Terminal Bottom Panel": "Basculer le panneau inférieur du terminal",
  "Toggle Theme (Dark/Light)": "Basculer le thème (Sombre/Clair)",
  "Toggle Workflows Sidebar": "Basculer la barre latérale des flux de travail",
  Undo: "Annuler",
  "Ungroup selected group nodes": "Dégrouper les nœuds de groupe sélectionnés",
  Workflow: "Flux de travail",
  "Zoom In": "Zoom avant",
  "Zoom Out": "Zoom arrière"
};
const missingModelsDialog$4 = {
  doNotAskAgain: "Ne plus afficher ce message",
  missingModels: "Modèles manquants",
  missingModelsMessage: "Lors du chargement du graphique, les modèles suivants n'ont pas été trouvés"
};
const nodeCategories$4 = {
  "3d": "3d",
  "3d_models": "modèles_3d",
  BFL: "BFL",
  Ideogram: "Ideogram",
  Kling: "Kling",
  Luma: "Luma",
  MiniMax: "MiniMax",
  OpenAI: "OpenAI",
  Pika: "Pika",
  PixVerse: "PixVerse",
  Recraft: "Recraft",
  "Stability AI": "Stability AI",
  Veo: "Veo",
  _for_testing: "_pour_test",
  advanced: "avancé",
  animation: "animation",
  api: "api",
  "api node": "nœud api",
  attention_experiments: "expériences_d'attention",
  audio: "audio",
  batch: "lot",
  clip: "clip",
  combine: "combiner",
  compositing: "composition",
  "cond pair": "cond pair",
  "cond single": "cond unique",
  conditioning: "conditionnement",
  controlnet: "controlnet",
  create: "créer",
  custom_sampling: "échantillonnage_personnalisé",
  debug: "débogage",
  deprecated: "déprécié",
  flux: "flux",
  gligen: "gligen",
  guidance: "guidance",
  guiders: "guides",
  hooks: "crochets",
  image: "image",
  inpaint: "inpaint",
  instructpix2pix: "instructpix2pix",
  latent: "latent",
  loaders: "chargeurs",
  lotus: "lotus",
  ltxv: "ltxv",
  mask: "masque",
  model: "modèle",
  model_merging: "fusion_de_modèles",
  model_patches: "patches_de_modèle",
  model_specific: "spécifique_au_modèle",
  noise: "bruit",
  operations: "opérations",
  photomaker: "photomaker",
  postprocessing: "post-traitement",
  preprocessors: "préprocesseurs",
  primitive: "primitif",
  samplers: "échantillonneurs",
  sampling: "échantillonnage",
  schedulers: "planificateurs",
  scheduling: "planification",
  sd: "sd",
  sd3: "sd3",
  sigmas: "sigmas",
  stable_cascade: "stable_cascade",
  style_model: "modèle_de_style",
  transform: "transformer",
  unet: "unet",
  upscale_diffusion: "diffusion_de_mise_à_l'échelle",
  upscaling: "mise_à_l'échelle",
  utils: "utilitaires",
  v1: "v1",
  v2: "v2",
  v3: "v3",
  video: "vidéo",
  video_models: "modèles_vidéo"
};
const nodeTemplates$4 = {
  enterName: "Entrez le nom",
  saveAsTemplate: "Enregistrer comme modèle"
};
const notSupported$4 = {
  "continue": "Continuer",
  continueTooltip: "Je suis sûr que mon appareil est pris en charge",
  learnMore: "En savoir plus",
  message: "Seuls les appareils suivants sont pris en charge :",
  reportIssue: "Signaler un problème",
  supportedDevices: {
    macos: "MacOS (M1 ou ultérieur)",
    windows: "Windows (GPU Nvidia avec support CUDA)"
  },
  title: "Votre appareil n'est pas pris en charge"
};
const selectionToolbox$4 = {
  executeButton: {
    disabledTooltip: "Aucun nœud de sortie sélectionné",
    tooltip: "Exécuter vers les nœuds de sortie sélectionnés (surlignés avec une bordure orange)"
  }
};
const serverConfig$4 = {
  modifiedConfigs: "Vous avez modifié les configurations suivantes du serveur. Redémarrez pour appliquer les modifications.",
  restart: "Redémarrer",
  revertChanges: "Annuler les modifications"
};
const serverConfigCategories$4 = {
  Attention: "Attention",
  CUDA: "CUDA",
  Cache: "Cache",
  Directories: "Répertoires",
  General: "Général",
  Inference: "Inférence",
  Memory: "Mémoire",
  Network: "Réseau",
  Preview: "Aperçu"
};
const serverConfigItems$4 = {
  "cache-classic": {
    name: "Utiliser le système de cache classique"
  },
  "cache-lru": {
    name: "Utiliser le cache LRU avec un maximum de N résultats de nœuds mis en cache.",
    tooltip: "Peut utiliser plus de RAM/VRAM."
  },
  "cpu-vae": {
    name: "Exécuter VAE sur CPU"
  },
  "cross-attention-method": {
    name: "Méthode d'attention croisée"
  },
  "cuda-device": {
    name: "Index de l'appareil CUDA à utiliser"
  },
  "cuda-malloc": {
    name: "Utiliser CUDA malloc pour l'allocation de mémoire"
  },
  "default-hashing-function": {
    name: "Fonction de hachage par défaut pour les fichiers de modèle"
  },
  deterministic: {
    name: "Faire utiliser à pytorch des algorithmes déterministes plus lents quand il le peut.",
    tooltip: "Notez que cela peut ne pas rendre les images déterministes dans tous les cas."
  },
  directml: {
    name: "Index de l'appareil DirectML"
  },
  "disable-all-custom-nodes": {
    name: "Désactiver le chargement de tous les nœuds personnalisés."
  },
  "disable-ipex-optimize": {
    name: "Désactiver l'optimisation IPEX"
  },
  "disable-metadata": {
    name: "Désactiver l'enregistrement des métadonnées d'invite dans les fichiers."
  },
  "disable-smart-memory": {
    name: "Désactiver la gestion intelligente de la mémoire",
    tooltip: "Force ComfyUI à décharger agressivement vers la ram régulière au lieu de garder les modèles dans la vram quand il le peut."
  },
  "disable-xformers": {
    name: "Désactiver l'optimisation xFormers"
  },
  "dont-print-server": {
    name: "Ne pas imprimer la sortie du serveur sur la console."
  },
  "dont-upcast-attention": {
    name: "Prévenir l'attention de conversion ascendante"
  },
  "enable-cors-header": {
    name: `Activer l'en-tête CORS: Utilisez "*" pour toutes les origines ou spécifiez le domaine`
  },
  fast: {
    name: "Activer certaines optimisations non testées et potentiellement dégradantes pour la qualité."
  },
  "force-channels-last": {
    name: "Forcer le format de mémoire des derniers canaux"
  },
  "force-upcast-attention": {
    name: "Forcer l'attention de conversion ascendante"
  },
  "global-precision": {
    name: "Précision globale des points flottants",
    tooltip: "Précision globale des points flottants"
  },
  "input-directory": {
    name: "Répertoire d'entrée"
  },
  listen: {
    name: "Hôte: L'adresse IP à écouter"
  },
  "log-level": {
    name: "Niveau de verbosité de la journalisation"
  },
  "max-upload-size": {
    name: "Taille maximale de téléchargement (MB)"
  },
  "output-directory": {
    name: "Répertoire de sortie"
  },
  port: {
    name: "Port: Le port à écouter"
  },
  "preview-method": {
    name: "Méthode utilisée pour les aperçus latents"
  },
  "preview-size": {
    name: "Taille des images d'aperçu"
  },
  "reserve-vram": {
    name: "VRAM réservée (GB)",
    tooltip: "Définissez la quantité de vram en GB que vous souhaitez réserver pour l'utilisation de votre OS/autres logiciels. Par défaut, une certaine quantité est réservée en fonction de votre OS."
  },
  "text-encoder-precision": {
    name: "Précision de l'encodeur de texte",
    tooltip: "Précision de l'encodeur de texte"
  },
  "tls-certfile": {
    name: "Fichier de certificat TLS: Chemin vers le fichier de certificat TLS pour HTTPS"
  },
  "tls-keyfile": {
    name: "Fichier de clé TLS: Chemin vers le fichier de clé TLS pour HTTPS"
  },
  "unet-precision": {
    name: "Précision UNET",
    tooltip: "Précision UNET"
  },
  "vae-precision": {
    name: "Précision VAE",
    tooltip: "Précision VAE"
  },
  "vram-management": {
    name: "Mode de gestion de la VRAM"
  }
};
const serverStart$4 = {
  openLogs: "Ouvrir les journaux",
  process: {
    error: "Impossible de démarrer ComfyUI Desktop",
    "initial-state": "Chargement...",
    "python-setup": "Configuration de l'environnement Python...",
    ready: "Finalisation...",
    "starting-server": "Démarrage du serveur ComfyUI..."
  },
  reportIssue: "Signaler un problème",
  showTerminal: "Afficher le terminal",
  troubleshoot: "Dépannage"
};
const settingsCategories$4 = {
  "3D": "3D",
  About: "À Propos",
  Appearance: "Apparence",
  BrushAdjustment: "Ajustement de Brosse",
  Camera: "Caméra",
  Canvas: "Toile",
  ColorPalette: "Palette de Couleurs",
  Comfy: "Confort",
  "Comfy-Desktop": "Comfy-Desktop",
  ContextMenu: "Menu Contextuel",
  Credits: "Crédits",
  CustomColorPalettes: "Palettes de Couleurs Personnalisées",
  DevMode: "Mode Développeur",
  EditTokenWeight: "Modifier le Poids du Jeton",
  Extension: "Extension",
  General: "Général",
  Graph: "Graphique",
  Group: "Groupe",
  Keybinding: "Raccourci Clavier",
  Light: "Clair",
  Link: "Lien",
  LinkRelease: "Libération de Lien",
  LiteGraph: "Lite Graph",
  "Load 3D": "Charger 3D",
  Locale: "Locale",
  "Mask Editor": "Éditeur de Masque",
  Menu: "Menu",
  ModelLibrary: "Bibliothèque de Modèles",
  NewEditor: "Nouvel Éditeur",
  Node: "Nœud",
  "Node Search Box": "Boîte de Recherche de Nœud",
  "Node Widget": "Widget de Nœud",
  NodeLibrary: "Bibliothèque de Nœuds",
  Pointer: "Pointeur",
  Queue: "File d'Attente",
  QueueButton: "Bouton de File d'Attente",
  Reroute: "Réacheminement",
  RerouteBeta: "Reroute Beta",
  Scene: "Scène",
  Server: "Serveur",
  "Server-Config": "Config-Serveur",
  Settings: "Paramètres",
  Sidebar: "Barre Latérale",
  "Tree Explorer": "Explorateur d'Arbre",
  UV: "UV",
  User: "Utilisateur",
  Validation: "Validation",
  Window: "Fenêtre",
  Workflow: "Flux de Travail"
};
const sideToolbar$4 = {
  browseTemplates: "Parcourir les modèles d'exemple",
  downloads: "Téléchargements",
  logout: "Déconnexion",
  modelLibrary: "Bibliothèque de modèles",
  newBlankWorkflow: "Créer un nouveau flux de travail vierge",
  nodeLibrary: "Bibliothèque de nœuds",
  nodeLibraryTab: {
    sortOrder: "Ordre de tri"
  },
  openWorkflow: "Ouvrir le flux de travail dans le système de fichiers local",
  queue: "File d'attente",
  queueTab: {
    backToAllTasks: "Retour à toutes les tâches",
    clearPendingTasks: "Effacer les tâches en attente",
    containImagePreview: "Remplir l'aperçu de l'image",
    coverImagePreview: "Adapter l'aperçu de l'image",
    filter: "Filtrer les sorties",
    filters: {
      hideCached: "Masquer le cache",
      hideCanceled: "Masquer les annulations"
    },
    showFlatList: "Afficher la liste plate"
  },
  themeToggle: "Changer de thème",
  workflowTab: {
    confirmDelete: "Êtes-vous sûr de vouloir supprimer ce flux de travail ?",
    confirmDeleteTitle: "Supprimer le flux de travail ?",
    confirmOverwrite: "Le fichier ci-dessous existe déjà. Souhaitez-vous le remplacer ?",
    confirmOverwriteTitle: "Écraser le fichier existant ?",
    deleteFailed: "La tentative de suppression du flux de travail a échoué.",
    deleteFailedTitle: "Échec de la suppression",
    deleted: "Flux de travail supprimé",
    dirtyClose: "Les fichiers ci-dessous ont été modifiés. Souhaitez-vous les enregistrer avant de fermer ?",
    dirtyCloseHint: "Maintenez Shift pour fermer sans invite",
    dirtyCloseTitle: "Enregistrer les modifications ?",
    workflowTreeType: {
      bookmarks: "Favoris",
      browse: "Parcourir",
      open: "Ouvrir"
    }
  },
  workflows: "Flux de travail"
};
const tabMenu$4 = {
  addToBookmarks: "Ajouter aux Favoris",
  closeOtherTabs: "Fermer les autres onglets",
  closeTab: "Fermer l'onglet",
  closeTabsToLeft: "Fermer les onglets à gauche",
  closeTabsToRight: "Fermer les onglets à droite",
  duplicateTab: "Dupliquer l'onglet",
  removeFromBookmarks: "Retirer des Favoris"
};
const templateWorkflows$4 = {
  category: {
    "3D": "3D",
    "Area Composition": "Composition de zone",
    Audio: "Audio",
    Basics: "Basiques",
    "ComfyUI Examples": "Exemples ComfyUI",
    ControlNet: "ControlNet",
    "Custom Nodes": "Nœuds personnalisés",
    Flux: "Flux",
    Image: "Image",
    "Image API": "API d'image",
    Upscaling: "Mise à l'échelle",
    Video: "Vidéo",
    "Video API": "API vidéo"
  },
  template: {
    "3D": {
      "hunyuan-3d-multiview-elf": "Hunyuan3D Multivue",
      "hunyuan-3d-turbo": "Hunyuan3D Turbo",
      "hunyuan3d-non-multiview-train": "Hunyuan3D",
      stable_zero123_example: "Stable Zero123"
    },
    "Area Composition": {
      area_composition: "Composition de Zone",
      area_composition_reversed: "Composition de Zone Inversée",
      area_composition_square_area_for_subject: "Composition de Zone Carrée pour le Sujet"
    },
    Audio: {
      stable_audio_example: "Stable Audio"
    },
    Basics: {
      "default": "Génération d'Image",
      embedding_example: "Intégration",
      gligen_textbox_example: "Boîte de Texte Gligen",
      image2image: "Image à Image",
      inpain_model_outpainting: "Modèle Inpaint Outpainting",
      inpaint_example: "Inpaint",
      lora: "Lora",
      lora_multiple: "Lora Multiple"
    },
    ControlNet: {
      "2_pass_pose_worship": "2 Passes Pose Worship",
      controlnet_example: "ControlNet",
      depth_controlnet: "Profondeur ControlNet",
      depth_t2i_adapter: "Adaptateur Profondeur T2I",
      mixing_controlnets: "Mélange de ControlNets"
    },
    Flux: {
      flux_canny_model_example: "Flux Canny Model",
      flux_depth_lora_example: "Flux Depth Lora",
      flux_dev_checkpoint_example: "Flux Dev",
      flux_fill_inpaint_example: "Flux Inpaint",
      flux_fill_outpaint_example: "Flux Outpaint",
      flux_redux_model_example: "Flux Redux Model",
      flux_schnell: "Flux Schnell"
    },
    Image: {
      hidream_i1_dev: "HiDream I1 Dev",
      hidream_i1_fast: "HiDream I1 Rapide",
      hidream_i1_full: "HiDream I1 Complet",
      sd3_5_large_blur: "SD3.5 Grand Flou",
      sd3_5_large_canny_controlnet_example: "SD3.5 Grand Canny ControlNet",
      sd3_5_large_depth: "SD3.5 Grande Profondeur",
      sd3_5_simple_example: "SD3.5 Simple",
      sdxl_refiner_prompt_example: "SDXL Refiner Prompt",
      sdxl_revision_text_prompts: "Révisions de Texte SDXL",
      sdxl_revision_zero_positive: "Révision Zéro Positive SDXL",
      sdxl_simple_example: "SDXL Simple",
      sdxlturbo_example: "SDXL Turbo"
    },
    "Image API": {
      "api-openai-dall-e-2-inpaint": "Dall-E 2 Inpainting",
      "api-openai-dall-e-2-t2i": "Dall-E 2 Texte vers Image",
      "api-openai-dall-e-3-t2i": "Dall-E 3 Texte vers Image",
      api_bfl_flux_pro_t2i: "BFL Flux 1.1[pro] Ultra Texte vers Image",
      api_ideogram_v3_t2i: "Ideogram V3 Texte vers Image",
      api_luma_photon_i2i: "Luma Photon Image vers Image",
      api_luma_photon_style_ref: "Luma Photon Référence de Style",
      api_openai_image_1_i2i: "OpenAI Image-1 Image vers Image",
      api_openai_image_1_inpaint: "OpenAI Image-1 Inpainting",
      api_openai_image_1_multi_inputs: "OpenAI Image-1 Entrées Multiples",
      api_openai_image_1_t2i: "OpenAI Image-1 Texte vers Image",
      api_recraft_image_gen_with_color_control: "Recraft Génération d’Image avec Contrôle des Couleurs",
      api_recraft_image_gen_with_style_control: "Recraft Génération d’Image avec Contrôle du Style",
      api_recraft_vector_gen: "Recraft Génération de Vecteur",
      api_stability_sd3_t2i: "Stability AI Stable Image Ultra Texte vers Image"
    },
    Upscaling: {
      esrgan_example: "ESRGAN",
      hiresfix_esrgan_workflow: "Flux de Travail ESRGAN HiresFix",
      hiresfix_latent_workflow: "Flux de Travail Latent HiresFix",
      latent_upscale_different_prompt_model: "Modèle d'Agrandissement Latent Différent Prompt"
    },
    Video: {
      hunyuan_video_text_to_video: "Texte à Vidéo Hunyuan",
      image_to_video: "Image à Vidéo",
      image_to_video_wan: "Wan 2.1 Image à Vidéo",
      ltxv_image_to_video: "LTXV Image à Vidéo",
      ltxv_text_to_video: "LTXV Texte à Vidéo",
      mochi_text_to_video_example: "Exemple de Texte à Vidéo Mochi",
      text_to_video_wan: "Wan 2.1 Texte à Vidéo",
      txt_to_image_to_video: "Texte à Image à Vidéo",
      wan2_1_fun_control: "Wan 2.1 ControlNet",
      wan2_1_fun_inp: "Wan 2.1 Inpainting"
    },
    "Video API": {
      api_hailuo_minimax_i2v: "MiniMax Image vers Vidéo",
      api_kling_i2v: "Kling Image vers Vidéo",
      api_luma_i2v: "Luma Image vers Vidéo",
      api_pika_scene: "Pika Scènes : Images vers Vidéo",
      api_pixverse_t2v: "PixVerse Texte vers Vidéo",
      api_pixverse_template_i2v: "PixVerse Template Effects: Image vers Vidéo",
      api_veo2_i2v: "Veo2 Image vers Vidéo"
    }
  },
  templateDescription: {
    "3D": {
      "hunyuan-3d-multiview-elf": "Utilisez Hunyuan3D 2mv pour générer des modèles à partir de plusieurs vues.",
      "hunyuan-3d-turbo": "Utilisez Hunyuan3D 2mv turbo pour générer des modèles à partir de plusieurs vues.",
      "hunyuan3d-non-multiview-train": "Utilisez Hunyuan3D 2.0 pour générer des modèles à partir d'une seule vue.",
      stable_zero123_example: "Générez des vues 3D à partir d'images uniques."
    },
    "Area Composition": {
      area_composition: "Contrôlez la composition d'image avec des zones.",
      area_composition_reversed: "Inversez le workflow de composition de zones.",
      area_composition_square_area_for_subject: "Créez un placement cohérent du sujet."
    },
    Audio: {
      stable_audio_example: "Générez de l'audio à partir de descriptions textuelles."
    },
    Basics: {
      "default": "Générez des images à partir de descriptions textuelles.",
      embedding_example: "Utilisez l'inversion textuelle pour des styles cohérents.",
      gligen_textbox_example: "Spécifiez l'emplacement et la taille des objets.",
      image2image: "Transformez des images existantes à l'aide de prompts textuels.",
      inpain_model_outpainting: "Étendez les images au-delà de leurs limites d'origine.",
      inpaint_example: "Modifiez de façon transparente des parties spécifiques d'une image.",
      lora: "Appliquez des modèles LoRA pour des styles ou sujets spécialisés.",
      lora_multiple: "Combinez plusieurs modèles LoRA pour des résultats uniques."
    },
    ControlNet: {
      "2_pass_pose_worship": "Générez des images à partir de références de pose.",
      controlnet_example: "Contrôlez la génération d'image avec des images de référence.",
      depth_controlnet: "Créez des images avec une génération sensible à la profondeur.",
      depth_t2i_adapter: "Générez rapidement des images sensibles à la profondeur avec un adaptateur T2I.",
      mixing_controlnets: "Combinez plusieurs modèles ControlNet ensemble."
    },
    Flux: {
      flux_canny_model_example: "Générez des images à partir de la détection de contours.",
      flux_depth_lora_example: "Créez des images avec LoRA sensible à la profondeur.",
      flux_dev_checkpoint_example: "Créez des images avec les modèles de développement Flux.",
      flux_fill_inpaint_example: "Complétez les parties manquantes d'une image.",
      flux_fill_outpaint_example: "Étendez les images avec l'outpainting Flux.",
      flux_redux_model_example: "Transférez le style d'une image de référence pour guider la génération d'image avec Flux.",
      flux_schnell: "Générez des images rapidement avec Flux Schnell."
    },
    Image: {
      hidream_e1_full: "Modifiez des images avec HiDream E1.",
      hidream_i1_dev: "Générez des images avec HiDream I1 Dev.",
      hidream_i1_fast: "Générez rapidement des images avec HiDream I1.",
      hidream_i1_full: "Générez des images avec HiDream I1.",
      sd3_5_large_blur: "Générez des images à partir d'images de référence floues avec SD 3.5.",
      sd3_5_large_canny_controlnet_example: "Utilisez la détection de contours pour guider la génération d'images avec SD 3.5.",
      sd3_5_large_depth: "Créez des images sensibles à la profondeur avec SD 3.5.",
      sd3_5_simple_example: "Générez des images avec SD 3.5.",
      sdxl_refiner_prompt_example: "Améliorez les résultats SDXL avec des refineurs.",
      sdxl_revision_text_prompts: "Transférez des concepts à partir d'images de référence pour guider la génération d'images avec SDXL.",
      sdxl_revision_zero_positive: "Ajoutez des prompts textuels en plus des images de référence pour guider la génération d'images avec SDXL.",
      sdxl_simple_example: "Créez des images de haute qualité avec SDXL.",
      sdxlturbo_example: "Générez des images en une seule étape avec SDXL Turbo."
    },
    "Image API": {
      "api-openai-dall-e-2-inpaint": "Utilisez l'API Dall-E 2 pour faire de l'inpainting sur des images.",
      "api-openai-dall-e-2-t2i": "Utilisez l'API Dall-E 2 pour générer des images à partir de descriptions textuelles.",
      "api-openai-dall-e-3-t2i": "Utilisez l'API Dall-E 3 pour générer des images à partir de descriptions textuelles.",
      api_bfl_flux_pro_t2i: "Créez des images avec FLUX.1 [pro] pour un excellent suivi des prompts, une qualité visuelle, des détails d'image et une grande diversité de sorties.",
      api_ideogram_v3_t2i: "Générez des images avec un alignement prompt-image de haute qualité, du photoréalisme et du rendu de texte. Créez des logos professionnels, affiches promotionnelles, concepts de pages d'accueil, photographies de produits et plus. Composez facilement des compositions spatiales sophistiquées avec des arrière-plans complexes, un éclairage et des couleurs précis et nuancés, et des détails environnementaux réalistes.",
      api_luma_photon_i2i: "Guidez la génération d'image en combinant images et prompt.",
      api_luma_photon_style_ref: "Appliquez et mélangez des références de style avec un contrôle précis. Luma Photon capture l'essence de chaque image de référence, vous permettant de combiner des éléments visuels distincts tout en maintenant une qualité professionnelle.",
      api_openai_image_1_i2i: "Utilisez l'API GPT Image 1 pour générer des images à partir d'images.",
      api_openai_image_1_inpaint: "Utilisez l'API GPT Image 1 pour faire de l'inpainting sur des images.",
      api_openai_image_1_multi_inputs: "Utilisez l'API GPT Image 1 avec plusieurs entrées pour générer des images.",
      api_openai_image_1_t2i: "Utilisez l'API GPT Image 1 pour générer des images à partir de descriptions textuelles.",
      api_recraft_image_gen_with_color_control: "Créez une palette personnalisée à réutiliser pour plusieurs images ou choisissez les couleurs pour chaque photo. Adaptez la palette de couleurs de votre marque et créez des visuels qui vous ressemblent.",
      api_recraft_image_gen_with_style_control: "Contrôlez le style avec des exemples visuels, alignez le positionnement et affinez les objets. Stockez et partagez des styles pour une cohérence parfaite de la marque.",
      api_recraft_vector_gen: "Passez d'un prompt textuel à une image vectorielle avec le générateur vectoriel IA de Recraft. Produisez des illustrations vectorielles de la meilleure qualité pour des logos, affiches, icônes, publicités, bannières et maquettes. Perfectionnez vos designs avec des fichiers SVG nets et de haute qualité. Créez des illustrations vectorielles de marque pour votre application ou site web en quelques secondes.",
      api_stability_sd3_t2i: "Générez des images de haute qualité avec une excellente fidélité au prompt. Parfait pour les cas d'usage professionnels en résolution 1 mégapixel."
    },
    Upscaling: {
      esrgan_example: "Utilisez des modèles d'upscaling pour améliorer la qualité d'image.",
      hiresfix_esrgan_workflow: "Utilisez des modèles d'upscaling lors des étapes intermédiaires.",
      hiresfix_latent_workflow: "Améliorez la qualité d'image dans l'espace latent.",
      latent_upscale_different_prompt_model: "Upscalez et changez le prompt à chaque passage."
    },
    Video: {
      hunyuan_video_text_to_video: "Générez des vidéos avec le modèle Hunyuan.",
      image_to_video: "Transformez des images en vidéos animées.",
      image_to_video_wan: "Générez rapidement des vidéos à partir d'images.",
      ltxv_image_to_video: "Convertissez des images fixes en vidéos.",
      ltxv_text_to_video: "Générez des vidéos à partir de descriptions textuelles.",
      mochi_text_to_video_example: "Créez des vidéos avec le modèle Mochi.",
      text_to_video_wan: "Générez rapidement des vidéos à partir de descriptions textuelles.",
      txt_to_image_to_video: "Générez des images à partir de texte puis convertissez-les en vidéos.",
      wan2_1_flf2v_720_f16: "Générez une vidéo en contrôlant la première et la dernière image.",
      wan2_1_fun_control: "Guidez la génération vidéo avec le contrôle de pose, profondeur, contours et plus.",
      wan2_1_fun_inp: "Créez des vidéos à partir d'images de début et de fin."
    },
    "Video API": {
      api_hailuo_minimax_i2v: "Créez des vidéos raffinées à partir d'images et de texte, incluant l'intégration CGI et des effets photo tendance comme le hugging IA viral. Choisissez parmi une variété de styles et thèmes vidéo pour correspondre à votre vision créative.",
      api_kling_i2v: "Créez des vidéos avec une excellente fidélité au prompt pour les actions, expressions et mouvements de caméra. Prend désormais en charge des prompts complexes avec des actions séquentielles pour vous permettre de diriger votre scène.",
      api_luma_i2v: "Transformez des images statiques en animations magiques de haute qualité instantanément.",
      api_pika_scene: "Utilisez plusieurs images comme ingrédients et générez des vidéos qui les intègrent toutes.",
      api_pixverse_t2v: "Générez des vidéos avec une interprétation précise du prompt et des dynamiques vidéo impressionnantes.",
      api_pixverse_template_i2v: "Transformez des images statiques en vidéos dynamiques avec mouvement et effets.",
      api_veo2_i2v: "Utilisez l'API Google Veo2 pour générer des vidéos à partir d'images."
    }
  },
  title: "Commencez avec un modèle"
};
const toastMessages$4 = {
  couldNotDetermineFileType: "Impossible de déterminer le type de fichier",
  dropFileError: "Impossible de traiter l'élément déposé : {error}",
  emptyCanvas: "Toile vide",
  errorCopyImage: "Erreur lors de la copie de l'image: {error}",
  errorLoadingModel: "Erreur lors du chargement du modèle",
  errorSaveSetting: "Erreur lors de l'enregistrement du paramètre {id}: {err}",
  failedToAccessBillingPortal: "Échec de l'accès au portail de facturation : {error}",
  failedToApplyTexture: "Échec de l'application de la texture",
  failedToCreateCustomer: "Échec de la création du client : {error}",
  failedToDownloadFile: "Échec du téléchargement du fichier",
  failedToExportModel: "Échec de l'exportation du modèle en {format}",
  failedToFetchBalance: "Échec de la récupération du solde : {error}",
  failedToFetchLogs: "Échec de la récupération des journaux du serveur",
  failedToInitiateCreditPurchase: "Échec de l'initiation de l'achat de crédits : {error}",
  failedToPurchaseCredits: "Échec de l'achat de crédits : {error}",
  fileLoadError: "Impossible de trouver le flux de travail dans {fileName}",
  fileUploadFailed: "Échec du téléchargement du fichier",
  interrupted: "L'exécution a été interrompue",
  migrateToLitegraphReroute: "Les nœuds de reroute seront supprimés dans les futures versions. Cliquez pour migrer vers le reroute natif de litegraph.",
  no3dScene: "Aucune scène 3D pour appliquer la texture",
  no3dSceneToExport: "Aucune scène 3D à exporter",
  noTemplatesToExport: "Aucun modèle à exporter",
  nodeDefinitionsUpdated: "Définitions de nœuds mises à jour",
  nothingToGroup: "Rien à regrouper",
  nothingToQueue: "Rien à ajouter à la file d’attente",
  pendingTasksDeleted: "Tâches en attente supprimées",
  pleaseSelectNodesToGroup: "Veuillez sélectionner les nœuds (ou autres groupes) pour créer un groupe pour",
  pleaseSelectOutputNodes: "Veuillez sélectionner les nœuds de sortie",
  unableToGetModelFilePath: "Impossible d'obtenir le chemin du fichier modèle",
  unauthorizedDomain: "Votre domaine {domain} n'est pas autorisé à utiliser ce service. Veuillez contacter {email} pour ajouter votre domaine à la liste blanche.",
  updateRequested: "Mise à jour demandée",
  useApiKeyTip: "Astuce : Vous ne pouvez pas accéder à la connexion normale ? Utilisez l’option Clé API Comfy.",
  userNotAuthenticated: "Utilisateur non authentifié"
};
const userSelect$4 = {
  enterUsername: "Entrez un nom d'utilisateur",
  existingUser: "Utilisateur existant",
  newUser: "Nouvel utilisateur",
  next: "Suivant",
  selectUser: "Sélectionnez un utilisateur"
};
const userSettings$4 = {
  email: "E-mail",
  name: "Nom",
  notSet: "Non défini",
  provider: "Méthode de connexion",
  title: "Paramètres utilisateur",
  updatePassword: "Mettre à jour le mot de passe"
};
const validation$4 = {
  invalidEmail: "Adresse e-mail invalide",
  length: "Doit comporter {length} caractères",
  maxLength: "Ne doit pas dépasser {length} caractères",
  minLength: "Doit contenir au moins {length} caractères",
  password: {
    lowercase: "Doit contenir au moins une lettre minuscule",
    match: "Les mots de passe doivent correspondre",
    minLength: "Doit contenir entre 8 et 32 caractères",
    number: "Doit contenir au moins un chiffre",
    requirements: "Exigences du mot de passe",
    special: "Doit contenir au moins un caractère spécial",
    uppercase: "Doit contenir au moins une lettre majuscule"
  },
  personalDataConsentRequired: "Vous devez accepter le traitement de vos données personnelles.",
  prefix: "Doit commencer par {prefix}",
  required: "Requis"
};
const welcome$4 = {
  getStarted: "Commencer",
  title: "Bienvenue sur ComfyUI"
};
const workflowService$4 = {
  enterFilename: "Entrez le nom du fichier",
  exportWorkflow: "Exporter le flux de travail",
  saveWorkflow: "Enregistrer le flux de travail"
};
const fr = {
  apiNodesCostBreakdown: apiNodesCostBreakdown$4,
  apiNodesNews: apiNodesNews$4,
  apiNodesSignInDialog: apiNodesSignInDialog$4,
  auth: auth$4,
  clipboard: clipboard$4,
  color: color$4,
  contextMenu: contextMenu$4,
  credits: credits$4,
  dataTypes: dataTypes$4,
  desktopMenu: desktopMenu$4,
  desktopUpdate: desktopUpdate$4,
  downloadGit: downloadGit$4,
  electronFileDownload: electronFileDownload$4,
  errorDialog: errorDialog$4,
  g: g$4,
  graphCanvasMenu: graphCanvasMenu$4,
  groupNode: groupNode$4,
  icon: icon$4,
  install: install$4,
  issueReport: issueReport$4,
  load3d: load3d$4,
  maintenance: maintenance$4,
  manager: manager$4,
  maskEditor: maskEditor$4,
  menu: menu$4,
  menuLabels: menuLabels$4,
  missingModelsDialog: missingModelsDialog$4,
  nodeCategories: nodeCategories$4,
  nodeTemplates: nodeTemplates$4,
  notSupported: notSupported$4,
  selectionToolbox: selectionToolbox$4,
  serverConfig: serverConfig$4,
  serverConfigCategories: serverConfigCategories$4,
  serverConfigItems: serverConfigItems$4,
  serverStart: serverStart$4,
  settingsCategories: settingsCategories$4,
  sideToolbar: sideToolbar$4,
  tabMenu: tabMenu$4,
  templateWorkflows: templateWorkflows$4,
  toastMessages: toastMessages$4,
  userSelect: userSelect$4,
  userSettings: userSettings$4,
  validation: validation$4,
  welcome: welcome$4,
  workflowService: workflowService$4
};
const AddNoise$4 = {
  display_name: "AjouterBruit",
  inputs: {
    latent_image: {
      name: "image_latente"
    },
    model: {
      name: "modèle"
    },
    noise: {
      name: "bruit"
    },
    sigmas: {
      name: "sigmas"
    }
  }
};
const AlignYourStepsScheduler$4 = {
  display_name: "PlanificateurAlignezVosÉtapes",
  inputs: {
    denoise: {
      name: "débruitage"
    },
    model_type: {
      name: "type_de_modèle"
    },
    steps: {
      name: "étapes"
    }
  }
};
const BasicGuider$4 = {
  display_name: "GuideBasique",
  inputs: {
    conditioning: {
      name: "conditionnement"
    },
    model: {
      name: "modèle"
    }
  }
};
const BasicScheduler$4 = {
  display_name: "PlanificateurBasique",
  inputs: {
    denoise: {
      name: "débruitage"
    },
    model: {
      name: "modèle"
    },
    scheduler: {
      name: "planificateur"
    },
    steps: {
      name: "étapes"
    }
  }
};
const BetaSamplingScheduler$4 = {
  display_name: "PlanificateurÉchantillonnageBeta",
  inputs: {
    alpha: {
      name: "alpha"
    },
    beta: {
      name: "beta"
    },
    model: {
      name: "modèle"
    },
    steps: {
      name: "étapes"
    }
  }
};
const CFGGuider$4 = {
  display_name: "GuideCFG",
  inputs: {
    cfg: {
      name: "cfg"
    },
    model: {
      name: "modèle"
    },
    negative: {
      name: "négative"
    },
    positive: {
      name: "positive"
    }
  }
};
const CFGZeroStar$4 = {
  display_name: "CFGZeroStar",
  inputs: {
    model: {
      name: "modèle"
    }
  },
  outputs: {
    "0": {
      name: "modèle corrigé"
    }
  }
};
const CLIPAttentionMultiply$4 = {
  display_name: "MultiplierAttentionCLIP",
  inputs: {
    clip: {
      name: "clip"
    },
    k: {
      name: "k"
    },
    out: {
      name: "sortie"
    },
    q: {
      name: "q"
    },
    v: {
      name: "v"
    }
  }
};
const CLIPLoader$4 = {
  description: "[Recettes]\n\nstable_diffusion: clip-l\nstable_cascade: clip-g\nsd3: t5 / clip-g / clip-l\nstable_audio: t5\nmochi: t5\ncosmos: old t5 xxl",
  display_name: "Charger CLIP",
  inputs: {
    clip_name: {
      name: "clip_name"
    },
    device: {
      name: "appareil"
    },
    type: {
      name: "type"
    }
  }
};
const CLIPMergeAdd$4 = {
  display_name: "CLIPMergeAdd",
  inputs: {
    clip1: {
      name: "clip1"
    },
    clip2: {
      name: "clip2"
    }
  }
};
const CLIPMergeSimple$4 = {
  display_name: "CLIPMergeSimple",
  inputs: {
    clip1: {
      name: "clip1"
    },
    clip2: {
      name: "clip2"
    },
    ratio: {
      name: "ratio"
    }
  }
};
const CLIPMergeSubtract$4 = {
  display_name: "CLIPMergeSubtract",
  inputs: {
    clip1: {
      name: "clip1"
    },
    clip2: {
      name: "clip2"
    },
    multiplier: {
      name: "multiplier"
    }
  }
};
const CLIPSave$4 = {
  display_name: "CLIPSave",
  inputs: {
    clip: {
      name: "clip"
    },
    filename_prefix: {
      name: "filename_prefix"
    }
  }
};
const CLIPSetLastLayer$4 = {
  display_name: "CLIP Définir Dernière Couche",
  inputs: {
    clip: {
      name: "clip"
    },
    stop_at_clip_layer: {
      name: "stop_at_clip_layer"
    }
  }
};
const CLIPTextEncode$4 = {
  description: "Encode une invite de texte à l'aide d'un modèle CLIP en une intégration qui peut être utilisée pour guider le modèle de diffusion vers la génération d'images spécifiques.",
  display_name: "CLIP Text Encode (Prompt)",
  inputs: {
    clip: {
      name: "clip",
      tooltip: "Le modèle CLIP utilisé pour encoder le texte."
    },
    text: {
      name: "text",
      tooltip: "Le texte à encoder."
    }
  },
  outputs: {
    "0": {
      tooltip: "Une condition contenant le texte intégré utilisé pour guider le modèle de diffusion."
    }
  }
};
const CLIPTextEncodeControlnet$4 = {
  display_name: "CLIPTextEncodeControlnet",
  inputs: {
    clip: {
      name: "clip"
    },
    conditioning: {
      name: "conditioning"
    },
    text: {
      name: "text"
    }
  }
};
const CLIPTextEncodeFlux$4 = {
  display_name: "CLIPTextEncodeFlux",
  inputs: {
    clip: {
      name: "clip"
    },
    clip_l: {
      name: "clip_l"
    },
    guidance: {
      name: "guidance"
    },
    t5xxl: {
      name: "t5xxl"
    }
  }
};
const CLIPTextEncodeHiDream$4 = {
  display_name: "CLIPTextEncodeHiDream",
  inputs: {
    clip: {
      name: "clip"
    },
    clip_g: {
      name: "clip_g"
    },
    clip_l: {
      name: "clip_l"
    },
    llama: {
      name: "llama"
    },
    t5xxl: {
      name: "t5xxl"
    }
  }
};
const CLIPTextEncodeHunyuanDiT$4 = {
  display_name: "CLIPTextEncodeHunyuanDiT",
  inputs: {
    bert: {
      name: "bert"
    },
    clip: {
      name: "clip"
    },
    mt5xl: {
      name: "mt5xl"
    }
  }
};
const CLIPTextEncodeLumina2$4 = {
  description: "Encode une invite système et une invite utilisateur à l'aide d'un modèle CLIP en une intégration qui peut être utilisée pour guider le modèle de diffusion vers la génération d'images spécifiques.",
  display_name: "CLIP Text Encode pour Lumina2",
  inputs: {
    clip: {
      name: "clip",
      tooltip: "Le modèle CLIP utilisé pour encoder le texte."
    },
    system_prompt: {
      name: "system_prompt",
      tooltip: "Lumina2 propose deux types d'invites système : Supérieur : Vous êtes un assistant conçu pour générer des images supérieures avec le degré supérieur d'alignement image-texte basé sur des invites textuelles ou des invites utilisateur. Alignement : Vous êtes un assistant conçu pour générer des images de haute qualité avec le plus haut degré d'alignement image-texte basé sur des invites textuelles."
    },
    user_prompt: {
      name: "user_prompt",
      tooltip: "Le texte à encoder."
    }
  },
  outputs: {
    "0": {
      tooltip: "Une condition contenant le texte intégré utilisé pour guider le modèle de diffusion."
    }
  }
};
const CLIPTextEncodePixArtAlpha$4 = {
  description: "Encode le texte et définit la condition de résolution pour PixArt Alpha. Ne s'applique pas à PixArt Sigma.",
  display_name: "CLIPTextEncodePixArtAlpha",
  inputs: {
    clip: {
      name: "clip"
    },
    height: {
      name: "height"
    },
    text: {
      name: "text"
    },
    width: {
      name: "width"
    }
  }
};
const CLIPTextEncodeSD3$4 = {
  display_name: "CLIPTextEncodeSD3",
  inputs: {
    clip: {
      name: "clip"
    },
    clip_g: {
      name: "clip_g"
    },
    clip_l: {
      name: "clip_l"
    },
    empty_padding: {
      name: "remplissage_vide"
    },
    t5xxl: {
      name: "t5xxl"
    }
  }
};
const CLIPTextEncodeSDXL$4 = {
  display_name: "CLIPTextEncodeSDXL",
  inputs: {
    clip: {
      name: "clip"
    },
    crop_h: {
      name: "crop_h"
    },
    crop_w: {
      name: "crop_w"
    },
    height: {
      name: "hauteur"
    },
    target_height: {
      name: "hauteur_cible"
    },
    target_width: {
      name: "largeur_cible"
    },
    text_g: {
      name: "text_g"
    },
    text_l: {
      name: "text_l"
    },
    width: {
      name: "largeur"
    }
  }
};
const CLIPTextEncodeSDXLRefiner$4 = {
  display_name: "CLIPTextEncodeSDXLRefiner",
  inputs: {
    ascore: {
      name: "ascore"
    },
    clip: {
      name: "clip"
    },
    height: {
      name: "hauteur"
    },
    text: {
      name: "texte"
    },
    width: {
      name: "largeur"
    }
  }
};
const CLIPVisionEncode$4 = {
  display_name: "CLIP Vision Encode",
  inputs: {
    clip_vision: {
      name: "clip_vision"
    },
    crop: {
      name: "crop"
    },
    image: {
      name: "image"
    }
  }
};
const CLIPVisionLoader$4 = {
  display_name: "Charger CLIP Vision",
  inputs: {
    clip_name: {
      name: "nom_clip"
    }
  }
};
const Canny$4 = {
  display_name: "Canny",
  inputs: {
    high_threshold: {
      name: "seuil_haut"
    },
    image: {
      name: "image"
    },
    low_threshold: {
      name: "seuil_bas"
    }
  }
};
const CheckpointLoader$4 = {
  display_name: "Charger Point de Contrôle Avec Config (OBSOLÈTE)",
  inputs: {
    ckpt_name: {
      name: "nom_ckpt"
    },
    config_name: {
      name: "nom_config"
    }
  }
};
const CheckpointLoaderSimple$4 = {
  description: "Charge un point de contrôle de modèle de diffusion, les modèles de diffusion sont utilisés pour débruiter les latents.",
  display_name: "Charger Point de Contrôle",
  inputs: {
    ckpt_name: {
      name: "nom_ckpt",
      tooltip: "Le nom du point de contrôle (modèle) à charger."
    }
  },
  outputs: {
    "0": {
      tooltip: "Le modèle utilisé pour débruiter les latents."
    },
    "1": {
      tooltip: "Le modèle CLIP utilisé pour encoder les invites de texte."
    },
    "2": {
      tooltip: "Le modèle VAE utilisé pour encoder et décoder les images en espace latent et vice versa."
    }
  }
};
const CheckpointSave$4 = {
  display_name: "Sauvegarder Point de Contrôle",
  inputs: {
    clip: {
      name: "clip"
    },
    filename_prefix: {
      name: "préfixe_nom_fichier"
    },
    model: {
      name: "modèle"
    },
    vae: {
      name: "vae"
    }
  }
};
const CombineHooks2$4 = {
  display_name: "Combiner Hooks [2]",
  inputs: {
    hooks_A: {
      name: "hooks_A"
    },
    hooks_B: {
      name: "hooks_B"
    }
  }
};
const CombineHooks4$4 = {
  display_name: "Combiner Hooks [4]",
  inputs: {
    hooks_A: {
      name: "hooks_A"
    },
    hooks_B: {
      name: "hooks_B"
    },
    hooks_C: {
      name: "hooks_C"
    },
    hooks_D: {
      name: "hooks_D"
    }
  }
};
const CombineHooks8$4 = {
  display_name: "Combiner Hooks [8]",
  inputs: {
    hooks_A: {
      name: "hooks_A"
    },
    hooks_B: {
      name: "hooks_B"
    },
    hooks_C: {
      name: "hooks_C"
    },
    hooks_D: {
      name: "hooks_D"
    },
    hooks_E: {
      name: "hooks_E"
    },
    hooks_F: {
      name: "hooks_F"
    },
    hooks_G: {
      name: "hooks_G"
    },
    hooks_H: {
      name: "hooks_H"
    }
  }
};
const ConditioningAverage$4 = {
  display_name: "Moyenne de Conditionnement",
  inputs: {
    conditioning_from: {
      name: "conditionnement_de"
    },
    conditioning_to: {
      name: "conditionnement_à"
    },
    conditioning_to_strength: {
      name: "force_conditionnement_à"
    }
  }
};
const ConditioningCombine$4 = {
  display_name: "Conditionnement (Combiner)",
  inputs: {
    conditioning_1: {
      name: "conditionnement_1"
    },
    conditioning_2: {
      name: "conditionnement_2"
    }
  }
};
const ConditioningConcat$4 = {
  display_name: "Conditionnement (Concat)",
  inputs: {
    conditioning_from: {
      name: "conditionnement_de"
    },
    conditioning_to: {
      name: "conditionnement_vers"
    }
  }
};
const ConditioningSetArea$4 = {
  display_name: "Conditionnement (Définir Zone)",
  inputs: {
    conditioning: {
      name: "conditionnement"
    },
    height: {
      name: "hauteur"
    },
    strength: {
      name: "force"
    },
    width: {
      name: "largeur"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const ConditioningSetAreaPercentage$4 = {
  display_name: "Conditionnement (Définir Zone avec Pourcentage)",
  inputs: {
    conditioning: {
      name: "conditionnement"
    },
    height: {
      name: "hauteur"
    },
    strength: {
      name: "force"
    },
    width: {
      name: "largeur"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const ConditioningSetAreaPercentageVideo$4 = {
  display_name: "Pourcentage de la zone de conditionnement vidéo",
  inputs: {
    conditioning: {
      name: "conditionnement"
    },
    height: {
      name: "hauteur"
    },
    strength: {
      name: "force"
    },
    temporal: {
      name: "temporel"
    },
    width: {
      name: "largeur"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    },
    z: {
      name: "z"
    }
  }
};
const ConditioningSetAreaStrength$4 = {
  display_name: "ConditionnementDéfinirForceZone",
  inputs: {
    conditioning: {
      name: "conditionnement"
    },
    strength: {
      name: "force"
    }
  }
};
const ConditioningSetDefaultCombine$4 = {
  display_name: "Cond Définir Combinaison par Défaut",
  inputs: {
    cond: {
      name: "cond"
    },
    cond_DEFAULT: {
      name: "cond_DEFAULT"
    },
    hooks: {
      name: "hooks"
    }
  }
};
const ConditioningSetMask$4 = {
  display_name: "Conditionnement (Définir Masque)",
  inputs: {
    conditioning: {
      name: "conditionnement"
    },
    mask: {
      name: "masque"
    },
    set_cond_area: {
      name: "définir_zone_cond"
    },
    strength: {
      name: "force"
    }
  }
};
const ConditioningSetProperties$4 = {
  display_name: "Cond Définir Propriétés",
  inputs: {
    cond_NEW: {
      name: "cond_NOUVEAU"
    },
    hooks: {
      name: "hooks"
    },
    mask: {
      name: "masque"
    },
    set_cond_area: {
      name: "définir_zone_cond"
    },
    strength: {
      name: "force"
    },
    timesteps: {
      name: "pas_de_temps"
    }
  }
};
const ConditioningSetPropertiesAndCombine$4 = {
  display_name: "Cond Définir Propriétés Combinaison",
  inputs: {
    cond: {
      name: "cond"
    },
    cond_NEW: {
      name: "cond_NOUVEAU"
    },
    hooks: {
      name: "hooks"
    },
    mask: {
      name: "masque"
    },
    set_cond_area: {
      name: "définir_zone_cond"
    },
    strength: {
      name: "force"
    },
    timesteps: {
      name: "pas_de_temps"
    }
  }
};
const ConditioningSetTimestepRange$4 = {
  display_name: "ConditionnementDéfinirPlagePasDeTemps",
  inputs: {
    conditioning: {
      name: "conditionnement"
    },
    end: {
      name: "fin"
    },
    start: {
      name: "début"
    }
  }
};
const ConditioningStableAudio$4 = {
  display_name: "ConditionnementStableAudio",
  inputs: {
    negative: {
      name: "négative"
    },
    positive: {
      name: "positive"
    },
    seconds_start: {
      name: "secondes_début"
    },
    seconds_total: {
      name: "secondes_total"
    }
  },
  outputs: {
    "0": {
      name: "positive"
    },
    "1": {
      name: "négative"
    }
  }
};
const ConditioningTimestepsRange$4 = {
  display_name: "Plage de pas de temps",
  inputs: {
    end_percent: {
      name: "end_percent"
    },
    start_percent: {
      name: "start_percent"
    }
  },
  outputs: {
    "1": {
      name: "AVANT_PLAGE"
    },
    "2": {
      name: "APRÈS_PLAGE"
    }
  }
};
const ConditioningZeroOut$4 = {
  display_name: "ConditioningZeroOut",
  inputs: {
    conditioning: {
      name: "conditioning"
    }
  }
};
const ControlNetApply$4 = {
  display_name: "Appliquer ControlNet (ANCIEN)",
  inputs: {
    conditioning: {
      name: "conditioning"
    },
    control_net: {
      name: "control_net"
    },
    image: {
      name: "image"
    },
    strength: {
      name: "strength"
    }
  }
};
const ControlNetApplyAdvanced$4 = {
  display_name: "Appliquer ControlNet",
  inputs: {
    control_net: {
      name: "control_net"
    },
    end_percent: {
      name: "end_percent"
    },
    image: {
      name: "image"
    },
    negative: {
      name: "negative"
    },
    positive: {
      name: "positive"
    },
    start_percent: {
      name: "start_percent"
    },
    strength: {
      name: "strength"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "positive"
    },
    "1": {
      name: "negative"
    }
  }
};
const ControlNetApplySD3$4 = {
  display_name: "Appliquer Controlnet avec VAE",
  inputs: {
    control_net: {
      name: "control_net"
    },
    end_percent: {
      name: "end_percent"
    },
    image: {
      name: "image"
    },
    negative: {
      name: "negative"
    },
    positive: {
      name: "positive"
    },
    start_percent: {
      name: "start_percent"
    },
    strength: {
      name: "strength"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "positive"
    },
    "1": {
      name: "negative"
    }
  }
};
const ControlNetInpaintingAliMamaApply$4 = {
  display_name: "ControlNetInpaintingAliMamaApply",
  inputs: {
    control_net: {
      name: "control_net"
    },
    end_percent: {
      name: "end_percent"
    },
    image: {
      name: "image"
    },
    mask: {
      name: "mask"
    },
    negative: {
      name: "negative"
    },
    positive: {
      name: "positive"
    },
    start_percent: {
      name: "start_percent"
    },
    strength: {
      name: "strength"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "positive"
    },
    "1": {
      name: "negative"
    }
  }
};
const ControlNetLoader$4 = {
  display_name: "Charger le modèle ControlNet",
  inputs: {
    control_net_name: {
      name: "control_net_name"
    }
  }
};
const CosmosImageToVideoLatent$4 = {
  display_name: "CosmosImageVersVidéoLatent",
  inputs: {
    batch_size: {
      name: "taille_du_lot"
    },
    end_image: {
      name: "image_de_fin"
    },
    height: {
      name: "hauteur"
    },
    length: {
      name: "longueur"
    },
    start_image: {
      name: "image_de_départ"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "largeur"
    }
  }
};
const CreateHookKeyframe$4 = {
  display_name: "Créer une image clé de crochet",
  inputs: {
    prev_hook_kf: {
      name: "prev_hook_kf"
    },
    start_percent: {
      name: "start_percent"
    },
    strength_mult: {
      name: "strength_mult"
    }
  },
  outputs: {
    "0": {
      name: "HOOK_KF"
    }
  }
};
const CreateHookKeyframesFromFloats$4 = {
  display_name: "Créer des images clés de crochet à partir de flottants",
  inputs: {
    end_percent: {
      name: "pourcentage_fin"
    },
    floats_strength: {
      name: "force_flottants"
    },
    prev_hook_kf: {
      name: "precedent_crochet_kf"
    },
    print_keyframes: {
      name: "imprimer_images_cles"
    },
    start_percent: {
      name: "pourcentage_debut"
    }
  },
  outputs: {
    "0": {
      name: "CROCHET_KF"
    }
  }
};
const CreateHookKeyframesInterpolated$4 = {
  display_name: "Créer des images clés de crochet interpolées.",
  inputs: {
    end_percent: {
      name: "pourcentage_fin"
    },
    interpolation: {
      name: "interpolation"
    },
    keyframes_count: {
      name: "compte_images_cles"
    },
    prev_hook_kf: {
      name: "precedent_crochet_kf"
    },
    print_keyframes: {
      name: "imprimer_images_cles"
    },
    start_percent: {
      name: "pourcentage_debut"
    },
    strength_end: {
      name: "force_fin"
    },
    strength_start: {
      name: "force_debut"
    }
  },
  outputs: {
    "0": {
      name: "CROCHET_KF"
    }
  }
};
const CreateHookLora$4 = {
  display_name: "Créer un crochet LoRA",
  inputs: {
    lora_name: {
      name: "nom_lora"
    },
    prev_hooks: {
      name: "crochets_precedents"
    },
    strength_clip: {
      name: "force_clip"
    },
    strength_model: {
      name: "force_modele"
    }
  }
};
const CreateHookLoraModelOnly$4 = {
  display_name: "Créer un crochet LoRA (MO)",
  inputs: {
    lora_name: {
      name: "nom_lora"
    },
    prev_hooks: {
      name: "crochets_precedents"
    },
    strength_model: {
      name: "force_modele"
    }
  }
};
const CreateHookModelAsLora$4 = {
  display_name: "Créer un modèle de crochet comme LoRA",
  inputs: {
    ckpt_name: {
      name: "nom_ckpt"
    },
    prev_hooks: {
      name: "crochets_precedents"
    },
    strength_clip: {
      name: "force_clip"
    },
    strength_model: {
      name: "force_modele"
    }
  }
};
const CreateHookModelAsLoraModelOnly$4 = {
  display_name: "Créer un modèle de crochet comme LoRA (MO)",
  inputs: {
    ckpt_name: {
      name: "nom_ckpt"
    },
    prev_hooks: {
      name: "crochets_precedents"
    },
    strength_model: {
      name: "force_modele"
    }
  }
};
const CreateVideo$4 = {
  description: "Créer une vidéo à partir d’images.",
  display_name: "Créer une vidéo",
  inputs: {
    audio: {
      name: "audio",
      tooltip: "L’audio à ajouter à la vidéo."
    },
    fps: {
      name: "fps"
    },
    images: {
      name: "images",
      tooltip: "Les images à utiliser pour créer une vidéo."
    }
  }
};
const CropMask$4 = {
  display_name: "CropMask",
  inputs: {
    height: {
      name: "hauteur"
    },
    mask: {
      name: "masque"
    },
    width: {
      name: "largeur"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const DiffControlNetLoader$4 = {
  display_name: "Charger le modèle ControlNet (diff)",
  inputs: {
    control_net_name: {
      name: "nom_control_net"
    },
    model: {
      name: "modèle"
    }
  }
};
const DifferentialDiffusion$4 = {
  display_name: "Diffusion différentielle",
  inputs: {
    model: {
      name: "modèle"
    }
  }
};
const DiffusersLoader$4 = {
  display_name: "Chargeur de diffuseurs",
  inputs: {
    model_path: {
      name: "chemin_modèle"
    }
  }
};
const DisableNoise$4 = {
  display_name: "DésactiverBruit"
};
const DualCFGGuider$4 = {
  display_name: "GuideurDualCFG",
  inputs: {
    cfg_cond2_negative: {
      name: "cfg_cond2_négatif"
    },
    cfg_conds: {
      name: "cfg_conds"
    },
    cond1: {
      name: "cond1"
    },
    cond2: {
      name: "cond2"
    },
    model: {
      name: "modèle"
    },
    negative: {
      name: "négatif"
    }
  }
};
const DualCLIPLoader$4 = {
  description: "[Recettes]\n\nsdxl: clip-l, clip-g\nsd3: clip-l, clip-g / clip-l, t5 / clip-g, t5\nflux: clip-l, t5",
  display_name: "ChargeurDualCLIP",
  inputs: {
    clip_name1: {
      name: "nom_clip1"
    },
    clip_name2: {
      name: "nom_clip2"
    },
    device: {
      name: "appareil"
    },
    type: {
      name: "type"
    }
  }
};
const EmptyCosmosLatentVideo$4 = {
  display_name: "VidéoLatenteCosmosVide",
  inputs: {
    batch_size: {
      name: "taille_du_lot"
    },
    height: {
      name: "hauteur"
    },
    length: {
      name: "longueur"
    },
    width: {
      name: "largeur"
    }
  }
};
const EmptyHunyuanLatentVideo$4 = {
  display_name: "EmptyHunyuanLatentVideo",
  inputs: {
    batch_size: {
      name: "taille_du_lot"
    },
    height: {
      name: "hauteur"
    },
    length: {
      name: "longueur"
    },
    width: {
      name: "largeur"
    }
  }
};
const EmptyImage$4 = {
  display_name: "ImageVide",
  inputs: {
    batch_size: {
      name: "taille_du_lot"
    },
    color: {
      name: "couleur"
    },
    height: {
      name: "hauteur"
    },
    width: {
      name: "largeur"
    }
  }
};
const EmptyLTXVLatentVideo$4 = {
  display_name: "EmptyLTXVLatentVideo",
  inputs: {
    batch_size: {
      name: "taille_du_lot"
    },
    height: {
      name: "hauteur"
    },
    length: {
      name: "longueur"
    },
    width: {
      name: "largeur"
    }
  }
};
const EmptyLatentAudio$4 = {
  display_name: "AudioLatentVide",
  inputs: {
    batch_size: {
      name: "taille_du_lot",
      tooltip: "Le nombre d'images latentes dans le lot."
    },
    seconds: {
      name: "secondes"
    }
  }
};
const EmptyLatentHunyuan3Dv2$4 = {
  display_name: "EmptyLatentHunyuan3Dv2",
  inputs: {
    batch_size: {
      name: "taille_du_lot",
      tooltip: "Le nombre d'images latentes dans le lot."
    },
    resolution: {
      name: "résolution"
    }
  }
};
const EmptyLatentImage$4 = {
  description: "Créez un nouveau lot d'images latentes vides à débruiter via l'échantillonnage.",
  display_name: "Image Latente Vide",
  inputs: {
    batch_size: {
      name: "taille_du_lot",
      tooltip: "Le nombre d'images latentes dans le lot."
    },
    height: {
      name: "hauteur",
      tooltip: "La hauteur des images latentes en pixels."
    },
    width: {
      name: "largeur",
      tooltip: "La largeur des images latentes en pixels."
    }
  },
  outputs: {
    "0": {
      tooltip: "Le lot d'images latentes vides."
    }
  }
};
const EmptyMochiLatentVideo$4 = {
  display_name: "EmptyMochiLatentVideo",
  inputs: {
    batch_size: {
      name: "taille_du_lot"
    },
    height: {
      name: "hauteur"
    },
    length: {
      name: "longueur"
    },
    width: {
      name: "largeur"
    }
  }
};
const EmptySD3LatentImage$4 = {
  display_name: "EmptySD3LatentImage",
  inputs: {
    batch_size: {
      name: "taille_du_lot"
    },
    height: {
      name: "hauteur"
    },
    width: {
      name: "largeur"
    }
  }
};
const ExponentialScheduler$4 = {
  display_name: "PlanificateurExponentiel",
  inputs: {
    sigma_max: {
      name: "sigma_max"
    },
    sigma_min: {
      name: "sigma_min"
    },
    steps: {
      name: "étapes"
    }
  }
};
const ExtendIntermediateSigmas$4 = {
  display_name: "ExtendIntermediateSigmas",
  inputs: {
    end_at_sigma: {
      name: "finir_à_sigma"
    },
    sigmas: {
      name: "sigmas"
    },
    spacing: {
      name: "espacement"
    },
    start_at_sigma: {
      name: "commencer_à_sigma"
    },
    steps: {
      name: "étapes"
    }
  }
};
const FeatherMask$4 = {
  display_name: "MasquePlume",
  inputs: {
    bottom: {
      name: "bas"
    },
    left: {
      name: "gauche"
    },
    mask: {
      name: "masque"
    },
    right: {
      name: "droite"
    },
    top: {
      name: "haut"
    }
  }
};
const FlipSigmas$4 = {
  display_name: "InverserSigmas",
  inputs: {
    sigmas: {
      name: "sigmas"
    }
  }
};
const FluxDisableGuidance$4 = {
  description: "Ce nœud désactive complètement l'intégration de guidage sur les modèles Flux et similaires à Flux",
  display_name: "FluxDisableGuidance",
  inputs: {
    conditioning: {
      name: "conditionnement"
    }
  }
};
const FluxGuidance$4 = {
  display_name: "GuidageFlux",
  inputs: {
    conditioning: {
      name: "conditionnement"
    },
    guidance: {
      name: "guidage"
    }
  }
};
const FluxProCannyNode$4 = {
  description: "Générer une image en utilisant une image de contrôle (canny).",
  display_name: "Flux.1 Image de Contrôle Canny",
  inputs: {
    canny_high_threshold: {
      name: "canny_high_threshold",
      tooltip: "Seuil haut pour la détection de contours Canny ; ignoré si skip_processing est à True"
    },
    canny_low_threshold: {
      name: "canny_low_threshold",
      tooltip: "Seuil bas pour la détection de contours Canny ; ignoré si skip_processing est à True"
    },
    control_after_generate: {
      name: "control after generate"
    },
    control_image: {
      name: "control_image"
    },
    guidance: {
      name: "guidance",
      tooltip: "Intensité de la guidance pour le processus de génération d'image"
    },
    prompt: {
      name: "prompt",
      tooltip: "Invite pour la génération d'image"
    },
    prompt_upsampling: {
      name: "prompt_upsampling",
      tooltip: "Indique s'il faut effectuer un suréchantillonnage sur l'invite. Si activé, modifie automatiquement l'invite pour une génération plus créative, mais les résultats sont non déterministes (la même graine ne produira pas exactement le même résultat)."
    },
    seed: {
      name: "seed",
      tooltip: "La graine aléatoire utilisée pour créer le bruit."
    },
    skip_preprocessing: {
      name: "skip_preprocessing",
      tooltip: "Indique s'il faut ignorer le prétraitement ; mettre à True si control_image est déjà canny-fiée, à False si c'est une image brute."
    },
    steps: {
      name: "steps",
      tooltip: "Nombre d'étapes pour le processus de génération d'image"
    }
  }
};
const FluxProDepthNode$4 = {
  description: "Générer une image en utilisant une image de contrôle (profondeur).",
  display_name: "Flux.1 Contrôle de Profondeur Image",
  inputs: {
    control_after_generate: {
      name: "control after generate"
    },
    control_image: {
      name: "control_image"
    },
    guidance: {
      name: "guidance",
      tooltip: "Intensité de la guidance pour le processus de génération d'image"
    },
    prompt: {
      name: "prompt",
      tooltip: "Invite pour la génération d'image"
    },
    prompt_upsampling: {
      name: "prompt_upsampling",
      tooltip: "Indique s'il faut effectuer un suréchantillonnage sur l'invite. Si activé, modifie automatiquement l'invite pour une génération plus créative, mais les résultats sont non déterministes (la même graine ne produira pas exactement le même résultat)."
    },
    seed: {
      name: "seed",
      tooltip: "La graine aléatoire utilisée pour créer le bruit."
    },
    skip_preprocessing: {
      name: "skip_preprocessing",
      tooltip: "Indique s'il faut ignorer le prétraitement ; mettez sur True si control_image est déjà en profondeur, False si c'est une image brute."
    },
    steps: {
      name: "steps",
      tooltip: "Nombre d'étapes pour le processus de génération d'image"
    }
  }
};
const FluxProExpandNode$4 = {
  description: "Étend l’image selon le prompt.",
  display_name: "Flux.1 Élargir l’image",
  inputs: {
    bottom: {
      name: "bas",
      tooltip: "Nombre de pixels à ajouter en bas de l’image"
    },
    control_after_generate: {
      name: "contrôle après génération"
    },
    guidance: {
      name: "guidage",
      tooltip: "Intensité du guidage pour le processus de génération d’image"
    },
    image: {
      name: "image"
    },
    left: {
      name: "gauche",
      tooltip: "Nombre de pixels à ajouter à gauche de l’image"
    },
    prompt: {
      name: "prompt",
      tooltip: "Prompt pour la génération d’image"
    },
    prompt_upsampling: {
      name: "suréchantillonnage du prompt",
      tooltip: "Indique s’il faut effectuer un suréchantillonnage sur le prompt. Si activé, modifie automatiquement le prompt pour une génération plus créative, mais les résultats sont non déterministes (la même graine ne produira pas exactement le même résultat)."
    },
    right: {
      name: "droite",
      tooltip: "Nombre de pixels à ajouter à droite de l’image"
    },
    seed: {
      name: "graine",
      tooltip: "La graine aléatoire utilisée pour créer le bruit."
    },
    steps: {
      name: "étapes",
      tooltip: "Nombre d’étapes pour le processus de génération d’image"
    },
    top: {
      name: "haut",
      tooltip: "Nombre de pixels à ajouter en haut de l’image"
    }
  }
};
const FluxProFillNode$4 = {
  description: "Reconstitue l'image en fonction du mask et du prompt.",
  display_name: "Flux.1 Remplir l'image",
  inputs: {
    control_after_generate: {
      name: "contrôle après génération"
    },
    guidance: {
      name: "guidage",
      tooltip: "Intensité du guidage pour le processus de génération d'image"
    },
    image: {
      name: "image"
    },
    mask: {
      name: "mask"
    },
    prompt: {
      name: "prompt",
      tooltip: "Prompt pour la génération d'image"
    },
    prompt_upsampling: {
      name: "suréchantillonnage du prompt",
      tooltip: "Indique s'il faut effectuer un suréchantillonnage du prompt. Si activé, modifie automatiquement le prompt pour une génération plus créative, mais les résultats sont non déterministes (la même seed ne produira pas exactement le même résultat)."
    },
    seed: {
      name: "seed",
      tooltip: "La seed aléatoire utilisée pour créer le bruit."
    },
    steps: {
      name: "étapes",
      tooltip: "Nombre d'étapes pour le processus de génération d'image"
    }
  }
};
const FluxProUltraImageNode$4 = {
  description: "Génère des images avec Flux Pro 1.1 Ultra via l'API à partir d'un prompt et d'une résolution.",
  display_name: "Flux 1.1 [pro] Ultra Image",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio",
      tooltip: "Rapport d'aspect de l'image ; doit être compris entre 1:4 et 4:1."
    },
    control_after_generate: {
      name: "control after generate"
    },
    image_prompt: {
      name: "image_prompt"
    },
    image_prompt_strength: {
      name: "image_prompt_strength",
      tooltip: "Mélange entre le prompt et le prompt image."
    },
    prompt: {
      name: "prompt",
      tooltip: "Prompt pour la génération d'image"
    },
    prompt_upsampling: {
      name: "prompt_upsampling",
      tooltip: "Indique s'il faut effectuer un upsampling sur le prompt. Si activé, modifie automatiquement le prompt pour une génération plus créative, mais les résultats sont non déterministes (la même graine ne produira pas exactement le même résultat)."
    },
    raw: {
      name: "raw",
      tooltip: "Si vrai, génère des images moins traitées et d'apparence plus naturelle."
    },
    seed: {
      name: "seed",
      tooltip: "La graine aléatoire utilisée pour créer le bruit."
    }
  }
};
const FreSca$4 = {
  description: "Applique une mise à l'échelle dépendante de la fréquence au guidage",
  display_name: "FreSca",
  inputs: {
    freq_cutoff: {
      name: "seuil_fréquence",
      tooltip: "Nombre d'indices de fréquence autour du centre à considérer comme basses fréquences"
    },
    model: {
      name: "modèle"
    },
    scale_high: {
      name: "échelle_haute",
      tooltip: "Facteur d'échelle pour les composantes hautes fréquences"
    },
    scale_low: {
      name: "échelle_basse",
      tooltip: "Facteur d'échelle pour les composantes basses fréquences"
    }
  }
};
const FreeU$4 = {
  display_name: "FreeU",
  inputs: {
    b1: {
      name: "b1"
    },
    b2: {
      name: "b2"
    },
    model: {
      name: "modèle"
    },
    s1: {
      name: "s1"
    },
    s2: {
      name: "s2"
    }
  }
};
const FreeU_V2$4 = {
  display_name: "FreeU_V2",
  inputs: {
    b1: {
      name: "b1"
    },
    b2: {
      name: "b2"
    },
    model: {
      name: "modèle"
    },
    s1: {
      name: "s1"
    },
    s2: {
      name: "s2"
    }
  }
};
const GITSScheduler$4 = {
  display_name: "GITSScheduler",
  inputs: {
    coeff: {
      name: "coeff"
    },
    denoise: {
      name: "débruitage"
    },
    steps: {
      name: "étapes"
    }
  }
};
const GLIGENLoader$4 = {
  display_name: "GLIGENLoader",
  inputs: {
    gligen_name: {
      name: "nom_gligen"
    }
  }
};
const GLIGENTextBoxApply$4 = {
  display_name: "GLIGENTextBoxApply",
  inputs: {
    clip: {
      name: "clip"
    },
    conditioning_to: {
      name: "conditionnement_à"
    },
    gligen_textbox_model: {
      name: "modèle_boîte_texte_gligen"
    },
    height: {
      name: "hauteur"
    },
    text: {
      name: "texte"
    },
    width: {
      name: "largeur"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const GetVideoComponents$4 = {
  description: "Extrait tous les composants d'une vidéo : images, audio et fréquence d’images.",
  display_name: "Obtenir les composants vidéo",
  inputs: {
    video: {
      name: "vidéo",
      tooltip: "La vidéo dont extraire les composants."
    }
  },
  outputs: {
    "0": {
      name: "images"
    },
    "1": {
      name: "audio"
    },
    "2": {
      name: "ips"
    }
  }
};
const GrowMask$4 = {
  display_name: "GrowMask",
  inputs: {
    expand: {
      name: "agrandir"
    },
    mask: {
      name: "masque"
    },
    tapered_corners: {
      name: "coins_évasés"
    }
  }
};
const Hunyuan3Dv2Conditioning$4 = {
  display_name: "Hunyuan3Dv2Conditioning",
  inputs: {
    clip_vision_output: {
      name: "sortie_vision_clip"
    }
  },
  outputs: {
    "0": {
      name: "positif"
    },
    "1": {
      name: "négatif"
    }
  }
};
const Hunyuan3Dv2ConditioningMultiView$4 = {
  display_name: "Hunyuan3Dv2ConditioningMultiView",
  inputs: {
    back: {
      name: "arrière"
    },
    front: {
      name: "avant"
    },
    left: {
      name: "gauche"
    },
    right: {
      name: "droite"
    }
  },
  outputs: {
    "0": {
      name: "positif"
    },
    "1": {
      name: "négatif"
    }
  }
};
const HunyuanImageToVideo$4 = {
  display_name: "HunyuanImageToVideo",
  inputs: {
    batch_size: {
      name: "taille_du_lot"
    },
    guidance_type: {
      name: "type_de_guidage"
    },
    height: {
      name: "hauteur"
    },
    length: {
      name: "longueur"
    },
    positive: {
      name: "positive"
    },
    start_image: {
      name: "image_de_départ"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "largeur"
    }
  },
  outputs: {
    "0": {
      name: "positive"
    },
    "1": {
      name: "latent"
    }
  }
};
const HyperTile$4 = {
  display_name: "HyperTile",
  inputs: {
    max_depth: {
      name: "profondeur_max"
    },
    model: {
      name: "modèle"
    },
    scale_depth: {
      name: "échelle_profondeur"
    },
    swap_size: {
      name: "taille_échange"
    },
    tile_size: {
      name: "taille_tuile"
    }
  }
};
const HypernetworkLoader$4 = {
  display_name: "HypernetworkLoader",
  inputs: {
    hypernetwork_name: {
      name: "nom_hypernetwork"
    },
    model: {
      name: "modèle"
    },
    strength: {
      name: "force"
    }
  }
};
const IdeogramV1$4 = {
  description: "Génère des images de manière synchrone en utilisant le modèle Ideogram V1.\n\nLes liens des images sont disponibles pour une durée limitée ; si vous souhaitez conserver l'image, vous devez la télécharger.",
  display_name: "Ideogram V1",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio",
      tooltip: "Le format d'image pour la génération."
    },
    control_after_generate: {
      name: "control after generate"
    },
    magic_prompt_option: {
      name: "magic_prompt_option",
      tooltip: "Déterminer si MagicPrompt doit être utilisé lors de la génération"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Description de ce qu'il faut exclure de l'image"
    },
    num_images: {
      name: "num_images"
    },
    prompt: {
      name: "prompt",
      tooltip: "Invite pour la génération d'image"
    },
    seed: {
      name: "seed"
    },
    turbo: {
      name: "turbo",
      tooltip: "Activer le mode turbo (génération plus rapide, qualité potentiellement inférieure)"
    }
  }
};
const IdeogramV2$4 = {
  description: "Génère des images de manière synchrone en utilisant le modèle Ideogram V2.\n\nLes liens vers les images sont disponibles pour une durée limitée ; si vous souhaitez conserver l'image, vous devez la télécharger.",
  display_name: "Ideogram V2",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio",
      tooltip: "Le format d'image pour la génération. Ignoré si la résolution n'est pas définie sur AUTO."
    },
    control_after_generate: {
      name: "control after generate"
    },
    magic_prompt_option: {
      name: "magic_prompt_option",
      tooltip: "Déterminer si MagicPrompt doit être utilisé lors de la génération"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Description de ce qu'il faut exclure de l'image"
    },
    num_images: {
      name: "num_images"
    },
    prompt: {
      name: "prompt",
      tooltip: "Invite pour la génération d'image"
    },
    resolution: {
      name: "resolution",
      tooltip: "La résolution pour la génération d'image. Si elle n'est pas définie sur AUTO, cela remplace le paramètre aspect_ratio."
    },
    seed: {
      name: "seed"
    },
    style_type: {
      name: "style_type",
      tooltip: "Type de style pour la génération (V2 uniquement)"
    },
    turbo: {
      name: "turbo",
      tooltip: "Activer le mode turbo (génération plus rapide, qualité potentiellement inférieure)"
    }
  }
};
const IdeogramV3$4 = {
  description: "Génère des images de façon synchrone avec le modèle Ideogram V3.\n\nPrend en charge la génération d’images à partir de prompts textuels ainsi que l’édition d’images avec mask.\nLes liens des images sont disponibles pour une durée limitée ; si vous souhaitez conserver l’image, vous devez la télécharger.",
  display_name: "Ideogram V3",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio",
      tooltip: "Le ratio d’aspect pour la génération d’image. Ignoré si la résolution n’est pas réglée sur Auto."
    },
    control_after_generate: {
      name: "control after generate"
    },
    image: {
      name: "image",
      tooltip: "Image de référence optionnelle pour l’édition d’image."
    },
    magic_prompt_option: {
      name: "magic_prompt_option",
      tooltip: "Détermine si MagicPrompt doit être utilisé lors de la génération"
    },
    mask: {
      name: "mask",
      tooltip: "Mask optionnel pour l’inpainting (les zones blanches seront remplacées)"
    },
    num_images: {
      name: "num_images"
    },
    prompt: {
      name: "prompt",
      tooltip: "Prompt pour la génération ou l’édition d’image"
    },
    rendering_speed: {
      name: "rendering_speed",
      tooltip: "Contrôle le compromis entre la vitesse de génération et la qualité"
    },
    resolution: {
      name: "resolution",
      tooltip: "La résolution pour la génération d’image. Si elle n’est pas réglée sur Auto, cela remplace le paramètre aspect_ratio."
    },
    seed: {
      name: "seed"
    }
  }
};
const ImageBatch$4 = {
  display_name: "Images en lot",
  inputs: {
    image1: {
      name: "image1"
    },
    image2: {
      name: "image2"
    }
  }
};
const ImageBlend$4 = {
  display_name: "Mélange d'images",
  inputs: {
    blend_factor: {
      name: "facteur_mélange"
    },
    blend_mode: {
      name: "mode_mélange"
    },
    image1: {
      name: "image1"
    },
    image2: {
      name: "image2"
    }
  }
};
const ImageBlur$4 = {
  display_name: "Flou d'image",
  inputs: {
    blur_radius: {
      name: "rayon_flou"
    },
    image: {
      name: "image"
    },
    sigma: {
      name: "sigma"
    }
  }
};
const ImageColorToMask$4 = {
  display_name: "ImageCouleurEnMasque",
  inputs: {
    color: {
      name: "couleur"
    },
    image: {
      name: "image"
    }
  }
};
const ImageCompositeMasked$4 = {
  display_name: "ImageCompositeMasked",
  inputs: {
    destination: {
      name: "destination"
    },
    mask: {
      name: "masque"
    },
    resize_source: {
      name: "redimensionner_source"
    },
    source: {
      name: "source"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const ImageCrop$4 = {
  display_name: "Rogner l'image",
  inputs: {
    height: {
      name: "hauteur"
    },
    image: {
      name: "image"
    },
    width: {
      name: "largeur"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const ImageFromBatch$4 = {
  display_name: "ImageDeBatch",
  inputs: {
    batch_index: {
      name: "index_de_lot"
    },
    image: {
      name: "image"
    },
    length: {
      name: "longueur"
    }
  }
};
const ImageInvert$4 = {
  display_name: "Inverser l'image",
  inputs: {
    image: {
      name: "image"
    }
  }
};
const ImageOnlyCheckpointLoader$4 = {
  display_name: "Chargeur de points de contrôle uniquement pour image (modèle img2vid)",
  inputs: {
    ckpt_name: {
      name: "nom_ckpt"
    }
  }
};
const ImageOnlyCheckpointSave$4 = {
  display_name: "ImageOnlyCheckpointSave",
  inputs: {
    clip_vision: {
      name: "clip_vision"
    },
    filename_prefix: {
      name: "préfixe_de_nom_de_fichier"
    },
    model: {
      name: "modèle"
    },
    vae: {
      name: "vae"
    }
  }
};
const ImagePadForOutpaint$4 = {
  display_name: "Rembourrage d'image pour la peinture extérieure",
  inputs: {
    bottom: {
      name: "bas"
    },
    feathering: {
      name: "adoucissement"
    },
    image: {
      name: "image"
    },
    left: {
      name: "gauche"
    },
    right: {
      name: "droite"
    },
    top: {
      name: "haut"
    }
  }
};
const ImageQuantize$4 = {
  display_name: "Quantification d'image",
  inputs: {
    colors: {
      name: "couleurs"
    },
    dither: {
      name: "dither"
    },
    image: {
      name: "image"
    }
  }
};
const ImageRGBToYUV$4 = {
  display_name: "ImageRGBToYUV",
  inputs: {
    image: {
      name: "image"
    }
  },
  outputs: {
    "0": {
      name: "Y"
    },
    "1": {
      name: "U"
    },
    "2": {
      name: "V"
    }
  }
};
const ImageScale$4 = {
  display_name: "Agrandir l'image",
  inputs: {
    crop: {
      name: "crop"
    },
    height: {
      name: "hauteur"
    },
    image: {
      name: "image"
    },
    upscale_method: {
      name: "méthode_d'agrandissement"
    },
    width: {
      name: "largeur"
    }
  }
};
const ImageScaleBy$4 = {
  display_name: "Agrandir l'image par",
  inputs: {
    image: {
      name: "image"
    },
    scale_by: {
      name: "agrandir_par"
    },
    upscale_method: {
      name: "méthode_d'agrandissement"
    }
  }
};
const ImageScaleToTotalPixels$4 = {
  display_name: "Redimensionner l'image en fonction du nombre total de pixels",
  inputs: {
    image: {
      name: "image"
    },
    megapixels: {
      name: "mégapixels"
    },
    upscale_method: {
      name: "méthode_d'agrandissement"
    }
  }
};
const ImageSharpen$4 = {
  display_name: "Affiner l'image",
  inputs: {
    alpha: {
      name: "alpha"
    },
    image: {
      name: "image"
    },
    sharpen_radius: {
      name: "rayon_d'affûtage"
    },
    sigma: {
      name: "sigma"
    }
  }
};
const ImageToMask$4 = {
  display_name: "Convertir Image en Masque",
  inputs: {
    channel: {
      name: "canal"
    },
    image: {
      name: "image"
    }
  }
};
const ImageUpscaleWithModel$4 = {
  display_name: "Agrandir l'Image (à l'aide du Modèle)",
  inputs: {
    image: {
      name: "image"
    },
    upscale_model: {
      name: "modèle_d'agrandissement"
    }
  }
};
const ImageYUVToRGB$4 = {
  display_name: "ImageYUVToRGB",
  inputs: {
    U: {
      name: "U"
    },
    V: {
      name: "V"
    },
    Y: {
      name: "Y"
    }
  }
};
const InpaintModelConditioning$4 = {
  display_name: "InpaintModelConditioning",
  inputs: {
    mask: {
      name: "masque"
    },
    negative: {
      name: "négatif"
    },
    noise_mask: {
      name: "masque_de_bruit",
      tooltip: "Ajoutez un masque de bruit au latent pour que l'échantillonnage ne se produise que dans le masque. Peut améliorer les résultats ou complètement les détruire en fonction du modèle."
    },
    pixels: {
      name: "pixels"
    },
    positive: {
      name: "positive"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "positive"
    },
    "1": {
      name: "négatif"
    },
    "2": {
      name: "latent"
    }
  }
};
const InstructPixToPixConditioning$4 = {
  display_name: "InstructPixToPixConditioning",
  inputs: {
    negative: {
      name: "négatif"
    },
    pixels: {
      name: "pixels"
    },
    positive: {
      name: "positive"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "positive"
    },
    "1": {
      name: "négatif"
    },
    "2": {
      name: "latent"
    }
  }
};
const InvertMask$4 = {
  display_name: "InverserMasque",
  inputs: {
    mask: {
      name: "masque"
    }
  }
};
const JoinImageWithAlpha$4 = {
  display_name: "Joindre Image avec Alpha",
  inputs: {
    alpha: {
      name: "alpha"
    },
    image: {
      name: "image"
    }
  }
};
const KSampler$4 = {
  description: "Utilise le modèle fourni, le conditionnement positif et négatif pour débruiter l'image latente.",
  display_name: "KSampler",
  inputs: {
    cfg: {
      name: "cfg",
      tooltip: "L'échelle de guidage sans classificateur équilibre la créativité et l'adhérence à l'invite. Des valeurs plus élevées donnent des images correspondant plus étroitement à l'invite, cependant des valeurs trop élevées auront un impact négatif sur la qualité."
    },
    control_after_generate: {
      name: "contrôle après génération"
    },
    denoise: {
      name: "denoise",
      tooltip: "La quantité de débruitage appliquée, des valeurs plus faibles maintiendront la structure de l'image initiale permettant un échantillonnage d'image à image."
    },
    latent_image: {
      name: "latent_image",
      tooltip: "L'image latente à débruiter."
    },
    model: {
      name: "model",
      tooltip: "Le modèle utilisé pour débruiter l'entrée latente."
    },
    negative: {
      name: "negative",
      tooltip: "Le conditionnement décrivant les attributs que vous voulez exclure de l'image."
    },
    positive: {
      name: "positive",
      tooltip: "Le conditionnement décrivant les attributs que vous voulez inclure dans l'image."
    },
    sampler_name: {
      name: "sampler_name",
      tooltip: "L'algorithme utilisé lors de l'échantillonnage, cela peut affecter la qualité, la vitesse et le style de la sortie générée."
    },
    scheduler: {
      name: "scheduler",
      tooltip: "Le planificateur contrôle comment le bruit est progressivement éliminé pour former l'image."
    },
    seed: {
      name: "seed",
      tooltip: "La graine aléatoire utilisée pour créer le bruit."
    },
    steps: {
      name: "steps",
      tooltip: "Le nombre d'étapes utilisées dans le processus de débruitage."
    }
  },
  outputs: {
    "0": {
      tooltip: "Le latent débruité."
    }
  }
};
const KSamplerAdvanced$4 = {
  display_name: "KSampler (Avancé)",
  inputs: {
    add_noise: {
      name: "add_noise"
    },
    cfg: {
      name: "cfg"
    },
    control_after_generate: {
      name: "contrôle après génération"
    },
    end_at_step: {
      name: "end_at_step"
    },
    latent_image: {
      name: "latent_image"
    },
    model: {
      name: "model"
    },
    negative: {
      name: "negative"
    },
    noise_seed: {
      name: "noise_seed"
    },
    positive: {
      name: "positive"
    },
    return_with_leftover_noise: {
      name: "return_with_leftover_noise"
    },
    sampler_name: {
      name: "sampler_name"
    },
    scheduler: {
      name: "scheduler"
    },
    start_at_step: {
      name: "start_at_step"
    },
    steps: {
      name: "steps"
    }
  }
};
const KSamplerSelect$4 = {
  display_name: "KSamplerSelect",
  inputs: {
    sampler_name: {
      name: "sampler_name"
    }
  }
};
const KarrasScheduler$4 = {
  display_name: "PlanificateurKarras",
  inputs: {
    rho: {
      name: "rho"
    },
    sigma_max: {
      name: "sigma_max"
    },
    sigma_min: {
      name: "sigma_min"
    },
    steps: {
      name: "étapes"
    }
  }
};
const KlingCameraControlI2VNode$4 = {
  description: "Transformez des images fixes en vidéos cinématographiques avec des mouvements de caméra professionnels qui simulent la cinématographie réelle. Contrôlez les actions de la caméra virtuelle, y compris le zoom, la rotation, le panoramique, l'inclinaison et la vue à la première personne, tout en maintenant la mise au point sur votre image d'origine.",
  display_name: "Kling Image to Video (Contrôle de la caméra)",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio"
    },
    camera_control: {
      name: "camera_control",
      tooltip: "Peut être créé à l'aide du nœud Kling Camera Controls. Contrôle le mouvement et l'animation de la caméra pendant la génération de la vidéo."
    },
    cfg_scale: {
      name: "cfg_scale"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Invite textuelle négative"
    },
    prompt: {
      name: "prompt",
      tooltip: "Invite textuelle positive"
    },
    start_frame: {
      name: "start_frame",
      tooltip: "Image de référence - URL ou chaîne encodée en Base64, ne peut pas dépasser 10 Mo, résolution d'au moins 300*300px, ratio d'aspect entre 1:2,5 et 2,5:1. Le Base64 ne doit pas inclure le préfixe data:image."
    }
  },
  outputs: {
    "1": {
      name: "video_id"
    },
    "2": {
      name: "duration"
    }
  }
};
const KlingCameraControlT2VNode$4 = {
  description: "Transformez du texte en vidéos cinématographiques avec des mouvements de caméra professionnels qui simulent la cinématographie réelle. Contrôlez les actions de la caméra virtuelle, y compris le zoom, la rotation, le panoramique, l’inclinaison et la vue à la première personne, tout en gardant le focus sur votre texte d’origine.",
  display_name: "Kling Texte vers Vidéo (Contrôle de Caméra)",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio"
    },
    camera_control: {
      name: "camera_control",
      tooltip: "Peut être créé à l’aide du nœud Kling Camera Controls. Contrôle le mouvement et l’animation de la caméra pendant la génération de la vidéo."
    },
    cfg_scale: {
      name: "cfg_scale"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Invite de texte négative"
    },
    prompt: {
      name: "prompt",
      tooltip: "Invite de texte positive"
    }
  },
  outputs: {
    "1": {
      name: "video_id"
    },
    "2": {
      name: "duration"
    }
  }
};
const KlingCameraControls$4 = {
  description: "Permet de spécifier les options de configuration pour les contrôles de la caméra Kling et les effets de contrôle du mouvement.",
  display_name: "Contrôles de la caméra Kling",
  inputs: {
    camera_control_type: {
      name: "camera_control_type"
    },
    horizontal_movement: {
      name: "horizontal_movement",
      tooltip: "Contrôle le mouvement de la caméra sur l’axe horizontal (axe x). Négatif indique la gauche, positif indique la droite."
    },
    pan: {
      name: "pan",
      tooltip: "Contrôle la rotation de la caméra dans le plan vertical (axe x). Négatif indique une rotation vers le bas, positif indique une rotation vers le haut."
    },
    roll: {
      name: "roll",
      tooltip: "Contrôle la quantité de roulis de la caméra (axe z). Négatif indique un mouvement antihoraire, positif indique un mouvement horaire."
    },
    tilt: {
      name: "tilt",
      tooltip: "Contrôle la rotation de la caméra dans le plan horizontal (axe y). Négatif indique une rotation vers la gauche, positif indique une rotation vers la droite."
    },
    vertical_movement: {
      name: "vertical_movement",
      tooltip: "Contrôle le mouvement de la caméra sur l’axe vertical (axe y). Négatif indique vers le bas, positif indique vers le haut."
    },
    zoom: {
      name: "zoom",
      tooltip: "Contrôle le changement de la longueur focale de la caméra. Négatif indique un champ de vision plus étroit, positif indique un champ de vision plus large."
    }
  },
  outputs: {
    "0": {
      name: "camera_control"
    }
  }
};
const KlingDualCharacterVideoEffectNode$4 = {
  description: "Obtenez différents effets spéciaux lors de la génération d'une vidéo en fonction de l'effect_scene. La première image sera positionnée à gauche, la seconde à droite du composite.",
  display_name: "Effets vidéo à deux personnages Kling",
  inputs: {
    duration: {
      name: "duration"
    },
    effect_scene: {
      name: "effect_scene"
    },
    image_left: {
      name: "image_left",
      tooltip: "Image côté gauche"
    },
    image_right: {
      name: "image_right",
      tooltip: "Image côté droit"
    },
    mode: {
      name: "mode"
    },
    model_name: {
      name: "model_name"
    }
  },
  outputs: {
    "1": {
      name: "duration"
    }
  }
};
const KlingImage2VideoNode$4 = {
  description: "Nœud Kling Image to Video",
  display_name: "Kling Image to Video",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio"
    },
    cfg_scale: {
      name: "cfg_scale"
    },
    duration: {
      name: "duration"
    },
    mode: {
      name: "mode"
    },
    model_name: {
      name: "model_name"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Invite textuelle négative"
    },
    prompt: {
      name: "prompt",
      tooltip: "Invite textuelle positive"
    },
    start_frame: {
      name: "start_frame",
      tooltip: "Image de référence - URL ou chaîne encodée en Base64, ne doit pas dépasser 10 Mo, résolution d'au moins 300*300px, ratio d'aspect entre 1:2,5 et 2,5:1. Le Base64 ne doit pas inclure le préfixe data:image."
    }
  },
  outputs: {
    "1": {
      name: "video_id"
    },
    "2": {
      name: "duration"
    }
  }
};
const KlingImageGenerationNode$4 = {
  description: "Nœud de génération d'image Kling. Générez une image à partir d'une invite textuelle avec une image de référence optionnelle.",
  display_name: "Génération d'image Kling",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio"
    },
    human_fidelity: {
      name: "human_fidelity",
      tooltip: "Similarité de référence du sujet"
    },
    image: {
      name: "image"
    },
    image_fidelity: {
      name: "image_fidelity",
      tooltip: "Intensité de référence pour les images téléchargées par l'utilisateur"
    },
    image_type: {
      name: "image_type"
    },
    model_name: {
      name: "model_name"
    },
    n: {
      name: "n",
      tooltip: "Nombre d'images générées"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Invite textuelle négative"
    },
    prompt: {
      name: "prompt",
      tooltip: "Invite textuelle positive"
    }
  }
};
const KlingLipSyncAudioToVideoNode$4 = {
  description: "Nœud de synchronisation labiale Kling. Synchronise les mouvements de la bouche dans un fichier vidéo avec le contenu audio d’un fichier audio.",
  display_name: "Synchronisation labiale Kling : Vidéo avec audio",
  inputs: {
    audio: {
      name: "audio"
    },
    video: {
      name: "vidéo"
    },
    voice_language: {
      name: "langue de la voix"
    }
  },
  outputs: {
    "1": {
      name: "id_vidéo"
    },
    "2": {
      name: "durée"
    }
  }
};
const KlingLipSyncTextToVideoNode$4 = {
  description: "Nœud Kling de synchronisation labiale texte vers vidéo. Synchronise les mouvements de la bouche dans un fichier vidéo avec une invite textuelle.",
  display_name: "Synchronisation labiale Kling vidéo avec texte",
  inputs: {
    text: {
      name: "texte",
      tooltip: "Contenu textuel pour la génération de vidéo synchronisée labiale. Requis lorsque le mode est text2video. Longueur maximale : 120 caractères."
    },
    video: {
      name: "vidéo"
    },
    voice: {
      name: "voix"
    },
    voice_speed: {
      name: "vitesse de la voix",
      tooltip: "Vitesse de la parole. Plage valide : 0,8~2,0, avec une précision d’un chiffre après la virgule."
    }
  },
  outputs: {
    "1": {
      name: "id_vidéo"
    },
    "2": {
      name: "durée"
    }
  }
};
const KlingSingleImageVideoEffectNode$4 = {
  description: "Obtenez différents effets spéciaux lors de la génération d'une vidéo selon le effect_scene.",
  display_name: "Effets vidéo Kling",
  inputs: {
    duration: {
      name: "durée"
    },
    effect_scene: {
      name: "effect_scene"
    },
    image: {
      name: "image",
      tooltip: "Image de référence. URL ou chaîne encodée en Base64 (sans le préfixe data:image). La taille du fichier ne doit pas dépasser 10 Mo, la résolution ne doit pas être inférieure à 300*300px, le ratio d'aspect doit être compris entre 1:2,5 et 2,5:1"
    },
    model_name: {
      name: "model_name"
    }
  },
  outputs: {
    "1": {
      name: "video_id"
    },
    "2": {
      name: "durée"
    }
  }
};
const KlingStartEndFrameNode$4 = {
  description: "Générez une séquence vidéo qui effectue une transition entre les images de début et de fin que vous fournissez. Le nœud crée tous les cadres intermédiaires, produisant une transformation fluide du premier au dernier cadre.",
  display_name: "Kling Début-Fin Image vers Vidéo",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio"
    },
    cfg_scale: {
      name: "cfg_scale"
    },
    end_frame: {
      name: "end_frame",
      tooltip: "Image de référence - Contrôle de l'image de fin. URL ou chaîne encodée en Base64, ne doit pas dépasser 10 Mo, résolution d'au moins 300*300px. La Base64 ne doit pas inclure le préfixe data:image."
    },
    mode: {
      name: "mode",
      tooltip: "La configuration à utiliser pour la génération vidéo selon le format : mode / durée / nom_du_modèle."
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Invite textuelle négative"
    },
    prompt: {
      name: "prompt",
      tooltip: "Invite textuelle positive"
    },
    start_frame: {
      name: "start_frame",
      tooltip: "Image de référence - URL ou chaîne encodée en Base64, ne doit pas dépasser 10 Mo, résolution d'au moins 300*300px, ratio d'aspect entre 1:2.5 et 2.5:1. La Base64 ne doit pas inclure le préfixe data:image."
    }
  },
  outputs: {
    "1": {
      name: "video_id"
    },
    "2": {
      name: "duration"
    }
  }
};
const KlingTextToVideoNode$4 = {
  description: "Nœud Kling Texte en Vidéo",
  display_name: "Kling Texte en Vidéo",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio"
    },
    cfg_scale: {
      name: "cfg_scale"
    },
    mode: {
      name: "mode",
      tooltip: "La configuration à utiliser pour la génération vidéo selon le format : mode / durée / nom_du_modèle."
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Invite texte négative"
    },
    prompt: {
      name: "prompt",
      tooltip: "Invite texte positive"
    }
  },
  outputs: {
    "1": {
      name: "video_id"
    },
    "2": {
      name: "duration"
    }
  }
};
const KlingVideoExtendNode$4 = {
  description: "Nœud Kling Video Extend. Étend les vidéos créées par d'autres nœuds Kling. Le video_id est créé en utilisant d'autres nœuds Kling.",
  display_name: "Kling Video Extend",
  inputs: {
    cfg_scale: {
      name: "cfg_scale"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Invite textuelle négative pour les éléments à éviter dans la vidéo étendue"
    },
    prompt: {
      name: "prompt",
      tooltip: "Invite textuelle positive pour guider l’extension de la vidéo"
    },
    video_id: {
      name: "video_id",
      tooltip: "L’ID de la vidéo à étendre. Prend en charge les vidéos générées par texte-vers-vidéo, image-vers-vidéo et les opérations précédentes d’extension de vidéo. La durée totale ne peut pas dépasser 3 minutes après extension."
    }
  },
  outputs: {
    "1": {
      name: "video_id"
    },
    "2": {
      name: "duration"
    }
  }
};
const KlingVirtualTryOnNode$4 = {
  description: "Nœud Kling Virtual Try On. Importez une image humaine et une image de vêtement pour essayer le vêtement sur la personne.",
  display_name: "Kling Virtual Try On",
  inputs: {
    cloth_image: {
      name: "cloth_image"
    },
    human_image: {
      name: "human_image"
    },
    model_name: {
      name: "model_name"
    }
  }
};
const LTXVAddGuide$4 = {
  display_name: "LTXVAddGuide",
  inputs: {
    frame_idx: {
      name: "indice_de_l'image",
      tooltip: "Indice de l'image pour commencer le conditionnement. Pour les images uniques ou les vidéos de 1 à 8 images, toute valeur d'indice de l'image est acceptable. Pour les vidéos de 9 images ou plus, l'indice de l'image doit être divisible par 8, sinon il sera arrondi à la baisse au multiple de 8 le plus proche. Les valeurs négatives sont comptées à partir de la fin de la vidéo."
    },
    image: {
      name: "image",
      tooltip: "Image ou vidéo pour conditionner la vidéo latente. Doit être 8*n + 1 images. Si la vidéo n'est pas 8*n + 1 images, elle sera coupée au plus proche 8*n + 1 images."
    },
    latent: {
      name: "latent"
    },
    negative: {
      name: "négatif"
    },
    positive: {
      name: "positive"
    },
    strength: {
      name: "force"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "positive"
    },
    "1": {
      name: "négatif"
    },
    "2": {
      name: "latent"
    }
  }
};
const LTXVConditioning$4 = {
  display_name: "LTXVConditioning",
  inputs: {
    frame_rate: {
      name: "frame_rate"
    },
    negative: {
      name: "negative"
    },
    positive: {
      name: "positive"
    }
  },
  outputs: {
    "0": {
      name: "positive"
    },
    "1": {
      name: "negative"
    }
  }
};
const LTXVCropGuides$4 = {
  display_name: "LTXVCropGuides",
  inputs: {
    latent: {
      name: "latent"
    },
    negative: {
      name: "négatif"
    },
    positive: {
      name: "positive"
    }
  },
  outputs: {
    "0": {
      name: "positive"
    },
    "1": {
      name: "négatif"
    },
    "2": {
      name: "latent"
    }
  }
};
const LTXVImgToVideo$4 = {
  display_name: "LTXVImgToVideo",
  inputs: {
    batch_size: {
      name: "batch_size"
    },
    height: {
      name: "height"
    },
    image: {
      name: "image"
    },
    length: {
      name: "length"
    },
    negative: {
      name: "negative"
    },
    positive: {
      name: "positive"
    },
    strength: {
      name: "force"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "width"
    }
  },
  outputs: {
    "0": {
      name: "positive"
    },
    "1": {
      name: "negative"
    },
    "2": {
      name: "latent"
    }
  }
};
const LTXVPreprocess$4 = {
  display_name: "LTXVPreprocess",
  inputs: {
    image: {
      name: "image"
    },
    img_compression: {
      name: "compression_d'image",
      tooltip: "Quantité de compression à appliquer sur l'image."
    }
  },
  outputs: {
    "0": {
      name: "image_de_sortie"
    }
  }
};
const LTXVScheduler$4 = {
  display_name: "LTXVScheduler",
  inputs: {
    base_shift: {
      name: "décalage_base"
    },
    latent: {
      name: "latent"
    },
    max_shift: {
      name: "décalage_max"
    },
    steps: {
      name: "étapes"
    },
    stretch: {
      name: "étirement",
      tooltip: "Étirez les sigmas pour être dans la plage [terminal, 1]."
    },
    terminal: {
      name: "terminal",
      tooltip: "La valeur terminale des sigmas après étirement."
    }
  }
};
const LaplaceScheduler$4 = {
  display_name: "LaplaceScheduler",
  inputs: {
    beta: {
      name: "beta"
    },
    mu: {
      name: "mu"
    },
    sigma_max: {
      name: "sigma_max"
    },
    sigma_min: {
      name: "sigma_min"
    },
    steps: {
      name: "steps"
    }
  }
};
const LatentAdd$4 = {
  display_name: "LatentAdd",
  inputs: {
    samples1: {
      name: "samples1"
    },
    samples2: {
      name: "samples2"
    }
  }
};
const LatentApplyOperation$4 = {
  display_name: "LatentApplyOperation",
  inputs: {
    operation: {
      name: "operation"
    },
    samples: {
      name: "samples"
    }
  }
};
const LatentApplyOperationCFG$4 = {
  display_name: "LatentApplyOperationCFG",
  inputs: {
    model: {
      name: "model"
    },
    operation: {
      name: "operation"
    }
  }
};
const LatentBatch$4 = {
  display_name: "LatentBatch",
  inputs: {
    samples1: {
      name: "échantillons1"
    },
    samples2: {
      name: "échantillons2"
    }
  }
};
const LatentBatchSeedBehavior$4 = {
  display_name: "Comportement de la Graine LatentBatch",
  inputs: {
    samples: {
      name: "échantillons"
    },
    seed_behavior: {
      name: "comportement_de_graine"
    }
  }
};
const LatentBlend$4 = {
  display_name: "Mélange Latent",
  inputs: {
    blend_factor: {
      name: "facteur_de_mélange"
    },
    samples1: {
      name: "échantillons1"
    },
    samples2: {
      name: "échantillons2"
    }
  }
};
const LatentComposite$4 = {
  display_name: "Composite Latent",
  inputs: {
    feather: {
      name: "plume"
    },
    samples_from: {
      name: "échantillons_de"
    },
    samples_to: {
      name: "échantillons_vers"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const LatentCompositeMasked$4 = {
  display_name: "Composite Latent Masqué",
  inputs: {
    destination: {
      name: "destination"
    },
    mask: {
      name: "masque"
    },
    resize_source: {
      name: "redimensionner_source"
    },
    source: {
      name: "source"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const LatentCrop$4 = {
  display_name: "Couper Latent",
  inputs: {
    height: {
      name: "hauteur"
    },
    samples: {
      name: "échantillons"
    },
    width: {
      name: "largeur"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const LatentFlip$4 = {
  display_name: "Retourner Latent",
  inputs: {
    flip_method: {
      name: "méthode_de_retournement"
    },
    samples: {
      name: "échantillons"
    }
  }
};
const LatentFromBatch$4 = {
  display_name: "Latent De Batch",
  inputs: {
    batch_index: {
      name: "index_de_batch"
    },
    length: {
      name: "longueur"
    },
    samples: {
      name: "échantillons"
    }
  }
};
const LatentInterpolate$4 = {
  display_name: "Interpoler Latent",
  inputs: {
    ratio: {
      name: "ratio"
    },
    samples1: {
      name: "échantillons1"
    },
    samples2: {
      name: "échantillons2"
    }
  }
};
const LatentMultiply$4 = {
  display_name: "Multiplier Latent",
  inputs: {
    multiplier: {
      name: "multiplicateur"
    },
    samples: {
      name: "échantillons"
    }
  }
};
const LatentOperationSharpen$4 = {
  display_name: "Opération d'Affûtage Latent",
  inputs: {
    alpha: {
      name: "alpha"
    },
    sharpen_radius: {
      name: "rayon_d'affûtage"
    },
    sigma: {
      name: "sigma"
    }
  }
};
const LatentOperationTonemapReinhard$4 = {
  display_name: "Opération de Mappage de Tons Reinhard Latent",
  inputs: {
    multiplier: {
      name: "multiplicateur"
    }
  }
};
const LatentRotate$4 = {
  display_name: "Tourner Latent",
  inputs: {
    rotation: {
      name: "rotation"
    },
    samples: {
      name: "échantillons"
    }
  }
};
const LatentSubtract$4 = {
  display_name: "Soustraction Latente",
  inputs: {
    samples1: {
      name: "samples1"
    },
    samples2: {
      name: "samples2"
    }
  }
};
const LatentUpscale$4 = {
  display_name: "Mise à l'échelle Latente",
  inputs: {
    crop: {
      name: "recadrage"
    },
    height: {
      name: "hauteur"
    },
    samples: {
      name: "samples"
    },
    upscale_method: {
      name: "méthode_de_mise_à_l'échelle"
    },
    width: {
      name: "largeur"
    }
  }
};
const LatentUpscaleBy$4 = {
  display_name: "Mise à l'échelle Latente Par",
  inputs: {
    samples: {
      name: "samples"
    },
    scale_by: {
      name: "mise_à_l'échelle_par"
    },
    upscale_method: {
      name: "méthode_de_mise_à_l'échelle"
    }
  }
};
const Load3D$4 = {
  display_name: "Charger 3D",
  inputs: {
    clear: {},
    height: {
      name: "hauteur"
    },
    image: {
      name: "image"
    },
    model_file: {
      name: "fichier_modèle"
    },
    "upload 3d model": {},
    width: {
      name: "largeur"
    }
  },
  outputs: [
    null,
    null,
    null,
    {
      name: "normale"
    },
    {
      name: "ligne artistique"
    },
    {
      name: "informations caméra"
    }
  ]
};
const Load3DAnimation$4 = {
  display_name: "Charger 3D - Animation",
  inputs: {
    clear: {},
    height: {
      name: "hauteur"
    },
    image: {
      name: "image"
    },
    model_file: {
      name: "fichier_modèle"
    },
    "upload 3d model": {},
    width: {
      name: "largeur"
    }
  },
  outputs: [
    null,
    null,
    null,
    {
      name: "normal"
    },
    {
      name: "camera_info"
    }
  ]
};
const LoadAudio$4 = {
  display_name: "ChargerAudio",
  inputs: {
    audio: {
      name: "audio"
    },
    audioUI: {
      name: "audioUI"
    },
    upload: {
      name: "choisissez le fichier à télécharger"
    }
  }
};
const LoadImage$4 = {
  display_name: "Charger Image",
  inputs: {
    image: {
      name: "image"
    },
    upload: {
      name: "choisissez le fichier à télécharger"
    }
  }
};
const LoadImageMask$4 = {
  display_name: "Charger Image (comme Masque)",
  inputs: {
    channel: {
      name: "canal"
    },
    image: {
      name: "image"
    },
    upload: {
      name: "choisissez le fichier à télécharger"
    }
  }
};
const LoadImageOutput$4 = {
  description: "Chargez une image à partir du dossier de sortie. Lorsque le bouton de rafraîchissement est cliqué, le nœud mettra à jour la liste des images et sélectionnera automatiquement la première image, permettant une itération facile.",
  display_name: "Charger l'image (à partir des sorties)",
  inputs: {
    image: {
      name: "image"
    },
    refresh: {},
    upload: {
      name: "choisissez le fichier à télécharger"
    }
  }
};
const LoadLatent$4 = {
  display_name: "ChargerLatent",
  inputs: {
    latent: {
      name: "latent"
    }
  }
};
const LoadVideo$4 = {
  display_name: "Charger une vidéo",
  inputs: {
    file: {
      name: "fichier"
    },
    upload: {
      name: "choisir un fichier à télécharger"
    }
  }
};
const LoraLoader$4 = {
  description: "Les LoRAs sont utilisés pour modifier les modèles de diffusion et CLIP, modifiant la manière dont les latents sont débruités comme l'application de styles. Plusieurs nœuds LoRA peuvent être liés ensemble.",
  display_name: "Charger LoRA",
  inputs: {
    clip: {
      name: "clip",
      tooltip: "Le modèle CLIP auquel le LoRA sera appliqué."
    },
    lora_name: {
      name: "lora_name",
      tooltip: "Le nom du LoRA."
    },
    model: {
      name: "model",
      tooltip: "Le modèle de diffusion auquel le LoRA sera appliqué."
    },
    strength_clip: {
      name: "strength_clip",
      tooltip: "À quel point modifier le modèle CLIP. Cette valeur peut être négative."
    },
    strength_model: {
      name: "strength_model",
      tooltip: "À quel point modifier le modèle de diffusion. Cette valeur peut être négative."
    }
  },
  outputs: {
    "0": {
      tooltip: "Le modèle de diffusion modifié."
    },
    "1": {
      tooltip: "Le modèle CLIP modifié."
    }
  }
};
const LoraLoaderModelOnly$4 = {
  description: "Les LoRAs sont utilisés pour modifier les modèles de diffusion et CLIP, modifiant la manière dont les latents sont débruités comme l'application de styles. Plusieurs nœuds LoRA peuvent être liés ensemble.",
  display_name: "LoraLoaderModelOnly",
  inputs: {
    lora_name: {
      name: "lora_name"
    },
    model: {
      name: "model"
    },
    strength_model: {
      name: "strength_model"
    }
  },
  outputs: {
    "0": {
      tooltip: "Le modèle de diffusion modifié."
    }
  }
};
const LoraSave$4 = {
  display_name: "Extraire et Sauvegarder Lora",
  inputs: {
    bias_diff: {
      name: "bias_diff"
    },
    filename_prefix: {
      name: "filename_prefix"
    },
    lora_type: {
      name: "lora_type"
    },
    model_diff: {
      name: "model_diff",
      tooltip: "La sortie ModelSubtract à convertir en lora."
    },
    rank: {
      name: "rank"
    },
    text_encoder_diff: {
      name: "text_encoder_diff",
      tooltip: "La sortie CLIPSubtract à convertir en lora."
    }
  }
};
const LotusConditioning$4 = {
  display_name: "LotusConditioning",
  outputs: {
    "0": {
      name: "conditionnement"
    }
  }
};
const LumaConceptsNode$4 = {
  description: "Contient un ou plusieurs Concepts de Caméra à utiliser avec les nœuds Luma Text to Video et Luma Image to Video.",
  display_name: "Luma Concepts",
  inputs: {
    concept1: {
      name: "concept1"
    },
    concept2: {
      name: "concept2"
    },
    concept3: {
      name: "concept3"
    },
    concept4: {
      name: "concept4"
    },
    luma_concepts: {
      name: "luma_concepts",
      tooltip: "Concepts de Caméra optionnels à ajouter à ceux sélectionnés ici."
    }
  },
  outputs: {
    "0": {
      name: "luma_concepts"
    }
  }
};
const LumaImageModifyNode$4 = {
  description: "Modifie les images de manière synchrone en fonction du prompt et du format d'image.",
  display_name: "Luma Image vers Image",
  inputs: {
    control_after_generate: {
      name: "contrôle après génération"
    },
    image: {
      name: "image"
    },
    image_weight: {
      name: "poids de l'image",
      tooltip: "Poids de l'image ; plus la valeur est proche de 1.0, moins l'image sera modifiée."
    },
    model: {
      name: "modèle"
    },
    prompt: {
      name: "prompt",
      tooltip: "Prompt pour la génération d'image"
    },
    seed: {
      name: "graine",
      tooltip: "Graine pour déterminer si le nœud doit être relancé ; les résultats réels sont non déterministes quel que soit la graine."
    }
  }
};
const LumaImageNode$4 = {
  description: "Génère des images de manière synchrone à partir d'une invite et d'un ratio d'aspect.",
  display_name: "Luma Texte vers Image",
  inputs: {
    aspect_ratio: {
      name: "ratio_d'aspect"
    },
    character_image: {
      name: "image_de_personnage",
      tooltip: "Images de référence de personnage ; peut être un lot de plusieurs, jusqu'à 4 images peuvent être prises en compte."
    },
    control_after_generate: {
      name: "contrôle après génération"
    },
    image_luma_ref: {
      name: "référence_image_luma",
      tooltip: "Connexion au nœud de référence Luma pour influencer la génération avec des images d'entrée ; jusqu'à 4 images peuvent être prises en compte."
    },
    model: {
      name: "modèle"
    },
    prompt: {
      name: "invite",
      tooltip: "Invite pour la génération d'image"
    },
    seed: {
      name: "graine",
      tooltip: "Graine pour déterminer si le nœud doit être relancé ; les résultats réels restent non déterministes, quelle que soit la graine."
    },
    style_image: {
      name: "image_de_style",
      tooltip: "Image de référence de style ; seule 1 image sera utilisée."
    },
    style_image_weight: {
      name: "poids_image_de_style",
      tooltip: "Poids de l'image de style. Ignoré si aucune image de style n'est fournie."
    }
  }
};
const LumaImageToVideoNode$4 = {
  description: "Génère des vidéos de manière synchrone à partir d'un prompt, d'images d'entrée et de la taille de sortie.",
  display_name: "Luma Image to Video",
  inputs: {
    control_after_generate: {
      name: "contrôle après génération"
    },
    duration: {
      name: "durée"
    },
    first_image: {
      name: "première_image",
      tooltip: "Première image de la vidéo générée."
    },
    last_image: {
      name: "dernière_image",
      tooltip: "Dernière image de la vidéo générée."
    },
    loop: {
      name: "boucle"
    },
    luma_concepts: {
      name: "luma_concepts",
      tooltip: "Concepts de caméra optionnels pour dicter le mouvement de la caméra via le nœud Luma Concepts."
    },
    model: {
      name: "modèle"
    },
    prompt: {
      name: "prompt",
      tooltip: "Prompt pour la génération de la vidéo"
    },
    resolution: {
      name: "résolution"
    },
    seed: {
      name: "seed",
      tooltip: "Seed pour déterminer si le nœud doit être relancé ; les résultats réels restent non déterministes quel que soit le seed."
    }
  }
};
const LumaReferenceNode$4 = {
  description: "Contient une image et un poids à utiliser avec le nœud Luma Générer Image.",
  display_name: "Référence Luma",
  inputs: {
    image: {
      name: "image",
      tooltip: "Image à utiliser comme référence."
    },
    luma_ref: {
      name: "luma_ref"
    },
    weight: {
      name: "poids",
      tooltip: "Poids de la référence d'image."
    }
  },
  outputs: {
    "0": {
      name: "luma_ref"
    }
  }
};
const LumaVideoNode$4 = {
  description: "Génère des vidéos de manière synchrone à partir du prompt et de la taille de sortie.",
  display_name: "Luma Texte vers Vidéo",
  inputs: {
    aspect_ratio: {
      name: "rapport d'aspect"
    },
    control_after_generate: {
      name: "contrôle après génération"
    },
    duration: {
      name: "durée"
    },
    loop: {
      name: "boucle"
    },
    luma_concepts: {
      name: "luma_concepts",
      tooltip: "Concepts de caméra optionnels pour dicter le mouvement de la caméra via le nœud Luma Concepts."
    },
    model: {
      name: "modèle"
    },
    prompt: {
      name: "prompt",
      tooltip: "Prompt pour la génération de la vidéo"
    },
    resolution: {
      name: "résolution"
    },
    seed: {
      name: "graine",
      tooltip: "Graine pour déterminer si le nœud doit être relancé ; les résultats réels restent non déterministes quelle que soit la graine."
    }
  }
};
const Mahiro$4 = {
  description: "Modifiez le guidage pour qu'il se concentre davantage sur la 'direction' de l'invite positive plutôt que sur la différence avec l'invite négative.",
  display_name: "Mahiro est si mignonne qu'elle mérite une meilleure fonction de guidage!! (。・ω・。)",
  inputs: {
    model: {
      name: "modèle"
    }
  },
  outputs: {
    "0": {
      name: "modèle_modifié"
    }
  }
};
const MaskComposite$4 = {
  display_name: "MaskComposite",
  inputs: {
    destination: {
      name: "destination"
    },
    operation: {
      name: "opération"
    },
    source: {
      name: "source"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const MaskPreview$4 = {
  description: "Enregistre les images d'entrée dans votre répertoire de sortie ComfyUI.",
  display_name: "MaskPreview",
  inputs: {
    mask: {
      name: "mask"
    }
  }
};
const MaskToImage$4 = {
  display_name: "Convertir le masque en image",
  inputs: {
    mask: {
      name: "masque"
    }
  }
};
const MinimaxImageToVideoNode$4 = {
  description: "Génère des vidéos à partir d'une image et d'invites en utilisant l'API de MiniMax",
  display_name: "MiniMax Image vers Vidéo",
  inputs: {
    control_after_generate: {
      name: "contrôle après génération"
    },
    image: {
      name: "image",
      tooltip: "Image à utiliser comme première image pour la génération de vidéo"
    },
    model: {
      name: "modèle",
      tooltip: "Modèle à utiliser pour la génération de vidéo"
    },
    prompt_text: {
      name: "texte d'invite",
      tooltip: "Texte d'invite pour guider la génération de la vidéo"
    },
    seed: {
      name: "graine",
      tooltip: "La graine aléatoire utilisée pour créer le bruit."
    }
  }
};
const MinimaxTextToVideoNode$4 = {
  description: "Génère des vidéos à partir d'invites en utilisant l'API de MiniMax",
  display_name: "MiniMax Texte en Vidéo",
  inputs: {
    control_after_generate: {
      name: "contrôle après génération"
    },
    model: {
      name: "modèle",
      tooltip: "Modèle à utiliser pour la génération de vidéo"
    },
    prompt_text: {
      name: "texte d'invite",
      tooltip: "Texte d'invite pour guider la génération de la vidéo"
    },
    seed: {
      name: "graine",
      tooltip: "La graine aléatoire utilisée pour créer le bruit."
    }
  }
};
const ModelComputeDtype$4 = {
  display_name: "ModelComputeDtype",
  inputs: {
    dtype: {
      name: "dtype"
    },
    model: {
      name: "modèle"
    }
  }
};
const ModelMergeAdd$4 = {
  display_name: "ModelMergeAdd",
  inputs: {
    model1: {
      name: "modèle1"
    },
    model2: {
      name: "modèle2"
    }
  }
};
const ModelMergeAuraflow$4 = {
  display_name: "ModelMergeAuraflow",
  inputs: {
    cond_seq_linear_: {
      name: "cond_seq_linear."
    },
    double_layers_0_: {
      name: "double_layers.0."
    },
    double_layers_1_: {
      name: "double_layers.1."
    },
    double_layers_2_: {
      name: "double_layers.2."
    },
    double_layers_3_: {
      name: "double_layers.3."
    },
    final_linear_: {
      name: "final_linear."
    },
    init_x_linear_: {
      name: "init_x_linear."
    },
    modF_: {
      name: "modF."
    },
    model1: {
      name: "model1"
    },
    model2: {
      name: "model2"
    },
    positional_encoding: {
      name: "codage_positionnel"
    },
    register_tokens: {
      name: "enregistrer_tokens"
    },
    single_layers_0_: {
      name: "single_layers.0."
    },
    single_layers_10_: {
      name: "single_layers.10."
    },
    single_layers_11_: {
      name: "single_layers.11."
    },
    single_layers_12_: {
      name: "single_layers.12."
    },
    single_layers_13_: {
      name: "single_layers.13."
    },
    single_layers_14_: {
      name: "single_layers.14."
    },
    single_layers_15_: {
      name: "single_layers.15."
    },
    single_layers_16_: {
      name: "single_layers.16."
    },
    single_layers_17_: {
      name: "single_layers.17."
    },
    single_layers_18_: {
      name: "single_layers.18."
    },
    single_layers_19_: {
      name: "single_layers.19."
    },
    single_layers_1_: {
      name: "single_layers.1."
    },
    single_layers_20_: {
      name: "single_layers.20."
    },
    single_layers_21_: {
      name: "single_layers.21."
    },
    single_layers_22_: {
      name: "single_layers.22."
    },
    single_layers_23_: {
      name: "single_layers.23."
    },
    single_layers_24_: {
      name: "single_layers.24."
    },
    single_layers_25_: {
      name: "single_layers.25."
    },
    single_layers_26_: {
      name: "single_layers.26."
    },
    single_layers_27_: {
      name: "single_layers.27."
    },
    single_layers_28_: {
      name: "single_layers.28."
    },
    single_layers_29_: {
      name: "single_layers.29."
    },
    single_layers_2_: {
      name: "single_layers.2."
    },
    single_layers_30_: {
      name: "single_layers.30."
    },
    single_layers_31_: {
      name: "single_layers.31."
    },
    single_layers_3_: {
      name: "single_layers.3."
    },
    single_layers_4_: {
      name: "single_layers.4."
    },
    single_layers_5_: {
      name: "single_layers.5."
    },
    single_layers_6_: {
      name: "single_layers.6."
    },
    single_layers_7_: {
      name: "single_layers.7."
    },
    single_layers_8_: {
      name: "single_layers.8."
    },
    single_layers_9_: {
      name: "single_layers.9."
    },
    t_embedder_: {
      name: "t_embedder."
    }
  }
};
const ModelMergeBlocks$4 = {
  display_name: "ModelMergeBlocks",
  inputs: {
    input: {
      name: "entrée"
    },
    middle: {
      name: "milieu"
    },
    model1: {
      name: "modèle1"
    },
    model2: {
      name: "modèle2"
    },
    out: {
      name: "sortie"
    }
  }
};
const ModelMergeCosmos14B$4 = {
  display_name: "ModelMergeCosmos14B",
  inputs: {
    affline_norm_: {
      name: "affline_norm."
    },
    blocks_block0_: {
      name: "blocks.block0."
    },
    blocks_block10_: {
      name: "blocks.block10."
    },
    blocks_block11_: {
      name: "blocks.block11."
    },
    blocks_block12_: {
      name: "blocks.block12."
    },
    blocks_block13_: {
      name: "blocks.block13."
    },
    blocks_block14_: {
      name: "blocks.block14."
    },
    blocks_block15_: {
      name: "blocks.block15."
    },
    blocks_block16_: {
      name: "blocks.block16."
    },
    blocks_block17_: {
      name: "blocks.block17."
    },
    blocks_block18_: {
      name: "blocks.block18."
    },
    blocks_block19_: {
      name: "blocks.block19."
    },
    blocks_block1_: {
      name: "blocks.block1."
    },
    blocks_block20_: {
      name: "blocks.block20."
    },
    blocks_block21_: {
      name: "blocks.block21."
    },
    blocks_block22_: {
      name: "blocks.block22."
    },
    blocks_block23_: {
      name: "blocks.block23."
    },
    blocks_block24_: {
      name: "blocks.block24."
    },
    blocks_block25_: {
      name: "blocks.block25."
    },
    blocks_block26_: {
      name: "blocks.block26."
    },
    blocks_block27_: {
      name: "blocks.block27."
    },
    blocks_block28_: {
      name: "blocks.block28."
    },
    blocks_block29_: {
      name: "blocks.block29."
    },
    blocks_block2_: {
      name: "blocks.block2."
    },
    blocks_block30_: {
      name: "blocks.block30."
    },
    blocks_block31_: {
      name: "blocks.block31."
    },
    blocks_block32_: {
      name: "blocks.block32."
    },
    blocks_block33_: {
      name: "blocks.block33."
    },
    blocks_block34_: {
      name: "blocks.block34."
    },
    blocks_block35_: {
      name: "blocks.block35."
    },
    blocks_block3_: {
      name: "blocks.block3."
    },
    blocks_block4_: {
      name: "blocks.block4."
    },
    blocks_block5_: {
      name: "blocks.block5."
    },
    blocks_block6_: {
      name: "blocks.block6."
    },
    blocks_block7_: {
      name: "blocks.block7."
    },
    blocks_block8_: {
      name: "blocks.block8."
    },
    blocks_block9_: {
      name: "blocks.block9."
    },
    extra_pos_embedder_: {
      name: "extra_pos_embedder."
    },
    final_layer_: {
      name: "couche_finale."
    },
    model1: {
      name: "modèle1"
    },
    model2: {
      name: "modèle2"
    },
    pos_embedder_: {
      name: "pos_embedder."
    },
    t_embedder_: {
      name: "t_embedder."
    },
    x_embedder_: {
      name: "x_embedder."
    }
  }
};
const ModelMergeCosmos7B$4 = {
  display_name: "ModelMergeCosmos7B",
  inputs: {
    affline_norm_: {
      name: "affline_norm."
    },
    blocks_block0_: {
      name: "blocks.block0."
    },
    blocks_block10_: {
      name: "blocks.block10."
    },
    blocks_block11_: {
      name: "blocks.block11."
    },
    blocks_block12_: {
      name: "blocks.block12."
    },
    blocks_block13_: {
      name: "blocks.block13."
    },
    blocks_block14_: {
      name: "blocks.block14."
    },
    blocks_block15_: {
      name: "blocks.block15."
    },
    blocks_block16_: {
      name: "blocks.block16."
    },
    blocks_block17_: {
      name: "blocks.block17."
    },
    blocks_block18_: {
      name: "blocks.block18."
    },
    blocks_block19_: {
      name: "blocks.block19."
    },
    blocks_block1_: {
      name: "blocks.block1."
    },
    blocks_block20_: {
      name: "blocks.block20."
    },
    blocks_block21_: {
      name: "blocks.block21."
    },
    blocks_block22_: {
      name: "blocks.block22."
    },
    blocks_block23_: {
      name: "blocks.block23."
    },
    blocks_block24_: {
      name: "blocks.block24."
    },
    blocks_block25_: {
      name: "blocks.block25."
    },
    blocks_block26_: {
      name: "blocks.block26."
    },
    blocks_block27_: {
      name: "blocks.block27."
    },
    blocks_block2_: {
      name: "blocks.block2."
    },
    blocks_block3_: {
      name: "blocks.block3."
    },
    blocks_block4_: {
      name: "blocks.block4."
    },
    blocks_block5_: {
      name: "blocks.block5."
    },
    blocks_block6_: {
      name: "blocks.block6."
    },
    blocks_block7_: {
      name: "blocks.block7."
    },
    blocks_block8_: {
      name: "blocks.block8."
    },
    blocks_block9_: {
      name: "blocks.block9."
    },
    extra_pos_embedder_: {
      name: "extra_pos_embedder."
    },
    final_layer_: {
      name: "final_layer."
    },
    model1: {
      name: "model1"
    },
    model2: {
      name: "model2"
    },
    pos_embedder_: {
      name: "pos_embedder."
    },
    t_embedder_: {
      name: "t_embedder."
    },
    x_embedder_: {
      name: "x_embedder."
    }
  }
};
const ModelMergeFlux1$4 = {
  display_name: "ModelMergeFlux1",
  inputs: {
    double_blocks_0_: {
      name: "double_blocks.0."
    },
    double_blocks_10_: {
      name: "double_blocks.10."
    },
    double_blocks_11_: {
      name: "double_blocks.11."
    },
    double_blocks_12_: {
      name: "double_blocks.12."
    },
    double_blocks_13_: {
      name: "double_blocks.13."
    },
    double_blocks_14_: {
      name: "double_blocks.14."
    },
    double_blocks_15_: {
      name: "double_blocks.15."
    },
    double_blocks_16_: {
      name: "double_blocks.16."
    },
    double_blocks_17_: {
      name: "double_blocks.17."
    },
    double_blocks_18_: {
      name: "double_blocks.18."
    },
    double_blocks_1_: {
      name: "double_blocks.1."
    },
    double_blocks_2_: {
      name: "double_blocks.2."
    },
    double_blocks_3_: {
      name: "double_blocks.3."
    },
    double_blocks_4_: {
      name: "double_blocks.4."
    },
    double_blocks_5_: {
      name: "double_blocks.5."
    },
    double_blocks_6_: {
      name: "double_blocks.6."
    },
    double_blocks_7_: {
      name: "double_blocks.7."
    },
    double_blocks_8_: {
      name: "double_blocks.8."
    },
    double_blocks_9_: {
      name: "double_blocks.9."
    },
    final_layer_: {
      name: "final_layer."
    },
    guidance_in: {
      name: "guidance_in"
    },
    img_in_: {
      name: "img_in."
    },
    model1: {
      name: "model1"
    },
    model2: {
      name: "model2"
    },
    single_blocks_0_: {
      name: "single_blocks.0."
    },
    single_blocks_10_: {
      name: "single_blocks.10."
    },
    single_blocks_11_: {
      name: "single_blocks.11."
    },
    single_blocks_12_: {
      name: "single_blocks.12."
    },
    single_blocks_13_: {
      name: "single_blocks.13."
    },
    single_blocks_14_: {
      name: "single_blocks.14."
    },
    single_blocks_15_: {
      name: "single_blocks.15."
    },
    single_blocks_16_: {
      name: "single_blocks.16."
    },
    single_blocks_17_: {
      name: "single_blocks.17."
    },
    single_blocks_18_: {
      name: "single_blocks.18."
    },
    single_blocks_19_: {
      name: "single_blocks.19."
    },
    single_blocks_1_: {
      name: "single_blocks.1."
    },
    single_blocks_20_: {
      name: "single_blocks.20."
    },
    single_blocks_21_: {
      name: "single_blocks.21."
    },
    single_blocks_22_: {
      name: "single_blocks.22."
    },
    single_blocks_23_: {
      name: "single_blocks.23."
    },
    single_blocks_24_: {
      name: "single_blocks.24."
    },
    single_blocks_25_: {
      name: "single_blocks.25."
    },
    single_blocks_26_: {
      name: "single_blocks.26."
    },
    single_blocks_27_: {
      name: "single_blocks.27."
    },
    single_blocks_28_: {
      name: "single_blocks.28."
    },
    single_blocks_29_: {
      name: "single_blocks.29."
    },
    single_blocks_2_: {
      name: "single_blocks.2."
    },
    single_blocks_30_: {
      name: "single_blocks.30."
    },
    single_blocks_31_: {
      name: "single_blocks.31."
    },
    single_blocks_32_: {
      name: "single_blocks.32."
    },
    single_blocks_33_: {
      name: "single_blocks.33."
    },
    single_blocks_34_: {
      name: "single_blocks.34."
    },
    single_blocks_35_: {
      name: "single_blocks.35."
    },
    single_blocks_36_: {
      name: "single_blocks.36."
    },
    single_blocks_37_: {
      name: "single_blocks.37."
    },
    single_blocks_3_: {
      name: "single_blocks.3."
    },
    single_blocks_4_: {
      name: "single_blocks.4."
    },
    single_blocks_5_: {
      name: "single_blocks.5."
    },
    single_blocks_6_: {
      name: "single_blocks.6."
    },
    single_blocks_7_: {
      name: "single_blocks.7."
    },
    single_blocks_8_: {
      name: "single_blocks.8."
    },
    single_blocks_9_: {
      name: "single_blocks.9."
    },
    time_in_: {
      name: "time_in."
    },
    txt_in_: {
      name: "txt_in."
    },
    vector_in_: {
      name: "vector_in."
    }
  }
};
const ModelMergeLTXV$4 = {
  display_name: "ModelMergeLTXV",
  inputs: {
    adaln_single_: {
      name: "adaln_single."
    },
    caption_projection_: {
      name: "projection_de_légende."
    },
    model1: {
      name: "model1"
    },
    model2: {
      name: "model2"
    },
    patchify_proj_: {
      name: "patchify_proj."
    },
    proj_out_: {
      name: "proj_out."
    },
    scale_shift_table: {
      name: "table_de_décalage_d'échelle"
    },
    transformer_blocks_0_: {
      name: "blocs_transformateurs.0."
    },
    transformer_blocks_10_: {
      name: "blocs_transformateurs.10."
    },
    transformer_blocks_11_: {
      name: "blocs_transformateurs.11."
    },
    transformer_blocks_12_: {
      name: "blocs_transformateurs.12."
    },
    transformer_blocks_13_: {
      name: "blocs_transformateurs.13."
    },
    transformer_blocks_14_: {
      name: "blocs_transformateurs.14."
    },
    transformer_blocks_15_: {
      name: "blocs_transformateurs.15."
    },
    transformer_blocks_16_: {
      name: "blocs_transformateurs.16."
    },
    transformer_blocks_17_: {
      name: "blocs_transformateurs.17."
    },
    transformer_blocks_18_: {
      name: "blocs_transformateurs.18."
    },
    transformer_blocks_19_: {
      name: "blocs_transformateurs.19."
    },
    transformer_blocks_1_: {
      name: "blocs_transformateurs.1."
    },
    transformer_blocks_20_: {
      name: "blocs_transformateurs.20."
    },
    transformer_blocks_21_: {
      name: "blocs_transformateurs.21."
    },
    transformer_blocks_22_: {
      name: "blocs_transformateurs.22."
    },
    transformer_blocks_23_: {
      name: "blocs_transformateurs.23."
    },
    transformer_blocks_24_: {
      name: "blocs_transformateurs.24."
    },
    transformer_blocks_25_: {
      name: "blocs_transformateurs.25."
    },
    transformer_blocks_26_: {
      name: "blocs_transformateurs.26."
    },
    transformer_blocks_27_: {
      name: "blocs_transformateurs.27."
    },
    transformer_blocks_2_: {
      name: "blocs_transformateurs.2."
    },
    transformer_blocks_3_: {
      name: "blocs_transformateurs.3."
    },
    transformer_blocks_4_: {
      name: "blocs_transformateurs.4."
    },
    transformer_blocks_5_: {
      name: "blocs_transformateurs.5."
    },
    transformer_blocks_6_: {
      name: "blocs_transformateurs.6."
    },
    transformer_blocks_7_: {
      name: "blocs_transformateurs.7."
    },
    transformer_blocks_8_: {
      name: "blocs_transformateurs.8."
    },
    transformer_blocks_9_: {
      name: "blocs_transformateurs.9."
    }
  }
};
const ModelMergeMochiPreview$4 = {
  display_name: "Aperçu de la Fusion de Modèles Mochi",
  inputs: {
    blocks_0_: {
      name: "blocs.0."
    },
    blocks_10_: {
      name: "blocs.10."
    },
    blocks_11_: {
      name: "blocs.11."
    },
    blocks_12_: {
      name: "blocs.12."
    },
    blocks_13_: {
      name: "blocs.13."
    },
    blocks_14_: {
      name: "blocs.14."
    },
    blocks_15_: {
      name: "blocs.15."
    },
    blocks_16_: {
      name: "blocs.16."
    },
    blocks_17_: {
      name: "blocs.17."
    },
    blocks_18_: {
      name: "blocs.18."
    },
    blocks_19_: {
      name: "blocs.19."
    },
    blocks_1_: {
      name: "blocs.1."
    },
    blocks_20_: {
      name: "blocs.20."
    },
    blocks_21_: {
      name: "blocs.21."
    },
    blocks_22_: {
      name: "blocs.22."
    },
    blocks_23_: {
      name: "blocs.23."
    },
    blocks_24_: {
      name: "blocs.24."
    },
    blocks_25_: {
      name: "blocs.25."
    },
    blocks_26_: {
      name: "blocs.26."
    },
    blocks_27_: {
      name: "blocs.27."
    },
    blocks_28_: {
      name: "blocs.28."
    },
    blocks_29_: {
      name: "blocs.29."
    },
    blocks_2_: {
      name: "blocs.2."
    },
    blocks_30_: {
      name: "blocs.30."
    },
    blocks_31_: {
      name: "blocs.31."
    },
    blocks_32_: {
      name: "blocs.32."
    },
    blocks_33_: {
      name: "blocs.33."
    },
    blocks_34_: {
      name: "blocs.34."
    },
    blocks_35_: {
      name: "blocs.35."
    },
    blocks_36_: {
      name: "blocs.36."
    },
    blocks_37_: {
      name: "blocs.37."
    },
    blocks_38_: {
      name: "blocs.38."
    },
    blocks_39_: {
      name: "blocs.39."
    },
    blocks_3_: {
      name: "blocs.3."
    },
    blocks_40_: {
      name: "blocs.40."
    },
    blocks_41_: {
      name: "blocs.41."
    },
    blocks_42_: {
      name: "blocs.42."
    },
    blocks_43_: {
      name: "blocs.43."
    },
    blocks_44_: {
      name: "blocs.44."
    },
    blocks_45_: {
      name: "blocs.45."
    },
    blocks_46_: {
      name: "blocs.46."
    },
    blocks_47_: {
      name: "blocs.47."
    },
    blocks_4_: {
      name: "blocs.4."
    },
    blocks_5_: {
      name: "blocs.5."
    },
    blocks_6_: {
      name: "blocs.6."
    },
    blocks_7_: {
      name: "blocs.7."
    },
    blocks_8_: {
      name: "blocs.8."
    },
    blocks_9_: {
      name: "blocs.9."
    },
    final_layer_: {
      name: "couche_finale."
    },
    model1: {
      name: "modèle1"
    },
    model2: {
      name: "modèle2"
    },
    pos_frequencies_: {
      name: "pos_frequences."
    },
    t5_y_embedder_: {
      name: "t5_y_embedder."
    },
    t5_yproj_: {
      name: "t5_yproj."
    },
    t_embedder_: {
      name: "t_embedder."
    }
  }
};
const ModelMergeSD1$4 = {
  display_name: "ModelMergeSD1",
  inputs: {
    input_blocks_0_: {
      name: "input_blocks.0."
    },
    input_blocks_10_: {
      name: "input_blocks.10."
    },
    input_blocks_11_: {
      name: "input_blocks.11."
    },
    input_blocks_1_: {
      name: "input_blocks.1."
    },
    input_blocks_2_: {
      name: "input_blocks.2."
    },
    input_blocks_3_: {
      name: "input_blocks.3."
    },
    input_blocks_4_: {
      name: "input_blocks.4."
    },
    input_blocks_5_: {
      name: "input_blocks.5."
    },
    input_blocks_6_: {
      name: "input_blocks.6."
    },
    input_blocks_7_: {
      name: "input_blocks.7."
    },
    input_blocks_8_: {
      name: "input_blocks.8."
    },
    input_blocks_9_: {
      name: "input_blocks.9."
    },
    label_emb_: {
      name: "label_emb."
    },
    middle_block_0_: {
      name: "middle_block.0."
    },
    middle_block_1_: {
      name: "middle_block.1."
    },
    middle_block_2_: {
      name: "middle_block.2."
    },
    model1: {
      name: "model1"
    },
    model2: {
      name: "model2"
    },
    out_: {
      name: "out."
    },
    output_blocks_0_: {
      name: "output_blocks.0."
    },
    output_blocks_10_: {
      name: "output_blocks.10."
    },
    output_blocks_11_: {
      name: "output_blocks.11."
    },
    output_blocks_1_: {
      name: "output_blocks.1."
    },
    output_blocks_2_: {
      name: "output_blocks.2."
    },
    output_blocks_3_: {
      name: "output_blocks.3."
    },
    output_blocks_4_: {
      name: "output_blocks.4."
    },
    output_blocks_5_: {
      name: "output_blocks.5."
    },
    output_blocks_6_: {
      name: "output_blocks.6."
    },
    output_blocks_7_: {
      name: "output_blocks.7."
    },
    output_blocks_8_: {
      name: "output_blocks.8."
    },
    output_blocks_9_: {
      name: "output_blocks.9."
    },
    time_embed_: {
      name: "time_embed."
    }
  }
};
const ModelMergeSD2$4 = {
  display_name: "ModelMergeSD2",
  inputs: {
    input_blocks_0_: {
      name: "input_blocks.0."
    },
    input_blocks_10_: {
      name: "input_blocks.10."
    },
    input_blocks_11_: {
      name: "input_blocks.11."
    },
    input_blocks_1_: {
      name: "input_blocks.1."
    },
    input_blocks_2_: {
      name: "input_blocks.2."
    },
    input_blocks_3_: {
      name: "input_blocks.3."
    },
    input_blocks_4_: {
      name: "input_blocks.4."
    },
    input_blocks_5_: {
      name: "input_blocks.5."
    },
    input_blocks_6_: {
      name: "input_blocks.6."
    },
    input_blocks_7_: {
      name: "input_blocks.7."
    },
    input_blocks_8_: {
      name: "input_blocks.8."
    },
    input_blocks_9_: {
      name: "input_blocks.9."
    },
    label_emb_: {
      name: "label_emb."
    },
    middle_block_0_: {
      name: "middle_block.0."
    },
    middle_block_1_: {
      name: "middle_block.1."
    },
    middle_block_2_: {
      name: "middle_block.2."
    },
    model1: {
      name: "model1"
    },
    model2: {
      name: "model2"
    },
    out_: {
      name: "out."
    },
    output_blocks_0_: {
      name: "output_blocks.0."
    },
    output_blocks_10_: {
      name: "output_blocks.10."
    },
    output_blocks_11_: {
      name: "output_blocks.11."
    },
    output_blocks_1_: {
      name: "output_blocks.1."
    },
    output_blocks_2_: {
      name: "output_blocks.2."
    },
    output_blocks_3_: {
      name: "output_blocks.3."
    },
    output_blocks_4_: {
      name: "output_blocks.4."
    },
    output_blocks_5_: {
      name: "output_blocks.5."
    },
    output_blocks_6_: {
      name: "output_blocks.6."
    },
    output_blocks_7_: {
      name: "output_blocks.7."
    },
    output_blocks_8_: {
      name: "output_blocks.8."
    },
    output_blocks_9_: {
      name: "output_blocks.9."
    },
    time_embed_: {
      name: "time_embed."
    }
  }
};
const ModelMergeSD35_Large$4 = {
  display_name: "ModelMergeSD35_Large",
  inputs: {
    context_embedder_: {
      name: "context_embedder."
    },
    final_layer_: {
      name: "final_layer."
    },
    joint_blocks_0_: {
      name: "joint_blocks.0."
    },
    joint_blocks_10_: {
      name: "joint_blocks.10."
    },
    joint_blocks_11_: {
      name: "joint_blocks.11."
    },
    joint_blocks_12_: {
      name: "joint_blocks.12."
    },
    joint_blocks_13_: {
      name: "joint_blocks.13."
    },
    joint_blocks_14_: {
      name: "joint_blocks.14."
    },
    joint_blocks_15_: {
      name: "joint_blocks.15."
    },
    joint_blocks_16_: {
      name: "joint_blocks.16."
    },
    joint_blocks_17_: {
      name: "joint_blocks.17."
    },
    joint_blocks_18_: {
      name: "joint_blocks.18."
    },
    joint_blocks_19_: {
      name: "joint_blocks.19."
    },
    joint_blocks_1_: {
      name: "joint_blocks.1."
    },
    joint_blocks_20_: {
      name: "joint_blocks.20."
    },
    joint_blocks_21_: {
      name: "joint_blocks.21."
    },
    joint_blocks_22_: {
      name: "joint_blocks.22."
    },
    joint_blocks_23_: {
      name: "joint_blocks.23."
    },
    joint_blocks_24_: {
      name: "joint_blocks.24."
    },
    joint_blocks_25_: {
      name: "joint_blocks.25."
    },
    joint_blocks_26_: {
      name: "joint_blocks.26."
    },
    joint_blocks_27_: {
      name: "joint_blocks.27."
    },
    joint_blocks_28_: {
      name: "joint_blocks.28."
    },
    joint_blocks_29_: {
      name: "joint_blocks.29."
    },
    joint_blocks_2_: {
      name: "joint_blocks.2."
    },
    joint_blocks_30_: {
      name: "joint_blocks.30."
    },
    joint_blocks_31_: {
      name: "joint_blocks.31."
    },
    joint_blocks_32_: {
      name: "joint_blocks.32."
    },
    joint_blocks_33_: {
      name: "joint_blocks.33."
    },
    joint_blocks_34_: {
      name: "joint_blocks.34."
    },
    joint_blocks_35_: {
      name: "joint_blocks.35."
    },
    joint_blocks_36_: {
      name: "joint_blocks.36."
    },
    joint_blocks_37_: {
      name: "joint_blocks.37."
    },
    joint_blocks_3_: {
      name: "joint_blocks.3."
    },
    joint_blocks_4_: {
      name: "joint_blocks.4."
    },
    joint_blocks_5_: {
      name: "joint_blocks.5."
    },
    joint_blocks_6_: {
      name: "joint_blocks.6."
    },
    joint_blocks_7_: {
      name: "joint_blocks.7."
    },
    joint_blocks_8_: {
      name: "joint_blocks.8."
    },
    joint_blocks_9_: {
      name: "joint_blocks.9."
    },
    model1: {
      name: "model1"
    },
    model2: {
      name: "model2"
    },
    pos_embed_: {
      name: "pos_embed."
    },
    t_embedder_: {
      name: "t_embedder."
    },
    x_embedder_: {
      name: "x_embedder."
    },
    y_embedder_: {
      name: "y_embedder."
    }
  }
};
const ModelMergeSD3_2B$4 = {
  display_name: "ModelMergeSD3_2B",
  inputs: {
    context_embedder_: {
      name: "context_embedder."
    },
    final_layer_: {
      name: "couche_finale."
    },
    joint_blocks_0_: {
      name: "joint_blocks.0."
    },
    joint_blocks_10_: {
      name: "joint_blocks.10."
    },
    joint_blocks_11_: {
      name: "joint_blocks.11."
    },
    joint_blocks_12_: {
      name: "joint_blocks.12."
    },
    joint_blocks_13_: {
      name: "joint_blocks.13."
    },
    joint_blocks_14_: {
      name: "joint_blocks.14."
    },
    joint_blocks_15_: {
      name: "joint_blocks.15."
    },
    joint_blocks_16_: {
      name: "joint_blocks.16."
    },
    joint_blocks_17_: {
      name: "joint_blocks.17."
    },
    joint_blocks_18_: {
      name: "joint_blocks.18."
    },
    joint_blocks_19_: {
      name: "joint_blocks.19."
    },
    joint_blocks_1_: {
      name: "joint_blocks.1."
    },
    joint_blocks_20_: {
      name: "joint_blocks.20."
    },
    joint_blocks_21_: {
      name: "joint_blocks.21."
    },
    joint_blocks_22_: {
      name: "joint_blocks.22."
    },
    joint_blocks_23_: {
      name: "joint_blocks.23."
    },
    joint_blocks_2_: {
      name: "joint_blocks.2."
    },
    joint_blocks_3_: {
      name: "joint_blocks.3."
    },
    joint_blocks_4_: {
      name: "joint_blocks.4."
    },
    joint_blocks_5_: {
      name: "joint_blocks.5."
    },
    joint_blocks_6_: {
      name: "joint_blocks.6."
    },
    joint_blocks_7_: {
      name: "joint_blocks.7."
    },
    joint_blocks_8_: {
      name: "joint_blocks.8."
    },
    joint_blocks_9_: {
      name: "joint_blocks.9."
    },
    model1: {
      name: "modèle1"
    },
    model2: {
      name: "modèle2"
    },
    pos_embed_: {
      name: "pos_embed."
    },
    t_embedder_: {
      name: "t_embedder."
    },
    x_embedder_: {
      name: "x_embedder."
    },
    y_embedder_: {
      name: "y_embedder."
    }
  }
};
const ModelMergeSDXL$4 = {
  display_name: "ModelMergeSDXL",
  inputs: {
    input_blocks_0: {
      name: "input_blocks.0"
    },
    input_blocks_1: {
      name: "input_blocks.1"
    },
    input_blocks_2: {
      name: "input_blocks.2"
    },
    input_blocks_3: {
      name: "input_blocks.3"
    },
    input_blocks_4: {
      name: "input_blocks.4"
    },
    input_blocks_5: {
      name: "input_blocks.5"
    },
    input_blocks_6: {
      name: "input_blocks.6"
    },
    input_blocks_7: {
      name: "input_blocks.7"
    },
    input_blocks_8: {
      name: "input_blocks.8"
    },
    label_emb_: {
      name: "label_emb."
    },
    middle_block_0: {
      name: "middle_block.0"
    },
    middle_block_1: {
      name: "middle_block.1"
    },
    middle_block_2: {
      name: "middle_block.2"
    },
    model1: {
      name: "modèle1"
    },
    model2: {
      name: "modèle2"
    },
    out_: {
      name: "out."
    },
    output_blocks_0: {
      name: "output_blocks.0"
    },
    output_blocks_1: {
      name: "output_blocks.1"
    },
    output_blocks_2: {
      name: "output_blocks.2"
    },
    output_blocks_3: {
      name: "output_blocks.3"
    },
    output_blocks_4: {
      name: "output_blocks.4"
    },
    output_blocks_5: {
      name: "output_blocks.5"
    },
    output_blocks_6: {
      name: "output_blocks.6"
    },
    output_blocks_7: {
      name: "output_blocks.7"
    },
    output_blocks_8: {
      name: "output_blocks.8"
    },
    time_embed_: {
      name: "time_embed."
    }
  }
};
const ModelMergeSimple$4 = {
  display_name: "ModelMergeSimple",
  inputs: {
    model1: {
      name: "modèle1"
    },
    model2: {
      name: "modèle2"
    },
    ratio: {
      name: "ratio"
    }
  }
};
const ModelMergeSubtract$4 = {
  display_name: "ModelMergeSubtract",
  inputs: {
    model1: {
      name: "modèle1"
    },
    model2: {
      name: "modèle2"
    },
    multiplier: {
      name: "multiplicateur"
    }
  }
};
const ModelMergeWAN2_1$4 = {
  description: "Le modèle 1,3B possède 30 blocs, le modèle 14B en possède 40. Le modèle image vers vidéo dispose de l'embedding supplémentaire img_emb.",
  display_name: "ModelMergeWAN2_1",
  inputs: {
    blocks_0_: {
      name: "blocks.0."
    },
    blocks_10_: {
      name: "blocks.10."
    },
    blocks_11_: {
      name: "blocks.11."
    },
    blocks_12_: {
      name: "blocks.12."
    },
    blocks_13_: {
      name: "blocks.13."
    },
    blocks_14_: {
      name: "blocks.14."
    },
    blocks_15_: {
      name: "blocks.15."
    },
    blocks_16_: {
      name: "blocks.16."
    },
    blocks_17_: {
      name: "blocks.17."
    },
    blocks_18_: {
      name: "blocks.18."
    },
    blocks_19_: {
      name: "blocks.19."
    },
    blocks_1_: {
      name: "blocks.1."
    },
    blocks_20_: {
      name: "blocks.20."
    },
    blocks_21_: {
      name: "blocks.21."
    },
    blocks_22_: {
      name: "blocks.22."
    },
    blocks_23_: {
      name: "blocks.23."
    },
    blocks_24_: {
      name: "blocks.24."
    },
    blocks_25_: {
      name: "blocks.25."
    },
    blocks_26_: {
      name: "blocks.26."
    },
    blocks_27_: {
      name: "blocks.27."
    },
    blocks_28_: {
      name: "blocks.28."
    },
    blocks_29_: {
      name: "blocks.29."
    },
    blocks_2_: {
      name: "blocks.2."
    },
    blocks_30_: {
      name: "blocks.30."
    },
    blocks_31_: {
      name: "blocks.31."
    },
    blocks_32_: {
      name: "blocks.32."
    },
    blocks_33_: {
      name: "blocks.33."
    },
    blocks_34_: {
      name: "blocks.34."
    },
    blocks_35_: {
      name: "blocks.35."
    },
    blocks_36_: {
      name: "blocks.36."
    },
    blocks_37_: {
      name: "blocks.37."
    },
    blocks_38_: {
      name: "blocks.38."
    },
    blocks_39_: {
      name: "blocks.39."
    },
    blocks_3_: {
      name: "blocks.3."
    },
    blocks_4_: {
      name: "blocks.4."
    },
    blocks_5_: {
      name: "blocks.5."
    },
    blocks_6_: {
      name: "blocks.6."
    },
    blocks_7_: {
      name: "blocks.7."
    },
    blocks_8_: {
      name: "blocks.8."
    },
    blocks_9_: {
      name: "blocks.9."
    },
    head_: {
      name: "head."
    },
    img_emb_: {
      name: "img_emb."
    },
    model1: {
      name: "model1"
    },
    model2: {
      name: "model2"
    },
    patch_embedding_: {
      name: "patch_embedding."
    },
    text_embedding_: {
      name: "text_embedding."
    },
    time_embedding_: {
      name: "time_embedding."
    },
    time_projection_: {
      name: "time_projection."
    }
  }
};
const ModelSamplingAuraFlow$4 = {
  display_name: "ModelSamplingAuraFlow",
  inputs: {
    model: {
      name: "modèle"
    },
    shift: {
      name: "décalage"
    }
  }
};
const ModelSamplingContinuousEDM$4 = {
  display_name: "ModelSamplingContinuousEDM",
  inputs: {
    model: {
      name: "modèle"
    },
    sampling: {
      name: "échantillonnage"
    },
    sigma_max: {
      name: "sigma_max"
    },
    sigma_min: {
      name: "sigma_min"
    }
  }
};
const ModelSamplingContinuousV$4 = {
  display_name: "ModelSamplingContinuousV",
  inputs: {
    model: {
      name: "modèle"
    },
    sampling: {
      name: "échantillonnage"
    },
    sigma_max: {
      name: "sigma_max"
    },
    sigma_min: {
      name: "sigma_min"
    }
  }
};
const ModelSamplingDiscrete$4 = {
  display_name: "ModèleÉchantillonnageDiscret",
  inputs: {
    model: {
      name: "modèle"
    },
    sampling: {
      name: "échantillonnage"
    },
    zsnr: {
      name: "zsnr"
    }
  }
};
const ModelSamplingFlux$4 = {
  display_name: "ModèleÉchantillonnageFlux",
  inputs: {
    base_shift: {
      name: "décalage_base"
    },
    height: {
      name: "hauteur"
    },
    max_shift: {
      name: "décalage_max"
    },
    model: {
      name: "modèle"
    },
    width: {
      name: "largeur"
    }
  }
};
const ModelSamplingLTXV$4 = {
  display_name: "ModèleÉchantillonnageLTXV",
  inputs: {
    base_shift: {
      name: "décalage_base"
    },
    latent: {
      name: "latent"
    },
    max_shift: {
      name: "décalage_max"
    },
    model: {
      name: "modèle"
    }
  }
};
const ModelSamplingSD3$4 = {
  display_name: "ModèleÉchantillonnageSD3",
  inputs: {
    model: {
      name: "modèle"
    },
    shift: {
      name: "décalage"
    }
  }
};
const ModelSamplingStableCascade$4 = {
  display_name: "ModèleÉchantillonnageStableCascade",
  inputs: {
    model: {
      name: "modèle"
    },
    shift: {
      name: "décalage"
    }
  }
};
const ModelSave$4 = {
  display_name: "ModèleEnregistrer",
  inputs: {
    filename_prefix: {
      name: "préfixe_fichier"
    },
    model: {
      name: "modèle"
    }
  }
};
const Morphology$4 = {
  display_name: "ImageMorphologie",
  inputs: {
    image: {
      name: "image"
    },
    kernel_size: {
      name: "taille_noyau"
    },
    operation: {
      name: "opération"
    }
  }
};
const OpenAIDalle2$4 = {
  description: "Génère des images de façon synchrone via l’endpoint DALL·E 2 d’OpenAI.",
  display_name: "OpenAI DALL·E 2",
  inputs: {
    control_after_generate: {
      name: "contrôle après génération"
    },
    image: {
      name: "image",
      tooltip: "Image de référence optionnelle pour l’édition d’image."
    },
    mask: {
      name: "mask",
      tooltip: "Masque optionnel pour l’inpainting (les zones blanches seront remplacées)"
    },
    n: {
      name: "n",
      tooltip: "Nombre d’images à générer"
    },
    prompt: {
      name: "prompt",
      tooltip: "Invite textuelle pour DALL·E"
    },
    seed: {
      name: "seed",
      tooltip: "pas encore implémenté côté backend"
    },
    size: {
      name: "taille",
      tooltip: "Taille de l’image"
    }
  }
};
const OpenAIDalle3$4 = {
  description: "Génère des images de manière synchrone via l’endpoint DALL·E 3 d’OpenAI.",
  display_name: "OpenAI DALL·E 3",
  inputs: {
    control_after_generate: {
      name: "contrôle après génération"
    },
    prompt: {
      name: "prompt",
      tooltip: "Invite textuelle pour DALL·E"
    },
    quality: {
      name: "qualité",
      tooltip: "Qualité de l’image"
    },
    seed: {
      name: "seed",
      tooltip: "pas encore implémenté côté backend"
    },
    size: {
      name: "taille",
      tooltip: "Taille de l’image"
    },
    style: {
      name: "style",
      tooltip: "Vivid pousse le modèle à générer des images hyper-réalistes et dramatiques. Natural fait produire au modèle des images plus naturelles, moins hyper-réalistes."
    }
  }
};
const OpenAIGPTImage1$4 = {
  description: "Génère des images de manière synchrone via l'endpoint GPT Image 1 d'OpenAI.",
  display_name: "OpenAI GPT Image 1",
  inputs: {
    background: {
      name: "arrière-plan",
      tooltip: "Retourner l'image avec ou sans arrière-plan"
    },
    control_after_generate: {
      name: "contrôle après génération"
    },
    image: {
      name: "image",
      tooltip: "Image de référence optionnelle pour l'édition d'image."
    },
    mask: {
      name: "mask",
      tooltip: "Masque optionnel pour l'inpainting (les zones blanches seront remplacées)"
    },
    n: {
      name: "n",
      tooltip: "Combien d'images générer"
    },
    prompt: {
      name: "prompt",
      tooltip: "Invite textuelle pour GPT Image 1"
    },
    quality: {
      name: "qualité",
      tooltip: "Qualité de l'image, affecte le coût et le temps de génération."
    },
    seed: {
      name: "seed",
      tooltip: "pas encore implémenté côté backend"
    },
    size: {
      name: "taille",
      tooltip: "Taille de l'image"
    }
  }
};
const OptimalStepsScheduler$4 = {
  display_name: "OptimalStepsScheduler",
  inputs: {
    denoise: {
      name: "réduction du bruit"
    },
    model_type: {
      name: "model_type"
    },
    steps: {
      name: "étapes"
    }
  }
};
const PairConditioningCombine$4 = {
  display_name: "Cond Pair Combiner",
  inputs: {
    negative_A: {
      name: "negative_A"
    },
    negative_B: {
      name: "negative_B"
    },
    positive_A: {
      name: "positive_A"
    },
    positive_B: {
      name: "positive_B"
    }
  },
  outputs: {
    "0": {
      name: "positive"
    },
    "1": {
      name: "negative"
    }
  }
};
const PairConditioningSetDefaultCombine$4 = {
  display_name: "Cond Pair Définir Combiner par Défaut",
  inputs: {
    hooks: {
      name: "hooks"
    },
    negative: {
      name: "negative"
    },
    negative_DEFAULT: {
      name: "negative_DEFAULT"
    },
    positive: {
      name: "positive"
    },
    positive_DEFAULT: {
      name: "positive_DEFAULT"
    }
  },
  outputs: {
    "0": {
      name: "positive"
    },
    "1": {
      name: "negative"
    }
  }
};
const PairConditioningSetProperties$4 = {
  display_name: "Cond Pair Définir Propriétés",
  inputs: {
    hooks: {
      name: "hooks"
    },
    mask: {
      name: "masque"
    },
    negative_NEW: {
      name: "negative_NEW"
    },
    positive_NEW: {
      name: "positive_NEW"
    },
    set_cond_area: {
      name: "définir_zone_cond"
    },
    strength: {
      name: "force"
    },
    timesteps: {
      name: "pas_de_temps"
    }
  },
  outputs: {
    "0": {
      name: "positive"
    },
    "1": {
      name: "negative"
    }
  }
};
const PairConditioningSetPropertiesAndCombine$4 = {
  display_name: "Cond Pair Set Props Combine",
  inputs: {
    hooks: {
      name: "crochets"
    },
    mask: {
      name: "masque"
    },
    negative: {
      name: "negative"
    },
    negative_NEW: {
      name: "negative_NEW"
    },
    positive: {
      name: "positive"
    },
    positive_NEW: {
      name: "positive_NEW"
    },
    set_cond_area: {
      name: "set_cond_area"
    },
    strength: {
      name: "force"
    },
    timesteps: {
      name: "pas de temps"
    }
  },
  outputs: {
    "0": {
      name: "positive"
    },
    "1": {
      name: "negative"
    }
  }
};
const PatchModelAddDownscale$4 = {
  display_name: "PatchModelAddDownscale (Kohya Deep Shrink)",
  inputs: {
    block_number: {
      name: "numéro de bloc"
    },
    downscale_after_skip: {
      name: "réduction après saut"
    },
    downscale_factor: {
      name: "facteur de réduction"
    },
    downscale_method: {
      name: "méthode de réduction"
    },
    end_percent: {
      name: "pourcentage de fin"
    },
    model: {
      name: "modèle"
    },
    start_percent: {
      name: "pourcentage de départ"
    },
    upscale_method: {
      name: "méthode d'agrandissement"
    }
  }
};
const PerpNeg$4 = {
  display_name: "Perp-Neg (OBSOLÈTE par PerpNegGuider)",
  inputs: {
    empty_conditioning: {
      name: "conditionnement vide"
    },
    model: {
      name: "modèle"
    },
    neg_scale: {
      name: "échelle nég"
    }
  }
};
const PerpNegGuider$4 = {
  display_name: "PerpNegGuider",
  inputs: {
    cfg: {
      name: "cfg"
    },
    empty_conditioning: {
      name: "conditionnement vide"
    },
    model: {
      name: "modèle"
    },
    neg_scale: {
      name: "échelle nég"
    },
    negative: {
      name: "négative"
    },
    positive: {
      name: "positive"
    }
  }
};
const PerturbedAttentionGuidance$4 = {
  display_name: "PerturbedAttentionGuidance",
  inputs: {
    model: {
      name: "modèle"
    },
    scale: {
      name: "échelle"
    }
  }
};
const PhotoMakerEncode$4 = {
  display_name: "PhotoMakerEncode",
  inputs: {
    clip: {
      name: "clip"
    },
    image: {
      name: "image"
    },
    photomaker: {
      name: "photomaker"
    },
    text: {
      name: "texte"
    }
  }
};
const PhotoMakerLoader$4 = {
  display_name: "PhotoMakerLoader",
  inputs: {
    photomaker_model_name: {
      name: "nom_du_modèle_photomaker"
    }
  }
};
const PikaImageToVideoNode2_2$4 = {
  description: "Envoie une image et une invite à l'API Pika v2.2 pour générer une vidéo.",
  display_name: "Pika Image vers Vidéo",
  inputs: {
    control_after_generate: {
      name: "contrôle après génération"
    },
    duration: {
      name: "durée"
    },
    image: {
      name: "image",
      tooltip: "L'image à convertir en vidéo"
    },
    negative_prompt: {
      name: "invite négative"
    },
    prompt_text: {
      name: "texte de l'invite"
    },
    resolution: {
      name: "résolution"
    },
    seed: {
      name: "graine"
    }
  }
};
const PikaScenesV2_2$4 = {
  description: "Combinez vos images pour créer une vidéo avec les objets qu'elles contiennent. Téléchargez plusieurs images comme ingrédients et générez une vidéo de haute qualité qui les intègre toutes.",
  display_name: "Pika Scenes (Composition Vidéo Image)",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio",
      tooltip: "Rapport d'aspect (largeur / hauteur)"
    },
    control_after_generate: {
      name: "control after generate"
    },
    duration: {
      name: "duration"
    },
    image_ingredient_1: {
      name: "image_ingredient_1",
      tooltip: "Image qui sera utilisée comme ingrédient pour créer une vidéo."
    },
    image_ingredient_2: {
      name: "image_ingredient_2",
      tooltip: "Image qui sera utilisée comme ingrédient pour créer une vidéo."
    },
    image_ingredient_3: {
      name: "image_ingredient_3",
      tooltip: "Image qui sera utilisée comme ingrédient pour créer une vidéo."
    },
    image_ingredient_4: {
      name: "image_ingredient_4",
      tooltip: "Image qui sera utilisée comme ingrédient pour créer une vidéo."
    },
    image_ingredient_5: {
      name: "image_ingredient_5",
      tooltip: "Image qui sera utilisée comme ingrédient pour créer une vidéo."
    },
    ingredients_mode: {
      name: "ingredients_mode"
    },
    negative_prompt: {
      name: "negative_prompt"
    },
    prompt_text: {
      name: "prompt_text"
    },
    resolution: {
      name: "resolution"
    },
    seed: {
      name: "seed"
    }
  }
};
const PikaStartEndFrameNode2_2$4 = {
  description: "Générez une vidéo en combinant votre première et dernière image. Téléversez deux images pour définir les points de départ et d’arrivée, et laissez l’IA créer une transition fluide entre elles.",
  display_name: "Pika Début et Fin d’Image en Vidéo",
  inputs: {
    control_after_generate: {
      name: "contrôle après génération"
    },
    duration: {
      name: "duration"
    },
    image_end: {
      name: "image_end",
      tooltip: "La dernière image à combiner."
    },
    image_start: {
      name: "image_start",
      tooltip: "La première image à combiner."
    },
    negative_prompt: {
      name: "negative_prompt"
    },
    prompt_text: {
      name: "prompt_text"
    },
    resolution: {
      name: "resolution"
    },
    seed: {
      name: "seed"
    }
  }
};
const PikaTextToVideoNode2_2$4 = {
  description: "Envoie une invite textuelle à l'API Pika v2.2 pour générer une vidéo.",
  display_name: "Pika Texte en Vidéo",
  inputs: {
    aspect_ratio: {
      name: "rapport d'aspect",
      tooltip: "Rapport d'aspect (largeur / hauteur)"
    },
    control_after_generate: {
      name: "contrôle après génération"
    },
    duration: {
      name: "durée"
    },
    negative_prompt: {
      name: "invite négative"
    },
    prompt_text: {
      name: "texte de l'invite"
    },
    resolution: {
      name: "résolution"
    },
    seed: {
      name: "graine"
    }
  }
};
const Pikadditions$4 = {
  description: "Ajoutez n'importe quel objet ou image dans votre vidéo. Téléchargez une vidéo et spécifiez ce que vous souhaitez ajouter pour obtenir un résultat parfaitement intégré.",
  display_name: "Pikadditions (Insertion d'objet vidéo)",
  inputs: {
    control_after_generate: {
      name: "contrôle après génération"
    },
    image: {
      name: "image",
      tooltip: "L'image à ajouter à la vidéo."
    },
    negative_prompt: {
      name: "invite négative"
    },
    prompt_text: {
      name: "texte d'invite"
    },
    seed: {
      name: "graine"
    },
    video: {
      name: "vidéo",
      tooltip: "La vidéo à laquelle ajouter une image."
    }
  }
};
const Pikaffects$4 = {
  description: "Générez une vidéo avec un Pikaffect spécifique. Pikaffects pris en charge : Cake-ify, Crumble, Crush, Decapitate, Deflate, Dissolve, Explode, Eye-pop, Inflate, Levitate, Melt, Peel, Poke, Squish, Ta-da, Tear",
  display_name: "Pikaffects (Effets vidéo)",
  inputs: {
    control_after_generate: {
      name: "contrôle après génération"
    },
    image: {
      name: "image",
      tooltip: "L’image de référence à laquelle appliquer le Pikaffect."
    },
    negative_prompt: {
      name: "negative_prompt"
    },
    pikaffect: {
      name: "pikaffect"
    },
    prompt_text: {
      name: "prompt_text"
    },
    seed: {
      name: "seed"
    }
  }
};
const Pikaswaps$4 = {
  description: "Remplacez n’importe quel objet ou région de votre vidéo par une nouvelle image ou un nouvel objet. Définissez les zones à remplacer soit avec un mask, soit avec des coordonnées.",
  display_name: "Pika Swaps (Remplacement d’objet vidéo)",
  inputs: {
    control_after_generate: {
      name: "contrôle après génération"
    },
    image: {
      name: "image",
      tooltip: "L’image utilisée pour remplacer l’objet masqué dans la vidéo."
    },
    mask: {
      name: "mask",
      tooltip: "Utilisez le mask pour définir les zones à remplacer dans la vidéo"
    },
    negative_prompt: {
      name: "invite négative"
    },
    prompt_text: {
      name: "texte d’invite"
    },
    seed: {
      name: "graine"
    },
    video: {
      name: "vidéo",
      tooltip: "La vidéo dans laquelle remplacer un objet."
    }
  }
};
const PixverseImageToVideoNode$4 = {
  description: "Génère des vidéos de manière synchrone à partir du prompt et de la taille de sortie.",
  display_name: "PixVerse Image vers Vidéo",
  inputs: {
    control_after_generate: {
      name: "contrôle après génération"
    },
    duration_seconds: {
      name: "durée_secondes"
    },
    image: {
      name: "image"
    },
    motion_mode: {
      name: "mode_mouvement"
    },
    negative_prompt: {
      name: "prompt_négatif",
      tooltip: "Une description textuelle optionnelle des éléments indésirables sur une image."
    },
    pixverse_template: {
      name: "modèle_pixverse",
      tooltip: "Un modèle optionnel pour influencer le style de génération, créé par le nœud PixVerse Template."
    },
    prompt: {
      name: "prompt",
      tooltip: "Prompt pour la génération de la vidéo"
    },
    quality: {
      name: "qualité"
    },
    seed: {
      name: "graine",
      tooltip: "Graine pour la génération de la vidéo."
    }
  }
};
const PixverseTemplateNode$4 = {
  display_name: "Modèle PixVerse",
  inputs: {
    template: {
      name: "modèle"
    }
  },
  outputs: {
    "0": {
      name: "modèle_pixverse"
    }
  }
};
const PixverseTextToVideoNode$4 = {
  description: "Génère des vidéos de manière synchrone à partir d'un prompt et d'une taille de sortie.",
  display_name: "PixVerse Texte en Vidéo",
  inputs: {
    aspect_ratio: {
      name: "rapport d'aspect"
    },
    control_after_generate: {
      name: "contrôle après génération"
    },
    duration_seconds: {
      name: "durée (secondes)"
    },
    motion_mode: {
      name: "mode de mouvement"
    },
    negative_prompt: {
      name: "prompt négatif",
      tooltip: "Une description textuelle optionnelle des éléments indésirables sur une image."
    },
    pixverse_template: {
      name: "modèle PixVerse",
      tooltip: "Un modèle optionnel pour influencer le style de génération, créé par le nœud Modèle PixVerse."
    },
    prompt: {
      name: "prompt",
      tooltip: "Prompt pour la génération de la vidéo"
    },
    quality: {
      name: "qualité"
    },
    seed: {
      name: "graine",
      tooltip: "Graine pour la génération de la vidéo."
    }
  }
};
const PixverseTransitionVideoNode$4 = {
  description: "Génère des vidéos de manière synchrone selon le prompt et la taille de sortie.",
  display_name: "PixVerse Transition Vidéo",
  inputs: {
    control_after_generate: {
      name: "contrôle après génération"
    },
    duration_seconds: {
      name: "durée (secondes)"
    },
    first_frame: {
      name: "première image"
    },
    last_frame: {
      name: "dernière image"
    },
    motion_mode: {
      name: "mode de mouvement"
    },
    negative_prompt: {
      name: "prompt négatif",
      tooltip: "Une description textuelle optionnelle des éléments indésirables sur une image."
    },
    prompt: {
      name: "prompt",
      tooltip: "Prompt pour la génération de la vidéo"
    },
    quality: {
      name: "qualité"
    },
    seed: {
      name: "seed",
      tooltip: "Seed pour la génération de la vidéo."
    }
  }
};
const PolyexponentialScheduler$4 = {
  display_name: "PolyexponentialScheduler",
  inputs: {
    rho: {
      name: "rho"
    },
    sigma_max: {
      name: "sigma_max"
    },
    sigma_min: {
      name: "sigma_min"
    },
    steps: {
      name: "étapes"
    }
  }
};
const PorterDuffImageComposite$4 = {
  display_name: "Composite d'image Porter-Duff",
  inputs: {
    destination: {
      name: "destination"
    },
    destination_alpha: {
      name: "alpha_destination"
    },
    mode: {
      name: "mode"
    },
    source: {
      name: "source"
    },
    source_alpha: {
      name: "alpha_source"
    }
  }
};
const Preview3D$4 = {
  display_name: "Aperçu 3D",
  inputs: {
    camera_info: {
      name: "informations_de_camera"
    },
    image: {
      name: "image"
    },
    model_file: {
      name: "fichier_modèle"
    }
  }
};
const Preview3DAnimation$4 = {
  display_name: "Aperçu 3D - Animation",
  inputs: {
    camera_info: {
      name: "informations_camera"
    },
    image: {
      name: "image"
    },
    model_file: {
      name: "fichier_modèle"
    }
  }
};
const PreviewAny$4 = {
  display_name: "Aperçu de n'importe quel",
  inputs: {
    preview: {},
    source: {
      name: "source"
    }
  }
};
const PreviewAudio$4 = {
  display_name: "AperçuAudio",
  inputs: {
    audio: {
      name: "audio"
    },
    audioUI: {
      name: "audioUI"
    }
  }
};
const PreviewImage$4 = {
  description: "Enregistre les images d'entrée dans votre répertoire de sortie ComfyUI.",
  display_name: "Aperçu Image",
  inputs: {
    images: {
      name: "images"
    }
  }
};
const PrimitiveBoolean$4 = {
  display_name: "Booléen",
  inputs: {
    value: {
      name: "valeur"
    }
  }
};
const PrimitiveFloat$4 = {
  display_name: "Flottant",
  inputs: {
    value: {
      name: "valeur"
    }
  }
};
const PrimitiveInt$4 = {
  display_name: "Int",
  inputs: {
    control_after_generate: {
      name: "contrôler après génération"
    },
    value: {
      name: "valeur"
    }
  }
};
const PrimitiveString$4 = {
  display_name: "Chaîne",
  inputs: {
    value: {
      name: "valeur"
    }
  }
};
const PrimitiveStringMultiline$4 = {
  display_name: "Chaîne (multiligne)",
  inputs: {
    value: {
      name: "valeur"
    }
  }
};
const QuadrupleCLIPLoader$4 = {
  description: "[Recettes]\n\nhidream : long clip-l, long clip-g, t5xxl, llama_8b_3.1_instruct",
  display_name: "QuadrupleCLIPLoader",
  inputs: {
    clip_name1: {
      name: "clip_name1"
    },
    clip_name2: {
      name: "clip_name2"
    },
    clip_name3: {
      name: "clip_name3"
    },
    clip_name4: {
      name: "clip_name4"
    }
  }
};
const RandomNoise$4 = {
  display_name: "BruitAléatoire",
  inputs: {
    control_after_generate: {
      name: "contrôle après génération"
    },
    noise_seed: {
      name: "graine_de_bruit"
    }
  }
};
const RebatchImages$4 = {
  display_name: "Rebatch Images",
  inputs: {
    batch_size: {
      name: "taille_de_lot"
    },
    images: {
      name: "images"
    }
  }
};
const RebatchLatents$4 = {
  display_name: "Rebatch Latents",
  inputs: {
    batch_size: {
      name: "taille_de_lot"
    },
    latents: {
      name: "latents"
    }
  }
};
const RecraftColorRGB$4 = {
  description: "Créez une couleur Recraft en choisissant des valeurs RGB spécifiques.",
  display_name: "Recraft Couleur RGB",
  inputs: {
    b: {
      name: "b",
      tooltip: "Valeur bleue de la couleur."
    },
    g: {
      name: "g",
      tooltip: "Valeur verte de la couleur."
    },
    r: {
      name: "r",
      tooltip: "Valeur rouge de la couleur."
    },
    recraft_color: {
      name: "recraft_color"
    }
  },
  outputs: {
    "0": {
      name: "recraft_color"
    }
  }
};
const RecraftControls$4 = {
  description: "Créez des contrôles Recraft pour personnaliser la génération Recraft.",
  display_name: "Contrôles Recraft",
  inputs: {
    background_color: {
      name: "couleur_de_fond"
    },
    colors: {
      name: "couleurs"
    }
  },
  outputs: {
    "0": {
      name: "contrôles_recraft"
    }
  }
};
const RecraftCreativeUpscaleNode$4 = {
  description: "Agrandit l'image de manière synchrone.\nAméliore une image matricielle donnée à l'aide de l'outil « creative upscale », augmentant la résolution avec un accent sur l'affinement des petits détails et des visages.",
  display_name: "Recraft Creative Upscale Image",
  inputs: {
    image: {
      name: "image"
    }
  }
};
const RecraftCrispUpscaleNode$4 = {
  description: "Agrandit l’image de façon synchrone.\nAméliore une image matricielle donnée à l’aide de l’outil « crisp upscale », en augmentant la résolution et en rendant l’image plus nette et plus propre.",
  display_name: "Recraft Crisp Upscale Image",
  inputs: {
    image: {
      name: "image"
    }
  }
};
const RecraftImageInpaintingNode$4 = {
  description: "Modifiez l’image selon l’invite et le mask.",
  display_name: "Recraft Image Inpainting",
  inputs: {
    control_after_generate: {
      name: "contrôle après génération"
    },
    image: {
      name: "image"
    },
    mask: {
      name: "mask"
    },
    n: {
      name: "n",
      tooltip: "Nombre d’images à générer."
    },
    negative_prompt: {
      name: "invite négative",
      tooltip: "Une description textuelle optionnelle des éléments indésirables sur une image."
    },
    prompt: {
      name: "invite",
      tooltip: "Invite pour la génération d’image."
    },
    recraft_style: {
      name: "recraft_style"
    },
    seed: {
      name: "seed",
      tooltip: "Seed pour déterminer si le nœud doit être relancé ; les résultats réels sont non déterministes quel que soit le seed."
    }
  }
};
const RecraftImageToImageNode$4 = {
  description: "Modifiez l'image en fonction de l'invite et de l'intensité.",
  display_name: "Recraft Image vers Image",
  inputs: {
    control_after_generate: {
      name: "contrôle après génération"
    },
    image: {
      name: "image"
    },
    n: {
      name: "n",
      tooltip: "Nombre d'images à générer."
    },
    negative_prompt: {
      name: "invite_négative",
      tooltip: "Une description textuelle optionnelle des éléments indésirables sur une image."
    },
    prompt: {
      name: "invite",
      tooltip: "Invite pour la génération d'image."
    },
    recraft_controls: {
      name: "recraft_controls",
      tooltip: "Contrôles supplémentaires optionnels sur la génération via le nœud Recraft Controls."
    },
    recraft_style: {
      name: "recraft_style"
    },
    seed: {
      name: "graine",
      tooltip: "Graine pour déterminer si le nœud doit être relancé ; les résultats réels sont non déterministes, quelle que soit la graine."
    },
    strength: {
      name: "intensité",
      tooltip: "Définit la différence avec l'image originale, doit être comprise entre [0, 1], où 0 signifie presque identique et 1 signifie une similarité très faible."
    }
  }
};
const RecraftRemoveBackgroundNode$4 = {
  description: "Supprime l'arrière-plan de l'image et retourne l'image traitée ainsi que le masque.",
  display_name: "Recraft Remove Background",
  inputs: {
    image: {
      name: "image"
    }
  }
};
const RecraftReplaceBackgroundNode$4 = {
  description: "Remplace l’arrière-plan d’une image, selon l’invite fournie.",
  display_name: "Recraft Remplacer l’arrière-plan",
  inputs: {
    control_after_generate: {
      name: "contrôle après génération"
    },
    image: {
      name: "image"
    },
    n: {
      name: "n",
      tooltip: "Nombre d’images à générer."
    },
    negative_prompt: {
      name: "invite négative",
      tooltip: "Une description textuelle optionnelle des éléments indésirables sur une image."
    },
    prompt: {
      name: "invite",
      tooltip: "Invite pour la génération d’image."
    },
    recraft_style: {
      name: "recraft_style"
    },
    seed: {
      name: "graine",
      tooltip: "Graine pour déterminer si le nœud doit être relancé ; les résultats réels restent non déterministes, quelle que soit la graine."
    }
  }
};
const RecraftStyleV3DigitalIllustration$4 = {
  description: "Sélectionnez le style realistic_image et un sous-style optionnel.",
  display_name: "Style Recraft - Illustration numérique",
  inputs: {
    substyle: {
      name: "sous-style"
    }
  },
  outputs: {
    "0": {
      name: "recraft_style"
    }
  }
};
const RecraftStyleV3InfiniteStyleLibrary$4 = {
  description: "Sélectionnez un style basé sur l'UUID préexistant de la Infinite Style Library de Recraft.",
  display_name: "Recraft Style - Infinite Style Library",
  inputs: {
    style_id: {
      name: "style_id",
      tooltip: "UUID du style provenant de la Infinite Style Library."
    }
  },
  outputs: {
    "0": {
      name: "recraft_style"
    }
  }
};
const RecraftStyleV3LogoRaster$4 = {
  description: "Sélectionnez le style realistic_image et un sous-style optionnel.",
  display_name: "Recraft Style - Logo Raster",
  inputs: {
    substyle: {
      name: "sous-style"
    }
  },
  outputs: {
    "0": {
      name: "recraft_style"
    }
  }
};
const RecraftStyleV3RealisticImage$4 = {
  description: "Sélectionnez le style realistic_image et un sous-style optionnel.",
  display_name: "Recraft Style - Image réaliste",
  inputs: {
    substyle: {
      name: "sous-style"
    }
  },
  outputs: {
    "0": {
      name: "recraft_style"
    }
  }
};
const RecraftTextToImageNode$4 = {
  description: "Génère des images de manière synchrone à partir d'une invite et d'une résolution.",
  display_name: "Recraft Texte en Image",
  inputs: {
    control_after_generate: {
      name: "contrôle après génération"
    },
    n: {
      name: "n",
      tooltip: "Le nombre d'images à générer."
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Une description textuelle optionnelle des éléments indésirables sur une image."
    },
    prompt: {
      name: "prompt",
      tooltip: "Invite pour la génération d'image."
    },
    recraft_controls: {
      name: "recraft_controls",
      tooltip: "Contrôles supplémentaires optionnels sur la génération via le nœud Recraft Controls."
    },
    recraft_style: {
      name: "recraft_style"
    },
    seed: {
      name: "seed",
      tooltip: "Graine pour déterminer si le nœud doit être relancé ; les résultats réels sont non déterministes, quelle que soit la graine."
    },
    size: {
      name: "taille",
      tooltip: "La taille de l'image générée."
    }
  }
};
const RecraftTextToVectorNode$4 = {
  description: "Génère un SVG de manière synchrone à partir du prompt et de la résolution.",
  display_name: "Recraft Texte vers Vecteur",
  inputs: {
    control_after_generate: {
      name: "contrôle après génération"
    },
    n: {
      name: "n",
      tooltip: "Le nombre d'images à générer."
    },
    negative_prompt: {
      name: "prompt négatif",
      tooltip: "Une description textuelle optionnelle des éléments indésirables sur une image."
    },
    prompt: {
      name: "prompt",
      tooltip: "Prompt pour la génération d'image."
    },
    recraft_controls: {
      name: "recraft_controls",
      tooltip: "Contrôles supplémentaires optionnels sur la génération via le nœud Recraft Controls."
    },
    seed: {
      name: "seed",
      tooltip: "Seed pour déterminer si le nœud doit être relancé ; les résultats réels sont non déterministes quel que soit le seed."
    },
    size: {
      name: "taille",
      tooltip: "La taille de l'image générée."
    },
    substyle: {
      name: "sous-style"
    }
  }
};
const RecraftVectorizeImageNode$4 = {
  description: "Génère un SVG de manière synchrone à partir d'une image d'entrée.",
  display_name: "Vectoriser une image avec Recraft",
  inputs: {
    image: {
      name: "image"
    }
  }
};
const RenormCFG$4 = {
  display_name: "RenormCFG",
  inputs: {
    cfg_trunc: {
      name: "cfg_trunc"
    },
    model: {
      name: "modèle"
    },
    renorm_cfg: {
      name: "renorm_cfg"
    }
  }
};
const RepeatImageBatch$4 = {
  display_name: "RépéterLotImage",
  inputs: {
    amount: {
      name: "quantité"
    },
    image: {
      name: "image"
    }
  }
};
const RepeatLatentBatch$4 = {
  display_name: "Répéter Lot Latent",
  inputs: {
    amount: {
      name: "quantité"
    },
    samples: {
      name: "échantillons"
    }
  }
};
const RescaleCFG$4 = {
  display_name: "RescaleCFG",
  inputs: {
    model: {
      name: "modèle"
    },
    multiplier: {
      name: "multiplicateur"
    }
  }
};
const SDTurboScheduler$4 = {
  display_name: "SDTurboScheduler",
  inputs: {
    denoise: {
      name: "débruitage"
    },
    model: {
      name: "modèle"
    },
    steps: {
      name: "étapes"
    }
  }
};
const SD_4XUpscale_Conditioning$4 = {
  display_name: "SD_4XUpscale_Conditioning",
  inputs: {
    images: {
      name: "images"
    },
    negative: {
      name: "négatif"
    },
    noise_augmentation: {
      name: "augmentation_du_bruit"
    },
    positive: {
      name: "positive"
    },
    scale_ratio: {
      name: "ratio_d'échelle"
    }
  },
  outputs: {
    "0": {
      name: "positive"
    },
    "1": {
      name: "négatif"
    },
    "2": {
      name: "latent"
    }
  }
};
const SV3D_Conditioning$4 = {
  display_name: "SV3D_Conditioning",
  inputs: {
    clip_vision: {
      name: "clip_vision"
    },
    elevation: {
      name: "élévation"
    },
    height: {
      name: "hauteur"
    },
    init_image: {
      name: "init_image"
    },
    vae: {
      name: "vae"
    },
    video_frames: {
      name: "cadres_vidéo"
    },
    width: {
      name: "largeur"
    }
  },
  outputs: {
    "0": {
      name: "positif"
    },
    "1": {
      name: "négatif"
    },
    "2": {
      name: "latent"
    }
  }
};
const SVD_img2vid_Conditioning$4 = {
  display_name: "SVD_img2vid_Conditioning",
  inputs: {
    augmentation_level: {
      name: "niveau_d'augmentation"
    },
    clip_vision: {
      name: "clip_vision"
    },
    fps: {
      name: "fps"
    },
    height: {
      name: "hauteur"
    },
    init_image: {
      name: "init_image"
    },
    motion_bucket_id: {
      name: "id_seau_de_mouvement"
    },
    vae: {
      name: "vae"
    },
    video_frames: {
      name: "cadres_vidéo"
    },
    width: {
      name: "largeur"
    }
  },
  outputs: {
    "0": {
      name: "positif"
    },
    "1": {
      name: "négatif"
    },
    "2": {
      name: "latent"
    }
  }
};
const SamplerCustom$4 = {
  display_name: "ÉchantillonneurPersonnalisé",
  inputs: {
    add_noise: {
      name: "ajouter_bruit"
    },
    cfg: {
      name: "cfg"
    },
    control_after_generate: {
      name: "contrôle après génération"
    },
    latent_image: {
      name: "image_latente"
    },
    model: {
      name: "modèle"
    },
    negative: {
      name: "négative"
    },
    noise_seed: {
      name: "graine_de_bruit"
    },
    positive: {
      name: "positive"
    },
    sampler: {
      name: "échantillonneur"
    },
    sigmas: {
      name: "sigmas"
    }
  },
  outputs: {
    "0": {
      name: "sortie"
    },
    "1": {
      name: "sortie_débruitée"
    }
  }
};
const SamplerCustomAdvanced$4 = {
  display_name: "ÉchantillonneurPersonnaliséAvancé",
  inputs: {
    guider: {
      name: "guide"
    },
    latent_image: {
      name: "image_latente"
    },
    noise: {
      name: "bruit"
    },
    sampler: {
      name: "échantillonneur"
    },
    sigmas: {
      name: "sigmas"
    }
  },
  outputs: {
    "0": {
      name: "sortie"
    },
    "1": {
      name: "sortie_débruitée"
    }
  }
};
const SamplerDPMAdaptative$4 = {
  display_name: "SamplerDPMAdaptative",
  inputs: {
    accept_safety: {
      name: "accept_safety"
    },
    atol: {
      name: "atol"
    },
    dcoeff: {
      name: "dcoeff"
    },
    eta: {
      name: "eta"
    },
    h_init: {
      name: "h_init"
    },
    icoeff: {
      name: "icoeff"
    },
    order: {
      name: "ordre"
    },
    pcoeff: {
      name: "pcoeff"
    },
    rtol: {
      name: "rtol"
    },
    s_noise: {
      name: "s_bruit"
    }
  }
};
const SamplerDPMPP_2M_SDE$4 = {
  display_name: "SamplerDPMPP_2M_SDE",
  inputs: {
    eta: {
      name: "eta"
    },
    noise_device: {
      name: "appareil_bruit"
    },
    s_noise: {
      name: "s_bruit"
    },
    solver_type: {
      name: "type_solveur"
    }
  }
};
const SamplerDPMPP_2S_Ancestral$4 = {
  display_name: "SamplerDPMPP_2S_Ancestral",
  inputs: {
    eta: {
      name: "eta"
    },
    s_noise: {
      name: "s_bruit"
    }
  }
};
const SamplerDPMPP_3M_SDE$4 = {
  display_name: "SamplerDPMPP_3M_SDE",
  inputs: {
    eta: {
      name: "eta"
    },
    noise_device: {
      name: "appareil_bruit"
    },
    s_noise: {
      name: "s_bruit"
    }
  }
};
const SamplerDPMPP_SDE$4 = {
  display_name: "SamplerDPMPP_SDE",
  inputs: {
    eta: {
      name: "eta"
    },
    noise_device: {
      name: "appareil_bruit"
    },
    r: {
      name: "r"
    },
    s_noise: {
      name: "s_bruit"
    }
  }
};
const SamplerEulerAncestral$4 = {
  display_name: "SamplerEulerAncestral",
  inputs: {
    eta: {
      name: "eta"
    },
    s_noise: {
      name: "s_bruit"
    }
  }
};
const SamplerEulerAncestralCFGPP$4 = {
  display_name: "SamplerEulerAncestralCFG++",
  inputs: {
    eta: {
      name: "eta"
    },
    s_noise: {
      name: "s_bruit"
    }
  }
};
const SamplerEulerCFGpp$4 = {
  display_name: "SamplerEulerCFG++",
  inputs: {
    version: {
      name: "version"
    }
  }
};
const SamplerLCMUpscale$4 = {
  display_name: "SamplerLCMUpscale",
  inputs: {
    scale_ratio: {
      name: "ratio_échelle"
    },
    scale_steps: {
      name: "étapes_échelle"
    },
    upscale_method: {
      name: "méthode_agrandissement"
    }
  }
};
const SamplerLMS$4 = {
  display_name: "SamplerLMS",
  inputs: {
    order: {
      name: "ordre"
    }
  }
};
const SaveAnimatedPNG$4 = {
  display_name: "EnregistrerPNGAnimé",
  inputs: {
    compress_level: {
      name: "niveau_compression"
    },
    filename_prefix: {
      name: "préfixe_nom_fichier"
    },
    fps: {
      name: "fps"
    },
    images: {
      name: "images"
    }
  }
};
const SaveAnimatedWEBP$4 = {
  display_name: "EnregistrerWEBPAnimé",
  inputs: {
    filename_prefix: {
      name: "préfixe_du_nom_de_fichier"
    },
    fps: {
      name: "fps"
    },
    images: {
      name: "images"
    },
    lossless: {
      name: "sans_perte"
    },
    method: {
      name: "méthode"
    },
    quality: {
      name: "qualité"
    }
  }
};
const SaveAudio$4 = {
  display_name: "EnregistrerAudio",
  inputs: {
    audio: {
      name: "audio"
    },
    audioUI: {
      name: "audioUI"
    },
    filename_prefix: {
      name: "préfixe_du_nom_de_fichier"
    }
  }
};
const SaveGLB$4 = {
  display_name: "SaveGLB",
  inputs: {
    filename_prefix: {
      name: "préfixe_du_nom_de_fichier"
    },
    image: {
      name: "image"
    },
    mesh: {
      name: "maillage"
    }
  }
};
const SaveImage$4 = {
  description: "Enregistre les images d'entrée dans votre répertoire de sortie ComfyUI.",
  display_name: "Enregistrer Image",
  inputs: {
    filename_prefix: {
      name: "préfixe_du_nom_de_fichier",
      tooltip: "Le préfixe pour le fichier à enregistrer. Cela peut inclure des informations de formatage telles que %date:yyyy-MM-dd% ou %Empty Latent Image.width% pour inclure des valeurs à partir de nœuds."
    },
    images: {
      name: "images",
      tooltip: "Les images à enregistrer."
    }
  }
};
const SaveImageWebsocket$4 = {
  display_name: "EnregistrerImageWebsocket",
  inputs: {
    images: {
      name: "images"
    }
  }
};
const SaveLatent$4 = {
  display_name: "EnregistrerLatent",
  inputs: {
    filename_prefix: {
      name: "préfixe_du_nom_de_fichier"
    },
    samples: {
      name: "échantillons"
    }
  }
};
const SaveSVG$4 = {
  description: "Enregistrer les fichiers SVG sur le disque.",
  display_name: "Enregistrer SVG",
  inputs: {
    filename_prefix: {
      name: "préfixe_nom_fichier",
      tooltip: "Le préfixe pour le fichier à enregistrer. Cela peut inclure des informations de formatage telles que %date:yyyy-MM-dd% ou %Empty Latent Image.width% pour inclure des valeurs provenant des nœuds."
    },
    svg: {
      name: "svg"
    }
  }
};
const SaveVideo$4 = {
  description: "Enregistre les images d'entrée dans votre répertoire de sortie ComfyUI.",
  display_name: "Enregistrer la vidéo",
  inputs: {
    codec: {
      name: "codec",
      tooltip: "Le codec à utiliser pour la vidéo."
    },
    filename_prefix: {
      name: "préfixe_nom_fichier",
      tooltip: "Le préfixe du fichier à enregistrer. Cela peut inclure des informations de formatage telles que %date:yyyy-MM-dd% ou %Empty Latent Image.width% pour inclure des valeurs provenant des nœuds."
    },
    format: {
      name: "format",
      tooltip: "Le format sous lequel enregistrer la vidéo."
    },
    video: {
      name: "vidéo",
      tooltip: "La vidéo à enregistrer."
    }
  }
};
const SaveWEBM$4 = {
  display_name: "EnregistrerWEBM",
  inputs: {
    codec: {
      name: "codec"
    },
    crf: {
      name: "crf",
      tooltip: "Un crf plus élevé signifie une qualité inférieure avec une taille de fichier plus petite, un crf plus bas signifie une qualité supérieure avec une taille de fichier plus grande."
    },
    filename_prefix: {
      name: "préfixe_de_nom_de_fichier"
    },
    fps: {
      name: "fps"
    },
    images: {
      name: "images"
    }
  }
};
const SelfAttentionGuidance$4 = {
  display_name: "Guidance d'Auto-Attention",
  inputs: {
    blur_sigma: {
      name: "blur_sigma"
    },
    model: {
      name: "modèle"
    },
    scale: {
      name: "échelle"
    }
  }
};
const SetClipHooks$4 = {
  display_name: "Définir les Crochets CLIP",
  inputs: {
    apply_to_conds: {
      name: "appliquer_à_conds"
    },
    clip: {
      name: "clip"
    },
    hooks: {
      name: "crochets"
    },
    schedule_clip: {
      name: "programmer_clip"
    }
  }
};
const SetFirstSigma$4 = {
  display_name: "DéfinirPremierSigma",
  inputs: {
    sigma: {
      name: "sigma"
    },
    sigmas: {
      name: "sigmas"
    }
  }
};
const SetHookKeyframes$4 = {
  display_name: "Définir les Images Clés de Crochet",
  inputs: {
    hook_kf: {
      name: "crochet_kf"
    },
    hooks: {
      name: "crochets"
    }
  }
};
const SetLatentNoiseMask$4 = {
  display_name: "Définir le Masque de Bruit Latent",
  inputs: {
    mask: {
      name: "masque"
    },
    samples: {
      name: "échantillons"
    }
  }
};
const SetUnionControlNetType$4 = {
  display_name: "Définir le Type de Réseau de Contrôle d'Union",
  inputs: {
    control_net: {
      name: "réseau_de_contrôle"
    },
    type: {
      name: "type"
    }
  }
};
const SkipLayerGuidanceDiT$4 = {
  description: "Version générique du nœud SkipLayerGuidance qui peut être utilisée sur chaque modèle DiT.",
  display_name: "SkipLayerGuidanceDiT",
  inputs: {
    double_layers: {
      name: "double_couches"
    },
    end_percent: {
      name: "pourcentage_de_fin"
    },
    model: {
      name: "modèle"
    },
    rescaling_scale: {
      name: "échelle_de_redimensionnement"
    },
    scale: {
      name: "échelle"
    },
    single_layers: {
      name: "couches_simples"
    },
    start_percent: {
      name: "pourcentage_de_départ"
    }
  }
};
const SkipLayerGuidanceSD3$4 = {
  description: "Version générique du nœud SkipLayerGuidance qui peut être utilisée sur chaque modèle DiT.",
  display_name: "SkipLayerGuidanceSD3",
  inputs: {
    end_percent: {
      name: "pourcentage_de_fin"
    },
    layers: {
      name: "couches"
    },
    model: {
      name: "modèle"
    },
    scale: {
      name: "échelle"
    },
    start_percent: {
      name: "pourcentage_de_départ"
    }
  }
};
const SolidMask$4 = {
  display_name: "SolidMask",
  inputs: {
    height: {
      name: "hauteur"
    },
    value: {
      name: "valeur"
    },
    width: {
      name: "largeur"
    }
  }
};
const SplitImageWithAlpha$4 = {
  display_name: "Diviser l'image avec Alpha",
  inputs: {
    image: {
      name: "image"
    }
  }
};
const SplitSigmas$4 = {
  display_name: "SplitSigmas",
  inputs: {
    sigmas: {
      name: "sigmas"
    },
    step: {
      name: "étape"
    }
  },
  outputs: {
    "0": {
      name: "high_sigmas"
    },
    "1": {
      name: "low_sigmas"
    }
  }
};
const SplitSigmasDenoise$4 = {
  display_name: "SplitSigmasDenoise",
  inputs: {
    denoise: {
      name: "réduction_du_bruit"
    },
    sigmas: {
      name: "sigmas"
    }
  },
  outputs: {
    "0": {
      name: "high_sigmas"
    },
    "1": {
      name: "low_sigmas"
    }
  }
};
const StabilityStableImageSD_3_5Node$4 = {
  description: "Génère des images de manière synchrone à partir d'un prompt et d'une résolution.",
  display_name: "Stability AI Stable Diffusion 3.5 Image",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio",
      tooltip: "Rapport d’aspect de l’image générée."
    },
    cfg_scale: {
      name: "cfg_scale",
      tooltip: "À quel point le processus de diffusion suit strictement le texte du prompt (des valeurs plus élevées rapprochent l’image de votre prompt)."
    },
    control_after_generate: {
      name: "control after generate"
    },
    image: {
      name: "image"
    },
    image_denoise: {
      name: "image_denoise",
      tooltip: "Dénuagement de l’image d’entrée ; 0,0 donne une image identique à l’entrée, 1,0 équivaut à ne pas fournir d’image du tout."
    },
    model: {
      name: "model"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Mots-clés de ce que vous ne souhaitez pas voir dans l’image générée. Il s’agit d’une fonctionnalité avancée."
    },
    prompt: {
      name: "prompt",
      tooltip: "Ce que vous souhaitez voir dans l’image générée. Un prompt fort et descriptif qui définit clairement les éléments, les couleurs et les sujets donnera de meilleurs résultats."
    },
    seed: {
      name: "seed",
      tooltip: "La graine aléatoire utilisée pour créer le bruit."
    },
    style_preset: {
      name: "style_preset",
      tooltip: "Style optionnel souhaité pour l’image générée."
    }
  }
};
const StabilityStableImageUltraNode$4 = {
  description: "Génère des images de manière synchrone à partir d'un prompt et d'une résolution.",
  display_name: "Stability AI Stable Image Ultra",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio",
      tooltip: "Rapport d'aspect de l'image générée."
    },
    control_after_generate: {
      name: "control after generate"
    },
    image: {
      name: "image"
    },
    image_denoise: {
      name: "image_denoise",
      tooltip: "Dénuage de l'image d'entrée ; 0.0 donne une image identique à l'entrée, 1.0 comme si aucune image n'avait été fournie."
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Un texte décrivant ce que vous ne souhaitez pas voir dans l'image générée. Il s'agit d'une fonctionnalité avancée."
    },
    prompt: {
      name: "prompt",
      tooltip: "Ce que vous souhaitez voir dans l'image générée. Un prompt fort et descriptif qui définit clairement les éléments, les couleurs et les sujets donnera de meilleurs résultats. Pour contrôler le poids d'un mot donné, utilisez le format `(mot:poids)`, où `mot` est le mot dont vous souhaitez contrôler le poids et `poids` est une valeur entre 0 et 1. Par exemple : `Le ciel était d'un (bleu:0.3) vif et (vert:0.8)` indiquerait un ciel bleu et vert, mais plus vert que bleu."
    },
    seed: {
      name: "seed",
      tooltip: "La graine aléatoire utilisée pour créer le bruit."
    },
    style_preset: {
      name: "style_preset",
      tooltip: "Style souhaité optionnel de l'image générée."
    }
  }
};
const StabilityUpscaleConservativeNode$4 = {
  description: "Agrandit l’image avec des modifications minimales jusqu’à une résolution 4K.",
  display_name: "Stability AI Upscale Conservateur",
  inputs: {
    control_after_generate: {
      name: "contrôle après génération"
    },
    creativity: {
      name: "créativité",
      tooltip: "Contrôle la probabilité de créer des détails supplémentaires non fortement conditionnés par l’image initiale."
    },
    image: {
      name: "image"
    },
    negative_prompt: {
      name: "prompt négatif",
      tooltip: "Mots-clés de ce que vous ne souhaitez pas voir dans l’image générée. Il s’agit d’une fonctionnalité avancée."
    },
    prompt: {
      name: "prompt",
      tooltip: "Ce que vous souhaitez voir dans l’image générée. Un prompt fort et descriptif, définissant clairement les éléments, couleurs et sujets, donnera de meilleurs résultats."
    },
    seed: {
      name: "seed",
      tooltip: "La graine aléatoire utilisée pour générer le bruit."
    }
  }
};
const StabilityUpscaleCreativeNode$4 = {
  description: "Agrandir l’image avec des modifications minimales jusqu’à une résolution 4K.",
  display_name: "Stability AI Upscale Creative",
  inputs: {
    control_after_generate: {
      name: "contrôle après génération"
    },
    creativity: {
      name: "créativité",
      tooltip: "Contrôle la probabilité de créer des détails supplémentaires non fortement conditionnés par l’image initiale."
    },
    image: {
      name: "image"
    },
    negative_prompt: {
      name: "prompt_négatif",
      tooltip: "Mots-clés de ce que vous ne souhaitez pas voir dans l’image générée. Fonctionnalité avancée."
    },
    prompt: {
      name: "prompt",
      tooltip: "Ce que vous souhaitez voir dans l’image générée. Un prompt fort et descriptif, définissant clairement les éléments, couleurs et sujets, donnera de meilleurs résultats."
    },
    seed: {
      name: "graine",
      tooltip: "La graine aléatoire utilisée pour créer le bruit."
    },
    style_preset: {
      name: "style_prédéfini",
      tooltip: "Style souhaité de l’image générée (optionnel)."
    }
  }
};
const StabilityUpscaleFastNode$4 = {
  description: "Agrandit rapidement une image via un appel à l’API Stability jusqu’à 4x sa taille d’origine ; destiné à l’agrandissement d’images de faible qualité ou compressées.",
  display_name: "Stability AI Agrandissement Rapide",
  inputs: {
    image: {
      name: "image"
    }
  }
};
const StableCascade_EmptyLatentImage$4 = {
  display_name: "StableCascade_EmptyLatentImage",
  inputs: {
    batch_size: {
      name: "taille_du_lot"
    },
    compression: {
      name: "compression"
    },
    height: {
      name: "hauteur"
    },
    width: {
      name: "largeur"
    }
  },
  outputs: {
    "0": {
      name: "stage_c"
    },
    "1": {
      name: "stage_b"
    }
  }
};
const StableCascade_StageB_Conditioning$4 = {
  display_name: "StableCascade_StageB_Conditioning",
  inputs: {
    conditioning: {
      name: "conditionnement"
    },
    stage_c: {
      name: "stage_c"
    }
  }
};
const StableCascade_StageC_VAEEncode$4 = {
  display_name: "StableCascade_StageC_VAEEncode",
  inputs: {
    compression: {
      name: "compression"
    },
    image: {
      name: "image"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "stage_c"
    },
    "1": {
      name: "stage_b"
    }
  }
};
const StableCascade_SuperResolutionControlnet$4 = {
  display_name: "StableCascade_SuperResolutionControlnet",
  inputs: {
    image: {
      name: "image"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "entrée_controlnet"
    },
    "1": {
      name: "étape_c"
    },
    "2": {
      name: "étape_b"
    }
  }
};
const StableZero123_Conditioning$4 = {
  display_name: "StableZero123_Conditioning",
  inputs: {
    azimuth: {
      name: "azimut"
    },
    batch_size: {
      name: "taille_lot"
    },
    clip_vision: {
      name: "clip_vision"
    },
    elevation: {
      name: "élévation"
    },
    height: {
      name: "hauteur"
    },
    init_image: {
      name: "init_image"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "largeur"
    }
  },
  outputs: {
    "0": {
      name: "positif"
    },
    "1": {
      name: "négatif"
    },
    "2": {
      name: "latent"
    }
  }
};
const StableZero123_Conditioning_Batched$4 = {
  display_name: "StableZero123_Conditioning_Batched",
  inputs: {
    azimuth: {
      name: "azimut"
    },
    azimuth_batch_increment: {
      name: "incrément_lot_azimut"
    },
    batch_size: {
      name: "taille_lot"
    },
    clip_vision: {
      name: "clip_vision"
    },
    elevation: {
      name: "élévation"
    },
    elevation_batch_increment: {
      name: "incrément_lot_élévation"
    },
    height: {
      name: "hauteur"
    },
    init_image: {
      name: "init_image"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "largeur"
    }
  },
  outputs: {
    "0": {
      name: "positif"
    },
    "1": {
      name: "négatif"
    },
    "2": {
      name: "latent"
    }
  }
};
const StyleModelApply$4 = {
  display_name: "Appliquer le modèle de style",
  inputs: {
    clip_vision_output: {
      name: "sortie_clip_vision"
    },
    conditioning: {
      name: "conditionnement"
    },
    strength: {
      name: "force"
    },
    strength_type: {
      name: "type_de_force"
    },
    style_model: {
      name: "modèle_de_style"
    }
  }
};
const StyleModelLoader$4 = {
  display_name: "Charger le modèle de style",
  inputs: {
    style_model_name: {
      name: "nom_du_modèle_de_style"
    }
  }
};
const T5TokenizerOptions$4 = {
  display_name: "T5TokenizerOptions",
  inputs: {
    clip: {
      name: "clip"
    },
    min_length: {
      name: "longueur_min"
    },
    min_padding: {
      name: "remplissage_min"
    }
  }
};
const TextEncodeHunyuanVideo_ImageToVideo$4 = {
  display_name: "TextEncodeHunyuanVideo_ImageToVideo",
  inputs: {
    clip: {
      name: "clip"
    },
    clip_vision_output: {
      name: "sortie_vision_clip"
    },
    image_interleave: {
      name: "entrelacement_image",
      tooltip: "À quel point l'image influence les choses par rapport à l'invite de texte. Un nombre plus élevé signifie plus d'influence de l'invite de texte."
    },
    prompt: {
      name: "invite"
    }
  }
};
const ThresholdMask$4 = {
  display_name: "SeuilMasque",
  inputs: {
    mask: {
      name: "masque"
    },
    value: {
      name: "valeur"
    }
  }
};
const TomePatchModel$4 = {
  display_name: "ModèlePatchTome",
  inputs: {
    model: {
      name: "modèle"
    },
    ratio: {
      name: "ratio"
    }
  }
};
const TorchCompileModel$4 = {
  display_name: "ModèleCompilationTorch",
  inputs: {
    backend: {
      name: "backend"
    },
    model: {
      name: "modèle"
    }
  }
};
const TrimVideoLatent$4 = {
  display_name: "TrimVideoLatent",
  inputs: {
    samples: {
      name: "échantillons"
    },
    trim_amount: {
      name: "quantité de découpe"
    }
  }
};
const TripleCLIPLoader$4 = {
  description: "[Recettes]\n\nsd3: clip-l, clip-g, t5",
  display_name: "ChargeurTripleCLIP",
  inputs: {
    clip_name1: {
      name: "nom_clip1"
    },
    clip_name2: {
      name: "nom_clip2"
    },
    clip_name3: {
      name: "nom_clip3"
    }
  }
};
const UNETLoader$4 = {
  display_name: "Charger Modèle Diffusion",
  inputs: {
    unet_name: {
      name: "nom_unet"
    },
    weight_dtype: {
      name: "dtype_poids"
    }
  }
};
const UNetCrossAttentionMultiply$4 = {
  display_name: "UNetMultiplicationAttentionCroisée",
  inputs: {
    k: {
      name: "k"
    },
    model: {
      name: "modèle"
    },
    out: {
      name: "sortie"
    },
    q: {
      name: "q"
    },
    v: {
      name: "v"
    }
  }
};
const UNetSelfAttentionMultiply$4 = {
  display_name: "UNetMultiplicationAutoAttention",
  inputs: {
    k: {
      name: "k"
    },
    model: {
      name: "modèle"
    },
    out: {
      name: "sortie"
    },
    q: {
      name: "q"
    },
    v: {
      name: "v"
    }
  }
};
const UNetTemporalAttentionMultiply$4 = {
  display_name: "UNetTemporalAttentionMultiply",
  inputs: {
    cross_structural: {
      name: "cross_structural"
    },
    cross_temporal: {
      name: "cross_temporal"
    },
    model: {
      name: "modèle"
    },
    self_structural: {
      name: "self_structural"
    },
    self_temporal: {
      name: "self_temporal"
    }
  }
};
const UpscaleModelLoader$4 = {
  display_name: "Charger le modèle de mise à l'échelle",
  inputs: {
    model_name: {
      name: "nom_du_modèle"
    }
  }
};
const VAEDecode$4 = {
  description: "Décode les images latentes en images d'espace de pixels.",
  display_name: "VAE Decode",
  inputs: {
    samples: {
      name: "échantillons",
      tooltip: "Le latent à décoder."
    },
    vae: {
      name: "vae",
      tooltip: "Le modèle VAE utilisé pour le décodage du latent."
    }
  },
  outputs: {
    "0": {
      tooltip: "L'image décodée."
    }
  }
};
const VAEDecodeAudio$4 = {
  display_name: "VAEDecodeAudio",
  inputs: {
    samples: {
      name: "échantillons"
    },
    vae: {
      name: "vae"
    }
  }
};
const VAEDecodeHunyuan3D$4 = {
  display_name: "VAEDecodeHunyuan3D",
  inputs: {
    num_chunks: {
      name: "nombre_de_morceaux"
    },
    octree_resolution: {
      name: "résolution_octree"
    },
    samples: {
      name: "échantillons"
    },
    vae: {
      name: "vae"
    }
  }
};
const VAEDecodeTiled$4 = {
  display_name: "VAE Decode (Tiled)",
  inputs: {
    overlap: {
      name: "chevauchement"
    },
    samples: {
      name: "échantillons"
    },
    temporal_overlap: {
      name: "chevauchement_temporel",
      tooltip: "Uniquement utilisé pour les VAE vidéo : Nombre de trames à chevaucher."
    },
    temporal_size: {
      name: "taille_temporelle",
      tooltip: "Uniquement utilisé pour les VAE vidéo : Nombre de trames à décoder à la fois."
    },
    tile_size: {
      name: "taille_de_tuile"
    },
    vae: {
      name: "vae"
    }
  }
};
const VAEEncode$4 = {
  display_name: "VAE Encode",
  inputs: {
    pixels: {
      name: "pixels"
    },
    vae: {
      name: "vae"
    }
  }
};
const VAEEncodeAudio$4 = {
  display_name: "VAEEncodeAudio",
  inputs: {
    audio: {
      name: "audio"
    },
    vae: {
      name: "vae"
    }
  }
};
const VAEEncodeForInpaint$4 = {
  display_name: "VAE Encode (pour Inpainting)",
  inputs: {
    grow_mask_by: {
      name: "agrandir_masque_par"
    },
    mask: {
      name: "masque"
    },
    pixels: {
      name: "pixels"
    },
    vae: {
      name: "vae"
    }
  }
};
const VAEEncodeTiled$4 = {
  display_name: "VAE Encode (Tiled)",
  inputs: {
    overlap: {
      name: "chevauchement"
    },
    pixels: {
      name: "pixels"
    },
    temporal_overlap: {
      name: "chevauchement_temporel",
      tooltip: "Uniquement utilisé pour les VAE vidéo : Nombre de trames à chevaucher."
    },
    temporal_size: {
      name: "taille_temporelle",
      tooltip: "Uniquement utilisé pour les VAE vidéo : Nombre de trames à encoder à la fois."
    },
    tile_size: {
      name: "taille_de_tuile"
    },
    vae: {
      name: "vae"
    }
  }
};
const VAELoader$4 = {
  display_name: "Charger VAE",
  inputs: {
    vae_name: {
      name: "nom_vae"
    }
  }
};
const VAESave$4 = {
  display_name: "VAESauvegarder",
  inputs: {
    filename_prefix: {
      name: "préfixe_de_fichier"
    },
    vae: {
      name: "vae"
    }
  }
};
const VPScheduler$4 = {
  display_name: "PlanificateurVP",
  inputs: {
    beta_d: {
      name: "beta_d"
    },
    beta_min: {
      name: "beta_min"
    },
    eps_s: {
      name: "eps_s"
    },
    steps: {
      name: "étapes"
    }
  }
};
const VeoVideoGenerationNode$4 = {
  description: "Génère des vidéos à partir de prompts textuels en utilisant l'API Veo de Google",
  display_name: "Génération de vidéo Google Veo2",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio",
      tooltip: "Format d'image de la vidéo générée"
    },
    control_after_generate: {
      name: "control after generate"
    },
    duration_seconds: {
      name: "duration_seconds",
      tooltip: "Durée de la vidéo générée en secondes"
    },
    enhance_prompt: {
      name: "enhance_prompt",
      tooltip: "Améliorer le prompt avec l'aide de l'IA"
    },
    image: {
      name: "image",
      tooltip: "Image de référence optionnelle pour guider la génération vidéo"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Prompt négatif pour indiquer ce qu'il faut éviter dans la vidéo"
    },
    person_generation: {
      name: "person_generation",
      tooltip: "Autoriser la génération de personnes dans la vidéo"
    },
    prompt: {
      name: "prompt",
      tooltip: "Description textuelle de la vidéo"
    },
    seed: {
      name: "seed",
      tooltip: "Graine pour la génération vidéo (0 pour aléatoire)"
    }
  }
};
const VideoLinearCFGGuidance$4 = {
  display_name: "Guidance VideoLinearCFG",
  inputs: {
    min_cfg: {
      name: "min_cfg"
    },
    model: {
      name: "modèle"
    }
  }
};
const VideoTriangleCFGGuidance$4 = {
  display_name: "Guidance VideoTriangleCFG",
  inputs: {
    min_cfg: {
      name: "min_cfg"
    },
    model: {
      name: "modèle"
    }
  }
};
const VoxelToMesh$4 = {
  display_name: "VoxelToMesh",
  inputs: {
    algorithm: {
      name: "algorithme"
    },
    threshold: {
      name: "seuil"
    },
    voxel: {
      name: "voxel"
    }
  }
};
const VoxelToMeshBasic$4 = {
  display_name: "VoxelToMeshBasic",
  inputs: {
    threshold: {
      name: "seuil"
    },
    voxel: {
      name: "voxel"
    }
  }
};
const WanFirstLastFrameToVideo$4 = {
  display_name: "WanFirstLastFrameToVideo",
  inputs: {
    batch_size: {
      name: "taille_du_lot"
    },
    clip_vision_end_image: {
      name: "clip_vision_image_de_fin"
    },
    clip_vision_start_image: {
      name: "clip_vision_image_de_départ"
    },
    end_image: {
      name: "image_de_fin"
    },
    height: {
      name: "hauteur"
    },
    length: {
      name: "longueur"
    },
    negative: {
      name: "négatif"
    },
    positive: {
      name: "positif"
    },
    start_image: {
      name: "image_de_départ"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "largeur"
    }
  },
  outputs: {
    "0": {
      name: "positif"
    },
    "1": {
      name: "négatif"
    },
    "2": {
      name: "latent"
    }
  }
};
const WanFunControlToVideo$4 = {
  display_name: "WanFunControlToVideo",
  inputs: {
    batch_size: {
      name: "taille_du_lot"
    },
    clip_vision_output: {
      name: "clip_vision_output"
    },
    control_video: {
      name: "contrôler_la_vidéo"
    },
    height: {
      name: "hauteur"
    },
    length: {
      name: "longueur"
    },
    negative: {
      name: "négatif"
    },
    positive: {
      name: "positif"
    },
    start_image: {
      name: "image_de_départ"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "largeur"
    }
  },
  outputs: {
    "0": {
      name: "positif"
    },
    "1": {
      name: "négatif"
    },
    "2": {
      name: "latent"
    }
  }
};
const WanFunInpaintToVideo$4 = {
  display_name: "WanFunInpaintToVideo",
  inputs: {
    batch_size: {
      name: "taille_du_lot"
    },
    clip_vision_output: {
      name: "clip_vision_output"
    },
    end_image: {
      name: "image_de_fin"
    },
    height: {
      name: "hauteur"
    },
    length: {
      name: "longueur"
    },
    negative: {
      name: "négatif"
    },
    positive: {
      name: "positif"
    },
    start_image: {
      name: "image_de_départ"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "largeur"
    }
  },
  outputs: {
    "0": {
      name: "positif"
    },
    "1": {
      name: "négatif"
    },
    "2": {
      name: "latent"
    }
  }
};
const WanImageToVideo$4 = {
  display_name: "WanImageVersVidéo",
  inputs: {
    batch_size: {
      name: "taille_du_lot"
    },
    clip_vision_output: {
      name: "sortie_vision_clip"
    },
    height: {
      name: "hauteur"
    },
    length: {
      name: "longueur"
    },
    negative: {
      name: "négatif"
    },
    positive: {
      name: "positive"
    },
    start_image: {
      name: "image_de_départ"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "largeur"
    }
  },
  outputs: {
    "0": {
      name: "positive"
    },
    "1": {
      name: "négatif"
    },
    "2": {
      name: "latent"
    }
  }
};
const WanVaceToVideo$4 = {
  display_name: "WanVaceToVideo",
  inputs: {
    batch_size: {
      name: "taille_lot"
    },
    control_masks: {
      name: "masques_de_contrôle"
    },
    control_video: {
      name: "contrôle_vidéo"
    },
    height: {
      name: "hauteur"
    },
    length: {
      name: "longueur"
    },
    negative: {
      name: "négatif"
    },
    positive: {
      name: "positif"
    },
    reference_image: {
      name: "image_de_référence"
    },
    strength: {
      name: "intensité"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "largeur"
    }
  },
  outputs: {
    "0": {
      name: "positif"
    },
    "1": {
      name: "négatif"
    },
    "2": {
      name: "latent"
    },
    "3": {
      name: "latent_coupé"
    }
  }
};
const WebcamCapture$4 = {
  display_name: "Capture Webcam",
  inputs: {
    capture_on_queue: {
      name: "capture_en_file_d'attente"
    },
    height: {
      name: "hauteur"
    },
    image: {
      name: "image"
    },
    "waiting for camera___": {},
    width: {
      name: "largeur"
    }
  }
};
const unCLIPCheckpointLoader$4 = {
  display_name: "ChargeurPointContrôleunCLIP",
  inputs: {
    ckpt_name: {
      name: "nom_ckpt"
    }
  }
};
const unCLIPConditioning$4 = {
  display_name: "ConditionnementunCLIP",
  inputs: {
    clip_vision_output: {
      name: "sortie_vision_clip"
    },
    conditioning: {
      name: "conditionnement"
    },
    noise_augmentation: {
      name: "augmentation_bruit"
    },
    strength: {
      name: "force"
    }
  }
};
const frNodes = {
  AddNoise: AddNoise$4,
  AlignYourStepsScheduler: AlignYourStepsScheduler$4,
  BasicGuider: BasicGuider$4,
  BasicScheduler: BasicScheduler$4,
  BetaSamplingScheduler: BetaSamplingScheduler$4,
  CFGGuider: CFGGuider$4,
  CFGZeroStar: CFGZeroStar$4,
  CLIPAttentionMultiply: CLIPAttentionMultiply$4,
  CLIPLoader: CLIPLoader$4,
  CLIPMergeAdd: CLIPMergeAdd$4,
  CLIPMergeSimple: CLIPMergeSimple$4,
  CLIPMergeSubtract: CLIPMergeSubtract$4,
  CLIPSave: CLIPSave$4,
  CLIPSetLastLayer: CLIPSetLastLayer$4,
  CLIPTextEncode: CLIPTextEncode$4,
  CLIPTextEncodeControlnet: CLIPTextEncodeControlnet$4,
  CLIPTextEncodeFlux: CLIPTextEncodeFlux$4,
  CLIPTextEncodeHiDream: CLIPTextEncodeHiDream$4,
  CLIPTextEncodeHunyuanDiT: CLIPTextEncodeHunyuanDiT$4,
  CLIPTextEncodeLumina2: CLIPTextEncodeLumina2$4,
  CLIPTextEncodePixArtAlpha: CLIPTextEncodePixArtAlpha$4,
  CLIPTextEncodeSD3: CLIPTextEncodeSD3$4,
  CLIPTextEncodeSDXL: CLIPTextEncodeSDXL$4,
  CLIPTextEncodeSDXLRefiner: CLIPTextEncodeSDXLRefiner$4,
  CLIPVisionEncode: CLIPVisionEncode$4,
  CLIPVisionLoader: CLIPVisionLoader$4,
  Canny: Canny$4,
  CheckpointLoader: CheckpointLoader$4,
  CheckpointLoaderSimple: CheckpointLoaderSimple$4,
  CheckpointSave: CheckpointSave$4,
  CombineHooks2: CombineHooks2$4,
  CombineHooks4: CombineHooks4$4,
  CombineHooks8: CombineHooks8$4,
  ConditioningAverage: ConditioningAverage$4,
  ConditioningCombine: ConditioningCombine$4,
  ConditioningConcat: ConditioningConcat$4,
  ConditioningSetArea: ConditioningSetArea$4,
  ConditioningSetAreaPercentage: ConditioningSetAreaPercentage$4,
  ConditioningSetAreaPercentageVideo: ConditioningSetAreaPercentageVideo$4,
  ConditioningSetAreaStrength: ConditioningSetAreaStrength$4,
  ConditioningSetDefaultCombine: ConditioningSetDefaultCombine$4,
  ConditioningSetMask: ConditioningSetMask$4,
  ConditioningSetProperties: ConditioningSetProperties$4,
  ConditioningSetPropertiesAndCombine: ConditioningSetPropertiesAndCombine$4,
  ConditioningSetTimestepRange: ConditioningSetTimestepRange$4,
  ConditioningStableAudio: ConditioningStableAudio$4,
  ConditioningTimestepsRange: ConditioningTimestepsRange$4,
  ConditioningZeroOut: ConditioningZeroOut$4,
  ControlNetApply: ControlNetApply$4,
  ControlNetApplyAdvanced: ControlNetApplyAdvanced$4,
  ControlNetApplySD3: ControlNetApplySD3$4,
  ControlNetInpaintingAliMamaApply: ControlNetInpaintingAliMamaApply$4,
  ControlNetLoader: ControlNetLoader$4,
  CosmosImageToVideoLatent: CosmosImageToVideoLatent$4,
  CreateHookKeyframe: CreateHookKeyframe$4,
  CreateHookKeyframesFromFloats: CreateHookKeyframesFromFloats$4,
  CreateHookKeyframesInterpolated: CreateHookKeyframesInterpolated$4,
  CreateHookLora: CreateHookLora$4,
  CreateHookLoraModelOnly: CreateHookLoraModelOnly$4,
  CreateHookModelAsLora: CreateHookModelAsLora$4,
  CreateHookModelAsLoraModelOnly: CreateHookModelAsLoraModelOnly$4,
  CreateVideo: CreateVideo$4,
  CropMask: CropMask$4,
  DiffControlNetLoader: DiffControlNetLoader$4,
  DifferentialDiffusion: DifferentialDiffusion$4,
  DiffusersLoader: DiffusersLoader$4,
  DisableNoise: DisableNoise$4,
  DualCFGGuider: DualCFGGuider$4,
  DualCLIPLoader: DualCLIPLoader$4,
  EmptyCosmosLatentVideo: EmptyCosmosLatentVideo$4,
  EmptyHunyuanLatentVideo: EmptyHunyuanLatentVideo$4,
  EmptyImage: EmptyImage$4,
  EmptyLTXVLatentVideo: EmptyLTXVLatentVideo$4,
  EmptyLatentAudio: EmptyLatentAudio$4,
  EmptyLatentHunyuan3Dv2: EmptyLatentHunyuan3Dv2$4,
  EmptyLatentImage: EmptyLatentImage$4,
  EmptyMochiLatentVideo: EmptyMochiLatentVideo$4,
  EmptySD3LatentImage: EmptySD3LatentImage$4,
  ExponentialScheduler: ExponentialScheduler$4,
  ExtendIntermediateSigmas: ExtendIntermediateSigmas$4,
  FeatherMask: FeatherMask$4,
  FlipSigmas: FlipSigmas$4,
  FluxDisableGuidance: FluxDisableGuidance$4,
  FluxGuidance: FluxGuidance$4,
  FluxProCannyNode: FluxProCannyNode$4,
  FluxProDepthNode: FluxProDepthNode$4,
  FluxProExpandNode: FluxProExpandNode$4,
  FluxProFillNode: FluxProFillNode$4,
  FluxProUltraImageNode: FluxProUltraImageNode$4,
  FreSca: FreSca$4,
  FreeU: FreeU$4,
  FreeU_V2: FreeU_V2$4,
  GITSScheduler: GITSScheduler$4,
  GLIGENLoader: GLIGENLoader$4,
  GLIGENTextBoxApply: GLIGENTextBoxApply$4,
  GetVideoComponents: GetVideoComponents$4,
  GrowMask: GrowMask$4,
  Hunyuan3Dv2Conditioning: Hunyuan3Dv2Conditioning$4,
  Hunyuan3Dv2ConditioningMultiView: Hunyuan3Dv2ConditioningMultiView$4,
  HunyuanImageToVideo: HunyuanImageToVideo$4,
  HyperTile: HyperTile$4,
  HypernetworkLoader: HypernetworkLoader$4,
  IdeogramV1: IdeogramV1$4,
  IdeogramV2: IdeogramV2$4,
  IdeogramV3: IdeogramV3$4,
  ImageBatch: ImageBatch$4,
  ImageBlend: ImageBlend$4,
  ImageBlur: ImageBlur$4,
  ImageColorToMask: ImageColorToMask$4,
  ImageCompositeMasked: ImageCompositeMasked$4,
  ImageCrop: ImageCrop$4,
  ImageFromBatch: ImageFromBatch$4,
  ImageInvert: ImageInvert$4,
  ImageOnlyCheckpointLoader: ImageOnlyCheckpointLoader$4,
  ImageOnlyCheckpointSave: ImageOnlyCheckpointSave$4,
  ImagePadForOutpaint: ImagePadForOutpaint$4,
  ImageQuantize: ImageQuantize$4,
  ImageRGBToYUV: ImageRGBToYUV$4,
  ImageScale: ImageScale$4,
  ImageScaleBy: ImageScaleBy$4,
  ImageScaleToTotalPixels: ImageScaleToTotalPixels$4,
  ImageSharpen: ImageSharpen$4,
  ImageToMask: ImageToMask$4,
  ImageUpscaleWithModel: ImageUpscaleWithModel$4,
  ImageYUVToRGB: ImageYUVToRGB$4,
  InpaintModelConditioning: InpaintModelConditioning$4,
  InstructPixToPixConditioning: InstructPixToPixConditioning$4,
  InvertMask: InvertMask$4,
  JoinImageWithAlpha: JoinImageWithAlpha$4,
  KSampler: KSampler$4,
  KSamplerAdvanced: KSamplerAdvanced$4,
  KSamplerSelect: KSamplerSelect$4,
  KarrasScheduler: KarrasScheduler$4,
  KlingCameraControlI2VNode: KlingCameraControlI2VNode$4,
  KlingCameraControlT2VNode: KlingCameraControlT2VNode$4,
  KlingCameraControls: KlingCameraControls$4,
  KlingDualCharacterVideoEffectNode: KlingDualCharacterVideoEffectNode$4,
  KlingImage2VideoNode: KlingImage2VideoNode$4,
  KlingImageGenerationNode: KlingImageGenerationNode$4,
  KlingLipSyncAudioToVideoNode: KlingLipSyncAudioToVideoNode$4,
  KlingLipSyncTextToVideoNode: KlingLipSyncTextToVideoNode$4,
  KlingSingleImageVideoEffectNode: KlingSingleImageVideoEffectNode$4,
  KlingStartEndFrameNode: KlingStartEndFrameNode$4,
  KlingTextToVideoNode: KlingTextToVideoNode$4,
  KlingVideoExtendNode: KlingVideoExtendNode$4,
  KlingVirtualTryOnNode: KlingVirtualTryOnNode$4,
  LTXVAddGuide: LTXVAddGuide$4,
  LTXVConditioning: LTXVConditioning$4,
  LTXVCropGuides: LTXVCropGuides$4,
  LTXVImgToVideo: LTXVImgToVideo$4,
  LTXVPreprocess: LTXVPreprocess$4,
  LTXVScheduler: LTXVScheduler$4,
  LaplaceScheduler: LaplaceScheduler$4,
  LatentAdd: LatentAdd$4,
  LatentApplyOperation: LatentApplyOperation$4,
  LatentApplyOperationCFG: LatentApplyOperationCFG$4,
  LatentBatch: LatentBatch$4,
  LatentBatchSeedBehavior: LatentBatchSeedBehavior$4,
  LatentBlend: LatentBlend$4,
  LatentComposite: LatentComposite$4,
  LatentCompositeMasked: LatentCompositeMasked$4,
  LatentCrop: LatentCrop$4,
  LatentFlip: LatentFlip$4,
  LatentFromBatch: LatentFromBatch$4,
  LatentInterpolate: LatentInterpolate$4,
  LatentMultiply: LatentMultiply$4,
  LatentOperationSharpen: LatentOperationSharpen$4,
  LatentOperationTonemapReinhard: LatentOperationTonemapReinhard$4,
  LatentRotate: LatentRotate$4,
  LatentSubtract: LatentSubtract$4,
  LatentUpscale: LatentUpscale$4,
  LatentUpscaleBy: LatentUpscaleBy$4,
  Load3D: Load3D$4,
  Load3DAnimation: Load3DAnimation$4,
  LoadAudio: LoadAudio$4,
  LoadImage: LoadImage$4,
  LoadImageMask: LoadImageMask$4,
  LoadImageOutput: LoadImageOutput$4,
  LoadLatent: LoadLatent$4,
  LoadVideo: LoadVideo$4,
  LoraLoader: LoraLoader$4,
  LoraLoaderModelOnly: LoraLoaderModelOnly$4,
  LoraSave: LoraSave$4,
  LotusConditioning: LotusConditioning$4,
  LumaConceptsNode: LumaConceptsNode$4,
  LumaImageModifyNode: LumaImageModifyNode$4,
  LumaImageNode: LumaImageNode$4,
  LumaImageToVideoNode: LumaImageToVideoNode$4,
  LumaReferenceNode: LumaReferenceNode$4,
  LumaVideoNode: LumaVideoNode$4,
  Mahiro: Mahiro$4,
  MaskComposite: MaskComposite$4,
  MaskPreview: MaskPreview$4,
  MaskToImage: MaskToImage$4,
  MinimaxImageToVideoNode: MinimaxImageToVideoNode$4,
  MinimaxTextToVideoNode: MinimaxTextToVideoNode$4,
  ModelComputeDtype: ModelComputeDtype$4,
  ModelMergeAdd: ModelMergeAdd$4,
  ModelMergeAuraflow: ModelMergeAuraflow$4,
  ModelMergeBlocks: ModelMergeBlocks$4,
  ModelMergeCosmos14B: ModelMergeCosmos14B$4,
  ModelMergeCosmos7B: ModelMergeCosmos7B$4,
  ModelMergeFlux1: ModelMergeFlux1$4,
  ModelMergeLTXV: ModelMergeLTXV$4,
  ModelMergeMochiPreview: ModelMergeMochiPreview$4,
  ModelMergeSD1: ModelMergeSD1$4,
  ModelMergeSD2: ModelMergeSD2$4,
  ModelMergeSD35_Large: ModelMergeSD35_Large$4,
  ModelMergeSD3_2B: ModelMergeSD3_2B$4,
  ModelMergeSDXL: ModelMergeSDXL$4,
  ModelMergeSimple: ModelMergeSimple$4,
  ModelMergeSubtract: ModelMergeSubtract$4,
  ModelMergeWAN2_1: ModelMergeWAN2_1$4,
  ModelSamplingAuraFlow: ModelSamplingAuraFlow$4,
  ModelSamplingContinuousEDM: ModelSamplingContinuousEDM$4,
  ModelSamplingContinuousV: ModelSamplingContinuousV$4,
  ModelSamplingDiscrete: ModelSamplingDiscrete$4,
  ModelSamplingFlux: ModelSamplingFlux$4,
  ModelSamplingLTXV: ModelSamplingLTXV$4,
  ModelSamplingSD3: ModelSamplingSD3$4,
  ModelSamplingStableCascade: ModelSamplingStableCascade$4,
  ModelSave: ModelSave$4,
  Morphology: Morphology$4,
  OpenAIDalle2: OpenAIDalle2$4,
  OpenAIDalle3: OpenAIDalle3$4,
  OpenAIGPTImage1: OpenAIGPTImage1$4,
  OptimalStepsScheduler: OptimalStepsScheduler$4,
  PairConditioningCombine: PairConditioningCombine$4,
  PairConditioningSetDefaultCombine: PairConditioningSetDefaultCombine$4,
  PairConditioningSetProperties: PairConditioningSetProperties$4,
  PairConditioningSetPropertiesAndCombine: PairConditioningSetPropertiesAndCombine$4,
  PatchModelAddDownscale: PatchModelAddDownscale$4,
  PerpNeg: PerpNeg$4,
  PerpNegGuider: PerpNegGuider$4,
  PerturbedAttentionGuidance: PerturbedAttentionGuidance$4,
  PhotoMakerEncode: PhotoMakerEncode$4,
  PhotoMakerLoader: PhotoMakerLoader$4,
  PikaImageToVideoNode2_2: PikaImageToVideoNode2_2$4,
  PikaScenesV2_2: PikaScenesV2_2$4,
  PikaStartEndFrameNode2_2: PikaStartEndFrameNode2_2$4,
  PikaTextToVideoNode2_2: PikaTextToVideoNode2_2$4,
  Pikadditions: Pikadditions$4,
  Pikaffects: Pikaffects$4,
  Pikaswaps: Pikaswaps$4,
  PixverseImageToVideoNode: PixverseImageToVideoNode$4,
  PixverseTemplateNode: PixverseTemplateNode$4,
  PixverseTextToVideoNode: PixverseTextToVideoNode$4,
  PixverseTransitionVideoNode: PixverseTransitionVideoNode$4,
  PolyexponentialScheduler: PolyexponentialScheduler$4,
  PorterDuffImageComposite: PorterDuffImageComposite$4,
  Preview3D: Preview3D$4,
  Preview3DAnimation: Preview3DAnimation$4,
  PreviewAny: PreviewAny$4,
  PreviewAudio: PreviewAudio$4,
  PreviewImage: PreviewImage$4,
  PrimitiveBoolean: PrimitiveBoolean$4,
  PrimitiveFloat: PrimitiveFloat$4,
  PrimitiveInt: PrimitiveInt$4,
  PrimitiveString: PrimitiveString$4,
  PrimitiveStringMultiline: PrimitiveStringMultiline$4,
  QuadrupleCLIPLoader: QuadrupleCLIPLoader$4,
  RandomNoise: RandomNoise$4,
  RebatchImages: RebatchImages$4,
  RebatchLatents: RebatchLatents$4,
  RecraftColorRGB: RecraftColorRGB$4,
  RecraftControls: RecraftControls$4,
  RecraftCreativeUpscaleNode: RecraftCreativeUpscaleNode$4,
  RecraftCrispUpscaleNode: RecraftCrispUpscaleNode$4,
  RecraftImageInpaintingNode: RecraftImageInpaintingNode$4,
  RecraftImageToImageNode: RecraftImageToImageNode$4,
  RecraftRemoveBackgroundNode: RecraftRemoveBackgroundNode$4,
  RecraftReplaceBackgroundNode: RecraftReplaceBackgroundNode$4,
  RecraftStyleV3DigitalIllustration: RecraftStyleV3DigitalIllustration$4,
  RecraftStyleV3InfiniteStyleLibrary: RecraftStyleV3InfiniteStyleLibrary$4,
  RecraftStyleV3LogoRaster: RecraftStyleV3LogoRaster$4,
  RecraftStyleV3RealisticImage: RecraftStyleV3RealisticImage$4,
  RecraftTextToImageNode: RecraftTextToImageNode$4,
  RecraftTextToVectorNode: RecraftTextToVectorNode$4,
  RecraftVectorizeImageNode: RecraftVectorizeImageNode$4,
  RenormCFG: RenormCFG$4,
  RepeatImageBatch: RepeatImageBatch$4,
  RepeatLatentBatch: RepeatLatentBatch$4,
  RescaleCFG: RescaleCFG$4,
  SDTurboScheduler: SDTurboScheduler$4,
  SD_4XUpscale_Conditioning: SD_4XUpscale_Conditioning$4,
  SV3D_Conditioning: SV3D_Conditioning$4,
  SVD_img2vid_Conditioning: SVD_img2vid_Conditioning$4,
  SamplerCustom: SamplerCustom$4,
  SamplerCustomAdvanced: SamplerCustomAdvanced$4,
  SamplerDPMAdaptative: SamplerDPMAdaptative$4,
  SamplerDPMPP_2M_SDE: SamplerDPMPP_2M_SDE$4,
  SamplerDPMPP_2S_Ancestral: SamplerDPMPP_2S_Ancestral$4,
  SamplerDPMPP_3M_SDE: SamplerDPMPP_3M_SDE$4,
  SamplerDPMPP_SDE: SamplerDPMPP_SDE$4,
  SamplerEulerAncestral: SamplerEulerAncestral$4,
  SamplerEulerAncestralCFGPP: SamplerEulerAncestralCFGPP$4,
  SamplerEulerCFGpp: SamplerEulerCFGpp$4,
  SamplerLCMUpscale: SamplerLCMUpscale$4,
  SamplerLMS: SamplerLMS$4,
  SaveAnimatedPNG: SaveAnimatedPNG$4,
  SaveAnimatedWEBP: SaveAnimatedWEBP$4,
  SaveAudio: SaveAudio$4,
  SaveGLB: SaveGLB$4,
  SaveImage: SaveImage$4,
  SaveImageWebsocket: SaveImageWebsocket$4,
  SaveLatent: SaveLatent$4,
  SaveSVG: SaveSVG$4,
  SaveVideo: SaveVideo$4,
  SaveWEBM: SaveWEBM$4,
  SelfAttentionGuidance: SelfAttentionGuidance$4,
  SetClipHooks: SetClipHooks$4,
  SetFirstSigma: SetFirstSigma$4,
  SetHookKeyframes: SetHookKeyframes$4,
  SetLatentNoiseMask: SetLatentNoiseMask$4,
  SetUnionControlNetType: SetUnionControlNetType$4,
  SkipLayerGuidanceDiT: SkipLayerGuidanceDiT$4,
  SkipLayerGuidanceSD3: SkipLayerGuidanceSD3$4,
  SolidMask: SolidMask$4,
  SplitImageWithAlpha: SplitImageWithAlpha$4,
  SplitSigmas: SplitSigmas$4,
  SplitSigmasDenoise: SplitSigmasDenoise$4,
  StabilityStableImageSD_3_5Node: StabilityStableImageSD_3_5Node$4,
  StabilityStableImageUltraNode: StabilityStableImageUltraNode$4,
  StabilityUpscaleConservativeNode: StabilityUpscaleConservativeNode$4,
  StabilityUpscaleCreativeNode: StabilityUpscaleCreativeNode$4,
  StabilityUpscaleFastNode: StabilityUpscaleFastNode$4,
  StableCascade_EmptyLatentImage: StableCascade_EmptyLatentImage$4,
  StableCascade_StageB_Conditioning: StableCascade_StageB_Conditioning$4,
  StableCascade_StageC_VAEEncode: StableCascade_StageC_VAEEncode$4,
  StableCascade_SuperResolutionControlnet: StableCascade_SuperResolutionControlnet$4,
  StableZero123_Conditioning: StableZero123_Conditioning$4,
  StableZero123_Conditioning_Batched: StableZero123_Conditioning_Batched$4,
  StyleModelApply: StyleModelApply$4,
  StyleModelLoader: StyleModelLoader$4,
  T5TokenizerOptions: T5TokenizerOptions$4,
  TextEncodeHunyuanVideo_ImageToVideo: TextEncodeHunyuanVideo_ImageToVideo$4,
  ThresholdMask: ThresholdMask$4,
  TomePatchModel: TomePatchModel$4,
  TorchCompileModel: TorchCompileModel$4,
  TrimVideoLatent: TrimVideoLatent$4,
  TripleCLIPLoader: TripleCLIPLoader$4,
  UNETLoader: UNETLoader$4,
  UNetCrossAttentionMultiply: UNetCrossAttentionMultiply$4,
  UNetSelfAttentionMultiply: UNetSelfAttentionMultiply$4,
  UNetTemporalAttentionMultiply: UNetTemporalAttentionMultiply$4,
  UpscaleModelLoader: UpscaleModelLoader$4,
  VAEDecode: VAEDecode$4,
  VAEDecodeAudio: VAEDecodeAudio$4,
  VAEDecodeHunyuan3D: VAEDecodeHunyuan3D$4,
  VAEDecodeTiled: VAEDecodeTiled$4,
  VAEEncode: VAEEncode$4,
  VAEEncodeAudio: VAEEncodeAudio$4,
  VAEEncodeForInpaint: VAEEncodeForInpaint$4,
  VAEEncodeTiled: VAEEncodeTiled$4,
  VAELoader: VAELoader$4,
  VAESave: VAESave$4,
  VPScheduler: VPScheduler$4,
  VeoVideoGenerationNode: VeoVideoGenerationNode$4,
  VideoLinearCFGGuidance: VideoLinearCFGGuidance$4,
  VideoTriangleCFGGuidance: VideoTriangleCFGGuidance$4,
  VoxelToMesh: VoxelToMesh$4,
  VoxelToMeshBasic: VoxelToMeshBasic$4,
  WanFirstLastFrameToVideo: WanFirstLastFrameToVideo$4,
  WanFunControlToVideo: WanFunControlToVideo$4,
  WanFunInpaintToVideo: WanFunInpaintToVideo$4,
  WanImageToVideo: WanImageToVideo$4,
  WanVaceToVideo: WanVaceToVideo$4,
  WebcamCapture: WebcamCapture$4,
  unCLIPCheckpointLoader: unCLIPCheckpointLoader$4,
  unCLIPConditioning: unCLIPConditioning$4
};
const Comfy_Canvas_SelectionToolbox$4 = {
  name: "Afficher la boîte à outils de sélection"
};
const Comfy_ConfirmClear$4 = {
  name: "Demander une confirmation lors de l'effacement du flux de travail"
};
const Comfy_DOMClippingEnabled$4 = {
  name: "Activer le découpage des éléments DOM (peut réduire les performances)"
};
const Comfy_DevMode$4 = {
  name: "Activer les options du mode développeur (sauvegarde API, etc.)"
};
const Comfy_DisableFloatRounding$4 = {
  name: "Désactiver l'arrondi par défaut du widget flottant.",
  tooltip: "(nécessite le rechargement de la page) Impossible de désactiver l'arrondi lorsque l'arrondi est défini par le nœud dans le backend."
};
const Comfy_DisableSliders$4 = {
  name: "Désactiver les curseurs du widget de nœud"
};
const Comfy_EditAttention_Delta$4 = {
  name: "Précision Ctrl+haut/bas"
};
const Comfy_EnableTooltips$4 = {
  name: "Activer les infobulles"
};
const Comfy_EnableWorkflowViewRestore$4 = {
  name: "Sauvegarder et restaurer la position et le niveau de zoom du canevas dans les flux de travail"
};
const Comfy_FloatRoundingPrecision$4 = {
  name: "Nombre de décimales pour l'arrondi du widget flottant [0 = auto].",
  tooltip: "(nécessite le rechargement de la page)"
};
const Comfy_Graph_CanvasInfo$4 = {
  name: "Afficher les informations du canevas en bas à gauche (fps, etc.)"
};
const Comfy_Graph_CanvasMenu$4 = {
  name: "Afficher le menu du canevas graphique"
};
const Comfy_Graph_CtrlShiftZoom$4 = {
  name: "Activer le raccourci de zoom rapide (Ctrl + Shift + Glisser)"
};
const Comfy_Graph_LinkMarkers$4 = {
  name: "Marqueurs de point médian du lien",
  options: {
    Arrow: "Flèche",
    Circle: "Cercle",
    None: "Aucun"
  }
};
const Comfy_Graph_ZoomSpeed$4 = {
  name: "Vitesse de zoom du canevas"
};
const Comfy_GroupSelectedNodes_Padding$4 = {
  name: "Marge des nœuds sélectionnés dans le groupe"
};
const Comfy_Group_DoubleClickTitleToEdit$4 = {
  name: "Double-cliquer sur le titre du groupe pour le modifier"
};
const Comfy_LinkRelease_Action$4 = {
  name: "Action lors du relâchement du lien (sans modificateur)",
  options: {
    "context menu": "menu contextuel",
    "no action": "aucune action",
    "search box": "boîte de recherche"
  }
};
const Comfy_LinkRelease_ActionShift$4 = {
  name: "Action lors du relâchement du lien (Shift)",
  options: {
    "context menu": "menu contextuel",
    "no action": "aucune action",
    "search box": "boîte de recherche"
  }
};
const Comfy_LinkRenderMode$4 = {
  name: "Mode de rendu du lien",
  options: {
    Hidden: "Caché",
    Linear: "Linéaire",
    Spline: "Spline",
    Straight: "Droit"
  }
};
const Comfy_Load3D_BackgroundColor$4 = {
  name: "Couleur de fond initiale",
  tooltip: "Contrôle la couleur de fond par défaut de la scène 3D. Ce paramètre détermine l'apparence du fond lors de la création d'un nouveau widget 3D, mais peut être ajusté individuellement pour chaque widget après la création."
};
const Comfy_Load3D_CameraType$4 = {
  name: "Type de Caméra",
  options: {
    orthographic: "orthographique",
    perspective: "perspective"
  },
  tooltip: "Contrôle si la caméra est en perspective ou orthographique par défaut lorsqu'un nouveau widget 3D est créé. Ce défaut peut toujours être basculé individuellement pour chaque widget après sa création."
};
const Comfy_Load3D_LightAdjustmentIncrement$4 = {
  name: "Incrément d'ajustement de la lumière",
  tooltip: "Contrôle la taille de l'incrément lors de l'ajustement de l'intensité lumineuse dans les scènes 3D. Une valeur de pas plus petite permet un contrôle plus précis des ajustements de lumière, tandis qu'une valeur plus grande entraîne des changements plus visibles à chaque ajustement."
};
const Comfy_Load3D_LightIntensity$4 = {
  name: "Intensité lumineuse initiale",
  tooltip: "Définit le niveau de luminosité par défaut de l’éclairage dans la scène 3D. Cette valeur détermine l’intensité avec laquelle les lumières illuminent les objets lors de la création d’un nouveau widget 3D, mais peut être ajustée individuellement pour chaque widget après la création."
};
const Comfy_Load3D_LightIntensityMaximum$4 = {
  name: "Intensité lumineuse maximale",
  tooltip: "Définit la valeur maximale autorisée pour l’intensité lumineuse dans les scènes 3D. Cela fixe la limite supérieure de luminosité pouvant être réglée lors de l’ajustement de l’éclairage dans tout widget 3D."
};
const Comfy_Load3D_LightIntensityMinimum$4 = {
  name: "Intensité lumineuse minimale",
  tooltip: "Définit la valeur minimale autorisée de l’intensité lumineuse pour les scènes 3D. Cela définit la limite inférieure de luminosité pouvant être réglée lors de l’ajustement de l’éclairage dans tout widget 3D."
};
const Comfy_Load3D_ShowGrid$4 = {
  name: "Afficher la Grille",
  tooltip: "Basculer pour afficher la grille par défaut"
};
const Comfy_Load3D_ShowPreview$4 = {
  name: "Afficher l'Aperçu",
  tooltip: "Basculer pour afficher l'aperçu par défaut"
};
const Comfy_Locale$4 = {
  name: "Langue"
};
const Comfy_MaskEditor_BrushAdjustmentSpeed$4 = {
  name: "Multiplicateur de vitesse d'ajustement du pinceau",
  tooltip: "Contrôle la rapidité de changement de la taille et de la dureté du pinceau lors de l'ajustement. Des valeurs plus élevées signifient des changements plus rapides."
};
const Comfy_MaskEditor_UseDominantAxis$4 = {
  name: "Verrouiller l'ajustement du pinceau sur l'axe dominant",
  tooltip: "Lorsqu'il est activé, les ajustements du pinceau n'affecteront que la taille OU la dureté en fonction de la direction dans laquelle vous bougez le plus"
};
const Comfy_MaskEditor_UseNewEditor$4 = {
  name: "Utiliser le nouvel éditeur de masque",
  tooltip: "Passer à la nouvelle interface de l'éditeur de masque"
};
const Comfy_ModelLibrary_AutoLoadAll$4 = {
  name: "Charger automatiquement tous les dossiers de modèles",
  tooltip: "Si vrai, tous les dossiers seront chargés dès que vous ouvrez la bibliothèque de modèles (cela peut causer des retards pendant le chargement). Si faux, les dossiers de modèles de niveau racine ne seront chargés que lorsque vous cliquerez dessus."
};
const Comfy_ModelLibrary_NameFormat$4 = {
  name: "Quel nom afficher dans l'arborescence de la bibliothèque de modèles",
  options: {
    filename: "nom de fichier",
    title: "titre"
  },
  tooltip: 'Sélectionnez "filename" pour afficher une vue simplifiée du nom de fichier brut (sans répertoire ou extension ".safetensors") dans la liste des modèles. Sélectionnez "title" pour afficher le titre configurable des métadonnées du modèle.'
};
const Comfy_NodeBadge_NodeIdBadgeMode$4 = {
  name: "Mode de badge d'identifiant de nœud",
  options: {
    None: "Aucun",
    "Show all": "Afficher tout"
  }
};
const Comfy_NodeBadge_NodeLifeCycleBadgeMode$4 = {
  name: "Mode de badge de cycle de vie du nœud",
  options: {
    None: "Aucun",
    "Show all": "Afficher tout"
  }
};
const Comfy_NodeBadge_NodeSourceBadgeMode$4 = {
  name: "Mode de badge de source de nœud",
  options: {
    "Hide built-in": "Cacher intégré",
    None: "Aucun",
    "Show all": "Afficher tout"
  }
};
const Comfy_NodeSearchBoxImpl$4 = {
  name: "Implémentation de la boîte de recherche de nœud",
  options: {
    "default": "par défaut",
    "litegraph (legacy)": "litegraph (héritage)"
  }
};
const Comfy_NodeSearchBoxImpl_NodePreview$4 = {
  name: "Aperçu du nœud",
  tooltip: "S'applique uniquement à l'implémentation par défaut"
};
const Comfy_NodeSearchBoxImpl_ShowCategory$4 = {
  name: "Afficher la catégorie de nœud dans les résultats de recherche",
  tooltip: "S'applique uniquement à l'implémentation par défaut"
};
const Comfy_NodeSearchBoxImpl_ShowIdName$4 = {
  name: "Afficher le nom de l'identifiant du nœud dans les résultats de recherche",
  tooltip: "S'applique uniquement à l'implémentation par défaut"
};
const Comfy_NodeSearchBoxImpl_ShowNodeFrequency$4 = {
  name: "Afficher la fréquence du nœud dans les résultats de recherche",
  tooltip: "S'applique uniquement à l'implémentation par défaut"
};
const Comfy_NodeSuggestions_number$4 = {
  name: "Nombre de suggestions de nœuds",
  tooltip: "Uniquement pour la boîte de recherche/contexte du menu litegraph"
};
const Comfy_Node_AllowImageSizeDraw$4 = {
  name: "Afficher la largeur × la hauteur sous l'aperçu de l'image"
};
const Comfy_Node_AutoSnapLinkToSlot$4 = {
  name: "Lien d'ancrage automatique à l'emplacement du nœud",
  tooltip: "Lorsque vous faites glisser un lien sur un nœud, le lien se fixe automatiquement à une fente d'entrée viable sur le nœud"
};
const Comfy_Node_BypassAllLinksOnDelete$4 = {
  name: "Conserver tous les liens lors de la suppression de nœuds",
  tooltip: "Lors de la suppression d'un nœud, tentez de reconnecter tous ses liens d'entrée et de sortie (en contournant le nœud supprimé)"
};
const Comfy_Node_DoubleClickTitleToEdit$4 = {
  name: "Double-cliquez sur le titre du nœud pour le modifier"
};
const Comfy_Node_MiddleClickRerouteNode$4 = {
  name: "Le clic du milieu crée un nouveau nœud de réacheminement"
};
const Comfy_Node_Opacity$4 = {
  name: "Opacité du nœud"
};
const Comfy_Node_ShowDeprecated$4 = {
  name: "Afficher les nœuds obsolètes dans la recherche",
  tooltip: "Les nœuds obsolètes sont cachés par défaut dans l'interface utilisateur, mais restent fonctionnels dans les flux de travail existants qui les utilisent."
};
const Comfy_Node_ShowExperimental$4 = {
  name: "Afficher les nœuds expérimentaux dans la recherche",
  tooltip: "Les nœuds expérimentaux sont marqués comme tels dans l'interface utilisateur et peuvent être sujets à des modifications importantes ou à une suppression dans les versions futures. À utiliser avec prudence dans les flux de travail de production"
};
const Comfy_Node_SnapHighlightsNode$4 = {
  name: "Le snap met en évidence le nœud",
  tooltip: "Lorsque vous faites glisser un lien sur un nœud avec une fente d'entrée viable, mettez en évidence le nœud"
};
const Comfy_Pointer_ClickBufferTime$4 = {
  name: "Délai de dérive du clic du pointeur",
  tooltip: "Après avoir appuyé sur un bouton de pointeur, c'est le temps maximum (en millisecondes) que le mouvement du pointeur peut être ignoré.\n\nAide à prévenir que les objets soient déplacés involontairement si le pointeur est déplacé lors du clic."
};
const Comfy_Pointer_ClickDrift$4 = {
  name: "Dérive du clic du pointeur (distance maximale)",
  tooltip: "Si le pointeur se déplace plus que cette distance en maintenant un bouton enfoncé, il est considéré comme un glissement (plutôt qu'un clic).\n\nAide à prévenir que les objets soient déplacés involontairement si le pointeur est déplacé lors du clic."
};
const Comfy_Pointer_DoubleClickTime$4 = {
  name: "Intervalle de double clic (maximum)",
  tooltip: "Le temps maximum en millisecondes entre les deux clics d'un double-clic. Augmenter cette valeur peut aider si les double-clics ne sont parfois pas enregistrés."
};
const Comfy_PreviewFormat$4 = {
  name: "Format de l'image de prévisualisation",
  tooltip: "Lors de l'affichage d'une prévisualisation dans le widget d'image, convertissez-la en une image légère, par exemple webp, jpeg, webp;50, etc."
};
const Comfy_PromptFilename$4 = {
  name: "Demander le nom du fichier lors de l'enregistrement du flux de travail"
};
const Comfy_QueueButton_BatchCountLimit$4 = {
  name: "Limite du nombre de lots",
  tooltip: "Le nombre maximum de tâches ajoutées à la file d'attente en un seul clic de bouton"
};
const Comfy_Queue_MaxHistoryItems$4 = {
  name: "Taille de l'historique de la file d'attente",
  tooltip: "Le nombre maximum de tâches qui s'affichent dans l'historique de la file d'attente."
};
const Comfy_Sidebar_Location$4 = {
  name: "Emplacement de la barre latérale",
  options: {
    left: "gauche",
    right: "droite"
  }
};
const Comfy_Sidebar_Size$4 = {
  name: "Taille de la barre latérale",
  options: {
    normal: "normal",
    small: "petit"
  }
};
const Comfy_Sidebar_UnifiedWidth$4 = {
  name: "Largeur unifiée de la barre latérale"
};
const Comfy_SnapToGrid_GridSize$4 = {
  name: "Taille de la grille d'alignement",
  tooltip: "Lors du déplacement et du redimensionnement des nœuds tout en maintenant shift, ils seront alignés sur la grille, cela contrôle la taille de cette grille."
};
const Comfy_TextareaWidget_FontSize$4 = {
  name: "Taille de la police du widget de zone de texte"
};
const Comfy_TextareaWidget_Spellcheck$4 = {
  name: "Vérification orthographique du widget de zone de texte"
};
const Comfy_TreeExplorer_ItemPadding$4 = {
  name: "Espacement des éléments de l'explorateur d'arborescence"
};
const Comfy_UseNewMenu$4 = {
  name: "Utiliser le nouveau menu",
  options: {
    Bottom: "Bas",
    Disabled: "Désactivé",
    Top: "Haut"
  }
};
const Comfy_Validation_NodeDefs$4 = {
  name: "Valider les définitions de nœuds (lent)",
  tooltip: "Recommandé pour les développeurs de nœuds. Cela validera toutes les définitions de nœuds au démarrage."
};
const Comfy_Validation_Workflows$4 = {
  name: "Valider les flux de travail"
};
const Comfy_WidgetControlMode$4 = {
  name: "Mode de contrôle du widget",
  options: {
    after: "après",
    before: "avant"
  },
  tooltip: "Contrôle quand les valeurs du widget sont mises à jour (randomize/increment/decrement), soit avant que l'invite ne soit mise en file d'attente, soit après."
};
const Comfy_Window_UnloadConfirmation$4 = {
  name: "Afficher une confirmation lors de la fermeture de la fenêtre"
};
const Comfy_Workflow_AutoSave$4 = {
  name: "Auto Sauvegarde",
  options: {
    "after delay": "après délai",
    off: "désactivé"
  }
};
const Comfy_Workflow_AutoSaveDelay$4 = {
  name: "Délai de l'Auto Sauvegarde (ms)",
  tooltip: `S'applique uniquement si l'Auto Sauvegarde est réglée sur "après délai".`
};
const Comfy_Workflow_ConfirmDelete$4 = {
  name: "Afficher une confirmation lors de la suppression des flux de travail"
};
const Comfy_Workflow_Persist$4 = {
  name: "Persiste l'état du flux de travail et restaure lors du (re)chargement de la page"
};
const Comfy_Workflow_ShowMissingModelsWarning$4 = {
  name: "Afficher l'avertissement des modèles manquants"
};
const Comfy_Workflow_ShowMissingNodesWarning$4 = {
  name: "Afficher l'avertissement des nœuds manquants"
};
const Comfy_Workflow_SortNodeIdOnSave$4 = {
  name: "Trier les ID de nœuds lors de l'enregistrement du flux de travail"
};
const Comfy_Workflow_WorkflowTabsPosition$4 = {
  name: "Position des flux de travail ouverts",
  options: {
    Sidebar: "Barre latérale",
    Topbar: "Barre supérieure",
    "Topbar (2nd-row)": "Barre supérieure (2ème rangée)"
  }
};
const LiteGraph_Canvas_LowQualityRenderingZoomThreshold$4 = {
  name: "Seuil de zoom pour le rendu de faible qualité",
  tooltip: "Rendre des formes de faible qualité lorsqu'on est dézoomé"
};
const LiteGraph_Canvas_MaximumFps$4 = {
  name: "FPS maximum",
  tooltip: "Le nombre maximum d'images par seconde que le canevas est autorisé à rendre. Limite l'utilisation du GPU au détriment de la fluidité. Si 0, le taux de rafraîchissement de l'écran est utilisé. Par défaut : 0"
};
const LiteGraph_ContextMenu_Scaling$4 = {
  name: "Mise à l'échelle des menus de widgets combinés de nœuds (listes) lors du zoom"
};
const LiteGraph_Node_DefaultPadding$4 = {
  name: "Toujours réduire les nouveaux nœuds",
  tooltip: "Redimensionner les nœuds à la taille minimale possible lors de leur création. Lorsque cette option est désactivée, un nœud nouvellement ajouté sera légèrement élargi pour afficher les valeurs des widgets."
};
const LiteGraph_Node_TooltipDelay$4 = {
  name: "Délai d'infobulle"
};
const LiteGraph_Pointer_TrackpadGestures$4 = {
  name: "Activer les gestes du trackpad",
  tooltip: "Ce paramètre active le mode trackpad pour le canevas, permettant le zoom par pincement et le déplacement à deux doigts."
};
const LiteGraph_Reroute_SplineOffset$4 = {
  name: "Réacheminement décalage de spline",
  tooltip: "Le point de contrôle de Bézier est décalé par rapport au point central de réacheminement"
};
const pysssss_SnapToGrid$4 = {
  name: "Toujours aligner sur la grille"
};
const frSettings = {
  "Comfy-Desktop_AutoUpdate": {
    name: "Vérifier automatiquement les mises à jour"
  },
  "Comfy-Desktop_SendStatistics": {
    name: "Envoyer des métriques d'utilisation anonymes"
  },
  "Comfy-Desktop_UV_PypiInstallMirror": {
    name: "Miroir d'installation Pypi",
    tooltip: "Miroir d'installation pip par défaut"
  },
  "Comfy-Desktop_UV_PythonInstallMirror": {
    name: "Miroir d'installation Python",
    tooltip: "Les installations Python gérées sont téléchargées depuis le projet Astral python-build-standalone. Cette variable peut être définie sur une URL de miroir pour utiliser une source différente pour les installations Python. L'URL fournie remplacera https://github.com/astral-sh/python-build-standalone/releases/download dans, par exemple, https://github.com/astral-sh/python-build-standalone/releases/download/20240713/cpython-3.12.4%2B20240713-aarch64-apple-darwin-install_only.tar.gz. Les distributions peuvent être lues à partir d'un répertoire local en utilisant le schéma d'URL file://."
  },
  "Comfy-Desktop_UV_TorchInstallMirror": {
    name: "Miroir d'installation Torch",
    tooltip: "Miroir d'installation Pip pour pytorch"
  },
  "Comfy-Desktop_WindowStyle": {
    name: "Style de fenêtre",
    options: {
      custom: "personnalisé",
      "default": "défaut"
    },
    tooltip: "Choisissez l'option personnalisée pour masquer la barre de titre du système"
  },
  Comfy_Canvas_SelectionToolbox: Comfy_Canvas_SelectionToolbox$4,
  Comfy_ConfirmClear: Comfy_ConfirmClear$4,
  Comfy_DOMClippingEnabled: Comfy_DOMClippingEnabled$4,
  Comfy_DevMode: Comfy_DevMode$4,
  Comfy_DisableFloatRounding: Comfy_DisableFloatRounding$4,
  Comfy_DisableSliders: Comfy_DisableSliders$4,
  Comfy_EditAttention_Delta: Comfy_EditAttention_Delta$4,
  Comfy_EnableTooltips: Comfy_EnableTooltips$4,
  Comfy_EnableWorkflowViewRestore: Comfy_EnableWorkflowViewRestore$4,
  Comfy_FloatRoundingPrecision: Comfy_FloatRoundingPrecision$4,
  Comfy_Graph_CanvasInfo: Comfy_Graph_CanvasInfo$4,
  Comfy_Graph_CanvasMenu: Comfy_Graph_CanvasMenu$4,
  Comfy_Graph_CtrlShiftZoom: Comfy_Graph_CtrlShiftZoom$4,
  Comfy_Graph_LinkMarkers: Comfy_Graph_LinkMarkers$4,
  Comfy_Graph_ZoomSpeed: Comfy_Graph_ZoomSpeed$4,
  Comfy_GroupSelectedNodes_Padding: Comfy_GroupSelectedNodes_Padding$4,
  Comfy_Group_DoubleClickTitleToEdit: Comfy_Group_DoubleClickTitleToEdit$4,
  Comfy_LinkRelease_Action: Comfy_LinkRelease_Action$4,
  Comfy_LinkRelease_ActionShift: Comfy_LinkRelease_ActionShift$4,
  Comfy_LinkRenderMode: Comfy_LinkRenderMode$4,
  Comfy_Load3D_BackgroundColor: Comfy_Load3D_BackgroundColor$4,
  Comfy_Load3D_CameraType: Comfy_Load3D_CameraType$4,
  Comfy_Load3D_LightAdjustmentIncrement: Comfy_Load3D_LightAdjustmentIncrement$4,
  Comfy_Load3D_LightIntensity: Comfy_Load3D_LightIntensity$4,
  Comfy_Load3D_LightIntensityMaximum: Comfy_Load3D_LightIntensityMaximum$4,
  Comfy_Load3D_LightIntensityMinimum: Comfy_Load3D_LightIntensityMinimum$4,
  Comfy_Load3D_ShowGrid: Comfy_Load3D_ShowGrid$4,
  Comfy_Load3D_ShowPreview: Comfy_Load3D_ShowPreview$4,
  Comfy_Locale: Comfy_Locale$4,
  Comfy_MaskEditor_BrushAdjustmentSpeed: Comfy_MaskEditor_BrushAdjustmentSpeed$4,
  Comfy_MaskEditor_UseDominantAxis: Comfy_MaskEditor_UseDominantAxis$4,
  Comfy_MaskEditor_UseNewEditor: Comfy_MaskEditor_UseNewEditor$4,
  Comfy_ModelLibrary_AutoLoadAll: Comfy_ModelLibrary_AutoLoadAll$4,
  Comfy_ModelLibrary_NameFormat: Comfy_ModelLibrary_NameFormat$4,
  Comfy_NodeBadge_NodeIdBadgeMode: Comfy_NodeBadge_NodeIdBadgeMode$4,
  Comfy_NodeBadge_NodeLifeCycleBadgeMode: Comfy_NodeBadge_NodeLifeCycleBadgeMode$4,
  Comfy_NodeBadge_NodeSourceBadgeMode: Comfy_NodeBadge_NodeSourceBadgeMode$4,
  Comfy_NodeSearchBoxImpl: Comfy_NodeSearchBoxImpl$4,
  Comfy_NodeSearchBoxImpl_NodePreview: Comfy_NodeSearchBoxImpl_NodePreview$4,
  Comfy_NodeSearchBoxImpl_ShowCategory: Comfy_NodeSearchBoxImpl_ShowCategory$4,
  Comfy_NodeSearchBoxImpl_ShowIdName: Comfy_NodeSearchBoxImpl_ShowIdName$4,
  Comfy_NodeSearchBoxImpl_ShowNodeFrequency: Comfy_NodeSearchBoxImpl_ShowNodeFrequency$4,
  Comfy_NodeSuggestions_number: Comfy_NodeSuggestions_number$4,
  Comfy_Node_AllowImageSizeDraw: Comfy_Node_AllowImageSizeDraw$4,
  Comfy_Node_AutoSnapLinkToSlot: Comfy_Node_AutoSnapLinkToSlot$4,
  Comfy_Node_BypassAllLinksOnDelete: Comfy_Node_BypassAllLinksOnDelete$4,
  Comfy_Node_DoubleClickTitleToEdit: Comfy_Node_DoubleClickTitleToEdit$4,
  Comfy_Node_MiddleClickRerouteNode: Comfy_Node_MiddleClickRerouteNode$4,
  Comfy_Node_Opacity: Comfy_Node_Opacity$4,
  Comfy_Node_ShowDeprecated: Comfy_Node_ShowDeprecated$4,
  Comfy_Node_ShowExperimental: Comfy_Node_ShowExperimental$4,
  Comfy_Node_SnapHighlightsNode: Comfy_Node_SnapHighlightsNode$4,
  Comfy_Pointer_ClickBufferTime: Comfy_Pointer_ClickBufferTime$4,
  Comfy_Pointer_ClickDrift: Comfy_Pointer_ClickDrift$4,
  Comfy_Pointer_DoubleClickTime: Comfy_Pointer_DoubleClickTime$4,
  Comfy_PreviewFormat: Comfy_PreviewFormat$4,
  Comfy_PromptFilename: Comfy_PromptFilename$4,
  Comfy_QueueButton_BatchCountLimit: Comfy_QueueButton_BatchCountLimit$4,
  Comfy_Queue_MaxHistoryItems: Comfy_Queue_MaxHistoryItems$4,
  Comfy_Sidebar_Location: Comfy_Sidebar_Location$4,
  Comfy_Sidebar_Size: Comfy_Sidebar_Size$4,
  Comfy_Sidebar_UnifiedWidth: Comfy_Sidebar_UnifiedWidth$4,
  Comfy_SnapToGrid_GridSize: Comfy_SnapToGrid_GridSize$4,
  Comfy_TextareaWidget_FontSize: Comfy_TextareaWidget_FontSize$4,
  Comfy_TextareaWidget_Spellcheck: Comfy_TextareaWidget_Spellcheck$4,
  Comfy_TreeExplorer_ItemPadding: Comfy_TreeExplorer_ItemPadding$4,
  Comfy_UseNewMenu: Comfy_UseNewMenu$4,
  Comfy_Validation_NodeDefs: Comfy_Validation_NodeDefs$4,
  Comfy_Validation_Workflows: Comfy_Validation_Workflows$4,
  Comfy_WidgetControlMode: Comfy_WidgetControlMode$4,
  Comfy_Window_UnloadConfirmation: Comfy_Window_UnloadConfirmation$4,
  Comfy_Workflow_AutoSave: Comfy_Workflow_AutoSave$4,
  Comfy_Workflow_AutoSaveDelay: Comfy_Workflow_AutoSaveDelay$4,
  Comfy_Workflow_ConfirmDelete: Comfy_Workflow_ConfirmDelete$4,
  Comfy_Workflow_Persist: Comfy_Workflow_Persist$4,
  Comfy_Workflow_ShowMissingModelsWarning: Comfy_Workflow_ShowMissingModelsWarning$4,
  Comfy_Workflow_ShowMissingNodesWarning: Comfy_Workflow_ShowMissingNodesWarning$4,
  Comfy_Workflow_SortNodeIdOnSave: Comfy_Workflow_SortNodeIdOnSave$4,
  Comfy_Workflow_WorkflowTabsPosition: Comfy_Workflow_WorkflowTabsPosition$4,
  LiteGraph_Canvas_LowQualityRenderingZoomThreshold: LiteGraph_Canvas_LowQualityRenderingZoomThreshold$4,
  LiteGraph_Canvas_MaximumFps: LiteGraph_Canvas_MaximumFps$4,
  LiteGraph_ContextMenu_Scaling: LiteGraph_ContextMenu_Scaling$4,
  LiteGraph_Node_DefaultPadding: LiteGraph_Node_DefaultPadding$4,
  LiteGraph_Node_TooltipDelay: LiteGraph_Node_TooltipDelay$4,
  LiteGraph_Pointer_TrackpadGestures: LiteGraph_Pointer_TrackpadGestures$4,
  LiteGraph_Reroute_SplineOffset: LiteGraph_Reroute_SplineOffset$4,
  pysssss_SnapToGrid: pysssss_SnapToGrid$4
};
const Comfy_BrowseTemplates$3 = {
  label: "テンプレートを参照"
};
const Comfy_Canvas_DeleteSelectedItems$3 = {
  label: "選択したアイテムを削除"
};
const Comfy_Canvas_FitView$3 = {
  label: "選択したノードにビューを合わせる"
};
const Comfy_Canvas_ResetView$3 = {
  label: "ビューをリセット"
};
const Comfy_Canvas_Resize$3 = {
  label: "選択したノードのサイズ変更"
};
const Comfy_Canvas_ToggleLinkVisibility$3 = {
  label: "キャンバスのリンク表示を切り替える"
};
const Comfy_Canvas_ToggleLock$3 = {
  label: "キャンバスのロックを切り替える"
};
const Comfy_Canvas_ToggleSelectedNodes_Bypass$3 = {
  label: "選択したノードのバイパス/バイパス解除"
};
const Comfy_Canvas_ToggleSelectedNodes_Collapse$3 = {
  label: "選択したノードの折りたたみ/展開"
};
const Comfy_Canvas_ToggleSelectedNodes_Mute$3 = {
  label: "選択したノードのミュート/ミュート解除"
};
const Comfy_Canvas_ToggleSelectedNodes_Pin$3 = {
  label: "選択したノードのピン留め/ピン留め解除"
};
const Comfy_Canvas_ToggleSelected_Pin$3 = {
  label: "選択したアイテムのピン留め/ピン留め解除"
};
const Comfy_Canvas_ZoomIn$3 = {
  label: "ズームイン"
};
const Comfy_Canvas_ZoomOut$3 = {
  label: "ズームアウト"
};
const Comfy_ClearPendingTasks$3 = {
  label: "保留中のタスクをクリア"
};
const Comfy_ClearWorkflow$3 = {
  label: "ワークフローをクリア"
};
const Comfy_ContactSupport$3 = {
  label: "サポートに連絡"
};
const Comfy_DuplicateWorkflow$3 = {
  label: "現在のワークフローを複製"
};
const Comfy_ExportWorkflow$3 = {
  label: "ワークフローをエクスポート"
};
const Comfy_ExportWorkflowAPI$3 = {
  label: "ワークフローをエクスポート（API形式）"
};
const Comfy_Feedback$3 = {
  label: "フィードバック"
};
const Comfy_Graph_FitGroupToContents$3 = {
  label: "グループを内容に合わせて調整"
};
const Comfy_Graph_GroupSelectedNodes$3 = {
  label: "選択したノードをグループ化"
};
const Comfy_GroupNode_ConvertSelectedNodesToGroupNode$3 = {
  label: "選択したノードをグループノードに変換"
};
const Comfy_GroupNode_ManageGroupNodes$3 = {
  label: "グループノードの管理"
};
const Comfy_GroupNode_UngroupSelectedGroupNodes$3 = {
  label: "選択したグループノードのグループ解除"
};
const Comfy_Help_AboutComfyUI$3 = {
  label: "ComfyUIについてを開く"
};
const Comfy_Help_OpenComfyOrgDiscord$3 = {
  label: "Comfy-OrgのDiscordを開く"
};
const Comfy_Help_OpenComfyUIDocs$3 = {
  label: "ComfyUIのドキュメントを開く"
};
const Comfy_Help_OpenComfyUIForum$3 = {
  label: "Comfy-Orgフォーラムを開く"
};
const Comfy_Help_OpenComfyUIIssues$3 = {
  label: "ComfyUIの問題を開く"
};
const Comfy_Interrupt$3 = {
  label: "中断"
};
const Comfy_LoadDefaultWorkflow$3 = {
  label: "デフォルトのワークフローを読み込む"
};
const Comfy_Manager_CustomNodesManager$3 = {
  label: "カスタムノードマネージャ"
};
const Comfy_Manager_ToggleManagerProgressDialog$3 = {
  label: "プログレスダイアログの切り替え"
};
const Comfy_NewBlankWorkflow$3 = {
  label: "新しい空のワークフロー"
};
const Comfy_OpenClipspace$3 = {
  label: "クリップスペース"
};
const Comfy_OpenWorkflow$3 = {
  label: "ワークフローを開く"
};
const Comfy_QueuePrompt$3 = {
  label: "キュープロンプト"
};
const Comfy_QueuePromptFront$3 = {
  label: "キュープロンプト（フロント）"
};
const Comfy_QueueSelectedOutputNodes$3 = {
  label: "選択した出力ノードをキューに追加"
};
const Comfy_Redo$3 = {
  label: "やり直す"
};
const Comfy_RefreshNodeDefinitions$3 = {
  label: "ノード定義を更新"
};
const Comfy_SaveWorkflow$3 = {
  label: "ワークフローを保存する"
};
const Comfy_SaveWorkflowAs$3 = {
  label: "名前を付けてワークフローを保存"
};
const Comfy_ShowSettingsDialog$3 = {
  label: "設定ダイアログを表示"
};
const Comfy_ToggleTheme$3 = {
  label: "テーマの切り替え（ダーク/ライト）"
};
const Comfy_Undo$3 = {
  label: "元に戻す"
};
const Comfy_User_OpenSignInDialog$3 = {
  label: "サインインダイアログを開く"
};
const Comfy_User_SignOut$3 = {
  label: "サインアウト"
};
const Workspace_CloseWorkflow$3 = {
  label: "現在のワークフローを閉じる"
};
const Workspace_NextOpenedWorkflow$3 = {
  label: "次の開いたワークフロー"
};
const Workspace_PreviousOpenedWorkflow$3 = {
  label: "前の開いたワークフロー"
};
const Workspace_SearchBox_Toggle$3 = {
  label: "検索ボックスの切り替え"
};
const Workspace_ToggleBottomPanel$3 = {
  label: "パネル下部の切り替え"
};
const Workspace_ToggleFocusMode$3 = {
  label: "フォーカスモードの切り替え"
};
const Workspace_ToggleSidebarTab_queue$3 = {
  label: "キューサイドバーの切り替え",
  tooltip: "キュー"
};
const Workspace_ToggleSidebarTab_workflows$3 = {
  label: "ワークフローサイドバーの切り替え",
  tooltip: "ワークフロー"
};
const jaCommands = {
  "Comfy-Desktop_CheckForUpdates": {
    label: "更新を確認する"
  },
  "Comfy-Desktop_Folders_OpenCustomNodesFolder": {
    label: "カスタムノードフォルダを開く"
  },
  "Comfy-Desktop_Folders_OpenInputsFolder": {
    label: "入力フォルダを開く"
  },
  "Comfy-Desktop_Folders_OpenLogsFolder": {
    label: "ログフォルダを開く"
  },
  "Comfy-Desktop_Folders_OpenModelConfig": {
    label: "extra_model_paths.yamlを開く"
  },
  "Comfy-Desktop_Folders_OpenModelsFolder": {
    label: "モデルフォルダを開く"
  },
  "Comfy-Desktop_Folders_OpenOutputsFolder": {
    label: "出力フォルダを開く"
  },
  "Comfy-Desktop_OpenDevTools": {
    label: "DevToolsを開く"
  },
  "Comfy-Desktop_OpenUserGuide": {
    label: "デスクトップユーザーガイド"
  },
  "Comfy-Desktop_Quit": {
    label: "終了"
  },
  "Comfy-Desktop_Reinstall": {
    label: "再インストール"
  },
  "Comfy-Desktop_Restart": {
    label: "再起動"
  },
  Comfy_BrowseTemplates: Comfy_BrowseTemplates$3,
  Comfy_Canvas_DeleteSelectedItems: Comfy_Canvas_DeleteSelectedItems$3,
  Comfy_Canvas_FitView: Comfy_Canvas_FitView$3,
  Comfy_Canvas_ResetView: Comfy_Canvas_ResetView$3,
  Comfy_Canvas_Resize: Comfy_Canvas_Resize$3,
  Comfy_Canvas_ToggleLinkVisibility: Comfy_Canvas_ToggleLinkVisibility$3,
  Comfy_Canvas_ToggleLock: Comfy_Canvas_ToggleLock$3,
  Comfy_Canvas_ToggleSelectedNodes_Bypass: Comfy_Canvas_ToggleSelectedNodes_Bypass$3,
  Comfy_Canvas_ToggleSelectedNodes_Collapse: Comfy_Canvas_ToggleSelectedNodes_Collapse$3,
  Comfy_Canvas_ToggleSelectedNodes_Mute: Comfy_Canvas_ToggleSelectedNodes_Mute$3,
  Comfy_Canvas_ToggleSelectedNodes_Pin: Comfy_Canvas_ToggleSelectedNodes_Pin$3,
  Comfy_Canvas_ToggleSelected_Pin: Comfy_Canvas_ToggleSelected_Pin$3,
  Comfy_Canvas_ZoomIn: Comfy_Canvas_ZoomIn$3,
  Comfy_Canvas_ZoomOut: Comfy_Canvas_ZoomOut$3,
  Comfy_ClearPendingTasks: Comfy_ClearPendingTasks$3,
  Comfy_ClearWorkflow: Comfy_ClearWorkflow$3,
  Comfy_ContactSupport: Comfy_ContactSupport$3,
  Comfy_DuplicateWorkflow: Comfy_DuplicateWorkflow$3,
  Comfy_ExportWorkflow: Comfy_ExportWorkflow$3,
  Comfy_ExportWorkflowAPI: Comfy_ExportWorkflowAPI$3,
  Comfy_Feedback: Comfy_Feedback$3,
  Comfy_Graph_FitGroupToContents: Comfy_Graph_FitGroupToContents$3,
  Comfy_Graph_GroupSelectedNodes: Comfy_Graph_GroupSelectedNodes$3,
  Comfy_GroupNode_ConvertSelectedNodesToGroupNode: Comfy_GroupNode_ConvertSelectedNodesToGroupNode$3,
  Comfy_GroupNode_ManageGroupNodes: Comfy_GroupNode_ManageGroupNodes$3,
  Comfy_GroupNode_UngroupSelectedGroupNodes: Comfy_GroupNode_UngroupSelectedGroupNodes$3,
  Comfy_Help_AboutComfyUI: Comfy_Help_AboutComfyUI$3,
  Comfy_Help_OpenComfyOrgDiscord: Comfy_Help_OpenComfyOrgDiscord$3,
  Comfy_Help_OpenComfyUIDocs: Comfy_Help_OpenComfyUIDocs$3,
  Comfy_Help_OpenComfyUIForum: Comfy_Help_OpenComfyUIForum$3,
  Comfy_Help_OpenComfyUIIssues: Comfy_Help_OpenComfyUIIssues$3,
  Comfy_Interrupt: Comfy_Interrupt$3,
  Comfy_LoadDefaultWorkflow: Comfy_LoadDefaultWorkflow$3,
  Comfy_Manager_CustomNodesManager: Comfy_Manager_CustomNodesManager$3,
  Comfy_Manager_ToggleManagerProgressDialog: Comfy_Manager_ToggleManagerProgressDialog$3,
  Comfy_NewBlankWorkflow: Comfy_NewBlankWorkflow$3,
  Comfy_OpenClipspace: Comfy_OpenClipspace$3,
  Comfy_OpenWorkflow: Comfy_OpenWorkflow$3,
  Comfy_QueuePrompt: Comfy_QueuePrompt$3,
  Comfy_QueuePromptFront: Comfy_QueuePromptFront$3,
  Comfy_QueueSelectedOutputNodes: Comfy_QueueSelectedOutputNodes$3,
  Comfy_Redo: Comfy_Redo$3,
  Comfy_RefreshNodeDefinitions: Comfy_RefreshNodeDefinitions$3,
  Comfy_SaveWorkflow: Comfy_SaveWorkflow$3,
  Comfy_SaveWorkflowAs: Comfy_SaveWorkflowAs$3,
  Comfy_ShowSettingsDialog: Comfy_ShowSettingsDialog$3,
  Comfy_ToggleTheme: Comfy_ToggleTheme$3,
  Comfy_Undo: Comfy_Undo$3,
  Comfy_User_OpenSignInDialog: Comfy_User_OpenSignInDialog$3,
  Comfy_User_SignOut: Comfy_User_SignOut$3,
  Workspace_CloseWorkflow: Workspace_CloseWorkflow$3,
  Workspace_NextOpenedWorkflow: Workspace_NextOpenedWorkflow$3,
  Workspace_PreviousOpenedWorkflow: Workspace_PreviousOpenedWorkflow$3,
  Workspace_SearchBox_Toggle: Workspace_SearchBox_Toggle$3,
  Workspace_ToggleBottomPanel: Workspace_ToggleBottomPanel$3,
  "Workspace_ToggleBottomPanelTab_command-terminal": {
    label: "ターミナルパネル下部の切り替え"
  },
  "Workspace_ToggleBottomPanelTab_logs-terminal": {
    label: "ログパネル下部の切り替え"
  },
  Workspace_ToggleFocusMode: Workspace_ToggleFocusMode$3,
  "Workspace_ToggleSidebarTab_model-library": {
    label: "モデルライブラリサイドバーの切り替え",
    tooltip: "モデルライブラリ"
  },
  "Workspace_ToggleSidebarTab_node-library": {
    label: "ノードライブラリサイドバーの切り替え",
    tooltip: "ノードライブラリ"
  },
  Workspace_ToggleSidebarTab_queue: Workspace_ToggleSidebarTab_queue$3,
  Workspace_ToggleSidebarTab_workflows: Workspace_ToggleSidebarTab_workflows$3
};
const apiNodesCostBreakdown$3 = {
  costPerRun: "実行あたりのコスト",
  title: "APIノード",
  totalCost: "合計コスト"
};
const apiNodesNews$3 = {
  introducing: "紹介",
  steps: {
    step1: {
      subtitle: "設定 > ユーザー > ログイン",
      title: "ログイン／アカウント作成："
    },
    step2: {
      subtitle: "設定 > クレジット > クレジットを購入",
      title: "クレジットを購入："
    },
    step3: {
      title: "「APIノード」セクションで新しいAPIノードを見つけてキャンバスに追加"
    },
    step4: {
      title: "実行！"
    }
  },
  subtitle: "すべての外部モデルがComfyUIで利用可能になりました"
};
const apiNodesSignInDialog$3 = {
  message: "このワークフローにはAPIノードが含まれており、実行するためにはアカウントにサインインする必要があります。",
  title: "APIノードを使用するためにはサインインが必要です"
};
const auth$3 = {
  apiKey: {
    cleared: "APIキーが削除されました",
    clearedDetail: "APIキーが正常に削除されました",
    description: "Comfy APIキーを使用してAPIノードを有効にします",
    error: "無効なAPIキーです",
    generateKey: "こちらから取得",
    helpText: "APIキーが必要ですか？",
    invalid: "無効なAPIキーです",
    invalidDetail: "有効なAPIキーを入力してください",
    label: "APIキー",
    placeholder: "APIキーを入力してください",
    storageFailed: "APIキーの保存に失敗しました",
    storageFailedDetail: "もう一度お試しください。",
    stored: "APIキーが保存されました",
    storedDetail: "APIキーが正常に保存されました",
    title: "APIキー",
    whitelistInfo: "ホワイトリストに登録されていないサイトについて"
  },
  login: {
    andText: "および",
    confirmPasswordLabel: "パスワードの確認",
    confirmPasswordPlaceholder: "もう一度同じパスワードを入力してください",
    emailLabel: "メール",
    emailPlaceholder: "メールアドレスを入力してください",
    failed: "ログイン失敗",
    forgotPassword: "パスワードを忘れましたか？",
    forgotPasswordError: "パスワードリセット用メールの送信に失敗しました",
    insecureContextWarning: "この接続は安全ではありません（HTTP）- このままログインを続けると、認証情報が攻撃者に傍受される可能性があります。",
    loginButton: "ログイン",
    loginWithGithub: "Githubでログイン",
    loginWithGoogle: "Googleでログイン",
    newUser: "新規ユーザーですか？",
    noAssociatedUser: "指定されたAPIキーに関連付けられたComfyユーザーが存在しません",
    orContinueWith: "または以下で続ける",
    passwordLabel: "パスワード",
    passwordPlaceholder: "パスワードを入力してください",
    passwordResetSent: "パスワードリセット用メールを送信しました",
    passwordResetSentDetail: "パスワードをリセットするためのリンクが記載されたメールをご確認ください。",
    privacyLink: "プライバシーポリシー",
    questionsContactPrefix: "ご不明な点がございますか？お問い合わせはこちら：",
    signInOrSignUp: "サインイン / サインアップ",
    signUp: "サインアップ",
    success: "ログイン成功",
    termsLink: "利用規約",
    termsText: "「次へ」または「サインアップ」をクリックすると、私たちの",
    title: "アカウントにログインする",
    useApiKey: "Comfy APIキー",
    userAvatar: "ユーザーアバター"
  },
  passwordUpdate: {
    success: "パスワードが更新されました",
    successDetail: "パスワードが正常に更新されました"
  },
  signOut: {
    signOut: "ログアウト",
    success: "正常にサインアウトしました",
    successDetail: "アカウントからサインアウトしました。"
  },
  signup: {
    alreadyHaveAccount: "すでにアカウントをお持ちですか？",
    emailLabel: "メール",
    emailPlaceholder: "メールアドレスを入力してください",
    passwordLabel: "パスワード",
    passwordPlaceholder: "新しいパスワードを入力してください",
    personalDataConsentLabel: "個人データの取扱いに同意します。",
    regionRestrictionChina: "現地の規制要件に従い、当社のサービスは現在中国本土のユーザーにはご利用いただけません。",
    signIn: "サインイン",
    signUpButton: "サインアップ",
    signUpWithGithub: "Githubでサインアップ",
    signUpWithGoogle: "Googleでサインアップ",
    title: "アカウントを作成する"
  }
};
const clipboard$3 = {
  errorMessage: "クリップボードへのコピーに失敗しました",
  errorNotSupported: "お使いのブラウザではクリップボードAPIがサポートされていません",
  successMessage: "クリップボードにコピーしました"
};
const color$3 = {
  black: "黒",
  blue: "青",
  brown: "ブラウン",
  custom: "カスタム",
  cyan: "シアン",
  "default": "デフォルト",
  green: "緑",
  noColor: "色なし",
  pale_blue: "淡い青",
  pink: "ピンク",
  purple: "パープル",
  red: "赤",
  yellow: "黄色"
};
const contextMenu$3 = {
  "Add Group": "グループを追加",
  "Add Group For Selected Nodes": "選択したノードのグループを追加",
  "Add Node": "ノードを追加",
  Bypass: "バイパス",
  Clone: "クローン",
  Collapse: "折りたたむ",
  Colors: "色",
  "Convert to Group Node": "グループノードに変換",
  "Copy (Clipspace)": "コピー (Clipspace)",
  Expand: "展開",
  Inputs: "入力",
  Manage: "管理",
  "Manage Group Nodes": "グループノードを管理",
  Mode: "モード",
  "Node Templates": "ノードテンプレート",
  Outputs: "出力",
  Pin: "ピン",
  Properties: "プロパティ",
  "Properties Panel": "プロパティパネル",
  Remove: "削除",
  Resize: "リサイズ",
  "Save Selected as Template": "選択したものをテンプレートとして保存",
  Search: "検索",
  Shapes: "形",
  Title: "タイトル",
  Unpin: "ピンを解除"
};
const credits$3 = {
  apiPricing: "API料金",
  credits: "クレジット",
  faqs: "よくある質問",
  invoiceHistory: "請求履歴",
  lastUpdated: "最終更新",
  messageSupport: "サポートにメッセージ",
  purchaseCredits: "クレジットを購入",
  topUp: {
    buyNow: "今すぐ購入",
    insufficientMessage: "このワークフローを実行するのに十分なクレジットがありません。",
    insufficientTitle: "クレジット不足",
    maxAmount: "（最大 $1,000 USD）",
    quickPurchase: "クイック購入",
    seeDetails: "詳細を見る",
    topUp: "チャージ"
  },
  yourCreditBalance: "あなたのクレジット残高"
};
const dataTypes$3 = {
  "*": "*",
  AUDIO: "オーディオ",
  BOOLEAN: "ブール",
  CAMERA_CONTROL: "カメラコントロール",
  CLIP: "CLIP",
  CLIP_VISION: "CLIP_VISION",
  CLIP_VISION_OUTPUT: "CLIP_VISION_OUTPUT",
  COMBO: "コンボ",
  CONDITIONING: "条件付け",
  CONTROL_NET: "コントロールネット",
  FLOAT: "浮動小数点",
  FLOATS: "浮動小数点数",
  GLIGEN: "GLIGEN",
  GUIDER: "ガイダー",
  HOOKS: "フック",
  HOOK_KEYFRAMES: "フックキーフレーム",
  IMAGE: "画像",
  INT: "整数",
  LATENT: "潜在",
  LATENT_OPERATION: "潜在操作",
  LOAD3D_CAMERA: "3Dカメラの読み込み",
  LOAD_3D: "3Dをロード",
  LOAD_3D_ANIMATION: "3Dアニメーションをロード",
  LUMA_CONCEPTS: "Lumaコンセプト",
  LUMA_REF: "Luma参照",
  MASK: "マスク",
  MESH: "メッシュ",
  MODEL: "モデル",
  NOISE: "ノイズ",
  PHOTOMAKER: "PHOTOMAKER",
  PIXVERSE_TEMPLATE: "Pixverseテンプレート",
  RECRAFT_COLOR: "Recraftカラー",
  RECRAFT_CONTROLS: "Recraftコントロール",
  RECRAFT_V3_STYLE: "Recraft V3スタイル",
  SAMPLER: "サンプラー",
  SIGMAS: "シグマ",
  STRING: "文字列",
  STYLE_MODEL: "スタイルモデル",
  SVG: "SVG",
  TIMESTEPS_RANGE: "タイムステップの範囲",
  UPSCALE_MODEL: "アップスケールモデル",
  VAE: "VAE",
  VIDEO: "ビデオ",
  VOXEL: "ボクセル",
  WEBCAM: "ウェブカメラ"
};
const desktopMenu$3 = {
  confirmQuit: "保存されていないワークフローを終了しようとしています。保存されていない変更はすべて失われます。これを無視して終了しますか？",
  confirmReinstall: "これにより、extra_models_config.yamlファイルがクリアされ、再インストールが開始されます。本当によろしいですか？",
  quit: "終了",
  reinstall: "再インストール"
};
const desktopUpdate$3 = {
  description: "ComfyUIデスクトップは新しい依存関係をインストールしています。これには数分かかる場合があります。",
  errorCheckingUpdate: "アップデートの確認中にエラーが発生しました",
  errorInstallingUpdate: "アップデートのインストール中にエラーが発生しました",
  noUpdateFound: "アップデートは見つかりませんでした",
  terminalDefaultMessage: "更新からの任意のコンソール出力はここに表示されます。",
  title: "ComfyUIデスクトップの更新",
  updateAvailableMessage: "アップデートが利用可能です。今すぐ再起動してアップデートしますか？",
  updateFoundTitle: "アップデートが見つかりました (v{version})"
};
const downloadGit$3 = {
  gitWebsite: "Gitをダウンロード",
  instructions: "お使いのオペレーティングシステムに最新のバージョンをダウンロードしてインストールしてください。以下の「Gitをダウンロード」ボタンをクリックすると、git-scm.comのダウンロードページが開きます。",
  message: "Gitを見つけることができません。正常に動作するためには、Gitの作業コピーが必要です。",
  skip: "スキップ",
  title: "Gitをダウンロード",
  warning: "Gitがインストールされていなくても問題ないと確信している場合、または間違いがあった場合は、「スキップ」をクリックしてこのチェックをスキップできます。作業コピーのない状態でComfyUIを実行することは現在サポートされていません。"
};
const electronFileDownload$3 = {
  cancel: "ダウンロードをキャンセル",
  cancelled: "キャンセルされました",
  inProgress: "ダウンロード中",
  pause: "ダウンロードを一時停止",
  paused: "一時停止",
  resume: "ダウンロードを再開"
};
const errorDialog$3 = {
  defaultTitle: "エラーが発生しました",
  extensionFileHint: "これは次のスクリプトが原因かもしれません",
  loadWorkflowTitle: "ワークフローデータの再読み込みエラーにより、読み込みが中止されました",
  noStackTrace: "スタックトレースは利用できません",
  promptExecutionError: "プロンプトの実行に失敗しました"
};
const g$3 = {
  about: "情報",
  add: "追加",
  all: "すべて",
  amount: "量",
  apply: "適用する",
  back: "戻る",
  cancel: "キャンセル",
  capture: "キャプチャ",
  category: "カテゴリ",
  choose_file_to_upload: "アップロードするファイルを選択",
  close: "閉じる",
  color: "色",
  comingSoon: "近日公開",
  command: "コマンド",
  community: "コミュニティ",
  completed: "完了",
  confirm: "確認",
  confirmed: "確認済み",
  "continue": "続ける",
  control_after_generate: "生成後の制御",
  control_before_generate: "生成前の制御",
  copyToClipboard: "クリップボードにコピー",
  currentUser: "現在のユーザー",
  customize: "カスタマイズ",
  customizeFolder: "フォルダーをカスタマイズ",
  "delete": "削除",
  deprecated: "非推奨",
  description: "説明",
  devices: "デバイス",
  disableAll: "すべて無効にする",
  disabling: "無効化",
  download: "ダウンロード",
  empty: "空",
  enableAll: "すべて有効にする",
  enabled: "有効",
  enabling: "有効化",
  error: "エラー",
  experimental: "ベータ",
  "export": "エクスポート",
  extensionName: "拡張機能名",
  feedback: "フィードバック",
  filter: "フィルタ",
  findIssues: "問題を見つける",
  firstTimeUIMessage: "新しいUIを初めて使用しています。「メニュー > 新しいメニューを使用 > 無効」を選択することで古いUIに戻すことが可能です。",
  goToNode: "ノードに移動",
  icon: "アイコン",
  imageFailedToLoad: "画像の読み込みに失敗しました",
  "import": "インポート",
  inProgress: "進行中",
  insert: "挿入",
  install: "インストール",
  installed: "インストール済み",
  installing: "インストール中",
  interrupted: "中断されました",
  keybinding: "キーバインディング",
  learnMore: "詳細を学ぶ",
  loadAllFolders: "すべてのフォルダーを読み込む",
  loadWorkflow: "ワークフローを読み込む",
  loading: "読み込み中",
  login: "ログイン",
  logs: "ログ",
  migrate: "移行する",
  missing: "不足している",
  name: "名前",
  newFolder: "新しいフォルダー",
  next: "次へ",
  no: "いいえ",
  noResultsFound: "結果が見つかりません",
  noTasksFound: "タスクが見つかりません",
  noTasksFoundMessage: "キューにタスクがありません。",
  noWorkflowsFound: "ワークフローが見つかりません。",
  nodes: "ノード",
  ok: "OK",
  openNewIssue: "新しい問題を開く",
  overwrite: "上書き",
  reconnected: "再接続されました",
  reconnecting: "再接続中",
  refresh: "更新",
  reloadToApplyChanges: "変更を適用するには再読み込みしてください",
  rename: "名前を変更",
  reportIssue: "報告する",
  reportIssueTooltip: "エラーレポートをComfy Orgに送信",
  reportSent: "レポートが送信されました",
  reset: "リセット",
  resetAll: "すべてリセット",
  resetAllKeybindingsTooltip: "すべてのキーバインディングをデフォルトにリセット",
  restart: "再起動",
  resultsCount: "{count}件の結果が見つかりました",
  save: "保存",
  saving: "保存中",
  searchExtensions: "拡張機能を検索",
  searchFailedMessage: "検索に一致する設定が見つかりませんでした。検索キーワードを調整してみてください。",
  searchKeybindings: "キーバインディングを検索",
  searchModels: "モデルを検索",
  searchNodes: "ノードを検索",
  searchSettings: "設定を検索",
  searchWorkflows: "ワークフローを検索",
  settings: "設定",
  showReport: "レポートを表示",
  sort: "並び替え",
  source: "ソース",
  status: "ステータス",
  success: "成功",
  systemInfo: "システム情報",
  terminal: "ターミナル",
  title: "タイトル",
  unknownError: "不明なエラー",
  update: "更新",
  updateAvailable: "更新が利用可能",
  updated: "更新済み",
  updating: "更新中",
  upload: "アップロード",
  user: "ユーザー",
  videoFailedToLoad: "ビデオの読み込みに失敗しました",
  workflow: "ワークフロー"
};
const graphCanvasMenu$3 = {
  fitView: "ビューに合わせる",
  panMode: "パンモード",
  resetView: "ビューをリセット",
  selectMode: "選択モード",
  toggleLinkVisibility: "リンクの表示切り替え",
  zoomIn: "拡大",
  zoomOut: "縮小"
};
const groupNode$3 = {
  create: "グループノードを作成",
  enterName: "名前を入力"
};
const icon$3 = {
  bookmark: "ブックマーク",
  box: "ボックス",
  briefcase: "ブリーフケース",
  "exclamation-triangle": "警告",
  file: "ファイル",
  folder: "フォルダー",
  heart: "ハート",
  inbox: "受信トレイ",
  star: "星"
};
const install$3 = {
  appDataLocationTooltip: "ComfyUIのアプリデータディレクトリ。保存内容:\n- ログ\n- サーバー設定",
  appPathLocationTooltip: "ComfyUIのアプリ資産ディレクトリ。ComfyUIのコードとアセットを保存します",
  cannotWrite: "選択したパスに書き込むことができません",
  chooseInstallationLocation: "インストール先を選択",
  customNodes: "カスタムノード",
  customNodesDescription: "既存のComfyUIインストールからカスタムノードを再インストールします。",
  desktopAppSettings: "デスクトップアプリの設定",
  desktopAppSettingsDescription: "ComfyUIのデスクトップでの動作を設定します。これらの設定は後で変更可能です。",
  desktopSettings: "デスクトップ設定",
  failedToSelectDirectory: "ディレクトリの選択に失敗しました",
  gpu: "GPU",
  gpuSelection: {
    cpuMode: "CPUモード",
    cpuModeDescription: "CPUモードは開発者や、まれなエッジケースのみを対象としています。",
    cpuModeDescription2: "これが絶対に必要であることが確定していない場合は、このボックスを無視して上でGPUを選択してください。",
    customComfyNeedsPython: "ComfyUIはpythonがセットアップされるまで動作しません",
    customInstallRequirements: "すべての要件と依存関係をインストールする（例：カスタムtorch）",
    customManualVenv: "python venvを手動で設定する",
    customMayNotWork: "これは完全にサポートされておらず、単純に動作しない場合があります。",
    customSkipsPython: "このオプションは通常のpythonセットアップをスキップします。",
    enableCpuMode: "CPUモードを有効にする",
    mpsDescription: "Apple Metal Performance Shadersは、pytorch nightlyを使用してサポートされています。",
    nvidiaDescription: "NVIDIAデバイスは、pytorch CUDAビルドを使用して直接サポートされています。",
    selectGpu: "GPUを選択",
    selectGpuDescription: "所有しているGPUのタイプを選択してください"
  },
  helpImprove: "ComfyUIの改善にご協力ください",
  installLocation: "インストール先",
  installLocationDescription: "ComfyUIのユーザーデータを保存するディレクトリを選択してください。Python環境が選択した場所にインストールされます。選択したディスクに約15GBの空き容量が必要です。",
  installLocationTooltip: "ComfyUIのユーザーデータディレクトリ。保存内容:\n- Python環境\n- モデル\n- カスタムノード\n",
  insufficientFreeSpace: "空き容量が不足しています - 最低限の空き容量",
  isOneDrive: "OneDriveにインストールすると問題が発生する可能性があります。非OneDriveの場所にインストールすることを強くお勧めします。",
  manualConfiguration: {
    createVenv: "次のディレクトリに仮想環境を作成する必要があります",
    requirements: "要件",
    restartWhenFinished: "仮想環境の設定が完了したら、ComfyUIを再起動してください。",
    title: "マニュアル設定",
    virtualEnvironmentPath: "仮想環境のパス"
  },
  metricsDisabled: "メトリクスを無効にする",
  metricsEnabled: "メトリクスを有効にする",
  migrateFromExistingInstallation: "既存のインストールから移行",
  migration: "移行",
  migrationOptional: "移行は任意です。既存のインストールがない場合、このステップをスキップできます。",
  migrationSourcePathDescription: "既存のComfyUIインストールがある場合、既存のユーザーファイルとモデルを新しいインストールにコピー/リンクすることができます。既存のComfyUIインストールは影響を受けません。",
  moreInfo: "詳しくはこちらをご覧ください",
  nonDefaultDrive: "ComfyUIをシステムドライブ（例：C:\\）にインストールしてください。異なるファイルシステムを持つドライブでは、予測不能な問題が発生する可能性があります。インストール後にモデルやその他のファイルを他のドライブに保存することができます。",
  parentMissing: "パスが存在しません - 最初に含まれるディレクトリを作成してください",
  pathExists: "ディレクトリはすでに存在します - すべてのデータをバックアップしたことを確認してください",
  pathValidationFailed: "パスの検証に失敗しました",
  privacyPolicy: "プライバシーポリシー",
  selectItemsToMigrate: "移行する項目を選択",
  settings: {
    allowMetrics: "使用状況のメトリクス",
    allowMetricsDescription: "匿名の使用状況メトリクスを送信してComfyUIを改善します。個人情報やワークフローの内容は収集されません。",
    autoUpdate: "自動更新",
    autoUpdateDescription: "更新が利用可能になると、自動的にダウンロードおよびインストールを行います。インストール前に通知が表示されます。",
    checkingMirrors: "Pythonミラーへのネットワークアクセスを確認中...",
    dataCollectionDialog: {
      collect: {
        errorReports: "エラーメッセージとスタックトレース",
        systemInfo: "ハードウェア、OSタイプ、アプリバージョン",
        userJourneyEvents: "ユーザージャーニーイベント"
      },
      doNotCollect: {
        customNodeConfigurations: "カスタムノードの設定",
        fileSystemInformation: "ファイルシステム情報",
        personalInformation: "個人情報",
        workflowContents: "ワークフローの内容"
      },
      title: "データ収集について",
      viewFullPolicy: "完全なポリシーを見る",
      whatWeCollect: "収集内容:",
      whatWeDoNotCollect: "収集しない内容:"
    },
    errorUpdatingConsent: "同意の更新エラー",
    errorUpdatingConsentDetail: "メトリクスの同意設定の更新に失敗しました",
    learnMoreAboutData: "データ収集の詳細を見る",
    mirrorSettings: "ミラー設定",
    mirrorsReachable: "Pythonミラーへのネットワークアクセスは良好です",
    mirrorsUnreachable: "一部のpythonミラーへのネットワークアクセスが悪い",
    pypiMirrorPlaceholder: "PyPIミラーURLを入力してください",
    pythonMirrorPlaceholder: "PythonミラーURLを入力してください"
  },
  systemLocations: "システムの場所",
  unhandledError: "未知のエラー",
  updateConsent: "以前、クラッシュレポートを報告することに同意していました。現在、バグの特定とアプリの改善を助けるためにイベントベースのメトリクスを追跡しています。個人を特定できる情報は収集されません。"
};
const issueReport$3 = {
  contactFollowUp: "フォローアップのために私に連絡する",
  contactSupportDescription: "下記のフォームにご報告内容をご記入ください",
  contactSupportTitle: "サポートに連絡",
  describeTheProblem: "問題の内容を記述してください",
  email: "メールアドレス",
  feedbackTitle: "フィードバックを提供してComfyUIの改善にご協力ください",
  helpFix: "これを修正するのを助ける",
  helpTypes: {
    billingPayments: "請求／支払い",
    bugReport: "バグ報告",
    giveFeedback: "フィードバックを送る",
    loginAccessIssues: "ログイン／アクセスの問題",
    somethingElse: "その他"
  },
  notifyResolve: "解決したときに通知する",
  provideAdditionalDetails: "追加の詳細を提供する（オプション）",
  provideEmail: "あなたのメールアドレスを教えてください（オプション）",
  rating: "評価",
  selectIssue: "問題を選択してください",
  stackTrace: "スタックトレース",
  submitErrorReport: "エラーレポートを提出する（オプション）",
  systemStats: "システム統計",
  validation: {
    invalidEmail: "有効なメールアドレスを入力してください",
    maxLength: "メッセージが長すぎます",
    selectIssueType: "問題の種類を選択してください"
  },
  whatCanWeInclude: "レポートに含める内容を指定してください",
  whatDoYouNeedHelpWith: "どのようなサポートが必要ですか？"
};
const load3d$3 = {
  applyingTexture: "テクスチャを適用中...",
  backgroundColor: "背景色",
  camera: "カメラ",
  clearRecording: "録画をクリア",
  edgeThreshold: "エッジ閾値",
  "export": "エクスポート",
  exportModel: "モデルをエクスポート",
  exportRecording: "録画をエクスポート",
  exportingModel: "モデルをエクスポート中...",
  fov: "FOV",
  light: "ライト",
  lightIntensity: "光の強度",
  loadingModel: "3Dモデルを読み込んでいます...",
  materialMode: "マテリアルモード",
  materialModes: {
    depth: "深度",
    lineart: "線画",
    normal: "ノーマル",
    original: "オリジナル",
    wireframe: "ワイヤーフレーム"
  },
  model: "モデル",
  previewOutput: "出力のプレビュー",
  removeBackgroundImage: "背景画像を削除",
  resizeNodeMatchOutput: "ノードを出力に合わせてリサイズ",
  scene: "シーン",
  showGrid: "グリッドを表示",
  startRecording: "録画開始",
  stopRecording: "録画停止",
  switchCamera: "カメラを切り替える",
  switchingMaterialMode: "マテリアルモードの切り替え中...",
  upDirection: "上方向",
  uploadBackgroundImage: "背景画像をアップロード",
  uploadTexture: "テクスチャをアップロード"
};
const maintenance$3 = {
  None: "なし",
  OK: "OK",
  Skipped: "スキップされました",
  allOk: "問題は検出されませんでした。",
  confirmTitle: "よろしいですか？",
  consoleLogs: "コンソールログ",
  detected: "検出されました",
  error: {
    cannotContinue: "続行できません - エラーが残っています",
    defaultDescription: "メンテナンスタスクの実行中にエラーが発生しました。",
    taskFailed: "タスクの実行に失敗しました。",
    toastTitle: "タスクエラー"
  },
  refreshing: "更新中",
  showManual: "メンテナンスタスクを表示",
  status: "ステータス",
  terminalDefaultMessage: "トラブルシューティングコマンドを実行すると、出力はここに表示されます。",
  title: "メンテナンス"
};
const manager$3 = {
  changingVersion: "バージョンを {from} から {to} に変更",
  createdBy: "作成者",
  dependencies: "依存関係",
  discoverCommunityContent: "コミュニティが作成したノードパック、拡張機能などを探す...",
  downloads: "ダウンロード",
  errorConnecting: "Comfy Node Registryへの接続エラー。",
  failed: "失敗しました ({count})",
  filter: {
    disabled: "無効",
    enabled: "有効",
    nodePack: "ノードパック"
  },
  inWorkflow: "ワークフロー内",
  infoPanelEmpty: "アイテムをクリックして情報を表示します",
  installSelected: "選択したものをインストール",
  installationQueue: "インストールキュー",
  lastUpdated: "最終更新日",
  latestVersion: "最新",
  license: "ライセンス",
  loadingVersions: "バージョンを読み込んでいます...",
  nightlyVersion: "ナイトリー",
  noDescription: "説明はありません",
  noNodesFound: "ノードが見つかりません",
  noNodesFoundDescription: "パックのノードは解析できなかったか、パックがフロントエンドの拡張機能のみでノードがない可能性があります。",
  noResultsFound: "検索に一致する結果が見つかりませんでした。",
  nodePack: "ノードパック",
  packsSelected: "選択したパック",
  repository: "リポジトリ",
  restartToApplyChanges: "変更を適用するには、ComfyUIを再起動してください",
  searchPlaceholder: "検索",
  selectVersion: "バージョンを選択",
  sort: {
    created: "最新",
    downloads: "最も人気",
    publisher: "出版社",
    updated: "最近更新"
  },
  status: {
    active: "アクティブ",
    banned: "禁止",
    deleted: "削除済み",
    flagged: "フラグ付き",
    pending: "保留中",
    unknown: "不明"
  },
  title: "カスタムノードマネージャ",
  totalNodes: "合計ノード数",
  tryAgainLater: "後ほど再試行してください。",
  tryDifferentSearch: "別の検索クエリを試してみてください。",
  uninstall: "アンインストール",
  uninstallSelected: "選択したものをアンインストール",
  uninstalling: "アンインストール中",
  update: "更新",
  updatingAllPacks: "すべてのパッケージを更新中",
  version: "バージョン"
};
const maskEditor$3 = {
  "Apply to Whole Image": "全画像に適用",
  "Brush Settings": "ブラシ設定",
  "Brush Shape": "ブラシ形状",
  Clear: "クリア",
  "Color Select Settings": "色選択設定",
  "Fill Opacity": "塗りつぶしの不透明度",
  Hardness: "硬さ",
  "Image Layer": "画像レイヤー",
  Invert: "反転",
  Layers: "レイヤー",
  "Live Preview": "ライブプレビュー",
  "Mask Layer": "マスクレイヤー",
  "Mask Opacity": "マスクの不透明度",
  "Mask Tolerance": "マスクの許容範囲",
  Method: "方法",
  Opacity: "不透明度",
  "Paint Bucket Settings": "ペイントバケツ設定",
  "Reset to Default": "デフォルトにリセット",
  "Selection Opacity": "選択範囲の不透明度",
  "Smoothing Precision": "スムージング精度",
  "Stop at mask": "マスクで停止",
  Thickness: "厚さ",
  Tolerance: "許容範囲"
};
const menu$3 = {
  autoQueue: "自動キュー",
  batchCount: "バッチ数",
  batchCountTooltip: "ワークフロー生成回数",
  clear: "ワークフローをクリア",
  clipspace: "クリップスペースを開く",
  disabled: "無効",
  disabledTooltip: "ワークフローは自動的にキューに追加されません",
  execute: "実行",
  hideMenu: "メニューを隠す",
  instant: "即時",
  instantTooltip: "生成完了後すぐにキューに追加",
  interrupt: "現在の実行を中止",
  onChange: "変更時",
  onChangeTooltip: "変更が行われるとワークフローがキューに追加されます",
  refresh: "ノードを更新",
  resetView: "ビューをリセット",
  run: "実行する",
  runWorkflow: "ワークフローを実行する (Shiftで先頭にキュー)",
  runWorkflowFront: "ワークフローを実行する (先頭にキュー)",
  showMenu: "メニューを表示",
  toggleBottomPanel: "下部パネルを切り替え"
};
const menuLabels$3 = {
  "About ComfyUI": "ComfyUIについて",
  "Browse Templates": "テンプレートを参照",
  "Bypass/Unbypass Selected Nodes": "選択したノードのバイパス/バイパス解除",
  "Canvas Toggle Link Visibility": "キャンバスのリンク表示を切り替え",
  "Canvas Toggle Lock": "キャンバスのロックを切り替え",
  "Check for Updates": "更新を確認する",
  "Clear Pending Tasks": "保留中のタスクをクリア",
  "Clear Workflow": "ワークフローをクリア",
  Clipspace: "クリップスペース",
  "Close Current Workflow": "現在のワークフローを閉じる",
  "Collapse/Expand Selected Nodes": "選択したノードの折りたたみ/展開",
  "Comfy-Org Discord": "Comfy-Org Discord",
  "ComfyUI Docs": "ComfyUIのドキュメント",
  "ComfyUI Forum": "ComfyUI フォーラム",
  "ComfyUI Issues": "ComfyUIの問題",
  "Contact Support": "サポートに連絡",
  "Convert selected nodes to group node": "選択したノードをグループノードに変換",
  "Custom Nodes Manager": "カスタムノードマネージャ",
  "Delete Selected Items": "選択したアイテムを削除",
  "Desktop User Guide": "デスクトップユーザーガイド",
  "Duplicate Current Workflow": "現在のワークフローを複製",
  Edit: "編集",
  Export: "エクスポート",
  "Export (API)": "エクスポート (API)",
  "Fit Group To Contents": "グループを内容に合わせる",
  "Fit view to selected nodes": "選択したノードにビューを合わせる",
  "Give Feedback": "フィードバックを送る",
  "Group Selected Nodes": "選択したノードをグループ化",
  Help: "ヘルプ",
  Interrupt: "中断",
  "Load Default Workflow": "デフォルトワークフローを読み込む",
  "Manage group nodes": "グループノードを管理",
  "Mute/Unmute Selected Nodes": "選択したノードのミュート/ミュート解除",
  New: "新規",
  "Next Opened Workflow": "次に開いたワークフロー",
  Open: "開く",
  "Open Custom Nodes Folder": "カスタムノードフォルダを開く",
  "Open DevTools": "DevToolsを開く",
  "Open Inputs Folder": "入力フォルダを開く",
  "Open Logs Folder": "ログフォルダを開く",
  "Open Models Folder": "モデルフォルダを開く",
  "Open Outputs Folder": "出力フォルダを開く",
  "Open Sign In Dialog": "サインインダイアログを開く",
  "Open extra_model_paths_yaml": "extra_model_paths.yamlを開く",
  "Pin/Unpin Selected Items": "選択したアイテムのピン留め/ピン留め解除",
  "Pin/Unpin Selected Nodes": "選択したノードのピン留め/ピン留め解除",
  "Previous Opened Workflow": "前に開いたワークフロー",
  "Queue Prompt": "キューのプロンプト",
  "Queue Prompt (Front)": "キューのプロンプト (前面)",
  "Queue Selected Output Nodes": "選択した出力ノードをキューに追加",
  Quit: "終了",
  Redo: "やり直す",
  "Refresh Node Definitions": "ノード定義を更新",
  Reinstall: "再インストール",
  "Reset View": "ビューをリセット",
  "Resize Selected Nodes": "選択したノードのサイズ変更",
  Restart: "再起動",
  Save: "保存",
  "Save As": "名前を付けて保存",
  "Show Settings Dialog": "設定ダイアログを表示",
  "Sign Out": "サインアウト",
  "Toggle Bottom Panel": "下部パネルの切り替え",
  "Toggle Focus Mode": "フォーカスモードの切り替え",
  "Toggle Logs Bottom Panel": "ログパネル下部を切り替え",
  "Toggle Model Library Sidebar": "モデルライブラリサイドバーを切り替え",
  "Toggle Node Library Sidebar": "ノードライブラリサイドバーを切り替え",
  "Toggle Progress Dialog": "進行状況ダイアログの切り替え",
  "Toggle Queue Sidebar": "キューサイドバーを切り替え",
  "Toggle Search Box": "検索ボックスの切り替え",
  "Toggle Terminal Bottom Panel": "ターミナルパネル下部を切り替え",
  "Toggle Theme (Dark/Light)": "テーマを切り替え（ダーク/ライト）",
  "Toggle Workflows Sidebar": "ワークフローサイドバーを切り替え",
  Undo: "元に戻す",
  "Ungroup selected group nodes": "選択したグループノードのグループ解除",
  Workflow: "ワークフロー",
  "Zoom In": "ズームイン",
  "Zoom Out": "ズームアウト"
};
const missingModelsDialog$3 = {
  doNotAskAgain: "再度表示しない",
  missingModels: "モデルが見つかりません",
  missingModelsMessage: "グラフを読み込む際に、次のモデルが見つかりませんでした"
};
const nodeCategories$3 = {
  "3d": "3d",
  "3d_models": "3Dモデル",
  BFL: "BFL",
  Ideogram: "Ideogram",
  Kling: "Kling",
  Luma: "Luma",
  MiniMax: "MiniMax",
  OpenAI: "OpenAI",
  Pika: "Pika",
  PixVerse: "PixVerse",
  Recraft: "Recraft",
  "Stability AI": "Stability AI",
  Veo: "Veo",
  _for_testing: "_テスト用",
  advanced: "高度な機能",
  animation: "アニメーション",
  api: "API",
  "api node": "apiノード",
  attention_experiments: "アテンション実験",
  audio: "オーディオ",
  batch: "バッチ",
  clip: "クリップ",
  combine: "結合",
  compositing: "合成",
  "cond pair": "条件ペア",
  "cond single": "条件単体",
  conditioning: "条件付け",
  controlnet: "コントロールネット",
  create: "作成",
  custom_sampling: "カスタムサンプリング",
  debug: "デバッグ",
  deprecated: "非推奨",
  flux: "flux",
  gligen: "グライジェン",
  guidance: "ガイダンス",
  guiders: "ガイダー",
  hooks: "フック",
  image: "画像",
  inpaint: "インペイント",
  instructpix2pix: "インストラクションピクス2ピクス",
  latent: "潜在",
  loaders: "ローダー",
  lotus: "lotus",
  ltxv: "LTXV",
  mask: "マスク",
  model: "モデル",
  model_merging: "モデルマージ",
  model_patches: "モデルパッチ",
  model_specific: "モデル特有",
  noise: "ノイズ",
  operations: "操作",
  photomaker: "photomaker",
  postprocessing: "ポストプロセッシング",
  preprocessors: "前処理",
  primitive: "プリミティブ",
  samplers: "サンプラー",
  sampling: "サンプリング",
  schedulers: "スケジューラー",
  scheduling: "スケジューリング",
  sd: "sd",
  sd3: "SD3",
  sigmas: "シグマ",
  stable_cascade: "安定したカスケード",
  style_model: "スタイルモデル",
  transform: "変換",
  unet: "U-Net",
  upscale_diffusion: "アップスケール拡散",
  upscaling: "アップスケーリング",
  utils: "ユーティリティ",
  v1: "v1",
  v2: "v2",
  v3: "v3",
  video: "ビデオ",
  video_models: "ビデオモデル"
};
const nodeTemplates$3 = {
  enterName: "名前を入力",
  saveAsTemplate: "テンプレートとして保存"
};
const notSupported$3 = {
  "continue": "続ける",
  continueTooltip: "私のデバイスはサポートされていると確信しています",
  learnMore: "詳細を見る",
  message: "以下のデバイスのみサポートされています:",
  reportIssue: "問題を報告",
  supportedDevices: {
    macos: "MacOS (M1以降)",
    windows: "Windows (CUDA対応のNvidia GPU)"
  },
  title: "お使いのデバイスはサポートされていません"
};
const selectionToolbox$3 = {
  executeButton: {
    disabledTooltip: "出力ノードが選択されていません",
    tooltip: "選択した出力ノードに実行（オレンジ色の枠でハイライト表示）"
  }
};
const serverConfig$3 = {
  modifiedConfigs: "以下のサーバー設定を変更しました。変更を適用するには再起動してください。",
  restart: "再起動",
  revertChanges: "変更を元に戻す"
};
const serverConfigCategories$3 = {
  Attention: "アテンション",
  CUDA: "CUDA",
  Cache: "キャッシュ",
  Directories: "ディレクトリ",
  General: "一般",
  Inference: "推論",
  Memory: "メモリ",
  Network: "ネットワーク",
  Preview: "プレビュー"
};
const serverConfigItems$3 = {
  "cache-classic": {
    name: "クラシックキャッシュシステムを使用する"
  },
  "cache-lru": {
    name: "最大Nノード結果をキャッシュするLRUキャッシングを使用する。",
    tooltip: "RAM/VRAMを多く使用する可能性があります。"
  },
  "cpu-vae": {
    name: "CPUでVAEを実行する"
  },
  "cross-attention-method": {
    name: "クロスアテンションメソッド"
  },
  "cuda-device": {
    name: "使用するCUDAデバイスインデックス"
  },
  "cuda-malloc": {
    name: "メモリ割り当てにCUDA mallocを使用する"
  },
  "default-hashing-function": {
    name: "モデルファイルのデフォルトハッシュ関数"
  },
  deterministic: {
    name: "可能な場合、PyTorchが遅い決定論的アルゴリズムを使用する。",
    tooltip: "これにより、すべてのケースで画像が決定論的になるわけではないことに注意してください。"
  },
  directml: {
    name: "DirectMLデバイスインデックス"
  },
  "disable-all-custom-nodes": {
    name: "すべてのカスタムノードの読み込みを無効にする。"
  },
  "disable-ipex-optimize": {
    name: "IPEX最適化を無効にする"
  },
  "disable-metadata": {
    name: "ファイルにプロンプトメタデータを保存しない。"
  },
  "disable-smart-memory": {
    name: "スマートメモリ管理を無効にする",
    tooltip: "ComfyUIがモデルをVRAMに保持する代わりに、通常のRAMに積極的にオフロードするように強制します。"
  },
  "disable-xformers": {
    name: "xFormers最適化を無効にする"
  },
  "dont-print-server": {
    name: "サーバー出力をコンソールに表示しない。"
  },
  "dont-upcast-attention": {
    name: "アテンションのアップキャストを防ぐ"
  },
  "enable-cors-header": {
    name: 'CORSヘッダーを有効にする: "*"を使用してすべてのオリジンを許可するか、ドメインを指定する'
  },
  fast: {
    name: "未テストの潜在的に品質を低下させる最適化を有効にする。"
  },
  "force-channels-last": {
    name: "チャネルを最後に強制するメモリ形式"
  },
  "force-upcast-attention": {
    name: "アテンションのアップキャストを強制する"
  },
  "global-precision": {
    name: "グローバル浮動小数点精度",
    tooltip: "グローバル浮動小数点精度"
  },
  "input-directory": {
    name: "入力ディレクトリ"
  },
  listen: {
    name: "ホスト：リッスンするIPアドレス"
  },
  "log-level": {
    name: "ログの冗長性レベル"
  },
  "max-upload-size": {
    name: "最大アップロードサイズ (MB)"
  },
  "output-directory": {
    name: "出力ディレクトリ"
  },
  port: {
    name: "ポート：リッスンするポート"
  },
  "preview-method": {
    name: "潜在プレビューに使用されるメソッド"
  },
  "preview-size": {
    name: "プレビュー画像のサイズ"
  },
  "reserve-vram": {
    name: "予約済みVRAM (GB)",
    tooltip: "OS/他のソフトウェアで使用するために予約したいVRAMの量をGB単位で設定します。デフォルトでは、OSに応じていくらかの量が予約されます。"
  },
  "text-encoder-precision": {
    name: "テキストエンコーダー精度",
    tooltip: "テキストエンコーダー精度"
  },
  "tls-certfile": {
    name: "TLS証明書ファイル: HTTPS用のTLS証明書ファイルのパス"
  },
  "tls-keyfile": {
    name: "TLSキーファイル: HTTPS用のTLSキーファイルのパス"
  },
  "unet-precision": {
    name: "UNET精度",
    tooltip: "UNET精度"
  },
  "vae-precision": {
    name: "VAE精度",
    tooltip: "VAE精度"
  },
  "vram-management": {
    name: "VRAM管理モード"
  }
};
const serverStart$3 = {
  openLogs: "ログを開く",
  process: {
    error: "ComfyUIデスクトップを起動できません",
    "initial-state": "読み込み中...",
    "python-setup": "Python環境を設定中...",
    ready: "完了中...",
    "starting-server": "ComfyUIサーバーを起動中..."
  },
  reportIssue: "問題を報告",
  showTerminal: "ターミナルを表示",
  troubleshoot: "トラブルシューティング"
};
const settingsCategories$3 = {
  "3D": "3D",
  About: "情報",
  Appearance: "外観",
  BrushAdjustment: "ブラシ調整",
  Camera: "カメラ",
  Canvas: "キャンバス",
  ColorPalette: "カラーパレット",
  Comfy: "Comfy",
  "Comfy-Desktop": "Comfyデスクトップ",
  ContextMenu: "コンテキストメニュー",
  Credits: "クレジット",
  CustomColorPalettes: "カスタムカラーパレット",
  DevMode: "開発モード",
  EditTokenWeight: "トークンの重みを編集",
  Extension: "拡張",
  General: "一般",
  Graph: "グラフ",
  Group: "グループ",
  Keybinding: "キー割り当て",
  Light: "ライト",
  Link: "リンク",
  LinkRelease: "リンク解除",
  LiteGraph: "Lite Graph",
  "Load 3D": "3Dを読み込む",
  Locale: "ロケール",
  "Mask Editor": "マスクエディタ",
  Menu: "メニュー",
  ModelLibrary: "モデルライブラリ",
  NewEditor: "新しいエディタ",
  Node: "ノード",
  "Node Search Box": "ノード検索ボックス",
  "Node Widget": "ノードウィジェット",
  NodeLibrary: "ノードライブラリ",
  Pointer: "ポインタ",
  Queue: "キュー",
  QueueButton: "キューボタン",
  Reroute: "リルート",
  RerouteBeta: "ルート変更ベータ",
  Scene: "シーン",
  Server: "サーバー",
  "Server-Config": "サーバー設定",
  Settings: "設定",
  Sidebar: "サイドバー",
  "Tree Explorer": "ツリーエクスプローラー",
  UV: "UV",
  User: "ユーザー",
  Validation: "検証",
  Window: "ウィンドウ",
  Workflow: "ワークフロー"
};
const sideToolbar$3 = {
  browseTemplates: "サンプルテンプレートを表示",
  downloads: "ダウンロード",
  logout: "ログアウト",
  modelLibrary: "モデルライブラリ",
  newBlankWorkflow: "新しい空のワークフローを作成",
  nodeLibrary: "ノードライブラリ",
  nodeLibraryTab: {
    sortOrder: "並び順"
  },
  openWorkflow: "ローカルでワークフローを開く",
  queue: "キュー",
  queueTab: {
    backToAllTasks: "すべてのタスクに戻る",
    clearPendingTasks: "保留中のタスクをクリア",
    containImagePreview: "画像プレビューを含める",
    coverImagePreview: "画像プレビューに合わせる",
    filter: "出力をフィルタ",
    filters: {
      hideCached: "キャッシュを非表示",
      hideCanceled: "キャンセル済みを非表示"
    },
    showFlatList: "フラットリストを表示"
  },
  themeToggle: "テーマの切り替え",
  workflowTab: {
    confirmDelete: "このワークフローを削除してもよろしいですか？",
    confirmDeleteTitle: "ワークフローを削除しますか？",
    confirmOverwrite: "以下のファイルはすでに存在します。上書きしますか？",
    confirmOverwriteTitle: "既存のファイルを上書きしますか？",
    deleteFailed: "ワークフローの削除を試みましたが、失敗しました。",
    deleteFailedTitle: "削除に失敗しました",
    deleted: "ワークフローが削除されました",
    dirtyClose: "以下のファイルが変更されました。閉じる前に保存しますか？",
    dirtyCloseHint: "Shiftキーを押しながら閉じると、プロンプトなしで閉じます",
    dirtyCloseTitle: "変更を保存しますか？",
    workflowTreeType: {
      bookmarks: "ブックマーク",
      browse: "ブラウズ",
      open: "開く"
    }
  },
  workflows: "ワークフロー"
};
const tabMenu$3 = {
  addToBookmarks: "ブックマークに追加",
  closeOtherTabs: "他のタブを閉じる",
  closeTab: "タブを閉じる",
  closeTabsToLeft: "左のタブを閉じる",
  closeTabsToRight: "右のタブを閉じる",
  duplicateTab: "タブを複製",
  removeFromBookmarks: "ブックマークから削除"
};
const templateWorkflows$3 = {
  category: {
    "3D": "3D",
    "Area Composition": "エリア構成",
    Audio: "オーディオ",
    Basics: "基本",
    "ComfyUI Examples": "ComfyUIの例",
    ControlNet: "ControlNet",
    "Custom Nodes": "カスタムノード",
    Flux: "Flux",
    Image: "画像",
    "Image API": "画像API",
    Upscaling: "アップスケーリング",
    Video: "ビデオ",
    "Video API": "動画API"
  },
  template: {
    "3D": {
      "hunyuan-3d-multiview-elf": "Hunyuan3D マルチビュー",
      "hunyuan-3d-turbo": "Hunyuan3D ターボ",
      "hunyuan3d-non-multiview-train": "Hunyuan3D",
      stable_zero123_example: "Stable Zero123"
    },
    "Area Composition": {
      area_composition: "エリア構成",
      area_composition_reversed: "エリア構成反転",
      area_composition_square_area_for_subject: "主題のためのエリア構成スクエア"
    },
    Audio: {
      stable_audio_example: "Stable Audio"
    },
    Basics: {
      "default": "画像生成",
      embedding_example: "埋め込み",
      gligen_textbox_example: "Gligenテキストボックス",
      image2image: "画像から画像へ",
      inpain_model_outpainting: "InpaintモデルのOutpainting",
      inpaint_example: "Inpaint",
      lora: "Lora",
      lora_multiple: "Lora複数"
    },
    ControlNet: {
      "2_pass_pose_worship": "2 Pass Pose Worship",
      controlnet_example: "ControlNet",
      depth_controlnet: "Depth ControlNet",
      depth_t2i_adapter: "Depth T2Iアダプタ",
      mixing_controlnets: "ControlNetsの混合"
    },
    Flux: {
      flux_canny_model_example: "Flux Cannyモデル",
      flux_depth_lora_example: "Flux Depth Lora",
      flux_dev_checkpoint_example: "Flux Dev",
      flux_fill_inpaint_example: "Flux Inpaint",
      flux_fill_outpaint_example: "Flux Outpaint",
      flux_redux_model_example: "Flux Reduxモデル",
      flux_schnell: "Flux Schnell"
    },
    Image: {
      hidream_i1_dev: "HiDream I1 Dev",
      hidream_i1_fast: "HiDream I1 Fast",
      hidream_i1_full: "HiDream I1 Full",
      sd3_5_large_blur: "SD3.5 ラージブラー",
      sd3_5_large_canny_controlnet_example: "SD3.5 ラージキャニーコントロールネット",
      sd3_5_large_depth: "SD3.5 ラージデプス",
      sd3_5_simple_example: "SD3.5 シンプル",
      sdxl_refiner_prompt_example: "SDXL Refinerプロンプト",
      sdxl_revision_text_prompts: "SDXL Revisionテキストプロンプト",
      sdxl_revision_zero_positive: "SDXL Revisionゼロポジティブ",
      sdxl_simple_example: "SDXLシンプル",
      sdxlturbo_example: "SDXLターボ"
    },
    "Image API": {
      "api-openai-dall-e-2-inpaint": "Dall-E 2 インペイント",
      "api-openai-dall-e-2-t2i": "Dall-E 2 テキストから画像へ",
      "api-openai-dall-e-3-t2i": "Dall-E 3 テキストから画像へ",
      api_bfl_flux_pro_t2i: "BFL Flux 1.1[pro] Ultra テキストから画像へ",
      api_ideogram_v3_t2i: "Ideogram V3 テキストから画像へ",
      api_luma_photon_i2i: "Luma Photon 画像から画像へ",
      api_luma_photon_style_ref: "Luma Photon スタイル参照",
      api_openai_image_1_i2i: "OpenAI Image-1 画像から画像へ",
      api_openai_image_1_inpaint: "OpenAI Image-1 インペイント",
      api_openai_image_1_multi_inputs: "OpenAI Image-1 複数入力",
      api_openai_image_1_t2i: "OpenAI Image-1 テキストから画像へ",
      api_recraft_image_gen_with_color_control: "Recraft カラーコントロール画像生成",
      api_recraft_image_gen_with_style_control: "Recraft スタイルコントロール画像生成",
      api_recraft_vector_gen: "Recraft ベクター生成",
      api_stability_sd3_t2i: "Stability AI Stable Image Ultra テキストから画像へ"
    },
    Upscaling: {
      esrgan_example: "ESRGAN",
      hiresfix_esrgan_workflow: "HiresFix ESRGANワークフロー",
      hiresfix_latent_workflow: "HiresFix Latentワークフロー",
      latent_upscale_different_prompt_model: "Latent Upscale異なるプロンプトモデル"
    },
    Video: {
      hunyuan_video_text_to_video: "Hunyuanビデオテキストからビデオへ",
      image_to_video: "画像からビデオへ",
      image_to_video_wan: "Wan 2.1 画像からビデオへ",
      ltxv_image_to_video: "LTXV画像からビデオへ",
      ltxv_text_to_video: "LTXVテキストからビデオへ",
      mochi_text_to_video_example: "Mochiテキストからビデオへ",
      text_to_video_wan: "Wan 2.1 テキストからビデオへ",
      txt_to_image_to_video: "テキストから画像へ、画像からビデオへ",
      wan2_1_fun_control: "Wan 2.1 ControlNet",
      wan2_1_fun_inp: "Wan 2.1 インペインティング"
    },
    "Video API": {
      api_hailuo_minimax_i2v: "MiniMax 画像から動画へ",
      api_kling_i2v: "Kling 画像から動画へ",
      api_luma_i2v: "Luma 画像から動画へ",
      api_pika_scene: "Pika シーン: 画像から動画へ",
      api_pixverse_t2v: "PixVerse テキストから動画へ",
      api_pixverse_template_i2v: "PixVerse Template Effects: 画像から動画へ",
      api_veo2_i2v: "Veo2 画像から動画へ"
    }
  },
  templateDescription: {
    "3D": {
      "hunyuan-3d-multiview-elf": "Hunyuan3D 2mvで複数ビューからモデルを生成します。",
      "hunyuan-3d-turbo": "Hunyuan3D 2mv turboで複数ビューからモデルを生成します。",
      "hunyuan3d-non-multiview-train": "Hunyuan3D 2.0で単一ビューからモデルを生成します。",
      stable_zero123_example: "単一画像から3Dビューを生成します。"
    },
    "Area Composition": {
      area_composition: "エリアで画像構成をコントロールします。",
      area_composition_reversed: "エリア構成ワークフローを逆転します。",
      area_composition_square_area_for_subject: "被写体の配置を一貫させます。"
    },
    Audio: {
      stable_audio_example: "テキストの説明から音声を生成します。"
    },
    Basics: {
      "default": "テキストの説明から画像を生成します。",
      embedding_example: "テキスト反転を使って一貫したスタイルを実現します。",
      gligen_textbox_example: "オブジェクトの位置とサイズを指定します。",
      image2image: "テキストプロンプトを使って既存の画像を変換します。",
      inpain_model_outpainting: "画像を元の境界を超えて拡張します。",
      inpaint_example: "画像の特定部分をシームレスに編集します。",
      lora: "LoRAモデルを適用して特定のスタイルや対象を表現します。",
      lora_multiple: "複数のLoRAモデルを組み合わせて独自の結果を得ます。"
    },
    ControlNet: {
      "2_pass_pose_worship": "ポーズ参照から画像を生成します。",
      controlnet_example: "参照画像で画像生成をコントロールします。",
      depth_controlnet: "深度認識生成で画像を作成します。",
      depth_t2i_adapter: "T2Iアダプターで素早く深度認識画像を生成します。",
      mixing_controlnets: "複数のControlNetモデルを組み合わせます。"
    },
    Flux: {
      flux_canny_model_example: "エッジ検出から画像を生成します。",
      flux_depth_lora_example: "深度認識LoRAで画像を生成します。",
      flux_dev_checkpoint_example: "Flux開発モデルを使って画像を生成します。",
      flux_fill_inpaint_example: "画像の欠損部分を補完します。",
      flux_fill_outpaint_example: "Fluxのアウトペイントで画像を拡張します。",
      flux_redux_model_example: "参照画像のスタイルを転送し、Fluxで画像生成をガイドします。",
      flux_schnell: "Flux Schnellで素早く画像を生成します。"
    },
    Image: {
      hidream_e1_full: "HiDream E1で画像を編集します。",
      hidream_i1_dev: "HiDream I1 Devで画像を生成します。",
      hidream_i1_fast: "HiDream I1で素早く画像を生成します。",
      hidream_i1_full: "HiDream I1で画像を生成します。",
      sd3_5_large_blur: "SD 3.5でぼかし参照画像から画像を生成します。",
      sd3_5_large_canny_controlnet_example: "SD 3.5でエッジ検出を使って画像生成をガイドします。",
      sd3_5_large_depth: "SD 3.5で深度認識画像を生成します。",
      sd3_5_simple_example: "SD 3.5で画像を生成します。",
      sdxl_refiner_prompt_example: "SDXLの出力をリファイナーで強化します。",
      sdxl_revision_text_prompts: "参照画像からコンセプトを転送し、SDXLで画像生成をガイドします。",
      sdxl_revision_zero_positive: "参照画像とテキストプロンプトを組み合わせてSDXLで画像生成をガイドします。",
      sdxl_simple_example: "SDXLで高品質な画像を生成します。",
      sdxlturbo_example: "SDXL Turboでワンステップで画像を生成します。"
    },
    "Image API": {
      "api-openai-dall-e-2-inpaint": "Dall-E 2 APIで画像のインペイントを行います。",
      "api-openai-dall-e-2-t2i": "Dall-E 2 APIでテキストの説明から画像を生成します。",
      "api-openai-dall-e-3-t2i": "Dall-E 3 APIでテキストの説明から画像を生成します。",
      api_bfl_flux_pro_t2i: "FLUX.1 [pro]で優れたプロンプト追従性、画質、ディテール、多様な出力の画像を生成します。",
      api_ideogram_v3_t2i: "高品質な画像・プロンプト整合性、フォトリアリズム、テキスト描画で画像を生成します。プロ品質のロゴ、ポスター、ランディングページ、商品写真などを作成。複雑な背景や精密なライティング、リアルな環境ディテールで洗練された空間構成を簡単に作成できます。",
      api_luma_photon_i2i: "画像とプロンプトを組み合わせて画像生成をガイドします。",
      api_luma_photon_style_ref: "スタイル参照を正確に適用・ブレンドします。Luma Photonは各参照画像の本質を捉え、異なるビジュアル要素を組み合わせつつプロ品質を維持します。",
      api_openai_image_1_i2i: "GPT Image 1 APIで画像から画像を生成します。",
      api_openai_image_1_inpaint: "GPT Image 1 APIで画像のインペイントを行います。",
      api_openai_image_1_multi_inputs: "GPT Image 1 APIで複数入力を使って画像を生成します。",
      api_openai_image_1_t2i: "GPT Image 1 APIでテキストの説明から画像を生成します。",
      api_recraft_image_gen_with_color_control: "カスタムパレットを作成して複数画像で再利用したり、各写真の色を手動で選択できます。ブランドのカラーパレットに合わせて独自のビジュアルを作成します。",
      api_recraft_image_gen_with_style_control: "ビジュアル例でスタイルを制御し、位置合わせやオブジェクトの微調整が可能です。スタイルを保存・共有してブランドの一貫性を保ちます。",
      api_recraft_vector_gen: "テキストプロンプトからRecraftのAIベクター生成でベクター画像を作成します。ロゴ、ポスター、アイコンセット、広告、バナー、モックアップに最適な高品質SVGファイルを生成。アプリやウェブサイト用のブランドベクターイラストを数秒で作成します。",
      api_stability_sd3_t2i: "高品質でプロンプト追従性の高い画像を生成します。1メガピクセル解像度でプロ用途に最適です。"
    },
    Upscaling: {
      esrgan_example: "アップスケールモデルで画像品質を向上させます。",
      hiresfix_esrgan_workflow: "中間ステップでアップスケールモデルを使用します。",
      hiresfix_latent_workflow: "latent空間で画像品質を向上させます。",
      latent_upscale_different_prompt_model: "アップスケールしつつパスごとにプロンプトを変更します。"
    },
    Video: {
      hunyuan_video_text_to_video: "Hunyuanモデルで動画を生成します。",
      image_to_video: "画像をアニメーション動画に変換します。",
      image_to_video_wan: "画像から素早く動画を生成します。",
      ltxv_image_to_video: "静止画像を動画に変換します。",
      ltxv_text_to_video: "テキストの説明から動画を生成します。",
      mochi_text_to_video_example: "Mochiモデルで動画を作成します。",
      text_to_video_wan: "テキストの説明から素早く動画を生成します。",
      txt_to_image_to_video: "テキストから画像を生成し、それを動画に変換します。",
      wan2_1_flf2v_720_f16: "最初と最後のフレームを制御して動画を生成します。",
      wan2_1_fun_control: "ポーズ、深度、エッジ制御などで動画生成をガイドします。",
      wan2_1_fun_inp: "開始フレームと終了フレームから動画を作成します。"
    },
    "Video API": {
      api_hailuo_minimax_i2v: "画像とテキストから洗練された動画を作成。CGI統合や流行のAIハグなどのエフェクトも。多彩なスタイルやテーマから選択可能です。",
      api_kling_i2v: "アクション、表情、カメラワークのプロンプト追従性に優れた動画を作成します。複雑なシーケンシャルアクションもサポートし、あなたがシーンの監督になれます。",
      api_luma_i2v: "静止画像から瞬時に高品質なアニメーションを作成します。",
      api_pika_scene: "複数の画像を素材として使い、それらを組み込んだ動画を生成します。",
      api_pixverse_t2v: "プロンプト解釈が正確で、ダイナミックな動画を生成します。",
      api_pixverse_template_i2v: "静止画像を動きやエフェクトのあるダイナミックな動画に変換します。",
      api_veo2_i2v: "Google Veo2 APIで画像から動画を生成します。"
    }
  },
  title: "テンプレートを利用して開始"
};
const toastMessages$3 = {
  couldNotDetermineFileType: "ファイルタイプを判断できませんでした",
  dropFileError: "ドロップされたアイテムを処理できません: {error}",
  emptyCanvas: "キャンバスが空です",
  errorCopyImage: "画像のコピーにエラーが発生しました: {error}",
  errorLoadingModel: "モデルの読み込みエラー",
  errorSaveSetting: "設定{id}の保存エラー: {err}",
  failedToAccessBillingPortal: "請求ポータルへのアクセスに失敗しました: {error}",
  failedToApplyTexture: "テクスチャの適用に失敗しました",
  failedToCreateCustomer: "顧客の作成に失敗しました: {error}",
  failedToDownloadFile: "ファイルのダウンロードに失敗しました",
  failedToExportModel: "{format}としてモデルのエクスポートに失敗しました",
  failedToFetchBalance: "残高の取得に失敗しました: {error}",
  failedToFetchLogs: "サーバーログの取得に失敗しました",
  failedToInitiateCreditPurchase: "クレジット購入の開始に失敗しました: {error}",
  failedToPurchaseCredits: "クレジットの購入に失敗しました: {error}",
  fileLoadError: "{fileName}でワークフローが見つかりません",
  fileUploadFailed: "ファイルのアップロードに失敗しました",
  interrupted: "実行が中断されました",
  migrateToLitegraphReroute: "将来のバージョンではRerouteノードが削除されます。litegraph-native rerouteに移行するにはクリックしてください。",
  no3dScene: "テクスチャを適用する3Dシーンがありません",
  no3dSceneToExport: "エクスポートする3Dシーンがありません",
  noTemplatesToExport: "エクスポートするテンプレートがありません",
  nodeDefinitionsUpdated: "ノード定義が更新されました",
  nothingToGroup: "グループ化するものがありません",
  nothingToQueue: "キューに追加する項目がありません",
  pendingTasksDeleted: "保留中のタスクが削除されました",
  pleaseSelectNodesToGroup: "グループを作成するためのノード（または他のグループ）を選択してください",
  pleaseSelectOutputNodes: "出力ノードを選択してください",
  unableToGetModelFilePath: "モデルファイルのパスを取得できません",
  unauthorizedDomain: "あなたのドメイン {domain} はこのサービスを利用する権限がありません。ご利用のドメインをホワイトリストに追加するには、{email} までご連絡ください。",
  updateRequested: "更新が要求されました",
  useApiKeyTip: "ヒント：通常のログインにアクセスできませんか？Comfy APIキーオプションを使用してください。",
  userNotAuthenticated: "ユーザーが認証されていません"
};
const userSelect$3 = {
  enterUsername: "ユーザー名を入力してください",
  existingUser: "既存のユーザー",
  newUser: "新しいユーザー",
  next: "次へ",
  selectUser: "ユーザーを選択"
};
const userSettings$3 = {
  email: "メールアドレス",
  name: "名前",
  notSet: "未設定",
  provider: "サインイン方法",
  title: "ユーザー設定",
  updatePassword: "パスワードを更新"
};
const validation$3 = {
  invalidEmail: "無効なメールアドレス",
  length: "{length}文字でなければなりません",
  maxLength: "{length}文字以下でなければなりません",
  minLength: "{length}文字以上でなければなりません",
  password: {
    lowercase: "少なくとも1つの小文字を含む必要があります",
    match: "パスワードが一致する必要があります",
    minLength: "8文字から32文字の間でなければなりません",
    number: "少なくとも1つの数字を含む必要があります",
    requirements: "パスワードの要件",
    special: "少なくとも1つの特殊文字を含む必要があります",
    uppercase: "少なくとも1つの大文字を含む必要があります"
  },
  personalDataConsentRequired: "個人データの処理に同意する必要があります。",
  prefix: "{prefix}で始める必要があります",
  required: "必須"
};
const welcome$3 = {
  getStarted: "はじめる",
  title: "ComfyUIへようこそ"
};
const workflowService$3 = {
  enterFilename: "ファイル名を入力",
  exportWorkflow: "ワークフローをエクスポート",
  saveWorkflow: "ワークフローを保存"
};
const ja = {
  apiNodesCostBreakdown: apiNodesCostBreakdown$3,
  apiNodesNews: apiNodesNews$3,
  apiNodesSignInDialog: apiNodesSignInDialog$3,
  auth: auth$3,
  clipboard: clipboard$3,
  color: color$3,
  contextMenu: contextMenu$3,
  credits: credits$3,
  dataTypes: dataTypes$3,
  desktopMenu: desktopMenu$3,
  desktopUpdate: desktopUpdate$3,
  downloadGit: downloadGit$3,
  electronFileDownload: electronFileDownload$3,
  errorDialog: errorDialog$3,
  g: g$3,
  graphCanvasMenu: graphCanvasMenu$3,
  groupNode: groupNode$3,
  icon: icon$3,
  install: install$3,
  issueReport: issueReport$3,
  load3d: load3d$3,
  maintenance: maintenance$3,
  manager: manager$3,
  maskEditor: maskEditor$3,
  menu: menu$3,
  menuLabels: menuLabels$3,
  missingModelsDialog: missingModelsDialog$3,
  nodeCategories: nodeCategories$3,
  nodeTemplates: nodeTemplates$3,
  notSupported: notSupported$3,
  selectionToolbox: selectionToolbox$3,
  serverConfig: serverConfig$3,
  serverConfigCategories: serverConfigCategories$3,
  serverConfigItems: serverConfigItems$3,
  serverStart: serverStart$3,
  settingsCategories: settingsCategories$3,
  sideToolbar: sideToolbar$3,
  tabMenu: tabMenu$3,
  templateWorkflows: templateWorkflows$3,
  toastMessages: toastMessages$3,
  userSelect: userSelect$3,
  userSettings: userSettings$3,
  validation: validation$3,
  welcome: welcome$3,
  workflowService: workflowService$3
};
const AddNoise$3 = {
  display_name: "ノイズを追加",
  inputs: {
    latent_image: {
      name: "潜在イメージ"
    },
    model: {
      name: "モデル"
    },
    noise: {
      name: "ノイズ"
    },
    sigmas: {
      name: "シグマ"
    }
  }
};
const AlignYourStepsScheduler$3 = {
  display_name: "ステップを整列",
  inputs: {
    denoise: {
      name: "ノイズ除去"
    },
    model_type: {
      name: "モデルタイプ"
    },
    steps: {
      name: "ステップ"
    }
  }
};
const BasicGuider$3 = {
  display_name: "基本ガイダー",
  inputs: {
    conditioning: {
      name: "コンディショニング"
    },
    model: {
      name: "モデル"
    }
  }
};
const BasicScheduler$3 = {
  display_name: "基本スケジューラー",
  inputs: {
    denoise: {
      name: "ノイズ除去"
    },
    model: {
      name: "モデル"
    },
    scheduler: {
      name: "スケジューラ"
    },
    steps: {
      name: "ステップ"
    }
  }
};
const BetaSamplingScheduler$3 = {
  display_name: "ベータサンプリングスケジューラー",
  inputs: {
    alpha: {
      name: "アルファ"
    },
    beta: {
      name: "ベータ"
    },
    model: {
      name: "モデル"
    },
    steps: {
      name: "ステップ"
    }
  }
};
const CFGGuider$3 = {
  display_name: "CFGガイダー",
  inputs: {
    cfg: {
      name: "cfg"
    },
    model: {
      name: "モデル"
    },
    negative: {
      name: "ネガティブ"
    },
    positive: {
      name: "ポジティブ"
    }
  }
};
const CFGZeroStar$3 = {
  display_name: "CFGZeroStar",
  inputs: {
    model: {
      name: "モデル"
    }
  },
  outputs: {
    "0": {
      name: "パッチ済みモデル"
    }
  }
};
const CLIPAttentionMultiply$3 = {
  display_name: "CLIP注意の乗算",
  inputs: {
    clip: {
      name: "clip"
    },
    k: {
      name: "k"
    },
    out: {
      name: "出力"
    },
    q: {
      name: "q"
    },
    v: {
      name: "v"
    }
  }
};
const CLIPLoader$3 = {
  description: "[レシピ]\n\nstable_diffusion: clip-l\nstable_cascade: clip-g\nsd3: t5 / clip-g / clip-l\nstable_audio: t5\nmochi: t5\ncosmos: old t5 xxl",
  display_name: "CLIPを読み込む",
  inputs: {
    clip_name: {
      name: "clip名"
    },
    device: {
      name: "デバイス"
    },
    type: {
      name: "タイプ"
    }
  }
};
const CLIPMergeAdd$3 = {
  display_name: "CLIPマージ追加",
  inputs: {
    clip1: {
      name: "clip1"
    },
    clip2: {
      name: "clip2"
    }
  }
};
const CLIPMergeSimple$3 = {
  display_name: "CLIPマージシンプル",
  inputs: {
    clip1: {
      name: "clip1"
    },
    clip2: {
      name: "clip2"
    },
    ratio: {
      name: "比率"
    }
  }
};
const CLIPMergeSubtract$3 = {
  display_name: "CLIPマージ減算",
  inputs: {
    clip1: {
      name: "clip1"
    },
    clip2: {
      name: "clip2"
    },
    multiplier: {
      name: "乗数"
    }
  }
};
const CLIPSave$3 = {
  display_name: "CLIPを保存",
  inputs: {
    clip: {
      name: "clip"
    },
    filename_prefix: {
      name: "ファイル名プレフィックス"
    }
  }
};
const CLIPSetLastLayer$3 = {
  display_name: "CLIPの最終層を設定",
  inputs: {
    clip: {
      name: "クリップ"
    },
    stop_at_clip_layer: {
      name: "クリップ_レイヤーで停止"
    }
  }
};
const CLIPTextEncode$3 = {
  description: "テキストプロンプトをCLIPモデルを使用してエンコードし、特定の画像を生成するために拡散モデルをガイドするために使用できる埋め込みに変換します。",
  display_name: "CLIPテキストエンコード（プロンプト）",
  inputs: {
    clip: {
      name: "クリップ",
      tooltip: "テキストのエンコードに使用されるCLIPモデル。"
    },
    text: {
      name: "テキスト",
      tooltip: "エンコードするテキスト。"
    }
  },
  outputs: {
    "0": {
      tooltip: "拡散モデルをガイドするために使用される埋め込まれたテキストを含む条件付け。"
    }
  }
};
const CLIPTextEncodeControlnet$3 = {
  display_name: "CLIPテキストエンコードコントロールネット",
  inputs: {
    clip: {
      name: "クリップ"
    },
    conditioning: {
      name: "コンディショニング"
    },
    text: {
      name: "テキスト"
    }
  }
};
const CLIPTextEncodeFlux$3 = {
  display_name: "CLIPテキストエンコードフラックス",
  inputs: {
    clip: {
      name: "クリップ"
    },
    clip_l: {
      name: "クリップ_l"
    },
    guidance: {
      name: "ガイダンス"
    },
    t5xxl: {
      name: "t5xxl"
    }
  }
};
const CLIPTextEncodeHiDream$3 = {
  display_name: "CLIPTextEncodeHiDream",
  inputs: {
    clip: {
      name: "clip"
    },
    clip_g: {
      name: "clip_g"
    },
    clip_l: {
      name: "clip_l"
    },
    llama: {
      name: "llama"
    },
    t5xxl: {
      name: "t5xxl"
    }
  }
};
const CLIPTextEncodeHunyuanDiT$3 = {
  display_name: "CLIPテキストエンコードフンユアンDiT",
  inputs: {
    bert: {
      name: "bert"
    },
    clip: {
      name: "クリップ"
    },
    mt5xl: {
      name: "mt5xl"
    }
  }
};
const CLIPTextEncodeLumina2$3 = {
  description: "CLIPモデルを使用してシステムプロンプトとユーザープロンプトをエンコードし、特定の画像の生成をガイドするために使用できる埋め込みを生成します。",
  display_name: "CLIP Text Encode for Lumina2",
  inputs: {
    clip: {
      name: "clip",
      tooltip: "テキストのエンコードに使用されるCLIPモデル。"
    },
    system_prompt: {
      name: "system_prompt",
      tooltip: "Lumina2は2種類のシステムプロンプトを提供します：Superior: あなたは、テキストプロンプトまたはユーザープロンプトに基づいて優れた画像と画像テキストの整列度を生成するためのアシスタントです。 Alignment: あなたは、テキストプロンプトに基づいて高品質の画像と最高度の画像テキストの整列度を生成するためのアシスタントです。"
    },
    user_prompt: {
      name: "user_prompt",
      tooltip: "エンコードするテキスト。"
    }
  },
  outputs: {
    "0": {
      tooltip: "拡散モデルをガイドするために使用される埋め込まれたテキストを含む条件付け。"
    }
  }
};
const CLIPTextEncodePixArtAlpha$3 = {
  description: "テキストをエンコードし、PixArt Alphaの解像度条件を設定します。PixArt Sigmaには適用されません。",
  display_name: "CLIPTextEncodePixArtAlpha",
  inputs: {
    clip: {
      name: "clip"
    },
    height: {
      name: "高さ"
    },
    text: {
      name: "テキスト"
    },
    width: {
      name: "幅"
    }
  }
};
const CLIPTextEncodeSD3$3 = {
  display_name: "CLIPテキストエンコードSD3",
  inputs: {
    clip: {
      name: "クリップ"
    },
    clip_g: {
      name: "クリップ_g"
    },
    clip_l: {
      name: "クリップ_l"
    },
    empty_padding: {
      name: "空のパディング"
    },
    t5xxl: {
      name: "t5xxl"
    }
  }
};
const CLIPTextEncodeSDXL$3 = {
  display_name: "CLIPテキストエンコードSDXL",
  inputs: {
    clip: {
      name: "クリップ"
    },
    crop_h: {
      name: "crop_h"
    },
    crop_w: {
      name: "crop_w"
    },
    height: {
      name: "高さ"
    },
    target_height: {
      name: "目標の高さ"
    },
    target_width: {
      name: "目標の幅"
    },
    text_g: {
      name: "テキスト_g"
    },
    text_l: {
      name: "テキスト_l"
    },
    width: {
      name: "幅"
    }
  }
};
const CLIPTextEncodeSDXLRefiner$3 = {
  display_name: "CLIPテキストエンコードSDXLリファイナー",
  inputs: {
    ascore: {
      name: "ascore"
    },
    clip: {
      name: "クリップ"
    },
    height: {
      name: "高さ"
    },
    text: {
      name: "テキスト"
    },
    width: {
      name: "幅"
    }
  }
};
const CLIPVisionEncode$3 = {
  display_name: "CLIPビジョンエンコード",
  inputs: {
    clip_vision: {
      name: "クリップビジョン"
    },
    crop: {
      name: "クロップ"
    },
    image: {
      name: "画像"
    }
  }
};
const CLIPVisionLoader$3 = {
  display_name: "CLIPビジョンを読み込む",
  inputs: {
    clip_name: {
      name: "クリップ名"
    }
  }
};
const Canny$3 = {
  display_name: "キャニー",
  inputs: {
    high_threshold: {
      name: "高い閾値"
    },
    image: {
      name: "イメージ"
    },
    low_threshold: {
      name: "低い閾値"
    }
  }
};
const CheckpointLoader$3 = {
  display_name: "設定でチェックポイントを読み込む（非推奨）",
  inputs: {
    ckpt_name: {
      name: "ckpt名"
    },
    config_name: {
      name: "設定名"
    }
  }
};
const CheckpointLoaderSimple$3 = {
  description: "拡散モデルのチェックポイントを読み込みます。拡散モデルは潜在変数のノイズを除去するために使用されます。",
  display_name: "チェックポイントを読み込む",
  inputs: {
    ckpt_name: {
      name: "ckpt名",
      tooltip: "読み込むチェックポイント（モデル）の名前。"
    }
  },
  outputs: {
    "0": {
      tooltip: "潜在変数のデノイズに使用されるモデル。"
    },
    "1": {
      tooltip: "テキストプロンプトをエンコードするために使用されるCLIPモデル。"
    },
    "2": {
      tooltip: "画像を潜在空間にエンコードおよびデコードするために使用されるVAEモデル。"
    }
  }
};
const CheckpointSave$3 = {
  display_name: "チェックポイントを保存",
  inputs: {
    clip: {
      name: "clip"
    },
    filename_prefix: {
      name: "ファイル名プレフィックス"
    },
    model: {
      name: "モデル"
    },
    vae: {
      name: "vae"
    }
  }
};
const CombineHooks2$3 = {
  display_name: "フックを組み合わせる [2]",
  inputs: {
    hooks_A: {
      name: "フック_A"
    },
    hooks_B: {
      name: "フック_B"
    }
  }
};
const CombineHooks4$3 = {
  display_name: "フックを組み合わせる [4]",
  inputs: {
    hooks_A: {
      name: "フック_A"
    },
    hooks_B: {
      name: "フック_B"
    },
    hooks_C: {
      name: "フック_C"
    },
    hooks_D: {
      name: "フック_D"
    }
  }
};
const CombineHooks8$3 = {
  display_name: "フックを組み合わせる [8]",
  inputs: {
    hooks_A: {
      name: "フック_A"
    },
    hooks_B: {
      name: "フック_B"
    },
    hooks_C: {
      name: "フック_C"
    },
    hooks_D: {
      name: "フック_D"
    },
    hooks_E: {
      name: "フック_E"
    },
    hooks_F: {
      name: "フック_F"
    },
    hooks_G: {
      name: "フック_G"
    },
    hooks_H: {
      name: "フック_H"
    }
  }
};
const ConditioningAverage$3 = {
  display_name: "条件付け平均",
  inputs: {
    conditioning_from: {
      name: "条件付け元"
    },
    conditioning_to: {
      name: "条件付け先"
    },
    conditioning_to_strength: {
      name: "条件付け先の強度"
    }
  }
};
const ConditioningCombine$3 = {
  display_name: "条件付け（組み合わせ）",
  inputs: {
    conditioning_1: {
      name: "条件付け_1"
    },
    conditioning_2: {
      name: "条件付け_2"
    }
  }
};
const ConditioningConcat$3 = {
  display_name: "条件付け（連結）",
  inputs: {
    conditioning_from: {
      name: "条件付け元"
    },
    conditioning_to: {
      name: "条件付け先"
    }
  }
};
const ConditioningSetArea$3 = {
  display_name: "条件付け（エリア設定）",
  inputs: {
    conditioning: {
      name: "条件付け"
    },
    height: {
      name: "高さ"
    },
    strength: {
      name: "強度"
    },
    width: {
      name: "幅"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const ConditioningSetAreaPercentage$3 = {
  display_name: "条件付け（パーセンテージでエリア設定）",
  inputs: {
    conditioning: {
      name: "条件付け"
    },
    height: {
      name: "高さ"
    },
    strength: {
      name: "強度"
    },
    width: {
      name: "幅"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const ConditioningSetAreaPercentageVideo$3 = {
  display_name: "ビデオの条件設定エリアのパーセンテージ",
  inputs: {
    conditioning: {
      name: "条件設定"
    },
    height: {
      name: "高さ"
    },
    strength: {
      name: "強度"
    },
    temporal: {
      name: "時間的"
    },
    width: {
      name: "幅"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    },
    z: {
      name: "z"
    }
  }
};
const ConditioningSetAreaStrength$3 = {
  display_name: "条件付けエリア強度",
  inputs: {
    conditioning: {
      name: "条件付け"
    },
    strength: {
      name: "強度"
    }
  }
};
const ConditioningSetDefaultCombine$3 = {
  display_name: "条件付けデフォルト組み合わせを設定",
  inputs: {
    cond: {
      name: "条件"
    },
    cond_DEFAULT: {
      name: "デフォルト条件"
    },
    hooks: {
      name: "フック"
    }
  }
};
const ConditioningSetMask$3 = {
  display_name: "条件付け（マスク設定）",
  inputs: {
    conditioning: {
      name: "条件付け"
    },
    mask: {
      name: "マスク"
    },
    set_cond_area: {
      name: "条件付けエリア設定"
    },
    strength: {
      name: "強度"
    }
  }
};
const ConditioningSetProperties$3 = {
  display_name: "条件付けプロパティ設定",
  inputs: {
    cond_NEW: {
      name: "新しい条件"
    },
    hooks: {
      name: "フック"
    },
    mask: {
      name: "マスク"
    },
    set_cond_area: {
      name: "条件付けエリア設定"
    },
    strength: {
      name: "強度"
    },
    timesteps: {
      name: "タイムステップ"
    }
  }
};
const ConditioningSetPropertiesAndCombine$3 = {
  display_name: "条件付けプロパティ設定と組み合わせ",
  inputs: {
    cond: {
      name: "条件"
    },
    cond_NEW: {
      name: "新しい条件"
    },
    hooks: {
      name: "フック"
    },
    mask: {
      name: "マスク"
    },
    set_cond_area: {
      name: "条件付けエリア設定"
    },
    strength: {
      name: "強度"
    },
    timesteps: {
      name: "タイムステップ"
    }
  }
};
const ConditioningSetTimestepRange$3 = {
  display_name: "条件付けタイムステップ範囲",
  inputs: {
    conditioning: {
      name: "コンディショニング"
    },
    end: {
      name: "終了"
    },
    start: {
      name: "開始"
    }
  }
};
const ConditioningStableAudio$3 = {
  display_name: "ConditioningStableAudio",
  inputs: {
    negative: {
      name: "ネガティブ"
    },
    positive: {
      name: "ポジティブ"
    },
    seconds_start: {
      name: "秒_開始"
    },
    seconds_total: {
      name: "秒_合計"
    }
  },
  outputs: {
    "0": {
      name: "ポジティブ"
    },
    "1": {
      name: "ネガティブ"
    }
  }
};
const ConditioningTimestepsRange$3 = {
  display_name: "タイムステップ範囲",
  inputs: {
    end_percent: {
      name: "終了パーセント"
    },
    start_percent: {
      name: "開始パーセント"
    }
  },
  outputs: {
    "1": {
      name: "範囲前"
    },
    "2": {
      name: "範囲後"
    }
  }
};
const ConditioningZeroOut$3 = {
  display_name: "条件付けゼロアウト",
  inputs: {
    conditioning: {
      name: "コンディショニング"
    }
  }
};
const ControlNetApply$3 = {
  display_name: "ControlNetを適用（旧）",
  inputs: {
    conditioning: {
      name: "コンディショニング"
    },
    control_net: {
      name: "コントロールネット"
    },
    image: {
      name: "画像"
    },
    strength: {
      name: "強度"
    }
  }
};
const ControlNetApplyAdvanced$3 = {
  display_name: "ControlNetを適用",
  inputs: {
    control_net: {
      name: "コントロールネット"
    },
    end_percent: {
      name: "終了パーセント"
    },
    image: {
      name: "画像"
    },
    negative: {
      name: "ネガティブ"
    },
    positive: {
      name: "ポジティブ"
    },
    start_percent: {
      name: "開始パーセント"
    },
    strength: {
      name: "強度"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "ポジティブ"
    },
    "1": {
      name: "ネガティブ"
    }
  }
};
const ControlNetApplySD3$3 = {
  display_name: "VAEでControlNetを適用",
  inputs: {
    control_net: {
      name: "コントロールネット"
    },
    end_percent: {
      name: "終了パーセント"
    },
    image: {
      name: "画像"
    },
    negative: {
      name: "ネガティブ"
    },
    positive: {
      name: "ポジティブ"
    },
    start_percent: {
      name: "開始パーセント"
    },
    strength: {
      name: "強度"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "ポジティブ"
    },
    "1": {
      name: "ネガティブ"
    }
  }
};
const ControlNetInpaintingAliMamaApply$3 = {
  display_name: "ControlNetインペインティングAliMamaを適用",
  inputs: {
    control_net: {
      name: "コントロールネット"
    },
    end_percent: {
      name: "終了パーセント"
    },
    image: {
      name: "画像"
    },
    mask: {
      name: "マスク"
    },
    negative: {
      name: "ネガティブ"
    },
    positive: {
      name: "ポジティブ"
    },
    start_percent: {
      name: "開始パーセント"
    },
    strength: {
      name: "強度"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "ポジティブ"
    },
    "1": {
      name: "ネガティブ"
    }
  }
};
const ControlNetLoader$3 = {
  display_name: "ControlNetモデルを読み込む",
  inputs: {
    control_net_name: {
      name: "コントロールネット名"
    }
  }
};
const CosmosImageToVideoLatent$3 = {
  display_name: "CosmosImageToVideoLatent",
  inputs: {
    batch_size: {
      name: "バッチサイズ"
    },
    end_image: {
      name: "終了画像"
    },
    height: {
      name: "高さ"
    },
    length: {
      name: "長さ"
    },
    start_image: {
      name: "開始画像"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "幅"
    }
  }
};
const CreateHookKeyframe$3 = {
  display_name: "フックキーフレームを作成",
  inputs: {
    prev_hook_kf: {
      name: "前のフックキーフレーム"
    },
    start_percent: {
      name: "開始パーセント"
    },
    strength_mult: {
      name: "強度倍数"
    }
  },
  outputs: {
    "0": {
      name: "フックKF"
    }
  }
};
const CreateHookKeyframesFromFloats$3 = {
  display_name: "フックキーフレームを浮動小数点から作成",
  inputs: {
    end_percent: {
      name: "終了パーセント"
    },
    floats_strength: {
      name: "浮動小数点数の強度"
    },
    prev_hook_kf: {
      name: "前のフックキーフレーム"
    },
    print_keyframes: {
      name: "キーフレームを印刷"
    },
    start_percent: {
      name: "開始パーセント"
    }
  },
  outputs: {
    "0": {
      name: "フックKF"
    }
  }
};
const CreateHookKeyframesInterpolated$3 = {
  display_name: "フックキーフレームを補間",
  inputs: {
    end_percent: {
      name: "end_percent"
    },
    interpolation: {
      name: "補間"
    },
    keyframes_count: {
      name: "キーフレーム数"
    },
    prev_hook_kf: {
      name: "prev_hook_kf"
    },
    print_keyframes: {
      name: "キーフレームを印刷"
    },
    start_percent: {
      name: "start_percent"
    },
    strength_end: {
      name: "strength_end"
    },
    strength_start: {
      name: "strength_start"
    }
  },
  outputs: {
    "0": {
      name: "フックKF"
    }
  }
};
const CreateHookLora$3 = {
  display_name: "フックLoRAを作成",
  inputs: {
    lora_name: {
      name: "lora_name"
    },
    prev_hooks: {
      name: "prev_hooks"
    },
    strength_clip: {
      name: "strength_clip"
    },
    strength_model: {
      name: "strength_model"
    }
  }
};
const CreateHookLoraModelOnly$3 = {
  display_name: "フックLoRA（モデルのみ）",
  inputs: {
    lora_name: {
      name: "lora_name"
    },
    prev_hooks: {
      name: "prev_hooks"
    },
    strength_model: {
      name: "strength_model"
    }
  }
};
const CreateHookModelAsLora$3 = {
  display_name: "フックモデルをLoRAとして作成",
  inputs: {
    ckpt_name: {
      name: "ckpt_name"
    },
    prev_hooks: {
      name: "prev_hooks"
    },
    strength_clip: {
      name: "strength_clip"
    },
    strength_model: {
      name: "strength_model"
    }
  }
};
const CreateHookModelAsLoraModelOnly$3 = {
  display_name: "フックモデルをLoRAとして作成（モデルのみ）",
  inputs: {
    ckpt_name: {
      name: "ckpt_name"
    },
    prev_hooks: {
      name: "prev_hooks"
    },
    strength_model: {
      name: "strength_model"
    }
  }
};
const CreateVideo$3 = {
  description: "画像から動画を作成します。",
  display_name: "動画を作成",
  inputs: {
    audio: {
      name: "オーディオ",
      tooltip: "動画に追加するオーディオです。"
    },
    fps: {
      name: "fps"
    },
    images: {
      name: "画像",
      tooltip: "動画を作成するための画像です。"
    }
  }
};
const CropMask$3 = {
  display_name: "マスクをトリミング",
  inputs: {
    height: {
      name: "高さ"
    },
    mask: {
      name: "マスク"
    },
    width: {
      name: "幅"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const DiffControlNetLoader$3 = {
  display_name: "ControlNetモデルを読み込む（diff）",
  inputs: {
    control_net_name: {
      name: "control_net_name"
    },
    model: {
      name: "モデル"
    }
  }
};
const DifferentialDiffusion$3 = {
  display_name: "差分拡散",
  inputs: {
    model: {
      name: "モデル"
    }
  }
};
const DiffusersLoader$3 = {
  display_name: "ディフューザーを読み込む",
  inputs: {
    model_path: {
      name: "モデルパス"
    }
  }
};
const DisableNoise$3 = {
  display_name: "ノイズを無効にする"
};
const DualCFGGuider$3 = {
  display_name: "デュアルCFGガイダー",
  inputs: {
    cfg_cond2_negative: {
      name: "cfg_cond2_negative"
    },
    cfg_conds: {
      name: "cfg_conds"
    },
    cond1: {
      name: "cond1"
    },
    cond2: {
      name: "cond2"
    },
    model: {
      name: "モデル"
    },
    negative: {
      name: "ネガティブ"
    }
  }
};
const DualCLIPLoader$3 = {
  description: "[レシピ]\n\nsdxl: clip-l, clip-g\nsd3: clip-l, clip-g / clip-l, t5 / clip-g, t5\nflux: clip-l, t5",
  display_name: "デュアルCLIPを読み込む",
  inputs: {
    clip_name1: {
      name: "clip_name1"
    },
    clip_name2: {
      name: "clip_name2"
    },
    device: {
      name: "デバイス"
    },
    type: {
      name: "タイプ"
    }
  }
};
const EmptyCosmosLatentVideo$3 = {
  display_name: "EmptyCosmosLatentVideo",
  inputs: {
    batch_size: {
      name: "バッチサイズ"
    },
    height: {
      name: "高さ"
    },
    length: {
      name: "長さ"
    },
    width: {
      name: "幅"
    }
  }
};
const EmptyHunyuanLatentVideo$3 = {
  display_name: "EmptyHunyuanLatentVideo",
  inputs: {
    batch_size: {
      name: "バッチサイズ"
    },
    height: {
      name: "高さ"
    },
    length: {
      name: "長さ"
    },
    width: {
      name: "幅"
    }
  }
};
const EmptyImage$3 = {
  display_name: "空の画像",
  inputs: {
    batch_size: {
      name: "バッチサイズ"
    },
    color: {
      name: "色"
    },
    height: {
      name: "高さ"
    },
    width: {
      name: "幅"
    }
  }
};
const EmptyLTXVLatentVideo$3 = {
  display_name: "空のLTXV潜在ビデオ",
  inputs: {
    batch_size: {
      name: "バッチサイズ"
    },
    height: {
      name: "高さ"
    },
    length: {
      name: "長さ"
    },
    width: {
      name: "幅"
    }
  }
};
const EmptyLatentAudio$3 = {
  display_name: "空の潜在音声",
  inputs: {
    batch_size: {
      name: "バッチサイズ",
      tooltip: "バッチ内の潜在画像の数。"
    },
    seconds: {
      name: "秒"
    }
  }
};
const EmptyLatentHunyuan3Dv2$3 = {
  display_name: "EmptyLatentHunyuan3Dv2",
  inputs: {
    batch_size: {
      name: "バッチサイズ",
      tooltip: "バッチ内の潜在画像の数。"
    },
    resolution: {
      name: "解像度"
    }
  }
};
const EmptyLatentImage$3 = {
  description: "サンプリングを通じてノイズを除去するための空の潜在画像の新しいバッチを作成します。",
  display_name: "空の潜在画像",
  inputs: {
    batch_size: {
      name: "バッチサイズ",
      tooltip: "バッチ内の潜在画像の数。"
    },
    height: {
      name: "高さ",
      tooltip: "潜在画像の高さ（ピクセル単位）。"
    },
    width: {
      name: "幅",
      tooltip: "潜在画像の幅（ピクセル単位）。"
    }
  },
  outputs: {
    "0": {
      tooltip: "空の潜在画像バッチ。"
    }
  }
};
const EmptyMochiLatentVideo$3 = {
  display_name: "空のMochi潜在ビデオ",
  inputs: {
    batch_size: {
      name: "バッチサイズ"
    },
    height: {
      name: "高さ"
    },
    length: {
      name: "長さ"
    },
    width: {
      name: "幅"
    }
  }
};
const EmptySD3LatentImage$3 = {
  display_name: "空のSD3潜在画像",
  inputs: {
    batch_size: {
      name: "バッチサイズ"
    },
    height: {
      name: "高さ"
    },
    width: {
      name: "幅"
    }
  }
};
const ExponentialScheduler$3 = {
  display_name: "指数スケジューラー",
  inputs: {
    sigma_max: {
      name: "sigma_max"
    },
    sigma_min: {
      name: "sigma_min"
    },
    steps: {
      name: "ステップ"
    }
  }
};
const ExtendIntermediateSigmas$3 = {
  display_name: "ExtendIntermediateSigmas",
  inputs: {
    end_at_sigma: {
      name: "終了シグマ"
    },
    sigmas: {
      name: "sigmas"
    },
    spacing: {
      name: "間隔"
    },
    start_at_sigma: {
      name: "開始シグマ"
    },
    steps: {
      name: "ステップ数"
    }
  }
};
const FeatherMask$3 = {
  display_name: "フェザー マスク",
  inputs: {
    bottom: {
      name: "下"
    },
    left: {
      name: "左"
    },
    mask: {
      name: "マスク"
    },
    right: {
      name: "右"
    },
    top: {
      name: "上"
    }
  }
};
const FlipSigmas$3 = {
  display_name: "シグマを反転",
  inputs: {
    sigmas: {
      name: "sigmas"
    }
  }
};
const FluxDisableGuidance$3 = {
  description: "このノードはFluxおよびFluxのようなモデルのガイダンス埋め込みを完全に無効にします",
  display_name: "FluxDisableGuidance",
  inputs: {
    conditioning: {
      name: "conditioning"
    }
  }
};
const FluxGuidance$3 = {
  display_name: "フラックスガイダンス",
  inputs: {
    conditioning: {
      name: "コンディショニング"
    },
    guidance: {
      name: "ガイダンス"
    }
  }
};
const FluxProCannyNode$3 = {
  description: "コントロール画像（canny）を使用して画像を生成します。",
  display_name: "Flux.1 Canny コントロール画像",
  inputs: {
    canny_high_threshold: {
      name: "canny_high_threshold",
      tooltip: "Cannyエッジ検出の高しきい値。skip_processingがTrueの場合は無視されます。"
    },
    canny_low_threshold: {
      name: "canny_low_threshold",
      tooltip: "Cannyエッジ検出の低しきい値。skip_processingがTrueの場合は無視されます。"
    },
    control_after_generate: {
      name: "control after generate"
    },
    control_image: {
      name: "control_image"
    },
    guidance: {
      name: "guidance",
      tooltip: "画像生成プロセスのガイダンス強度"
    },
    prompt: {
      name: "prompt",
      tooltip: "画像生成のためのプロンプト"
    },
    prompt_upsampling: {
      name: "prompt_upsampling",
      tooltip: "プロンプトのアップサンプリングを行うかどうか。有効にすると、より創造的な生成のためにプロンプトが自動的に修正されますが、結果は非決定的になります（同じシードでも全く同じ結果にはなりません）。"
    },
    seed: {
      name: "seed",
      tooltip: "ノイズ生成に使用されるランダムシード。"
    },
    skip_preprocessing: {
      name: "skip_preprocessing",
      tooltip: "前処理をスキップするかどうか。control_imageがすでにcanny化されている場合はTrue、生の画像の場合はFalseに設定してください。"
    },
    steps: {
      name: "steps",
      tooltip: "画像生成プロセスのステップ数"
    }
  }
};
const FluxProDepthNode$3 = {
  description: "コントロール画像（深度）を使用して画像を生成します。",
  display_name: "Flux.1 デプスコントロール画像",
  inputs: {
    control_after_generate: {
      name: "生成後コントロール"
    },
    control_image: {
      name: "control_image"
    },
    guidance: {
      name: "ガイダンス",
      tooltip: "画像生成プロセスのガイダンス強度"
    },
    prompt: {
      name: "プロンプト",
      tooltip: "画像生成のためのプロンプト"
    },
    prompt_upsampling: {
      name: "プロンプトアップサンプリング",
      tooltip: "プロンプトにアップサンプリングを行うかどうか。有効にすると、より創造的な生成のためにプロンプトが自動的に修正されますが、結果は非決定的になります（同じシードでも全く同じ結果にはなりません）。"
    },
    seed: {
      name: "シード",
      tooltip: "ノイズ生成に使用されるランダムシード。"
    },
    skip_preprocessing: {
      name: "前処理をスキップ",
      tooltip: "前処理をスキップするかどうか。control_imageがすでに深度化されている場合はTrue、生の画像の場合はFalseに設定してください。"
    },
    steps: {
      name: "ステップ数",
      tooltip: "画像生成プロセスのステップ数"
    }
  }
};
const FluxProExpandNode$3 = {
  description: "プロンプトに基づいて画像をアウトペイントします。",
  display_name: "Flux.1 画像拡張",
  inputs: {
    bottom: {
      name: "下",
      tooltip: "画像の下部に拡張するピクセル数"
    },
    control_after_generate: {
      name: "生成後のコントロール"
    },
    guidance: {
      name: "ガイダンス",
      tooltip: "画像生成プロセスのガイダンス強度"
    },
    image: {
      name: "画像"
    },
    left: {
      name: "左",
      tooltip: "画像の左側に拡張するピクセル数"
    },
    prompt: {
      name: "プロンプト",
      tooltip: "画像生成用のプロンプト"
    },
    prompt_upsampling: {
      name: "プロンプトアップサンプリング",
      tooltip: "プロンプトにアップサンプリングを行うかどうか。有効にすると、より創造的な生成のためにプロンプトが自動的に修正されますが、結果は非決定的になります（同じシードでも全く同じ結果にはなりません）。"
    },
    right: {
      name: "右",
      tooltip: "画像の右側に拡張するピクセル数"
    },
    seed: {
      name: "シード",
      tooltip: "ノイズ生成に使用されるランダムシード。"
    },
    steps: {
      name: "ステップ数",
      tooltip: "画像生成プロセスのステップ数"
    },
    top: {
      name: "上",
      tooltip: "画像の上部に拡張するピクセル数"
    }
  }
};
const FluxProFillNode$3 = {
  description: "マスクとプロンプトに基づいて画像をインペイントします。",
  display_name: "Flux.1 画像塗りつぶし",
  inputs: {
    control_after_generate: {
      name: "生成後のコントロール"
    },
    guidance: {
      name: "ガイダンス",
      tooltip: "画像生成プロセスのガイダンス強度"
    },
    image: {
      name: "画像"
    },
    mask: {
      name: "マスク"
    },
    prompt: {
      name: "プロンプト",
      tooltip: "画像生成用のプロンプト"
    },
    prompt_upsampling: {
      name: "プロンプトアップサンプリング",
      tooltip: "プロンプトにアップサンプリングを行うかどうか。有効にすると、より創造的な生成のためにプロンプトが自動的に修正されますが、結果は非決定的になります（同じシードでも全く同じ結果にはなりません）。"
    },
    seed: {
      name: "シード",
      tooltip: "ノイズ生成に使用されるランダムシード。"
    },
    steps: {
      name: "ステップ数",
      tooltip: "画像生成プロセスのステップ数"
    }
  }
};
const FluxProUltraImageNode$3 = {
  description: "プロンプトと解像度に基づき、API経由でFlux Pro 1.1 Ultraを使用して画像を生成します。",
  display_name: "Flux 1.1 [pro] ウルトラ画像",
  inputs: {
    aspect_ratio: {
      name: "アスペクト比",
      tooltip: "画像のアスペクト比。1:4から4:1の間で指定してください。"
    },
    control_after_generate: {
      name: "生成後のコントロール"
    },
    image_prompt: {
      name: "画像プロンプト"
    },
    image_prompt_strength: {
      name: "画像プロンプト強度",
      tooltip: "プロンプトと画像プロンプトのブレンド比率。"
    },
    prompt: {
      name: "プロンプト",
      tooltip: "画像生成のためのプロンプト"
    },
    prompt_upsampling: {
      name: "プロンプトアップサンプリング",
      tooltip: "プロンプトにアップサンプリングを行うかどうか。有効にすると、よりクリエイティブな生成のためにプロンプトが自動的に修正されますが、結果は非決定的になります（同じシードでも全く同じ結果にはなりません）。"
    },
    raw: {
      name: "生画像",
      tooltip: "Trueの場合、処理が少なく、より自然な見た目の画像を生成します。"
    },
    seed: {
      name: "シード",
      tooltip: "ノイズ生成に使用されるランダムシード。"
    }
  }
};
const FreSca$3 = {
  description: "ガイダンスに周波数依存のスケーリングを適用します",
  display_name: "FreSca",
  inputs: {
    freq_cutoff: {
      name: "freq_cutoff",
      tooltip: "中心付近の低周波数成分として扱う周波数インデックス数"
    },
    model: {
      name: "model"
    },
    scale_high: {
      name: "scale_high",
      tooltip: "高周波成分のスケーリング係数"
    },
    scale_low: {
      name: "scale_low",
      tooltip: "低周波成分のスケーリング係数"
    }
  }
};
const FreeU$3 = {
  display_name: "FreeU",
  inputs: {
    b1: {
      name: "b1"
    },
    b2: {
      name: "b2"
    },
    model: {
      name: "モデル"
    },
    s1: {
      name: "s1"
    },
    s2: {
      name: "s2"
    }
  }
};
const FreeU_V2$3 = {
  display_name: "FreeU_V2",
  inputs: {
    b1: {
      name: "b1"
    },
    b2: {
      name: "b2"
    },
    model: {
      name: "モデル"
    },
    s1: {
      name: "s1"
    },
    s2: {
      name: "s2"
    }
  }
};
const GITSScheduler$3 = {
  display_name: "GITSスケジューラー",
  inputs: {
    coeff: {
      name: "係数"
    },
    denoise: {
      name: "ノイズ除去"
    },
    steps: {
      name: "ステップ"
    }
  }
};
const GLIGENLoader$3 = {
  display_name: "GLIGENを読み込む",
  inputs: {
    gligen_name: {
      name: "gligen_name"
    }
  }
};
const GLIGENTextBoxApply$3 = {
  display_name: "GLIGENテキストボックスを適用",
  inputs: {
    clip: {
      name: "クリップ"
    },
    conditioning_to: {
      name: "条件付け先"
    },
    gligen_textbox_model: {
      name: "gligen_textbox_model"
    },
    height: {
      name: "高さ"
    },
    text: {
      name: "テキスト"
    },
    width: {
      name: "幅"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const GetVideoComponents$3 = {
  description: "ビデオからすべてのコンポーネント（フレーム、オーディオ、フレームレート）を抽出します。",
  display_name: "ビデオコンポーネントの取得",
  inputs: {
    video: {
      name: "ビデオ",
      tooltip: "コンポーネントを抽出するビデオ。"
    }
  },
  outputs: {
    "0": {
      name: "画像"
    },
    "1": {
      name: "オーディオ"
    },
    "2": {
      name: "fps"
    }
  }
};
const GrowMask$3 = {
  display_name: "マスクを拡大",
  inputs: {
    expand: {
      name: "拡大"
    },
    mask: {
      name: "マスク"
    },
    tapered_corners: {
      name: "テーパードコーナー"
    }
  }
};
const Hunyuan3Dv2Conditioning$3 = {
  display_name: "Hunyuan3Dv2Conditioning",
  inputs: {
    clip_vision_output: {
      name: "clip_vision_output"
    }
  },
  outputs: {
    "0": {
      name: "ポジティブ"
    },
    "1": {
      name: "ネガティブ"
    }
  }
};
const Hunyuan3Dv2ConditioningMultiView$3 = {
  display_name: "Hunyuan3Dv2ConditioningMultiView",
  inputs: {
    back: {
      name: "バック"
    },
    front: {
      name: "フロント"
    },
    left: {
      name: "左"
    },
    right: {
      name: "右"
    }
  },
  outputs: {
    "0": {
      name: "ポジティブ"
    },
    "1": {
      name: "ネガティブ"
    }
  }
};
const HunyuanImageToVideo$3 = {
  display_name: "HunyuanImageToVideo",
  inputs: {
    batch_size: {
      name: "バッチサイズ"
    },
    guidance_type: {
      name: "ガイダンスタイプ"
    },
    height: {
      name: "高さ"
    },
    length: {
      name: "長さ"
    },
    positive: {
      name: "ポジティブ"
    },
    start_image: {
      name: "開始画像"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "幅"
    }
  },
  outputs: {
    "0": {
      name: "ポジティブ"
    },
    "1": {
      name: "潜在"
    }
  }
};
const HyperTile$3 = {
  display_name: "ハイパータイル",
  inputs: {
    max_depth: {
      name: "最大深度"
    },
    model: {
      name: "モデル"
    },
    scale_depth: {
      name: "スケール深度"
    },
    swap_size: {
      name: "スワップサイズ"
    },
    tile_size: {
      name: "タイルサイズ"
    }
  }
};
const HypernetworkLoader$3 = {
  display_name: "ハイパーネットワークを読み込む",
  inputs: {
    hypernetwork_name: {
      name: "hypernetwork_name"
    },
    model: {
      name: "モデル"
    },
    strength: {
      name: "強度"
    }
  }
};
const IdeogramV1$3 = {
  description: "Ideogram V1モデルを使用して同期的に画像を生成します。\n\n画像リンクは一定期間のみ有効です。画像を保存したい場合は、ダウンロードしてください。",
  display_name: "Ideogram V1",
  inputs: {
    aspect_ratio: {
      name: "アスペクト比",
      tooltip: "画像生成のアスペクト比。"
    },
    control_after_generate: {
      name: "生成後のコントロール"
    },
    magic_prompt_option: {
      name: "マジックプロンプトオプション",
      tooltip: "生成時にMagicPromptを使用するかどうかを決定"
    },
    negative_prompt: {
      name: "ネガティブプロンプト",
      tooltip: "画像から除外したい内容の説明"
    },
    num_images: {
      name: "画像数"
    },
    prompt: {
      name: "プロンプト",
      tooltip: "画像生成のためのプロンプト"
    },
    seed: {
      name: "シード"
    },
    turbo: {
      name: "ターボ",
      tooltip: "ターボモードを使用するかどうか（高速生成、品質が低下する可能性あり）"
    }
  }
};
const IdeogramV2$3 = {
  description: "Ideogram V2モデルを使用して同期的に画像を生成します。\n\n画像リンクは一定期間のみ有効です。画像を保存したい場合は、ダウンロードしてください。",
  display_name: "Ideogram V2",
  inputs: {
    aspect_ratio: {
      name: "アスペクト比",
      tooltip: "画像生成のアスペクト比。解像度がAUTOでない場合は無視されます。"
    },
    control_after_generate: {
      name: "生成後のコントロール"
    },
    magic_prompt_option: {
      name: "マジックプロンプトオプション",
      tooltip: "生成時にMagicPromptを使用するかどうかを決定します"
    },
    negative_prompt: {
      name: "ネガティブプロンプト",
      tooltip: "画像から除外したい内容の説明"
    },
    num_images: {
      name: "画像数"
    },
    prompt: {
      name: "プロンプト",
      tooltip: "画像生成のためのプロンプト"
    },
    resolution: {
      name: "解像度",
      tooltip: "画像生成の解像度。AUTOでない場合、aspect_ratioの設定を上書きします。"
    },
    seed: {
      name: "シード"
    },
    style_type: {
      name: "スタイルタイプ",
      tooltip: "生成時のスタイルタイプ（V2のみ）"
    },
    turbo: {
      name: "ターボ",
      tooltip: "ターボモードを使用するかどうか（高速生成、品質が低下する可能性あり）"
    }
  }
};
const IdeogramV3$3 = {
  description: "Ideogram V3モデルを使用して同期的に画像を生成します。\n\nテキストプロンプトからの通常の画像生成と、マスクを使った画像編集の両方に対応しています。\n画像リンクは一定期間のみ有効です。画像を保存したい場合は、必ずダウンロードしてください。",
  display_name: "Ideogram V3",
  inputs: {
    aspect_ratio: {
      name: "アスペクト比",
      tooltip: "画像生成時のアスペクト比。解像度が自動でない場合は無視されます。"
    },
    control_after_generate: {
      name: "生成後のコントロール"
    },
    image: {
      name: "画像",
      tooltip: "画像編集用のオプションの参照画像。"
    },
    magic_prompt_option: {
      name: "マジックプロンプトオプション",
      tooltip: "生成時にMagicPromptを使用するかどうかを決定します"
    },
    mask: {
      name: "マスク",
      tooltip: "インペインティング用のオプションのマスク（白い部分が置き換えられます）"
    },
    num_images: {
      name: "画像数"
    },
    prompt: {
      name: "プロンプト",
      tooltip: "画像生成または編集のためのプロンプト"
    },
    rendering_speed: {
      name: "レンダリング速度",
      tooltip: "生成速度と品質のトレードオフを制御します"
    },
    resolution: {
      name: "解像度",
      tooltip: "画像生成時の解像度。自動でない場合、アスペクト比の設定を上書きします。"
    },
    seed: {
      name: "シード"
    }
  }
};
const ImageBatch$3 = {
  display_name: "画像バッチ",
  inputs: {
    image1: {
      name: "画像1"
    },
    image2: {
      name: "画像2"
    }
  }
};
const ImageBlend$3 = {
  display_name: "画像ブレンド",
  inputs: {
    blend_factor: {
      name: "ブレンドファクター"
    },
    blend_mode: {
      name: "ブレンドモード"
    },
    image1: {
      name: "画像1"
    },
    image2: {
      name: "画像2"
    }
  }
};
const ImageBlur$3 = {
  display_name: "画像ぼかし",
  inputs: {
    blur_radius: {
      name: "ブラーレイディウス"
    },
    image: {
      name: "画像"
    },
    sigma: {
      name: "シグマ"
    }
  }
};
const ImageColorToMask$3 = {
  display_name: "画像色をマスクに変換",
  inputs: {
    color: {
      name: "色"
    },
    image: {
      name: "画像"
    }
  }
};
const ImageCompositeMasked$3 = {
  display_name: "マスクされた画像合成",
  inputs: {
    destination: {
      name: "宛先"
    },
    mask: {
      name: "マスク"
    },
    resize_source: {
      name: "ソースのリサイズ"
    },
    source: {
      name: "ソース"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const ImageCrop$3 = {
  display_name: "画像トリミング",
  inputs: {
    height: {
      name: "高さ"
    },
    image: {
      name: "画像"
    },
    width: {
      name: "幅"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const ImageFromBatch$3 = {
  display_name: "バッチから画像を取得",
  inputs: {
    batch_index: {
      name: "バッチインデックス"
    },
    image: {
      name: "画像"
    },
    length: {
      name: "長さ"
    }
  }
};
const ImageInvert$3 = {
  display_name: "画像を反転",
  inputs: {
    image: {
      name: "画像"
    }
  }
};
const ImageOnlyCheckpointLoader$3 = {
  display_name: "画像のみのチェックポイントローダー（img2vidモデル）",
  inputs: {
    ckpt_name: {
      name: "ckpt_name"
    }
  }
};
const ImageOnlyCheckpointSave$3 = {
  display_name: "画像のみのチェックポイント保存",
  inputs: {
    clip_vision: {
      name: "clip_vision"
    },
    filename_prefix: {
      name: "ファイル名プレフィックス"
    },
    model: {
      name: "モデル"
    },
    vae: {
      name: "vae"
    }
  }
};
const ImagePadForOutpaint$3 = {
  display_name: "アウトペイント用に画像をパッド",
  inputs: {
    bottom: {
      name: "下"
    },
    feathering: {
      name: "フェザリング"
    },
    image: {
      name: "画像"
    },
    left: {
      name: "左"
    },
    right: {
      name: "右"
    },
    top: {
      name: "上"
    }
  }
};
const ImageQuantize$3 = {
  display_name: "画像を量子化",
  inputs: {
    colors: {
      name: "色"
    },
    dither: {
      name: "ディザリング"
    },
    image: {
      name: "画像"
    }
  }
};
const ImageRGBToYUV$3 = {
  display_name: "ImageRGBToYUV",
  inputs: {
    image: {
      name: "画像"
    }
  },
  outputs: {
    "0": {
      name: "Y"
    },
    "1": {
      name: "U"
    },
    "2": {
      name: "V"
    }
  }
};
const ImageScale$3 = {
  display_name: "画像を拡大",
  inputs: {
    crop: {
      name: "クロップ"
    },
    height: {
      name: "高さ"
    },
    image: {
      name: "画像"
    },
    upscale_method: {
      name: "拡大方法"
    },
    width: {
      name: "幅"
    }
  }
};
const ImageScaleBy$3 = {
  display_name: "画像を拡大（指定サイズ）",
  inputs: {
    image: {
      name: "画像"
    },
    scale_by: {
      name: "スケールバイ"
    },
    upscale_method: {
      name: "拡大方法"
    }
  }
};
const ImageScaleToTotalPixels$3 = {
  display_name: "画像を総ピクセルにスケール",
  inputs: {
    image: {
      name: "画像"
    },
    megapixels: {
      name: "メガピクセル"
    },
    upscale_method: {
      name: "拡大方法"
    }
  }
};
const ImageSharpen$3 = {
  display_name: "画像をシャープ化",
  inputs: {
    alpha: {
      name: "アルファ"
    },
    image: {
      name: "画像"
    },
    sharpen_radius: {
      name: "シャープ化半径"
    },
    sigma: {
      name: "シグマ"
    }
  }
};
const ImageToMask$3 = {
  display_name: "画像をマスクに変換",
  inputs: {
    channel: {
      name: "チャンネル"
    },
    image: {
      name: "画像"
    }
  }
};
const ImageUpscaleWithModel$3 = {
  display_name: "モデルを使用して画像を拡大",
  inputs: {
    image: {
      name: "画像"
    },
    upscale_model: {
      name: "拡大モデル"
    }
  }
};
const ImageYUVToRGB$3 = {
  display_name: "ImageYUVToRGB",
  inputs: {
    U: {
      name: "U"
    },
    V: {
      name: "V"
    },
    Y: {
      name: "Y"
    }
  }
};
const InpaintModelConditioning$3 = {
  display_name: "インペイントモデル条件付け",
  inputs: {
    mask: {
      name: "マスク"
    },
    negative: {
      name: "ネガティブ"
    },
    noise_mask: {
      name: "ノイズマスク",
      tooltip: "潜在にノイズマスクを追加し、サンプリングがマスク内でのみ行われるようにします。モデルによっては結果が改善されるか、完全に壊れる可能性があります。"
    },
    pixels: {
      name: "ピクセル"
    },
    positive: {
      name: "ポジティブ"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "ポジティブ"
    },
    "1": {
      name: "ネガティブ"
    },
    "2": {
      name: "潜在"
    }
  }
};
const InstructPixToPixConditioning$3 = {
  display_name: "PixToPix条件付け",
  inputs: {
    negative: {
      name: "ネガティブ"
    },
    pixels: {
      name: "ピクセル"
    },
    positive: {
      name: "ポジティブ"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "ポジティブ"
    },
    "1": {
      name: "ネガティブ"
    },
    "2": {
      name: "潜在"
    }
  }
};
const InvertMask$3 = {
  display_name: "マスクを反転",
  inputs: {
    mask: {
      name: "マスク"
    }
  }
};
const JoinImageWithAlpha$3 = {
  display_name: "アルファで画像を結合",
  inputs: {
    alpha: {
      name: "アルファ"
    },
    image: {
      name: "画像"
    }
  }
};
const KSampler$3 = {
  description: "提供されたモデル、正の条件付けと負の条件付けを使用して潜在画像のノイズを除去します。",
  display_name: "Kサンプラー",
  inputs: {
    cfg: {
      name: "cfg",
      tooltip: "Classifier-Free Guidanceスケールは、創造性とプロンプトへの遵守のバランスを取ります。値が高いほど、生成される画像はプロンプトにより近くなりますが、値が高すぎると品質に悪影響を及ぼす可能性があります。"
    },
    control_after_generate: {
      name: "生成後の制御"
    },
    denoise: {
      name: "ノイズ除去",
      tooltip: "適用されるデノイズの量。値が低いほど、初期画像の構造を維持し、画像から画像へのサンプリングが可能になります。"
    },
    latent_image: {
      name: "潜在画像",
      tooltip: "デノイズする潜在画像。"
    },
    model: {
      name: "モデル",
      tooltip: "入力潜在のデノイズに使用されるモデル。"
    },
    negative: {
      name: "ネガティブ",
      tooltip: "画像から除外したい属性を説明する条件付け。"
    },
    positive: {
      name: "ポジティブ",
      tooltip: "画像に含めたい属性を説明する条件付け。"
    },
    sampler_name: {
      name: "サンプラー名",
      tooltip: "サンプリング時に使用されるアルゴリズムで、生成される出力の品質、速度、スタイルに影響を与える可能性があります。"
    },
    scheduler: {
      name: "スケジューラ",
      tooltip: "スケジューラは、ノイズが徐々に除去されて画像が形成される方法を制御します。"
    },
    seed: {
      name: "シード",
      tooltip: "ノイズを生成するために使用されるランダムシード。"
    },
    steps: {
      name: "ステップ",
      tooltip: "デノイズプロセスで使用されるステップ数。"
    }
  },
  outputs: {
    "0": {
      tooltip: "デノイズされた潜在変数。"
    }
  }
};
const KSamplerAdvanced$3 = {
  display_name: "Kサンプラー（高度）",
  inputs: {
    add_noise: {
      name: "ノイズ追加"
    },
    cfg: {
      name: "cfg"
    },
    control_after_generate: {
      name: "生成後の制御"
    },
    end_at_step: {
      name: "ステップ終了"
    },
    latent_image: {
      name: "潜在画像"
    },
    model: {
      name: "モデル"
    },
    negative: {
      name: "ネガティブ"
    },
    noise_seed: {
      name: "ノイズシード"
    },
    positive: {
      name: "ポジティブ"
    },
    return_with_leftover_noise: {
      name: "残りのノイズと一緒に返す"
    },
    sampler_name: {
      name: "サンプラー名"
    },
    scheduler: {
      name: "スケジューラ"
    },
    start_at_step: {
      name: "ステップ開始"
    },
    steps: {
      name: "ステップ"
    }
  }
};
const KSamplerSelect$3 = {
  display_name: "Kサンプラー選択",
  inputs: {
    sampler_name: {
      name: "サンプラー名"
    }
  }
};
const KarrasScheduler$3 = {
  display_name: "カラススケジューラー",
  inputs: {
    rho: {
      name: "ロー"
    },
    sigma_max: {
      name: "シグマ_最大"
    },
    sigma_min: {
      name: "シグマ_最小"
    },
    steps: {
      name: "ステップ"
    }
  }
};
const KlingCameraControlI2VNode$3 = {
  description: "静止画像を、実際の映画撮影のようなプロフェッショナルなカメラ動作でシネマティックな動画に変換します。ズーム、回転、パン、チルト、一人称視点などのバーチャルカメラ操作を制御し、元画像へのフォーカスを維持します。",
  display_name: "Kling 画像から動画へ（カメラコントロール）",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio"
    },
    camera_control: {
      name: "camera_control",
      tooltip: "Kling Camera Controlsノードで作成できます。動画生成時のカメラの動きやモーションを制御します。"
    },
    cfg_scale: {
      name: "cfg_scale"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "ネガティブテキストプロンプト"
    },
    prompt: {
      name: "prompt",
      tooltip: "ポジティブテキストプロンプト"
    },
    start_frame: {
      name: "start_frame",
      tooltip: "参照画像 - URLまたはBase64エンコード文字列。10MBを超えず、解像度は300×300px以上、アスペクト比は1:2.5〜2.5:1の範囲。Base64の場合、data:imageプレフィックスは含めないでください。"
    }
  },
  outputs: {
    "1": {
      name: "video_id"
    },
    "2": {
      name: "duration"
    }
  }
};
const KlingCameraControlT2VNode$3 = {
  description: "テキストを本格的なカメラワークで映画のようなビデオに変換します。ズーム、回転、パン、チルト、一人称視点など、実際の映画撮影を模したバーチャルカメラの動きを制御し、元のテキストの内容に焦点を当てたまま映像を生成します。",
  display_name: "Kling テキストからビデオへ（カメラコントロール）",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio"
    },
    camera_control: {
      name: "camera_control",
      tooltip: "Kling Camera Controlsノードで作成できます。ビデオ生成中のカメラの動きやモーションを制御します。"
    },
    cfg_scale: {
      name: "cfg_scale"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "ネガティブなテキストプロンプト"
    },
    prompt: {
      name: "prompt",
      tooltip: "ポジティブなテキストプロンプト"
    }
  },
  outputs: {
    "1": {
      name: "video_id"
    },
    "2": {
      name: "duration"
    }
  }
};
const KlingCameraControls$3 = {
  description: "Klingカメラコントロールおよびモーションコントロール効果の設定オプションを指定できます。",
  display_name: "Klingカメラコントロール",
  inputs: {
    camera_control_type: {
      name: "camera_control_type"
    },
    horizontal_movement: {
      name: "horizontal_movement",
      tooltip: "カメラの水平方向（x軸）の動きを制御します。負の値は左、正の値は右を示します。"
    },
    pan: {
      name: "pan",
      tooltip: "カメラの垂直面（x軸）での回転を制御します。負の値は下方向への回転、正の値は上方向への回転を示します。"
    },
    roll: {
      name: "roll",
      tooltip: "カメラの回転量（z軸）を制御します。負の値は反時計回り、正の値は時計回りを示します。"
    },
    tilt: {
      name: "tilt",
      tooltip: "カメラの水平面（y軸）での回転を制御します。負の値は左回転、正の値は右回転を示します。"
    },
    vertical_movement: {
      name: "vertical_movement",
      tooltip: "カメラの垂直方向（y軸）の動きを制御します。負の値は下方向、正の値は上方向を示します。"
    },
    zoom: {
      name: "zoom",
      tooltip: "カメラの焦点距離の変化を制御します。負の値は視野が狭くなり、正の値は視野が広くなります。"
    }
  },
  outputs: {
    "0": {
      name: "camera_control"
    }
  }
};
const KlingDualCharacterVideoEffectNode$3 = {
  description: "effect_scene に基づいて動画生成時に様々な特殊効果を実現します。最初の画像は合成画像の左側に、2番目の画像は右側に配置されます。",
  display_name: "Kling デュアルキャラクター動画エフェクト",
  inputs: {
    duration: {
      name: "duration"
    },
    effect_scene: {
      name: "effect_scene"
    },
    image_left: {
      name: "image_left",
      tooltip: "左側の画像"
    },
    image_right: {
      name: "image_right",
      tooltip: "右側の画像"
    },
    mode: {
      name: "mode"
    },
    model_name: {
      name: "model_name"
    }
  },
  outputs: {
    "1": {
      name: "duration"
    }
  }
};
const KlingImage2VideoNode$3 = {
  description: "Kling 画像から動画ノード",
  display_name: "Kling 画像から動画へ",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio"
    },
    cfg_scale: {
      name: "cfg_scale"
    },
    duration: {
      name: "duration"
    },
    mode: {
      name: "mode"
    },
    model_name: {
      name: "model_name"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "ネガティブテキストプロンプト"
    },
    prompt: {
      name: "prompt",
      tooltip: "ポジティブテキストプロンプト"
    },
    start_frame: {
      name: "start_frame",
      tooltip: "参照画像 - URLまたはBase64エンコード文字列。10MBを超えてはいけません。解像度は300×300px以上、アスペクト比は1:2.5〜2.5:1の範囲。Base64の場合、data:imageプレフィックスは含めないでください。"
    }
  },
  outputs: {
    "1": {
      name: "video_id"
    },
    "2": {
      name: "duration"
    }
  }
};
const KlingImageGenerationNode$3 = {
  description: "Kling画像生成ノード。テキストプロンプトと任意の参照画像から画像を生成します。",
  display_name: "Kling画像生成",
  inputs: {
    aspect_ratio: {
      name: "アスペクト比"
    },
    human_fidelity: {
      name: "人物忠実度",
      tooltip: "被写体の参照類似度"
    },
    image: {
      name: "画像"
    },
    image_fidelity: {
      name: "画像忠実度",
      tooltip: "ユーザーがアップロードした画像の参照強度"
    },
    image_type: {
      name: "画像タイプ"
    },
    model_name: {
      name: "モデル名"
    },
    n: {
      name: "生成画像数",
      tooltip: "生成される画像の数"
    },
    negative_prompt: {
      name: "ネガティブプロンプト",
      tooltip: "ネガティブテキストプロンプト"
    },
    prompt: {
      name: "プロンプト",
      tooltip: "ポジティブテキストプロンプト"
    }
  }
};
const KlingLipSyncAudioToVideoNode$3 = {
  description: "Klingリップシンク音声から動画ノード。動画ファイル内の口の動きを音声ファイルの内容に同期します。",
  display_name: "Klingリップシンク：音声付き動画",
  inputs: {
    audio: {
      name: "音声"
    },
    video: {
      name: "動画"
    },
    voice_language: {
      name: "音声言語"
    }
  },
  outputs: {
    "1": {
      name: "動画ID"
    },
    "2": {
      name: "再生時間"
    }
  }
};
const KlingLipSyncTextToVideoNode$3 = {
  description: "Kling リップシンク テキストから動画ノード。動画ファイル内の口の動きをテキストプロンプトに同期させます。",
  display_name: "Kling リップシンク動画（テキスト入力）",
  inputs: {
    text: {
      name: "テキスト",
      tooltip: "リップシンク動画生成用のテキスト内容。モードが text2video の場合は必須です。最大120文字まで。"
    },
    video: {
      name: "動画"
    },
    voice: {
      name: "音声"
    },
    voice_speed: {
      name: "話速",
      tooltip: "話す速度。有効範囲：0.8～2.0、小数点第一位まで指定可能。"
    }
  },
  outputs: {
    "1": {
      name: "動画ID"
    },
    "2": {
      name: "再生時間"
    }
  }
};
const KlingSingleImageVideoEffectNode$3 = {
  description: "effect_scene に基づいてビデオを生成する際に、さまざまな特殊効果を実現します。",
  display_name: "Kling ビデオエフェクト",
  inputs: {
    duration: {
      name: "duration"
    },
    effect_scene: {
      name: "effect_scene"
    },
    image: {
      name: "image",
      tooltip: "参照画像。URL または Base64 エンコード文字列（data:image プレフィックスなし）。ファイルサイズは10MB以下、解像度は300×300px以上、アスペクト比は1:2.5～2.5:1の範囲である必要があります。"
    },
    model_name: {
      name: "model_name"
    }
  },
  outputs: {
    "1": {
      name: "video_id"
    },
    "2": {
      name: "duration"
    }
  }
};
const KlingStartEndFrameNode$3 = {
  description: "指定した開始画像と終了画像の間を遷移する動画シーケンスを生成します。このノードは中間のすべてのフレームを作成し、最初のフレームから最後のフレームまで滑らかな変化を実現します。",
  display_name: "Kling 開始-終了フレームから動画生成",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio"
    },
    cfg_scale: {
      name: "cfg_scale"
    },
    end_frame: {
      name: "end_frame",
      tooltip: "参照画像 - 終了フレームの指定。URLまたはBase64エンコード文字列。10MBを超えてはいけません。解像度は300×300px以上。Base64の場合、data:imageプレフィックスは含めないでください。"
    },
    mode: {
      name: "mode",
      tooltip: "動画生成に使用する設定。形式：mode / duration / model_name"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "ネガティブテキストプロンプト"
    },
    prompt: {
      name: "prompt",
      tooltip: "ポジティブテキストプロンプト"
    },
    start_frame: {
      name: "start_frame",
      tooltip: "参照画像 - URLまたはBase64エンコード文字列。10MBを超えてはいけません。解像度は300×300px以上、アスペクト比は1:2.5～2.5:1の範囲。Base64の場合、data:imageプレフィックスは含めないでください。"
    }
  },
  outputs: {
    "1": {
      name: "video_id"
    },
    "2": {
      name: "duration"
    }
  }
};
const KlingTextToVideoNode$3 = {
  description: "Kling テキストからビデオノード",
  display_name: "Kling テキストからビデオへ",
  inputs: {
    aspect_ratio: {
      name: "アスペクト比"
    },
    cfg_scale: {
      name: "cfg_scale"
    },
    mode: {
      name: "モード",
      tooltip: "ビデオ生成のために使用する設定（形式: モード / 継続時間 / モデル名）"
    },
    negative_prompt: {
      name: "ネガティブプロンプト",
      tooltip: "ネガティブテキストプロンプト"
    },
    prompt: {
      name: "プロンプト",
      tooltip: "ポジティブテキストプロンプト"
    }
  },
  outputs: {
    "1": {
      name: "video_id"
    },
    "2": {
      name: "継続時間"
    }
  }
};
const KlingVideoExtendNode$3 = {
  description: "Kling Video Extendノード。他のKlingノードで作成された動画を拡張します。video_idは他のKlingノードを使用して作成されます。",
  display_name: "Kling Video Extend",
  inputs: {
    cfg_scale: {
      name: "cfg_scale"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "拡張動画で避けたい要素のネガティブテキストプロンプト"
    },
    prompt: {
      name: "prompt",
      tooltip: "動画拡張をガイドするためのポジティブなテキストプロンプト"
    },
    video_id: {
      name: "video_id",
      tooltip: "拡張する動画のID。テキストから動画、画像から動画、または以前の動画拡張操作で生成された動画をサポートします。拡張後の合計再生時間は3分を超えることはできません。"
    }
  },
  outputs: {
    "1": {
      name: "video_id"
    },
    "2": {
      name: "duration"
    }
  }
};
const KlingVirtualTryOnNode$3 = {
  description: "Klingバーチャル試着ノード。人物画像と服画像を入力して、人物に服を試着させます。",
  display_name: "Klingバーチャル試着",
  inputs: {
    cloth_image: {
      name: "服画像"
    },
    human_image: {
      name: "人物画像"
    },
    model_name: {
      name: "モデル名"
    }
  }
};
const LTXVAddGuide$3 = {
  display_name: "LTXVAddGuide",
  inputs: {
    frame_idx: {
      name: "フレームインデックス",
      tooltip: "条件付けを開始するフレームインデックス。単一フレームの画像や1-8フレームのビデオの場合、任意のframe_idx値が許容されます。9フレーム以上のビデオの場合、frame_idxは8で割り切れる数でなければならず、そうでない場合は最も近い8の倍数に切り捨てられます。負の値はビデオの終わりから数えます。"
    },
    image: {
      name: "画像",
      tooltip: "潜在ビデオの条件付けに使用する画像またはビデオ。フレーム数は8*n + 1でなければなりません。ビデオが8*n + 1フレームでない場合、最も近い8*n + 1フレームに切り取られます。"
    },
    latent: {
      name: "潜在"
    },
    negative: {
      name: "ネガティブ"
    },
    positive: {
      name: "ポジティブ"
    },
    strength: {
      name: "強度"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "ポジティブ"
    },
    "1": {
      name: "ネガティブ"
    },
    "2": {
      name: "潜在"
    }
  }
};
const LTXVConditioning$3 = {
  display_name: "LTXV条件付け",
  inputs: {
    frame_rate: {
      name: "フレームレート"
    },
    negative: {
      name: "ネガティブ"
    },
    positive: {
      name: "ポジティブ"
    }
  },
  outputs: {
    "0": {
      name: "ポジティブ"
    },
    "1": {
      name: "ネガティブ"
    }
  }
};
const LTXVCropGuides$3 = {
  display_name: "LTXVCropGuides",
  inputs: {
    latent: {
      name: "潜在"
    },
    negative: {
      name: "ネガティブ"
    },
    positive: {
      name: "ポジティブ"
    }
  },
  outputs: {
    "0": {
      name: "ポジティブ"
    },
    "1": {
      name: "ネガティブ"
    },
    "2": {
      name: "潜在"
    }
  }
};
const LTXVImgToVideo$3 = {
  display_name: "LTXV画像からビデオへ",
  inputs: {
    batch_size: {
      name: "バッチサイズ"
    },
    height: {
      name: "高さ"
    },
    image: {
      name: "画像"
    },
    length: {
      name: "長さ"
    },
    negative: {
      name: "ネガティブ"
    },
    positive: {
      name: "ポジティブ"
    },
    strength: {
      name: "強度"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "幅"
    }
  },
  outputs: {
    "0": {
      name: "ポジティブ"
    },
    "1": {
      name: "ネガティブ"
    },
    "2": {
      name: "潜在"
    }
  }
};
const LTXVPreprocess$3 = {
  display_name: "LTXVPreprocess",
  inputs: {
    image: {
      name: "画像"
    },
    img_compression: {
      name: "画像圧縮",
      tooltip: "画像に適用する圧縮の量。"
    }
  },
  outputs: {
    "0": {
      name: "出力画像"
    }
  }
};
const LTXVScheduler$3 = {
  display_name: "LTXVスケジューラー",
  inputs: {
    base_shift: {
      name: "基本シフト"
    },
    latent: {
      name: "潜在"
    },
    max_shift: {
      name: "最大シフト"
    },
    steps: {
      name: "ステップ"
    },
    stretch: {
      name: "ストレッチ",
      tooltip: "シグマを[terminal, 1]の範囲に伸ばします。"
    },
    terminal: {
      name: "端末",
      tooltip: "ストレッチ後のシグマの端末値。"
    }
  }
};
const LaplaceScheduler$3 = {
  display_name: "ラプラススケジューラー",
  inputs: {
    beta: {
      name: "ベータ"
    },
    mu: {
      name: "ミュー"
    },
    sigma_max: {
      name: "シグマ_最大"
    },
    sigma_min: {
      name: "シグマ_最小"
    },
    steps: {
      name: "ステップ"
    }
  }
};
const LatentAdd$3 = {
  display_name: "潜在追加",
  inputs: {
    samples1: {
      name: "サンプル1"
    },
    samples2: {
      name: "サンプル2"
    }
  }
};
const LatentApplyOperation$3 = {
  display_name: "潜在操作を適用",
  inputs: {
    operation: {
      name: "操作"
    },
    samples: {
      name: "サンプル"
    }
  }
};
const LatentApplyOperationCFG$3 = {
  display_name: "潜在操作CFGを適用",
  inputs: {
    model: {
      name: "モデル"
    },
    operation: {
      name: "操作"
    }
  }
};
const LatentBatch$3 = {
  display_name: "潜在バッチ",
  inputs: {
    samples1: {
      name: "サンプル1"
    },
    samples2: {
      name: "サンプル2"
    }
  }
};
const LatentBatchSeedBehavior$3 = {
  display_name: "潜在バッチシード動作",
  inputs: {
    samples: {
      name: "サンプル"
    },
    seed_behavior: {
      name: "シード行動"
    }
  }
};
const LatentBlend$3 = {
  display_name: "潜在ブレンド",
  inputs: {
    blend_factor: {
      name: "ブレンド係数"
    },
    samples1: {
      name: "サンプル1"
    },
    samples2: {
      name: "サンプル2"
    }
  }
};
const LatentComposite$3 = {
  display_name: "潜在合成",
  inputs: {
    feather: {
      name: "フェザー"
    },
    samples_from: {
      name: "samples_from"
    },
    samples_to: {
      name: "samples_to"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const LatentCompositeMasked$3 = {
  display_name: "マスクされた潜在合成",
  inputs: {
    destination: {
      name: "destination"
    },
    mask: {
      name: "マスク"
    },
    resize_source: {
      name: "resize_source"
    },
    source: {
      name: "source"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const LatentCrop$3 = {
  display_name: "潜在トリミング",
  inputs: {
    height: {
      name: "高さ"
    },
    samples: {
      name: "samples"
    },
    width: {
      name: "幅"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const LatentFlip$3 = {
  display_name: "潜在反転",
  inputs: {
    flip_method: {
      name: "反転方法"
    },
    samples: {
      name: "samples"
    }
  }
};
const LatentFromBatch$3 = {
  display_name: "バッチから潜在を取得",
  inputs: {
    batch_index: {
      name: "バッチインデックス"
    },
    length: {
      name: "長さ"
    },
    samples: {
      name: "samples"
    }
  }
};
const LatentInterpolate$3 = {
  display_name: "潜在補間",
  inputs: {
    ratio: {
      name: "比率"
    },
    samples1: {
      name: "samples1"
    },
    samples2: {
      name: "samples2"
    }
  }
};
const LatentMultiply$3 = {
  display_name: "潜在乗算",
  inputs: {
    multiplier: {
      name: "乗数"
    },
    samples: {
      name: "samples"
    }
  }
};
const LatentOperationSharpen$3 = {
  display_name: "潜在操作シャープ化",
  inputs: {
    alpha: {
      name: "アルファ"
    },
    sharpen_radius: {
      name: "シャープ化半径"
    },
    sigma: {
      name: "シグマ"
    }
  }
};
const LatentOperationTonemapReinhard$3 = {
  display_name: "潜在操作トーンマップライナード",
  inputs: {
    multiplier: {
      name: "乗数"
    }
  }
};
const LatentRotate$3 = {
  display_name: "潜在回転",
  inputs: {
    rotation: {
      name: "回転"
    },
    samples: {
      name: "samples"
    }
  }
};
const LatentSubtract$3 = {
  display_name: "潜在減算",
  inputs: {
    samples1: {
      name: "samples1"
    },
    samples2: {
      name: "samples2"
    }
  }
};
const LatentUpscale$3 = {
  display_name: "潜在を拡大",
  inputs: {
    crop: {
      name: "クロップ"
    },
    height: {
      name: "高さ"
    },
    samples: {
      name: "samples"
    },
    upscale_method: {
      name: "拡大方法"
    },
    width: {
      name: "幅"
    }
  }
};
const LatentUpscaleBy$3 = {
  display_name: "潜在を拡大（指定サイズ）",
  inputs: {
    samples: {
      name: "samples"
    },
    scale_by: {
      name: "スケールバイ"
    },
    upscale_method: {
      name: "拡大方法"
    }
  }
};
const Load3D$3 = {
  display_name: "3Dを読み込む",
  inputs: {
    clear: {},
    height: {
      name: "高さ"
    },
    image: {
      name: "画像"
    },
    model_file: {
      name: "モデルファイル"
    },
    "upload 3d model": {},
    width: {
      name: "幅"
    }
  },
  outputs: [
    null,
    null,
    null,
    {
      name: "法線"
    },
    {
      name: "線画"
    },
    {
      name: "カメラ情報"
    }
  ]
};
const Load3DAnimation$3 = {
  display_name: "3Dを読み込む - アニメーション",
  inputs: {
    clear: {},
    height: {
      name: "高さ"
    },
    image: {
      name: "画像"
    },
    model_file: {
      name: "モデルファイル"
    },
    "upload 3d model": {},
    width: {
      name: "幅"
    }
  },
  outputs: [
    null,
    null,
    null,
    {
      name: "法線"
    },
    {
      name: "カメラ情報"
    }
  ]
};
const LoadAudio$3 = {
  display_name: "音声を読み込む",
  inputs: {
    audio: {
      name: "オーディオ"
    },
    audioUI: {
      name: "audioUI"
    },
    upload: {
      name: "アップロードするファイルを選択"
    }
  }
};
const LoadImage$3 = {
  display_name: "画像を読み込む",
  inputs: {
    image: {
      name: "画像"
    },
    upload: {
      name: "アップロードするファイルを選択"
    }
  }
};
const LoadImageMask$3 = {
  display_name: "画像を読み込む（マスクとして）",
  inputs: {
    channel: {
      name: "チャンネル"
    },
    image: {
      name: "画像"
    },
    upload: {
      name: "アップロードするファイルを選択"
    }
  }
};
const LoadImageOutput$3 = {
  description: "出力フォルダから画像を読み込みます。更新ボタンをクリックすると、ノードは画像リストを更新し、自動的に最初の画像を選択します。これにより、簡単に反復処理が可能になります。",
  display_name: "画像の読み込み（出力から）",
  inputs: {
    image: {
      name: "画像"
    },
    refresh: {},
    upload: {
      name: "アップロードするファイルを選択"
    }
  }
};
const LoadLatent$3 = {
  display_name: "潜在を読み込む",
  inputs: {
    latent: {
      name: "latent"
    }
  }
};
const LoadVideo$3 = {
  display_name: "ビデオを読み込む",
  inputs: {
    file: {
      name: "ファイル"
    },
    upload: {
      name: "アップロードするファイルを選択"
    }
  }
};
const LoraLoader$3 = {
  description: "LoRAは拡散およびCLIPモデルを修正するために使用され、潜在のノイズ除去方法を変更します。複数のLoRAノードを連結できます。",
  display_name: "LoRAを読み込む",
  inputs: {
    clip: {
      name: "クリップ",
      tooltip: "LoRAが適用されるCLIPモデル。"
    },
    lora_name: {
      name: "lora_name",
      tooltip: "LoRAの名前。"
    },
    model: {
      name: "モデル",
      tooltip: "LoRAが適用される拡散モデル。"
    },
    strength_clip: {
      name: "クリップの強度",
      tooltip: "CLIPモデルをどの程度変更するか。この値は負の値になる可能性があります。"
    },
    strength_model: {
      name: "モデルの強度",
      tooltip: "拡散モデルをどの程度変更するか。この値は負の値になる可能性があります。"
    }
  },
  outputs: {
    "0": {
      tooltip: "修正された拡散モデル。"
    },
    "1": {
      tooltip: "修正されたCLIPモデル。"
    }
  }
};
const LoraLoaderModelOnly$3 = {
  description: "LoRAは拡散およびCLIPモデルを修正するために使用され、潜在のノイズ除去方法を変更します。複数のLoRAノードを連結できます。",
  display_name: "LoRAローダーモデルのみ",
  inputs: {
    lora_name: {
      name: "lora_name"
    },
    model: {
      name: "モデル"
    },
    strength_model: {
      name: "モデルの強度"
    }
  },
  outputs: {
    "0": {
      tooltip: "修正された拡散モデル。"
    }
  }
};
const LoraSave$3 = {
  display_name: "LoRAを抽出して保存",
  inputs: {
    bias_diff: {
      name: "バイアスの差"
    },
    filename_prefix: {
      name: "ファイル名のプレフィックス"
    },
    lora_type: {
      name: "lora_type"
    },
    model_diff: {
      name: "モデルの差",
      tooltip: "loraに変換されるModelSubtract出力。"
    },
    rank: {
      name: "ランク"
    },
    text_encoder_diff: {
      name: "テキストエンコーダの差",
      tooltip: "loraに変換されるCLIPSubtract出力。"
    }
  }
};
const LotusConditioning$3 = {
  display_name: "LotusConditioning",
  outputs: {
    "0": {
      name: "コンディショニング"
    }
  }
};
const LumaConceptsNode$3 = {
  description: "Luma Text to VideoおよびLuma Image to Videoノードで使用するための1つ以上のカメラコンセプトを保持します。",
  display_name: "Lumaコンセプト",
  inputs: {
    concept1: {
      name: "concept1"
    },
    concept2: {
      name: "concept2"
    },
    concept3: {
      name: "concept3"
    },
    concept4: {
      name: "concept4"
    },
    luma_concepts: {
      name: "luma_concepts",
      tooltip: "ここで選択したものに追加するオプションのカメラコンセプト。"
    }
  },
  outputs: {
    "0": {
      name: "luma_concepts"
    }
  }
};
const LumaImageModifyNode$3 = {
  description: "プロンプトとアスペクト比に基づいて画像を同期的に変更します。",
  display_name: "Luma 画像から画像へ",
  inputs: {
    control_after_generate: {
      name: "生成後のコントロール"
    },
    image: {
      name: "画像"
    },
    image_weight: {
      name: "画像の重み",
      tooltip: "画像の重み。1.0に近いほど画像の変更が少なくなります。"
    },
    model: {
      name: "モデル"
    },
    prompt: {
      name: "プロンプト",
      tooltip: "画像生成のためのプロンプト"
    },
    seed: {
      name: "シード",
      tooltip: "ノードを再実行するかどうかを決定するシード。実際の結果はシードに関係なく非決定的です。"
    }
  }
};
const LumaImageNode$3 = {
  description: "プロンプトとアスペクト比に基づいて同期的に画像を生成します。",
  display_name: "Luma テキストから画像へ",
  inputs: {
    aspect_ratio: {
      name: "アスペクト比"
    },
    character_image: {
      name: "キャラクター参照画像",
      tooltip: "キャラクター参照画像。複数のバッチが可能で、最大4枚の画像が考慮されます。"
    },
    control_after_generate: {
      name: "生成後のコントロール"
    },
    image_luma_ref: {
      name: "Luma参照画像",
      tooltip: "入力画像で生成を補助するLuma参照ノード接続。最大4枚の画像が考慮されます。"
    },
    model: {
      name: "モデル"
    },
    prompt: {
      name: "プロンプト",
      tooltip: "画像生成のためのプロンプト"
    },
    seed: {
      name: "シード",
      tooltip: "ノードを再実行するかどうかを決定するシード。実際の結果はシードに関係なく非決定的です。"
    },
    style_image: {
      name: "スタイル参照画像",
      tooltip: "スタイル参照画像。1枚のみ使用されます。"
    },
    style_image_weight: {
      name: "スタイル画像の重み",
      tooltip: "スタイル画像の重み。style_imageが指定されていない場合は無視されます。"
    }
  }
};
const LumaImageToVideoNode$3 = {
  description: "プロンプト、入力画像、およびoutput_sizeに基づいて同期的に動画を生成します。",
  display_name: "Luma画像から動画へ",
  inputs: {
    control_after_generate: {
      name: "生成後の制御"
    },
    duration: {
      name: "再生時間"
    },
    first_image: {
      name: "最初の画像",
      tooltip: "生成された動画の最初のフレーム。"
    },
    last_image: {
      name: "最後の画像",
      tooltip: "生成された動画の最後のフレーム。"
    },
    loop: {
      name: "ループ"
    },
    luma_concepts: {
      name: "luma_concepts",
      tooltip: "Luma Conceptsノードを通じてカメラの動きを制御するためのオプションのカメラコンセプト。"
    },
    model: {
      name: "モデル"
    },
    prompt: {
      name: "プロンプト",
      tooltip: "動画生成用のプロンプト"
    },
    resolution: {
      name: "解像度"
    },
    seed: {
      name: "シード",
      tooltip: "ノードを再実行するかどうかを決定するシード値。実際の結果はシードに関係なく非決定的です。"
    }
  }
};
const LumaReferenceNode$3 = {
  description: "Luma Generate Imageノードで使用する画像と重みを保持します。",
  display_name: "Luma Reference",
  inputs: {
    image: {
      name: "image",
      tooltip: "参照として使用する画像。"
    },
    luma_ref: {
      name: "luma_ref"
    },
    weight: {
      name: "weight",
      tooltip: "画像参照の重み。"
    }
  },
  outputs: {
    "0": {
      name: "luma_ref"
    }
  }
};
const LumaVideoNode$3 = {
  description: "プロンプトと出力サイズに基づいて同期的にビデオを生成します。",
  display_name: "Luma テキストからビデオへ",
  inputs: {
    aspect_ratio: {
      name: "アスペクト比"
    },
    control_after_generate: {
      name: "生成後のコントロール"
    },
    duration: {
      name: "再生時間"
    },
    loop: {
      name: "ループ"
    },
    luma_concepts: {
      name: "luma_concepts",
      tooltip: "Luma Conceptsノードを通じてカメラの動きを指示するためのオプションのカメラコンセプト。"
    },
    model: {
      name: "モデル"
    },
    prompt: {
      name: "プロンプト",
      tooltip: "ビデオ生成のためのプロンプト"
    },
    resolution: {
      name: "解像度"
    },
    seed: {
      name: "シード",
      tooltip: "ノードを再実行するかどうかを決定するシード。実際の結果はシードに関係なく非決定的です。"
    }
  }
};
const Mahiro$3 = {
  description: "ネガティブなプロンプトとの差ではなく、ポジティブなプロンプトの「方向」によりスケールするようにガイダンスを修正します。",
  display_name: "Mahiroはとても可愛いので、より良いガイダンス機能が必要です!! (。・ω・。)",
  inputs: {
    model: {
      name: "モデル"
    }
  },
  outputs: {
    "0": {
      name: "パッチ適用モデル"
    }
  }
};
const MaskComposite$3 = {
  display_name: "マスク合成",
  inputs: {
    destination: {
      name: "目的地"
    },
    operation: {
      name: "操作"
    },
    source: {
      name: "ソース"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const MaskPreview$3 = {
  description: "入力画像をComfyUIの出力ディレクトリに保存します。",
  display_name: "MaskPreview",
  inputs: {
    mask: {
      name: "mask"
    }
  }
};
const MaskToImage$3 = {
  display_name: "マスクを画像に変換",
  inputs: {
    mask: {
      name: "マスク"
    }
  }
};
const MinimaxImageToVideoNode$3 = {
  description: "MiniMaxのAPIを使用して画像とプロンプトから動画を生成します",
  display_name: "MiniMax 画像から動画へ",
  inputs: {
    control_after_generate: {
      name: "生成後のコントロール"
    },
    image: {
      name: "画像",
      tooltip: "動画生成の最初のフレームとして使用する画像"
    },
    model: {
      name: "モデル",
      tooltip: "動画生成に使用するモデル"
    },
    prompt_text: {
      name: "プロンプトテキスト",
      tooltip: "動画生成をガイドするテキストプロンプト"
    },
    seed: {
      name: "シード",
      tooltip: "ノイズ生成に使用される乱数シード。"
    }
  }
};
const MinimaxTextToVideoNode$3 = {
  description: "MiniMaxのAPIを使用してプロンプトからビデオを生成します",
  display_name: "MiniMax テキストからビデオへ",
  inputs: {
    control_after_generate: {
      name: "生成後のコントロール"
    },
    model: {
      name: "モデル",
      tooltip: "ビデオ生成に使用するモデル"
    },
    prompt_text: {
      name: "プロンプトテキスト",
      tooltip: "ビデオ生成をガイドするテキストプロンプト"
    },
    seed: {
      name: "シード",
      tooltip: "ノイズ生成に使用されるランダムシード。"
    }
  }
};
const ModelComputeDtype$3 = {
  display_name: "ModelComputeDtype",
  inputs: {
    dtype: {
      name: "dtype"
    },
    model: {
      name: "モデル"
    }
  }
};
const ModelMergeAdd$3 = {
  display_name: "モデルマージ追加",
  inputs: {
    model1: {
      name: "モデル1"
    },
    model2: {
      name: "モデル2"
    }
  }
};
const ModelMergeAuraflow$3 = {
  display_name: "モデルマージオーラフロー",
  inputs: {
    cond_seq_linear_: {
      name: "cond_seq_linear."
    },
    double_layers_0_: {
      name: "double_layers.0."
    },
    double_layers_1_: {
      name: "double_layers.1."
    },
    double_layers_2_: {
      name: "double_layers.2."
    },
    double_layers_3_: {
      name: "double_layers.3."
    },
    final_linear_: {
      name: "final_linear."
    },
    init_x_linear_: {
      name: "init_x_linear."
    },
    modF_: {
      name: "modF."
    },
    model1: {
      name: "モデル1"
    },
    model2: {
      name: "モデル2"
    },
    positional_encoding: {
      name: "位置エンコーディング"
    },
    register_tokens: {
      name: "トークンを登録"
    },
    single_layers_0_: {
      name: "single_layers.0."
    },
    single_layers_10_: {
      name: "single_layers.10."
    },
    single_layers_11_: {
      name: "single_layers.11."
    },
    single_layers_12_: {
      name: "single_layers.12."
    },
    single_layers_13_: {
      name: "single_layers.13."
    },
    single_layers_14_: {
      name: "single_layers.14."
    },
    single_layers_15_: {
      name: "single_layers.15."
    },
    single_layers_16_: {
      name: "single_layers.16."
    },
    single_layers_17_: {
      name: "single_layers.17."
    },
    single_layers_18_: {
      name: "single_layers.18."
    },
    single_layers_19_: {
      name: "single_layers.19."
    },
    single_layers_1_: {
      name: "single_layers.1."
    },
    single_layers_20_: {
      name: "single_layers.20."
    },
    single_layers_21_: {
      name: "single_layers.21."
    },
    single_layers_22_: {
      name: "single_layers.22."
    },
    single_layers_23_: {
      name: "single_layers.23."
    },
    single_layers_24_: {
      name: "single_layers.24."
    },
    single_layers_25_: {
      name: "single_layers.25."
    },
    single_layers_26_: {
      name: "single_layers.26."
    },
    single_layers_27_: {
      name: "single_layers.27."
    },
    single_layers_28_: {
      name: "single_layers.28."
    },
    single_layers_29_: {
      name: "single_layers.29."
    },
    single_layers_2_: {
      name: "single_layers.2."
    },
    single_layers_30_: {
      name: "single_layers.30."
    },
    single_layers_31_: {
      name: "single_layers.31."
    },
    single_layers_3_: {
      name: "single_layers.3."
    },
    single_layers_4_: {
      name: "single_layers.4."
    },
    single_layers_5_: {
      name: "single_layers.5."
    },
    single_layers_6_: {
      name: "single_layers.6."
    },
    single_layers_7_: {
      name: "single_layers.7."
    },
    single_layers_8_: {
      name: "single_layers.8."
    },
    single_layers_9_: {
      name: "single_layers.9."
    },
    t_embedder_: {
      name: "t_embedder."
    }
  }
};
const ModelMergeBlocks$3 = {
  display_name: "モデルマージブロック",
  inputs: {
    input: {
      name: "入力"
    },
    middle: {
      name: "中間"
    },
    model1: {
      name: "モデル1"
    },
    model2: {
      name: "モデル2"
    },
    out: {
      name: "出力"
    }
  }
};
const ModelMergeCosmos14B$3 = {
  display_name: "ModelMergeCosmos14B",
  inputs: {
    affline_norm_: {
      name: "affline_norm."
    },
    blocks_block0_: {
      name: "blocks.block0."
    },
    blocks_block10_: {
      name: "blocks.block10."
    },
    blocks_block11_: {
      name: "blocks.block11."
    },
    blocks_block12_: {
      name: "blocks.block12."
    },
    blocks_block13_: {
      name: "blocks.block13."
    },
    blocks_block14_: {
      name: "blocks.block14."
    },
    blocks_block15_: {
      name: "blocks.block15."
    },
    blocks_block16_: {
      name: "blocks.block16."
    },
    blocks_block17_: {
      name: "blocks.block17."
    },
    blocks_block18_: {
      name: "blocks.block18."
    },
    blocks_block19_: {
      name: "blocks.block19."
    },
    blocks_block1_: {
      name: "blocks.block1."
    },
    blocks_block20_: {
      name: "blocks.block20."
    },
    blocks_block21_: {
      name: "blocks.block21."
    },
    blocks_block22_: {
      name: "blocks.block22."
    },
    blocks_block23_: {
      name: "blocks.block23."
    },
    blocks_block24_: {
      name: "blocks.block24."
    },
    blocks_block25_: {
      name: "blocks.block25."
    },
    blocks_block26_: {
      name: "blocks.block26."
    },
    blocks_block27_: {
      name: "blocks.block27."
    },
    blocks_block28_: {
      name: "blocks.block28."
    },
    blocks_block29_: {
      name: "blocks.block29."
    },
    blocks_block2_: {
      name: "blocks.block2."
    },
    blocks_block30_: {
      name: "blocks.block30."
    },
    blocks_block31_: {
      name: "blocks.block31."
    },
    blocks_block32_: {
      name: "blocks.block32."
    },
    blocks_block33_: {
      name: "blocks.block33."
    },
    blocks_block34_: {
      name: "blocks.block34."
    },
    blocks_block35_: {
      name: "blocks.block35."
    },
    blocks_block3_: {
      name: "blocks.block3."
    },
    blocks_block4_: {
      name: "blocks.block4."
    },
    blocks_block5_: {
      name: "blocks.block5."
    },
    blocks_block6_: {
      name: "blocks.block6."
    },
    blocks_block7_: {
      name: "blocks.block7."
    },
    blocks_block8_: {
      name: "blocks.block8."
    },
    blocks_block9_: {
      name: "blocks.block9."
    },
    extra_pos_embedder_: {
      name: "extra_pos_embedder."
    },
    final_layer_: {
      name: "final_layer."
    },
    model1: {
      name: "モデル1"
    },
    model2: {
      name: "モデル2"
    },
    pos_embedder_: {
      name: "pos_embedder."
    },
    t_embedder_: {
      name: "t_embedder."
    },
    x_embedder_: {
      name: "x_embedder."
    }
  }
};
const ModelMergeCosmos7B$3 = {
  display_name: "ModelMergeCosmos7B",
  inputs: {
    affline_norm_: {
      name: "affline_norm."
    },
    blocks_block0_: {
      name: "blocks.block0."
    },
    blocks_block10_: {
      name: "blocks.block10."
    },
    blocks_block11_: {
      name: "blocks.block11."
    },
    blocks_block12_: {
      name: "blocks.block12."
    },
    blocks_block13_: {
      name: "blocks.block13."
    },
    blocks_block14_: {
      name: "blocks.block14."
    },
    blocks_block15_: {
      name: "blocks.block15."
    },
    blocks_block16_: {
      name: "blocks.block16."
    },
    blocks_block17_: {
      name: "blocks.block17."
    },
    blocks_block18_: {
      name: "blocks.block18."
    },
    blocks_block19_: {
      name: "blocks.block19."
    },
    blocks_block1_: {
      name: "blocks.block1."
    },
    blocks_block20_: {
      name: "blocks.block20."
    },
    blocks_block21_: {
      name: "blocks.block21."
    },
    blocks_block22_: {
      name: "blocks.block22."
    },
    blocks_block23_: {
      name: "blocks.block23."
    },
    blocks_block24_: {
      name: "blocks.block24."
    },
    blocks_block25_: {
      name: "blocks.block25."
    },
    blocks_block26_: {
      name: "blocks.block26."
    },
    blocks_block27_: {
      name: "blocks.block27."
    },
    blocks_block2_: {
      name: "blocks.block2."
    },
    blocks_block3_: {
      name: "blocks.block3."
    },
    blocks_block4_: {
      name: "blocks.block4."
    },
    blocks_block5_: {
      name: "blocks.block5."
    },
    blocks_block6_: {
      name: "blocks.block6."
    },
    blocks_block7_: {
      name: "blocks.block7."
    },
    blocks_block8_: {
      name: "blocks.block8."
    },
    blocks_block9_: {
      name: "blocks.block9."
    },
    extra_pos_embedder_: {
      name: "extra_pos_embedder."
    },
    final_layer_: {
      name: "final_layer."
    },
    model1: {
      name: "モデル1"
    },
    model2: {
      name: "モデル2"
    },
    pos_embedder_: {
      name: "pos_embedder."
    },
    t_embedder_: {
      name: "t_embedder."
    },
    x_embedder_: {
      name: "x_embedder."
    }
  }
};
const ModelMergeFlux1$3 = {
  display_name: "モデルマージフラックス1",
  inputs: {
    double_blocks_0_: {
      name: "double_blocks.0."
    },
    double_blocks_10_: {
      name: "double_blocks.10."
    },
    double_blocks_11_: {
      name: "double_blocks.11."
    },
    double_blocks_12_: {
      name: "double_blocks.12."
    },
    double_blocks_13_: {
      name: "double_blocks.13."
    },
    double_blocks_14_: {
      name: "double_blocks.14."
    },
    double_blocks_15_: {
      name: "double_blocks.15."
    },
    double_blocks_16_: {
      name: "double_blocks.16."
    },
    double_blocks_17_: {
      name: "double_blocks.17."
    },
    double_blocks_18_: {
      name: "double_blocks.18."
    },
    double_blocks_1_: {
      name: "double_blocks.1."
    },
    double_blocks_2_: {
      name: "double_blocks.2."
    },
    double_blocks_3_: {
      name: "double_blocks.3."
    },
    double_blocks_4_: {
      name: "double_blocks.4."
    },
    double_blocks_5_: {
      name: "double_blocks.5."
    },
    double_blocks_6_: {
      name: "double_blocks.6."
    },
    double_blocks_7_: {
      name: "double_blocks.7."
    },
    double_blocks_8_: {
      name: "double_blocks.8."
    },
    double_blocks_9_: {
      name: "double_blocks.9."
    },
    final_layer_: {
      name: "final_layer."
    },
    guidance_in: {
      name: "guidance_in"
    },
    img_in_: {
      name: "img_in."
    },
    model1: {
      name: "モデル1"
    },
    model2: {
      name: "モデル2"
    },
    single_blocks_0_: {
      name: "single_blocks.0."
    },
    single_blocks_10_: {
      name: "single_blocks.10."
    },
    single_blocks_11_: {
      name: "single_blocks.11."
    },
    single_blocks_12_: {
      name: "single_blocks.12."
    },
    single_blocks_13_: {
      name: "single_blocks.13."
    },
    single_blocks_14_: {
      name: "single_blocks.14."
    },
    single_blocks_15_: {
      name: "single_blocks.15."
    },
    single_blocks_16_: {
      name: "single_blocks.16."
    },
    single_blocks_17_: {
      name: "single_blocks.17."
    },
    single_blocks_18_: {
      name: "single_blocks.18."
    },
    single_blocks_19_: {
      name: "single_blocks.19."
    },
    single_blocks_1_: {
      name: "single_blocks.1."
    },
    single_blocks_20_: {
      name: "single_blocks.20."
    },
    single_blocks_21_: {
      name: "single_blocks.21."
    },
    single_blocks_22_: {
      name: "single_blocks.22."
    },
    single_blocks_23_: {
      name: "single_blocks.23."
    },
    single_blocks_24_: {
      name: "single_blocks.24."
    },
    single_blocks_25_: {
      name: "single_blocks.25."
    },
    single_blocks_26_: {
      name: "single_blocks.26."
    },
    single_blocks_27_: {
      name: "single_blocks.27."
    },
    single_blocks_28_: {
      name: "single_blocks.28."
    },
    single_blocks_29_: {
      name: "single_blocks.29."
    },
    single_blocks_2_: {
      name: "single_blocks.2."
    },
    single_blocks_30_: {
      name: "single_blocks.30."
    },
    single_blocks_31_: {
      name: "single_blocks.31."
    },
    single_blocks_32_: {
      name: "single_blocks.32."
    },
    single_blocks_33_: {
      name: "single_blocks.33."
    },
    single_blocks_34_: {
      name: "single_blocks.34."
    },
    single_blocks_35_: {
      name: "single_blocks.35."
    },
    single_blocks_36_: {
      name: "single_blocks.36."
    },
    single_blocks_37_: {
      name: "single_blocks.37."
    },
    single_blocks_3_: {
      name: "single_blocks.3."
    },
    single_blocks_4_: {
      name: "single_blocks.4."
    },
    single_blocks_5_: {
      name: "single_blocks.5."
    },
    single_blocks_6_: {
      name: "single_blocks.6."
    },
    single_blocks_7_: {
      name: "single_blocks.7."
    },
    single_blocks_8_: {
      name: "single_blocks.8."
    },
    single_blocks_9_: {
      name: "single_blocks.9."
    },
    time_in_: {
      name: "time_in."
    },
    txt_in_: {
      name: "txt_in."
    },
    vector_in_: {
      name: "vector_in."
    }
  }
};
const ModelMergeLTXV$3 = {
  display_name: "モデルマージLTXV",
  inputs: {
    adaln_single_: {
      name: "adaln_single."
    },
    caption_projection_: {
      name: "キャプション投影."
    },
    model1: {
      name: "モデル1"
    },
    model2: {
      name: "モデル2"
    },
    patchify_proj_: {
      name: "patchify_proj."
    },
    proj_out_: {
      name: "proj_out."
    },
    scale_shift_table: {
      name: "スケールシフトテーブル"
    },
    transformer_blocks_0_: {
      name: "トランスフォーマーブロック.0."
    },
    transformer_blocks_10_: {
      name: "トランスフォーマーブロック.10."
    },
    transformer_blocks_11_: {
      name: "トランスフォーマーブロック.11."
    },
    transformer_blocks_12_: {
      name: "トランスフォーマーブロック.12."
    },
    transformer_blocks_13_: {
      name: "トランスフォーマーブロック.13."
    },
    transformer_blocks_14_: {
      name: "トランスフォーマーブロック.14."
    },
    transformer_blocks_15_: {
      name: "トランスフォーマーブロック.15."
    },
    transformer_blocks_16_: {
      name: "トランスフォーマーブロック.16."
    },
    transformer_blocks_17_: {
      name: "トランスフォーマーブロック.17."
    },
    transformer_blocks_18_: {
      name: "トランスフォーマーブロック.18."
    },
    transformer_blocks_19_: {
      name: "トランスフォーマーブロック.19."
    },
    transformer_blocks_1_: {
      name: "トランスフォーマーブロック.1."
    },
    transformer_blocks_20_: {
      name: "トランスフォーマーブロック.20."
    },
    transformer_blocks_21_: {
      name: "トランスフォーマーブロック.21."
    },
    transformer_blocks_22_: {
      name: "トランスフォーマーブロック.22."
    },
    transformer_blocks_23_: {
      name: "トランスフォーマーブロック.23."
    },
    transformer_blocks_24_: {
      name: "トランスフォーマーブロック.24."
    },
    transformer_blocks_25_: {
      name: "トランスフォーマーブロック.25."
    },
    transformer_blocks_26_: {
      name: "トランスフォーマーブロック.26."
    },
    transformer_blocks_27_: {
      name: "トランスフォーマーブロック.27."
    },
    transformer_blocks_2_: {
      name: "トランスフォーマーブロック.2."
    },
    transformer_blocks_3_: {
      name: "トランスフォーマーブロック.3."
    },
    transformer_blocks_4_: {
      name: "トランスフォーマーブロック.4."
    },
    transformer_blocks_5_: {
      name: "トランスフォーマーブロック.5."
    },
    transformer_blocks_6_: {
      name: "トランスフォーマーブロック.6."
    },
    transformer_blocks_7_: {
      name: "トランスフォーマーブロック.7."
    },
    transformer_blocks_8_: {
      name: "トランスフォーマーブロック.8."
    },
    transformer_blocks_9_: {
      name: "トランスフォーマーブロック.9."
    }
  }
};
const ModelMergeMochiPreview$3 = {
  display_name: "モデルマージMochiプレビュー",
  inputs: {
    blocks_0_: {
      name: "blocks.0."
    },
    blocks_10_: {
      name: "blocks.10."
    },
    blocks_11_: {
      name: "blocks.11."
    },
    blocks_12_: {
      name: "blocks.12."
    },
    blocks_13_: {
      name: "blocks.13."
    },
    blocks_14_: {
      name: "blocks.14."
    },
    blocks_15_: {
      name: "blocks.15."
    },
    blocks_16_: {
      name: "blocks.16."
    },
    blocks_17_: {
      name: "blocks.17."
    },
    blocks_18_: {
      name: "blocks.18."
    },
    blocks_19_: {
      name: "blocks.19."
    },
    blocks_1_: {
      name: "blocks.1."
    },
    blocks_20_: {
      name: "blocks.20."
    },
    blocks_21_: {
      name: "blocks.21."
    },
    blocks_22_: {
      name: "blocks.22."
    },
    blocks_23_: {
      name: "blocks.23."
    },
    blocks_24_: {
      name: "blocks.24."
    },
    blocks_25_: {
      name: "blocks.25."
    },
    blocks_26_: {
      name: "blocks.26."
    },
    blocks_27_: {
      name: "blocks.27."
    },
    blocks_28_: {
      name: "blocks.28."
    },
    blocks_29_: {
      name: "blocks.29."
    },
    blocks_2_: {
      name: "blocks.2."
    },
    blocks_30_: {
      name: "blocks.30."
    },
    blocks_31_: {
      name: "blocks.31."
    },
    blocks_32_: {
      name: "blocks.32."
    },
    blocks_33_: {
      name: "blocks.33."
    },
    blocks_34_: {
      name: "blocks.34."
    },
    blocks_35_: {
      name: "blocks.35."
    },
    blocks_36_: {
      name: "blocks.36."
    },
    blocks_37_: {
      name: "blocks.37."
    },
    blocks_38_: {
      name: "blocks.38."
    },
    blocks_39_: {
      name: "blocks.39."
    },
    blocks_3_: {
      name: "blocks.3."
    },
    blocks_40_: {
      name: "blocks.40."
    },
    blocks_41_: {
      name: "blocks.41."
    },
    blocks_42_: {
      name: "blocks.42."
    },
    blocks_43_: {
      name: "blocks.43."
    },
    blocks_44_: {
      name: "blocks.44."
    },
    blocks_45_: {
      name: "blocks.45."
    },
    blocks_46_: {
      name: "blocks.46."
    },
    blocks_47_: {
      name: "blocks.47."
    },
    blocks_4_: {
      name: "blocks.4."
    },
    blocks_5_: {
      name: "blocks.5."
    },
    blocks_6_: {
      name: "blocks.6."
    },
    blocks_7_: {
      name: "blocks.7."
    },
    blocks_8_: {
      name: "blocks.8."
    },
    blocks_9_: {
      name: "blocks.9."
    },
    final_layer_: {
      name: "final_layer."
    },
    model1: {
      name: "モデル1"
    },
    model2: {
      name: "モデル2"
    },
    pos_frequencies_: {
      name: "pos_frequencies."
    },
    t5_y_embedder_: {
      name: "t5_y_embedder."
    },
    t5_yproj_: {
      name: "t5_yproj."
    },
    t_embedder_: {
      name: "t_embedder."
    }
  }
};
const ModelMergeSD1$3 = {
  display_name: "モデルマージSD1",
  inputs: {
    input_blocks_0_: {
      name: "input_blocks.0."
    },
    input_blocks_10_: {
      name: "input_blocks.10."
    },
    input_blocks_11_: {
      name: "input_blocks.11."
    },
    input_blocks_1_: {
      name: "input_blocks.1."
    },
    input_blocks_2_: {
      name: "input_blocks.2."
    },
    input_blocks_3_: {
      name: "input_blocks.3."
    },
    input_blocks_4_: {
      name: "input_blocks.4."
    },
    input_blocks_5_: {
      name: "input_blocks.5."
    },
    input_blocks_6_: {
      name: "input_blocks.6."
    },
    input_blocks_7_: {
      name: "input_blocks.7."
    },
    input_blocks_8_: {
      name: "input_blocks.8."
    },
    input_blocks_9_: {
      name: "input_blocks.9."
    },
    label_emb_: {
      name: "label_emb."
    },
    middle_block_0_: {
      name: "middle_block.0."
    },
    middle_block_1_: {
      name: "middle_block.1."
    },
    middle_block_2_: {
      name: "middle_block.2."
    },
    model1: {
      name: "モデル1"
    },
    model2: {
      name: "モデル2"
    },
    out_: {
      name: "out."
    },
    output_blocks_0_: {
      name: "output_blocks.0."
    },
    output_blocks_10_: {
      name: "output_blocks.10."
    },
    output_blocks_11_: {
      name: "output_blocks.11."
    },
    output_blocks_1_: {
      name: "output_blocks.1."
    },
    output_blocks_2_: {
      name: "output_blocks.2."
    },
    output_blocks_3_: {
      name: "output_blocks.3."
    },
    output_blocks_4_: {
      name: "output_blocks.4."
    },
    output_blocks_5_: {
      name: "output_blocks.5."
    },
    output_blocks_6_: {
      name: "output_blocks.6."
    },
    output_blocks_7_: {
      name: "output_blocks.7."
    },
    output_blocks_8_: {
      name: "output_blocks.8."
    },
    output_blocks_9_: {
      name: "output_blocks.9."
    },
    time_embed_: {
      name: "time_embed."
    }
  }
};
const ModelMergeSD2$3 = {
  display_name: "モデルマージSD2",
  inputs: {
    input_blocks_0_: {
      name: "input_blocks.0."
    },
    input_blocks_10_: {
      name: "input_blocks.10."
    },
    input_blocks_11_: {
      name: "input_blocks.11."
    },
    input_blocks_1_: {
      name: "input_blocks.1."
    },
    input_blocks_2_: {
      name: "input_blocks.2."
    },
    input_blocks_3_: {
      name: "input_blocks.3."
    },
    input_blocks_4_: {
      name: "input_blocks.4."
    },
    input_blocks_5_: {
      name: "input_blocks.5."
    },
    input_blocks_6_: {
      name: "input_blocks.6."
    },
    input_blocks_7_: {
      name: "input_blocks.7."
    },
    input_blocks_8_: {
      name: "input_blocks.8."
    },
    input_blocks_9_: {
      name: "input_blocks.9."
    },
    label_emb_: {
      name: "label_emb."
    },
    middle_block_0_: {
      name: "middle_block.0."
    },
    middle_block_1_: {
      name: "middle_block.1."
    },
    middle_block_2_: {
      name: "middle_block.2."
    },
    model1: {
      name: "モデル1"
    },
    model2: {
      name: "モデル2"
    },
    out_: {
      name: "out."
    },
    output_blocks_0_: {
      name: "output_blocks.0."
    },
    output_blocks_10_: {
      name: "output_blocks.10."
    },
    output_blocks_11_: {
      name: "output_blocks.11."
    },
    output_blocks_1_: {
      name: "output_blocks.1."
    },
    output_blocks_2_: {
      name: "output_blocks.2."
    },
    output_blocks_3_: {
      name: "output_blocks.3."
    },
    output_blocks_4_: {
      name: "output_blocks.4."
    },
    output_blocks_5_: {
      name: "output_blocks.5."
    },
    output_blocks_6_: {
      name: "output_blocks.6."
    },
    output_blocks_7_: {
      name: "output_blocks.7."
    },
    output_blocks_8_: {
      name: "output_blocks.8."
    },
    output_blocks_9_: {
      name: "output_blocks.9."
    },
    time_embed_: {
      name: "time_embed."
    }
  }
};
const ModelMergeSD35_Large$3 = {
  display_name: "モデルマージSD35_Large",
  inputs: {
    context_embedder_: {
      name: "context_embedder."
    },
    final_layer_: {
      name: "final_layer."
    },
    joint_blocks_0_: {
      name: "joint_blocks.0."
    },
    joint_blocks_10_: {
      name: "joint_blocks.10."
    },
    joint_blocks_11_: {
      name: "joint_blocks.11."
    },
    joint_blocks_12_: {
      name: "joint_blocks.12."
    },
    joint_blocks_13_: {
      name: "joint_blocks.13."
    },
    joint_blocks_14_: {
      name: "joint_blocks.14."
    },
    joint_blocks_15_: {
      name: "joint_blocks.15."
    },
    joint_blocks_16_: {
      name: "joint_blocks.16."
    },
    joint_blocks_17_: {
      name: "joint_blocks.17."
    },
    joint_blocks_18_: {
      name: "joint_blocks.18."
    },
    joint_blocks_19_: {
      name: "joint_blocks.19."
    },
    joint_blocks_1_: {
      name: "joint_blocks.1."
    },
    joint_blocks_20_: {
      name: "joint_blocks.20."
    },
    joint_blocks_21_: {
      name: "joint_blocks.21."
    },
    joint_blocks_22_: {
      name: "joint_blocks.22."
    },
    joint_blocks_23_: {
      name: "joint_blocks.23."
    },
    joint_blocks_24_: {
      name: "joint_blocks.24."
    },
    joint_blocks_25_: {
      name: "joint_blocks.25."
    },
    joint_blocks_26_: {
      name: "joint_blocks.26."
    },
    joint_blocks_27_: {
      name: "joint_blocks.27."
    },
    joint_blocks_28_: {
      name: "joint_blocks.28."
    },
    joint_blocks_29_: {
      name: "joint_blocks.29."
    },
    joint_blocks_2_: {
      name: "joint_blocks.2."
    },
    joint_blocks_30_: {
      name: "joint_blocks.30."
    },
    joint_blocks_31_: {
      name: "joint_blocks.31."
    },
    joint_blocks_32_: {
      name: "joint_blocks.32."
    },
    joint_blocks_33_: {
      name: "joint_blocks.33."
    },
    joint_blocks_34_: {
      name: "joint_blocks.34."
    },
    joint_blocks_35_: {
      name: "joint_blocks.35."
    },
    joint_blocks_36_: {
      name: "joint_blocks.36."
    },
    joint_blocks_37_: {
      name: "joint_blocks.37."
    },
    joint_blocks_3_: {
      name: "joint_blocks.3."
    },
    joint_blocks_4_: {
      name: "joint_blocks.4."
    },
    joint_blocks_5_: {
      name: "joint_blocks.5."
    },
    joint_blocks_6_: {
      name: "joint_blocks.6."
    },
    joint_blocks_7_: {
      name: "joint_blocks.7."
    },
    joint_blocks_8_: {
      name: "joint_blocks.8."
    },
    joint_blocks_9_: {
      name: "joint_blocks.9."
    },
    model1: {
      name: "モデル1"
    },
    model2: {
      name: "モデル2"
    },
    pos_embed_: {
      name: "pos_embed."
    },
    t_embedder_: {
      name: "t_embedder."
    },
    x_embedder_: {
      name: "x_embedder."
    },
    y_embedder_: {
      name: "y_embedder."
    }
  }
};
const ModelMergeSD3_2B$3 = {
  display_name: "モデルマージSD3_2B",
  inputs: {
    context_embedder_: {
      name: "context_embedder."
    },
    final_layer_: {
      name: "final_layer."
    },
    joint_blocks_0_: {
      name: "joint_blocks.0."
    },
    joint_blocks_10_: {
      name: "joint_blocks.10."
    },
    joint_blocks_11_: {
      name: "joint_blocks.11."
    },
    joint_blocks_12_: {
      name: "joint_blocks.12."
    },
    joint_blocks_13_: {
      name: "joint_blocks.13."
    },
    joint_blocks_14_: {
      name: "joint_blocks.14."
    },
    joint_blocks_15_: {
      name: "joint_blocks.15."
    },
    joint_blocks_16_: {
      name: "joint_blocks.16."
    },
    joint_blocks_17_: {
      name: "joint_blocks.17."
    },
    joint_blocks_18_: {
      name: "joint_blocks.18."
    },
    joint_blocks_19_: {
      name: "joint_blocks.19."
    },
    joint_blocks_1_: {
      name: "joint_blocks.1."
    },
    joint_blocks_20_: {
      name: "joint_blocks.20."
    },
    joint_blocks_21_: {
      name: "joint_blocks.21."
    },
    joint_blocks_22_: {
      name: "joint_blocks.22."
    },
    joint_blocks_23_: {
      name: "joint_blocks.23."
    },
    joint_blocks_2_: {
      name: "joint_blocks.2."
    },
    joint_blocks_3_: {
      name: "joint_blocks.3."
    },
    joint_blocks_4_: {
      name: "joint_blocks.4."
    },
    joint_blocks_5_: {
      name: "joint_blocks.5."
    },
    joint_blocks_6_: {
      name: "joint_blocks.6."
    },
    joint_blocks_7_: {
      name: "joint_blocks.7."
    },
    joint_blocks_8_: {
      name: "joint_blocks.8."
    },
    joint_blocks_9_: {
      name: "joint_blocks.9."
    },
    model1: {
      name: "モデル1"
    },
    model2: {
      name: "モデル2"
    },
    pos_embed_: {
      name: "pos_embed."
    },
    t_embedder_: {
      name: "t_embedder."
    },
    x_embedder_: {
      name: "x_embedder."
    },
    y_embedder_: {
      name: "y_embedder."
    }
  }
};
const ModelMergeSDXL$3 = {
  display_name: "モデルマージSDXL",
  inputs: {
    input_blocks_0: {
      name: "input_blocks.0"
    },
    input_blocks_1: {
      name: "input_blocks.1"
    },
    input_blocks_2: {
      name: "input_blocks.2"
    },
    input_blocks_3: {
      name: "input_blocks.3"
    },
    input_blocks_4: {
      name: "input_blocks.4"
    },
    input_blocks_5: {
      name: "input_blocks.5"
    },
    input_blocks_6: {
      name: "input_blocks.6"
    },
    input_blocks_7: {
      name: "input_blocks.7"
    },
    input_blocks_8: {
      name: "input_blocks.8"
    },
    label_emb_: {
      name: "label_emb."
    },
    middle_block_0: {
      name: "middle_block.0"
    },
    middle_block_1: {
      name: "middle_block.1"
    },
    middle_block_2: {
      name: "middle_block.2"
    },
    model1: {
      name: "モデル1"
    },
    model2: {
      name: "モデル2"
    },
    out_: {
      name: "out."
    },
    output_blocks_0: {
      name: "output_blocks.0"
    },
    output_blocks_1: {
      name: "output_blocks.1"
    },
    output_blocks_2: {
      name: "output_blocks.2"
    },
    output_blocks_3: {
      name: "output_blocks.3"
    },
    output_blocks_4: {
      name: "output_blocks.4"
    },
    output_blocks_5: {
      name: "output_blocks.5"
    },
    output_blocks_6: {
      name: "output_blocks.6"
    },
    output_blocks_7: {
      name: "output_blocks.7"
    },
    output_blocks_8: {
      name: "output_blocks.8"
    },
    time_embed_: {
      name: "time_embed."
    }
  }
};
const ModelMergeSimple$3 = {
  display_name: "モデルマージシンプル",
  inputs: {
    model1: {
      name: "モデル1"
    },
    model2: {
      name: "モデル2"
    },
    ratio: {
      name: "比率"
    }
  }
};
const ModelMergeSubtract$3 = {
  display_name: "モデルマージ減算",
  inputs: {
    model1: {
      name: "モデル1"
    },
    model2: {
      name: "モデル2"
    },
    multiplier: {
      name: "乗数"
    }
  }
};
const ModelMergeWAN2_1$3 = {
  description: "1.3Bモデルは30ブロック、14Bモデルは40ブロックです。画像から動画へのモデルには追加のimg_embがあります。",
  display_name: "ModelMergeWAN2_1",
  inputs: {
    blocks_0_: {
      name: "blocks.0."
    },
    blocks_10_: {
      name: "blocks.10."
    },
    blocks_11_: {
      name: "blocks.11."
    },
    blocks_12_: {
      name: "blocks.12."
    },
    blocks_13_: {
      name: "blocks.13."
    },
    blocks_14_: {
      name: "blocks.14."
    },
    blocks_15_: {
      name: "blocks.15."
    },
    blocks_16_: {
      name: "blocks.16."
    },
    blocks_17_: {
      name: "blocks.17."
    },
    blocks_18_: {
      name: "blocks.18."
    },
    blocks_19_: {
      name: "blocks.19."
    },
    blocks_1_: {
      name: "blocks.1."
    },
    blocks_20_: {
      name: "blocks.20."
    },
    blocks_21_: {
      name: "blocks.21."
    },
    blocks_22_: {
      name: "blocks.22."
    },
    blocks_23_: {
      name: "blocks.23."
    },
    blocks_24_: {
      name: "blocks.24."
    },
    blocks_25_: {
      name: "blocks.25."
    },
    blocks_26_: {
      name: "blocks.26."
    },
    blocks_27_: {
      name: "blocks.27."
    },
    blocks_28_: {
      name: "blocks.28."
    },
    blocks_29_: {
      name: "blocks.29."
    },
    blocks_2_: {
      name: "blocks.2."
    },
    blocks_30_: {
      name: "blocks.30."
    },
    blocks_31_: {
      name: "blocks.31."
    },
    blocks_32_: {
      name: "blocks.32."
    },
    blocks_33_: {
      name: "blocks.33."
    },
    blocks_34_: {
      name: "blocks.34."
    },
    blocks_35_: {
      name: "blocks.35."
    },
    blocks_36_: {
      name: "blocks.36."
    },
    blocks_37_: {
      name: "blocks.37."
    },
    blocks_38_: {
      name: "blocks.38."
    },
    blocks_39_: {
      name: "blocks.39."
    },
    blocks_3_: {
      name: "blocks.3."
    },
    blocks_4_: {
      name: "blocks.4."
    },
    blocks_5_: {
      name: "blocks.5."
    },
    blocks_6_: {
      name: "blocks.6."
    },
    blocks_7_: {
      name: "blocks.7."
    },
    blocks_8_: {
      name: "blocks.8."
    },
    blocks_9_: {
      name: "blocks.9."
    },
    head_: {
      name: "head."
    },
    img_emb_: {
      name: "img_emb."
    },
    model1: {
      name: "model1"
    },
    model2: {
      name: "model2"
    },
    patch_embedding_: {
      name: "patch_embedding."
    },
    text_embedding_: {
      name: "text_embedding."
    },
    time_embedding_: {
      name: "time_embedding."
    },
    time_projection_: {
      name: "time_projection."
    }
  }
};
const ModelSamplingAuraFlow$3 = {
  display_name: "モデルサンプリングオーラフロー",
  inputs: {
    model: {
      name: "モデル"
    },
    shift: {
      name: "シフト"
    }
  }
};
const ModelSamplingContinuousEDM$3 = {
  display_name: "モデルサンプリング連続EDM",
  inputs: {
    model: {
      name: "モデル"
    },
    sampling: {
      name: "サンプリング"
    },
    sigma_max: {
      name: "sigma_max"
    },
    sigma_min: {
      name: "sigma_min"
    }
  }
};
const ModelSamplingContinuousV$3 = {
  display_name: "モデルサンプリング連続V",
  inputs: {
    model: {
      name: "モデル"
    },
    sampling: {
      name: "サンプリング"
    },
    sigma_max: {
      name: "sigma_max"
    },
    sigma_min: {
      name: "sigma_min"
    }
  }
};
const ModelSamplingDiscrete$3 = {
  display_name: "モデルサンプリング離散",
  inputs: {
    model: {
      name: "モデル"
    },
    sampling: {
      name: "サンプリング"
    },
    zsnr: {
      name: "zsnr"
    }
  }
};
const ModelSamplingFlux$3 = {
  display_name: "モデルサンプリングフラックス",
  inputs: {
    base_shift: {
      name: "基本シフト"
    },
    height: {
      name: "高さ"
    },
    max_shift: {
      name: "最大シフト"
    },
    model: {
      name: "モデル"
    },
    width: {
      name: "幅"
    }
  }
};
const ModelSamplingLTXV$3 = {
  display_name: "モデルサンプリングLTXV",
  inputs: {
    base_shift: {
      name: "基本シフト"
    },
    latent: {
      name: "潜在"
    },
    max_shift: {
      name: "最大シフト"
    },
    model: {
      name: "モデル"
    }
  }
};
const ModelSamplingSD3$3 = {
  display_name: "モデルサンプリングSD3",
  inputs: {
    model: {
      name: "モデル"
    },
    shift: {
      name: "シフト"
    }
  }
};
const ModelSamplingStableCascade$3 = {
  display_name: "モデルサンプリング安定カスケード",
  inputs: {
    model: {
      name: "モデル"
    },
    shift: {
      name: "シフト"
    }
  }
};
const ModelSave$3 = {
  display_name: "モデルを保存",
  inputs: {
    filename_prefix: {
      name: "ファイル名プレフィックス"
    },
    model: {
      name: "モデル"
    }
  }
};
const Morphology$3 = {
  display_name: "画像形態学",
  inputs: {
    image: {
      name: "画像"
    },
    kernel_size: {
      name: "カーネルサイズ"
    },
    operation: {
      name: "操作"
    }
  }
};
const OpenAIDalle2$3 = {
  description: "OpenAIのDALL·E 2エンドポイントを通じて同期的に画像を生成します。",
  display_name: "OpenAI DALL·E 2",
  inputs: {
    control_after_generate: {
      name: "生成後のコントロール"
    },
    image: {
      name: "画像",
      tooltip: "画像編集用のオプション参照画像。"
    },
    mask: {
      name: "マスク",
      tooltip: "インペインティング用のオプションマスク（白い部分が置き換えられます）"
    },
    n: {
      name: "生成数",
      tooltip: "生成する画像の枚数"
    },
    prompt: {
      name: "プロンプト",
      tooltip: "DALL·E用のテキストプロンプト"
    },
    seed: {
      name: "シード",
      tooltip: "バックエンドではまだ未実装"
    },
    size: {
      name: "サイズ",
      tooltip: "画像サイズ"
    }
  }
};
const OpenAIDalle3$3 = {
  description: "OpenAIのDALL·E 3エンドポイントを通じて同期的に画像を生成します。",
  display_name: "OpenAI DALL·E 3",
  inputs: {
    control_after_generate: {
      name: "生成後のコントロール"
    },
    prompt: {
      name: "プロンプト",
      tooltip: "DALL·E用のテキストプロンプト"
    },
    quality: {
      name: "画質",
      tooltip: "画像の品質"
    },
    seed: {
      name: "シード",
      tooltip: "バックエンドではまだ未実装"
    },
    size: {
      name: "サイズ",
      tooltip: "画像サイズ"
    },
    style: {
      name: "スタイル",
      tooltip: "「Vivid」はモデルがハイパーリアルでドラマチックな画像を生成する傾向になります。「Natural」はより自然で、ハイパーリアルではない画像を生成します。"
    }
  }
};
const OpenAIGPTImage1$3 = {
  description: "OpenAIのGPT Image 1エンドポイントを通じて同期的に画像を生成します。",
  display_name: "OpenAI GPT Image 1",
  inputs: {
    background: {
      name: "背景",
      tooltip: "背景あり／なしの画像を返す"
    },
    control_after_generate: {
      name: "生成後のコントロール"
    },
    image: {
      name: "参照画像",
      tooltip: "画像編集用のオプション参照画像。"
    },
    mask: {
      name: "マスク",
      tooltip: "インペインティング用のオプションマスク（白い部分が置き換えられます）"
    },
    n: {
      name: "生成数",
      tooltip: "生成する画像の枚数"
    },
    prompt: {
      name: "プロンプト",
      tooltip: "GPT Image 1用のテキストプロンプト"
    },
    quality: {
      name: "品質",
      tooltip: "画像の品質。コストと生成時間に影響します。"
    },
    seed: {
      name: "シード",
      tooltip: "バックエンドではまだ未実装"
    },
    size: {
      name: "サイズ",
      tooltip: "画像サイズ"
    }
  }
};
const OptimalStepsScheduler$3 = {
  display_name: "OptimalStepsScheduler",
  inputs: {
    denoise: {
      name: "ノイズ除去"
    },
    model_type: {
      name: "model_type"
    },
    steps: {
      name: "ステップ数"
    }
  }
};
const PairConditioningCombine$3 = {
  display_name: "ペア条件付け組み合わせ",
  inputs: {
    negative_A: {
      name: "ネガティブ_A"
    },
    negative_B: {
      name: "ネガティブ_B"
    },
    positive_A: {
      name: "ポジティブ_A"
    },
    positive_B: {
      name: "ポジティブ_B"
    }
  },
  outputs: {
    "0": {
      name: "ポジティブ"
    },
    "1": {
      name: "ネガティブ"
    }
  }
};
const PairConditioningSetDefaultCombine$3 = {
  display_name: "ペア条件付けデフォルト組み合わせを設定",
  inputs: {
    hooks: {
      name: "フック"
    },
    negative: {
      name: "ネガティブ"
    },
    negative_DEFAULT: {
      name: "ネガティブ_DEFAULT"
    },
    positive: {
      name: "ポジティブ"
    },
    positive_DEFAULT: {
      name: "ポジティブ_DEFAULT"
    }
  },
  outputs: {
    "0": {
      name: "ポジティブ"
    },
    "1": {
      name: "ネガティブ"
    }
  }
};
const PairConditioningSetProperties$3 = {
  display_name: "ペア条件付けプロパティ設定",
  inputs: {
    hooks: {
      name: "フック"
    },
    mask: {
      name: "マスク"
    },
    negative_NEW: {
      name: "ネガティブ_NEW"
    },
    positive_NEW: {
      name: "ポジティブ_NEW"
    },
    set_cond_area: {
      name: "set_cond_area"
    },
    strength: {
      name: "強度"
    },
    timesteps: {
      name: "タイムステップ"
    }
  },
  outputs: {
    "0": {
      name: "ポジティブ"
    },
    "1": {
      name: "ネガティブ"
    }
  }
};
const PairConditioningSetPropertiesAndCombine$3 = {
  display_name: "ペア条件付けプロパティ設定と組み合わせ",
  inputs: {
    hooks: {
      name: "フック"
    },
    mask: {
      name: "マスク"
    },
    negative: {
      name: "ネガティブ"
    },
    negative_NEW: {
      name: "ネガティブ_NEW"
    },
    positive: {
      name: "ポジティブ"
    },
    positive_NEW: {
      name: "ポジティブ_NEW"
    },
    set_cond_area: {
      name: "set_cond_area"
    },
    strength: {
      name: "強度"
    },
    timesteps: {
      name: "タイムステップ"
    }
  },
  outputs: {
    "0": {
      name: "ポジティブ"
    },
    "1": {
      name: "ネガティブ"
    }
  }
};
const PatchModelAddDownscale$3 = {
  display_name: "パッチモデル追加ダウンスケール（Kohya Deep Shrink）",
  inputs: {
    block_number: {
      name: "ブロック番号"
    },
    downscale_after_skip: {
      name: "スキップ後のダウンスケール"
    },
    downscale_factor: {
      name: "ダウンスケール係数"
    },
    downscale_method: {
      name: "ダウンスケール方法"
    },
    end_percent: {
      name: "終了パーセント"
    },
    model: {
      name: "モデル"
    },
    start_percent: {
      name: "開始パーセント"
    },
    upscale_method: {
      name: "アップスケール方法"
    }
  }
};
const PerpNeg$3 = {
  display_name: "Perp-Neg（PerpNegGuiderによって非推奨）",
  inputs: {
    empty_conditioning: {
      name: "空のコンディショニング"
    },
    model: {
      name: "モデル"
    },
    neg_scale: {
      name: "ネガティブスケール"
    }
  }
};
const PerpNegGuider$3 = {
  display_name: "PerpNegガイダー",
  inputs: {
    cfg: {
      name: "cfg"
    },
    empty_conditioning: {
      name: "空のコンディショニング"
    },
    model: {
      name: "モデル"
    },
    neg_scale: {
      name: "ネガティブスケール"
    },
    negative: {
      name: "ネガティブ"
    },
    positive: {
      name: "ポジティブ"
    }
  }
};
const PerturbedAttentionGuidance$3 = {
  display_name: "摂動注意ガイダンス",
  inputs: {
    model: {
      name: "モデル"
    },
    scale: {
      name: "スケール"
    }
  }
};
const PhotoMakerEncode$3 = {
  display_name: "フォトメーカーエンコード",
  inputs: {
    clip: {
      name: "clip"
    },
    image: {
      name: "画像"
    },
    photomaker: {
      name: "photomaker"
    },
    text: {
      name: "テキスト"
    }
  }
};
const PhotoMakerLoader$3 = {
  display_name: "フォトメーカーを読み込む",
  inputs: {
    photomaker_model_name: {
      name: "photomakerモデル名"
    }
  }
};
const PikaImageToVideoNode2_2$3 = {
  description: "画像とプロンプトをPika API v2.2に送信して動画を生成します。",
  display_name: "Pika画像から動画へ",
  inputs: {
    control_after_generate: {
      name: "生成後のコントロール"
    },
    duration: {
      name: "再生時間"
    },
    image: {
      name: "画像",
      tooltip: "動画に変換する画像"
    },
    negative_prompt: {
      name: "ネガティブプロンプト"
    },
    prompt_text: {
      name: "プロンプトテキスト"
    },
    resolution: {
      name: "解像度"
    },
    seed: {
      name: "シード"
    }
  }
};
const PikaScenesV2_2$3 = {
  description: "複数の画像を組み合わせて、そこに含まれるオブジェクトを使ったビデオを作成します。複数の画像を素材としてアップロードし、それらすべてを取り入れた高品質なビデオを生成します。",
  display_name: "Pika Scenes（ビデオ画像合成）",
  inputs: {
    aspect_ratio: {
      name: "アスペクト比",
      tooltip: "アスペクト比（幅 / 高さ）"
    },
    control_after_generate: {
      name: "生成後のコントロール"
    },
    duration: {
      name: "再生時間"
    },
    image_ingredient_1: {
      name: "画像素材1",
      tooltip: "ビデオ作成の素材として使用する画像です。"
    },
    image_ingredient_2: {
      name: "画像素材2",
      tooltip: "ビデオ作成の素材として使用する画像です。"
    },
    image_ingredient_3: {
      name: "画像素材3",
      tooltip: "ビデオ作成の素材として使用する画像です。"
    },
    image_ingredient_4: {
      name: "画像素材4",
      tooltip: "ビデオ作成の素材として使用する画像です。"
    },
    image_ingredient_5: {
      name: "画像素材5",
      tooltip: "ビデオ作成の素材として使用する画像です。"
    },
    ingredients_mode: {
      name: "素材モード"
    },
    negative_prompt: {
      name: "ネガティブプロンプト"
    },
    prompt_text: {
      name: "プロンプト"
    },
    resolution: {
      name: "解像度"
    },
    seed: {
      name: "シード"
    }
  }
};
const PikaStartEndFrameNode2_2$3 = {
  description: "最初と最後のフレームを組み合わせて動画を生成します。2枚の画像をアップロードして開始点と終了点を定義し、AIがその間を滑らかに遷移させます。",
  display_name: "Pika 開始・終了フレームから動画生成",
  inputs: {
    control_after_generate: {
      name: "生成後のコントロール"
    },
    duration: {
      name: "duration"
    },
    image_end: {
      name: "image_end",
      tooltip: "組み合わせる最後の画像。"
    },
    image_start: {
      name: "image_start",
      tooltip: "組み合わせる最初の画像。"
    },
    negative_prompt: {
      name: "negative_prompt"
    },
    prompt_text: {
      name: "prompt_text"
    },
    resolution: {
      name: "resolution"
    },
    seed: {
      name: "seed"
    }
  }
};
const PikaTextToVideoNode2_2$3 = {
  description: "テキストプロンプトをPika API v2.2に送信してビデオを生成します。",
  display_name: "Pika テキストからビデオへ",
  inputs: {
    aspect_ratio: {
      name: "アスペクト比",
      tooltip: "アスペクト比（幅 / 高さ）"
    },
    control_after_generate: {
      name: "生成後のコントロール"
    },
    duration: {
      name: "再生時間"
    },
    negative_prompt: {
      name: "ネガティブプロンプト"
    },
    prompt_text: {
      name: "プロンプトテキスト"
    },
    resolution: {
      name: "解像度"
    },
    seed: {
      name: "シード"
    }
  }
};
const Pikadditions$3 = {
  description: "任意のオブジェクトや画像をビデオに追加できます。ビデオをアップロードし、追加したい内容を指定して、シームレスに統合された結果を作成します。",
  display_name: "Pikadditions（ビデオオブジェクト挿入）",
  inputs: {
    control_after_generate: {
      name: "生成後のコントロール"
    },
    image: {
      name: "画像",
      tooltip: "ビデオに追加する画像です。"
    },
    negative_prompt: {
      name: "ネガティブプロンプト"
    },
    prompt_text: {
      name: "プロンプトテキスト"
    },
    seed: {
      name: "シード"
    },
    video: {
      name: "ビデオ",
      tooltip: "画像を追加するビデオです。"
    }
  }
};
const Pikaffects$3 = {
  description: "特定のPikaffectを使ってビデオを生成します。対応しているPikaffect：Cake-ify、Crumble、Crush、Decapitate、Deflate、Dissolve、Explode、Eye-pop、Inflate、Levitate、Melt、Peel、Poke、Squish、Ta-da、Tear",
  display_name: "Pikaffects（ビデオエフェクト）",
  inputs: {
    control_after_generate: {
      name: "生成後のコントロール"
    },
    image: {
      name: "画像",
      tooltip: "Pikaffectを適用する参照画像。"
    },
    negative_prompt: {
      name: "ネガティブプロンプト"
    },
    pikaffect: {
      name: "Pikaffect"
    },
    prompt_text: {
      name: "プロンプトテキスト"
    },
    seed: {
      name: "シード"
    }
  }
};
const Pikaswaps$3 = {
  description: "ビデオ内の任意のオブジェクトや領域を新しい画像やオブジェクトで置き換えます。置換する領域はマスクまたは座標で指定できます。",
  display_name: "Pika Swaps（ビデオオブジェクト置換）",
  inputs: {
    control_after_generate: {
      name: "生成後のコントロール"
    },
    image: {
      name: "image",
      tooltip: "ビデオ内のマスクされたオブジェクトを置き換えるために使用する画像。"
    },
    mask: {
      name: "mask",
      tooltip: "ビデオ内で置換する領域を定義するためのマスクを使用します"
    },
    negative_prompt: {
      name: "negative_prompt"
    },
    prompt_text: {
      name: "prompt_text"
    },
    seed: {
      name: "seed"
    },
    video: {
      name: "video",
      tooltip: "オブジェクトを置換するビデオ。"
    }
  }
};
const PixverseImageToVideoNode$3 = {
  description: "プロンプトと出力サイズに基づいて同期的に動画を生成します。",
  display_name: "PixVerse 画像から動画へ",
  inputs: {
    control_after_generate: {
      name: "生成後のコントロール"
    },
    duration_seconds: {
      name: "継続時間（秒）"
    },
    image: {
      name: "画像"
    },
    motion_mode: {
      name: "モーションモード"
    },
    negative_prompt: {
      name: "ネガティブプロンプト",
      tooltip: "画像に含めたくない要素のテキスト説明（任意）。"
    },
    pixverse_template: {
      name: "PixVerseテンプレート",
      tooltip: "生成スタイルに影響を与える任意のテンプレート。PixVerse Templateノードで作成。"
    },
    prompt: {
      name: "プロンプト",
      tooltip: "動画生成用のプロンプト"
    },
    quality: {
      name: "品質"
    },
    seed: {
      name: "シード",
      tooltip: "動画生成用のシード値。"
    }
  }
};
const PixverseTemplateNode$3 = {
  display_name: "PixVerseテンプレート",
  inputs: {
    template: {
      name: "テンプレート"
    }
  },
  outputs: {
    "0": {
      name: "pixverse_template"
    }
  }
};
const PixverseTextToVideoNode$3 = {
  description: "プロンプトと出力サイズに基づいて同期的にビデオを生成します。",
  display_name: "PixVerse テキストからビデオへ",
  inputs: {
    aspect_ratio: {
      name: "アスペクト比"
    },
    control_after_generate: {
      name: "生成後のコントロール"
    },
    duration_seconds: {
      name: "秒数"
    },
    motion_mode: {
      name: "モーションモード"
    },
    negative_prompt: {
      name: "ネガティブプロンプト",
      tooltip: "画像に含めたくない要素のテキスト説明（任意）。"
    },
    pixverse_template: {
      name: "PixVerse テンプレート",
      tooltip: "生成スタイルに影響を与える任意のテンプレート。PixVerse Templateノードで作成。"
    },
    prompt: {
      name: "プロンプト",
      tooltip: "ビデオ生成のためのプロンプト"
    },
    quality: {
      name: "品質"
    },
    seed: {
      name: "シード",
      tooltip: "ビデオ生成のためのシード。"
    }
  }
};
const PixverseTransitionVideoNode$3 = {
  description: "プロンプトと出力サイズに基づいて同期的にビデオを生成します。",
  display_name: "PixVerse トランジションビデオ",
  inputs: {
    control_after_generate: {
      name: "生成後のコントロール"
    },
    duration_seconds: {
      name: "継続時間（秒）"
    },
    first_frame: {
      name: "first_frame"
    },
    last_frame: {
      name: "last_frame"
    },
    motion_mode: {
      name: "モーションモード"
    },
    negative_prompt: {
      name: "ネガティブプロンプト",
      tooltip: "画像に含めたくない要素のテキスト説明（任意）。"
    },
    prompt: {
      name: "プロンプト",
      tooltip: "ビデオ生成用のプロンプト"
    },
    quality: {
      name: "品質"
    },
    seed: {
      name: "シード",
      tooltip: "ビデオ生成用のシード値。"
    }
  }
};
const PolyexponentialScheduler$3 = {
  display_name: "ポリ指数スケジューラー",
  inputs: {
    rho: {
      name: "ロー"
    },
    sigma_max: {
      name: "シグママックス"
    },
    sigma_min: {
      name: "シグマミン"
    },
    steps: {
      name: "ステップ"
    }
  }
};
const PorterDuffImageComposite$3 = {
  display_name: "ポーターダフ画像合成",
  inputs: {
    destination: {
      name: "デスティネーション"
    },
    destination_alpha: {
      name: "デスティネーションアルファ"
    },
    mode: {
      name: "モード"
    },
    source: {
      name: "ソース"
    },
    source_alpha: {
      name: "ソースアルファ"
    }
  }
};
const Preview3D$3 = {
  display_name: "3Dプレビュー",
  inputs: {
    camera_info: {
      name: "カメラ情報"
    },
    image: {
      name: "画像"
    },
    model_file: {
      name: "モデルファイル"
    }
  }
};
const Preview3DAnimation$3 = {
  display_name: "プレビュー 3D - アニメーション",
  inputs: {
    camera_info: {
      name: "カメラ情報"
    },
    image: {
      name: "画像"
    },
    model_file: {
      name: "モデルファイル"
    }
  }
};
const PreviewAny$3 = {
  display_name: "プレビュー任意",
  inputs: {
    preview: {},
    source: {
      name: "ソース"
    }
  }
};
const PreviewAudio$3 = {
  display_name: "オーディオプレビュー",
  inputs: {
    audio: {
      name: "オーディオ"
    },
    audioUI: {
      name: "audioUI"
    }
  }
};
const PreviewImage$3 = {
  description: "入力画像をComfyUI出力ディレクトリに保存します。",
  display_name: "画像プレビュー",
  inputs: {
    images: {
      name: "画像"
    }
  }
};
const PrimitiveBoolean$3 = {
  display_name: "ブール値",
  inputs: {
    value: {
      name: "値"
    }
  }
};
const PrimitiveFloat$3 = {
  display_name: "浮動小数点数",
  inputs: {
    value: {
      name: "値"
    }
  }
};
const PrimitiveInt$3 = {
  display_name: "整数",
  inputs: {
    control_after_generate: {
      name: "生成後に制御"
    },
    value: {
      name: "値"
    }
  }
};
const PrimitiveString$3 = {
  display_name: "文字列",
  inputs: {
    value: {
      name: "値"
    }
  }
};
const PrimitiveStringMultiline$3 = {
  display_name: "文字列（複数行）",
  inputs: {
    value: {
      name: "値"
    }
  }
};
const QuadrupleCLIPLoader$3 = {
  description: "[レシピ]\n\nhidream: long clip-l、long clip-g、t5xxl、llama_8b_3.1_instruct",
  display_name: "QuadrupleCLIPLoader",
  inputs: {
    clip_name1: {
      name: "clip_name1"
    },
    clip_name2: {
      name: "clip_name2"
    },
    clip_name3: {
      name: "clip_name3"
    },
    clip_name4: {
      name: "clip_name4"
    }
  }
};
const RandomNoise$3 = {
  display_name: "ランダムノイズ",
  inputs: {
    control_after_generate: {
      name: "生成後の制御"
    },
    noise_seed: {
      name: "ノイズシード"
    }
  }
};
const RebatchImages$3 = {
  display_name: "画像を再バッチ",
  inputs: {
    batch_size: {
      name: "バッチサイズ"
    },
    images: {
      name: "画像"
    }
  }
};
const RebatchLatents$3 = {
  display_name: "潜在を再バッチ",
  inputs: {
    batch_size: {
      name: "バッチサイズ"
    },
    latents: {
      name: "潜在変数"
    }
  }
};
const RecraftColorRGB$3 = {
  description: "特定のRGB値を選択してRecraftカラーを作成します。",
  display_name: "Recraft カラー RGB",
  inputs: {
    b: {
      name: "b",
      tooltip: "色の青の値。"
    },
    g: {
      name: "g",
      tooltip: "色の緑の値。"
    },
    r: {
      name: "r",
      tooltip: "色の赤の値。"
    },
    recraft_color: {
      name: "recraft_color"
    }
  },
  outputs: {
    "0": {
      name: "recraft_color"
    }
  }
};
const RecraftControls$3 = {
  description: "Recraft生成をカスタマイズするためのRecraftコントロールを作成します。",
  display_name: "Recraftコントロール",
  inputs: {
    background_color: {
      name: "background_color"
    },
    colors: {
      name: "colors"
    }
  },
  outputs: {
    "0": {
      name: "recraft_controls"
    }
  }
};
const RecraftCreativeUpscaleNode$3 = {
  description: "画像を同期的にアップスケールします。\n「creative upscale」ツールを使用して指定されたラスタ画像を強化し、解像度を高めながら細部や顔の精細さに重点を置いて向上させます。",
  display_name: "Recraft Creative アップスケール画像",
  inputs: {
    image: {
      name: "画像"
    }
  }
};
const RecraftCrispUpscaleNode$3 = {
  description: "画像を同期的にアップスケールします。\n「シャープ高解像度アップスケール」ツールを使用して、指定されたラスタ画像の解像度を上げ、より鮮明でクリアな画像にします。",
  display_name: "Recraft シャープ高解像度アップスケール画像",
  inputs: {
    image: {
      name: "画像"
    }
  }
};
const RecraftImageInpaintingNode$3 = {
  description: "プロンプトとマスクに基づいて画像を修正します。",
  display_name: "Recraft画像インペインティング",
  inputs: {
    control_after_generate: {
      name: "生成後のコントロール"
    },
    image: {
      name: "image"
    },
    mask: {
      name: "mask"
    },
    n: {
      name: "生成数",
      tooltip: "生成する画像の枚数。"
    },
    negative_prompt: {
      name: "ネガティブプロンプト",
      tooltip: "画像に含めたくない要素のテキスト説明（任意）。"
    },
    prompt: {
      name: "プロンプト",
      tooltip: "画像生成のためのプロンプト。"
    },
    recraft_style: {
      name: "recraft_style"
    },
    seed: {
      name: "シード値",
      tooltip: "ノードを再実行するかどうかを決定するシード値です。実際の結果はシード値に関係なく非決定的です。"
    }
  }
};
const RecraftImageToImageNode$3 = {
  description: "プロンプトと強度に基づいて画像を修正します。",
  display_name: "Recraft 画像から画像へ",
  inputs: {
    control_after_generate: {
      name: "生成後のコントロール"
    },
    image: {
      name: "画像"
    },
    n: {
      name: "生成数",
      tooltip: "生成する画像の枚数。"
    },
    negative_prompt: {
      name: "ネガティブプロンプト",
      tooltip: "画像に含めたくない要素のための任意のテキスト説明。"
    },
    prompt: {
      name: "プロンプト",
      tooltip: "画像生成のためのプロンプト。"
    },
    recraft_controls: {
      name: "recraft_controls",
      tooltip: "Recraft Controlsノードを通じて生成に追加のコントロールを加えるオプション。"
    },
    recraft_style: {
      name: "recraft_style"
    },
    seed: {
      name: "シード",
      tooltip: "ノードを再実行するかどうかを決定するシード値。実際の結果はシードに関係なく非決定的です。"
    },
    strength: {
      name: "強度",
      tooltip: "元画像との違いを定義します。[0, 1]の範囲で、0はほぼ同一、1は大きく異なります。"
    }
  }
};
const RecraftRemoveBackgroundNode$3 = {
  description: "画像の背景を除去し、処理済み画像とmaskを返します。",
  display_name: "Recraft 背景除去",
  inputs: {
    image: {
      name: "画像"
    }
  }
};
const RecraftReplaceBackgroundNode$3 = {
  description: "指定されたプロンプトに基づいて画像の背景を置き換えます。",
  display_name: "Recraft 背景置換",
  inputs: {
    control_after_generate: {
      name: "生成後のコントロール"
    },
    image: {
      name: "画像"
    },
    n: {
      name: "生成数",
      tooltip: "生成する画像の枚数。"
    },
    negative_prompt: {
      name: "ネガティブプロンプト",
      tooltip: "画像に含めたくない要素のテキスト説明（任意）。"
    },
    prompt: {
      name: "プロンプト",
      tooltip: "画像生成のためのプロンプト。"
    },
    recraft_style: {
      name: "Recraftスタイル"
    },
    seed: {
      name: "シード",
      tooltip: "ノードを再実行するかどうかを決定するシード値。実際の結果はシードに関係なく非決定的です。"
    }
  }
};
const RecraftStyleV3DigitalIllustration$3 = {
  description: "realistic_imageスタイルとオプションのサブスタイルを選択してください。",
  display_name: "Recraftスタイル - デジタルイラストレーション",
  inputs: {
    substyle: {
      name: "サブスタイル"
    }
  },
  outputs: {
    "0": {
      name: "recraft_style"
    }
  }
};
const RecraftStyleV3InfiniteStyleLibrary$3 = {
  description: "Recraftのインフィニットスタイルライブラリから既存のUUIDに基づいてスタイルを選択します。",
  display_name: "Recraftスタイル - インフィニットスタイルライブラリ",
  inputs: {
    style_id: {
      name: "style_id",
      tooltip: "インフィニットスタイルライブラリのスタイルUUID。"
    }
  },
  outputs: {
    "0": {
      name: "recraft_style"
    }
  }
};
const RecraftStyleV3LogoRaster$3 = {
  description: "realistic_imageスタイルとオプションのサブスタイルを選択します。",
  display_name: "Recraft Style - ロゴラスタ",
  inputs: {
    substyle: {
      name: "サブスタイル"
    }
  },
  outputs: {
    "0": {
      name: "recraft_style"
    }
  }
};
const RecraftStyleV3RealisticImage$3 = {
  description: "realistic_imageスタイルとオプションのサブスタイルを選択します。",
  display_name: "Recraftスタイル - リアルな画像",
  inputs: {
    substyle: {
      name: "サブスタイル"
    }
  },
  outputs: {
    "0": {
      name: "recraft_style"
    }
  }
};
const RecraftTextToImageNode$3 = {
  description: "プロンプトと解像度に基づいて同期的に画像を生成します。",
  display_name: "Recraft テキストから画像へ",
  inputs: {
    control_after_generate: {
      name: "生成後コントロール"
    },
    n: {
      name: "枚数",
      tooltip: "生成する画像の枚数。"
    },
    negative_prompt: {
      name: "ネガティブプロンプト",
      tooltip: "画像に含めたくない要素のオプションのテキスト説明。"
    },
    prompt: {
      name: "プロンプト",
      tooltip: "画像生成のためのプロンプト。"
    },
    recraft_controls: {
      name: "Recraftコントロール",
      tooltip: "Recraft Controlsノードを通じて生成に対する追加のコントロール（オプション）。"
    },
    recraft_style: {
      name: "recraft_style"
    },
    seed: {
      name: "シード",
      tooltip: "ノードを再実行するかどうかを決定するためのシード。実際の結果はシードに関係なく非決定的です。"
    },
    size: {
      name: "サイズ",
      tooltip: "生成される画像のサイズ。"
    }
  }
};
const RecraftTextToVectorNode$3 = {
  description: "プロンプトと解像度に基づいてSVGを同期的に生成します。",
  display_name: "Recraft テキストからベクターへ",
  inputs: {
    control_after_generate: {
      name: "生成後のコントロール"
    },
    n: {
      name: "生成数",
      tooltip: "生成する画像の枚数。"
    },
    negative_prompt: {
      name: "ネガティブプロンプト",
      tooltip: "画像に含めたくない要素のテキスト説明（オプション）。"
    },
    prompt: {
      name: "プロンプト",
      tooltip: "画像生成のためのプロンプト。"
    },
    recraft_controls: {
      name: "Recraft コントロール",
      tooltip: "Recraft Controlsノードを通じて生成に追加のコントロールを加える（オプション）。"
    },
    seed: {
      name: "シード",
      tooltip: "ノードを再実行するかどうかを決定するシード；実際の結果はシードに関係なく非決定的です。"
    },
    size: {
      name: "サイズ",
      tooltip: "生成される画像のサイズ。"
    },
    substyle: {
      name: "サブスタイル"
    }
  }
};
const RecraftVectorizeImageNode$3 = {
  description: "入力画像からSVGを同期的に生成します。",
  display_name: "Recraft ベクトル化画像",
  inputs: {
    image: {
      name: "画像"
    }
  }
};
const RenormCFG$3 = {
  display_name: "RenormCFG",
  inputs: {
    cfg_trunc: {
      name: "cfg_trunc"
    },
    model: {
      name: "モデル"
    },
    renorm_cfg: {
      name: "renorm_cfg"
    }
  }
};
const RepeatImageBatch$3 = {
  display_name: "画像バッチを繰り返す",
  inputs: {
    amount: {
      name: "量"
    },
    image: {
      name: "画像"
    }
  }
};
const RepeatLatentBatch$3 = {
  display_name: "潜在バッチを繰り返す",
  inputs: {
    amount: {
      name: "量"
    },
    samples: {
      name: "サンプル"
    }
  }
};
const RescaleCFG$3 = {
  display_name: "CFGを再スケール",
  inputs: {
    model: {
      name: "モデル"
    },
    multiplier: {
      name: "乗数"
    }
  }
};
const SDTurboScheduler$3 = {
  display_name: "SDターボスケジューラー",
  inputs: {
    denoise: {
      name: "ノイズ除去"
    },
    model: {
      name: "モデル"
    },
    steps: {
      name: "ステップ"
    }
  }
};
const SD_4XUpscale_Conditioning$3 = {
  display_name: "SD_4X拡大条件付け",
  inputs: {
    images: {
      name: "画像"
    },
    negative: {
      name: "ネガティブ"
    },
    noise_augmentation: {
      name: "ノイズ増強"
    },
    positive: {
      name: "ポジティブ"
    },
    scale_ratio: {
      name: "スケール比"
    }
  },
  outputs: {
    "0": {
      name: "ポジティブ"
    },
    "1": {
      name: "ネガティブ"
    },
    "2": {
      name: "潜在"
    }
  }
};
const SV3D_Conditioning$3 = {
  display_name: "SV3D条件付け",
  inputs: {
    clip_vision: {
      name: "クリップビジョン"
    },
    elevation: {
      name: "高度"
    },
    height: {
      name: "高さ"
    },
    init_image: {
      name: "初期画像"
    },
    vae: {
      name: "vae"
    },
    video_frames: {
      name: "ビデオフレーム"
    },
    width: {
      name: "幅"
    }
  },
  outputs: {
    "0": {
      name: "ポジティブ"
    },
    "1": {
      name: "ネガティブ"
    },
    "2": {
      name: "潜在"
    }
  }
};
const SVD_img2vid_Conditioning$3 = {
  display_name: "SVD_img2vid条件付け",
  inputs: {
    augmentation_level: {
      name: "増強レベル"
    },
    clip_vision: {
      name: "clip_vision"
    },
    fps: {
      name: "fps"
    },
    height: {
      name: "高さ"
    },
    init_image: {
      name: "初期画像"
    },
    motion_bucket_id: {
      name: "モーションバケットID"
    },
    vae: {
      name: "vae"
    },
    video_frames: {
      name: "ビデオフレーム"
    },
    width: {
      name: "幅"
    }
  },
  outputs: {
    "0": {
      name: "ポジティブ"
    },
    "1": {
      name: "ネガティブ"
    },
    "2": {
      name: "潜在"
    }
  }
};
const SamplerCustom$3 = {
  display_name: "カスタムサンプラー",
  inputs: {
    add_noise: {
      name: "ノイズを追加"
    },
    cfg: {
      name: "cfg"
    },
    control_after_generate: {
      name: "生成後の制御"
    },
    latent_image: {
      name: "潜在画像"
    },
    model: {
      name: "モデル"
    },
    negative: {
      name: "ネガティブ"
    },
    noise_seed: {
      name: "ノイズシード"
    },
    positive: {
      name: "ポジティブ"
    },
    sampler: {
      name: "サンプラー"
    },
    sigmas: {
      name: "シグマ"
    }
  },
  outputs: {
    "0": {
      name: "出力"
    },
    "1": {
      name: "デノイズ出力"
    }
  }
};
const SamplerCustomAdvanced$3 = {
  display_name: "カスタムサンプラー（高度）",
  inputs: {
    guider: {
      name: "ガイダー"
    },
    latent_image: {
      name: "潜在イメージ"
    },
    noise: {
      name: "ノイズ"
    },
    sampler: {
      name: "サンプラー"
    },
    sigmas: {
      name: "シグマ"
    }
  },
  outputs: {
    "0": {
      name: "出力"
    },
    "1": {
      name: "デノイズ出力"
    }
  }
};
const SamplerDPMAdaptative$3 = {
  display_name: "サンプラーDPM適応",
  inputs: {
    accept_safety: {
      name: "accept_safety"
    },
    atol: {
      name: "atol"
    },
    dcoeff: {
      name: "dcoeff"
    },
    eta: {
      name: "eta"
    },
    h_init: {
      name: "h_init"
    },
    icoeff: {
      name: "icoeff"
    },
    order: {
      name: "順序"
    },
    pcoeff: {
      name: "pcoeff"
    },
    rtol: {
      name: "rtol"
    },
    s_noise: {
      name: "s_noise"
    }
  }
};
const SamplerDPMPP_2M_SDE$3 = {
  display_name: "サンプラーDPMPP_2M_SDE",
  inputs: {
    eta: {
      name: "eta"
    },
    noise_device: {
      name: "ノイズデバイス"
    },
    s_noise: {
      name: "s_noise"
    },
    solver_type: {
      name: "ソルバータイプ"
    }
  }
};
const SamplerDPMPP_2S_Ancestral$3 = {
  display_name: "サンプラーDPMPP_2S_祖先",
  inputs: {
    eta: {
      name: "eta"
    },
    s_noise: {
      name: "s_noise"
    }
  }
};
const SamplerDPMPP_3M_SDE$3 = {
  display_name: "サンプラーDPMPP_3M_SDE",
  inputs: {
    eta: {
      name: "eta"
    },
    noise_device: {
      name: "ノイズデバイス"
    },
    s_noise: {
      name: "s_noise"
    }
  }
};
const SamplerDPMPP_SDE$3 = {
  display_name: "サンプラーDPMPP_SDE",
  inputs: {
    eta: {
      name: "eta"
    },
    noise_device: {
      name: "ノイズデバイス"
    },
    r: {
      name: "r"
    },
    s_noise: {
      name: "s_noise"
    }
  }
};
const SamplerEulerAncestral$3 = {
  display_name: "サンプラーオイラー祖先",
  inputs: {
    eta: {
      name: "eta"
    },
    s_noise: {
      name: "s_noise"
    }
  }
};
const SamplerEulerAncestralCFGPP$3 = {
  display_name: "サンプラーオイラー祖先CFG++",
  inputs: {
    eta: {
      name: "eta"
    },
    s_noise: {
      name: "s_noise"
    }
  }
};
const SamplerEulerCFGpp$3 = {
  display_name: "サンプラーオイラーCFG++",
  inputs: {
    version: {
      name: "バージョン"
    }
  }
};
const SamplerLCMUpscale$3 = {
  display_name: "サンプラーLCM拡大",
  inputs: {
    scale_ratio: {
      name: "スケール比"
    },
    scale_steps: {
      name: "スケールステップ"
    },
    upscale_method: {
      name: "アップスケール方法"
    }
  }
};
const SamplerLMS$3 = {
  display_name: "サンプラーLMS",
  inputs: {
    order: {
      name: "順序"
    }
  }
};
const SaveAnimatedPNG$3 = {
  display_name: "アニメーションPNGを保存",
  inputs: {
    compress_level: {
      name: "圧縮レベル"
    },
    filename_prefix: {
      name: "ファイル名プレフィックス"
    },
    fps: {
      name: "fps"
    },
    images: {
      name: "画像"
    }
  }
};
const SaveAnimatedWEBP$3 = {
  display_name: "アニメーションWEBPを保存",
  inputs: {
    filename_prefix: {
      name: "ファイル名プレフィックス"
    },
    fps: {
      name: "fps"
    },
    images: {
      name: "画像"
    },
    lossless: {
      name: "ロスレス"
    },
    method: {
      name: "方法"
    },
    quality: {
      name: "品質"
    }
  }
};
const SaveAudio$3 = {
  display_name: "オーディオを保存",
  inputs: {
    audio: {
      name: "オーディオ"
    },
    audioUI: {
      name: "audioUI"
    },
    filename_prefix: {
      name: "ファイル名_プレフィックス"
    }
  }
};
const SaveGLB$3 = {
  display_name: "SaveGLB",
  inputs: {
    filename_prefix: {
      name: "ファイル名のプレフィックス"
    },
    image: {
      name: "画像"
    },
    mesh: {
      name: "メッシュ"
    }
  }
};
const SaveImage$3 = {
  description: "入力画像をComfyUI出力ディレクトリに保存します。",
  display_name: "画像を保存",
  inputs: {
    filename_prefix: {
      name: "ファイル名_プレフィックス",
      tooltip: "保存するファイルのプレフィックス。この中には、ノードからの値を含めるために、%date:yyyy-MM-dd%や%Empty Latent Image.width%などのフォーマット情報が含まれる場合があります。"
    },
    images: {
      name: "画像",
      tooltip: "保存する画像。"
    }
  }
};
const SaveImageWebsocket$3 = {
  display_name: "画像を保存するWebSocket",
  inputs: {
    images: {
      name: "画像"
    }
  }
};
const SaveLatent$3 = {
  display_name: "潜在を保存",
  inputs: {
    filename_prefix: {
      name: "ファイル名_プレフィックス"
    },
    samples: {
      name: "サンプル"
    }
  }
};
const SaveSVG$3 = {
  description: "SVGファイルをディスクに保存します。",
  display_name: "SVGを保存",
  inputs: {
    filename_prefix: {
      name: "ファイル名プレフィックス",
      tooltip: "保存するファイルのプレフィックスです。%date:yyyy-MM-dd% や %Empty Latent Image.width% など、ノードからの値を含めるフォーマット情報を指定できます。"
    },
    svg: {
      name: "svg"
    }
  }
};
const SaveVideo$3 = {
  description: "入力画像をComfyUIの出力ディレクトリに保存します。",
  display_name: "ビデオを保存",
  inputs: {
    codec: {
      name: "コーデック",
      tooltip: "ビデオに使用するコーデック。"
    },
    filename_prefix: {
      name: "ファイル名プレフィックス",
      tooltip: "保存するファイルのプレフィックス。%date:yyyy-MM-dd% や %Empty Latent Image.width% など、ノードからの値を含める書式情報を含めることができます。"
    },
    format: {
      name: "フォーマット",
      tooltip: "ビデオを保存するフォーマット。"
    },
    video: {
      name: "ビデオ",
      tooltip: "保存するビデオ。"
    }
  }
};
const SaveWEBM$3 = {
  display_name: "SaveWEBM",
  inputs: {
    codec: {
      name: "コーデック"
    },
    crf: {
      name: "crf",
      tooltip: "crfが高いほどファイルサイズは小さくなりますが、品質は低下します。逆に、crfが低いほど品質は高くなりますが、ファイルサイズは大きくなります。"
    },
    filename_prefix: {
      name: "ファイル名の接頭辞"
    },
    fps: {
      name: "fps"
    },
    images: {
      name: "画像"
    }
  }
};
const SelfAttentionGuidance$3 = {
  display_name: "自己注意ガイダンス",
  inputs: {
    blur_sigma: {
      name: "ブラーシグマ"
    },
    model: {
      name: "モデル"
    },
    scale: {
      name: "スケール"
    }
  }
};
const SetClipHooks$3 = {
  display_name: "CLIPフックを設定",
  inputs: {
    apply_to_conds: {
      name: "apply_to_conds"
    },
    clip: {
      name: "クリップ"
    },
    hooks: {
      name: "フック"
    },
    schedule_clip: {
      name: "schedule_clip"
    }
  }
};
const SetFirstSigma$3 = {
  display_name: "SetFirstSigma",
  inputs: {
    sigma: {
      name: "シグマ"
    },
    sigmas: {
      name: "シグマ"
    }
  }
};
const SetHookKeyframes$3 = {
  display_name: "フックキーフレームを設定",
  inputs: {
    hook_kf: {
      name: "フック_kf"
    },
    hooks: {
      name: "フック"
    }
  }
};
const SetLatentNoiseMask$3 = {
  display_name: "潜在ノイズマスクを設定",
  inputs: {
    mask: {
      name: "マスク"
    },
    samples: {
      name: "サンプル"
    }
  }
};
const SetUnionControlNetType$3 = {
  display_name: "Union ControlNetタイプを設定",
  inputs: {
    control_net: {
      name: "control_net"
    },
    type: {
      name: "タイプ"
    }
  }
};
const SkipLayerGuidanceDiT$3 = {
  description: "すべてのDiTモデルで使用できるSkipLayerGuidanceノードの一般的なバージョン。",
  display_name: "SkipLayerGuidanceDiT",
  inputs: {
    double_layers: {
      name: "ダブルレイヤー"
    },
    end_percent: {
      name: "終了パーセント"
    },
    model: {
      name: "モデル"
    },
    rescaling_scale: {
      name: "リスケーリングスケール"
    },
    scale: {
      name: "スケール"
    },
    single_layers: {
      name: "シングルレイヤー"
    },
    start_percent: {
      name: "開始パーセント"
    }
  }
};
const SkipLayerGuidanceSD3$3 = {
  description: "すべてのDiTモデルで使用できるSkipLayerGuidanceノードの一般的なバージョン。",
  display_name: "SkipLayerGuidanceSD3",
  inputs: {
    end_percent: {
      name: "終了パーセント"
    },
    layers: {
      name: "レイヤー"
    },
    model: {
      name: "モデル"
    },
    scale: {
      name: "スケール"
    },
    start_percent: {
      name: "開始パーセント"
    }
  }
};
const SolidMask$3 = {
  display_name: "ソリッドマスク",
  inputs: {
    height: {
      name: "高さ"
    },
    value: {
      name: "値"
    },
    width: {
      name: "幅"
    }
  }
};
const SplitImageWithAlpha$3 = {
  display_name: "アルファで画像を分割",
  inputs: {
    image: {
      name: "画像"
    }
  }
};
const SplitSigmas$3 = {
  display_name: "シグマを分割",
  inputs: {
    sigmas: {
      name: "シグマ"
    },
    step: {
      name: "ステップ"
    }
  },
  outputs: {
    "0": {
      name: "高シグマ"
    },
    "1": {
      name: "低シグマ"
    }
  }
};
const SplitSigmasDenoise$3 = {
  display_name: "シグマを分割してノイズ除去",
  inputs: {
    denoise: {
      name: "ノイズ除去"
    },
    sigmas: {
      name: "シグマ"
    }
  },
  outputs: {
    "0": {
      name: "高シグマ"
    },
    "1": {
      name: "低シグマ"
    }
  }
};
const StabilityStableImageSD_3_5Node$3 = {
  description: "プロンプトと解像度に基づいて同期的に画像を生成します。",
  display_name: "Stability AI Stable Diffusion 3.5 Image",
  inputs: {
    aspect_ratio: {
      name: "アスペクト比",
      tooltip: "生成される画像のアスペクト比。"
    },
    cfg_scale: {
      name: "cfgスケール",
      tooltip: "拡散プロセスがプロンプトテキストにどれだけ厳密に従うか（値が高いほどプロンプトに近い画像になります）"
    },
    control_after_generate: {
      name: "生成後コントロール"
    },
    image: {
      name: "画像"
    },
    image_denoise: {
      name: "画像ノイズ除去",
      tooltip: "入力画像のノイズ除去度合い。0.0は入力画像と同一、1.0は画像が全く提供されていない状態と同じです。"
    },
    model: {
      name: "モデル"
    },
    negative_prompt: {
      name: "ネガティブプロンプト",
      tooltip: "出力画像に表示したくないキーワード。上級者向けの機能です。"
    },
    prompt: {
      name: "プロンプト",
      tooltip: "出力画像に表示したい内容を入力してください。要素、色、被写体を明確に定義した強く詳細なプロンプトは、より良い結果につながります。"
    },
    seed: {
      name: "シード",
      tooltip: "ノイズ生成に使用されるランダムシード。"
    },
    style_preset: {
      name: "スタイルプリセット",
      tooltip: "生成画像に希望するスタイル（任意）。"
    }
  }
};
const StabilityStableImageUltraNode$3 = {
  description: "プロンプトと解像度に基づいて同期的に画像を生成します。",
  display_name: "Stability AI Stable Image Ultra",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio",
      tooltip: "生成される画像のアスペクト比。"
    },
    control_after_generate: {
      name: "control after generate"
    },
    image: {
      name: "image"
    },
    image_denoise: {
      name: "image_denoise",
      tooltip: "入力画像のノイズ除去度合い。0.0は入力画像と同一、1.0は画像が全く提供されていない状態と同じです。"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "出力画像に表示したくない内容を記述します。これは上級者向けの機能です。"
    },
    prompt: {
      name: "prompt",
      tooltip: "出力画像に見たいものを入力します。要素、色、被写体を明確に定義した強く詳細なプロンプトがより良い結果につながります。特定の単語の重みを調整したい場合は、`(word:weight)`の形式を使用します。ここで`word`は重みを調整したい単語、`weight`は0から1の値です。例: `The sky was a crisp (blue:0.3) and (green:0.8)`は、空が青と緑で、青よりも緑が強いことを表します。"
    },
    seed: {
      name: "seed",
      tooltip: "ノイズ生成に使用されるランダムシード。"
    },
    style_preset: {
      name: "style_preset",
      tooltip: "生成画像の任意のスタイル。"
    }
  }
};
const StabilityUpscaleConservativeNode$3 = {
  description: "画像を最小限の変更で4K解像度にアップスケールします。",
  display_name: "Stability AI アップスケール（コンサバティブ）",
  inputs: {
    control_after_generate: {
      name: "生成後のコントロール"
    },
    creativity: {
      name: "クリエイティビティ",
      tooltip: "初期画像に強く依存しない追加のディテールを生成する可能性を制御します。"
    },
    image: {
      name: "image"
    },
    negative_prompt: {
      name: "ネガティブプロンプト",
      tooltip: "出力画像に表示したくないキーワード。上級者向けの機能です。"
    },
    prompt: {
      name: "プロンプト",
      tooltip: "出力画像に何を表示したいか。要素、色、被写体を明確に定義した強く詳細なプロンプトが、より良い結果につながります。"
    },
    seed: {
      name: "シード",
      tooltip: "ノイズ生成に使用されるランダムシードです。"
    }
  }
};
const StabilityUpscaleCreativeNode$3 = {
  description: "画像を最小限の変更で4K解像度にアップスケールします。",
  display_name: "Stability AI アップスケール クリエイティブ",
  inputs: {
    control_after_generate: {
      name: "生成後のコントロール"
    },
    creativity: {
      name: "クリエイティビティ",
      tooltip: "初期画像に強く依存しない追加のディテールを生成する可能性を制御します。"
    },
    image: {
      name: "画像"
    },
    negative_prompt: {
      name: "ネガティブプロンプト",
      tooltip: "出力画像に表示したくないキーワード。上級者向けの機能です。"
    },
    prompt: {
      name: "プロンプト",
      tooltip: "出力画像に何を表示したいか。要素、色、被写体を明確に定義した強く詳細なプロンプトが、より良い結果につながります。"
    },
    seed: {
      name: "シード",
      tooltip: "ノイズ生成に使用されるランダムシード。"
    },
    style_preset: {
      name: "スタイルプリセット",
      tooltip: "生成画像の希望するスタイル（任意）。"
    }
  }
};
const StabilityUpscaleFastNode$3 = {
  description: "Stability API を使用して画像を元の4倍のサイズに素早くアップスケールします。低品質や圧縮された画像のアップスケールを目的としています。",
  display_name: "Stability AI 高速アップスケール",
  inputs: {
    image: {
      name: "画像"
    }
  }
};
const StableCascade_EmptyLatentImage$3 = {
  display_name: "安定カスケード_空の潜在画像",
  inputs: {
    batch_size: {
      name: "バッチサイズ"
    },
    compression: {
      name: "圧縮"
    },
    height: {
      name: "高さ"
    },
    width: {
      name: "幅"
    }
  },
  outputs: {
    "0": {
      name: "ステージC"
    },
    "1": {
      name: "ステージB"
    }
  }
};
const StableCascade_StageB_Conditioning$3 = {
  display_name: "安定カスケード_ステージB条件付け",
  inputs: {
    conditioning: {
      name: "コンディショニング"
    },
    stage_c: {
      name: "ステージc"
    }
  }
};
const StableCascade_StageC_VAEEncode$3 = {
  display_name: "安定カスケード_ステージC_VAEエンコード",
  inputs: {
    compression: {
      name: "圧縮"
    },
    image: {
      name: "画像"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "ステージC"
    },
    "1": {
      name: "ステージB"
    }
  }
};
const StableCascade_SuperResolutionControlnet$3 = {
  display_name: "安定カスケード_超解像Controlnet",
  inputs: {
    image: {
      name: "画像"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "コントロールネット入力"
    },
    "1": {
      name: "ステージC"
    },
    "2": {
      name: "ステージB"
    }
  }
};
const StableZero123_Conditioning$3 = {
  display_name: "安定ゼロ123条件付け",
  inputs: {
    azimuth: {
      name: "方位角"
    },
    batch_size: {
      name: "バッチサイズ"
    },
    clip_vision: {
      name: "クリップビジョン"
    },
    elevation: {
      name: "高度"
    },
    height: {
      name: "高さ"
    },
    init_image: {
      name: "初期画像"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "幅"
    }
  },
  outputs: {
    "0": {
      name: "ポジティブ"
    },
    "1": {
      name: "ネガティブ"
    },
    "2": {
      name: "潜在"
    }
  }
};
const StableZero123_Conditioning_Batched$3 = {
  display_name: "安定ゼロ123条件付け（バッチ）",
  inputs: {
    azimuth: {
      name: "方位角"
    },
    azimuth_batch_increment: {
      name: "方位角バッチ増分"
    },
    batch_size: {
      name: "バッチサイズ"
    },
    clip_vision: {
      name: "クリップビジョン"
    },
    elevation: {
      name: "高度"
    },
    elevation_batch_increment: {
      name: "高度バッチ増分"
    },
    height: {
      name: "高さ"
    },
    init_image: {
      name: "初期画像"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "幅"
    }
  },
  outputs: {
    "0": {
      name: "ポジティブ"
    },
    "1": {
      name: "ネガティブ"
    },
    "2": {
      name: "潜在"
    }
  }
};
const StyleModelApply$3 = {
  display_name: "スタイルモデルを適用",
  inputs: {
    clip_vision_output: {
      name: "クリップビジョン出力"
    },
    conditioning: {
      name: "コンディショニング"
    },
    strength: {
      name: "強度"
    },
    strength_type: {
      name: "強度タイプ"
    },
    style_model: {
      name: "スタイルモデル"
    }
  }
};
const StyleModelLoader$3 = {
  display_name: "スタイルモデルを読み込む",
  inputs: {
    style_model_name: {
      name: "スタイルモデル名"
    }
  }
};
const T5TokenizerOptions$3 = {
  display_name: "T5TokenizerOptions",
  inputs: {
    clip: {
      name: "clip"
    },
    min_length: {
      name: "最小長"
    },
    min_padding: {
      name: "最小パディング"
    }
  }
};
const TextEncodeHunyuanVideo_ImageToVideo$3 = {
  display_name: "TextEncodeHunyuanVideo_ImageToVideo",
  inputs: {
    clip: {
      name: "clip"
    },
    clip_vision_output: {
      name: "clip_vision_output"
    },
    image_interleave: {
      name: "画像インターリーブ",
      tooltip: "画像がテキストプロンプトと比べてどれだけ影響を与えるか。数値が大きいほどテキストプロンプトからの影響が大きくなります。"
    },
    prompt: {
      name: "プロンプト"
    }
  }
};
const ThresholdMask$3 = {
  display_name: "しきい値マスク",
  inputs: {
    mask: {
      name: "マスク"
    },
    value: {
      name: "値"
    }
  }
};
const TomePatchModel$3 = {
  display_name: "トメパッチモデル",
  inputs: {
    model: {
      name: "モデル"
    },
    ratio: {
      name: "比率"
    }
  }
};
const TorchCompileModel$3 = {
  display_name: "Torchコンパイルモデル",
  inputs: {
    backend: {
      name: "バックエンド"
    },
    model: {
      name: "モデル"
    }
  }
};
const TrimVideoLatent$3 = {
  display_name: "TrimVideoLatent",
  inputs: {
    samples: {
      name: "サンプル"
    },
    trim_amount: {
      name: "トリム量"
    }
  }
};
const TripleCLIPLoader$3 = {
  description: "[レシピ]\n\nsd3: clip-l, clip-g, t5",
  display_name: "トリプルCLIPを読み込む",
  inputs: {
    clip_name1: {
      name: "clip_name1"
    },
    clip_name2: {
      name: "clip_name2"
    },
    clip_name3: {
      name: "clip_name3"
    }
  }
};
const UNETLoader$3 = {
  display_name: "拡散モデルを読み込む",
  inputs: {
    unet_name: {
      name: "unet_name"
    },
    weight_dtype: {
      name: "重みdtype"
    }
  }
};
const UNetCrossAttentionMultiply$3 = {
  display_name: "UNetクロス注意の乗算",
  inputs: {
    k: {
      name: "k"
    },
    model: {
      name: "モデル"
    },
    out: {
      name: "出力"
    },
    q: {
      name: "q"
    },
    v: {
      name: "v"
    }
  }
};
const UNetSelfAttentionMultiply$3 = {
  display_name: "UNet自己注意の乗算",
  inputs: {
    k: {
      name: "k"
    },
    model: {
      name: "モデル"
    },
    out: {
      name: "出力"
    },
    q: {
      name: "q"
    },
    v: {
      name: "v"
    }
  }
};
const UNetTemporalAttentionMultiply$3 = {
  display_name: "UNet時間的注意の乗算",
  inputs: {
    cross_structural: {
      name: "クロス構造"
    },
    cross_temporal: {
      name: "クロス時間"
    },
    model: {
      name: "モデル"
    },
    self_structural: {
      name: "自己構造"
    },
    self_temporal: {
      name: "自己時間"
    }
  }
};
const UpscaleModelLoader$3 = {
  display_name: "拡大モデルを読み込む",
  inputs: {
    model_name: {
      name: "モデル名"
    }
  }
};
const VAEDecode$3 = {
  description: "潜在画像をピクセル空間画像にデコードします。",
  display_name: "VAEデコード",
  inputs: {
    samples: {
      name: "サンプル",
      tooltip: "デコードされる潜在。"
    },
    vae: {
      name: "vae",
      tooltip: "潜在のデコードに使用されるVAEモデル。"
    }
  },
  outputs: {
    "0": {
      tooltip: "デコードされた画像。"
    }
  }
};
const VAEDecodeAudio$3 = {
  display_name: "VAEデコード音声",
  inputs: {
    samples: {
      name: "サンプル"
    },
    vae: {
      name: "vae"
    }
  }
};
const VAEDecodeHunyuan3D$3 = {
  display_name: "VAEDecodeHunyuan3D",
  inputs: {
    num_chunks: {
      name: "num_chunks"
    },
    octree_resolution: {
      name: "octree_resolution"
    },
    samples: {
      name: "サンプル"
    },
    vae: {
      name: "vae"
    }
  }
};
const VAEDecodeTiled$3 = {
  display_name: "VAEデコード（タイル）",
  inputs: {
    overlap: {
      name: "オーバーラップ"
    },
    samples: {
      name: "サンプル"
    },
    temporal_overlap: {
      name: "temporal_overlap",
      tooltip: "ビデオVAE専用：重複するフレームの数。"
    },
    temporal_size: {
      name: "temporal_size",
      tooltip: "ビデオVAE専用：一度にデコードするフレームの数。"
    },
    tile_size: {
      name: "タイルサイズ"
    },
    vae: {
      name: "vae"
    }
  }
};
const VAEEncode$3 = {
  display_name: "VAEエンコード",
  inputs: {
    pixels: {
      name: "ピクセル"
    },
    vae: {
      name: "vae"
    }
  }
};
const VAEEncodeAudio$3 = {
  display_name: "VAEエンコード音声",
  inputs: {
    audio: {
      name: "オーディオ"
    },
    vae: {
      name: "vae"
    }
  }
};
const VAEEncodeForInpaint$3 = {
  display_name: "VAEエンコード（インペイント用）",
  inputs: {
    grow_mask_by: {
      name: "マスクの拡大"
    },
    mask: {
      name: "マスク"
    },
    pixels: {
      name: "ピクセル"
    },
    vae: {
      name: "vae"
    }
  }
};
const VAEEncodeTiled$3 = {
  display_name: "VAEエンコード（タイル）",
  inputs: {
    overlap: {
      name: "オーバーラップ"
    },
    pixels: {
      name: "ピクセル"
    },
    temporal_overlap: {
      name: "temporal_overlap",
      tooltip: "ビデオVAE専用：重複するフレームの数。"
    },
    temporal_size: {
      name: "temporal_size",
      tooltip: "ビデオVAE専用：一度にエンコードするフレームの数。"
    },
    tile_size: {
      name: "タイルサイズ"
    },
    vae: {
      name: "vae"
    }
  }
};
const VAELoader$3 = {
  display_name: "VAEを読み込む",
  inputs: {
    vae_name: {
      name: "vae_name"
    }
  }
};
const VAESave$3 = {
  display_name: "VAEを保存",
  inputs: {
    filename_prefix: {
      name: "ファイル名プレフィックス"
    },
    vae: {
      name: "vae"
    }
  }
};
const VPScheduler$3 = {
  display_name: "VPスケジューラー",
  inputs: {
    beta_d: {
      name: "beta_d"
    },
    beta_min: {
      name: "beta_min"
    },
    eps_s: {
      name: "eps_s"
    },
    steps: {
      name: "ステップ"
    }
  }
};
const VeoVideoGenerationNode$3 = {
  description: "Google の Veo API を使用してテキストプロンプトからビデオを生成します",
  display_name: "Google Veo2 ビデオ生成",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio",
      tooltip: "出力ビデオのアスペクト比"
    },
    control_after_generate: {
      name: "control after generate"
    },
    duration_seconds: {
      name: "duration_seconds",
      tooltip: "出力ビデオの長さ（秒）"
    },
    enhance_prompt: {
      name: "enhance_prompt",
      tooltip: "AIアシストでプロンプトを強化するかどうか"
    },
    image: {
      name: "image",
      tooltip: "ビデオ生成の参考となる画像（オプション）"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "ビデオで避けたい内容を指定するネガティブプロンプト"
    },
    person_generation: {
      name: "person_generation",
      tooltip: "ビデオ内で人物生成を許可するかどうか"
    },
    prompt: {
      name: "prompt",
      tooltip: "ビデオのテキスト説明"
    },
    seed: {
      name: "seed",
      tooltip: "ビデオ生成用のシード値（0でランダム）"
    }
  }
};
const VideoLinearCFGGuidance$3 = {
  display_name: "ビデオ線形CFGガイダンス",
  inputs: {
    min_cfg: {
      name: "最小cfg"
    },
    model: {
      name: "モデル"
    }
  }
};
const VideoTriangleCFGGuidance$3 = {
  display_name: "ビデオ三角形CFGガイダンス",
  inputs: {
    min_cfg: {
      name: "最小cfg"
    },
    model: {
      name: "モデル"
    }
  }
};
const VoxelToMesh$3 = {
  display_name: "VoxelToMesh",
  inputs: {
    algorithm: {
      name: "アルゴリズム"
    },
    threshold: {
      name: "しきい値"
    },
    voxel: {
      name: "voxel"
    }
  }
};
const VoxelToMeshBasic$3 = {
  display_name: "VoxelToMeshBasic",
  inputs: {
    threshold: {
      name: "閾値"
    },
    voxel: {
      name: "ボクセル"
    }
  }
};
const WanFirstLastFrameToVideo$3 = {
  display_name: "WanFirstLastFrameToVideo",
  inputs: {
    batch_size: {
      name: "バッチサイズ"
    },
    clip_vision_end_image: {
      name: "clipビジョン終了画像"
    },
    clip_vision_start_image: {
      name: "clipビジョン開始画像"
    },
    end_image: {
      name: "終了画像"
    },
    height: {
      name: "高さ"
    },
    length: {
      name: "長さ"
    },
    negative: {
      name: "ネガティブ"
    },
    positive: {
      name: "ポジティブ"
    },
    start_image: {
      name: "開始画像"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "幅"
    }
  },
  outputs: {
    "0": {
      name: "ポジティブ"
    },
    "1": {
      name: "ネガティブ"
    },
    "2": {
      name: "latent"
    }
  }
};
const WanFunControlToVideo$3 = {
  display_name: "WanFunControlToVideo",
  inputs: {
    batch_size: {
      name: "バッチサイズ"
    },
    clip_vision_output: {
      name: "clip_vision_output"
    },
    control_video: {
      name: "コントロールビデオ"
    },
    height: {
      name: "高さ"
    },
    length: {
      name: "長さ"
    },
    negative: {
      name: "ネガティブ"
    },
    positive: {
      name: "ポジティブ"
    },
    start_image: {
      name: "開始画像"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "幅"
    }
  },
  outputs: {
    "0": {
      name: "ポジティブ"
    },
    "1": {
      name: "ネガティブ"
    },
    "2": {
      name: "latent"
    }
  }
};
const WanFunInpaintToVideo$3 = {
  display_name: "WanFunInpaintToVideo",
  inputs: {
    batch_size: {
      name: "バッチサイズ"
    },
    clip_vision_output: {
      name: "clip_vision_output"
    },
    end_image: {
      name: "終了画像"
    },
    height: {
      name: "高さ"
    },
    length: {
      name: "長さ"
    },
    negative: {
      name: "ネガティブ"
    },
    positive: {
      name: "ポジティブ"
    },
    start_image: {
      name: "開始画像"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "幅"
    }
  },
  outputs: {
    "0": {
      name: "ポジティブ"
    },
    "1": {
      name: "ネガティブ"
    },
    "2": {
      name: "latent"
    }
  }
};
const WanImageToVideo$3 = {
  display_name: "Wan画像からビデオへ",
  inputs: {
    batch_size: {
      name: "バッチサイズ"
    },
    clip_vision_output: {
      name: "clipビジョン出力"
    },
    height: {
      name: "高さ"
    },
    length: {
      name: "長さ"
    },
    negative: {
      name: "ネガティブ"
    },
    positive: {
      name: "ポジティブ"
    },
    start_image: {
      name: "開始画像"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "幅"
    }
  },
  outputs: {
    "0": {
      name: "ポジティブ"
    },
    "1": {
      name: "ネガティブ"
    },
    "2": {
      name: "潜在"
    }
  }
};
const WanVaceToVideo$3 = {
  display_name: "WanVaceToVideo",
  inputs: {
    batch_size: {
      name: "バッチサイズ"
    },
    control_masks: {
      name: "コントロールマスク"
    },
    control_video: {
      name: "コントロールビデオ"
    },
    height: {
      name: "高さ"
    },
    length: {
      name: "長さ"
    },
    negative: {
      name: "ネガティブ"
    },
    positive: {
      name: "ポジティブ"
    },
    reference_image: {
      name: "参照画像"
    },
    strength: {
      name: "強度"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "幅"
    }
  },
  outputs: {
    "0": {
      name: "ポジティブ"
    },
    "1": {
      name: "ネガティブ"
    },
    "2": {
      name: "latent"
    },
    "3": {
      name: "トリムlatent"
    }
  }
};
const WebcamCapture$3 = {
  display_name: "ウェブカメラキャプチャ",
  inputs: {
    capture_on_queue: {
      name: "キューでキャプチャ"
    },
    height: {
      name: "高さ"
    },
    image: {
      name: "画像"
    },
    "waiting for camera___": {},
    width: {
      name: "幅"
    }
  }
};
const unCLIPCheckpointLoader$3 = {
  display_name: "unCLIPチェックポイントローダー",
  inputs: {
    ckpt_name: {
      name: "ckpt_name"
    }
  }
};
const unCLIPConditioning$3 = {
  display_name: "unCLIP条件付け",
  inputs: {
    clip_vision_output: {
      name: "clip_vision_output"
    },
    conditioning: {
      name: "コンディショニング"
    },
    noise_augmentation: {
      name: "ノイズ増強"
    },
    strength: {
      name: "強度"
    }
  }
};
const jaNodes = {
  AddNoise: AddNoise$3,
  AlignYourStepsScheduler: AlignYourStepsScheduler$3,
  BasicGuider: BasicGuider$3,
  BasicScheduler: BasicScheduler$3,
  BetaSamplingScheduler: BetaSamplingScheduler$3,
  CFGGuider: CFGGuider$3,
  CFGZeroStar: CFGZeroStar$3,
  CLIPAttentionMultiply: CLIPAttentionMultiply$3,
  CLIPLoader: CLIPLoader$3,
  CLIPMergeAdd: CLIPMergeAdd$3,
  CLIPMergeSimple: CLIPMergeSimple$3,
  CLIPMergeSubtract: CLIPMergeSubtract$3,
  CLIPSave: CLIPSave$3,
  CLIPSetLastLayer: CLIPSetLastLayer$3,
  CLIPTextEncode: CLIPTextEncode$3,
  CLIPTextEncodeControlnet: CLIPTextEncodeControlnet$3,
  CLIPTextEncodeFlux: CLIPTextEncodeFlux$3,
  CLIPTextEncodeHiDream: CLIPTextEncodeHiDream$3,
  CLIPTextEncodeHunyuanDiT: CLIPTextEncodeHunyuanDiT$3,
  CLIPTextEncodeLumina2: CLIPTextEncodeLumina2$3,
  CLIPTextEncodePixArtAlpha: CLIPTextEncodePixArtAlpha$3,
  CLIPTextEncodeSD3: CLIPTextEncodeSD3$3,
  CLIPTextEncodeSDXL: CLIPTextEncodeSDXL$3,
  CLIPTextEncodeSDXLRefiner: CLIPTextEncodeSDXLRefiner$3,
  CLIPVisionEncode: CLIPVisionEncode$3,
  CLIPVisionLoader: CLIPVisionLoader$3,
  Canny: Canny$3,
  CheckpointLoader: CheckpointLoader$3,
  CheckpointLoaderSimple: CheckpointLoaderSimple$3,
  CheckpointSave: CheckpointSave$3,
  CombineHooks2: CombineHooks2$3,
  CombineHooks4: CombineHooks4$3,
  CombineHooks8: CombineHooks8$3,
  ConditioningAverage: ConditioningAverage$3,
  ConditioningCombine: ConditioningCombine$3,
  ConditioningConcat: ConditioningConcat$3,
  ConditioningSetArea: ConditioningSetArea$3,
  ConditioningSetAreaPercentage: ConditioningSetAreaPercentage$3,
  ConditioningSetAreaPercentageVideo: ConditioningSetAreaPercentageVideo$3,
  ConditioningSetAreaStrength: ConditioningSetAreaStrength$3,
  ConditioningSetDefaultCombine: ConditioningSetDefaultCombine$3,
  ConditioningSetMask: ConditioningSetMask$3,
  ConditioningSetProperties: ConditioningSetProperties$3,
  ConditioningSetPropertiesAndCombine: ConditioningSetPropertiesAndCombine$3,
  ConditioningSetTimestepRange: ConditioningSetTimestepRange$3,
  ConditioningStableAudio: ConditioningStableAudio$3,
  ConditioningTimestepsRange: ConditioningTimestepsRange$3,
  ConditioningZeroOut: ConditioningZeroOut$3,
  ControlNetApply: ControlNetApply$3,
  ControlNetApplyAdvanced: ControlNetApplyAdvanced$3,
  ControlNetApplySD3: ControlNetApplySD3$3,
  ControlNetInpaintingAliMamaApply: ControlNetInpaintingAliMamaApply$3,
  ControlNetLoader: ControlNetLoader$3,
  CosmosImageToVideoLatent: CosmosImageToVideoLatent$3,
  CreateHookKeyframe: CreateHookKeyframe$3,
  CreateHookKeyframesFromFloats: CreateHookKeyframesFromFloats$3,
  CreateHookKeyframesInterpolated: CreateHookKeyframesInterpolated$3,
  CreateHookLora: CreateHookLora$3,
  CreateHookLoraModelOnly: CreateHookLoraModelOnly$3,
  CreateHookModelAsLora: CreateHookModelAsLora$3,
  CreateHookModelAsLoraModelOnly: CreateHookModelAsLoraModelOnly$3,
  CreateVideo: CreateVideo$3,
  CropMask: CropMask$3,
  DiffControlNetLoader: DiffControlNetLoader$3,
  DifferentialDiffusion: DifferentialDiffusion$3,
  DiffusersLoader: DiffusersLoader$3,
  DisableNoise: DisableNoise$3,
  DualCFGGuider: DualCFGGuider$3,
  DualCLIPLoader: DualCLIPLoader$3,
  EmptyCosmosLatentVideo: EmptyCosmosLatentVideo$3,
  EmptyHunyuanLatentVideo: EmptyHunyuanLatentVideo$3,
  EmptyImage: EmptyImage$3,
  EmptyLTXVLatentVideo: EmptyLTXVLatentVideo$3,
  EmptyLatentAudio: EmptyLatentAudio$3,
  EmptyLatentHunyuan3Dv2: EmptyLatentHunyuan3Dv2$3,
  EmptyLatentImage: EmptyLatentImage$3,
  EmptyMochiLatentVideo: EmptyMochiLatentVideo$3,
  EmptySD3LatentImage: EmptySD3LatentImage$3,
  ExponentialScheduler: ExponentialScheduler$3,
  ExtendIntermediateSigmas: ExtendIntermediateSigmas$3,
  FeatherMask: FeatherMask$3,
  FlipSigmas: FlipSigmas$3,
  FluxDisableGuidance: FluxDisableGuidance$3,
  FluxGuidance: FluxGuidance$3,
  FluxProCannyNode: FluxProCannyNode$3,
  FluxProDepthNode: FluxProDepthNode$3,
  FluxProExpandNode: FluxProExpandNode$3,
  FluxProFillNode: FluxProFillNode$3,
  FluxProUltraImageNode: FluxProUltraImageNode$3,
  FreSca: FreSca$3,
  FreeU: FreeU$3,
  FreeU_V2: FreeU_V2$3,
  GITSScheduler: GITSScheduler$3,
  GLIGENLoader: GLIGENLoader$3,
  GLIGENTextBoxApply: GLIGENTextBoxApply$3,
  GetVideoComponents: GetVideoComponents$3,
  GrowMask: GrowMask$3,
  Hunyuan3Dv2Conditioning: Hunyuan3Dv2Conditioning$3,
  Hunyuan3Dv2ConditioningMultiView: Hunyuan3Dv2ConditioningMultiView$3,
  HunyuanImageToVideo: HunyuanImageToVideo$3,
  HyperTile: HyperTile$3,
  HypernetworkLoader: HypernetworkLoader$3,
  IdeogramV1: IdeogramV1$3,
  IdeogramV2: IdeogramV2$3,
  IdeogramV3: IdeogramV3$3,
  ImageBatch: ImageBatch$3,
  ImageBlend: ImageBlend$3,
  ImageBlur: ImageBlur$3,
  ImageColorToMask: ImageColorToMask$3,
  ImageCompositeMasked: ImageCompositeMasked$3,
  ImageCrop: ImageCrop$3,
  ImageFromBatch: ImageFromBatch$3,
  ImageInvert: ImageInvert$3,
  ImageOnlyCheckpointLoader: ImageOnlyCheckpointLoader$3,
  ImageOnlyCheckpointSave: ImageOnlyCheckpointSave$3,
  ImagePadForOutpaint: ImagePadForOutpaint$3,
  ImageQuantize: ImageQuantize$3,
  ImageRGBToYUV: ImageRGBToYUV$3,
  ImageScale: ImageScale$3,
  ImageScaleBy: ImageScaleBy$3,
  ImageScaleToTotalPixels: ImageScaleToTotalPixels$3,
  ImageSharpen: ImageSharpen$3,
  ImageToMask: ImageToMask$3,
  ImageUpscaleWithModel: ImageUpscaleWithModel$3,
  ImageYUVToRGB: ImageYUVToRGB$3,
  InpaintModelConditioning: InpaintModelConditioning$3,
  InstructPixToPixConditioning: InstructPixToPixConditioning$3,
  InvertMask: InvertMask$3,
  JoinImageWithAlpha: JoinImageWithAlpha$3,
  KSampler: KSampler$3,
  KSamplerAdvanced: KSamplerAdvanced$3,
  KSamplerSelect: KSamplerSelect$3,
  KarrasScheduler: KarrasScheduler$3,
  KlingCameraControlI2VNode: KlingCameraControlI2VNode$3,
  KlingCameraControlT2VNode: KlingCameraControlT2VNode$3,
  KlingCameraControls: KlingCameraControls$3,
  KlingDualCharacterVideoEffectNode: KlingDualCharacterVideoEffectNode$3,
  KlingImage2VideoNode: KlingImage2VideoNode$3,
  KlingImageGenerationNode: KlingImageGenerationNode$3,
  KlingLipSyncAudioToVideoNode: KlingLipSyncAudioToVideoNode$3,
  KlingLipSyncTextToVideoNode: KlingLipSyncTextToVideoNode$3,
  KlingSingleImageVideoEffectNode: KlingSingleImageVideoEffectNode$3,
  KlingStartEndFrameNode: KlingStartEndFrameNode$3,
  KlingTextToVideoNode: KlingTextToVideoNode$3,
  KlingVideoExtendNode: KlingVideoExtendNode$3,
  KlingVirtualTryOnNode: KlingVirtualTryOnNode$3,
  LTXVAddGuide: LTXVAddGuide$3,
  LTXVConditioning: LTXVConditioning$3,
  LTXVCropGuides: LTXVCropGuides$3,
  LTXVImgToVideo: LTXVImgToVideo$3,
  LTXVPreprocess: LTXVPreprocess$3,
  LTXVScheduler: LTXVScheduler$3,
  LaplaceScheduler: LaplaceScheduler$3,
  LatentAdd: LatentAdd$3,
  LatentApplyOperation: LatentApplyOperation$3,
  LatentApplyOperationCFG: LatentApplyOperationCFG$3,
  LatentBatch: LatentBatch$3,
  LatentBatchSeedBehavior: LatentBatchSeedBehavior$3,
  LatentBlend: LatentBlend$3,
  LatentComposite: LatentComposite$3,
  LatentCompositeMasked: LatentCompositeMasked$3,
  LatentCrop: LatentCrop$3,
  LatentFlip: LatentFlip$3,
  LatentFromBatch: LatentFromBatch$3,
  LatentInterpolate: LatentInterpolate$3,
  LatentMultiply: LatentMultiply$3,
  LatentOperationSharpen: LatentOperationSharpen$3,
  LatentOperationTonemapReinhard: LatentOperationTonemapReinhard$3,
  LatentRotate: LatentRotate$3,
  LatentSubtract: LatentSubtract$3,
  LatentUpscale: LatentUpscale$3,
  LatentUpscaleBy: LatentUpscaleBy$3,
  Load3D: Load3D$3,
  Load3DAnimation: Load3DAnimation$3,
  LoadAudio: LoadAudio$3,
  LoadImage: LoadImage$3,
  LoadImageMask: LoadImageMask$3,
  LoadImageOutput: LoadImageOutput$3,
  LoadLatent: LoadLatent$3,
  LoadVideo: LoadVideo$3,
  LoraLoader: LoraLoader$3,
  LoraLoaderModelOnly: LoraLoaderModelOnly$3,
  LoraSave: LoraSave$3,
  LotusConditioning: LotusConditioning$3,
  LumaConceptsNode: LumaConceptsNode$3,
  LumaImageModifyNode: LumaImageModifyNode$3,
  LumaImageNode: LumaImageNode$3,
  LumaImageToVideoNode: LumaImageToVideoNode$3,
  LumaReferenceNode: LumaReferenceNode$3,
  LumaVideoNode: LumaVideoNode$3,
  Mahiro: Mahiro$3,
  MaskComposite: MaskComposite$3,
  MaskPreview: MaskPreview$3,
  MaskToImage: MaskToImage$3,
  MinimaxImageToVideoNode: MinimaxImageToVideoNode$3,
  MinimaxTextToVideoNode: MinimaxTextToVideoNode$3,
  ModelComputeDtype: ModelComputeDtype$3,
  ModelMergeAdd: ModelMergeAdd$3,
  ModelMergeAuraflow: ModelMergeAuraflow$3,
  ModelMergeBlocks: ModelMergeBlocks$3,
  ModelMergeCosmos14B: ModelMergeCosmos14B$3,
  ModelMergeCosmos7B: ModelMergeCosmos7B$3,
  ModelMergeFlux1: ModelMergeFlux1$3,
  ModelMergeLTXV: ModelMergeLTXV$3,
  ModelMergeMochiPreview: ModelMergeMochiPreview$3,
  ModelMergeSD1: ModelMergeSD1$3,
  ModelMergeSD2: ModelMergeSD2$3,
  ModelMergeSD35_Large: ModelMergeSD35_Large$3,
  ModelMergeSD3_2B: ModelMergeSD3_2B$3,
  ModelMergeSDXL: ModelMergeSDXL$3,
  ModelMergeSimple: ModelMergeSimple$3,
  ModelMergeSubtract: ModelMergeSubtract$3,
  ModelMergeWAN2_1: ModelMergeWAN2_1$3,
  ModelSamplingAuraFlow: ModelSamplingAuraFlow$3,
  ModelSamplingContinuousEDM: ModelSamplingContinuousEDM$3,
  ModelSamplingContinuousV: ModelSamplingContinuousV$3,
  ModelSamplingDiscrete: ModelSamplingDiscrete$3,
  ModelSamplingFlux: ModelSamplingFlux$3,
  ModelSamplingLTXV: ModelSamplingLTXV$3,
  ModelSamplingSD3: ModelSamplingSD3$3,
  ModelSamplingStableCascade: ModelSamplingStableCascade$3,
  ModelSave: ModelSave$3,
  Morphology: Morphology$3,
  OpenAIDalle2: OpenAIDalle2$3,
  OpenAIDalle3: OpenAIDalle3$3,
  OpenAIGPTImage1: OpenAIGPTImage1$3,
  OptimalStepsScheduler: OptimalStepsScheduler$3,
  PairConditioningCombine: PairConditioningCombine$3,
  PairConditioningSetDefaultCombine: PairConditioningSetDefaultCombine$3,
  PairConditioningSetProperties: PairConditioningSetProperties$3,
  PairConditioningSetPropertiesAndCombine: PairConditioningSetPropertiesAndCombine$3,
  PatchModelAddDownscale: PatchModelAddDownscale$3,
  PerpNeg: PerpNeg$3,
  PerpNegGuider: PerpNegGuider$3,
  PerturbedAttentionGuidance: PerturbedAttentionGuidance$3,
  PhotoMakerEncode: PhotoMakerEncode$3,
  PhotoMakerLoader: PhotoMakerLoader$3,
  PikaImageToVideoNode2_2: PikaImageToVideoNode2_2$3,
  PikaScenesV2_2: PikaScenesV2_2$3,
  PikaStartEndFrameNode2_2: PikaStartEndFrameNode2_2$3,
  PikaTextToVideoNode2_2: PikaTextToVideoNode2_2$3,
  Pikadditions: Pikadditions$3,
  Pikaffects: Pikaffects$3,
  Pikaswaps: Pikaswaps$3,
  PixverseImageToVideoNode: PixverseImageToVideoNode$3,
  PixverseTemplateNode: PixverseTemplateNode$3,
  PixverseTextToVideoNode: PixverseTextToVideoNode$3,
  PixverseTransitionVideoNode: PixverseTransitionVideoNode$3,
  PolyexponentialScheduler: PolyexponentialScheduler$3,
  PorterDuffImageComposite: PorterDuffImageComposite$3,
  Preview3D: Preview3D$3,
  Preview3DAnimation: Preview3DAnimation$3,
  PreviewAny: PreviewAny$3,
  PreviewAudio: PreviewAudio$3,
  PreviewImage: PreviewImage$3,
  PrimitiveBoolean: PrimitiveBoolean$3,
  PrimitiveFloat: PrimitiveFloat$3,
  PrimitiveInt: PrimitiveInt$3,
  PrimitiveString: PrimitiveString$3,
  PrimitiveStringMultiline: PrimitiveStringMultiline$3,
  QuadrupleCLIPLoader: QuadrupleCLIPLoader$3,
  RandomNoise: RandomNoise$3,
  RebatchImages: RebatchImages$3,
  RebatchLatents: RebatchLatents$3,
  RecraftColorRGB: RecraftColorRGB$3,
  RecraftControls: RecraftControls$3,
  RecraftCreativeUpscaleNode: RecraftCreativeUpscaleNode$3,
  RecraftCrispUpscaleNode: RecraftCrispUpscaleNode$3,
  RecraftImageInpaintingNode: RecraftImageInpaintingNode$3,
  RecraftImageToImageNode: RecraftImageToImageNode$3,
  RecraftRemoveBackgroundNode: RecraftRemoveBackgroundNode$3,
  RecraftReplaceBackgroundNode: RecraftReplaceBackgroundNode$3,
  RecraftStyleV3DigitalIllustration: RecraftStyleV3DigitalIllustration$3,
  RecraftStyleV3InfiniteStyleLibrary: RecraftStyleV3InfiniteStyleLibrary$3,
  RecraftStyleV3LogoRaster: RecraftStyleV3LogoRaster$3,
  RecraftStyleV3RealisticImage: RecraftStyleV3RealisticImage$3,
  RecraftTextToImageNode: RecraftTextToImageNode$3,
  RecraftTextToVectorNode: RecraftTextToVectorNode$3,
  RecraftVectorizeImageNode: RecraftVectorizeImageNode$3,
  RenormCFG: RenormCFG$3,
  RepeatImageBatch: RepeatImageBatch$3,
  RepeatLatentBatch: RepeatLatentBatch$3,
  RescaleCFG: RescaleCFG$3,
  SDTurboScheduler: SDTurboScheduler$3,
  SD_4XUpscale_Conditioning: SD_4XUpscale_Conditioning$3,
  SV3D_Conditioning: SV3D_Conditioning$3,
  SVD_img2vid_Conditioning: SVD_img2vid_Conditioning$3,
  SamplerCustom: SamplerCustom$3,
  SamplerCustomAdvanced: SamplerCustomAdvanced$3,
  SamplerDPMAdaptative: SamplerDPMAdaptative$3,
  SamplerDPMPP_2M_SDE: SamplerDPMPP_2M_SDE$3,
  SamplerDPMPP_2S_Ancestral: SamplerDPMPP_2S_Ancestral$3,
  SamplerDPMPP_3M_SDE: SamplerDPMPP_3M_SDE$3,
  SamplerDPMPP_SDE: SamplerDPMPP_SDE$3,
  SamplerEulerAncestral: SamplerEulerAncestral$3,
  SamplerEulerAncestralCFGPP: SamplerEulerAncestralCFGPP$3,
  SamplerEulerCFGpp: SamplerEulerCFGpp$3,
  SamplerLCMUpscale: SamplerLCMUpscale$3,
  SamplerLMS: SamplerLMS$3,
  SaveAnimatedPNG: SaveAnimatedPNG$3,
  SaveAnimatedWEBP: SaveAnimatedWEBP$3,
  SaveAudio: SaveAudio$3,
  SaveGLB: SaveGLB$3,
  SaveImage: SaveImage$3,
  SaveImageWebsocket: SaveImageWebsocket$3,
  SaveLatent: SaveLatent$3,
  SaveSVG: SaveSVG$3,
  SaveVideo: SaveVideo$3,
  SaveWEBM: SaveWEBM$3,
  SelfAttentionGuidance: SelfAttentionGuidance$3,
  SetClipHooks: SetClipHooks$3,
  SetFirstSigma: SetFirstSigma$3,
  SetHookKeyframes: SetHookKeyframes$3,
  SetLatentNoiseMask: SetLatentNoiseMask$3,
  SetUnionControlNetType: SetUnionControlNetType$3,
  SkipLayerGuidanceDiT: SkipLayerGuidanceDiT$3,
  SkipLayerGuidanceSD3: SkipLayerGuidanceSD3$3,
  SolidMask: SolidMask$3,
  SplitImageWithAlpha: SplitImageWithAlpha$3,
  SplitSigmas: SplitSigmas$3,
  SplitSigmasDenoise: SplitSigmasDenoise$3,
  StabilityStableImageSD_3_5Node: StabilityStableImageSD_3_5Node$3,
  StabilityStableImageUltraNode: StabilityStableImageUltraNode$3,
  StabilityUpscaleConservativeNode: StabilityUpscaleConservativeNode$3,
  StabilityUpscaleCreativeNode: StabilityUpscaleCreativeNode$3,
  StabilityUpscaleFastNode: StabilityUpscaleFastNode$3,
  StableCascade_EmptyLatentImage: StableCascade_EmptyLatentImage$3,
  StableCascade_StageB_Conditioning: StableCascade_StageB_Conditioning$3,
  StableCascade_StageC_VAEEncode: StableCascade_StageC_VAEEncode$3,
  StableCascade_SuperResolutionControlnet: StableCascade_SuperResolutionControlnet$3,
  StableZero123_Conditioning: StableZero123_Conditioning$3,
  StableZero123_Conditioning_Batched: StableZero123_Conditioning_Batched$3,
  StyleModelApply: StyleModelApply$3,
  StyleModelLoader: StyleModelLoader$3,
  T5TokenizerOptions: T5TokenizerOptions$3,
  TextEncodeHunyuanVideo_ImageToVideo: TextEncodeHunyuanVideo_ImageToVideo$3,
  ThresholdMask: ThresholdMask$3,
  TomePatchModel: TomePatchModel$3,
  TorchCompileModel: TorchCompileModel$3,
  TrimVideoLatent: TrimVideoLatent$3,
  TripleCLIPLoader: TripleCLIPLoader$3,
  UNETLoader: UNETLoader$3,
  UNetCrossAttentionMultiply: UNetCrossAttentionMultiply$3,
  UNetSelfAttentionMultiply: UNetSelfAttentionMultiply$3,
  UNetTemporalAttentionMultiply: UNetTemporalAttentionMultiply$3,
  UpscaleModelLoader: UpscaleModelLoader$3,
  VAEDecode: VAEDecode$3,
  VAEDecodeAudio: VAEDecodeAudio$3,
  VAEDecodeHunyuan3D: VAEDecodeHunyuan3D$3,
  VAEDecodeTiled: VAEDecodeTiled$3,
  VAEEncode: VAEEncode$3,
  VAEEncodeAudio: VAEEncodeAudio$3,
  VAEEncodeForInpaint: VAEEncodeForInpaint$3,
  VAEEncodeTiled: VAEEncodeTiled$3,
  VAELoader: VAELoader$3,
  VAESave: VAESave$3,
  VPScheduler: VPScheduler$3,
  VeoVideoGenerationNode: VeoVideoGenerationNode$3,
  VideoLinearCFGGuidance: VideoLinearCFGGuidance$3,
  VideoTriangleCFGGuidance: VideoTriangleCFGGuidance$3,
  VoxelToMesh: VoxelToMesh$3,
  VoxelToMeshBasic: VoxelToMeshBasic$3,
  WanFirstLastFrameToVideo: WanFirstLastFrameToVideo$3,
  WanFunControlToVideo: WanFunControlToVideo$3,
  WanFunInpaintToVideo: WanFunInpaintToVideo$3,
  WanImageToVideo: WanImageToVideo$3,
  WanVaceToVideo: WanVaceToVideo$3,
  WebcamCapture: WebcamCapture$3,
  unCLIPCheckpointLoader: unCLIPCheckpointLoader$3,
  unCLIPConditioning: unCLIPConditioning$3
};
const Comfy_Canvas_SelectionToolbox$3 = {
  name: "選択ツールボックスを表示"
};
const Comfy_ConfirmClear$3 = {
  name: "ワークフローをクリアする際に確認を要求する"
};
const Comfy_DOMClippingEnabled$3 = {
  name: "DOM要素のクリッピングを有効にする（有効にするとパフォーマンスが低下する可能性があります）"
};
const Comfy_DevMode$3 = {
  name: "開発モードオプションを有効にする（API保存など）"
};
const Comfy_DisableFloatRounding$3 = {
  name: "デフォルトの浮動小数点ウィジェットの丸めを無効にする。",
  tooltip: "(ページの再読み込みが必要) バックエンドのノードで丸めが設定されている場合、丸めを無効にすることはできません。"
};
const Comfy_DisableSliders$3 = {
  name: "ノードウィジェットスライダーを無効にする"
};
const Comfy_EditAttention_Delta$3 = {
  name: "Ctrl+上/下の精度"
};
const Comfy_EnableTooltips$3 = {
  name: "ツールチップを有効にする"
};
const Comfy_EnableWorkflowViewRestore$3 = {
  name: "ワークフロー内のキャンバスの位置とズームレベルを保存および復元する"
};
const Comfy_FloatRoundingPrecision$3 = {
  name: "浮動小数点ウィジェットの丸め小数点数 [0 = 自動]。",
  tooltip: "(ページの再読み込みが必要)"
};
const Comfy_Graph_CanvasInfo$3 = {
  name: "左下隅にキャンバス情報を表示する（fpsなど）"
};
const Comfy_Graph_CanvasMenu$3 = {
  name: "グラフキャンバスメニューを表示する"
};
const Comfy_Graph_CtrlShiftZoom$3 = {
  name: "ファストズームショートカットを有効にする（Ctrl + Shift + ドラッグ）"
};
const Comfy_Graph_LinkMarkers$3 = {
  name: "リンク中点マーカー",
  options: {
    Arrow: "矢印",
    Circle: "円",
    None: "なし"
  }
};
const Comfy_Graph_ZoomSpeed$3 = {
  name: "キャンバスズーム速度"
};
const Comfy_GroupSelectedNodes_Padding$3 = {
  name: "選択したノードのパディング"
};
const Comfy_Group_DoubleClickTitleToEdit$3 = {
  name: "グループタイトルをダブルクリックして編集"
};
const Comfy_LinkRelease_Action$3 = {
  name: "リンクリリース時のアクション（修飾子なし）",
  options: {
    "context menu": "コンテキストメニュー",
    "no action": "アクションなし",
    "search box": "検索ボックス"
  }
};
const Comfy_LinkRelease_ActionShift$3 = {
  name: "リンクリリース時のアクション（Shift）",
  options: {
    "context menu": "コンテキストメニュー",
    "no action": "アクションなし",
    "search box": "検索ボックス"
  }
};
const Comfy_LinkRenderMode$3 = {
  name: "リンクレンダーモード",
  options: {
    Hidden: "隠す",
    Linear: "リニア",
    Spline: "スプライン",
    Straight: "ストレート"
  }
};
const Comfy_Load3D_BackgroundColor$3 = {
  name: "初期背景色",
  tooltip: "3Dシーンのデフォルト背景色を設定します。この設定は新しい3Dウィジェット作成時の背景の見た目を決定しますが、作成後に各ウィジェットごとに個別に調整できます。"
};
const Comfy_Load3D_CameraType$3 = {
  name: "カメラタイプ",
  options: {
    orthographic: "オルソグラフィック",
    perspective: "パースペクティブ"
  },
  tooltip: "新しい3Dウィジェットが作成されたときに、デフォルトでカメラが透視投影か平行投影かを制御します。このデフォルトは、作成後に各ウィジェットごとに個別に切り替えることができます。"
};
const Comfy_Load3D_LightAdjustmentIncrement$3 = {
  name: "ライト調整増分",
  tooltip: "3Dシーンでライトの強度を調整する際の増分サイズを制御します。ステップ値が小さいほど、照明調整をより細かく制御でき、大きい値では1回の調整ごとにより顕著な変化が得られます。"
};
const Comfy_Load3D_LightIntensity$3 = {
  name: "初期ライト強度",
  tooltip: "3Dシーン内の照明のデフォルトの明るさレベルを設定します。この値は新しい3Dウィジェット作成時にライトがオブジェクトをどれだけ強く照らすかを決定しますが、作成後に各ウィジェットごとに個別に調整できます。"
};
const Comfy_Load3D_LightIntensityMaximum$3 = {
  name: "最大光度",
  tooltip: "3Dシーンで許可される最大光度値を設定します。これは、3Dウィジェットで照明を調整する際に設定できる明るさの上限を定義します。"
};
const Comfy_Load3D_LightIntensityMinimum$3 = {
  name: "光の強度の最小値",
  tooltip: "3Dシーンで許可される光の強度の最小値を設定します。これは、3Dウィジェットで照明を調整する際に設定できる明るさの下限を定義します。"
};
const Comfy_Load3D_ShowGrid$3 = {
  name: "グリッドを表示",
  tooltip: "デフォルトでグリッドを表示するには切り替えます"
};
const Comfy_Load3D_ShowPreview$3 = {
  name: "プレビューを表示",
  tooltip: "デフォルトでプレビューを表示するには切り替えます"
};
const Comfy_Locale$3 = {
  name: "言語"
};
const Comfy_MaskEditor_BrushAdjustmentSpeed$3 = {
  name: "ブラシ調整速度の倍率",
  tooltip: "調整時にブラシのサイズと硬さがどれだけ速く変化するかを制御します。値が高いほど、変化が速くなります。"
};
const Comfy_MaskEditor_UseDominantAxis$3 = {
  name: "ブラシ調整を優先軸に固定する",
  tooltip: "有効にすると、ブラシの調整は、どの方向に多く動かすかに基づいて、サイズまたは硬さのいずれかにのみ影響します。"
};
const Comfy_MaskEditor_UseNewEditor$3 = {
  name: "新しいマスクエディタを使用する",
  tooltip: "新しいマスクエディタインターフェースに切り替えます。"
};
const Comfy_ModelLibrary_AutoLoadAll$3 = {
  name: "すべてのモデルフォルダーを自動的に読み込む",
  tooltip: "trueの場合、モデルライブラリを開くとすぐにすべてのフォルダーが読み込まれます（これにより読み込み中に遅延が発生する可能性があります）。falseの場合、ルートレベルのモデルフォルダーはクリックするまで読み込まれません。"
};
const Comfy_ModelLibrary_NameFormat$3 = {
  name: "モデルライブラリツリービューに表示する名前",
  options: {
    filename: "ファイル名",
    title: "タイトル"
  },
  tooltip: '"ファイル名"を選択すると、モデルリストにディレクトリや".safetensors"拡張子なしの生のファイル名の簡略化されたビューが表示されます。"タイトル"を選択すると、設定可能なモデルメタデータタイトルが表示されます。'
};
const Comfy_NodeBadge_NodeIdBadgeMode$3 = {
  name: "ノードIDバッジモード",
  options: {
    None: "なし",
    "Show all": "すべて表示"
  }
};
const Comfy_NodeBadge_NodeLifeCycleBadgeMode$3 = {
  name: "ノードライフサイクルバッジモード",
  options: {
    None: "なし",
    "Show all": "すべて表示"
  }
};
const Comfy_NodeBadge_NodeSourceBadgeMode$3 = {
  name: "ノードソースバッジモード",
  options: {
    "Hide built-in": "組み込みを隠す",
    None: "なし",
    "Show all": "すべて表示"
  }
};
const Comfy_NodeSearchBoxImpl$3 = {
  name: "ノード検索ボックスの実装",
  options: {
    "default": "デフォルト",
    "litegraph (legacy)": "litegraph (レガシー)"
  }
};
const Comfy_NodeSearchBoxImpl_NodePreview$3 = {
  name: "ノードプレビュー",
  tooltip: "デフォルトの実装にのみ適用されます"
};
const Comfy_NodeSearchBoxImpl_ShowCategory$3 = {
  name: "検索結果にノードカテゴリを表示",
  tooltip: "デフォルトの実装にのみ適用されます"
};
const Comfy_NodeSearchBoxImpl_ShowIdName$3 = {
  name: "検索結果にノードID名を表示",
  tooltip: "デフォルトの実装にのみ適用されます"
};
const Comfy_NodeSearchBoxImpl_ShowNodeFrequency$3 = {
  name: "検索結果にノード頻度を表示",
  tooltip: "デフォルトの実装にのみ適用されます"
};
const Comfy_NodeSuggestions_number$3 = {
  name: "ノード提案の数",
  tooltip: "ライトグラフの検索ボックス/コンテキストメニュー専用"
};
const Comfy_Node_AllowImageSizeDraw$3 = {
  name: "画像プレビューの下に幅×高さを表示する"
};
const Comfy_Node_AutoSnapLinkToSlot$3 = {
  name: "ノードスロットにリンクを自動スナップ",
  tooltip: "ノードの上にリンクをドラッグすると、リンクがノードの有効な入力スロットに自動的にスナップします"
};
const Comfy_Node_BypassAllLinksOnDelete$3 = {
  name: "ノード削除時にすべてのリンクを保持",
  tooltip: "ノードを削除する際、削除されたノードをバイパスしてすべての入力および出力リンクを再接続しようとします"
};
const Comfy_Node_DoubleClickTitleToEdit$3 = {
  name: "ノードタイトルをダブルクリックして編集"
};
const Comfy_Node_MiddleClickRerouteNode$3 = {
  name: "ミドルクリックで新しいリルートノードを作成"
};
const Comfy_Node_Opacity$3 = {
  name: "ノードの不透明度"
};
const Comfy_Node_ShowDeprecated$3 = {
  name: "検索で非推奨ノードを表示",
  tooltip: "非推奨ノードはデフォルトでUIに隠されていますが、それを使用する既存のワークフローでは機能し続けます。"
};
const Comfy_Node_ShowExperimental$3 = {
  name: "検索で実験的ノードを表示",
  tooltip: "実験的ノードはUIでそのようにマークされており、将来のバージョンで大幅な変更や削除の対象となる可能性があります。生産ワークフローでの使用には注意が必要です"
};
const Comfy_Node_SnapHighlightsNode$3 = {
  name: "スナップハイライトノード",
  tooltip: "有効な入力スロットを持つノードの上にリンクをドラッグすると、ノードがハイライトされます"
};
const Comfy_Pointer_ClickBufferTime$3 = {
  name: "ポインタークリックドリフト遅延",
  tooltip: "ポインターボタンを押した後、ポインタの動きが無視される最大時間（ミリ秒単位）です。\n\nクリック中にポインタが移動した場合、オブジェクトが意図せず動かされるのを防ぎます。"
};
const Comfy_Pointer_ClickDrift$3 = {
  name: "ポインタークリックドリフト（最大距離）",
  tooltip: "ボタンを押し続けている間にポインタがこの距離以上移動した場合、クリックではなくドラッグと見なされます。\n\nクリック中にポインタが移動した場合、オブジェクトが意図せず動かされるのを防ぎます。"
};
const Comfy_Pointer_DoubleClickTime$3 = {
  name: "ダブルクリック間隔（最大）",
  tooltip: "ダブルクリックの2回のクリック間の最大時間（ミリ秒単位）。この値を増やすことで、ダブルクリックが時々登録されない場合に助けになるかもしれません。"
};
const Comfy_PreviewFormat$3 = {
  name: "プレビュー画像フォーマット",
  tooltip: "画像ウィジェットでプレビューを表示する際、軽量画像に変換します（例：webp、jpeg、webp;50など）。"
};
const Comfy_PromptFilename$3 = {
  name: "ワークフローを保存する際にファイル名を入力するよう促す"
};
const Comfy_QueueButton_BatchCountLimit$3 = {
  name: "バッチ数制限",
  tooltip: "1回のボタンクリックでキューに追加できるタスクの最大数"
};
const Comfy_Queue_MaxHistoryItems$3 = {
  name: "キュー履歴サイズ",
  tooltip: "キュー履歴に表示されるタスクの最大数。"
};
const Comfy_Sidebar_Location$3 = {
  name: "サイドバーの位置",
  options: {
    left: "左",
    right: "右"
  }
};
const Comfy_Sidebar_Size$3 = {
  name: "サイドバーのサイズ",
  options: {
    normal: "通常",
    small: "小"
  }
};
const Comfy_Sidebar_UnifiedWidth$3 = {
  name: "サイドバーの幅を統一"
};
const Comfy_SnapToGrid_GridSize$3 = {
  name: "グリッドサイズにスナップ",
  tooltip: "シフトを押しながらノードをドラッグおよびサイズ変更すると、グリッドに整列されます。これにより、そのグリッドのサイズが制御されます。"
};
const Comfy_TextareaWidget_FontSize$3 = {
  name: "テキストエリアウィジェットのフォントサイズ"
};
const Comfy_TextareaWidget_Spellcheck$3 = {
  name: "テキストエリアウィジェットのスペルチェック"
};
const Comfy_TreeExplorer_ItemPadding$3 = {
  name: "ツリーエクスプローラーアイテムのパディング"
};
const Comfy_UseNewMenu$3 = {
  name: "新しいメニューを使用",
  options: {
    Bottom: "下",
    Disabled: "無効",
    Top: "上"
  }
};
const Comfy_Validation_NodeDefs$3 = {
  name: "ノード定義を検証（遅い）",
  tooltip: "ノード開発者に推奨されます。これにより、起動時にすべてのノード定義が検証されます。"
};
const Comfy_Validation_Workflows$3 = {
  name: "ワークフローを検証"
};
const Comfy_WidgetControlMode$3 = {
  name: "ウィジェット制御モード",
  options: {
    after: "後",
    before: "前"
  },
  tooltip: "ウィジェットの値が更新されるタイミングを制御します（ランダム化/インクリメント/デクリメント）、プロンプトがキューに入れられる前または後のいずれかです。"
};
const Comfy_Window_UnloadConfirmation$3 = {
  name: "ウィンドウを閉じるときに確認を表示"
};
const Comfy_Workflow_AutoSave$3 = {
  name: "自動保存",
  options: {
    "after delay": "遅延後",
    off: "オフ"
  }
};
const Comfy_Workflow_AutoSaveDelay$3 = {
  name: "自動保存遅延（ms）",
  tooltip: "自動保存が「遅延後」に設定されている場合のみ適用されます。"
};
const Comfy_Workflow_ConfirmDelete$3 = {
  name: "ワークフローを削除する際に確認を表示"
};
const Comfy_Workflow_Persist$3 = {
  name: "ページ（再）ロード時にワークフローの状態を保持し、復元します"
};
const Comfy_Workflow_ShowMissingModelsWarning$3 = {
  name: "欠落しているモデルの警告を表示"
};
const Comfy_Workflow_ShowMissingNodesWarning$3 = {
  name: "欠落しているノードの警告を表示"
};
const Comfy_Workflow_SortNodeIdOnSave$3 = {
  name: "ワークフローを保存する際にノードIDをソート"
};
const Comfy_Workflow_WorkflowTabsPosition$3 = {
  name: "開いているワークフローの位置",
  options: {
    Sidebar: "サイドバー",
    Topbar: "トップバー",
    "Topbar (2nd-row)": "トップバー（2行目）"
  }
};
const LiteGraph_Canvas_LowQualityRenderingZoomThreshold$3 = {
  name: "低品質レンダリングズーム閾値",
  tooltip: "ズームアウト時に低品質の形状をレンダリングする"
};
const LiteGraph_Canvas_MaximumFps$3 = {
  name: "最大FPS",
  tooltip: "キャンバスがレンダリングできる最大フレーム数です。スムーズさの代わりにGPU使用量を制限します。0の場合、画面のリフレッシュレートが使用されます。デフォルト：0"
};
const LiteGraph_ContextMenu_Scaling$3 = {
  name: "ズームイン時にノードコンボウィジェットメニュー（リスト）をスケーリングする"
};
const LiteGraph_Node_DefaultPadding$3 = {
  name: "新しいノードを常に縮小",
  tooltip: "ノード作成時に可能な限り小さいサイズにリサイズします。無効にすると、新しく追加されたノードはウィジェットの値が表示されるように少し幅広くなります。"
};
const LiteGraph_Node_TooltipDelay$3 = {
  name: "ツールチップ遅延"
};
const LiteGraph_Pointer_TrackpadGestures$3 = {
  name: "トラックパッドジェスチャーを有効にする",
  tooltip: "この設定を有効にすると、キャンバスでトラックパッドモードが有効になり、ピンチズームや2本指でのパン操作が可能になります。"
};
const LiteGraph_Reroute_SplineOffset$3 = {
  name: "リルートスプラインオフセット",
  tooltip: "リルート中心点からのベジエ制御点のオフセット"
};
const pysssss_SnapToGrid$3 = {
  name: "常にグリッドにスナップ"
};
const jaSettings = {
  "Comfy-Desktop_AutoUpdate": {
    name: "自動的に更新を確認する"
  },
  "Comfy-Desktop_SendStatistics": {
    name: "匿名の使用統計を送信する"
  },
  "Comfy-Desktop_UV_PypiInstallMirror": {
    name: "Pypi インストールミラー",
    tooltip: "デフォルトの pip インストールミラー"
  },
  "Comfy-Desktop_UV_PythonInstallMirror": {
    name: "Python Install Mirror",
    tooltip: "管理されたPythonのインストールは、Astral python-build-standaloneプロジェクトからダウンロードされます。この変数は、Pythonのインストールのための異なるソースを使用するためのミラーURLに設定することができます。提供されたURLは、例えば、https://github.com/astral-sh/python-build-standalone/releases/download/20240713/cpython-3.12.4%2B20240713-aarch64-apple-darwin-install_only.tar.gzの中でhttps://github.com/astral-sh/python-build-standalone/releases/downloadを置き換えます。ディストリビューションは、file:// URLスキームを使用してローカルディレクトリから読み取ることができます。"
  },
  "Comfy-Desktop_UV_TorchInstallMirror": {
    name: "Torch Install Mirror",
    tooltip: "pytorchのpipインストールミラー"
  },
  "Comfy-Desktop_WindowStyle": {
    name: "ウィンドウスタイル",
    options: {
      custom: "カスタム",
      "default": "デフォルト"
    },
    tooltip: "システムタイトルバーを非表示にするにはカスタムオプションを選択してください"
  },
  Comfy_Canvas_SelectionToolbox: Comfy_Canvas_SelectionToolbox$3,
  Comfy_ConfirmClear: Comfy_ConfirmClear$3,
  Comfy_DOMClippingEnabled: Comfy_DOMClippingEnabled$3,
  Comfy_DevMode: Comfy_DevMode$3,
  Comfy_DisableFloatRounding: Comfy_DisableFloatRounding$3,
  Comfy_DisableSliders: Comfy_DisableSliders$3,
  Comfy_EditAttention_Delta: Comfy_EditAttention_Delta$3,
  Comfy_EnableTooltips: Comfy_EnableTooltips$3,
  Comfy_EnableWorkflowViewRestore: Comfy_EnableWorkflowViewRestore$3,
  Comfy_FloatRoundingPrecision: Comfy_FloatRoundingPrecision$3,
  Comfy_Graph_CanvasInfo: Comfy_Graph_CanvasInfo$3,
  Comfy_Graph_CanvasMenu: Comfy_Graph_CanvasMenu$3,
  Comfy_Graph_CtrlShiftZoom: Comfy_Graph_CtrlShiftZoom$3,
  Comfy_Graph_LinkMarkers: Comfy_Graph_LinkMarkers$3,
  Comfy_Graph_ZoomSpeed: Comfy_Graph_ZoomSpeed$3,
  Comfy_GroupSelectedNodes_Padding: Comfy_GroupSelectedNodes_Padding$3,
  Comfy_Group_DoubleClickTitleToEdit: Comfy_Group_DoubleClickTitleToEdit$3,
  Comfy_LinkRelease_Action: Comfy_LinkRelease_Action$3,
  Comfy_LinkRelease_ActionShift: Comfy_LinkRelease_ActionShift$3,
  Comfy_LinkRenderMode: Comfy_LinkRenderMode$3,
  Comfy_Load3D_BackgroundColor: Comfy_Load3D_BackgroundColor$3,
  Comfy_Load3D_CameraType: Comfy_Load3D_CameraType$3,
  Comfy_Load3D_LightAdjustmentIncrement: Comfy_Load3D_LightAdjustmentIncrement$3,
  Comfy_Load3D_LightIntensity: Comfy_Load3D_LightIntensity$3,
  Comfy_Load3D_LightIntensityMaximum: Comfy_Load3D_LightIntensityMaximum$3,
  Comfy_Load3D_LightIntensityMinimum: Comfy_Load3D_LightIntensityMinimum$3,
  Comfy_Load3D_ShowGrid: Comfy_Load3D_ShowGrid$3,
  Comfy_Load3D_ShowPreview: Comfy_Load3D_ShowPreview$3,
  Comfy_Locale: Comfy_Locale$3,
  Comfy_MaskEditor_BrushAdjustmentSpeed: Comfy_MaskEditor_BrushAdjustmentSpeed$3,
  Comfy_MaskEditor_UseDominantAxis: Comfy_MaskEditor_UseDominantAxis$3,
  Comfy_MaskEditor_UseNewEditor: Comfy_MaskEditor_UseNewEditor$3,
  Comfy_ModelLibrary_AutoLoadAll: Comfy_ModelLibrary_AutoLoadAll$3,
  Comfy_ModelLibrary_NameFormat: Comfy_ModelLibrary_NameFormat$3,
  Comfy_NodeBadge_NodeIdBadgeMode: Comfy_NodeBadge_NodeIdBadgeMode$3,
  Comfy_NodeBadge_NodeLifeCycleBadgeMode: Comfy_NodeBadge_NodeLifeCycleBadgeMode$3,
  Comfy_NodeBadge_NodeSourceBadgeMode: Comfy_NodeBadge_NodeSourceBadgeMode$3,
  Comfy_NodeSearchBoxImpl: Comfy_NodeSearchBoxImpl$3,
  Comfy_NodeSearchBoxImpl_NodePreview: Comfy_NodeSearchBoxImpl_NodePreview$3,
  Comfy_NodeSearchBoxImpl_ShowCategory: Comfy_NodeSearchBoxImpl_ShowCategory$3,
  Comfy_NodeSearchBoxImpl_ShowIdName: Comfy_NodeSearchBoxImpl_ShowIdName$3,
  Comfy_NodeSearchBoxImpl_ShowNodeFrequency: Comfy_NodeSearchBoxImpl_ShowNodeFrequency$3,
  Comfy_NodeSuggestions_number: Comfy_NodeSuggestions_number$3,
  Comfy_Node_AllowImageSizeDraw: Comfy_Node_AllowImageSizeDraw$3,
  Comfy_Node_AutoSnapLinkToSlot: Comfy_Node_AutoSnapLinkToSlot$3,
  Comfy_Node_BypassAllLinksOnDelete: Comfy_Node_BypassAllLinksOnDelete$3,
  Comfy_Node_DoubleClickTitleToEdit: Comfy_Node_DoubleClickTitleToEdit$3,
  Comfy_Node_MiddleClickRerouteNode: Comfy_Node_MiddleClickRerouteNode$3,
  Comfy_Node_Opacity: Comfy_Node_Opacity$3,
  Comfy_Node_ShowDeprecated: Comfy_Node_ShowDeprecated$3,
  Comfy_Node_ShowExperimental: Comfy_Node_ShowExperimental$3,
  Comfy_Node_SnapHighlightsNode: Comfy_Node_SnapHighlightsNode$3,
  Comfy_Pointer_ClickBufferTime: Comfy_Pointer_ClickBufferTime$3,
  Comfy_Pointer_ClickDrift: Comfy_Pointer_ClickDrift$3,
  Comfy_Pointer_DoubleClickTime: Comfy_Pointer_DoubleClickTime$3,
  Comfy_PreviewFormat: Comfy_PreviewFormat$3,
  Comfy_PromptFilename: Comfy_PromptFilename$3,
  Comfy_QueueButton_BatchCountLimit: Comfy_QueueButton_BatchCountLimit$3,
  Comfy_Queue_MaxHistoryItems: Comfy_Queue_MaxHistoryItems$3,
  Comfy_Sidebar_Location: Comfy_Sidebar_Location$3,
  Comfy_Sidebar_Size: Comfy_Sidebar_Size$3,
  Comfy_Sidebar_UnifiedWidth: Comfy_Sidebar_UnifiedWidth$3,
  Comfy_SnapToGrid_GridSize: Comfy_SnapToGrid_GridSize$3,
  Comfy_TextareaWidget_FontSize: Comfy_TextareaWidget_FontSize$3,
  Comfy_TextareaWidget_Spellcheck: Comfy_TextareaWidget_Spellcheck$3,
  Comfy_TreeExplorer_ItemPadding: Comfy_TreeExplorer_ItemPadding$3,
  Comfy_UseNewMenu: Comfy_UseNewMenu$3,
  Comfy_Validation_NodeDefs: Comfy_Validation_NodeDefs$3,
  Comfy_Validation_Workflows: Comfy_Validation_Workflows$3,
  Comfy_WidgetControlMode: Comfy_WidgetControlMode$3,
  Comfy_Window_UnloadConfirmation: Comfy_Window_UnloadConfirmation$3,
  Comfy_Workflow_AutoSave: Comfy_Workflow_AutoSave$3,
  Comfy_Workflow_AutoSaveDelay: Comfy_Workflow_AutoSaveDelay$3,
  Comfy_Workflow_ConfirmDelete: Comfy_Workflow_ConfirmDelete$3,
  Comfy_Workflow_Persist: Comfy_Workflow_Persist$3,
  Comfy_Workflow_ShowMissingModelsWarning: Comfy_Workflow_ShowMissingModelsWarning$3,
  Comfy_Workflow_ShowMissingNodesWarning: Comfy_Workflow_ShowMissingNodesWarning$3,
  Comfy_Workflow_SortNodeIdOnSave: Comfy_Workflow_SortNodeIdOnSave$3,
  Comfy_Workflow_WorkflowTabsPosition: Comfy_Workflow_WorkflowTabsPosition$3,
  LiteGraph_Canvas_LowQualityRenderingZoomThreshold: LiteGraph_Canvas_LowQualityRenderingZoomThreshold$3,
  LiteGraph_Canvas_MaximumFps: LiteGraph_Canvas_MaximumFps$3,
  LiteGraph_ContextMenu_Scaling: LiteGraph_ContextMenu_Scaling$3,
  LiteGraph_Node_DefaultPadding: LiteGraph_Node_DefaultPadding$3,
  LiteGraph_Node_TooltipDelay: LiteGraph_Node_TooltipDelay$3,
  LiteGraph_Pointer_TrackpadGestures: LiteGraph_Pointer_TrackpadGestures$3,
  LiteGraph_Reroute_SplineOffset: LiteGraph_Reroute_SplineOffset$3,
  pysssss_SnapToGrid: pysssss_SnapToGrid$3
};
const Comfy_BrowseTemplates$2 = {
  label: "템플릿 탐색"
};
const Comfy_Canvas_DeleteSelectedItems$2 = {
  label: "선택한 항목 삭제"
};
const Comfy_Canvas_FitView$2 = {
  label: "선택한 노드에 뷰 맞추기"
};
const Comfy_Canvas_ResetView$2 = {
  label: "뷰 재설정"
};
const Comfy_Canvas_Resize$2 = {
  label: "선택된 노드 크기 조정"
};
const Comfy_Canvas_ToggleLinkVisibility$2 = {
  label: "캔버스 링크 가시성 토글"
};
const Comfy_Canvas_ToggleLock$2 = {
  label: "캔버스 잠금 토글"
};
const Comfy_Canvas_ToggleSelectedNodes_Bypass$2 = {
  label: "선택한 노드 우회/우회 해제"
};
const Comfy_Canvas_ToggleSelectedNodes_Collapse$2 = {
  label: "선택한 노드 축소/확장"
};
const Comfy_Canvas_ToggleSelectedNodes_Mute$2 = {
  label: "선택한 노드 음소거/음소거 해제"
};
const Comfy_Canvas_ToggleSelectedNodes_Pin$2 = {
  label: "선택한 노드 고정/고정 해제"
};
const Comfy_Canvas_ToggleSelected_Pin$2 = {
  label: "선택한 항목 고정/고정 해제"
};
const Comfy_Canvas_ZoomIn$2 = {
  label: "확대"
};
const Comfy_Canvas_ZoomOut$2 = {
  label: "축소"
};
const Comfy_ClearPendingTasks$2 = {
  label: "보류 중인 작업 지우기"
};
const Comfy_ClearWorkflow$2 = {
  label: "워크플로 지우기"
};
const Comfy_ContactSupport$2 = {
  label: "지원팀에 문의하기"
};
const Comfy_DuplicateWorkflow$2 = {
  label: "현재 워크플로우 복제"
};
const Comfy_ExportWorkflow$2 = {
  label: "워크플로 내보내기"
};
const Comfy_ExportWorkflowAPI$2 = {
  label: "워크플로 내보내기 (API 형식)"
};
const Comfy_Feedback$2 = {
  label: "피드백"
};
const Comfy_Graph_FitGroupToContents$2 = {
  label: "그룹을 내용에 맞게 맞추기"
};
const Comfy_Graph_GroupSelectedNodes$2 = {
  label: "선택한 노드 그룹화"
};
const Comfy_GroupNode_ConvertSelectedNodesToGroupNode$2 = {
  label: "선택한 노드를 그룹 노드로 변환"
};
const Comfy_GroupNode_ManageGroupNodes$2 = {
  label: "그룹 노드 관리"
};
const Comfy_GroupNode_UngroupSelectedGroupNodes$2 = {
  label: "선택한 그룹 노드 분리"
};
const Comfy_Help_AboutComfyUI$2 = {
  label: "ComfyUI 정보 열기"
};
const Comfy_Help_OpenComfyOrgDiscord$2 = {
  label: "Comfy-Org 디스코드 열기"
};
const Comfy_Help_OpenComfyUIDocs$2 = {
  label: "ComfyUI 문서 열기"
};
const Comfy_Help_OpenComfyUIForum$2 = {
  label: "Comfy-Org 포럼 열기"
};
const Comfy_Help_OpenComfyUIIssues$2 = {
  label: "ComfyUI 문제 열기"
};
const Comfy_Interrupt$2 = {
  label: "중단"
};
const Comfy_LoadDefaultWorkflow$2 = {
  label: "기본 워크플로 로드"
};
const Comfy_Manager_CustomNodesManager$2 = {
  label: "사용자 정의 노드 관리자"
};
const Comfy_Manager_ToggleManagerProgressDialog$2 = {
  label: "진행 상황 대화 상자 전환"
};
const Comfy_NewBlankWorkflow$2 = {
  label: "새로운 빈 워크플로"
};
const Comfy_OpenClipspace$2 = {
  label: "클립스페이스"
};
const Comfy_OpenWorkflow$2 = {
  label: "워크플로 열기"
};
const Comfy_QueuePrompt$2 = {
  label: "실행 큐에 프롬프트 추가"
};
const Comfy_QueuePromptFront$2 = {
  label: "실행 큐 맨 앞에 프롬프트 추가"
};
const Comfy_QueueSelectedOutputNodes$2 = {
  label: "선택한 출력 노드 대기열에 추가"
};
const Comfy_Redo$2 = {
  label: "다시 실행"
};
const Comfy_RefreshNodeDefinitions$2 = {
  label: "노드 정의 새로 고침"
};
const Comfy_SaveWorkflow$2 = {
  label: "워크플로 저장"
};
const Comfy_SaveWorkflowAs$2 = {
  label: "다른 이름으로 워크플로 저장"
};
const Comfy_ShowSettingsDialog$2 = {
  label: "설정 대화상자 보기"
};
const Comfy_ToggleTheme$2 = {
  label: "밝기 테마 전환 (어두운/밝은)"
};
const Comfy_Undo$2 = {
  label: "실행 취소"
};
const Comfy_User_OpenSignInDialog$2 = {
  label: "로그인 대화상자 열기"
};
const Comfy_User_SignOut$2 = {
  label: "로그아웃"
};
const Workspace_CloseWorkflow$2 = {
  label: "현재 워크플로우 닫기"
};
const Workspace_NextOpenedWorkflow$2 = {
  label: "다음 열린 워크플로"
};
const Workspace_PreviousOpenedWorkflow$2 = {
  label: "이전 열린 워크플로"
};
const Workspace_SearchBox_Toggle$2 = {
  label: "검색 상자 토글"
};
const Workspace_ToggleBottomPanel$2 = {
  label: "하단 패널 토글"
};
const Workspace_ToggleFocusMode$2 = {
  label: "포커스 모드 토글"
};
const Workspace_ToggleSidebarTab_queue$2 = {
  label: "실행 큐 사이드바 토글",
  tooltip: "실행 큐"
};
const Workspace_ToggleSidebarTab_workflows$2 = {
  label: "워크플로 사이드바 토글",
  tooltip: "워크플로"
};
const koCommands = {
  "Comfy-Desktop_CheckForUpdates": {
    label: "업데이트 확인"
  },
  "Comfy-Desktop_Folders_OpenCustomNodesFolder": {
    label: "사용자 정의 노드 폴더 열기"
  },
  "Comfy-Desktop_Folders_OpenInputsFolder": {
    label: "입력 폴더 열기"
  },
  "Comfy-Desktop_Folders_OpenLogsFolder": {
    label: "로그 폴더 열기"
  },
  "Comfy-Desktop_Folders_OpenModelConfig": {
    label: "extra_model_paths.yaml 열기"
  },
  "Comfy-Desktop_Folders_OpenModelsFolder": {
    label: "모델 폴더 열기"
  },
  "Comfy-Desktop_Folders_OpenOutputsFolder": {
    label: "출력 폴더 열기"
  },
  "Comfy-Desktop_OpenDevTools": {
    label: "DevTools 열기"
  },
  "Comfy-Desktop_OpenUserGuide": {
    label: "데스크톱 사용자 가이드"
  },
  "Comfy-Desktop_Quit": {
    label: "종료"
  },
  "Comfy-Desktop_Reinstall": {
    label: "재설치"
  },
  "Comfy-Desktop_Restart": {
    label: "재시작"
  },
  Comfy_BrowseTemplates: Comfy_BrowseTemplates$2,
  Comfy_Canvas_DeleteSelectedItems: Comfy_Canvas_DeleteSelectedItems$2,
  Comfy_Canvas_FitView: Comfy_Canvas_FitView$2,
  Comfy_Canvas_ResetView: Comfy_Canvas_ResetView$2,
  Comfy_Canvas_Resize: Comfy_Canvas_Resize$2,
  Comfy_Canvas_ToggleLinkVisibility: Comfy_Canvas_ToggleLinkVisibility$2,
  Comfy_Canvas_ToggleLock: Comfy_Canvas_ToggleLock$2,
  Comfy_Canvas_ToggleSelectedNodes_Bypass: Comfy_Canvas_ToggleSelectedNodes_Bypass$2,
  Comfy_Canvas_ToggleSelectedNodes_Collapse: Comfy_Canvas_ToggleSelectedNodes_Collapse$2,
  Comfy_Canvas_ToggleSelectedNodes_Mute: Comfy_Canvas_ToggleSelectedNodes_Mute$2,
  Comfy_Canvas_ToggleSelectedNodes_Pin: Comfy_Canvas_ToggleSelectedNodes_Pin$2,
  Comfy_Canvas_ToggleSelected_Pin: Comfy_Canvas_ToggleSelected_Pin$2,
  Comfy_Canvas_ZoomIn: Comfy_Canvas_ZoomIn$2,
  Comfy_Canvas_ZoomOut: Comfy_Canvas_ZoomOut$2,
  Comfy_ClearPendingTasks: Comfy_ClearPendingTasks$2,
  Comfy_ClearWorkflow: Comfy_ClearWorkflow$2,
  Comfy_ContactSupport: Comfy_ContactSupport$2,
  Comfy_DuplicateWorkflow: Comfy_DuplicateWorkflow$2,
  Comfy_ExportWorkflow: Comfy_ExportWorkflow$2,
  Comfy_ExportWorkflowAPI: Comfy_ExportWorkflowAPI$2,
  Comfy_Feedback: Comfy_Feedback$2,
  Comfy_Graph_FitGroupToContents: Comfy_Graph_FitGroupToContents$2,
  Comfy_Graph_GroupSelectedNodes: Comfy_Graph_GroupSelectedNodes$2,
  Comfy_GroupNode_ConvertSelectedNodesToGroupNode: Comfy_GroupNode_ConvertSelectedNodesToGroupNode$2,
  Comfy_GroupNode_ManageGroupNodes: Comfy_GroupNode_ManageGroupNodes$2,
  Comfy_GroupNode_UngroupSelectedGroupNodes: Comfy_GroupNode_UngroupSelectedGroupNodes$2,
  Comfy_Help_AboutComfyUI: Comfy_Help_AboutComfyUI$2,
  Comfy_Help_OpenComfyOrgDiscord: Comfy_Help_OpenComfyOrgDiscord$2,
  Comfy_Help_OpenComfyUIDocs: Comfy_Help_OpenComfyUIDocs$2,
  Comfy_Help_OpenComfyUIForum: Comfy_Help_OpenComfyUIForum$2,
  Comfy_Help_OpenComfyUIIssues: Comfy_Help_OpenComfyUIIssues$2,
  Comfy_Interrupt: Comfy_Interrupt$2,
  Comfy_LoadDefaultWorkflow: Comfy_LoadDefaultWorkflow$2,
  Comfy_Manager_CustomNodesManager: Comfy_Manager_CustomNodesManager$2,
  Comfy_Manager_ToggleManagerProgressDialog: Comfy_Manager_ToggleManagerProgressDialog$2,
  Comfy_NewBlankWorkflow: Comfy_NewBlankWorkflow$2,
  Comfy_OpenClipspace: Comfy_OpenClipspace$2,
  Comfy_OpenWorkflow: Comfy_OpenWorkflow$2,
  Comfy_QueuePrompt: Comfy_QueuePrompt$2,
  Comfy_QueuePromptFront: Comfy_QueuePromptFront$2,
  Comfy_QueueSelectedOutputNodes: Comfy_QueueSelectedOutputNodes$2,
  Comfy_Redo: Comfy_Redo$2,
  Comfy_RefreshNodeDefinitions: Comfy_RefreshNodeDefinitions$2,
  Comfy_SaveWorkflow: Comfy_SaveWorkflow$2,
  Comfy_SaveWorkflowAs: Comfy_SaveWorkflowAs$2,
  Comfy_ShowSettingsDialog: Comfy_ShowSettingsDialog$2,
  Comfy_ToggleTheme: Comfy_ToggleTheme$2,
  Comfy_Undo: Comfy_Undo$2,
  Comfy_User_OpenSignInDialog: Comfy_User_OpenSignInDialog$2,
  Comfy_User_SignOut: Comfy_User_SignOut$2,
  Workspace_CloseWorkflow: Workspace_CloseWorkflow$2,
  Workspace_NextOpenedWorkflow: Workspace_NextOpenedWorkflow$2,
  Workspace_PreviousOpenedWorkflow: Workspace_PreviousOpenedWorkflow$2,
  Workspace_SearchBox_Toggle: Workspace_SearchBox_Toggle$2,
  Workspace_ToggleBottomPanel: Workspace_ToggleBottomPanel$2,
  "Workspace_ToggleBottomPanelTab_command-terminal": {
    label: "터미널 하단 패널 토글"
  },
  "Workspace_ToggleBottomPanelTab_logs-terminal": {
    label: "로그 하단 패널 토글"
  },
  Workspace_ToggleFocusMode: Workspace_ToggleFocusMode$2,
  "Workspace_ToggleSidebarTab_model-library": {
    label: "모델 라이브러리 사이드바 토글",
    tooltip: "모델 라이브러리"
  },
  "Workspace_ToggleSidebarTab_node-library": {
    label: "노드 라이브러리 사이드바 토글",
    tooltip: "노드 라이브러리"
  },
  Workspace_ToggleSidebarTab_queue: Workspace_ToggleSidebarTab_queue$2,
  Workspace_ToggleSidebarTab_workflows: Workspace_ToggleSidebarTab_workflows$2
};
const apiNodesCostBreakdown$2 = {
  costPerRun: "실행 당 비용",
  title: "API 노드(들)",
  totalCost: "총 비용"
};
const apiNodesNews$2 = {
  introducing: "소개합니다",
  steps: {
    step1: {
      subtitle: "설정 > 사용자 > 로그인",
      title: "로그인/계정 생성:"
    },
    step2: {
      subtitle: "설정 > 크레딧 > 크레딧 구매",
      title: "크레딧 구매:"
    },
    step3: {
      title: "'API Node' 섹션에서 새로운 API 노드를 찾아 캔버스에 추가하세요"
    },
    step4: {
      title: "실행!"
    }
  },
  subtitle: "모든 외부 모델이 이제 ComfyUI에서 사용 가능합니다"
};
const apiNodesSignInDialog$2 = {
  message: "이 워크플로우에는 API 노드가 포함되어 있으며, 실행하려면 계정에 로그인해야 합니다.",
  title: "API 노드 사용에 필요한 로그인"
};
const auth$2 = {
  apiKey: {
    cleared: "API 키 삭제됨",
    clearedDetail: "API 키가 성공적으로 삭제되었습니다",
    description: "Comfy API 키를 사용하여 API 노드를 활성화하세요",
    error: "유효하지 않은 API 키",
    generateKey: "여기에서 받기",
    helpText: "API 키가 필요하신가요?",
    invalid: "유효하지 않은 API 키",
    invalidDetail: "유효한 API 키를 입력해 주세요",
    label: "API 키",
    placeholder: "API 키를 입력하세요",
    storageFailed: "API 키 저장 실패",
    storageFailedDetail: "다시 시도해 주세요.",
    stored: "API 키 저장됨",
    storedDetail: "API 키가 성공적으로 저장되었습니다",
    title: "API 키",
    whitelistInfo: "비허용 사이트에 대하여"
  },
  login: {
    andText: "및",
    confirmPasswordLabel: "비밀번호 확인",
    confirmPasswordPlaceholder: "동일한 비밀번호를 다시 입력하세요",
    emailLabel: "이메일",
    emailPlaceholder: "이메일을 입력하세요",
    failed: "로그인 실패",
    forgotPassword: "비밀번호를 잊으셨나요?",
    forgotPasswordError: "비밀번호 재설정 이메일 전송에 실패했습니다",
    insecureContextWarning: "이 연결은 안전하지 않습니다(HTTP) - 로그인을 계속하면 자격 증명이 공격자에게 가로채질 수 있습니다.",
    loginButton: "로그인",
    loginWithGithub: "Github로 로그인",
    loginWithGoogle: "구글로 로그인",
    newUser: "처음이신가요?",
    noAssociatedUser: "제공된 API 키와 연결된 Comfy 사용자가 없습니다",
    orContinueWith: "또는 다음으로 계속",
    passwordLabel: "비밀번호",
    passwordPlaceholder: "비밀번호를 입력하세요",
    passwordResetSent: "비밀번호 재설정 이메일이 전송되었습니다",
    passwordResetSentDetail: "비밀번호를 재설정할 수 있는 링크가 포함된 이메일을 확인해 주세요.",
    privacyLink: "개인정보 보호정책",
    questionsContactPrefix: "질문이 있으신가요? 문의: ",
    signInOrSignUp: "로그인 / 회원가입",
    signUp: "가입하기",
    success: "로그인 성공",
    termsLink: "이용 약관",
    termsText: '"다음" 또는 "가입하기"를 클릭하면 우리의',
    title: "계정에 로그인",
    useApiKey: "Comfy API 키",
    userAvatar: "사용자 아바타"
  },
  passwordUpdate: {
    success: "비밀번호가 업데이트되었습니다",
    successDetail: "비밀번호가 성공적으로 업데이트되었습니다"
  },
  signOut: {
    signOut: "로그아웃",
    success: "성공적으로 로그아웃되었습니다",
    successDetail: "계정에서 로그아웃되었습니다."
  },
  signup: {
    alreadyHaveAccount: "이미 계정이 있으신가요?",
    emailLabel: "이메일",
    emailPlaceholder: "이메일을 입력하세요",
    passwordLabel: "비밀번호",
    passwordPlaceholder: "새 비밀번호를 입력하세요",
    personalDataConsentLabel: "개인 정보 처리에 동의합니다.",
    regionRestrictionChina: "현지 규제 요건에 따라, 본 서비스는 현재 중국 본토에 위치한 사용자에게 제공되지 않습니다.",
    signIn: "로그인",
    signUpButton: "가입하기",
    signUpWithGithub: "Github로 가입하기",
    signUpWithGoogle: "구글로 가입하기",
    title: "계정 생성"
  }
};
const clipboard$2 = {
  errorMessage: "클립보드에 복사하지 못했습니다",
  errorNotSupported: "브라우저가 클립보드 API를 지원하지 않습니다.",
  successMessage: "클립보드에 복사됨"
};
const color$2 = {
  black: "검정색",
  blue: "파란색",
  brown: "갈색",
  custom: "사용자 정의",
  cyan: "청록색",
  "default": "기본값",
  green: "초록색",
  noColor: "색 없음",
  pale_blue: "흐린 파랑색",
  pink: "분홍색",
  purple: "보라색",
  red: "빨간색",
  yellow: "노란색"
};
const contextMenu$2 = {
  "Add Group": "그룹 추가",
  "Add Group For Selected Nodes": "선택한 노드 그룹 추가",
  "Add Node": "노드 추가",
  Bypass: "실행 건너뛰기",
  Clone: "복제",
  Collapse: "접기",
  Colors: "색상",
  "Convert to Group Node": "그룹 노드로 변환",
  "Copy (Clipspace)": "복사 (Clipspace)",
  Expand: "확장",
  Inputs: "입력",
  Manage: "관리",
  "Manage Group Nodes": "그룹 노드 관리",
  Mode: "모드",
  "Node Templates": "노드 템플릿",
  Outputs: "출력",
  Pin: "고정",
  Properties: "속성",
  "Properties Panel": "속성 패널",
  Remove: "제거",
  Resize: "크기 조정",
  "Save Selected as Template": "선택된 부분을 템플릿으로 저장",
  Search: "검색",
  Shapes: "형태",
  Title: "제목",
  Unpin: "고정 해제"
};
const credits$2 = {
  apiPricing: "API 가격",
  credits: "크레딧",
  faqs: "자주 묻는 질문",
  invoiceHistory: "청구서 내역",
  lastUpdated: "마지막 업데이트",
  messageSupport: "지원 문의",
  purchaseCredits: "크레딧 구매",
  topUp: {
    buyNow: "지금 구매",
    insufficientMessage: "이 워크플로우를 실행하기에 크레딧이 부족합니다.",
    insufficientTitle: "크레딧 부족",
    maxAmount: "(최대 $1,000 USD)",
    quickPurchase: "빠른 구매",
    seeDetails: "자세히 보기",
    topUp: "충전하기"
  },
  yourCreditBalance: "보유 크레딧 잔액"
};
const dataTypes$2 = {
  "*": "*",
  AUDIO: "오디오",
  BOOLEAN: "논리값",
  CAMERA_CONTROL: "카메라 제어",
  CLIP: "CLIP",
  CLIP_VISION: "CLIP_VISION",
  CLIP_VISION_OUTPUT: "CLIP_VISION 출력",
  COMBO: "콤보",
  CONDITIONING: "조건",
  CONTROL_NET: "컨트롤넷",
  FLOAT: "실수",
  FLOATS: "실수 배열",
  GLIGEN: "GLIGEN",
  GUIDER: "가이드",
  HOOKS: "후크",
  HOOK_KEYFRAMES: "후크 키프레임",
  IMAGE: "이미지",
  INT: "정수",
  LATENT: "잠재 데이터",
  LATENT_OPERATION: "잠재 연산",
  LOAD3D_CAMERA: "3D 카메라 불러오기",
  LOAD_3D: "3D 로드",
  LOAD_3D_ANIMATION: "3D 애니메이션 로드",
  LUMA_CONCEPTS: "Luma 컨셉",
  LUMA_REF: "Luma 참조",
  MASK: "마스크",
  MESH: "메시",
  MODEL: "모델",
  NOISE: "노이즈",
  PHOTOMAKER: "PHOTOMAKER",
  PIXVERSE_TEMPLATE: "Pixverse 템플릿",
  RECRAFT_COLOR: "Recraft 색상",
  RECRAFT_CONTROLS: "Recraft 컨트롤",
  RECRAFT_V3_STYLE: "Recraft V3 스타일",
  SAMPLER: "샘플러",
  SIGMAS: "시그마",
  STRING: "문자열",
  STYLE_MODEL: "스타일 모델",
  SVG: "SVG",
  TIMESTEPS_RANGE: "타임스텝 범위",
  UPSCALE_MODEL: "업스케일 모델",
  VAE: "VAE",
  VIDEO: "비디오",
  VOXEL: "복셀",
  WEBCAM: "웹캠"
};
const desktopMenu$2 = {
  confirmQuit: "저장되지 않은 워크플로가 열려 있습니다. 저장되지 않은 변경 사항은 모두 손실됩니다. 이를 무시하고 종료하시겠습니까?",
  confirmReinstall: "이 작업은 extra_models_config.yaml 파일을 지우고 설치를 다시 시작합니다. 정말로 진행하시겠습니까?",
  quit: "종료",
  reinstall: "재설치"
};
const desktopUpdate$2 = {
  description: "ComfyUI 데스크톱이 새로운 종속성을 설치하고 있습니다. 이 작업은 몇 분 정도 걸릴 수 있습니다.",
  errorCheckingUpdate: "업데이트 확인 중 오류가 발생했습니다",
  errorInstallingUpdate: "업데이트 설치 중 오류가 발생했습니다",
  noUpdateFound: "업데이트를 찾을 수 없습니다",
  terminalDefaultMessage: "업데이트 콘솔 출력은 여기에 표시됩니다.",
  title: "ComfyUI 데스크톱 업데이트 중",
  updateAvailableMessage: "업데이트가 가능합니다. 지금 재시작하고 업데이트하시겠습니까?",
  updateFoundTitle: "업데이트 발견 (v{version})"
};
const downloadGit$2 = {
  gitWebsite: "git 프로그램 다운로드",
  instructions: "운영 체제에 맞는 최신 버전을 다운로드하여 설치하십시오. 아래의 'git 프로그램 다운로드' 버튼을 클릭하면 git-scm.com 다운로드 페이지가 열립니다.",
  message: "git 프로그램을 찾을 수 없습니다. 정상적인 작업을 위해서는 git 프로그램이 필요합니다.",
  skip: "건너뛰기",
  title: "git 프로그램 다운로드",
  warning: "git 프로그램이 이미 설치된 것이 확실하다면, 이 검사 단계를 스킵할 수 있습니다. 현재는 정상적으로 실행 가능한 git 프로그램이 없는 경우, ComfyUI를 실행할 수 없습니다."
};
const electronFileDownload$2 = {
  cancel: "다운로드 취소",
  cancelled: "취소됨",
  inProgress: "진행 중",
  pause: "다운로드 일시 중지",
  paused: "일시 중지됨",
  resume: "다운로드 재개"
};
const errorDialog$2 = {
  defaultTitle: "오류가 발생했습니다",
  extensionFileHint: "다음 스크립트 때문일 수 있습니다",
  loadWorkflowTitle: "워크플로우 데이터를 다시 로드하는 중 오류로 인해 로드가 중단되었습니다",
  noStackTrace: "스택 추적을 사용할 수 없습니다",
  promptExecutionError: "프롬프트 실행 실패"
};
const g$2 = {
  about: "정보",
  add: "추가",
  all: "모두",
  amount: "수량",
  apply: "적용",
  back: "뒤로",
  cancel: "취소",
  capture: "캡처",
  category: "카테고리",
  choose_file_to_upload: "업로드할 파일 선택",
  close: "닫기",
  color: "색상",
  comingSoon: "곧 출시 예정",
  command: "명령",
  community: "커뮤니티",
  completed: "완료됨",
  confirm: "확인",
  confirmed: "확인됨",
  "continue": "계속",
  control_after_generate: "생성 후 제어",
  control_before_generate: "생성 전 제어",
  copyToClipboard: "클립보드에 복사",
  currentUser: "현재 사용자",
  customize: "사용자 정의",
  customizeFolder: "폴더 사용자 정의",
  "delete": "삭제",
  deprecated: "사용 중단",
  description: "설명",
  devices: "장치",
  disableAll: "모두 비활성화",
  disabling: "비활성화 중",
  download: "다운로드",
  empty: "비어 있음",
  enableAll: "모두 활성화",
  enabled: "활성화됨",
  enabling: "활성화 중",
  error: "오류",
  experimental: "베타",
  "export": "내보내기",
  extensionName: "확장 이름",
  feedback: "피드백",
  filter: "필터",
  findIssues: "문제 찾기",
  firstTimeUIMessage: '새 UI를 처음 사용합니다. "메뉴 > 새 메뉴 사용 > 비활성화"를 선택하여 이전 UI로 복원하세요.',
  goToNode: "노드로 이동",
  icon: "아이콘",
  imageFailedToLoad: "이미지를 로드하지 못했습니다.",
  "import": "가져오기",
  inProgress: "진행 중",
  insert: "삽입",
  install: "설치",
  installed: "설치됨",
  installing: "설치 중",
  interrupted: "중단됨",
  keybinding: "키 바인딩",
  learnMore: "더 알아보기",
  loadAllFolders: "모든 폴더 로드",
  loadWorkflow: "워크플로 로드",
  loading: "로딩 중",
  login: "로그인",
  logs: "로그",
  migrate: "이전(migrate)",
  missing: "누락됨",
  name: "이름",
  newFolder: "새 폴더",
  next: "다음",
  no: "아니오",
  noResultsFound: "결과를 찾을 수 없습니다.",
  noTasksFound: "작업을 찾을 수 없습니다.",
  noTasksFoundMessage: "대기열에 작업이 없습니다.",
  noWorkflowsFound: "워크플로를 찾을 수 없습니다.",
  nodes: "노드",
  ok: "확인",
  openNewIssue: "새 문제 열기",
  overwrite: "덮어쓰기",
  reconnected: "재연결됨",
  reconnecting: "재연결 중",
  refresh: "새로 고침",
  reloadToApplyChanges: "변경 사항을 적용하려면 새로 고침하세요.",
  rename: "이름 바꾸기",
  reportIssue: "보고서 보내기",
  reportIssueTooltip: "Comfy Org에 오류 보고서를 제출합니다.",
  reportSent: "보고서 제출됨",
  reset: "재설정",
  resetAll: "모두 초기화",
  resetAllKeybindingsTooltip: "모든 키 바인딩을 기본값으로 초기화",
  restart: "재시작",
  resultsCount: "{count} 개의 결과를 찾았습니다",
  save: "저장",
  saving: "저장 중",
  searchExtensions: "확장 검색",
  searchFailedMessage: "검색어와 일치하는 설정을 찾을 수 없습니다. 검색어를 조정해 보세요.",
  searchKeybindings: "키 바인딩 검색",
  searchModels: "모델 검색",
  searchNodes: "노드 검색",
  searchSettings: "설정 검색",
  searchWorkflows: "워크플로 검색",
  settings: "설정",
  showReport: "보고서 보기",
  sort: "정렬",
  source: "소스",
  status: "상태",
  success: "성공",
  systemInfo: "시스템 정보",
  terminal: "터미널",
  title: "제목",
  unknownError: "알 수 없는 오류",
  update: "업데이트",
  updateAvailable: "업데이트 가능",
  updated: "업데이트 됨",
  updating: "업데이트 중",
  upload: "업로드",
  user: "사용자",
  videoFailedToLoad: "비디오를 로드하지 못했습니다.",
  workflow: "워크플로"
};
const graphCanvasMenu$2 = {
  fitView: "보기 맞춤",
  panMode: "팬 모드",
  resetView: "보기 재설정",
  selectMode: "선택 모드",
  toggleLinkVisibility: "링크 가시성 전환",
  zoomIn: "확대",
  zoomOut: "축소"
};
const groupNode$2 = {
  create: "그룹 노드 만들기",
  enterName: "이름 입력"
};
const icon$2 = {
  bookmark: "북마크",
  box: "상자",
  briefcase: "서류가방",
  "exclamation-triangle": "경고",
  file: "파일",
  folder: "폴더",
  heart: "하트",
  inbox: "받은 편지함",
  star: "별"
};
const install$2 = {
  appDataLocationTooltip: "ComfyUI의 앱 데이터 디렉토리. 저장소:\n- 로그\n- 서버 구성",
  appPathLocationTooltip: "ComfyUI의 앱 에셋 디렉토리. ComfyUI 코드 및 에셋을 저장합니다.",
  cannotWrite: "선택한 경로에 쓸 수 없습니다",
  chooseInstallationLocation: "설치 위치 선택",
  customNodes: "사용자 정의 노드",
  customNodesDescription: "기존 ComfyUI 설치에서 사용자 정의 노드를 다시 설치합니다.",
  desktopAppSettings: "데스크탑 앱 설정",
  desktopAppSettingsDescription: "ComfyUI가 데스크탑에서 어떻게 작동하는지 구성하세요. 이 설정은 나중에 변경할 수 있습니다.",
  desktopSettings: "데스크탑 설정",
  failedToSelectDirectory: "디렉토리 선택 실패",
  gpu: "GPU",
  gpuSelection: {
    cpuMode: "CPU 모드",
    cpuModeDescription: "CPU 모드는 개발자와 드문 경우에만 사용됩니다.",
    cpuModeDescription2: "이것이 필요한지 확실하지 않다면, 이 상자를 무시하고 위에서 GPU를 선택하세요.",
    customComfyNeedsPython: "Python이 설정되지 않으면 ComfyUI가 작동하지 않습니다",
    customInstallRequirements: "모든 요구 사항과 종속성 설치 (예: 사용자 정의 torch)",
    customManualVenv: "Python venv를 수동으로 구성",
    customMayNotWork: "이것은 전혀 지원되지 않으며, 작동하지 않을 수 있습니다",
    customSkipsPython: "이 옵션은 일반 Python 설정을 건너뜁니다.",
    enableCpuMode: "CPU 모드 활성화",
    mpsDescription: "Apple Metal Performance Shaders는 pytorch nightly를 사용하여 지원됩니다.",
    nvidiaDescription: "NVIDIA 장치는 pytorch CUDA 빌드를 사용하여 직접 지원됩니다.",
    selectGpu: "GPU 선택",
    selectGpuDescription: "소유한 GPU 유형을 선택하세요"
  },
  helpImprove: "ComfyUI 개선에 도움을 주세요",
  installLocation: "설치 위치",
  installLocationDescription: "ComfyUI의 사용자 데이터 디렉토리를 선택하십시오. 선택한 위치에 Python 환경이 설치됩니다. 선택한 디스크에 충분한 공간(~15GB)이 남아 있는지 확인하십시오.",
  installLocationTooltip: "ComfyUI의 사용자 데이터 디렉토리. 저장소:\n- Python 환경\n- 모델\n- 사용자 정의 노드\n",
  insufficientFreeSpace: "공간이 부족합니다 - 최소한의 여유 공간",
  isOneDrive: "OneDrive에 설치하면 문제가 발생할 수 있습니다. OneDrive가 아닌 위치에 설치하는 것을 강력히 권장합니다.",
  manualConfiguration: {
    createVenv: "다음 디렉토리에 가상 환경을 생성해야 합니다",
    requirements: "요구 사항",
    restartWhenFinished: "가상 환경 구성을 완료하면 ComfyUI를 다시 시작해주세요.",
    title: "수동 구성",
    virtualEnvironmentPath: "가상 환경 경로"
  },
  metricsDisabled: "데이터 수집 비활성화",
  metricsEnabled: "데이터 수집 활성화",
  migrateFromExistingInstallation: "기존 설치에서 마이그레이션",
  migration: "마이그레이션",
  migrationOptional: "마이그레이션은 선택 사항입니다. 기존에 설치된 것이 없다면, 이 단계를 건너뛸 수 있습니다.",
  migrationSourcePathDescription: "기존에 설치된 ComfyUI가 있으면, 기존 사용자 파일과 모델을 새 설치본으로 복사하거나 링크 할 수 있습니다. 기존의 ComfyUI 설치는 영향을 받지 않습니다.",
  moreInfo: "더 많은 정보를 원하시면, 다음을 읽어주세요",
  nonDefaultDrive: "ComfyUI를 시스템 드라이브(예: C:\\)에 설치하십시오. 다른 파일 시스템을 가진 드라이브는 예측할 수 없는 문제를 일으킬 수 있습니다. 설치 후에는 모델 및 기타 파일을 다른 드라이브에 저장할 수 있습니다.",
  parentMissing: "경로가 존재하지 않습니다 - 먼저 포함하는 디렉토리를 생성하세요",
  pathExists: "디렉토리가 이미 존재합니다 - 모든 데이터를 백업했는지 확인해 주세요",
  pathValidationFailed: "경로 유효성 검사 실패",
  privacyPolicy: "개인정보 보호정책",
  selectItemsToMigrate: "마이그레이션 항목 선택",
  settings: {
    allowMetrics: "사용 통계",
    allowMetricsDescription: "익명의 사용 통계를 보내 ComfyUI를 개선하는 데 도움을 줍니다. 개인 정보나 워크플로 내용은 수집되지 않습니다.",
    autoUpdate: "자동 업데이트",
    autoUpdateDescription: "업데이트가 가능해지면 자동으로 다운로드하고 설치합니다. 업데이트가 설치되기 전에 항상 알림을 받습니다.",
    checkingMirrors: "Python 미러에 대한 네트워크 액세스 확인 중...",
    dataCollectionDialog: {
      collect: {
        errorReports: "오류 메시지 및 스택 추적",
        systemInfo: "하드웨어, OS 유형, 앱 버전",
        userJourneyEvents: "사용자 행동 흐름 이벤트"
      },
      doNotCollect: {
        customNodeConfigurations: "커스텀 노드 구성",
        fileSystemInformation: "파일 시스템 정보",
        personalInformation: "개인 정보",
        workflowContents: "워크플로 내용"
      },
      title: "데이터 수집 안내",
      viewFullPolicy: "전체 정책 보기",
      whatWeCollect: "수집하는 정보:",
      whatWeDoNotCollect: "수집하지 않는 정보:"
    },
    errorUpdatingConsent: "데이터 수집 동의 설정 업데이트 오류",
    errorUpdatingConsentDetail: "데이터 수집 동의 설정 업데이트에 실패했습니다",
    learnMoreAboutData: "데이터 수집에 대해 더 알아보기",
    mirrorSettings: "미러 URL 설정",
    mirrorsReachable: "Python 미러에 대한 네트워크 액세스가 좋습니다",
    mirrorsUnreachable: "일부 Python 미러에 대한 네트워크 접근이 나쁩니다",
    pypiMirrorPlaceholder: "PyPI 미러 URL 입력",
    pythonMirrorPlaceholder: "Python 미러 URL 입력"
  },
  systemLocations: "시스템 위치",
  unhandledError: "알 수 없는 오류",
  updateConsent: "이전에 충돌 보고에 동의하셨습니다. 이제 버그를 식별하고 앱을 개선하기 위해 이벤트 기반 통계 정보의 추적을 시작합니다. 개인을 식별할 수 있는 정보는 수집되지 않습니다."
};
const issueReport$2 = {
  contactFollowUp: "추적 조사를 위해 연락해 주세요",
  contactSupportDescription: "아래 양식에 보고 내용을 작성해 주세요",
  contactSupportTitle: "지원팀에 문의하기",
  describeTheProblem: "문제를 설명해 주세요",
  email: "이메일",
  feedbackTitle: "피드백을 제공함으로써 ComfyUI를 개선하는 데 도움을 주십시오",
  helpFix: "이 문제 해결에 도움을 주세요",
  helpTypes: {
    billingPayments: "결제 / 지불",
    bugReport: "버그 신고",
    giveFeedback: "피드백 제공",
    loginAccessIssues: "로그인 / 접근 문제",
    somethingElse: "기타"
  },
  notifyResolve: "해결되었을 때 알려주세요",
  provideAdditionalDetails: "추가 세부 사항 제공 (선택 사항)",
  provideEmail: "이메일을 알려주세요 (선택 사항)",
  rating: "평가",
  selectIssue: "문제를 선택하세요",
  stackTrace: "스택 추적",
  submitErrorReport: "오류 보고서 제출 (선택 사항)",
  systemStats: "시스템 통계",
  validation: {
    invalidEmail: "유효한 이메일 주소를 입력해 주세요",
    maxLength: "메시지가 너무 깁니다",
    selectIssueType: "문제 유형을 선택해 주세요"
  },
  whatCanWeInclude: "보고서에 포함할 내용을 지정하세요",
  whatDoYouNeedHelpWith: "어떤 도움이 필요하신가요?"
};
const load3d$2 = {
  applyingTexture: "텍스처 적용 중...",
  backgroundColor: "배경색",
  camera: "카메라",
  clearRecording: "녹화 지우기",
  edgeThreshold: "엣지 임계값",
  "export": "내보내기",
  exportModel: "모델 내보내기",
  exportRecording: "녹화 내보내기",
  exportingModel: "모델 내보내기 중...",
  fov: "FOV",
  light: "빛",
  lightIntensity: "조명 강도",
  loadingModel: "3D 모델 로딩 중...",
  materialMode: "재질 모드",
  materialModes: {
    depth: "깊이",
    lineart: "라인아트",
    normal: "노멀(normal)",
    original: "원본",
    wireframe: "와이어프레임"
  },
  model: "모델",
  previewOutput: "출력 미리보기",
  removeBackgroundImage: "배경 이미지 제거",
  resizeNodeMatchOutput: "노드 크기를 출력에 맞추기",
  scene: "장면",
  showGrid: "그리드 표시",
  startRecording: "녹화 시작",
  stopRecording: "녹화 중지",
  switchCamera: "카메라 전환",
  switchingMaterialMode: "재질 모드 전환 중...",
  upDirection: "위 방향",
  uploadBackgroundImage: "배경 이미지 업로드",
  uploadTexture: "텍스처 업로드"
};
const maintenance$2 = {
  None: "없음",
  OK: "확인",
  Skipped: "건너뜀",
  allOk: "문제가 발견되지 않았습니다.",
  confirmTitle: "확실합니까?",
  consoleLogs: "콘솔 로그",
  detected: "감지됨",
  error: {
    cannotContinue: "계속할 수 없습니다 - 오류가 남아 있습니다",
    defaultDescription: "유지 보수 작업을 실행하는 동안 오류가 발생했습니다.",
    taskFailed: "작업 실행에 실패했습니다.",
    toastTitle: "작업 오류"
  },
  refreshing: "새로 고침 중",
  showManual: "유지 보수 작업 보기",
  status: "상태",
  terminalDefaultMessage: "문제 해결 명령을 실행하면 출력이 여기에 표시됩니다.",
  title: "유지 보수"
};
const manager$2 = {
  changingVersion: "{from}에서 {to}(으)로 버전 변경 중",
  createdBy: "작성자",
  dependencies: "의존성",
  discoverCommunityContent: "커뮤니티에서 만든 노드 팩 및 확장 프로그램을 찾아보세요...",
  downloads: "다운로드",
  errorConnecting: "Comfy Node Registry에 연결하는 중 오류가 발생했습니다.",
  failed: "실패 ({count})",
  filter: {
    disabled: "비활성화",
    enabled: "활성화",
    nodePack: "노드 팩"
  },
  inWorkflow: "워크플로우 내",
  infoPanelEmpty: "정보를 보려면 항목을 클릭하세요",
  installSelected: "선택한 항목 설치",
  installationQueue: "설치 대기열",
  lastUpdated: "마지막 업데이트",
  latestVersion: "최신",
  license: "라이선스",
  loadingVersions: "버전 로딩 중...",
  nightlyVersion: "최신 테스트 버전(nightly)",
  noDescription: "설명이 없습니다",
  noNodesFound: "노드를 찾을 수 없습니다",
  noNodesFoundDescription: "팩의 노드를 파싱할 수 없거나, 팩이 프론트엔드 확장만을 가지고 있어서 노드가 없습니다.",
  noResultsFound: "검색과 일치하는 결과가 없습니다.",
  nodePack: "노드 팩",
  packsSelected: "선택한 노드 팩",
  repository: "저장소",
  restartToApplyChanges: "변경 사항을 적용하려면 ComfyUI를 재시작해 주세요",
  searchPlaceholder: "검색",
  selectVersion: "버전 선택",
  sort: {
    created: "최신",
    downloads: "가장 인기 있는",
    publisher: "배포자",
    updated: "최근 업데이트"
  },
  status: {
    active: "활성",
    banned: "차단됨",
    deleted: "삭제됨",
    flagged: "검토 대상",
    pending: "대기 중",
    unknown: "알 수 없음"
  },
  title: "사용자 정의 노드 관리자",
  totalNodes: "총 노드",
  tryAgainLater: "나중에 다시 시도해 주세요.",
  tryDifferentSearch: "다른 검색어를 시도해 주세요.",
  uninstall: "제거",
  uninstallSelected: "선택 항목 제거",
  uninstalling: "제거 중",
  update: "업데이트",
  updatingAllPacks: "모든 패키지 업데이트 중",
  version: "버전"
};
const maskEditor$2 = {
  "Apply to Whole Image": "전체 이미지에 적용",
  "Brush Settings": "브러시 설정",
  "Brush Shape": "브러시 모양",
  Clear: "지우기",
  "Color Select Settings": "색상 선택 설정",
  "Fill Opacity": "채우기 투명도",
  Hardness: "경도",
  "Image Layer": "이미지 레이어",
  Invert: "반전",
  Layers: "레이어",
  "Live Preview": "실시간 미리보기",
  "Mask Layer": "마스크 레이어",
  "Mask Opacity": "마스크 투명도",
  "Mask Tolerance": "마스크 허용 오차",
  Method: "방법",
  Opacity: "투명도",
  "Paint Bucket Settings": "페인트 버킷 설정",
  "Reset to Default": "기본값으로 재설정",
  "Selection Opacity": "선택 투명도",
  "Smoothing Precision": "스무딩 정밀도",
  "Stop at mask": "마스크에서 중지",
  Thickness: "두께",
  Tolerance: "허용 오차"
};
const menu$2 = {
  autoQueue: "자동 실행 대기열",
  batchCount: "배치 수",
  batchCountTooltip: "워크플로 작업을 실행 대기열에 반복 추가할 횟수",
  clear: "워크플로 비우기",
  clipspace: "클립스페이스 열기",
  disabled: "비활성화됨",
  disabledTooltip: "워크플로 작업을 자동으로 실행 대기열에 추가하지 않습니다.",
  execute: "실행",
  hideMenu: "메뉴 숨기기",
  instant: "즉시",
  instantTooltip: "워크플로 실행이 완료되면 즉시 실행 대기열에 추가합니다.",
  interrupt: "현재 실행 취소",
  onChange: "변경 시",
  onChangeTooltip: "변경이 있는 경우에만 워크플로를 실행 대기열에 추가합니다.",
  refresh: "노드 정의 새로 고침",
  resetView: "캔버스 보기 재설정",
  run: "실행",
  runWorkflow: "워크플로우 실행 (시프트 키와 함께 클릭시 가장 먼저 실행)",
  runWorkflowFront: "워크플로우 실행 (가장 먼저 실행)",
  showMenu: "메뉴 표시",
  toggleBottomPanel: "하단 패널 전환"
};
const menuLabels$2 = {
  "About ComfyUI": "ComfyUI에 대하여",
  "Browse Templates": "템플릿 탐색",
  "Bypass/Unbypass Selected Nodes": "선택한 노드 우회/우회 해제",
  "Canvas Toggle Link Visibility": "캔버스 토글 링크 가시성",
  "Canvas Toggle Lock": "캔버스 토글 잠금",
  "Check for Updates": "업데이트 확인",
  "Clear Pending Tasks": "보류 중인 작업 제거하기",
  "Clear Workflow": "워크플로 지우기",
  Clipspace: "클립스페이스",
  "Close Current Workflow": "현재 워크플로 닫기",
  "Collapse/Expand Selected Nodes": "선택한 노드 축소/확장",
  "Comfy-Org Discord": "Comfy-Org 디스코드",
  "ComfyUI Docs": "ComfyUI 문서",
  "ComfyUI Forum": "ComfyUI 포럼",
  "ComfyUI Issues": "ComfyUI 이슈 페이지",
  "Contact Support": "고객 지원 문의",
  "Convert selected nodes to group node": "선택한 노드를 그룹 노드로 변환",
  "Custom Nodes Manager": "사용자 정의 노드 관리자",
  "Delete Selected Items": "선택한 항목 삭제",
  "Desktop User Guide": "데스크톱 사용자 가이드",
  "Duplicate Current Workflow": "현재 워크플로 복제",
  Edit: "편집",
  Export: "내보내기",
  "Export (API)": "내보내기 (API)",
  "Fit Group To Contents": "그룹을 내용에 맞게 조정",
  "Fit view to selected nodes": "선택한 노드에 맞게 보기 조정",
  "Give Feedback": "피드백 제공",
  "Group Selected Nodes": "선택한 노드 그룹화",
  Help: "도움말",
  Interrupt: "중단",
  "Load Default Workflow": "기본 워크플로 불러오기",
  "Manage group nodes": "그룹 노드 관리",
  "Mute/Unmute Selected Nodes": "선택한 노드 활성화/비활성화",
  New: "새로 만들기",
  "Next Opened Workflow": "다음 열린 워크플로",
  Open: "열기",
  "Open Custom Nodes Folder": "사용자 정의 노드 폴더 열기",
  "Open DevTools": "개발자 도구 열기",
  "Open Inputs Folder": "입력 폴더 열기",
  "Open Logs Folder": "로그 폴더 열기",
  "Open Models Folder": "모델 폴더 열기",
  "Open Outputs Folder": "출력 폴더 열기",
  "Open Sign In Dialog": "로그인 대화 상자 열기",
  "Open extra_model_paths_yaml": "extra_model_paths.yaml 열기",
  "Pin/Unpin Selected Items": "선택한 항목 고정/고정 해제",
  "Pin/Unpin Selected Nodes": "선택한 노드 고정/고정 해제",
  "Previous Opened Workflow": "이전 열린 워크플로",
  "Queue Prompt": "실행 대기열에 프롬프트 추가",
  "Queue Prompt (Front)": "실행 대기열 맨 앞에 프롬프트 추가",
  "Queue Selected Output Nodes": "선택한 출력 노드 대기열에 추가",
  Quit: "종료",
  Redo: "다시 실행",
  "Refresh Node Definitions": "노드 정의 새로 고침",
  Reinstall: "재설치",
  "Reset View": "보기 초기화",
  "Resize Selected Nodes": "선택된 노드 크기 조정",
  Restart: "재시작",
  Save: "저장",
  "Save As": "다른 이름으로 저장",
  "Show Settings Dialog": "설정 대화상자 표시",
  "Sign Out": "로그아웃",
  "Toggle Bottom Panel": "하단 패널 전환",
  "Toggle Focus Mode": "포커스 모드 전환",
  "Toggle Logs Bottom Panel": "로그 하단 패널 전환",
  "Toggle Model Library Sidebar": "모델 라이브러리 사이드바 전환",
  "Toggle Node Library Sidebar": "노드 라이브러리 사이드바 전환",
  "Toggle Progress Dialog": "진행 상황 대화 상자 전환",
  "Toggle Queue Sidebar": "실행 대기열 사이드바 전환",
  "Toggle Search Box": "검색 상자 전환",
  "Toggle Terminal Bottom Panel": "터미널 하단 패널 전환",
  "Toggle Theme (Dark/Light)": "테마 전환 (어두운/밝은)",
  "Toggle Workflows Sidebar": "워크플로 사이드바 전환",
  Undo: "실행 취소",
  "Ungroup selected group nodes": "선택한 그룹 노드 그룹 해제",
  Workflow: "워크플로",
  "Zoom In": "확대",
  "Zoom Out": "축소"
};
const missingModelsDialog$2 = {
  doNotAskAgain: "다시 보지 않기",
  missingModels: "모델이 없습니다",
  missingModelsMessage: "그래프를 로드할 때 다음 모델을 찾을 수 없었습니다"
};
const nodeCategories$2 = {
  "3d": "3d",
  "3d_models": "3D 모델",
  BFL: "BFL",
  Ideogram: "Ideogram",
  Kling: "Kling",
  Luma: "Luma",
  MiniMax: "MiniMax",
  OpenAI: "OpenAI",
  Pika: "Pika",
  PixVerse: "PixVerse",
  Recraft: "Recraft",
  "Stability AI": "Stability AI",
  Veo: "Veo",
  _for_testing: "_테스트용",
  advanced: "고급",
  animation: "애니메이션",
  api: "API",
  "api node": "api 노드",
  attention_experiments: "어텐션 실험",
  audio: "오디오",
  batch: "배치",
  clip: "클립",
  combine: "결합",
  compositing: "합성",
  "cond pair": "조건 쌍",
  "cond single": "단일 조건",
  conditioning: "조건화",
  controlnet: "컨트롤넷",
  create: "생성",
  custom_sampling: "사용자 정의 샘플링",
  debug: "디버그",
  deprecated: "지원 중단",
  flux: "flux",
  gligen: "글리젠",
  guidance: "가이드",
  guiders: "가이드",
  hooks: "후크",
  image: "이미지",
  inpaint: "인페인팅",
  instructpix2pix: "InstructPix2Pix",
  latent: "잠재 데이터",
  loaders: "로더",
  lotus: "lotus",
  ltxv: "ltxv",
  mask: "마스크",
  model: "모델",
  model_merging: "모델 병합",
  model_patches: "모델 패치",
  model_specific: "모델 특정",
  noise: "노이즈",
  operations: "연산",
  photomaker: "포토메이커",
  postprocessing: "후처리",
  preprocessors: "전처리기",
  primitive: "기본 입력",
  samplers: "샘플러",
  sampling: "샘플링",
  schedulers: "스케줄러",
  scheduling: "스케줄링",
  sd: "sd",
  sd3: "sd3",
  sigmas: "시그마",
  stable_cascade: "Stable Cascade",
  style_model: "스타일 모델",
  transform: "변환",
  unet: "UNet",
  upscale_diffusion: "업스케일 확산",
  upscaling: "업스케일링",
  utils: "유틸리티",
  v1: "v1",
  v2: "v2",
  v3: "v3",
  video: "비디오",
  video_models: "비디오 모델"
};
const nodeTemplates$2 = {
  enterName: "이름 입력",
  saveAsTemplate: "템플릿으로 저장"
};
const notSupported$2 = {
  "continue": "계속",
  continueTooltip: "내 장치가 지원되는 장치가 확실합니다.",
  learnMore: "자세히 알아보기",
  message: "다음 장치만 지원됩니다:",
  reportIssue: "이슈 보고",
  supportedDevices: {
    macos: "MacOS (M1 이상)",
    windows: "Windows (CUDA 지원 Nvidia GPU)"
  },
  title: "이 장치는 지원되지 않습니다."
};
const selectionToolbox$2 = {
  executeButton: {
    disabledTooltip: "선택된 출력 노드가 없습니다",
    tooltip: "선택한 출력 노드에 실행 (주황색 테두리로 강조 표시됨)"
  }
};
const serverConfig$2 = {
  modifiedConfigs: "다음 서버 구성을 수정했습니다. 변경 사항을 적용하려면 다시 시작하세오.",
  restart: "다시 시작",
  revertChanges: "변경 사항 되돌리기"
};
const serverConfigCategories$2 = {
  Attention: "어텐션",
  CUDA: "CUDA",
  Cache: "캐시",
  Directories: "디렉토리",
  General: "일반",
  Inference: "추론",
  Memory: "메모리",
  Network: "네트워크",
  Preview: "미리보기"
};
const serverConfigItems$2 = {
  "cache-classic": {
    name: "예전 방식의 공격적 캐시 시스템 사용"
  },
  "cache-lru": {
    name: "최대 N개 노드 결과를 캐시하는 LRU(Least Recently Used) 캐싱 사용.",
    tooltip: "RAM/VRAM 사용량이 증가합니다"
  },
  "cpu-vae": {
    name: "CPU에서 VAE 실행"
  },
  "cross-attention-method": {
    name: "교차 어텐션 방법"
  },
  "cuda-device": {
    name: "사용할 CUDA 장치 번호"
  },
  "cuda-malloc": {
    name: "메모리 할당에 CUDA malloc 사용"
  },
  "default-hashing-function": {
    name: "모델 파일의 기본 해싱 함수"
  },
  deterministic: {
    name: "사용 가능한 경우 pytorch가 느리지만 결정론적인 알고리즘을 사용하도록 설정합니다.",
    tooltip: "주의: 이 옵션이 항상 결정론적 이미지를 보장하지는 않습니다."
  },
  directml: {
    name: "DirectML 장치 번호"
  },
  "disable-all-custom-nodes": {
    name: "모든 사용자 정의 노드 로드 비활성화."
  },
  "disable-ipex-optimize": {
    name: "IPEX 최적화 비활성화"
  },
  "disable-metadata": {
    name: "파일에 프롬프트(워크플로) 메타데이터 저장 비활성화."
  },
  "disable-smart-memory": {
    name: "스마트 메모리 관리 비활성화",
    tooltip: "ComfyUI가 모델을 VRAM에 유지하는 대신 시스템 메모리로 공격적으로 오프로드하도록 강제합니다."
  },
  "disable-xformers": {
    name: "xFormers 최적화 비활성화"
  },
  "dont-print-server": {
    name: "서버 출력을 콘솔에 출력하지 않음."
  },
  "dont-upcast-attention": {
    name: "어텐션 업캐스트 방지"
  },
  "enable-cors-header": {
    name: 'CORS 헤더 활성화: 모든 출처에 대해 "*" 사용 또는 도메인 지정'
  },
  fast: {
    name: "테스트되지 않고 품질 저하 가능성이 있는 실험적 최적화 기능을 활성화 합니다."
  },
  "force-channels-last": {
    name: "channels-last 메모리 형식 강제 적용"
  },
  "force-upcast-attention": {
    name: "어텐션 업캐스트 강제 적용"
  },
  "global-precision": {
    name: "전역 부동 소수점 정밀도",
    tooltip: "전역 부동 소수점 정밀도"
  },
  "input-directory": {
    name: "입력 디렉토리"
  },
  listen: {
    name: "호스트: 접속될 IP 주소"
  },
  "log-level": {
    name: "로그 출력 수준"
  },
  "max-upload-size": {
    name: "최대 업로드 크기 (MB)"
  },
  "output-directory": {
    name: "출력 디렉토리"
  },
  port: {
    name: "포트: 접속될 포트"
  },
  "preview-method": {
    name: "잠재 데이터 미리보기 방법"
  },
  "preview-size": {
    name: "미리보기 최대 이미지 크기"
  },
  "reserve-vram": {
    name: "예약된 VRAM (GB)",
    tooltip: "OS/기타 소프트웨어에서 사용하기 위해 예약할 VRAM의 양을 GB 단위로 설정합니다. 기본적으로 OS에 따라 일부 양이 예약됩니다."
  },
  "text-encoder-precision": {
    name: "텍스트 인코더 정밀도",
    tooltip: "텍스트 인코더 정밀도"
  },
  "tls-certfile": {
    name: "TLS 인증서 파일: HTTPS용 TLS 인증서 파일 경로"
  },
  "tls-keyfile": {
    name: "TLS 키 파일: HTTPS용 TLS 키 파일 경로"
  },
  "unet-precision": {
    name: "UNET 정밀도",
    tooltip: "UNET 정밀도"
  },
  "vae-precision": {
    name: "VAE 정밀도",
    tooltip: "VAE 정밀도"
  },
  "vram-management": {
    name: "VRAM 관리 모드"
  }
};
const serverStart$2 = {
  openLogs: "로그 열기",
  process: {
    error: "ComfyUI Desktop을 시작할 수 없습니다",
    "initial-state": "로딩 중...",
    "python-setup": "Python 환경 설정 중...",
    ready: "마무리 중...",
    "starting-server": "ComfyUI 서버 시작 중..."
  },
  reportIssue: "문제 보고",
  showTerminal: "터미널 보기",
  troubleshoot: "문제 해결"
};
const settingsCategories$2 = {
  "3D": "3D",
  About: "정보",
  Appearance: "모양",
  BrushAdjustment: "브러시 조정",
  Camera: "카메라",
  Canvas: "캔버스",
  ColorPalette: "색상 팔레트",
  Comfy: "Comfy",
  "Comfy-Desktop": "Comfy-Desktop",
  ContextMenu: "컨텍스트 메뉴",
  Credits: "크레딧",
  CustomColorPalettes: "사용자 정의 색상 팔레트",
  DevMode: "개발자 모드",
  EditTokenWeight: "토큰 가중치 편집",
  Extension: "확장",
  General: "일반",
  Graph: "그래프",
  Group: "그룹",
  Keybinding: "키 바인딩",
  Light: "라이트",
  Link: "링크",
  LinkRelease: "링크 해제",
  LiteGraph: "LiteGraph",
  "Load 3D": "3D 불러오기",
  Locale: "언어 설정",
  "Mask Editor": "마스크 편집기",
  Menu: "메뉴",
  ModelLibrary: "모델 라이브러리",
  NewEditor: "새 편집기",
  Node: "노드",
  "Node Search Box": "노드 검색 상자",
  "Node Widget": "노드 위젯",
  NodeLibrary: "노드 라이브러리",
  Pointer: "포인터",
  Queue: "실행 대기열",
  QueueButton: "실행 대기열 버튼",
  Reroute: "경유점",
  RerouteBeta: "경유점 (베타)",
  Scene: "장면",
  Server: "서버",
  "Server-Config": "서버 구성",
  Settings: "설정",
  Sidebar: "사이드바",
  "Tree Explorer": "트리 탐색기",
  UV: "UV",
  User: "사용자",
  Validation: "검증",
  Window: "창",
  Workflow: "워크플로"
};
const sideToolbar$2 = {
  browseTemplates: "예제 템플릿 탐색",
  downloads: "다운로드",
  logout: "로그아웃",
  modelLibrary: "모델 라이브러리",
  newBlankWorkflow: "새 빈 워크플로 만들기",
  nodeLibrary: "노드 라이브러리",
  nodeLibraryTab: {
    sortOrder: "정렬 순서"
  },
  openWorkflow: "로컬 파일 시스템에서 워크플로 열기",
  queue: "실행 대기열",
  queueTab: {
    backToAllTasks: "모든 작업으로 돌아가기",
    clearPendingTasks: "보류 중인 작업 지우기",
    containImagePreview: "이미지 미리보기 채우기",
    coverImagePreview: "이미지 미리보기 맞추기",
    filter: "출력 필터",
    filters: {
      hideCached: "캐시 숨기기",
      hideCanceled: "취소된 작업 숨기기"
    },
    showFlatList: "평면 목록 표시"
  },
  themeToggle: "테마 전환",
  workflowTab: {
    confirmDelete: "정말로 이 워크플로를 삭제하시겠습니까?",
    confirmDeleteTitle: "워크플로 삭제",
    confirmOverwrite: "아래 파일이 이미 존재합니다. 덮어쓰시겠습니까?",
    confirmOverwriteTitle: "기존 파일 덮어쓰기?",
    deleteFailed: "워크플로 삭제를 시도했으나 실패했습니다.",
    deleteFailedTitle: "삭제 실패",
    deleted: "워크플로가 삭제되었습니다.",
    dirtyClose: "아래 파일들이 변경되었습니다. 닫기 전에 저장하시겠습니까?",
    dirtyCloseHint: "프롬프트 없이 닫으려면 Shift를 누르세요",
    dirtyCloseTitle: "변경 사항 저장",
    workflowTreeType: {
      bookmarks: "북마크",
      browse: "찾아보기",
      open: "열기"
    }
  },
  workflows: "워크플로"
};
const tabMenu$2 = {
  addToBookmarks: "북마크에 추가",
  closeOtherTabs: "다른 탭 닫기",
  closeTab: "탭 닫기",
  closeTabsToLeft: "왼쪽 탭 닫기",
  closeTabsToRight: "오른쪽 탭 닫기",
  duplicateTab: "탭 복제",
  removeFromBookmarks: "북마크에서 제거"
};
const templateWorkflows$2 = {
  category: {
    "3D": "3D",
    "Area Composition": "영역 구성",
    Audio: "오디오",
    Basics: "기본",
    "ComfyUI Examples": "ComfyUI 예시",
    ControlNet: "컨트롤넷",
    "Custom Nodes": "사용자 정의 노드",
    Flux: "FLUX",
    Image: "이미지",
    "Image API": "이미지 API",
    Upscaling: "업스케일링",
    Video: "비디오",
    "Video API": "비디오 API"
  },
  template: {
    "3D": {
      "hunyuan-3d-multiview-elf": "Hunyuan3D 다중뷰",
      "hunyuan-3d-turbo": "Hunyuan3D 터보",
      "hunyuan3d-non-multiview-train": "Hunyuan3D",
      stable_zero123_example: "스테이블 제로123"
    },
    "Area Composition": {
      area_composition: "영역 구성",
      area_composition_reversed: "역 영역 구성",
      area_composition_square_area_for_subject: "주제를 위한 사각형 영역 구성"
    },
    Audio: {
      stable_audio_example: "스테이블 오디오"
    },
    Basics: {
      "default": "이미지 생성",
      embedding_example: "임베딩 예제",
      gligen_textbox_example: "글리젠 텍스트박스 예제",
      image2image: "이미지로 이미지 생성 예제",
      inpain_model_outpainting: "인페인트 모델 아웃페인팅",
      inpaint_example: "인페인트",
      lora: "로라",
      lora_multiple: "다중 로라"
    },
    ControlNet: {
      "2_pass_pose_worship": "2 패스 경배 포즈",
      controlnet_example: "컨트롤넷",
      depth_controlnet: "깊이 컨트롤넷",
      depth_t2i_adapter: "깊이 T2I 어댑터",
      mixing_controlnets: "컨트롤넷 섞기"
    },
    Flux: {
      flux_canny_model_example: "FLUX 캐니 모델 예제",
      flux_depth_lora_example: "FLUX 깊이 로라 예제",
      flux_dev_checkpoint_example: "FLUX Dev 예제",
      flux_fill_inpaint_example: "FLUX 인페인트 예제",
      flux_fill_outpaint_example: "FLUX 아웃페인트 예제",
      flux_redux_model_example: "FLUX Redux 모델 예제",
      flux_schnell: "FLUX Schnell"
    },
    Image: {
      hidream_i1_dev: "HiDream I1 Dev",
      hidream_i1_fast: "HiDream I1 Fast",
      hidream_i1_full: "HiDream I1 Full",
      sd3_5_large_blur: "SD3.5 Large 블러 컨트롤넷",
      sd3_5_large_canny_controlnet_example: "SD3.5 Large 캐니 컨트롤넷",
      sd3_5_large_depth: "SD3.5 Large 깊이 컨트롤넷",
      sd3_5_simple_example: "간단한 SD3.5 예제",
      sdxl_refiner_prompt_example: "SDXL 리파이너 프롬프트",
      sdxl_revision_text_prompts: "SDXL Revision 텍스트 프롬프트",
      sdxl_revision_zero_positive: "SDXL Revision Zero Positive",
      sdxl_simple_example: "간단한 SDXL 예제",
      sdxlturbo_example: "SDXL 터보"
    },
    "Image API": {
      "api-openai-dall-e-2-inpaint": "Dall-E 2 인페인트",
      "api-openai-dall-e-2-t2i": "Dall-E 2 텍스트 투 이미지",
      "api-openai-dall-e-3-t2i": "Dall-E 3 텍스트 투 이미지",
      api_bfl_flux_pro_t2i: "BFL Flux 1.1[pro] Ultra 텍스트 투 이미지",
      api_ideogram_v3_t2i: "Ideogram V3 텍스트 투 이미지",
      api_luma_photon_i2i: "Luma Photon 이미지 투 이미지",
      api_luma_photon_style_ref: "Luma Photon 스타일 참조",
      api_openai_image_1_i2i: "OpenAI Image-1 이미지 투 이미지",
      api_openai_image_1_inpaint: "OpenAI Image-1 인페인트",
      api_openai_image_1_multi_inputs: "OpenAI Image-1 멀티 입력",
      api_openai_image_1_t2i: "OpenAI Image-1 텍스트 투 이미지",
      api_recraft_image_gen_with_color_control: "Recraft 색상 제어 이미지 생성",
      api_recraft_image_gen_with_style_control: "Recraft 스타일 제어 이미지 생성",
      api_recraft_vector_gen: "Recraft 벡터 생성",
      api_stability_sd3_t2i: "Stability AI Stable Image Ultra 텍스트 투 이미지"
    },
    Upscaling: {
      esrgan_example: "ESRGAN",
      hiresfix_esrgan_workflow: "HiresFix ESRGAN 워크플로우",
      hiresfix_latent_workflow: "HiresFix Latent 워크플로우",
      latent_upscale_different_prompt_model: "Latent Upscale 다른 프롬프트 모델"
    },
    Video: {
      hunyuan_video_text_to_video: "텍스트 -> 비디오 (Hunyuan Video)",
      image_to_video: "이미지 -> 동영상",
      image_to_video_wan: "Wan 2.1 이미지에서 비디오로",
      ltxv_image_to_video: "이미지 -> 동영상 (LTXV)",
      ltxv_text_to_video: "텍스트 -> 동영상 (LTXV)",
      mochi_text_to_video_example: "텍스트 -> 동영상 (Mochi)",
      text_to_video_wan: "Wan 2.1 텍스트를 비디오로",
      txt_to_image_to_video: "텍스트 -> 이미지 -> 동영상",
      wan2_1_fun_control: "Wan 2.1 컨트롤넷",
      wan2_1_fun_inp: "Wan 2.1 인페인트"
    },
    "Video API": {
      api_hailuo_minimax_i2v: "MiniMax 이미지 투 비디오",
      api_kling_i2v: "Kling 이미지 투 비디오",
      api_luma_i2v: "Luma 이미지 투 비디오",
      api_pika_scene: "Pika 장면: 이미지 투 비디오",
      api_pixverse_t2v: "PixVerse 텍스트 투 비디오",
      api_pixverse_template_i2v: "PixVerse Template Effects: 이미지 투 비디오",
      api_veo2_i2v: "Veo2 이미지 투 비디오"
    }
  },
  templateDescription: {
    "3D": {
      "hunyuan-3d-multiview-elf": "Hunyuan3D 2mv로 여러 뷰에서 모델을 생성합니다.",
      "hunyuan-3d-turbo": "Hunyuan3D 2mv turbo로 여러 뷰에서 모델을 생성합니다.",
      "hunyuan3d-non-multiview-train": "Hunyuan3D 2.0으로 단일 뷰에서 모델을 생성합니다.",
      stable_zero123_example: "단일 이미지에서 3D 뷰를 생성합니다."
    },
    "Area Composition": {
      area_composition: "영역을 통해 이미지 구성을 제어합니다.",
      area_composition_reversed: "영역 구성 워크플로우를 반대로 적용합니다.",
      area_composition_square_area_for_subject: "일관된 피사체 배치를 만듭니다."
    },
    Audio: {
      stable_audio_example: "텍스트 설명으로 오디오를 생성합니다."
    },
    Basics: {
      "default": "텍스트 설명으로 이미지를 생성합니다.",
      embedding_example: "일관된 스타일을 위해 텍스트 인버전을 사용합니다.",
      gligen_textbox_example: "객체의 위치와 크기를 지정합니다.",
      image2image: "텍스트 프롬프트를 사용하여 기존 이미지를 변환합니다.",
      inpain_model_outpainting: "이미지의 원래 경계를 넘어 확장합니다.",
      inpaint_example: "이미지의 특정 부분을 자연스럽게 편집합니다.",
      lora: "특정 스타일이나 주제를 위해 LoRA 모델을 적용합니다.",
      lora_multiple: "여러 LoRA 모델을 결합하여 독특한 결과를 만듭니다."
    },
    ControlNet: {
      "2_pass_pose_worship": "포즈 참조로 이미지를 생성합니다.",
      controlnet_example: "참조 이미지를 사용해 이미지 생성을 제어합니다.",
      depth_controlnet: "깊이 인식 이미지 생성을 합니다.",
      depth_t2i_adapter: "T2I 어댑터로 깊이 인식 이미지를 빠르게 생성합니다.",
      mixing_controlnets: "여러 ControlNet 모델을 결합합니다."
    },
    Flux: {
      flux_canny_model_example: "검출된 경계선으로 이미지를 생성합니다.",
      flux_depth_lora_example: "깊이 인식 LoRA 를 이용해 이미지를 생성합니다.",
      flux_dev_checkpoint_example: "FLUX Dev 모델로 이미지를 생성합니다.",
      flux_fill_inpaint_example: "이미지의 누락된 부분을 채웁니다.",
      flux_fill_outpaint_example: "FLUX 아웃페인팅으로 이미지를 확장합니다.",
      flux_redux_model_example: "참조 이미지의 스타일을 가이드 이미지 생성에 적용합니다.",
      flux_schnell: "FLUX Schnell 모델로 이미지를 빠르게 생성합니다."
    },
    Image: {
      hidream_e1_full: "HiDream E1 모델로 이미지를 편집합니다.",
      hidream_i1_dev: "HiDream I1 Dev 모델로 이미지를 생성합니다.",
      hidream_i1_fast: "HiDream I1 Fast 모델로 이미지를 빠르게 생성합니다.",
      hidream_i1_full: "HiDream I1 Full 모델로 이미지를 생성합니다.",
      sd3_5_large_blur: "SD 3.5 모델로 흐릿한 참조 이미지에서 이미지를 생성합니다.",
      sd3_5_large_canny_controlnet_example: "Canny 에지 이미지를 통해 SD 3.5 모델 이미지 생성을 가이드합니다.",
      sd3_5_large_depth: "깊이 인식 이미지를 통해 SD 3.5 모델 이미지 생성을 가이드합니다.",
      sd3_5_simple_example: "SD 3.5 모델로 이미지를 생성합니다.",
      sdxl_refiner_prompt_example: "SDXL 결과물을 리파이너로 향상시킵니다.",
      sdxl_revision_text_prompts: "참조 이미지의 개념을 SDXL 이미지 생성에 적용합니다.",
      sdxl_revision_zero_positive: "참조 이미지와 함께 텍스트 프롬프트를 추가하여 SDXL 이미지 생성을 가이드합니다.",
      sdxl_simple_example: "SDXL 모델로 고품질 이미지를 생성합니다.",
      sdxlturbo_example: "SDXL Turbo 모델로 1 스텝으로 이미지를 생성합니다."
    },
    "Image API": {
      "api-openai-dall-e-2-inpaint": "Dall-E 2 API로 이미지를 인페인팅합니다.",
      "api-openai-dall-e-2-t2i": "Dall-E 2 API로 텍스트 설명에서 이미지를 생성합니다.",
      "api-openai-dall-e-3-t2i": "Dall-E 3 API로 텍스트 설명에서 이미지를 생성합니다.",
      api_bfl_flux_pro_t2i: "FLUX.1 [pro]의 뛰어난 프롬프트 반영, 시각적 품질, 이미지 디테일, 다양성으로 이미지를 생성합니다.",
      api_ideogram_v3_t2i: "고품질 이미지-프롬프트 일치, 포토리얼리즘, 텍스트 렌더링으로 이미지를 생성합니다. 전문가 수준의 로고, 홍보 포스터, 랜딩 페이지 컨셉, 제품 사진 등을 만드세요. 정교한 배경, 섬세한 조명과 색상, 사실적인 환경 디테일로 세련된 공간 구성을 손쉽게 제작할 수 있습니다.",
      api_luma_photon_i2i: "이미지와 프롬프트를 조합하여 이미지 생성을 가이드합니다.",
      api_luma_photon_style_ref: "정확한 제어로 스타일 참조를 적용하고 혼합합니다. Luma Photon은 각 참조 이미지의 본질을 포착하여, 전문적인 품질을 유지하면서 독특한 시각적 요소를 결합할 수 있습니다.",
      api_openai_image_1_i2i: "GPT Image 1 API로 이미지에서 이미지를 생성합니다.",
      api_openai_image_1_inpaint: "GPT Image 1 API로 이미지를 인페인팅합니다.",
      api_openai_image_1_multi_inputs: "GPT Image 1 API로 여러 입력을 사용해 이미지를 생성합니다.",
      api_openai_image_1_t2i: "GPT Image 1 API로 텍스트 설명에서 이미지를 생성합니다.",
      api_recraft_image_gen_with_color_control: "여러 이미지에 재사용할 맞춤 팔레트를 만들거나 각 사진마다 색상을 직접 선택하세요. 브랜드의 색상 팔레트에 맞추고, 독창적인 비주얼을 제작하세요.",
      api_recraft_image_gen_with_style_control: "시각적 예시로 스타일을 제어하고, 위치를 맞추며, 객체를 미세 조정하세요. 스타일을 저장 및 공유하여 브랜드 일관성을 유지할 수 있습니다.",
      api_recraft_vector_gen: "텍스트 프롬프트에서 Recraft의 AI 벡터 생성기로 벡터 이미지를 만드세요. 로고, 포스터, 아이콘 세트, 광고, 배너, 목업 등 최고의 품질의 벡터 아트를 제작할 수 있습니다. 선명하고 고품질의 SVG 파일로 디자인을 완성하세요. 앱이나 웹사이트를 위한 브랜드 벡터 일러스트를 몇 초 만에 만드세요.",
      api_stability_sd3_t2i: "1메가픽셀 해상도에서 전문가용 고품질 이미지를 생성합니다. 프롬프트 반영이 우수합니다."
    },
    Upscaling: {
      esrgan_example: "업스케일 모델로 이미지 품질을 향상합니다.",
      hiresfix_esrgan_workflow: "중간 단계에서 업스케일 모델을 사용합니다.",
      hiresfix_latent_workflow: "latent 공간에서 이미지 품질을 향상합니다.",
      latent_upscale_different_prompt_model: "업스케일과 프롬프트 변경을 여러 번에 걸쳐 적용합니다."
    },
    Video: {
      hunyuan_video_text_to_video: "Hunyuan 모델을 사용하여 비디오를 생성합니다.",
      image_to_video: "이미지를 애니메이션 비디오로 변환합니다.",
      image_to_video_wan: "이미지로부터 빠르게 비디오를 생성합니다.",
      ltxv_image_to_video: "정지 이미지를 비디오로 변환합니다.",
      ltxv_text_to_video: "텍스트 설명으로 비디오를 생성합니다.",
      mochi_text_to_video_example: "Mochi 모델로 비디오를 생성합니다.",
      text_to_video_wan: "텍스트 설명으로 빠르게 비디오를 생성합니다.",
      txt_to_image_to_video: "텍스트로 이미지를 생성한 후 비디오로 변환합니다.",
      wan2_1_flf2v_720_f16: "첫 프레임과 마지막 프레임을 제어하여 비디오를 생성합니다.",
      wan2_1_fun_control: "포즈, 깊이, 에지 등으로 비디오 생성을 가이드합니다.",
      wan2_1_fun_inp: "시작 및 종료 프레임으로 비디오를 생성합니다."
    },
    "Video API": {
      api_hailuo_minimax_i2v: "이미지와 텍스트로 정교한 비디오를 생성합니다. CGI 통합, 바이럴 AI 허깅 등 트렌디한 사진 효과도 포함됩니다. 다양한 비디오 스타일과 테마로 창의적인 비전을 실현하세요.",
      api_kling_i2v: "동작, 표정, 카메라 움직임에 대한 프롬프트 반영이 뛰어난 비디오를 생성합니다. 이제 복잡한 프롬프트와 연속 동작도 지원되어, 장면의 연출자가 될 수 있습니다.",
      api_luma_i2v: "정지 이미지를 즉시 고품질 애니메이션으로 만드세요.",
      api_pika_scene: "여러 이미지를 재료로 사용하여 모두를 포함하는 비디오를 생성합니다.",
      api_pixverse_t2v: "정확한 프롬프트 해석과 놀라운 비디오 다이내믹스로 비디오를 생성합니다.",
      api_pixverse_template_i2v: "정지 이미지를 동적 비디오로 변환하고 모션과 효과를 추가합니다.",
      api_veo2_i2v: "Google Veo2 API로 이미지에서 비디오를 생성합니다."
    }
  },
  title: "템플릿으로 시작하기"
};
const toastMessages$2 = {
  couldNotDetermineFileType: "파일 유형을 결정할 수 없습니다",
  dropFileError: "드롭된 항목을 처리할 수 없습니다: {error}",
  emptyCanvas: "빈 캔버스",
  errorCopyImage: "이미지 복사 오류: {error}",
  errorLoadingModel: "모델 로딩 오류",
  errorSaveSetting: "설정 {id} 저장 오류: {err}",
  failedToAccessBillingPortal: "결제 포털에 접근하지 못했습니다: {error}",
  failedToApplyTexture: "텍스처 적용에 실패했습니다",
  failedToCreateCustomer: "고객 생성에 실패했습니다: {error}",
  failedToDownloadFile: "파일 다운로드에 실패했습니다",
  failedToExportModel: "{format} 형식으로 모델 내보내기에 실패했습니다",
  failedToFetchBalance: "잔액을 가져오지 못했습니다: {error}",
  failedToFetchLogs: "서버 로그를 가져오는 데 실패했습니다",
  failedToInitiateCreditPurchase: "크레딧 구매를 시작하지 못했습니다: {error}",
  failedToPurchaseCredits: "크레딧 구매에 실패했습니다: {error}",
  fileLoadError: "{fileName}에서 워크플로우를 찾을 수 없습니다",
  fileUploadFailed: "파일 업로드에 실패했습니다",
  interrupted: "실행이 중단되었습니다",
  migrateToLitegraphReroute: "향후 버전에서는 Reroute 노드가 제거됩니다. LiteGraph 에서 자체 제공하는 경유점으로 변환하려면 클릭하세요.",
  no3dScene: "텍스처를 적용할 3D 장면이 없습니다",
  no3dSceneToExport: "내보낼 3D 장면이 없습니다",
  noTemplatesToExport: "내보낼 템플릿이 없습니다",
  nodeDefinitionsUpdated: "노드 정의가 업데이트되었습니다",
  nothingToGroup: "그룹화할 항목이 없습니다",
  nothingToQueue: "대기열에 추가할 항목이 없습니다",
  pendingTasksDeleted: "보류 중인 작업이 삭제되었습니다",
  pleaseSelectNodesToGroup: "그룹을 만들기 위해 노드(또는 다른 그룹)를 선택해 주세요",
  pleaseSelectOutputNodes: "출력 노드를 선택해 주세요",
  unableToGetModelFilePath: "모델 파일 경로를 가져올 수 없습니다",
  unauthorizedDomain: "귀하의 도메인 {domain}은(는) 이 서비스를 사용할 수 있는 권한이 없습니다. 도메인을 허용 목록에 추가하려면 {email}로 문의해 주세요.",
  updateRequested: "업데이트 요청됨",
  useApiKeyTip: "팁: 일반 로그인을 사용할 수 없나요? Comfy API Key 옵션을 사용하세요.",
  userNotAuthenticated: "사용자가 인증되지 않았습니다"
};
const userSelect$2 = {
  enterUsername: "사용자 이름 입력",
  existingUser: "기존 사용자",
  newUser: "새 사용자",
  next: "다음",
  selectUser: "사용자 선택"
};
const userSettings$2 = {
  email: "이메일",
  name: "이름",
  notSet: "설정되지 않음",
  provider: "로그인 방법",
  title: "사용자 설정",
  updatePassword: "비밀번호 업데이트"
};
const validation$2 = {
  invalidEmail: "유효하지 않은 이메일 주소",
  length: "{length}자여야 합니다",
  maxLength: "{length}자를 초과할 수 없습니다",
  minLength: "{length}자 이상이어야 합니다",
  password: {
    lowercase: "적어도 하나의 소문자를 포함해야 합니다",
    match: "비밀번호가 일치해야 합니다",
    minLength: "8자에서 32자 사이여야 합니다",
    number: "적어도 하나의 숫자를 포함해야 합니다",
    requirements: "비밀번호 요구사항",
    special: "적어도 하나의 특수 문자를 포함해야 합니다",
    uppercase: "적어도 하나의 대문자를 포함해야 합니다"
  },
  personalDataConsentRequired: "개인 데이터 처리에 동의해야 합니다.",
  prefix: "{prefix}(으)로 시작해야 합니다",
  required: "필수"
};
const welcome$2 = {
  getStarted: "시작하기",
  title: "ComfyUI에 오신 것을 환영합니다"
};
const workflowService$2 = {
  enterFilename: "파일 이름 입력",
  exportWorkflow: "워크플로 내보내기",
  saveWorkflow: "워크플로 저장"
};
const ko = {
  apiNodesCostBreakdown: apiNodesCostBreakdown$2,
  apiNodesNews: apiNodesNews$2,
  apiNodesSignInDialog: apiNodesSignInDialog$2,
  auth: auth$2,
  clipboard: clipboard$2,
  color: color$2,
  contextMenu: contextMenu$2,
  credits: credits$2,
  dataTypes: dataTypes$2,
  desktopMenu: desktopMenu$2,
  desktopUpdate: desktopUpdate$2,
  downloadGit: downloadGit$2,
  electronFileDownload: electronFileDownload$2,
  errorDialog: errorDialog$2,
  g: g$2,
  graphCanvasMenu: graphCanvasMenu$2,
  groupNode: groupNode$2,
  icon: icon$2,
  install: install$2,
  issueReport: issueReport$2,
  load3d: load3d$2,
  maintenance: maintenance$2,
  manager: manager$2,
  maskEditor: maskEditor$2,
  menu: menu$2,
  menuLabels: menuLabels$2,
  missingModelsDialog: missingModelsDialog$2,
  nodeCategories: nodeCategories$2,
  nodeTemplates: nodeTemplates$2,
  notSupported: notSupported$2,
  selectionToolbox: selectionToolbox$2,
  serverConfig: serverConfig$2,
  serverConfigCategories: serverConfigCategories$2,
  serverConfigItems: serverConfigItems$2,
  serverStart: serverStart$2,
  settingsCategories: settingsCategories$2,
  sideToolbar: sideToolbar$2,
  tabMenu: tabMenu$2,
  templateWorkflows: templateWorkflows$2,
  toastMessages: toastMessages$2,
  userSelect: userSelect$2,
  userSettings: userSettings$2,
  validation: validation$2,
  welcome: welcome$2,
  workflowService: workflowService$2
};
const AddNoise$2 = {
  display_name: "노이즈 추가",
  inputs: {
    latent_image: {
      name: "잠재 이미지"
    },
    model: {
      name: "모델"
    },
    noise: {
      name: "노이즈"
    },
    sigmas: {
      name: "시그마 배열"
    }
  }
};
const AlignYourStepsScheduler$2 = {
  display_name: "AlignYourSteps 스케쥴러",
  inputs: {
    denoise: {
      name: "노이즈 제거양"
    },
    model_type: {
      name: "모델 유형"
    },
    steps: {
      name: "스텝 수"
    }
  }
};
const BasicGuider$2 = {
  display_name: "기본 가이드",
  inputs: {
    conditioning: {
      name: "조건"
    },
    model: {
      name: "모델"
    }
  }
};
const BasicScheduler$2 = {
  display_name: "기본 스케줄러",
  inputs: {
    denoise: {
      name: "노이즈 제거양"
    },
    model: {
      name: "모델"
    },
    scheduler: {
      name: "스케줄러"
    },
    steps: {
      name: "스텝 수"
    }
  }
};
const BetaSamplingScheduler$2 = {
  display_name: "베타 샘플링 스케줄러",
  inputs: {
    alpha: {
      name: "알파"
    },
    beta: {
      name: "베타"
    },
    model: {
      name: "모델"
    },
    steps: {
      name: "스텝 수"
    }
  }
};
const CFGGuider$2 = {
  display_name: "CFG 가이드",
  inputs: {
    cfg: {
      name: "cfg"
    },
    model: {
      name: "모델"
    },
    negative: {
      name: "부정 조건"
    },
    positive: {
      name: "긍정 조건"
    }
  }
};
const CFGZeroStar$2 = {
  display_name: "CFGZeroStar",
  inputs: {
    model: {
      name: "모델"
    }
  },
  outputs: {
    "0": {
      name: "패치된 모델"
    }
  }
};
const CLIPAttentionMultiply$2 = {
  display_name: "CLIP 어텐션 곱하기",
  inputs: {
    clip: {
      name: "clip"
    },
    k: {
      name: "k"
    },
    out: {
      name: "out"
    },
    q: {
      name: "q"
    },
    v: {
      name: "v"
    }
  }
};
const CLIPLoader$2 = {
  description: "[조합법]\n\nstable_diffusion: clip-l\nstable_cascade: clip-g\nsd3: t5 / clip-g / clip-l\nstable_audio: t5\nmochi: t5\ncosmos: old t5 xxl",
  display_name: "CLIP 로드",
  inputs: {
    clip_name: {
      name: "CLIP 파일명"
    },
    device: {
      name: "장치"
    },
    type: {
      name: "유형"
    }
  }
};
const CLIPMergeAdd$2 = {
  display_name: "CLIP 병합 (더하기)",
  inputs: {
    clip1: {
      name: "CLIP1"
    },
    clip2: {
      name: "CLIP2"
    }
  }
};
const CLIPMergeSimple$2 = {
  display_name: "CLIP 병합 (단순)",
  inputs: {
    clip1: {
      name: "CLIP1"
    },
    clip2: {
      name: "CLIP2"
    },
    ratio: {
      name: "비율"
    }
  }
};
const CLIPMergeSubtract$2 = {
  display_name: "CLIP 병합 (빼기)",
  inputs: {
    clip1: {
      name: "CLIP1"
    },
    clip2: {
      name: "CLIP2"
    },
    multiplier: {
      name: "배율"
    }
  }
};
const CLIPSave$2 = {
  display_name: "CLIP 저장",
  inputs: {
    clip: {
      name: "clip"
    },
    filename_prefix: {
      name: "파일명 접두사"
    }
  }
};
const CLIPSetLastLayer$2 = {
  display_name: "CLIP 마지막 레이어 설정",
  inputs: {
    clip: {
      name: "clip"
    },
    stop_at_clip_layer: {
      name: "CLIP 레이어 중단점"
    }
  }
};
const CLIPTextEncode$2 = {
  description: "CLIP 모델을 사용하여 텍스트 프롬프트를 인코딩하여 확산 모델이 특정 이미지를 생성하도록 유도하는 임베딩으로 변환합니다.",
  display_name: "CLIP 텍스트 인코딩 (프롬프트)",
  inputs: {
    clip: {
      name: "clip",
      tooltip: "텍스트 인코딩에 사용되는 CLIP 모델입니다."
    },
    text: {
      name: "프롬프트 텍스트",
      tooltip: "인코딩할 텍스트입니다."
    }
  },
  outputs: {
    "0": {
      tooltip: "확산 모델을 유도하는 데 사용되는 텍스트 임베딩을 포함하는 조건입니다."
    }
  }
};
const CLIPTextEncodeControlnet$2 = {
  display_name: "CLIP 텍스트 인코딩 (컨트롤넷)",
  inputs: {
    clip: {
      name: "clip"
    },
    conditioning: {
      name: "조건"
    },
    text: {
      name: "프롬프트 텍스트"
    }
  }
};
const CLIPTextEncodeFlux$2 = {
  display_name: "CLIP 텍스트 인코딩 (FLUX)",
  inputs: {
    clip: {
      name: "clip"
    },
    clip_l: {
      name: "clip-l 프롬프트"
    },
    guidance: {
      name: "가이던스"
    },
    t5xxl: {
      name: "t5xxl 프롬프트"
    }
  }
};
const CLIPTextEncodeHiDream$2 = {
  display_name: "CLIPTextEncodeHiDream",
  inputs: {
    clip: {
      name: "clip"
    },
    clip_g: {
      name: "clip-g 프롬프트"
    },
    clip_l: {
      name: "clip-l 프롬프트"
    },
    llama: {
      name: "llama 프롬프트"
    },
    t5xxl: {
      name: "t5xxl 프롬프트"
    }
  }
};
const CLIPTextEncodeHunyuanDiT$2 = {
  display_name: "CLIP 텍스트 인코딩 (HunyuanDiT)",
  inputs: {
    bert: {
      name: "bert 프롬프트"
    },
    clip: {
      name: "clip"
    },
    mt5xl: {
      name: "mt5xl 프롬프트"
    }
  }
};
const CLIPTextEncodeLumina2$2 = {
  description: "CLIP 모델을 사용하여 시스템 프롬프트와 사용자 프롬프트를 인코딩하여 특정 이미지를 생성하는 데 사용할 수 있는 임베딩으로 변환합니다.",
  display_name: "CLIP 텍스트 인코딩 (Lumina2)",
  inputs: {
    clip: {
      name: "clip",
      tooltip: "텍스트를 인코딩하는 데 사용되는 CLIP 모델입니다."
    },
    system_prompt: {
      name: "system_prompt",
      tooltip: "Lumina2는 두 가지 유형의 시스템 프롬프트를 제공합니다.\nSuperior: 텍스트 프롬프트 또는 사용자 프롬프트를 기반으로 우수한 이미지-텍스트 정렬 정도로 우수한 이미지를 생성하도록 설계된 도우미입니다.\nAlignment: 텍스트 프롬프트를 기반으로 이미지-텍스트 정렬의 최고 수준으로 고품질 이미지를 생성하도록 설계된 도우미입니다."
    },
    user_prompt: {
      name: "user_prompt",
      tooltip: "인코딩할 텍스트입니다."
    }
  },
  outputs: {
    "0": {
      tooltip: "확산 모델을 유도하는 데 사용되는 텍스트 임베딩을 포함하는 조건입니다."
    }
  }
};
const CLIPTextEncodePixArtAlpha$2 = {
  description: "텍스트를 인코딩하고 PixArt Alpha의 해상도 조건을 설정합니다. PixArt Sigma에는 적용되지 않습니다.",
  display_name: "CLIPTextEncodePixArtAlpha",
  inputs: {
    clip: {
      name: "clip"
    },
    height: {
      name: "높이"
    },
    text: {
      name: "프롬프트 텍스트"
    },
    width: {
      name: "너비"
    }
  }
};
const CLIPTextEncodeSD3$2 = {
  display_name: "CLIP 텍스트 인코딩 (SD3)",
  inputs: {
    clip: {
      name: "clip"
    },
    clip_g: {
      name: "clip-g 프롬프트"
    },
    clip_l: {
      name: "clip-l 프롬프트"
    },
    empty_padding: {
      name: "빈_패딩"
    },
    t5xxl: {
      name: "t5xxl"
    }
  }
};
const CLIPTextEncodeSDXL$2 = {
  display_name: "CLIP 텍스트 인코딩 (SDXL)",
  inputs: {
    clip: {
      name: "clip"
    },
    crop_h: {
      name: "크롭 높이"
    },
    crop_w: {
      name: "크롭 너비"
    },
    height: {
      name: "높이"
    },
    target_height: {
      name: "목표 높이"
    },
    target_width: {
      name: "목표 너비"
    },
    text_g: {
      name: "clip-g 프롬프트"
    },
    text_l: {
      name: "clip-l 프롬프트"
    },
    width: {
      name: "너비"
    }
  }
};
const CLIPTextEncodeSDXLRefiner$2 = {
  display_name: "CLIP 텍스트 인코딩 (SDXL Refiner)",
  inputs: {
    ascore: {
      name: "ascore"
    },
    clip: {
      name: "clip"
    },
    height: {
      name: "높이"
    },
    text: {
      name: "텍스트"
    },
    width: {
      name: "너비"
    }
  }
};
const CLIPVisionEncode$2 = {
  display_name: "CLIP_VISION 인코딩",
  inputs: {
    clip_vision: {
      name: "clip_vision"
    },
    crop: {
      name: "자르기 방법"
    },
    image: {
      name: "이미지"
    }
  }
};
const CLIPVisionLoader$2 = {
  display_name: "CLIP_VISION 로드",
  inputs: {
    clip_name: {
      name: "CLIP 파일명"
    }
  }
};
const Canny$2 = {
  display_name: "Canny 경계 필터",
  inputs: {
    high_threshold: {
      name: "높은 임계값"
    },
    image: {
      name: "이미지"
    },
    low_threshold: {
      name: "낮은 임계값"
    }
  }
};
const CheckpointLoader$2 = {
  display_name: "구성으로 체크포인트 로드 (지원 중단)",
  inputs: {
    ckpt_name: {
      name: "체크포인트 파일명"
    },
    config_name: {
      name: "설정 이름"
    }
  }
};
const CheckpointLoaderSimple$2 = {
  description: "확산 모델 체크포인트를 로드합니다. 확산 모델은 잠재 데이터의 노이즈를 제거하는 데 사용됩니다.",
  display_name: "체크포인트 로드",
  inputs: {
    ckpt_name: {
      name: "체크포인트 파일명",
      tooltip: "로드할 체크포인트(모델)의 이름입니다."
    }
  },
  outputs: {
    "0": {
      tooltip: "노이즈 제거를 위한 잠재 모델입니다."
    },
    "1": {
      tooltip: "텍스트 프롬프트를 인코딩하는 데 사용되는 CLIP 모델입니다."
    },
    "2": {
      tooltip: "이미지를 잠재 공간으로 인코딩하고 디코딩하는 데 사용되는 VAE 모델입니다."
    }
  }
};
const CheckpointSave$2 = {
  display_name: "체크포인트 저장",
  inputs: {
    clip: {
      name: "clip"
    },
    filename_prefix: {
      name: "파일명 접두사"
    },
    model: {
      name: "모델"
    },
    vae: {
      name: "vae"
    }
  }
};
const CombineHooks2$2 = {
  display_name: "후크 결합 [2]",
  inputs: {
    hooks_A: {
      name: "후크 A"
    },
    hooks_B: {
      name: "후크 B"
    }
  }
};
const CombineHooks4$2 = {
  display_name: "후크 결합 [4]",
  inputs: {
    hooks_A: {
      name: "후크 A"
    },
    hooks_B: {
      name: "후크 B"
    },
    hooks_C: {
      name: "후크 C"
    },
    hooks_D: {
      name: "후크 D"
    }
  }
};
const CombineHooks8$2 = {
  display_name: "후크 결합 [8]",
  inputs: {
    hooks_A: {
      name: "후크 A"
    },
    hooks_B: {
      name: "후크 B"
    },
    hooks_C: {
      name: "후크 C"
    },
    hooks_D: {
      name: "후크 D"
    },
    hooks_E: {
      name: "후크 E"
    },
    hooks_F: {
      name: "후크 F"
    },
    hooks_G: {
      name: "후크 G"
    },
    hooks_H: {
      name: "후크 H"
    }
  }
};
const ConditioningAverage$2 = {
  display_name: "조건 (평균)",
  inputs: {
    conditioning_from: {
      name: "추가 조건"
    },
    conditioning_to: {
      name: "대상 조건"
    },
    conditioning_to_strength: {
      name: "대상 조건 강도"
    }
  }
};
const ConditioningCombine$2 = {
  display_name: "조건 (결합)",
  inputs: {
    conditioning_1: {
      name: "조건 1"
    },
    conditioning_2: {
      name: "조건 2"
    }
  }
};
const ConditioningConcat$2 = {
  display_name: "조건 (연결)",
  inputs: {
    conditioning_from: {
      name: "추가 조건"
    },
    conditioning_to: {
      name: "대상 조건"
    }
  }
};
const ConditioningSetArea$2 = {
  display_name: "조건 (영역 설정)",
  inputs: {
    conditioning: {
      name: "조건"
    },
    height: {
      name: "높이"
    },
    strength: {
      name: "강도"
    },
    width: {
      name: "너비"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const ConditioningSetAreaPercentage$2 = {
  display_name: "조건 (비율로 영역 설정)",
  inputs: {
    conditioning: {
      name: "조건"
    },
    height: {
      name: "높이"
    },
    strength: {
      name: "강도"
    },
    width: {
      name: "너비"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const ConditioningSetAreaPercentageVideo$2 = {
  display_name: "비디오 조건 (비율로 영역 설정)",
  inputs: {
    conditioning: {
      name: "조건"
    },
    height: {
      name: "높이"
    },
    strength: {
      name: "강도"
    },
    temporal: {
      name: "시간"
    },
    width: {
      name: "너비"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    },
    z: {
      name: "z"
    }
  }
};
const ConditioningSetAreaStrength$2 = {
  display_name: "조건 (영역 강도 설정)",
  inputs: {
    conditioning: {
      name: "조건"
    },
    strength: {
      name: "강도"
    }
  }
};
const ConditioningSetDefaultCombine$2 = {
  display_name: "조건 (기본 결합 설정)",
  inputs: {
    cond: {
      name: "조건"
    },
    cond_DEFAULT: {
      name: "기본 조건"
    },
    hooks: {
      name: "후크"
    }
  }
};
const ConditioningSetMask$2 = {
  display_name: "조건 (마스크 설정)",
  inputs: {
    conditioning: {
      name: "조건"
    },
    mask: {
      name: "마스크"
    },
    set_cond_area: {
      name: "조건 영역 설정"
    },
    strength: {
      name: "강도"
    }
  }
};
const ConditioningSetProperties$2 = {
  display_name: "조건 (속성 설정)",
  inputs: {
    cond_NEW: {
      name: "새 조건"
    },
    hooks: {
      name: "후크"
    },
    mask: {
      name: "마스크"
    },
    set_cond_area: {
      name: "조건 영역 설정"
    },
    strength: {
      name: "강도"
    },
    timesteps: {
      name: "타임스텝 범위"
    }
  }
};
const ConditioningSetPropertiesAndCombine$2 = {
  display_name: "조건 (속성 설정 및 결합)",
  inputs: {
    cond: {
      name: "조건"
    },
    cond_NEW: {
      name: "새 조건"
    },
    hooks: {
      name: "후크"
    },
    mask: {
      name: "마스크"
    },
    set_cond_area: {
      name: "조건 영역 설정"
    },
    strength: {
      name: "강도"
    },
    timesteps: {
      name: "타임스텝 범위"
    }
  }
};
const ConditioningSetTimestepRange$2 = {
  display_name: "조건 (타임스텝 범위 설정)",
  inputs: {
    conditioning: {
      name: "조건"
    },
    end: {
      name: "끝"
    },
    start: {
      name: "시작"
    }
  }
};
const ConditioningStableAudio$2 = {
  display_name: "Stable Audio 조건 설정",
  inputs: {
    negative: {
      name: "부정 조건"
    },
    positive: {
      name: "긍정 조건"
    },
    seconds_start: {
      name: "시작(초)"
    },
    seconds_total: {
      name: "전체(초)"
    }
  },
  outputs: {
    "0": {
      name: "긍정 조건"
    },
    "1": {
      name: "부정 조건"
    }
  }
};
const ConditioningTimestepsRange$2 = {
  display_name: "조건 (타임스텝 범위)",
  inputs: {
    end_percent: {
      name: "종료 퍼센트"
    },
    start_percent: {
      name: "시작 퍼센트"
    }
  },
  outputs: {
    "1": {
      name: "이전 범위"
    },
    "2": {
      name: "이후 범위"
    }
  }
};
const ConditioningZeroOut$2 = {
  display_name: "조건 (0으로 출력)",
  inputs: {
    conditioning: {
      name: "조건"
    }
  }
};
const ControlNetApply$2 = {
  display_name: "컨트롤넷 적용 (구형)",
  inputs: {
    conditioning: {
      name: "조건"
    },
    control_net: {
      name: "컨트롤넷"
    },
    image: {
      name: "이미지"
    },
    strength: {
      name: "강도"
    }
  }
};
const ControlNetApplyAdvanced$2 = {
  display_name: "컨트롤넷 적용",
  inputs: {
    control_net: {
      name: "컨트롤넷"
    },
    end_percent: {
      name: "종료 퍼센트"
    },
    image: {
      name: "이미지"
    },
    negative: {
      name: "부정 조건"
    },
    positive: {
      name: "긍정 조건"
    },
    start_percent: {
      name: "시작 퍼센트"
    },
    strength: {
      name: "강도"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "긍정 조건"
    },
    "1": {
      name: "부정 조건"
    }
  }
};
const ControlNetApplySD3$2 = {
  display_name: "컨트롤넷을 VAE와 함께 적용",
  inputs: {
    control_net: {
      name: "컨트롤넷"
    },
    end_percent: {
      name: "종료 퍼센트"
    },
    image: {
      name: "이미지"
    },
    negative: {
      name: "부정 조건"
    },
    positive: {
      name: "긍정 조건"
    },
    start_percent: {
      name: "시작 퍼센트"
    },
    strength: {
      name: "강도"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "긍정 조건"
    },
    "1": {
      name: "부정 조건"
    }
  }
};
const ControlNetInpaintingAliMamaApply$2 = {
  display_name: "컨트롤넷 인페인팅 AliMama 적용",
  inputs: {
    control_net: {
      name: "컨트롤넷"
    },
    end_percent: {
      name: "종료 퍼센트"
    },
    image: {
      name: "이미지"
    },
    mask: {
      name: "마스크"
    },
    negative: {
      name: "부정 조건"
    },
    positive: {
      name: "긍정 조건"
    },
    start_percent: {
      name: "시작 퍼센트"
    },
    strength: {
      name: "강도"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "긍정 조건"
    },
    "1": {
      name: "부정 조건"
    }
  }
};
const ControlNetLoader$2 = {
  display_name: "컨트롤넷 모델 로드",
  inputs: {
    control_net_name: {
      name: "컨트롤넷 파일명"
    }
  }
};
const CosmosImageToVideoLatent$2 = {
  display_name: "Cosmos 비디오 생성 (이미지 → 비디오)",
  inputs: {
    batch_size: {
      name: "배치 크기"
    },
    end_image: {
      name: "끝 이미지"
    },
    height: {
      name: "높이"
    },
    length: {
      name: "길이"
    },
    start_image: {
      name: "시작 이미지"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "너비"
    }
  }
};
const CreateHookKeyframe$2 = {
  display_name: "후크 키프레임 생성",
  inputs: {
    prev_hook_kf: {
      name: "이전 KF 후크"
    },
    start_percent: {
      name: "시작 퍼센트"
    },
    strength_mult: {
      name: "강도 곱"
    }
  },
  outputs: {
    "0": {
      name: "KF 후크"
    }
  }
};
const CreateHookKeyframesFromFloats$2 = {
  display_name: "실수로 후크 키프레임 생성",
  inputs: {
    end_percent: {
      name: "종료 퍼센트"
    },
    floats_strength: {
      name: "실수 강도"
    },
    prev_hook_kf: {
      name: "이전 KF 후크"
    },
    print_keyframes: {
      name: "키프레임 출력"
    },
    start_percent: {
      name: "시작 퍼센트"
    }
  },
  outputs: {
    "0": {
      name: "KF 후크"
    }
  }
};
const CreateHookKeyframesInterpolated$2 = {
  display_name: "보간된 후크 키프레임 생성",
  inputs: {
    end_percent: {
      name: "종료 퍼센트"
    },
    interpolation: {
      name: "보간"
    },
    keyframes_count: {
      name: "키프레임 카운트"
    },
    prev_hook_kf: {
      name: "이전 KF 후크"
    },
    print_keyframes: {
      name: "키프레임 출력"
    },
    start_percent: {
      name: "시작 퍼센트"
    },
    strength_end: {
      name: "종료 강도"
    },
    strength_start: {
      name: "시작 강도"
    }
  },
  outputs: {
    "0": {
      name: "KF 후크"
    }
  }
};
const CreateHookLora$2 = {
  display_name: "후크 LoRA 생성",
  inputs: {
    lora_name: {
      name: "LoRA 파일명"
    },
    prev_hooks: {
      name: "이전 후크"
    },
    strength_clip: {
      name: "CLIP 강도"
    },
    strength_model: {
      name: "모델 강도"
    }
  }
};
const CreateHookLoraModelOnly$2 = {
  display_name: "후크 LoRA 생성 (모델 전용)",
  inputs: {
    lora_name: {
      name: "LoRA 파일명"
    },
    prev_hooks: {
      name: "이전 후크"
    },
    strength_model: {
      name: "모델 강도"
    }
  }
};
const CreateHookModelAsLora$2 = {
  display_name: "후크 모델을 LoRA로 생성",
  inputs: {
    ckpt_name: {
      name: "체크포인트 파일명"
    },
    prev_hooks: {
      name: "이전 후크"
    },
    strength_clip: {
      name: "CLIP 강도"
    },
    strength_model: {
      name: "모델 강도"
    }
  }
};
const CreateHookModelAsLoraModelOnly$2 = {
  display_name: "후크 모델을 LoRA로 생성 (모델 전용)",
  inputs: {
    ckpt_name: {
      name: "체크포인트 파일명"
    },
    prev_hooks: {
      name: "이전 후크"
    },
    strength_model: {
      name: "모델 강도"
    }
  }
};
const CreateVideo$2 = {
  description: "이미지로부터 비디오를 생성합니다.",
  display_name: "비디오 생성",
  inputs: {
    audio: {
      name: "오디오",
      tooltip: "비디오에 추가할 오디오입니다."
    },
    fps: {
      name: "fps"
    },
    images: {
      name: "이미지",
      tooltip: "비디오를 생성할 이미지입니다."
    }
  }
};
const CropMask$2 = {
  display_name: "마스크 자르기",
  inputs: {
    height: {
      name: "높이"
    },
    mask: {
      name: "마스크"
    },
    width: {
      name: "너비"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const DiffControlNetLoader$2 = {
  display_name: "컨트롤넷 모델 로드 (차이)",
  inputs: {
    control_net_name: {
      name: "컨트롤넷 파일명"
    },
    model: {
      name: "모델"
    }
  }
};
const DifferentialDiffusion$2 = {
  display_name: "차등 확산",
  inputs: {
    model: {
      name: "모델"
    }
  }
};
const DiffusersLoader$2 = {
  display_name: "Diffusers 로드",
  inputs: {
    model_path: {
      name: "모델 경로"
    }
  }
};
const DisableNoise$2 = {
  display_name: "노이즈 비활성화"
};
const DualCFGGuider$2 = {
  display_name: "이중 CFG 가이드",
  inputs: {
    cfg_cond2_negative: {
      name: "(조건2 - 부정 조건) cfg"
    },
    cfg_conds: {
      name: "전체 조건 cfg"
    },
    cond1: {
      name: "조건1"
    },
    cond2: {
      name: "조건2"
    },
    model: {
      name: "모델"
    },
    negative: {
      name: "부정 조건"
    }
  }
};
const DualCLIPLoader$2 = {
  description: "[조합법]\n\nsdxl: clip-l, clip-g\nsd3: clip-l, clip-g / clip-l, t5 / clip-g, t5\nflux: clip-l, t5",
  display_name: "이중 CLIP 로드",
  inputs: {
    clip_name1: {
      name: "CLIP 파일명1"
    },
    clip_name2: {
      name: "CLIP 파일명2"
    },
    device: {
      name: "장치"
    },
    type: {
      name: "유형"
    }
  }
};
const EmptyCosmosLatentVideo$2 = {
  display_name: "빈 잠재 비디오 (Cosmos)",
  inputs: {
    batch_size: {
      name: "배치 크기"
    },
    height: {
      name: "높이"
    },
    length: {
      name: "길이"
    },
    width: {
      name: "너비"
    }
  }
};
const EmptyHunyuanLatentVideo$2 = {
  display_name: "빈 잠재 비디오 (Hunyuan)",
  inputs: {
    batch_size: {
      name: "배치 크기"
    },
    height: {
      name: "높이"
    },
    length: {
      name: "길이"
    },
    width: {
      name: "너비"
    }
  }
};
const EmptyImage$2 = {
  display_name: "빈 이미지",
  inputs: {
    batch_size: {
      name: "배치 크기"
    },
    color: {
      name: "색"
    },
    height: {
      name: "높이"
    },
    width: {
      name: "너비"
    }
  }
};
const EmptyLTXVLatentVideo$2 = {
  display_name: "빈 잠재 비디오 (LTXV)",
  inputs: {
    batch_size: {
      name: "배치 크기"
    },
    height: {
      name: "높이"
    },
    length: {
      name: "길이"
    },
    width: {
      name: "너비"
    }
  }
};
const EmptyLatentAudio$2 = {
  display_name: "빈 잠재 오디오",
  inputs: {
    batch_size: {
      name: "배치 크기",
      tooltip: "배치의 잠재 이미지 수입니다."
    },
    seconds: {
      name: "초"
    }
  }
};
const EmptyLatentHunyuan3Dv2$2 = {
  display_name: "EmptyLatentHunyuan3Dv2",
  inputs: {
    batch_size: {
      name: "배치 크기",
      tooltip: "배치에 있는 잠재 이미지의 수입니다."
    },
    resolution: {
      name: "해상도"
    }
  }
};
const EmptyLatentImage$2 = {
  description: "샘플링을 통해 디노이즈할 빈 잠재 이미지의 새 배치를 생성합니다.",
  display_name: "빈 잠재 이미지",
  inputs: {
    batch_size: {
      name: "배치 크기",
      tooltip: "배치의 잠재 이미지 수입니다."
    },
    height: {
      name: "높이",
      tooltip: "잠재 이미지의 높이(픽셀)입니다."
    },
    width: {
      name: "너비",
      tooltip: "잠재 이미지의 너비(픽셀)입니다."
    }
  },
  outputs: {
    "0": {
      tooltip: "빈 잠재 이미지 배치입니다."
    }
  }
};
const EmptyMochiLatentVideo$2 = {
  display_name: "빈 잠재 비디오 (Mochi)",
  inputs: {
    batch_size: {
      name: "배치 크기"
    },
    height: {
      name: "높이"
    },
    length: {
      name: "길이"
    },
    width: {
      name: "너비"
    }
  }
};
const EmptySD3LatentImage$2 = {
  display_name: "빈 잠재 이미지 (SD3)",
  inputs: {
    batch_size: {
      name: "배치 크기"
    },
    height: {
      name: "높이"
    },
    width: {
      name: "너비"
    }
  }
};
const ExponentialScheduler$2 = {
  display_name: "지수 스케줄러",
  inputs: {
    sigma_max: {
      name: "sigma_max"
    },
    sigma_min: {
      name: "sigma_min"
    },
    steps: {
      name: "스텝 수"
    }
  }
};
const ExtendIntermediateSigmas$2 = {
  display_name: "시그마 배열 중간 구간 확장",
  inputs: {
    end_at_sigma: {
      name: "시그마 종료점"
    },
    sigmas: {
      name: "시그마 배열"
    },
    spacing: {
      name: "간격 분포 방식"
    },
    start_at_sigma: {
      name: "시그마 시작점"
    },
    steps: {
      name: "스텝 수"
    }
  }
};
const FeatherMask$2 = {
  display_name: "마스크 가장자리 흐리게",
  inputs: {
    bottom: {
      name: "아래쪽"
    },
    left: {
      name: "왼쪽"
    },
    mask: {
      name: "마스크"
    },
    right: {
      name: "오른쪽"
    },
    top: {
      name: "위쪽"
    }
  }
};
const FlipSigmas$2 = {
  display_name: "시그마 배열 뒤집기",
  inputs: {
    sigmas: {
      name: "시그마 배열"
    }
  }
};
const FluxDisableGuidance$2 = {
  description: "이 노드는 Flux 및 Flux와 유사한 모델에서 가이던스 임베드를 완전히 비활성화합니다",
  display_name: "가이드 비활성화 (FLUX)",
  inputs: {
    conditioning: {
      name: "조건"
    }
  }
};
const FluxGuidance$2 = {
  display_name: "FLUX 가이드",
  inputs: {
    conditioning: {
      name: "조건"
    },
    guidance: {
      name: "지침"
    }
  }
};
const FluxProCannyNode$2 = {
  description: "컨트롤 이미지(canny)를 사용하여 이미지를 생성합니다.",
  display_name: "Flux.1 캐니 제어 이미지",
  inputs: {
    canny_high_threshold: {
      name: "canny 상한 임계값",
      tooltip: "윤곽선이 뚜렷할수록 선으로 인식되며, 이 값은 그 상한 임계값입니다. skip_processing이 True이면 무시됩니다."
    },
    canny_low_threshold: {
      name: "canny 하한 임계값",
      tooltip: "덜 뚜렷한 윤곽선도 강한 선과 연결되면 표시되며, 이 값은 그 하한 임계값입니다. skip_processing이 True이면 무시됩니다."
    },
    control_after_generate: {
      name: "생성 후 제어"
    },
    control_image: {
      name: "제어 이미지"
    },
    guidance: {
      name: "가이던스",
      tooltip: "이미지 생성 과정의 가이던스 강도"
    },
    prompt: {
      name: "프롬프트",
      tooltip: "이미지 생성을 위한 프롬프트"
    },
    prompt_upsampling: {
      name: "프롬프트 업샘플링",
      tooltip: "프롬프트 업샘플링을 수행할지 여부입니다. 활성화 시, 더 창의적인 생성을 위해 프롬프트가 자동으로 수정되지만 결과는 비결정적입니다(같은 시드여도 정확히 같은 결과가 나오지 않습니다)."
    },
    seed: {
      name: "시드",
      tooltip: "노이즈 생성을 위해 사용되는 랜덤 시드입니다."
    },
    skip_preprocessing: {
      name: "전처리 건너뛰기",
      tooltip: "전처리를 건너뛸지 여부입니다. 제어 이미지가 이미 캐니 처리된 이미지라면 True, 원본 이미지라면 False로 설정하세요."
    },
    steps: {
      name: "스텝 수",
      tooltip: "이미지 생성 과정의 단계 수"
    }
  }
};
const FluxProDepthNode$2 = {
  description: "제어 이미지(깊이)를 사용하여 이미지를 생성합니다.",
  display_name: "Flux.1 깊이 제어 이미지",
  inputs: {
    control_after_generate: {
      name: "생성 후 제어"
    },
    control_image: {
      name: "제어 이미지"
    },
    guidance: {
      name: "가이던스",
      tooltip: "이미지 생성 과정의 가이던스 강도"
    },
    prompt: {
      name: "프롬프트",
      tooltip: "이미지 생성을 위한 프롬프트"
    },
    prompt_upsampling: {
      name: "프롬프트 업샘플링",
      tooltip: "프롬프트에 업샘플링을 수행할지 여부입니다. 활성화하면 프롬프트가 자동으로 더 창의적인 생성이 가능하도록 수정되지만, 결과는 비결정적입니다(같은 시드라도 정확히 같은 결과가 나오지 않습니다)."
    },
    seed: {
      name: "시드",
      tooltip: "노이즈 생성을 위해 사용되는 랜덤 시드입니다."
    },
    skip_preprocessing: {
      name: "전처리 건너뛰기",
      tooltip: "전처리를 건너뛸지 여부입니다. 제어 이미지가 이미 깊이화된 이미지라면 True로, 원본 이미지라면 False로 설정하세요."
    },
    steps: {
      name: "스텝 수",
      tooltip: "이미지 생성 과정의 스텝 수"
    }
  }
};
const FluxProExpandNode$2 = {
  description: "프롬프트를 기반으로 이미지의 바깥 영역을 확장합니다.",
  display_name: "Flux.1 이미지 확장",
  inputs: {
    bottom: {
      name: "하단",
      tooltip: "이미지 하단에 확장할 픽셀 수"
    },
    control_after_generate: {
      name: "생성 후 제어"
    },
    guidance: {
      name: "가이던스",
      tooltip: "이미지 생성 과정의 가이던스 강도"
    },
    image: {
      name: "이미지"
    },
    left: {
      name: "좌측",
      tooltip: "이미지 좌측에 확장할 픽셀 수"
    },
    prompt: {
      name: "프롬프트",
      tooltip: "이미지 생성을 위한 프롬프트"
    },
    prompt_upsampling: {
      name: "프롬프트 업샘플링",
      tooltip: "프롬프트에 업샘플링을 수행할지 여부입니다. 활성화 시, 더 창의적인 생성을 위해 프롬프트가 자동으로 수정되지만 결과는 비결정적입니다(같은 시드라도 정확히 같은 결과가 나오지 않습니다)."
    },
    right: {
      name: "우측",
      tooltip: "이미지 우측에 확장할 픽셀 수"
    },
    seed: {
      name: "시드",
      tooltip: "노이즈 생성을 위해 사용되는 랜덤 시드입니다."
    },
    steps: {
      name: "스텝 수",
      tooltip: "이미지 생성 과정의 스텝 수"
    },
    top: {
      name: "상단",
      tooltip: "이미지 상단에 확장할 픽셀 수"
    }
  }
};
const FluxProFillNode$2 = {
  description: "마스크와 프롬프트를 기반으로 이미지를 인페인팅합니다.",
  display_name: "Flux.1 이미지 채우기",
  inputs: {
    control_after_generate: {
      name: "생성 후 제어"
    },
    guidance: {
      name: "가이던스",
      tooltip: "이미지 생성 과정의 가이던스 강도"
    },
    image: {
      name: "이미지"
    },
    mask: {
      name: "마스크"
    },
    prompt: {
      name: "프롬프트",
      tooltip: "이미지 생성을 위한 프롬프트"
    },
    prompt_upsampling: {
      name: "프롬프트 업샘플링",
      tooltip: "프롬프트에 업샘플링을 수행할지 여부입니다. 활성화 시, 더 창의적인 생성을 위해 프롬프트가 자동으로 수정되지만 결과는 비결정적입니다(같은 시드라도 정확히 같은 결과가 나오지 않습니다)."
    },
    seed: {
      name: "시드",
      tooltip: "노이즈 생성을 위해 사용되는 랜덤 시드입니다."
    },
    steps: {
      name: "스텝 수",
      tooltip: "이미지 생성 과정의 스텝 수"
    }
  }
};
const FluxProUltraImageNode$2 = {
  description: "프롬프트와 해상도를 기반으로 api를 통해 Flux Pro 1.1 Ultra로 이미지를 생성합니다.",
  display_name: "Flux 1.1 [pro] Ultra 이미지",
  inputs: {
    aspect_ratio: {
      name: "종횡비",
      tooltip: "이미지의 종횡비; 1:4에서 4:1 사이여야 합니다."
    },
    control_after_generate: {
      name: "생성 후 제어"
    },
    image_prompt: {
      name: "이미지 프롬프트"
    },
    image_prompt_strength: {
      name: "이미지 프롬프트 강도",
      tooltip: "프롬프트와 이미지 프롬프트 간의 혼합 비율입니다."
    },
    prompt: {
      name: "프롬프트",
      tooltip: "이미지 생성을 위한 프롬프트"
    },
    prompt_upsampling: {
      name: "프롬프트 업샘플링",
      tooltip: "프롬프트에 업샘플링을 수행할지 여부입니다. 활성화하면 프롬프트가 자동으로 더 창의적으로 수정되지만, 결과는 비결정적입니다(같은 시드라도 정확히 같은 결과가 나오지 않습니다)."
    },
    raw: {
      name: "원본",
      tooltip: "True로 설정하면 덜 가공되고 더 자연스러운 이미지를 생성합니다."
    },
    seed: {
      name: "시드",
      tooltip: "노이즈 생성을 위한 랜덤 시드입니다."
    }
  }
};
const FreSca$2 = {
  description: "주파수에 따라 가이던스에 스케일을 적용합니다",
  display_name: "FreSca",
  inputs: {
    freq_cutoff: {
      name: "주파수 컷오프",
      tooltip: "저주파수로 간주할 중심 주위의 주파수 인덱스 개수"
    },
    model: {
      name: "모델"
    },
    scale_high: {
      name: "고주파 스케일",
      tooltip: "고주파수 성분에 대한 스케일 계수"
    },
    scale_low: {
      name: "저주파 스케일",
      tooltip: "저주파수 성분에 대한 스케일 계수"
    }
  }
};
const FreeU$2 = {
  display_name: "FreeU",
  inputs: {
    b1: {
      name: "b1"
    },
    b2: {
      name: "b2"
    },
    model: {
      name: "모델"
    },
    s1: {
      name: "s1"
    },
    s2: {
      name: "s2"
    }
  }
};
const FreeU_V2$2 = {
  display_name: "FreeU V2",
  inputs: {
    b1: {
      name: "b1"
    },
    b2: {
      name: "b2"
    },
    model: {
      name: "모델"
    },
    s1: {
      name: "s1"
    },
    s2: {
      name: "s2"
    }
  }
};
const GITSScheduler$2 = {
  display_name: "GITS 스케줄러",
  inputs: {
    coeff: {
      name: "계수"
    },
    denoise: {
      name: "노이즈 제거양"
    },
    steps: {
      name: "스텝 수"
    }
  }
};
const GLIGENLoader$2 = {
  display_name: "GLIGEN 로드",
  inputs: {
    gligen_name: {
      name: "gligen 파일명"
    }
  }
};
const GLIGENTextBoxApply$2 = {
  display_name: "GLIGEN 텍스트 박스 적용",
  inputs: {
    clip: {
      name: "clip"
    },
    conditioning_to: {
      name: "조건 대상"
    },
    gligen_textbox_model: {
      name: "gligen 텍스트상자 모델"
    },
    height: {
      name: "높이"
    },
    text: {
      name: "텍스트"
    },
    width: {
      name: "너비"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const GetVideoComponents$2 = {
  description: "비디오에서 모든 컴포넌트(프레임, 오디오, 프레임레이트)를 추출합니다.",
  display_name: "비디오 컴포넌트 추출",
  inputs: {
    video: {
      name: "비디오",
      tooltip: "컴포넌트를 추출할 비디오입니다."
    }
  },
  outputs: {
    "0": {
      name: "이미지"
    },
    "1": {
      name: "오디오"
    },
    "2": {
      name: "fps"
    }
  }
};
const GrowMask$2 = {
  display_name: "마스크 확장",
  inputs: {
    expand: {
      name: "확장"
    },
    mask: {
      name: "마스크"
    },
    tapered_corners: {
      name: "마름모 모서리"
    }
  }
};
const Hunyuan3Dv2Conditioning$2 = {
  display_name: "Hunyuan3Dv2Conditioning",
  inputs: {
    clip_vision_output: {
      name: "clip_vision_output"
    }
  },
  outputs: {
    "0": {
      name: "긍정 조건"
    },
    "1": {
      name: "부정 조건"
    }
  }
};
const Hunyuan3Dv2ConditioningMultiView$2 = {
  display_name: "Hunyuan3Dv2ConditioningMultiView",
  inputs: {
    back: {
      name: "뒤"
    },
    front: {
      name: "앞"
    },
    left: {
      name: "왼쪽"
    },
    right: {
      name: "오른쪽"
    }
  },
  outputs: {
    "0": {
      name: "긍정 조건"
    },
    "1": {
      name: "부정 조건"
    }
  }
};
const HunyuanImageToVideo$2 = {
  display_name: "HunyuanImageToVideo",
  inputs: {
    batch_size: {
      name: "배치 크기"
    },
    guidance_type: {
      name: "가이던스 유형"
    },
    height: {
      name: "높이"
    },
    length: {
      name: "길이"
    },
    positive: {
      name: "긍정 조건"
    },
    start_image: {
      name: "시작 이미지"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "너비"
    }
  },
  outputs: {
    "0": {
      name: "긍정 조건"
    },
    "1": {
      name: "잠재 비디오"
    }
  }
};
const HyperTile$2 = {
  display_name: "하이퍼 타일",
  inputs: {
    max_depth: {
      name: "최대 깊이"
    },
    model: {
      name: "모델"
    },
    scale_depth: {
      name: "스케일 깊이"
    },
    swap_size: {
      name: "스왑 크기"
    },
    tile_size: {
      name: "타일 크기"
    }
  }
};
const HypernetworkLoader$2 = {
  display_name: "하이퍼네트워크 로드",
  inputs: {
    hypernetwork_name: {
      name: "하이퍼네트워크 이름"
    },
    model: {
      name: "모델"
    },
    strength: {
      name: "강도"
    }
  }
};
const IdeogramV1$2 = {
  description: "Ideogram V1 모델을 사용하여 동기적으로 이미지를 생성합니다.\n\n이미지 링크는 제한된 기간 동안만 제공되며, 이미지를 보관하려면 반드시 다운로드해야 합니다.",
  display_name: "Ideogram V1",
  inputs: {
    aspect_ratio: {
      name: "종횡비",
      tooltip: "이미지 생성에 사용할 종횡비"
    },
    control_after_generate: {
      name: "생성 후 제어"
    },
    magic_prompt_option: {
      name: "매직 프롬프트 옵션",
      tooltip: "생성 시 MagicPrompt 사용 여부 결정"
    },
    negative_prompt: {
      name: "부정 프롬프트",
      tooltip: "이미지에서 제외할 내용을 설명"
    },
    num_images: {
      name: "이미지 수"
    },
    prompt: {
      name: "프롬프트",
      tooltip: "이미지 생성을 위한 프롬프트"
    },
    seed: {
      name: "시드"
    },
    turbo: {
      name: "터보",
      tooltip: "터보 모드 사용 여부 (더 빠른 생성, 품질 저하 가능성 있음)"
    }
  }
};
const IdeogramV2$2 = {
  description: "Ideogram V2 모델을 사용하여 동기적으로 이미지를 생성합니다.\n\n이미지 링크는 일정 기간 동안만 제공되며, 이미지를 보관하려면 반드시 다운로드해야 합니다.",
  display_name: "Ideogram V2",
  inputs: {
    aspect_ratio: {
      name: "종횡비",
      tooltip: "이미지 생성에 사용할 종횡비. 해상도가 AUTO로 설정되지 않은 경우 무시됩니다."
    },
    control_after_generate: {
      name: "생성 후 제어"
    },
    magic_prompt_option: {
      name: "매직 프롬프트 옵션",
      tooltip: "생성 시 MagicPrompt 사용 여부 결정"
    },
    negative_prompt: {
      name: "부정 프롬프트",
      tooltip: "이미지에서 제외할 내용을 설명"
    },
    num_images: {
      name: "이미지 수"
    },
    prompt: {
      name: "프롬프트",
      tooltip: "이미지 생성을 위한 프롬프트"
    },
    resolution: {
      name: "해상도",
      tooltip: "이미지 생성에 사용할 해상도. AUTO로 설정되지 않은 경우, aspect_ratio 설정을 덮어씁니다."
    },
    seed: {
      name: "시드"
    },
    style_type: {
      name: "스타일 타입",
      tooltip: "생성에 사용할 스타일 타입 (V2 전용)"
    },
    turbo: {
      name: "터보",
      tooltip: "터보 모드 사용 여부 (더 빠른 생성, 품질 저하 가능성 있음)"
    }
  }
};
const IdeogramV3$2 = {
  description: "Ideogram V3 모델을 사용하여 동기적으로 이미지를 생성합니다.\n\n텍스트 프롬프트를 통한 일반 이미지 생성과 mask를 사용한 이미지 편집을 모두 지원합니다.\n이미지 링크는 제한된 기간 동안만 제공되며, 이미지를 보관하려면 반드시 다운로드해야 합니다.",
  display_name: "Ideogram V3",
  inputs: {
    aspect_ratio: {
      name: "종횡비",
      tooltip: "이미지 생성을 위한 종횡비입니다. 해상도가 자동이 아닐 경우 무시됩니다."
    },
    control_after_generate: {
      name: "생성 후 제어"
    },
    image: {
      name: "이미지",
      tooltip: "이미지 편집을 위한 선택적 참조 이미지입니다."
    },
    magic_prompt_option: {
      name: "매직 프롬프트 옵션",
      tooltip: "생성 시 MagicPrompt 사용 여부를 결정합니다"
    },
    mask: {
      name: "마스크",
      tooltip: "인페인팅을 위한 선택적 마스크 (흰색 영역이 대체됩니다)"
    },
    num_images: {
      name: "이미지 수"
    },
    prompt: {
      name: "프롬프트",
      tooltip: "이미지 생성 또는 편집을 위한 프롬프트"
    },
    rendering_speed: {
      name: "렌더링 속도",
      tooltip: "생성 속도와 품질 간의 균형을 조절합니다"
    },
    resolution: {
      name: "해상도",
      tooltip: "이미지 생성을 위한 해상도입니다. 자동이 아닐 경우 종횡비 설정을 덮어씁니다."
    },
    seed: {
      name: "시드"
    }
  }
};
const ImageBatch$2 = {
  display_name: "이미지 배치",
  inputs: {
    image1: {
      name: "이미지1"
    },
    image2: {
      name: "이미지2"
    }
  }
};
const ImageBlend$2 = {
  display_name: "이미지 혼합",
  inputs: {
    blend_factor: {
      name: "혼합 계수"
    },
    blend_mode: {
      name: "혼합 모드"
    },
    image1: {
      name: "이미지1"
    },
    image2: {
      name: "이미지2"
    }
  }
};
const ImageBlur$2 = {
  display_name: "이미지 흐림",
  inputs: {
    blur_radius: {
      name: "블러 반경"
    },
    image: {
      name: "이미지"
    },
    sigma: {
      name: "시그마"
    }
  }
};
const ImageColorToMask$2 = {
  display_name: "이미지 색상을 마스크로 변환",
  inputs: {
    color: {
      name: "색상"
    },
    image: {
      name: "이미지"
    }
  }
};
const ImageCompositeMasked$2 = {
  display_name: "마스크된 이미지 합성",
  inputs: {
    destination: {
      name: "대상"
    },
    mask: {
      name: "마스크"
    },
    resize_source: {
      name: "원본 크기 조정"
    },
    source: {
      name: "원본"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const ImageCrop$2 = {
  display_name: "이미지 자르기",
  inputs: {
    height: {
      name: "높이"
    },
    image: {
      name: "이미지"
    },
    width: {
      name: "너비"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const ImageFromBatch$2 = {
  display_name: "배치에서 이미지 가져오기",
  inputs: {
    batch_index: {
      name: "배치 번호"
    },
    image: {
      name: "이미지"
    },
    length: {
      name: "길이"
    }
  }
};
const ImageInvert$2 = {
  display_name: "이미지 반전",
  inputs: {
    image: {
      name: "이미지"
    }
  }
};
const ImageOnlyCheckpointLoader$2 = {
  display_name: "이미지 전용 체크포인트 로드 (img2vid 모델)",
  inputs: {
    ckpt_name: {
      name: "체크포인트 파일명"
    }
  }
};
const ImageOnlyCheckpointSave$2 = {
  display_name: "이미지 전용 체크포인트 저장",
  inputs: {
    clip_vision: {
      name: "clip_vision"
    },
    filename_prefix: {
      name: "파일명 접두사"
    },
    model: {
      name: "모델"
    },
    vae: {
      name: "vae"
    }
  }
};
const ImagePadForOutpaint$2 = {
  display_name: "아웃페인팅을 위한 이미지 패딩",
  inputs: {
    bottom: {
      name: "아래"
    },
    feathering: {
      name: "가장자리 흐림"
    },
    image: {
      name: "이미지"
    },
    left: {
      name: "왼쪽"
    },
    right: {
      name: "오른쪽"
    },
    top: {
      name: "위"
    }
  }
};
const ImageQuantize$2 = {
  display_name: "이미지 양자화",
  inputs: {
    colors: {
      name: "색상"
    },
    dither: {
      name: "디더링"
    },
    image: {
      name: "이미지"
    }
  }
};
const ImageRGBToYUV$2 = {
  display_name: "ImageRGBToYUV",
  inputs: {
    image: {
      name: "이미지"
    }
  },
  outputs: {
    "0": {
      name: "Y"
    },
    "1": {
      name: "U"
    },
    "2": {
      name: "V"
    }
  }
};
const ImageScale$2 = {
  display_name: "이미지 확대",
  inputs: {
    crop: {
      name: "자르기"
    },
    height: {
      name: "높이"
    },
    image: {
      name: "이미지"
    },
    upscale_method: {
      name: "확대 방법"
    },
    width: {
      name: "너비"
    }
  }
};
const ImageScaleBy$2 = {
  display_name: "이미지 확대 비율",
  inputs: {
    image: {
      name: "이미지"
    },
    scale_by: {
      name: "배율"
    },
    upscale_method: {
      name: "확대 방법"
    }
  }
};
const ImageScaleToTotalPixels$2 = {
  display_name: "총 픽셀 수에 맞춰 이미지 크기 조정",
  inputs: {
    image: {
      name: "이미지"
    },
    megapixels: {
      name: "메가픽셀수"
    },
    upscale_method: {
      name: "확대 방법"
    }
  }
};
const ImageSharpen$2 = {
  display_name: "이미지 선명화",
  inputs: {
    alpha: {
      name: "알파"
    },
    image: {
      name: "이미지"
    },
    sharpen_radius: {
      name: "선명화 반경"
    },
    sigma: {
      name: "시그마"
    }
  }
};
const ImageToMask$2 = {
  display_name: "이미지를 마스크로 변환",
  inputs: {
    channel: {
      name: "채널"
    },
    image: {
      name: "이미지"
    }
  }
};
const ImageUpscaleWithModel$2 = {
  display_name: "모델을 사용한 이미지 확대",
  inputs: {
    image: {
      name: "이미지"
    },
    upscale_model: {
      name: "확대 모델"
    }
  }
};
const ImageYUVToRGB$2 = {
  display_name: "ImageYUVToRGB",
  inputs: {
    U: {
      name: "U"
    },
    V: {
      name: "V"
    },
    Y: {
      name: "Y"
    }
  }
};
const InpaintModelConditioning$2 = {
  display_name: "인페인팅 모델 조건 설정",
  inputs: {
    mask: {
      name: "마스크"
    },
    negative: {
      name: "부정 조건"
    },
    noise_mask: {
      name: "노이즈 마스크",
      tooltip: "잠재 데이터에 노이즈 마스크를 추가하여 샘플링이 마스크 내에서만 발생하도록 합니다. 모델에 따라 결과가 개선되거나 완전히 망가질 수 있습니다."
    },
    pixels: {
      name: "픽셀 이미지"
    },
    positive: {
      name: "긍정 조건"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "긍정 조건"
    },
    "1": {
      name: "부정 조건"
    },
    "2": {
      name: "잠재 데이터"
    }
  }
};
const InstructPixToPixConditioning$2 = {
  display_name: "InstructPixToPix 조건 설정",
  inputs: {
    negative: {
      name: "부정 조건"
    },
    pixels: {
      name: "픽셀"
    },
    positive: {
      name: "긍정 조건"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "긍정 조건"
    },
    "1": {
      name: "부정 조건"
    },
    "2": {
      name: "잠재 이미지"
    }
  }
};
const InvertMask$2 = {
  display_name: "마스크 반전",
  inputs: {
    mask: {
      name: "마스크"
    }
  }
};
const JoinImageWithAlpha$2 = {
  display_name: "알파와 함께 이미지 결합",
  inputs: {
    alpha: {
      name: "알파"
    },
    image: {
      name: "이미지"
    }
  }
};
const KSampler$2 = {
  description: "제공된 모델, 긍정 및 부정 조건을 사용하여 잠재 데이터를 디노이즈합니다.",
  display_name: "KSampler",
  inputs: {
    cfg: {
      name: "cfg",
      tooltip: "Classifier-Free Guidance 스케일은 창의성과 프롬프트 준수를 균형 있게 조절합니다. 값이 높을수록 프롬프트와 더 밀접하게 일치하는 이미지가 생성되지만, 너무 높은 값은 품질에 부정적인 영향을 미칠 수 있습니다."
    },
    control_after_generate: {
      name: "생성 후 제어"
    },
    denoise: {
      name: "노이즈 제거양",
      tooltip: "적용되는 노이즈 제거의 양으로, 낮은 값은 초기 이미지의 구조를 유지하여 이미지 간 샘플링을 가능하게 합니다."
    },
    latent_image: {
      name: "잠재 데이터",
      tooltip: "노이즈 제거할 잠재 데이터입니다."
    },
    model: {
      name: "모델",
      tooltip: "입력 잠재 데이터의 노이즈 제거에 사용되는 모델입니다."
    },
    negative: {
      name: "부정 조건",
      tooltip: "이미지에서 제외하고 싶은 속성을 설명하는 조건입니다."
    },
    positive: {
      name: "긍정 조건",
      tooltip: "이미지에 포함하고 싶은 속성을 설명하는 조건입니다."
    },
    sampler_name: {
      name: "샘플러 이름",
      tooltip: "샘플링 시 사용되는 알고리즘으로, 생성된 출력의 품질, 속도 및 스타일에 영향을 미칠 수 있습니다."
    },
    scheduler: {
      name: "스케줄러",
      tooltip: "스케줄러는 노이즈가 점진적으로 제거되어 이미지를 형성하는 방식을 제어합니다."
    },
    seed: {
      name: "시드",
      tooltip: "노이즈 생성을 위한 랜덤 시드입니다."
    },
    steps: {
      name: "스텝 수",
      tooltip: "노이즈 제거 과정에서 사용되는 단계 수입니다."
    }
  },
  outputs: {
    "0": {
      tooltip: "노이즈가 제거된 잠재 데이터입니다."
    }
  }
};
const KSamplerAdvanced$2 = {
  display_name: "고급 KSampler",
  inputs: {
    add_noise: {
      name: "노이즈 추가"
    },
    cfg: {
      name: "cfg"
    },
    control_after_generate: {
      name: "생성 후 제어"
    },
    end_at_step: {
      name: "종료 스텝"
    },
    latent_image: {
      name: "잠재 데이터"
    },
    model: {
      name: "모델"
    },
    negative: {
      name: "부정 조건"
    },
    noise_seed: {
      name: "노이즈 시드"
    },
    positive: {
      name: "긍정 조건"
    },
    return_with_leftover_noise: {
      name: "잔여 노이즈 반환"
    },
    sampler_name: {
      name: "샘플러 이름"
    },
    scheduler: {
      name: "스케줄러"
    },
    start_at_step: {
      name: "시작 스텝"
    },
    steps: {
      name: "스텝 수"
    }
  }
};
const KSamplerSelect$2 = {
  display_name: "KSampler (선택)",
  inputs: {
    sampler_name: {
      name: "샘플러 이름"
    }
  }
};
const KarrasScheduler$2 = {
  display_name: "Karras 스케줄러",
  inputs: {
    rho: {
      name: "rho"
    },
    sigma_max: {
      name: "최대 시그마"
    },
    sigma_min: {
      name: "최소 시그마"
    },
    steps: {
      name: "스텝 수"
    }
  }
};
const KlingCameraControlI2VNode$2 = {
  description: "정지 이미지를 실제 영화 촬영과 유사한 전문적인 카메라 움직임으로 시네마틱 비디오로 변환합니다. 원본 이미지에 초점을 유지하면서 줌, 회전, 패닝, 틸트, 1인칭 시점 등 가상 카메라 동작을 제어할 수 있습니다.",
  display_name: "Kling 이미지 투 비디오 (카메라 컨트롤)",
  inputs: {
    aspect_ratio: {
      name: "종횡비"
    },
    camera_control: {
      name: "카메라 제어",
      tooltip: "Kling Camera Controls 노드를 사용하여 생성할 수 있습니다. 비디오 생성 중 카메라의 움직임과 모션을 제어합니다."
    },
    cfg_scale: {
      name: "cfg 스케일"
    },
    negative_prompt: {
      name: "부정 프롬프트",
      tooltip: "비디오에서 제외할 내용을 설명"
    },
    prompt: {
      name: "프롬프트",
      tooltip: "비디오 생성을 위한 프롬프트"
    },
    start_frame: {
      name: "start_frame",
      tooltip: "참조 이미지 - URL 또는 Base64 인코딩 문자열, 10MB를 초과할 수 없으며, 해상도는 최소 300*300px, 가로세로 비율은 1:2.5 ~ 2.5:1 사이여야 합니다. Base64는 data:image 접두사를 포함하지 않아야 합니다."
    }
  },
  outputs: {
    "1": {
      name: "비디오 ID"
    },
    "2": {
      name: "길이"
    }
  }
};
const KlingCameraControlT2VNode$2 = {
  description: "텍스트를 실제 영화 촬영과 유사한 전문적인 카메라 움직임이 적용된 시네마틱 비디오로 변환합니다. 원본 텍스트에 초점을 유지하면서 줌, 회전, 팬, 틸트, 1인칭 시점 등 가상 카메라 동작을 제어할 수 있습니다.",
  display_name: "Kling 텍스트 투 비디오 (카메라 컨트롤)",
  inputs: {
    aspect_ratio: {
      name: "종횡비"
    },
    camera_control: {
      name: "카메라 제어",
      tooltip: "Kling 카메라 컨트롤 노드를 사용하여 생성할 수 있습니다. 비디오 생성 중 카메라의 움직임과 모션을 제어합니다."
    },
    cfg_scale: {
      name: "cfg 스케일"
    },
    negative_prompt: {
      name: "부정 프롬프트",
      tooltip: "비디오에서 제외할 내용을 설명"
    },
    prompt: {
      name: "프롬프트",
      tooltip: "비디오 생성을 위한 프롬프트"
    }
  },
  outputs: {
    "1": {
      name: "비디오 ID"
    },
    "2": {
      name: "길이"
    }
  }
};
const KlingCameraControls$2 = {
  description: "Kling 카메라 컨트롤 및 모션 제어 효과를 위한 구성 옵션을 지정할 수 있습니다.",
  display_name: "Kling 카메라 컨트롤",
  inputs: {
    camera_control_type: {
      name: "카메라 제어 종류"
    },
    horizontal_movement: {
      name: "수평 이동",
      tooltip: "카메라의 수평 축(x축) 이동을 제어합니다. 음수는 왼쪽, 양수는 오른쪽을 의미합니다."
    },
    pan: {
      name: "수평 회전",
      tooltip: "카메라의 수직 평면(x축) 회전을 제어합니다. 음수는 아래쪽 회전, 양수는 위쪽 회전을 의미합니다."
    },
    roll: {
      name: "축 회전",
      tooltip: "카메라의 롤링(z축) 정도를 제어합니다. 음수는 반시계 방향, 양수는 시계 방향을 의미합니다."
    },
    tilt: {
      name: "상하 회전",
      tooltip: "카메라의 수평 평면(y축) 회전을 제어합니다. 음수는 왼쪽 회전, 양수는 오른쪽 회전을 의미합니다."
    },
    vertical_movement: {
      name: "수직 이동",
      tooltip: "카메라의 수직 축(y축) 이동을 제어합니다. 음수는 아래쪽, 양수는 위쪽을 의미합니다."
    },
    zoom: {
      name: "확대/축소",
      tooltip: "카메라의 초점 거리 변화를 제어합니다. 음수는 좁은 시야각, 양수는 넓은 시야각을 의미합니다."
    }
  },
  outputs: {
    "0": {
      name: "카메라 제어"
    }
  }
};
const KlingDualCharacterVideoEffectNode$2 = {
  description: "'효과 장면'에 따라 비디오를 생성할 때 다양한 특수 효과를 적용합니다. 첫 번째 이미지는 합성의 왼쪽에, 두 번째 이미지는 오른쪽에 배치됩니다.",
  display_name: "Kling 듀얼 캐릭터 비디오 효과",
  inputs: {
    duration: {
      name: "길이"
    },
    effect_scene: {
      name: "효과 장면"
    },
    image_left: {
      name: "왼쪽 이미지",
      tooltip: "왼쪽 이미지"
    },
    image_right: {
      name: "오른쪽 이미지",
      tooltip: "오른쪽 이미지"
    },
    mode: {
      name: "모드"
    },
    model_name: {
      name: "모델명"
    }
  },
  outputs: {
    "1": {
      name: "길이"
    }
  }
};
const KlingImage2VideoNode$2 = {
  description: "Kling 이미지에서 비디오로 노드",
  display_name: "Kling 비디오 생성 (이미지 → 비디오)",
  inputs: {
    aspect_ratio: {
      name: "종횡비"
    },
    cfg_scale: {
      name: "cfg 스케일"
    },
    duration: {
      name: "길이"
    },
    mode: {
      name: "모드"
    },
    model_name: {
      name: "모델명"
    },
    negative_prompt: {
      name: "부정 프롬프트",
      tooltip: "비디오에서 제외할 내용을 설명"
    },
    prompt: {
      name: "프롬프트",
      tooltip: "비디오 생성을 위한 프롬프트"
    },
    start_frame: {
      name: "start_frame",
      tooltip: "참조 이미지 - URL 또는 Base64 인코딩 문자열, 10MB를 초과할 수 없으며, 해상도는 최소 300*300px, 가로세로 비율은 1:2.5 ~ 2.5:1 사이여야 합니다. Base64에는 data:image 접두사가 포함되지 않아야 합니다."
    }
  },
  outputs: {
    "1": {
      name: "비디오 ID"
    },
    "2": {
      name: "길이"
    }
  }
};
const KlingImageGenerationNode$2 = {
  description: "Kling 이미지 생성 노드. 텍스트 프롬프트와 선택적 참조 이미지를 사용하여 이미지를 생성합니다.",
  display_name: "Kling 이미지 생성 (텍스트 → 이미지)",
  inputs: {
    aspect_ratio: {
      name: "종횡비"
    },
    human_fidelity: {
      name: "사람 충실도",
      tooltip: "피사체 참조 유사도"
    },
    image: {
      name: "이미지"
    },
    image_fidelity: {
      name: "이미지 충실도",
      tooltip: "사용자 업로드 이미지의 참조 강도"
    },
    image_type: {
      name: "이미지 종류"
    },
    model_name: {
      name: "모델 명"
    },
    n: {
      name: "개수",
      tooltip: "생성할 이미지 수"
    },
    negative_prompt: {
      name: "부정 프롬프트",
      tooltip: "이미지에서 제외할 내용을 설명"
    },
    prompt: {
      name: "프롬프트",
      tooltip: "이미지 생성을 위한 프롬프트"
    }
  }
};
const KlingLipSyncAudioToVideoNode$2 = {
  description: "Kling 립싱크 오디오 투 비디오 노드. 비디오 파일의 입 모양 움직임을 오디오 파일의 오디오 내용에 맞게 동기화합니다.",
  display_name: "Kling 립싱크 비디오 오디오와 함께",
  inputs: {
    audio: {
      name: "오디오"
    },
    video: {
      name: "비디오"
    },
    voice_language: {
      name: "음성 언어"
    }
  },
  outputs: {
    "1": {
      name: "비디오 ID"
    },
    "2": {
      name: "재생 시간"
    }
  }
};
const KlingLipSyncTextToVideoNode$2 = {
  description: "Kling 립싱크 텍스트-투-비디오 노드입니다. 비디오 파일에서 입 모양 움직임을 텍스트 프롬프트에 맞춰 동기화합니다.",
  display_name: "Kling 립싱크 비디오 (텍스트 기반)",
  inputs: {
    text: {
      name: "텍스트",
      tooltip: "립싱크 비디오 생성을 위한 텍스트 내용입니다. text2video 모드에서 필수입니다. 최대 길이는 120자입니다."
    },
    video: {
      name: "비디오"
    },
    voice: {
      name: "음성"
    },
    voice_speed: {
      name: "음성 속도",
      tooltip: "음성 속도. 유효 범위: 0.8~2.0, 소수점 한 자리까지 입력 가능합니다."
    }
  },
  outputs: {
    "1": {
      name: "비디오 ID"
    },
    "2": {
      name: "길이"
    }
  }
};
const KlingSingleImageVideoEffectNode$2 = {
  description: "'효과 장면'에 따라 비디오를 생성할 때 다양한 특수 효과를 적용합니다.",
  display_name: "Kling 비디오 효과",
  inputs: {
    duration: {
      name: "길이"
    },
    effect_scene: {
      name: "효과 장면"
    },
    image: {
      name: "이미지",
      tooltip: "참조 이미지. URL 또는 Base64 인코딩 문자열(data:image 접두사 제외). 파일 크기는 10MB를 초과할 수 없으며, 해상도는 최소 300*300px, 가로세로 비율은 1:2.5 ~ 2.5:1 사이여야 합니다."
    },
    model_name: {
      name: "모델 명"
    }
  },
  outputs: {
    "1": {
      name: "비디오 ID"
    },
    "2": {
      name: "길이"
    }
  }
};
const KlingStartEndFrameNode$2 = {
  description: "제공한 시작 이미지와 종료 이미지 사이를 전환하는 비디오 시퀀스를 생성합니다. 이 노드는 중간의 모든 프레임을 만들어 첫 프레임에서 마지막 프레임까지 부드러운 변환을 제공합니다.",
  display_name: "Kling 비디오 생성 (시작-끝 프레임)",
  inputs: {
    aspect_ratio: {
      name: "종횡비"
    },
    cfg_scale: {
      name: "cfg 스케일"
    },
    end_frame: {
      name: "끝 프레임",
      tooltip: "참조 이미지 - 끝 프레임 제어. URL 또는 Base64 인코딩 문자열, 10MB를 초과할 수 없으며, 해상도는 최소 300*300px이어야 합니다. Base64에는 data:image 접두사가 포함되지 않아야 합니다."
    },
    mode: {
      name: "모드",
      tooltip: "비디오 생성을 위한 구성. 형식: 모드 / 길이 / 모델명"
    },
    negative_prompt: {
      name: "부정 프롬프트",
      tooltip: "비디오에서 제외할 내용을 설명"
    },
    prompt: {
      name: "프롬프트",
      tooltip: "비디오 생성을 위한 프롬프트"
    },
    start_frame: {
      name: "시작 프레임",
      tooltip: "참조 이미지 - URL 또는 Base64 인코딩 문자열, 10MB를 초과할 수 없으며, 해상도는 최소 300*300px, 가로세로 비율은 1:2.5 ~ 2.5:1 사이여야 합니다. Base64에는 data:image 접두사가 포함되지 않아야 합니다."
    }
  },
  outputs: {
    "1": {
      name: "비디오 ID"
    },
    "2": {
      name: "길이"
    }
  }
};
const KlingTextToVideoNode$2 = {
  description: "Kling 텍스트 투 비디오 노드",
  display_name: "Kling 비디오 생성 (텍스트 → 비디오)",
  inputs: {
    aspect_ratio: {
      name: "종횡비"
    },
    cfg_scale: {
      name: "cfg 스케일"
    },
    mode: {
      name: "모드",
      tooltip: "비디오 생성을 위한 설정 (형식: 모드 / 길이 / 모델명)"
    },
    negative_prompt: {
      name: "부정 프롬프트",
      tooltip: "부정 텍스트 프롬프트"
    },
    prompt: {
      name: "프롬프트",
      tooltip: "긍정 텍스트 프롬프트"
    }
  },
  outputs: {
    "1": {
      name: "비디오 ID"
    },
    "2": {
      name: "길이"
    }
  }
};
const KlingVideoExtendNode$2 = {
  description: "Kling 비디오 확장 노드입니다. 다른 Kling 노드에서 생성된 비디오를 확장합니다. video_id는 다른 Kling 노드를 사용하여 생성됩니다.",
  display_name: "Kling 비디오 확장",
  inputs: {
    cfg_scale: {
      name: "cfg 스케일"
    },
    negative_prompt: {
      name: "부정 프롬프트",
      tooltip: "확장된 비디오에서 피하고 싶은 요소를 위한 부정적인 텍스트 프롬프트"
    },
    prompt: {
      name: "프롬프트",
      tooltip: "비디오 확장을 안내하는 긍정적인 텍스트 프롬프트"
    },
    video_id: {
      name: "비디오 ID",
      tooltip: "확장할 비디오의 ID입니다. 텍스트-투-비디오, 이미지-투-비디오, 이전 비디오 확장 작업에서 생성된 비디오를 지원합니다. 확장 후 총 길이는 3분을 초과할 수 없습니다."
    }
  },
  outputs: {
    "1": {
      name: "비디오 ID"
    },
    "2": {
      name: "길이"
    }
  }
};
const KlingVirtualTryOnNode$2 = {
  description: "Kling 가상 착용 노드입니다. 인물 이미지와 의류 이미지를 입력하여 인물에게 의류를 착용시킵니다.",
  display_name: "Kling 가상 착용",
  inputs: {
    cloth_image: {
      name: "의상 이미지"
    },
    human_image: {
      name: "사람 이미지"
    },
    model_name: {
      name: "모델 명"
    }
  }
};
const LTXVAddGuide$2 = {
  display_name: "LTXV 가이드 추가",
  inputs: {
    frame_idx: {
      name: "프레임 번호",
      tooltip: "조건을 시작할 프레임 번호. 단일 프레임 이미지 또는 1-8 프레임의 비디오의 경우 어떤 프레임 번호 값도 허용됩니다. 9+ 프레임의 비디오의 경우, 프레임 번호는 8의 배수여야 합니다. 그렇지 않으면 가장 가까운 8의 배수로 내림됩니다. 음수 값은 비디오의 끝에서부터 계산됩니다."
    },
    image: {
      name: "이미지",
      tooltip: "잠재 비디오에 조건을 부여하는 이미지 또는 비디오. 8*n + 1 프레임이어야 합니다. 비디오가 8*n + 1 프레임이 아닌 경우 가장 가까운 8*n + 1 프레임으로 자릅니다."
    },
    latent: {
      name: "잠재 비디오"
    },
    negative: {
      name: "부정 조건"
    },
    positive: {
      name: "긍정 조건"
    },
    strength: {
      name: "강도"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "긍정 조건"
    },
    "1": {
      name: "부정 조건"
    },
    "2": {
      name: "잠재 비디오"
    }
  }
};
const LTXVConditioning$2 = {
  display_name: "LTXV 조건 설정",
  inputs: {
    frame_rate: {
      name: "프레임율"
    },
    negative: {
      name: "부정 조건"
    },
    positive: {
      name: "긍정 조건"
    }
  },
  outputs: {
    "0": {
      name: "긍정 조건"
    },
    "1": {
      name: "부정 조건"
    }
  }
};
const LTXVCropGuides$2 = {
  display_name: "LTXV 가이드 자르기",
  inputs: {
    latent: {
      name: "잠재 비디오"
    },
    negative: {
      name: "부정 조건"
    },
    positive: {
      name: "긍정 조건"
    }
  },
  outputs: {
    "0": {
      name: "긍정 조건"
    },
    "1": {
      name: "부정 조건"
    },
    "2": {
      name: "잠재 비디오"
    }
  }
};
const LTXVImgToVideo$2 = {
  display_name: "LTXV 비디오 생성 (이미지 → 비디오)",
  inputs: {
    batch_size: {
      name: "배치 크기"
    },
    height: {
      name: "높이"
    },
    image: {
      name: "이미지"
    },
    length: {
      name: "길이"
    },
    negative: {
      name: "부정 조건"
    },
    positive: {
      name: "긍정 조건"
    },
    strength: {
      name: "강도"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "너비"
    }
  },
  outputs: {
    "0": {
      name: "긍정 조건"
    },
    "1": {
      name: "부정 조건"
    },
    "2": {
      name: "잠재 데이터"
    }
  }
};
const LTXVPreprocess$2 = {
  display_name: "LTXV 전처리",
  inputs: {
    image: {
      name: "이미지"
    },
    img_compression: {
      name: "이미지 압축",
      tooltip: "이미지에 적용할 압축의 양."
    }
  },
  outputs: {
    "0": {
      name: "출력 이미지"
    }
  }
};
const LTXVScheduler$2 = {
  display_name: "LTXV 스케줄러",
  inputs: {
    base_shift: {
      name: "기반 시프트"
    },
    latent: {
      name: "잠재 비디오"
    },
    max_shift: {
      name: "최대 시프트"
    },
    steps: {
      name: "스텝 수"
    },
    stretch: {
      name: "늘이기",
      tooltip: "시그마를 [종료값, 1] 범위로 늘립니다."
    },
    terminal: {
      name: "종료값",
      tooltip: "늘린 후 시그마의 종료값입니다."
    }
  }
};
const LaplaceScheduler$2 = {
  display_name: "라플라스 스케줄러",
  inputs: {
    beta: {
      name: "beta"
    },
    mu: {
      name: "mu"
    },
    sigma_max: {
      name: "최대 시그마"
    },
    sigma_min: {
      name: "최소 시그마"
    },
    steps: {
      name: "스텝 수"
    }
  }
};
const LatentAdd$2 = {
  display_name: "잠재 데이터 연산 (더하기)",
  inputs: {
    samples1: {
      name: "잠재 데이터1"
    },
    samples2: {
      name: "잠재 데이터2"
    }
  }
};
const LatentApplyOperation$2 = {
  display_name: "잠재 데이터 연산 (연산 적용)",
  inputs: {
    operation: {
      name: "연산"
    },
    samples: {
      name: "잠재 데이터"
    }
  }
};
const LatentApplyOperationCFG$2 = {
  display_name: "잠재 데이터 CFG 연산 (연산 적용)",
  inputs: {
    model: {
      name: "모델"
    },
    operation: {
      name: "연산"
    }
  }
};
const LatentBatch$2 = {
  display_name: "잠재 데이터 배치 연결",
  inputs: {
    samples1: {
      name: "잠재 데이터1"
    },
    samples2: {
      name: "잠재 데이터2"
    }
  }
};
const LatentBatchSeedBehavior$2 = {
  display_name: "잠재 데이터 배치 시드 동작",
  inputs: {
    samples: {
      name: "잠재 데이터"
    },
    seed_behavior: {
      name: "시드 동작"
    }
  }
};
const LatentBlend$2 = {
  display_name: "잠재 데이터 연산 (혼합)",
  inputs: {
    blend_factor: {
      name: "혼합 계수"
    },
    samples1: {
      name: "잠재 데이터1"
    },
    samples2: {
      name: "잠재 데이터2"
    }
  }
};
const LatentComposite$2 = {
  display_name: "잠재 데이터 합성 (위치 기반)",
  inputs: {
    feather: {
      name: "가장자리 흐림"
    },
    samples_from: {
      name: "추가 잠재 데이터"
    },
    samples_to: {
      name: "대상 잠재 데이터"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const LatentCompositeMasked$2 = {
  display_name: "잠재 데이터 합성 (마스크 기반)",
  inputs: {
    destination: {
      name: "대상"
    },
    mask: {
      name: "마스크"
    },
    resize_source: {
      name: "원본 크기 조정"
    },
    source: {
      name: "원본"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const LatentCrop$2 = {
  display_name: "잠재 데이터 자르기",
  inputs: {
    height: {
      name: "높이"
    },
    samples: {
      name: "잠재 데이터"
    },
    width: {
      name: "너비"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const LatentFlip$2 = {
  display_name: "잠재 데이터 연산 (뒤집기)",
  inputs: {
    flip_method: {
      name: "뒤집기 방법"
    },
    samples: {
      name: "잠재 데이터"
    }
  }
};
const LatentFromBatch$2 = {
  display_name: "배치에서 잠재 데이터 가져오기",
  inputs: {
    batch_index: {
      name: "배치_인덱스"
    },
    length: {
      name: "길이"
    },
    samples: {
      name: "잠재 데이터"
    }
  }
};
const LatentInterpolate$2 = {
  display_name: "잠재 데이터 연산 (보간)",
  inputs: {
    ratio: {
      name: "비율"
    },
    samples1: {
      name: "잠재 데이터1"
    },
    samples2: {
      name: "잠재 데이터2"
    }
  }
};
const LatentMultiply$2 = {
  display_name: "잠재 데이터 연산 (곱하기)",
  inputs: {
    multiplier: {
      name: "배율"
    },
    samples: {
      name: "잠재 데이터"
    }
  }
};
const LatentOperationSharpen$2 = {
  display_name: "잠재 데이터 연산 (선명화)",
  inputs: {
    alpha: {
      name: "알파"
    },
    sharpen_radius: {
      name: "선명화 반경"
    },
    sigma: {
      name: "시그마"
    }
  }
};
const LatentOperationTonemapReinhard$2 = {
  display_name: "잠재 데이터 연산 (톤맵 레인하르트)",
  inputs: {
    multiplier: {
      name: "배율"
    }
  }
};
const LatentRotate$2 = {
  display_name: "잠재 데이터 연산 (회전)",
  inputs: {
    rotation: {
      name: "회전"
    },
    samples: {
      name: "잠재 데이터"
    }
  }
};
const LatentSubtract$2 = {
  display_name: "잠재 데이터 연산 (빼기)",
  inputs: {
    samples1: {
      name: "잠재 데이터1"
    },
    samples2: {
      name: "잠재 데이터2"
    }
  }
};
const LatentUpscale$2 = {
  display_name: "잠재 데이터 크기 조정",
  inputs: {
    crop: {
      name: "자르기"
    },
    height: {
      name: "높이"
    },
    samples: {
      name: "잠재 데이터"
    },
    upscale_method: {
      name: "업스케일 방법"
    },
    width: {
      name: "너비"
    }
  }
};
const LatentUpscaleBy$2 = {
  display_name: "잠재 데이터 크기 배율 조정",
  inputs: {
    samples: {
      name: "잠재 데이터"
    },
    scale_by: {
      name: "확대율"
    },
    upscale_method: {
      name: "확대 방법"
    }
  }
};
const Load3D$2 = {
  display_name: "3D 로드",
  inputs: {
    clear: {},
    height: {
      name: "높이"
    },
    image: {
      name: "이미지"
    },
    model_file: {
      name: "모델 파일"
    },
    "upload 3d model": {},
    width: {
      name: "너비"
    }
  },
  outputs: [
    null,
    null,
    null,
    {
      name: "노멀"
    },
    {
      name: "라인아트"
    },
    {
      name: "카메라 정보"
    }
  ]
};
const Load3DAnimation$2 = {
  display_name: "3D 로드 - 애니메이션",
  inputs: {
    clear: {},
    height: {
      name: "높이"
    },
    image: {
      name: "이미지"
    },
    model_file: {
      name: "모델 파일"
    },
    "upload 3d model": {},
    width: {
      name: "너비"
    }
  },
  outputs: [
    null,
    null,
    null,
    {
      name: "노멀"
    },
    {
      name: "카메라 정보"
    }
  ]
};
const LoadAudio$2 = {
  display_name: "오디오 로드",
  inputs: {
    audio: {
      name: "오디오"
    },
    audioUI: {
      name: "오디오UI"
    },
    upload: {
      name: "업로드할 파일 선택"
    }
  }
};
const LoadImage$2 = {
  display_name: "이미지 로드",
  inputs: {
    image: {
      name: "이미지"
    },
    upload: {
      name: "업로드할 파일 선택"
    }
  }
};
const LoadImageMask$2 = {
  display_name: "마스크 이미지 로드",
  inputs: {
    channel: {
      name: "채널"
    },
    image: {
      name: "이미지"
    },
    upload: {
      name: "업로드할 파일 선택"
    }
  }
};
const LoadImageOutput$2 = {
  description: "입력(input) 폴더 대신 출력(output) 폴더에서 이미지를 로드합니다. 새로 고침 버튼을 클릭하면 노드는 이미지 목록을 업데이트하고 자동으로 첫 번째 이미지를 선택하여 쉬운 반복을 가능하게 합니다.",
  display_name: "이미지 로드 (출력에서)",
  inputs: {
    image: {
      name: "이미지"
    },
    refresh: {},
    upload: {
      name: "업로드할 파일 선택"
    }
  }
};
const LoadLatent$2 = {
  display_name: "잠재 데이터 로드",
  inputs: {
    latent: {
      name: "잠재 데이터"
    }
  }
};
const LoadVideo$2 = {
  display_name: "비디오 불러오기",
  inputs: {
    file: {
      name: "파일"
    },
    upload: {
      name: "업로드할 파일 선택"
    }
  }
};
const LoraLoader$2 = {
  description: "LoRA는 확산 모델과 CLIP 모델을 부분적으로 변경해서, 잠재 데이터의 노이즈 제거 방향을 바꿉니다. 여러 LoRA 노드를 연결할 수 있습니다.",
  display_name: "LoRA 로드",
  inputs: {
    clip: {
      name: "clip",
      tooltip: "LoRA가 적용될 CLIP 모델입니다."
    },
    lora_name: {
      name: "LoRA 이름",
      tooltip: "LoRA의 이름입니다."
    },
    model: {
      name: "모델",
      tooltip: "LoRA가 적용될 확산 모델입니다."
    },
    strength_clip: {
      name: "clip 강도",
      tooltip: "CLIP 모델을 적용하는 강도입니다. 이 값은 음수가 될 수 있습니다."
    },
    strength_model: {
      name: "모델 강도",
      tooltip: "확산 모델을 적용하는 강도입니다. 이 값은 음수가 될 수 있습니다."
    }
  },
  outputs: {
    "0": {
      tooltip: "수정된 확산 모델입니다."
    },
    "1": {
      tooltip: "수정된 CLIP 모델입니다."
    }
  }
};
const LoraLoaderModelOnly$2 = {
  description: "LoRA는 확산 모델과 CLIP 모델을 부분적으로 변경해서, 잠재 데이터의 노이즈 제거 방향을 바꿉니다. 여러 LoRA 노드를 연결할 수 있습니다. (이 노드는 CLIP 모델은 로드하지 않습니다.)",
  display_name: "LoRA 로드 (모델 전용)",
  inputs: {
    lora_name: {
      name: "LoRA 이름"
    },
    model: {
      name: "모델"
    },
    strength_model: {
      name: "모델 강도"
    }
  },
  outputs: {
    "0": {
      tooltip: "수정된 확산 모델입니다."
    }
  }
};
const LoraSave$2 = {
  display_name: "LoRA 추출 및 저장",
  inputs: {
    bias_diff: {
      name: "차이 편향"
    },
    filename_prefix: {
      name: "파일명 접두사"
    },
    lora_type: {
      name: "LoRA 유형"
    },
    model_diff: {
      name: "모델 차이",
      tooltip: "LoRA로 변환 될 ModelSubtract 출력입니다."
    },
    rank: {
      name: "순위"
    },
    text_encoder_diff: {
      name: "텍스트 인코더 차이",
      tooltip: "LoRA로 변환 될 CLIPSubtract 출력입니다."
    }
  }
};
const LotusConditioning$2 = {
  display_name: "Lotus 조건 설정",
  outputs: {
    "0": {
      name: "조건"
    }
  }
};
const LumaConceptsNode$2 = {
  description: "루마 텍스트 투 비디오 및 루마 이미지 투 비디오 노드에서 사용할 하나 이상의 카메라 컨셉을 보관합니다.",
  display_name: "Luma 컨셉",
  inputs: {
    concept1: {
      name: "컨셉1"
    },
    concept2: {
      name: "컨셉2"
    },
    concept3: {
      name: "컨셉3"
    },
    concept4: {
      name: "컨셉4"
    },
    luma_concepts: {
      name: "luma 컨셉",
      tooltip: "여기에 선택한 컨셉에 추가할 선택적 카메라 컨셉입니다."
    }
  },
  outputs: {
    "0": {
      name: "luma 컨셉"
    }
  }
};
const LumaImageModifyNode$2 = {
  description: "프롬프트와 종횡비에 따라 이미지를 동기적으로 수정합니다.",
  display_name: "Luma 이미지 생성 (이미지 → 이미지)",
  inputs: {
    control_after_generate: {
      name: "생성 후 제어"
    },
    image: {
      name: "이미지"
    },
    image_weight: {
      name: "이미지 가중치",
      tooltip: "이미지의 가중치; 1.0에 가까울수록 이미지가 덜 수정됩니다."
    },
    model: {
      name: "모델"
    },
    prompt: {
      name: "프롬프트",
      tooltip: "이미지 생성을 위한 프롬프트"
    },
    seed: {
      name: "시드",
      tooltip: "노드를 다시 실행할지 결정하는 시드; 실제 결과는 시드와 상관없이 비결정적입니다."
    }
  }
};
const LumaImageNode$2 = {
  description: "프롬프트와 종횡비에 따라 이미지를 동기적으로 생성합니다.",
  display_name: "Luma 이미지 생성 (텍스트 → 이미지)",
  inputs: {
    aspect_ratio: {
      name: "종횡비"
    },
    character_image: {
      name: "캐릭터 참조 이미지",
      tooltip: "캐릭터 참조 이미지; 여러 장의 배치가 가능하며, 최대 4개의 이미지를 사용할 수 있습니다."
    },
    control_after_generate: {
      name: "생성 후 제어"
    },
    image_luma_ref: {
      name: "Luma 참조 이미지",
      tooltip: "입력 이미지를 사용해 생성에 영향을 주는 Luma Reference 노드 연결; 최대 4개의 이미지를 사용할 수 있습니다."
    },
    model: {
      name: "모델"
    },
    prompt: {
      name: "프롬프트",
      tooltip: "이미지 생성을 위한 프롬프트"
    },
    seed: {
      name: "시드",
      tooltip: "노드가 다시 실행될지 결정하는 시드; 실제 결과는 시드와 관계없이 비결정적입니다."
    },
    style_image: {
      name: "스타일 참조 이미지",
      tooltip: "스타일 참조 이미지; 1개의 이미지만 사용됩니다."
    },
    style_image_weight: {
      name: "스타일 이미지 가중치",
      tooltip: "스타일 이미지의 가중치. 스타일 이미지가 제공되지 않으면 무시됩니다."
    }
  }
};
const LumaImageToVideoNode$2 = {
  description: "프롬프트, 입력 이미지, output_size를 기반으로 동기적으로 비디오를 생성합니다.",
  display_name: "Luma 이미지 → 비디오",
  inputs: {
    control_after_generate: {
      name: "생성 후 제어"
    },
    duration: {
      name: "길이"
    },
    first_image: {
      name: "첫 이미지",
      tooltip: "생성된 비디오의 첫 프레임."
    },
    last_image: {
      name: "마지막 이미지",
      tooltip: "생성된 비디오의 마지막 프레임."
    },
    loop: {
      name: "루프"
    },
    luma_concepts: {
      name: "Luma 컨셉",
      tooltip: "선택 사항: Luma 컨셉 노드를 통해 카메라 움직임을 지정하는 카메라 컨셉."
    },
    model: {
      name: "모델"
    },
    prompt: {
      name: "프롬프트",
      tooltip: "비디오 생성을 위한 프롬프트"
    },
    resolution: {
      name: "해상도"
    },
    seed: {
      name: "시드",
      tooltip: "노드가 다시 실행되어야 하는지 결정하는 시드입니다. 실제 결과는 시드와 상관없이 비결정적입니다."
    }
  }
};
const LumaReferenceNode$2 = {
  description: "Luma 이미지 생성 노드에서 사용할 이미지와 가중치를 보관합니다.",
  display_name: "Luma 이미지 참조",
  inputs: {
    image: {
      name: "이미지",
      tooltip: "참조로 사용할 이미지입니다."
    },
    luma_ref: {
      name: "luma_ref"
    },
    weight: {
      name: "가중치",
      tooltip: "이미지 참조의 가중치입니다."
    }
  },
  outputs: {
    "0": {
      name: "luma_ref"
    }
  }
};
const LumaVideoNode$2 = {
  description: "프롬프트와 output_size에 따라 동기적으로 비디오를 생성합니다.",
  display_name: "Luma 텍스트 투 비디오",
  inputs: {
    aspect_ratio: {
      name: "종횡비"
    },
    control_after_generate: {
      name: "생성 후 제어"
    },
    duration: {
      name: "길이"
    },
    loop: {
      name: "루프"
    },
    luma_concepts: {
      name: "Luma 컨셉",
      tooltip: "카메라 움직임을 제어하기 위한 선택적 Camera Concepts (Luma Concepts 노드 사용)."
    },
    model: {
      name: "모델"
    },
    prompt: {
      name: "프롬프트",
      tooltip: "비디오 생성을 위한 프롬프트"
    },
    resolution: {
      name: "해상도"
    },
    seed: {
      name: "시드",
      tooltip: "노드가 다시 실행되어야 하는지 결정하는 시드입니다. 실제 결과는 시드와 관계없이 비결정적입니다."
    }
  }
};
const Mahiro$2 = {
  description: "노이즈 제거의 '방향'을 긍정 조건과 부정 조건 차에 의한 것 보다는 긍정 조건 방향으로 더 크게 작동하도록 가이더 동작을 변경합니다.",
  display_name: "마히로",
  inputs: {
    model: {
      name: "모델"
    }
  },
  outputs: {
    "0": {
      name: "변경된 모델"
    }
  }
};
const MaskComposite$2 = {
  display_name: "마스크 합성",
  inputs: {
    destination: {
      name: "대상"
    },
    operation: {
      name: "연산"
    },
    source: {
      name: "원본"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const MaskPreview$2 = {
  description: "입력 이미지를 ComfyUI 출력 디렉터리에 저장합니다.",
  display_name: "마스크 미리보기",
  inputs: {
    mask: {
      name: "마스크"
    }
  }
};
const MaskToImage$2 = {
  display_name: "마스크를 이미지로 변환",
  inputs: {
    mask: {
      name: "마스크"
    }
  }
};
const MinimaxImageToVideoNode$2 = {
  description: "MiniMax의 API를 사용하여 이미지와 프롬프트로부터 비디오를 생성합니다",
  display_name: "MiniMax 이미지에서 비디오로",
  inputs: {
    control_after_generate: {
      name: "생성 후 제어"
    },
    image: {
      name: "이미지",
      tooltip: "비디오 생성의 첫 프레임으로 사용할 이미지"
    },
    model: {
      name: "모델",
      tooltip: "비디오 생성에 사용할 모델"
    },
    prompt_text: {
      name: "프롬프트 텍스트",
      tooltip: "비디오 생성을 안내할 텍스트 프롬프트"
    },
    seed: {
      name: "시드",
      tooltip: "노이즈 생성을 위해 사용되는 랜덤 시드입니다."
    }
  }
};
const MinimaxTextToVideoNode$2 = {
  description: "MiniMax의 API를 사용하여 프롬프트로부터 비디오를 생성합니다",
  display_name: "MiniMax 텍스트 투 비디오",
  inputs: {
    control_after_generate: {
      name: "생성 후 제어"
    },
    model: {
      name: "모델",
      tooltip: "비디오 생성을 위해 사용할 모델"
    },
    prompt_text: {
      name: "프롬프트 텍스트",
      tooltip: "비디오 생성을 안내할 텍스트 프롬프트"
    },
    seed: {
      name: "시드",
      tooltip: "노이즈 생성을 위해 사용되는 랜덤 시드입니다."
    }
  }
};
const ModelComputeDtype$2 = {
  display_name: "ModelComputeDtype",
  inputs: {
    dtype: {
      name: "dtype"
    },
    model: {
      name: "모델"
    }
  }
};
const ModelMergeAdd$2 = {
  display_name: "모델 병합 (더하기)",
  inputs: {
    model1: {
      name: "모델1"
    },
    model2: {
      name: "모델2"
    }
  }
};
const ModelMergeAuraflow$2 = {
  display_name: "모델 병합 (AuraFlow)",
  inputs: {
    cond_seq_linear_: {
      name: "cond_seq_linear."
    },
    double_layers_0_: {
      name: "double_layers.0."
    },
    double_layers_1_: {
      name: "double_layers.1."
    },
    double_layers_2_: {
      name: "double_layers.2."
    },
    double_layers_3_: {
      name: "double_layers.3."
    },
    final_linear_: {
      name: "final_linear."
    },
    init_x_linear_: {
      name: "init_x_linear."
    },
    modF_: {
      name: "modF."
    },
    model1: {
      name: "모델1"
    },
    model2: {
      name: "모델2"
    },
    positional_encoding: {
      name: "positional_encoding"
    },
    register_tokens: {
      name: "register_tokens"
    },
    single_layers_0_: {
      name: "single_layers.0."
    },
    single_layers_10_: {
      name: "single_layers.10."
    },
    single_layers_11_: {
      name: "single_layers.11."
    },
    single_layers_12_: {
      name: "single_layers.12."
    },
    single_layers_13_: {
      name: "single_layers.13."
    },
    single_layers_14_: {
      name: "single_layers.14."
    },
    single_layers_15_: {
      name: "single_layers.15."
    },
    single_layers_16_: {
      name: "single_layers.16."
    },
    single_layers_17_: {
      name: "single_layers.17."
    },
    single_layers_18_: {
      name: "single_layers.18."
    },
    single_layers_19_: {
      name: "single_layers.19."
    },
    single_layers_1_: {
      name: "single_layers.1."
    },
    single_layers_20_: {
      name: "single_layers.20."
    },
    single_layers_21_: {
      name: "single_layers.21."
    },
    single_layers_22_: {
      name: "single_layers.22."
    },
    single_layers_23_: {
      name: "single_layers.23."
    },
    single_layers_24_: {
      name: "single_layers.24."
    },
    single_layers_25_: {
      name: "single_layers.25."
    },
    single_layers_26_: {
      name: "single_layers.26."
    },
    single_layers_27_: {
      name: "single_layers.27."
    },
    single_layers_28_: {
      name: "single_layers.28."
    },
    single_layers_29_: {
      name: "single_layers.29."
    },
    single_layers_2_: {
      name: "single_layers.2."
    },
    single_layers_30_: {
      name: "single_layers.30."
    },
    single_layers_31_: {
      name: "single_layers.31."
    },
    single_layers_3_: {
      name: "single_layers.3."
    },
    single_layers_4_: {
      name: "single_layers.4."
    },
    single_layers_5_: {
      name: "single_layers.5."
    },
    single_layers_6_: {
      name: "single_layers.6."
    },
    single_layers_7_: {
      name: "single_layers.7."
    },
    single_layers_8_: {
      name: "single_layers.8."
    },
    single_layers_9_: {
      name: "single_layers.9."
    },
    t_embedder_: {
      name: "t_embedder."
    }
  }
};
const ModelMergeBlocks$2 = {
  display_name: "모델 병합 (블록)",
  inputs: {
    input: {
      name: "input"
    },
    middle: {
      name: "middle"
    },
    model1: {
      name: "모델1"
    },
    model2: {
      name: "모델2"
    },
    out: {
      name: "out"
    }
  }
};
const ModelMergeCosmos14B$2 = {
  display_name: "모델 병합 (Cosmos 14B)",
  inputs: {
    affline_norm_: {
      name: "affline_norm."
    },
    blocks_block0_: {
      name: "blocks.block0."
    },
    blocks_block10_: {
      name: "blocks.block10."
    },
    blocks_block11_: {
      name: "blocks.block11."
    },
    blocks_block12_: {
      name: "blocks.block12."
    },
    blocks_block13_: {
      name: "blocks.block13."
    },
    blocks_block14_: {
      name: "blocks.block14."
    },
    blocks_block15_: {
      name: "blocks.block15."
    },
    blocks_block16_: {
      name: "blocks.block16."
    },
    blocks_block17_: {
      name: "blocks.block17."
    },
    blocks_block18_: {
      name: "blocks.block18."
    },
    blocks_block19_: {
      name: "blocks.block19."
    },
    blocks_block1_: {
      name: "blocks.block1."
    },
    blocks_block20_: {
      name: "blocks.block20."
    },
    blocks_block21_: {
      name: "blocks.block21."
    },
    blocks_block22_: {
      name: "blocks.block22."
    },
    blocks_block23_: {
      name: "blocks.block23."
    },
    blocks_block24_: {
      name: "blocks.block24."
    },
    blocks_block25_: {
      name: "blocks.block25."
    },
    blocks_block26_: {
      name: "blocks.block26."
    },
    blocks_block27_: {
      name: "blocks.block27."
    },
    blocks_block28_: {
      name: "blocks.block28."
    },
    blocks_block29_: {
      name: "blocks.block29."
    },
    blocks_block2_: {
      name: "blocks.block2."
    },
    blocks_block30_: {
      name: "blocks.block30."
    },
    blocks_block31_: {
      name: "blocks.block31."
    },
    blocks_block32_: {
      name: "blocks.block32."
    },
    blocks_block33_: {
      name: "blocks.block33."
    },
    blocks_block34_: {
      name: "blocks.block34."
    },
    blocks_block35_: {
      name: "blocks.block35."
    },
    blocks_block3_: {
      name: "blocks.block3."
    },
    blocks_block4_: {
      name: "blocks.block4."
    },
    blocks_block5_: {
      name: "blocks.block5."
    },
    blocks_block6_: {
      name: "blocks.block6."
    },
    blocks_block7_: {
      name: "blocks.block7."
    },
    blocks_block8_: {
      name: "blocks.block8."
    },
    blocks_block9_: {
      name: "blocks.block9."
    },
    extra_pos_embedder_: {
      name: "extra_pos_embedder."
    },
    final_layer_: {
      name: "final_layer."
    },
    model1: {
      name: "모델1"
    },
    model2: {
      name: "모델2"
    },
    pos_embedder_: {
      name: "pos_embedder."
    },
    t_embedder_: {
      name: "t_embedder."
    },
    x_embedder_: {
      name: "x_embedder."
    }
  }
};
const ModelMergeCosmos7B$2 = {
  display_name: "모델 병합 (Cosmos 7B)",
  inputs: {
    affline_norm_: {
      name: "affline_norm."
    },
    blocks_block0_: {
      name: "blocks.block0."
    },
    blocks_block10_: {
      name: "blocks.block10."
    },
    blocks_block11_: {
      name: "blocks.block11."
    },
    blocks_block12_: {
      name: "blocks.block12."
    },
    blocks_block13_: {
      name: "blocks.block13."
    },
    blocks_block14_: {
      name: "blocks.block14."
    },
    blocks_block15_: {
      name: "blocks.block15."
    },
    blocks_block16_: {
      name: "blocks.block16."
    },
    blocks_block17_: {
      name: "blocks.block17."
    },
    blocks_block18_: {
      name: "blocks.block18."
    },
    blocks_block19_: {
      name: "blocks.block19."
    },
    blocks_block1_: {
      name: "blocks.block1."
    },
    blocks_block20_: {
      name: "blocks.block20."
    },
    blocks_block21_: {
      name: "blocks.block21."
    },
    blocks_block22_: {
      name: "blocks.block22."
    },
    blocks_block23_: {
      name: "blocks.block23."
    },
    blocks_block24_: {
      name: "blocks.block24."
    },
    blocks_block25_: {
      name: "blocks.block25."
    },
    blocks_block26_: {
      name: "blocks.block26."
    },
    blocks_block27_: {
      name: "blocks.block27."
    },
    blocks_block2_: {
      name: "blocks.block2."
    },
    blocks_block3_: {
      name: "blocks.block3."
    },
    blocks_block4_: {
      name: "blocks.block4."
    },
    blocks_block5_: {
      name: "blocks.block5."
    },
    blocks_block6_: {
      name: "blocks.block6."
    },
    blocks_block7_: {
      name: "blocks.block7."
    },
    blocks_block8_: {
      name: "blocks.block8."
    },
    blocks_block9_: {
      name: "blocks.block9."
    },
    extra_pos_embedder_: {
      name: "extra_pos_embedder."
    },
    final_layer_: {
      name: "final_layer."
    },
    model1: {
      name: "모델1"
    },
    model2: {
      name: "모델2"
    },
    pos_embedder_: {
      name: "pos_embedder."
    },
    t_embedder_: {
      name: "t_embedder."
    },
    x_embedder_: {
      name: "x_embedder."
    }
  }
};
const ModelMergeFlux1$2 = {
  display_name: "모델 병합 (FLUX.1)",
  inputs: {
    double_blocks_0_: {
      name: "double_blocks.0."
    },
    double_blocks_10_: {
      name: "double_blocks.10."
    },
    double_blocks_11_: {
      name: "double_blocks.11."
    },
    double_blocks_12_: {
      name: "double_blocks.12."
    },
    double_blocks_13_: {
      name: "double_blocks.13."
    },
    double_blocks_14_: {
      name: "double_blocks.14."
    },
    double_blocks_15_: {
      name: "double_blocks.15."
    },
    double_blocks_16_: {
      name: "double_blocks.16."
    },
    double_blocks_17_: {
      name: "double_blocks.17."
    },
    double_blocks_18_: {
      name: "double_blocks.18."
    },
    double_blocks_1_: {
      name: "double_blocks.1."
    },
    double_blocks_2_: {
      name: "double_blocks.2."
    },
    double_blocks_3_: {
      name: "double_blocks.3."
    },
    double_blocks_4_: {
      name: "double_blocks.4."
    },
    double_blocks_5_: {
      name: "double_blocks.5."
    },
    double_blocks_6_: {
      name: "double_blocks.6."
    },
    double_blocks_7_: {
      name: "double_blocks.7."
    },
    double_blocks_8_: {
      name: "double_blocks.8."
    },
    double_blocks_9_: {
      name: "double_blocks.9."
    },
    final_layer_: {
      name: "final_layer."
    },
    guidance_in: {
      name: "guidance_in"
    },
    img_in_: {
      name: "img_in."
    },
    model1: {
      name: "모델1"
    },
    model2: {
      name: "모델2"
    },
    single_blocks_0_: {
      name: "single_blocks.0."
    },
    single_blocks_10_: {
      name: "single_blocks.10."
    },
    single_blocks_11_: {
      name: "single_blocks.11."
    },
    single_blocks_12_: {
      name: "single_blocks.12."
    },
    single_blocks_13_: {
      name: "single_blocks.13."
    },
    single_blocks_14_: {
      name: "single_blocks.14."
    },
    single_blocks_15_: {
      name: "single_blocks.15."
    },
    single_blocks_16_: {
      name: "single_blocks.16."
    },
    single_blocks_17_: {
      name: "single_blocks.17."
    },
    single_blocks_18_: {
      name: "single_blocks.18."
    },
    single_blocks_19_: {
      name: "single_blocks.19."
    },
    single_blocks_1_: {
      name: "single_blocks.1."
    },
    single_blocks_20_: {
      name: "single_blocks.20."
    },
    single_blocks_21_: {
      name: "single_blocks.21."
    },
    single_blocks_22_: {
      name: "single_blocks.22."
    },
    single_blocks_23_: {
      name: "single_blocks.23."
    },
    single_blocks_24_: {
      name: "single_blocks.24."
    },
    single_blocks_25_: {
      name: "single_blocks.25."
    },
    single_blocks_26_: {
      name: "single_blocks.26."
    },
    single_blocks_27_: {
      name: "single_blocks.27."
    },
    single_blocks_28_: {
      name: "single_blocks.28."
    },
    single_blocks_29_: {
      name: "single_blocks.29."
    },
    single_blocks_2_: {
      name: "single_blocks.2."
    },
    single_blocks_30_: {
      name: "single_blocks.30."
    },
    single_blocks_31_: {
      name: "single_blocks.31."
    },
    single_blocks_32_: {
      name: "single_blocks.32."
    },
    single_blocks_33_: {
      name: "single_blocks.33."
    },
    single_blocks_34_: {
      name: "single_blocks.34."
    },
    single_blocks_35_: {
      name: "single_blocks.35."
    },
    single_blocks_36_: {
      name: "single_blocks.36."
    },
    single_blocks_37_: {
      name: "single_blocks.37."
    },
    single_blocks_3_: {
      name: "single_blocks.3."
    },
    single_blocks_4_: {
      name: "single_blocks.4."
    },
    single_blocks_5_: {
      name: "single_blocks.5."
    },
    single_blocks_6_: {
      name: "single_blocks.6."
    },
    single_blocks_7_: {
      name: "single_blocks.7."
    },
    single_blocks_8_: {
      name: "single_blocks.8."
    },
    single_blocks_9_: {
      name: "single_blocks.9."
    },
    time_in_: {
      name: "time_in."
    },
    txt_in_: {
      name: "txt_in."
    },
    vector_in_: {
      name: "vector_in."
    }
  }
};
const ModelMergeLTXV$2 = {
  display_name: "모델 병합 (LTXV)",
  inputs: {
    adaln_single_: {
      name: "adaln_single."
    },
    caption_projection_: {
      name: "caption_projection."
    },
    model1: {
      name: "모델1"
    },
    model2: {
      name: "모델2"
    },
    patchify_proj_: {
      name: "patchify_proj."
    },
    proj_out_: {
      name: "proj_out."
    },
    scale_shift_table: {
      name: "scale_shift_table"
    },
    transformer_blocks_0_: {
      name: "transformer_blocks.0."
    },
    transformer_blocks_10_: {
      name: "transformer_blocks.10."
    },
    transformer_blocks_11_: {
      name: "transformer_blocks.11."
    },
    transformer_blocks_12_: {
      name: "transformer_blocks.12."
    },
    transformer_blocks_13_: {
      name: "transformer_blocks.13."
    },
    transformer_blocks_14_: {
      name: "transformer_blocks.14."
    },
    transformer_blocks_15_: {
      name: "transformer_blocks.15."
    },
    transformer_blocks_16_: {
      name: "transformer_blocks.16."
    },
    transformer_blocks_17_: {
      name: "transformer_blocks.17."
    },
    transformer_blocks_18_: {
      name: "transformer_blocks.18."
    },
    transformer_blocks_19_: {
      name: "transformer_blocks.19."
    },
    transformer_blocks_1_: {
      name: "transformer_blocks.1."
    },
    transformer_blocks_20_: {
      name: "transformer_blocks.20."
    },
    transformer_blocks_21_: {
      name: "transformer_blocks.21."
    },
    transformer_blocks_22_: {
      name: "transformer_blocks.22."
    },
    transformer_blocks_23_: {
      name: "transformer_blocks.23."
    },
    transformer_blocks_24_: {
      name: "transformer_blocks.24."
    },
    transformer_blocks_25_: {
      name: "transformer_blocks.25."
    },
    transformer_blocks_26_: {
      name: "transformer_blocks.26."
    },
    transformer_blocks_27_: {
      name: "transformer_blocks.27."
    },
    transformer_blocks_2_: {
      name: "transformer_blocks.2."
    },
    transformer_blocks_3_: {
      name: "transformer_blocks.3."
    },
    transformer_blocks_4_: {
      name: "transformer_blocks.4."
    },
    transformer_blocks_5_: {
      name: "transformer_blocks.5."
    },
    transformer_blocks_6_: {
      name: "transformer_blocks.6."
    },
    transformer_blocks_7_: {
      name: "transformer_blocks.7."
    },
    transformer_blocks_8_: {
      name: "transformer_blocks.8."
    },
    transformer_blocks_9_: {
      name: "transformer_blocks.9."
    }
  }
};
const ModelMergeMochiPreview$2 = {
  display_name: "모델 병합 (Mochi Preview)",
  inputs: {
    blocks_0_: {
      name: "blocks.0."
    },
    blocks_10_: {
      name: "blocks.10."
    },
    blocks_11_: {
      name: "blocks.11."
    },
    blocks_12_: {
      name: "blocks.12."
    },
    blocks_13_: {
      name: "blocks.13."
    },
    blocks_14_: {
      name: "blocks.14."
    },
    blocks_15_: {
      name: "blocks.15."
    },
    blocks_16_: {
      name: "blocks.16."
    },
    blocks_17_: {
      name: "blocks.17."
    },
    blocks_18_: {
      name: "blocks.18."
    },
    blocks_19_: {
      name: "blocks.19."
    },
    blocks_1_: {
      name: "blocks.1."
    },
    blocks_20_: {
      name: "blocks.20."
    },
    blocks_21_: {
      name: "blocks.21."
    },
    blocks_22_: {
      name: "blocks.22."
    },
    blocks_23_: {
      name: "blocks.23."
    },
    blocks_24_: {
      name: "blocks.24."
    },
    blocks_25_: {
      name: "blocks.25."
    },
    blocks_26_: {
      name: "blocks.26."
    },
    blocks_27_: {
      name: "blocks.27."
    },
    blocks_28_: {
      name: "blocks.28."
    },
    blocks_29_: {
      name: "blocks.29."
    },
    blocks_2_: {
      name: "blocks.2."
    },
    blocks_30_: {
      name: "blocks.30."
    },
    blocks_31_: {
      name: "blocks.31."
    },
    blocks_32_: {
      name: "blocks.32."
    },
    blocks_33_: {
      name: "blocks.33."
    },
    blocks_34_: {
      name: "blocks.34."
    },
    blocks_35_: {
      name: "blocks.35."
    },
    blocks_36_: {
      name: "blocks.36."
    },
    blocks_37_: {
      name: "blocks.37."
    },
    blocks_38_: {
      name: "blocks.38."
    },
    blocks_39_: {
      name: "blocks.39."
    },
    blocks_3_: {
      name: "blocks.3."
    },
    blocks_40_: {
      name: "blocks.40."
    },
    blocks_41_: {
      name: "blocks.41."
    },
    blocks_42_: {
      name: "blocks.42."
    },
    blocks_43_: {
      name: "blocks.43."
    },
    blocks_44_: {
      name: "blocks.44."
    },
    blocks_45_: {
      name: "blocks.45."
    },
    blocks_46_: {
      name: "blocks.46."
    },
    blocks_47_: {
      name: "blocks.47."
    },
    blocks_4_: {
      name: "blocks.4."
    },
    blocks_5_: {
      name: "blocks.5."
    },
    blocks_6_: {
      name: "blocks.6."
    },
    blocks_7_: {
      name: "blocks.7."
    },
    blocks_8_: {
      name: "blocks.8."
    },
    blocks_9_: {
      name: "blocks.9."
    },
    final_layer_: {
      name: "final_layer."
    },
    model1: {
      name: "모델1"
    },
    model2: {
      name: "모델2"
    },
    pos_frequencies_: {
      name: "pos_frequencies."
    },
    t5_y_embedder_: {
      name: "t5_y_embedder."
    },
    t5_yproj_: {
      name: "t5_yproj."
    },
    t_embedder_: {
      name: "t_embedder."
    }
  }
};
const ModelMergeSD1$2 = {
  display_name: "모델 병합 (SD1)",
  inputs: {
    input_blocks_0_: {
      name: "input_blocks.0."
    },
    input_blocks_10_: {
      name: "input_blocks.10."
    },
    input_blocks_11_: {
      name: "input_blocks.11."
    },
    input_blocks_1_: {
      name: "input_blocks.1."
    },
    input_blocks_2_: {
      name: "input_blocks.2."
    },
    input_blocks_3_: {
      name: "input_blocks.3."
    },
    input_blocks_4_: {
      name: "input_blocks.4."
    },
    input_blocks_5_: {
      name: "input_blocks.5."
    },
    input_blocks_6_: {
      name: "input_blocks.6."
    },
    input_blocks_7_: {
      name: "input_blocks.7."
    },
    input_blocks_8_: {
      name: "input_blocks.8."
    },
    input_blocks_9_: {
      name: "input_blocks.9."
    },
    label_emb_: {
      name: "label_emb."
    },
    middle_block_0_: {
      name: "middle_blocks.0."
    },
    middle_block_1_: {
      name: "middle_blocks.1."
    },
    middle_block_2_: {
      name: "middle_blocks.2."
    },
    model1: {
      name: "모델1"
    },
    model2: {
      name: "모델2"
    },
    out_: {
      name: "out."
    },
    output_blocks_0_: {
      name: "out_blocks.0."
    },
    output_blocks_10_: {
      name: "out_blocks.10."
    },
    output_blocks_11_: {
      name: "out_blocks.11."
    },
    output_blocks_1_: {
      name: "out_blocks.1."
    },
    output_blocks_2_: {
      name: "out_blocks.2."
    },
    output_blocks_3_: {
      name: "out_blocks.3."
    },
    output_blocks_4_: {
      name: "out_blocks.4."
    },
    output_blocks_5_: {
      name: "out_blocks.5."
    },
    output_blocks_6_: {
      name: "out_blocks.6."
    },
    output_blocks_7_: {
      name: "out_blocks.7."
    },
    output_blocks_8_: {
      name: "out_blocks.8."
    },
    output_blocks_9_: {
      name: "out_blocks.9."
    },
    time_embed_: {
      name: "time_embed."
    }
  }
};
const ModelMergeSD2$2 = {
  display_name: "모델 병합 (SD2)",
  inputs: {
    input_blocks_0_: {
      name: "input_blocks.0."
    },
    input_blocks_10_: {
      name: "input_blocks.10."
    },
    input_blocks_11_: {
      name: "input_blocks.11."
    },
    input_blocks_1_: {
      name: "input_blocks.1."
    },
    input_blocks_2_: {
      name: "input_blocks.2."
    },
    input_blocks_3_: {
      name: "input_blocks.3."
    },
    input_blocks_4_: {
      name: "input_blocks.4."
    },
    input_blocks_5_: {
      name: "input_blocks.5."
    },
    input_blocks_6_: {
      name: "input_blocks.6."
    },
    input_blocks_7_: {
      name: "input_blocks.7."
    },
    input_blocks_8_: {
      name: "input_blocks.8."
    },
    input_blocks_9_: {
      name: "input_blocks.9."
    },
    label_emb_: {
      name: "label_emb."
    },
    middle_block_0_: {
      name: "middle_blocks.0."
    },
    middle_block_1_: {
      name: "middle_blocks.1."
    },
    middle_block_2_: {
      name: "middle_blocks.2."
    },
    model1: {
      name: "모델1"
    },
    model2: {
      name: "모델2"
    },
    out_: {
      name: "out."
    },
    output_blocks_0_: {
      name: "out_blocks.0."
    },
    output_blocks_10_: {
      name: "out_blocks.10."
    },
    output_blocks_11_: {
      name: "out_blocks.11."
    },
    output_blocks_1_: {
      name: "out_blocks.1."
    },
    output_blocks_2_: {
      name: "out_blocks.2."
    },
    output_blocks_3_: {
      name: "out_blocks.3."
    },
    output_blocks_4_: {
      name: "out_blocks.4."
    },
    output_blocks_5_: {
      name: "out_blocks.5."
    },
    output_blocks_6_: {
      name: "out_blocks.6."
    },
    output_blocks_7_: {
      name: "out_blocks.7."
    },
    output_blocks_8_: {
      name: "out_blocks.8."
    },
    output_blocks_9_: {
      name: "out_blocks.9."
    },
    time_embed_: {
      name: "time_embed."
    }
  }
};
const ModelMergeSD35_Large$2 = {
  display_name: "모델 병합 (SD35 Large)",
  inputs: {
    context_embedder_: {
      name: "context_embedder."
    },
    final_layer_: {
      name: "final_layer."
    },
    joint_blocks_0_: {
      name: "joint_blocks.0."
    },
    joint_blocks_10_: {
      name: "joint_blocks.10."
    },
    joint_blocks_11_: {
      name: "joint_blocks.11."
    },
    joint_blocks_12_: {
      name: "joint_blocks.12."
    },
    joint_blocks_13_: {
      name: "joint_blocks.13."
    },
    joint_blocks_14_: {
      name: "joint_blocks.14."
    },
    joint_blocks_15_: {
      name: "joint_blocks.15."
    },
    joint_blocks_16_: {
      name: "joint_blocks.16."
    },
    joint_blocks_17_: {
      name: "joint_blocks.17."
    },
    joint_blocks_18_: {
      name: "joint_blocks.18."
    },
    joint_blocks_19_: {
      name: "joint_blocks.19."
    },
    joint_blocks_1_: {
      name: "joint_blocks.1."
    },
    joint_blocks_20_: {
      name: "joint_blocks.20."
    },
    joint_blocks_21_: {
      name: "joint_blocks.21."
    },
    joint_blocks_22_: {
      name: "joint_blocks.22."
    },
    joint_blocks_23_: {
      name: "joint_blocks.23."
    },
    joint_blocks_24_: {
      name: "joint_blocks.24."
    },
    joint_blocks_25_: {
      name: "joint_blocks.25."
    },
    joint_blocks_26_: {
      name: "joint_blocks.26."
    },
    joint_blocks_27_: {
      name: "joint_blocks.27."
    },
    joint_blocks_28_: {
      name: "joint_blocks.28."
    },
    joint_blocks_29_: {
      name: "joint_blocks.29."
    },
    joint_blocks_2_: {
      name: "joint_blocks.2."
    },
    joint_blocks_30_: {
      name: "joint_blocks.30."
    },
    joint_blocks_31_: {
      name: "joint_blocks.31."
    },
    joint_blocks_32_: {
      name: "joint_blocks.32."
    },
    joint_blocks_33_: {
      name: "joint_blocks.33."
    },
    joint_blocks_34_: {
      name: "joint_blocks.34."
    },
    joint_blocks_35_: {
      name: "joint_blocks.35."
    },
    joint_blocks_36_: {
      name: "joint_blocks.36."
    },
    joint_blocks_37_: {
      name: "joint_blocks.37."
    },
    joint_blocks_3_: {
      name: "joint_blocks.3."
    },
    joint_blocks_4_: {
      name: "joint_blocks.4."
    },
    joint_blocks_5_: {
      name: "joint_blocks.5."
    },
    joint_blocks_6_: {
      name: "joint_blocks.6."
    },
    joint_blocks_7_: {
      name: "joint_blocks.7."
    },
    joint_blocks_8_: {
      name: "joint_blocks.8."
    },
    joint_blocks_9_: {
      name: "joint_blocks.9."
    },
    model1: {
      name: "모델1"
    },
    model2: {
      name: "모델2"
    },
    pos_embed_: {
      name: "pos_embed."
    },
    t_embedder_: {
      name: "t_embedder."
    },
    x_embedder_: {
      name: "x_embedder."
    },
    y_embedder_: {
      name: "y_embedder."
    }
  }
};
const ModelMergeSD3_2B$2 = {
  display_name: "모델 병합 (SD3 2B)",
  inputs: {
    context_embedder_: {
      name: "context_embedder."
    },
    final_layer_: {
      name: "final_layer."
    },
    joint_blocks_0_: {
      name: "joint_blocks.0."
    },
    joint_blocks_10_: {
      name: "joint_blocks.10."
    },
    joint_blocks_11_: {
      name: "joint_blocks.11."
    },
    joint_blocks_12_: {
      name: "joint_blocks.12."
    },
    joint_blocks_13_: {
      name: "joint_blocks.13."
    },
    joint_blocks_14_: {
      name: "joint_blocks.14."
    },
    joint_blocks_15_: {
      name: "joint_blocks.15."
    },
    joint_blocks_16_: {
      name: "joint_blocks.16."
    },
    joint_blocks_17_: {
      name: "joint_blocks.17."
    },
    joint_blocks_18_: {
      name: "joint_blocks.18."
    },
    joint_blocks_19_: {
      name: "joint_blocks.19."
    },
    joint_blocks_1_: {
      name: "joint_blocks.1."
    },
    joint_blocks_20_: {
      name: "joint_blocks.20."
    },
    joint_blocks_21_: {
      name: "joint_blocks.21."
    },
    joint_blocks_22_: {
      name: "joint_blocks.22."
    },
    joint_blocks_23_: {
      name: "joint_blocks.23."
    },
    joint_blocks_2_: {
      name: "joint_blocks.2."
    },
    joint_blocks_3_: {
      name: "joint_blocks.3."
    },
    joint_blocks_4_: {
      name: "joint_blocks.4."
    },
    joint_blocks_5_: {
      name: "joint_blocks.5."
    },
    joint_blocks_6_: {
      name: "joint_blocks.6."
    },
    joint_blocks_7_: {
      name: "joint_blocks.7."
    },
    joint_blocks_8_: {
      name: "joint_blocks.8."
    },
    joint_blocks_9_: {
      name: "joint_blocks.9."
    },
    model1: {
      name: "모델1"
    },
    model2: {
      name: "모델2"
    },
    pos_embed_: {
      name: "pos_embed."
    },
    t_embedder_: {
      name: "t_embedder."
    },
    x_embedder_: {
      name: "x_embedder."
    },
    y_embedder_: {
      name: "y_embedder."
    }
  }
};
const ModelMergeSDXL$2 = {
  display_name: "모델 병합 (SDXL)",
  inputs: {
    input_blocks_0: {
      name: "input_blocks.0"
    },
    input_blocks_1: {
      name: "input_blocks.1"
    },
    input_blocks_2: {
      name: "input_blocks.2"
    },
    input_blocks_3: {
      name: "input_blocks.3"
    },
    input_blocks_4: {
      name: "input_blocks.4"
    },
    input_blocks_5: {
      name: "input_blocks.5"
    },
    input_blocks_6: {
      name: "input_blocks.6"
    },
    input_blocks_7: {
      name: "input_blocks.7"
    },
    input_blocks_8: {
      name: "input_blocks.8"
    },
    label_emb_: {
      name: "label_emb."
    },
    middle_block_0: {
      name: "middle_block.0"
    },
    middle_block_1: {
      name: "middle_block.1"
    },
    middle_block_2: {
      name: "middle_block.2"
    },
    model1: {
      name: "모델1"
    },
    model2: {
      name: "모델2"
    },
    out_: {
      name: "out."
    },
    output_blocks_0: {
      name: "output_blocks.0"
    },
    output_blocks_1: {
      name: "output_blocks.1"
    },
    output_blocks_2: {
      name: "output_blocks.2"
    },
    output_blocks_3: {
      name: "output_blocks.3"
    },
    output_blocks_4: {
      name: "output_blocks.4"
    },
    output_blocks_5: {
      name: "output_blocks.5"
    },
    output_blocks_6: {
      name: "output_blocks.6"
    },
    output_blocks_7: {
      name: "output_blocks.7"
    },
    output_blocks_8: {
      name: "output_blocks.8"
    },
    time_embed_: {
      name: "time_embed."
    }
  }
};
const ModelMergeSimple$2 = {
  display_name: "모델 병합 (단순)",
  inputs: {
    model1: {
      name: "모델1"
    },
    model2: {
      name: "모델2"
    },
    ratio: {
      name: "비율"
    }
  }
};
const ModelMergeSubtract$2 = {
  display_name: "모델 병합 (빼기)",
  inputs: {
    model1: {
      name: "모델1"
    },
    model2: {
      name: "모델2"
    },
    multiplier: {
      name: "배율"
    }
  }
};
const ModelMergeWAN2_1$2 = {
  description: "1.3B 모델은 30개의 블록, 14B 모델은 40개의 블록을 가지고 있습니다. 이미지 투 비디오 모델에는 추가적인 img_emb가 있습니다.",
  display_name: "모델 병합 (WAN2.1)",
  inputs: {
    blocks_0_: {
      name: "blocks.0."
    },
    blocks_10_: {
      name: "blocks.10."
    },
    blocks_11_: {
      name: "blocks.11."
    },
    blocks_12_: {
      name: "blocks.12."
    },
    blocks_13_: {
      name: "blocks.13."
    },
    blocks_14_: {
      name: "blocks.14."
    },
    blocks_15_: {
      name: "blocks.15."
    },
    blocks_16_: {
      name: "blocks.16."
    },
    blocks_17_: {
      name: "blocks.17."
    },
    blocks_18_: {
      name: "blocks.18."
    },
    blocks_19_: {
      name: "blocks.19."
    },
    blocks_1_: {
      name: "blocks.1."
    },
    blocks_20_: {
      name: "blocks.20."
    },
    blocks_21_: {
      name: "blocks.21."
    },
    blocks_22_: {
      name: "blocks.22."
    },
    blocks_23_: {
      name: "blocks.23."
    },
    blocks_24_: {
      name: "blocks.24."
    },
    blocks_25_: {
      name: "blocks.25."
    },
    blocks_26_: {
      name: "blocks.26."
    },
    blocks_27_: {
      name: "blocks.27."
    },
    blocks_28_: {
      name: "blocks.28."
    },
    blocks_29_: {
      name: "blocks.29."
    },
    blocks_2_: {
      name: "blocks.2."
    },
    blocks_30_: {
      name: "blocks.30."
    },
    blocks_31_: {
      name: "blocks.31."
    },
    blocks_32_: {
      name: "blocks.32."
    },
    blocks_33_: {
      name: "blocks.33."
    },
    blocks_34_: {
      name: "blocks.34."
    },
    blocks_35_: {
      name: "blocks.35."
    },
    blocks_36_: {
      name: "blocks.36."
    },
    blocks_37_: {
      name: "blocks.37."
    },
    blocks_38_: {
      name: "blocks.38."
    },
    blocks_39_: {
      name: "blocks.39."
    },
    blocks_3_: {
      name: "blocks.3."
    },
    blocks_4_: {
      name: "blocks.4."
    },
    blocks_5_: {
      name: "blocks.5."
    },
    blocks_6_: {
      name: "blocks.6."
    },
    blocks_7_: {
      name: "blocks.7."
    },
    blocks_8_: {
      name: "blocks.8."
    },
    blocks_9_: {
      name: "blocks.9."
    },
    head_: {
      name: "head."
    },
    img_emb_: {
      name: "img_emb."
    },
    model1: {
      name: "모델1"
    },
    model2: {
      name: "모델2"
    },
    patch_embedding_: {
      name: "patch_embedding."
    },
    text_embedding_: {
      name: "text_embedding."
    },
    time_embedding_: {
      name: "time_embedding."
    },
    time_projection_: {
      name: "time_projection."
    }
  }
};
const ModelSamplingAuraFlow$2 = {
  display_name: "모델 샘플링 (AuraFlow)",
  inputs: {
    model: {
      name: "모델"
    },
    shift: {
      name: "시프트"
    }
  }
};
const ModelSamplingContinuousEDM$2 = {
  display_name: "모델 샘플링 (연속 EDM)",
  inputs: {
    model: {
      name: "모델"
    },
    sampling: {
      name: "샘플링"
    },
    sigma_max: {
      name: "최대 시그마"
    },
    sigma_min: {
      name: "최소 시그마"
    }
  }
};
const ModelSamplingContinuousV$2 = {
  display_name: "모델 샘플링 (연속 V)",
  inputs: {
    model: {
      name: "모델"
    },
    sampling: {
      name: "샘플링"
    },
    sigma_max: {
      name: "최대 시그마"
    },
    sigma_min: {
      name: "최소 시그마"
    }
  }
};
const ModelSamplingDiscrete$2 = {
  display_name: "모델 샘플링 (이산)",
  inputs: {
    model: {
      name: "모델"
    },
    sampling: {
      name: "샘플링"
    },
    zsnr: {
      name: "zsnr"
    }
  }
};
const ModelSamplingFlux$2 = {
  display_name: "모델 샘플링 (FLUX)",
  inputs: {
    base_shift: {
      name: "기본 시프트"
    },
    height: {
      name: "높이"
    },
    max_shift: {
      name: "최대 시프트"
    },
    model: {
      name: "모델"
    },
    width: {
      name: "너비"
    }
  }
};
const ModelSamplingLTXV$2 = {
  display_name: "모델 샘플링 (LTXV)",
  inputs: {
    base_shift: {
      name: "기반 시프트"
    },
    latent: {
      name: "잠재 비디오"
    },
    max_shift: {
      name: "최대 시프트"
    },
    model: {
      name: "모델"
    }
  }
};
const ModelSamplingSD3$2 = {
  display_name: "모델 샘플링 (SD3)",
  inputs: {
    model: {
      name: "모델"
    },
    shift: {
      name: "시프트"
    }
  }
};
const ModelSamplingStableCascade$2 = {
  display_name: "모델 샘플링 (StableCascade)",
  inputs: {
    model: {
      name: "모델"
    },
    shift: {
      name: "시프트"
    }
  }
};
const ModelSave$2 = {
  display_name: "모델 저장",
  inputs: {
    filename_prefix: {
      name: "파일명 접두사"
    },
    model: {
      name: "모델"
    }
  }
};
const Morphology$2 = {
  display_name: "이미지 형태 변환",
  inputs: {
    image: {
      name: "이미지"
    },
    kernel_size: {
      name: "커널 크기"
    },
    operation: {
      name: "연산"
    }
  }
};
const OpenAIDalle2$2 = {
  description: "OpenAI의 DALL·E 2 엔드포인트를 통해 동기적으로 이미지를 생성합니다.",
  display_name: "OpenAI DALL·E 2",
  inputs: {
    control_after_generate: {
      name: "생성 후 제어"
    },
    image: {
      name: "이미지",
      tooltip: "이미지 편집을 위한 선택적 참조 이미지."
    },
    mask: {
      name: "마스크",
      tooltip: "인페인팅을 위한 선택적 마스크 (흰색 영역이 대체됨)"
    },
    n: {
      name: "개수",
      tooltip: "생성할 이미지 수"
    },
    prompt: {
      name: "프롬프트",
      tooltip: "DALL·E를 위한 텍스트 프롬프트"
    },
    seed: {
      name: "시드",
      tooltip: "백엔드에 아직 구현되지 않음"
    },
    size: {
      name: "크기",
      tooltip: "이미지 크기"
    }
  }
};
const OpenAIDalle3$2 = {
  description: "OpenAI의 DALL·E 3 엔드포인트를 통해 동기적으로 이미지를 생성합니다.",
  display_name: "OpenAI DALL·E 3",
  inputs: {
    control_after_generate: {
      name: "생성 후 제어"
    },
    prompt: {
      name: "프롬프트",
      tooltip: "DALL·E를 위한 텍스트 프롬프트"
    },
    quality: {
      name: "품질",
      tooltip: "이미지 품질"
    },
    seed: {
      name: "시드",
      tooltip: "백엔드에 아직 구현되지 않음"
    },
    size: {
      name: "크기",
      tooltip: "이미지 크기"
    },
    style: {
      name: "스타일",
      tooltip: "Vivid는 모델이 하이퍼리얼하고 극적인 이미지를 생성하도록 유도합니다. Natural은 모델이 더 자연스럽고 덜 하이퍼리얼한 이미지를 생성하도록 합니다."
    }
  }
};
const OpenAIGPTImage1$2 = {
  description: "OpenAI의 GPT Image 1 엔드포인트를 통해 동기적으로 이미지를 생성합니다.",
  display_name: "OpenAI GPT Image 1",
  inputs: {
    background: {
      name: "배경",
      tooltip: "배경이 있는 이미지 또는 없는 이미지를 반환"
    },
    control_after_generate: {
      name: "생성 후 제어"
    },
    image: {
      name: "참조 이미지",
      tooltip: "이미지 편집을 위한 선택적 참조 이미지."
    },
    mask: {
      name: "마스크",
      tooltip: "인페인팅을 위한 선택적 마스크 (흰색 영역이 대체됨)"
    },
    n: {
      name: "개수",
      tooltip: "생성할 이미지의 수"
    },
    prompt: {
      name: "프롬프트",
      tooltip: "GPT Image 1을 위한 텍스트 프롬프트"
    },
    quality: {
      name: "품질",
      tooltip: "이미지 품질, 비용과 생성 시간에 영향을 줍니다."
    },
    seed: {
      name: "시드",
      tooltip: "백엔드에 아직 구현되지 않음"
    },
    size: {
      name: "크기",
      tooltip: "이미지 크기"
    }
  }
};
const OptimalStepsScheduler$2 = {
  display_name: "OptimalStepsScheduler",
  inputs: {
    denoise: {
      name: "디노이즈"
    },
    model_type: {
      name: "모델 종류"
    },
    steps: {
      name: "스텝"
    }
  }
};
const PairConditioningCombine$2 = {
  display_name: "조건 쌍 (결합)",
  inputs: {
    negative_A: {
      name: "부정 조건 A"
    },
    negative_B: {
      name: "부정 조건 B"
    },
    positive_A: {
      name: "긍정 조건 A"
    },
    positive_B: {
      name: "긍정 조건 B"
    }
  },
  outputs: {
    "0": {
      name: "긍정 조건"
    },
    "1": {
      name: "부정 조건"
    }
  }
};
const PairConditioningSetDefaultCombine$2 = {
  display_name: "조건 쌍 (기본 결합 설정)",
  inputs: {
    hooks: {
      name: "후크"
    },
    negative: {
      name: "부정 조건"
    },
    negative_DEFAULT: {
      name: "기본 부정 조건"
    },
    positive: {
      name: "긍정 조건"
    },
    positive_DEFAULT: {
      name: "기본 긍정 조건"
    }
  },
  outputs: {
    "0": {
      name: "긍정 조건"
    },
    "1": {
      name: "부정 조건"
    }
  }
};
const PairConditioningSetProperties$2 = {
  display_name: "조건 쌍 (속성 설정)",
  inputs: {
    hooks: {
      name: "후크"
    },
    mask: {
      name: "마스크"
    },
    negative_NEW: {
      name: "새 부정 조건"
    },
    positive_NEW: {
      name: "새 긍정 조건"
    },
    set_cond_area: {
      name: "조건 영역 설정"
    },
    strength: {
      name: "강도"
    },
    timesteps: {
      name: "타임스텝 범위"
    }
  },
  outputs: {
    "0": {
      name: "긍정 조건"
    },
    "1": {
      name: "부정 조건"
    }
  }
};
const PairConditioningSetPropertiesAndCombine$2 = {
  display_name: "조건 쌍 (속성 설정 및 결합)",
  inputs: {
    hooks: {
      name: "후크"
    },
    mask: {
      name: "마스크"
    },
    negative: {
      name: "부정 조건"
    },
    negative_NEW: {
      name: "새 부정 조건"
    },
    positive: {
      name: "긍정 조건"
    },
    positive_NEW: {
      name: "새 긍정 조건"
    },
    set_cond_area: {
      name: "조건 영역 설정"
    },
    strength: {
      name: "강도"
    },
    timesteps: {
      name: "타임스텝 범위"
    }
  },
  outputs: {
    "0": {
      name: "긍정 조건"
    },
    "1": {
      name: "부정 조건"
    }
  }
};
const PatchModelAddDownscale$2 = {
  display_name: "다운스케일 추가 모델 패치 (Kohya Deep Shrink)",
  inputs: {
    block_number: {
      name: "블록 번호"
    },
    downscale_after_skip: {
      name: "스킵 후 다운스케일"
    },
    downscale_factor: {
      name: "다운스케일 배율"
    },
    downscale_method: {
      name: "다운스케일 방법"
    },
    end_percent: {
      name: "종료 퍼센트"
    },
    model: {
      name: "모델"
    },
    start_percent: {
      name: "시작 퍼센트"
    },
    upscale_method: {
      name: "업스케일 방법"
    }
  }
};
const PerpNeg$2 = {
  display_name: "Perp-Neg (PerpNegGuider에 의해 지원 중단됨)",
  inputs: {
    empty_conditioning: {
      name: "빈 조건"
    },
    model: {
      name: "모델"
    },
    neg_scale: {
      name: "부정 스케일"
    }
  }
};
const PerpNegGuider$2 = {
  display_name: "PerpNeg 가이드",
  inputs: {
    cfg: {
      name: "cfg"
    },
    empty_conditioning: {
      name: "빈 조건"
    },
    model: {
      name: "모델"
    },
    neg_scale: {
      name: "부정 스케일"
    },
    negative: {
      name: "부정 조건"
    },
    positive: {
      name: "긍정 조건"
    }
  }
};
const PerturbedAttentionGuidance$2 = {
  display_name: "교란 어텐션 유도 (PAG)",
  inputs: {
    model: {
      name: "모델"
    },
    scale: {
      name: "스케일"
    }
  }
};
const PhotoMakerEncode$2 = {
  display_name: "포토메이커 인코딩",
  inputs: {
    clip: {
      name: "clip"
    },
    image: {
      name: "이미지"
    },
    photomaker: {
      name: "포토메이커 모델"
    },
    text: {
      name: "텍스트"
    }
  }
};
const PhotoMakerLoader$2 = {
  display_name: "포토메이커 로드",
  inputs: {
    photomaker_model_name: {
      name: "포토메이커 파일명"
    }
  }
};
const PikaImageToVideoNode2_2$2 = {
  description: "이미지와 프롬프트를 Pika API v2.2에 전송하여 비디오를 생성합니다.",
  display_name: "Pika 비디오 생성 (이미지 → 비디오)",
  inputs: {
    control_after_generate: {
      name: "생성 후 제어"
    },
    duration: {
      name: "길이"
    },
    image: {
      name: "이미지",
      tooltip: "비디오로 변환할 이미지"
    },
    negative_prompt: {
      name: "부정 프롬프트"
    },
    prompt_text: {
      name: "프롬프트"
    },
    resolution: {
      name: "해상도"
    },
    seed: {
      name: "시드"
    }
  }
};
const PikaScenesV2_2$2 = {
  description: "여러 이미지를 결합하여 이미지 속 객체들이 포함된 비디오를 만듭니다. 여러 이미지를 재료로 업로드하고, 이 모든 이미지를 반영한 고품질 비디오를 생성하세요.",
  display_name: "Pika Scenes (비디오 이미지 합성)",
  inputs: {
    aspect_ratio: {
      name: "종횡비",
      tooltip: "종횡비 (가로 / 세로)"
    },
    control_after_generate: {
      name: "생성 후 제어"
    },
    duration: {
      name: "길이"
    },
    image_ingredient_1: {
      name: "이미지 재료 1",
      tooltip: "비디오 생성을 위한 재료로 사용할 이미지입니다."
    },
    image_ingredient_2: {
      name: "이미지 재료 2",
      tooltip: "비디오 생성을 위한 재료로 사용할 이미지입니다."
    },
    image_ingredient_3: {
      name: "이미지 재료 3",
      tooltip: "비디오 생성을 위한 재료로 사용할 이미지입니다."
    },
    image_ingredient_4: {
      name: "이미지 재료 4",
      tooltip: "비디오 생성을 위한 재료로 사용할 이미지입니다."
    },
    image_ingredient_5: {
      name: "이미지 재료 5",
      tooltip: "비디오 생성을 위한 재료로 사용할 이미지입니다."
    },
    ingredients_mode: {
      name: "재료 모드"
    },
    negative_prompt: {
      name: "부정 프롬프트"
    },
    prompt_text: {
      name: "프롬프트 텍스트"
    },
    resolution: {
      name: "해상도"
    },
    seed: {
      name: "시드"
    }
  }
};
const PikaStartEndFrameNode2_2$2 = {
  description: "첫 번째 프레임과 마지막 프레임을 결합하여 비디오를 생성합니다. 시작점과 종료점을 정의할 두 이미지를 업로드하면, AI가 그 사이를 부드럽게 전환하는 영상을 만들어줍니다.",
  display_name: "Pika 비디오 생성 (시작-끝 프레임)",
  inputs: {
    control_after_generate: {
      name: "생성 후 제어"
    },
    duration: {
      name: "길이"
    },
    image_end: {
      name: "끝 이미지",
      tooltip: "결합할 마지막 이미지입니다."
    },
    image_start: {
      name: "시작 이미지",
      tooltip: "결합할 첫 번째 이미지입니다."
    },
    negative_prompt: {
      name: "부정 프롬프트"
    },
    prompt_text: {
      name: "프롬프트 텍스트"
    },
    resolution: {
      name: "해상도"
    },
    seed: {
      name: "시드"
    }
  }
};
const PikaTextToVideoNode2_2$2 = {
  description: "텍스트 프롬프트를 Pika API v2.2에 전송하여 비디오를 생성합니다.",
  display_name: "Pika 비디오 생성 (텍스트 → 비디오)",
  inputs: {
    aspect_ratio: {
      name: "종횡비",
      tooltip: "종횡비 (가로 / 세로)"
    },
    control_after_generate: {
      name: "생성 후 제어"
    },
    duration: {
      name: "길이"
    },
    negative_prompt: {
      name: "부정 프롬프트"
    },
    prompt_text: {
      name: "프롬프트 텍스트"
    },
    resolution: {
      name: "해상도"
    },
    seed: {
      name: "시드"
    }
  }
};
const Pikadditions$2 = {
  description: "비디오에 원하는 객체나 이미지를 추가하세요. 비디오를 업로드하고 추가하고 싶은 내용을 지정하면 자연스럽게 통합된 결과를 얻을 수 있습니다.",
  display_name: "Pikadditions (비디오 객체 삽입)",
  inputs: {
    control_after_generate: {
      name: "생성 후 제어"
    },
    image: {
      name: "이미지",
      tooltip: "비디오에 추가할 이미지입니다."
    },
    negative_prompt: {
      name: "부정 프롬프트"
    },
    prompt_text: {
      name: "프롬프트 텍스트"
    },
    seed: {
      name: "시드"
    },
    video: {
      name: "비디오",
      tooltip: "이미지를 추가할 비디오입니다."
    }
  }
};
const Pikaffects$2 = {
  description: "특정 Pikaffect로 비디오를 생성합니다. 지원되는 Pikaffect: Cake-ify, Crumble, Crush, Decapitate, Deflate, Dissolve, Explode, Eye-pop, Inflate, Levitate, Melt, Peel, Poke, Squish, Ta-da, Tear",
  display_name: "Pikaffects (비디오 효과)",
  inputs: {
    control_after_generate: {
      name: "생성 후 제어"
    },
    image: {
      name: "이미지",
      tooltip: "Pikaffect를 적용할 기준 이미지입니다."
    },
    negative_prompt: {
      name: "부정 프롬프트"
    },
    pikaffect: {
      name: "pikaffect"
    },
    prompt_text: {
      name: "프롬프트 텍스트"
    },
    seed: {
      name: "시드"
    }
  }
};
const Pikaswaps$2 = {
  description: "비디오의 어떤 객체나 영역도 새로운 이미지나 객체로 교체하세요. 마스크나 좌표를 사용해 교체할 영역을 정의할 수 있습니다.",
  display_name: "Pika Swaps (비디오 객체 교체)",
  inputs: {
    control_after_generate: {
      name: "생성 후 제어"
    },
    image: {
      name: "이미지",
      tooltip: "비디오에서 마스킹된 객체를 교체하는 데 사용되는 이미지입니다."
    },
    mask: {
      name: "마스크",
      tooltip: "비디오에서 교체할 영역을 정의하려면 마스크를 사용하세요."
    },
    negative_prompt: {
      name: "부정 프롬프트"
    },
    prompt_text: {
      name: "프롬프트 텍스트"
    },
    seed: {
      name: "시드"
    },
    video: {
      name: "비디오",
      tooltip: "객체를 교체할 비디오입니다."
    }
  }
};
const PixverseImageToVideoNode$2 = {
  description: "프롬프트와 output_size에 따라 동기적으로 비디오를 생성합니다.",
  display_name: "PixVerse 이미지에서 비디오로",
  inputs: {
    control_after_generate: {
      name: "생성 후 제어"
    },
    duration_seconds: {
      name: "길이(초)"
    },
    image: {
      name: "이미지"
    },
    motion_mode: {
      name: "모션 모드"
    },
    negative_prompt: {
      name: "부정 프롬프트",
      tooltip: "이미지에서 원하지 않는 요소에 대한 선택적 텍스트 설명."
    },
    pixverse_template: {
      name: "PixVerse 템플릿",
      tooltip: "생성 스타일에 영향을 주는 선택적 템플릿으로, PixVerse Template 노드에서 생성됩니다."
    },
    prompt: {
      name: "프롬프트",
      tooltip: "비디오 생성을 위한 프롬프트"
    },
    quality: {
      name: "품질"
    },
    seed: {
      name: "시드",
      tooltip: "비디오 생성을 위한 시드."
    }
  }
};
const PixverseTemplateNode$2 = {
  display_name: "PixVerse 템플릿",
  inputs: {
    template: {
      name: "템플릿"
    }
  },
  outputs: {
    "0": {
      name: "pixverse 템플릿"
    }
  }
};
const PixverseTextToVideoNode$2 = {
  description: "프롬프트와 output_size에 따라 동기적으로 비디오를 생성합니다.",
  display_name: "PixVerse 텍스트 투 비디오",
  inputs: {
    aspect_ratio: {
      name: "화면 비율"
    },
    control_after_generate: {
      name: "생성 후 제어"
    },
    duration_seconds: {
      name: "길이(초)"
    },
    motion_mode: {
      name: "모션 모드"
    },
    negative_prompt: {
      name: "부정 프롬프트",
      tooltip: "이미지에서 원하지 않는 요소에 대한 선택적 텍스트 설명."
    },
    pixverse_template: {
      name: "PixVerse 템플릿",
      tooltip: "생성 스타일에 영향을 주는 선택적 템플릿으로, PixVerse Template 노드에서 생성됩니다."
    },
    prompt: {
      name: "프롬프트",
      tooltip: "비디오 생성을 위한 프롬프트"
    },
    quality: {
      name: "품질"
    },
    seed: {
      name: "시드",
      tooltip: "비디오 생성을 위한 시드."
    }
  }
};
const PixverseTransitionVideoNode$2 = {
  description: "프롬프트와 output_size에 따라 동기적으로 비디오를 생성합니다.",
  display_name: "PixVerse 전환 비디오",
  inputs: {
    control_after_generate: {
      name: "생성 후 제어"
    },
    duration_seconds: {
      name: "길이(초)"
    },
    first_frame: {
      name: "시작 프레임"
    },
    last_frame: {
      name: "끝 프레임"
    },
    motion_mode: {
      name: "모션 모드"
    },
    negative_prompt: {
      name: "부정 프롬프트",
      tooltip: "이미지에서 원하지 않는 요소에 대한 선택적 텍스트 설명입니다."
    },
    prompt: {
      name: "프롬프트",
      tooltip: "비디오 생성을 위한 프롬프트"
    },
    quality: {
      name: "품질"
    },
    seed: {
      name: "시드",
      tooltip: "비디오 생성을 위한 시드."
    }
  }
};
const PolyexponentialScheduler$2 = {
  display_name: "다항 지수 스케줄러",
  inputs: {
    rho: {
      name: "rho"
    },
    sigma_max: {
      name: "최대 시그마"
    },
    sigma_min: {
      name: "최소 시그마"
    },
    steps: {
      name: "스텝 수"
    }
  }
};
const PorterDuffImageComposite$2 = {
  display_name: "포터-더프 이미지 합성",
  inputs: {
    destination: {
      name: "대상"
    },
    destination_alpha: {
      name: "대상 알파"
    },
    mode: {
      name: "모드"
    },
    source: {
      name: "원본"
    },
    source_alpha: {
      name: "원본 알파"
    }
  }
};
const Preview3D$2 = {
  display_name: "3D 미리보기",
  inputs: {
    camera_info: {
      name: "카메라 정보"
    },
    image: {
      name: "이미지"
    },
    model_file: {
      name: "모델 파일"
    }
  }
};
const Preview3DAnimation$2 = {
  display_name: "3D 미리보기 - 애니메이션",
  inputs: {
    camera_info: {
      name: "카메라 정보"
    },
    image: {
      name: "이미지"
    },
    model_file: {
      name: "모델 파일"
    }
  }
};
const PreviewAny$2 = {
  display_name: "미리보기 아무거나",
  inputs: {
    preview: {},
    source: {
      name: "소스"
    }
  }
};
const PreviewAudio$2 = {
  display_name: "오디오 미리듣기",
  inputs: {
    audio: {
      name: "오디오"
    },
    audioUI: {
      name: "오디오UI"
    }
  }
};
const PreviewImage$2 = {
  description: "입력 이미지를 ComfyUI 의 임시(temp) 폴더에 저장합니다.",
  display_name: "이미지 미리보기",
  inputs: {
    images: {
      name: "이미지"
    }
  }
};
const PrimitiveBoolean$2 = {
  display_name: "논리값",
  inputs: {
    value: {
      name: "값"
    }
  }
};
const PrimitiveFloat$2 = {
  display_name: "실수",
  inputs: {
    value: {
      name: "값"
    }
  }
};
const PrimitiveInt$2 = {
  display_name: "정수",
  inputs: {
    control_after_generate: {
      name: "생성 후 제어"
    },
    value: {
      name: "값"
    }
  }
};
const PrimitiveString$2 = {
  display_name: "문자열",
  inputs: {
    value: {
      name: "값"
    }
  }
};
const PrimitiveStringMultiline$2 = {
  display_name: "문자열 (여러 줄)",
  inputs: {
    value: {
      name: "값"
    }
  }
};
const QuadrupleCLIPLoader$2 = {
  description: "[레시피]\n\nhidream: long clip-l, long clip-g, t5xxl, llama_8b_3.1_instruct",
  display_name: "QuadrupleCLIPLoader",
  inputs: {
    clip_name1: {
      name: "clip 이름 1"
    },
    clip_name2: {
      name: "clip 이름 2"
    },
    clip_name3: {
      name: "clip 이름 3"
    },
    clip_name4: {
      name: "clip 이름 4"
    }
  }
};
const RandomNoise$2 = {
  display_name: "무작위 노이즈",
  inputs: {
    control_after_generate: {
      name: "생성 후 제어"
    },
    noise_seed: {
      name: "노이즈 시드"
    }
  }
};
const RebatchImages$2 = {
  display_name: "이미지 배치 재배치",
  inputs: {
    batch_size: {
      name: "배치 크기"
    },
    images: {
      name: "이미지"
    }
  }
};
const RebatchLatents$2 = {
  display_name: "잠재 데이터 배치 재배치",
  inputs: {
    batch_size: {
      name: "배치 크기"
    },
    latents: {
      name: "잠재 데이터"
    }
  }
};
const RecraftColorRGB$2 = {
  description: "특정 RGB 값을 선택하여 Recraft Color를 생성합니다.",
  display_name: "Recraft Color RGB",
  inputs: {
    b: {
      name: "b",
      tooltip: "색상의 파란색 값입니다."
    },
    g: {
      name: "g",
      tooltip: "색상의 초록색 값입니다."
    },
    r: {
      name: "r",
      tooltip: "색상의 빨간색 값입니다."
    },
    recraft_color: {
      name: "recraft 색"
    }
  },
  outputs: {
    "0": {
      name: "recraft 색"
    }
  }
};
const RecraftControls$2 = {
  description: "Recraft 생성을 커스터마이즈하기 위한 'Recraft 제어'을 생성합니다.",
  display_name: "Recraft 제어",
  inputs: {
    background_color: {
      name: "배경색"
    },
    colors: {
      name: "색상"
    }
  },
  outputs: {
    "0": {
      name: "recraft 제어"
    }
  }
};
const RecraftCreativeUpscaleNode$2 = {
  description: "이미지를 동기적으로 업스케일합니다.\n‘크리에이티브 업스케일’ 도구를 사용하여 주어진 래스터 이미지를 향상시키고, 작은 디테일과 얼굴을 정교하게 개선하면서 해상도를 높입니다.",
  display_name: "Recraft 크리에이티브 업스케일 이미지",
  inputs: {
    image: {
      name: "이미지"
    }
  }
};
const RecraftCrispUpscaleNode$2 = {
  description: "이미지를 동기적으로 업스케일합니다.\n‘선명 업스케일’ 도구를 사용하여 주어진 래스터 이미지를 향상시키고, 해상도를 높여 이미지를 더 선명하고 깨끗하게 만듭니다.",
  display_name: "Recraft 선명 업스케일 이미지",
  inputs: {
    image: {
      name: "이미지"
    }
  }
};
const RecraftImageInpaintingNode$2 = {
  description: "프롬프트와 마스크를 기반으로 이미지를 수정합니다.",
  display_name: "Recraft 이미지 인페인팅",
  inputs: {
    control_after_generate: {
      name: "생성 후 제어"
    },
    image: {
      name: "이미지"
    },
    mask: {
      name: "마스크"
    },
    n: {
      name: "n",
      tooltip: "생성할 이미지의 개수입니다."
    },
    negative_prompt: {
      name: "부정 프롬프트",
      tooltip: "이미지에서 원하지 않는 요소에 대한 선택적 텍스트 설명입니다."
    },
    prompt: {
      name: "프롬프트",
      tooltip: "이미지 생성을 위한 프롬프트입니다."
    },
    recraft_style: {
      name: "recraft 스타일"
    },
    seed: {
      name: "시드",
      tooltip: "노드가 다시 실행되어야 하는지 결정하는 시드입니다. 실제 결과는 시드와 관계없이 비결정적입니다."
    }
  }
};
const RecraftImageToImageNode$2 = {
  description: "프롬프트와 강도를 기반으로 이미지를 수정합니다.",
  display_name: "Recraft 이미지 생성 (이미지 → 이미지)",
  inputs: {
    control_after_generate: {
      name: "생성 후 제어"
    },
    image: {
      name: "이미지"
    },
    n: {
      name: "개수",
      tooltip: "생성할 이미지의 수입니다."
    },
    negative_prompt: {
      name: "부정 프롬프트",
      tooltip: "이미지에서 원하지 않는 요소에 대한 선택적 텍스트 설명입니다."
    },
    prompt: {
      name: "프롬프트",
      tooltip: "이미지 생성을 위한 프롬프트입니다."
    },
    recraft_controls: {
      name: "recraft 제어",
      tooltip: "Recraft 제어 노드를 통한 생성에 대한 추가 제어(선택 사항)입니다."
    },
    recraft_style: {
      name: "recraft 스타일"
    },
    seed: {
      name: "시드",
      tooltip: "노드가 다시 실행되어야 하는지 결정하는 시드입니다. 실제 결과는 시드와 관계없이 비결정적입니다."
    },
    strength: {
      name: "강도",
      tooltip: "원본 이미지와의 차이를 정의합니다. [0, 1] 범위 내에서, 0은 거의 동일함을, 1은 매우 다름을 의미합니다."
    }
  }
};
const RecraftRemoveBackgroundNode$2 = {
  description: "이미지에서 배경을 제거하고, 처리된 이미지와 mask를 반환합니다.",
  display_name: "Recraft 배경 제거",
  inputs: {
    image: {
      name: "이미지"
    }
  }
};
const RecraftReplaceBackgroundNode$2 = {
  description: "제공된 프롬프트를 기반으로 이미지의 배경을 교체합니다.",
  display_name: "Recraft 배경 교체",
  inputs: {
    control_after_generate: {
      name: "생성 후 제어"
    },
    image: {
      name: "이미지"
    },
    n: {
      name: "개수",
      tooltip: "생성할 이미지의 수입니다."
    },
    negative_prompt: {
      name: "부정 프롬프트",
      tooltip: "이미지에서 원하지 않는 요소에 대한 선택적 텍스트 설명입니다."
    },
    prompt: {
      name: "프롬프트",
      tooltip: "이미지 생성을 위한 프롬프트입니다."
    },
    recraft_style: {
      name: "recraft 스타일"
    },
    seed: {
      name: "시드",
      tooltip: "노드를 다시 실행할지 결정하는 시드입니다. 실제 결과는 시드와 상관없이 비결정적입니다."
    }
  }
};
const RecraftStyleV3DigitalIllustration$2 = {
  description: "realistic_image 스타일과 선택적 하위 스타일을 선택하세요.",
  display_name: "Recraft 스타일 - 디지털 일러스트레이션",
  inputs: {
    substyle: {
      name: "하위 스타일"
    }
  },
  outputs: {
    "0": {
      name: "recraft 스타일"
    }
  }
};
const RecraftStyleV3InfiniteStyleLibrary$2 = {
  description: "Recraft의 무한 스타일 라이브러리에서 기존 UUID를 기반으로 스타일을 선택합니다.",
  display_name: "Recraft 스타일 - 무한 스타일 라이브러리",
  inputs: {
    style_id: {
      name: "스타일 ID",
      tooltip: "무한 스타일 라이브러리의 스타일 UUID입니다."
    }
  },
  outputs: {
    "0": {
      name: "recraft 스타일"
    }
  }
};
const RecraftStyleV3LogoRaster$2 = {
  description: "realistic_image 스타일과 선택적 하위 스타일을 선택하세요.",
  display_name: "Recraft 스타일 - 로고 래스터",
  inputs: {
    substyle: {
      name: "하위 스타일"
    }
  },
  outputs: {
    "0": {
      name: "recraft 스타일"
    }
  }
};
const RecraftStyleV3RealisticImage$2 = {
  description: "realistic_image 스타일과 선택적 하위 스타일을 선택하세요.",
  display_name: "Recraft 스타일 - 사실적인 이미지",
  inputs: {
    substyle: {
      name: "하위 스타일"
    }
  },
  outputs: {
    "0": {
      name: "recraft 스타일"
    }
  }
};
const RecraftTextToImageNode$2 = {
  description: "프롬프트와 해상도에 따라 이미지를 동기적으로 생성합니다.",
  display_name: "Recraft 이미지 생성 (텍스트 → 이미지)",
  inputs: {
    control_after_generate: {
      name: "생성 후 제어"
    },
    n: {
      name: "개수",
      tooltip: "생성할 이미지의 개수입니다."
    },
    negative_prompt: {
      name: "부정 프롬프트",
      tooltip: "이미지에서 원하지 않는 요소에 대한 선택적 텍스트 설명입니다."
    },
    prompt: {
      name: "프롬프트",
      tooltip: "이미지 생성을 위한 프롬프트입니다."
    },
    recraft_controls: {
      name: "recraft 제어",
      tooltip: "Recraft 제어 노드를 통한 생성에 대한 추가 제어(선택 사항)입니다."
    },
    recraft_style: {
      name: "recraft 스타일"
    },
    seed: {
      name: "시드",
      tooltip: "노드를 다시 실행할지 결정하는 시드입니다. 실제 결과는 시드와 관계없이 비결정적입니다."
    },
    size: {
      name: "크기",
      tooltip: "생성된 이미지의 크기입니다."
    }
  }
};
const RecraftTextToVectorNode$2 = {
  description: "프롬프트와 해상도에 따라 SVG를 동기적으로 생성합니다.",
  display_name: "Recraft 벡터 생성 (텍스트 → 벡터)",
  inputs: {
    control_after_generate: {
      name: "생성 후 제어"
    },
    n: {
      name: "개수",
      tooltip: "생성할 이미지의 개수입니다."
    },
    negative_prompt: {
      name: "부정 프롬프트",
      tooltip: "이미지에서 원하지 않는 요소에 대한 선택적 텍스트 설명입니다."
    },
    prompt: {
      name: "프롬프트",
      tooltip: "이미지 생성을 위한 프롬프트입니다."
    },
    recraft_controls: {
      name: "Recraft 제어",
      tooltip: "Recraft 제어 노드를 통한 생성에 대한 추가적인 선택적 제어입니다."
    },
    seed: {
      name: "시드",
      tooltip: "노드를 다시 실행할지 결정하는 시드입니다. 실제 결과는 시드와 관계없이 비결정적입니다."
    },
    size: {
      name: "크기",
      tooltip: "생성된 이미지의 크기입니다."
    },
    substyle: {
      name: "하위 스타일"
    }
  }
};
const RecraftVectorizeImageNode$2 = {
  description: "입력 이미지로부터 SVG를 동기적으로 생성합니다.",
  display_name: "Recraft 벡터 생성 (이미지 → 벡터)",
  inputs: {
    image: {
      name: "이미지"
    }
  }
};
const RenormCFG$2 = {
  display_name: "RenormCFG",
  inputs: {
    cfg_trunc: {
      name: "cfg_trunc"
    },
    model: {
      name: "모델"
    },
    renorm_cfg: {
      name: "renorm_cfg"
    }
  }
};
const RepeatImageBatch$2 = {
  display_name: "이미지 반복 배치 생성",
  inputs: {
    amount: {
      name: "개수"
    },
    image: {
      name: "이미지"
    }
  }
};
const RepeatLatentBatch$2 = {
  display_name: "잠재 데이터 반복 배치 생성",
  inputs: {
    amount: {
      name: "개수"
    },
    samples: {
      name: "잠재 데이터"
    }
  }
};
const RescaleCFG$2 = {
  display_name: "CFG 리스케일",
  inputs: {
    model: {
      name: "모델"
    },
    multiplier: {
      name: "배율"
    }
  }
};
const SDTurboScheduler$2 = {
  display_name: "SD-Turbo 스케줄러",
  inputs: {
    denoise: {
      name: "노이즈 제거양"
    },
    model: {
      name: "모델"
    },
    steps: {
      name: "스텝 수"
    }
  }
};
const SD_4XUpscale_Conditioning$2 = {
  display_name: "SD_4X 확대 조건 설정",
  inputs: {
    images: {
      name: "이미지"
    },
    negative: {
      name: "부정 조건"
    },
    noise_augmentation: {
      name: "노이즈 증강"
    },
    positive: {
      name: "긍정 조건"
    },
    scale_ratio: {
      name: "확대율"
    }
  },
  outputs: {
    "0": {
      name: "긍정 조건"
    },
    "1": {
      name: "부정 조건"
    },
    "2": {
      name: "잠재 이미지"
    }
  }
};
const SV3D_Conditioning$2 = {
  display_name: "SV3D 조건 설정",
  inputs: {
    clip_vision: {
      name: "clip_vision"
    },
    elevation: {
      name: "고도"
    },
    height: {
      name: "높이"
    },
    init_image: {
      name: "초기 이미지"
    },
    vae: {
      name: "vae"
    },
    video_frames: {
      name: "비디오 프레임"
    },
    width: {
      name: "너비"
    }
  },
  outputs: {
    "0": {
      name: "긍정 조건"
    },
    "1": {
      name: "부정 조건"
    },
    "2": {
      name: "잠재 데이터"
    }
  }
};
const SVD_img2vid_Conditioning$2 = {
  display_name: "SVD 조건 설정 (이미지 → 비디오)",
  inputs: {
    augmentation_level: {
      name: "증강 레벨"
    },
    clip_vision: {
      name: "clip_vision"
    },
    fps: {
      name: "fps"
    },
    height: {
      name: "높이"
    },
    init_image: {
      name: "초기 이미지"
    },
    motion_bucket_id: {
      name: "모션 버킷 ID"
    },
    vae: {
      name: "vae"
    },
    video_frames: {
      name: "비디오 프레임"
    },
    width: {
      name: "너비"
    }
  },
  outputs: {
    "0": {
      name: "긍정 조건"
    },
    "1": {
      name: "부정 조건"
    },
    "2": {
      name: "잠재 비디오"
    }
  }
};
const SamplerCustom$2 = {
  display_name: "사용자 정의 샘플러",
  inputs: {
    add_noise: {
      name: "노이즈 추가"
    },
    cfg: {
      name: "cfg"
    },
    control_after_generate: {
      name: "생성 후 제어"
    },
    latent_image: {
      name: "잠재 데이터"
    },
    model: {
      name: "모델"
    },
    negative: {
      name: "부정 조건"
    },
    noise_seed: {
      name: "노이즈 시드"
    },
    positive: {
      name: "긍정 조건"
    },
    sampler: {
      name: "샘플러"
    },
    sigmas: {
      name: "시그마 배열"
    }
  },
  outputs: {
    "0": {
      name: "출력"
    },
    "1": {
      name: "노이즈 제거된 출력"
    }
  }
};
const SamplerCustomAdvanced$2 = {
  display_name: "고급 사용자 정의 샘플러",
  inputs: {
    guider: {
      name: "가이더"
    },
    latent_image: {
      name: "잠재 데이터"
    },
    noise: {
      name: "노이즈"
    },
    sampler: {
      name: "샘플러"
    },
    sigmas: {
      name: "시그마 배열"
    }
  },
  outputs: {
    "0": {
      name: "출력"
    },
    "1": {
      name: "노이즈 제거된 출력"
    }
  }
};
const SamplerDPMAdaptative$2 = {
  display_name: "DPMAdaptive 샘플러",
  inputs: {
    accept_safety: {
      name: "accept_safety"
    },
    atol: {
      name: "atol"
    },
    dcoeff: {
      name: "dcoeff"
    },
    eta: {
      name: "eta"
    },
    h_init: {
      name: "초기 h"
    },
    icoeff: {
      name: "icoeff"
    },
    order: {
      name: "order"
    },
    pcoeff: {
      name: "pcoeff"
    },
    rtol: {
      name: "rtol"
    },
    s_noise: {
      name: "s_noise"
    }
  }
};
const SamplerDPMPP_2M_SDE$2 = {
  display_name: "DPMPP_2M_SDE 샘플러",
  inputs: {
    eta: {
      name: "eta"
    },
    noise_device: {
      name: "노이즈 생성 장치"
    },
    s_noise: {
      name: "s_noise"
    },
    solver_type: {
      name: "Solver 유형"
    }
  }
};
const SamplerDPMPP_2S_Ancestral$2 = {
  display_name: "DPMPP_2S_Ancestral 샘플러",
  inputs: {
    eta: {
      name: "eta"
    },
    s_noise: {
      name: "s_noise"
    }
  }
};
const SamplerDPMPP_3M_SDE$2 = {
  display_name: "DPMPP_3M_SDE 샘플러",
  inputs: {
    eta: {
      name: "eta"
    },
    noise_device: {
      name: "노이즈 생성 장치"
    },
    s_noise: {
      name: "s_noise"
    }
  }
};
const SamplerDPMPP_SDE$2 = {
  display_name: "DPMPP_SDE 샘플러",
  inputs: {
    eta: {
      name: "eta"
    },
    noise_device: {
      name: "노이즈 생성 장치"
    },
    r: {
      name: "r"
    },
    s_noise: {
      name: "s_noise"
    }
  }
};
const SamplerEulerAncestral$2 = {
  display_name: "Eluer Ancestral 샘플러",
  inputs: {
    eta: {
      name: "eta"
    },
    s_noise: {
      name: "s_noise"
    }
  }
};
const SamplerEulerAncestralCFGPP$2 = {
  display_name: "Eluer Acnestral CFG++ 샘플러",
  inputs: {
    eta: {
      name: "eta"
    },
    s_noise: {
      name: "s_noise"
    }
  }
};
const SamplerEulerCFGpp$2 = {
  display_name: "Eluer CFG++ 샘플러",
  inputs: {
    version: {
      name: "버전"
    }
  }
};
const SamplerLCMUpscale$2 = {
  display_name: "LCM 확대 샘플러",
  inputs: {
    scale_ratio: {
      name: "확대율"
    },
    scale_steps: {
      name: "확대 스텝 수"
    },
    upscale_method: {
      name: "업스케일 방법"
    }
  }
};
const SamplerLMS$2 = {
  display_name: "LMS 샘플러",
  inputs: {
    order: {
      name: "순서"
    }
  }
};
const SaveAnimatedPNG$2 = {
  display_name: "애니메이션 PNG 저장",
  inputs: {
    compress_level: {
      name: "압축 레벨"
    },
    filename_prefix: {
      name: "파일명 접두사"
    },
    fps: {
      name: "fps"
    },
    images: {
      name: "이미지"
    }
  }
};
const SaveAnimatedWEBP$2 = {
  display_name: "애니메이션 WEBP 저장",
  inputs: {
    filename_prefix: {
      name: "파일명 접두사"
    },
    fps: {
      name: "fps"
    },
    images: {
      name: "이미지"
    },
    lossless: {
      name: "무손실"
    },
    method: {
      name: "방법"
    },
    quality: {
      name: "품질"
    }
  }
};
const SaveAudio$2 = {
  display_name: "오디오 저장",
  inputs: {
    audio: {
      name: "오디오"
    },
    audioUI: {
      name: "오디오UI"
    },
    filename_prefix: {
      name: "파일명 접두사"
    }
  }
};
const SaveGLB$2 = {
  display_name: "GLB 저장",
  inputs: {
    filename_prefix: {
      name: "파일명 접두사"
    },
    image: {
      name: "이미지"
    },
    mesh: {
      name: "메시"
    }
  }
};
const SaveImage$2 = {
  description: "입력 이미지를 ComfyUI 출력 디렉토리에 저장합니다.",
  display_name: "이미지 저장",
  inputs: {
    filename_prefix: {
      name: "파일명 접두사",
      tooltip: "저장할 파일의 접두사입니다. 여기에는 %date:yyyy-MM-dd% 또는 %Empty Latent Image.width%와 같은 형식 정보가 포함되어 노드의 값을 포함할 수 있습니다."
    },
    images: {
      name: "이미지",
      tooltip: "저장할 이미지입니다."
    }
  }
};
const SaveImageWebsocket$2 = {
  display_name: "이미지 웹소켓 전송",
  inputs: {
    images: {
      name: "이미지"
    }
  }
};
const SaveLatent$2 = {
  display_name: "잠재 데이터 저장",
  inputs: {
    filename_prefix: {
      name: "파일명 접두사"
    },
    samples: {
      name: "잠재 데이터"
    }
  }
};
const SaveSVG$2 = {
  description: "SVG 파일을 디스크에 저장합니다.",
  display_name: "SVG 저장",
  inputs: {
    filename_prefix: {
      name: "파일명 접두사",
      tooltip: "저장할 파일의 접두사입니다. %date:yyyy-MM-dd% 또는 %Empty Latent Image.width%와 같이 노드의 값을 포함하는 형식 정보를 사용할 수 있습니다."
    },
    svg: {
      name: "svg"
    }
  }
};
const SaveVideo$2 = {
  description: "입력 이미지를 ComfyUI 출력 디렉토리에 저장합니다.",
  display_name: "비디오 저장",
  inputs: {
    codec: {
      name: "코덱",
      tooltip: "비디오에 사용할 코덱입니다."
    },
    filename_prefix: {
      name: "파일명 접두사",
      tooltip: "저장할 파일의 접두사입니다. %date:yyyy-MM-dd% 또는 %Empty Latent Image.width%와 같이 노드의 값을 포함하는 포맷 정보를 사용할 수 있습니다."
    },
    format: {
      name: "포맷",
      tooltip: "비디오를 저장할 포맷입니다."
    },
    video: {
      name: "비디오",
      tooltip: "저장할 비디오입니다."
    }
  }
};
const SaveWEBM$2 = {
  display_name: "동영상 저장 (WEBM)",
  inputs: {
    codec: {
      name: "코덱"
    },
    crf: {
      name: "crf",
      tooltip: "crf가 높을수록 파일 크기는 작지만 품질은 낮아집니다. crf가 낮을수록 파일 크기는 커지지만 품질은 높아집니다."
    },
    filename_prefix: {
      name: "파일명_접두사"
    },
    fps: {
      name: "fps"
    },
    images: {
      name: "이미지"
    }
  }
};
const SelfAttentionGuidance$2 = {
  display_name: "셀프 어텐션 가이드",
  inputs: {
    blur_sigma: {
      name: "블러 시그마"
    },
    model: {
      name: "모델"
    },
    scale: {
      name: "스케일"
    }
  }
};
const SetClipHooks$2 = {
  display_name: "CLIP 후크 설정",
  inputs: {
    apply_to_conds: {
      name: "조건에 적용"
    },
    clip: {
      name: "clip"
    },
    hooks: {
      name: "후크"
    },
    schedule_clip: {
      name: "clip 스케쥴 사용"
    }
  }
};
const SetFirstSigma$2 = {
  display_name: "SetFirstSigma",
  inputs: {
    sigma: {
      name: "시그마"
    },
    sigmas: {
      name: "시그마 배열"
    }
  }
};
const SetHookKeyframes$2 = {
  display_name: "후크 키프레임 설정",
  inputs: {
    hook_kf: {
      name: "KF 후크"
    },
    hooks: {
      name: "후크"
    }
  }
};
const SetLatentNoiseMask$2 = {
  display_name: "잠재 데이터에 노이즈 마스크 설정",
  inputs: {
    mask: {
      name: "마스크"
    },
    samples: {
      name: "잠재 데이터"
    }
  }
};
const SetUnionControlNetType$2 = {
  display_name: "통합 컨트롤넷 유형 설정",
  inputs: {
    control_net: {
      name: "컨트롤넷"
    },
    type: {
      name: "유형"
    }
  }
};
const SkipLayerGuidanceDiT$2 = {
  description: "모든 DiT 모델에서 사용할 수 있는 '레이어 건너뛰기 가이던스' 노드의 범용 버전입니다.",
  display_name: "레이어 건너뛰기 가이던스 (DiT)",
  inputs: {
    double_layers: {
      name: "double_layers"
    },
    end_percent: {
      name: "종료 퍼센트"
    },
    model: {
      name: "모델"
    },
    rescaling_scale: {
      name: "리스케일 크기"
    },
    scale: {
      name: "크기"
    },
    single_layers: {
      name: "single_layers"
    },
    start_percent: {
      name: "시작 퍼센트"
    }
  }
};
const SkipLayerGuidanceSD3$2 = {
  description: "SD3 용 레이어 건너뛰기 가이던스 노드입니다.",
  display_name: "레이어 건너뛰기 가이던스 (SD3)",
  inputs: {
    end_percent: {
      name: "종료 퍼센트"
    },
    layers: {
      name: "layers"
    },
    model: {
      name: "모델"
    },
    scale: {
      name: "크기"
    },
    start_percent: {
      name: "시작 퍼센트"
    }
  }
};
const SolidMask$2 = {
  display_name: "단색 마스크",
  inputs: {
    height: {
      name: "높이"
    },
    value: {
      name: "값"
    },
    width: {
      name: "너비"
    }
  }
};
const SplitImageWithAlpha$2 = {
  display_name: "이미지와 알파채널 분리",
  inputs: {
    image: {
      name: "이미지"
    }
  }
};
const SplitSigmas$2 = {
  display_name: "시그마 배열 분할 (스텝)",
  inputs: {
    sigmas: {
      name: "시그마 배열"
    },
    step: {
      name: "분할 스텝"
    }
  },
  outputs: {
    "0": {
      name: "높은 시그마 배열"
    },
    "1": {
      name: "낮은 시그마 배열"
    }
  }
};
const SplitSigmasDenoise$2 = {
  display_name: "시그마 배열 분할 (노이즈 제거양)",
  inputs: {
    denoise: {
      name: "노이즈 제거양"
    },
    sigmas: {
      name: "시그마 배열"
    }
  },
  outputs: {
    "0": {
      name: "높은 시그마 배열"
    },
    "1": {
      name: "낮은 시그마 배열"
    }
  }
};
const StabilityStableImageSD_3_5Node$2 = {
  description: "프롬프트와 해상도에 따라 이미지를 동기적으로 생성합니다.",
  display_name: "Stability AI Stable Diffusion 3.5 이미지",
  inputs: {
    aspect_ratio: {
      name: "종횡비",
      tooltip: "생성된 이미지의 종횡비입니다."
    },
    cfg_scale: {
      name: "cfg 스케일",
      tooltip: "디퓨전 과정이 프롬프트 텍스트를 얼마나 엄격하게 따르는지 결정합니다(값이 높을수록 이미지가 프롬프트에 더 가깝게 생성됩니다)."
    },
    control_after_generate: {
      name: "생성 후 제어"
    },
    image: {
      name: "이미지"
    },
    image_denoise: {
      name: "노이즈 제거양",
      tooltip: "입력 이미지의 노이즈 제거 정도; 0.0은 입력 이미지와 동일, 1.0은 이미지가 전혀 제공되지 않은 것과 같습니다."
    },
    model: {
      name: "모델"
    },
    negative_prompt: {
      name: "부정 프롬프트",
      tooltip: "출력 이미지에 나타나지 않길 원하는 키워드입니다. 고급 기능입니다."
    },
    prompt: {
      name: "프롬프트",
      tooltip: "출력 이미지에서 보고 싶은 내용을 입력하세요. 요소, 색상, 주제를 명확하게 정의하는 강력하고 구체적인 프롬프트가 더 나은 결과를 가져옵니다."
    },
    seed: {
      name: "시드",
      tooltip: "노이즈 생성을 위해 사용되는 랜덤 시드입니다."
    },
    style_preset: {
      name: "스타일 프리셋",
      tooltip: "생성된 이미지에 원하는 스타일(선택 사항)입니다."
    }
  }
};
const StabilityStableImageUltraNode$2 = {
  description: "프롬프트와 해상도에 따라 이미지를 동기적으로 생성합니다.",
  display_name: "Stability AI Stable Image Ultra",
  inputs: {
    aspect_ratio: {
      name: "종횡비",
      tooltip: "생성된 이미지의 가로세로 비율입니다."
    },
    control_after_generate: {
      name: "생성 후 제어"
    },
    image: {
      name: "이미지"
    },
    image_denoise: {
      name: "노이즈 제거양",
      tooltip: "입력 이미지의 노이즈 제거 정도입니다. 0.0은 입력 이미지와 동일하며, 1.0은 이미지가 전혀 제공되지 않은 것과 같습니다."
    },
    negative_prompt: {
      name: "부정 프롬프트",
      tooltip: "출력 이미지에서 보고 싶지 않은 내용을 설명하는 텍스트입니다. 고급 기능입니다."
    },
    prompt: {
      name: "프롬프트",
      tooltip: "출력 이미지에서 보고 싶은 내용을 입력하세요. 요소, 색상, 주제를 명확하게 정의하는 강력하고 구체적인 프롬프트가 더 나은 결과를 가져옵니다. 특정 단어의 가중치를 조절하려면 `(단어:가중치)` 형식을 사용하세요. 여기서 `단어`는 가중치를 조절하고 싶은 단어이고, `가중치`는 0과 1 사이의 값입니다. 예시: `The sky was a crisp (blue:0.3) and (green:0.8)`는 하늘이 파란색과 초록색이지만 초록색이 더 많다는 의미입니다."
    },
    seed: {
      name: "시드",
      tooltip: "노이즈 생성을 위한 랜덤 시드 값입니다."
    },
    style_preset: {
      name: "스타일 프리셋",
      tooltip: "생성된 이미지에 적용할 선택적 스타일입니다."
    }
  }
};
const StabilityUpscaleConservativeNode$2 = {
  description: "이미지를 최소한의 변경으로 4K 해상도로 업스케일합니다.",
  display_name: "Stability AI 업스케일 보수적",
  inputs: {
    control_after_generate: {
      name: "생성 후 제어"
    },
    creativity: {
      name: "창의성",
      tooltip: "초기 이미지에 크게 의존하지 않는 추가 디테일이 생성될 가능성을 조절합니다."
    },
    image: {
      name: "이미지"
    },
    negative_prompt: {
      name: "부정 프롬프트",
      tooltip: "출력 이미지에 나타나길 원하지 않는 키워드를 입력하세요. 고급 기능입니다."
    },
    prompt: {
      name: "프롬프트",
      tooltip: "출력 이미지에서 보고 싶은 내용을 입력하세요. 요소, 색상, 주제를 명확하게 정의하는 강력하고 구체적인 프롬프트가 더 나은 결과를 가져옵니다."
    },
    seed: {
      name: "시드",
      tooltip: "노이즈 생성을 위한 랜덤 시드입니다."
    }
  }
};
const StabilityUpscaleCreativeNode$2 = {
  description: "이미지를 최소한의 변경으로 4K 해상도로 업스케일합니다.",
  display_name: "Stability AI 업스케일 크리에이티브",
  inputs: {
    control_after_generate: {
      name: "생성 후 제어"
    },
    creativity: {
      name: "창의성",
      tooltip: "초기 이미지에 크게 의존하지 않고 추가적인 디테일이 생성될 가능성을 조절합니다."
    },
    image: {
      name: "이미지"
    },
    negative_prompt: {
      name: "부정 프롬프트",
      tooltip: "출력 이미지에 나타나길 원하지 않는 키워드를 입력하세요. 고급 기능입니다."
    },
    prompt: {
      name: "프롬프트",
      tooltip: "출력 이미지에서 보고 싶은 내용을 입력하세요. 요소, 색상, 주제를 명확하게 정의하는 강력하고 구체적인 프롬프트가 더 나은 결과를 가져옵니다."
    },
    seed: {
      name: "시드",
      tooltip: "노이즈 생성을 위한 랜덤 시드입니다."
    },
    style_preset: {
      name: "스타일 프리셋",
      tooltip: "생성된 이미지에 원하는 스타일(선택 사항)을 지정합니다."
    }
  }
};
const StabilityUpscaleFastNode$2 = {
  description: "Stability API 호출을 통해 이미지를 원본의 4배 크기로 빠르게 업스케일합니다. 저화질/압축 이미지의 업스케일에 적합합니다.",
  display_name: "Stability AI 초고속 업스케일",
  inputs: {
    image: {
      name: "이미지"
    }
  }
};
const StableCascade_EmptyLatentImage$2 = {
  display_name: "StableCascade 빈 잠재 이미지",
  inputs: {
    batch_size: {
      name: "배치 크기"
    },
    compression: {
      name: "압축"
    },
    height: {
      name: "높이"
    },
    width: {
      name: "너비"
    }
  },
  outputs: {
    "0": {
      name: "StageC 잠재 이미지"
    },
    "1": {
      name: "StageB 잠재 이미지"
    }
  }
};
const StableCascade_StageB_Conditioning$2 = {
  display_name: "StableCascasde_StageB 조건 설정",
  inputs: {
    conditioning: {
      name: "조건"
    },
    stage_c: {
      name: "StageC 잠재 이미지"
    }
  }
};
const StableCascade_StageC_VAEEncode$2 = {
  display_name: "StableCascade_StageC VAE 인코딩",
  inputs: {
    compression: {
      name: "압축"
    },
    image: {
      name: "이미지"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "StageC 잠재 이미지"
    },
    "1": {
      name: "StageB 잠재 이미지"
    }
  }
};
const StableCascade_SuperResolutionControlnet$2 = {
  display_name: "StableCascade 초고해상도 컨트롤넷",
  inputs: {
    image: {
      name: "이미지"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "컨트롤넷 입력"
    },
    "1": {
      name: "StageC 잠재 이미지"
    },
    "2": {
      name: "StageB 잠재 이미지"
    }
  }
};
const StableZero123_Conditioning$2 = {
  display_name: "StableZero123 조건 설정",
  inputs: {
    azimuth: {
      name: "방위각"
    },
    batch_size: {
      name: "배치 크기"
    },
    clip_vision: {
      name: "clip_vision"
    },
    elevation: {
      name: "고도"
    },
    height: {
      name: "높이"
    },
    init_image: {
      name: "초기 이미지"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "너비"
    }
  },
  outputs: {
    "0": {
      name: "긍정 조건"
    },
    "1": {
      name: "부정 조건"
    },
    "2": {
      name: "잠재 데이터"
    }
  }
};
const StableZero123_Conditioning_Batched$2 = {
  display_name: "StableZero123 조건 설정 (배치)",
  inputs: {
    azimuth: {
      name: "방위각"
    },
    azimuth_batch_increment: {
      name: "방위각 배치 증가"
    },
    batch_size: {
      name: "배치 크기"
    },
    clip_vision: {
      name: "clip_vision"
    },
    elevation: {
      name: "고도"
    },
    elevation_batch_increment: {
      name: "고도 배치 증가"
    },
    height: {
      name: "높이"
    },
    init_image: {
      name: "초기 이미지"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "너비"
    }
  },
  outputs: {
    "0": {
      name: "긍정 조건"
    },
    "1": {
      name: "부정 조건"
    },
    "2": {
      name: "잠재 데이터"
    }
  }
};
const StyleModelApply$2 = {
  display_name: "스타일 모델 적용",
  inputs: {
    clip_vision_output: {
      name: "clip_vision 출력"
    },
    conditioning: {
      name: "조건"
    },
    strength: {
      name: "강도"
    },
    strength_type: {
      name: "강도 유형"
    },
    style_model: {
      name: "스타일 모델"
    }
  }
};
const StyleModelLoader$2 = {
  display_name: "스타일 모델 로드",
  inputs: {
    style_model_name: {
      name: "스타일 모델 이름"
    }
  }
};
const T5TokenizerOptions$2 = {
  display_name: "T5 토큰생성기 옵션",
  inputs: {
    clip: {
      name: "clip"
    },
    min_length: {
      name: "최소 길이"
    },
    min_padding: {
      name: "최소 패딩"
    }
  }
};
const TextEncodeHunyuanVideo_ImageToVideo$2 = {
  display_name: "HunyuanVideo 텍스트 인코딩 (이미지 → 비디오)",
  inputs: {
    clip: {
      name: "클립"
    },
    clip_vision_output: {
      name: "clip_vision 출력"
    },
    image_interleave: {
      name: "이미지 인터리브",
      tooltip: "이미지가 텍스트 프롬프트와 비교하여 얼마나 영향을 미치는지. 높은 숫자는 텍스트 프롬프트로부터 더 많은 영향을 받음을 의미합니다."
    },
    prompt: {
      name: "프롬프트"
    }
  }
};
const ThresholdMask$2 = {
  display_name: "임계값 마스크",
  inputs: {
    mask: {
      name: "마스크"
    },
    value: {
      name: "값"
    }
  }
};
const TomePatchModel$2 = {
  display_name: "토큰 병합(ToMe) 모델 패치",
  inputs: {
    model: {
      name: "모델"
    },
    ratio: {
      name: "비율"
    }
  }
};
const TorchCompileModel$2 = {
  display_name: "모델 토치 컴파일",
  inputs: {
    backend: {
      name: "백엔드"
    },
    model: {
      name: "모델"
    }
  }
};
const TrimVideoLatent$2 = {
  display_name: "잠재 비디오 자르기",
  inputs: {
    samples: {
      name: "샘플"
    },
    trim_amount: {
      name: "자르기 양"
    }
  }
};
const TripleCLIPLoader$2 = {
  description: "[조합법]\n\nsd3: clip-l, clip-g, t5",
  display_name: "삼중 CLIP 로드",
  inputs: {
    clip_name1: {
      name: "CLIP 파일명1"
    },
    clip_name2: {
      name: "CLIP 파일명2"
    },
    clip_name3: {
      name: "CLIP 파일명3"
    }
  }
};
const UNETLoader$2 = {
  display_name: "확산 모델 로드",
  inputs: {
    unet_name: {
      name: "UNet 모델 파일명"
    },
    weight_dtype: {
      name: "가중치 데이터 유형"
    }
  }
};
const UNetCrossAttentionMultiply$2 = {
  display_name: "UNet 교차 어텐션 곱하기",
  inputs: {
    k: {
      name: "k"
    },
    model: {
      name: "모델"
    },
    out: {
      name: "out"
    },
    q: {
      name: "q"
    },
    v: {
      name: "v"
    }
  }
};
const UNetSelfAttentionMultiply$2 = {
  display_name: "UNet 셀프 어텐션 곱하기",
  inputs: {
    k: {
      name: "k"
    },
    model: {
      name: "모델"
    },
    out: {
      name: "out"
    },
    q: {
      name: "q"
    },
    v: {
      name: "v"
    }
  }
};
const UNetTemporalAttentionMultiply$2 = {
  display_name: "UNet 템포럴 어텐션 곱하기",
  inputs: {
    cross_structural: {
      name: "구조적 크로스"
    },
    cross_temporal: {
      name: "시간적 크로스"
    },
    model: {
      name: "모델"
    },
    self_structural: {
      name: "구조적 셀프"
    },
    self_temporal: {
      name: "시간적 셀프"
    }
  }
};
const UpscaleModelLoader$2 = {
  display_name: "업스케일 모델 로드",
  inputs: {
    model_name: {
      name: "모델 파일명"
    }
  }
};
const VAEDecode$2 = {
  description: "잠재 데이터를 픽셀 공간 이미지로 디코딩합니다.",
  display_name: "VAE 디코드",
  inputs: {
    samples: {
      name: "잠재 데이터",
      tooltip: "디코딩할 잠재입니다."
    },
    vae: {
      name: "vae",
      tooltip: "잠재 디코딩에 사용되는 VAE 모델입니다."
    }
  },
  outputs: {
    "0": {
      tooltip: "디코딩된 이미지입니다."
    }
  }
};
const VAEDecodeAudio$2 = {
  display_name: "오디오 VAE 디코드",
  inputs: {
    samples: {
      name: "잠재 오디오"
    },
    vae: {
      name: "vae"
    }
  }
};
const VAEDecodeHunyuan3D$2 = {
  display_name: "VAEDecodeHunyuan3D",
  inputs: {
    num_chunks: {
      name: "분할 수"
    },
    octree_resolution: {
      name: "옥트리 해상도"
    },
    samples: {
      name: "샘플"
    },
    vae: {
      name: "vae"
    }
  }
};
const VAEDecodeTiled$2 = {
  display_name: "VAE 디코드 (타일)",
  inputs: {
    overlap: {
      name: "겹침"
    },
    samples: {
      name: "잠재 데이터"
    },
    temporal_overlap: {
      name: "시간 겹침",
      tooltip: "비디오 VAE에만 사용됩니다: 겹치는 프레임의 양."
    },
    temporal_size: {
      name: "시간 크기",
      tooltip: "비디오 VAE에만 사용됩니다: 한 번에 디코딩할 프레임의 양."
    },
    tile_size: {
      name: "타일 크기"
    },
    vae: {
      name: "vae"
    }
  }
};
const VAEEncode$2 = {
  display_name: "VAE 인코드",
  inputs: {
    pixels: {
      name: "픽셀 이미지"
    },
    vae: {
      name: "vae"
    }
  }
};
const VAEEncodeAudio$2 = {
  display_name: "오디오 VAE 인코드",
  inputs: {
    audio: {
      name: "오디오"
    },
    vae: {
      name: "vae"
    }
  }
};
const VAEEncodeForInpaint$2 = {
  display_name: "VAE 인코드 (인페인팅용)",
  inputs: {
    grow_mask_by: {
      name: "마스크 확장"
    },
    mask: {
      name: "마스크"
    },
    pixels: {
      name: "픽셀"
    },
    vae: {
      name: "vae"
    }
  }
};
const VAEEncodeTiled$2 = {
  display_name: "VAE 인코드 (타일)",
  inputs: {
    overlap: {
      name: "겹침"
    },
    pixels: {
      name: "픽셀"
    },
    temporal_overlap: {
      name: "시간적 겹침",
      tooltip: "비디오 VAE에만 사용됩니다: 겹치는 프레임의 양."
    },
    temporal_size: {
      name: "시간적 크기",
      tooltip: "비디오 VAE에만 사용됩니다: 한 번에 인코딩할 프레임의 양."
    },
    tile_size: {
      name: "타일 크기"
    },
    vae: {
      name: "vae"
    }
  }
};
const VAELoader$2 = {
  display_name: "VAE 로드",
  inputs: {
    vae_name: {
      name: "vae 파일명"
    }
  }
};
const VAESave$2 = {
  display_name: "VAE 저장",
  inputs: {
    filename_prefix: {
      name: "파일명 접두사"
    },
    vae: {
      name: "vae"
    }
  }
};
const VPScheduler$2 = {
  display_name: "VP 스케줄러",
  inputs: {
    beta_d: {
      name: "beta_d"
    },
    beta_min: {
      name: "beta_min"
    },
    eps_s: {
      name: "eps_s"
    },
    steps: {
      name: "스텝 수"
    }
  }
};
const VeoVideoGenerationNode$2 = {
  description: "Google의 Veo API를 사용하여 텍스트 프롬프트로부터 비디오를 생성합니다",
  display_name: "Google Veo2 비디오 생성",
  inputs: {
    aspect_ratio: {
      name: "종횡비",
      tooltip: "출력 비디오의 가로세로 비율"
    },
    control_after_generate: {
      name: "생성 후 제어"
    },
    duration_seconds: {
      name: "duration_seconds",
      tooltip: "출력 비디오의 길이(초)"
    },
    enhance_prompt: {
      name: "프롬프트 개선",
      tooltip: "AI 지원으로 프롬프트를 향상시킬지 여부"
    },
    image: {
      name: "이미지",
      tooltip: "비디오 생성을 안내할 선택적 참조 이미지"
    },
    negative_prompt: {
      name: "부정 프롬프트",
      tooltip: "비디오에서 피해야 할 내용을 안내하는 네거티브 텍스트 프롬프트"
    },
    person_generation: {
      name: "사람 생성",
      tooltip: "비디오에서 사람 생성을 허용할지 여부"
    },
    prompt: {
      name: "프롬프트",
      tooltip: "비디오에 대한 텍스트 설명"
    },
    seed: {
      name: "시드",
      tooltip: "비디오 생성용 시드 (0은 무작위)"
    }
  }
};
const VideoLinearCFGGuidance$2 = {
  display_name: "비디오 선형 CFG 가이드",
  inputs: {
    min_cfg: {
      name: "최소 cfg"
    },
    model: {
      name: "모델"
    }
  }
};
const VideoTriangleCFGGuidance$2 = {
  display_name: "비디오 삼각형 CFG 가이드",
  inputs: {
    min_cfg: {
      name: "최소 cfg"
    },
    model: {
      name: "모델"
    }
  }
};
const VoxelToMesh$2 = {
  display_name: "복셀 → 매시",
  inputs: {
    algorithm: {
      name: "알고리즘"
    },
    threshold: {
      name: "임계값"
    },
    voxel: {
      name: "복셀"
    }
  }
};
const VoxelToMeshBasic$2 = {
  display_name: "복셀 → 매시 (기본)",
  inputs: {
    threshold: {
      name: "임계값"
    },
    voxel: {
      name: "복셀"
    }
  }
};
const WanFirstLastFrameToVideo$2 = {
  display_name: "WAN 비디오 생성 (시작-끝 프레임)",
  inputs: {
    batch_size: {
      name: "배치 크기"
    },
    clip_vision_end_image: {
      name: "clip 비전 종료 이미지"
    },
    clip_vision_start_image: {
      name: "clip 비전 시작 이미지"
    },
    end_image: {
      name: "종료 이미지"
    },
    height: {
      name: "높이"
    },
    length: {
      name: "길이"
    },
    negative: {
      name: "부정 조건"
    },
    positive: {
      name: "긍정 조건"
    },
    start_image: {
      name: "시작 이미지"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "너비"
    }
  },
  outputs: {
    "0": {
      name: "긍정 조건"
    },
    "1": {
      name: "부정 조건"
    },
    "2": {
      name: "latent"
    }
  }
};
const WanFunControlToVideo$2 = {
  display_name: "WAN 비디오 생성 (Fun Control)",
  inputs: {
    batch_size: {
      name: "배치 크기"
    },
    clip_vision_output: {
      name: "clip 비전 출력"
    },
    control_video: {
      name: "제어 비디오"
    },
    height: {
      name: "높이"
    },
    length: {
      name: "길이"
    },
    negative: {
      name: "부정 조건"
    },
    positive: {
      name: "긍정 조건"
    },
    start_image: {
      name: "시작 이미지"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "너비"
    }
  },
  outputs: {
    "0": {
      name: "긍정 조건"
    },
    "1": {
      name: "부정 조건"
    },
    "2": {
      name: "latent"
    }
  }
};
const WanFunInpaintToVideo$2 = {
  display_name: "WAN 비디오 생성 (Fun Inpaint)",
  inputs: {
    batch_size: {
      name: "배치 크기"
    },
    clip_vision_output: {
      name: "clip_vision 출력"
    },
    end_image: {
      name: "종료 이미지"
    },
    height: {
      name: "높이"
    },
    length: {
      name: "길이"
    },
    negative: {
      name: "부정 조건"
    },
    positive: {
      name: "긍정 조건"
    },
    start_image: {
      name: "시작 이미지"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "너비"
    }
  },
  outputs: {
    "0": {
      name: "긍정 조건"
    },
    "1": {
      name: "부정 조건"
    },
    "2": {
      name: "latent"
    }
  }
};
const WanImageToVideo$2 = {
  display_name: "WAN 비디오 생성 (이미지 → 비디오)",
  inputs: {
    batch_size: {
      name: "배치 크기"
    },
    clip_vision_output: {
      name: "clip_vision 출력"
    },
    height: {
      name: "높이"
    },
    length: {
      name: "길이"
    },
    negative: {
      name: "부정 조건"
    },
    positive: {
      name: "긍정 조건"
    },
    start_image: {
      name: "시작 이미지"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "너비"
    }
  },
  outputs: {
    "0": {
      name: "긍정 조건"
    },
    "1": {
      name: "부정 조건"
    },
    "2": {
      name: "잠재 비디오"
    }
  }
};
const WanVaceToVideo$2 = {
  display_name: "WAN 비디오 생성 (VACE)",
  inputs: {
    batch_size: {
      name: "배치 크기"
    },
    control_masks: {
      name: "제어 마스크"
    },
    control_video: {
      name: "제어 비디오"
    },
    height: {
      name: "높이"
    },
    length: {
      name: "길이"
    },
    negative: {
      name: "부정 조건"
    },
    positive: {
      name: "긍정 조건"
    },
    reference_image: {
      name: "참조 이미지"
    },
    strength: {
      name: "강도"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "너비"
    }
  },
  outputs: {
    "0": {
      name: "긍정 조건"
    },
    "1": {
      name: "부정 조건"
    },
    "2": {
      name: "잠재 비디오"
    },
    "3": {
      name: "잘린 잠재 비디오"
    }
  }
};
const WebcamCapture$2 = {
  display_name: "웹캠 캡처",
  inputs: {
    capture_on_queue: {
      name: "큐에서 캡처"
    },
    height: {
      name: "높이"
    },
    image: {
      name: "이미지"
    },
    "waiting for camera___": {},
    width: {
      name: "너비"
    }
  }
};
const unCLIPCheckpointLoader$2 = {
  display_name: "unCLIP 체크포인트 로드",
  inputs: {
    ckpt_name: {
      name: "체크포인트 파일명"
    }
  }
};
const unCLIPConditioning$2 = {
  display_name: "unCLIP 조건 설정",
  inputs: {
    clip_vision_output: {
      name: "clip_vision 출력"
    },
    conditioning: {
      name: "조건"
    },
    noise_augmentation: {
      name: "노이즈 증강"
    },
    strength: {
      name: "강도"
    }
  }
};
const koNodes = {
  AddNoise: AddNoise$2,
  AlignYourStepsScheduler: AlignYourStepsScheduler$2,
  BasicGuider: BasicGuider$2,
  BasicScheduler: BasicScheduler$2,
  BetaSamplingScheduler: BetaSamplingScheduler$2,
  CFGGuider: CFGGuider$2,
  CFGZeroStar: CFGZeroStar$2,
  CLIPAttentionMultiply: CLIPAttentionMultiply$2,
  CLIPLoader: CLIPLoader$2,
  CLIPMergeAdd: CLIPMergeAdd$2,
  CLIPMergeSimple: CLIPMergeSimple$2,
  CLIPMergeSubtract: CLIPMergeSubtract$2,
  CLIPSave: CLIPSave$2,
  CLIPSetLastLayer: CLIPSetLastLayer$2,
  CLIPTextEncode: CLIPTextEncode$2,
  CLIPTextEncodeControlnet: CLIPTextEncodeControlnet$2,
  CLIPTextEncodeFlux: CLIPTextEncodeFlux$2,
  CLIPTextEncodeHiDream: CLIPTextEncodeHiDream$2,
  CLIPTextEncodeHunyuanDiT: CLIPTextEncodeHunyuanDiT$2,
  CLIPTextEncodeLumina2: CLIPTextEncodeLumina2$2,
  CLIPTextEncodePixArtAlpha: CLIPTextEncodePixArtAlpha$2,
  CLIPTextEncodeSD3: CLIPTextEncodeSD3$2,
  CLIPTextEncodeSDXL: CLIPTextEncodeSDXL$2,
  CLIPTextEncodeSDXLRefiner: CLIPTextEncodeSDXLRefiner$2,
  CLIPVisionEncode: CLIPVisionEncode$2,
  CLIPVisionLoader: CLIPVisionLoader$2,
  Canny: Canny$2,
  CheckpointLoader: CheckpointLoader$2,
  CheckpointLoaderSimple: CheckpointLoaderSimple$2,
  CheckpointSave: CheckpointSave$2,
  CombineHooks2: CombineHooks2$2,
  CombineHooks4: CombineHooks4$2,
  CombineHooks8: CombineHooks8$2,
  ConditioningAverage: ConditioningAverage$2,
  ConditioningCombine: ConditioningCombine$2,
  ConditioningConcat: ConditioningConcat$2,
  ConditioningSetArea: ConditioningSetArea$2,
  ConditioningSetAreaPercentage: ConditioningSetAreaPercentage$2,
  ConditioningSetAreaPercentageVideo: ConditioningSetAreaPercentageVideo$2,
  ConditioningSetAreaStrength: ConditioningSetAreaStrength$2,
  ConditioningSetDefaultCombine: ConditioningSetDefaultCombine$2,
  ConditioningSetMask: ConditioningSetMask$2,
  ConditioningSetProperties: ConditioningSetProperties$2,
  ConditioningSetPropertiesAndCombine: ConditioningSetPropertiesAndCombine$2,
  ConditioningSetTimestepRange: ConditioningSetTimestepRange$2,
  ConditioningStableAudio: ConditioningStableAudio$2,
  ConditioningTimestepsRange: ConditioningTimestepsRange$2,
  ConditioningZeroOut: ConditioningZeroOut$2,
  ControlNetApply: ControlNetApply$2,
  ControlNetApplyAdvanced: ControlNetApplyAdvanced$2,
  ControlNetApplySD3: ControlNetApplySD3$2,
  ControlNetInpaintingAliMamaApply: ControlNetInpaintingAliMamaApply$2,
  ControlNetLoader: ControlNetLoader$2,
  CosmosImageToVideoLatent: CosmosImageToVideoLatent$2,
  CreateHookKeyframe: CreateHookKeyframe$2,
  CreateHookKeyframesFromFloats: CreateHookKeyframesFromFloats$2,
  CreateHookKeyframesInterpolated: CreateHookKeyframesInterpolated$2,
  CreateHookLora: CreateHookLora$2,
  CreateHookLoraModelOnly: CreateHookLoraModelOnly$2,
  CreateHookModelAsLora: CreateHookModelAsLora$2,
  CreateHookModelAsLoraModelOnly: CreateHookModelAsLoraModelOnly$2,
  CreateVideo: CreateVideo$2,
  CropMask: CropMask$2,
  DiffControlNetLoader: DiffControlNetLoader$2,
  DifferentialDiffusion: DifferentialDiffusion$2,
  DiffusersLoader: DiffusersLoader$2,
  DisableNoise: DisableNoise$2,
  DualCFGGuider: DualCFGGuider$2,
  DualCLIPLoader: DualCLIPLoader$2,
  EmptyCosmosLatentVideo: EmptyCosmosLatentVideo$2,
  EmptyHunyuanLatentVideo: EmptyHunyuanLatentVideo$2,
  EmptyImage: EmptyImage$2,
  EmptyLTXVLatentVideo: EmptyLTXVLatentVideo$2,
  EmptyLatentAudio: EmptyLatentAudio$2,
  EmptyLatentHunyuan3Dv2: EmptyLatentHunyuan3Dv2$2,
  EmptyLatentImage: EmptyLatentImage$2,
  EmptyMochiLatentVideo: EmptyMochiLatentVideo$2,
  EmptySD3LatentImage: EmptySD3LatentImage$2,
  ExponentialScheduler: ExponentialScheduler$2,
  ExtendIntermediateSigmas: ExtendIntermediateSigmas$2,
  FeatherMask: FeatherMask$2,
  FlipSigmas: FlipSigmas$2,
  FluxDisableGuidance: FluxDisableGuidance$2,
  FluxGuidance: FluxGuidance$2,
  FluxProCannyNode: FluxProCannyNode$2,
  FluxProDepthNode: FluxProDepthNode$2,
  FluxProExpandNode: FluxProExpandNode$2,
  FluxProFillNode: FluxProFillNode$2,
  FluxProUltraImageNode: FluxProUltraImageNode$2,
  FreSca: FreSca$2,
  FreeU: FreeU$2,
  FreeU_V2: FreeU_V2$2,
  GITSScheduler: GITSScheduler$2,
  GLIGENLoader: GLIGENLoader$2,
  GLIGENTextBoxApply: GLIGENTextBoxApply$2,
  GetVideoComponents: GetVideoComponents$2,
  GrowMask: GrowMask$2,
  Hunyuan3Dv2Conditioning: Hunyuan3Dv2Conditioning$2,
  Hunyuan3Dv2ConditioningMultiView: Hunyuan3Dv2ConditioningMultiView$2,
  HunyuanImageToVideo: HunyuanImageToVideo$2,
  HyperTile: HyperTile$2,
  HypernetworkLoader: HypernetworkLoader$2,
  IdeogramV1: IdeogramV1$2,
  IdeogramV2: IdeogramV2$2,
  IdeogramV3: IdeogramV3$2,
  ImageBatch: ImageBatch$2,
  ImageBlend: ImageBlend$2,
  ImageBlur: ImageBlur$2,
  ImageColorToMask: ImageColorToMask$2,
  ImageCompositeMasked: ImageCompositeMasked$2,
  ImageCrop: ImageCrop$2,
  ImageFromBatch: ImageFromBatch$2,
  ImageInvert: ImageInvert$2,
  ImageOnlyCheckpointLoader: ImageOnlyCheckpointLoader$2,
  ImageOnlyCheckpointSave: ImageOnlyCheckpointSave$2,
  ImagePadForOutpaint: ImagePadForOutpaint$2,
  ImageQuantize: ImageQuantize$2,
  ImageRGBToYUV: ImageRGBToYUV$2,
  ImageScale: ImageScale$2,
  ImageScaleBy: ImageScaleBy$2,
  ImageScaleToTotalPixels: ImageScaleToTotalPixels$2,
  ImageSharpen: ImageSharpen$2,
  ImageToMask: ImageToMask$2,
  ImageUpscaleWithModel: ImageUpscaleWithModel$2,
  ImageYUVToRGB: ImageYUVToRGB$2,
  InpaintModelConditioning: InpaintModelConditioning$2,
  InstructPixToPixConditioning: InstructPixToPixConditioning$2,
  InvertMask: InvertMask$2,
  JoinImageWithAlpha: JoinImageWithAlpha$2,
  KSampler: KSampler$2,
  KSamplerAdvanced: KSamplerAdvanced$2,
  KSamplerSelect: KSamplerSelect$2,
  KarrasScheduler: KarrasScheduler$2,
  KlingCameraControlI2VNode: KlingCameraControlI2VNode$2,
  KlingCameraControlT2VNode: KlingCameraControlT2VNode$2,
  KlingCameraControls: KlingCameraControls$2,
  KlingDualCharacterVideoEffectNode: KlingDualCharacterVideoEffectNode$2,
  KlingImage2VideoNode: KlingImage2VideoNode$2,
  KlingImageGenerationNode: KlingImageGenerationNode$2,
  KlingLipSyncAudioToVideoNode: KlingLipSyncAudioToVideoNode$2,
  KlingLipSyncTextToVideoNode: KlingLipSyncTextToVideoNode$2,
  KlingSingleImageVideoEffectNode: KlingSingleImageVideoEffectNode$2,
  KlingStartEndFrameNode: KlingStartEndFrameNode$2,
  KlingTextToVideoNode: KlingTextToVideoNode$2,
  KlingVideoExtendNode: KlingVideoExtendNode$2,
  KlingVirtualTryOnNode: KlingVirtualTryOnNode$2,
  LTXVAddGuide: LTXVAddGuide$2,
  LTXVConditioning: LTXVConditioning$2,
  LTXVCropGuides: LTXVCropGuides$2,
  LTXVImgToVideo: LTXVImgToVideo$2,
  LTXVPreprocess: LTXVPreprocess$2,
  LTXVScheduler: LTXVScheduler$2,
  LaplaceScheduler: LaplaceScheduler$2,
  LatentAdd: LatentAdd$2,
  LatentApplyOperation: LatentApplyOperation$2,
  LatentApplyOperationCFG: LatentApplyOperationCFG$2,
  LatentBatch: LatentBatch$2,
  LatentBatchSeedBehavior: LatentBatchSeedBehavior$2,
  LatentBlend: LatentBlend$2,
  LatentComposite: LatentComposite$2,
  LatentCompositeMasked: LatentCompositeMasked$2,
  LatentCrop: LatentCrop$2,
  LatentFlip: LatentFlip$2,
  LatentFromBatch: LatentFromBatch$2,
  LatentInterpolate: LatentInterpolate$2,
  LatentMultiply: LatentMultiply$2,
  LatentOperationSharpen: LatentOperationSharpen$2,
  LatentOperationTonemapReinhard: LatentOperationTonemapReinhard$2,
  LatentRotate: LatentRotate$2,
  LatentSubtract: LatentSubtract$2,
  LatentUpscale: LatentUpscale$2,
  LatentUpscaleBy: LatentUpscaleBy$2,
  Load3D: Load3D$2,
  Load3DAnimation: Load3DAnimation$2,
  LoadAudio: LoadAudio$2,
  LoadImage: LoadImage$2,
  LoadImageMask: LoadImageMask$2,
  LoadImageOutput: LoadImageOutput$2,
  LoadLatent: LoadLatent$2,
  LoadVideo: LoadVideo$2,
  LoraLoader: LoraLoader$2,
  LoraLoaderModelOnly: LoraLoaderModelOnly$2,
  LoraSave: LoraSave$2,
  LotusConditioning: LotusConditioning$2,
  LumaConceptsNode: LumaConceptsNode$2,
  LumaImageModifyNode: LumaImageModifyNode$2,
  LumaImageNode: LumaImageNode$2,
  LumaImageToVideoNode: LumaImageToVideoNode$2,
  LumaReferenceNode: LumaReferenceNode$2,
  LumaVideoNode: LumaVideoNode$2,
  Mahiro: Mahiro$2,
  MaskComposite: MaskComposite$2,
  MaskPreview: MaskPreview$2,
  MaskToImage: MaskToImage$2,
  MinimaxImageToVideoNode: MinimaxImageToVideoNode$2,
  MinimaxTextToVideoNode: MinimaxTextToVideoNode$2,
  ModelComputeDtype: ModelComputeDtype$2,
  ModelMergeAdd: ModelMergeAdd$2,
  ModelMergeAuraflow: ModelMergeAuraflow$2,
  ModelMergeBlocks: ModelMergeBlocks$2,
  ModelMergeCosmos14B: ModelMergeCosmos14B$2,
  ModelMergeCosmos7B: ModelMergeCosmos7B$2,
  ModelMergeFlux1: ModelMergeFlux1$2,
  ModelMergeLTXV: ModelMergeLTXV$2,
  ModelMergeMochiPreview: ModelMergeMochiPreview$2,
  ModelMergeSD1: ModelMergeSD1$2,
  ModelMergeSD2: ModelMergeSD2$2,
  ModelMergeSD35_Large: ModelMergeSD35_Large$2,
  ModelMergeSD3_2B: ModelMergeSD3_2B$2,
  ModelMergeSDXL: ModelMergeSDXL$2,
  ModelMergeSimple: ModelMergeSimple$2,
  ModelMergeSubtract: ModelMergeSubtract$2,
  ModelMergeWAN2_1: ModelMergeWAN2_1$2,
  ModelSamplingAuraFlow: ModelSamplingAuraFlow$2,
  ModelSamplingContinuousEDM: ModelSamplingContinuousEDM$2,
  ModelSamplingContinuousV: ModelSamplingContinuousV$2,
  ModelSamplingDiscrete: ModelSamplingDiscrete$2,
  ModelSamplingFlux: ModelSamplingFlux$2,
  ModelSamplingLTXV: ModelSamplingLTXV$2,
  ModelSamplingSD3: ModelSamplingSD3$2,
  ModelSamplingStableCascade: ModelSamplingStableCascade$2,
  ModelSave: ModelSave$2,
  Morphology: Morphology$2,
  OpenAIDalle2: OpenAIDalle2$2,
  OpenAIDalle3: OpenAIDalle3$2,
  OpenAIGPTImage1: OpenAIGPTImage1$2,
  OptimalStepsScheduler: OptimalStepsScheduler$2,
  PairConditioningCombine: PairConditioningCombine$2,
  PairConditioningSetDefaultCombine: PairConditioningSetDefaultCombine$2,
  PairConditioningSetProperties: PairConditioningSetProperties$2,
  PairConditioningSetPropertiesAndCombine: PairConditioningSetPropertiesAndCombine$2,
  PatchModelAddDownscale: PatchModelAddDownscale$2,
  PerpNeg: PerpNeg$2,
  PerpNegGuider: PerpNegGuider$2,
  PerturbedAttentionGuidance: PerturbedAttentionGuidance$2,
  PhotoMakerEncode: PhotoMakerEncode$2,
  PhotoMakerLoader: PhotoMakerLoader$2,
  PikaImageToVideoNode2_2: PikaImageToVideoNode2_2$2,
  PikaScenesV2_2: PikaScenesV2_2$2,
  PikaStartEndFrameNode2_2: PikaStartEndFrameNode2_2$2,
  PikaTextToVideoNode2_2: PikaTextToVideoNode2_2$2,
  Pikadditions: Pikadditions$2,
  Pikaffects: Pikaffects$2,
  Pikaswaps: Pikaswaps$2,
  PixverseImageToVideoNode: PixverseImageToVideoNode$2,
  PixverseTemplateNode: PixverseTemplateNode$2,
  PixverseTextToVideoNode: PixverseTextToVideoNode$2,
  PixverseTransitionVideoNode: PixverseTransitionVideoNode$2,
  PolyexponentialScheduler: PolyexponentialScheduler$2,
  PorterDuffImageComposite: PorterDuffImageComposite$2,
  Preview3D: Preview3D$2,
  Preview3DAnimation: Preview3DAnimation$2,
  PreviewAny: PreviewAny$2,
  PreviewAudio: PreviewAudio$2,
  PreviewImage: PreviewImage$2,
  PrimitiveBoolean: PrimitiveBoolean$2,
  PrimitiveFloat: PrimitiveFloat$2,
  PrimitiveInt: PrimitiveInt$2,
  PrimitiveString: PrimitiveString$2,
  PrimitiveStringMultiline: PrimitiveStringMultiline$2,
  QuadrupleCLIPLoader: QuadrupleCLIPLoader$2,
  RandomNoise: RandomNoise$2,
  RebatchImages: RebatchImages$2,
  RebatchLatents: RebatchLatents$2,
  RecraftColorRGB: RecraftColorRGB$2,
  RecraftControls: RecraftControls$2,
  RecraftCreativeUpscaleNode: RecraftCreativeUpscaleNode$2,
  RecraftCrispUpscaleNode: RecraftCrispUpscaleNode$2,
  RecraftImageInpaintingNode: RecraftImageInpaintingNode$2,
  RecraftImageToImageNode: RecraftImageToImageNode$2,
  RecraftRemoveBackgroundNode: RecraftRemoveBackgroundNode$2,
  RecraftReplaceBackgroundNode: RecraftReplaceBackgroundNode$2,
  RecraftStyleV3DigitalIllustration: RecraftStyleV3DigitalIllustration$2,
  RecraftStyleV3InfiniteStyleLibrary: RecraftStyleV3InfiniteStyleLibrary$2,
  RecraftStyleV3LogoRaster: RecraftStyleV3LogoRaster$2,
  RecraftStyleV3RealisticImage: RecraftStyleV3RealisticImage$2,
  RecraftTextToImageNode: RecraftTextToImageNode$2,
  RecraftTextToVectorNode: RecraftTextToVectorNode$2,
  RecraftVectorizeImageNode: RecraftVectorizeImageNode$2,
  RenormCFG: RenormCFG$2,
  RepeatImageBatch: RepeatImageBatch$2,
  RepeatLatentBatch: RepeatLatentBatch$2,
  RescaleCFG: RescaleCFG$2,
  SDTurboScheduler: SDTurboScheduler$2,
  SD_4XUpscale_Conditioning: SD_4XUpscale_Conditioning$2,
  SV3D_Conditioning: SV3D_Conditioning$2,
  SVD_img2vid_Conditioning: SVD_img2vid_Conditioning$2,
  SamplerCustom: SamplerCustom$2,
  SamplerCustomAdvanced: SamplerCustomAdvanced$2,
  SamplerDPMAdaptative: SamplerDPMAdaptative$2,
  SamplerDPMPP_2M_SDE: SamplerDPMPP_2M_SDE$2,
  SamplerDPMPP_2S_Ancestral: SamplerDPMPP_2S_Ancestral$2,
  SamplerDPMPP_3M_SDE: SamplerDPMPP_3M_SDE$2,
  SamplerDPMPP_SDE: SamplerDPMPP_SDE$2,
  SamplerEulerAncestral: SamplerEulerAncestral$2,
  SamplerEulerAncestralCFGPP: SamplerEulerAncestralCFGPP$2,
  SamplerEulerCFGpp: SamplerEulerCFGpp$2,
  SamplerLCMUpscale: SamplerLCMUpscale$2,
  SamplerLMS: SamplerLMS$2,
  SaveAnimatedPNG: SaveAnimatedPNG$2,
  SaveAnimatedWEBP: SaveAnimatedWEBP$2,
  SaveAudio: SaveAudio$2,
  SaveGLB: SaveGLB$2,
  SaveImage: SaveImage$2,
  SaveImageWebsocket: SaveImageWebsocket$2,
  SaveLatent: SaveLatent$2,
  SaveSVG: SaveSVG$2,
  SaveVideo: SaveVideo$2,
  SaveWEBM: SaveWEBM$2,
  SelfAttentionGuidance: SelfAttentionGuidance$2,
  SetClipHooks: SetClipHooks$2,
  SetFirstSigma: SetFirstSigma$2,
  SetHookKeyframes: SetHookKeyframes$2,
  SetLatentNoiseMask: SetLatentNoiseMask$2,
  SetUnionControlNetType: SetUnionControlNetType$2,
  SkipLayerGuidanceDiT: SkipLayerGuidanceDiT$2,
  SkipLayerGuidanceSD3: SkipLayerGuidanceSD3$2,
  SolidMask: SolidMask$2,
  SplitImageWithAlpha: SplitImageWithAlpha$2,
  SplitSigmas: SplitSigmas$2,
  SplitSigmasDenoise: SplitSigmasDenoise$2,
  StabilityStableImageSD_3_5Node: StabilityStableImageSD_3_5Node$2,
  StabilityStableImageUltraNode: StabilityStableImageUltraNode$2,
  StabilityUpscaleConservativeNode: StabilityUpscaleConservativeNode$2,
  StabilityUpscaleCreativeNode: StabilityUpscaleCreativeNode$2,
  StabilityUpscaleFastNode: StabilityUpscaleFastNode$2,
  StableCascade_EmptyLatentImage: StableCascade_EmptyLatentImage$2,
  StableCascade_StageB_Conditioning: StableCascade_StageB_Conditioning$2,
  StableCascade_StageC_VAEEncode: StableCascade_StageC_VAEEncode$2,
  StableCascade_SuperResolutionControlnet: StableCascade_SuperResolutionControlnet$2,
  StableZero123_Conditioning: StableZero123_Conditioning$2,
  StableZero123_Conditioning_Batched: StableZero123_Conditioning_Batched$2,
  StyleModelApply: StyleModelApply$2,
  StyleModelLoader: StyleModelLoader$2,
  T5TokenizerOptions: T5TokenizerOptions$2,
  TextEncodeHunyuanVideo_ImageToVideo: TextEncodeHunyuanVideo_ImageToVideo$2,
  ThresholdMask: ThresholdMask$2,
  TomePatchModel: TomePatchModel$2,
  TorchCompileModel: TorchCompileModel$2,
  TrimVideoLatent: TrimVideoLatent$2,
  TripleCLIPLoader: TripleCLIPLoader$2,
  UNETLoader: UNETLoader$2,
  UNetCrossAttentionMultiply: UNetCrossAttentionMultiply$2,
  UNetSelfAttentionMultiply: UNetSelfAttentionMultiply$2,
  UNetTemporalAttentionMultiply: UNetTemporalAttentionMultiply$2,
  UpscaleModelLoader: UpscaleModelLoader$2,
  VAEDecode: VAEDecode$2,
  VAEDecodeAudio: VAEDecodeAudio$2,
  VAEDecodeHunyuan3D: VAEDecodeHunyuan3D$2,
  VAEDecodeTiled: VAEDecodeTiled$2,
  VAEEncode: VAEEncode$2,
  VAEEncodeAudio: VAEEncodeAudio$2,
  VAEEncodeForInpaint: VAEEncodeForInpaint$2,
  VAEEncodeTiled: VAEEncodeTiled$2,
  VAELoader: VAELoader$2,
  VAESave: VAESave$2,
  VPScheduler: VPScheduler$2,
  VeoVideoGenerationNode: VeoVideoGenerationNode$2,
  VideoLinearCFGGuidance: VideoLinearCFGGuidance$2,
  VideoTriangleCFGGuidance: VideoTriangleCFGGuidance$2,
  VoxelToMesh: VoxelToMesh$2,
  VoxelToMeshBasic: VoxelToMeshBasic$2,
  WanFirstLastFrameToVideo: WanFirstLastFrameToVideo$2,
  WanFunControlToVideo: WanFunControlToVideo$2,
  WanFunInpaintToVideo: WanFunInpaintToVideo$2,
  WanImageToVideo: WanImageToVideo$2,
  WanVaceToVideo: WanVaceToVideo$2,
  WebcamCapture: WebcamCapture$2,
  unCLIPCheckpointLoader: unCLIPCheckpointLoader$2,
  unCLIPConditioning: unCLIPConditioning$2
};
const Comfy_Canvas_SelectionToolbox$2 = {
  name: "선택 도구 상자 표시"
};
const Comfy_ConfirmClear$2 = {
  name: "워크플로 비우기 시 확인 요구"
};
const Comfy_DOMClippingEnabled$2 = {
  name: "DOM 요소 클리핑 활성화 (활성화 시 성능 저하 가능)"
};
const Comfy_DevMode$2 = {
  name: "개발자 모드 옵션 활성화 (API 저장 등)"
};
const Comfy_DisableFloatRounding$2 = {
  name: "기본 부동 소수점 위젯 반올림 비활성화",
  tooltip: "(페이지 새로 고침 필요) 백엔드에서 노드에 의해 설정된 반올림이 있을 때 반올림을 비활성화할 수 없습니다."
};
const Comfy_DisableSliders$2 = {
  name: "노드 위젯 슬라이더 비활성화"
};
const Comfy_EditAttention_Delta$2 = {
  name: "Ctrl+위/아래 정밀도"
};
const Comfy_EnableTooltips$2 = {
  name: "툴팁 활성화"
};
const Comfy_EnableWorkflowViewRestore$2 = {
  name: "워크플로에서 캔버스 위치 및 확대/축소 수준 저장 및 복원"
};
const Comfy_FloatRoundingPrecision$2 = {
  name: "부동 소수점 위젯 반올림 소수 자리 수 [0 = 자동]",
  tooltip: "(페이지 새로 고침 필요)"
};
const Comfy_Graph_CanvasInfo$2 = {
  name: "왼쪽 하단 모서리에 캔버스 정보 표시 (fps 등)"
};
const Comfy_Graph_CanvasMenu$2 = {
  name: "그래프 캔버스 메뉴 표시"
};
const Comfy_Graph_CtrlShiftZoom$2 = {
  name: "빠른 확대/축소 단축키 활성화 (Ctrl + Shift + 드래그)"
};
const Comfy_Graph_LinkMarkers$2 = {
  name: "링크 중간점 마커",
  options: {
    Arrow: "화살표",
    Circle: "원",
    None: "없음"
  }
};
const Comfy_Graph_ZoomSpeed$2 = {
  name: "캔버스 확대/축소 속도"
};
const Comfy_GroupSelectedNodes_Padding$2 = {
  name: "선택된 노드 패딩"
};
const Comfy_Group_DoubleClickTitleToEdit$2 = {
  name: "그룹 제목을 두 번 클릭하여 편집"
};
const Comfy_LinkRelease_Action$2 = {
  name: "링크 해제 시 동작 (수정자 없음)",
  options: {
    "context menu": "컨텍스트 메뉴",
    "no action": "작업 없음",
    "search box": "검색 상자"
  }
};
const Comfy_LinkRelease_ActionShift$2 = {
  name: "링크 해제 시 동작 (Shift)",
  options: {
    "context menu": "컨텍스트 메뉴",
    "no action": "작업 없음",
    "search box": "검색 상자"
  }
};
const Comfy_LinkRenderMode$2 = {
  name: "링크 렌더 모드",
  options: {
    Hidden: "숨김",
    Linear: "선형",
    Spline: "스플라인",
    Straight: "직선"
  }
};
const Comfy_Load3D_BackgroundColor$2 = {
  name: "초기 배경색",
  tooltip: "3D 장면의 기본 배경색을 설정합니다. 이 설정은 새 3D 위젯이 생성될 때 배경의 모양을 결정하지만, 생성 후 각 위젯별로 개별적으로 조정할 수 있습니다."
};
const Comfy_Load3D_CameraType$2 = {
  name: "카메라 유형",
  options: {
    orthographic: "직교법",
    perspective: "원근법"
  },
  tooltip: "새로운 3D 위젯이 생성될 때 카메라가 기본적으로 원근법 또는 직교법을 사용하는지를 제어합니다. 이 기본값은 생성 후 각 위젯별로 개별적으로 전환할 수 있습니다."
};
const Comfy_Load3D_LightAdjustmentIncrement$2 = {
  name: "조명 조정 증가량",
  tooltip: "3D 장면에서 조명 강도를 조정할 때 증가하는 크기를 제어합니다. 값이 작을수록 조명을 더 세밀하게 조정할 수 있고, 값이 클수록 한 번에 더 눈에 띄는 변화가 발생합니다."
};
const Comfy_Load3D_LightIntensity$2 = {
  name: "초기 조명 강도",
  tooltip: "3D 장면에서 조명의 기본 밝기 수준을 설정합니다. 이 값은 새 3D 위젯이 생성될 때 조명이 오브젝트를 얼마나 강하게 비추는지 결정하지만, 생성 후 각 위젯별로 개별적으로 조정할 수 있습니다."
};
const Comfy_Load3D_LightIntensityMaximum$2 = {
  name: "최대 조명 강도",
  tooltip: "3D 장면에서 허용되는 최대 조명 강도 값을 설정합니다. 이는 모든 3D 위젯에서 조명을 조정할 때 설정할 수 있는 밝기의 상한선을 정의합니다."
};
const Comfy_Load3D_LightIntensityMinimum$2 = {
  name: "최소 광원 세기",
  tooltip: "3D 장면에서 허용되는 최소 광원 세기 값을 설정합니다. 이는 모든 3D 위젯에서 조명을 조정할 때 설정할 수 있는 밝기의 하한을 정의합니다."
};
const Comfy_Load3D_ShowGrid$2 = {
  name: "그리드 표시",
  tooltip: "기본적으로 그리드를 표시하도록 전환"
};
const Comfy_Load3D_ShowPreview$2 = {
  name: "미리보기 표시",
  tooltip: "기본적으로 미리보기를 표시하도록 전환"
};
const Comfy_Locale$2 = {
  name: "언어"
};
const Comfy_MaskEditor_BrushAdjustmentSpeed$2 = {
  name: "브러시 조정 속도 배수",
  tooltip: "조정할 때 브러시 크기와 경도가 얼마나 빨리 변하는지를 제어합니다. 값이 높을수록 변화가 더 빠릅니다."
};
const Comfy_MaskEditor_UseDominantAxis$2 = {
  name: "브러시 조정을 지배 축에 고정",
  tooltip: "활성화하면 브러시 조정이 이동하는 방향에 따라 크기 또는 경도에만 영향을 미칩니다."
};
const Comfy_MaskEditor_UseNewEditor$2 = {
  name: "새 마스크 편집기 사용",
  tooltip: "새 마스크 편집기 인터페이스로 전환"
};
const Comfy_ModelLibrary_AutoLoadAll$2 = {
  name: "모든 모델 폴더 자동 로드",
  tooltip: "참이면 모든 폴더가 모델 라이브러리를 열 때 즉시 로드됩니다 (로드하는 동안 지연이 발생할 수 있습니다). 거짓이면 루트 수준 모델 폴더는 클릭할 때만 로드됩니다."
};
const Comfy_ModelLibrary_NameFormat$2 = {
  name: "모델 라이브러리 트리 뷰에 표시할 이름",
  options: {
    filename: "파일 이름",
    title: "제목"
  },
  tooltip: '"파일 이름"을 선택하면 모델 목록에서 원시 파일 이름(디렉토리 또는 ".safetensors" 확장자 없이)의 단순화된 뷰가 렌더링됩니다. "제목"을 선택하면 구성 가능한 모델 메타데이터 제목이 표시됩니다.'
};
const Comfy_NodeBadge_NodeIdBadgeMode$2 = {
  name: "노드 ID 배지 모드",
  options: {
    None: "없음",
    "Show all": "모두 표시"
  }
};
const Comfy_NodeBadge_NodeLifeCycleBadgeMode$2 = {
  name: "노드 생명 주기 배지 모드",
  options: {
    None: "없음",
    "Show all": "모두 표시"
  }
};
const Comfy_NodeBadge_NodeSourceBadgeMode$2 = {
  name: "노드 출처 배지 모드",
  options: {
    "Hide built-in": "내장 숨기기",
    None: "없음",
    "Show all": "모두 표시"
  }
};
const Comfy_NodeSearchBoxImpl$2 = {
  name: "노드 검색 상자 구현",
  options: {
    "default": "기본",
    "litegraph (legacy)": "litegraph (구버전)"
  }
};
const Comfy_NodeSearchBoxImpl_NodePreview$2 = {
  name: "노드 미리보기",
  tooltip: "기본 구현에만 적용됩니다."
};
const Comfy_NodeSearchBoxImpl_ShowCategory$2 = {
  name: "검색 결과에 노드 카테고리 표시",
  tooltip: "기본 구현에만 적용됩니다."
};
const Comfy_NodeSearchBoxImpl_ShowIdName$2 = {
  name: "검색 결과에 노드 ID 이름 표시",
  tooltip: "기본 구현에만 적용됩니다."
};
const Comfy_NodeSearchBoxImpl_ShowNodeFrequency$2 = {
  name: "검색 결과에 노드 빈도 표시",
  tooltip: "기본 구현에만 적용됩니다."
};
const Comfy_NodeSuggestions_number$2 = {
  name: "노드 제안 수",
  tooltip: "라이트그래프 검색 상자/컨텍스트 메뉴 전용"
};
const Comfy_Node_AllowImageSizeDraw$2 = {
  name: "이미지 미리보기 아래에 너비 × 높이 표시"
};
const Comfy_Node_AutoSnapLinkToSlot$2 = {
  name: "링크를 노드 슬롯에 자동 스냅",
  tooltip: "링크를 노드 위로 드래그할 때 링크가 노드의 유효한 입력 슬롯에 자동으로 스냅됩니다."
};
const Comfy_Node_BypassAllLinksOnDelete$2 = {
  name: "노드 삭제 시 모든 링크 유지",
  tooltip: "노드를 삭제할 때 모든 입력 및 출력 링크를 재연결하려고 시도합니다 (삭제된 노드를 우회)."
};
const Comfy_Node_DoubleClickTitleToEdit$2 = {
  name: "노드 제목을 두 번 클릭하여 편집"
};
const Comfy_Node_MiddleClickRerouteNode$2 = {
  name: "중간 클릭으로 새 경유점 생성"
};
const Comfy_Node_Opacity$2 = {
  name: "노드 불투명도"
};
const Comfy_Node_ShowDeprecated$2 = {
  name: "검색에서 지원 중단된 노드 표시",
  tooltip: "지원 중단된 노드는 기본적으로 UI에서 숨겨지지만, 이를 사용하는 기존 워크플로에서는 여전히 기능합니다."
};
const Comfy_Node_ShowExperimental$2 = {
  name: "검색에서 실험적 노드 표시",
  tooltip: "실험적 노드는 UI에서 그렇게 표시되며, 향후 버전에서 상당한 변경이나 제거의 대상이 될 수 있습니다. 프로덕션 워크플로에서 주의하여 사용하십시오."
};
const Comfy_Node_SnapHighlightsNode$2 = {
  name: "스냅 하이라이트 노드",
  tooltip: "링크를 유효한 입력 슬롯이 있는 노드 위로 드래그할 때 노드를 강조 표시합니다."
};
const Comfy_Pointer_ClickBufferTime$2 = {
  name: "포인터 클릭 드리프트 지연",
  tooltip: "포인터 버튼을 누른 후, 포인터 움직임을 무시할 수 있는 최대 시간(밀리초)입니다.\n\n클릭하는 동안 포인터가 움직여 의도치 않게 객체가 밀리는 것을 방지합니다."
};
const Comfy_Pointer_ClickDrift$2 = {
  name: "포인터 클릭 드리프트 (최대 거리)",
  tooltip: "버튼을 누른 상태에서 포인터가 이 거리보다 더 많이 움직이면, 클릭이 아닌 드래그로 간주됩니다.\n\n클릭하는 동안 포인터가 움직여 의도치 않게 객체가 밀리는 것을 방지합니다."
};
const Comfy_Pointer_DoubleClickTime$2 = {
  name: "더블 클릭 간격 (최대)",
  tooltip: "더블 클릭의 두 클릭 사이의 최대 시간(밀리초)입니다. 이 값을 늘리면 가끔 더블 클릭이 인식되지 않는 문제를 해결할 수 있습니다."
};
const Comfy_PreviewFormat$2 = {
  name: "미리보기 이미지 형식",
  tooltip: "이미지 위젯에서 미리보기를 표시할 때 경량 이미지로 변환합니다. '이미지 포맷;품질' 예: webp, jpeg, webp;50 등."
};
const Comfy_PromptFilename$2 = {
  name: "워크플로 저장 시 파일 이름 프롬프트"
};
const Comfy_QueueButton_BatchCountLimit$2 = {
  name: "배치 수 제한",
  tooltip: "한 번의 버튼 클릭으로 실행 큐에 추가되는 최대 작업 수입니다."
};
const Comfy_Queue_MaxHistoryItems$2 = {
  name: "실행 큐 기록 갯수",
  tooltip: "실행 큐 기록에 표시되는 최대 작업 수입니다."
};
const Comfy_Sidebar_Location$2 = {
  name: "사이드바 위치",
  options: {
    left: "왼쪽",
    right: "오른쪽"
  }
};
const Comfy_Sidebar_Size$2 = {
  name: "사이드바 크기",
  options: {
    normal: "보통",
    small: "작음"
  }
};
const Comfy_Sidebar_UnifiedWidth$2 = {
  name: "통합 사이드바 너비"
};
const Comfy_SnapToGrid_GridSize$2 = {
  name: "그리드 크기에 스냅",
  tooltip: "Shift 키를 누른 상태에서 노드를 드래그하거나 크기를 조절하면 그리드에 맞춰 정렬됩니다. 이 설정은 그리드의 크기를 제어합니다."
};
const Comfy_TextareaWidget_FontSize$2 = {
  name: "텍스트 영역 위젯 글꼴 크기"
};
const Comfy_TextareaWidget_Spellcheck$2 = {
  name: "텍스트 영역 위젯 맞춤법 검사"
};
const Comfy_TreeExplorer_ItemPadding$2 = {
  name: "트리 탐색기 항목 패딩"
};
const Comfy_UseNewMenu$2 = {
  name: "새 메뉴 사용",
  options: {
    Bottom: "하단",
    Disabled: "비활성화",
    Top: "상단"
  }
};
const Comfy_Validation_NodeDefs$2 = {
  name: "노드 정의 유효성 검사 (느림)",
  tooltip: "노드 개발자에게 권장됩니다. 시작 시 모든 노드 정의를 유효성 검사합니다."
};
const Comfy_Validation_Workflows$2 = {
  name: "워크플로 유효성 검사"
};
const Comfy_WidgetControlMode$2 = {
  name: "위젯 제어 모드",
  options: {
    after: "다음",
    before: "이전"
  },
  tooltip: "위젯 값이 업데이트되는 시점을 제어합니다 (무작위화/증가/감소), 프롬프트가 큐에 추가되기 전 또는 후입니다."
};
const Comfy_Window_UnloadConfirmation$2 = {
  name: "창 닫을 때 확인 표시"
};
const Comfy_Workflow_AutoSave$2 = {
  name: "자동 저장",
  options: {
    "after delay": "지연 후",
    off: "끄기"
  }
};
const Comfy_Workflow_AutoSaveDelay$2 = {
  name: "자동 저장 지연 시간 (ms)",
  tooltip: '자동 저장이 "지연 후"로 설정된 경우에만 적용됩니다.'
};
const Comfy_Workflow_ConfirmDelete$2 = {
  name: "워크플로 삭제 시 확인 표시"
};
const Comfy_Workflow_Persist$2 = {
  name: "페이지 (재)로드시 워크플로우 상태를 유지하고 복원"
};
const Comfy_Workflow_ShowMissingModelsWarning$2 = {
  name: "누락된 모델 경고 표시"
};
const Comfy_Workflow_ShowMissingNodesWarning$2 = {
  name: "누락된 노드 경고 표시"
};
const Comfy_Workflow_SortNodeIdOnSave$2 = {
  name: "워크플로 저장 시 노드 ID 정렬"
};
const Comfy_Workflow_WorkflowTabsPosition$2 = {
  name: "열린 워크플로 위치",
  options: {
    Sidebar: "사이드바",
    Topbar: "상단바",
    "Topbar (2nd-row)": "상단바 (2번째 행)"
  }
};
const LiteGraph_Canvas_LowQualityRenderingZoomThreshold$2 = {
  name: "저품질 렌더링 줌 임계값",
  tooltip: "줌 아웃시 저품질 도형 렌더링"
};
const LiteGraph_Canvas_MaximumFps$2 = {
  name: "최대 FPS",
  tooltip: "캔버스가 렌더링할 수 있는 최대 프레임 수입니다. 부드럽게 동작하도록 GPU 사용률을 제한 합니다. 0이면 화면 주사율로 작동 합니다. 기본값: 0"
};
const LiteGraph_ContextMenu_Scaling$2 = {
  name: "확대시 노드 콤보 위젯 메뉴 (목록) 스케일링"
};
const LiteGraph_Node_DefaultPadding$2 = {
  name: "새 노드를 항상 축소",
  tooltip: "노드를 생성할 때 가능한 가장 작은 크기로 크기를 조정합니다. 비활성화하면 새로 추가된 노드가 위젯 값을 표시하기 위해 약간 넓어집니다."
};
const LiteGraph_Node_TooltipDelay$2 = {
  name: "툴팁 지연"
};
const LiteGraph_Pointer_TrackpadGestures$2 = {
  name: "트랙패드 제스처 활성화",
  tooltip: "이 설정을 켜면 캔버스에서 트랙패드 모드를 사용할 수 있으며, 두 손가락으로 확대/축소 및 이동이 가능합니다."
};
const LiteGraph_Reroute_SplineOffset$2 = {
  name: "경유점 스플라인 오프셋",
  tooltip: "경유점 중심에서 베지어 제어점까지의 오프셋"
};
const pysssss_SnapToGrid$2 = {
  name: "항상 그리드에 스냅"
};
const koSettings = {
  "Comfy-Desktop_AutoUpdate": {
    name: "자동 업데이트 확인"
  },
  "Comfy-Desktop_SendStatistics": {
    name: "익명 사용 통계 보내기"
  },
  "Comfy-Desktop_UV_PypiInstallMirror": {
    name: "PyPI 설치 미러",
    tooltip: "기본 pip 설치 미러"
  },
  "Comfy-Desktop_UV_PythonInstallMirror": {
    name: "Python 설치 미러",
    tooltip: "관리되는 Python 설치파일은 Astral python-build-standalone 프로젝트에서 다운로드됩니다. 이 변수는 Python 설치파일의 다른 출처를 사용하기 위해 미러 URL로 설정할 수 있습니다. 예를 들어, 제공된 URL은 https://github.com/astral-sh/python-build-standalone/releases/download/20240713/cpython-3.12.4%2B20240713-aarch64-apple-darwin-install_only.tar.gz에서 https://github.com/astral-sh/python-build-standalone/releases/download 를 대체합니다. 배포판은 file:// URL 스키마를 사용하여 로컬 디렉토리에서 읽을 수 있습니다."
  },
  "Comfy-Desktop_UV_TorchInstallMirror": {
    name: "torch 설치 미러",
    tooltip: "pytorch를 위한 pip 설치 미러"
  },
  "Comfy-Desktop_WindowStyle": {
    name: "창 스타일",
    options: {
      custom: "사용자 정의",
      "default": "기본"
    },
    tooltip: "시스템 제목 표시 줄을 숨기려면 사용자 정의 옵션을 선택하세요"
  },
  Comfy_Canvas_SelectionToolbox: Comfy_Canvas_SelectionToolbox$2,
  Comfy_ConfirmClear: Comfy_ConfirmClear$2,
  Comfy_DOMClippingEnabled: Comfy_DOMClippingEnabled$2,
  Comfy_DevMode: Comfy_DevMode$2,
  Comfy_DisableFloatRounding: Comfy_DisableFloatRounding$2,
  Comfy_DisableSliders: Comfy_DisableSliders$2,
  Comfy_EditAttention_Delta: Comfy_EditAttention_Delta$2,
  Comfy_EnableTooltips: Comfy_EnableTooltips$2,
  Comfy_EnableWorkflowViewRestore: Comfy_EnableWorkflowViewRestore$2,
  Comfy_FloatRoundingPrecision: Comfy_FloatRoundingPrecision$2,
  Comfy_Graph_CanvasInfo: Comfy_Graph_CanvasInfo$2,
  Comfy_Graph_CanvasMenu: Comfy_Graph_CanvasMenu$2,
  Comfy_Graph_CtrlShiftZoom: Comfy_Graph_CtrlShiftZoom$2,
  Comfy_Graph_LinkMarkers: Comfy_Graph_LinkMarkers$2,
  Comfy_Graph_ZoomSpeed: Comfy_Graph_ZoomSpeed$2,
  Comfy_GroupSelectedNodes_Padding: Comfy_GroupSelectedNodes_Padding$2,
  Comfy_Group_DoubleClickTitleToEdit: Comfy_Group_DoubleClickTitleToEdit$2,
  Comfy_LinkRelease_Action: Comfy_LinkRelease_Action$2,
  Comfy_LinkRelease_ActionShift: Comfy_LinkRelease_ActionShift$2,
  Comfy_LinkRenderMode: Comfy_LinkRenderMode$2,
  Comfy_Load3D_BackgroundColor: Comfy_Load3D_BackgroundColor$2,
  Comfy_Load3D_CameraType: Comfy_Load3D_CameraType$2,
  Comfy_Load3D_LightAdjustmentIncrement: Comfy_Load3D_LightAdjustmentIncrement$2,
  Comfy_Load3D_LightIntensity: Comfy_Load3D_LightIntensity$2,
  Comfy_Load3D_LightIntensityMaximum: Comfy_Load3D_LightIntensityMaximum$2,
  Comfy_Load3D_LightIntensityMinimum: Comfy_Load3D_LightIntensityMinimum$2,
  Comfy_Load3D_ShowGrid: Comfy_Load3D_ShowGrid$2,
  Comfy_Load3D_ShowPreview: Comfy_Load3D_ShowPreview$2,
  Comfy_Locale: Comfy_Locale$2,
  Comfy_MaskEditor_BrushAdjustmentSpeed: Comfy_MaskEditor_BrushAdjustmentSpeed$2,
  Comfy_MaskEditor_UseDominantAxis: Comfy_MaskEditor_UseDominantAxis$2,
  Comfy_MaskEditor_UseNewEditor: Comfy_MaskEditor_UseNewEditor$2,
  Comfy_ModelLibrary_AutoLoadAll: Comfy_ModelLibrary_AutoLoadAll$2,
  Comfy_ModelLibrary_NameFormat: Comfy_ModelLibrary_NameFormat$2,
  Comfy_NodeBadge_NodeIdBadgeMode: Comfy_NodeBadge_NodeIdBadgeMode$2,
  Comfy_NodeBadge_NodeLifeCycleBadgeMode: Comfy_NodeBadge_NodeLifeCycleBadgeMode$2,
  Comfy_NodeBadge_NodeSourceBadgeMode: Comfy_NodeBadge_NodeSourceBadgeMode$2,
  Comfy_NodeSearchBoxImpl: Comfy_NodeSearchBoxImpl$2,
  Comfy_NodeSearchBoxImpl_NodePreview: Comfy_NodeSearchBoxImpl_NodePreview$2,
  Comfy_NodeSearchBoxImpl_ShowCategory: Comfy_NodeSearchBoxImpl_ShowCategory$2,
  Comfy_NodeSearchBoxImpl_ShowIdName: Comfy_NodeSearchBoxImpl_ShowIdName$2,
  Comfy_NodeSearchBoxImpl_ShowNodeFrequency: Comfy_NodeSearchBoxImpl_ShowNodeFrequency$2,
  Comfy_NodeSuggestions_number: Comfy_NodeSuggestions_number$2,
  Comfy_Node_AllowImageSizeDraw: Comfy_Node_AllowImageSizeDraw$2,
  Comfy_Node_AutoSnapLinkToSlot: Comfy_Node_AutoSnapLinkToSlot$2,
  Comfy_Node_BypassAllLinksOnDelete: Comfy_Node_BypassAllLinksOnDelete$2,
  Comfy_Node_DoubleClickTitleToEdit: Comfy_Node_DoubleClickTitleToEdit$2,
  Comfy_Node_MiddleClickRerouteNode: Comfy_Node_MiddleClickRerouteNode$2,
  Comfy_Node_Opacity: Comfy_Node_Opacity$2,
  Comfy_Node_ShowDeprecated: Comfy_Node_ShowDeprecated$2,
  Comfy_Node_ShowExperimental: Comfy_Node_ShowExperimental$2,
  Comfy_Node_SnapHighlightsNode: Comfy_Node_SnapHighlightsNode$2,
  Comfy_Pointer_ClickBufferTime: Comfy_Pointer_ClickBufferTime$2,
  Comfy_Pointer_ClickDrift: Comfy_Pointer_ClickDrift$2,
  Comfy_Pointer_DoubleClickTime: Comfy_Pointer_DoubleClickTime$2,
  Comfy_PreviewFormat: Comfy_PreviewFormat$2,
  Comfy_PromptFilename: Comfy_PromptFilename$2,
  Comfy_QueueButton_BatchCountLimit: Comfy_QueueButton_BatchCountLimit$2,
  Comfy_Queue_MaxHistoryItems: Comfy_Queue_MaxHistoryItems$2,
  Comfy_Sidebar_Location: Comfy_Sidebar_Location$2,
  Comfy_Sidebar_Size: Comfy_Sidebar_Size$2,
  Comfy_Sidebar_UnifiedWidth: Comfy_Sidebar_UnifiedWidth$2,
  Comfy_SnapToGrid_GridSize: Comfy_SnapToGrid_GridSize$2,
  Comfy_TextareaWidget_FontSize: Comfy_TextareaWidget_FontSize$2,
  Comfy_TextareaWidget_Spellcheck: Comfy_TextareaWidget_Spellcheck$2,
  Comfy_TreeExplorer_ItemPadding: Comfy_TreeExplorer_ItemPadding$2,
  Comfy_UseNewMenu: Comfy_UseNewMenu$2,
  Comfy_Validation_NodeDefs: Comfy_Validation_NodeDefs$2,
  Comfy_Validation_Workflows: Comfy_Validation_Workflows$2,
  Comfy_WidgetControlMode: Comfy_WidgetControlMode$2,
  Comfy_Window_UnloadConfirmation: Comfy_Window_UnloadConfirmation$2,
  Comfy_Workflow_AutoSave: Comfy_Workflow_AutoSave$2,
  Comfy_Workflow_AutoSaveDelay: Comfy_Workflow_AutoSaveDelay$2,
  Comfy_Workflow_ConfirmDelete: Comfy_Workflow_ConfirmDelete$2,
  Comfy_Workflow_Persist: Comfy_Workflow_Persist$2,
  Comfy_Workflow_ShowMissingModelsWarning: Comfy_Workflow_ShowMissingModelsWarning$2,
  Comfy_Workflow_ShowMissingNodesWarning: Comfy_Workflow_ShowMissingNodesWarning$2,
  Comfy_Workflow_SortNodeIdOnSave: Comfy_Workflow_SortNodeIdOnSave$2,
  Comfy_Workflow_WorkflowTabsPosition: Comfy_Workflow_WorkflowTabsPosition$2,
  LiteGraph_Canvas_LowQualityRenderingZoomThreshold: LiteGraph_Canvas_LowQualityRenderingZoomThreshold$2,
  LiteGraph_Canvas_MaximumFps: LiteGraph_Canvas_MaximumFps$2,
  LiteGraph_ContextMenu_Scaling: LiteGraph_ContextMenu_Scaling$2,
  LiteGraph_Node_DefaultPadding: LiteGraph_Node_DefaultPadding$2,
  LiteGraph_Node_TooltipDelay: LiteGraph_Node_TooltipDelay$2,
  LiteGraph_Pointer_TrackpadGestures: LiteGraph_Pointer_TrackpadGestures$2,
  LiteGraph_Reroute_SplineOffset: LiteGraph_Reroute_SplineOffset$2,
  pysssss_SnapToGrid: pysssss_SnapToGrid$2
};
const Comfy_BrowseTemplates$1 = {
  label: "Просмотр шаблонов"
};
const Comfy_Canvas_DeleteSelectedItems$1 = {
  label: "Удалить выбранные элементы"
};
const Comfy_Canvas_FitView$1 = {
  label: "Подогнать вид к выбранным нодам"
};
const Comfy_Canvas_ResetView$1 = {
  label: "Сбросить вид"
};
const Comfy_Canvas_Resize$1 = {
  label: "Изменить размер выбранных узлов"
};
const Comfy_Canvas_ToggleLinkVisibility$1 = {
  label: "Переключить видимость ссылки"
};
const Comfy_Canvas_ToggleLock$1 = {
  label: "Переключить блокировку холста"
};
const Comfy_Canvas_ToggleSelectedNodes_Bypass$1 = {
  label: "Обход/Необход выбранных нод"
};
const Comfy_Canvas_ToggleSelectedNodes_Collapse$1 = {
  label: "Свернуть/Развернуть выбранные ноды"
};
const Comfy_Canvas_ToggleSelectedNodes_Mute$1 = {
  label: "Отключить/Включить звук выбранных нод"
};
const Comfy_Canvas_ToggleSelectedNodes_Pin$1 = {
  label: "Закрепить/Открепить выбранные ноды"
};
const Comfy_Canvas_ToggleSelected_Pin$1 = {
  label: "Закрепить/Открепить выбранных нод"
};
const Comfy_Canvas_ZoomIn$1 = {
  label: "Увеличить"
};
const Comfy_Canvas_ZoomOut$1 = {
  label: "Уменьшить"
};
const Comfy_ClearPendingTasks$1 = {
  label: "Очистить ожидающие задачи"
};
const Comfy_ClearWorkflow$1 = {
  label: "Очистить рабочий процесс"
};
const Comfy_ContactSupport$1 = {
  label: "Связаться с поддержкой"
};
const Comfy_DuplicateWorkflow$1 = {
  label: "Дублировать текущий рабочий процесс"
};
const Comfy_ExportWorkflow$1 = {
  label: "Экспорт рабочего процесса"
};
const Comfy_ExportWorkflowAPI$1 = {
  label: "Экспорт рабочего процесса (формат API)"
};
const Comfy_Feedback$1 = {
  label: "Обратная связь"
};
const Comfy_Graph_FitGroupToContents$1 = {
  label: "Подогнать группу к содержимому"
};
const Comfy_Graph_GroupSelectedNodes$1 = {
  label: "Группировать выбранные ноды"
};
const Comfy_GroupNode_ConvertSelectedNodesToGroupNode$1 = {
  label: "Преобразовать выбранные ноды в групповую ноду"
};
const Comfy_GroupNode_ManageGroupNodes$1 = {
  label: "Управление групповыми нодами"
};
const Comfy_GroupNode_UngroupSelectedGroupNodes$1 = {
  label: "Разгруппировать выбранные групповые ноды"
};
const Comfy_Help_AboutComfyUI$1 = {
  label: "Открыть «О ComfyUI»"
};
const Comfy_Help_OpenComfyOrgDiscord$1 = {
  label: "Открыть Comfy-Org Discord"
};
const Comfy_Help_OpenComfyUIDocs$1 = {
  label: "Открыть документацию ComfyUI"
};
const Comfy_Help_OpenComfyUIForum$1 = {
  label: "Открыть форум Comfy-Org"
};
const Comfy_Help_OpenComfyUIIssues$1 = {
  label: "Открыть ComfyUI  Issues"
};
const Comfy_Interrupt$1 = {
  label: "Прервать"
};
const Comfy_LoadDefaultWorkflow$1 = {
  label: "Загрузить стандартный рабочий процесс"
};
const Comfy_Manager_CustomNodesManager$1 = {
  label: "Менеджер Пользовательских Узлов"
};
const Comfy_Manager_ToggleManagerProgressDialog$1 = {
  label: "Переключить диалоговое окно прогресса"
};
const Comfy_NewBlankWorkflow$1 = {
  label: "Новый пустой рабочий процесс"
};
const Comfy_OpenClipspace$1 = {
  label: "Клипспейс"
};
const Comfy_OpenWorkflow$1 = {
  label: "Открыть рабочий процесс"
};
const Comfy_QueuePrompt$1 = {
  label: "Очередь запросов"
};
const Comfy_QueuePromptFront$1 = {
  label: "Очередь запросов (передняя)"
};
const Comfy_QueueSelectedOutputNodes$1 = {
  label: "Добавить выбранные выходные узлы в очередь"
};
const Comfy_Redo$1 = {
  label: "Повторить"
};
const Comfy_RefreshNodeDefinitions$1 = {
  label: "Обновить определения нод"
};
const Comfy_SaveWorkflow$1 = {
  label: "Сохранить рабочий процесс"
};
const Comfy_SaveWorkflowAs$1 = {
  label: "Сохранить рабочий процесс как"
};
const Comfy_ShowSettingsDialog$1 = {
  label: "Показать диалог настроек"
};
const Comfy_ToggleTheme$1 = {
  label: "Переключить тему (Тёмная/Светлая)"
};
const Comfy_Undo$1 = {
  label: "Отменить"
};
const Comfy_User_OpenSignInDialog$1 = {
  label: "Открыть окно входа"
};
const Comfy_User_SignOut$1 = {
  label: "Выйти"
};
const Workspace_CloseWorkflow$1 = {
  label: "Закрыть текущий рабочий процесс"
};
const Workspace_NextOpenedWorkflow$1 = {
  label: "Следующий открытый рабочий процесс"
};
const Workspace_PreviousOpenedWorkflow$1 = {
  label: "Предыдущий открытый рабочий процесс"
};
const Workspace_SearchBox_Toggle$1 = {
  label: "Переключить поисковое окно"
};
const Workspace_ToggleBottomPanel$1 = {
  label: "Переключить нижнюю панель"
};
const Workspace_ToggleFocusMode$1 = {
  label: "Переключить режим фокуса"
};
const Workspace_ToggleSidebarTab_queue$1 = {
  label: "Переключить боковую панель очереди",
  tooltip: "Очередь"
};
const Workspace_ToggleSidebarTab_workflows$1 = {
  label: "Переключить боковую панель рабочих процессов",
  tooltip: "Рабочие процессы"
};
const ruCommands = {
  "Comfy-Desktop_CheckForUpdates": {
    label: "Проверить наличие обновлений"
  },
  "Comfy-Desktop_Folders_OpenCustomNodesFolder": {
    label: "Открыть папку пользовательских нод"
  },
  "Comfy-Desktop_Folders_OpenInputsFolder": {
    label: "Открыть папку входных данных"
  },
  "Comfy-Desktop_Folders_OpenLogsFolder": {
    label: "Открыть папку логов"
  },
  "Comfy-Desktop_Folders_OpenModelConfig": {
    label: "Открыть extra_model_paths.yaml"
  },
  "Comfy-Desktop_Folders_OpenModelsFolder": {
    label: "Открыть папку моделей"
  },
  "Comfy-Desktop_Folders_OpenOutputsFolder": {
    label: "Открыть папку результатов"
  },
  "Comfy-Desktop_OpenDevTools": {
    label: "Открыть инструменты разработчика"
  },
  "Comfy-Desktop_OpenUserGuide": {
    label: "Руководство пользователя для рабочего стола"
  },
  "Comfy-Desktop_Quit": {
    label: "Выйти"
  },
  "Comfy-Desktop_Reinstall": {
    label: "Переустановить"
  },
  "Comfy-Desktop_Restart": {
    label: "Перезагрузить"
  },
  Comfy_BrowseTemplates: Comfy_BrowseTemplates$1,
  Comfy_Canvas_DeleteSelectedItems: Comfy_Canvas_DeleteSelectedItems$1,
  Comfy_Canvas_FitView: Comfy_Canvas_FitView$1,
  Comfy_Canvas_ResetView: Comfy_Canvas_ResetView$1,
  Comfy_Canvas_Resize: Comfy_Canvas_Resize$1,
  Comfy_Canvas_ToggleLinkVisibility: Comfy_Canvas_ToggleLinkVisibility$1,
  Comfy_Canvas_ToggleLock: Comfy_Canvas_ToggleLock$1,
  Comfy_Canvas_ToggleSelectedNodes_Bypass: Comfy_Canvas_ToggleSelectedNodes_Bypass$1,
  Comfy_Canvas_ToggleSelectedNodes_Collapse: Comfy_Canvas_ToggleSelectedNodes_Collapse$1,
  Comfy_Canvas_ToggleSelectedNodes_Mute: Comfy_Canvas_ToggleSelectedNodes_Mute$1,
  Comfy_Canvas_ToggleSelectedNodes_Pin: Comfy_Canvas_ToggleSelectedNodes_Pin$1,
  Comfy_Canvas_ToggleSelected_Pin: Comfy_Canvas_ToggleSelected_Pin$1,
  Comfy_Canvas_ZoomIn: Comfy_Canvas_ZoomIn$1,
  Comfy_Canvas_ZoomOut: Comfy_Canvas_ZoomOut$1,
  Comfy_ClearPendingTasks: Comfy_ClearPendingTasks$1,
  Comfy_ClearWorkflow: Comfy_ClearWorkflow$1,
  Comfy_ContactSupport: Comfy_ContactSupport$1,
  Comfy_DuplicateWorkflow: Comfy_DuplicateWorkflow$1,
  Comfy_ExportWorkflow: Comfy_ExportWorkflow$1,
  Comfy_ExportWorkflowAPI: Comfy_ExportWorkflowAPI$1,
  Comfy_Feedback: Comfy_Feedback$1,
  Comfy_Graph_FitGroupToContents: Comfy_Graph_FitGroupToContents$1,
  Comfy_Graph_GroupSelectedNodes: Comfy_Graph_GroupSelectedNodes$1,
  Comfy_GroupNode_ConvertSelectedNodesToGroupNode: Comfy_GroupNode_ConvertSelectedNodesToGroupNode$1,
  Comfy_GroupNode_ManageGroupNodes: Comfy_GroupNode_ManageGroupNodes$1,
  Comfy_GroupNode_UngroupSelectedGroupNodes: Comfy_GroupNode_UngroupSelectedGroupNodes$1,
  Comfy_Help_AboutComfyUI: Comfy_Help_AboutComfyUI$1,
  Comfy_Help_OpenComfyOrgDiscord: Comfy_Help_OpenComfyOrgDiscord$1,
  Comfy_Help_OpenComfyUIDocs: Comfy_Help_OpenComfyUIDocs$1,
  Comfy_Help_OpenComfyUIForum: Comfy_Help_OpenComfyUIForum$1,
  Comfy_Help_OpenComfyUIIssues: Comfy_Help_OpenComfyUIIssues$1,
  Comfy_Interrupt: Comfy_Interrupt$1,
  Comfy_LoadDefaultWorkflow: Comfy_LoadDefaultWorkflow$1,
  Comfy_Manager_CustomNodesManager: Comfy_Manager_CustomNodesManager$1,
  Comfy_Manager_ToggleManagerProgressDialog: Comfy_Manager_ToggleManagerProgressDialog$1,
  Comfy_NewBlankWorkflow: Comfy_NewBlankWorkflow$1,
  Comfy_OpenClipspace: Comfy_OpenClipspace$1,
  Comfy_OpenWorkflow: Comfy_OpenWorkflow$1,
  Comfy_QueuePrompt: Comfy_QueuePrompt$1,
  Comfy_QueuePromptFront: Comfy_QueuePromptFront$1,
  Comfy_QueueSelectedOutputNodes: Comfy_QueueSelectedOutputNodes$1,
  Comfy_Redo: Comfy_Redo$1,
  Comfy_RefreshNodeDefinitions: Comfy_RefreshNodeDefinitions$1,
  Comfy_SaveWorkflow: Comfy_SaveWorkflow$1,
  Comfy_SaveWorkflowAs: Comfy_SaveWorkflowAs$1,
  Comfy_ShowSettingsDialog: Comfy_ShowSettingsDialog$1,
  Comfy_ToggleTheme: Comfy_ToggleTheme$1,
  Comfy_Undo: Comfy_Undo$1,
  Comfy_User_OpenSignInDialog: Comfy_User_OpenSignInDialog$1,
  Comfy_User_SignOut: Comfy_User_SignOut$1,
  Workspace_CloseWorkflow: Workspace_CloseWorkflow$1,
  Workspace_NextOpenedWorkflow: Workspace_NextOpenedWorkflow$1,
  Workspace_PreviousOpenedWorkflow: Workspace_PreviousOpenedWorkflow$1,
  Workspace_SearchBox_Toggle: Workspace_SearchBox_Toggle$1,
  Workspace_ToggleBottomPanel: Workspace_ToggleBottomPanel$1,
  "Workspace_ToggleBottomPanelTab_command-terminal": {
    label: "Переключить нижнюю панель терминала"
  },
  "Workspace_ToggleBottomPanelTab_logs-terminal": {
    label: "Переключить нижнюю панель логов"
  },
  Workspace_ToggleFocusMode: Workspace_ToggleFocusMode$1,
  "Workspace_ToggleSidebarTab_model-library": {
    label: "Переключить боковую панель библиотеки моделей",
    tooltip: "Библиотека моделей"
  },
  "Workspace_ToggleSidebarTab_node-library": {
    label: "Переключить боковую панель библиотеки нод",
    tooltip: "Библиотека нод"
  },
  Workspace_ToggleSidebarTab_queue: Workspace_ToggleSidebarTab_queue$1,
  Workspace_ToggleSidebarTab_workflows: Workspace_ToggleSidebarTab_workflows$1
};
const apiNodesCostBreakdown$1 = {
  costPerRun: "Стоимость за запуск",
  title: "API Node(s)",
  totalCost: "Общая стоимость"
};
const apiNodesNews$1 = {
  introducing: "Представляем",
  steps: {
    step1: {
      subtitle: "Настройки > Пользователь > Войти",
      title: "Войти/Создать аккаунт:"
    },
    step2: {
      subtitle: "Настройки > Кредиты > Купить кредиты",
      title: "Купить кредиты:"
    },
    step3: {
      title: "Найдите новые API-узлы в разделе 'API Node' и добавьте их на холст"
    },
    step4: {
      title: "Запустить!"
    }
  },
  subtitle: "Все внешние модели теперь доступны в ComfyUI"
};
const apiNodesSignInDialog$1 = {
  message: "Этот рабочий процесс содержит API Nodes, которые требуют входа в вашу учетную запись для выполнения.",
  title: "Требуется вход для использования API Nodes"
};
const auth$1 = {
  apiKey: {
    cleared: "API-ключ удалён",
    clearedDetail: "Ваш API-ключ был успешно удалён",
    description: "Используйте ваш Comfy API-ключ для активации API-узлов",
    error: "Недействительный API-ключ",
    generateKey: "Получить здесь",
    helpText: "Нужен API-ключ?",
    invalid: "Недействительный API-ключ",
    invalidDetail: "Пожалуйста, введите действительный API-ключ",
    label: "API-ключ",
    placeholder: "Введите ваш API-ключ",
    storageFailed: "Не удалось сохранить API-ключ",
    storageFailedDetail: "Пожалуйста, попробуйте еще раз.",
    stored: "API-ключ сохранён",
    storedDetail: "Ваш API-ключ был успешно сохранён",
    title: "API-ключ",
    whitelistInfo: "О не включённых в белый список сайтах"
  },
  login: {
    andText: "и",
    confirmPasswordLabel: "Подтвердите пароль",
    confirmPasswordPlaceholder: "Введите тот же пароль еще раз",
    emailLabel: "Электронная почта",
    emailPlaceholder: "Введите вашу электронную почту",
    failed: "Вход не удался",
    forgotPassword: "Забыли пароль?",
    forgotPasswordError: "Не удалось отправить письмо для сброса пароля",
    insecureContextWarning: "Это соединение небезопасно (HTTP) — ваши учетные данные могут быть перехвачены злоумышленниками, если вы продолжите вход.",
    loginButton: "Войти",
    loginWithGithub: "Войти через Github",
    loginWithGoogle: "Войти через Google",
    newUser: "Вы здесь впервые?",
    noAssociatedUser: "С предоставленным API-ключом не связан ни один пользователь Comfy",
    orContinueWith: "Или продолжить с",
    passwordLabel: "Пароль",
    passwordPlaceholder: "Введите ваш пароль",
    passwordResetSent: "Письмо для сброса пароля отправлено",
    passwordResetSentDetail: "Пожалуйста, проверьте свою электронную почту для получения ссылки на сброс пароля.",
    privacyLink: "Политикой конфиденциальности",
    questionsContactPrefix: "Вопросы? Свяжитесь с нами по адресу",
    signInOrSignUp: "Войти / Зарегистрироваться",
    signUp: "Зарегистрироваться",
    success: "Вход выполнен успешно",
    termsLink: "Условиями использования",
    termsText: 'Нажимая "Далее" или "Зарегистрироваться", вы соглашаетесь с нашими',
    title: "Войдите в свой аккаунт",
    useApiKey: "Comfy API-ключ",
    userAvatar: "Аватар пользователя"
  },
  passwordUpdate: {
    success: "Пароль обновлён",
    successDetail: "Ваш пароль был успешно обновлён"
  },
  signOut: {
    signOut: "Выйти",
    success: "Вы успешно вышли из системы",
    successDetail: "Вы вышли из своей учетной записи."
  },
  signup: {
    alreadyHaveAccount: "Уже есть аккаунт?",
    emailLabel: "Электронная почта",
    emailPlaceholder: "Введите вашу электронную почту",
    passwordLabel: "Пароль",
    passwordPlaceholder: "Введите новый пароль",
    personalDataConsentLabel: "Я согласен на обработку моих персональных данных.",
    regionRestrictionChina: "В соответствии с местными нормативными требованиями наши услуги в настоящее время недоступны для пользователей, находящихся в материковом Китае.",
    signIn: "Войти",
    signUpButton: "Зарегистрироваться",
    signUpWithGithub: "Зарегистрироваться через Github",
    signUpWithGoogle: "Зарегистрироваться через Google",
    title: "Создать аккаунт"
  }
};
const clipboard$1 = {
  errorMessage: "Не удалось скопировать в буфер обмена",
  errorNotSupported: "API буфера обмена не поддерживается в вашем браузере",
  successMessage: "Скопировано в буфер обмена"
};
const color$1 = {
  black: "Черный",
  blue: "Синий",
  brown: "Коричневый",
  custom: "Пользовательский",
  cyan: "Голубой",
  "default": "По умолчанию",
  green: "Зелёный",
  noColor: "Без цвета",
  pale_blue: "Бледно-синий",
  pink: "Розовый",
  purple: "Фиолетовый",
  red: "Красный",
  yellow: "Жёлтый"
};
const contextMenu$1 = {
  "Add Group": "Добавить группу",
  "Add Group For Selected Nodes": "Добавить группу для выбранных узлов",
  "Add Node": "Добавить узел",
  Bypass: "Обход",
  Clone: "Клонировать",
  Collapse: "Свернуть",
  Colors: "Цвета",
  "Convert to Group Node": "Преобразовать в групповой узел",
  "Copy (Clipspace)": "Копировать (Clipspace)",
  Expand: "Развернуть",
  Inputs: "Входы",
  Manage: "Управлять",
  "Manage Group Nodes": "Управление групповыми узлами",
  Mode: "Режим",
  "Node Templates": "Шаблоны узлов",
  Outputs: "Выходы",
  Pin: "Закрепить",
  Properties: "Свойства",
  "Properties Panel": "Панель свойств",
  Remove: "Удалить",
  Resize: "Изменить размер",
  "Save Selected as Template": "Сохранить выбранное как шаблон",
  Search: "Поиск",
  Shapes: "Формы",
  Title: "Заголовок",
  Unpin: "Открепить"
};
const credits$1 = {
  apiPricing: "Цены на API",
  credits: "Кредиты",
  faqs: "Часто задаваемые вопросы",
  invoiceHistory: "История счетов",
  lastUpdated: "Последнее обновление",
  messageSupport: "Связаться с поддержкой",
  purchaseCredits: "Купить кредиты",
  topUp: {
    buyNow: "Купить сейчас",
    insufficientMessage: "У вас недостаточно кредитов для запуска этого рабочего процесса.",
    insufficientTitle: "Недостаточно кредитов",
    maxAmount: "(Макс. $1,000 USD)",
    quickPurchase: "Быстрая покупка",
    seeDetails: "Смотреть детали",
    topUp: "Пополнить"
  },
  yourCreditBalance: "Ваш баланс кредитов"
};
const dataTypes$1 = {
  "*": "*",
  AUDIO: "АУДИО",
  BOOLEAN: "БУЛЕВО",
  CAMERA_CONTROL: "УПРАВЛЕНИЕ_КАМЕРОЙ",
  CLIP: "CLIP",
  CLIP_VISION: "CLIP_VISION",
  CLIP_VISION_OUTPUT: "CLIP_VISION_OUTPUT",
  COMBO: "КОМБО",
  CONDITIONING: "КОНДИЦИОНИРОВАНИЕ",
  CONTROL_NET: "CONTROL_NET",
  FLOAT: "ПЛАВАЮЩИЙ",
  FLOATS: "ПЛАВАЮЩИЕ",
  GLIGEN: "GLIGEN",
  GUIDER: "ГИД",
  HOOKS: "ХУКИ",
  HOOK_KEYFRAMES: "КЛЮЧЕВЫЕ_КАДРЫ_ХУКА",
  IMAGE: "ИЗОБРАЖЕНИЕ",
  INT: "ЦЕЛОЕ",
  LATENT: "ЛАТЕНТНЫЙ",
  LATENT_OPERATION: "ЛАТЕНТНАЯ_ОПЕРАЦИЯ",
  LOAD3D_CAMERA: "ЗАГРУЗИТЬ3D_КАМЕРУ",
  LOAD_3D: "ЗАГРУЗИТЬ_3D",
  LOAD_3D_ANIMATION: "ЗАГРУЗИТЬ_3D_АНИМАЦИЮ",
  LUMA_CONCEPTS: "LUMA_CONCEPTS",
  LUMA_REF: "LUMA_REF",
  MASK: "МАСКА",
  MESH: "СЕТКА",
  MODEL: "МОДЕЛЬ",
  NOISE: "ШУМ",
  PHOTOMAKER: "PHOTOMAKER",
  PIXVERSE_TEMPLATE: "ШАБЛОН_PIXVERSE",
  RECRAFT_COLOR: "RECRAFT_ЦВЕТ",
  RECRAFT_CONTROLS: "RECRAFT_УПРАВЛЕНИЯ",
  RECRAFT_V3_STYLE: "RECRAFT_V3_СТИЛЬ",
  SAMPLER: "СЭМПЛЕР",
  SIGMAS: "СИГМЫ",
  STRING: "СТРОКА",
  STYLE_MODEL: "МОДЕЛЬ_СТИЛЯ",
  SVG: "SVG",
  TIMESTEPS_RANGE: "ДИАПАЗОН_ВРЕМЕННЫХ_ШАГОВ",
  UPSCALE_MODEL: "МОДЕЛЬ_АПСКЕЙЛА",
  VAE: "VAE",
  VIDEO: "ВИДЕО",
  VOXEL: "ВОКСЕЛ",
  WEBCAM: "ВЕБ-КАМЕРА"
};
const desktopMenu$1 = {
  confirmQuit: "Открыты несохраненные рабочие процессы; все несохраненные изменения будут потеряны. Проигнорировать это и выйти?",
  confirmReinstall: "Это очистит ваш файл extra_models_config.yaml и начнёт установку заново. Вы уверены?",
  quit: "Выйти",
  reinstall: "Переустановить"
};
const desktopUpdate$1 = {
  description: "ComfyUI Desktop устанавливает новые зависимости. Это может занять несколько минут.",
  errorCheckingUpdate: "Ошибка при проверке обновлений",
  errorInstallingUpdate: "Ошибка при установке обновления",
  noUpdateFound: "Обновлений не найдено",
  terminalDefaultMessage: "Любой вывод консоли из обновления будет отображаться здесь.",
  title: "Обновление ComfyUI Desktop",
  updateAvailableMessage: "Доступно обновление. Вы хотите перезагрузить и обновить сейчас?",
  updateFoundTitle: "Найдено обновление (v{version})"
};
const downloadGit$1 = {
  gitWebsite: "Скачать git",
  instructions: "Пожалуйста, скачайте и установите последнюю версию для вашей операционной системы. Кнопка «Скачать git» ниже открывает страницу загрузок git-scm.com.",
  message: "Не удалось найти git. Рабочая копия git необходима для нормальной работы.",
  skip: "Пропустить",
  title: "Скачать git",
  warning: "Если вы уверены, что вам не нужно устанавливать git, или произошла ошибка, вы можете нажать «Пропустить», чтобы обойти эту проверку. Попытка запустить ComfyUI без рабочей копии git в настоящее время не поддерживается."
};
const electronFileDownload$1 = {
  cancel: "Отменить загрузку",
  cancelled: "Отменено",
  inProgress: "В процессе",
  pause: "Приостановить загрузку",
  paused: "Приостановлено",
  resume: "Возобновить загрузку"
};
const errorDialog$1 = {
  defaultTitle: "Произошла ошибка",
  extensionFileHint: "Это может быть связано со следующим скриптом",
  loadWorkflowTitle: "Загрузка прервана из-за ошибки при перезагрузке данных рабочего процесса",
  noStackTrace: "Стек вызовов недоступен",
  promptExecutionError: "Ошибка выполнения запроса"
};
const g$1 = {
  about: "О программе",
  add: "Добавить",
  all: "Все",
  amount: "Количество",
  apply: "Применить",
  back: "Назад",
  cancel: "Отмена",
  capture: "захват",
  category: "Категория",
  choose_file_to_upload: "выберите файл для загрузки",
  close: "Закрыть",
  color: "Цвет",
  comingSoon: "Скоро будет",
  command: "Команда",
  community: "Сообщество",
  completed: "Завершено",
  confirm: "Подтвердить",
  confirmed: "Подтверждено",
  "continue": "Продолжить",
  control_after_generate: "управление после генерации",
  control_before_generate: "управление до генерации",
  copyToClipboard: "Скопировать в буфер обмена",
  currentUser: "Текущий пользователь",
  customize: "Настроить",
  customizeFolder: "Настроить папку",
  "delete": "Удалить",
  deprecated: "Устарело",
  description: "Описание",
  devices: "Устройства",
  disableAll: "Отключить все",
  disabling: "Отключение",
  download: "Скачать",
  empty: "Пусто",
  enableAll: "Включить все",
  enabled: "Включено",
  enabling: "Включение",
  error: "Ошибка",
  experimental: "БЕТА",
  "export": "Экспорт",
  extensionName: "Название расширения",
  feedback: "Обратная связь",
  filter: "Фильтр",
  findIssues: "Найти проблемы",
  firstTimeUIMessage: 'Вы впервые используете новый интерфейс. Выберите "Меню > Использовать новое меню > Отключено", чтобы восстановить старый интерфейс.',
  goToNode: "Перейти к ноде",
  icon: "Иконка",
  imageFailedToLoad: "Не удалось загрузить изображение",
  "import": "Импорт",
  inProgress: "В процессе",
  insert: "Вставить",
  install: "Установить",
  installed: "Установлено",
  installing: "Установка",
  interrupted: "Прервано",
  keybinding: "Привязка клавиш",
  learnMore: "Узнать больше",
  loadAllFolders: "Загрузить все папки",
  loadWorkflow: "Загрузить рабочий процесс",
  loading: "Загрузка",
  login: "Вход",
  logs: "Логи",
  migrate: "Мигрировать",
  missing: "Отсутствует",
  name: "Имя",
  newFolder: "Новая папка",
  next: "Далее",
  no: "Нет",
  noResultsFound: "Результатов не найдено",
  noTasksFound: "Задачи не найдены",
  noTasksFoundMessage: "В очереди нет задач.",
  noWorkflowsFound: "Рабочие процессы не найдены.",
  nodes: "Узлы",
  ok: "ОК",
  openNewIssue: "Открыть новую проблему",
  overwrite: "Перезаписать",
  reconnected: "Переподключено",
  reconnecting: "Переподключение",
  refresh: "Обновить",
  reloadToApplyChanges: "Перезагрузите, чтобы применить изменения",
  rename: "Переименовать",
  reportIssue: "Отправить отчёт",
  reportIssueTooltip: "Отправить отчёт об ошибке в Comfy Org",
  reportSent: "Отчёт отправлен",
  reset: "Сброс",
  resetAll: "Сбросить все",
  resetAllKeybindingsTooltip: "Сбросить все сочетания клавиш по умолчанию",
  restart: "Перезапустить",
  resultsCount: "Найдено {count} результатов",
  save: "Сохранить",
  saving: "Сохранение",
  searchExtensions: "Поиск расширений",
  searchFailedMessage: "Мы не смогли найти настройки, соответствующие вашему запросу. Попробуйте изменить поисковые термины.",
  searchKeybindings: "Поиск сочетаний клавиш",
  searchModels: "Поиск моделей",
  searchNodes: "Поиск нод",
  searchSettings: "Поиск настроек",
  searchWorkflows: "Поиск рабочих процессов",
  settings: "Настройки",
  showReport: "Показать отчёт",
  sort: "Сортировать",
  source: "Источник",
  status: "Статус",
  success: "Успех",
  systemInfo: "Информация о системе",
  terminal: "Терминал",
  title: "Заголовок",
  unknownError: "Неизвестная ошибка",
  update: "Обновить",
  updateAvailable: "Доступно обновление",
  updated: "Обновлено",
  updating: "Обновление",
  upload: "Загрузить",
  user: "Пользователь",
  videoFailedToLoad: "Не удалось загрузить видео",
  workflow: "Рабочий процесс"
};
const graphCanvasMenu$1 = {
  fitView: "Подгонять под выделенные",
  panMode: "Режим панорамирования",
  resetView: "Сбросить вид",
  selectMode: "Выбрать режим",
  toggleLinkVisibility: "Переключить видимость ссылок",
  zoomIn: "Увеличить",
  zoomOut: "Уменьшить"
};
const groupNode$1 = {
  create: "Создать ноду группы",
  enterName: "Введите название"
};
const icon$1 = {
  bookmark: "Закладка",
  box: "Коробка",
  briefcase: "Портфель",
  "exclamation-triangle": "Предупреждение",
  file: "Файл",
  folder: "Папка",
  heart: "Сердце",
  inbox: "Входящие",
  star: "Звезда"
};
const install$1 = {
  appDataLocationTooltip: "Директория данных приложения ComfyUI. Хранит:\n- Логи\n- Конфигурации сервера",
  appPathLocationTooltip: "Директория активов приложения ComfyUI. Хранит код и активы ComfyUI",
  cannotWrite: "Невозможно записать в выбранный путь",
  chooseInstallationLocation: "Выберите место установки",
  customNodes: "Пользовательские ноды",
  customNodesDescription: "Переустановите пользовательские ноды из существующих установок ComfyUI.",
  desktopAppSettings: "Настройки десктопного приложения",
  desktopAppSettingsDescription: "Настройте, как ComfyUI ведёт себя на вашем рабочем столе. Вы можете изменить эти настройки позже.",
  desktopSettings: "Настройки рабочего стола",
  failedToSelectDirectory: "Не удалось выбрать директорию",
  gpu: "GPU",
  gpuSelection: {
    cpuMode: "Режим CPU",
    cpuModeDescription: "Режим CPU предназначен только для разработчиков и крайне редких случаев.",
    cpuModeDescription2: "Если вы не полностью уверены, что вам это нужно, пожалуйста, проигнорируйте эту галочку и выберите ваш GPU выше.",
    customComfyNeedsPython: "ComfyUI не будет работать, пока python не будет настроен",
    customInstallRequirements: "Установите все требования и зависимости (например, custom torch)",
    customManualVenv: "Вручную настроить python venv",
    customMayNotWork: "Это полностью не поддерживается и может просто не работать",
    customSkipsPython: "Этот вариант пропускает обычную настройку python.",
    enableCpuMode: "Включить режим CPU",
    mpsDescription: "Поддерживаются Apple Metal Performance Shaders с использованием pytorch nightly.",
    nvidiaDescription: "Устройства NVIDIA напрямую поддерживаются с использованием сборок pytorch CUDA.",
    selectGpu: "Выберите GPU",
    selectGpuDescription: "Выберите тип GPU, который у вас есть"
  },
  helpImprove: "Пожалуйста, помогите улучшить ComfyUI",
  installLocation: "Место установки",
  installLocationDescription: "Выберите директорию для пользовательских данных ComfyUI. В выбранном месте будет установлена среда Python. Пожалуйста, убедитесь, что на выбранном диске достаточно места (~15 ГБ).",
  installLocationTooltip: "Директория пользовательских данных ComfyUI. Хранит:\n- Среда Python\n- Модели\n- Пользовательские ноды\n",
  insufficientFreeSpace: "Недостаточно места — минимально необходимое свободное место",
  isOneDrive: "Установка в OneDrive может вызвать проблемы. Настоятельно рекомендуем устанавливать в месте, не связанном с OneDrive.",
  manualConfiguration: {
    createVenv: "Вам потребуется создать виртуальное окружение в следующем каталоге",
    requirements: "Требования",
    restartWhenFinished: "После завершения настройки виртуального окружения, пожалуйста, перезапустите ComfyUI.",
    title: "Ручная Конфигурация",
    virtualEnvironmentPath: "Путь виртуального окружения"
  },
  metricsDisabled: "Метрики отключены",
  metricsEnabled: "Метрики включены",
  migrateFromExistingInstallation: "Миграция из существующей установки",
  migration: "Миграция",
  migrationOptional: "Миграция является необязательной. Если у вас нет существующей установки, вы можете пропустить этот шаг.",
  migrationSourcePathDescription: "Если у вас уже есть установленный ComfyUI, мы можем скопировать/связать ваши существующие пользовательские файлы и модели с новой установкой. Ваша существующая установка ComfyUI не будет затронута.",
  moreInfo: "Для получения дополнительной информации, пожалуйста, прочтите нашу",
  nonDefaultDrive: "Пожалуйста, установите ComfyUI на системный диск (например, C:\\). Диски с другими файловыми системами могут вызвать непредсказуемые проблемы. Модели и другие файлы можно хранить на других дисках после установки.",
  parentMissing: "Путь не существует — сначала создайте родительский каталог",
  pathExists: "Директория уже существует — пожалуйста, убедитесь, что вы сделали резервное копирование всех данных",
  pathValidationFailed: "Не удалось проверить путь",
  privacyPolicy: "политику конфиденциальности",
  selectItemsToMigrate: "Выберите элементы для миграции",
  settings: {
    allowMetrics: "Метрики использования",
    allowMetricsDescription: "Помогите улучшить ComfyUI, отправляя анонимные метрики использования. Личная информация или содержание рабочего процесса не будут собираться.",
    autoUpdate: "Автоматические обновления",
    autoUpdateDescription: "Автоматически загружать и устанавливать обновления, когда они становятся доступными. Вы всегда будете уведомлены перед установкой обновлений.",
    checkingMirrors: "Проверка доступа к зеркалам python по сети...",
    dataCollectionDialog: {
      collect: {
        errorReports: "Сообщение об ошибке и трассировка стека",
        systemInfo: "Аппаратное обеспечение, тип ОС и версия приложения",
        userJourneyEvents: "События пользовательского пути"
      },
      doNotCollect: {
        customNodeConfigurations: "Пользовательские конфигурации нод",
        fileSystemInformation: "Информация о файловой системе",
        personalInformation: "Личная информация",
        workflowContents: "Содержание рабочего процесса"
      },
      title: "О сборе данных",
      viewFullPolicy: "Просмотреть политику полностью",
      whatWeCollect: "Что мы собираем:",
      whatWeDoNotCollect: "Что мы не собираем:"
    },
    errorUpdatingConsent: "Ошибка обновления согласия",
    errorUpdatingConsentDetail: "Не удалось обновить настройки согласия на метрики",
    learnMoreAboutData: "Узнать больше о сборе данных",
    mirrorSettings: "Настройки зеркала",
    mirrorsReachable: "Сетевой доступ к зеркалам python хороший",
    mirrorsUnreachable: "Сетевой доступ к некоторым зеркалам python плохой",
    pypiMirrorPlaceholder: "Введите URL-зеркало PyPI",
    pythonMirrorPlaceholder: "Введите URL-зеркало Python"
  },
  systemLocations: "Системные места",
  unhandledError: "Неизвестная ошибка",
  updateConsent: "Вы ранее согласились на отчётность об ошибках. Теперь мы отслеживаем метрики событий, чтобы помочь выявить ошибки и улучшить приложение. Личная идентифицируемая информация не собирается."
};
const issueReport$1 = {
  contactFollowUp: "Свяжитесь со мной для уточнения",
  contactSupportDescription: "Пожалуйста, заполните форму ниже для отправки вашего отчёта",
  contactSupportTitle: "Связаться с поддержкой",
  describeTheProblem: "Опишите проблему",
  email: "Электронная почта",
  feedbackTitle: "Помогите нам улучшить ComfyUI, оставив отзыв",
  helpFix: "Помочь исправить это",
  helpTypes: {
    billingPayments: "Оплата / Платежи",
    bugReport: "Сообщить об ошибке",
    giveFeedback: "Оставить отзыв",
    loginAccessIssues: "Проблемы со входом / доступом",
    somethingElse: "Другое"
  },
  notifyResolve: "Уведомить меня, когда проблема будет решена",
  provideAdditionalDetails: "Предоставьте дополнительные сведения (необязательно)",
  provideEmail: "Укажите вашу электронную почту (необязательно)",
  rating: "Рейтинг",
  selectIssue: "Выберите проблему",
  stackTrace: "Трассировка стека",
  submitErrorReport: "Отправить отчёт об ошибке (необязательно)",
  systemStats: "Статистика системы",
  validation: {
    invalidEmail: "Пожалуйста, введите действительный адрес электронной почты",
    maxLength: "Сообщение слишком длинное",
    selectIssueType: "Пожалуйста, выберите тип проблемы"
  },
  whatCanWeInclude: "Уточните, что включить в отчёт",
  whatDoYouNeedHelpWith: "С чем вам нужна помощь?"
};
const load3d$1 = {
  applyingTexture: "Применение текстуры...",
  backgroundColor: "Цвет фона",
  camera: "Камера",
  clearRecording: "Очистить запись",
  edgeThreshold: "Пороговое значение края",
  "export": "Экспорт",
  exportModel: "Экспорт модели",
  exportRecording: "Экспортировать запись",
  exportingModel: "Экспорт модели...",
  fov: "Угол обзора",
  light: "Свет",
  lightIntensity: "Интенсивность света",
  loadingModel: "Загрузка 3D модели...",
  materialMode: "Режим Материала",
  materialModes: {
    depth: "Глубина",
    lineart: "Лайнарт",
    normal: "Нормальный",
    original: "Оригинал",
    wireframe: "Каркас"
  },
  model: "Модель",
  previewOutput: "Предварительный просмотр",
  removeBackgroundImage: "Удалить фоновое изображение",
  resizeNodeMatchOutput: "Изменить размер узла под вывод",
  scene: "Сцена",
  showGrid: "Показать сетку",
  startRecording: "Начать запись",
  stopRecording: "Остановить запись",
  switchCamera: "Переключить камеру",
  switchingMaterialMode: "Переключение режима материала...",
  upDirection: "Направление Вверх",
  uploadBackgroundImage: "Загрузить фоновое изображение",
  uploadTexture: "Загрузить текстуру"
};
const maintenance$1 = {
  None: "Нет",
  OK: "OK",
  Skipped: "Пропущено",
  allOk: "Проблем не обнаружено.",
  confirmTitle: "Вы уверены?",
  consoleLogs: "Консольные журналы",
  detected: "Обнаружено",
  error: {
    cannotContinue: "Невозможно продолжить - остались ошибки",
    defaultDescription: "Произошла ошибка при выполнении задачи по обслуживанию.",
    taskFailed: "Не удалось выполнить задачу.",
    toastTitle: "Ошибка задачи"
  },
  refreshing: "Обновление",
  showManual: "Показать задачи по обслуживанию",
  status: "Статус",
  terminalDefaultMessage: "Когда вы запускаете команду для устранения неполадок, любой вывод будет отображаться здесь.",
  title: "Обслуживание"
};
const manager$1 = {
  changingVersion: "Изменение версии с {from} на {to}",
  createdBy: "Создано",
  dependencies: "Зависимости",
  discoverCommunityContent: "Откройте для себя пакеты узлов, расширения и многое другое, созданные сообществом...",
  downloads: "Загрузки",
  errorConnecting: "Ошибка подключения к реестру Comfy Node.",
  failed: "Не удалось ({count})",
  filter: {
    disabled: "Отключено",
    enabled: "Включено",
    nodePack: "Пакет Узлов"
  },
  inWorkflow: "В рабочем процессе",
  infoPanelEmpty: "Нажмите на элемент, чтобы увидеть информацию",
  installSelected: "Установить выбранное",
  installationQueue: "Очередь установки",
  lastUpdated: "Последнее обновление",
  latestVersion: "Последняя",
  license: "Лицензия",
  loadingVersions: "Загрузка версий...",
  nightlyVersion: "Ночная",
  noDescription: "Описание отсутствует",
  noNodesFound: "Узлы не найдены",
  noNodesFoundDescription: "Узлы пакета не могут быть проанализированы, или пакет является только расширением интерфейса и не имеет узлов.",
  noResultsFound: "По вашему запросу ничего не найдено.",
  nodePack: "Пакет Узлов",
  packsSelected: "Выбрано пакетов",
  repository: "Репозиторий",
  restartToApplyChanges: "Чтобы применить изменения, пожалуйста, перезапустите ComfyUI",
  searchPlaceholder: "Поиск",
  selectVersion: "Выберите версию",
  sort: {
    created: "Новейшие",
    downloads: "Самые популярные",
    publisher: "Издатель",
    updated: "Недавно обновленные"
  },
  status: {
    active: "Активный",
    banned: "Заблокировано",
    deleted: "Удалено",
    flagged: "Отмечено",
    pending: "В ожидании",
    unknown: "Неизвестно"
  },
  title: "Менеджер Пользовательских Узлов",
  totalNodes: "Всего Узлов",
  tryAgainLater: "Пожалуйста, попробуйте позже.",
  tryDifferentSearch: "Пожалуйста, попробуйте изменить запрос.",
  uninstall: "Удалить",
  uninstallSelected: "Удалить выбранное",
  uninstalling: "Удаление",
  update: "Обновить",
  updatingAllPacks: "Обновление всех пакетов",
  version: "Версия"
};
const maskEditor$1 = {
  "Apply to Whole Image": "Применить ко всему изображению",
  "Brush Settings": "Настройки кисти",
  "Brush Shape": "Форма кисти",
  Clear: "Очистить",
  "Color Select Settings": "Настройки выбора цвета",
  "Fill Opacity": "Прозрачность заливки",
  Hardness: "Жесткость",
  "Image Layer": "Слой изображения",
  Invert: "Инвертировать",
  Layers: "Слои",
  "Live Preview": "Предварительный просмотр",
  "Mask Layer": "Слой маски",
  "Mask Opacity": "Прозрачность маски",
  "Mask Tolerance": "Толерантность маски",
  Method: "Метод",
  Opacity: "Прозрачность",
  "Paint Bucket Settings": "Настройки заливки",
  "Reset to Default": "Сбросить до стандартных",
  "Selection Opacity": "Прозрачность выбора",
  "Smoothing Precision": "Точность сглаживания",
  "Stop at mask": "Остановиться на маске",
  Thickness: "Толщина",
  Tolerance: "Толерантность"
};
const menu$1 = {
  autoQueue: "Автоочередь",
  batchCount: "Количество пакетов",
  batchCountTooltip: "Количество раз, когда генерация рабочего процесса должна быть помещена в очередь",
  clear: "Очистить рабочий процесс",
  clipspace: "Открыть Clipspace",
  disabled: "Отключено",
  disabledTooltip: "Рабочий процесс не будет автоматически помещён в очередь",
  execute: "Выполнить",
  hideMenu: "Скрыть меню",
  instant: "Мгновенно",
  instantTooltip: "Рабочий процесс будет помещён в очередь сразу же после завершения генерации",
  interrupt: "Отменить текущее выполнение",
  onChange: "При изменении",
  onChangeTooltip: "Рабочий процесс будет поставлен в очередь после внесения изменений",
  refresh: "Обновить определения нод",
  resetView: "Сбросить вид холста",
  run: "Запустить",
  runWorkflow: "Запустить рабочий процесс (Shift для очереди в начале)",
  runWorkflowFront: "Запустить рабочий процесс (Очередь в начале)",
  showMenu: "Показать меню",
  toggleBottomPanel: "Переключить нижнюю панель"
};
const menuLabels$1 = {
  "About ComfyUI": "О ComfyUI",
  "Browse Templates": "Просмотреть шаблоны",
  "Bypass/Unbypass Selected Nodes": "Обойти/восстановить выбранные ноды",
  "Canvas Toggle Link Visibility": "Переключение видимости ссылки на холст",
  "Canvas Toggle Lock": "Переключение блокировки холста",
  "Check for Updates": "Проверить наличие обновлений",
  "Clear Pending Tasks": "Очистить ожидающие задачи",
  "Clear Workflow": "Очистить рабочий процесс",
  Clipspace: "Клиппространство",
  "Close Current Workflow": "Закрыть текущий рабочий процесс",
  "Collapse/Expand Selected Nodes": "Свернуть/развернуть выбранные ноды",
  "Comfy-Org Discord": "Discord Comfy-Org",
  "ComfyUI Docs": "Документация ComfyUI",
  "ComfyUI Forum": "Форум ComfyUI",
  "ComfyUI Issues": "Проблемы ComfyUI",
  "Contact Support": "Связаться с поддержкой",
  "Convert selected nodes to group node": "Преобразовать выбранные ноды в групповую ноду",
  "Custom Nodes Manager": "Менеджер Пользовательских Узлов",
  "Delete Selected Items": "Удалить выбранные элементы",
  "Desktop User Guide": "Руководство пользователя для настольных ПК",
  "Duplicate Current Workflow": "Дублировать текущий рабочий процесс",
  Edit: "Редактировать",
  Export: "Экспортировать",
  "Export (API)": "Экспорт (API)",
  "Fit Group To Contents": "Подогнать группу под содержимое",
  "Fit view to selected nodes": "Подогнать вид под выбранные ноды",
  "Give Feedback": "Оставить отзыв",
  "Group Selected Nodes": "Сгруппировать выбранные ноды",
  Help: "Помощь",
  Interrupt: "Прервать",
  "Load Default Workflow": "Загрузить стандартный рабочий процесс",
  "Manage group nodes": "Управление групповыми нодами",
  "Mute/Unmute Selected Nodes": "Отключить/включить звук для выбранных нод",
  New: "Новый",
  "Next Opened Workflow": "Следующий открытый рабочий процесс",
  Open: "Открыть",
  "Open Custom Nodes Folder": "Открыть папку пользовательских нод",
  "Open DevTools": "Открыть инструменты разработчика",
  "Open Inputs Folder": "Открыть папку входных данных",
  "Open Logs Folder": "Открыть папку журналов",
  "Open Models Folder": "Открыть папку моделей",
  "Open Outputs Folder": "Открыть папку выходных данных",
  "Open Sign In Dialog": "Открыть окно входа",
  "Open extra_model_paths_yaml": "Открыть extra_model_paths.yaml",
  "Pin/Unpin Selected Items": "Закрепить/открепить выбранные элементы",
  "Pin/Unpin Selected Nodes": "Закрепить/открепить выбранные ноды",
  "Previous Opened Workflow": "Предыдущий открытый рабочий процесс",
  "Queue Prompt": "Запрос в очереди",
  "Queue Prompt (Front)": "Запрос в очереди (спереди)",
  "Queue Selected Output Nodes": "Добавить выбранные выходные узлы в очередь",
  Quit: "Выйти",
  Redo: "Повторить",
  "Refresh Node Definitions": "Обновить определения нод",
  Reinstall: "Переустановить",
  "Reset View": "Сбросить вид",
  "Resize Selected Nodes": "Изменить размер выбранных узлов",
  Restart: "Перезапустить",
  Save: "Сохранить",
  "Save As": "Сохранить как",
  "Show Settings Dialog": "Показать диалог настроек",
  "Sign Out": "Выйти",
  "Toggle Bottom Panel": "Переключить нижнюю панель",
  "Toggle Focus Mode": "Переключить режим фокуса",
  "Toggle Logs Bottom Panel": "Переключение нижней панели журналов",
  "Toggle Model Library Sidebar": "Переключение боковой панели библиотеки моделей",
  "Toggle Node Library Sidebar": "Переключение боковой панели библиотеки нод",
  "Toggle Progress Dialog": "Переключить диалоговое окно прогресса",
  "Toggle Queue Sidebar": "Переключение боковой панели очереди",
  "Toggle Search Box": "Переключить поисковую панель",
  "Toggle Terminal Bottom Panel": "Переключение нижней панели терминала",
  "Toggle Theme (Dark/Light)": "Переключение темы (Тёмная/Светлая)",
  "Toggle Workflows Sidebar": "Переключение боковой панели рабочих процессов",
  Undo: "Отменить",
  "Ungroup selected group nodes": "Разгруппировать выбранные групповые ноды",
  Workflow: "Рабочий процесс",
  "Zoom In": "Увеличить",
  "Zoom Out": "Уменьшить"
};
const missingModelsDialog$1 = {
  doNotAskAgain: "Больше не показывать это",
  missingModels: "Отсутствующие модели",
  missingModelsMessage: "При загрузке графа следующие модели не были найдены"
};
const nodeCategories$1 = {
  "3d": "3d",
  "3d_models": "3d_модели",
  BFL: "BFL",
  Ideogram: "Ideogram",
  Kling: "Kling",
  Luma: "Luma",
  MiniMax: "MiniMax",
  OpenAI: "OpenAI",
  Pika: "Pika",
  PixVerse: "PixVerse",
  Recraft: "Recraft",
  "Stability AI": "Stability AI",
  Veo: "Veo",
  _for_testing: "_для_тестирования",
  advanced: "расширенный",
  animation: "анимация",
  api: "api",
  "api node": "api-узел",
  attention_experiments: "эксперименты_внимания",
  audio: "аудио",
  batch: "пакет",
  clip: "clip",
  combine: "объединить",
  compositing: "композиционирование",
  "cond pair": "условие_пара",
  "cond single": "условие_одиночное",
  conditioning: "условие",
  controlnet: "controlnet",
  create: "создать",
  custom_sampling: "пользовательский_семплинг",
  debug: "отладка",
  deprecated: "устаревший",
  flux: "flux",
  gligen: "gligen",
  guidance: "направление",
  guiders: "направляющие",
  hooks: "хуки",
  image: "изображение",
  inpaint: "восстановление",
  instructpix2pix: "instructpix2pix",
  latent: "латентный",
  loaders: "загрузчики",
  lotus: "lotus",
  ltxv: "ltxv",
  mask: "маска",
  model: "модель",
  model_merging: "слияние_моделей",
  model_patches: "патчи_моделей",
  model_specific: "специфичная_модель",
  noise: "шум",
  operations: "операции",
  photomaker: "photomaker",
  postprocessing: "постобработка",
  preprocessors: "предобработчики",
  primitive: "примитив",
  samplers: "семплеры",
  sampling: "выборка",
  schedulers: "schedulers",
  scheduling: "scheduling",
  sd: "sd",
  sd3: "sd3",
  sigmas: "сигмы",
  stable_cascade: "стабильная_каскадная",
  style_model: "модель_стиля",
  transform: "преобразование",
  unet: "unet",
  upscale_diffusion: "диффузии_апскейла",
  upscaling: "апскейл",
  utils: "утилиты",
  v1: "v1",
  v2: "v2",
  v3: "v3",
  video: "видео",
  video_models: "видеомодели"
};
const nodeTemplates$1 = {
  enterName: "Введите название",
  saveAsTemplate: "Сохранить как шаблон"
};
const notSupported$1 = {
  "continue": "Продолжить",
  continueTooltip: "Я уверен, что моё устройство поддерживается",
  learnMore: "Узнать больше",
  message: "Поддерживаются только следующие устройства:",
  reportIssue: "Сообщить о проблеме",
  supportedDevices: {
    macos: "MacOS (M1 или новее)",
    windows: "Windows (Nvidia GPU с поддержкой CUDA)"
  },
  title: "Ваше устройство не поддерживается"
};
const selectionToolbox$1 = {
  executeButton: {
    disabledTooltip: "Выходные узлы не выбраны",
    tooltip: "Выполнить для выбранных выходных узлов (выделены оранжевой рамкой)"
  }
};
const serverConfig$1 = {
  modifiedConfigs: "Вы изменили следующие конфигурации сервера. Перезапустите, чтобы применить изменения.",
  restart: "Перезапустить",
  revertChanges: "Отменить изменения"
};
const serverConfigCategories$1 = {
  Attention: "Внимание",
  CUDA: "CUDA",
  Cache: "Кэш",
  Directories: "Каталоги",
  General: "Общее",
  Inference: "Вывод",
  Memory: "Память",
  Network: "Сеть",
  Preview: "Предпросмотр"
};
const serverConfigItems$1 = {
  "cache-classic": {
    name: "Использовать классическую систему кэширования"
  },
  "cache-lru": {
    name: "Использовать LRU кэширование с максимальным количеством N кэшированных результатов нод.",
    tooltip: "Может использовать больше ОЗУ/ВРП."
  },
  "cpu-vae": {
    name: "Запуск VAE на CPU"
  },
  "cross-attention-method": {
    name: "Метод перекрёстного внимания"
  },
  "cuda-device": {
    name: "Индекс устройства CUDA для использования"
  },
  "cuda-malloc": {
    name: "Использовать CUDA malloc для выделения памяти"
  },
  "default-hashing-function": {
    name: "Функция хеширования по умолчанию для файлов моделей"
  },
  deterministic: {
    name: "Заставить pytorch использовать более медленные детерминированные алгоритмы, когда это возможно.",
    tooltip: "Обратите внимание, что это может не сделать изображения детерминированными во всех случаях."
  },
  directml: {
    name: "Индекс устройства DirectML"
  },
  "disable-all-custom-nodes": {
    name: "Отключить загрузку всех пользовательских нод."
  },
  "disable-ipex-optimize": {
    name: "Отключить оптимизацию IPEX"
  },
  "disable-metadata": {
    name: "Отключить сохранение метаданных подсказок в файлах."
  },
  "disable-smart-memory": {
    name: "Отключить управление умной памятью",
    tooltip: "Принудить ComfyUI агрессивно выгружать в обычную оперативную память вместо того, чтобы держать модели в VRAM, когда это возможно."
  },
  "disable-xformers": {
    name: "Отключить оптимизацию xFormers"
  },
  "dont-print-server": {
    name: "Не показывать вывод сервера в консоль."
  },
  "dont-upcast-attention": {
    name: "Предотвратить повышение внимания"
  },
  "enable-cors-header": {
    name: 'Включить CORS заголовок: Используйте "*" для всех источников или укажите домен'
  },
  fast: {
    name: "Включить некоторые непроверенные и потенциально ухудшающие качество оптимизации."
  },
  "force-channels-last": {
    name: "Принудительное использование формата памяти с последними каналами"
  },
  "force-upcast-attention": {
    name: "Принудительное повышение внимания"
  },
  "global-precision": {
    name: "Глобальная точность с плавающей запятой",
    tooltip: "Глобальная точность с плавающей запятой"
  },
  "input-directory": {
    name: "Входной каталог"
  },
  listen: {
    name: "Хост: IP-адрес для прослушивания"
  },
  "log-level": {
    name: "Уровень подробности логирования"
  },
  "max-upload-size": {
    name: "Максимальный размер загрузки (МБ)"
  },
  "output-directory": {
    name: "Выходной каталог"
  },
  port: {
    name: "Порт: Порт для прослушивания"
  },
  "preview-method": {
    name: "Метод, используемый для латентных превью"
  },
  "preview-size": {
    name: "Размер превью изображений"
  },
  "reserve-vram": {
    name: "Резервируемая VRAM (ГБ)",
    tooltip: "Установите количество VRAM в ГБ, которое вы хотите зарезервировать для использования вашей ОС/другими программами. По умолчанию резервируется определённое количество в зависимости от вашей ОС."
  },
  "text-encoder-precision": {
    name: "Точность текстового кодировщика",
    tooltip: "Точность текстового кодировщика"
  },
  "tls-certfile": {
    name: "TLS сертификат: Путь к TLS сертификату для HTTPS"
  },
  "tls-keyfile": {
    name: "TLS ключевой файл: Путь к TLS ключевому файлу для HTTPS"
  },
  "unet-precision": {
    name: "Точность UNET",
    tooltip: "Точность UNET"
  },
  "vae-precision": {
    name: "Точность VAE",
    tooltip: "Точность VAE"
  },
  "vram-management": {
    name: "Режим управления VRAM"
  }
};
const serverStart$1 = {
  openLogs: "Открыть логи",
  process: {
    error: "Не удалось запустить ComfyUI Desktop",
    "initial-state": "Загрузка…",
    "python-setup": "Настройка окружения Python…",
    ready: "Завершение…",
    "starting-server": "Запуск сервера ComfyUI…"
  },
  reportIssue: "Сообщить о проблеме",
  showTerminal: "Показать терминал",
  troubleshoot: "Устранение неполадок"
};
const settingsCategories$1 = {
  "3D": "3D",
  About: "О программе",
  Appearance: "Внешний вид",
  BrushAdjustment: "Настройка кисти",
  Camera: "Камера",
  Canvas: "Холст",
  ColorPalette: "Цветовая палитра",
  Comfy: "Comfy",
  "Comfy-Desktop": "Десктопный Comfy",
  ContextMenu: "Контекстное меню",
  Credits: "Кредиты",
  CustomColorPalettes: "Пользовательские цветовые палитры",
  DevMode: "Режим разработчика",
  EditTokenWeight: "Редактировать вес токена",
  Extension: "Расширение",
  General: "Общие",
  Graph: "Граф",
  Group: "Группа",
  Keybinding: "Сочетание клавиш",
  Light: "Светлый",
  Link: "Ссылка",
  LinkRelease: "Освобождение ссылки",
  LiteGraph: "Lite Graph",
  "Load 3D": "Загрузить 3D",
  Locale: "Локализация",
  "Mask Editor": "Редактор масок",
  Menu: "Меню",
  ModelLibrary: "Библиотека моделей",
  NewEditor: "Новый редактор",
  Node: "Нода",
  "Node Search Box": "Поисковая строка нод",
  "Node Widget": "Виджет ноды",
  NodeLibrary: "Библиотека нод",
  Pointer: "Указатель",
  Queue: "Очередь",
  QueueButton: "Кнопка очереди",
  Reroute: "Перенаправление",
  RerouteBeta: "Бета-версия перенаправления",
  Scene: "Сцена",
  Server: "Сервер",
  "Server-Config": "Настройки сервера",
  Settings: "Настройки",
  Sidebar: "Боковая панель",
  "Tree Explorer": "Дерево проводника",
  UV: "UV",
  User: "Пользователь",
  Validation: "Валидация",
  Window: "Окно",
  Workflow: "Рабочий процесс"
};
const sideToolbar$1 = {
  browseTemplates: "Просмотреть примеры шаблонов",
  downloads: "Загрузки",
  logout: "Выйти",
  modelLibrary: "Библиотека моделей",
  newBlankWorkflow: "Создайте новый пустой рабочий процесс",
  nodeLibrary: "Библиотека нод",
  nodeLibraryTab: {
    sortOrder: "Порядок сортировки"
  },
  openWorkflow: "Открыть рабочий процесс в локальной файловой системе",
  queue: "Очередь",
  queueTab: {
    backToAllTasks: "Вернуться ко всем задачам",
    clearPendingTasks: "Очистить отложенные задачи",
    containImagePreview: "Предпросмотр заливающего изображения",
    coverImagePreview: "Предпросмотр подходящего изображения",
    filter: "Фильтровать выводы",
    filters: {
      hideCached: "Скрыть кэшированные",
      hideCanceled: "Скрыть отмененные"
    },
    showFlatList: "Показать плоский список"
  },
  themeToggle: "Переключить тему",
  workflowTab: {
    confirmDelete: "Вы уверены, что хотите удалить этот рабочий процесс?",
    confirmDeleteTitle: "Удалить рабочий процесс?",
    confirmOverwrite: "Файл ниже уже существует. Вы хотите его перезаписать?",
    confirmOverwriteTitle: "Перезаписать существующий файл?",
    deleteFailed: "Попытка удалить рабочий процесс не удалась.",
    deleteFailedTitle: "Не удалось удалить",
    deleted: "Рабочий процесс удалён",
    dirtyClose: "Файлы ниже были изменены. Вы хотите сохранить их перед закрытием?",
    dirtyCloseHint: "Удерживайте Shift, чтобы закрыть без подсказки",
    dirtyCloseTitle: "Сохранить изменения?",
    workflowTreeType: {
      bookmarks: "Закладки",
      browse: "Просмотреть",
      open: "Открыть"
    }
  },
  workflows: "Рабочие процессы"
};
const tabMenu$1 = {
  addToBookmarks: "Добавить в закладки",
  closeOtherTabs: "Закрыть другие вкладки",
  closeTab: "Закрыть вкладку",
  closeTabsToLeft: "Закрыть вкладки слева",
  closeTabsToRight: "Закрыть вкладки справа",
  duplicateTab: "Дублировать вкладку",
  removeFromBookmarks: "Удалить из закладок"
};
const templateWorkflows$1 = {
  category: {
    "3D": "3D",
    "Area Composition": "Композиция области",
    Audio: "Аудио",
    Basics: "Основы",
    "ComfyUI Examples": "Примеры ComfyUI",
    ControlNet: "ControlNet",
    "Custom Nodes": "Пользовательские узлы",
    Flux: "Flux",
    Image: "Изображение",
    "Image API": "Image API",
    Upscaling: "Увеличение разрешения",
    Video: "Видео",
    "Video API": "Video API"
  },
  template: {
    "3D": {
      "hunyuan-3d-multiview-elf": "Hunyuan3D Многовидовой",
      "hunyuan-3d-turbo": "Hunyuan3D Турбо",
      "hunyuan3d-non-multiview-train": "Hunyuan3D",
      stable_zero123_example: "Stable Zero123"
    },
    "Area Composition": {
      area_composition: "Композиция области",
      area_composition_reversed: "Обратная композиция области",
      area_composition_square_area_for_subject: "Композиция области квадратной области для субъекта"
    },
    Audio: {
      stable_audio_example: "Stable Audio"
    },
    Basics: {
      "default": "Генерация изображений",
      embedding_example: "Встраивание",
      gligen_textbox_example: "Gligen Textbox",
      image2image: "Изображение в изображение",
      inpain_model_outpainting: "Inpaint Model Outpainting",
      inpaint_example: "Inpaint",
      lora: "Lora",
      lora_multiple: "Lora Multiple"
    },
    ControlNet: {
      "2_pass_pose_worship": "2 Pass Pose Worship",
      controlnet_example: "ControlNet",
      depth_controlnet: "Depth ControlNet",
      depth_t2i_adapter: "Depth T2I Adapter",
      mixing_controlnets: "Mixing ControlNets"
    },
    Flux: {
      flux_canny_model_example: "Flux Canny Model",
      flux_depth_lora_example: "Flux Depth Lora",
      flux_dev_checkpoint_example: "Flux Dev",
      flux_fill_inpaint_example: "Flux Inpaint",
      flux_fill_outpaint_example: "Flux Outpaint",
      flux_redux_model_example: "Flux Redux Model",
      flux_schnell: "Flux Schnell"
    },
    Image: {
      hidream_i1_dev: "HiDream I1 Dev",
      hidream_i1_fast: "HiDream I1 Fast",
      hidream_i1_full: "HiDream I1 Full",
      sd3_5_large_blur: "SD3.5 Большое размытие",
      sd3_5_large_canny_controlnet_example: "SD3.5 Большой Canny ControlNet",
      sd3_5_large_depth: "SD3.5 Большая глубина",
      sd3_5_simple_example: "SD3.5 Простой",
      sdxl_refiner_prompt_example: "SDXL Уточняющий запрос",
      sdxl_revision_text_prompts: "SDXL Редактирование текстовых запросов",
      sdxl_revision_zero_positive: "SDXL Редактирование нулевого положительного",
      sdxl_simple_example: "SDXL Простой",
      sdxlturbo_example: "SDXL Turbo"
    },
    "Image API": {
      "api-openai-dall-e-2-inpaint": "Dall-E 2: дорисовка",
      "api-openai-dall-e-2-t2i": "Dall-E 2: текст в изображение",
      "api-openai-dall-e-3-t2i": "Dall-E 3: текст в изображение",
      api_bfl_flux_pro_t2i: "BFL Flux 1.1[pro] Ultra текст в изображение",
      api_ideogram_v3_t2i: "Ideogram V3: текст в изображение",
      api_luma_photon_i2i: "Luma Photon: изображение в изображение",
      api_luma_photon_style_ref: "Luma Photon: стиль по образцу",
      api_openai_image_1_i2i: "OpenAI Image-1: изображение в изображение",
      api_openai_image_1_inpaint: "OpenAI Image-1: дорисовка",
      api_openai_image_1_multi_inputs: "OpenAI Image-1: несколько входов",
      api_openai_image_1_t2i: "OpenAI Image-1: текст в изображение",
      api_recraft_image_gen_with_color_control: "Recraft: генерация изображения с управлением цветом",
      api_recraft_image_gen_with_style_control: "Recraft: генерация изображения с управлением стилем",
      api_recraft_vector_gen: "Recraft: генерация векторного изображения",
      api_stability_sd3_t2i: "Stability AI Stable Image Ultra текст в изображение"
    },
    Upscaling: {
      esrgan_example: "ESRGAN",
      hiresfix_esrgan_workflow: "HiresFix ESRGAN Workflow",
      hiresfix_latent_workflow: "HiresFix Latent Workflow",
      latent_upscale_different_prompt_model: "Latent Upscale Different Prompt Model"
    },
    Video: {
      hunyuan_video_text_to_video: "Hunyuan Video Text to Video",
      image_to_video: "Изображение в видео",
      image_to_video_wan: "Wan 2.1 Изображение в Видео",
      ltxv_image_to_video: "LTXV Image to Video",
      ltxv_text_to_video: "LTXV Text to Video",
      mochi_text_to_video_example: "Mochi Text to Video",
      text_to_video_wan: "Wan 2.1 Текст в Видео",
      txt_to_image_to_video: "Текст в изображение в видео",
      wan2_1_fun_control: "Wan 2.1 ControlNet",
      wan2_1_fun_inp: "Wan 2.1 Inpainting"
    },
    "Video API": {
      api_hailuo_minimax_i2v: "MiniMax: изображение в видео",
      api_kling_i2v: "Kling: изображение в видео",
      api_luma_i2v: "Luma: изображение в видео",
      api_pika_scene: "Pika Scenes: изображения в видео",
      api_pixverse_t2v: "PixVerse: текст в видео",
      api_pixverse_template_i2v: "PixVerse Template Effects: изображение в видео",
      api_veo2_i2v: "Veo2: изображение в видео"
    }
  },
  templateDescription: {
    "3D": {
      "hunyuan-3d-multiview-elf": "Используйте Hunyuan3D 2mv для генерации моделей по нескольким видам.",
      "hunyuan-3d-turbo": "Используйте Hunyuan3D 2mv turbo для генерации моделей по нескольким видам.",
      "hunyuan3d-non-multiview-train": "Используйте Hunyuan3D 2.0 для генерации моделей по одному виду.",
      stable_zero123_example: "Генерируйте 3D-виды по одному изображению."
    },
    "Area Composition": {
      area_composition: "Управляйте композицией изображения с помощью областей.",
      area_composition_reversed: "Обратный рабочий процесс композиции областей.",
      area_composition_square_area_for_subject: "Создавайте стабильное размещение объекта."
    },
    Audio: {
      stable_audio_example: "Генерируйте аудио по текстовым описаниям."
    },
    Basics: {
      "default": "Генерируйте изображения по текстовым описаниям.",
      embedding_example: "Используйте текстовую инверсию для единых стилей.",
      gligen_textbox_example: "Указывайте расположение и размер объектов.",
      image2image: "Преобразуйте существующие изображения с помощью текстовых подсказок.",
      inpain_model_outpainting: "Расширяйте изображения за пределы их исходных границ.",
      inpaint_example: "Редактируйте отдельные части изображений без швов.",
      lora: "Применяйте LoRA-модели для специализированных стилей или объектов.",
      lora_multiple: "Комбинируйте несколько LoRA-моделей для уникальных результатов."
    },
    ControlNet: {
      "2_pass_pose_worship": "Генерируйте изображения по референсам поз.",
      controlnet_example: "Управляйте генерацией изображений с помощью референсных изображений.",
      depth_controlnet: "Создавайте изображения с учетом глубины.",
      depth_t2i_adapter: "Быстро генерируйте изображения с глубиной с помощью T2I-адаптера.",
      mixing_controlnets: "Комбинируйте несколько моделей ControlNet вместе."
    },
    Flux: {
      flux_canny_model_example: "Генерируйте изображения по детекции границ.",
      flux_depth_lora_example: "Создавайте изображения с глубиной с помощью LoRA.",
      flux_dev_checkpoint_example: "Создавайте изображения с помощью Flux development models.",
      flux_fill_inpaint_example: "Заполняйте отсутствующие части изображений.",
      flux_fill_outpaint_example: "Расширяйте изображения с помощью Flux outpainting.",
      flux_redux_model_example: "Передавайте стиль с референсного изображения для управления генерацией с помощью Flux.",
      flux_schnell: "Быстро генерируйте изображения с Flux Schnell."
    },
    Image: {
      hidream_e1_full: "Редактируйте изображения с HiDream E1.",
      hidream_i1_dev: "Генерируйте изображения с HiDream I1 Dev.",
      hidream_i1_fast: "Быстро генерируйте изображения с HiDream I1.",
      hidream_i1_full: "Генерируйте изображения с HiDream I1.",
      sd3_5_large_blur: "Генерируйте изображения по размытым референсам с SD 3.5.",
      sd3_5_large_canny_controlnet_example: "Используйте детекцию границ для управления генерацией с SD 3.5.",
      sd3_5_large_depth: "Создавайте изображения с глубиной с SD 3.5.",
      sd3_5_simple_example: "Генерируйте изображения с SD 3.5.",
      sdxl_refiner_prompt_example: "Улучшайте результаты SDXL с помощью refiners.",
      sdxl_revision_text_prompts: "Передавайте концепции с референсных изображений для управления генерацией с SDXL.",
      sdxl_revision_zero_positive: "Добавляйте текстовые подсказки вместе с референсными изображениями для управления генерацией с SDXL.",
      sdxl_simple_example: "Создавайте высококачественные изображения с SDXL.",
      sdxlturbo_example: "Генерируйте изображения за один шаг с SDXL Turbo."
    },
    "Image API": {
      "api-openai-dall-e-2-inpaint": "Используйте Dall-E 2 API для инпейнта изображений.",
      "api-openai-dall-e-2-t2i": "Используйте Dall-E 2 API для генерации изображений по текстовым описаниям.",
      "api-openai-dall-e-3-t2i": "Используйте Dall-E 3 API для генерации изображений по текстовым описаниям.",
      api_bfl_flux_pro_t2i: "Создавайте изображения с помощью FLUX.1 [pro] с отличным следованием подсказкам, высоким качеством, детализацией и разнообразием.",
      api_ideogram_v3_t2i: "Генерируйте изображения с высоким соответствием подсказкам, фотореализмом и рендерингом текста. Создавайте профессиональные логотипы, промо-постеры, концепты лендингов, продуктовые фото и многое другое. Легко создавайте сложные пространственные композиции с детализированным фоном, точным освещением и реалистичной средой.",
      api_luma_photon_i2i: "Управляйте генерацией изображений с помощью комбинации изображений и подсказки.",
      api_luma_photon_style_ref: "Применяйте и смешивайте стили с точным контролем. Luma Photon захватывает суть каждого референса, позволяя комбинировать уникальные визуальные элементы с профессиональным качеством.",
      api_openai_image_1_i2i: "Используйте GPT Image 1 API для генерации изображений по изображениям.",
      api_openai_image_1_inpaint: "Используйте GPT Image 1 API для инпейнта изображений.",
      api_openai_image_1_multi_inputs: "Используйте GPT Image 1 API с несколькими входами для генерации изображений.",
      api_openai_image_1_t2i: "Используйте GPT Image 1 API для генерации изображений по текстовым описаниям.",
      api_recraft_image_gen_with_color_control: "Создайте собственную палитру для повторного использования или подберите цвета для каждого фото. Совместите фирменную палитру и создайте уникальные визуалы.",
      api_recraft_image_gen_with_style_control: "Контролируйте стиль с помощью визуальных примеров, выравнивайте объекты и настраивайте детали. Сохраняйте и делитесь стилями для идеального брендирования.",
      api_recraft_vector_gen: "Преобразуйте текстовую подсказку в векторное изображение с помощью AI-генератора Recraft. Создавайте лучшие векторные арты для логотипов, постеров, иконок, баннеров и мокапов. Дорабатывайте дизайн с помощью качественных SVG-файлов. Создавайте фирменные векторные иллюстрации для приложений и сайтов за секунды.",
      api_stability_sd3_t2i: "Генерируйте высококачественные изображения с отличным следованием подсказкам. Идеально для профессионального использования при разрешении 1 мегапиксель."
    },
    Upscaling: {
      esrgan_example: "Используйте модели апскейлинга для повышения качества изображений.",
      hiresfix_esrgan_workflow: "Используйте модели апскейлинга на промежуточных этапах.",
      hiresfix_latent_workflow: "Улучшайте качество изображений в latent space.",
      latent_upscale_different_prompt_model: "Увеличивайте и меняйте подсказку на разных проходах."
    },
    Video: {
      hunyuan_video_text_to_video: "Генерируйте видео с помощью модели Hunyuan.",
      image_to_video: "Преобразуйте изображения в анимированные видео.",
      image_to_video_wan: "Быстро генерируйте видео из изображений.",
      ltxv_image_to_video: "Преобразуйте статичные изображения в видео.",
      ltxv_text_to_video: "Генерируйте видео по текстовым описаниям.",
      mochi_text_to_video_example: "Создавайте видео с помощью модели Mochi.",
      text_to_video_wan: "Быстро генерируйте видео по текстовым описаниям.",
      txt_to_image_to_video: "Генерируйте изображения по тексту, а затем преобразуйте их в видео.",
      wan2_1_flf2v_720_f16: "Генерируйте видео, контролируя первый и последний кадры.",
      wan2_1_fun_control: "Управляйте генерацией видео с помощью позы, глубины, границ и других параметров.",
      wan2_1_fun_inp: "Создавайте видео по начальному и конечному кадрам."
    },
    "Video API": {
      api_hailuo_minimax_i2v: "Создавайте изысканные видео из изображений и текста, включая CGI и трендовые эффекты, такие как viral AI hugging. Выбирайте стили и темы для вашего креатива.",
      api_kling_i2v: "Создавайте видео с отличным следованием подсказкам для действий, эмоций и движений камеры. Теперь поддерживаются сложные подсказки с последовательными действиями — вы режиссёр своей сцены.",
      api_luma_i2v: "Преобразуйте статичные изображения в волшебные анимации высокого качества.",
      api_pika_scene: "Используйте несколько изображений как ингредиенты и генерируйте видео, включающие их все.",
      api_pixverse_t2v: "Генерируйте видео с точной интерпретацией подсказок и впечатляющей динамикой.",
      api_pixverse_template_i2v: "Преобразует статичные изображения в динамичные видео с движением и эффектами.",
      api_veo2_i2v: "Используйте Google Veo2 API для генерации видео из изображений."
    }
  },
  title: "Начните с шаблона"
};
const toastMessages$1 = {
  couldNotDetermineFileType: "Не удалось определить тип файла",
  dropFileError: "Не удалось обработать перетаскиваемый элемент: {error}",
  emptyCanvas: "Пустой холст",
  errorCopyImage: "Ошибка копирования изображения: {error}",
  errorLoadingModel: "Ошибка загрузки модели",
  errorSaveSetting: "Ошибка сохранения настройки {id}: {err}",
  failedToAccessBillingPortal: "Не удалось получить доступ к биллинговому порталу: {error}",
  failedToApplyTexture: "Не удалось применить текстуру",
  failedToCreateCustomer: "Не удалось создать клиента: {error}",
  failedToDownloadFile: "Не удалось скачать файл",
  failedToExportModel: "Не удалось экспортировать модель как {format}",
  failedToFetchBalance: "Не удалось получить баланс: {error}",
  failedToFetchLogs: "Не удалось получить серверные логи",
  failedToInitiateCreditPurchase: "Не удалось начать покупку кредитов: {error}",
  failedToPurchaseCredits: "Не удалось купить кредиты: {error}",
  fileLoadError: "Не удалось найти рабочий процесс в {fileName}",
  fileUploadFailed: "Не удалось загрузить файл",
  interrupted: "Выполнение было прервано",
  migrateToLitegraphReroute: "Узлы перенаправления будут удалены в будущих версиях. Нажмите, чтобы перейти на litegraph-native reroute.",
  no3dScene: "Нет 3D сцены для применения текстуры",
  no3dSceneToExport: "Нет 3D сцены для экспорта",
  noTemplatesToExport: "Нет шаблонов для экспорта",
  nodeDefinitionsUpdated: "Определения узлов обновлены",
  nothingToGroup: "Нечего группировать",
  nothingToQueue: "Нет заданий в очереди",
  pendingTasksDeleted: "Ожидающие задачи удалены",
  pleaseSelectNodesToGroup: "Пожалуйста, выберите узлы (или другие группы) для создания группы",
  pleaseSelectOutputNodes: "Пожалуйста, выберите выходные узлы",
  unableToGetModelFilePath: "Не удалось получить путь к файлу модели",
  unauthorizedDomain: "Ваш домен {domain} не авторизован для использования этого сервиса. Пожалуйста, свяжитесь с {email}, чтобы добавить ваш домен в белый список.",
  updateRequested: "Запрошено обновление",
  useApiKeyTip: "Совет: Нет доступа к обычному входу? Используйте опцию Comfy API Key.",
  userNotAuthenticated: "Пользователь не аутентифицирован"
};
const userSelect$1 = {
  enterUsername: "Введите имя пользователя",
  existingUser: "Существующий пользователь",
  newUser: "Новый пользователь",
  next: "Далее",
  selectUser: "Выберите пользователя"
};
const userSettings$1 = {
  email: "Электронная почта",
  name: "Имя",
  notSet: "Не задано",
  provider: "Способ входа",
  title: "Настройки пользователя",
  updatePassword: "Обновить пароль"
};
const validation$1 = {
  invalidEmail: "Недействительный адрес электронной почты",
  length: "Должно быть {length} символов",
  maxLength: "Должно быть не более {length} символов",
  minLength: "Должно быть не менее {length} символов",
  password: {
    lowercase: "Должен содержать хотя бы одну строчную букву",
    match: "Пароли должны совпадать",
    minLength: "Должно быть от 8 до 32 символов",
    number: "Должен содержать хотя бы одну цифру",
    requirements: "Требования к паролю",
    special: "Должен содержать хотя бы один специальный символ",
    uppercase: "Должен содержать хотя бы одну заглавную букву"
  },
  personalDataConsentRequired: "Вы должны согласиться на обработку ваших персональных данных.",
  prefix: "Должно начинаться с {prefix}",
  required: "Обязательно"
};
const welcome$1 = {
  getStarted: "Начать",
  title: "Добро пожаловать в ComfyUI"
};
const workflowService$1 = {
  enterFilename: "Введите название файла",
  exportWorkflow: "Экспорт рабочего процесса",
  saveWorkflow: "Сохранить рабочий процесс"
};
const ru = {
  apiNodesCostBreakdown: apiNodesCostBreakdown$1,
  apiNodesNews: apiNodesNews$1,
  apiNodesSignInDialog: apiNodesSignInDialog$1,
  auth: auth$1,
  clipboard: clipboard$1,
  color: color$1,
  contextMenu: contextMenu$1,
  credits: credits$1,
  dataTypes: dataTypes$1,
  desktopMenu: desktopMenu$1,
  desktopUpdate: desktopUpdate$1,
  downloadGit: downloadGit$1,
  electronFileDownload: electronFileDownload$1,
  errorDialog: errorDialog$1,
  g: g$1,
  graphCanvasMenu: graphCanvasMenu$1,
  groupNode: groupNode$1,
  icon: icon$1,
  install: install$1,
  issueReport: issueReport$1,
  load3d: load3d$1,
  maintenance: maintenance$1,
  manager: manager$1,
  maskEditor: maskEditor$1,
  menu: menu$1,
  menuLabels: menuLabels$1,
  missingModelsDialog: missingModelsDialog$1,
  nodeCategories: nodeCategories$1,
  nodeTemplates: nodeTemplates$1,
  notSupported: notSupported$1,
  selectionToolbox: selectionToolbox$1,
  serverConfig: serverConfig$1,
  serverConfigCategories: serverConfigCategories$1,
  serverConfigItems: serverConfigItems$1,
  serverStart: serverStart$1,
  settingsCategories: settingsCategories$1,
  sideToolbar: sideToolbar$1,
  tabMenu: tabMenu$1,
  templateWorkflows: templateWorkflows$1,
  toastMessages: toastMessages$1,
  userSelect: userSelect$1,
  userSettings: userSettings$1,
  validation: validation$1,
  welcome: welcome$1,
  workflowService: workflowService$1
};
const AddNoise$1 = {
  display_name: "Добавить шум",
  inputs: {
    latent_image: {
      name: "латентное_изображение"
    },
    model: {
      name: "модель"
    },
    noise: {
      name: "шум"
    },
    sigmas: {
      name: "сигмы"
    }
  }
};
const AlignYourStepsScheduler$1 = {
  display_name: "Scheduler выравнивания шагов",
  inputs: {
    denoise: {
      name: "шумоподавление"
    },
    model_type: {
      name: "тип_модели"
    },
    steps: {
      name: "шаги"
    }
  }
};
const BasicGuider$1 = {
  display_name: "Основной гид",
  inputs: {
    conditioning: {
      name: "кондиционирование"
    },
    model: {
      name: "модель"
    }
  }
};
const BasicScheduler$1 = {
  display_name: "Основной scheduler",
  inputs: {
    denoise: {
      name: "шумоподавление"
    },
    model: {
      name: "модель"
    },
    scheduler: {
      name: "scheduler"
    },
    steps: {
      name: "шаги"
    }
  }
};
const BetaSamplingScheduler$1 = {
  display_name: "Scheduler выборки Бета",
  inputs: {
    alpha: {
      name: "альфа"
    },
    beta: {
      name: "бета"
    },
    model: {
      name: "модель"
    },
    steps: {
      name: "шаги"
    }
  }
};
const CFGGuider$1 = {
  display_name: "CFG Гид",
  inputs: {
    cfg: {
      name: "cfg"
    },
    model: {
      name: "модель"
    },
    negative: {
      name: "отрицательный"
    },
    positive: {
      name: "положительный"
    }
  }
};
const CFGZeroStar$1 = {
  display_name: "CFGZeroStar",
  inputs: {
    model: {
      name: "model"
    }
  },
  outputs: {
    "0": {
      name: "patched_model"
    }
  }
};
const CLIPAttentionMultiply$1 = {
  display_name: "Умножение внимания CLIP",
  inputs: {
    clip: {
      name: "clip"
    },
    k: {
      name: "k"
    },
    out: {
      name: "выход"
    },
    q: {
      name: "q"
    },
    v: {
      name: "v"
    }
  }
};
const CLIPLoader$1 = {
  description: "[Рецепты]\n\nstable_diffusion: clip-l\nstable_cascade: clip-g\nsd3: t5 / clip-g / clip-l\nstable_audio: t5\nmochi: t5\ncosmos: old t5 xxl",
  display_name: "Загрузить CLIP",
  inputs: {
    clip_name: {
      name: "название_clip"
    },
    device: {
      name: "устройство"
    },
    type: {
      name: "тип"
    }
  }
};
const CLIPMergeAdd$1 = {
  display_name: "Сложение CLIP",
  inputs: {
    clip1: {
      name: "clip1"
    },
    clip2: {
      name: "clip2"
    }
  }
};
const CLIPMergeSimple$1 = {
  display_name: "Простое слияние CLIP",
  inputs: {
    clip1: {
      name: "clip1"
    },
    clip2: {
      name: "clip2"
    },
    ratio: {
      name: "соотношение"
    }
  }
};
const CLIPMergeSubtract$1 = {
  display_name: "Вычитание CLIP",
  inputs: {
    clip1: {
      name: "clip1"
    },
    clip2: {
      name: "clip2"
    },
    multiplier: {
      name: "множитель"
    }
  }
};
const CLIPSave$1 = {
  display_name: "Сохранить CLIP",
  inputs: {
    clip: {
      name: "clip"
    },
    filename_prefix: {
      name: "префикс_названия_файла"
    }
  }
};
const CLIPSetLastLayer$1 = {
  display_name: "Установить последний слой CLIP",
  inputs: {
    clip: {
      name: "clip"
    },
    stop_at_clip_layer: {
      name: "остановиться_на_clip_слое"
    }
  }
};
const CLIPTextEncode$1 = {
  description: "Кодирует текстовый запрос с помощью модели CLIP в вектор, который можно использовать для управления моделью диффузии для генерации конкретных изображений.",
  display_name: "Кодирование текста CLIP (Запрос)",
  inputs: {
    clip: {
      name: "clip",
      tooltip: "Модель CLIP, используемая для кодирования текста."
    },
    text: {
      name: "текст",
      tooltip: "Текст для кодирования."
    }
  },
  outputs: {
    "0": {
      tooltip: "Условие, содержащее встроенный текст, используемое для управления моделью диффузии."
    }
  }
};
const CLIPTextEncodeControlnet$1 = {
  display_name: "Кодирование текста CLIP для Controlnet",
  inputs: {
    clip: {
      name: "clip"
    },
    conditioning: {
      name: "кондиционирование"
    },
    text: {
      name: "текст"
    }
  }
};
const CLIPTextEncodeFlux$1 = {
  display_name: "Кодирование текста CLIP Flux",
  inputs: {
    clip: {
      name: "clip"
    },
    clip_l: {
      name: "clip_l"
    },
    guidance: {
      name: "руководство"
    },
    t5xxl: {
      name: "t5xxl"
    }
  }
};
const CLIPTextEncodeHiDream$1 = {
  display_name: "CLIPTextEncodeHiDream",
  inputs: {
    clip: {
      name: "clip"
    },
    clip_g: {
      name: "clip_g"
    },
    clip_l: {
      name: "clip_l"
    },
    llama: {
      name: "llama"
    },
    t5xxl: {
      name: "t5xxl"
    }
  }
};
const CLIPTextEncodeHunyuanDiT$1 = {
  display_name: "Кодирование текста CLIP HunyuanDiT",
  inputs: {
    bert: {
      name: "bert"
    },
    clip: {
      name: "clip"
    },
    mt5xl: {
      name: "mt5xl"
    }
  }
};
const CLIPTextEncodeLumina2$1 = {
  description: "Кодирует системный запрос и запрос пользователя с помощью модели CLIP во встраиваемый элемент, который можно использовать для направления модели диффузии на генерацию конкретных изображений.",
  display_name: "CLIP Text Encode для Lumina2",
  inputs: {
    clip: {
      name: "clip",
      tooltip: "Модель CLIP, используемая для кодирования текста."
    },
    system_prompt: {
      name: "system_prompt",
      tooltip: "Lumina2 предоставляет два типа системных запросов: Высший: Вы - помощник, разработанный для генерации высококачественных изображений с наивысшей степенью соответствия текста и изображения на основе текстовых запросов или запросов пользователя. Соответствие: Вы - помощник, разработанный для генерации высококачественных изображений с наивысшей степенью соответствия текста и изображения на основе текстовых запросов."
    },
    user_prompt: {
      name: "user_prompt",
      tooltip: "Текст для кодирования."
    }
  },
  outputs: {
    "0": {
      tooltip: "Условие, содержащее встроенный текст, используемый для направления модели диффузии."
    }
  }
};
const CLIPTextEncodePixArtAlpha$1 = {
  description: "Кодирует текст и устанавливает условие разрешения для PixArt Alpha. Не применяется к PixArt Sigma.",
  display_name: "CLIPTextEncodePixArtAlpha",
  inputs: {
    clip: {
      name: "clip"
    },
    height: {
      name: "высота"
    },
    text: {
      name: "текст"
    },
    width: {
      name: "ширина"
    }
  }
};
const CLIPTextEncodeSD3$1 = {
  display_name: "Кодирование текста CLIP SD3",
  inputs: {
    clip: {
      name: "clip"
    },
    clip_g: {
      name: "clip_g"
    },
    clip_l: {
      name: "clip_l"
    },
    empty_padding: {
      name: "пустое_заполнение"
    },
    t5xxl: {
      name: "t5xxl"
    }
  }
};
const CLIPTextEncodeSDXL$1 = {
  display_name: "Кодирование текста CLIP SDXL",
  inputs: {
    clip: {
      name: "clip"
    },
    crop_h: {
      name: "обрезка_высоты"
    },
    crop_w: {
      name: "обрезка_ширины"
    },
    height: {
      name: "высота"
    },
    target_height: {
      name: "целевая_высота"
    },
    target_width: {
      name: "целевая_ширина"
    },
    text_g: {
      name: "текст_g"
    },
    text_l: {
      name: "текст_l"
    },
    width: {
      name: "ширина"
    }
  }
};
const CLIPTextEncodeSDXLRefiner$1 = {
  display_name: "Кодирование текста CLIP SDXL Refinement",
  inputs: {
    ascore: {
      name: "ascore"
    },
    clip: {
      name: "clip"
    },
    height: {
      name: "высота"
    },
    text: {
      name: "текст"
    },
    width: {
      name: "ширина"
    }
  }
};
const CLIPVisionEncode$1 = {
  display_name: "Кодирование видения CLIP",
  inputs: {
    clip_vision: {
      name: "clip_vision"
    },
    crop: {
      name: "обрезка"
    },
    image: {
      name: "изображение"
    }
  }
};
const CLIPVisionLoader$1 = {
  display_name: "Загрузить видение CLIP",
  inputs: {
    clip_name: {
      name: "название_clip"
    }
  }
};
const Canny$1 = {
  display_name: "Canny",
  inputs: {
    high_threshold: {
      name: "верхний_порог"
    },
    image: {
      name: "изображение"
    },
    low_threshold: {
      name: "нижний_порог"
    }
  }
};
const CheckpointLoader$1 = {
  display_name: "Загрузить сheckpoint с конфигурацией (УСТАРЕЛО)",
  inputs: {
    ckpt_name: {
      name: "название_точки_проверки"
    },
    config_name: {
      name: "название_конфигурации"
    }
  }
};
const CheckpointLoaderSimple$1 = {
  description: "Загружает сheckpoint-модели диффузии, модели диффузии используются для удаления шума из латентов.",
  display_name: "Загрузить сheckpoint",
  inputs: {
    ckpt_name: {
      name: "название_точки_проверки",
      tooltip: "Название сheckpoint (модели) для загрузки."
    }
  },
  outputs: {
    "0": {
      tooltip: "Модель, используемая для шумоподавления латентов."
    },
    "1": {
      tooltip: "Модель CLIP, используемая для кодирования текстовых подсказок."
    },
    "2": {
      tooltip: "Модель VAE, используемая для кодирования и декодирования изображений из и в латентное пространство."
    }
  }
};
const CheckpointSave$1 = {
  display_name: "Сохранить сheckpoint",
  inputs: {
    clip: {
      name: "clip"
    },
    filename_prefix: {
      name: "префикс_названия_файла"
    },
    model: {
      name: "модель"
    },
    vae: {
      name: "vae"
    }
  }
};
const CombineHooks2$1 = {
  display_name: "Объединить хуки [2]",
  inputs: {
    hooks_A: {
      name: "hooks_A"
    },
    hooks_B: {
      name: "hooks_B"
    }
  }
};
const CombineHooks4$1 = {
  display_name: "Объединить хуки [4]",
  inputs: {
    hooks_A: {
      name: "hooks_A"
    },
    hooks_B: {
      name: "hooks_B"
    },
    hooks_C: {
      name: "hooks_C"
    },
    hooks_D: {
      name: "hooks_D"
    }
  }
};
const CombineHooks8$1 = {
  display_name: "Объединить хуки [8]",
  inputs: {
    hooks_A: {
      name: "hooks_A"
    },
    hooks_B: {
      name: "hooks_B"
    },
    hooks_C: {
      name: "hooks_C"
    },
    hooks_D: {
      name: "hooks_D"
    },
    hooks_E: {
      name: "hooks_E"
    },
    hooks_F: {
      name: "hooks_F"
    },
    hooks_G: {
      name: "hooks_G"
    },
    hooks_H: {
      name: "hooks_H"
    }
  }
};
const ConditioningAverage$1 = {
  display_name: "Среднее кондиционирование",
  inputs: {
    conditioning_from: {
      name: "условие_от"
    },
    conditioning_to: {
      name: "условие_к"
    },
    conditioning_to_strength: {
      name: "сила_условия_к"
    }
  }
};
const ConditioningCombine$1 = {
  display_name: "Кондиционирование (Объединение)",
  inputs: {
    conditioning_1: {
      name: "условие_1"
    },
    conditioning_2: {
      name: "условие_2"
    }
  }
};
const ConditioningConcat$1 = {
  display_name: "Кондиционирование (Конкатенация)",
  inputs: {
    conditioning_from: {
      name: "условие_от"
    },
    conditioning_to: {
      name: "условие_к"
    }
  }
};
const ConditioningSetArea$1 = {
  display_name: "Кондиционирование (Установить область)",
  inputs: {
    conditioning: {
      name: "условие"
    },
    height: {
      name: "высота"
    },
    strength: {
      name: "сила"
    },
    width: {
      name: "ширина"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const ConditioningSetAreaPercentage$1 = {
  display_name: "Кондиционирование (Установить область с процентом)",
  inputs: {
    conditioning: {
      name: "условие"
    },
    height: {
      name: "высота"
    },
    strength: {
      name: "сила"
    },
    width: {
      name: "ширина"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const ConditioningSetAreaPercentageVideo$1 = {
  display_name: "УсловныйНаборПроцентПлощадиВидео",
  inputs: {
    conditioning: {
      name: "условие"
    },
    height: {
      name: "высота"
    },
    strength: {
      name: "сила"
    },
    temporal: {
      name: "временной"
    },
    width: {
      name: "ширина"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    },
    z: {
      name: "z"
    }
  }
};
const ConditioningSetAreaStrength$1 = {
  display_name: "Сила установки области кондиционирования",
  inputs: {
    conditioning: {
      name: "условие"
    },
    strength: {
      name: "сила"
    }
  }
};
const ConditioningSetDefaultCombine$1 = {
  display_name: "Установить значение по умолчанию для объединения кондиционирования",
  inputs: {
    cond: {
      name: "условие"
    },
    cond_DEFAULT: {
      name: "условие_ПО_УМОЛЧАНИЮ"
    },
    hooks: {
      name: "hooks"
    }
  }
};
const ConditioningSetMask$1 = {
  display_name: "Кондиционирование (Установить маску)",
  inputs: {
    conditioning: {
      name: "условие"
    },
    mask: {
      name: "маска"
    },
    set_cond_area: {
      name: "установить_область_условия"
    },
    strength: {
      name: "сила"
    }
  }
};
const ConditioningSetProperties$1 = {
  display_name: "Установить свойства кондиционирования",
  inputs: {
    cond_NEW: {
      name: "новое_условие"
    },
    hooks: {
      name: "хуки"
    },
    mask: {
      name: "маска"
    },
    set_cond_area: {
      name: "установить_область_условия"
    },
    strength: {
      name: "сила"
    },
    timesteps: {
      name: "временные_шаги"
    }
  }
};
const ConditioningSetPropertiesAndCombine$1 = {
  display_name: "Установить свойства кондиционирования и объединить",
  inputs: {
    cond: {
      name: "условие"
    },
    cond_NEW: {
      name: "новое_условие"
    },
    hooks: {
      name: "хуки"
    },
    mask: {
      name: "маска"
    },
    set_cond_area: {
      name: "установить_область_условия"
    },
    strength: {
      name: "сила"
    },
    timesteps: {
      name: "временные_шаги"
    }
  }
};
const ConditioningSetTimestepRange$1 = {
  display_name: "Установить диапазон временных шагов кондиционирования",
  inputs: {
    conditioning: {
      name: "условие"
    },
    end: {
      name: "конец"
    },
    start: {
      name: "начало"
    }
  }
};
const ConditioningStableAudio$1 = {
  display_name: "ConditioningStableAudio",
  inputs: {
    negative: {
      name: "отрицательный"
    },
    positive: {
      name: "положительный"
    },
    seconds_start: {
      name: "секунды_начала"
    },
    seconds_total: {
      name: "всего_секунд"
    }
  },
  outputs: {
    "0": {
      name: "положительный"
    },
    "1": {
      name: "отрицательный"
    }
  }
};
const ConditioningTimestepsRange$1 = {
  display_name: "Диапазон временных шагов",
  inputs: {
    end_percent: {
      name: "процент_конца"
    },
    start_percent: {
      name: "процент_начала"
    }
  },
  outputs: {
    "1": {
      name: "ДО_ДИАПАЗОНА"
    },
    "2": {
      name: "ПОСЛЕ_ДИАПАЗОНА"
    }
  }
};
const ConditioningZeroOut$1 = {
  display_name: "Обнуление кондиционирования",
  inputs: {
    conditioning: {
      name: "условие"
    }
  }
};
const ControlNetApply$1 = {
  display_name: "Применить ControlNet (УСТАРЕЛО)",
  inputs: {
    conditioning: {
      name: "условие"
    },
    control_net: {
      name: "control_net"
    },
    image: {
      name: "изображение"
    },
    strength: {
      name: "сила"
    }
  }
};
const ControlNetApplyAdvanced$1 = {
  display_name: "Применить ControlNet",
  inputs: {
    control_net: {
      name: "control_net"
    },
    end_percent: {
      name: "процент_конца"
    },
    image: {
      name: "изображение"
    },
    negative: {
      name: "отрицательный"
    },
    positive: {
      name: "положительный"
    },
    start_percent: {
      name: "процент_начала"
    },
    strength: {
      name: "сила"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "положительный"
    },
    "1": {
      name: "отрицательный"
    }
  }
};
const ControlNetApplySD3$1 = {
  display_name: "Применить ControlNet с VAE",
  inputs: {
    control_net: {
      name: "control_net"
    },
    end_percent: {
      name: "процент_конца"
    },
    image: {
      name: "изображение"
    },
    negative: {
      name: "отрицательный"
    },
    positive: {
      name: "положительный"
    },
    start_percent: {
      name: "процент_начала"
    },
    strength: {
      name: "сила"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "положительный"
    },
    "1": {
      name: "отрицательный"
    }
  }
};
const ControlNetInpaintingAliMamaApply$1 = {
  display_name: "Применить ControlNet для инпейнтинга AliMama",
  inputs: {
    control_net: {
      name: "control_net"
    },
    end_percent: {
      name: "процент_конца"
    },
    image: {
      name: "изображение"
    },
    mask: {
      name: "маска"
    },
    negative: {
      name: "отрицательный"
    },
    positive: {
      name: "положительный"
    },
    start_percent: {
      name: "процент_начала"
    },
    strength: {
      name: "сила"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "положительный"
    },
    "1": {
      name: "отрицательный"
    }
  }
};
const ControlNetLoader$1 = {
  display_name: "Загрузить модель ControlNet",
  inputs: {
    control_net_name: {
      name: "название_control_net"
    }
  }
};
const CosmosImageToVideoLatent$1 = {
  display_name: "CosmosImageToVideoLatent",
  inputs: {
    batch_size: {
      name: "размер_пакета"
    },
    end_image: {
      name: "конечное_изображение"
    },
    height: {
      name: "высота"
    },
    length: {
      name: "длина"
    },
    start_image: {
      name: "начальное_изображение"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "ширина"
    }
  }
};
const CreateHookKeyframe$1 = {
  display_name: "Создать ключевой кадр хука",
  inputs: {
    prev_hook_kf: {
      name: "предыдущий_hook_kf"
    },
    start_percent: {
      name: "процент_начала"
    },
    strength_mult: {
      name: "множитель_силы"
    }
  },
  outputs: {
    "0": {
      name: "КЛЮЧЕВОЙ_КАДР"
    }
  }
};
const CreateHookKeyframesFromFloats$1 = {
  display_name: "Создать ключевые кадры хука из чисел с плавающей запятой",
  inputs: {
    end_percent: {
      name: "процент_конца"
    },
    floats_strength: {
      name: "сила_в_виде_чисел"
    },
    prev_hook_kf: {
      name: "предыдущий_hook_kf"
    },
    print_keyframes: {
      name: "печать_ключевых_кадров"
    },
    start_percent: {
      name: "процент_начала"
    }
  },
  outputs: {
    "0": {
      name: "КЛЮЧЕВОЙ_КАДР"
    }
  }
};
const CreateHookKeyframesInterpolated$1 = {
  display_name: "Создать интерполированные ключевые кадры хука",
  inputs: {
    end_percent: {
      name: "конечный_процент"
    },
    interpolation: {
      name: "интерполяция"
    },
    keyframes_count: {
      name: "количество_ключевых_кадров"
    },
    prev_hook_kf: {
      name: "предыдущий_хук_kf"
    },
    print_keyframes: {
      name: "печать_ключевых_кадров"
    },
    start_percent: {
      name: "начальный_процент"
    },
    strength_end: {
      name: "конечная_сила"
    },
    strength_start: {
      name: "начальная_сила"
    }
  },
  outputs: {
    "0": {
      name: "КЛЮЧЕВОЙ_КАДР"
    }
  }
};
const CreateHookLora$1 = {
  display_name: "Создать хук LoRA",
  inputs: {
    lora_name: {
      name: "название_lora"
    },
    prev_hooks: {
      name: "предыдущие_хуки"
    },
    strength_clip: {
      name: "сила_клипа"
    },
    strength_model: {
      name: "сила_модели"
    }
  }
};
const CreateHookLoraModelOnly$1 = {
  display_name: "Создать хук LoRA (Только модель)",
  inputs: {
    lora_name: {
      name: "название_lora"
    },
    prev_hooks: {
      name: "предыдущие_хуки"
    },
    strength_model: {
      name: "сила_модели"
    }
  }
};
const CreateHookModelAsLora$1 = {
  display_name: "Создать хук модели как LoRA",
  inputs: {
    ckpt_name: {
      name: "название_ckpt"
    },
    prev_hooks: {
      name: "предыдущие_хуки"
    },
    strength_clip: {
      name: "сила_клипа"
    },
    strength_model: {
      name: "сила_модели"
    }
  }
};
const CreateHookModelAsLoraModelOnly$1 = {
  display_name: "Создать хук модели как LoRA (Только модель)",
  inputs: {
    ckpt_name: {
      name: "название_ckpt"
    },
    prev_hooks: {
      name: "предыдущие_хуки"
    },
    strength_model: {
      name: "сила_модели"
    }
  }
};
const CreateVideo$1 = {
  description: "Создайте видео из изображений.",
  display_name: "Создать видео",
  inputs: {
    audio: {
      name: "аудио",
      tooltip: "Аудио, которое будет добавлено к видео."
    },
    fps: {
      name: "кадров в секунду"
    },
    images: {
      name: "изображения",
      tooltip: "Изображения, из которых будет создано видео."
    }
  }
};
const CropMask$1 = {
  display_name: "Обрезать маску",
  inputs: {
    height: {
      name: "высота"
    },
    mask: {
      name: "маска"
    },
    width: {
      name: "ширина"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const DiffControlNetLoader$1 = {
  display_name: "Загрузить модель ControlNet (дифф)",
  inputs: {
    control_net_name: {
      name: "название_control_net"
    },
    model: {
      name: "модель"
    }
  }
};
const DifferentialDiffusion$1 = {
  display_name: "Дифференциальная диффузия",
  inputs: {
    model: {
      name: "модель"
    }
  }
};
const DiffusersLoader$1 = {
  display_name: "Загрузчик диффузоров",
  inputs: {
    model_path: {
      name: "путь_модели"
    }
  }
};
const DisableNoise$1 = {
  display_name: "Отключить шум"
};
const DualCFGGuider$1 = {
  display_name: "Двойной CFG Гид",
  inputs: {
    cfg_cond2_negative: {
      name: "cfg_cond2_negative"
    },
    cfg_conds: {
      name: "cfg_conds"
    },
    cond1: {
      name: "cond1"
    },
    cond2: {
      name: "cond2"
    },
    model: {
      name: "модель"
    },
    negative: {
      name: "отрицательный"
    }
  }
};
const DualCLIPLoader$1 = {
  description: "[Рецепты]\n\nsdxl: clip-l, clip-g\nsd3: clip-l, clip-g / clip-l, t5 / clip-g, t5\nflux: clip-l, t5",
  display_name: "Двойной загрузчик CLIP",
  inputs: {
    clip_name1: {
      name: "clip_name1"
    },
    clip_name2: {
      name: "clip_name2"
    },
    device: {
      name: "устройство"
    },
    type: {
      name: "тип"
    }
  }
};
const EmptyCosmosLatentVideo$1 = {
  display_name: "EmptyCosmosLatentVideo",
  inputs: {
    batch_size: {
      name: "размер_пакета"
    },
    height: {
      name: "высота"
    },
    length: {
      name: "длина"
    },
    width: {
      name: "ширина"
    }
  }
};
const EmptyHunyuanLatentVideo$1 = {
  display_name: "Пустой HunyuanLatentVideo",
  inputs: {
    batch_size: {
      name: "размер_пакета"
    },
    height: {
      name: "высота"
    },
    length: {
      name: "длина"
    },
    width: {
      name: "ширина"
    }
  }
};
const EmptyImage$1 = {
  display_name: "Пустое изображение",
  inputs: {
    batch_size: {
      name: "размер_пакета"
    },
    color: {
      name: "цвет"
    },
    height: {
      name: "высота"
    },
    width: {
      name: "ширина"
    }
  }
};
const EmptyLTXVLatentVideo$1 = {
  display_name: "Пустой LTXVLatentVideo",
  inputs: {
    batch_size: {
      name: "размер_пакета"
    },
    height: {
      name: "высота"
    },
    length: {
      name: "длина"
    },
    width: {
      name: "ширина"
    }
  }
};
const EmptyLatentAudio$1 = {
  display_name: "Пустой LatentAudio",
  inputs: {
    batch_size: {
      name: "размер_пакета",
      tooltip: "Количество латентных изображений в партии."
    },
    seconds: {
      name: "секунды"
    }
  }
};
const EmptyLatentHunyuan3Dv2$1 = {
  display_name: "EmptyLatentHunyuan3Dv2",
  inputs: {
    batch_size: {
      name: "размер_пакета",
      tooltip: "Количество скрытых изображений в пакете."
    },
    resolution: {
      name: "разрешение"
    }
  }
};
const EmptyLatentImage$1 = {
  description: "Создаёт новую партию пустых латентных изображений для удаления шума через выборку.",
  display_name: "Пустое латентное изображение",
  inputs: {
    batch_size: {
      name: "размер_пакета",
      tooltip: "Количество латентных изображений в партии."
    },
    height: {
      name: "высота",
      tooltip: "Высота латентных изображений в пикселях."
    },
    width: {
      name: "ширина",
      tooltip: "Ширина латентных изображений в пикселях."
    }
  },
  outputs: {
    "0": {
      tooltip: "Пустая партия латентных изображений."
    }
  }
};
const EmptyMochiLatentVideo$1 = {
  display_name: "Пустой MochiLatentVideo",
  inputs: {
    batch_size: {
      name: "размер_пакета"
    },
    height: {
      name: "высота"
    },
    length: {
      name: "длина"
    },
    width: {
      name: "ширина"
    }
  }
};
const EmptySD3LatentImage$1 = {
  display_name: "Пустой SD3LatentImage",
  inputs: {
    batch_size: {
      name: "размер_пакета"
    },
    height: {
      name: "высота"
    },
    width: {
      name: "ширина"
    }
  }
};
const ExponentialScheduler$1 = {
  display_name: "Экспоненциальный scheduler",
  inputs: {
    sigma_max: {
      name: "sigma_max"
    },
    sigma_min: {
      name: "sigma_min"
    },
    steps: {
      name: "шаги"
    }
  }
};
const ExtendIntermediateSigmas$1 = {
  display_name: "ExtendIntermediateSigmas",
  inputs: {
    end_at_sigma: {
      name: "закончить_на_sigma"
    },
    sigmas: {
      name: "sigmas"
    },
    spacing: {
      name: "интервал"
    },
    start_at_sigma: {
      name: "начать_с_sigma"
    },
    steps: {
      name: "шаги"
    }
  }
};
const FeatherMask$1 = {
  display_name: "Пернатая маска",
  inputs: {
    bottom: {
      name: "снизу"
    },
    left: {
      name: "слева"
    },
    mask: {
      name: "маска"
    },
    right: {
      name: "справа"
    },
    top: {
      name: "сверху"
    }
  }
};
const FlipSigmas$1 = {
  display_name: "Перевернуть сигмы",
  inputs: {
    sigmas: {
      name: "sigmas"
    }
  }
};
const FluxDisableGuidance$1 = {
  description: "Этот узел полностью отключает встраиваемое руководство на Flux и подобных моделях Flux",
  display_name: "FluxDisableGuidance",
  inputs: {
    conditioning: {
      name: "conditioning"
    }
  }
};
const FluxGuidance$1 = {
  display_name: "Направление Flux",
  inputs: {
    conditioning: {
      name: "условие"
    },
    guidance: {
      name: "руководство"
    }
  }
};
const FluxProCannyNode$1 = {
  description: "Генерировать изображение с использованием контрольного изображения (canny).",
  display_name: "Flux.1 Canny контрольное изображение",
  inputs: {
    canny_high_threshold: {
      name: "canny_high_threshold",
      tooltip: "Верхний порог для детектирования границ Canny; игнорируется, если skip_processing установлен в True"
    },
    canny_low_threshold: {
      name: "canny_low_threshold",
      tooltip: "Нижний порог для детектирования границ Canny; игнорируется, если skip_processing установлен в True"
    },
    control_after_generate: {
      name: "control after generate"
    },
    control_image: {
      name: "control_image"
    },
    guidance: {
      name: "guidance",
      tooltip: "Сила направляющего сигнала для процесса генерации изображения"
    },
    prompt: {
      name: "prompt",
      tooltip: "Промпт для генерации изображения"
    },
    prompt_upsampling: {
      name: "prompt_upsampling",
      tooltip: "Выполнять ли апсемплинг промпта. Если активно, автоматически изменяет промпт для более креативной генерации, но результаты будут недетерминированными (одинаковое зерно не даст точно такой же результат)."
    },
    seed: {
      name: "seed",
      tooltip: "Случайное зерно, используемое для создания шума."
    },
    skip_preprocessing: {
      name: "skip_preprocessing",
      tooltip: "Пропускать ли предварительную обработку; установите True, если control_image уже обработано Canny, False — если это исходное изображение."
    },
    steps: {
      name: "steps",
      tooltip: "Количество шагов для процесса генерации изображения"
    }
  }
};
const FluxProDepthNode$1 = {
  description: "Генерировать изображение с использованием контрольного изображения (глубина).",
  display_name: "Flux.1 Контроль изображения по глубине",
  inputs: {
    control_after_generate: {
      name: "control after generate"
    },
    control_image: {
      name: "control_image"
    },
    guidance: {
      name: "guidance",
      tooltip: "Сила направляющего сигнала для процесса генерации изображения"
    },
    prompt: {
      name: "prompt",
      tooltip: "Промпт для генерации изображения"
    },
    prompt_upsampling: {
      name: "prompt_upsampling",
      tooltip: "Выполнять ли апсемплинг промпта. Если активно, автоматически изменяет промпт для более креативной генерации, но результаты будут недетерминированными (одинаковое зерно не даст точно такой же результат)."
    },
    seed: {
      name: "seed",
      tooltip: "Случайное зерно, используемое для создания шума."
    },
    skip_preprocessing: {
      name: "skip_preprocessing",
      tooltip: "Пропустить ли предварительную обработку; установите True, если control_image уже содержит глубину, False — если это исходное изображение."
    },
    steps: {
      name: "steps",
      tooltip: "Количество шагов для процесса генерации изображения"
    }
  }
};
const FluxProExpandNode$1 = {
  description: "Дорисовывает изображение на основе запроса.",
  display_name: "Flux.1 Расширить изображение",
  inputs: {
    bottom: {
      name: "низ",
      tooltip: "Количество пикселей для расширения снизу изображения"
    },
    control_after_generate: {
      name: "контроль после генерации"
    },
    guidance: {
      name: "направление",
      tooltip: "Сила направляющего сигнала для процесса генерации изображения"
    },
    image: {
      name: "изображение"
    },
    left: {
      name: "слева",
      tooltip: "Количество пикселей для расширения слева изображения"
    },
    prompt: {
      name: "запрос",
      tooltip: "Запрос для генерации изображения"
    },
    prompt_upsampling: {
      name: "апсемплинг запроса",
      tooltip: "Выполнять ли апсемплинг запроса. Если включено, запрос автоматически модифицируется для более креативной генерации, но результаты будут недетерминированными (одинаковое зерно не даст точно такой же результат)."
    },
    right: {
      name: "справа",
      tooltip: "Количество пикселей для расширения справа изображения"
    },
    seed: {
      name: "seed",
      tooltip: "Случайное зерно, используемое для создания шума."
    },
    steps: {
      name: "шаги",
      tooltip: "Количество шагов для процесса генерации изображения"
    },
    top: {
      name: "верх",
      tooltip: "Количество пикселей для расширения сверху изображения"
    }
  }
};
const FluxProFillNode$1 = {
  description: "Дорисовывает изображение на основе mask и prompt.",
  display_name: "Flux.1 Заполнение изображения",
  inputs: {
    control_after_generate: {
      name: "контроль после генерации"
    },
    guidance: {
      name: "направление",
      tooltip: "Сила направляющего сигнала для процесса генерации изображения"
    },
    image: {
      name: "image"
    },
    mask: {
      name: "mask"
    },
    prompt: {
      name: "prompt",
      tooltip: "Промпт для генерации изображения"
    },
    prompt_upsampling: {
      name: "повышение разрешения промпта",
      tooltip: "Выполнять ли повышение разрешения промпта. Если активно, автоматически изменяет промпт для более креативной генерации, но результаты будут недетерминированными (одинаковое значение seed не даст точно такой же результат)."
    },
    seed: {
      name: "seed",
      tooltip: "Случайное значение seed, используемое для создания шума."
    },
    steps: {
      name: "шаги",
      tooltip: "Количество шагов для процесса генерации изображения"
    }
  }
};
const FluxProUltraImageNode$1 = {
  description: "Генерирует изображения с помощью Flux Pro 1.1 Ultra через API на основе запроса и разрешения.",
  display_name: "Flux 1.1 [pro] Ultra Image",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio",
      tooltip: "Соотношение сторон изображения; должно быть между 1:4 и 4:1."
    },
    control_after_generate: {
      name: "control after generate"
    },
    image_prompt: {
      name: "image_prompt"
    },
    image_prompt_strength: {
      name: "image_prompt_strength",
      tooltip: "Смешивание между текстовым запросом и image prompt."
    },
    prompt: {
      name: "prompt",
      tooltip: "Запрос для генерации изображения"
    },
    prompt_upsampling: {
      name: "prompt_upsampling",
      tooltip: "Выполнять ли апсемплинг запроса. Если включено, автоматически изменяет запрос для более креативной генерации, но результаты будут недетерминированными (одинаковое зерно не даст точно такой же результат)."
    },
    raw: {
      name: "raw",
      tooltip: "Если True, генерирует менее обработанные, более естественные изображения."
    },
    seed: {
      name: "seed",
      tooltip: "Случайное зерно, используемое для создания шума."
    }
  }
};
const FreSca$1 = {
  description: "Применяет масштабирование, зависящее от частоты, к управлению",
  display_name: "FreSca",
  inputs: {
    freq_cutoff: {
      name: "freq_cutoff",
      tooltip: "Количество частотных индексов вокруг центра, считающихся низкочастотными"
    },
    model: {
      name: "model"
    },
    scale_high: {
      name: "scale_high",
      tooltip: "Масштабный коэффициент для высокочастотных компонентов"
    },
    scale_low: {
      name: "scale_low",
      tooltip: "Масштабный коэффициент для низкочастотных компонентов"
    }
  }
};
const FreeU$1 = {
  display_name: "FreeU",
  inputs: {
    b1: {
      name: "b1"
    },
    b2: {
      name: "b2"
    },
    model: {
      name: "модель"
    },
    s1: {
      name: "s1"
    },
    s2: {
      name: "s2"
    }
  }
};
const FreeU_V2$1 = {
  display_name: "FreeU_V2",
  inputs: {
    b1: {
      name: "b1"
    },
    b2: {
      name: "b2"
    },
    model: {
      name: "модель"
    },
    s1: {
      name: "s1"
    },
    s2: {
      name: "s2"
    }
  }
};
const GITSScheduler$1 = {
  display_name: "GITSScheduler",
  inputs: {
    coeff: {
      name: "коэфф"
    },
    denoise: {
      name: "шумоподавление"
    },
    steps: {
      name: "шаги"
    }
  }
};
const GLIGENLoader$1 = {
  display_name: "Загрузчик GLIGEN",
  inputs: {
    gligen_name: {
      name: "название_gligen"
    }
  }
};
const GLIGENTextBoxApply$1 = {
  display_name: "Применить текстовое поле GLIGEN",
  inputs: {
    clip: {
      name: "clip"
    },
    conditioning_to: {
      name: "условие_для"
    },
    gligen_textbox_model: {
      name: "модель_текстового_поля_gligen"
    },
    height: {
      name: "высота"
    },
    text: {
      name: "текст"
    },
    width: {
      name: "ширина"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const GetVideoComponents$1 = {
  description: "Извлекает все компоненты из видео: кадры, аудио и частоту кадров.",
  display_name: "Извлечь компоненты видео",
  inputs: {
    video: {
      name: "видео",
      tooltip: "Видео, из которого нужно извлечь компоненты."
    }
  },
  outputs: {
    "0": {
      name: "изображения"
    },
    "1": {
      name: "аудио"
    },
    "2": {
      name: "fps"
    }
  }
};
const GrowMask$1 = {
  display_name: "Увеличить маску",
  inputs: {
    expand: {
      name: "расширить"
    },
    mask: {
      name: "маска"
    },
    tapered_corners: {
      name: "заостренные_углы"
    }
  }
};
const Hunyuan3Dv2Conditioning$1 = {
  display_name: "Hunyuan3Dv2Conditioning",
  inputs: {
    clip_vision_output: {
      name: "выход_clip_vision"
    }
  },
  outputs: {
    "0": {
      name: "положительный"
    },
    "1": {
      name: "отрицательный"
    }
  }
};
const Hunyuan3Dv2ConditioningMultiView$1 = {
  display_name: "Hunyuan3Dv2ConditioningMultiView",
  inputs: {
    back: {
      name: "сзади"
    },
    front: {
      name: "фронт"
    },
    left: {
      name: "слева"
    },
    right: {
      name: "справа"
    }
  },
  outputs: {
    "0": {
      name: "положительный"
    },
    "1": {
      name: "отрицательный"
    }
  }
};
const HunyuanImageToVideo$1 = {
  display_name: "HunyuanImageToVideo",
  inputs: {
    batch_size: {
      name: "размер пакета"
    },
    guidance_type: {
      name: "тип руководства"
    },
    height: {
      name: "высота"
    },
    length: {
      name: "длина"
    },
    positive: {
      name: "положительный"
    },
    start_image: {
      name: "начальное изображение"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "ширина"
    }
  },
  outputs: {
    "0": {
      name: "положительный"
    },
    "1": {
      name: "скрытое пространство"
    }
  }
};
const HyperTile$1 = {
  display_name: "Гиперплитка",
  inputs: {
    max_depth: {
      name: "максимальная_глубина"
    },
    model: {
      name: "модель"
    },
    scale_depth: {
      name: "масштаб_глубины"
    },
    swap_size: {
      name: "размер_замены"
    },
    tile_size: {
      name: "размер_плитки"
    }
  }
};
const HypernetworkLoader$1 = {
  display_name: "Загрузчик hypernetwork",
  inputs: {
    hypernetwork_name: {
      name: "название_hypernetwork"
    },
    model: {
      name: "модель"
    },
    strength: {
      name: "сила"
    }
  }
};
const IdeogramV1$1 = {
  description: "Генерирует изображения синхронно с использованием модели Ideogram V1.\n\nСсылки на изображения доступны ограниченное время; если вы хотите сохранить изображение, его необходимо скачать.",
  display_name: "Ideogram V1",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio",
      tooltip: "Соотношение сторон для генерации изображения."
    },
    control_after_generate: {
      name: "control after generate"
    },
    magic_prompt_option: {
      name: "magic_prompt_option",
      tooltip: "Определяет, использовать ли MagicPrompt при генерации"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Описание того, что нужно исключить из изображения"
    },
    num_images: {
      name: "num_images"
    },
    prompt: {
      name: "prompt",
      tooltip: "Запрос для генерации изображения"
    },
    seed: {
      name: "seed"
    },
    turbo: {
      name: "turbo",
      tooltip: "Использовать ли turbo-режим (более быстрая генерация, возможно, с пониженным качеством)"
    }
  }
};
const IdeogramV2$1 = {
  description: "Генерирует изображения синхронно с использованием модели Ideogram V2.\n\nСсылки на изображения доступны ограниченное время; если вы хотите сохранить изображение, его необходимо скачать.",
  display_name: "Ideogram V2",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio",
      tooltip: "Соотношение сторон для генерации изображения. Игнорируется, если разрешение не установлено в AUTO."
    },
    control_after_generate: {
      name: "control after generate"
    },
    magic_prompt_option: {
      name: "magic_prompt_option",
      tooltip: "Определяет, использовать ли MagicPrompt при генерации"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Описание того, что следует исключить из изображения"
    },
    num_images: {
      name: "num_images"
    },
    prompt: {
      name: "prompt",
      tooltip: "Запрос для генерации изображения"
    },
    resolution: {
      name: "resolution",
      tooltip: "Разрешение для генерации изображения. Если не установлено в AUTO, этот параметр переопределяет настройку aspect_ratio."
    },
    seed: {
      name: "seed"
    },
    style_type: {
      name: "style_type",
      tooltip: "Тип стиля для генерации (только для V2)"
    },
    turbo: {
      name: "turbo",
      tooltip: "Использовать ли turbo-режим (более быстрая генерация, возможно, с пониженным качеством)"
    }
  }
};
const IdeogramV3$1 = {
  description: "Генерирует изображения синхронно с использованием модели Ideogram V3.\n\nПоддерживает как обычную генерацию изображений по текстовым подсказкам, так и редактирование изображений с маской.\nСсылки на изображения доступны ограниченное время; если вы хотите сохранить изображение, его необходимо скачать.",
  display_name: "Ideogram V3",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio",
      tooltip: "Соотношение сторон для генерации изображения. Игнорируется, если разрешение не установлено в Авто."
    },
    control_after_generate: {
      name: "control after generate"
    },
    image: {
      name: "image",
      tooltip: "Необязательное референсное изображение для редактирования."
    },
    magic_prompt_option: {
      name: "magic_prompt_option",
      tooltip: "Определяет, использовать ли MagicPrompt при генерации"
    },
    mask: {
      name: "mask",
      tooltip: "Необязательная маска для дорисовки (белые области будут заменены)"
    },
    num_images: {
      name: "num_images"
    },
    prompt: {
      name: "prompt",
      tooltip: "Подсказка для генерации или редактирования изображения"
    },
    rendering_speed: {
      name: "rendering_speed",
      tooltip: "Управляет балансом между скоростью генерации и качеством"
    },
    resolution: {
      name: "resolution",
      tooltip: "Разрешение для генерации изображения. Если не установлено в Авто, этот параметр переопределяет aspect_ratio."
    },
    seed: {
      name: "seed"
    }
  }
};
const ImageBatch$1 = {
  display_name: "Партия изображений",
  inputs: {
    image1: {
      name: "изображение1"
    },
    image2: {
      name: "изображение2"
    }
  }
};
const ImageBlend$1 = {
  display_name: "Смешивание изображений",
  inputs: {
    blend_factor: {
      name: "фактор_смешивания"
    },
    blend_mode: {
      name: "режим_смешивания"
    },
    image1: {
      name: "изображение1"
    },
    image2: {
      name: "изображение2"
    }
  }
};
const ImageBlur$1 = {
  display_name: "Размытие изображения",
  inputs: {
    blur_radius: {
      name: "радиус_размытия"
    },
    image: {
      name: "изображение"
    },
    sigma: {
      name: "сигма"
    }
  }
};
const ImageColorToMask$1 = {
  display_name: "Цвет изображения в маску",
  inputs: {
    color: {
      name: "цвет"
    },
    image: {
      name: "изображение"
    }
  }
};
const ImageCompositeMasked$1 = {
  display_name: "Составное изображение с маской",
  inputs: {
    destination: {
      name: "назначение"
    },
    mask: {
      name: "маска"
    },
    resize_source: {
      name: "изменить_размер_источника"
    },
    source: {
      name: "источник"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const ImageCrop$1 = {
  display_name: "Обрезка изображения",
  inputs: {
    height: {
      name: "высота"
    },
    image: {
      name: "изображение"
    },
    width: {
      name: "ширина"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const ImageFromBatch$1 = {
  display_name: "Изображение из партии",
  inputs: {
    batch_index: {
      name: "индекс_пакета"
    },
    image: {
      name: "изображение"
    },
    length: {
      name: "длина"
    }
  }
};
const ImageInvert$1 = {
  display_name: "Инвертировать изображение",
  inputs: {
    image: {
      name: "изображение"
    }
  }
};
const ImageOnlyCheckpointLoader$1 = {
  display_name: "Загрузчик checkpoint только для изображения (модель img2vid)",
  inputs: {
    ckpt_name: {
      name: "название_ckpt"
    }
  }
};
const ImageOnlyCheckpointSave$1 = {
  display_name: "Сохранить только checkpoint изображения",
  inputs: {
    clip_vision: {
      name: "clip_vision"
    },
    filename_prefix: {
      name: "префикс_названия_файла"
    },
    model: {
      name: "модель"
    },
    vae: {
      name: "vae"
    }
  }
};
const ImagePadForOutpaint$1 = {
  display_name: "Добавить поля к изображению для выкрашивания",
  inputs: {
    bottom: {
      name: "снизу"
    },
    feathering: {
      name: "смягчение"
    },
    image: {
      name: "изображение"
    },
    left: {
      name: "слева"
    },
    right: {
      name: "справа"
    },
    top: {
      name: "сверху"
    }
  }
};
const ImageQuantize$1 = {
  display_name: "Квантизация изображения",
  inputs: {
    colors: {
      name: "цвета"
    },
    dither: {
      name: "дизеринг"
    },
    image: {
      name: "изображение"
    }
  }
};
const ImageRGBToYUV$1 = {
  display_name: "ImageRGBToYUV",
  inputs: {
    image: {
      name: "изображение"
    }
  },
  outputs: {
    "0": {
      name: "Y"
    },
    "1": {
      name: "U"
    },
    "2": {
      name: "V"
    }
  }
};
const ImageScale$1 = {
  display_name: "Масштабировать изображение",
  inputs: {
    crop: {
      name: "обрезка"
    },
    height: {
      name: "высота"
    },
    image: {
      name: "изображение"
    },
    upscale_method: {
      name: "метод_увеличения"
    },
    width: {
      name: "ширина"
    }
  }
};
const ImageScaleBy$1 = {
  display_name: "Масштабировать изображение на",
  inputs: {
    image: {
      name: "изображение"
    },
    scale_by: {
      name: "увеличить_на"
    },
    upscale_method: {
      name: "метод_апскейла"
    }
  }
};
const ImageScaleToTotalPixels$1 = {
  display_name: "Масштабировать изображение до общего количества пикселей",
  inputs: {
    image: {
      name: "изображение"
    },
    megapixels: {
      name: "мегапиксели"
    },
    upscale_method: {
      name: "метод_апскейла"
    }
  }
};
const ImageSharpen$1 = {
  display_name: "Резкость изображения",
  inputs: {
    alpha: {
      name: "альфа"
    },
    image: {
      name: "изображение"
    },
    sharpen_radius: {
      name: "радиус_резкости"
    },
    sigma: {
      name: "сигма"
    }
  }
};
const ImageToMask$1 = {
  display_name: "Преобразовать изображение в маску",
  inputs: {
    channel: {
      name: "канал"
    },
    image: {
      name: "изображение"
    }
  }
};
const ImageUpscaleWithModel$1 = {
  display_name: "Апскейл изображения (с использованием модели)",
  inputs: {
    image: {
      name: "изображение"
    },
    upscale_model: {
      name: "модель_апскейла"
    }
  }
};
const ImageYUVToRGB$1 = {
  display_name: "ImageYUVToRGB",
  inputs: {
    U: {
      name: "U"
    },
    V: {
      name: "V"
    },
    Y: {
      name: "Y"
    }
  }
};
const InpaintModelConditioning$1 = {
  display_name: "Кондиционирование модели инпейнтинга",
  inputs: {
    mask: {
      name: "маска"
    },
    negative: {
      name: "отрицательный"
    },
    noise_mask: {
      name: "шумовая_маска",
      tooltip: "Добавьте маску шума к латентному изображению, чтобы выборка происходила только в пределах маски. Это может улучшить результаты или полностью испортить их в зависимости от модели."
    },
    pixels: {
      name: "пиксели"
    },
    positive: {
      name: "положительный"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "положительный"
    },
    "1": {
      name: "отрицательный"
    },
    "2": {
      name: "латентный"
    }
  }
};
const InstructPixToPixConditioning$1 = {
  display_name: "Кондиционирование PixToPix",
  inputs: {
    negative: {
      name: "отрицательный"
    },
    pixels: {
      name: "пиксели"
    },
    positive: {
      name: "положительный"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "положительный"
    },
    "1": {
      name: "отрицательный"
    },
    "2": {
      name: "латентный"
    }
  }
};
const InvertMask$1 = {
  display_name: "Инвертировать маску",
  inputs: {
    mask: {
      name: "маска"
    }
  }
};
const JoinImageWithAlpha$1 = {
  display_name: "Объединить изображение с альфа-каналом",
  inputs: {
    alpha: {
      name: "альфа"
    },
    image: {
      name: "изображение"
    }
  }
};
const KSampler$1 = {
  description: "Использует предоставленную модель, положительное и отрицательное кондиционирование для удаления шума из латентного изображения.",
  display_name: "KSampler",
  inputs: {
    cfg: {
      name: "cfg",
      tooltip: "Масштаб без классификатора балансирует креативность и соблюдение запроса. Более высокие значения приводят к изображениям, более точно соответствующим запросу, однако слишком высокие значения негативно скажутся на качестве."
    },
    control_after_generate: {
      name: "control after generate"
    },
    denoise: {
      name: "шумоподавление",
      tooltip: "Количество уменьшения шума, более низкие значения сохранят структуру начального изображения, позволяя выборку изображений."
    },
    latent_image: {
      name: "латентное_изображение",
      tooltip: "Латентное изображение для уменьшения шума."
    },
    model: {
      name: "модель",
      tooltip: "Модель, используемая для уменьшения шума входного латентного изображения."
    },
    negative: {
      name: "отрицательный",
      tooltip: "Условие, описывающее атрибуты, которые вы хотите исключить из изображения."
    },
    positive: {
      name: "положительный",
      tooltip: "Условие, описывающее атрибуты, которые вы хотите включить в изображение."
    },
    sampler_name: {
      name: "название_сэмплера",
      tooltip: "Алгоритм, используемый при выборке, это может повлиять на качество, скорость и стиль сгенерированного вывода."
    },
    scheduler: {
      name: "scheduler",
      tooltip: "Scheduler контролирует, как шум постепенно удаляется для формирования изображения."
    },
    seed: {
      name: "сид",
      tooltip: "Случайный сид, используемый для создания шума."
    },
    steps: {
      name: "шаги",
      tooltip: "Количество шагов, используемых в процессе уменьшения шума."
    }
  },
  outputs: {
    "0": {
      tooltip: "шумоподавленный латент."
    }
  }
};
const KSamplerAdvanced$1 = {
  display_name: "KSampler (Расширенный)",
  inputs: {
    add_noise: {
      name: "добавить_шум"
    },
    cfg: {
      name: "cfg"
    },
    control_after_generate: {
      name: "control after generate"
    },
    end_at_step: {
      name: "закончить_на_шаге"
    },
    latent_image: {
      name: "латентное_изображение"
    },
    model: {
      name: "модель"
    },
    negative: {
      name: "отрицательный"
    },
    noise_seed: {
      name: "сид_шума"
    },
    positive: {
      name: "положительный"
    },
    return_with_leftover_noise: {
      name: "вернуться_с_оставшимся_шумом"
    },
    sampler_name: {
      name: "название_сэмплера"
    },
    scheduler: {
      name: "scheduler"
    },
    start_at_step: {
      name: "начать_с_шага"
    },
    steps: {
      name: "шаги"
    }
  }
};
const KSamplerSelect$1 = {
  display_name: "Выбор KSampler",
  inputs: {
    sampler_name: {
      name: "название_сэмплера"
    }
  }
};
const KarrasScheduler$1 = {
  display_name: "Scheduler Карраса",
  inputs: {
    rho: {
      name: "ро"
    },
    sigma_max: {
      name: "максимальное_сигма"
    },
    sigma_min: {
      name: "минимальное_сигма"
    },
    steps: {
      name: "шаги"
    }
  }
};
const KlingCameraControlI2VNode$1 = {
  description: "Преобразуйте статичные изображения в кинематографичные видео с профессиональными движениями камеры, имитирующими реальную кинематографию. Управляйте виртуальными действиями камеры, включая зум, вращение, панорамирование, наклон и вид от первого лица, сохраняя фокус на исходном изображении.",
  display_name: "Kling Image to Video (Управление камерой)",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio"
    },
    camera_control: {
      name: "camera_control",
      tooltip: "Может быть создан с помощью узла Kling Camera Controls. Управляет движением и перемещением камеры во время генерации видео."
    },
    cfg_scale: {
      name: "cfg_scale"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Негативный текстовый промпт"
    },
    prompt: {
      name: "prompt",
      tooltip: "Положительный текстовый промпт"
    },
    start_frame: {
      name: "start_frame",
      tooltip: "Референсное изображение — URL или строка в формате Base64, размер не более 10 МБ, разрешение не менее 300*300 пикселей, соотношение сторон от 1:2.5 до 2.5:1. В Base64 не должно быть префикса data:image."
    }
  },
  outputs: {
    "1": {
      name: "video_id"
    },
    "2": {
      name: "duration"
    }
  }
};
const KlingCameraControlT2VNode$1 = {
  description: "Преобразуйте текст в кинематографические видео с профессиональными движениями камеры, имитирующими реальную кинематографию. Управляйте виртуальными действиями камеры, включая зум, вращение, панорамирование, наклон и вид от первого лица, сохраняя при этом фокус на исходном тексте.",
  display_name: "Kling Текст в Видео (Управление Камерой)",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio"
    },
    camera_control: {
      name: "camera_control",
      tooltip: "Может быть создан с помощью узла Kling Camera Controls. Управляет движением и перемещением камеры во время генерации видео."
    },
    cfg_scale: {
      name: "cfg_scale"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Отрицательный текстовый запрос"
    },
    prompt: {
      name: "prompt",
      tooltip: "Положительный текстовый запрос"
    }
  },
  outputs: {
    "1": {
      name: "video_id"
    },
    "2": {
      name: "duration"
    }
  }
};
const KlingCameraControls$1 = {
  description: "Позволяет указывать параметры конфигурации для управления камерой Kling и эффектами управления движением.",
  display_name: "Управление камерой Kling",
  inputs: {
    camera_control_type: {
      name: "camera_control_type"
    },
    horizontal_movement: {
      name: "horizontal_movement",
      tooltip: "Управляет движением камеры по горизонтальной оси (ось x). Отрицательное значение — влево, положительное — вправо."
    },
    pan: {
      name: "pan",
      tooltip: "Управляет вращением камеры в вертикальной плоскости (ось x). Отрицательное значение — вращение вниз, положительное — вращение вверх."
    },
    roll: {
      name: "roll",
      tooltip: "Управляет степенью наклона камеры (ось z). Отрицательное значение — против часовой стрелки, положительное — по часовой стрелке."
    },
    tilt: {
      name: "tilt",
      tooltip: "Управляет вращением камеры в горизонтальной плоскости (ось y). Отрицательное значение — вращение влево, положительное — вращение вправо."
    },
    vertical_movement: {
      name: "vertical_movement",
      tooltip: "Управляет движением камеры по вертикальной оси (ось y). Отрицательное значение — вниз, положительное — вверх."
    },
    zoom: {
      name: "zoom",
      tooltip: "Управляет изменением фокусного расстояния камеры. Отрицательное значение — более узкий угол обзора, положительное — более широкий угол обзора."
    }
  },
  outputs: {
    "0": {
      name: "camera_control"
    }
  }
};
const KlingDualCharacterVideoEffectNode$1 = {
  description: "Достигайте различных спецэффектов при генерации видео на основе effect_scene. Первое изображение будет размещено слева, второе — справа в композиции.",
  display_name: "Kling: Видеоэффекты с двумя персонажами",
  inputs: {
    duration: {
      name: "duration"
    },
    effect_scene: {
      name: "effect_scene"
    },
    image_left: {
      name: "image_left",
      tooltip: "Изображение слева"
    },
    image_right: {
      name: "image_right",
      tooltip: "Изображение справа"
    },
    mode: {
      name: "mode"
    },
    model_name: {
      name: "model_name"
    }
  },
  outputs: {
    "1": {
      name: "duration"
    }
  }
};
const KlingImage2VideoNode$1 = {
  description: "Узел Kling Image to Video",
  display_name: "Kling Image to Video",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio"
    },
    cfg_scale: {
      name: "cfg_scale"
    },
    duration: {
      name: "duration"
    },
    mode: {
      name: "mode"
    },
    model_name: {
      name: "model_name"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Негативный текстовый запрос"
    },
    prompt: {
      name: "prompt",
      tooltip: "Положительный текстовый запрос"
    },
    start_frame: {
      name: "start_frame",
      tooltip: "Референсное изображение — URL или строка в формате Base64, не более 10 МБ, разрешение не менее 300×300 пикселей, соотношение сторон от 1:2.5 до 2.5:1. В Base64 не должно быть префикса data:image."
    }
  },
  outputs: {
    "1": {
      name: "video_id"
    },
    "2": {
      name: "duration"
    }
  }
};
const KlingImageGenerationNode$1 = {
  description: "Узел генерации изображений Kling. Генерирует изображение по текстовому запросу с необязательным референсным изображением.",
  display_name: "Генерация изображений Kling",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio"
    },
    human_fidelity: {
      name: "human_fidelity",
      tooltip: "Сходство с референсом субъекта"
    },
    image: {
      name: "image"
    },
    image_fidelity: {
      name: "image_fidelity",
      tooltip: "Интенсивность референса для загруженных пользователем изображений"
    },
    image_type: {
      name: "image_type"
    },
    model_name: {
      name: "model_name"
    },
    n: {
      name: "n",
      tooltip: "Количество сгенерированных изображений"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Отрицательный текстовый запрос"
    },
    prompt: {
      name: "prompt",
      tooltip: "Положительный текстовый запрос"
    }
  }
};
const KlingLipSyncAudioToVideoNode$1 = {
  description: "Узел Kling Lip Sync Audio to Video. Синхронизирует движения рта на видео с аудиосодержимым аудиофайла.",
  display_name: "Kling синхронизация губ в видео с аудио",
  inputs: {
    audio: {
      name: "аудио"
    },
    video: {
      name: "видео"
    },
    voice_language: {
      name: "язык голоса"
    }
  },
  outputs: {
    "1": {
      name: "video_id"
    },
    "2": {
      name: "длительность"
    }
  }
};
const KlingLipSyncTextToVideoNode$1 = {
  description: "Узел Kling Lip Sync Text to Video. Синхронизирует движения рта в видеофайле с текстовой подсказкой.",
  display_name: "Kling Синхронизация губ в видео с текстом",
  inputs: {
    text: {
      name: "текст",
      tooltip: "Текст для генерации видео с синхронизацией губ. Обязательно при режиме text2video. Максимальная длина — 120 символов."
    },
    video: {
      name: "видео"
    },
    voice: {
      name: "голос"
    },
    voice_speed: {
      name: "скорость_голоса",
      tooltip: "Скорость речи. Допустимый диапазон: 0.8~2.0, с точностью до одной десятой."
    }
  },
  outputs: {
    "1": {
      name: "video_id"
    },
    "2": {
      name: "длительность"
    }
  }
};
const KlingSingleImageVideoEffectNode$1 = {
  description: "Достигайте различных спецэффектов при генерации видео на основе effect_scene.",
  display_name: "Kling Видеоэффекты",
  inputs: {
    duration: {
      name: "duration"
    },
    effect_scene: {
      name: "effect_scene"
    },
    image: {
      name: "image",
      tooltip: "Референсное изображение. URL или строка в формате Base64 (без префикса data:image). Размер файла не должен превышать 10 МБ, разрешение не менее 300*300 пикселей, соотношение сторон от 1:2.5 до 2.5:1"
    },
    model_name: {
      name: "model_name"
    }
  },
  outputs: {
    "1": {
      name: "video_id"
    },
    "2": {
      name: "duration"
    }
  }
};
const KlingStartEndFrameNode$1 = {
  description: "Создайте видеопоследовательность, плавно переходящую между заданными начальными и конечными изображениями. Узел генерирует все промежуточные кадры, обеспечивая плавную трансформацию от первого кадра к последнему.",
  display_name: "Kling: Кадры начала и конца в видео",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio"
    },
    cfg_scale: {
      name: "cfg_scale"
    },
    end_frame: {
      name: "end_frame",
      tooltip: "Референсное изображение — контроль конечного кадра. URL или строка в формате Base64, не более 10 МБ, разрешение не менее 300×300 пикселей. В Base64 не должно быть префикса data:image."
    },
    mode: {
      name: "mode",
      tooltip: "Конфигурация для генерации видео в формате: режим / длительность / model_name."
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Негативный текстовый промпт"
    },
    prompt: {
      name: "prompt",
      tooltip: "Положительный текстовый промпт"
    },
    start_frame: {
      name: "start_frame",
      tooltip: "Референсное изображение — URL или строка в формате Base64, не более 10 МБ, разрешение не менее 300×300 пикселей, соотношение сторон от 1:2.5 до 2.5:1. В Base64 не должно быть префикса data:image."
    }
  },
  outputs: {
    "1": {
      name: "video_id"
    },
    "2": {
      name: "duration"
    }
  }
};
const KlingTextToVideoNode$1 = {
  description: "Узел Kling: текст в видео",
  display_name: "Kling: текст в видео",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio"
    },
    cfg_scale: {
      name: "cfg_scale"
    },
    mode: {
      name: "mode",
      tooltip: "Конфигурация для генерации видео в формате: режим / длительность / имя_модели."
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Отрицательный текстовый запрос"
    },
    prompt: {
      name: "prompt",
      tooltip: "Положительный текстовый запрос"
    }
  },
  outputs: {
    "1": {
      name: "video_id"
    },
    "2": {
      name: "duration"
    }
  }
};
const KlingVideoExtendNode$1 = {
  description: "Узел Kling Video Extend. Расширяет видео, созданные другими узлами Kling. video_id создаётся с помощью других узлов Kling.",
  display_name: "Kling Video Extend",
  inputs: {
    cfg_scale: {
      name: "cfg_scale"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Отрицательный текстовый запрос для указания элементов, которых следует избегать в расширенном видео"
    },
    prompt: {
      name: "prompt",
      tooltip: "Положительный текстовый запрос для управления расширением видео"
    },
    video_id: {
      name: "video_id",
      tooltip: "ID видео, которое нужно расширить. Поддерживаются видео, созданные с помощью text-to-video, image-to-video и предыдущих операций расширения видео. Общая продолжительность после расширения не может превышать 3 минуты."
    }
  },
  outputs: {
    "1": {
      name: "video_id"
    },
    "2": {
      name: "duration"
    }
  }
};
const KlingVirtualTryOnNode$1 = {
  description: "Узел Kling Виртуальная Примерка. Введите изображение человека и изображение одежды, чтобы примерить одежду на человеке.",
  display_name: "Kling Виртуальная Примерка",
  inputs: {
    cloth_image: {
      name: "cloth_image"
    },
    human_image: {
      name: "human_image"
    },
    model_name: {
      name: "model_name"
    }
  }
};
const LTXVAddGuide$1 = {
  display_name: "LTXVAddGuide",
  inputs: {
    frame_idx: {
      name: "индекс кадра",
      tooltip: "Индекс кадра для начала условия. Для однокадровых изображений или видео с 1-8 кадрами любое значение frame_idx приемлемо. Для видео с 9+ кадрами, frame_idx должен быть кратен 8, в противном случае он будет округлен вниз до ближайшего кратного 8. Отрицательные значения считаются с конца видео."
    },
    image: {
      name: "изображение",
      tooltip: "Изображение или видео для условия скрытого видео. Должно быть 8*n + 1 кадров. Если видео не 8*n + 1 кадров, оно будет обрезано до ближайших 8*n + 1 кадров."
    },
    latent: {
      name: "скрытое пространство"
    },
    negative: {
      name: "отрицательный"
    },
    positive: {
      name: "положительный"
    },
    strength: {
      name: "сила"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "положительный"
    },
    "1": {
      name: "отрицательный"
    },
    "2": {
      name: "скрытое пространство"
    }
  }
};
const LTXVConditioning$1 = {
  display_name: "Кондиционирование LTXV",
  inputs: {
    frame_rate: {
      name: "частота_кадров"
    },
    negative: {
      name: "отрицательный"
    },
    positive: {
      name: "положительный"
    }
  },
  outputs: {
    "0": {
      name: "положительный"
    },
    "1": {
      name: "отрицательный"
    }
  }
};
const LTXVCropGuides$1 = {
  display_name: "LTXVCropGuides",
  inputs: {
    latent: {
      name: "скрытое пространство"
    },
    negative: {
      name: "отрицательный"
    },
    positive: {
      name: "положительный"
    }
  },
  outputs: {
    "0": {
      name: "положительный"
    },
    "1": {
      name: "отрицательный"
    },
    "2": {
      name: "скрытое пространство"
    }
  }
};
const LTXVImgToVideo$1 = {
  display_name: "LTXVImgToVideo",
  inputs: {
    batch_size: {
      name: "размер_пакета"
    },
    height: {
      name: "высота"
    },
    image: {
      name: "изображение"
    },
    length: {
      name: "длина"
    },
    negative: {
      name: "отрицательный"
    },
    positive: {
      name: "положительный"
    },
    strength: {
      name: "интенсивность"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "ширина"
    }
  },
  outputs: {
    "0": {
      name: "положительный"
    },
    "1": {
      name: "отрицательный"
    },
    "2": {
      name: "латентный"
    }
  }
};
const LTXVPreprocess$1 = {
  display_name: "LTXVPreprocess",
  inputs: {
    image: {
      name: "изображение"
    },
    img_compression: {
      name: "сжатие изображения",
      tooltip: "Степень сжатия, применяемая к изображению."
    }
  },
  outputs: {
    "0": {
      name: "выходное изображение"
    }
  }
};
const LTXVScheduler$1 = {
  display_name: "Scheduler LTXV",
  inputs: {
    base_shift: {
      name: "базовое_смещение"
    },
    latent: {
      name: "скрытый"
    },
    max_shift: {
      name: "максимальное_смещение"
    },
    steps: {
      name: "шаги"
    },
    stretch: {
      name: "растяжение",
      tooltip: "Растянуть сигмы, чтобы они находились в диапазоне [terminal, 1]."
    },
    terminal: {
      name: "терминал",
      tooltip: "Конечное значение сигм после растяжения."
    }
  }
};
const LaplaceScheduler$1 = {
  display_name: "Scheduler Лапласа",
  inputs: {
    beta: {
      name: "бета"
    },
    mu: {
      name: "мю"
    },
    sigma_max: {
      name: "максимальное_сигма"
    },
    sigma_min: {
      name: "минимальное_сигма"
    },
    steps: {
      name: "шаги"
    }
  }
};
const LatentAdd$1 = {
  display_name: "Добавить латент",
  inputs: {
    samples1: {
      name: "образцы1"
    },
    samples2: {
      name: "образцы2"
    }
  }
};
const LatentApplyOperation$1 = {
  display_name: "Применить операцию к латенту",
  inputs: {
    operation: {
      name: "операция"
    },
    samples: {
      name: "образцы"
    }
  }
};
const LatentApplyOperationCFG$1 = {
  display_name: "Применить операцию к латенту CFG",
  inputs: {
    model: {
      name: "модель"
    },
    operation: {
      name: "операция"
    }
  }
};
const LatentBatch$1 = {
  display_name: "Партия латентов",
  inputs: {
    samples1: {
      name: "образцы1"
    },
    samples2: {
      name: "образцы2"
    }
  }
};
const LatentBatchSeedBehavior$1 = {
  display_name: "Поведение сида партии латентов",
  inputs: {
    samples: {
      name: "образцы"
    },
    seed_behavior: {
      name: "поведение_сида"
    }
  }
};
const LatentBlend$1 = {
  display_name: "Смешивание латентов",
  inputs: {
    blend_factor: {
      name: "фактор_смешивания"
    },
    samples1: {
      name: "образцы1"
    },
    samples2: {
      name: "образцы2"
    }
  }
};
const LatentComposite$1 = {
  display_name: "Составной латент",
  inputs: {
    feather: {
      name: "перо"
    },
    samples_from: {
      name: "образцы_из"
    },
    samples_to: {
      name: "образцы_для"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const LatentCompositeMasked$1 = {
  display_name: "Составной латент с маской",
  inputs: {
    destination: {
      name: "назначение"
    },
    mask: {
      name: "маска"
    },
    resize_source: {
      name: "изменить_размер_источника"
    },
    source: {
      name: "источник"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const LatentCrop$1 = {
  display_name: "Обрезка латента",
  inputs: {
    height: {
      name: "высота"
    },
    samples: {
      name: "образцы"
    },
    width: {
      name: "ширина"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const LatentFlip$1 = {
  display_name: "Перевернуть латент",
  inputs: {
    flip_method: {
      name: "метод_отражения"
    },
    samples: {
      name: "образцы"
    }
  }
};
const LatentFromBatch$1 = {
  display_name: "Латент из партии",
  inputs: {
    batch_index: {
      name: "индекс_пакета"
    },
    length: {
      name: "длина"
    },
    samples: {
      name: "образцы"
    }
  }
};
const LatentInterpolate$1 = {
  display_name: "Интерполяция латента",
  inputs: {
    ratio: {
      name: "соотношение"
    },
    samples1: {
      name: "образцы1"
    },
    samples2: {
      name: "образцы2"
    }
  }
};
const LatentMultiply$1 = {
  display_name: "Умножить латент",
  inputs: {
    multiplier: {
      name: "множитель"
    },
    samples: {
      name: "образцы"
    }
  }
};
const LatentOperationSharpen$1 = {
  display_name: "Операция латента: резкость",
  inputs: {
    alpha: {
      name: "альфа"
    },
    sharpen_radius: {
      name: "радиус_резкости"
    },
    sigma: {
      name: "сигма"
    }
  }
};
const LatentOperationTonemapReinhard$1 = {
  display_name: "Операция латента: тональная карта Рейнхарда",
  inputs: {
    multiplier: {
      name: "множитель"
    }
  }
};
const LatentRotate$1 = {
  display_name: "Повернуть латент",
  inputs: {
    rotation: {
      name: "вращение"
    },
    samples: {
      name: "образцы"
    }
  }
};
const LatentSubtract$1 = {
  display_name: "Вычесть латент",
  inputs: {
    samples1: {
      name: "образцы1"
    },
    samples2: {
      name: "образцы2"
    }
  }
};
const LatentUpscale$1 = {
  display_name: "Увеличить латент",
  inputs: {
    crop: {
      name: "обрезка"
    },
    height: {
      name: "высота"
    },
    samples: {
      name: "образцы"
    },
    upscale_method: {
      name: "метод_апскейла"
    },
    width: {
      name: "ширина"
    }
  }
};
const LatentUpscaleBy$1 = {
  display_name: "Увеличить латент на",
  inputs: {
    samples: {
      name: "образцы"
    },
    scale_by: {
      name: "масштабировать_по"
    },
    upscale_method: {
      name: "метод_апскейла"
    }
  }
};
const Load3D$1 = {
  display_name: "Загрузить 3D",
  inputs: {
    clear: {},
    height: {
      name: "высота"
    },
    image: {
      name: "изображение"
    },
    model_file: {
      name: "файл_модели"
    },
    "upload 3d model": {},
    width: {
      name: "ширина"
    }
  },
  outputs: [
    null,
    null,
    null,
    {
      name: "нормаль"
    },
    {
      name: "линеарт"
    },
    {
      name: "информация_камеры"
    }
  ]
};
const Load3DAnimation$1 = {
  display_name: "Загрузить 3D — Анимация",
  inputs: {
    clear: {},
    height: {
      name: "высота"
    },
    image: {
      name: "изображение"
    },
    model_file: {
      name: "файл_модели"
    },
    "upload 3d model": {},
    width: {
      name: "ширина"
    }
  },
  outputs: [
    null,
    null,
    null,
    {
      name: "нормаль"
    },
    {
      name: "информация_камеры"
    }
  ]
};
const LoadAudio$1 = {
  display_name: "Загрузить аудио",
  inputs: {
    audio: {
      name: "аудио"
    },
    audioUI: {
      name: "audioUI"
    },
    upload: {
      name: "выберите файл для загрузки"
    }
  }
};
const LoadImage$1 = {
  display_name: "Загрузить изображение",
  inputs: {
    image: {
      name: "изображение"
    },
    upload: {
      name: "выберите файл для загрузки"
    }
  }
};
const LoadImageMask$1 = {
  display_name: "Загрузить изображение (как маску)",
  inputs: {
    channel: {
      name: "канал"
    },
    image: {
      name: "изображение"
    },
    upload: {
      name: "выберите файл для загрузки"
    }
  }
};
const LoadImageOutput$1 = {
  description: "Загрузите изображение из папки вывода. При нажатии кнопки обновления, узел обновит список изображений и автоматически выберет первое изображение, что позволяет легко итерировать.",
  display_name: "Загрузить изображение (из выходных данных)",
  inputs: {
    image: {
      name: "изображение"
    },
    refresh: {},
    upload: {
      name: "выберите файл для загрузки"
    }
  }
};
const LoadLatent$1 = {
  display_name: "Загрузить латент",
  inputs: {
    latent: {
      name: "скрытый"
    }
  }
};
const LoadVideo$1 = {
  display_name: "Загрузить видео",
  inputs: {
    file: {
      name: "файл"
    },
    upload: {
      name: "выберите файл для загрузки"
    }
  }
};
const LoraLoader$1 = {
  description: "LoRA используются для изменения моделей диффузии и CLIP, изменяя способ, которым латенты удаляются от шума, например, применяя стили. Несколько нод LoRA могут быть связаны вместе.",
  display_name: "Загрузить LoRA",
  inputs: {
    clip: {
      name: "клип",
      tooltip: "Модель CLIP, к которой будет применена LoRA."
    },
    lora_name: {
      name: "название_lora",
      tooltip: "Название LoRA."
    },
    model: {
      name: "модель",
      tooltip: "Диффузионная модель, к которой будет применена LoRA."
    },
    strength_clip: {
      name: "сила_клипа",
      tooltip: "Насколько сильно модифицировать модель CLIP. Это значение может быть отрицательным."
    },
    strength_model: {
      name: "сила_модели",
      tooltip: "Насколько сильно модифицировать диффузионную модель. Это значение может быть отрицательным."
    }
  },
  outputs: {
    "0": {
      tooltip: "Модифицированная модель диффузии."
    },
    "1": {
      tooltip: "Модифицированная модель CLIP."
    }
  }
};
const LoraLoaderModelOnly$1 = {
  description: "LoRA используются для изменения моделей диффузии и CLIP, изменяя способ, которым латенты удаляются от шума, например, применяя стили. Несколько нод LoRA могут быть связаны вместе.",
  display_name: "Загрузчик LoRA (Только модель)",
  inputs: {
    lora_name: {
      name: "название_lora"
    },
    model: {
      name: "модель"
    },
    strength_model: {
      name: "сила_модели"
    }
  },
  outputs: {
    "0": {
      tooltip: "Модифицированная модель диффузии."
    }
  }
};
const LoraSave$1 = {
  display_name: "Извлечь и сохранить LoRA",
  inputs: {
    bias_diff: {
      name: "разница_смещения"
    },
    filename_prefix: {
      name: "префикс_названия_файла"
    },
    lora_type: {
      name: "тип_lora"
    },
    model_diff: {
      name: "разница_модели",
      tooltip: "Вывод ModelSubtract, который будет преобразован в lora."
    },
    rank: {
      name: "ранг"
    },
    text_encoder_diff: {
      name: "разница_текстового_кодировщика",
      tooltip: "Вывод CLIPSubtract, который будет преобразован в lora."
    }
  }
};
const LotusConditioning$1 = {
  display_name: "LotusConditioning",
  outputs: {
    "0": {
      name: "условие"
    }
  }
};
const LumaConceptsNode$1 = {
  description: "Содержит одну или несколько концепций камеры для использования с узлами Luma Text to Video и Luma Image to Video.",
  display_name: "Luma Концепции",
  inputs: {
    concept1: {
      name: "concept1"
    },
    concept2: {
      name: "concept2"
    },
    concept3: {
      name: "concept3"
    },
    concept4: {
      name: "concept4"
    },
    luma_concepts: {
      name: "luma_concepts",
      tooltip: "Необязательные концепции камеры для добавления к выбранным здесь."
    }
  },
  outputs: {
    "0": {
      name: "luma_concepts"
    }
  }
};
const LumaImageModifyNode$1 = {
  description: "Синхронно изменяет изображения на основе запроса и соотношения сторон.",
  display_name: "Luma Image to Image",
  inputs: {
    control_after_generate: {
      name: "контроль после генерации"
    },
    image: {
      name: "изображение"
    },
    image_weight: {
      name: "вес изображения",
      tooltip: "Вес изображения; чем ближе к 1.0, тем меньше будет изменено изображение."
    },
    model: {
      name: "модель"
    },
    prompt: {
      name: "промпт",
      tooltip: "Промпт для генерации изображения"
    },
    seed: {
      name: "seed",
      tooltip: "Seed для определения необходимости повторного запуска узла; фактические результаты недетерминированы независимо от seed."
    }
  }
};
const LumaImageNode$1 = {
  description: "Синхронно генерирует изображения на основе запроса и соотношения сторон.",
  display_name: "Luma Текст в изображение",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio"
    },
    character_image: {
      name: "character_image",
      tooltip: "Референсные изображения персонажей; может быть пакет из нескольких, учитывается до 4 изображений."
    },
    control_after_generate: {
      name: "control after generate"
    },
    image_luma_ref: {
      name: "image_luma_ref",
      tooltip: "Подключение к Luma Reference для влияния на генерацию с помощью входных изображений; может быть учтено до 4 изображений."
    },
    model: {
      name: "model"
    },
    prompt: {
      name: "prompt",
      tooltip: "Запрос для генерации изображения"
    },
    seed: {
      name: "seed",
      tooltip: "Сид для определения необходимости повторного запуска узла; фактические результаты не являются детерминированными независимо от сида."
    },
    style_image: {
      name: "style_image",
      tooltip: "Референсное изображение стиля; будет использовано только 1 изображение."
    },
    style_image_weight: {
      name: "style_image_weight",
      tooltip: "Вес изображения стиля. Игнорируется, если style_image не предоставлено."
    }
  }
};
const LumaImageToVideoNode$1 = {
  description: "Генерирует видео синхронно на основе запроса, входных изображений и output_size.",
  display_name: "Luma Image to Video",
  inputs: {
    control_after_generate: {
      name: "контроль после генерации"
    },
    duration: {
      name: "длительность"
    },
    first_image: {
      name: "первое_изображение",
      tooltip: "Первый кадр сгенерированного видео."
    },
    last_image: {
      name: "последнее_изображение",
      tooltip: "Последний кадр сгенерированного видео."
    },
    loop: {
      name: "зацикливание"
    },
    luma_concepts: {
      name: "luma_concepts",
      tooltip: "Необязательные Camera Concepts для управления движением камеры через узел Luma Concepts."
    },
    model: {
      name: "model"
    },
    prompt: {
      name: "prompt",
      tooltip: "Запрос для генерации видео"
    },
    resolution: {
      name: "разрешение"
    },
    seed: {
      name: "seed",
      tooltip: "Seed для определения необходимости повторного запуска узла; фактические результаты недетерминированы независимо от seed."
    }
  }
};
const LumaReferenceNode$1 = {
  description: "Содержит изображение и вес для использования с узлом Luma Generate Image.",
  display_name: "Luma Reference",
  inputs: {
    image: {
      name: "image",
      tooltip: "Изображение для использования в качестве эталона."
    },
    luma_ref: {
      name: "luma_ref"
    },
    weight: {
      name: "weight",
      tooltip: "Вес эталонного изображения."
    }
  },
  outputs: {
    "0": {
      name: "luma_ref"
    }
  }
};
const LumaVideoNode$1 = {
  description: "Синхронно генерирует видео на основе запроса и output_size.",
  display_name: "Luma Текст в Видео",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio"
    },
    control_after_generate: {
      name: "control after generate"
    },
    duration: {
      name: "duration"
    },
    loop: {
      name: "loop"
    },
    luma_concepts: {
      name: "luma_concepts",
      tooltip: "Необязательные Camera Concepts для управления движением камеры через узел Luma Concepts."
    },
    model: {
      name: "model"
    },
    prompt: {
      name: "prompt",
      tooltip: "Запрос для генерации видео"
    },
    resolution: {
      name: "resolution"
    },
    seed: {
      name: "seed",
      tooltip: "Seed для определения, нужно ли повторно запускать узел; фактические результаты всегда недетерминированы, независимо от seed."
    }
  }
};
const Mahiro$1 = {
  description: "Измените руководство, чтобы оно больше масштабировалось в «направлении» положительной подсказки, а не разницы между отрицательной подсказкой.",
  display_name: "Mahiro настолько мила, что заслуживает лучшей функции руководства!! (。・ω・。)",
  inputs: {
    model: {
      name: "модель"
    }
  },
  outputs: {
    "0": {
      name: "исправленная_модель"
    }
  }
};
const MaskComposite$1 = {
  display_name: "Составная маска",
  inputs: {
    destination: {
      name: "назначение"
    },
    operation: {
      name: "операция"
    },
    source: {
      name: "источник"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const MaskPreview$1 = {
  description: "Сохраняет входные изображения в ваш выходной каталог ComfyUI.",
  display_name: "MaskPreview",
  inputs: {
    mask: {
      name: "mask"
    }
  }
};
const MaskToImage$1 = {
  display_name: "Преобразовать маску в изображение",
  inputs: {
    mask: {
      name: "маска"
    }
  }
};
const MinimaxImageToVideoNode$1 = {
  description: "Генерирует видео из изображения и подсказок с помощью API MiniMax",
  display_name: "MiniMax: изображение в видео",
  inputs: {
    control_after_generate: {
      name: "контроль после генерации"
    },
    image: {
      name: "изображение",
      tooltip: "Изображение, используемое в качестве первого кадра для генерации видео"
    },
    model: {
      name: "модель",
      tooltip: "Модель, используемая для генерации видео"
    },
    prompt_text: {
      name: "текстовый промпт",
      tooltip: "Текстовая подсказка для управления генерацией видео"
    },
    seed: {
      name: "seed",
      tooltip: "Случайное зерно, используемое для создания шума."
    }
  }
};
const MinimaxTextToVideoNode$1 = {
  description: "Генерирует видео по подсказкам с помощью API MiniMax",
  display_name: "MiniMax: текст в видео",
  inputs: {
    control_after_generate: {
      name: "control after generate"
    },
    model: {
      name: "model",
      tooltip: "Модель для генерации видео"
    },
    prompt_text: {
      name: "prompt_text",
      tooltip: "Текстовая подсказка для управления генерацией видео"
    },
    seed: {
      name: "seed",
      tooltip: "Случайное зерно, используемое для создания шума."
    }
  }
};
const ModelComputeDtype$1 = {
  display_name: "ModelComputeDtype",
  inputs: {
    dtype: {
      name: "dtype"
    },
    model: {
      name: "модель"
    }
  }
};
const ModelMergeAdd$1 = {
  display_name: "Слияние моделей",
  inputs: {
    model1: {
      name: "модель1"
    },
    model2: {
      name: "модель2"
    }
  }
};
const ModelMergeAuraflow$1 = {
  display_name: "Слияние моделей Auraflow",
  inputs: {
    cond_seq_linear_: {
      name: "cond_seq_linear."
    },
    double_layers_0_: {
      name: "double_layers.0."
    },
    double_layers_1_: {
      name: "double_layers.1."
    },
    double_layers_2_: {
      name: "double_layers.2."
    },
    double_layers_3_: {
      name: "double_layers.3."
    },
    final_linear_: {
      name: "final_linear."
    },
    init_x_linear_: {
      name: "init_x_linear."
    },
    modF_: {
      name: "modF."
    },
    model1: {
      name: "модель1"
    },
    model2: {
      name: "модель2"
    },
    positional_encoding: {
      name: "позиционное кодирование"
    },
    register_tokens: {
      name: "регистрация токенов"
    },
    single_layers_0_: {
      name: "single_layers.0."
    },
    single_layers_10_: {
      name: "single_layers.10."
    },
    single_layers_11_: {
      name: "single_layers.11."
    },
    single_layers_12_: {
      name: "single_layers.12."
    },
    single_layers_13_: {
      name: "single_layers.13."
    },
    single_layers_14_: {
      name: "single_layers.14."
    },
    single_layers_15_: {
      name: "single_layers.15."
    },
    single_layers_16_: {
      name: "single_layers.16."
    },
    single_layers_17_: {
      name: "single_layers.17."
    },
    single_layers_18_: {
      name: "single_layers.18."
    },
    single_layers_19_: {
      name: "single_layers.19."
    },
    single_layers_1_: {
      name: "single_layers.1."
    },
    single_layers_20_: {
      name: "single_layers.20."
    },
    single_layers_21_: {
      name: "single_layers.21."
    },
    single_layers_22_: {
      name: "single_layers.22."
    },
    single_layers_23_: {
      name: "single_layers.23."
    },
    single_layers_24_: {
      name: "single_layers.24."
    },
    single_layers_25_: {
      name: "single_layers.25."
    },
    single_layers_26_: {
      name: "single_layers.26."
    },
    single_layers_27_: {
      name: "single_layers.27."
    },
    single_layers_28_: {
      name: "single_layers.28."
    },
    single_layers_29_: {
      name: "single_layers.29."
    },
    single_layers_2_: {
      name: "single_layers.2."
    },
    single_layers_30_: {
      name: "single_layers.30."
    },
    single_layers_31_: {
      name: "single_layers.31."
    },
    single_layers_3_: {
      name: "single_layers.3."
    },
    single_layers_4_: {
      name: "single_layers.4."
    },
    single_layers_5_: {
      name: "single_layers.5."
    },
    single_layers_6_: {
      name: "single_layers.6."
    },
    single_layers_7_: {
      name: "single_layers.7."
    },
    single_layers_8_: {
      name: "single_layers.8."
    },
    single_layers_9_: {
      name: "single_layers.9."
    },
    t_embedder_: {
      name: "t_embedder."
    }
  }
};
const ModelMergeBlocks$1 = {
  display_name: "Слияние блоков моделей",
  inputs: {
    input: {
      name: "вход"
    },
    middle: {
      name: "середина"
    },
    model1: {
      name: "модель1"
    },
    model2: {
      name: "модель2"
    },
    out: {
      name: "выход"
    }
  }
};
const ModelMergeCosmos14B$1 = {
  display_name: "ModelMergeCosmos14B",
  inputs: {
    affline_norm_: {
      name: "affline_norm."
    },
    blocks_block0_: {
      name: "blocks.block0."
    },
    blocks_block10_: {
      name: "blocks.block10."
    },
    blocks_block11_: {
      name: "blocks.block11."
    },
    blocks_block12_: {
      name: "blocks.block12."
    },
    blocks_block13_: {
      name: "blocks.block13."
    },
    blocks_block14_: {
      name: "blocks.block14."
    },
    blocks_block15_: {
      name: "blocks.block15."
    },
    blocks_block16_: {
      name: "blocks.block16."
    },
    blocks_block17_: {
      name: "blocks.block17."
    },
    blocks_block18_: {
      name: "blocks.block18."
    },
    blocks_block19_: {
      name: "blocks.block19."
    },
    blocks_block1_: {
      name: "blocks.block1."
    },
    blocks_block20_: {
      name: "blocks.block20."
    },
    blocks_block21_: {
      name: "blocks.block21."
    },
    blocks_block22_: {
      name: "blocks.block22."
    },
    blocks_block23_: {
      name: "blocks.block23."
    },
    blocks_block24_: {
      name: "blocks.block24."
    },
    blocks_block25_: {
      name: "blocks.block25."
    },
    blocks_block26_: {
      name: "blocks.block26."
    },
    blocks_block27_: {
      name: "blocks.block27."
    },
    blocks_block28_: {
      name: "blocks.block28."
    },
    blocks_block29_: {
      name: "blocks.block29."
    },
    blocks_block2_: {
      name: "blocks.block2."
    },
    blocks_block30_: {
      name: "blocks.block30."
    },
    blocks_block31_: {
      name: "blocks.block31."
    },
    blocks_block32_: {
      name: "blocks.block32."
    },
    blocks_block33_: {
      name: "blocks.block33."
    },
    blocks_block34_: {
      name: "blocks.block34."
    },
    blocks_block35_: {
      name: "blocks.block35."
    },
    blocks_block3_: {
      name: "blocks.block3."
    },
    blocks_block4_: {
      name: "blocks.block4."
    },
    blocks_block5_: {
      name: "blocks.block5."
    },
    blocks_block6_: {
      name: "blocks.block6."
    },
    blocks_block7_: {
      name: "blocks.block7."
    },
    blocks_block8_: {
      name: "blocks.block8."
    },
    blocks_block9_: {
      name: "blocks.block9."
    },
    extra_pos_embedder_: {
      name: "extra_pos_embedder."
    },
    final_layer_: {
      name: "final_layer."
    },
    model1: {
      name: "модель1"
    },
    model2: {
      name: "модель2"
    },
    pos_embedder_: {
      name: "pos_embedder."
    },
    t_embedder_: {
      name: "t_embedder."
    },
    x_embedder_: {
      name: "x_embedder."
    }
  }
};
const ModelMergeCosmos7B$1 = {
  display_name: "ModelMergeCosmos7B",
  inputs: {
    affline_norm_: {
      name: "affline_norm."
    },
    blocks_block0_: {
      name: "blocks.block0."
    },
    blocks_block10_: {
      name: "blocks.block10."
    },
    blocks_block11_: {
      name: "blocks.block11."
    },
    blocks_block12_: {
      name: "blocks.block12."
    },
    blocks_block13_: {
      name: "blocks.block13."
    },
    blocks_block14_: {
      name: "blocks.block14."
    },
    blocks_block15_: {
      name: "blocks.block15."
    },
    blocks_block16_: {
      name: "blocks.block16."
    },
    blocks_block17_: {
      name: "blocks.block17."
    },
    blocks_block18_: {
      name: "blocks.block18."
    },
    blocks_block19_: {
      name: "blocks.block19."
    },
    blocks_block1_: {
      name: "blocks.block1."
    },
    blocks_block20_: {
      name: "blocks.block20."
    },
    blocks_block21_: {
      name: "blocks.block21."
    },
    blocks_block22_: {
      name: "blocks.block22."
    },
    blocks_block23_: {
      name: "blocks.block23."
    },
    blocks_block24_: {
      name: "blocks.block24."
    },
    blocks_block25_: {
      name: "blocks.block25."
    },
    blocks_block26_: {
      name: "blocks.block26."
    },
    blocks_block27_: {
      name: "blocks.block27."
    },
    blocks_block2_: {
      name: "blocks.block2."
    },
    blocks_block3_: {
      name: "blocks.block3."
    },
    blocks_block4_: {
      name: "blocks.block4."
    },
    blocks_block5_: {
      name: "blocks.block5."
    },
    blocks_block6_: {
      name: "blocks.block6."
    },
    blocks_block7_: {
      name: "blocks.block7."
    },
    blocks_block8_: {
      name: "blocks.block8."
    },
    blocks_block9_: {
      name: "blocks.block9."
    },
    extra_pos_embedder_: {
      name: "extra_pos_embedder."
    },
    final_layer_: {
      name: "final_layer."
    },
    model1: {
      name: "model1"
    },
    model2: {
      name: "model2"
    },
    pos_embedder_: {
      name: "pos_embedder."
    },
    t_embedder_: {
      name: "t_embedder."
    },
    x_embedder_: {
      name: "x_embedder."
    }
  }
};
const ModelMergeFlux1$1 = {
  display_name: "Слияние моделей Flux1",
  inputs: {
    double_blocks_0_: {
      name: "double_blocks.0."
    },
    double_blocks_10_: {
      name: "double_blocks.10."
    },
    double_blocks_11_: {
      name: "double_blocks.11."
    },
    double_blocks_12_: {
      name: "double_blocks.12."
    },
    double_blocks_13_: {
      name: "double_blocks.13."
    },
    double_blocks_14_: {
      name: "double_blocks.14."
    },
    double_blocks_15_: {
      name: "double_blocks.15."
    },
    double_blocks_16_: {
      name: "double_blocks.16."
    },
    double_blocks_17_: {
      name: "double_blocks.17."
    },
    double_blocks_18_: {
      name: "double_blocks.18."
    },
    double_blocks_1_: {
      name: "double_blocks.1."
    },
    double_blocks_2_: {
      name: "double_blocks.2."
    },
    double_blocks_3_: {
      name: "double_blocks.3."
    },
    double_blocks_4_: {
      name: "double_blocks.4."
    },
    double_blocks_5_: {
      name: "double_blocks.5."
    },
    double_blocks_6_: {
      name: "double_blocks.6."
    },
    double_blocks_7_: {
      name: "double_blocks.7."
    },
    double_blocks_8_: {
      name: "double_blocks.8."
    },
    double_blocks_9_: {
      name: "double_blocks.9."
    },
    final_layer_: {
      name: "final_layer."
    },
    guidance_in: {
      name: "guidance_in"
    },
    img_in_: {
      name: "img_in."
    },
    model1: {
      name: "модель1"
    },
    model2: {
      name: "модель2"
    },
    single_blocks_0_: {
      name: "single_blocks.0."
    },
    single_blocks_10_: {
      name: "single_blocks.10."
    },
    single_blocks_11_: {
      name: "single_blocks.11."
    },
    single_blocks_12_: {
      name: "single_blocks.12."
    },
    single_blocks_13_: {
      name: "single_blocks.13."
    },
    single_blocks_14_: {
      name: "single_blocks.14."
    },
    single_blocks_15_: {
      name: "single_blocks.15."
    },
    single_blocks_16_: {
      name: "single_blocks.16."
    },
    single_blocks_17_: {
      name: "single_blocks.17."
    },
    single_blocks_18_: {
      name: "single_blocks.18."
    },
    single_blocks_19_: {
      name: "single_blocks.19."
    },
    single_blocks_1_: {
      name: "single_blocks.1."
    },
    single_blocks_20_: {
      name: "single_blocks.20."
    },
    single_blocks_21_: {
      name: "single_blocks.21."
    },
    single_blocks_22_: {
      name: "single_blocks.22."
    },
    single_blocks_23_: {
      name: "single_blocks.23."
    },
    single_blocks_24_: {
      name: "single_blocks.24."
    },
    single_blocks_25_: {
      name: "single_blocks.25."
    },
    single_blocks_26_: {
      name: "single_blocks.26."
    },
    single_blocks_27_: {
      name: "single_blocks.27."
    },
    single_blocks_28_: {
      name: "single_blocks.28."
    },
    single_blocks_29_: {
      name: "single_blocks.29."
    },
    single_blocks_2_: {
      name: "single_blocks.2."
    },
    single_blocks_30_: {
      name: "single_blocks.30."
    },
    single_blocks_31_: {
      name: "single_blocks.31."
    },
    single_blocks_32_: {
      name: "single_blocks.32."
    },
    single_blocks_33_: {
      name: "single_blocks.33."
    },
    single_blocks_34_: {
      name: "single_blocks.34."
    },
    single_blocks_35_: {
      name: "single_blocks.35."
    },
    single_blocks_36_: {
      name: "single_blocks.36."
    },
    single_blocks_37_: {
      name: "single_blocks.37."
    },
    single_blocks_3_: {
      name: "single_blocks.3."
    },
    single_blocks_4_: {
      name: "single_blocks.4."
    },
    single_blocks_5_: {
      name: "single_blocks.5."
    },
    single_blocks_6_: {
      name: "single_blocks.6."
    },
    single_blocks_7_: {
      name: "single_blocks.7."
    },
    single_blocks_8_: {
      name: "single_blocks.8."
    },
    single_blocks_9_: {
      name: "single_blocks.9."
    },
    time_in_: {
      name: "time_in."
    },
    txt_in_: {
      name: "txt_in."
    },
    vector_in_: {
      name: "vector_in."
    }
  }
};
const ModelMergeLTXV$1 = {
  display_name: "Слияние моделей LTXV",
  inputs: {
    adaln_single_: {
      name: "adaln_single."
    },
    caption_projection_: {
      name: "caption_projection."
    },
    model1: {
      name: "модель1"
    },
    model2: {
      name: "модель2"
    },
    patchify_proj_: {
      name: "patchify_proj."
    },
    proj_out_: {
      name: "proj_out."
    },
    scale_shift_table: {
      name: "scale_shift_table"
    },
    transformer_blocks_0_: {
      name: "transformer_blocks.0."
    },
    transformer_blocks_10_: {
      name: "transformer_blocks.10."
    },
    transformer_blocks_11_: {
      name: "transformer_blocks.11."
    },
    transformer_blocks_12_: {
      name: "transformer_blocks.12."
    },
    transformer_blocks_13_: {
      name: "transformer_blocks.13."
    },
    transformer_blocks_14_: {
      name: "transformer_blocks.14."
    },
    transformer_blocks_15_: {
      name: "transformer_blocks.15."
    },
    transformer_blocks_16_: {
      name: "transformer_blocks.16."
    },
    transformer_blocks_17_: {
      name: "transformer_blocks.17."
    },
    transformer_blocks_18_: {
      name: "transformer_blocks.18."
    },
    transformer_blocks_19_: {
      name: "transformer_blocks.19."
    },
    transformer_blocks_1_: {
      name: "transformer_blocks.1."
    },
    transformer_blocks_20_: {
      name: "transformer_blocks.20."
    },
    transformer_blocks_21_: {
      name: "transformer_blocks.21."
    },
    transformer_blocks_22_: {
      name: "transformer_blocks.22."
    },
    transformer_blocks_23_: {
      name: "transformer_blocks.23."
    },
    transformer_blocks_24_: {
      name: "transformer_blocks.24."
    },
    transformer_blocks_25_: {
      name: "transformer_blocks.25."
    },
    transformer_blocks_26_: {
      name: "transformer_blocks.26."
    },
    transformer_blocks_27_: {
      name: "transformer_blocks.27."
    },
    transformer_blocks_2_: {
      name: "transformer_blocks.2."
    },
    transformer_blocks_3_: {
      name: "transformer_blocks.3."
    },
    transformer_blocks_4_: {
      name: "transformer_blocks.4."
    },
    transformer_blocks_5_: {
      name: "transformer_blocks.5."
    },
    transformer_blocks_6_: {
      name: "transformer_blocks.6."
    },
    transformer_blocks_7_: {
      name: "transformer_blocks.7."
    },
    transformer_blocks_8_: {
      name: "transformer_blocks.8."
    },
    transformer_blocks_9_: {
      name: "transformer_blocks.9."
    }
  }
};
const ModelMergeMochiPreview$1 = {
  display_name: "Предварительный просмотр слияния моделей Mochi",
  inputs: {
    blocks_0_: {
      name: "blocks.0."
    },
    blocks_10_: {
      name: "blocks.10."
    },
    blocks_11_: {
      name: "blocks.11."
    },
    blocks_12_: {
      name: "blocks.12."
    },
    blocks_13_: {
      name: "blocks.13."
    },
    blocks_14_: {
      name: "blocks.14."
    },
    blocks_15_: {
      name: "blocks.15."
    },
    blocks_16_: {
      name: "blocks.16."
    },
    blocks_17_: {
      name: "blocks.17."
    },
    blocks_18_: {
      name: "blocks.18."
    },
    blocks_19_: {
      name: "blocks.19."
    },
    blocks_1_: {
      name: "blocks.1."
    },
    blocks_20_: {
      name: "blocks.20."
    },
    blocks_21_: {
      name: "blocks.21."
    },
    blocks_22_: {
      name: "blocks.22."
    },
    blocks_23_: {
      name: "blocks.23."
    },
    blocks_24_: {
      name: "blocks.24."
    },
    blocks_25_: {
      name: "blocks.25."
    },
    blocks_26_: {
      name: "blocks.26."
    },
    blocks_27_: {
      name: "blocks.27."
    },
    blocks_28_: {
      name: "blocks.28."
    },
    blocks_29_: {
      name: "blocks.29."
    },
    blocks_2_: {
      name: "blocks.2."
    },
    blocks_30_: {
      name: "blocks.30."
    },
    blocks_31_: {
      name: "blocks.31."
    },
    blocks_32_: {
      name: "blocks.32."
    },
    blocks_33_: {
      name: "blocks.33."
    },
    blocks_34_: {
      name: "blocks.34."
    },
    blocks_35_: {
      name: "blocks.35."
    },
    blocks_36_: {
      name: "blocks.36."
    },
    blocks_37_: {
      name: "blocks.37."
    },
    blocks_38_: {
      name: "blocks.38."
    },
    blocks_39_: {
      name: "blocks.39."
    },
    blocks_3_: {
      name: "blocks.3."
    },
    blocks_40_: {
      name: "blocks.40."
    },
    blocks_41_: {
      name: "blocks.41."
    },
    blocks_42_: {
      name: "blocks.42."
    },
    blocks_43_: {
      name: "blocks.43."
    },
    blocks_44_: {
      name: "blocks.44."
    },
    blocks_45_: {
      name: "blocks.45."
    },
    blocks_46_: {
      name: "blocks.46."
    },
    blocks_47_: {
      name: "blocks.47."
    },
    blocks_4_: {
      name: "blocks.4."
    },
    blocks_5_: {
      name: "blocks.5."
    },
    blocks_6_: {
      name: "blocks.6."
    },
    blocks_7_: {
      name: "blocks.7."
    },
    blocks_8_: {
      name: "blocks.8."
    },
    blocks_9_: {
      name: "blocks.9."
    },
    final_layer_: {
      name: "final_layer."
    },
    model1: {
      name: "модель1"
    },
    model2: {
      name: "модель2"
    },
    pos_frequencies_: {
      name: "pos_frequencies."
    },
    t5_y_embedder_: {
      name: "t5_y_embedder."
    },
    t5_yproj_: {
      name: "t5_yproj."
    },
    t_embedder_: {
      name: "t_embedder."
    }
  }
};
const ModelMergeSD1$1 = {
  display_name: "Слияние моделей SD1",
  inputs: {
    input_blocks_0_: {
      name: "input_blocks.0."
    },
    input_blocks_10_: {
      name: "input_blocks.10."
    },
    input_blocks_11_: {
      name: "input_blocks.11."
    },
    input_blocks_1_: {
      name: "input_blocks.1."
    },
    input_blocks_2_: {
      name: "input_blocks.2."
    },
    input_blocks_3_: {
      name: "input_blocks.3."
    },
    input_blocks_4_: {
      name: "input_blocks.4."
    },
    input_blocks_5_: {
      name: "input_blocks.5."
    },
    input_blocks_6_: {
      name: "input_blocks.6."
    },
    input_blocks_7_: {
      name: "input_blocks.7."
    },
    input_blocks_8_: {
      name: "input_blocks.8."
    },
    input_blocks_9_: {
      name: "input_blocks.9."
    },
    label_emb_: {
      name: "label_emb."
    },
    middle_block_0_: {
      name: "middle_block.0."
    },
    middle_block_1_: {
      name: "middle_block.1."
    },
    middle_block_2_: {
      name: "middle_block.2."
    },
    model1: {
      name: "модель1"
    },
    model2: {
      name: "модель2"
    },
    out_: {
      name: "out."
    },
    output_blocks_0_: {
      name: "output_blocks.0."
    },
    output_blocks_10_: {
      name: "output_blocks.10."
    },
    output_blocks_11_: {
      name: "output_blocks.11."
    },
    output_blocks_1_: {
      name: "output_blocks.1."
    },
    output_blocks_2_: {
      name: "output_blocks.2."
    },
    output_blocks_3_: {
      name: "output_blocks.3."
    },
    output_blocks_4_: {
      name: "output_blocks.4."
    },
    output_blocks_5_: {
      name: "output_blocks.5."
    },
    output_blocks_6_: {
      name: "output_blocks.6."
    },
    output_blocks_7_: {
      name: "output_blocks.7."
    },
    output_blocks_8_: {
      name: "output_blocks.8."
    },
    output_blocks_9_: {
      name: "output_blocks.9."
    },
    time_embed_: {
      name: "time_embed."
    }
  }
};
const ModelMergeSD2$1 = {
  display_name: "Слияние моделей SD2",
  inputs: {
    input_blocks_0_: {
      name: "input_blocks.0."
    },
    input_blocks_10_: {
      name: "input_blocks.10."
    },
    input_blocks_11_: {
      name: "input_blocks.11."
    },
    input_blocks_1_: {
      name: "input_blocks.1."
    },
    input_blocks_2_: {
      name: "input_blocks.2."
    },
    input_blocks_3_: {
      name: "input_blocks.3."
    },
    input_blocks_4_: {
      name: "input_blocks.4."
    },
    input_blocks_5_: {
      name: "input_blocks.5."
    },
    input_blocks_6_: {
      name: "input_blocks.6."
    },
    input_blocks_7_: {
      name: "input_blocks.7."
    },
    input_blocks_8_: {
      name: "input_blocks.8."
    },
    input_blocks_9_: {
      name: "input_blocks.9."
    },
    label_emb_: {
      name: "label_emb."
    },
    middle_block_0_: {
      name: "middle_block.0."
    },
    middle_block_1_: {
      name: "middle_block.1."
    },
    middle_block_2_: {
      name: "middle_block.2."
    },
    model1: {
      name: "модель1"
    },
    model2: {
      name: "модель2"
    },
    out_: {
      name: "out."
    },
    output_blocks_0_: {
      name: "output_blocks.0."
    },
    output_blocks_10_: {
      name: "output_blocks.10."
    },
    output_blocks_11_: {
      name: "output_blocks.11."
    },
    output_blocks_1_: {
      name: "output_blocks.1."
    },
    output_blocks_2_: {
      name: "output_blocks.2."
    },
    output_blocks_3_: {
      name: "output_blocks.3."
    },
    output_blocks_4_: {
      name: "output_blocks.4."
    },
    output_blocks_5_: {
      name: "output_blocks.5."
    },
    output_blocks_6_: {
      name: "output_blocks.6."
    },
    output_blocks_7_: {
      name: "output_blocks.7."
    },
    output_blocks_8_: {
      name: "output_blocks.8."
    },
    output_blocks_9_: {
      name: "output_blocks.9."
    },
    time_embed_: {
      name: "time_embed."
    }
  }
};
const ModelMergeSD35_Large$1 = {
  display_name: "Слияние моделей SD35_Large",
  inputs: {
    context_embedder_: {
      name: "context_embedder."
    },
    final_layer_: {
      name: "final_layer."
    },
    joint_blocks_0_: {
      name: "joint_blocks.0."
    },
    joint_blocks_10_: {
      name: "joint_blocks.10."
    },
    joint_blocks_11_: {
      name: "joint_blocks.11."
    },
    joint_blocks_12_: {
      name: "joint_blocks.12."
    },
    joint_blocks_13_: {
      name: "joint_blocks.13."
    },
    joint_blocks_14_: {
      name: "joint_blocks.14."
    },
    joint_blocks_15_: {
      name: "joint_blocks.15."
    },
    joint_blocks_16_: {
      name: "joint_blocks.16."
    },
    joint_blocks_17_: {
      name: "joint_blocks.17."
    },
    joint_blocks_18_: {
      name: "joint_blocks.18."
    },
    joint_blocks_19_: {
      name: "joint_blocks.19."
    },
    joint_blocks_1_: {
      name: "joint_blocks.1."
    },
    joint_blocks_20_: {
      name: "joint_blocks.20."
    },
    joint_blocks_21_: {
      name: "joint_blocks.21."
    },
    joint_blocks_22_: {
      name: "joint_blocks.22."
    },
    joint_blocks_23_: {
      name: "joint_blocks.23."
    },
    joint_blocks_24_: {
      name: "joint_blocks.24."
    },
    joint_blocks_25_: {
      name: "joint_blocks.25."
    },
    joint_blocks_26_: {
      name: "joint_blocks.26."
    },
    joint_blocks_27_: {
      name: "joint_blocks.27."
    },
    joint_blocks_28_: {
      name: "joint_blocks.28."
    },
    joint_blocks_29_: {
      name: "joint_blocks.29."
    },
    joint_blocks_2_: {
      name: "joint_blocks.2."
    },
    joint_blocks_30_: {
      name: "joint_blocks.30."
    },
    joint_blocks_31_: {
      name: "joint_blocks.31."
    },
    joint_blocks_32_: {
      name: "joint_blocks.32."
    },
    joint_blocks_33_: {
      name: "joint_blocks.33."
    },
    joint_blocks_34_: {
      name: "joint_blocks.34."
    },
    joint_blocks_35_: {
      name: "joint_blocks.35."
    },
    joint_blocks_36_: {
      name: "joint_blocks.36."
    },
    joint_blocks_37_: {
      name: "joint_blocks.37."
    },
    joint_blocks_3_: {
      name: "joint_blocks.3."
    },
    joint_blocks_4_: {
      name: "joint_blocks.4."
    },
    joint_blocks_5_: {
      name: "joint_blocks.5."
    },
    joint_blocks_6_: {
      name: "joint_blocks.6."
    },
    joint_blocks_7_: {
      name: "joint_blocks.7."
    },
    joint_blocks_8_: {
      name: "joint_blocks.8."
    },
    joint_blocks_9_: {
      name: "joint_blocks.9."
    },
    model1: {
      name: "модель1"
    },
    model2: {
      name: "модель2"
    },
    pos_embed_: {
      name: "pos_embed."
    },
    t_embedder_: {
      name: "t_embedder."
    },
    x_embedder_: {
      name: "x_embedder."
    },
    y_embedder_: {
      name: "y_embedder."
    }
  }
};
const ModelMergeSD3_2B$1 = {
  display_name: "Слияние моделей SD3_2B",
  inputs: {
    context_embedder_: {
      name: "context_embedder."
    },
    final_layer_: {
      name: "final_layer."
    },
    joint_blocks_0_: {
      name: "joint_blocks.0."
    },
    joint_blocks_10_: {
      name: "joint_blocks.10."
    },
    joint_blocks_11_: {
      name: "joint_blocks.11."
    },
    joint_blocks_12_: {
      name: "joint_blocks.12."
    },
    joint_blocks_13_: {
      name: "joint_blocks.13."
    },
    joint_blocks_14_: {
      name: "joint_blocks.14."
    },
    joint_blocks_15_: {
      name: "joint_blocks.15."
    },
    joint_blocks_16_: {
      name: "joint_blocks.16."
    },
    joint_blocks_17_: {
      name: "joint_blocks.17."
    },
    joint_blocks_18_: {
      name: "joint_blocks.18."
    },
    joint_blocks_19_: {
      name: "joint_blocks.19."
    },
    joint_blocks_1_: {
      name: "joint_blocks.1."
    },
    joint_blocks_20_: {
      name: "joint_blocks.20."
    },
    joint_blocks_21_: {
      name: "joint_blocks.21."
    },
    joint_blocks_22_: {
      name: "joint_blocks.22."
    },
    joint_blocks_23_: {
      name: "joint_blocks.23."
    },
    joint_blocks_2_: {
      name: "joint_blocks.2."
    },
    joint_blocks_3_: {
      name: "joint_blocks.3."
    },
    joint_blocks_4_: {
      name: "joint_blocks.4."
    },
    joint_blocks_5_: {
      name: "joint_blocks.5."
    },
    joint_blocks_6_: {
      name: "joint_blocks.6."
    },
    joint_blocks_7_: {
      name: "joint_blocks.7."
    },
    joint_blocks_8_: {
      name: "joint_blocks.8."
    },
    joint_blocks_9_: {
      name: "joint_blocks.9."
    },
    model1: {
      name: "модель1"
    },
    model2: {
      name: "модель2"
    },
    pos_embed_: {
      name: "pos_embed."
    },
    t_embedder_: {
      name: "t_embedder."
    },
    x_embedder_: {
      name: "x_embedder."
    },
    y_embedder_: {
      name: "y_embedder."
    }
  }
};
const ModelMergeSDXL$1 = {
  display_name: "Слияние моделей SDXL",
  inputs: {
    input_blocks_0: {
      name: "input_blocks.0"
    },
    input_blocks_1: {
      name: "input_blocks.1"
    },
    input_blocks_2: {
      name: "input_blocks.2"
    },
    input_blocks_3: {
      name: "input_blocks.3"
    },
    input_blocks_4: {
      name: "input_blocks.4"
    },
    input_blocks_5: {
      name: "input_blocks.5"
    },
    input_blocks_6: {
      name: "input_blocks.6"
    },
    input_blocks_7: {
      name: "input_blocks.7"
    },
    input_blocks_8: {
      name: "input_blocks.8"
    },
    label_emb_: {
      name: "label_emb."
    },
    middle_block_0: {
      name: "middle_block.0"
    },
    middle_block_1: {
      name: "middle_block.1"
    },
    middle_block_2: {
      name: "middle_block.2"
    },
    model1: {
      name: "модель1"
    },
    model2: {
      name: "модель2"
    },
    out_: {
      name: "out."
    },
    output_blocks_0: {
      name: "output_blocks.0"
    },
    output_blocks_1: {
      name: "output_blocks.1"
    },
    output_blocks_2: {
      name: "output_blocks.2"
    },
    output_blocks_3: {
      name: "output_blocks.3"
    },
    output_blocks_4: {
      name: "output_blocks.4"
    },
    output_blocks_5: {
      name: "output_blocks.5"
    },
    output_blocks_6: {
      name: "output_blocks.6"
    },
    output_blocks_7: {
      name: "output_blocks.7"
    },
    output_blocks_8: {
      name: "output_blocks.8"
    },
    time_embed_: {
      name: "time_embed."
    }
  }
};
const ModelMergeSimple$1 = {
  display_name: "Простое слияние моделей",
  inputs: {
    model1: {
      name: "модель1"
    },
    model2: {
      name: "модель2"
    },
    ratio: {
      name: "соотношение"
    }
  }
};
const ModelMergeSubtract$1 = {
  display_name: "Вычитание моделей",
  inputs: {
    model1: {
      name: "модель1"
    },
    model2: {
      name: "модель2"
    },
    multiplier: {
      name: "множитель"
    }
  }
};
const ModelMergeWAN2_1$1 = {
  description: "Модель 1.3B имеет 30 блоков, модель 14B — 40 блоков. Модель для преобразования изображения в видео имеет дополнительный img_emb.",
  display_name: "ModelMergeWAN2_1",
  inputs: {
    blocks_0_: {
      name: "blocks.0."
    },
    blocks_10_: {
      name: "blocks.10."
    },
    blocks_11_: {
      name: "blocks.11."
    },
    blocks_12_: {
      name: "blocks.12."
    },
    blocks_13_: {
      name: "blocks.13."
    },
    blocks_14_: {
      name: "blocks.14."
    },
    blocks_15_: {
      name: "blocks.15."
    },
    blocks_16_: {
      name: "blocks.16."
    },
    blocks_17_: {
      name: "blocks.17."
    },
    blocks_18_: {
      name: "blocks.18."
    },
    blocks_19_: {
      name: "blocks.19."
    },
    blocks_1_: {
      name: "blocks.1."
    },
    blocks_20_: {
      name: "blocks.20."
    },
    blocks_21_: {
      name: "blocks.21."
    },
    blocks_22_: {
      name: "blocks.22."
    },
    blocks_23_: {
      name: "blocks.23."
    },
    blocks_24_: {
      name: "blocks.24."
    },
    blocks_25_: {
      name: "blocks.25."
    },
    blocks_26_: {
      name: "blocks.26."
    },
    blocks_27_: {
      name: "blocks.27."
    },
    blocks_28_: {
      name: "blocks.28."
    },
    blocks_29_: {
      name: "blocks.29."
    },
    blocks_2_: {
      name: "blocks.2."
    },
    blocks_30_: {
      name: "blocks.30."
    },
    blocks_31_: {
      name: "blocks.31."
    },
    blocks_32_: {
      name: "blocks.32."
    },
    blocks_33_: {
      name: "blocks.33."
    },
    blocks_34_: {
      name: "blocks.34."
    },
    blocks_35_: {
      name: "blocks.35."
    },
    blocks_36_: {
      name: "blocks.36."
    },
    blocks_37_: {
      name: "blocks.37."
    },
    blocks_38_: {
      name: "blocks.38."
    },
    blocks_39_: {
      name: "blocks.39."
    },
    blocks_3_: {
      name: "blocks.3."
    },
    blocks_4_: {
      name: "blocks.4."
    },
    blocks_5_: {
      name: "blocks.5."
    },
    blocks_6_: {
      name: "blocks.6."
    },
    blocks_7_: {
      name: "blocks.7."
    },
    blocks_8_: {
      name: "blocks.8."
    },
    blocks_9_: {
      name: "blocks.9."
    },
    head_: {
      name: "head."
    },
    img_emb_: {
      name: "img_emb."
    },
    model1: {
      name: "model1"
    },
    model2: {
      name: "model2"
    },
    patch_embedding_: {
      name: "patch_embedding."
    },
    text_embedding_: {
      name: "text_embedding."
    },
    time_embedding_: {
      name: "time_embedding."
    },
    time_projection_: {
      name: "time_projection."
    }
  }
};
const ModelSamplingAuraFlow$1 = {
  display_name: "Выборка модели AuraFlow",
  inputs: {
    model: {
      name: "модель"
    },
    shift: {
      name: "сдвиг"
    }
  }
};
const ModelSamplingContinuousEDM$1 = {
  display_name: "Выборка модели Continuous EDM",
  inputs: {
    model: {
      name: "модель"
    },
    sampling: {
      name: "выборка"
    },
    sigma_max: {
      name: "sigma_max"
    },
    sigma_min: {
      name: "sigma_min"
    }
  }
};
const ModelSamplingContinuousV$1 = {
  display_name: "Выборка модели Continuous V",
  inputs: {
    model: {
      name: "модель"
    },
    sampling: {
      name: "выборка"
    },
    sigma_max: {
      name: "sigma_max"
    },
    sigma_min: {
      name: "sigma_min"
    }
  }
};
const ModelSamplingDiscrete$1 = {
  display_name: "Дискретная выборка модели",
  inputs: {
    model: {
      name: "модель"
    },
    sampling: {
      name: "выборка"
    },
    zsnr: {
      name: "zsnr"
    }
  }
};
const ModelSamplingFlux$1 = {
  display_name: "Выборка модели Flux",
  inputs: {
    base_shift: {
      name: "базовый_сдвиг"
    },
    height: {
      name: "высота"
    },
    max_shift: {
      name: "макс_сдвиг"
    },
    model: {
      name: "модель"
    },
    width: {
      name: "ширина"
    }
  }
};
const ModelSamplingLTXV$1 = {
  display_name: "Выборка модели LTXV",
  inputs: {
    base_shift: {
      name: "базовый_сдвиг"
    },
    latent: {
      name: "скрытый"
    },
    max_shift: {
      name: "макс_сдвиг"
    },
    model: {
      name: "модель"
    }
  }
};
const ModelSamplingSD3$1 = {
  display_name: "Выборка модели SD3",
  inputs: {
    model: {
      name: "модель"
    },
    shift: {
      name: "сдвиг"
    }
  }
};
const ModelSamplingStableCascade$1 = {
  display_name: "Выборка модели Stable Cascade",
  inputs: {
    model: {
      name: "модель"
    },
    shift: {
      name: "сдвиг"
    }
  }
};
const ModelSave$1 = {
  display_name: "Сохранить модель",
  inputs: {
    filename_prefix: {
      name: "префикс_названия_файла"
    },
    model: {
      name: "модель"
    }
  }
};
const Morphology$1 = {
  display_name: "Морфология изображения",
  inputs: {
    image: {
      name: "изображение"
    },
    kernel_size: {
      name: "размер_ядра"
    },
    operation: {
      name: "операция"
    }
  }
};
const OpenAIDalle2$1 = {
  description: "Генерирует изображения синхронно через конечную точку DALL·E 2 от OpenAI.",
  display_name: "OpenAI DALL·E 2",
  inputs: {
    control_after_generate: {
      name: "control after generate"
    },
    image: {
      name: "image",
      tooltip: "Необязательное референсное изображение для редактирования."
    },
    mask: {
      name: "mask",
      tooltip: "Необязательная маска для дорисовки (белые области будут заменены)"
    },
    n: {
      name: "n",
      tooltip: "Сколько изображений сгенерировать"
    },
    prompt: {
      name: "prompt",
      tooltip: "Текстовый запрос для DALL·E"
    },
    seed: {
      name: "seed",
      tooltip: "ещё не реализовано на сервере"
    },
    size: {
      name: "size",
      tooltip: "Размер изображения"
    }
  }
};
const OpenAIDalle3$1 = {
  description: "Генерирует изображения синхронно через конечную точку DALL·E 3 от OpenAI.",
  display_name: "OpenAI DALL·E 3",
  inputs: {
    control_after_generate: {
      name: "дополнительное управление"
    },
    prompt: {
      name: "prompt",
      tooltip: "Текстовый запрос для DALL·E"
    },
    quality: {
      name: "качество",
      tooltip: "Качество изображения"
    },
    seed: {
      name: "seed",
      tooltip: "ещё не реализовано на сервере"
    },
    size: {
      name: "размер",
      tooltip: "Размер изображения"
    },
    style: {
      name: "стиль",
      tooltip: "Яркий стиль заставляет модель создавать более гиперреалистичные и драматичные изображения. Натуральный стиль приводит к более естественным, менее гиперреалистичным изображениям."
    }
  }
};
const OpenAIGPTImage1$1 = {
  description: "Генерирует изображения синхронно через конечную точку OpenAI GPT Image 1.",
  display_name: "OpenAI GPT Image 1",
  inputs: {
    background: {
      name: "background",
      tooltip: "Возвращать изображение с фоном или без него"
    },
    control_after_generate: {
      name: "control after generate"
    },
    image: {
      name: "image",
      tooltip: "Необязательное референсное изображение для редактирования."
    },
    mask: {
      name: "mask",
      tooltip: "Необязательная маска для дорисовки (белые области будут заменены)"
    },
    n: {
      name: "n",
      tooltip: "Сколько изображений сгенерировать"
    },
    prompt: {
      name: "prompt",
      tooltip: "Текстовый запрос для GPT Image 1"
    },
    quality: {
      name: "quality",
      tooltip: "Качество изображения, влияет на стоимость и время генерации."
    },
    seed: {
      name: "seed",
      tooltip: "ещё не реализовано на сервере"
    },
    size: {
      name: "size",
      tooltip: "Размер изображения"
    }
  }
};
const OptimalStepsScheduler$1 = {
  display_name: "OptimalStepsScheduler",
  inputs: {
    denoise: {
      name: "шумоподавление"
    },
    model_type: {
      name: "model_type"
    },
    steps: {
      name: "шаги"
    }
  }
};
const PairConditioningCombine$1 = {
  display_name: "Объединение пар кондиционирования",
  inputs: {
    negative_A: {
      name: "отрицательный_A"
    },
    negative_B: {
      name: "отрицательный_B"
    },
    positive_A: {
      name: "положительный_A"
    },
    positive_B: {
      name: "положительный_B"
    }
  },
  outputs: {
    "0": {
      name: "положительный"
    },
    "1": {
      name: "отрицательный"
    }
  }
};
const PairConditioningSetDefaultCombine$1 = {
  display_name: "Установить значение по умолчанию для объединения пар кондиционирования",
  inputs: {
    hooks: {
      name: "хуки"
    },
    negative: {
      name: "отрицательный"
    },
    negative_DEFAULT: {
      name: "отрицательный_ПО_УМОЛЧАНИЮ"
    },
    positive: {
      name: "положительный"
    },
    positive_DEFAULT: {
      name: "положительный_ПО_УМОЛЧАНИЮ"
    }
  },
  outputs: {
    "0": {
      name: "положительный"
    },
    "1": {
      name: "отрицательный"
    }
  }
};
const PairConditioningSetProperties$1 = {
  display_name: "Установить свойства пар кондиционирования",
  inputs: {
    hooks: {
      name: "хуки"
    },
    mask: {
      name: "маска"
    },
    negative_NEW: {
      name: "отрицательный_НОВЫЙ"
    },
    positive_NEW: {
      name: "положительный_НОВЫЙ"
    },
    set_cond_area: {
      name: "установить_область_условия"
    },
    strength: {
      name: "сила"
    },
    timesteps: {
      name: "временные_шаги"
    }
  },
  outputs: {
    "0": {
      name: "положительный"
    },
    "1": {
      name: "отрицательный"
    }
  }
};
const PairConditioningSetPropertiesAndCombine$1 = {
  display_name: "Установить свойства пар кондиционирования и объединить",
  inputs: {
    hooks: {
      name: "хуки"
    },
    mask: {
      name: "маска"
    },
    negative: {
      name: "отрицательный"
    },
    negative_NEW: {
      name: "отрицательный_НОВЫЙ"
    },
    positive: {
      name: "положительный"
    },
    positive_NEW: {
      name: "положительный_НОВЫЙ"
    },
    set_cond_area: {
      name: "установить_область_условия"
    },
    strength: {
      name: "сила"
    },
    timesteps: {
      name: "временные_шаги"
    }
  },
  outputs: {
    "0": {
      name: "положительный"
    },
    "1": {
      name: "отрицательный"
    }
  }
};
const PatchModelAddDownscale$1 = {
  display_name: "Добавить уменьшение модели патча (Kohya Deep Shrink)",
  inputs: {
    block_number: {
      name: "номер_блока"
    },
    downscale_after_skip: {
      name: "уменьшение_после_пропуска"
    },
    downscale_factor: {
      name: "коэффициент_уменьшения"
    },
    downscale_method: {
      name: "метод_уменьшения"
    },
    end_percent: {
      name: "конечный_процент"
    },
    model: {
      name: "модель"
    },
    start_percent: {
      name: "начальный_процент"
    },
    upscale_method: {
      name: "метод_увеличения"
    }
  }
};
const PerpNeg$1 = {
  display_name: "PerpNeg (УСТАРЕЛО из-за PerpNegGuider)",
  inputs: {
    empty_conditioning: {
      name: "пустое_условие"
    },
    model: {
      name: "модель"
    },
    neg_scale: {
      name: "масштаб_отриц"
    }
  }
};
const PerpNegGuider$1 = {
  display_name: "PerpNegGuider",
  inputs: {
    cfg: {
      name: "cfg"
    },
    empty_conditioning: {
      name: "пустое_условие"
    },
    model: {
      name: "модель"
    },
    neg_scale: {
      name: "масштаб_отриц"
    },
    negative: {
      name: "отрицательный"
    },
    positive: {
      name: "положительный"
    }
  }
};
const PerturbedAttentionGuidance$1 = {
  display_name: "Направление с учётом возмущений",
  inputs: {
    model: {
      name: "модель"
    },
    scale: {
      name: "масштаб"
    }
  }
};
const PhotoMakerEncode$1 = {
  display_name: "Кодирование PhotoMaker",
  inputs: {
    clip: {
      name: "clip"
    },
    image: {
      name: "изображение"
    },
    photomaker: {
      name: "photomaker"
    },
    text: {
      name: "текст"
    }
  }
};
const PhotoMakerLoader$1 = {
  display_name: "Загрузчик PhotoMaker",
  inputs: {
    photomaker_model_name: {
      name: "название_модели_photomaker"
    }
  }
};
const PikaImageToVideoNode2_2$1 = {
  description: "Отправляет изображение и подсказку в Pika API v2.2 для генерации видео.",
  display_name: "Pika: преобразование изображения в видео",
  inputs: {
    control_after_generate: {
      name: "контроль после генерации"
    },
    duration: {
      name: "длительность"
    },
    image: {
      name: "изображение",
      tooltip: "Изображение для преобразования в видео"
    },
    negative_prompt: {
      name: "негативная подсказка"
    },
    prompt_text: {
      name: "текст подсказки"
    },
    resolution: {
      name: "разрешение"
    },
    seed: {
      name: "seed"
    }
  }
};
const PikaScenesV2_2$1 = {
  description: "Объединяйте ваши изображения для создания видео с содержащимися в них объектами. Загрузите несколько изображений в качестве ингредиентов и создайте высококачественное видео, включающее все из них.",
  display_name: "Pika Scenes (Видеокомпозиция изображений)",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio",
      tooltip: "Соотношение сторон (ширина / высота)"
    },
    control_after_generate: {
      name: "control after generate"
    },
    duration: {
      name: "duration"
    },
    image_ingredient_1: {
      name: "image_ingredient_1",
      tooltip: "Изображение, которое будет использовано как ингредиент для создания видео."
    },
    image_ingredient_2: {
      name: "image_ingredient_2",
      tooltip: "Изображение, которое будет использовано как ингредиент для создания видео."
    },
    image_ingredient_3: {
      name: "image_ingredient_3",
      tooltip: "Изображение, которое будет использовано как ингредиент для создания видео."
    },
    image_ingredient_4: {
      name: "image_ingredient_4",
      tooltip: "Изображение, которое будет использовано как ингредиент для создания видео."
    },
    image_ingredient_5: {
      name: "image_ingredient_5",
      tooltip: "Изображение, которое будет использовано как ингредиент для создания видео."
    },
    ingredients_mode: {
      name: "ingredients_mode"
    },
    negative_prompt: {
      name: "negative_prompt"
    },
    prompt_text: {
      name: "prompt_text"
    },
    resolution: {
      name: "resolution"
    },
    seed: {
      name: "seed"
    }
  }
};
const PikaStartEndFrameNode2_2$1 = {
  description: "Создайте видео, объединив первый и последний кадры. Загрузите два изображения, чтобы определить начальную и конечную точки, и позвольте ИИ создать плавный переход между ними.",
  display_name: "Pika: видео из начального и конечного кадров",
  inputs: {
    control_after_generate: {
      name: "control after generate"
    },
    duration: {
      name: "duration"
    },
    image_end: {
      name: "image_end",
      tooltip: "Последнее изображение для объединения."
    },
    image_start: {
      name: "image_start",
      tooltip: "Первое изображение для объединения."
    },
    negative_prompt: {
      name: "negative_prompt"
    },
    prompt_text: {
      name: "prompt_text"
    },
    resolution: {
      name: "resolution"
    },
    seed: {
      name: "seed"
    }
  }
};
const PikaTextToVideoNode2_2$1 = {
  description: "Отправляет текстовый запрос в Pika API v2.2 для генерации видео.",
  display_name: "Pika: Текст в видео",
  inputs: {
    aspect_ratio: {
      name: "соотношение сторон",
      tooltip: "Соотношение сторон (ширина / высота)"
    },
    control_after_generate: {
      name: "управление после генерации"
    },
    duration: {
      name: "длительность"
    },
    negative_prompt: {
      name: "negative_prompt"
    },
    prompt_text: {
      name: "prompt_text"
    },
    resolution: {
      name: "разрешение"
    },
    seed: {
      name: "seed"
    }
  }
};
const Pikadditions$1 = {
  description: "Добавьте любой объект или изображение в ваше видео. Загрузите видео и укажите, что вы хотите добавить, чтобы получить гармонично интегрированный результат.",
  display_name: "Pikadditions (Вставка объектов в видео)",
  inputs: {
    control_after_generate: {
      name: "контроль после генерации"
    },
    image: {
      name: "изображение",
      tooltip: "Изображение, которое будет добавлено в видео."
    },
    negative_prompt: {
      name: "негативный запрос"
    },
    prompt_text: {
      name: "текстовый запрос"
    },
    seed: {
      name: "seed"
    },
    video: {
      name: "видео",
      tooltip: "Видео, в которое будет добавлено изображение."
    }
  }
};
const Pikaffects$1 = {
  description: "Создайте видео с определённым Pikaffect. Поддерживаемые Pikaffects: Cake-ify, Crumble, Crush, Decapitate, Deflate, Dissolve, Explode, Eye-pop, Inflate, Levitate, Melt, Peel, Poke, Squish, Ta-da, Tear",
  display_name: "Pikaffects (Видеоэффекты)",
  inputs: {
    control_after_generate: {
      name: "контроль после генерации"
    },
    image: {
      name: "изображение",
      tooltip: "Референсное изображение, к которому будет применён Pikaffect."
    },
    negative_prompt: {
      name: "негативный запрос"
    },
    pikaffect: {
      name: "pikaffect"
    },
    prompt_text: {
      name: "текст запроса"
    },
    seed: {
      name: "seed"
    }
  }
};
const Pikaswaps$1 = {
  description: "Заменяйте любой объект или область на вашем видео новым изображением или объектом. Определяйте области для замены с помощью маски или координат.",
  display_name: "Pika Swaps (Замена объектов на видео)",
  inputs: {
    control_after_generate: {
      name: "контроль после генерации"
    },
    image: {
      name: "изображение",
      tooltip: "Изображение, используемое для замены замаскированного объекта на видео."
    },
    mask: {
      name: "маска",
      tooltip: "Используйте маску для определения областей на видео, которые нужно заменить"
    },
    negative_prompt: {
      name: "негативный запрос"
    },
    prompt_text: {
      name: "текстовый запрос"
    },
    seed: {
      name: "seed"
    },
    video: {
      name: "видео",
      tooltip: "Видео, в котором будет заменён объект."
    }
  }
};
const PixverseImageToVideoNode$1 = {
  description: "Синхронно генерирует видео на основе запроса и размера вывода.",
  display_name: "PixVerse: изображение в видео",
  inputs: {
    control_after_generate: {
      name: "контроль после генерации"
    },
    duration_seconds: {
      name: "длительность_секунды"
    },
    image: {
      name: "изображение"
    },
    motion_mode: {
      name: "режим движения"
    },
    negative_prompt: {
      name: "негативный промпт",
      tooltip: "Необязательное текстовое описание нежелательных элементов на изображении."
    },
    pixverse_template: {
      name: "pixverse_template",
      tooltip: "Необязательный шаблон для влияния на стиль генерации, созданный узлом PixVerse Template."
    },
    prompt: {
      name: "промпт",
      tooltip: "Промпт для генерации видео"
    },
    quality: {
      name: "качество"
    },
    seed: {
      name: "seed",
      tooltip: "Seed для генерации видео."
    }
  }
};
const PixverseTemplateNode$1 = {
  display_name: "Шаблон PixVerse",
  inputs: {
    template: {
      name: "шаблон"
    }
  },
  outputs: {
    "0": {
      name: "pixverse_template"
    }
  }
};
const PixverseTextToVideoNode$1 = {
  description: "Синхронно генерирует видео на основе запроса и размера вывода.",
  display_name: "PixVerse: текст в видео",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio"
    },
    control_after_generate: {
      name: "control after generate"
    },
    duration_seconds: {
      name: "duration_seconds"
    },
    motion_mode: {
      name: "motion_mode"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Необязательное текстовое описание нежелательных элементов на изображении."
    },
    pixverse_template: {
      name: "pixverse_template",
      tooltip: "Необязательный шаблон для влияния на стиль генерации, созданный узлом PixVerse Template."
    },
    prompt: {
      name: "prompt",
      tooltip: "Запрос для генерации видео"
    },
    quality: {
      name: "quality"
    },
    seed: {
      name: "seed",
      tooltip: "Сид для генерации видео."
    }
  }
};
const PixverseTransitionVideoNode$1 = {
  description: "Синхронно генерирует видео на основе запроса и размера вывода.",
  display_name: "PixVerse Переходное Видео",
  inputs: {
    control_after_generate: {
      name: "контроль после генерации"
    },
    duration_seconds: {
      name: "длительность (секунды)"
    },
    first_frame: {
      name: "первый кадр"
    },
    last_frame: {
      name: "последний кадр"
    },
    motion_mode: {
      name: "режим движения"
    },
    negative_prompt: {
      name: "негативный промпт",
      tooltip: "Необязательное текстовое описание нежелательных элементов на изображении."
    },
    prompt: {
      name: "промпт",
      tooltip: "Промпт для генерации видео"
    },
    quality: {
      name: "качество"
    },
    seed: {
      name: "seed",
      tooltip: "Seed для генерации видео."
    }
  }
};
const PolyexponentialScheduler$1 = {
  display_name: "Полиэкспоненциальный scheduler",
  inputs: {
    rho: {
      name: "ро"
    },
    sigma_max: {
      name: "макс_сигма"
    },
    sigma_min: {
      name: "мин_сигма"
    },
    steps: {
      name: "шаги"
    }
  }
};
const PorterDuffImageComposite$1 = {
  display_name: "Составное изображение Портера-Даффа",
  inputs: {
    destination: {
      name: "назначение"
    },
    destination_alpha: {
      name: "альфа_назначения"
    },
    mode: {
      name: "режим"
    },
    source: {
      name: "источник"
    },
    source_alpha: {
      name: "альфа_источника"
    }
  }
};
const Preview3D$1 = {
  display_name: "Предварительный просмотр 3D",
  inputs: {
    camera_info: {
      name: "информация_камеры"
    },
    image: {
      name: "изображение"
    },
    model_file: {
      name: "файл_модели"
    }
  }
};
const Preview3DAnimation$1 = {
  display_name: "Предварительный просмотр 3D - Анимация",
  inputs: {
    camera_info: {
      name: "camera_info"
    },
    image: {
      name: "изображение"
    },
    model_file: {
      name: "файл_модели"
    }
  }
};
const PreviewAny$1 = {
  display_name: "Предпросмотр любого",
  inputs: {
    preview: {},
    source: {
      name: "источник"
    }
  }
};
const PreviewAudio$1 = {
  display_name: "Предварительное прослушивание аудио",
  inputs: {
    audio: {
      name: "аудио"
    },
    audioUI: {
      name: "audioUI"
    }
  }
};
const PreviewImage$1 = {
  description: "Сохраняет входные изображения в вашу директорию вывода ComfyUI.",
  display_name: "Предварительный просмотр изображения",
  inputs: {
    images: {
      name: "изображения"
    }
  }
};
const PrimitiveBoolean$1 = {
  display_name: "Булево значение",
  inputs: {
    value: {
      name: "значение"
    }
  }
};
const PrimitiveFloat$1 = {
  display_name: "Число с плавающей запятой",
  inputs: {
    value: {
      name: "значение"
    }
  }
};
const PrimitiveInt$1 = {
  display_name: "Int",
  inputs: {
    control_after_generate: {
      name: "контроль после генерации"
    },
    value: {
      name: "значение"
    }
  }
};
const PrimitiveString$1 = {
  display_name: "Строка",
  inputs: {
    value: {
      name: "значение"
    }
  }
};
const PrimitiveStringMultiline$1 = {
  display_name: "Строка (многострочная)",
  inputs: {
    value: {
      name: "значение"
    }
  }
};
const QuadrupleCLIPLoader$1 = {
  description: "[Рецепты]\n\nhidream: long clip-l, long clip-g, t5xxl, llama_8b_3.1_instruct",
  display_name: "QuadrupleCLIPLoader",
  inputs: {
    clip_name1: {
      name: "clip_name1"
    },
    clip_name2: {
      name: "clip_name2"
    },
    clip_name3: {
      name: "clip_name3"
    },
    clip_name4: {
      name: "clip_name4"
    }
  }
};
const RandomNoise$1 = {
  display_name: "Случайный шум",
  inputs: {
    control_after_generate: {
      name: "контроль_после_генерации"
    },
    noise_seed: {
      name: "сид_шума"
    }
  }
};
const RebatchImages$1 = {
  display_name: "Перепаковать изображения",
  inputs: {
    batch_size: {
      name: "размер_пакета"
    },
    images: {
      name: "изображения"
    }
  }
};
const RebatchLatents$1 = {
  display_name: "Перепаковать латенты",
  inputs: {
    batch_size: {
      name: "размер_пакета"
    },
    latents: {
      name: "латенты"
    }
  }
};
const RecraftColorRGB$1 = {
  description: "Создайте Recraft Color, выбрав определённые значения RGB.",
  display_name: "Recraft Color RGB",
  inputs: {
    b: {
      name: "b",
      tooltip: "Значение синего цвета."
    },
    g: {
      name: "g",
      tooltip: "Значение зелёного цвета."
    },
    r: {
      name: "r",
      tooltip: "Значение красного цвета."
    },
    recraft_color: {
      name: "recraft_color"
    }
  },
  outputs: {
    "0": {
      name: "recraft_color"
    }
  }
};
const RecraftControls$1 = {
  description: "Создайте Recraft Controls для настройки генерации Recraft.",
  display_name: "Recraft Controls",
  inputs: {
    background_color: {
      name: "background_color"
    },
    colors: {
      name: "colors"
    }
  },
  outputs: {
    "0": {
      name: "recraft_controls"
    }
  }
};
const RecraftCreativeUpscaleNode$1 = {
  description: "Масштабирует изображение синхронно.\nУлучшает заданное растровое изображение с помощью инструмента «creative upscale», повышая разрешение с акцентом на детализацию мелких элементов и лиц.",
  display_name: "Recraft Creative Upscale Image",
  inputs: {
    image: {
      name: "изображение"
    }
  }
};
const RecraftCrispUpscaleNode$1 = {
  description: "Увеличивает изображение синхронно.\nУлучшает заданное растровое изображение с помощью инструмента «четкое увеличение», повышая разрешение, делая изображение более резким и чистым.",
  display_name: "Recraft Четкое Увеличение Изображения",
  inputs: {
    image: {
      name: "изображение"
    }
  }
};
const RecraftImageInpaintingNode$1 = {
  description: "Изменить изображение на основе запроса и маски.",
  display_name: "Восстановление изображения Recraft",
  inputs: {
    control_after_generate: {
      name: "контроль после генерации"
    },
    image: {
      name: "изображение"
    },
    mask: {
      name: "mask"
    },
    n: {
      name: "n",
      tooltip: "Количество изображений для генерации."
    },
    negative_prompt: {
      name: "негативный запрос",
      tooltip: "Необязательное текстовое описание нежелательных элементов на изображении."
    },
    prompt: {
      name: "запрос",
      tooltip: "Запрос для генерации изображения."
    },
    recraft_style: {
      name: "recraft_style"
    },
    seed: {
      name: "seed",
      tooltip: "Сид для определения необходимости повторного запуска узла; фактические результаты недетерминированы независимо от сида."
    }
  }
};
const RecraftImageToImageNode$1 = {
  description: "Изменить изображение на основе запроса и степени изменения.",
  display_name: "Recraft: Изображение в изображение",
  inputs: {
    control_after_generate: {
      name: "управление после генерации"
    },
    image: {
      name: "изображение"
    },
    n: {
      name: "n",
      tooltip: "Количество изображений для генерации."
    },
    negative_prompt: {
      name: "негативный запрос",
      tooltip: "Необязательное текстовое описание нежелательных элементов на изображении."
    },
    prompt: {
      name: "запрос",
      tooltip: "Запрос для генерации изображения."
    },
    recraft_controls: {
      name: "recraft_controls",
      tooltip: "Необязательные дополнительные параметры управления генерацией через узел Recraft Controls."
    },
    recraft_style: {
      name: "recraft_style"
    },
    seed: {
      name: "seed",
      tooltip: "Seed для определения необходимости повторного запуска узла; фактические результаты недетерминированы независимо от seed."
    },
    strength: {
      name: "степень изменения",
      tooltip: "Определяет различие с оригинальным изображением, должно быть в диапазоне [0, 1], где 0 — почти идентично, а 1 — минимальное сходство."
    }
  }
};
const RecraftRemoveBackgroundNode$1 = {
  description: "Удаляет фон с изображения и возвращает обработанное изображение и маску.",
  display_name: "Recraft Remove Background",
  inputs: {
    image: {
      name: "изображение"
    }
  }
};
const RecraftReplaceBackgroundNode$1 = {
  description: "Заменить фон на изображении на основе заданного промпта.",
  display_name: "Recraft Замена Фона",
  inputs: {
    control_after_generate: {
      name: "контроль после генерации"
    },
    image: {
      name: "изображение"
    },
    n: {
      name: "n",
      tooltip: "Количество изображений для генерации."
    },
    negative_prompt: {
      name: "негативный_промпт",
      tooltip: "Необязательное текстовое описание нежелательных элементов на изображении."
    },
    prompt: {
      name: "промпт",
      tooltip: "Промпт для генерации изображения."
    },
    recraft_style: {
      name: "recraft_style"
    },
    seed: {
      name: "seed",
      tooltip: "Сид для определения необходимости повторного запуска узла; фактические результаты недетерминированы независимо от сида."
    }
  }
};
const RecraftStyleV3DigitalIllustration$1 = {
  description: "Выберите стиль realistic_image и необязательный подстиль.",
  display_name: "Recraft Стиль - Цифровая иллюстрация",
  inputs: {
    substyle: {
      name: "подстиль"
    }
  },
  outputs: {
    "0": {
      name: "recraft_style"
    }
  }
};
const RecraftStyleV3InfiniteStyleLibrary$1 = {
  description: "Выберите стиль на основе существующего UUID из Infinite Style Library Recraft.",
  display_name: "Recraft Style - Infinite Style Library",
  inputs: {
    style_id: {
      name: "style_id",
      tooltip: "UUID стиля из Infinite Style Library."
    }
  },
  outputs: {
    "0": {
      name: "recraft_style"
    }
  }
};
const RecraftStyleV3LogoRaster$1 = {
  description: "Выберите стиль realistic_image и дополнительный подстиль (опционально).",
  display_name: "Recraft Style - Логотип Растр",
  inputs: {
    substyle: {
      name: "подстиль"
    }
  },
  outputs: {
    "0": {
      name: "recraft_style"
    }
  }
};
const RecraftStyleV3RealisticImage$1 = {
  description: "Выберите стиль realistic_image и необязательный подстиль.",
  display_name: "Recraft Style - Реалистичное изображение",
  inputs: {
    substyle: {
      name: "подстиль"
    }
  },
  outputs: {
    "0": {
      name: "recraft_style"
    }
  }
};
const RecraftTextToImageNode$1 = {
  description: "Синхронно генерирует изображения на основе запроса и разрешения.",
  display_name: "Recraft: текст в изображение",
  inputs: {
    control_after_generate: {
      name: "control after generate"
    },
    n: {
      name: "n",
      tooltip: "Количество изображений для генерации."
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Необязательное текстовое описание нежелательных элементов на изображении."
    },
    prompt: {
      name: "prompt",
      tooltip: "Запрос для генерации изображения."
    },
    recraft_controls: {
      name: "recraft_controls",
      tooltip: "Необязательные дополнительные параметры управления генерацией через узел Recraft Controls."
    },
    recraft_style: {
      name: "recraft_style"
    },
    seed: {
      name: "seed",
      tooltip: "Сид для определения необходимости повторного запуска узла; фактические результаты не являются детерминированными независимо от сида."
    },
    size: {
      name: "size",
      tooltip: "Размер сгенерированного изображения."
    }
  }
};
const RecraftTextToVectorNode$1 = {
  description: "Синхронно генерирует SVG на основе запроса и разрешения.",
  display_name: "Recraft: Текст в вектор",
  inputs: {
    control_after_generate: {
      name: "control after generate"
    },
    n: {
      name: "n",
      tooltip: "Количество изображений для генерации."
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Необязательное текстовое описание нежелательных элементов на изображении."
    },
    prompt: {
      name: "prompt",
      tooltip: "Запрос для генерации изображения."
    },
    recraft_controls: {
      name: "recraft_controls",
      tooltip: "Необязательные дополнительные параметры управления генерацией через узел Recraft Controls."
    },
    seed: {
      name: "seed",
      tooltip: "Сид для определения необходимости повторного запуска узла; фактические результаты не являются детерминированными независимо от сида."
    },
    size: {
      name: "size",
      tooltip: "Размер сгенерированного изображения."
    },
    substyle: {
      name: "substyle"
    }
  }
};
const RecraftVectorizeImageNode$1 = {
  description: "Генерирует SVG синхронно из входного изображения.",
  display_name: "Recraft Векторизация Изображения",
  inputs: {
    image: {
      name: "изображение"
    }
  }
};
const RenormCFG$1 = {
  display_name: "RenormCFG",
  inputs: {
    cfg_trunc: {
      name: "cfg_trunc"
    },
    model: {
      name: "модель"
    },
    renorm_cfg: {
      name: "renorm_cfg"
    }
  }
};
const RepeatImageBatch$1 = {
  display_name: "Повторить партию изображений",
  inputs: {
    amount: {
      name: "количество"
    },
    image: {
      name: "изображение"
    }
  }
};
const RepeatLatentBatch$1 = {
  display_name: "Повторить партию латентов",
  inputs: {
    amount: {
      name: "количество"
    },
    samples: {
      name: "образцы"
    }
  }
};
const RescaleCFG$1 = {
  display_name: "Масштабировать CFG",
  inputs: {
    model: {
      name: "модель"
    },
    multiplier: {
      name: "множитель"
    }
  }
};
const SDTurboScheduler$1 = {
  display_name: "Scheduler SDTurbo",
  inputs: {
    denoise: {
      name: "шумоподавление"
    },
    model: {
      name: "модель"
    },
    steps: {
      name: "шаги"
    }
  }
};
const SD_4XUpscale_Conditioning$1 = {
  display_name: "SD_4XUpscale_Conditioning",
  inputs: {
    images: {
      name: "изображения"
    },
    negative: {
      name: "отрицательный"
    },
    noise_augmentation: {
      name: "шумовое_увеличение"
    },
    positive: {
      name: "положительный"
    },
    scale_ratio: {
      name: "коэффициент_масштабирования"
    }
  },
  outputs: {
    "0": {
      name: "положительный"
    },
    "1": {
      name: "отрицательный"
    },
    "2": {
      name: "латентный"
    }
  }
};
const SV3D_Conditioning$1 = {
  display_name: "SV3D_Кондиционирование",
  inputs: {
    clip_vision: {
      name: "clip_vision"
    },
    elevation: {
      name: "высота"
    },
    height: {
      name: "высота"
    },
    init_image: {
      name: "начальное_изображение"
    },
    vae: {
      name: "vae"
    },
    video_frames: {
      name: "кадры_видео"
    },
    width: {
      name: "ширина"
    }
  },
  outputs: {
    "0": {
      name: "положительный"
    },
    "1": {
      name: "отрицательный"
    },
    "2": {
      name: "латентный"
    }
  }
};
const SVD_img2vid_Conditioning$1 = {
  display_name: "SVD_img2vid_Кондиционирование",
  inputs: {
    augmentation_level: {
      name: "уровень_аугментации"
    },
    clip_vision: {
      name: "clip_vision"
    },
    fps: {
      name: "fps"
    },
    height: {
      name: "высота"
    },
    init_image: {
      name: "init_image"
    },
    motion_bucket_id: {
      name: "id_корзины_движения"
    },
    vae: {
      name: "vae"
    },
    video_frames: {
      name: "кадры_видео"
    },
    width: {
      name: "ширина"
    }
  },
  outputs: {
    "0": {
      name: "положительный"
    },
    "1": {
      name: "отрицательный"
    },
    "2": {
      name: "латентный"
    }
  }
};
const SamplerCustom$1 = {
  display_name: "Пользовательский выборщик",
  inputs: {
    add_noise: {
      name: "добавить_шум"
    },
    cfg: {
      name: "cfg"
    },
    control_after_generate: {
      name: "контроль после генерации"
    },
    latent_image: {
      name: "латентное_изображение"
    },
    model: {
      name: "модель"
    },
    negative: {
      name: "отрицательный"
    },
    noise_seed: {
      name: "сид_шума"
    },
    positive: {
      name: "положительный"
    },
    sampler: {
      name: "сэмплер"
    },
    sigmas: {
      name: "сигмы"
    }
  },
  outputs: {
    "0": {
      name: "выход"
    },
    "1": {
      name: "очищенный_выход"
    }
  }
};
const SamplerCustomAdvanced$1 = {
  display_name: "Пользовательский сэмплер (Расширенный)",
  inputs: {
    guider: {
      name: "гид"
    },
    latent_image: {
      name: "латентное_изображение"
    },
    noise: {
      name: "шум"
    },
    sampler: {
      name: "сэмплер"
    },
    sigmas: {
      name: "сигмы"
    }
  },
  outputs: {
    "0": {
      name: "выход"
    },
    "1": {
      name: "очищенный_выход"
    }
  }
};
const SamplerDPMAdaptative$1 = {
  display_name: "Адаптивный сэмплер DPM",
  inputs: {
    accept_safety: {
      name: "accept_safety"
    },
    atol: {
      name: "atol"
    },
    dcoeff: {
      name: "dcoeff"
    },
    eta: {
      name: "eta"
    },
    h_init: {
      name: "h_init"
    },
    icoeff: {
      name: "icoeff"
    },
    order: {
      name: "порядок"
    },
    pcoeff: {
      name: "pcoeff"
    },
    rtol: {
      name: "rtol"
    },
    s_noise: {
      name: "s_noise"
    }
  }
};
const SamplerDPMPP_2M_SDE$1 = {
  display_name: "Сэмплер DPMPP_2M_SDE",
  inputs: {
    eta: {
      name: "eta"
    },
    noise_device: {
      name: "устройство_шума"
    },
    s_noise: {
      name: "s_noise"
    },
    solver_type: {
      name: "тип_решателя"
    }
  }
};
const SamplerDPMPP_2S_Ancestral$1 = {
  display_name: "Сэмплер DPMPP_2S_Ancestral",
  inputs: {
    eta: {
      name: "eta"
    },
    s_noise: {
      name: "s_noise"
    }
  }
};
const SamplerDPMPP_3M_SDE$1 = {
  display_name: "Сэмплер DPMPP_3M_SDE",
  inputs: {
    eta: {
      name: "eta"
    },
    noise_device: {
      name: "устройство_шума"
    },
    s_noise: {
      name: "s_noise"
    }
  }
};
const SamplerDPMPP_SDE$1 = {
  display_name: "Сэмплер DPMPP_SDE",
  inputs: {
    eta: {
      name: "eta"
    },
    noise_device: {
      name: "устройство_шума"
    },
    r: {
      name: "r"
    },
    s_noise: {
      name: "s_noise"
    }
  }
};
const SamplerEulerAncestral$1 = {
  display_name: "Сэмплер Эйлера (Анастр.)",
  inputs: {
    eta: {
      name: "eta"
    },
    s_noise: {
      name: "s_noise"
    }
  }
};
const SamplerEulerAncestralCFGPP$1 = {
  display_name: "Сэмплер Эйлера (Анастр.) CFG++",
  inputs: {
    eta: {
      name: "eta"
    },
    s_noise: {
      name: "s_noise"
    }
  }
};
const SamplerEulerCFGpp$1 = {
  display_name: "Сэмплер Эйлера CFG++",
  inputs: {
    version: {
      name: "версия"
    }
  }
};
const SamplerLCMUpscale$1 = {
  display_name: "Сэмплер LCM Upscale",
  inputs: {
    scale_ratio: {
      name: "коэффициент_масштабирования"
    },
    scale_steps: {
      name: "шаги_масштабирования"
    },
    upscale_method: {
      name: "метод_масштабирования"
    }
  }
};
const SamplerLMS$1 = {
  display_name: "Сэмплер LMS",
  inputs: {
    order: {
      name: "порядок"
    }
  }
};
const SaveAnimatedPNG$1 = {
  display_name: "Сохранить анимированный PNG",
  inputs: {
    compress_level: {
      name: "уровень_сжатия"
    },
    filename_prefix: {
      name: "префикс_названия_файла"
    },
    fps: {
      name: "fps"
    },
    images: {
      name: "изображения"
    }
  }
};
const SaveAnimatedWEBP$1 = {
  display_name: "Сохранить анимированный WEBP",
  inputs: {
    filename_prefix: {
      name: "префикс_названия_файла"
    },
    fps: {
      name: "fps"
    },
    images: {
      name: "изображения"
    },
    lossless: {
      name: "без_потерь"
    },
    method: {
      name: "метод"
    },
    quality: {
      name: "качество"
    }
  }
};
const SaveAudio$1 = {
  display_name: "Сохранить аудио",
  inputs: {
    audio: {
      name: "аудио"
    },
    audioUI: {
      name: "audioUI"
    },
    filename_prefix: {
      name: "префикс_названия_файла"
    }
  }
};
const SaveGLB$1 = {
  display_name: "SaveGLB",
  inputs: {
    filename_prefix: {
      name: "префикс_имени_файла"
    },
    image: {
      name: "изображение"
    },
    mesh: {
      name: "сетка"
    }
  }
};
const SaveImage$1 = {
  description: "Сохраняет входные изображения в вашу директорию вывода ComfyUI.",
  display_name: "Сохранить изображение",
  inputs: {
    filename_prefix: {
      name: "префикс_названия_файла",
      tooltip: "Префикс для файла, который нужно сохранить. Это может включать информацию о форматировании, такую как %date:yyyy-MM-dd% или %Empty Latent Image.width%, чтобы включить значения из нод."
    },
    images: {
      name: "изображения",
      tooltip: "Изображения_для_сохранения."
    }
  }
};
const SaveImageWebsocket$1 = {
  display_name: "Сохранить изображение через веб-сокет",
  inputs: {
    images: {
      name: "изображения"
    }
  }
};
const SaveLatent$1 = {
  display_name: "Сохранить латент",
  inputs: {
    filename_prefix: {
      name: "префикс_названия_файла"
    },
    samples: {
      name: "образцы"
    }
  }
};
const SaveSVG$1 = {
  description: "Сохранять файлы SVG на диск.",
  display_name: "Сохранить SVG",
  inputs: {
    filename_prefix: {
      name: "префикс_имени_файла",
      tooltip: "Префикс для сохраняемого файла. Может включать информацию о форматировании, такую как %date:yyyy-MM-dd% или %Empty Latent Image.width% для включения значений из узлов."
    },
    svg: {
      name: "svg"
    }
  }
};
const SaveVideo$1 = {
  description: "Сохраняет входные изображения в вашу папку вывода ComfyUI.",
  display_name: "Сохранить видео",
  inputs: {
    codec: {
      name: "кодек",
      tooltip: "Кодек для видео."
    },
    filename_prefix: {
      name: "префикс_имени_файла",
      tooltip: "Префикс для сохраняемого файла. Может включать информацию о форматировании, такую как %date:yyyy-MM-dd% или %Empty Latent Image.width% для включения значений из узлов."
    },
    format: {
      name: "формат",
      tooltip: "Формат, в котором сохранить видео."
    },
    video: {
      name: "видео",
      tooltip: "Видео для сохранения."
    }
  }
};
const SaveWEBM$1 = {
  display_name: "SaveWEBM",
  inputs: {
    codec: {
      name: "кодек"
    },
    crf: {
      name: "crf",
      tooltip: "Большее значение crf означает нижнее качество с меньшим размером файла, меньшее значение crf означает высшее качество большего размера файла."
    },
    filename_prefix: {
      name: "префикс_имени_файла"
    },
    fps: {
      name: "fps"
    },
    images: {
      name: "изображения"
    }
  }
};
const SelfAttentionGuidance$1 = {
  display_name: "Направление самовнимания",
  inputs: {
    blur_sigma: {
      name: "сигма_размытия"
    },
    model: {
      name: "модель"
    },
    scale: {
      name: "масштаб"
    }
  }
};
const SetClipHooks$1 = {
  display_name: "Установить хуки CLIP",
  inputs: {
    apply_to_conds: {
      name: "применить_к_условиям"
    },
    clip: {
      name: "клип"
    },
    hooks: {
      name: "хуки"
    },
    schedule_clip: {
      name: "schedule_clip"
    }
  }
};
const SetFirstSigma$1 = {
  display_name: "SetFirstSigma",
  inputs: {
    sigma: {
      name: "сигма"
    },
    sigmas: {
      name: "сигмы"
    }
  }
};
const SetHookKeyframes$1 = {
  display_name: "Установить ключевые кадры хука",
  inputs: {
    hook_kf: {
      name: "ключевые_кадры_хука"
    },
    hooks: {
      name: "хуки"
    }
  }
};
const SetLatentNoiseMask$1 = {
  display_name: "Установить маску шума латента",
  inputs: {
    mask: {
      name: "маска"
    },
    samples: {
      name: "образцы"
    }
  }
};
const SetUnionControlNetType$1 = {
  display_name: "Установить тип объединенного ControlNet",
  inputs: {
    control_net: {
      name: "control_net"
    },
    type: {
      name: "тип"
    }
  }
};
const SkipLayerGuidanceDiT$1 = {
  description: "Универсальная версия ноды SkipLayerGuidance, которую можно использовать на любой модели DiT.",
  display_name: "Пропустить руководство по слоям DiT",
  inputs: {
    double_layers: {
      name: "двойные_слои"
    },
    end_percent: {
      name: "конечный_процент"
    },
    model: {
      name: "модель"
    },
    rescaling_scale: {
      name: "масштаб_перемасштабирования"
    },
    scale: {
      name: "масштаб"
    },
    single_layers: {
      name: "одиночные_слои"
    },
    start_percent: {
      name: "начальный_процент"
    }
  }
};
const SkipLayerGuidanceSD3$1 = {
  description: "Универсальная версия ноды SkipLayerGuidance, которую можно использовать на любой модели DiT.",
  display_name: "Пропустить руководство по слоям SD3",
  inputs: {
    end_percent: {
      name: "конечный_процент"
    },
    layers: {
      name: "слои"
    },
    model: {
      name: "модель"
    },
    scale: {
      name: "масштаб"
    },
    start_percent: {
      name: "начальный_процент"
    }
  }
};
const SolidMask$1 = {
  display_name: "Сплошная маска",
  inputs: {
    height: {
      name: "высота"
    },
    value: {
      name: "значение"
    },
    width: {
      name: "ширина"
    }
  }
};
const SplitImageWithAlpha$1 = {
  display_name: "Разделить изображение с альфа-каналом",
  inputs: {
    image: {
      name: "изображение"
    }
  }
};
const SplitSigmas$1 = {
  display_name: "Разделить сигмы",
  inputs: {
    sigmas: {
      name: "сигмы"
    },
    step: {
      name: "шаг"
    }
  },
  outputs: {
    "0": {
      name: "высокие_сигмы"
    },
    "1": {
      name: "низкие_сигмы"
    }
  }
};
const SplitSigmasDenoise$1 = {
  display_name: "Разделить сигмы для удаления шума",
  inputs: {
    denoise: {
      name: "шумоподавление"
    },
    sigmas: {
      name: "сигмы"
    }
  },
  outputs: {
    "0": {
      name: "высокие_сигмы"
    },
    "1": {
      name: "низкие_сигмы"
    }
  }
};
const StabilityStableImageSD_3_5Node$1 = {
  description: "Генерирует изображения синхронно на основе запроса и разрешения.",
  display_name: "Stability AI Stable Diffusion 3.5 Image",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio",
      tooltip: "Соотношение сторон сгенерированного изображения."
    },
    cfg_scale: {
      name: "cfg_scale",
      tooltip: "Насколько строго процесс диффузии следует тексту запроса (более высокие значения делают изображение ближе к вашему запросу)"
    },
    control_after_generate: {
      name: "control after generate"
    },
    image: {
      name: "image"
    },
    image_denoise: {
      name: "image_denoise",
      tooltip: "Уровень удаления шума исходного изображения; 0.0 — изображение идентично входному, 1.0 — как если бы изображение не было предоставлено вовсе."
    },
    model: {
      name: "model"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Ключевые слова того, что вы не хотите видеть на выходном изображении. Это расширенная функция."
    },
    prompt: {
      name: "prompt",
      tooltip: "Что вы хотите увидеть на выходном изображении. Сильный, описательный запрос, который чётко определяет элементы, цвета и объекты, приведёт к лучшим результатам."
    },
    seed: {
      name: "seed",
      tooltip: "Случайное зерно, используемое для создания шума."
    },
    style_preset: {
      name: "style_preset",
      tooltip: "Необязательный желаемый стиль сгенерированного изображения."
    }
  }
};
const StabilityStableImageUltraNode$1 = {
  description: "Генерирует изображения синхронно на основе запроса и разрешения.",
  display_name: "Stability AI Stable Image Ultra",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio",
      tooltip: "Соотношение сторон генерируемого изображения."
    },
    control_after_generate: {
      name: "control after generate"
    },
    image: {
      name: "image"
    },
    image_denoise: {
      name: "image_denoise",
      tooltip: "Уровень удаления шума с входного изображения; 0.0 даст изображение, идентичное входному, 1.0 — как если бы изображение не было предоставлено вовсе."
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Текст, описывающий, что вы НЕ хотите видеть на выходном изображении. Это расширенная функция."
    },
    prompt: {
      name: "prompt",
      tooltip: "Что вы хотите увидеть на выходном изображении. Сильный, описательный запрос, который чётко определяет элементы, цвета и объекты, приведёт к лучшим результатам. Чтобы управлять весом определённого слова, используйте формат `(word:weight)`, где `word` — это слово, вес которого вы хотите изменить, а `weight` — значение от 0 до 1. Например: `The sky was a crisp (blue:0.3) and (green:0.8)` будет означать, что небо было синим и зелёным, но больше зелёным, чем синим."
    },
    seed: {
      name: "seed",
      tooltip: "Случайное зерно, используемое для создания шума."
    },
    style_preset: {
      name: "style_preset",
      tooltip: "Необязательный желаемый стиль генерируемого изображения."
    }
  }
};
const StabilityUpscaleConservativeNode$1 = {
  description: "Увеличивает изображение до 4K с минимальными изменениями.",
  display_name: "Stability AI Увеличение (Консервативное)",
  inputs: {
    control_after_generate: {
      name: "контроль после генерации"
    },
    creativity: {
      name: "креативность",
      tooltip: "Управляет вероятностью создания дополнительных деталей, не сильно обусловленных исходным изображением."
    },
    image: {
      name: "изображение"
    },
    negative_prompt: {
      name: "негативный промпт",
      tooltip: "Ключевые слова того, что вы не хотите видеть на выходном изображении. Это расширенная функция."
    },
    prompt: {
      name: "промпт",
      tooltip: "Что вы хотите видеть на выходном изображении. Сильный, описательный промпт, чётко определяющий элементы, цвета и объекты, приведёт к лучшим результатам."
    },
    seed: {
      name: "seed",
      tooltip: "Случайное значение seed, используемое для создания шума."
    }
  }
};
const StabilityUpscaleCreativeNode$1 = {
  description: "Увеличение изображения до 4K разрешения с минимальными изменениями.",
  display_name: "Stability AI Upscale Creative",
  inputs: {
    control_after_generate: {
      name: "контроль после генерации"
    },
    creativity: {
      name: "креативность",
      tooltip: "Управляет вероятностью создания дополнительных деталей, не сильно обусловленных исходным изображением."
    },
    image: {
      name: "изображение"
    },
    negative_prompt: {
      name: "негативный промпт",
      tooltip: "Ключевые слова того, что вы не хотите видеть на выходном изображении. Это расширенная функция."
    },
    prompt: {
      name: "промпт",
      tooltip: "Что вы хотите видеть на выходном изображении. Сильный, описательный промпт, чётко определяющий элементы, цвета и объекты, приведёт к лучшим результатам."
    },
    seed: {
      name: "seed",
      tooltip: "Случайное значение, используемое для создания шума."
    },
    style_preset: {
      name: "стиль",
      tooltip: "Необязательный желаемый стиль сгенерированного изображения."
    }
  }
};
const StabilityUpscaleFastNode$1 = {
  description: "Быстро увеличивает изображение через Stability API до 4x от исходного размера; предназначено для увеличения изображений низкого качества или сжатых изображений.",
  display_name: "Stability AI Быстрое Увеличение",
  inputs: {
    image: {
      name: "изображение"
    }
  }
};
const StableCascade_EmptyLatentImage$1 = {
  display_name: "StableCascade_Пустое латентное изображение",
  inputs: {
    batch_size: {
      name: "размер_пакета"
    },
    compression: {
      name: "сжатие"
    },
    height: {
      name: "высота"
    },
    width: {
      name: "ширина"
    }
  },
  outputs: {
    "0": {
      name: "этап_c"
    },
    "1": {
      name: "этап_b"
    }
  }
};
const StableCascade_StageB_Conditioning$1 = {
  display_name: "StableCascade_Этап B_Кондиционирование",
  inputs: {
    conditioning: {
      name: "кондиционирование"
    },
    stage_c: {
      name: "стадия_c"
    }
  }
};
const StableCascade_StageC_VAEEncode$1 = {
  display_name: "StableCascade_Этап C_VAE Кодирование",
  inputs: {
    compression: {
      name: "сжатие"
    },
    image: {
      name: "изображение"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "этап_c"
    },
    "1": {
      name: "этап_b"
    }
  }
};
const StableCascade_SuperResolutionControlnet$1 = {
  display_name: "StableCascade_Суперразрешение Controlnet",
  inputs: {
    image: {
      name: "изображение"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "вход_controlnet"
    },
    "1": {
      name: "этап_c"
    },
    "2": {
      name: "этап_b"
    }
  }
};
const StableZero123_Conditioning$1 = {
  display_name: "StableZero123_Кондиционирование",
  inputs: {
    azimuth: {
      name: "азимут"
    },
    batch_size: {
      name: "размер_пакета"
    },
    clip_vision: {
      name: "clip_vision"
    },
    elevation: {
      name: "высота"
    },
    height: {
      name: "высота"
    },
    init_image: {
      name: "начальное_изображение"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "ширина"
    }
  },
  outputs: {
    "0": {
      name: "положительный"
    },
    "1": {
      name: "отрицательный"
    },
    "2": {
      name: "латентный"
    }
  }
};
const StableZero123_Conditioning_Batched$1 = {
  display_name: "StableZero123_Кондиционирование_Пакетное",
  inputs: {
    azimuth: {
      name: "азимут"
    },
    azimuth_batch_increment: {
      name: "инкремент_азимута_пакета"
    },
    batch_size: {
      name: "размер_пакета"
    },
    clip_vision: {
      name: "clip_vision"
    },
    elevation: {
      name: "высота"
    },
    elevation_batch_increment: {
      name: "инкремент_высоты_пакета"
    },
    height: {
      name: "высота"
    },
    init_image: {
      name: "начальное_изображение"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "ширина"
    }
  },
  outputs: {
    "0": {
      name: "положительный"
    },
    "1": {
      name: "отрицательный"
    },
    "2": {
      name: "латентный"
    }
  }
};
const StyleModelApply$1 = {
  display_name: "Применить модель стиля",
  inputs: {
    clip_vision_output: {
      name: "выход_clip_vision"
    },
    conditioning: {
      name: "кондиционирование"
    },
    strength: {
      name: "сила"
    },
    strength_type: {
      name: "тип_силы"
    },
    style_model: {
      name: "модель_стиля"
    }
  }
};
const StyleModelLoader$1 = {
  display_name: "Загрузить модель стиля",
  inputs: {
    style_model_name: {
      name: "название_модели_стиля"
    }
  }
};
const T5TokenizerOptions$1 = {
  display_name: "T5TokenizerOptions",
  inputs: {
    clip: {
      name: "clip"
    },
    min_length: {
      name: "минимальная_длина"
    },
    min_padding: {
      name: "минимальное_дополнение"
    }
  }
};
const TextEncodeHunyuanVideo_ImageToVideo$1 = {
  display_name: "TextEncodeHunyuanVideo_ImageToVideo",
  inputs: {
    clip: {
      name: "clip"
    },
    clip_vision_output: {
      name: "выход clip_vision"
    },
    image_interleave: {
      name: "перемежение изображения",
      tooltip: "Насколько сильно изображение влияет на текстовую подсказку. Чем выше число, тем больше влияние от текстовой подсказки."
    },
    prompt: {
      name: "подсказка"
    }
  }
};
const ThresholdMask$1 = {
  display_name: "Пороговая маска",
  inputs: {
    mask: {
      name: "маска"
    },
    value: {
      name: "значение"
    }
  }
};
const TomePatchModel$1 = {
  display_name: "Модель патча Tome",
  inputs: {
    model: {
      name: "модель"
    },
    ratio: {
      name: "соотношение"
    }
  }
};
const TorchCompileModel$1 = {
  display_name: "Скомпилировать модель Torch",
  inputs: {
    backend: {
      name: "бэкенд"
    },
    model: {
      name: "модель"
    }
  }
};
const TrimVideoLatent$1 = {
  display_name: "TrimVideoLatent",
  inputs: {
    samples: {
      name: "samples"
    },
    trim_amount: {
      name: "обрезать_на"
    }
  }
};
const TripleCLIPLoader$1 = {
  description: "[Рецепты]\n\nsd3: clip-l, clip-g, t5",
  display_name: "Тройной загрузчик CLIP",
  inputs: {
    clip_name1: {
      name: "clip_name1"
    },
    clip_name2: {
      name: "clip_name2"
    },
    clip_name3: {
      name: "clip_name3"
    }
  }
};
const UNETLoader$1 = {
  display_name: "Загрузить модель диффузии",
  inputs: {
    unet_name: {
      name: "название_unet"
    },
    weight_dtype: {
      name: "тип_данных_веса"
    }
  }
};
const UNetCrossAttentionMultiply$1 = {
  display_name: "Умножение перекрёстного внимания UNet",
  inputs: {
    k: {
      name: "k"
    },
    model: {
      name: "модель"
    },
    out: {
      name: "выход"
    },
    q: {
      name: "q"
    },
    v: {
      name: "v"
    }
  }
};
const UNetSelfAttentionMultiply$1 = {
  display_name: "Умножение самовнимания UNet",
  inputs: {
    k: {
      name: "k"
    },
    model: {
      name: "модель"
    },
    out: {
      name: "выход"
    },
    q: {
      name: "q"
    },
    v: {
      name: "v"
    }
  }
};
const UNetTemporalAttentionMultiply$1 = {
  display_name: "Умножение временного внимания UNet",
  inputs: {
    cross_structural: {
      name: "кросс-структурный"
    },
    cross_temporal: {
      name: "кросс-временной"
    },
    model: {
      name: "модель"
    },
    self_structural: {
      name: "самоструктурный"
    },
    self_temporal: {
      name: "самовременный"
    }
  }
};
const UpscaleModelLoader$1 = {
  display_name: "Загрузить модель апскейла",
  inputs: {
    model_name: {
      name: "название_модели"
    }
  }
};
const VAEDecode$1 = {
  description: "Декодирует латентные изображения обратно в изображения в пиксельном пространстве.",
  display_name: "Декодировать VAE",
  inputs: {
    samples: {
      name: "образцы",
      tooltip: "Латентное изображение для декодирования."
    },
    vae: {
      name: "vae",
      tooltip: "Модель VAE, используемая для декодирования латентного изображения."
    }
  },
  outputs: {
    "0": {
      tooltip: "Декодированное изображение."
    }
  }
};
const VAEDecodeAudio$1 = {
  display_name: "Декодировать аудио VAE",
  inputs: {
    samples: {
      name: "образцы"
    },
    vae: {
      name: "vae"
    }
  }
};
const VAEDecodeHunyuan3D$1 = {
  display_name: "VAEDecodeHunyuan3D",
  inputs: {
    num_chunks: {
      name: "количество_частей"
    },
    octree_resolution: {
      name: "разрешение_октодерева"
    },
    samples: {
      name: "образцы"
    },
    vae: {
      name: "vae"
    }
  }
};
const VAEDecodeTiled$1 = {
  display_name: "Декодировать VAE (плитками)",
  inputs: {
    overlap: {
      name: "перекрытие"
    },
    samples: {
      name: "образцы"
    },
    temporal_overlap: {
      name: "temporal_overlap",
      tooltip: "Используется только для видео VAE: количество кадров для перекрытия."
    },
    temporal_size: {
      name: "temporal_size",
      tooltip: "Используется только для видео VAE: количество кадров для декодирования за раз."
    },
    tile_size: {
      name: "размер_плитки"
    },
    vae: {
      name: "vae"
    }
  }
};
const VAEEncode$1 = {
  display_name: "Кодировать VAE",
  inputs: {
    pixels: {
      name: "пиксели"
    },
    vae: {
      name: "vae"
    }
  }
};
const VAEEncodeAudio$1 = {
  display_name: "Кодировать аудио VAE",
  inputs: {
    audio: {
      name: "аудио"
    },
    vae: {
      name: "vae"
    }
  }
};
const VAEEncodeForInpaint$1 = {
  display_name: "Кодировать VAE (для инпейнтинга)",
  inputs: {
    grow_mask_by: {
      name: "увеличить_маску_на"
    },
    mask: {
      name: "маска"
    },
    pixels: {
      name: "пиксели"
    },
    vae: {
      name: "vae"
    }
  }
};
const VAEEncodeTiled$1 = {
  display_name: "Кодировать VAE (плитками)",
  inputs: {
    overlap: {
      name: "перекрытие"
    },
    pixels: {
      name: "пиксели"
    },
    temporal_overlap: {
      name: "temporal_overlap",
      tooltip: "Используется только для видео VAEs: количество кадров для перекрытия."
    },
    temporal_size: {
      name: "temporal_size",
      tooltip: "Используется только для видео VAEs: количество кадров для кодирования за один раз."
    },
    tile_size: {
      name: "размер_плитки"
    },
    vae: {
      name: "vae"
    }
  }
};
const VAELoader$1 = {
  display_name: "Загрузить VAE",
  inputs: {
    vae_name: {
      name: "название_vae"
    }
  }
};
const VAESave$1 = {
  display_name: "Сохранить VAE",
  inputs: {
    filename_prefix: {
      name: "префикс_названия_файла"
    },
    vae: {
      name: "vae"
    }
  }
};
const VPScheduler$1 = {
  display_name: "VPScheduler",
  inputs: {
    beta_d: {
      name: "beta_d"
    },
    beta_min: {
      name: "beta_min"
    },
    eps_s: {
      name: "eps_s"
    },
    steps: {
      name: "шаги"
    }
  }
};
const VeoVideoGenerationNode$1 = {
  description: "Генерирует видео по текстовым подсказкам с помощью Google Veo API",
  display_name: "Google Veo2 Генерация видео",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio",
      tooltip: "Соотношение сторон выходного видео"
    },
    control_after_generate: {
      name: "control after generate"
    },
    duration_seconds: {
      name: "duration_seconds",
      tooltip: "Длительность выходного видео в секундах"
    },
    enhance_prompt: {
      name: "enhance_prompt",
      tooltip: "Улучшать ли подсказку с помощью ИИ"
    },
    image: {
      name: "image",
      tooltip: "Необязательное референсное изображение для направления генерации видео"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "Негативная текстовая подсказка для указания, чего избегать в видео"
    },
    person_generation: {
      name: "person_generation",
      tooltip: "Разрешить ли генерацию людей в видео"
    },
    prompt: {
      name: "prompt",
      tooltip: "Текстовое описание видео"
    },
    seed: {
      name: "seed",
      tooltip: "Сид для генерации видео (0 — случайный)"
    }
  }
};
const VideoLinearCFGGuidance$1 = {
  display_name: "Направление Video Linear CFG",
  inputs: {
    min_cfg: {
      name: "мин_cfg"
    },
    model: {
      name: "модель"
    }
  }
};
const VideoTriangleCFGGuidance$1 = {
  display_name: "Направление Video Triangle CFG",
  inputs: {
    min_cfg: {
      name: "мин_cfg"
    },
    model: {
      name: "модель"
    }
  }
};
const VoxelToMesh$1 = {
  display_name: "VoxelToMesh",
  inputs: {
    algorithm: {
      name: "алгоритм"
    },
    threshold: {
      name: "порог"
    },
    voxel: {
      name: "voxel"
    }
  }
};
const VoxelToMeshBasic$1 = {
  display_name: "VoxelToMeshBasic",
  inputs: {
    threshold: {
      name: "порог"
    },
    voxel: {
      name: "воксель"
    }
  }
};
const WanFirstLastFrameToVideo$1 = {
  display_name: "WanFirstLastFrameToVideo",
  inputs: {
    batch_size: {
      name: "размер_пакета"
    },
    clip_vision_end_image: {
      name: "clip_vision_end_image"
    },
    clip_vision_start_image: {
      name: "clip_vision_start_image"
    },
    end_image: {
      name: "конечное_изображение"
    },
    height: {
      name: "высота"
    },
    length: {
      name: "длина"
    },
    negative: {
      name: "отрицательный"
    },
    positive: {
      name: "положительный"
    },
    start_image: {
      name: "начальное_изображение"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "ширина"
    }
  },
  outputs: {
    "0": {
      name: "положительный"
    },
    "1": {
      name: "отрицательный"
    },
    "2": {
      name: "latent"
    }
  }
};
const WanFunControlToVideo$1 = {
  display_name: "WanFunControlToVideo",
  inputs: {
    batch_size: {
      name: "размер_пакета"
    },
    clip_vision_output: {
      name: "clip_vision_output"
    },
    control_video: {
      name: "control_video"
    },
    height: {
      name: "высота"
    },
    length: {
      name: "длина"
    },
    negative: {
      name: "негативный"
    },
    positive: {
      name: "позитивный"
    },
    start_image: {
      name: "стартовое_изображение"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "ширина"
    }
  },
  outputs: {
    "0": {
      name: "позитивный"
    },
    "1": {
      name: "негативный"
    },
    "2": {
      name: "латентный"
    }
  }
};
const WanFunInpaintToVideo$1 = {
  display_name: "WanFunInpaintToVideo",
  inputs: {
    batch_size: {
      name: "размер_пакета"
    },
    clip_vision_output: {
      name: "clip_vision_output"
    },
    end_image: {
      name: "конечное_изображение"
    },
    height: {
      name: "высота"
    },
    length: {
      name: "длина"
    },
    negative: {
      name: "негативный"
    },
    positive: {
      name: "позитивный"
    },
    start_image: {
      name: "начальное_изображение"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "ширина"
    }
  },
  outputs: {
    "0": {
      name: "позитивный"
    },
    "1": {
      name: "негативный"
    },
    "2": {
      name: "latent"
    }
  }
};
const WanImageToVideo$1 = {
  display_name: "WanИзображениеВВидео",
  inputs: {
    batch_size: {
      name: "размер_пакета"
    },
    clip_vision_output: {
      name: "clip_vision_output"
    },
    height: {
      name: "высота"
    },
    length: {
      name: "длина"
    },
    negative: {
      name: "отрицательный"
    },
    positive: {
      name: "положительный"
    },
    start_image: {
      name: "начальное_изображение"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "ширина"
    }
  },
  outputs: {
    "0": {
      name: "положительный"
    },
    "1": {
      name: "отрицательный"
    },
    "2": {
      name: "latent"
    }
  }
};
const WanVaceToVideo$1 = {
  display_name: "WanVaceToVideo",
  inputs: {
    batch_size: {
      name: "размер_пакета"
    },
    control_masks: {
      name: "control_masks"
    },
    control_video: {
      name: "control_video"
    },
    height: {
      name: "высота"
    },
    length: {
      name: "длина"
    },
    negative: {
      name: "негативный"
    },
    positive: {
      name: "позитивный"
    },
    reference_image: {
      name: "референсное_изображение"
    },
    strength: {
      name: "интенсивность"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "ширина"
    }
  },
  outputs: {
    "0": {
      name: "позитивный"
    },
    "1": {
      name: "негативный"
    },
    "2": {
      name: "latent"
    },
    "3": {
      name: "обрезанный_latent"
    }
  }
};
const WebcamCapture$1 = {
  display_name: "Захват с веб-камеры",
  inputs: {
    capture_on_queue: {
      name: "захват_в_очереди"
    },
    height: {
      name: "высота"
    },
    image: {
      name: "изображение"
    },
    "waiting for camera___": {},
    width: {
      name: "ширина"
    }
  }
};
const unCLIPCheckpointLoader$1 = {
  display_name: "Загрузчик контрольной точки unCLIP",
  inputs: {
    ckpt_name: {
      name: "название_ckpt"
    }
  }
};
const unCLIPConditioning$1 = {
  display_name: "unCLIP кондиционирование",
  inputs: {
    clip_vision_output: {
      name: "выход_clip_vision"
    },
    conditioning: {
      name: "условие"
    },
    noise_augmentation: {
      name: "аугментация_шума"
    },
    strength: {
      name: "сила"
    }
  }
};
const ruNodes = {
  AddNoise: AddNoise$1,
  AlignYourStepsScheduler: AlignYourStepsScheduler$1,
  BasicGuider: BasicGuider$1,
  BasicScheduler: BasicScheduler$1,
  BetaSamplingScheduler: BetaSamplingScheduler$1,
  CFGGuider: CFGGuider$1,
  CFGZeroStar: CFGZeroStar$1,
  CLIPAttentionMultiply: CLIPAttentionMultiply$1,
  CLIPLoader: CLIPLoader$1,
  CLIPMergeAdd: CLIPMergeAdd$1,
  CLIPMergeSimple: CLIPMergeSimple$1,
  CLIPMergeSubtract: CLIPMergeSubtract$1,
  CLIPSave: CLIPSave$1,
  CLIPSetLastLayer: CLIPSetLastLayer$1,
  CLIPTextEncode: CLIPTextEncode$1,
  CLIPTextEncodeControlnet: CLIPTextEncodeControlnet$1,
  CLIPTextEncodeFlux: CLIPTextEncodeFlux$1,
  CLIPTextEncodeHiDream: CLIPTextEncodeHiDream$1,
  CLIPTextEncodeHunyuanDiT: CLIPTextEncodeHunyuanDiT$1,
  CLIPTextEncodeLumina2: CLIPTextEncodeLumina2$1,
  CLIPTextEncodePixArtAlpha: CLIPTextEncodePixArtAlpha$1,
  CLIPTextEncodeSD3: CLIPTextEncodeSD3$1,
  CLIPTextEncodeSDXL: CLIPTextEncodeSDXL$1,
  CLIPTextEncodeSDXLRefiner: CLIPTextEncodeSDXLRefiner$1,
  CLIPVisionEncode: CLIPVisionEncode$1,
  CLIPVisionLoader: CLIPVisionLoader$1,
  Canny: Canny$1,
  CheckpointLoader: CheckpointLoader$1,
  CheckpointLoaderSimple: CheckpointLoaderSimple$1,
  CheckpointSave: CheckpointSave$1,
  CombineHooks2: CombineHooks2$1,
  CombineHooks4: CombineHooks4$1,
  CombineHooks8: CombineHooks8$1,
  ConditioningAverage: ConditioningAverage$1,
  ConditioningCombine: ConditioningCombine$1,
  ConditioningConcat: ConditioningConcat$1,
  ConditioningSetArea: ConditioningSetArea$1,
  ConditioningSetAreaPercentage: ConditioningSetAreaPercentage$1,
  ConditioningSetAreaPercentageVideo: ConditioningSetAreaPercentageVideo$1,
  ConditioningSetAreaStrength: ConditioningSetAreaStrength$1,
  ConditioningSetDefaultCombine: ConditioningSetDefaultCombine$1,
  ConditioningSetMask: ConditioningSetMask$1,
  ConditioningSetProperties: ConditioningSetProperties$1,
  ConditioningSetPropertiesAndCombine: ConditioningSetPropertiesAndCombine$1,
  ConditioningSetTimestepRange: ConditioningSetTimestepRange$1,
  ConditioningStableAudio: ConditioningStableAudio$1,
  ConditioningTimestepsRange: ConditioningTimestepsRange$1,
  ConditioningZeroOut: ConditioningZeroOut$1,
  ControlNetApply: ControlNetApply$1,
  ControlNetApplyAdvanced: ControlNetApplyAdvanced$1,
  ControlNetApplySD3: ControlNetApplySD3$1,
  ControlNetInpaintingAliMamaApply: ControlNetInpaintingAliMamaApply$1,
  ControlNetLoader: ControlNetLoader$1,
  CosmosImageToVideoLatent: CosmosImageToVideoLatent$1,
  CreateHookKeyframe: CreateHookKeyframe$1,
  CreateHookKeyframesFromFloats: CreateHookKeyframesFromFloats$1,
  CreateHookKeyframesInterpolated: CreateHookKeyframesInterpolated$1,
  CreateHookLora: CreateHookLora$1,
  CreateHookLoraModelOnly: CreateHookLoraModelOnly$1,
  CreateHookModelAsLora: CreateHookModelAsLora$1,
  CreateHookModelAsLoraModelOnly: CreateHookModelAsLoraModelOnly$1,
  CreateVideo: CreateVideo$1,
  CropMask: CropMask$1,
  DiffControlNetLoader: DiffControlNetLoader$1,
  DifferentialDiffusion: DifferentialDiffusion$1,
  DiffusersLoader: DiffusersLoader$1,
  DisableNoise: DisableNoise$1,
  DualCFGGuider: DualCFGGuider$1,
  DualCLIPLoader: DualCLIPLoader$1,
  EmptyCosmosLatentVideo: EmptyCosmosLatentVideo$1,
  EmptyHunyuanLatentVideo: EmptyHunyuanLatentVideo$1,
  EmptyImage: EmptyImage$1,
  EmptyLTXVLatentVideo: EmptyLTXVLatentVideo$1,
  EmptyLatentAudio: EmptyLatentAudio$1,
  EmptyLatentHunyuan3Dv2: EmptyLatentHunyuan3Dv2$1,
  EmptyLatentImage: EmptyLatentImage$1,
  EmptyMochiLatentVideo: EmptyMochiLatentVideo$1,
  EmptySD3LatentImage: EmptySD3LatentImage$1,
  ExponentialScheduler: ExponentialScheduler$1,
  ExtendIntermediateSigmas: ExtendIntermediateSigmas$1,
  FeatherMask: FeatherMask$1,
  FlipSigmas: FlipSigmas$1,
  FluxDisableGuidance: FluxDisableGuidance$1,
  FluxGuidance: FluxGuidance$1,
  FluxProCannyNode: FluxProCannyNode$1,
  FluxProDepthNode: FluxProDepthNode$1,
  FluxProExpandNode: FluxProExpandNode$1,
  FluxProFillNode: FluxProFillNode$1,
  FluxProUltraImageNode: FluxProUltraImageNode$1,
  FreSca: FreSca$1,
  FreeU: FreeU$1,
  FreeU_V2: FreeU_V2$1,
  GITSScheduler: GITSScheduler$1,
  GLIGENLoader: GLIGENLoader$1,
  GLIGENTextBoxApply: GLIGENTextBoxApply$1,
  GetVideoComponents: GetVideoComponents$1,
  GrowMask: GrowMask$1,
  Hunyuan3Dv2Conditioning: Hunyuan3Dv2Conditioning$1,
  Hunyuan3Dv2ConditioningMultiView: Hunyuan3Dv2ConditioningMultiView$1,
  HunyuanImageToVideo: HunyuanImageToVideo$1,
  HyperTile: HyperTile$1,
  HypernetworkLoader: HypernetworkLoader$1,
  IdeogramV1: IdeogramV1$1,
  IdeogramV2: IdeogramV2$1,
  IdeogramV3: IdeogramV3$1,
  ImageBatch: ImageBatch$1,
  ImageBlend: ImageBlend$1,
  ImageBlur: ImageBlur$1,
  ImageColorToMask: ImageColorToMask$1,
  ImageCompositeMasked: ImageCompositeMasked$1,
  ImageCrop: ImageCrop$1,
  ImageFromBatch: ImageFromBatch$1,
  ImageInvert: ImageInvert$1,
  ImageOnlyCheckpointLoader: ImageOnlyCheckpointLoader$1,
  ImageOnlyCheckpointSave: ImageOnlyCheckpointSave$1,
  ImagePadForOutpaint: ImagePadForOutpaint$1,
  ImageQuantize: ImageQuantize$1,
  ImageRGBToYUV: ImageRGBToYUV$1,
  ImageScale: ImageScale$1,
  ImageScaleBy: ImageScaleBy$1,
  ImageScaleToTotalPixels: ImageScaleToTotalPixels$1,
  ImageSharpen: ImageSharpen$1,
  ImageToMask: ImageToMask$1,
  ImageUpscaleWithModel: ImageUpscaleWithModel$1,
  ImageYUVToRGB: ImageYUVToRGB$1,
  InpaintModelConditioning: InpaintModelConditioning$1,
  InstructPixToPixConditioning: InstructPixToPixConditioning$1,
  InvertMask: InvertMask$1,
  JoinImageWithAlpha: JoinImageWithAlpha$1,
  KSampler: KSampler$1,
  KSamplerAdvanced: KSamplerAdvanced$1,
  KSamplerSelect: KSamplerSelect$1,
  KarrasScheduler: KarrasScheduler$1,
  KlingCameraControlI2VNode: KlingCameraControlI2VNode$1,
  KlingCameraControlT2VNode: KlingCameraControlT2VNode$1,
  KlingCameraControls: KlingCameraControls$1,
  KlingDualCharacterVideoEffectNode: KlingDualCharacterVideoEffectNode$1,
  KlingImage2VideoNode: KlingImage2VideoNode$1,
  KlingImageGenerationNode: KlingImageGenerationNode$1,
  KlingLipSyncAudioToVideoNode: KlingLipSyncAudioToVideoNode$1,
  KlingLipSyncTextToVideoNode: KlingLipSyncTextToVideoNode$1,
  KlingSingleImageVideoEffectNode: KlingSingleImageVideoEffectNode$1,
  KlingStartEndFrameNode: KlingStartEndFrameNode$1,
  KlingTextToVideoNode: KlingTextToVideoNode$1,
  KlingVideoExtendNode: KlingVideoExtendNode$1,
  KlingVirtualTryOnNode: KlingVirtualTryOnNode$1,
  LTXVAddGuide: LTXVAddGuide$1,
  LTXVConditioning: LTXVConditioning$1,
  LTXVCropGuides: LTXVCropGuides$1,
  LTXVImgToVideo: LTXVImgToVideo$1,
  LTXVPreprocess: LTXVPreprocess$1,
  LTXVScheduler: LTXVScheduler$1,
  LaplaceScheduler: LaplaceScheduler$1,
  LatentAdd: LatentAdd$1,
  LatentApplyOperation: LatentApplyOperation$1,
  LatentApplyOperationCFG: LatentApplyOperationCFG$1,
  LatentBatch: LatentBatch$1,
  LatentBatchSeedBehavior: LatentBatchSeedBehavior$1,
  LatentBlend: LatentBlend$1,
  LatentComposite: LatentComposite$1,
  LatentCompositeMasked: LatentCompositeMasked$1,
  LatentCrop: LatentCrop$1,
  LatentFlip: LatentFlip$1,
  LatentFromBatch: LatentFromBatch$1,
  LatentInterpolate: LatentInterpolate$1,
  LatentMultiply: LatentMultiply$1,
  LatentOperationSharpen: LatentOperationSharpen$1,
  LatentOperationTonemapReinhard: LatentOperationTonemapReinhard$1,
  LatentRotate: LatentRotate$1,
  LatentSubtract: LatentSubtract$1,
  LatentUpscale: LatentUpscale$1,
  LatentUpscaleBy: LatentUpscaleBy$1,
  Load3D: Load3D$1,
  Load3DAnimation: Load3DAnimation$1,
  LoadAudio: LoadAudio$1,
  LoadImage: LoadImage$1,
  LoadImageMask: LoadImageMask$1,
  LoadImageOutput: LoadImageOutput$1,
  LoadLatent: LoadLatent$1,
  LoadVideo: LoadVideo$1,
  LoraLoader: LoraLoader$1,
  LoraLoaderModelOnly: LoraLoaderModelOnly$1,
  LoraSave: LoraSave$1,
  LotusConditioning: LotusConditioning$1,
  LumaConceptsNode: LumaConceptsNode$1,
  LumaImageModifyNode: LumaImageModifyNode$1,
  LumaImageNode: LumaImageNode$1,
  LumaImageToVideoNode: LumaImageToVideoNode$1,
  LumaReferenceNode: LumaReferenceNode$1,
  LumaVideoNode: LumaVideoNode$1,
  Mahiro: Mahiro$1,
  MaskComposite: MaskComposite$1,
  MaskPreview: MaskPreview$1,
  MaskToImage: MaskToImage$1,
  MinimaxImageToVideoNode: MinimaxImageToVideoNode$1,
  MinimaxTextToVideoNode: MinimaxTextToVideoNode$1,
  ModelComputeDtype: ModelComputeDtype$1,
  ModelMergeAdd: ModelMergeAdd$1,
  ModelMergeAuraflow: ModelMergeAuraflow$1,
  ModelMergeBlocks: ModelMergeBlocks$1,
  ModelMergeCosmos14B: ModelMergeCosmos14B$1,
  ModelMergeCosmos7B: ModelMergeCosmos7B$1,
  ModelMergeFlux1: ModelMergeFlux1$1,
  ModelMergeLTXV: ModelMergeLTXV$1,
  ModelMergeMochiPreview: ModelMergeMochiPreview$1,
  ModelMergeSD1: ModelMergeSD1$1,
  ModelMergeSD2: ModelMergeSD2$1,
  ModelMergeSD35_Large: ModelMergeSD35_Large$1,
  ModelMergeSD3_2B: ModelMergeSD3_2B$1,
  ModelMergeSDXL: ModelMergeSDXL$1,
  ModelMergeSimple: ModelMergeSimple$1,
  ModelMergeSubtract: ModelMergeSubtract$1,
  ModelMergeWAN2_1: ModelMergeWAN2_1$1,
  ModelSamplingAuraFlow: ModelSamplingAuraFlow$1,
  ModelSamplingContinuousEDM: ModelSamplingContinuousEDM$1,
  ModelSamplingContinuousV: ModelSamplingContinuousV$1,
  ModelSamplingDiscrete: ModelSamplingDiscrete$1,
  ModelSamplingFlux: ModelSamplingFlux$1,
  ModelSamplingLTXV: ModelSamplingLTXV$1,
  ModelSamplingSD3: ModelSamplingSD3$1,
  ModelSamplingStableCascade: ModelSamplingStableCascade$1,
  ModelSave: ModelSave$1,
  Morphology: Morphology$1,
  OpenAIDalle2: OpenAIDalle2$1,
  OpenAIDalle3: OpenAIDalle3$1,
  OpenAIGPTImage1: OpenAIGPTImage1$1,
  OptimalStepsScheduler: OptimalStepsScheduler$1,
  PairConditioningCombine: PairConditioningCombine$1,
  PairConditioningSetDefaultCombine: PairConditioningSetDefaultCombine$1,
  PairConditioningSetProperties: PairConditioningSetProperties$1,
  PairConditioningSetPropertiesAndCombine: PairConditioningSetPropertiesAndCombine$1,
  PatchModelAddDownscale: PatchModelAddDownscale$1,
  PerpNeg: PerpNeg$1,
  PerpNegGuider: PerpNegGuider$1,
  PerturbedAttentionGuidance: PerturbedAttentionGuidance$1,
  PhotoMakerEncode: PhotoMakerEncode$1,
  PhotoMakerLoader: PhotoMakerLoader$1,
  PikaImageToVideoNode2_2: PikaImageToVideoNode2_2$1,
  PikaScenesV2_2: PikaScenesV2_2$1,
  PikaStartEndFrameNode2_2: PikaStartEndFrameNode2_2$1,
  PikaTextToVideoNode2_2: PikaTextToVideoNode2_2$1,
  Pikadditions: Pikadditions$1,
  Pikaffects: Pikaffects$1,
  Pikaswaps: Pikaswaps$1,
  PixverseImageToVideoNode: PixverseImageToVideoNode$1,
  PixverseTemplateNode: PixverseTemplateNode$1,
  PixverseTextToVideoNode: PixverseTextToVideoNode$1,
  PixverseTransitionVideoNode: PixverseTransitionVideoNode$1,
  PolyexponentialScheduler: PolyexponentialScheduler$1,
  PorterDuffImageComposite: PorterDuffImageComposite$1,
  Preview3D: Preview3D$1,
  Preview3DAnimation: Preview3DAnimation$1,
  PreviewAny: PreviewAny$1,
  PreviewAudio: PreviewAudio$1,
  PreviewImage: PreviewImage$1,
  PrimitiveBoolean: PrimitiveBoolean$1,
  PrimitiveFloat: PrimitiveFloat$1,
  PrimitiveInt: PrimitiveInt$1,
  PrimitiveString: PrimitiveString$1,
  PrimitiveStringMultiline: PrimitiveStringMultiline$1,
  QuadrupleCLIPLoader: QuadrupleCLIPLoader$1,
  RandomNoise: RandomNoise$1,
  RebatchImages: RebatchImages$1,
  RebatchLatents: RebatchLatents$1,
  RecraftColorRGB: RecraftColorRGB$1,
  RecraftControls: RecraftControls$1,
  RecraftCreativeUpscaleNode: RecraftCreativeUpscaleNode$1,
  RecraftCrispUpscaleNode: RecraftCrispUpscaleNode$1,
  RecraftImageInpaintingNode: RecraftImageInpaintingNode$1,
  RecraftImageToImageNode: RecraftImageToImageNode$1,
  RecraftRemoveBackgroundNode: RecraftRemoveBackgroundNode$1,
  RecraftReplaceBackgroundNode: RecraftReplaceBackgroundNode$1,
  RecraftStyleV3DigitalIllustration: RecraftStyleV3DigitalIllustration$1,
  RecraftStyleV3InfiniteStyleLibrary: RecraftStyleV3InfiniteStyleLibrary$1,
  RecraftStyleV3LogoRaster: RecraftStyleV3LogoRaster$1,
  RecraftStyleV3RealisticImage: RecraftStyleV3RealisticImage$1,
  RecraftTextToImageNode: RecraftTextToImageNode$1,
  RecraftTextToVectorNode: RecraftTextToVectorNode$1,
  RecraftVectorizeImageNode: RecraftVectorizeImageNode$1,
  RenormCFG: RenormCFG$1,
  RepeatImageBatch: RepeatImageBatch$1,
  RepeatLatentBatch: RepeatLatentBatch$1,
  RescaleCFG: RescaleCFG$1,
  SDTurboScheduler: SDTurboScheduler$1,
  SD_4XUpscale_Conditioning: SD_4XUpscale_Conditioning$1,
  SV3D_Conditioning: SV3D_Conditioning$1,
  SVD_img2vid_Conditioning: SVD_img2vid_Conditioning$1,
  SamplerCustom: SamplerCustom$1,
  SamplerCustomAdvanced: SamplerCustomAdvanced$1,
  SamplerDPMAdaptative: SamplerDPMAdaptative$1,
  SamplerDPMPP_2M_SDE: SamplerDPMPP_2M_SDE$1,
  SamplerDPMPP_2S_Ancestral: SamplerDPMPP_2S_Ancestral$1,
  SamplerDPMPP_3M_SDE: SamplerDPMPP_3M_SDE$1,
  SamplerDPMPP_SDE: SamplerDPMPP_SDE$1,
  SamplerEulerAncestral: SamplerEulerAncestral$1,
  SamplerEulerAncestralCFGPP: SamplerEulerAncestralCFGPP$1,
  SamplerEulerCFGpp: SamplerEulerCFGpp$1,
  SamplerLCMUpscale: SamplerLCMUpscale$1,
  SamplerLMS: SamplerLMS$1,
  SaveAnimatedPNG: SaveAnimatedPNG$1,
  SaveAnimatedWEBP: SaveAnimatedWEBP$1,
  SaveAudio: SaveAudio$1,
  SaveGLB: SaveGLB$1,
  SaveImage: SaveImage$1,
  SaveImageWebsocket: SaveImageWebsocket$1,
  SaveLatent: SaveLatent$1,
  SaveSVG: SaveSVG$1,
  SaveVideo: SaveVideo$1,
  SaveWEBM: SaveWEBM$1,
  SelfAttentionGuidance: SelfAttentionGuidance$1,
  SetClipHooks: SetClipHooks$1,
  SetFirstSigma: SetFirstSigma$1,
  SetHookKeyframes: SetHookKeyframes$1,
  SetLatentNoiseMask: SetLatentNoiseMask$1,
  SetUnionControlNetType: SetUnionControlNetType$1,
  SkipLayerGuidanceDiT: SkipLayerGuidanceDiT$1,
  SkipLayerGuidanceSD3: SkipLayerGuidanceSD3$1,
  SolidMask: SolidMask$1,
  SplitImageWithAlpha: SplitImageWithAlpha$1,
  SplitSigmas: SplitSigmas$1,
  SplitSigmasDenoise: SplitSigmasDenoise$1,
  StabilityStableImageSD_3_5Node: StabilityStableImageSD_3_5Node$1,
  StabilityStableImageUltraNode: StabilityStableImageUltraNode$1,
  StabilityUpscaleConservativeNode: StabilityUpscaleConservativeNode$1,
  StabilityUpscaleCreativeNode: StabilityUpscaleCreativeNode$1,
  StabilityUpscaleFastNode: StabilityUpscaleFastNode$1,
  StableCascade_EmptyLatentImage: StableCascade_EmptyLatentImage$1,
  StableCascade_StageB_Conditioning: StableCascade_StageB_Conditioning$1,
  StableCascade_StageC_VAEEncode: StableCascade_StageC_VAEEncode$1,
  StableCascade_SuperResolutionControlnet: StableCascade_SuperResolutionControlnet$1,
  StableZero123_Conditioning: StableZero123_Conditioning$1,
  StableZero123_Conditioning_Batched: StableZero123_Conditioning_Batched$1,
  StyleModelApply: StyleModelApply$1,
  StyleModelLoader: StyleModelLoader$1,
  T5TokenizerOptions: T5TokenizerOptions$1,
  TextEncodeHunyuanVideo_ImageToVideo: TextEncodeHunyuanVideo_ImageToVideo$1,
  ThresholdMask: ThresholdMask$1,
  TomePatchModel: TomePatchModel$1,
  TorchCompileModel: TorchCompileModel$1,
  TrimVideoLatent: TrimVideoLatent$1,
  TripleCLIPLoader: TripleCLIPLoader$1,
  UNETLoader: UNETLoader$1,
  UNetCrossAttentionMultiply: UNetCrossAttentionMultiply$1,
  UNetSelfAttentionMultiply: UNetSelfAttentionMultiply$1,
  UNetTemporalAttentionMultiply: UNetTemporalAttentionMultiply$1,
  UpscaleModelLoader: UpscaleModelLoader$1,
  VAEDecode: VAEDecode$1,
  VAEDecodeAudio: VAEDecodeAudio$1,
  VAEDecodeHunyuan3D: VAEDecodeHunyuan3D$1,
  VAEDecodeTiled: VAEDecodeTiled$1,
  VAEEncode: VAEEncode$1,
  VAEEncodeAudio: VAEEncodeAudio$1,
  VAEEncodeForInpaint: VAEEncodeForInpaint$1,
  VAEEncodeTiled: VAEEncodeTiled$1,
  VAELoader: VAELoader$1,
  VAESave: VAESave$1,
  VPScheduler: VPScheduler$1,
  VeoVideoGenerationNode: VeoVideoGenerationNode$1,
  VideoLinearCFGGuidance: VideoLinearCFGGuidance$1,
  VideoTriangleCFGGuidance: VideoTriangleCFGGuidance$1,
  VoxelToMesh: VoxelToMesh$1,
  VoxelToMeshBasic: VoxelToMeshBasic$1,
  WanFirstLastFrameToVideo: WanFirstLastFrameToVideo$1,
  WanFunControlToVideo: WanFunControlToVideo$1,
  WanFunInpaintToVideo: WanFunInpaintToVideo$1,
  WanImageToVideo: WanImageToVideo$1,
  WanVaceToVideo: WanVaceToVideo$1,
  WebcamCapture: WebcamCapture$1,
  unCLIPCheckpointLoader: unCLIPCheckpointLoader$1,
  unCLIPConditioning: unCLIPConditioning$1
};
const Comfy_Canvas_SelectionToolbox$1 = {
  name: "Показать панель инструментов выбора"
};
const Comfy_ConfirmClear$1 = {
  name: "Требовать подтверждение при очистке рабочего процесса"
};
const Comfy_DOMClippingEnabled$1 = {
  name: "Включить обрезку элементов DOM (включение может снизить производительность)"
};
const Comfy_DevMode$1 = {
  name: "Включить параметры режима разработчика (сохранение API и т. д.)"
};
const Comfy_DisableFloatRounding$1 = {
  name: "Отключить округление по умолчанию для плавающих виджетов.",
  tooltip: "(требуется перезагрузка страницы) Невозможно отключить округление, если оно установлено узлом на сервере."
};
const Comfy_DisableSliders$1 = {
  name: "Отключить ползунки виджетов нод"
};
const Comfy_EditAttention_Delta$1 = {
  name: "Точность Ctrl+вверх/вниз"
};
const Comfy_EnableTooltips$1 = {
  name: "Включить подсказки"
};
const Comfy_EnableWorkflowViewRestore$1 = {
  name: "Сохранять и восстанавливать положение и уровень масштабирования холста в рабочих процессах"
};
const Comfy_FloatRoundingPrecision$1 = {
  name: "Количество знаков после запятой для округления плавающего виджета [0 = авто].",
  tooltip: "(требуется перезагрузка страницы)"
};
const Comfy_Graph_CanvasInfo$1 = {
  name: "Показать информацию о холсте в нижнем левом углу (fps и т.д.)"
};
const Comfy_Graph_CanvasMenu$1 = {
  name: "Показать меню холста графа"
};
const Comfy_Graph_CtrlShiftZoom$1 = {
  name: "Включить быстрый зум с помощью сочетания клавиш (Ctrl + Shift + Колёсико мыши)"
};
const Comfy_Graph_LinkMarkers$1 = {
  name: "Маркер середины ссылки",
  options: {
    Arrow: "Стрелка",
    Circle: "Круг",
    None: "Нет"
  }
};
const Comfy_Graph_ZoomSpeed$1 = {
  name: "Скорость зума холста"
};
const Comfy_GroupSelectedNodes_Padding$1 = {
  name: "Отступ для выбранных нод группы"
};
const Comfy_Group_DoubleClickTitleToEdit$1 = {
  name: "Дважды щёлкните по заголовку группы, чтобы редактировать"
};
const Comfy_LinkRelease_Action$1 = {
  name: "Действие при отпускании ссылки (без модификатора)",
  options: {
    "context menu": "контекстное меню",
    "no action": "без действия",
    "search box": "поисковая строка"
  }
};
const Comfy_LinkRelease_ActionShift$1 = {
  name: "Действие при отпускании ссылки (Shift)",
  options: {
    "context menu": "контекстное меню",
    "no action": "без действия",
    "search box": "поисковая строка"
  }
};
const Comfy_LinkRenderMode$1 = {
  name: "Режим рендеринга ссылки",
  options: {
    Hidden: "Скрытый",
    Linear: "Линейный",
    Spline: "Сплайн",
    Straight: "Прямой"
  }
};
const Comfy_Load3D_BackgroundColor$1 = {
  name: "Начальный цвет фона",
  tooltip: "Управляет цветом фона по умолчанию для 3D-сцены. Этот параметр определяет внешний вид фона при создании нового 3D-виджета, но может быть изменён индивидуально для каждого виджета после создания."
};
const Comfy_Load3D_CameraType$1 = {
  name: "Тип камеры",
  options: {
    orthographic: "ортографическая",
    perspective: "перспективная"
  },
  tooltip: "Управляет тем, является ли камера перспективной или ортографической по умолчанию при создании нового 3D-виджета. Это значение по умолчанию все еще может быть переключено индивидуально для каждого виджета после его создания."
};
const Comfy_Load3D_LightAdjustmentIncrement$1 = {
  name: "Шаг регулировки освещения",
  tooltip: "Определяет размер шага при регулировке интенсивности освещения в 3D-сценах. Меньшее значение шага позволяет более точно настраивать освещение, а большее значение приводит к более заметным изменениям при каждой регулировке."
};
const Comfy_Load3D_LightIntensity$1 = {
  name: "Начальная интенсивность освещения",
  tooltip: "Устанавливает уровень яркости освещения по умолчанию в 3D-сцене. Это значение определяет, насколько сильно источники света освещают объекты при создании нового 3D-виджета, но может быть изменено для каждого виджета отдельно после создания."
};
const Comfy_Load3D_LightIntensityMaximum$1 = {
  name: "Максимальная интенсивность света",
  tooltip: "Устанавливает максимальное допустимое значение интенсивности света для 3D-сцен. Определяет верхний предел яркости, который можно задать при настройке освещения в любом 3D-виджете."
};
const Comfy_Load3D_LightIntensityMinimum$1 = {
  name: "Минимальная интенсивность света",
  tooltip: "Устанавливает минимально допустимое значение интенсивности света для 3D-сцен. Определяет нижний предел яркости, который можно установить при настройке освещения в любом 3D-виджете."
};
const Comfy_Load3D_ShowGrid$1 = {
  name: "Показать сетку",
  tooltip: "Переключиться, чтобы показывать сетку по умолчанию"
};
const Comfy_Load3D_ShowPreview$1 = {
  name: "Показать предварительный просмотр",
  tooltip: "Переключиться, чтобы показывать предварительный просмотр по умолчанию"
};
const Comfy_Locale$1 = {
  name: "Язык"
};
const Comfy_MaskEditor_BrushAdjustmentSpeed$1 = {
  name: "Множитель скорости регулировки кисти",
  tooltip: "Управляет тем, как быстро изменяются размер и жёсткость кисти при регулировке. Более высокие значения означают более быстрые изменения."
};
const Comfy_MaskEditor_UseDominantAxis$1 = {
  name: "Закрепить регулировку кисти по доминирующей оси",
  tooltip: "При включении регулировки кисти будет влиять только на размер или жёсткость в зависимости от того, в каком направлении вы двигаетесь больше"
};
const Comfy_MaskEditor_UseNewEditor$1 = {
  name: "Использовать новый редактор масок",
  tooltip: "Переключиться на новый интерфейс редактора масок"
};
const Comfy_ModelLibrary_AutoLoadAll$1 = {
  name: "Автоматически загружать все папки моделей",
  tooltip: "Если true, все папки будут загружены, как только вы откроете библиотеку моделей (это может вызвать задержки при загрузке). Если false, корневые папки моделей будут загружены только после нажатия на них."
};
const Comfy_ModelLibrary_NameFormat$1 = {
  name: "Какое название отображать в древовидном представлении библиотеки моделей",
  options: {
    filename: "название файла",
    title: "название"
  },
  tooltip: 'Выберите "название файла", чтобы отобразить упрощённый вид сырого названия файла (без директории или расширения ".safetensors") в списке моделей. Выберите "название", чтобы отобразить настраиваемое название метаданных модели.'
};
const Comfy_NodeBadge_NodeIdBadgeMode$1 = {
  name: "Режим значка ID ноды",
  options: {
    None: "Нет",
    "Show all": "Показать все"
  }
};
const Comfy_NodeBadge_NodeLifeCycleBadgeMode$1 = {
  name: "Режим значка жизненного цикла ноды",
  options: {
    None: "Нет",
    "Show all": "Показать все"
  }
};
const Comfy_NodeBadge_NodeSourceBadgeMode$1 = {
  name: "Режим значка источника ноды",
  options: {
    "Hide built-in": "Скрыть встроенные",
    None: "Нет",
    "Show all": "Показать все"
  }
};
const Comfy_NodeSearchBoxImpl$1 = {
  name: "Реализация поискового поля нод",
  options: {
    "default": "по умолчанию",
    "litegraph (legacy)": "litegraph (устаревший)"
  }
};
const Comfy_NodeSearchBoxImpl_NodePreview$1 = {
  name: "Предварительный просмотр ноды",
  tooltip: "Применяется только к стандартной реализации"
};
const Comfy_NodeSearchBoxImpl_ShowCategory$1 = {
  name: "Показать категорию ноды в результатах поиска",
  tooltip: "Применяется только к стандартной реализации"
};
const Comfy_NodeSearchBoxImpl_ShowIdName$1 = {
  name: "Показать название ID ноды в результатах поиска",
  tooltip: "Применяется только к стандартной реализации"
};
const Comfy_NodeSearchBoxImpl_ShowNodeFrequency$1 = {
  name: "Показать частоту ноды в результатах поиска",
  tooltip: "Применяется только к стандартной реализации"
};
const Comfy_NodeSuggestions_number$1 = {
  name: "Количество предложенных нод",
  tooltip: "Только для поля поиска litegraph/контекстного меню"
};
const Comfy_Node_AllowImageSizeDraw$1 = {
  name: "Показывать ширину × высоту под предварительным просмотром изображения"
};
const Comfy_Node_AutoSnapLinkToSlot$1 = {
  name: "Автоматически привязывать ссылку к слоту ноды",
  tooltip: "При перетаскивании ссылки над нодой ссылка автоматически привязывается к подходящему входному слоту ноды"
};
const Comfy_Node_BypassAllLinksOnDelete$1 = {
  name: "Сохранить все ссылки при удалении нод",
  tooltip: "При удалении ноды попытаться переподключить все её входные и выходные ссылки (обходя удалённую ноду)"
};
const Comfy_Node_DoubleClickTitleToEdit$1 = {
  name: "Дважды щёлкните по заголовку ноды, чтобы редактировать"
};
const Comfy_Node_MiddleClickRerouteNode$1 = {
  name: "Средний щелчок создаёт новую ноду перенаправления"
};
const Comfy_Node_Opacity$1 = {
  name: "Непрозрачность ноды"
};
const Comfy_Node_ShowDeprecated$1 = {
  name: "Показать устаревшие ноды в поиске",
  tooltip: "Устаревшие ноды по умолчанию скрыты в интерфейсе, но остаются функциональными в существующих рабочих процессах, которые их используют."
};
const Comfy_Node_ShowExperimental$1 = {
  name: "Показать экспериментальные ноды в поиске",
  tooltip: "Экспериментальные ноды помечены как таковые в интерфейсе и могут подвергаться значительным изменениям или удалению в будущих версиях. Используйте с осторожностью в производственных рабочих процессах"
};
const Comfy_Node_SnapHighlightsNode$1 = {
  name: "Подсветка ноды при привязке",
  tooltip: "При перетаскивании ссылки над нодой с подходящим входным слотом, нода подсвечивается"
};
const Comfy_Pointer_ClickBufferTime$1 = {
  name: "Задержка дрейфа щелчка указателя",
  tooltip: "После нажатия кнопки указателя, это максимальное время (в миллисекундах), в течение которого движение указателя может быть проигнорировано.\n\nПомогает предотвратить непреднамеренное смещение объектов, если указатель перемещается во время щелчка."
};
const Comfy_Pointer_ClickDrift$1 = {
  name: "Дрейф щелчка указателя (максимальное расстояние)",
  tooltip: "Если указатель перемещается более чем на это расстояние, удерживая кнопку, это считается перетаскиванием (а не щелчком).\n\nПомогает предотвратить непреднамеренное смещение объектов, если указатель перемещается во время щелчка."
};
const Comfy_Pointer_DoubleClickTime$1 = {
  name: "Интервал двойного щелчка (максимум)",
  tooltip: "Максимальное время в миллисекундах между двумя щелчками двойного щелчка. Увеличение этого значения может помочь, если двойные щелчки иногда не регистрируются."
};
const Comfy_PreviewFormat$1 = {
  name: "Формат изображения предварительного просмотра",
  tooltip: "При отображении предварительного просмотра в виджете изображения, преобразуйте его в легковесное изображение, например, webp, jpeg, webp;50 и т.д."
};
const Comfy_PromptFilename$1 = {
  name: "Запрос названия файла при сохранении рабочего процесса"
};
const Comfy_QueueButton_BatchCountLimit$1 = {
  name: "Ограничение количества партий",
  tooltip: "Максимальное количество задач, добавляемых в очередь за одно нажатие кнопки"
};
const Comfy_Queue_MaxHistoryItems$1 = {
  name: "Размер истории очереди",
  tooltip: "Максимальное количество задач, отображаемых в истории очереди."
};
const Comfy_Sidebar_Location$1 = {
  name: "Расположение боковой панели",
  options: {
    left: "слева",
    right: "справа"
  }
};
const Comfy_Sidebar_Size$1 = {
  name: "Размер боковой панели",
  options: {
    normal: "нормальный",
    small: "маленький"
  }
};
const Comfy_Sidebar_UnifiedWidth$1 = {
  name: "Унифицированная ширина боковой панели"
};
const Comfy_SnapToGrid_GridSize$1 = {
  name: "Размер сетки привязки",
  tooltip: "При перетаскивании и изменении размера нод, удерживая shift, они будут выровнены по сетке, это контролирует размер этой сетки."
};
const Comfy_TextareaWidget_FontSize$1 = {
  name: "Размер шрифта виджета текстовой области"
};
const Comfy_TextareaWidget_Spellcheck$1 = {
  name: "Проверка орфографии виджета текстовой области"
};
const Comfy_TreeExplorer_ItemPadding$1 = {
  name: "Отступ элемента в проводнике дерева"
};
const Comfy_UseNewMenu$1 = {
  name: "Использовать новое меню",
  options: {
    Bottom: "Внизу",
    Disabled: "Отключено",
    Top: "Вверху"
  }
};
const Comfy_Validation_NodeDefs$1 = {
  name: "Проверка определений нод (медленно)",
  tooltip: "Рекомендуется для разработчиков нод. Это проверит все определения нод при запуске."
};
const Comfy_Validation_Workflows$1 = {
  name: "Проверка рабочих процессов"
};
const Comfy_WidgetControlMode$1 = {
  name: "Режим управления виджетом",
  options: {
    after: "после",
    before: "до"
  },
  tooltip: "Управляет тем, когда обновляются значения виджета (случайные/увеличение/уменьшение), либо до того, как запрос будет поставлен в очередь, либо после."
};
const Comfy_Window_UnloadConfirmation$1 = {
  name: "Показать подтверждение при закрытии окна"
};
const Comfy_Workflow_AutoSave$1 = {
  name: "Автосохранение",
  options: {
    "after delay": "после задержки",
    off: "выключено"
  }
};
const Comfy_Workflow_AutoSaveDelay$1 = {
  name: "Задержка автосохранения (мс)",
  tooltip: 'Применяется только если автосохранение установлено на "после задержки".'
};
const Comfy_Workflow_ConfirmDelete$1 = {
  name: "Показать подтверждение при удалении рабочих процессов"
};
const Comfy_Workflow_Persist$1 = {
  name: "Сохранить состояние рабочего процесса и восстановить при (пере)загрузке страницы"
};
const Comfy_Workflow_ShowMissingModelsWarning$1 = {
  name: "Показать предупреждение об отсутствующих моделях"
};
const Comfy_Workflow_ShowMissingNodesWarning$1 = {
  name: "Показать предупреждение об отсутствующих нодах"
};
const Comfy_Workflow_SortNodeIdOnSave$1 = {
  name: "Сортировать ID нод при сохранении рабочего процесса"
};
const Comfy_Workflow_WorkflowTabsPosition$1 = {
  name: "Положение открытых рабочих процессов",
  options: {
    Sidebar: "Боковая панель",
    Topbar: "Верхняя панель",
    "Topbar (2nd-row)": "Топбар (2-й ряд)"
  }
};
const LiteGraph_Canvas_LowQualityRenderingZoomThreshold$1 = {
  name: "Порог масштабирования для рендеринга низкого качества",
  tooltip: "Рендеринг фигур низкого качества при уменьшении масштаба"
};
const LiteGraph_Canvas_MaximumFps$1 = {
  name: "Максимум FPS",
  tooltip: "Максимальное количество кадров в секунду, которое холст может рендерить. Ограничивает использование GPU за счёт плавности. Если 0, используется частота обновления экрана. По умолчанию: 0"
};
const LiteGraph_ContextMenu_Scaling$1 = {
  name: "Масштабирование комбинированных виджетов меню узлов (списков) при увеличении"
};
const LiteGraph_Node_DefaultPadding$1 = {
  name: "Всегда сжимать новые узлы",
  tooltip: "Изменять размер узлов до минимально возможного при создании. Если отключено, новый узел будет немного расширен для отображения значений виджетов."
};
const LiteGraph_Node_TooltipDelay$1 = {
  name: "Задержка всплывающей подсказки"
};
const LiteGraph_Pointer_TrackpadGestures$1 = {
  name: "Включить жесты трекпада",
  tooltip: "Эта настройка включает режим трекпада для холста, позволяя использовать масштабирование щипком и панорамирование двумя пальцами."
};
const LiteGraph_Reroute_SplineOffset$1 = {
  name: "Перераспределение смещения сплайна",
  tooltip: "Смещение контрольной точки Безье от центральной точки перераспределения"
};
const pysssss_SnapToGrid$1 = {
  name: "Всегда привязываться к сетке"
};
const ruSettings = {
  "Comfy-Desktop_AutoUpdate": {
    name: "Автоматически проверять обновления"
  },
  "Comfy-Desktop_SendStatistics": {
    name: "Отправлять анонимную статистику использования"
  },
  "Comfy-Desktop_UV_PypiInstallMirror": {
    name: "Pypi Установить Зеркало",
    tooltip: "Зеркало установки pip по умолчанию"
  },
  "Comfy-Desktop_UV_PythonInstallMirror": {
    name: "Зеркало для установки Python",
    tooltip: "Управляемые установки Python загружаются из проекта Astral python-build-standalone. Эта переменная может быть установлена на URL-адрес зеркала для использования другого источника для установок Python. Предоставленный URL заменит https://github.com/astral-sh/python-build-standalone/releases/download в, например, https://github.com/astral-sh/python-build-standalone/releases/download/20240713/cpython-3.12.4%2B20240713-aarch64-apple-darwin-install_only.tar.gz. Дистрибутивы могут быть прочитаны из локального каталога, используя схему URL file://."
  },
  "Comfy-Desktop_UV_TorchInstallMirror": {
    name: "Установочное Зеркало Torch",
    tooltip: "Зеркало для установки pip для pytorch"
  },
  "Comfy-Desktop_WindowStyle": {
    name: "Стиль окна",
    options: {
      custom: "пользовательский",
      "default": "по умолчанию"
    },
    tooltip: "Выберите пользовательский вариант, чтобы скрыть системную строку заголовка"
  },
  Comfy_Canvas_SelectionToolbox: Comfy_Canvas_SelectionToolbox$1,
  Comfy_ConfirmClear: Comfy_ConfirmClear$1,
  Comfy_DOMClippingEnabled: Comfy_DOMClippingEnabled$1,
  Comfy_DevMode: Comfy_DevMode$1,
  Comfy_DisableFloatRounding: Comfy_DisableFloatRounding$1,
  Comfy_DisableSliders: Comfy_DisableSliders$1,
  Comfy_EditAttention_Delta: Comfy_EditAttention_Delta$1,
  Comfy_EnableTooltips: Comfy_EnableTooltips$1,
  Comfy_EnableWorkflowViewRestore: Comfy_EnableWorkflowViewRestore$1,
  Comfy_FloatRoundingPrecision: Comfy_FloatRoundingPrecision$1,
  Comfy_Graph_CanvasInfo: Comfy_Graph_CanvasInfo$1,
  Comfy_Graph_CanvasMenu: Comfy_Graph_CanvasMenu$1,
  Comfy_Graph_CtrlShiftZoom: Comfy_Graph_CtrlShiftZoom$1,
  Comfy_Graph_LinkMarkers: Comfy_Graph_LinkMarkers$1,
  Comfy_Graph_ZoomSpeed: Comfy_Graph_ZoomSpeed$1,
  Comfy_GroupSelectedNodes_Padding: Comfy_GroupSelectedNodes_Padding$1,
  Comfy_Group_DoubleClickTitleToEdit: Comfy_Group_DoubleClickTitleToEdit$1,
  Comfy_LinkRelease_Action: Comfy_LinkRelease_Action$1,
  Comfy_LinkRelease_ActionShift: Comfy_LinkRelease_ActionShift$1,
  Comfy_LinkRenderMode: Comfy_LinkRenderMode$1,
  Comfy_Load3D_BackgroundColor: Comfy_Load3D_BackgroundColor$1,
  Comfy_Load3D_CameraType: Comfy_Load3D_CameraType$1,
  Comfy_Load3D_LightAdjustmentIncrement: Comfy_Load3D_LightAdjustmentIncrement$1,
  Comfy_Load3D_LightIntensity: Comfy_Load3D_LightIntensity$1,
  Comfy_Load3D_LightIntensityMaximum: Comfy_Load3D_LightIntensityMaximum$1,
  Comfy_Load3D_LightIntensityMinimum: Comfy_Load3D_LightIntensityMinimum$1,
  Comfy_Load3D_ShowGrid: Comfy_Load3D_ShowGrid$1,
  Comfy_Load3D_ShowPreview: Comfy_Load3D_ShowPreview$1,
  Comfy_Locale: Comfy_Locale$1,
  Comfy_MaskEditor_BrushAdjustmentSpeed: Comfy_MaskEditor_BrushAdjustmentSpeed$1,
  Comfy_MaskEditor_UseDominantAxis: Comfy_MaskEditor_UseDominantAxis$1,
  Comfy_MaskEditor_UseNewEditor: Comfy_MaskEditor_UseNewEditor$1,
  Comfy_ModelLibrary_AutoLoadAll: Comfy_ModelLibrary_AutoLoadAll$1,
  Comfy_ModelLibrary_NameFormat: Comfy_ModelLibrary_NameFormat$1,
  Comfy_NodeBadge_NodeIdBadgeMode: Comfy_NodeBadge_NodeIdBadgeMode$1,
  Comfy_NodeBadge_NodeLifeCycleBadgeMode: Comfy_NodeBadge_NodeLifeCycleBadgeMode$1,
  Comfy_NodeBadge_NodeSourceBadgeMode: Comfy_NodeBadge_NodeSourceBadgeMode$1,
  Comfy_NodeSearchBoxImpl: Comfy_NodeSearchBoxImpl$1,
  Comfy_NodeSearchBoxImpl_NodePreview: Comfy_NodeSearchBoxImpl_NodePreview$1,
  Comfy_NodeSearchBoxImpl_ShowCategory: Comfy_NodeSearchBoxImpl_ShowCategory$1,
  Comfy_NodeSearchBoxImpl_ShowIdName: Comfy_NodeSearchBoxImpl_ShowIdName$1,
  Comfy_NodeSearchBoxImpl_ShowNodeFrequency: Comfy_NodeSearchBoxImpl_ShowNodeFrequency$1,
  Comfy_NodeSuggestions_number: Comfy_NodeSuggestions_number$1,
  Comfy_Node_AllowImageSizeDraw: Comfy_Node_AllowImageSizeDraw$1,
  Comfy_Node_AutoSnapLinkToSlot: Comfy_Node_AutoSnapLinkToSlot$1,
  Comfy_Node_BypassAllLinksOnDelete: Comfy_Node_BypassAllLinksOnDelete$1,
  Comfy_Node_DoubleClickTitleToEdit: Comfy_Node_DoubleClickTitleToEdit$1,
  Comfy_Node_MiddleClickRerouteNode: Comfy_Node_MiddleClickRerouteNode$1,
  Comfy_Node_Opacity: Comfy_Node_Opacity$1,
  Comfy_Node_ShowDeprecated: Comfy_Node_ShowDeprecated$1,
  Comfy_Node_ShowExperimental: Comfy_Node_ShowExperimental$1,
  Comfy_Node_SnapHighlightsNode: Comfy_Node_SnapHighlightsNode$1,
  Comfy_Pointer_ClickBufferTime: Comfy_Pointer_ClickBufferTime$1,
  Comfy_Pointer_ClickDrift: Comfy_Pointer_ClickDrift$1,
  Comfy_Pointer_DoubleClickTime: Comfy_Pointer_DoubleClickTime$1,
  Comfy_PreviewFormat: Comfy_PreviewFormat$1,
  Comfy_PromptFilename: Comfy_PromptFilename$1,
  Comfy_QueueButton_BatchCountLimit: Comfy_QueueButton_BatchCountLimit$1,
  Comfy_Queue_MaxHistoryItems: Comfy_Queue_MaxHistoryItems$1,
  Comfy_Sidebar_Location: Comfy_Sidebar_Location$1,
  Comfy_Sidebar_Size: Comfy_Sidebar_Size$1,
  Comfy_Sidebar_UnifiedWidth: Comfy_Sidebar_UnifiedWidth$1,
  Comfy_SnapToGrid_GridSize: Comfy_SnapToGrid_GridSize$1,
  Comfy_TextareaWidget_FontSize: Comfy_TextareaWidget_FontSize$1,
  Comfy_TextareaWidget_Spellcheck: Comfy_TextareaWidget_Spellcheck$1,
  Comfy_TreeExplorer_ItemPadding: Comfy_TreeExplorer_ItemPadding$1,
  Comfy_UseNewMenu: Comfy_UseNewMenu$1,
  Comfy_Validation_NodeDefs: Comfy_Validation_NodeDefs$1,
  Comfy_Validation_Workflows: Comfy_Validation_Workflows$1,
  Comfy_WidgetControlMode: Comfy_WidgetControlMode$1,
  Comfy_Window_UnloadConfirmation: Comfy_Window_UnloadConfirmation$1,
  Comfy_Workflow_AutoSave: Comfy_Workflow_AutoSave$1,
  Comfy_Workflow_AutoSaveDelay: Comfy_Workflow_AutoSaveDelay$1,
  Comfy_Workflow_ConfirmDelete: Comfy_Workflow_ConfirmDelete$1,
  Comfy_Workflow_Persist: Comfy_Workflow_Persist$1,
  Comfy_Workflow_ShowMissingModelsWarning: Comfy_Workflow_ShowMissingModelsWarning$1,
  Comfy_Workflow_ShowMissingNodesWarning: Comfy_Workflow_ShowMissingNodesWarning$1,
  Comfy_Workflow_SortNodeIdOnSave: Comfy_Workflow_SortNodeIdOnSave$1,
  Comfy_Workflow_WorkflowTabsPosition: Comfy_Workflow_WorkflowTabsPosition$1,
  LiteGraph_Canvas_LowQualityRenderingZoomThreshold: LiteGraph_Canvas_LowQualityRenderingZoomThreshold$1,
  LiteGraph_Canvas_MaximumFps: LiteGraph_Canvas_MaximumFps$1,
  LiteGraph_ContextMenu_Scaling: LiteGraph_ContextMenu_Scaling$1,
  LiteGraph_Node_DefaultPadding: LiteGraph_Node_DefaultPadding$1,
  LiteGraph_Node_TooltipDelay: LiteGraph_Node_TooltipDelay$1,
  LiteGraph_Pointer_TrackpadGestures: LiteGraph_Pointer_TrackpadGestures$1,
  LiteGraph_Reroute_SplineOffset: LiteGraph_Reroute_SplineOffset$1,
  pysssss_SnapToGrid: pysssss_SnapToGrid$1
};
const Comfy_BrowseTemplates = {
  label: "浏览模板"
};
const Comfy_Canvas_DeleteSelectedItems = {
  label: "删除选定的项目"
};
const Comfy_Canvas_FitView = {
  label: "适应视图到选中节点"
};
const Comfy_Canvas_ResetView = {
  label: "重置视图"
};
const Comfy_Canvas_Resize = {
  label: "调整选定节点的大小"
};
const Comfy_Canvas_ToggleLinkVisibility = {
  label: "切换链接可见性"
};
const Comfy_Canvas_ToggleLock = {
  label: "锁定视图"
};
const Comfy_Canvas_ToggleSelectedNodes_Bypass = {
  label: "忽略/取消忽略选中节点"
};
const Comfy_Canvas_ToggleSelectedNodes_Collapse = {
  label: "折叠/展开选中节点"
};
const Comfy_Canvas_ToggleSelectedNodes_Mute = {
  label: "静音/取消静音选中节点"
};
const Comfy_Canvas_ToggleSelectedNodes_Pin = {
  label: "固定/取消固定选中节点"
};
const Comfy_Canvas_ToggleSelected_Pin = {
  label: "固定/取消固定选中项"
};
const Comfy_Canvas_ZoomIn = {
  label: "放大"
};
const Comfy_Canvas_ZoomOut = {
  label: "缩小"
};
const Comfy_ClearPendingTasks = {
  label: "清除待处理任务"
};
const Comfy_ClearWorkflow = {
  label: "清除工作流"
};
const Comfy_ContactSupport = {
  label: "联系支持"
};
const Comfy_DuplicateWorkflow = {
  label: "复制当前工作流"
};
const Comfy_ExportWorkflow = {
  label: "导出工作流"
};
const Comfy_ExportWorkflowAPI = {
  label: "导出工作流（API格式）"
};
const Comfy_Feedback = {
  label: "反馈"
};
const Comfy_Graph_FitGroupToContents = {
  label: "适应节点框到内容"
};
const Comfy_Graph_GroupSelectedNodes = {
  label: "添加框到选中节点"
};
const Comfy_GroupNode_ConvertSelectedNodesToGroupNode = {
  label: "将选中节点转换为组节点"
};
const Comfy_GroupNode_ManageGroupNodes = {
  label: "管理组节点"
};
const Comfy_GroupNode_UngroupSelectedGroupNodes = {
  label: "解散选中组节点"
};
const Comfy_Help_AboutComfyUI = {
  label: "打开关于ComfyUI"
};
const Comfy_Help_OpenComfyOrgDiscord = {
  label: "打开Comfy-Org Discord"
};
const Comfy_Help_OpenComfyUIDocs = {
  label: "打开ComfyUI文档"
};
const Comfy_Help_OpenComfyUIForum = {
  label: "打开 Comfy-Org 论坛"
};
const Comfy_Help_OpenComfyUIIssues = {
  label: "打开ComfyUI问题"
};
const Comfy_Interrupt = {
  label: "中断"
};
const Comfy_LoadDefaultWorkflow = {
  label: "加载默认工作流"
};
const Comfy_Manager_CustomNodesManager = {
  label: "自定义节点管理器"
};
const Comfy_Manager_ToggleManagerProgressDialog = {
  label: "切换进度对话框"
};
const Comfy_NewBlankWorkflow = {
  label: "新建空白工作流"
};
const Comfy_OpenClipspace = {
  label: "打开剪贴板"
};
const Comfy_OpenWorkflow = {
  label: "打开工作流"
};
const Comfy_QueuePrompt = {
  label: "执行提示词"
};
const Comfy_QueuePromptFront = {
  label: "执行提示词（前端）"
};
const Comfy_QueueSelectedOutputNodes = {
  label: "队列所选输出节点"
};
const Comfy_Redo = {
  label: "重做"
};
const Comfy_RefreshNodeDefinitions = {
  label: "刷新节点定义"
};
const Comfy_SaveWorkflow = {
  label: "保存工作流"
};
const Comfy_SaveWorkflowAs = {
  label: "另存工作流"
};
const Comfy_ShowSettingsDialog = {
  label: "显示设置对话框"
};
const Comfy_ToggleTheme = {
  label: "切换主题"
};
const Comfy_Undo = {
  label: "撤销"
};
const Comfy_User_OpenSignInDialog = {
  label: "打开登录对话框"
};
const Comfy_User_SignOut = {
  label: "退出登录"
};
const Workspace_CloseWorkflow = {
  label: "关闭当前工作流"
};
const Workspace_NextOpenedWorkflow = {
  label: "下一个打开的工作流"
};
const Workspace_PreviousOpenedWorkflow = {
  label: "上一个打开的工作流"
};
const Workspace_SearchBox_Toggle = {
  label: "切换搜索框"
};
const Workspace_ToggleBottomPanel = {
  label: "切换底部面板"
};
const Workspace_ToggleFocusMode = {
  label: "切换焦点模式"
};
const Workspace_ToggleSidebarTab_queue = {
  label: "切换执行队列侧边栏",
  tooltip: "执行队列"
};
const Workspace_ToggleSidebarTab_workflows = {
  label: "切换工作流侧边栏",
  tooltip: "工作流"
};
const zhCommands = {
  "Comfy-Desktop_CheckForUpdates": {
    label: "检查更新"
  },
  "Comfy-Desktop_Folders_OpenCustomNodesFolder": {
    label: "打开自定义节点文件夹"
  },
  "Comfy-Desktop_Folders_OpenInputsFolder": {
    label: "打开输入文件夹"
  },
  "Comfy-Desktop_Folders_OpenLogsFolder": {
    label: "打开日志文件夹"
  },
  "Comfy-Desktop_Folders_OpenModelConfig": {
    label: "打开 extra_model_paths.yaml"
  },
  "Comfy-Desktop_Folders_OpenModelsFolder": {
    label: "打开模型文件夹"
  },
  "Comfy-Desktop_Folders_OpenOutputsFolder": {
    label: "打开输出文件夹"
  },
  "Comfy-Desktop_OpenDevTools": {
    label: "打开开发者工具"
  },
  "Comfy-Desktop_OpenUserGuide": {
    label: "桌面用户指南"
  },
  "Comfy-Desktop_Quit": {
    label: "退出"
  },
  "Comfy-Desktop_Reinstall": {
    label: "重新安装"
  },
  "Comfy-Desktop_Restart": {
    label: "重启"
  },
  Comfy_BrowseTemplates,
  Comfy_Canvas_DeleteSelectedItems,
  Comfy_Canvas_FitView,
  Comfy_Canvas_ResetView,
  Comfy_Canvas_Resize,
  Comfy_Canvas_ToggleLinkVisibility,
  Comfy_Canvas_ToggleLock,
  Comfy_Canvas_ToggleSelectedNodes_Bypass,
  Comfy_Canvas_ToggleSelectedNodes_Collapse,
  Comfy_Canvas_ToggleSelectedNodes_Mute,
  Comfy_Canvas_ToggleSelectedNodes_Pin,
  Comfy_Canvas_ToggleSelected_Pin,
  Comfy_Canvas_ZoomIn,
  Comfy_Canvas_ZoomOut,
  Comfy_ClearPendingTasks,
  Comfy_ClearWorkflow,
  Comfy_ContactSupport,
  Comfy_DuplicateWorkflow,
  Comfy_ExportWorkflow,
  Comfy_ExportWorkflowAPI,
  Comfy_Feedback,
  Comfy_Graph_FitGroupToContents,
  Comfy_Graph_GroupSelectedNodes,
  Comfy_GroupNode_ConvertSelectedNodesToGroupNode,
  Comfy_GroupNode_ManageGroupNodes,
  Comfy_GroupNode_UngroupSelectedGroupNodes,
  Comfy_Help_AboutComfyUI,
  Comfy_Help_OpenComfyOrgDiscord,
  Comfy_Help_OpenComfyUIDocs,
  Comfy_Help_OpenComfyUIForum,
  Comfy_Help_OpenComfyUIIssues,
  Comfy_Interrupt,
  Comfy_LoadDefaultWorkflow,
  Comfy_Manager_CustomNodesManager,
  Comfy_Manager_ToggleManagerProgressDialog,
  Comfy_NewBlankWorkflow,
  Comfy_OpenClipspace,
  Comfy_OpenWorkflow,
  Comfy_QueuePrompt,
  Comfy_QueuePromptFront,
  Comfy_QueueSelectedOutputNodes,
  Comfy_Redo,
  Comfy_RefreshNodeDefinitions,
  Comfy_SaveWorkflow,
  Comfy_SaveWorkflowAs,
  Comfy_ShowSettingsDialog,
  Comfy_ToggleTheme,
  Comfy_Undo,
  Comfy_User_OpenSignInDialog,
  Comfy_User_SignOut,
  Workspace_CloseWorkflow,
  Workspace_NextOpenedWorkflow,
  Workspace_PreviousOpenedWorkflow,
  Workspace_SearchBox_Toggle,
  Workspace_ToggleBottomPanel,
  "Workspace_ToggleBottomPanelTab_command-terminal": {
    label: "切换终端底部面板"
  },
  "Workspace_ToggleBottomPanelTab_logs-terminal": {
    label: "切换日志底部面板"
  },
  Workspace_ToggleFocusMode,
  "Workspace_ToggleSidebarTab_model-library": {
    label: "切换模型库侧边栏",
    tooltip: "模型库"
  },
  "Workspace_ToggleSidebarTab_node-library": {
    label: "切换节点库侧边栏",
    tooltip: "节点库"
  },
  Workspace_ToggleSidebarTab_queue,
  Workspace_ToggleSidebarTab_workflows
};
const apiNodesCostBreakdown = {
  costPerRun: "每次运行的成本",
  title: "API节点",
  totalCost: "总成本"
};
const apiNodesNews = {
  introducing: "介绍",
  steps: {
    step1: {
      subtitle: "设置 > 用户 > 登录",
      title: "登录/创建账户："
    },
    step2: {
      subtitle: "设置 > 积分 > 购买积分",
      title: "购买积分："
    },
    step3: {
      title: "在“API 节点”部分找到新的 API 节点并添加到画布"
    },
    step4: {
      title: "运行！"
    }
  },
  subtitle: "所有外部模型现已在 ComfyUI 中可用"
};
const apiNodesSignInDialog = {
  message: "此工作流包含API节点，需要您登录账户才能运行。",
  title: "使用API节点需要登录"
};
const auth = {
  apiKey: {
    cleared: "API 密钥已清除",
    clearedDetail: "您的 API 密钥已成功清除",
    description: "使用您的 Comfy API 密钥以启用 API 节点",
    error: "无效的 API 密钥",
    generateKey: "在这里获取",
    helpText: "需要 API 密钥？",
    invalid: "无效的 API 密钥",
    invalidDetail: "请输入有效的 API 密钥",
    label: "API 密钥",
    placeholder: "请输入您的 API 密钥",
    storageFailed: "API 密钥存储失败",
    storageFailedDetail: "请重试。",
    stored: "API 密钥已存储",
    storedDetail: "您的 API 密钥已成功存储",
    title: "API 密钥",
    whitelistInfo: "关于非白名单网站"
  },
  login: {
    andText: "和",
    confirmPasswordLabel: "确认密码",
    confirmPasswordPlaceholder: "再次输入相同的密码",
    emailLabel: "电子邮件",
    emailPlaceholder: "输入您的电子邮件",
    failed: "登录失败",
    forgotPassword: "忘记密码？",
    forgotPasswordError: "发送重置密码邮件失败",
    insecureContextWarning: "此连接不安全（HTTP）—如果继续登录，您的凭据可能会被攻击者拦截。",
    loginButton: "登录",
    loginWithGithub: "使用Github登录",
    loginWithGoogle: "使用Google登录",
    newUser: "新来的？",
    noAssociatedUser: "所提供的 API 密钥未关联任何 Comfy 用户",
    orContinueWith: "或者继续使用",
    passwordLabel: "密码",
    passwordPlaceholder: "输入您的密码",
    passwordResetSent: "重置密码邮件已发送",
    passwordResetSentDetail: "请查收您的电子邮件，点击链接重置密码。",
    privacyLink: "隐私政策",
    questionsContactPrefix: "有疑问？请联系我们：",
    signInOrSignUp: "登录 / 注册",
    signUp: "注册",
    success: "登录成功",
    termsLink: "使用条款",
    termsText: "点击“下一步”或“注册”即表示您同意我们的",
    title: "登录您的账户",
    useApiKey: "Comfy API 密钥",
    userAvatar: "用户头像"
  },
  passwordUpdate: {
    success: "密码已更新",
    successDetail: "您的密码已成功更新"
  },
  signOut: {
    signOut: "退出登录",
    success: "成功退出登录",
    successDetail: "您已成功退出账户。"
  },
  signup: {
    alreadyHaveAccount: "已经有账户了？",
    emailLabel: "电子邮件",
    emailPlaceholder: "输入您的电子邮件",
    passwordLabel: "密码",
    passwordPlaceholder: "输入新密码",
    personalDataConsentLabel: "我同意处理我的个人数据。",
    regionRestrictionChina: "根据当地法规要求，我们暂时无法为中国地区的用户提供服务。",
    signIn: "登录",
    signUpButton: "注册",
    signUpWithGithub: "使用Github注册",
    signUpWithGoogle: "使用Google注册",
    title: "创建一个账户"
  }
};
const clipboard = {
  errorMessage: "复制到剪贴板失败",
  errorNotSupported: "您的浏览器不支持剪贴板API",
  successMessage: "已复制到剪贴板"
};
const color = {
  black: "黑色",
  blue: "蓝色",
  brown: "棕色",
  custom: "自定义",
  cyan: "青色",
  "default": "默认",
  green: "绿色",
  noColor: "无色",
  pale_blue: "淡蓝色",
  pink: "粉色",
  purple: "紫色",
  red: "红色",
  yellow: "黄色"
};
const contextMenu = {
  "Add Group": "添加组",
  "Add Group For Selected Nodes": "为选定节点添加组",
  "Add Node": "添加节点",
  Bypass: "绕过",
  Clone: "克隆",
  Collapse: "折叠",
  Colors: "颜色",
  "Convert to Group Node": "转换为组节点",
  "Copy (Clipspace)": "复制 (Clipspace)",
  Expand: "展开",
  Inputs: "输入",
  Manage: "管理",
  "Manage Group Nodes": "管理组节点",
  Mode: "模式",
  "Node Templates": "节点模板",
  Outputs: "输出",
  Pin: "固定",
  Properties: "属性",
  "Properties Panel": "属性面板",
  Remove: "删除",
  Resize: "调整大小",
  "Save Selected as Template": "将选定节点另存为模板",
  Search: "搜索",
  Shapes: "形状",
  Title: "标题",
  Unpin: "取消固定"
};
const credits = {
  apiPricing: "API 价格",
  credits: "积分",
  faqs: "常见问题",
  invoiceHistory: "发票历史",
  lastUpdated: "最近更新",
  messageSupport: "联系客服",
  purchaseCredits: "购买积分",
  topUp: {
    buyNow: "立即购买",
    insufficientMessage: "您的积分不足，无法运行此工作流。",
    insufficientTitle: "积分不足",
    maxAmount: "（最高 $1,000 美元）",
    quickPurchase: "快速购买",
    seeDetails: "查看详情",
    topUp: "充值"
  },
  yourCreditBalance: "您的积分余额"
};
const dataTypes = {
  "*": "*",
  AUDIO: "音频",
  BOOLEAN: "布尔",
  CAMERA_CONTROL: "相机控制",
  CLIP: "CLIP",
  CLIP_VISION: "CLIP视觉",
  CLIP_VISION_OUTPUT: "CLIP视觉输出",
  COMBO: "组合",
  CONDITIONING: "条件",
  CONTROL_NET: "ControlNet",
  FLOAT: "浮点",
  FLOATS: "浮点组",
  GLIGEN: "GLIGEN",
  GUIDER: "引导器",
  HOOKS: "约束",
  HOOK_KEYFRAMES: "约束关键帧",
  IMAGE: "图像",
  INT: "整数",
  LATENT: "Latent",
  LATENT_OPERATION: "Latent操作",
  LOAD3D_CAMERA: "加载3D相机",
  LOAD_3D: "加载3D",
  LOAD_3D_ANIMATION: "加载3D动画",
  LUMA_CONCEPTS: "Luma 概念",
  LUMA_REF: "Luma 参考",
  MASK: "遮罩",
  MESH: "网格",
  MODEL: "模型",
  NOISE: "噪波",
  PHOTOMAKER: "PhotoMaker",
  PIXVERSE_TEMPLATE: "Pixverse 模板",
  RECRAFT_COLOR: "Recraft 颜色",
  RECRAFT_CONTROLS: "Recraft 控件",
  RECRAFT_V3_STYLE: "Recraft V3 风格",
  SAMPLER: "采样器",
  SIGMAS: "Sigmas",
  STRING: "字符串",
  STYLE_MODEL: "风格模型",
  SVG: "SVG",
  TIMESTEPS_RANGE: "时间间隔范围",
  UPSCALE_MODEL: "放大模型",
  VAE: "VAE",
  VIDEO: "视频",
  VOXEL: "体素",
  WEBCAM: "摄像头"
};
const desktopMenu = {
  confirmQuit: "有未保存的工作流程开启；任何未保存的更改都将丢失。忽略此警告并退出？",
  confirmReinstall: "这将清除您的 extra_models_config.yaml 文件，并重新开始安装。您确定吗？",
  quit: "退出",
  reinstall: "重新安装"
};
const desktopUpdate = {
  description: "ComfyUI桌面正在安装新的依赖项。这可能需要几分钟的时间。",
  errorCheckingUpdate: "检查更新时出错",
  errorInstallingUpdate: "安装更新时出错",
  noUpdateFound: "未发现更新",
  terminalDefaultMessage: "更新过程中的任何控制台输出都将在这里显示。",
  title: "正在更新ComfyUI桌面",
  updateAvailableMessage: "有可用的更新。您现在要重启并更新吗？",
  updateFoundTitle: "找到更新 (v{version})"
};
const downloadGit = {
  gitWebsite: "下载 git",
  instructions: "请下载并安装适合您操作系统的最新版本。下面的下载 git 按钮将打开 git-scm.com 下载页面。",
  message: "无法找到 git。正常操作需要一个可用的 git 副本。",
  skip: "跳过",
  title: "下载 git",
  warning: "如果您确定不需要安装 git，或者已经安装了 git，您可以点击跳过以绕过此检查。当前不支持在没有可用 git 副本的情况下运行 ComfyUI。"
};
const electronFileDownload = {
  cancel: "取消下载",
  cancelled: "已取消",
  inProgress: "进行中",
  pause: "暂停下载",
  paused: "已暂停",
  resume: "恢复下载"
};
const errorDialog = {
  defaultTitle: "发生错误",
  extensionFileHint: "这可能是由于以下脚本",
  loadWorkflowTitle: "由于重新加载工作流数据出错，加载被中止",
  noStackTrace: "无可用堆栈跟踪",
  promptExecutionError: "提示执行失败"
};
const g = {
  about: "关于",
  add: "添加",
  all: "全部",
  amount: "数量",
  apply: "应用",
  back: "返回",
  cancel: "取消",
  capture: "捕获",
  category: "类别",
  choose_file_to_upload: "选择要上传的文件",
  close: "关闭",
  color: "颜色",
  comingSoon: "即将推出",
  command: "指令",
  community: "社区",
  completed: "已完成",
  confirm: "确认",
  confirmed: "已确认",
  "continue": "继续",
  control_after_generate: "生成后控制",
  control_before_generate: "生成前控制",
  copyToClipboard: "复制到剪贴板",
  currentUser: "当前用户",
  customize: "自定义",
  customizeFolder: "自定义文件夹",
  "delete": "删除",
  deprecated: "已弃用",
  description: "描述",
  devices: "设备",
  disableAll: "禁用全部",
  disabling: "禁用中",
  download: "下载",
  empty: "空",
  enableAll: "启用全部",
  enabled: "已启用",
  enabling: "启用中",
  error: "错误",
  experimental: "测试版",
  "export": "导出",
  extensionName: "扩展名称",
  feedback: "反馈",
  filter: "过滤",
  findIssues: "查找问题",
  firstTimeUIMessage: '这是您第一次使用新界面。选择 "菜单 > 使用新菜单 > 禁用" 来恢复旧界面。',
  goToNode: "转到节点",
  icon: "图标",
  imageFailedToLoad: "图像加载失败",
  "import": "导入",
  inProgress: "进行中",
  insert: "插入",
  install: "安装",
  installed: "已安装",
  installing: "正在安装",
  interrupted: "已中断",
  keybinding: "按键绑定",
  learnMore: "了解更多",
  loadAllFolders: "加载所有文件夹",
  loadWorkflow: "加载工作流",
  loading: "加载中",
  login: "登录",
  logs: "日志",
  migrate: "迁移",
  missing: "缺失",
  name: "名称",
  newFolder: "新文件夹",
  next: "下一个",
  no: "否",
  noResultsFound: "未找到结果",
  noTasksFound: "未找到任务",
  noTasksFoundMessage: "队列中没有任务。",
  noWorkflowsFound: "未找到工作流。",
  nodes: "节点",
  ok: "确定",
  openNewIssue: "打开新问题",
  overwrite: "覆盖",
  reconnected: "已重新连接",
  reconnecting: "重新连接中",
  refresh: "刷新",
  reloadToApplyChanges: "重新加载以应用更改",
  rename: "重命名",
  reportIssue: "发送报告",
  reportIssueTooltip: "向 Comfy Org 提交错误报告",
  reportSent: "报告已提交",
  reset: "重置",
  resetAll: "重置所有",
  resetAllKeybindingsTooltip: "将所有键绑定重置为默认",
  restart: "重新启动",
  resultsCount: "找到 {count} 个结果",
  save: "保存",
  saving: "正在保存",
  searchExtensions: "搜索扩展",
  searchFailedMessage: "我们找不到任何与您的搜索匹配的设置。请尝试调整您的搜索词。",
  searchKeybindings: "搜索快捷键",
  searchModels: "搜索模型",
  searchNodes: "搜索节点",
  searchSettings: "搜索设置",
  searchWorkflows: "搜索工作流",
  settings: "设置",
  showReport: "显示报告",
  sort: "排序",
  source: "来源",
  status: "状态",
  success: "成功",
  systemInfo: "系统信息",
  terminal: "终端",
  title: "标题",
  unknownError: "未知错误",
  update: "更新",
  updateAvailable: "有更新可用",
  updated: "已更新",
  updating: "更新中",
  upload: "上传",
  user: "用户",
  videoFailedToLoad: "视频加载失败",
  workflow: "工作流"
};
const graphCanvasMenu = {
  fitView: "适应视图",
  panMode: "平移模式",
  resetView: "重置视图",
  selectMode: "选择模式",
  toggleLinkVisibility: "切换连线可见性",
  zoomIn: "放大",
  zoomOut: "缩小"
};
const groupNode = {
  create: "创建组节点",
  enterName: "输入名称"
};
const icon = {
  bookmark: "书签",
  box: "盒子",
  briefcase: "公文包",
  "exclamation-triangle": "警告",
  file: "文件",
  folder: "文件夹",
  heart: "心",
  inbox: "收件箱",
  star: "星星"
};
const install = {
  appDataLocationTooltip: "ComfyUI 的应用数据目录。存储：\n- 日志\n- 服务器配置",
  appPathLocationTooltip: "ComfyUI 的应用资产目录。存储 ComfyUI 代码和资产",
  cannotWrite: "无法写入所选路径。",
  chooseInstallationLocation: "选择安装位置",
  customNodes: "自定义节点",
  customNodesDescription: "引用现有 ComfyUI 安装的自定义节点文件并安装其依赖项。",
  desktopAppSettings: "桌面应用设置",
  desktopAppSettingsDescription: "配置 ComfyUI 在桌面上的行为。您可以稍后更改这些设置。",
  desktopSettings: "桌面设置",
  failedToSelectDirectory: "选择目录失败",
  gpu: "GPU",
  gpuSelection: {
    cpuMode: "CPU 模式",
    cpuModeDescription: "CPU 模式仅适用于开发者和极少数特殊情况。",
    cpuModeDescription2: "如果你不完全确定你需要这个，忽略该选项并在上面选择你的 GPU。",
    customComfyNeedsPython: "在 python 完成设置前，ComfyUI 将无法工作",
    customInstallRequirements: "安装所有需求和依赖项（例如：自定义 torch）",
    customManualVenv: "手动配置 python 虚拟环境",
    customMayNotWork: "完全不支持，可能无法工作",
    customSkipsPython: "此选项跳过正常的 python 设置。",
    enableCpuMode: "启用 CPU 模式",
    mpsDescription: "Apple Metal Performance Shaders 使用 pytorch nightly 支持。",
    nvidiaDescription: "NVIDIA 设备直接支持使用 pytorch CUDA 构建。",
    selectGpu: "选择 GPU",
    selectGpuDescription: "选择你拥有的 GPU 类型"
  },
  helpImprove: "请帮助我们改进ComfyUI",
  installLocation: "安装位置",
  installLocationDescription: "选择 ComfyUI 用户数据的存放目录。将安装一个 Python 环境到所选位置。请确保所选磁盘有足够的空间（约 15GB）。",
  installLocationTooltip: "ComfyUI 的用户数据目录。存储：\n- Python 环境\n- 模型\n- 自定义节点\n",
  insufficientFreeSpace: "空间不足 - 最小可用空间",
  isOneDrive: "在OneDrive中安装可能会导致问题。强烈建议在非OneDrive位置安装。",
  manualConfiguration: {
    createVenv: "您需要在以下目录中创建虚拟环境",
    requirements: "依赖项",
    restartWhenFinished: "配置虚拟环境完成后，请重新启动ComfyUI。",
    title: "手动配置",
    virtualEnvironmentPath: "虚拟环境路径"
  },
  metricsDisabled: "禁用度量",
  metricsEnabled: "启用度量",
  migrateFromExistingInstallation: "从现有安装迁移",
  migration: "迁移",
  migrationOptional: "迁移是可选的。如果您之前没有安装过 ComfyUI，可以跳过此步骤。",
  migrationSourcePathDescription: "如果您已有现有的ComfyUI安装，我们可以复制/链接您现有的用户文件和模型到新的安装。您现有的ComfyUI安装将不会受到影响。",
  moreInfo: "有关更多信息，请阅读我们的",
  nonDefaultDrive: "请在您的系统驱动器上安装ComfyUI（例如C:\\）。具有不同文件系统的驱动器可能会导致不可预测的问题。安装后，模型和其他文件可以存储在其他驱动器上。",
  parentMissing: "路径不存在 - 请先创建包含该路径的目录",
  pathExists: "目录已存在 - 请确保您已备份全部数据",
  pathValidationFailed: "路径验证失败",
  privacyPolicy: "隐私政策",
  selectItemsToMigrate: "选择要迁移的项目",
  settings: {
    allowMetrics: "使用情况指标",
    allowMetricsDescription: "通过发送匿名使用情况指标来帮助改进ComfyUI。不会收集任何个人信息或工作流内容。",
    autoUpdate: "自动更新",
    autoUpdateDescription: "更新可用时自动更新。您将在安装更新之前收到通知。",
    checkingMirrors: "正在检查到Python镜像的网络访问...",
    dataCollectionDialog: {
      collect: {
        errorReports: "错误报告和堆栈跟踪",
        systemInfo: "硬件，操作系统类型和应用版本",
        userJourneyEvents: "用户旅程事件"
      },
      doNotCollect: {
        customNodeConfigurations: "自定义节点配置",
        fileSystemInformation: "文件系统信息",
        personalInformation: "个人信息",
        workflowContents: "工作流内容"
      },
      title: "关于数据收集",
      viewFullPolicy: "查看完整政策",
      whatWeCollect: "我们收集的内容：",
      whatWeDoNotCollect: "我们不收集的内容："
    },
    errorUpdatingConsent: "更新同意错误",
    errorUpdatingConsentDetail: "无法更新度量同意设置",
    learnMoreAboutData: "了解更多关于数据收集的信息",
    mirrorSettings: "镜像设置",
    mirrorsReachable: "到Python镜像的网络访问良好",
    mirrorsUnreachable: "对某些python镜像的网络访问不佳",
    pypiMirrorPlaceholder: "输入PyPI镜像URL",
    pythonMirrorPlaceholder: "输入Python镜像URL"
  },
  systemLocations: "系统位置",
  unhandledError: "未知错误",
  updateConsent: "您之前选择了报告崩溃。我们现在正在跟踪基于事件的度量，以帮助识别错误并改进应用程序。我们不收集任何个人可识别信息。"
};
const issueReport = {
  contactFollowUp: "跟进联系我",
  contactSupportDescription: "请填写下方表格提交您的报告",
  contactSupportTitle: "联系支持",
  describeTheProblem: "描述问题",
  email: "电子邮箱",
  feedbackTitle: "通过提供反馈帮助我们改进ComfyUI",
  helpFix: "帮助修复这个",
  helpTypes: {
    billingPayments: "账单 / 支付",
    bugReport: "错误报告",
    giveFeedback: "提交反馈",
    loginAccessIssues: "登录 / 访问问题",
    somethingElse: "其他"
  },
  notifyResolve: "解决时通知我",
  provideAdditionalDetails: "提供额外的详细信息（可选）",
  provideEmail: "提供您的电子邮件（可选）",
  rating: "评分",
  selectIssue: "选择问题",
  stackTrace: "堆栈跟踪",
  submitErrorReport: "提交错误报告（可选）",
  systemStats: "系统状态",
  validation: {
    invalidEmail: "请输入有效的电子邮件地址",
    maxLength: "消息过长",
    selectIssueType: "请选择一个问题类型"
  },
  whatCanWeInclude: "请说明报告中需要包含的内容",
  whatDoYouNeedHelpWith: "您需要什么帮助？"
};
const load3d = {
  applyingTexture: "应用纹理中...",
  backgroundColor: "背景颜色",
  camera: "摄影机",
  clearRecording: "清除录制",
  edgeThreshold: "边缘阈值",
  "export": "导出",
  exportModel: "导出模型",
  exportRecording: "导出录制",
  exportingModel: "正在导出模型...",
  fov: "视场",
  light: "灯光",
  lightIntensity: "光照强度",
  loadingModel: "正在加载3D模型...",
  materialMode: "材质模式",
  materialModes: {
    depth: "深度",
    lineart: "线稿",
    normal: "法线",
    original: "原始",
    wireframe: "线框"
  },
  model: "模型",
  previewOutput: "预览输出",
  removeBackgroundImage: "移除背景图片",
  resizeNodeMatchOutput: "调整节点以匹配输出",
  scene: "场景",
  showGrid: "显示网格",
  startRecording: "开始录制",
  stopRecording: "停止录制",
  switchCamera: "切换摄影机类型",
  switchingMaterialMode: "切换材质模式中...",
  upDirection: "上方向",
  uploadBackgroundImage: "上传背景图片",
  uploadTexture: "上传纹理"
};
const maintenance = {
  None: "无",
  OK: "确定",
  Skipped: "跳过",
  allOk: "未检测到任何问题。",
  confirmTitle: "你确定吗？",
  consoleLogs: "控制台日志",
  detected: "检测到",
  error: {
    cannotContinue: "无法继续 - 仍有错误",
    defaultDescription: "运行维护任务时发生错误。",
    taskFailed: "任务运行失败。",
    toastTitle: "任务错误"
  },
  refreshing: "刷新中",
  showManual: "显示维护任务",
  status: "状态",
  terminalDefaultMessage: "当你运行一个故障排除命令时，任何输出都会在这里显示。",
  title: "维护"
};
const manager = {
  changingVersion: "将版本从 {from} 更改为 {to}",
  createdBy: "创建者",
  dependencies: "依赖关系",
  discoverCommunityContent: "发现社区制作的节点包，扩展等等...",
  downloads: "下载",
  errorConnecting: "连接到Comfy节点注册表时出错。",
  failed: "失败 ({count})",
  filter: {
    disabled: "已禁用",
    enabled: "已启用",
    nodePack: "节点包"
  },
  inWorkflow: "在工作流中",
  infoPanelEmpty: "点击一个项目查看信息",
  installSelected: "安装选定",
  installationQueue: "安装队列",
  lastUpdated: "最后更新",
  latestVersion: "最新",
  license: "许可证",
  loadingVersions: "正在加载版本...",
  nightlyVersion: "每夜",
  noDescription: "无可用描述",
  noNodesFound: "未找到节点",
  noNodesFoundDescription: "无法解析包的节点，或者该包仅为前端扩展，没有任何节点。",
  noResultsFound: "未找到符合您搜索的结果。",
  nodePack: "节点包",
  packsSelected: "选定的包",
  repository: "仓库",
  restartToApplyChanges: "要应用更改，请重新启动ComfyUI",
  searchPlaceholder: "搜索",
  selectVersion: "选择版本",
  sort: {
    created: "最新",
    downloads: "最受欢迎",
    publisher: "出版商",
    updated: "最近更新"
  },
  status: {
    active: "活跃",
    banned: "已禁止",
    deleted: "已删除",
    flagged: "已标记",
    pending: "待定",
    unknown: "未知"
  },
  title: "自定义节点管理器",
  totalNodes: "节点总数",
  tryAgainLater: "请稍后再试。",
  tryDifferentSearch: "请尝试不同的搜索查询。",
  uninstall: "卸载",
  uninstallSelected: "卸载所选",
  uninstalling: "正在卸载",
  update: "更新",
  updatingAllPacks: "更新所有包",
  version: "版本"
};
const maskEditor = {
  "Apply to Whole Image": "应用到整个图像",
  "Brush Settings": "笔刷设置",
  "Brush Shape": "笔刷形状",
  Clear: "清空",
  "Color Select Settings": "颜色选择设置",
  "Fill Opacity": "填充不透明度",
  Hardness: "硬度",
  "Image Layer": "图像图层",
  Invert: "反转",
  Layers: "图层",
  "Live Preview": "实时预览",
  "Mask Layer": "遮罩图层",
  "Mask Opacity": "遮罩不透明度",
  "Mask Tolerance": "遮罩容差",
  Method: "方法",
  Opacity: "不透明度",
  "Paint Bucket Settings": "油漆桶设置",
  "Reset to Default": "恢复默认",
  "Selection Opacity": "选区不透明度",
  "Smoothing Precision": "平滑精度",
  "Stop at mask": "在遮罩处停止",
  Thickness: "粗细",
  Tolerance: "容差"
};
const menu = {
  autoQueue: "自动执行",
  batchCount: "批次数量",
  batchCountTooltip: "工作流生成次数",
  clear: "清空工作流",
  clipspace: "打开剪贴板",
  disabled: "禁用",
  disabledTooltip: "工作流将不会自动执行",
  execute: "执行",
  hideMenu: "隐藏菜单",
  instant: "实时",
  instantTooltip: "工作流将会在生成完成后立即执行",
  interrupt: "取消当前任务",
  onChange: "更改时",
  onChangeTooltip: "一旦进行更改，工作流将添加到执行队列",
  refresh: "刷新节点",
  resetView: "重置视图",
  run: "运行",
  runWorkflow: "运行工作流程（Shift排在前面）",
  runWorkflowFront: "运行工作流程（排在前面）",
  showMenu: "显示菜单",
  toggleBottomPanel: "底部面板"
};
const menuLabels = {
  "About ComfyUI": "关于ComfyUI",
  "Browse Templates": "浏览模板",
  "Bypass/Unbypass Selected Nodes": "忽略/取消忽略选定节点",
  "Canvas Toggle Link Visibility": "切换连线可见性",
  "Canvas Toggle Lock": "切换视图锁定",
  "Check for Updates": "检查更新",
  "Clear Pending Tasks": "清除待处理任务",
  "Clear Workflow": "清除工作流",
  Clipspace: "剪贴空间",
  "Close Current Workflow": "关闭当前工作流",
  "Collapse/Expand Selected Nodes": "折叠/展开选定节点",
  "Comfy-Org Discord": "Comfy-Org Discord",
  "ComfyUI Docs": "ComfyUI 文档",
  "ComfyUI Forum": "ComfyUI 论坛",
  "ComfyUI Issues": "ComfyUI 问题",
  "Contact Support": "联系支持",
  "Convert selected nodes to group node": "将选中节点转换为组节点",
  "Custom Nodes Manager": "自定义节点管理器",
  "Delete Selected Items": "删除选定的项目",
  "Desktop User Guide": "桌面端用户指南",
  "Duplicate Current Workflow": "复制当前工作流",
  Edit: "编辑",
  Export: "导出",
  "Export (API)": "导出 (API)",
  "Fit Group To Contents": "适应组内容",
  "Fit view to selected nodes": "适应视图到选中节点",
  "Give Feedback": "提供反馈",
  "Group Selected Nodes": "将选中节点转换为组节点",
  Help: "帮助",
  Interrupt: "中断",
  "Load Default Workflow": "加载默认工作流",
  "Manage group nodes": "管理组节点",
  "Mute/Unmute Selected Nodes": "静音/取消静音选定节点",
  New: "新建",
  "Next Opened Workflow": "下一个打开的工作流",
  Open: "打开",
  "Open Custom Nodes Folder": "打开自定义节点文件夹",
  "Open DevTools": "打开开发者工具",
  "Open Inputs Folder": "打开输入文件夹",
  "Open Logs Folder": "打开日志文件夹",
  "Open Models Folder": "打开模型文件夹",
  "Open Outputs Folder": "打开输出文件夹",
  "Open Sign In Dialog": "打开登录对话框",
  "Open extra_model_paths_yaml": "打开 extra_model_paths.yaml",
  "Pin/Unpin Selected Items": "固定/取消固定选定项目",
  "Pin/Unpin Selected Nodes": "固定/取消固定选定节点",
  "Previous Opened Workflow": "上一个打开的工作流",
  "Queue Prompt": "执行提示词",
  "Queue Prompt (Front)": "执行提示词 (优先执行)",
  "Queue Selected Output Nodes": "将所选输出节点加入队列",
  Quit: "退出",
  Redo: "重做",
  "Refresh Node Definitions": "刷新节点定义",
  Reinstall: "重新安装",
  "Reset View": "重置视图",
  "Resize Selected Nodes": "调整选定节点的大小",
  Restart: "重启",
  Save: "保存",
  "Save As": "另存为",
  "Show Settings Dialog": "显示设置对话框",
  "Sign Out": "退出登录",
  "Toggle Bottom Panel": "切换底部面板",
  "Toggle Focus Mode": "切换专注模式",
  "Toggle Logs Bottom Panel": "切换日志底部面板",
  "Toggle Model Library Sidebar": "切换模型库侧边栏",
  "Toggle Node Library Sidebar": "切换节点库侧边栏",
  "Toggle Progress Dialog": "切换进度对话框",
  "Toggle Queue Sidebar": "切换队列侧边栏",
  "Toggle Search Box": "切换搜索框",
  "Toggle Terminal Bottom Panel": "切换终端底部面板",
  "Toggle Theme (Dark/Light)": "切换主题（暗/亮）",
  "Toggle Workflows Sidebar": "切换工作流侧边栏",
  Undo: "撤销",
  "Ungroup selected group nodes": "解散选中组节点",
  Workflow: "工作流",
  "Zoom In": "放大画面",
  "Zoom Out": "缩小画面"
};
const missingModelsDialog = {
  doNotAskAgain: "不再显示此消息",
  missingModels: "缺少模型",
  missingModelsMessage: "加载图表时，未找到以下模型"
};
const nodeCategories = {
  "3d": "3d",
  "3d_models": "3D模型",
  BFL: "BFL",
  Ideogram: "Ideogram",
  Kling: "Kling",
  Luma: "Luma",
  MiniMax: "MiniMax",
  OpenAI: "OpenAI",
  Pika: "Pika",
  PixVerse: "PixVerse",
  Recraft: "Recraft",
  "Stability AI": "Stability AI",
  Veo: "Veo",
  _for_testing: "_用于测试",
  advanced: "高级",
  animation: "动画",
  api: "API",
  "api node": "api 节点",
  attention_experiments: "注意力实验",
  audio: "音频",
  batch: "批处理",
  clip: "CLIP",
  combine: "组合",
  compositing: "合成",
  "cond pair": "条件对",
  "cond single": "条件单",
  conditioning: "条件",
  controlnet: "ControlNet",
  create: "创建",
  custom_sampling: "自定义采样",
  debug: "调试",
  deprecated: "已弃用",
  flux: "Flux",
  gligen: "GLIGEN",
  guidance: "引导",
  guiders: "引导器",
  hooks: "约束",
  image: "图像",
  inpaint: "局部重绘",
  instructpix2pix: "InstructPix2Pix",
  latent: "Latent",
  loaders: "加载器",
  lotus: "lotus",
  ltxv: "LTXV",
  mask: "遮罩",
  model: "模型",
  model_merging: "模型合并",
  model_patches: "模型微调",
  model_specific: "模型特定",
  noise: "噪波",
  operations: "操作",
  photomaker: "PhotoMaker",
  postprocessing: "后处理",
  preprocessors: "预处理器",
  primitive: "基础",
  samplers: "采样器",
  sampling: "采样",
  schedulers: "调度器",
  scheduling: "调度",
  sd: "sd",
  sd3: "SD3",
  sigmas: "Sigmas",
  stable_cascade: "StableCascade",
  style_model: "风格模型",
  transform: "变换",
  unet: "U-Net",
  upscale_diffusion: "放大扩散",
  upscaling: "放大",
  utils: "工具",
  v1: "v1",
  v2: "v2",
  v3: "v3",
  video: "视频",
  video_models: "视频模型"
};
const nodeTemplates = {
  enterName: "输入名称",
  saveAsTemplate: "另存为模板"
};
const notSupported = {
  "continue": "继续",
  continueTooltip: "我确定我的设备是受支持的",
  learnMore: "了解更多",
  message: "仅支持以下设备：",
  reportIssue: "报告问题",
  supportedDevices: {
    macos: "MacOS (M1 或更高版本)",
    windows: "Windows (支持 CUDA 的 Nvidia GPU)"
  },
  title: "您的设备不受支持"
};
const selectionToolbox = {
  executeButton: {
    disabledTooltip: "未选择输出节点",
    tooltip: "执行到选定的输出节点（用橙色边框高亮显示）"
  }
};
const serverConfig = {
  modifiedConfigs: "您已修改以下服务器配置。重启以应用更改。",
  restart: "重启",
  revertChanges: "撤销更改"
};
const serverConfigCategories = {
  Attention: "注意力",
  CUDA: "CUDA",
  Cache: "缓存",
  Directories: "目录",
  General: "常规",
  Inference: "推理",
  Memory: "内存",
  Network: "网络",
  Preview: "预览"
};
const serverConfigItems = {
  "cache-classic": {
    name: "使用经典缓存系统"
  },
  "cache-lru": {
    name: "使用 LRU 缓存，最多缓存 N 个节点结果。",
    tooltip: "可能会使用更多的 RAM/VRAM。"
  },
  "cpu-vae": {
    name: "在 CPU 上运行 VAE"
  },
  "cross-attention-method": {
    name: "交叉注意力方法"
  },
  "cuda-device": {
    name: "要使用的 CUDA 设备索引"
  },
  "cuda-malloc": {
    name: "使用 CUDA malloc 进行内存分配"
  },
  "default-hashing-function": {
    name: "模型文件的默认哈希函数"
  },
  deterministic: {
    name: "使 pytorch 在可以时使用较慢的确定性算法。",
    tooltip: "请注意，这可能不会在所有情况下使图像具有确定性。"
  },
  directml: {
    name: "DirectML 设备索引"
  },
  "disable-all-custom-nodes": {
    name: "禁用加载所有自定义节点。"
  },
  "disable-ipex-optimize": {
    name: "禁用 IPEX 优化"
  },
  "disable-metadata": {
    name: "禁用在文件中保存提示元数据。"
  },
  "disable-smart-memory": {
    name: "禁用智能内存管理",
    tooltip: "强制 ComfyUI 在可以时将模型从 VRAM 移出到常规 RAM。"
  },
  "disable-xformers": {
    name: "禁用 xFormers 优化"
  },
  "dont-print-server": {
    name: "不将服务器输出打印到控制台。"
  },
  "dont-upcast-attention": {
    name: "不使用 upcast-attention"
  },
  "enable-cors-header": {
    name: '启用 CORS header：使用 "*" 代表所有来源或指定域名'
  },
  fast: {
    name: "启用一些未经测试且可能降低质量的优化。"
  },
  "force-channels-last": {
    name: "强制使用 channels-last 内存格式"
  },
  "force-upcast-attention": {
    name: "强制 upcast-attention"
  },
  "global-precision": {
    name: "全局浮点精度",
    tooltip: "全局浮点精度"
  },
  "input-directory": {
    name: "输入目录"
  },
  listen: {
    name: "主机：要监听的IP地址"
  },
  "log-level": {
    name: "日志详细级别"
  },
  "max-upload-size": {
    name: "最大上传大小 (MB)"
  },
  "output-directory": {
    name: "输出目录"
  },
  port: {
    name: "端口：要监听的端口"
  },
  "preview-method": {
    name: "用于潜空间预览的方法"
  },
  "preview-size": {
    name: "预览图像的大小"
  },
  "reserve-vram": {
    name: "保留 VRAM (GB)",
    tooltip: "设置您希望为操作系统/其他软件保留的 VRAM （GB）。默认会根据系统类型保留一定数量。"
  },
  "text-encoder-precision": {
    name: "文本编码器精度",
    tooltip: "文本编码器精度"
  },
  "tls-certfile": {
    name: "TLS 证书文件：HTTPS 的 TLS 证书文件路径"
  },
  "tls-keyfile": {
    name: "TLS 密钥文件：HTTPS 的 TLS 密钥文件路径"
  },
  "unet-precision": {
    name: "UNET 精度",
    tooltip: "UNET 精度"
  },
  "vae-precision": {
    name: "VAE 精度",
    tooltip: "VAE 精度"
  },
  "vram-management": {
    name: "VRAM 管理模式"
  }
};
const serverStart = {
  openLogs: "打开日志",
  process: {
    error: "无法启动 ComfyUI 桌面版",
    "initial-state": "加载中...",
    "python-setup": "正在设置 Python 环境...",
    ready: "完成中...",
    "starting-server": "正在启动 ComfyUI 服务器..."
  },
  reportIssue: "报告问题",
  showTerminal: "显示终端",
  troubleshoot: "故障排除"
};
const settingsCategories = {
  "3D": "3D",
  About: "关于",
  Appearance: "外观",
  BrushAdjustment: "画笔调整",
  Camera: "相机",
  Canvas: "画布",
  ColorPalette: "色彩主题",
  Comfy: "Comfy",
  "Comfy-Desktop": "Comfy桌面版",
  ContextMenu: "上下文菜单",
  Credits: "积分",
  CustomColorPalettes: "自定义色彩主题",
  DevMode: "开发模式",
  EditTokenWeight: "编辑令牌权重",
  Extension: "扩展",
  General: "常规",
  Graph: "画面",
  Group: "组节点",
  Keybinding: "快捷键",
  Light: "浅色",
  Link: "连线",
  LinkRelease: "释放链接",
  LiteGraph: "画面",
  "Load 3D": "加载3D",
  Locale: "区域设置",
  "Mask Editor": "遮罩编辑器",
  Menu: "菜单",
  ModelLibrary: "模型库",
  NewEditor: "新编辑器",
  Node: "节点",
  "Node Search Box": "节点搜索框",
  "Node Widget": "节点组件",
  NodeLibrary: "节点库",
  Pointer: "指针",
  Queue: "队列",
  QueueButton: "执行按钮",
  Reroute: "重新路由",
  RerouteBeta: "转接点 Beta",
  Scene: "场景",
  Server: "服务器",
  "Server-Config": "服务器配置",
  Settings: "设置",
  Sidebar: "侧边栏",
  "Tree Explorer": "树形浏览器",
  UV: "UV",
  User: "用户",
  Validation: "验证",
  Window: "窗口",
  Workflow: "工作流"
};
const sideToolbar = {
  browseTemplates: "浏览示例模板",
  downloads: "下载",
  logout: "登出",
  modelLibrary: "模型库",
  newBlankWorkflow: "创建空白工作流",
  nodeLibrary: "节点库",
  nodeLibraryTab: {
    sortOrder: "排序顺序"
  },
  openWorkflow: "在本地文件系统中打开工作流",
  queue: "队列",
  queueTab: {
    backToAllTasks: "返回",
    clearPendingTasks: "清除待处理任务",
    containImagePreview: "填充图像预览",
    coverImagePreview: "适应图像预览",
    filter: "过滤输出",
    filters: {
      hideCached: "隐藏缓存",
      hideCanceled: "隐藏已取消"
    },
    showFlatList: "平铺结果"
  },
  themeToggle: "主题切换",
  workflowTab: {
    confirmDelete: "您确定要删除此工作流吗？",
    confirmDeleteTitle: "删除工作流？",
    confirmOverwrite: "下面的文件已经存在。您想要覆盖它吗？",
    confirmOverwriteTitle: "覆盖现有文件？",
    deleteFailed: "尝试删除工作流失败。",
    deleteFailedTitle: "删除失败",
    deleted: "工作流已删除",
    dirtyClose: "以下文件已被更改。您想在关闭之前保存它们吗？",
    dirtyCloseHint: "按住 Shift 关闭而不提示",
    dirtyCloseTitle: "保存更改？",
    workflowTreeType: {
      bookmarks: "书签",
      browse: "浏览",
      open: "打开"
    }
  },
  workflows: "工作流"
};
const tabMenu = {
  addToBookmarks: "添加到书签",
  closeOtherTabs: "关闭其他标签",
  closeTab: "关闭标签",
  closeTabsToLeft: "关闭左侧标签",
  closeTabsToRight: "关闭右侧标签",
  duplicateTab: "复制标签",
  removeFromBookmarks: "从书签中移除"
};
const templateWorkflows = {
  category: {
    "3D": "3D",
    "Area Composition": "区域组成",
    Audio: "音频",
    Basics: "基础",
    "ComfyUI Examples": "ComfyUI示例",
    ControlNet: "ControlNet",
    "Custom Nodes": "自定义节点",
    Flux: "Flux",
    Image: "图片",
    "Image API": "图像 API",
    Upscaling: "放大",
    Video: "视频",
    "Video API": "视频 API"
  },
  template: {
    "3D": {
      "hunyuan-3d-multiview-elf": "混元3D多视图",
      "hunyuan-3d-turbo": "混元3D Turbo",
      "hunyuan3d-non-multiview-train": "混元3D",
      stable_zero123_example: "Stable Zero123"
    },
    "Area Composition": {
      area_composition: "区域构成",
      area_composition_reversed: "反向区域构成",
      area_composition_square_area_for_subject: "主题的方形区域构成"
    },
    Audio: {
      stable_audio_example: "Stable Audio"
    },
    Basics: {
      "default": "图像生成",
      embedding_example: "嵌入",
      gligen_textbox_example: "Gligen文本框",
      image2image: "图像到图像",
      inpain_model_outpainting: "Inpaint模型Outpainting",
      inpaint_example: "Inpaint",
      lora: "Lora",
      lora_multiple: "Lora多个"
    },
    ControlNet: {
      "2_pass_pose_worship": "双通道姿势处理",
      controlnet_example: "ControlNet",
      depth_controlnet: "深度ControlNet",
      depth_t2i_adapter: "深度T2I适配器",
      mixing_controlnets: "混合ControlNets"
    },
    Flux: {
      flux_canny_model_example: "Flux Canny Model",
      flux_depth_lora_example: "Flux Depth Lora",
      flux_dev_checkpoint_example: "Flux Dev的检查点示例",
      flux_fill_inpaint_example: "Flux Inpaint",
      flux_fill_outpaint_example: "Flux Outpaint",
      flux_redux_model_example: "Flux Redux Model",
      flux_schnell: "Flux Schnell"
    },
    Image: {
      hidream_i1_dev: "HiDream I1 Dev",
      hidream_i1_fast: "HiDream I1 Fast",
      hidream_i1_full: "HiDream I1 Full",
      sd3_5_large_blur: "SD3.5 Large 模糊",
      sd3_5_large_canny_controlnet_example: "SD3.5 Large Canny 控制网",
      sd3_5_large_depth: "SD3.5 Large 深度",
      sd3_5_simple_example: "SD3.5 简易示例",
      sdxl_refiner_prompt_example: "SDXL Refiner提示",
      sdxl_revision_text_prompts: "SDXL修订文本提示",
      sdxl_revision_zero_positive: "SDXL修订零正",
      sdxl_simple_example: "SDXL简单",
      sdxlturbo_example: "SDXL Turbo"
    },
    "Image API": {
      "api-openai-dall-e-2-inpaint": "Dall-E 2 局部修复",
      "api-openai-dall-e-2-t2i": "Dall-E 2 文生图",
      "api-openai-dall-e-3-t2i": "Dall-E 3 文生图",
      api_bfl_flux_pro_t2i: "BFL Flux 1.1[pro] Ultra 文生图",
      api_ideogram_v3_t2i: "Ideogram V3 文生图",
      api_luma_photon_i2i: "Luma Photon 图生图",
      api_luma_photon_style_ref: "Luma Photon 风格参考",
      api_openai_image_1_i2i: "OpenAI Image-1 图生图",
      api_openai_image_1_inpaint: "OpenAI Image-1 局部修复",
      api_openai_image_1_multi_inputs: "OpenAI Image-1 多输入",
      api_openai_image_1_t2i: "OpenAI Image-1 文生图",
      api_recraft_image_gen_with_color_control: "Recraft 颜色控制图像生成",
      api_recraft_image_gen_with_style_control: "Recraft 风格控制图像生成",
      api_recraft_vector_gen: "Recraft 矢量生成",
      api_stability_sd3_t2i: "Stability AI Stable Image Ultra 文生图"
    },
    Upscaling: {
      esrgan_example: "ESRGAN",
      hiresfix_esrgan_workflow: "HiresFix ESRGAN工作流",
      hiresfix_latent_workflow: "HiresFix潜在工作流",
      latent_upscale_different_prompt_model: "潜在升级不同提示模型"
    },
    Video: {
      hunyuan_video_text_to_video: "混元视频文本到视频",
      image_to_video: "图像到视频",
      image_to_video_wan: "Wan 2.1 图像到视频",
      ltxv_image_to_video: "LTXV图像到视频",
      ltxv_text_to_video: "LTXV文本到视频",
      mochi_text_to_video_example: "Mochi文本到视频",
      text_to_video_wan: "Wan 2.1 文字到视频",
      txt_to_image_to_video: "文本到图像到视频",
      wan2_1_fun_control: "Wan 2.1 ControlNet",
      wan2_1_fun_inp: "Wan 2.1 图像修复"
    },
    "Video API": {
      api_hailuo_minimax_i2v: "MiniMax 图生视频",
      api_kling_i2v: "Kling 图生视频",
      api_luma_i2v: "Luma 图生视频",
      api_pika_scene: "Pika 场景：图生视频",
      api_pixverse_t2v: "PixVerse 文生视频",
      api_pixverse_template_i2v: "PixVerse特效：图生视频",
      api_veo2_i2v: "Veo2 图生视频"
    }
  },
  templateDescription: {
    "3D": {
      "hunyuan-3d-multiview-elf": "使用 Hunyuan3D 2mv 从多视角生成模型。",
      "hunyuan-3d-turbo": "使用 Hunyuan3D 2mv turbo 从多视角生成模型。",
      "hunyuan3d-non-multiview-train": "使用 Hunyuan3D 2.0 从单视角生成模型。",
      stable_zero123_example: "通过单张图像生成 3D 视图。"
    },
    "Area Composition": {
      area_composition: "通过区域控制图像构图。",
      area_composition_reversed: "反向区域构图流程。",
      area_composition_square_area_for_subject: "实现主体位置一致性。"
    },
    Audio: {
      stable_audio_example: "根据文本描述生成音频。"
    },
    Basics: {
      "default": "根据文本描述生成图像。",
      embedding_example: "使用文本反演实现风格一致性。",
      gligen_textbox_example: "指定物体的位置和大小。",
      image2image: "使用文本提示转换现有图像。",
      inpain_model_outpainting: "将图像扩展到原始边界之外。",
      inpaint_example: "无缝编辑图像的特定部分。",
      lora: "应用 LoRA 模型以实现特定风格或主题。",
      lora_multiple: "组合多个 LoRA 模型以获得独特效果。"
    },
    ControlNet: {
      "2_pass_pose_worship": "通过姿态参考生成图像。",
      controlnet_example: "通过参考图像控制图像生成。",
      depth_controlnet: "生成深度感知图像。",
      depth_t2i_adapter: "使用 T2I 适配器快速生成深度感知图像。",
      mixing_controlnets: "组合多个 ControlNet 模型。"
    },
    Flux: {
      flux_canny_model_example: "通过边缘检测生成图像。",
      flux_depth_lora_example: "使用深度感知 LoRA 生成图像。",
      flux_dev_checkpoint_example: "使用 flux 开发模型生成图像。",
      flux_fill_inpaint_example: "填充图像中缺失的部分。",
      flux_fill_outpaint_example: "使用 flux 外扩生成图像。",
      flux_redux_model_example: "将参考图像的风格迁移到引导图像生成（flux）。",
      flux_schnell: "使用 flux schnell 快速生成图像。"
    },
    Image: {
      hidream_e1_full: "使用 HiDream E1 编辑图像。",
      hidream_i1_dev: "使用 HiDream I1 Dev 生成图像。",
      hidream_i1_fast: "使用 HiDream I1 快速生成图像。",
      hidream_i1_full: "使用 HiDream I1 生成图像。",
      sd3_5_large_blur: "使用 SD 3.5 通过模糊参考图像生成图像。",
      sd3_5_large_canny_controlnet_example: "使用边缘检测引导 SD 3.5 图像生成。",
      sd3_5_large_depth: "使用 SD 3.5 生成深度感知图像。",
      sd3_5_simple_example: "使用 SD 3.5 生成图像。",
      sdxl_refiner_prompt_example: "使用精炼器提升 SDXL 输出效果。",
      sdxl_revision_text_prompts: "将参考图像的概念迁移到 SDXL 图像生成中。",
      sdxl_revision_zero_positive: "在 SDXL 图像生成中结合文本提示和参考图像。",
      sdxl_simple_example: "使用 SDXL 生成高质量图像。",
      sdxlturbo_example: "使用 SDXL Turbo 一步生成图像。"
    },
    "Image API": {
      "api-openai-dall-e-2-inpaint": "使用 Dall-E 2 API 对图像进行修复。",
      "api-openai-dall-e-2-t2i": "使用 Dall-E 2 API 根据文本描述生成图像。",
      "api-openai-dall-e-3-t2i": "使用 Dall-E 3 API 根据文本描述生成图像。",
      api_bfl_flux_pro_t2i: "使用 FLUX.1 [pro] 生成高质量、细节丰富、提示遵循性强且多样化的图像。",
      api_ideogram_v3_t2i: "生成高质量图像与提示对齐、照片级真实感和文本渲染。可用于专业级 logo、宣传海报、落地页概念、产品摄影等。轻松打造复杂空间构图、精细背景、精准光影与色彩、逼真环境细节。",
      api_luma_photon_i2i: "结合图像和提示词引导图像生成。",
      api_luma_photon_style_ref: "精确控制并融合风格参考。Luma Photon 捕捉每个参考图像的精髓，让你在保持专业品质的同时融合不同视觉元素。",
      api_openai_image_1_i2i: "使用 GPT Image 1 API 通过图像生成图像。",
      api_openai_image_1_inpaint: "使用 GPT Image 1 API 对图像进行修复。",
      api_openai_image_1_multi_inputs: "使用 GPT Image 1 API 多输入生成图像。",
      api_openai_image_1_t2i: "使用 GPT Image 1 API 根据文本描述生成图像。",
      api_recraft_image_gen_with_color_control: "创建自定义调色板以复用或为每张照片手动选色。匹配品牌色彩，打造专属视觉风格。",
      api_recraft_image_gen_with_style_control: "通过视觉示例控制风格、对齐位置、微调物体。存储并分享风格，实现品牌一致性。",
      api_recraft_vector_gen: "通过文本提示生成矢量图像，使用 Recraft 的 AI 矢量生成器。可用于 logo、海报、图标集、广告、横幅和模型。生成高质量 SVG 文件，几秒内为你的应用或网站创建品牌矢量插画。",
      api_stability_sd3_t2i: "生成高质量、提示遵循性极佳的图像。适用于专业场景，分辨率达 1 兆像素。"
    },
    Upscaling: {
      esrgan_example: "使用超分模型提升图像质量。",
      hiresfix_esrgan_workflow: "在中间步骤使用超分模型提升图像质量。",
      hiresfix_latent_workflow: "在 latent 空间中提升图像质量。",
      latent_upscale_different_prompt_model: "放大图像并在不同阶段更换提示词。"
    },
    Video: {
      hunyuan_video_text_to_video: "使用 Hunyuan 模型生成视频。",
      image_to_video: "将图像转换为动画视频。",
      image_to_video_wan: "快速将图像生成视频。",
      ltxv_image_to_video: "将静态图像转换为视频。",
      ltxv_text_to_video: "根据文本描述生成视频。",
      mochi_text_to_video_example: "使用 Mochi 模型生成视频。",
      text_to_video_wan: "快速将文本描述生成视频。",
      txt_to_image_to_video: "先由文本生成图像，再转换为视频。",
      wan2_1_flf2v_720_f16: "通过控制首帧和尾帧生成视频。",
      wan2_1_fun_control: "通过姿态、深度、边缘等控制引导视频生成。",
      wan2_1_fun_inp: "通过起始帧和结束帧生成视频。"
    },
    "Video API": {
      api_hailuo_minimax_i2v: "通过图像和文本生成精致视频，支持 CGI 效果和流行 AI 拥抱等特效。多种视频风格和主题，满足你的创意需求。",
      api_kling_i2v: "生成动作、表情、镜头运动等提示遵循性强的视频。支持复杂提示和顺序动作，让你成为场景导演。",
      api_luma_i2v: "将静态图像瞬间转化为高质量动画。",
      api_pika_scene: "将多张图像作为素材，生成融合所有内容的视频。",
      api_pixverse_t2v: "根据提示生成高还原度、动态效果出色的视频。",
      api_pixverse_template_i2v: "将静态图像转化为带有动态和特效的视频。",
      api_veo2_i2v: "使用 Google Veo2 API 通过图像生成视频。"
    }
  },
  title: "从模板开始"
};
const toastMessages = {
  couldNotDetermineFileType: "无法确定文件类型",
  dropFileError: "无法处理掉落的项目：{error}",
  emptyCanvas: "画布为空",
  errorCopyImage: "复制图片出错：{error}",
  errorLoadingModel: "加载模型出错",
  errorSaveSetting: "保存设置 {id} 出错：{err}",
  failedToAccessBillingPortal: "访问账单门户失败：{error}",
  failedToApplyTexture: "应用纹理失败",
  failedToCreateCustomer: "创建客户失败：{error}",
  failedToDownloadFile: "文件下载失败",
  failedToExportModel: "无法将模型导出为 {format}",
  failedToFetchBalance: "获取余额失败：{error}",
  failedToFetchLogs: "无法获取服务器日志",
  failedToInitiateCreditPurchase: "发起积分购买失败：{error}",
  failedToPurchaseCredits: "购买积分失败：{error}",
  fileLoadError: "无法在 {fileName} 中找到工作流",
  fileUploadFailed: "文件上传失败",
  interrupted: "执行已被中断",
  migrateToLitegraphReroute: "将来的版本中将删除重定向节点。点击以迁移到litegraph-native重定向。",
  no3dScene: "没有3D场景可以应用纹理",
  no3dSceneToExport: "没有3D场景可以导出",
  noTemplatesToExport: "没有模板可以导出",
  nodeDefinitionsUpdated: "节点定义已更新",
  nothingToGroup: "没有可分组的内容",
  nothingToQueue: "没有可加入队列的内容",
  pendingTasksDeleted: "待处理任务已删除",
  pleaseSelectNodesToGroup: "请选取节点（或其他组）以创建分组",
  pleaseSelectOutputNodes: "请选择输出节点",
  unableToGetModelFilePath: "无法获取模型文件路径",
  unauthorizedDomain: "您的域名 {domain} 未被授权使用此服务。请联系 {email} 将您的域名添加到白名单。",
  updateRequested: "已请求更新",
  useApiKeyTip: "提示：无法正常登录？请使用 Comfy API Key 选项。",
  userNotAuthenticated: "用户未认证"
};
const userSelect = {
  enterUsername: "输入用户名",
  existingUser: "用户已存在",
  newUser: "新用户",
  next: "下一步",
  selectUser: "选择用户"
};
const userSettings = {
  email: "电子邮件",
  name: "名称",
  notSet: "未设置",
  provider: "登录方式",
  title: "用户设置",
  updatePassword: "更新密码"
};
const validation = {
  invalidEmail: "无效的电子邮件地址",
  length: "必须为{length}个字符",
  maxLength: "不能超过{length}个字符",
  minLength: "必须至少有{length}个字符",
  password: {
    lowercase: "必须包含至少一个小写字母",
    match: "密码必须匹配",
    minLength: "必须在8到32个字符之间",
    number: "必须包含至少一个数字",
    requirements: "密码要求",
    special: "必须包含至少一个特殊字符",
    uppercase: "必须包含至少一个大写字母"
  },
  personalDataConsentRequired: "您必须同意处理您的个人数据。",
  prefix: "必须以 {prefix} 开头",
  required: "必填"
};
const welcome = {
  getStarted: "开始使用",
  title: "欢迎使用 ComfyUI"
};
const workflowService = {
  enterFilename: "输入文件名",
  exportWorkflow: "导出工作流",
  saveWorkflow: "保存工作流"
};
const zh = {
  apiNodesCostBreakdown,
  apiNodesNews,
  apiNodesSignInDialog,
  auth,
  clipboard,
  color,
  contextMenu,
  credits,
  dataTypes,
  desktopMenu,
  desktopUpdate,
  downloadGit,
  electronFileDownload,
  errorDialog,
  g,
  graphCanvasMenu,
  groupNode,
  icon,
  install,
  issueReport,
  load3d,
  maintenance,
  manager,
  maskEditor,
  menu,
  menuLabels,
  missingModelsDialog,
  nodeCategories,
  nodeTemplates,
  notSupported,
  selectionToolbox,
  serverConfig,
  serverConfigCategories,
  serverConfigItems,
  serverStart,
  settingsCategories,
  sideToolbar,
  tabMenu,
  templateWorkflows,
  toastMessages,
  userSelect,
  userSettings,
  validation,
  welcome,
  workflowService
};
const AddNoise = {
  display_name: "添加噪波",
  inputs: {
    latent_image: {
      name: "Latent"
    },
    model: {
      name: "模型"
    },
    noise: {
      name: "噪波"
    },
    sigmas: {
      name: "Sigmas"
    }
  }
};
const AlignYourStepsScheduler = {
  display_name: "AlignYourSteps调度器",
  inputs: {
    denoise: {
      name: "降噪"
    },
    model_type: {
      name: "模型类型"
    },
    steps: {
      name: "步数"
    }
  }
};
const BasicGuider = {
  display_name: "基本引导器",
  inputs: {
    conditioning: {
      name: "条件"
    },
    model: {
      name: "模型"
    }
  }
};
const BasicScheduler = {
  display_name: "基本调度器",
  inputs: {
    denoise: {
      name: "降噪"
    },
    model: {
      name: "模型"
    },
    scheduler: {
      name: "调度器"
    },
    steps: {
      name: "步数"
    }
  }
};
const BetaSamplingScheduler = {
  display_name: "Beta采样调度器",
  inputs: {
    alpha: {
      name: "阿尔法"
    },
    beta: {
      name: "贝塔"
    },
    model: {
      name: "模型"
    },
    steps: {
      name: "步数"
    }
  }
};
const CFGGuider = {
  display_name: "CFG引导器",
  inputs: {
    cfg: {
      name: "CFG"
    },
    model: {
      name: "模型"
    },
    negative: {
      name: "负面条件"
    },
    positive: {
      name: "正面条件"
    }
  }
};
const CFGZeroStar = {
  display_name: "CFGZeroStar",
  inputs: {
    model: {
      name: "model"
    }
  },
  outputs: {
    "0": {
      name: "patched_model"
    }
  }
};
const CLIPAttentionMultiply = {
  display_name: "CLIP注意力相乘",
  inputs: {
    clip: {
      name: "clip"
    },
    k: {
      name: "k"
    },
    out: {
      name: "输出"
    },
    q: {
      name: "q"
    },
    v: {
      name: "v"
    }
  }
};
const CLIPLoader = {
  description: "[配方]\n\nStable Diffusion：clip-l\nStable Cascade：clip-g\nSD3：t5 / clip-g / clip-l\nStable Audio：t5\nMochi：t5\ncosmos：old t5 xxl",
  display_name: "加载CLIP",
  inputs: {
    clip_name: {
      name: "CLIP名称"
    },
    device: {
      name: "设备"
    },
    type: {
      name: "类型"
    }
  }
};
const CLIPMergeAdd = {
  display_name: "CLIP相加",
  inputs: {
    clip1: {
      name: "clip1"
    },
    clip2: {
      name: "clip2"
    }
  }
};
const CLIPMergeSimple = {
  display_name: "CLIP融合简易",
  inputs: {
    clip1: {
      name: "clip1"
    },
    clip2: {
      name: "clip2"
    },
    ratio: {
      name: "比例"
    }
  }
};
const CLIPMergeSubtract = {
  display_name: "CLIP相减",
  inputs: {
    clip1: {
      name: "clip1"
    },
    clip2: {
      name: "clip2"
    },
    multiplier: {
      name: "乘数"
    }
  }
};
const CLIPSave = {
  display_name: "CLIP保存",
  inputs: {
    clip: {
      name: "clip"
    },
    filename_prefix: {
      name: "文件名前缀"
    }
  }
};
const CLIPSetLastLayer = {
  display_name: "设置CLIP最后一层",
  inputs: {
    clip: {
      name: "clip"
    },
    stop_at_clip_layer: {
      name: "停止在CLIP层"
    }
  }
};
const CLIPTextEncode = {
  description: "使用 CLIP 模型将文本编码成嵌入组（embedding），用于引导扩散模型生成图像。",
  display_name: "CLIP文本编码",
  inputs: {
    clip: {
      name: "clip",
      tooltip: "用于编码文本的 CLIP 模型。"
    },
    text: {
      name: "文本",
      tooltip: "要编码的文本。"
    }
  },
  outputs: {
    "0": {
      tooltip: "包含嵌入文本的条件，用于引导扩散模型。"
    }
  }
};
const CLIPTextEncodeControlnet = {
  display_name: "CLIP文本编码ControlNet",
  inputs: {
    clip: {
      name: "clip"
    },
    conditioning: {
      name: "条件"
    },
    text: {
      name: "文本"
    }
  }
};
const CLIPTextEncodeFlux = {
  display_name: "CLIP文本编码Flux",
  inputs: {
    clip: {
      name: "clip"
    },
    clip_l: {
      name: "clip_l"
    },
    guidance: {
      name: "引导"
    },
    t5xxl: {
      name: "t5xxl"
    }
  }
};
const CLIPTextEncodeHiDream = {
  display_name: "CLIPTextEncodeHiDream",
  inputs: {
    clip: {
      name: "clip"
    },
    clip_g: {
      name: "clip_g"
    },
    clip_l: {
      name: "clip_l"
    },
    llama: {
      name: "llama"
    },
    t5xxl: {
      name: "t5xxl"
    }
  }
};
const CLIPTextEncodeHunyuanDiT = {
  display_name: "CLIP文本编码混元DiT",
  inputs: {
    bert: {
      name: "bert"
    },
    clip: {
      name: "clip"
    },
    mt5xl: {
      name: "mt5xl"
    }
  }
};
const CLIPTextEncodeLumina2 = {
  description: "使用CLIP模型将系统提示和用户提示编码成可以用来引导扩散模型生成特定图像的嵌入。",
  display_name: "Lumina2的CLIP文本编码",
  inputs: {
    clip: {
      name: "clip",
      tooltip: "用于编码文本的CLIP模型。"
    },
    system_prompt: {
      name: "system_prompt",
      tooltip: "Lumina2提供两种类型的系统提示：优越：你是一个设计来根据文本提示或用户提示生成优越图像的助手，这些图像具有基于文本提示的优越度的图像-文本对齐。对齐：你是一个设计来根据文本提示生成高质量图像的助手，这些图像具有基于文本提示的最高度的图像-文本对齐。"
    },
    user_prompt: {
      name: "user_prompt",
      tooltip: "需要编码的文本。"
    }
  },
  outputs: {
    "0": {
      tooltip: "包含用于引导扩散模型的嵌入文本的条件。"
    }
  }
};
const CLIPTextEncodePixArtAlpha = {
  description: "编码文本并设置PixArt Alpha的分辨率条件。不适用于PixArt Sigma。",
  display_name: "CLIPTextEncodePixArtAlpha",
  inputs: {
    clip: {
      name: "剪辑"
    },
    height: {
      name: "高度"
    },
    text: {
      name: "文本"
    },
    width: {
      name: "宽度"
    }
  }
};
const CLIPTextEncodeSD3 = {
  display_name: "CLIP文本编码SD3",
  inputs: {
    clip: {
      name: "clip"
    },
    clip_g: {
      name: "clip_g"
    },
    clip_l: {
      name: "clip_l"
    },
    empty_padding: {
      name: "空白填充"
    },
    t5xxl: {
      name: "t5xxl"
    }
  }
};
const CLIPTextEncodeSDXL = {
  display_name: "CLIP文本编码SDXL",
  inputs: {
    clip: {
      name: "clip"
    },
    crop_h: {
      name: "裁剪高"
    },
    crop_w: {
      name: "裁剪宽"
    },
    height: {
      name: "高度"
    },
    target_height: {
      name: "目标高度"
    },
    target_width: {
      name: "目标宽度"
    },
    text_g: {
      name: "文本_g"
    },
    text_l: {
      name: "文本_l"
    },
    width: {
      name: "宽度"
    }
  }
};
const CLIPTextEncodeSDXLRefiner = {
  display_name: "CLIP文本编码SDXL精炼器",
  inputs: {
    ascore: {
      name: "美学分数"
    },
    clip: {
      name: "clip"
    },
    height: {
      name: "高度"
    },
    text: {
      name: "文本"
    },
    width: {
      name: "宽度"
    }
  }
};
const CLIPVisionEncode = {
  display_name: "CLIP视觉编码",
  inputs: {
    clip_vision: {
      name: "clip视觉"
    },
    crop: {
      name: "裁剪"
    },
    image: {
      name: "图像"
    }
  }
};
const CLIPVisionLoader = {
  display_name: "加载CLIP视觉",
  inputs: {
    clip_name: {
      name: "clip名称"
    }
  }
};
const Canny = {
  display_name: "Canny边缘检测",
  inputs: {
    high_threshold: {
      name: "高阈值"
    },
    image: {
      name: "图像"
    },
    low_threshold: {
      name: "低阈值"
    }
  }
};
const CheckpointLoader = {
  display_name: "Ckeckpoint加载器（已弃用）",
  inputs: {
    ckpt_name: {
      name: "Checkpoint名称"
    },
    config_name: {
      name: "配置名称"
    }
  }
};
const CheckpointLoaderSimple = {
  description: "加载扩散模型 Checkpoint，用于去除 Latent 噪波。",
  display_name: "Checkpoint加载器（简易）",
  inputs: {
    ckpt_name: {
      name: "Checkpoint名称",
      tooltip: "要加载的Checkpoint模型的名称。"
    }
  },
  outputs: {
    "0": {
      tooltip: "用于去除 Latent 噪波的模型。"
    },
    "1": {
      tooltip: "用于编码文本提示的 CLIP 模型。"
    },
    "2": {
      tooltip: "用于将图像编码和解码到 Latent 的 VAE 模型。"
    }
  }
};
const CheckpointSave = {
  display_name: "保存Checkpoint",
  inputs: {
    clip: {
      name: "clip"
    },
    filename_prefix: {
      name: "文件名前缀"
    },
    model: {
      name: "模型"
    },
    vae: {
      name: "vae"
    }
  }
};
const CombineHooks2 = {
  display_name: "组合约束 [2]",
  inputs: {
    hooks_A: {
      name: "约束_A"
    },
    hooks_B: {
      name: "约束_B"
    }
  }
};
const CombineHooks4 = {
  display_name: "组合约束 [4]",
  inputs: {
    hooks_A: {
      name: "约束_A"
    },
    hooks_B: {
      name: "约束_B"
    },
    hooks_C: {
      name: "约束_C"
    },
    hooks_D: {
      name: "约束_D"
    }
  }
};
const CombineHooks8 = {
  display_name: "组合约束 [8]",
  inputs: {
    hooks_A: {
      name: "约束_A"
    },
    hooks_B: {
      name: "约束_B"
    },
    hooks_C: {
      name: "约束_C"
    },
    hooks_D: {
      name: "约束_D"
    },
    hooks_E: {
      name: "约束_E"
    },
    hooks_F: {
      name: "约束_F"
    },
    hooks_G: {
      name: "约束_G"
    },
    hooks_H: {
      name: "约束_H"
    }
  }
};
const ConditioningAverage = {
  display_name: "条件平均",
  inputs: {
    conditioning_from: {
      name: "条件从"
    },
    conditioning_to: {
      name: "条件到"
    },
    conditioning_to_strength: {
      name: "条件到强度"
    }
  }
};
const ConditioningCombine = {
  display_name: "条件合并",
  inputs: {
    conditioning_1: {
      name: "条件_1"
    },
    conditioning_2: {
      name: "条件_2"
    }
  }
};
const ConditioningConcat = {
  display_name: "条件连接",
  inputs: {
    conditioning_from: {
      name: "条件从"
    },
    conditioning_to: {
      name: "条件到"
    }
  }
};
const ConditioningSetArea = {
  display_name: "条件采样区域",
  inputs: {
    conditioning: {
      name: "条件"
    },
    height: {
      name: "高度"
    },
    strength: {
      name: "强度"
    },
    width: {
      name: "宽度"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const ConditioningSetAreaPercentage = {
  display_name: "条件采样区域（系数）",
  inputs: {
    conditioning: {
      name: "条件化"
    },
    height: {
      name: "高度"
    },
    strength: {
      name: "强度"
    },
    width: {
      name: "宽度"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const ConditioningSetAreaPercentageVideo = {
  display_name: "调节设置区域百分比视频",
  inputs: {
    conditioning: {
      name: "调节"
    },
    height: {
      name: "高度"
    },
    strength: {
      name: "强度"
    },
    temporal: {
      name: "时间"
    },
    width: {
      name: "宽度"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    },
    z: {
      name: "z"
    }
  }
};
const ConditioningSetAreaStrength = {
  display_name: "条件采样区域强度",
  inputs: {
    conditioning: {
      name: "条件化"
    },
    strength: {
      name: "强度"
    }
  }
};
const ConditioningSetDefaultCombine = {
  display_name: "条件设置默认合并",
  inputs: {
    cond: {
      name: "条件"
    },
    cond_DEFAULT: {
      name: "默认条件"
    },
    hooks: {
      name: "约束"
    }
  }
};
const ConditioningSetMask = {
  display_name: "条件遮罩",
  inputs: {
    conditioning: {
      name: "条件化"
    },
    mask: {
      name: "遮罩"
    },
    set_cond_area: {
      name: "设置条件区域"
    },
    strength: {
      name: "强度"
    }
  }
};
const ConditioningSetProperties = {
  display_name: "条件设置属性",
  inputs: {
    cond_NEW: {
      name: "新条件"
    },
    hooks: {
      name: "约束"
    },
    mask: {
      name: "遮罩"
    },
    set_cond_area: {
      name: "设置条件区域"
    },
    strength: {
      name: "强度"
    },
    timesteps: {
      name: "间隔"
    }
  }
};
const ConditioningSetPropertiesAndCombine = {
  display_name: "条件设置属性合并",
  inputs: {
    cond: {
      name: "条件"
    },
    cond_NEW: {
      name: "新条件"
    },
    hooks: {
      name: "约束"
    },
    mask: {
      name: "遮罩"
    },
    set_cond_area: {
      name: "设置条件区域"
    },
    strength: {
      name: "强度"
    },
    timesteps: {
      name: "间隔"
    }
  }
};
const ConditioningSetTimestepRange = {
  display_name: "设置条件时间",
  inputs: {
    conditioning: {
      name: "条件"
    },
    end: {
      name: "结束"
    },
    start: {
      name: "开始"
    }
  }
};
const ConditioningStableAudio = {
  display_name: "StableAudio条件",
  inputs: {
    negative: {
      name: "负面条件"
    },
    positive: {
      name: "正面条件"
    },
    seconds_start: {
      name: "开始秒数"
    },
    seconds_total: {
      name: "总秒数"
    }
  },
  outputs: {
    "0": {
      name: "正面条件"
    },
    "1": {
      name: "负面条件"
    }
  }
};
const ConditioningTimestepsRange = {
  display_name: "条件间隔范围",
  inputs: {
    end_percent: {
      name: "结束百分比"
    },
    start_percent: {
      name: "开始百分比"
    }
  },
  outputs: {
    "1": {
      name: "范围前"
    },
    "2": {
      name: "范围后"
    }
  }
};
const ConditioningZeroOut = {
  display_name: "条件零化",
  inputs: {
    conditioning: {
      name: "条件"
    }
  }
};
const ControlNetApply = {
  display_name: "应用ControlNet（旧版）",
  inputs: {
    conditioning: {
      name: "条件"
    },
    control_net: {
      name: "ControlNet"
    },
    image: {
      name: "图像"
    },
    strength: {
      name: "强度"
    }
  }
};
const ControlNetApplyAdvanced = {
  display_name: "应用ControlNet（旧版高级）",
  inputs: {
    control_net: {
      name: "ControlNet"
    },
    end_percent: {
      name: "结束百分比"
    },
    image: {
      name: "图像"
    },
    negative: {
      name: "负面条件"
    },
    positive: {
      name: "正面条件"
    },
    start_percent: {
      name: "开始百分比"
    },
    strength: {
      name: "强度"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "正面条件"
    },
    "1": {
      name: "负面条件"
    }
  }
};
const ControlNetApplySD3 = {
  display_name: "应用ControlNet",
  inputs: {
    control_net: {
      name: "ControlNet"
    },
    end_percent: {
      name: "结束百分比"
    },
    image: {
      name: "图像"
    },
    negative: {
      name: "负面条件"
    },
    positive: {
      name: "正面条件"
    },
    start_percent: {
      name: "开始百分比"
    },
    strength: {
      name: "强度"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "正面条件"
    },
    "1": {
      name: "负面条件"
    }
  }
};
const ControlNetInpaintingAliMamaApply = {
  display_name: "应用ControlNet（阿里妈妈局部重绘）",
  inputs: {
    control_net: {
      name: "ControlNet"
    },
    end_percent: {
      name: "结束百分比"
    },
    image: {
      name: "图像"
    },
    mask: {
      name: "遮罩"
    },
    negative: {
      name: "负面条件"
    },
    positive: {
      name: "正面条件"
    },
    start_percent: {
      name: "开始百分比"
    },
    strength: {
      name: "强度"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "正面条件"
    },
    "1": {
      name: "负面条件"
    }
  }
};
const ControlNetLoader = {
  display_name: "加载ControlNet模型",
  inputs: {
    control_net_name: {
      name: "ControlNet名称"
    }
  }
};
const CosmosImageToVideoLatent = {
  display_name: "Cosmos图像到视频潜在",
  inputs: {
    batch_size: {
      name: "批量大小"
    },
    end_image: {
      name: "结束图像"
    },
    height: {
      name: "高度"
    },
    length: {
      name: "长度"
    },
    start_image: {
      name: "开始图像"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "宽度"
    }
  }
};
const CreateHookKeyframe = {
  display_name: "创建约束关键帧",
  inputs: {
    prev_hook_kf: {
      name: "前一个约束关键帧"
    },
    start_percent: {
      name: "开始百分比"
    },
    strength_mult: {
      name: "强度倍数"
    }
  },
  outputs: {
    "0": {
      name: "约束关键帧"
    }
  }
};
const CreateHookKeyframesFromFloats = {
  display_name: "从浮点数创建约束关键帧",
  inputs: {
    end_percent: {
      name: "结束百分比"
    },
    floats_strength: {
      name: "浮点强度"
    },
    prev_hook_kf: {
      name: "前一个约束关键帧"
    },
    print_keyframes: {
      name: "打印关键帧"
    },
    start_percent: {
      name: "开始百分比"
    }
  },
  outputs: {
    "0": {
      name: "约束关键帧"
    }
  }
};
const CreateHookKeyframesInterpolated = {
  display_name: "创建约束关键帧插值",
  inputs: {
    end_percent: {
      name: "结束百分比"
    },
    interpolation: {
      name: "插值"
    },
    keyframes_count: {
      name: "关键帧数量"
    },
    prev_hook_kf: {
      name: "前一个约束关键帧"
    },
    print_keyframes: {
      name: "打印关键帧"
    },
    start_percent: {
      name: "开始百分比"
    },
    strength_end: {
      name: "结束强度"
    },
    strength_start: {
      name: "开始强度"
    }
  },
  outputs: {
    "0": {
      name: "约束关键帧"
    }
  }
};
const CreateHookLora = {
  display_name: "创建约束LoRA",
  inputs: {
    lora_name: {
      name: "LoRA名称"
    },
    prev_hooks: {
      name: "前一个约束"
    },
    strength_clip: {
      name: "CLIP强度"
    },
    strength_model: {
      name: "模型强度"
    }
  }
};
const CreateHookLoraModelOnly = {
  display_name: "创建约束LoRA（仅模型）",
  inputs: {
    lora_name: {
      name: "LoRA名称"
    },
    prev_hooks: {
      name: "前一个约束"
    },
    strength_model: {
      name: "模型强度"
    }
  }
};
const CreateHookModelAsLora = {
  display_name: "创建约束模型为LoRA",
  inputs: {
    ckpt_name: {
      name: "Checkpoint名称"
    },
    prev_hooks: {
      name: "前一个约束"
    },
    strength_clip: {
      name: "CLIP强度"
    },
    strength_model: {
      name: "模型强度"
    }
  }
};
const CreateHookModelAsLoraModelOnly = {
  display_name: "创建约束模型为LoRA（仅模型）",
  inputs: {
    ckpt_name: {
      name: "Checkpoint名称"
    },
    prev_hooks: {
      name: "前一个约束"
    },
    strength_model: {
      name: "模型强度"
    }
  }
};
const CreateVideo = {
  description: "从图像创建视频。",
  display_name: "创建视频",
  inputs: {
    audio: {
      name: "音频",
      tooltip: "要添加到视频中的音频。"
    },
    fps: {
      name: "帧率"
    },
    images: {
      name: "图像",
      tooltip: "用于创建视频的图像。"
    }
  }
};
const CropMask = {
  display_name: "裁剪遮罩",
  inputs: {
    height: {
      name: "高度"
    },
    mask: {
      name: "遮罩"
    },
    width: {
      name: "宽度"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const DiffControlNetLoader = {
  display_name: "加载ControlNet模型（diff）",
  inputs: {
    control_net_name: {
      name: "ControlNet名称"
    },
    model: {
      name: "模型"
    }
  }
};
const DifferentialDiffusion = {
  display_name: "差异扩散DifferentialDiffusion",
  inputs: {
    model: {
      name: "模型"
    }
  }
};
const DiffusersLoader = {
  display_name: "Diffusers加载器",
  inputs: {
    model_path: {
      name: "模型路径"
    }
  }
};
const DisableNoise = {
  display_name: "禁用噪波"
};
const DualCFGGuider = {
  display_name: "双CFG引导器",
  inputs: {
    cfg_cond2_negative: {
      name: "cfg_条件2_负面"
    },
    cfg_conds: {
      name: "cfg_条件1"
    },
    cond1: {
      name: "条件1"
    },
    cond2: {
      name: "条件2"
    },
    model: {
      name: "模型"
    },
    negative: {
      name: "负面条件"
    }
  }
};
const DualCLIPLoader = {
  description: "[配方]\n\nSDXL：clip-l，clip-g\nSD3：clip-l，clip-g / clip-l，t5 / clip-g，t5\nFlux：clip-l，t5",
  display_name: "双CLIP加载器",
  inputs: {
    clip_name1: {
      name: "CLIP名称1"
    },
    clip_name2: {
      name: "CLIP名称2"
    },
    device: {
      name: "设备"
    },
    type: {
      name: "类型"
    }
  }
};
const EmptyCosmosLatentVideo = {
  display_name: "空的Cosmos潜在视频",
  inputs: {
    batch_size: {
      name: "批量大小"
    },
    height: {
      name: "高度"
    },
    length: {
      name: "长度"
    },
    width: {
      name: "宽度"
    }
  }
};
const EmptyHunyuanLatentVideo = {
  display_name: "空Latent视频（混元）",
  inputs: {
    batch_size: {
      name: "批量大小"
    },
    height: {
      name: "高度"
    },
    length: {
      name: "长度"
    },
    width: {
      name: "宽度"
    }
  }
};
const EmptyImage = {
  display_name: "空图像",
  inputs: {
    batch_size: {
      name: "批量大小"
    },
    color: {
      name: "颜色"
    },
    height: {
      name: "高度"
    },
    width: {
      name: "宽度"
    }
  }
};
const EmptyLTXVLatentVideo = {
  display_name: "空Latent视频（LTXV）",
  inputs: {
    batch_size: {
      name: "批量大小"
    },
    height: {
      name: "高度"
    },
    length: {
      name: "长度"
    },
    width: {
      name: "宽度"
    }
  }
};
const EmptyLatentAudio = {
  display_name: "空Latent音频",
  inputs: {
    batch_size: {
      name: "批量大小",
      tooltip: "批次中的Latent数量。"
    },
    seconds: {
      name: "秒"
    }
  }
};
const EmptyLatentHunyuan3Dv2 = {
  display_name: "EmptyLatentHunyuan3Dv2",
  inputs: {
    batch_size: {
      name: "批量大小",
      tooltip: "批量中的潜在图像数量。"
    },
    resolution: {
      name: "分辨率"
    }
  }
};
const EmptyLatentImage = {
  description: "创建一批新的空Latent图像，以通过采样进行降噪。",
  display_name: "空Latent图像",
  inputs: {
    batch_size: {
      name: "批量大小",
      tooltip: "批次中的Latent数量。"
    },
    height: {
      name: "高度",
      tooltip: "Latent图像的高度（像素）。"
    },
    width: {
      name: "宽度",
      tooltip: "Latent图像的宽度（像素）。"
    }
  },
  outputs: {
    "0": {
      tooltip: "空Latent图像批次。"
    }
  }
};
const EmptyMochiLatentVideo = {
  display_name: "空Latent视频（Mochi）",
  inputs: {
    batch_size: {
      name: "批量大小"
    },
    height: {
      name: "高度"
    },
    length: {
      name: "长度"
    },
    width: {
      name: "宽度"
    }
  }
};
const EmptySD3LatentImage = {
  display_name: "空Latent图像（SD3）",
  inputs: {
    batch_size: {
      name: "批量大小"
    },
    height: {
      name: "高度"
    },
    width: {
      name: "宽度"
    }
  }
};
const ExponentialScheduler = {
  display_name: "Exponential调度器",
  inputs: {
    sigma_max: {
      name: "最大Sigma"
    },
    sigma_min: {
      name: "最新Sigma"
    },
    steps: {
      name: "步数"
    }
  }
};
const ExtendIntermediateSigmas = {
  display_name: "ExtendIntermediateSigmas",
  inputs: {
    end_at_sigma: {
      name: "结束 sigma"
    },
    sigmas: {
      name: "sigmas"
    },
    spacing: {
      name: "间距"
    },
    start_at_sigma: {
      name: "起始 sigma"
    },
    steps: {
      name: "步数"
    }
  }
};
const FeatherMask = {
  display_name: "羽化遮罩",
  inputs: {
    bottom: {
      name: "底"
    },
    left: {
      name: "左"
    },
    mask: {
      name: "遮罩"
    },
    right: {
      name: "右"
    },
    top: {
      name: "顶"
    }
  }
};
const FlipSigmas = {
  display_name: "翻转Sigma",
  inputs: {
    sigmas: {
      name: "sigmas"
    }
  }
};
const FluxDisableGuidance = {
  description: "此节点完全禁用Flux和类似Flux模型上的指导嵌入",
  display_name: "Flux禁用指导",
  inputs: {
    conditioning: {
      name: "conditioning"
    }
  }
};
const FluxGuidance = {
  display_name: "Flux引导",
  inputs: {
    conditioning: {
      name: "条件"
    },
    guidance: {
      name: "引导"
    }
  }
};
const FluxProCannyNode = {
  description: "使用控制图像（canny）生成图像。",
  display_name: "Flux.1 Canny 控制图像",
  inputs: {
    canny_high_threshold: {
      name: "canny_high_threshold",
      tooltip: "Canny 边缘检测的高阈值；如果 skip_processing 为 True，则忽略"
    },
    canny_low_threshold: {
      name: "canny_low_threshold",
      tooltip: "Canny 边缘检测的低阈值；如果 skip_processing 为 True，则忽略"
    },
    control_after_generate: {
      name: "control after generate"
    },
    control_image: {
      name: "control_image"
    },
    guidance: {
      name: "guidance",
      tooltip: "图像生成过程中的引导强度"
    },
    prompt: {
      name: "prompt",
      tooltip: "用于图像生成的提示词"
    },
    prompt_upsampling: {
      name: "prompt_upsampling",
      tooltip: "是否对提示词进行上采样。如果启用，将自动修改提示词以获得更具创意的生成，但结果是非确定性的（相同种子不会产生完全相同的结果）。"
    },
    seed: {
      name: "seed",
      tooltip: "用于生成噪声的随机种子。"
    },
    skip_preprocessing: {
      name: "skip_preprocessing",
      tooltip: "是否跳过预处理；如果 control_image 已经是 canny 处理后的图像，则设为 True，如果是原始图像则设为 False。"
    },
    steps: {
      name: "steps",
      tooltip: "图像生成过程的步数"
    }
  }
};
const FluxProDepthNode = {
  description: "使用控制图像（深度）生成图像。",
  display_name: "Flux.1 深度控制图像",
  inputs: {
    control_after_generate: {
      name: "control after generate"
    },
    control_image: {
      name: "control_image"
    },
    guidance: {
      name: "guidance",
      tooltip: "图像生成过程中的引导强度"
    },
    prompt: {
      name: "prompt",
      tooltip: "用于图像生成的提示词"
    },
    prompt_upsampling: {
      name: "prompt_upsampling",
      tooltip: "是否对提示词进行上采样。启用后会自动修改提示词以获得更具创意的生成，但结果具有不确定性（相同种子不会产生完全相同的结果）。"
    },
    seed: {
      name: "seed",
      tooltip: "用于生成噪声的随机种子。"
    },
    skip_preprocessing: {
      name: "skip_preprocessing",
      tooltip: "是否跳过预处理；如果 control_image 已经是深度图像则设为 True，如果是原始图像则设为 False。"
    },
    steps: {
      name: "steps",
      tooltip: "图像生成过程的步数"
    }
  }
};
const FluxProExpandNode = {
  description: "根据提示词对图像进行外扩。",
  display_name: "Flux.1 扩展图像",
  inputs: {
    bottom: {
      name: "下方扩展",
      tooltip: "在图像底部扩展的像素数"
    },
    control_after_generate: {
      name: "生成后控制"
    },
    guidance: {
      name: "引导强度",
      tooltip: "图像生成过程中的引导强度"
    },
    image: {
      name: "图像"
    },
    left: {
      name: "左侧扩展",
      tooltip: "在图像左侧扩展的像素数"
    },
    prompt: {
      name: "提示词",
      tooltip: "用于生成图像的提示词"
    },
    prompt_upsampling: {
      name: "提示词上采样",
      tooltip: "是否对提示词进行上采样。启用后会自动修改提示词以获得更具创意的生成效果，但结果具有不确定性（相同种子不会产生完全相同的结果）。"
    },
    right: {
      name: "右侧扩展",
      tooltip: "在图像右侧扩展的像素数"
    },
    seed: {
      name: "种子",
      tooltip: "用于生成噪声的随机种子。"
    },
    steps: {
      name: "步数",
      tooltip: "图像生成过程的步数"
    },
    top: {
      name: "上方扩展",
      tooltip: "在图像顶部扩展的像素数"
    }
  }
};
const FluxProFillNode = {
  description: "根据 mask 和提示词对图像进行修复填充。",
  display_name: "Flux.1 填充图像",
  inputs: {
    control_after_generate: {
      name: "生成后控制"
    },
    guidance: {
      name: "引导强度",
      tooltip: "图像生成过程中的引导强度"
    },
    image: {
      name: "图像"
    },
    mask: {
      name: "mask"
    },
    prompt: {
      name: "提示词",
      tooltip: "用于图像生成的提示词"
    },
    prompt_upsampling: {
      name: "提示词上采样",
      tooltip: "是否对提示词进行上采样。启用后会自动修改提示词以获得更具创意的生成效果，但结果具有不确定性（相同种子不会产生完全相同的结果）。"
    },
    seed: {
      name: "种子",
      tooltip: "用于生成噪声的随机种子。"
    },
    steps: {
      name: "步数",
      tooltip: "图像生成过程的步数"
    }
  }
};
const FluxProUltraImageNode = {
  description: "通过 API 使用 Flux Pro 1.1 Ultra 根据提示词和分辨率生成图像。",
  display_name: "Flux 1.1 [pro] Ultra Image",
  inputs: {
    aspect_ratio: {
      name: "宽高比",
      tooltip: "图像的宽高比；必须在 1:4 到 4:1 之间。"
    },
    control_after_generate: {
      name: "生成后控制"
    },
    image_prompt: {
      name: "图像提示词"
    },
    image_prompt_strength: {
      name: "图像提示词强度",
      tooltip: "在提示词和图像提示词之间进行混合。"
    },
    prompt: {
      name: "提示词",
      tooltip: "用于图像生成的提示词"
    },
    prompt_upsampling: {
      name: "提示词上采样",
      tooltip: "是否对提示词进行上采样。启用时，会自动修改提示词以获得更具创意的生成效果，但结果是非确定性的（相同种子不会产生完全相同的结果）。"
    },
    raw: {
      name: "原始",
      tooltip: "为 True 时，生成更少处理、更自然的图像。"
    },
    seed: {
      name: "种子",
      tooltip: "用于生成噪声的随机种子。"
    }
  }
};
const FreSca = {
  description: "对引导应用频率相关的缩放",
  display_name: "FreSca",
  inputs: {
    freq_cutoff: {
      name: "freq_cutoff",
      tooltip: "围绕中心被视为低频的频率索引数量"
    },
    model: {
      name: "model"
    },
    scale_high: {
      name: "scale_high",
      tooltip: "高频分量的缩放因子"
    },
    scale_low: {
      name: "scale_low",
      tooltip: "低频分量的缩放因子"
    }
  }
};
const FreeU = {
  display_name: "FreeU",
  inputs: {
    b1: {
      name: "b1"
    },
    b2: {
      name: "b2"
    },
    model: {
      name: "模型"
    },
    s1: {
      name: "s1"
    },
    s2: {
      name: "s2"
    }
  }
};
const FreeU_V2 = {
  display_name: "FreeU_V2",
  inputs: {
    b1: {
      name: "b1"
    },
    b2: {
      name: "b2"
    },
    model: {
      name: "模型"
    },
    s1: {
      name: "s1"
    },
    s2: {
      name: "s2"
    }
  }
};
const GITSScheduler = {
  display_name: "GITS调度器",
  inputs: {
    coeff: {
      name: "系数"
    },
    denoise: {
      name: "降噪"
    },
    steps: {
      name: "步数"
    }
  }
};
const GLIGENLoader = {
  display_name: "GLIGEN加载器",
  inputs: {
    gligen_name: {
      name: "gligen名称"
    }
  }
};
const GLIGENTextBoxApply = {
  display_name: "GLIGEN文本框应用",
  inputs: {
    clip: {
      name: "CLIPCLIP"
    },
    conditioning_to: {
      name: "条件到"
    },
    gligen_textbox_model: {
      name: "GLIGEN文本框模型"
    },
    height: {
      name: "高度"
    },
    text: {
      name: "文本"
    },
    width: {
      name: "宽度"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const GetVideoComponents = {
  description: "提取视频中的所有组件：帧、音频和帧率。",
  display_name: "获取视频组件",
  inputs: {
    video: {
      name: "视频",
      tooltip: "要提取组件的视频。"
    }
  },
  outputs: {
    "0": {
      name: "图像"
    },
    "1": {
      name: "音频"
    },
    "2": {
      name: "帧率"
    }
  }
};
const GrowMask = {
  display_name: "扩展遮罩",
  inputs: {
    expand: {
      name: "扩展"
    },
    mask: {
      name: "遮罩"
    },
    tapered_corners: {
      name: "倒角"
    }
  }
};
const Hunyuan3Dv2Conditioning = {
  display_name: "Hunyuan3Dv2Conditioning",
  inputs: {
    clip_vision_output: {
      name: "clip视觉输出"
    }
  },
  outputs: {
    "0": {
      name: "正向"
    },
    "1": {
      name: "反向"
    }
  }
};
const Hunyuan3Dv2ConditioningMultiView = {
  display_name: "Hunyuan3Dv2ConditioningMultiView",
  inputs: {
    back: {
      name: "后"
    },
    front: {
      name: "前"
    },
    left: {
      name: "左"
    },
    right: {
      name: "右"
    }
  },
  outputs: {
    "0": {
      name: "正向"
    },
    "1": {
      name: "反向"
    }
  }
};
const HunyuanImageToVideo = {
  display_name: "Hunyuan图像到视频",
  inputs: {
    batch_size: {
      name: "批量大小"
    },
    guidance_type: {
      name: "指导类型"
    },
    height: {
      name: "高度"
    },
    length: {
      name: "长度"
    },
    positive: {
      name: "正向"
    },
    start_image: {
      name: "起始图像"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "宽度"
    }
  },
  outputs: {
    "0": {
      name: "正向"
    },
    "1": {
      name: "潜在空间"
    }
  }
};
const HyperTile = {
  display_name: "超分块HyperTile",
  inputs: {
    max_depth: {
      name: "最大深度"
    },
    model: {
      name: "模型"
    },
    scale_depth: {
      name: "规模深度"
    },
    swap_size: {
      name: "分割尺寸"
    },
    tile_size: {
      name: "分块尺寸"
    }
  }
};
const HypernetworkLoader = {
  display_name: "超网络加载器",
  inputs: {
    hypernetwork_name: {
      name: "HyperNetwork名称"
    },
    model: {
      name: "模型"
    },
    strength: {
      name: "强度"
    }
  }
};
const IdeogramV1 = {
  description: "使用 Ideogram V1 模型同步生成图像。\n\n图片链接仅在有限时间内有效；如果您想保留图片，请务必下载。",
  display_name: "Ideogram V1",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio",
      tooltip: "图像生成的宽高比。"
    },
    control_after_generate: {
      name: "control after generate"
    },
    magic_prompt_option: {
      name: "magic_prompt_option",
      tooltip: "确定生成时是否使用 MagicPrompt"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "描述需要从图像中排除的内容"
    },
    num_images: {
      name: "num_images"
    },
    prompt: {
      name: "prompt",
      tooltip: "用于图像生成的提示词"
    },
    seed: {
      name: "seed"
    },
    turbo: {
      name: "turbo",
      tooltip: "是否启用 turbo 模式（生成更快，但可能质量较低）"
    }
  }
};
const IdeogramV2 = {
  description: "使用 Ideogram V2 模型同步生成图像。\n\n图像链接仅在有限时间内有效；如果您想保留图像，请务必下载。",
  display_name: "Ideogram V2",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio",
      tooltip: "图像生成的宽高比。如果分辨率未设置为 AUTO，则此项无效。"
    },
    control_after_generate: {
      name: "control after generate"
    },
    magic_prompt_option: {
      name: "magic_prompt_option",
      tooltip: "确定生成时是否使用 MagicPrompt"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "描述图像中需要排除的内容"
    },
    num_images: {
      name: "num_images"
    },
    prompt: {
      name: "prompt",
      tooltip: "用于图像生成的提示词"
    },
    resolution: {
      name: "resolution",
      tooltip: "图像生成的分辨率。如果未设置为 AUTO，则会覆盖 aspect_ratio 设置。"
    },
    seed: {
      name: "seed"
    },
    style_type: {
      name: "style_type",
      tooltip: "生成的风格类型（仅限 V2）"
    },
    turbo: {
      name: "turbo",
      tooltip: "是否启用 turbo 模式（生成更快，质量可能略低）"
    }
  }
};
const IdeogramV3 = {
  description: "使用 Ideogram V3 模型同步生成图像。\n\n支持从文本提示生成常规图像，也支持使用 mask 进行图像编辑。\n图片链接仅在有限时间内有效；如需保留图片，请务必下载。",
  display_name: "Ideogram V3",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio",
      tooltip: "图像生成的宽高比。如果分辨率未设置为自动，则忽略此项。"
    },
    control_after_generate: {
      name: "control after generate"
    },
    image: {
      name: "image",
      tooltip: "用于图像编辑的可选参考图片。"
    },
    magic_prompt_option: {
      name: "magic_prompt_option",
      tooltip: "决定生成时是否使用 MagicPrompt"
    },
    mask: {
      name: "mask",
      tooltip: "用于修复的可选 mask（白色区域将被替换）"
    },
    num_images: {
      name: "num_images"
    },
    prompt: {
      name: "prompt",
      tooltip: "用于图像生成或编辑的提示词"
    },
    rendering_speed: {
      name: "rendering_speed",
      tooltip: "控制生成速度与质量之间的权衡"
    },
    resolution: {
      name: "resolution",
      tooltip: "图像生成的分辨率。如果未设置为自动，则覆盖 aspect_ratio 设置。"
    },
    seed: {
      name: "seed"
    }
  }
};
const ImageBatch = {
  display_name: "组合图像批次",
  inputs: {
    image1: {
      name: "图像1"
    },
    image2: {
      name: "图像2"
    }
  }
};
const ImageBlend = {
  display_name: "混合图像",
  inputs: {
    blend_factor: {
      name: "系数"
    },
    blend_mode: {
      name: "混合模式"
    },
    image1: {
      name: "图像1"
    },
    image2: {
      name: "图像2"
    }
  }
};
const ImageBlur = {
  display_name: "模糊图像",
  inputs: {
    blur_radius: {
      name: "模糊半径"
    },
    image: {
      name: "图像"
    },
    sigma: {
      name: "西格玛"
    }
  }
};
const ImageColorToMask = {
  display_name: "图像颜色到遮罩",
  inputs: {
    color: {
      name: "颜色"
    },
    image: {
      name: "图像"
    }
  }
};
const ImageCompositeMasked = {
  display_name: "合成图像（遮罩）",
  inputs: {
    destination: {
      name: "目标图像"
    },
    mask: {
      name: "遮罩"
    },
    resize_source: {
      name: "缩放来源图像"
    },
    source: {
      name: "来源图像"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const ImageCrop = {
  display_name: "裁剪图像",
  inputs: {
    height: {
      name: "高度"
    },
    image: {
      name: "图像"
    },
    width: {
      name: "宽度"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const ImageFromBatch = {
  display_name: "从批次获取图像",
  inputs: {
    batch_index: {
      name: "批次索引"
    },
    image: {
      name: "图像"
    },
    length: {
      name: "长度"
    }
  }
};
const ImageInvert = {
  display_name: "反转图像",
  inputs: {
    image: {
      name: "图像"
    }
  }
};
const ImageOnlyCheckpointLoader = {
  display_name: "Checkpoint加载器（仅图像）",
  inputs: {
    ckpt_name: {
      name: "Checkpoint名称"
    }
  }
};
const ImageOnlyCheckpointSave = {
  display_name: "保存Checkpoint（仅图像）",
  inputs: {
    clip_vision: {
      name: "clip视觉"
    },
    filename_prefix: {
      name: "文件名前缀"
    },
    model: {
      name: "模型"
    },
    vae: {
      name: "vae"
    }
  }
};
const ImagePadForOutpaint = {
  display_name: "外补画板",
  inputs: {
    bottom: {
      name: "下"
    },
    feathering: {
      name: "羽化"
    },
    image: {
      name: "图像"
    },
    left: {
      name: "左"
    },
    right: {
      name: "右"
    },
    top: {
      name: "上"
    }
  }
};
const ImageQuantize = {
  display_name: "量化图像",
  inputs: {
    colors: {
      name: "颜色"
    },
    dither: {
      name: "抖动"
    },
    image: {
      name: "图像"
    }
  }
};
const ImageRGBToYUV = {
  display_name: "ImageRGBToYUV",
  inputs: {
    image: {
      name: "图像"
    }
  },
  outputs: {
    "0": {
      name: "Y"
    },
    "1": {
      name: "U"
    },
    "2": {
      name: "V"
    }
  }
};
const ImageScale = {
  display_name: "缩放图像",
  inputs: {
    crop: {
      name: "裁剪"
    },
    height: {
      name: "高度"
    },
    image: {
      name: "图像"
    },
    upscale_method: {
      name: "缩放算法"
    },
    width: {
      name: "宽度"
    }
  }
};
const ImageScaleBy = {
  display_name: "缩放图像（比例）",
  inputs: {
    image: {
      name: "图像"
    },
    scale_by: {
      name: "缩放系数"
    },
    upscale_method: {
      name: "缩放算法"
    }
  }
};
const ImageScaleToTotalPixels = {
  display_name: "缩放图像（像素）",
  inputs: {
    image: {
      name: "图像"
    },
    megapixels: {
      name: "像素数量"
    },
    upscale_method: {
      name: "缩放算法"
    }
  }
};
const ImageSharpen = {
  display_name: "锐化图像",
  inputs: {
    alpha: {
      name: "alpha"
    },
    image: {
      name: "图像"
    },
    sharpen_radius: {
      name: "锐化半径"
    },
    sigma: {
      name: "Sigma"
    }
  }
};
const ImageToMask = {
  display_name: "图像转换为遮罩",
  inputs: {
    channel: {
      name: "通道"
    },
    image: {
      name: "图像"
    }
  }
};
const ImageUpscaleWithModel = {
  display_name: "使用模型放大图像",
  inputs: {
    image: {
      name: "图像"
    },
    upscale_model: {
      name: "放大模型"
    }
  }
};
const ImageYUVToRGB = {
  display_name: "ImageYUVToRGB",
  inputs: {
    U: {
      name: "U"
    },
    V: {
      name: "V"
    },
    Y: {
      name: "Y"
    }
  }
};
const InpaintModelConditioning = {
  display_name: "内补模型条件",
  inputs: {
    mask: {
      name: "遮罩"
    },
    negative: {
      name: "负面条件"
    },
    noise_mask: {
      name: "噪波遮罩",
      tooltip: "向Latent图像添加遮罩，采样仅在遮罩内进行。根据模型的不同，可能会改善结果或完全破坏效果。"
    },
    pixels: {
      name: "像素"
    },
    positive: {
      name: "正面条件"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "正面条件"
    },
    "1": {
      name: "负面条件"
    },
    "2": {
      name: "Latent"
    }
  }
};
const InstructPixToPixConditioning = {
  display_name: "InstructPixToPix条件",
  inputs: {
    negative: {
      name: "负面条件"
    },
    pixels: {
      name: "像素"
    },
    positive: {
      name: "正面条件"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "正面条件"
    },
    "1": {
      name: "负面条件"
    },
    "2": {
      name: "Latent"
    }
  }
};
const InvertMask = {
  display_name: "反转遮罩",
  inputs: {
    mask: {
      name: "遮罩"
    }
  }
};
const JoinImageWithAlpha = {
  display_name: "合并图像Alpha",
  inputs: {
    alpha: {
      name: "阿尔法"
    },
    image: {
      name: "图像"
    }
  }
};
const KSampler = {
  description: "使用提供的模型、正面条件和负面条件条件降噪Latent图像。",
  display_name: "K采样器",
  inputs: {
    cfg: {
      name: "cfg",
      tooltip: "用于平衡随机性和提示词服从性。提高该值会使结果更加符合提示词，但过高会导致图像质量下降。"
    },
    control_after_generate: {
      name: "生成后的控制"
    },
    denoise: {
      name: "降噪",
      tooltip: "降噪的强度，降低该值会保留原图的大部分内容从而实现图生图。"
    },
    latent_image: {
      name: "Latent图像",
      tooltip: "要降噪的 Latent 图像。"
    },
    model: {
      name: "模型",
      tooltip: "用于降噪输入 Latent 图像的模型。"
    },
    negative: {
      name: "负面条件",
      tooltip: "描述不包含在图像中的内容的条件。"
    },
    positive: {
      name: "正面条件",
      tooltip: "描述包含在图像中的内容的条件。"
    },
    sampler_name: {
      name: "采样器名称",
      tooltip: "采样算法，会影响结果质量、生成速度、风格样式。"
    },
    scheduler: {
      name: "调度器",
      tooltip: "控制逐渐移除噪波的方法。"
    },
    seed: {
      name: "种子",
      tooltip: "生成噪波的随机种。"
    },
    steps: {
      name: "步数",
      tooltip: "降噪的步数。"
    }
  },
  outputs: {
    "0": {
      tooltip: "降噪后的 Latent。"
    }
  }
};
const KSamplerAdvanced = {
  display_name: "K采样器（高级）",
  inputs: {
    add_noise: {
      name: "添加噪波"
    },
    cfg: {
      name: "cfg"
    },
    control_after_generate: {
      name: "生成后的控制"
    },
    end_at_step: {
      name: "结束步数"
    },
    latent_image: {
      name: "Latent图像"
    },
    model: {
      name: "模型"
    },
    negative: {
      name: "负面条件"
    },
    noise_seed: {
      name: "随机种"
    },
    positive: {
      name: "正面条件"
    },
    return_with_leftover_noise: {
      name: "返回剩余噪波"
    },
    sampler_name: {
      name: "采样器名称"
    },
    scheduler: {
      name: "调度器"
    },
    start_at_step: {
      name: "开始步数"
    },
    steps: {
      name: "步数"
    }
  }
};
const KSamplerSelect = {
  display_name: "K采样器选择",
  inputs: {
    sampler_name: {
      name: "采样器名称"
    }
  }
};
const KarrasScheduler = {
  display_name: "Karras调度器",
  inputs: {
    rho: {
      name: "rho"
    },
    sigma_max: {
      name: "sigma_max"
    },
    sigma_min: {
      name: "sigma_min"
    },
    steps: {
      name: "步数"
    }
  }
};
const KlingCameraControlI2VNode = {
  description: "将静态图像转化为具有专业摄像机运动的电影级视频，模拟真实世界的电影摄影。可控制虚拟摄像机的缩放、旋转、平移、俯仰和第一人称视角，同时保持对原始图像的聚焦。",
  display_name: "Kling 图像转视频（摄像机控制）",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio"
    },
    camera_control: {
      name: "camera_control",
      tooltip: "可通过 Kling Camera Controls 节点创建。控制视频生成过程中的摄像机运动和动作。"
    },
    cfg_scale: {
      name: "cfg_scale"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "反向文本提示"
    },
    prompt: {
      name: "prompt",
      tooltip: "正向文本提示"
    },
    start_frame: {
      name: "start_frame",
      tooltip: "参考图像 - URL 或 Base64 编码字符串，不能超过 10MB，分辨率不低于 300*300 像素，宽高比在 1:2.5 ~ 2.5:1 之间。Base64 不应包含 data:image 前缀。"
    }
  },
  outputs: {
    "1": {
      name: "video_id"
    },
    "2": {
      name: "duration"
    }
  }
};
const KlingCameraControlT2VNode = {
  description: "将文本转化为具有专业摄像机运动的电影级视频，模拟真实世界的电影摄影。可控制虚拟摄像机的动作，包括缩放、旋转、平移、俯仰和第一人称视角，同时保持对原始文本的聚焦。",
  display_name: "Kling 文本转视频（摄像机控制）",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio"
    },
    camera_control: {
      name: "camera_control",
      tooltip: "可通过 Kling Camera Controls 节点创建。控制视频生成过程中的摄像机运动和移动。"
    },
    cfg_scale: {
      name: "cfg_scale"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "反向文本提示"
    },
    prompt: {
      name: "prompt",
      tooltip: "正向文本提示"
    }
  },
  outputs: {
    "1": {
      name: "video_id"
    },
    "2": {
      name: "duration"
    }
  }
};
const KlingCameraControls = {
  description: "允许指定 Kling 相机控制和运动控制效果的配置选项。",
  display_name: "Kling 相机控制",
  inputs: {
    camera_control_type: {
      name: "camera_control_type"
    },
    horizontal_movement: {
      name: "horizontal_movement",
      tooltip: "控制相机在水平轴（x 轴）上的移动。负值表示向左，正值表示向右。"
    },
    pan: {
      name: "pan",
      tooltip: "控制相机在垂直平面（x 轴）上的旋转。负值表示向下旋转，正值表示向上旋转。"
    },
    roll: {
      name: "roll",
      tooltip: "控制相机的滚转量（z 轴）。负值表示逆时针，正值表示顺时针。"
    },
    tilt: {
      name: "tilt",
      tooltip: "控制相机在水平平面（y 轴）上的旋转。负值表示向左旋转，正值表示向右旋转。"
    },
    vertical_movement: {
      name: "vertical_movement",
      tooltip: "控制相机在垂直轴（y 轴）上的移动。负值表示向下，正值表示向上。"
    },
    zoom: {
      name: "zoom",
      tooltip: "控制相机焦距的变化。负值表示视野变窄，正值表示视野变宽。"
    }
  },
  outputs: {
    "0": {
      name: "camera_control"
    }
  }
};
const KlingDualCharacterVideoEffectNode = {
  description: "根据 effect_scene 在生成视频时实现不同的特效。第一张图片将被放置在合成画面的左侧，第二张图片在右侧。",
  display_name: "Kling 双角色视频特效",
  inputs: {
    duration: {
      name: "duration"
    },
    effect_scene: {
      name: "effect_scene"
    },
    image_left: {
      name: "image_left",
      tooltip: "左侧图片"
    },
    image_right: {
      name: "image_right",
      tooltip: "右侧图片"
    },
    mode: {
      name: "mode"
    },
    model_name: {
      name: "model_name"
    }
  },
  outputs: {
    "1": {
      name: "duration"
    }
  }
};
const KlingImage2VideoNode = {
  description: "Kling 图像转视频节点",
  display_name: "Kling 图像转视频",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio"
    },
    cfg_scale: {
      name: "cfg_scale"
    },
    duration: {
      name: "duration"
    },
    mode: {
      name: "mode"
    },
    model_name: {
      name: "model_name"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "反向文本提示"
    },
    prompt: {
      name: "prompt",
      tooltip: "正向文本提示"
    },
    start_frame: {
      name: "start_frame",
      tooltip: "参考图像 - URL 或 Base64 编码字符串，不能超过 10MB，分辨率不少于 300*300 像素，宽高比在 1:2.5 ~ 2.5:1 之间。Base64 不应包含 data:image 前缀。"
    }
  },
  outputs: {
    "1": {
      name: "video_id"
    },
    "2": {
      name: "duration"
    }
  }
};
const KlingImageGenerationNode = {
  description: "Kling 图像生成节点。通过文本提示生成图像，可选参考图像。",
  display_name: "Kling 图像生成",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio"
    },
    human_fidelity: {
      name: "human_fidelity",
      tooltip: "主体参考相似度"
    },
    image: {
      name: "image"
    },
    image_fidelity: {
      name: "image_fidelity",
      tooltip: "用户上传图像的参考强度"
    },
    image_type: {
      name: "image_type"
    },
    model_name: {
      name: "model_name"
    },
    n: {
      name: "n",
      tooltip: "生成图像数量"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "反向文本提示"
    },
    prompt: {
      name: "prompt",
      tooltip: "正向文本提示"
    }
  }
};
const KlingLipSyncAudioToVideoNode = {
  description: "Kling 音频驱动视频口型同步节点。将视频文件中的嘴部动作与音频文件的音频内容进行同步。",
  display_name: "Kling 音频驱动视频口型同步",
  inputs: {
    audio: {
      name: "音频"
    },
    video: {
      name: "视频"
    },
    voice_language: {
      name: "语音语言"
    }
  },
  outputs: {
    "1": {
      name: "视频ID"
    },
    "2": {
      name: "时长"
    }
  }
};
const KlingLipSyncTextToVideoNode = {
  description: "Kling 文字驱动口型同步节点。将视频文件中的嘴部动作与文本提示同步。",
  display_name: "Kling 文字驱动口型同步视频",
  inputs: {
    text: {
      name: "文本",
      tooltip: "用于口型同步视频生成的文本内容。当模式为 text2video 时必填。最大长度为 120 个字符。"
    },
    video: {
      name: "视频"
    },
    voice: {
      name: "语音"
    },
    voice_speed: {
      name: "语速",
      tooltip: "语音速率。有效范围：0.8~2.0，精确到小数点后一位。"
    }
  },
  outputs: {
    "1": {
      name: "视频ID"
    },
    "2": {
      name: "时长"
    }
  }
};
const KlingSingleImageVideoEffectNode = {
  description: "根据 effect_scene 在生成视频时实现不同的特效。",
  display_name: "Kling 视频特效",
  inputs: {
    duration: {
      name: "duration"
    },
    effect_scene: {
      name: "effect_scene"
    },
    image: {
      name: "image",
      tooltip: "参考图片。URL 或 Base64 编码字符串（不含 data:image 前缀）。文件大小不得超过 10MB，分辨率不低于 300*300 像素，宽高比在 1:2.5 ~ 2.5:1 之间。"
    },
    model_name: {
      name: "model_name"
    }
  },
  outputs: {
    "1": {
      name: "video_id"
    },
    "2": {
      name: "duration"
    }
  }
};
const KlingStartEndFrameNode = {
  description: "生成一个在起始图像和结束图像之间过渡的视频序列。该节点会创建所有中间帧，实现从第一帧到最后一帧的平滑变换。",
  display_name: "Kling 起止帧生成视频",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio"
    },
    cfg_scale: {
      name: "cfg_scale"
    },
    end_frame: {
      name: "end_frame",
      tooltip: "参考图像 - 结束帧控制。URL 或 Base64 编码字符串，不能超过 10MB，分辨率不低于 300*300 像素。Base64 不应包含 data:image 前缀。"
    },
    mode: {
      name: "mode",
      tooltip: "用于视频生成的配置，格式为：mode / duration / model_name。"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "反向文本提示"
    },
    prompt: {
      name: "prompt",
      tooltip: "正向文本提示"
    },
    start_frame: {
      name: "start_frame",
      tooltip: "参考图像 - URL 或 Base64 编码字符串，不能超过 10MB，分辨率不低于 300*300 像素，宽高比在 1:2.5 ~ 2.5:1 之间。Base64 不应包含 data:image 前缀。"
    }
  },
  outputs: {
    "1": {
      name: "video_id"
    },
    "2": {
      name: "duration"
    }
  }
};
const KlingTextToVideoNode = {
  description: "Kling 文本转视频节点",
  display_name: "Kling 文本转视频",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio"
    },
    cfg_scale: {
      name: "cfg_scale"
    },
    mode: {
      name: "mode",
      tooltip: "用于视频生成的配置，格式为：mode / duration / model_name。"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "反向文本提示"
    },
    prompt: {
      name: "prompt",
      tooltip: "正向文本提示"
    }
  },
  outputs: {
    "1": {
      name: "video_id"
    },
    "2": {
      name: "duration"
    }
  }
};
const KlingVideoExtendNode = {
  description: "Kling 视频扩展节点。扩展由其他 Kling 节点生成的视频。video_id 由其他 Kling 节点生成。",
  display_name: "Kling 视频扩展",
  inputs: {
    cfg_scale: {
      name: "cfg_scale"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "用于在扩展视频中避免出现的元素的负向文本提示"
    },
    prompt: {
      name: "prompt",
      tooltip: "用于引导视频扩展的正向文本提示"
    },
    video_id: {
      name: "video_id",
      tooltip: "要扩展的视频 ID。支持由文本转视频、图像转视频以及之前的视频扩展操作生成的视频。扩展后总时长不能超过 3 分钟。"
    }
  },
  outputs: {
    "1": {
      name: "video_id"
    },
    "2": {
      name: "duration"
    }
  }
};
const KlingVirtualTryOnNode = {
  description: "Kling 虚拟试穿节点。输入一张人物图片和一张服装图片，将服装试穿到人物身上。",
  display_name: "Kling 虚拟试穿",
  inputs: {
    cloth_image: {
      name: "cloth_image"
    },
    human_image: {
      name: "human_image"
    },
    model_name: {
      name: "model_name"
    }
  }
};
const LTXVAddGuide = {
  display_name: "LTXV添加指导",
  inputs: {
    frame_idx: {
      name: "帧索引",
      tooltip: "开始调节的帧索引。对于单帧图像或1-8帧的视频，任何帧索引值都可以接受。对于9+帧的视频，帧索引必须能被8整除，否则它将被向下取整到最接近的8的倍数。负值从视频的末尾开始计算。"
    },
    image: {
      name: "图像",
      tooltip: "用于调节潜在视频的图像或视频。必须是8*n + 1帧。如果视频不是8*n + 1帧，它将被裁剪到最接近的8*n + 1帧。"
    },
    latent: {
      name: "潜在空间"
    },
    negative: {
      name: "负向"
    },
    positive: {
      name: "正向"
    },
    strength: {
      name: "强度"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "正向"
    },
    "1": {
      name: "负向"
    },
    "2": {
      name: "潜在空间"
    }
  }
};
const LTXVConditioning = {
  display_name: "LTXV条件",
  inputs: {
    frame_rate: {
      name: "帧率"
    },
    negative: {
      name: "负面条件"
    },
    positive: {
      name: "正面条件"
    }
  },
  outputs: {
    "0": {
      name: "正面条件"
    },
    "1": {
      name: "负面条件"
    }
  }
};
const LTXVCropGuides = {
  display_name: "LTXV裁剪指导",
  inputs: {
    latent: {
      name: "潜在空间"
    },
    negative: {
      name: "负向"
    },
    positive: {
      name: "正向"
    }
  },
  outputs: {
    "0": {
      name: "正向"
    },
    "1": {
      name: "负向"
    },
    "2": {
      name: "潜在空间"
    }
  }
};
const LTXVImgToVideo = {
  display_name: "LTXV图像到视频",
  inputs: {
    batch_size: {
      name: "批量大小"
    },
    height: {
      name: "高度"
    },
    image: {
      name: "图像"
    },
    length: {
      name: "长度"
    },
    negative: {
      name: "负面条件"
    },
    positive: {
      name: "正面条件"
    },
    strength: {
      name: "强度"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "宽度"
    }
  },
  outputs: {
    "0": {
      name: "正面条件"
    },
    "1": {
      name: "负面条件"
    },
    "2": {
      name: "Latent"
    }
  }
};
const LTXVPreprocess = {
  display_name: "LTXV预处理",
  inputs: {
    image: {
      name: "图像"
    },
    img_compression: {
      name: "图像压缩",
      tooltip: "应用于图像的压缩量。"
    }
  },
  outputs: {
    "0": {
      name: "输出图像"
    }
  }
};
const LTXVScheduler = {
  display_name: "LTXV调度器",
  inputs: {
    base_shift: {
      name: "基础移位"
    },
    latent: {
      name: "Latent"
    },
    max_shift: {
      name: "最大移位"
    },
    steps: {
      name: "步数"
    },
    stretch: {
      name: "拉伸",
      tooltip: "将 sigma 拉伸到范围 [终值, 1]。"
    },
    terminal: {
      name: "终值",
      tooltip: "拉伸后 sigma 的终值。"
    }
  }
};
const LaplaceScheduler = {
  display_name: "Laplace调度器",
  inputs: {
    beta: {
      name: "beta"
    },
    mu: {
      name: "mu"
    },
    sigma_max: {
      name: "sigma_max"
    },
    sigma_min: {
      name: "sigma_min"
    },
    steps: {
      name: "步数"
    }
  }
};
const LatentAdd = {
  display_name: "Latent相加",
  inputs: {
    samples1: {
      name: "Latent1"
    },
    samples2: {
      name: "Latent2"
    }
  }
};
const LatentApplyOperation = {
  display_name: "Latent应用操作",
  inputs: {
    operation: {
      name: "操作"
    },
    samples: {
      name: "Latent"
    }
  }
};
const LatentApplyOperationCFG = {
  display_name: "Latent应用操作CFG",
  inputs: {
    model: {
      name: "模型"
    },
    operation: {
      name: "操作"
    }
  }
};
const LatentBatch = {
  display_name: "组合Latent批次",
  inputs: {
    samples1: {
      name: "Latent1"
    },
    samples2: {
      name: "Latent2"
    }
  }
};
const LatentBatchSeedBehavior = {
  display_name: "Latent批处理随机种行为",
  inputs: {
    samples: {
      name: "Latent"
    },
    seed_behavior: {
      name: "随机种行为"
    }
  }
};
const LatentBlend = {
  display_name: "混合Latent",
  inputs: {
    blend_factor: {
      name: "系数"
    },
    samples1: {
      name: "Latent1"
    },
    samples2: {
      name: "Latent2"
    }
  }
};
const LatentComposite = {
  display_name: "合成Latent",
  inputs: {
    feather: {
      name: "羽化"
    },
    samples_from: {
      name: "Latent从"
    },
    samples_to: {
      name: "Latent到"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const LatentCompositeMasked = {
  display_name: "合成Latent遮罩",
  inputs: {
    destination: {
      name: "目标Latent"
    },
    mask: {
      name: "遮罩"
    },
    resize_source: {
      name: "调整来源大小"
    },
    source: {
      name: "来源Latent"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const LatentCrop = {
  display_name: "裁剪Latent",
  inputs: {
    height: {
      name: "高度"
    },
    samples: {
      name: "Latent"
    },
    width: {
      name: "宽度"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const LatentFlip = {
  display_name: "翻转Latent",
  inputs: {
    flip_method: {
      name: "翻转方法"
    },
    samples: {
      name: "Latent"
    }
  }
};
const LatentFromBatch = {
  display_name: "从批次获取Latent",
  inputs: {
    batch_index: {
      name: "批次索引"
    },
    length: {
      name: "长度"
    },
    samples: {
      name: "Latent"
    }
  }
};
const LatentInterpolate = {
  display_name: "Latent插值",
  inputs: {
    ratio: {
      name: "比率"
    },
    samples1: {
      name: "Latent1"
    },
    samples2: {
      name: "Latent2"
    }
  }
};
const LatentMultiply = {
  display_name: "Latent相乘",
  inputs: {
    multiplier: {
      name: "乘数"
    },
    samples: {
      name: "Latent"
    }
  }
};
const LatentOperationSharpen = {
  display_name: "Latent操作锐化",
  inputs: {
    alpha: {
      name: "阿尔法"
    },
    sharpen_radius: {
      name: "锐化半径"
    },
    sigma: {
      name: "西格玛"
    }
  }
};
const LatentOperationTonemapReinhard = {
  display_name: "Latent操作色调映射Reinhard",
  inputs: {
    multiplier: {
      name: "乘数"
    }
  }
};
const LatentRotate = {
  display_name: "旋转Latent",
  inputs: {
    rotation: {
      name: "旋转"
    },
    samples: {
      name: "Latent"
    }
  }
};
const LatentSubtract = {
  display_name: "Latent相减",
  inputs: {
    samples1: {
      name: "Latent1"
    },
    samples2: {
      name: "Latent2"
    }
  }
};
const LatentUpscale = {
  display_name: "缩放Latent",
  inputs: {
    crop: {
      name: "裁剪"
    },
    height: {
      name: "高度"
    },
    samples: {
      name: "Latent"
    },
    upscale_method: {
      name: "缩放算法"
    },
    width: {
      name: "宽度"
    }
  }
};
const LatentUpscaleBy = {
  display_name: "缩放Latent（比例）",
  inputs: {
    samples: {
      name: "Latent"
    },
    scale_by: {
      name: "缩放比例"
    },
    upscale_method: {
      name: "缩放算法"
    }
  }
};
const Load3D = {
  display_name: "加载3D",
  inputs: {
    clear: {},
    height: {
      name: "高度"
    },
    image: {
      name: "图像"
    },
    model_file: {
      name: "模型文件"
    },
    "upload 3d model": {},
    width: {
      name: "宽度"
    }
  },
  outputs: [
    null,
    null,
    null,
    {
      name: "法线"
    },
    {
      name: "线稿"
    },
    {
      name: "相机信息"
    }
  ]
};
const Load3DAnimation = {
  display_name: "加载3D动画",
  inputs: {
    clear: {},
    height: {
      name: "高度"
    },
    image: {
      name: "图像"
    },
    model_file: {
      name: "模型文件"
    },
    "upload 3d model": {},
    width: {
      name: "宽度"
    }
  },
  outputs: [
    null,
    null,
    null,
    {
      name: "法线"
    },
    {
      name: "相机信息"
    }
  ]
};
const LoadAudio = {
  display_name: "加载音频",
  inputs: {
    audio: {
      name: "音频"
    },
    audioUI: {
      name: "音频UI"
    },
    upload: {
      name: "选择文件上传"
    }
  }
};
const LoadImage = {
  display_name: "加载图像",
  inputs: {
    image: {
      name: "图像"
    },
    upload: {
      name: "选择文件上传"
    }
  }
};
const LoadImageMask = {
  display_name: "加载图像（作为遮罩）",
  inputs: {
    channel: {
      name: "通道"
    },
    image: {
      name: "图像"
    },
    upload: {
      name: "选择文件上传"
    }
  }
};
const LoadImageOutput = {
  description: "从输出文件夹加载图像。当点击刷新按钮时，节点将更新图像列表并自动选择第一张图像，便于轻松迭代。",
  display_name: "加载图像（来自输出）",
  inputs: {
    image: {
      name: "图像"
    },
    refresh: {},
    upload: {
      name: "选择文件上传"
    }
  }
};
const LoadLatent = {
  display_name: "加载Latent",
  inputs: {
    latent: {
      name: "Latent"
    }
  }
};
const LoadVideo = {
  display_name: "加载视频",
  inputs: {
    file: {
      name: "文件"
    },
    upload: {
      name: "选择要上传的文件"
    }
  }
};
const LoraLoader = {
  description: "LoRA用于修改扩散和CLIP模型，改变Latent图像的降噪方式，例如应用风格。多个LoRA节点可以链接在一起。",
  display_name: "加载LoRA",
  inputs: {
    clip: {
      name: "CLIPCLIP",
      tooltip: "LoRA 将应用于的 CLIP 模型。"
    },
    lora_name: {
      name: "LoRA名称",
      tooltip: "LoRA 的名称。"
    },
    model: {
      name: "模型",
      tooltip: "LoRA 将应用于的扩散模型。"
    },
    strength_clip: {
      name: "CLIP强度",
      tooltip: "修改 CLIP 模型的强度。此值可以为负。"
    },
    strength_model: {
      name: "模型强度",
      tooltip: "修改扩散模型的强度。此值可以为负。"
    }
  },
  outputs: {
    "0": {
      tooltip: "修改后的扩散模型。"
    },
    "1": {
      tooltip: "修改后的CLIP模型。"
    }
  }
};
const LoraLoaderModelOnly = {
  description: "LoRA用于修改扩散和CLIP模型，改变Latent图像的降噪方式，例如应用风格。多个LoRA节点可以链接在一起。",
  display_name: "LoRA加载器（仅模型）",
  inputs: {
    lora_name: {
      name: "LoRA名称"
    },
    model: {
      name: "模型"
    },
    strength_model: {
      name: "模型强度"
    }
  },
  outputs: {
    "0": {
      tooltip: "修改后的扩散模型。"
    }
  }
};
const LoraSave = {
  display_name: "保存LoRA",
  inputs: {
    bias_diff: {
      name: "偏差差异"
    },
    filename_prefix: {
      name: "文件名前缀"
    },
    lora_type: {
      name: "lora类型"
    },
    model_diff: {
      name: "模型差异",
      tooltip: "要转换为 LoRA 的模型差异输出。"
    },
    rank: {
      name: "排名"
    },
    text_encoder_diff: {
      name: "文本编码器差异",
      tooltip: "要转换为 LoRA 的CLIP差异输出。"
    }
  }
};
const LotusConditioning = {
  display_name: "LotusConditioning",
  outputs: {
    "0": {
      name: "条件"
    }
  }
};
const LumaConceptsNode = {
  description: "包含一个或多个相机概念，可用于 Luma 文本转视频和 Luma 图像转视频节点。",
  display_name: "Luma 概念",
  inputs: {
    concept1: {
      name: "concept1"
    },
    concept2: {
      name: "concept2"
    },
    concept3: {
      name: "concept3"
    },
    concept4: {
      name: "concept4"
    },
    luma_concepts: {
      name: "luma_concepts",
      tooltip: "可选的相机概念，将添加到此处选择的概念中。"
    }
  },
  outputs: {
    "0": {
      name: "luma_concepts"
    }
  }
};
const LumaImageModifyNode = {
  description: "根据提示词和宽高比同步修改图像。",
  display_name: "Luma 图像到图像",
  inputs: {
    control_after_generate: {
      name: "control after generate"
    },
    image: {
      name: "image"
    },
    image_weight: {
      name: "image_weight",
      tooltip: "图像权重；越接近 1.0，图像被修改的程度越小。"
    },
    model: {
      name: "model"
    },
    prompt: {
      name: "prompt",
      tooltip: "用于图像生成的提示词"
    },
    seed: {
      name: "seed",
      tooltip: "用于决定节点是否重新运行的种子；无论种子如何，实际结果都是非确定性的。"
    }
  }
};
const LumaImageNode = {
  description: "根据提示词和宽高比同步生成图像。",
  display_name: "Luma 文生图",
  inputs: {
    aspect_ratio: {
      name: "宽高比"
    },
    character_image: {
      name: "角色参考图",
      tooltip: "角色参考图像；可为多张批量输入，最多可考虑 4 张图像。"
    },
    control_after_generate: {
      name: "生成后控制"
    },
    image_luma_ref: {
      name: "Luma 参考图",
      tooltip: "Luma 参考节点连接，可用输入图像影响生成；最多可考虑 4 张图像。"
    },
    model: {
      name: "模型"
    },
    prompt: {
      name: "提示词",
      tooltip: "用于图像生成的提示词"
    },
    seed: {
      name: "种子",
      tooltip: "用于决定节点是否重新运行的种子；无论种子如何，实际结果都是非确定性的。"
    },
    style_image: {
      name: "风格参考图",
      tooltip: "风格参考图像；仅使用 1 张图像。"
    },
    style_image_weight: {
      name: "风格图权重",
      tooltip: "风格图像的权重。如果未提供风格图像则忽略。"
    }
  }
};
const LumaImageToVideoNode = {
  description: "根据提示词、输入图像和输出尺寸同步生成视频。",
  display_name: "Luma 图像转视频",
  inputs: {
    control_after_generate: {
      name: "生成后控制"
    },
    duration: {
      name: "时长"
    },
    first_image: {
      name: "首帧图像",
      tooltip: "生成视频的第一帧。"
    },
    last_image: {
      name: "末帧图像",
      tooltip: "生成视频的最后一帧。"
    },
    loop: {
      name: "循环"
    },
    luma_concepts: {
      name: "luma_concepts",
      tooltip: "可选的 Camera Concepts，通过 Luma Concepts 节点控制相机运动。"
    },
    model: {
      name: "模型"
    },
    prompt: {
      name: "提示词",
      tooltip: "用于视频生成的提示词"
    },
    resolution: {
      name: "分辨率"
    },
    seed: {
      name: "种子",
      tooltip: "用于决定节点是否重新运行的种子；无论种子如何，实际结果都是非确定性的。"
    }
  }
};
const LumaReferenceNode = {
  description: "用于 Luma 生成图像节点，包含一张图片和权重。",
  display_name: "Luma 参考",
  inputs: {
    image: {
      name: "图片",
      tooltip: "用作参考的图片。"
    },
    luma_ref: {
      name: "luma_ref"
    },
    weight: {
      name: "权重",
      tooltip: "图片参考的权重。"
    }
  },
  outputs: {
    "0": {
      name: "luma_ref"
    }
  }
};
const LumaVideoNode = {
  description: "根据提示词和输出尺寸同步生成视频。",
  display_name: "Luma 文本转视频",
  inputs: {
    aspect_ratio: {
      name: "宽高比"
    },
    control_after_generate: {
      name: "生成后控制"
    },
    duration: {
      name: "时长"
    },
    loop: {
      name: "循环"
    },
    luma_concepts: {
      name: "luma_concepts",
      tooltip: "可选的相机概念，通过 Luma Concepts 节点控制相机运动。"
    },
    model: {
      name: "模型"
    },
    prompt: {
      name: "提示词",
      tooltip: "用于视频生成的提示词"
    },
    resolution: {
      name: "分辨率"
    },
    seed: {
      name: "种子",
      tooltip: "用于决定节点是否重新运行的种子；无论种子如何，实际结果都是非确定性的。"
    }
  }
};
const Mahiro = {
  description: "修改引导以更多地侧重于正面条件提示的'方向'，而不是负面条件提示之间的差异。",
  display_name: "真寻太可爱了，她应该有个更好的引导功能！！(。・ω・。)",
  inputs: {
    model: {
      name: "模型"
    }
  },
  outputs: {
    "0": {
      name: "修补后的模型"
    }
  }
};
const MaskComposite = {
  display_name: "合成遮罩",
  inputs: {
    destination: {
      name: "目标"
    },
    operation: {
      name: "操作"
    },
    source: {
      name: "源"
    },
    x: {
      name: "x"
    },
    y: {
      name: "y"
    }
  }
};
const MaskPreview = {
  description: "将输入图像保存到您的 ComfyUI 输出目录。",
  display_name: "MaskPreview",
  inputs: {
    mask: {
      name: "mask"
    }
  }
};
const MaskToImage = {
  display_name: "遮罩转换为图像",
  inputs: {
    mask: {
      name: "遮罩"
    }
  }
};
const MinimaxImageToVideoNode = {
  description: "使用 MiniMax 的 API 根据图像和提示生成视频",
  display_name: "MiniMax 图像转视频",
  inputs: {
    control_after_generate: {
      name: "control after generate"
    },
    image: {
      name: "image",
      tooltip: "用于视频生成首帧的图像"
    },
    model: {
      name: "model",
      tooltip: "用于视频生成的模型"
    },
    prompt_text: {
      name: "prompt_text",
      tooltip: "用于引导视频生成的文本提示"
    },
    seed: {
      name: "seed",
      tooltip: "用于生成噪声的随机种子。"
    }
  }
};
const MinimaxTextToVideoNode = {
  description: "使用 MiniMax 的 API 根据提示生成视频",
  display_name: "MiniMax 文本转视频",
  inputs: {
    control_after_generate: {
      name: "control after generate"
    },
    model: {
      name: "model",
      tooltip: "用于视频生成的模型"
    },
    prompt_text: {
      name: "prompt_text",
      tooltip: "用于引导视频生成的文本提示"
    },
    seed: {
      name: "seed",
      tooltip: "用于生成噪声的随机种子。"
    }
  }
};
const ModelComputeDtype = {
  display_name: "模型计算Dtype",
  inputs: {
    dtype: {
      name: "dtype"
    },
    model: {
      name: "模型"
    }
  }
};
const ModelMergeAdd = {
  display_name: "模型相加",
  inputs: {
    model1: {
      name: "模型1"
    },
    model2: {
      name: "模型2"
    }
  }
};
const ModelMergeAuraflow = {
  display_name: "模型融合（Auraflow ）",
  inputs: {
    cond_seq_linear_: {
      name: "条件序列线性."
    },
    double_layers_0_: {
      name: "双层.0."
    },
    double_layers_1_: {
      name: "双层.1."
    },
    double_layers_2_: {
      name: "双层.2."
    },
    double_layers_3_: {
      name: "双层.3."
    },
    final_linear_: {
      name: "最终线性."
    },
    init_x_linear_: {
      name: "初始x线性."
    },
    modF_: {
      name: "modF."
    },
    model1: {
      name: "模型1"
    },
    model2: {
      name: "模型2"
    },
    positional_encoding: {
      name: "位置编码"
    },
    register_tokens: {
      name: "注册令牌"
    },
    single_layers_0_: {
      name: "单层.0."
    },
    single_layers_10_: {
      name: "单层.10."
    },
    single_layers_11_: {
      name: "单层.11."
    },
    single_layers_12_: {
      name: "单层.12."
    },
    single_layers_13_: {
      name: "单层.13."
    },
    single_layers_14_: {
      name: "单层.14."
    },
    single_layers_15_: {
      name: "单层.15."
    },
    single_layers_16_: {
      name: "单层.16."
    },
    single_layers_17_: {
      name: "单层.17."
    },
    single_layers_18_: {
      name: "单层.18."
    },
    single_layers_19_: {
      name: "单层.19."
    },
    single_layers_1_: {
      name: "单层.1."
    },
    single_layers_20_: {
      name: "单层.20."
    },
    single_layers_21_: {
      name: "单层.21."
    },
    single_layers_22_: {
      name: "单层.22."
    },
    single_layers_23_: {
      name: "单层.23."
    },
    single_layers_24_: {
      name: "单层.24."
    },
    single_layers_25_: {
      name: "单层.25."
    },
    single_layers_26_: {
      name: "单层.26."
    },
    single_layers_27_: {
      name: "单层.27."
    },
    single_layers_28_: {
      name: "单层.28."
    },
    single_layers_29_: {
      name: "单层.29."
    },
    single_layers_2_: {
      name: "单层.2."
    },
    single_layers_30_: {
      name: "单层.30."
    },
    single_layers_31_: {
      name: "单层.31."
    },
    single_layers_3_: {
      name: "单层.3."
    },
    single_layers_4_: {
      name: "单层.4."
    },
    single_layers_5_: {
      name: "单层.5."
    },
    single_layers_6_: {
      name: "单层.6."
    },
    single_layers_7_: {
      name: "单层.7."
    },
    single_layers_8_: {
      name: "单层.8."
    },
    single_layers_9_: {
      name: "单层.9."
    },
    t_embedder_: {
      name: "t嵌入器."
    }
  }
};
const ModelMergeBlocks = {
  display_name: "模型融合（分块）",
  inputs: {
    input: {
      name: "输入"
    },
    middle: {
      name: "中间"
    },
    model1: {
      name: "模型1"
    },
    model2: {
      name: "模型2"
    },
    out: {
      name: "输出"
    }
  }
};
const ModelMergeCosmos14B = {
  display_name: "ModelMergeCosmos14B",
  inputs: {
    affline_norm_: {
      name: "仿射规范化."
    },
    blocks_block0_: {
      name: "blocks.block0."
    },
    blocks_block10_: {
      name: "blocks.block10."
    },
    blocks_block11_: {
      name: "blocks.block11."
    },
    blocks_block12_: {
      name: "blocks.block12."
    },
    blocks_block13_: {
      name: "blocks.block13."
    },
    blocks_block14_: {
      name: "blocks.block14."
    },
    blocks_block15_: {
      name: "blocks.block15."
    },
    blocks_block16_: {
      name: "blocks.block16."
    },
    blocks_block17_: {
      name: "blocks.block17."
    },
    blocks_block18_: {
      name: "blocks.block18."
    },
    blocks_block19_: {
      name: "blocks.block19."
    },
    blocks_block1_: {
      name: "blocks.block1."
    },
    blocks_block20_: {
      name: "blocks.block20."
    },
    blocks_block21_: {
      name: "blocks.block21."
    },
    blocks_block22_: {
      name: "blocks.block22."
    },
    blocks_block23_: {
      name: "blocks.block23."
    },
    blocks_block24_: {
      name: "blocks.block24."
    },
    blocks_block25_: {
      name: "blocks.block25."
    },
    blocks_block26_: {
      name: "blocks.block26."
    },
    blocks_block27_: {
      name: "blocks.block27."
    },
    blocks_block28_: {
      name: "blocks.block28."
    },
    blocks_block29_: {
      name: "blocks.block29."
    },
    blocks_block2_: {
      name: "blocks.block2."
    },
    blocks_block30_: {
      name: "blocks.block30."
    },
    blocks_block31_: {
      name: "blocks.block31."
    },
    blocks_block32_: {
      name: "blocks.block32."
    },
    blocks_block33_: {
      name: "blocks.block33."
    },
    blocks_block34_: {
      name: "blocks.block34."
    },
    blocks_block35_: {
      name: "blocks.block35."
    },
    blocks_block3_: {
      name: "blocks.block3."
    },
    blocks_block4_: {
      name: "blocks.block4."
    },
    blocks_block5_: {
      name: "blocks.block5."
    },
    blocks_block6_: {
      name: "blocks.block6."
    },
    blocks_block7_: {
      name: "blocks.block7."
    },
    blocks_block8_: {
      name: "blocks.block8."
    },
    blocks_block9_: {
      name: "blocks.block9."
    },
    extra_pos_embedder_: {
      name: "额外位置嵌入器."
    },
    final_layer_: {
      name: "最终层."
    },
    model1: {
      name: "模型1"
    },
    model2: {
      name: "模型2"
    },
    pos_embedder_: {
      name: "位置嵌入器."
    },
    t_embedder_: {
      name: "t嵌入器."
    },
    x_embedder_: {
      name: "x嵌入器."
    }
  }
};
const ModelMergeCosmos7B = {
  display_name: "ModelMergeCosmos7B",
  inputs: {
    affline_norm_: {
      name: "仿射规范化."
    },
    blocks_block0_: {
      name: "blocks.block0."
    },
    blocks_block10_: {
      name: "blocks.block10."
    },
    blocks_block11_: {
      name: "blocks.block11."
    },
    blocks_block12_: {
      name: "blocks.block12."
    },
    blocks_block13_: {
      name: "blocks.block13."
    },
    blocks_block14_: {
      name: "blocks.block14."
    },
    blocks_block15_: {
      name: "blocks.block15."
    },
    blocks_block16_: {
      name: "blocks.block16."
    },
    blocks_block17_: {
      name: "blocks.block17."
    },
    blocks_block18_: {
      name: "blocks.block18."
    },
    blocks_block19_: {
      name: "blocks.block19."
    },
    blocks_block1_: {
      name: "blocks.block1."
    },
    blocks_block20_: {
      name: "blocks.block20."
    },
    blocks_block21_: {
      name: "blocks.block21."
    },
    blocks_block22_: {
      name: "blocks.block22."
    },
    blocks_block23_: {
      name: "blocks.block23."
    },
    blocks_block24_: {
      name: "blocks.block24."
    },
    blocks_block25_: {
      name: "blocks.block25."
    },
    blocks_block26_: {
      name: "blocks.block26."
    },
    blocks_block27_: {
      name: "blocks.block27."
    },
    blocks_block2_: {
      name: "blocks.block2."
    },
    blocks_block3_: {
      name: "blocks.block3."
    },
    blocks_block4_: {
      name: "blocks.block4."
    },
    blocks_block5_: {
      name: "blocks.block5."
    },
    blocks_block6_: {
      name: "blocks.block6."
    },
    blocks_block7_: {
      name: "blocks.block7."
    },
    blocks_block8_: {
      name: "blocks.block8."
    },
    blocks_block9_: {
      name: "blocks.block9."
    },
    extra_pos_embedder_: {
      name: "额外位置嵌入器."
    },
    final_layer_: {
      name: "最终层."
    },
    model1: {
      name: "模型1"
    },
    model2: {
      name: "模型2"
    },
    pos_embedder_: {
      name: "位置嵌入器."
    },
    t_embedder_: {
      name: "t嵌入器."
    },
    x_embedder_: {
      name: "x嵌入器."
    }
  }
};
const ModelMergeFlux1 = {
  display_name: "模型融合（Flux1）",
  inputs: {
    double_blocks_0_: {
      name: "双块.0."
    },
    double_blocks_10_: {
      name: "双块.10."
    },
    double_blocks_11_: {
      name: "双块.11."
    },
    double_blocks_12_: {
      name: "双块.12."
    },
    double_blocks_13_: {
      name: "双块.13."
    },
    double_blocks_14_: {
      name: "双块.14."
    },
    double_blocks_15_: {
      name: "双块.15."
    },
    double_blocks_16_: {
      name: "双块.16."
    },
    double_blocks_17_: {
      name: "双块.17."
    },
    double_blocks_18_: {
      name: "双块.18."
    },
    double_blocks_1_: {
      name: "双块.1."
    },
    double_blocks_2_: {
      name: "双块.2."
    },
    double_blocks_3_: {
      name: "双块.3."
    },
    double_blocks_4_: {
      name: "双块.4."
    },
    double_blocks_5_: {
      name: "双块.5."
    },
    double_blocks_6_: {
      name: "双块.6."
    },
    double_blocks_7_: {
      name: "双块.7."
    },
    double_blocks_8_: {
      name: "双块.8."
    },
    double_blocks_9_: {
      name: "双块.9."
    },
    final_layer_: {
      name: "最终层."
    },
    guidance_in: {
      name: "输入引导"
    },
    img_in_: {
      name: "输入图像."
    },
    model1: {
      name: "模型1"
    },
    model2: {
      name: "模型2"
    },
    single_blocks_0_: {
      name: "单块.0."
    },
    single_blocks_10_: {
      name: "单块.10."
    },
    single_blocks_11_: {
      name: "单块.11."
    },
    single_blocks_12_: {
      name: "单块.12."
    },
    single_blocks_13_: {
      name: "单块.13."
    },
    single_blocks_14_: {
      name: "单块.14."
    },
    single_blocks_15_: {
      name: "单块.15."
    },
    single_blocks_16_: {
      name: "单块.16."
    },
    single_blocks_17_: {
      name: "单块.17."
    },
    single_blocks_18_: {
      name: "单块.18."
    },
    single_blocks_19_: {
      name: "单块.19."
    },
    single_blocks_1_: {
      name: "单块.1."
    },
    single_blocks_20_: {
      name: "单块.20."
    },
    single_blocks_21_: {
      name: "单块.21."
    },
    single_blocks_22_: {
      name: "单块.22."
    },
    single_blocks_23_: {
      name: "单块.23."
    },
    single_blocks_24_: {
      name: "单块.24."
    },
    single_blocks_25_: {
      name: "单块.25."
    },
    single_blocks_26_: {
      name: "单块.26."
    },
    single_blocks_27_: {
      name: "单块.27."
    },
    single_blocks_28_: {
      name: "单块.28."
    },
    single_blocks_29_: {
      name: "单块.29."
    },
    single_blocks_2_: {
      name: "单块.2."
    },
    single_blocks_30_: {
      name: "单块.30."
    },
    single_blocks_31_: {
      name: "单块.31."
    },
    single_blocks_32_: {
      name: "单块.32."
    },
    single_blocks_33_: {
      name: "单块.33."
    },
    single_blocks_34_: {
      name: "单块.34."
    },
    single_blocks_35_: {
      name: "单块.35."
    },
    single_blocks_36_: {
      name: "单块.36."
    },
    single_blocks_37_: {
      name: "单块.37."
    },
    single_blocks_3_: {
      name: "单块.3."
    },
    single_blocks_4_: {
      name: "单块.4."
    },
    single_blocks_5_: {
      name: "单块.5."
    },
    single_blocks_6_: {
      name: "单块.6."
    },
    single_blocks_7_: {
      name: "单块.7."
    },
    single_blocks_8_: {
      name: "单块.8."
    },
    single_blocks_9_: {
      name: "单块.9."
    },
    time_in_: {
      name: "输入时间."
    },
    txt_in_: {
      name: "输入文本."
    },
    vector_in_: {
      name: "输入向量."
    }
  }
};
const ModelMergeLTXV = {
  display_name: "模型融合（LTXV）",
  inputs: {
    adaln_single_: {
      name: "adaln_single."
    },
    caption_projection_: {
      name: "caption_projection."
    },
    model1: {
      name: "模型1"
    },
    model2: {
      name: "模型2"
    },
    patchify_proj_: {
      name: "patchify_proj."
    },
    proj_out_: {
      name: "proj_out."
    },
    scale_shift_table: {
      name: "scale_shift_table"
    },
    transformer_blocks_0_: {
      name: "transformer_blocks.0."
    },
    transformer_blocks_10_: {
      name: "transformer_blocks.10."
    },
    transformer_blocks_11_: {
      name: "transformer_blocks.11."
    },
    transformer_blocks_12_: {
      name: "transformer_blocks.12."
    },
    transformer_blocks_13_: {
      name: "transformer_blocks.13."
    },
    transformer_blocks_14_: {
      name: "transformer_blocks.14."
    },
    transformer_blocks_15_: {
      name: "transformer_blocks.15."
    },
    transformer_blocks_16_: {
      name: "transformer_blocks.16."
    },
    transformer_blocks_17_: {
      name: "transformer_blocks.17."
    },
    transformer_blocks_18_: {
      name: "transformer_blocks.18."
    },
    transformer_blocks_19_: {
      name: "transformer_blocks.19."
    },
    transformer_blocks_1_: {
      name: "transformer_blocks.1."
    },
    transformer_blocks_20_: {
      name: "transformer_blocks.20."
    },
    transformer_blocks_21_: {
      name: "transformer_blocks.21."
    },
    transformer_blocks_22_: {
      name: "transformer_blocks.22."
    },
    transformer_blocks_23_: {
      name: "transformer_blocks.23."
    },
    transformer_blocks_24_: {
      name: "transformer_blocks.24."
    },
    transformer_blocks_25_: {
      name: "transformer_blocks.25."
    },
    transformer_blocks_26_: {
      name: "transformer_blocks.26."
    },
    transformer_blocks_27_: {
      name: "transformer_blocks.27."
    },
    transformer_blocks_2_: {
      name: "transformer_blocks.2."
    },
    transformer_blocks_3_: {
      name: "transformer_blocks.3."
    },
    transformer_blocks_4_: {
      name: "transformer_blocks.4."
    },
    transformer_blocks_5_: {
      name: "transformer_blocks.5."
    },
    transformer_blocks_6_: {
      name: "transformer_blocks.6."
    },
    transformer_blocks_7_: {
      name: "transformer_blocks.7."
    },
    transformer_blocks_8_: {
      name: "transformer_blocks.8."
    },
    transformer_blocks_9_: {
      name: "transformer_blocks.9."
    }
  }
};
const ModelMergeMochiPreview = {
  display_name: "模型融合（Mochi预览）",
  inputs: {
    blocks_0_: {
      name: "blocks.0."
    },
    blocks_10_: {
      name: "blocks.10."
    },
    blocks_11_: {
      name: "blocks.11."
    },
    blocks_12_: {
      name: "blocks.12."
    },
    blocks_13_: {
      name: "blocks.13."
    },
    blocks_14_: {
      name: "blocks.14."
    },
    blocks_15_: {
      name: "blocks.15."
    },
    blocks_16_: {
      name: "blocks.16."
    },
    blocks_17_: {
      name: "blocks.17."
    },
    blocks_18_: {
      name: "blocks.18."
    },
    blocks_19_: {
      name: "blocks.19."
    },
    blocks_1_: {
      name: "blocks.1."
    },
    blocks_20_: {
      name: "blocks.20."
    },
    blocks_21_: {
      name: "blocks.21."
    },
    blocks_22_: {
      name: "blocks.22."
    },
    blocks_23_: {
      name: "blocks.23."
    },
    blocks_24_: {
      name: "blocks.24."
    },
    blocks_25_: {
      name: "blocks.25."
    },
    blocks_26_: {
      name: "blocks.26."
    },
    blocks_27_: {
      name: "blocks.27."
    },
    blocks_28_: {
      name: "blocks.28."
    },
    blocks_29_: {
      name: "blocks.29."
    },
    blocks_2_: {
      name: "blocks.2."
    },
    blocks_30_: {
      name: "blocks.30."
    },
    blocks_31_: {
      name: "blocks.31."
    },
    blocks_32_: {
      name: "blocks.32."
    },
    blocks_33_: {
      name: "blocks.33."
    },
    blocks_34_: {
      name: "blocks.34."
    },
    blocks_35_: {
      name: "blocks.35."
    },
    blocks_36_: {
      name: "blocks.36."
    },
    blocks_37_: {
      name: "blocks.37."
    },
    blocks_38_: {
      name: "blocks.38."
    },
    blocks_39_: {
      name: "blocks.39."
    },
    blocks_3_: {
      name: "blocks.3."
    },
    blocks_40_: {
      name: "blocks.40."
    },
    blocks_41_: {
      name: "blocks.41."
    },
    blocks_42_: {
      name: "blocks.42."
    },
    blocks_43_: {
      name: "blocks.43."
    },
    blocks_44_: {
      name: "blocks.44."
    },
    blocks_45_: {
      name: "blocks.45."
    },
    blocks_46_: {
      name: "blocks.46."
    },
    blocks_47_: {
      name: "blocks.47."
    },
    blocks_4_: {
      name: "blocks.4."
    },
    blocks_5_: {
      name: "blocks.5."
    },
    blocks_6_: {
      name: "blocks.6."
    },
    blocks_7_: {
      name: "blocks.7."
    },
    blocks_8_: {
      name: "blocks.8."
    },
    blocks_9_: {
      name: "blocks.9."
    },
    final_layer_: {
      name: "final_layer."
    },
    model1: {
      name: "模型1"
    },
    model2: {
      name: "模型2"
    },
    pos_frequencies_: {
      name: "pos_frequencies."
    },
    t5_y_embedder_: {
      name: "t5_y_embedder."
    },
    t5_yproj_: {
      name: "t5_yproj."
    },
    t_embedder_: {
      name: "t_embedder."
    }
  }
};
const ModelMergeSD1 = {
  display_name: "模型融合（SD1）",
  inputs: {
    input_blocks_0_: {
      name: "输入块.0."
    },
    input_blocks_10_: {
      name: "输入块.10."
    },
    input_blocks_11_: {
      name: "输入块.11."
    },
    input_blocks_1_: {
      name: "输入块.1."
    },
    input_blocks_2_: {
      name: "输入块.2."
    },
    input_blocks_3_: {
      name: "输入块.3."
    },
    input_blocks_4_: {
      name: "输入块.4."
    },
    input_blocks_5_: {
      name: "输入块.5."
    },
    input_blocks_6_: {
      name: "输入块.6."
    },
    input_blocks_7_: {
      name: "输入块.7."
    },
    input_blocks_8_: {
      name: "输入块.8."
    },
    input_blocks_9_: {
      name: "输入块.9."
    },
    label_emb_: {
      name: "标签嵌入."
    },
    middle_block_0_: {
      name: "中间块.0."
    },
    middle_block_1_: {
      name: "中间块.1."
    },
    middle_block_2_: {
      name: "中间块.2."
    },
    model1: {
      name: "模型1"
    },
    model2: {
      name: "模型2"
    },
    out_: {
      name: "出."
    },
    output_blocks_0_: {
      name: "输出块.0."
    },
    output_blocks_10_: {
      name: "输出块.10."
    },
    output_blocks_11_: {
      name: "输出块.11."
    },
    output_blocks_1_: {
      name: "输出块.1."
    },
    output_blocks_2_: {
      name: "输出块.2."
    },
    output_blocks_3_: {
      name: "输出块.3."
    },
    output_blocks_4_: {
      name: "输出块.4."
    },
    output_blocks_5_: {
      name: "输出块.5."
    },
    output_blocks_6_: {
      name: "输出块.6."
    },
    output_blocks_7_: {
      name: "输出块.7."
    },
    output_blocks_8_: {
      name: "输出块.8."
    },
    output_blocks_9_: {
      name: "输出块.9."
    },
    time_embed_: {
      name: "时间嵌入."
    }
  }
};
const ModelMergeSD2 = {
  display_name: "模型融合（SD2）",
  inputs: {
    input_blocks_0_: {
      name: "输入块.0."
    },
    input_blocks_10_: {
      name: "输入块.10."
    },
    input_blocks_11_: {
      name: "输入块.11."
    },
    input_blocks_1_: {
      name: "输入块.1."
    },
    input_blocks_2_: {
      name: "输入块.2."
    },
    input_blocks_3_: {
      name: "输入块.3."
    },
    input_blocks_4_: {
      name: "输入块.4."
    },
    input_blocks_5_: {
      name: "输入块.5."
    },
    input_blocks_6_: {
      name: "输入块.6."
    },
    input_blocks_7_: {
      name: "输入块.7."
    },
    input_blocks_8_: {
      name: "输入块.8."
    },
    input_blocks_9_: {
      name: "输入块.9."
    },
    label_emb_: {
      name: "标签嵌入."
    },
    middle_block_0_: {
      name: "中间块.0."
    },
    middle_block_1_: {
      name: "中间块.1."
    },
    middle_block_2_: {
      name: "中间块.2."
    },
    model1: {
      name: "模型1"
    },
    model2: {
      name: "模型2"
    },
    out_: {
      name: "出."
    },
    output_blocks_0_: {
      name: "输出块.0."
    },
    output_blocks_10_: {
      name: "输出块.10."
    },
    output_blocks_11_: {
      name: "输出块.11."
    },
    output_blocks_1_: {
      name: "输出块.1."
    },
    output_blocks_2_: {
      name: "输出块.2."
    },
    output_blocks_3_: {
      name: "输出块.3."
    },
    output_blocks_4_: {
      name: "输出块.4."
    },
    output_blocks_5_: {
      name: "输出块.5."
    },
    output_blocks_6_: {
      name: "输出块.6."
    },
    output_blocks_7_: {
      name: "输出块.7."
    },
    output_blocks_8_: {
      name: "输出块.8."
    },
    output_blocks_9_: {
      name: "输出块.9."
    },
    time_embed_: {
      name: "时间嵌入."
    }
  }
};
const ModelMergeSD35_Large = {
  display_name: "模型融合（SD35_大）",
  inputs: {
    context_embedder_: {
      name: "上下文嵌入器."
    },
    final_layer_: {
      name: "最终层."
    },
    joint_blocks_0_: {
      name: "联合块.0."
    },
    joint_blocks_10_: {
      name: "联合块.10."
    },
    joint_blocks_11_: {
      name: "联合块.11."
    },
    joint_blocks_12_: {
      name: "联合块.12."
    },
    joint_blocks_13_: {
      name: "联合块.13."
    },
    joint_blocks_14_: {
      name: "联合块.14."
    },
    joint_blocks_15_: {
      name: "联合块.15."
    },
    joint_blocks_16_: {
      name: "联合块.16."
    },
    joint_blocks_17_: {
      name: "联合块.17."
    },
    joint_blocks_18_: {
      name: "联合块.18."
    },
    joint_blocks_19_: {
      name: "联合块.19."
    },
    joint_blocks_1_: {
      name: "联合块.1."
    },
    joint_blocks_20_: {
      name: "联合块.20."
    },
    joint_blocks_21_: {
      name: "联合块.21."
    },
    joint_blocks_22_: {
      name: "联合块.22."
    },
    joint_blocks_23_: {
      name: "联合块.23."
    },
    joint_blocks_24_: {
      name: "联合块.24."
    },
    joint_blocks_25_: {
      name: "联合块.25."
    },
    joint_blocks_26_: {
      name: "联合块.26."
    },
    joint_blocks_27_: {
      name: "联合块.27."
    },
    joint_blocks_28_: {
      name: "联合块.28."
    },
    joint_blocks_29_: {
      name: "联合块.29."
    },
    joint_blocks_2_: {
      name: "联合块.2."
    },
    joint_blocks_30_: {
      name: "联合块.30."
    },
    joint_blocks_31_: {
      name: "联合块.31."
    },
    joint_blocks_32_: {
      name: "联合块.32."
    },
    joint_blocks_33_: {
      name: "联合块.33."
    },
    joint_blocks_34_: {
      name: "联合块.34."
    },
    joint_blocks_35_: {
      name: "联合块.35."
    },
    joint_blocks_36_: {
      name: "联合块.36."
    },
    joint_blocks_37_: {
      name: "联合块.37."
    },
    joint_blocks_3_: {
      name: "联合块.3."
    },
    joint_blocks_4_: {
      name: "联合块.4."
    },
    joint_blocks_5_: {
      name: "联合块.5."
    },
    joint_blocks_6_: {
      name: "联合块.6."
    },
    joint_blocks_7_: {
      name: "联合块.7."
    },
    joint_blocks_8_: {
      name: "联合块.8."
    },
    joint_blocks_9_: {
      name: "联合块.9."
    },
    model1: {
      name: "模型1"
    },
    model2: {
      name: "模型2"
    },
    pos_embed_: {
      name: "位置嵌入."
    },
    t_embedder_: {
      name: "t嵌入器."
    },
    x_embedder_: {
      name: "x嵌入器."
    },
    y_embedder_: {
      name: "y嵌入器."
    }
  }
};
const ModelMergeSD3_2B = {
  display_name: "模型融合（SD3_2B）",
  inputs: {
    context_embedder_: {
      name: "上下文嵌入器."
    },
    final_layer_: {
      name: "最终层."
    },
    joint_blocks_0_: {
      name: "联合块.0."
    },
    joint_blocks_10_: {
      name: "联合块.10."
    },
    joint_blocks_11_: {
      name: "联合块.11."
    },
    joint_blocks_12_: {
      name: "联合块.12."
    },
    joint_blocks_13_: {
      name: "联合块.13."
    },
    joint_blocks_14_: {
      name: "联合块.14."
    },
    joint_blocks_15_: {
      name: "联合块.15."
    },
    joint_blocks_16_: {
      name: "联合块.16."
    },
    joint_blocks_17_: {
      name: "联合块.17."
    },
    joint_blocks_18_: {
      name: "联合块.18."
    },
    joint_blocks_19_: {
      name: "联合块.19."
    },
    joint_blocks_1_: {
      name: "联合块.1."
    },
    joint_blocks_20_: {
      name: "联合块.20."
    },
    joint_blocks_21_: {
      name: "联合块.21."
    },
    joint_blocks_22_: {
      name: "联合块.22."
    },
    joint_blocks_23_: {
      name: "联合块.23."
    },
    joint_blocks_2_: {
      name: "联合块.2."
    },
    joint_blocks_3_: {
      name: "联合块.3."
    },
    joint_blocks_4_: {
      name: "联合块.4."
    },
    joint_blocks_5_: {
      name: "联合块.5."
    },
    joint_blocks_6_: {
      name: "联合块.6."
    },
    joint_blocks_7_: {
      name: "联合块.7."
    },
    joint_blocks_8_: {
      name: "联合块.8."
    },
    joint_blocks_9_: {
      name: "联合块.9."
    },
    model1: {
      name: "模型1"
    },
    model2: {
      name: "模型2"
    },
    pos_embed_: {
      name: "位置嵌入."
    },
    t_embedder_: {
      name: "t嵌入器."
    },
    x_embedder_: {
      name: "x嵌入器."
    },
    y_embedder_: {
      name: "y嵌入器."
    }
  }
};
const ModelMergeSDXL = {
  display_name: "模型融合（SDXL）",
  inputs: {
    input_blocks_0: {
      name: "输入块.0"
    },
    input_blocks_1: {
      name: "输入块.1"
    },
    input_blocks_2: {
      name: "输入块.2"
    },
    input_blocks_3: {
      name: "输入块.3"
    },
    input_blocks_4: {
      name: "输入块.4"
    },
    input_blocks_5: {
      name: "输入块.5"
    },
    input_blocks_6: {
      name: "输入块.6"
    },
    input_blocks_7: {
      name: "输入块.7"
    },
    input_blocks_8: {
      name: "输入块.8"
    },
    label_emb_: {
      name: "标签嵌入."
    },
    middle_block_0: {
      name: "中间块.0"
    },
    middle_block_1: {
      name: "中间块.1"
    },
    middle_block_2: {
      name: "中间块.2"
    },
    model1: {
      name: "模型1"
    },
    model2: {
      name: "模型2"
    },
    out_: {
      name: "输出."
    },
    output_blocks_0: {
      name: "输出块.0"
    },
    output_blocks_1: {
      name: "输出块.1"
    },
    output_blocks_2: {
      name: "输出块.2"
    },
    output_blocks_3: {
      name: "输出块.3"
    },
    output_blocks_4: {
      name: "输出块.4"
    },
    output_blocks_5: {
      name: "输出块.5"
    },
    output_blocks_6: {
      name: "输出块.6"
    },
    output_blocks_7: {
      name: "输出块.7"
    },
    output_blocks_8: {
      name: "输出块.8"
    },
    time_embed_: {
      name: "时间嵌入."
    }
  }
};
const ModelMergeSimple = {
  display_name: "模型融合（简易）",
  inputs: {
    model1: {
      name: "模型1"
    },
    model2: {
      name: "模型2"
    },
    ratio: {
      name: "比例"
    }
  }
};
const ModelMergeSubtract = {
  display_name: "模型相减",
  inputs: {
    model1: {
      name: "模型1"
    },
    model2: {
      name: "模型2"
    },
    multiplier: {
      name: "乘数"
    }
  }
};
const ModelMergeWAN2_1 = {
  description: "1.3B模型有30个模块，14B模型有40个模块。图像转视频模型有额外的img_emb。",
  display_name: "ModelMergeWAN2_1",
  inputs: {
    blocks_0_: {
      name: "blocks.0."
    },
    blocks_10_: {
      name: "blocks.10."
    },
    blocks_11_: {
      name: "blocks.11."
    },
    blocks_12_: {
      name: "blocks.12."
    },
    blocks_13_: {
      name: "blocks.13."
    },
    blocks_14_: {
      name: "blocks.14."
    },
    blocks_15_: {
      name: "blocks.15."
    },
    blocks_16_: {
      name: "blocks.16."
    },
    blocks_17_: {
      name: "blocks.17."
    },
    blocks_18_: {
      name: "blocks.18."
    },
    blocks_19_: {
      name: "blocks.19."
    },
    blocks_1_: {
      name: "blocks.1."
    },
    blocks_20_: {
      name: "blocks.20."
    },
    blocks_21_: {
      name: "blocks.21."
    },
    blocks_22_: {
      name: "blocks.22."
    },
    blocks_23_: {
      name: "blocks.23."
    },
    blocks_24_: {
      name: "blocks.24."
    },
    blocks_25_: {
      name: "blocks.25."
    },
    blocks_26_: {
      name: "blocks.26."
    },
    blocks_27_: {
      name: "blocks.27."
    },
    blocks_28_: {
      name: "blocks.28."
    },
    blocks_29_: {
      name: "blocks.29."
    },
    blocks_2_: {
      name: "blocks.2."
    },
    blocks_30_: {
      name: "blocks.30."
    },
    blocks_31_: {
      name: "blocks.31."
    },
    blocks_32_: {
      name: "blocks.32."
    },
    blocks_33_: {
      name: "blocks.33."
    },
    blocks_34_: {
      name: "blocks.34."
    },
    blocks_35_: {
      name: "blocks.35."
    },
    blocks_36_: {
      name: "blocks.36."
    },
    blocks_37_: {
      name: "blocks.37."
    },
    blocks_38_: {
      name: "blocks.38."
    },
    blocks_39_: {
      name: "blocks.39."
    },
    blocks_3_: {
      name: "blocks.3."
    },
    blocks_4_: {
      name: "blocks.4."
    },
    blocks_5_: {
      name: "blocks.5."
    },
    blocks_6_: {
      name: "blocks.6."
    },
    blocks_7_: {
      name: "blocks.7."
    },
    blocks_8_: {
      name: "blocks.8."
    },
    blocks_9_: {
      name: "blocks.9."
    },
    head_: {
      name: "head."
    },
    img_emb_: {
      name: "img_emb."
    },
    model1: {
      name: "model1"
    },
    model2: {
      name: "model2"
    },
    patch_embedding_: {
      name: "patch_embedding."
    },
    text_embedding_: {
      name: "text_embedding."
    },
    time_embedding_: {
      name: "time_embedding."
    },
    time_projection_: {
      name: "time_projection."
    }
  }
};
const ModelSamplingAuraFlow = {
  display_name: "采样算法（AuraFlow）",
  inputs: {
    model: {
      name: "模型"
    },
    shift: {
      name: "移位"
    }
  }
};
const ModelSamplingContinuousEDM = {
  display_name: "采样算法（连续EDM）",
  inputs: {
    model: {
      name: "模型"
    },
    sampling: {
      name: "采样"
    },
    sigma_max: {
      name: "最大西格玛"
    },
    sigma_min: {
      name: "最小西格玛"
    }
  }
};
const ModelSamplingContinuousV = {
  display_name: "采样算法（连续V）",
  inputs: {
    model: {
      name: "模型"
    },
    sampling: {
      name: "采样"
    },
    sigma_max: {
      name: "最大西格玛"
    },
    sigma_min: {
      name: "最小西格玛"
    }
  }
};
const ModelSamplingDiscrete = {
  display_name: "采样算法（离散）",
  inputs: {
    model: {
      name: "模型"
    },
    sampling: {
      name: "采样"
    },
    zsnr: {
      name: "zsnr"
    }
  }
};
const ModelSamplingFlux = {
  display_name: "采样算法（Flux）",
  inputs: {
    base_shift: {
      name: "基础移位"
    },
    height: {
      name: "高度"
    },
    max_shift: {
      name: "最大移位"
    },
    model: {
      name: "模型"
    },
    width: {
      name: "宽度"
    }
  }
};
const ModelSamplingLTXV = {
  display_name: "采样算法（LTXV）",
  inputs: {
    base_shift: {
      name: "基础移位"
    },
    latent: {
      name: "Latent"
    },
    max_shift: {
      name: "最大移位"
    },
    model: {
      name: "模型"
    }
  }
};
const ModelSamplingSD3 = {
  display_name: "采样算法（SD3）",
  inputs: {
    model: {
      name: "模型"
    },
    shift: {
      name: "移位"
    }
  }
};
const ModelSamplingStableCascade = {
  display_name: "采样算法（Stable Cascade）",
  inputs: {
    model: {
      name: "模型"
    },
    shift: {
      name: "移位"
    }
  }
};
const ModelSave = {
  display_name: "保存模型",
  inputs: {
    filename_prefix: {
      name: "文件名前缀"
    },
    model: {
      name: "模型"
    }
  }
};
const Morphology = {
  display_name: "图像形态学",
  inputs: {
    image: {
      name: "图像"
    },
    kernel_size: {
      name: "核心大小"
    },
    operation: {
      name: "操作"
    }
  }
};
const OpenAIDalle2 = {
  description: "通过 OpenAI 的 DALL·E 2 接口同步生成图像。",
  display_name: "OpenAI DALL·E 2",
  inputs: {
    control_after_generate: {
      name: "生成后控制"
    },
    image: {
      name: "参考图像",
      tooltip: "用于图像编辑的可选参考图像。"
    },
    mask: {
      name: "掩码",
      tooltip: "用于修复的可选掩码（白色区域将被替换）"
    },
    n: {
      name: "数量",
      tooltip: "生成的图像数量"
    },
    prompt: {
      name: "提示词",
      tooltip: "用于 DALL·E 的文本提示"
    },
    seed: {
      name: "种子",
      tooltip: "后端尚未实现"
    },
    size: {
      name: "尺寸",
      tooltip: "图像尺寸"
    }
  }
};
const OpenAIDalle3 = {
  description: "通过 OpenAI 的 DALL·E 3 接口同步生成图像。",
  display_name: "OpenAI DALL·E 3",
  inputs: {
    control_after_generate: {
      name: "生成后控制"
    },
    prompt: {
      name: "提示词",
      tooltip: "DALL·E 的文本提示"
    },
    quality: {
      name: "质量",
      tooltip: "图像质量"
    },
    seed: {
      name: "种子",
      tooltip: "后端尚未实现"
    },
    size: {
      name: "尺寸",
      tooltip: "图像尺寸"
    },
    style: {
      name: "风格",
      tooltip: "“生动”会让模型倾向于生成超现实和戏剧性的图像。“自然”会让模型生成更自然、较少超现实感的图像。"
    }
  }
};
const OpenAIGPTImage1 = {
  description: "通过 OpenAI 的 GPT Image 1 端点同步生成图像。",
  display_name: "OpenAI GPT Image 1",
  inputs: {
    background: {
      name: "背景",
      tooltip: "返回带有或不带背景的图像"
    },
    control_after_generate: {
      name: "生成后控制"
    },
    image: {
      name: "参考图像",
      tooltip: "用于图像编辑的可选参考图像。"
    },
    mask: {
      name: "mask",
      tooltip: "用于修复的可选 mask（白色区域将被替换）"
    },
    n: {
      name: "数量",
      tooltip: "生成多少张图像"
    },
    prompt: {
      name: "提示词",
      tooltip: "用于 GPT Image 1 的文本提示"
    },
    quality: {
      name: "质量",
      tooltip: "图像质量，影响成本和生成时间。"
    },
    seed: {
      name: "种子",
      tooltip: "后端尚未实现"
    },
    size: {
      name: "尺寸",
      tooltip: "图像尺寸"
    }
  }
};
const OptimalStepsScheduler = {
  display_name: "OptimalStepsScheduler",
  inputs: {
    denoise: {
      name: "去噪"
    },
    model_type: {
      name: "model_type"
    },
    steps: {
      name: "步数"
    }
  }
};
const PairConditioningCombine = {
  display_name: "条件对合并",
  inputs: {
    negative_A: {
      name: "负面条件_A"
    },
    negative_B: {
      name: "负面条件_B"
    },
    positive_A: {
      name: "正面条件_A"
    },
    positive_B: {
      name: "正面条件_B"
    }
  },
  outputs: {
    "0": {
      name: "正面条件"
    },
    "1": {
      name: "负面条件"
    }
  }
};
const PairConditioningSetDefaultCombine = {
  display_name: "条件对设置默认合并",
  inputs: {
    hooks: {
      name: "约束"
    },
    negative: {
      name: "负面条件"
    },
    negative_DEFAULT: {
      name: "默认负面条件"
    },
    positive: {
      name: "正面条件"
    },
    positive_DEFAULT: {
      name: "默认正面条件"
    }
  },
  outputs: {
    "0": {
      name: "正面条件"
    },
    "1": {
      name: "负面条件"
    }
  }
};
const PairConditioningSetProperties = {
  display_name: "条件对设置属性",
  inputs: {
    hooks: {
      name: "约束"
    },
    mask: {
      name: "遮罩"
    },
    negative_NEW: {
      name: "新负面条件"
    },
    positive_NEW: {
      name: "新正面条件"
    },
    set_cond_area: {
      name: "设置条件区域"
    },
    strength: {
      name: "强度"
    },
    timesteps: {
      name: "间隔"
    }
  },
  outputs: {
    "0": {
      name: "正面条件"
    },
    "1": {
      name: "负面条件"
    }
  }
};
const PairConditioningSetPropertiesAndCombine = {
  display_name: "条件对设置属性合并",
  inputs: {
    hooks: {
      name: "约束"
    },
    mask: {
      name: "遮罩"
    },
    negative: {
      name: "负面条件"
    },
    negative_NEW: {
      name: "新负面条件"
    },
    positive: {
      name: "正面条件"
    },
    positive_NEW: {
      name: "新正面条件"
    },
    set_cond_area: {
      name: "设置条件区域"
    },
    strength: {
      name: "强度"
    },
    timesteps: {
      name: "间隔"
    }
  },
  outputs: {
    "0": {
      name: "正面条件"
    },
    "1": {
      name: "负面条件"
    }
  }
};
const PatchModelAddDownscale = {
  display_name: "收缩模型UNET（Kohya Deep Shrink）",
  inputs: {
    block_number: {
      name: "层编号"
    },
    downscale_after_skip: {
      name: "跳过后收缩"
    },
    downscale_factor: {
      name: "收缩系数"
    },
    downscale_method: {
      name: "收缩算法"
    },
    end_percent: {
      name: "结束百分比"
    },
    model: {
      name: "模型"
    },
    start_percent: {
      name: "开始百分比"
    },
    upscale_method: {
      name: "放大方法"
    }
  }
};
const PerpNeg = {
  display_name: "Perp-Neg（已弃用，使用PerpNegGuider）",
  inputs: {
    empty_conditioning: {
      name: "空条件"
    },
    model: {
      name: "模型"
    },
    neg_scale: {
      name: "负面缩放"
    }
  }
};
const PerpNegGuider = {
  display_name: "PerpNeg引导器",
  inputs: {
    cfg: {
      name: "cfg"
    },
    empty_conditioning: {
      name: "空条件"
    },
    model: {
      name: "模型"
    },
    neg_scale: {
      name: "负面缩放"
    },
    negative: {
      name: "负面条件"
    },
    positive: {
      name: "正面条件"
    }
  }
};
const PerturbedAttentionGuidance = {
  display_name: "PAG注意力引导",
  inputs: {
    model: {
      name: "模型"
    },
    scale: {
      name: "规模"
    }
  }
};
const PhotoMakerEncode = {
  display_name: "PhotoMaker编码",
  inputs: {
    clip: {
      name: "clip"
    },
    image: {
      name: "图像"
    },
    photomaker: {
      name: "photomaker"
    },
    text: {
      name: "文本"
    }
  }
};
const PhotoMakerLoader = {
  display_name: "PhotoMaker加载器",
  inputs: {
    photomaker_model_name: {
      name: "photomaker模型名称"
    }
  }
};
const PikaImageToVideoNode2_2 = {
  description: "将图像和提示词发送到 Pika API v2.2 以生成视频。",
  display_name: "Pika 图像转视频",
  inputs: {
    control_after_generate: {
      name: "生成后控制"
    },
    duration: {
      name: "时长"
    },
    image: {
      name: "图像",
      tooltip: "要转换为视频的图像"
    },
    negative_prompt: {
      name: "反向提示词"
    },
    prompt_text: {
      name: "提示词"
    },
    resolution: {
      name: "分辨率"
    },
    seed: {
      name: "种子"
    }
  }
};
const PikaScenesV2_2 = {
  description: "将你的图像组合在一起，生成包含所有物体的高质量视频。上传多张图片作为素材，生成融合所有内容的视频。",
  display_name: "Pika 场景（视频图像合成）",
  inputs: {
    aspect_ratio: {
      name: "宽高比",
      tooltip: "宽高比（宽 / 高）"
    },
    control_after_generate: {
      name: "生成后控制"
    },
    duration: {
      name: "时长"
    },
    image_ingredient_1: {
      name: "图片素材 1",
      tooltip: "用于生成视频的图片素材。"
    },
    image_ingredient_2: {
      name: "图片素材 2",
      tooltip: "用于生成视频的图片素材。"
    },
    image_ingredient_3: {
      name: "图片素材 3",
      tooltip: "用于生成视频的图片素材。"
    },
    image_ingredient_4: {
      name: "图片素材 4",
      tooltip: "用于生成视频的图片素材。"
    },
    image_ingredient_5: {
      name: "图片素材 5",
      tooltip: "用于生成视频的图片素材。"
    },
    ingredients_mode: {
      name: "素材模式"
    },
    negative_prompt: {
      name: "反向提示词"
    },
    prompt_text: {
      name: "提示词"
    },
    resolution: {
      name: "分辨率"
    },
    seed: {
      name: "随机种子"
    }
  }
};
const PikaStartEndFrameNode2_2 = {
  description: "通过合成首帧和尾帧生成视频。上传两张图片以定义起点和终点，让 AI 在它们之间创建平滑过渡。",
  display_name: "Pika 首尾帧合成视频",
  inputs: {
    control_after_generate: {
      name: "生成后控制"
    },
    duration: {
      name: "duration"
    },
    image_end: {
      name: "image_end",
      tooltip: "要合成的最后一张图片。"
    },
    image_start: {
      name: "image_start",
      tooltip: "要合成的第一张图片。"
    },
    negative_prompt: {
      name: "negative_prompt"
    },
    prompt_text: {
      name: "prompt_text"
    },
    resolution: {
      name: "resolution"
    },
    seed: {
      name: "seed"
    }
  }
};
const PikaTextToVideoNode2_2 = {
  description: "将文本提示发送到 Pika API v2.2 以生成视频。",
  display_name: "Pika 文本转视频",
  inputs: {
    aspect_ratio: {
      name: "宽高比",
      tooltip: "宽高比（宽 / 高）"
    },
    control_after_generate: {
      name: "生成后控制"
    },
    duration: {
      name: "时长"
    },
    negative_prompt: {
      name: "反向提示"
    },
    prompt_text: {
      name: "提示文本"
    },
    resolution: {
      name: "分辨率"
    },
    seed: {
      name: "种子"
    }
  }
};
const Pikadditions = {
  description: "将任意对象或图像添加到你的视频中。上传一个视频并指定你想要添加的内容，实现无缝集成的效果。",
  display_name: "Pikadditions（视频对象插入）",
  inputs: {
    control_after_generate: {
      name: "生成后控制"
    },
    image: {
      name: "图像",
      tooltip: "要添加到视频中的图像。"
    },
    negative_prompt: {
      name: "反向提示词"
    },
    prompt_text: {
      name: "提示词"
    },
    seed: {
      name: "种子"
    },
    video: {
      name: "视频",
      tooltip: "要添加图像的视频。"
    }
  }
};
const Pikaffects = {
  description: "生成带有特定Pikaffect的视频。支持的Pikaffect有：Cake-ify、Crumble、Crush、Decapitate、Deflate、Dissolve、Explode、Eye-pop、Inflate、Levitate、Melt、Peel、Poke、Squish、Ta-da、Tear",
  display_name: "Pikaffects（视频特效）",
  inputs: {
    control_after_generate: {
      name: "生成后控制"
    },
    image: {
      name: "image",
      tooltip: "要应用Pikaffect的参考图像。"
    },
    negative_prompt: {
      name: "negative_prompt"
    },
    pikaffect: {
      name: "pikaffect"
    },
    prompt_text: {
      name: "prompt_text"
    },
    seed: {
      name: "seed"
    }
  }
};
const Pikaswaps = {
  description: "用新图像或对象替换视频中的任意对象或区域。可通过 mask 或坐标定义需要替换的区域。",
  display_name: "Pika Swaps（视频对象替换）",
  inputs: {
    control_after_generate: {
      name: "生成后控制"
    },
    image: {
      name: "图像",
      tooltip: "用于替换视频中被 mask 的对象的图像。"
    },
    mask: {
      name: "mask",
      tooltip: "使用 mask 定义视频中需要替换的区域"
    },
    negative_prompt: {
      name: "反向提示词"
    },
    prompt_text: {
      name: "提示词"
    },
    seed: {
      name: "种子"
    },
    video: {
      name: "视频",
      tooltip: "要在其中替换对象的视频。"
    }
  }
};
const PixverseImageToVideoNode = {
  description: "根据提示词和输出尺寸同步生成视频。",
  display_name: "PixVerse 图像转视频",
  inputs: {
    control_after_generate: {
      name: "生成后控制"
    },
    duration_seconds: {
      name: "时长（秒）"
    },
    image: {
      name: "图像"
    },
    motion_mode: {
      name: "运动模式"
    },
    negative_prompt: {
      name: "反向提示词",
      tooltip: "可选的文本描述，用于指定图像中不希望出现的元素。"
    },
    pixverse_template: {
      name: "PixVerse 模板",
      tooltip: "可选模板，由 PixVerse Template 节点创建，用于影响生成风格。"
    },
    prompt: {
      name: "提示词",
      tooltip: "用于视频生成的提示词"
    },
    quality: {
      name: "质量"
    },
    seed: {
      name: "种子",
      tooltip: "用于视频生成的种子。"
    }
  }
};
const PixverseTemplateNode = {
  display_name: "PixVerse 模板",
  inputs: {
    template: {
      name: "模板"
    }
  },
  outputs: {
    "0": {
      name: "pixverse_template"
    }
  }
};
const PixverseTextToVideoNode = {
  description: "根据提示词和输出尺寸同步生成视频。",
  display_name: "PixVerse 文本转视频",
  inputs: {
    aspect_ratio: {
      name: "宽高比"
    },
    control_after_generate: {
      name: "生成后控制"
    },
    duration_seconds: {
      name: "时长（秒）"
    },
    motion_mode: {
      name: "运动模式"
    },
    negative_prompt: {
      name: "反向提示词",
      tooltip: "用于描述图像中不希望出现元素的可选文本。"
    },
    pixverse_template: {
      name: "PixVerse 模板",
      tooltip: "可选模板，用于影响生成风格，由 PixVerse Template 节点创建。"
    },
    prompt: {
      name: "提示词",
      tooltip: "用于视频生成的提示词"
    },
    quality: {
      name: "质量"
    },
    seed: {
      name: "种子",
      tooltip: "用于视频生成的种子。"
    }
  }
};
const PixverseTransitionVideoNode = {
  description: "根据提示词和输出尺寸同步生成视频。",
  display_name: "PixVerse 转场视频",
  inputs: {
    control_after_generate: {
      name: "生成后控制"
    },
    duration_seconds: {
      name: "时长（秒）"
    },
    first_frame: {
      name: "首帧"
    },
    last_frame: {
      name: "末帧"
    },
    motion_mode: {
      name: "运动模式"
    },
    negative_prompt: {
      name: "反向提示词",
      tooltip: "用于描述图像中不希望出现元素的可选文本。"
    },
    prompt: {
      name: "提示词",
      tooltip: "用于视频生成的提示词"
    },
    quality: {
      name: "质量"
    },
    seed: {
      name: "种子",
      tooltip: "用于视频生成的种子。"
    }
  }
};
const PolyexponentialScheduler = {
  display_name: "Polyexponential调度器",
  inputs: {
    rho: {
      name: "rho"
    },
    sigma_max: {
      name: "sigma最大值"
    },
    sigma_min: {
      name: "sigma最小值"
    },
    steps: {
      name: "步数"
    }
  }
};
const PorterDuffImageComposite = {
  display_name: "Porter-Duff图像合成",
  inputs: {
    destination: {
      name: "目标图像"
    },
    destination_alpha: {
      name: "目标图像alpha"
    },
    mode: {
      name: "模式"
    },
    source: {
      name: "来源图像"
    },
    source_alpha: {
      name: "来源图像alpha"
    }
  }
};
const Preview3D = {
  display_name: "预览3D",
  inputs: {
    camera_info: {
      name: "相机信息"
    },
    image: {
      name: "图像"
    },
    model_file: {
      name: "模型文件"
    }
  }
};
const Preview3DAnimation = {
  display_name: "预览3D - 动画",
  inputs: {
    camera_info: {
      name: "相机信息"
    },
    image: {
      name: "图像"
    },
    model_file: {
      name: "模型文件"
    }
  }
};
const PreviewAny = {
  display_name: "预览任意",
  inputs: {
    preview: {},
    source: {
      name: "源"
    }
  }
};
const PreviewAudio = {
  display_name: "预览音频",
  inputs: {
    audio: {
      name: "音频"
    },
    audioUI: {
      name: "音频UI"
    }
  }
};
const PreviewImage = {
  description: "将输入图像保存到您的ComfyUI临时目录。",
  display_name: "预览图像",
  inputs: {
    images: {
      name: "图像"
    }
  }
};
const PrimitiveBoolean = {
  display_name: "布尔值",
  inputs: {
    value: {
      name: "值"
    }
  }
};
const PrimitiveFloat = {
  display_name: "浮点数",
  inputs: {
    value: {
      name: "值"
    }
  }
};
const PrimitiveInt = {
  display_name: "整数",
  inputs: {
    control_after_generate: {
      name: "生成后控制"
    },
    value: {
      name: "数值"
    }
  }
};
const PrimitiveString = {
  display_name: "字符串",
  inputs: {
    value: {
      name: "值"
    }
  }
};
const PrimitiveStringMultiline = {
  display_name: "字符串（多行）",
  inputs: {
    value: {
      name: "值"
    }
  }
};
const QuadrupleCLIPLoader = {
  description: "[配方]\n\nhidream: long clip-l, long clip-g, t5xxl, llama_8b_3.1_instruct",
  display_name: "QuadrupleCLIPLoader",
  inputs: {
    clip_name1: {
      name: "clip_name1"
    },
    clip_name2: {
      name: "clip_name2"
    },
    clip_name3: {
      name: "clip_name3"
    },
    clip_name4: {
      name: "clip_name4"
    }
  }
};
const RandomNoise = {
  display_name: "随机噪波",
  inputs: {
    control_after_generate: {
      name: "生成后控制"
    },
    noise_seed: {
      name: "噪波随机种"
    }
  }
};
const RebatchImages = {
  display_name: "重设图像批次",
  inputs: {
    batch_size: {
      name: "批量大小"
    },
    images: {
      name: "图像"
    }
  }
};
const RebatchLatents = {
  display_name: "重设Latent批次",
  inputs: {
    batch_size: {
      name: "批量大小"
    },
    latents: {
      name: "Latent因素"
    }
  }
};
const RecraftColorRGB = {
  description: "通过选择特定的 RGB 值来创建 Recraft 颜色。",
  display_name: "Recraft 颜色 RGB",
  inputs: {
    b: {
      name: "b",
      tooltip: "颜色的蓝色值。"
    },
    g: {
      name: "g",
      tooltip: "颜色的绿色值。"
    },
    r: {
      name: "r",
      tooltip: "颜色的红色值。"
    },
    recraft_color: {
      name: "recraft_color"
    }
  },
  outputs: {
    "0": {
      name: "recraft_color"
    }
  }
};
const RecraftControls = {
  description: "创建 Recraft 控件以自定义 Recraft 生成。",
  display_name: "Recraft 控件",
  inputs: {
    background_color: {
      name: "background_color"
    },
    colors: {
      name: "colors"
    }
  },
  outputs: {
    "0": {
      name: "recraft_controls"
    }
  }
};
const RecraftCreativeUpscaleNode = {
  description: "同步放大图像。\n使用“创意放大”工具增强给定的光栅图像，提升分辨率，重点优化细节和人脸。",
  display_name: "Recraft 创意放大图像",
  inputs: {
    image: {
      name: "图像"
    }
  }
};
const RecraftCrispUpscaleNode = {
  description: "同步放大图像。\n使用“清晰放大”工具增强给定的光栅图像，提高图像分辨率，使图像更加锐利和干净。",
  display_name: "Recraft 清晰放大图像",
  inputs: {
    image: {
      name: "图像"
    }
  }
};
const RecraftImageInpaintingNode = {
  description: "根据提示词和 mask 修改图像。",
  display_name: "Recraft 图像修复",
  inputs: {
    control_after_generate: {
      name: "生成后控制"
    },
    image: {
      name: "image"
    },
    mask: {
      name: "mask"
    },
    n: {
      name: "数量",
      tooltip: "要生成的图像数量。"
    },
    negative_prompt: {
      name: "反向提示词",
      tooltip: "对图像中不希望出现元素的可选文本描述。"
    },
    prompt: {
      name: "提示词",
      tooltip: "用于图像生成的提示词。"
    },
    recraft_style: {
      name: "recraft_style"
    },
    seed: {
      name: "种子",
      tooltip: "用于决定节点是否重新运行的种子；无论种子如何，实际结果都是非确定性的。"
    }
  }
};
const RecraftImageToImageNode = {
  description: "根据提示词和强度修改图像。",
  display_name: "Recraft 图像到图像",
  inputs: {
    control_after_generate: {
      name: "生成后控制"
    },
    image: {
      name: "image"
    },
    n: {
      name: "数量",
      tooltip: "要生成的图像数量。"
    },
    negative_prompt: {
      name: "反向提示词",
      tooltip: "可选的文本描述，用于指定图像中不希望出现的元素。"
    },
    prompt: {
      name: "提示词",
      tooltip: "用于生成图像的提示词。"
    },
    recraft_controls: {
      name: "recraft_controls",
      tooltip: "通过 Recraft Controls 节点对生成过程进行可选的附加控制。"
    },
    recraft_style: {
      name: "recraft_style"
    },
    seed: {
      name: "种子",
      tooltip: "用于决定节点是否重新运行的种子；无论种子如何，实际结果都是非确定性的。"
    },
    strength: {
      name: "强度",
      tooltip: "定义与原始图像的差异，范围为[0, 1]，0表示几乎相同，1表示极大不同。"
    }
  }
};
const RecraftRemoveBackgroundNode = {
  description: "从图像中移除背景，返回处理后的图像和 mask。",
  display_name: "Recraft 移除背景",
  inputs: {
    image: {
      name: "图像"
    }
  }
};
const RecraftReplaceBackgroundNode = {
  description: "根据提供的提示词替换图像背景。",
  display_name: "Recraft 更换背景",
  inputs: {
    control_after_generate: {
      name: "生成后控制"
    },
    image: {
      name: "图像"
    },
    n: {
      name: "数量",
      tooltip: "要生成的图像数量。"
    },
    negative_prompt: {
      name: "反向提示词",
      tooltip: "对图像中不希望出现元素的可选文本描述。"
    },
    prompt: {
      name: "提示词",
      tooltip: "用于图像生成的提示词。"
    },
    recraft_style: {
      name: "recraft 风格"
    },
    seed: {
      name: "种子",
      tooltip: "用于决定节点是否重新运行的种子；无论种子如何，实际结果都是非确定性的。"
    }
  }
};
const RecraftStyleV3DigitalIllustration = {
  description: "选择 realistic_image 风格和可选的子风格。",
  display_name: "Recraft 风格 - 数字插画",
  inputs: {
    substyle: {
      name: "子风格"
    }
  },
  outputs: {
    "0": {
      name: "recraft_style"
    }
  }
};
const RecraftStyleV3InfiniteStyleLibrary = {
  description: "根据 Recraft 的无限风格库中已有的 UUID 选择风格。",
  display_name: "Recraft 风格 - 无限风格库",
  inputs: {
    style_id: {
      name: "style_id",
      tooltip: "来自无限风格库的风格 UUID。"
    }
  },
  outputs: {
    "0": {
      name: "recraft_style"
    }
  }
};
const RecraftStyleV3LogoRaster = {
  description: "选择 realistic_image 风格和可选的子风格。",
  display_name: "Recraft 风格 - 标志光栅图",
  inputs: {
    substyle: {
      name: "子风格"
    }
  },
  outputs: {
    "0": {
      name: "recraft_style"
    }
  }
};
const RecraftStyleV3RealisticImage = {
  description: "选择 realistic_image 风格和可选的子风格。",
  display_name: "Recraft 风格 - 真实图像",
  inputs: {
    substyle: {
      name: "子风格"
    }
  },
  outputs: {
    "0": {
      name: "recraft_style"
    }
  }
};
const RecraftTextToImageNode = {
  description: "根据提示词和分辨率同步生成图像。",
  display_name: "Recraft 文本转图像",
  inputs: {
    control_after_generate: {
      name: "control after generate"
    },
    n: {
      name: "n",
      tooltip: "要生成的图像数量。"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "对图像中不希望出现元素的可选文本描述。"
    },
    prompt: {
      name: "prompt",
      tooltip: "用于图像生成的提示词。"
    },
    recraft_controls: {
      name: "recraft_controls",
      tooltip: "通过 Recraft Controls 节点对生成过程的可选附加控制。"
    },
    recraft_style: {
      name: "recraft_style"
    },
    seed: {
      name: "seed",
      tooltip: "用于决定节点是否重新运行的种子；无论种子如何，实际结果都是非确定性的。"
    },
    size: {
      name: "size",
      tooltip: "生成图像的尺寸。"
    }
  }
};
const RecraftTextToVectorNode = {
  description: "根据提示词和分辨率同步生成 SVG。",
  display_name: "Recraft 文本转矢量",
  inputs: {
    control_after_generate: {
      name: "生成后控制"
    },
    n: {
      name: "数量",
      tooltip: "要生成的图像数量。"
    },
    negative_prompt: {
      name: "反向提示词",
      tooltip: "对图像中不希望出现元素的可选文本描述。"
    },
    prompt: {
      name: "提示词",
      tooltip: "用于生成图像的提示词。"
    },
    recraft_controls: {
      name: "Recraft 控制",
      tooltip: "通过 Recraft Controls 节点对生成过程的可选附加控制。"
    },
    seed: {
      name: "种子",
      tooltip: "用于决定节点是否重新运行的种子；无论种子如何，实际结果都是非确定性的。"
    },
    size: {
      name: "尺寸",
      tooltip: "生成图像的尺寸。"
    },
    substyle: {
      name: "子风格"
    }
  }
};
const RecraftVectorizeImageNode = {
  description: "从输入图像同步生成 SVG。",
  display_name: "Recraft 矢量化图像",
  inputs: {
    image: {
      name: "图像"
    }
  }
};
const RenormCFG = {
  display_name: "RenormCFG",
  inputs: {
    cfg_trunc: {
      name: "cfg_trunc"
    },
    model: {
      name: "模型"
    },
    renorm_cfg: {
      name: "renorm_cfg"
    }
  }
};
const RepeatImageBatch = {
  display_name: "复制图像批次",
  inputs: {
    amount: {
      name: "数量"
    },
    image: {
      name: "图像"
    }
  }
};
const RepeatLatentBatch = {
  display_name: "复制Latent批次",
  inputs: {
    amount: {
      name: "数量"
    },
    samples: {
      name: "Latent"
    }
  }
};
const RescaleCFG = {
  display_name: "缩放CFG",
  inputs: {
    model: {
      name: "模型"
    },
    multiplier: {
      name: "乘数"
    }
  }
};
const SDTurboScheduler = {
  display_name: "SDTurbo调度器",
  inputs: {
    denoise: {
      name: "降噪"
    },
    model: {
      name: "模型"
    },
    steps: {
      name: "步数"
    }
  }
};
const SD_4XUpscale_Conditioning = {
  display_name: "SD_4X放大条件",
  inputs: {
    images: {
      name: "图片"
    },
    negative: {
      name: "负面条件"
    },
    noise_augmentation: {
      name: "噪波增强"
    },
    positive: {
      name: "正面条件"
    },
    scale_ratio: {
      name: "缩放比例"
    }
  },
  outputs: {
    "0": {
      name: "正面条件"
    },
    "1": {
      name: "负面条件"
    },
    "2": {
      name: "Latent"
    }
  }
};
const SV3D_Conditioning = {
  display_name: "SV3D条件",
  inputs: {
    clip_vision: {
      name: "clip视觉"
    },
    elevation: {
      name: "俯仰角"
    },
    height: {
      name: "高度"
    },
    init_image: {
      name: "初始图像"
    },
    vae: {
      name: "vae"
    },
    video_frames: {
      name: "帧数"
    },
    width: {
      name: "宽度"
    }
  },
  outputs: {
    "0": {
      name: "正面条件"
    },
    "1": {
      name: "负面条件"
    },
    "2": {
      name: "Latent"
    }
  }
};
const SVD_img2vid_Conditioning = {
  display_name: "SVD_img2vid条件",
  inputs: {
    augmentation_level: {
      name: "增强"
    },
    clip_vision: {
      name: "clip视觉"
    },
    fps: {
      name: "帧率"
    },
    height: {
      name: "高度"
    },
    init_image: {
      name: "初始图像"
    },
    motion_bucket_id: {
      name: "动态bucketID"
    },
    vae: {
      name: "vae"
    },
    video_frames: {
      name: "帧数"
    },
    width: {
      name: "宽度"
    }
  },
  outputs: {
    "0": {
      name: "正面条件"
    },
    "1": {
      name: "负面条件"
    },
    "2": {
      name: "Latent"
    }
  }
};
const SamplerCustom = {
  display_name: "自定义采样器",
  inputs: {
    add_noise: {
      name: "添加噪波"
    },
    cfg: {
      name: "cfg"
    },
    control_after_generate: {
      name: "生成后的控制"
    },
    latent_image: {
      name: "Latent"
    },
    model: {
      name: "模型"
    },
    negative: {
      name: "负面条件"
    },
    noise_seed: {
      name: "噪波种子"
    },
    positive: {
      name: "正面条件"
    },
    sampler: {
      name: "采样器"
    },
    sigmas: {
      name: "Sigmas"
    }
  },
  outputs: {
    "0": {
      name: "Latent"
    },
    "1": {
      name: "降噪Latent"
    }
  }
};
const SamplerCustomAdvanced = {
  display_name: "自定义采样器（高级）",
  inputs: {
    guider: {
      name: "引导器"
    },
    latent_image: {
      name: "Latent图像"
    },
    noise: {
      name: "噪波"
    },
    sampler: {
      name: "采样器"
    },
    sigmas: {
      name: "西格玛"
    }
  },
  outputs: {
    "0": {
      name: "Latent"
    },
    "1": {
      name: "降噪Latent"
    }
  }
};
const SamplerDPMAdaptative = {
  display_name: "DPMAdaptative采样器",
  inputs: {
    accept_safety: {
      name: "accept_safety"
    },
    atol: {
      name: "atol"
    },
    dcoeff: {
      name: "dcoeff"
    },
    eta: {
      name: "eta"
    },
    h_init: {
      name: "h_init"
    },
    icoeff: {
      name: "icoeff"
    },
    order: {
      name: "order"
    },
    pcoeff: {
      name: "pcoeff"
    },
    rtol: {
      name: "rtol"
    },
    s_noise: {
      name: "s_noise"
    }
  }
};
const SamplerDPMPP_2M_SDE = {
  display_name: "DPMPP_2M_SDE采样器",
  inputs: {
    eta: {
      name: "eta"
    },
    noise_device: {
      name: "噪波设备"
    },
    s_noise: {
      name: "s_noise"
    },
    solver_type: {
      name: "求解器类型"
    }
  }
};
const SamplerDPMPP_2S_Ancestral = {
  display_name: "DPMPP_2S_Ancestral采样器",
  inputs: {
    eta: {
      name: "eta"
    },
    s_noise: {
      name: "s_noise"
    }
  }
};
const SamplerDPMPP_3M_SDE = {
  display_name: "DPMPP_3M_SDE采样器",
  inputs: {
    eta: {
      name: "eta"
    },
    noise_device: {
      name: "噪波设备"
    },
    s_noise: {
      name: "s_noise"
    }
  }
};
const SamplerDPMPP_SDE = {
  display_name: "DPMPP_SDE采样器",
  inputs: {
    eta: {
      name: "eta"
    },
    noise_device: {
      name: "噪波设备"
    },
    r: {
      name: "r"
    },
    s_noise: {
      name: "s_noise"
    }
  }
};
const SamplerEulerAncestral = {
  display_name: "EulerAncestral采样器",
  inputs: {
    eta: {
      name: "eta"
    },
    s_noise: {
      name: "s噪波"
    }
  }
};
const SamplerEulerAncestralCFGPP = {
  display_name: "EulerAncestralCFG++采样器",
  inputs: {
    eta: {
      name: "eta"
    },
    s_noise: {
      name: "s噪波"
    }
  }
};
const SamplerEulerCFGpp = {
  display_name: "EuleCFG++采样器",
  inputs: {
    version: {
      name: "版本"
    }
  }
};
const SamplerLCMUpscale = {
  display_name: "LCM缩放采样器",
  inputs: {
    scale_ratio: {
      name: "缩放比例"
    },
    scale_steps: {
      name: "缩放步数"
    },
    upscale_method: {
      name: "缩放方法"
    }
  }
};
const SamplerLMS = {
  display_name: "LMS采样器",
  inputs: {
    order: {
      name: "顺序"
    }
  }
};
const SaveAnimatedPNG = {
  display_name: "保存动画（APNG）",
  inputs: {
    compress_level: {
      name: "压缩级别"
    },
    filename_prefix: {
      name: "文件名前缀"
    },
    fps: {
      name: "帧率"
    },
    images: {
      name: "图片"
    }
  }
};
const SaveAnimatedWEBP = {
  display_name: "保存动画（WEBP）",
  inputs: {
    filename_prefix: {
      name: "文件名前缀"
    },
    fps: {
      name: "帧率"
    },
    images: {
      name: "图片"
    },
    lossless: {
      name: "无损"
    },
    method: {
      name: "方法"
    },
    quality: {
      name: "质量"
    }
  }
};
const SaveAudio = {
  display_name: "保存音频",
  inputs: {
    audio: {
      name: "音频"
    },
    audioUI: {
      name: "音频UI"
    },
    filename_prefix: {
      name: "文件名前缀"
    }
  }
};
const SaveGLB = {
  display_name: "SaveGLB",
  inputs: {
    filename_prefix: {
      name: "文件名前缀"
    },
    image: {
      name: "图像"
    },
    mesh: {
      name: "网格"
    }
  }
};
const SaveImage = {
  description: "将输入图像保存到您的ComfyUI输出目录。",
  display_name: "保存图像",
  inputs: {
    filename_prefix: {
      name: "文件名前缀",
      tooltip: "保存文件的文件名的前缀。可使用格式信息如 %date:yyyy-MM-dd% 或 %空Latent.width%，以包含来自工作流内的信息。"
    },
    images: {
      name: "图片",
      tooltip: "要保存的图像。"
    }
  }
};
const SaveImageWebsocket = {
  display_name: "保存图像（网络接口）",
  inputs: {
    images: {
      name: "图片"
    }
  }
};
const SaveLatent = {
  display_name: "保存Latent",
  inputs: {
    filename_prefix: {
      name: "文件名前缀"
    },
    samples: {
      name: "Latent"
    }
  }
};
const SaveSVG = {
  description: "将 SVG 文件保存到磁盘。",
  display_name: "保存 SVG",
  inputs: {
    filename_prefix: {
      name: "文件名前缀",
      tooltip: "要保存文件的前缀。可以包含格式化信息，如 %date:yyyy-MM-dd% 或 %Empty Latent Image.width%，以包含来自节点的数值。"
    },
    svg: {
      name: "svg"
    }
  }
};
const SaveVideo = {
  description: "将输入图像保存到您的 ComfyUI 输出目录。",
  display_name: "保存视频",
  inputs: {
    codec: {
      name: "编码器",
      tooltip: "用于视频的编码器。"
    },
    filename_prefix: {
      name: "文件名前缀",
      tooltip: "要保存文件的前缀。可以包含格式化信息，如 %date:yyyy-MM-dd% 或 %Empty Latent Image.width%，以包含来自节点的值。"
    },
    format: {
      name: "格式",
      tooltip: "保存视频的格式。"
    },
    video: {
      name: "视频",
      tooltip: "要保存的视频。"
    }
  }
};
const SaveWEBM = {
  display_name: "保存WEBM",
  inputs: {
    codec: {
      name: "编解码器"
    },
    crf: {
      name: "crf",
      tooltip: "更高的crf意味着更低的质量和更小的文件大小，更低的crf意味着更高的质量和更大的文件大小。"
    },
    filename_prefix: {
      name: "文件名前缀"
    },
    fps: {
      name: "帧率"
    },
    images: {
      name: "图像"
    }
  }
};
const SelfAttentionGuidance = {
  display_name: "SAG自注意力引导",
  inputs: {
    blur_sigma: {
      name: "模糊Sigma"
    },
    model: {
      name: "模型"
    },
    scale: {
      name: "缩放"
    }
  }
};
const SetClipHooks = {
  display_name: "设置CLIP约束",
  inputs: {
    apply_to_conds: {
      name: "应用于条件"
    },
    clip: {
      name: "clip"
    },
    hooks: {
      name: "约束"
    },
    schedule_clip: {
      name: "安排clip"
    }
  }
};
const SetFirstSigma = {
  display_name: "设置第一个Sigma",
  inputs: {
    sigma: {
      name: "sigma"
    },
    sigmas: {
      name: "sigmas"
    }
  }
};
const SetHookKeyframes = {
  display_name: "设置约束关键帧",
  inputs: {
    hook_kf: {
      name: "约束关键帧"
    },
    hooks: {
      name: "约束"
    }
  }
};
const SetLatentNoiseMask = {
  display_name: "设置Latent噪波遮罩",
  inputs: {
    mask: {
      name: "遮罩"
    },
    samples: {
      name: "Latent"
    }
  }
};
const SetUnionControlNetType = {
  display_name: "设置UnionControlNet类型",
  inputs: {
    control_net: {
      name: "ControlNet"
    },
    type: {
      name: "类型"
    }
  }
};
const SkipLayerGuidanceDiT = {
  description: "通用的跳过层引导节点，可用于每个DiT模型。",
  display_name: "跳过层引导（DiT）",
  inputs: {
    double_layers: {
      name: "双层"
    },
    end_percent: {
      name: "结束百分比"
    },
    model: {
      name: "模型"
    },
    rescaling_scale: {
      name: "重新缩放比例"
    },
    scale: {
      name: "缩放"
    },
    single_layers: {
      name: "单层"
    },
    start_percent: {
      name: "开始百分比"
    }
  }
};
const SkipLayerGuidanceSD3 = {
  description: "通用版本的跳过层引导节点，可用于每个DiT模型。",
  display_name: "跳过层引导（SD3）",
  inputs: {
    end_percent: {
      name: "结束百分比"
    },
    layers: {
      name: "层"
    },
    model: {
      name: "模型"
    },
    scale: {
      name: "缩放"
    },
    start_percent: {
      name: "开始百分比"
    }
  }
};
const SolidMask = {
  display_name: "纯块遮罩",
  inputs: {
    height: {
      name: "高度"
    },
    value: {
      name: "明度"
    },
    width: {
      name: "宽度"
    }
  }
};
const SplitImageWithAlpha = {
  display_name: "分离图像Alpha",
  inputs: {
    image: {
      name: "图片"
    }
  }
};
const SplitSigmas = {
  display_name: "分离Sigma",
  inputs: {
    sigmas: {
      name: "Sigmas"
    },
    step: {
      name: "步数"
    }
  },
  outputs: {
    "0": {
      name: "高方差"
    },
    "1": {
      name: "低方差"
    }
  }
};
const SplitSigmasDenoise = {
  display_name: "分离Sigma降噪",
  inputs: {
    denoise: {
      name: "降噪"
    },
    sigmas: {
      name: "Sigmas"
    }
  },
  outputs: {
    "0": {
      name: "高方差"
    },
    "1": {
      name: "低方差"
    }
  }
};
const StabilityStableImageSD_3_5Node = {
  description: "根据提示词和分辨率同步生成图像。",
  display_name: "Stability AI Stable Diffusion 3.5 图像",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio",
      tooltip: "生成图像的宽高比。"
    },
    cfg_scale: {
      name: "cfg_scale",
      tooltip: "扩散过程对提示词文本的遵循程度（数值越高，生成的图像越接近你的提示词）"
    },
    control_after_generate: {
      name: "control after generate"
    },
    image: {
      name: "image"
    },
    image_denoise: {
      name: "image_denoise",
      tooltip: "输入图像的去噪程度；0.0 表示与输入图像完全相同，1.0 表示完全不使用输入图像。"
    },
    model: {
      name: "model"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "你不希望在输出图像中出现的关键词。此为高级功能。"
    },
    prompt: {
      name: "prompt",
      tooltip: "你希望在输出图像中看到的内容。强有力且描述清晰的提示词，能够明确定义元素、颜色和主题，将带来更好的结果。"
    },
    seed: {
      name: "seed",
      tooltip: "用于生成噪声的随机种子。"
    },
    style_preset: {
      name: "style_preset",
      tooltip: "可选，生成图像的期望风格。"
    }
  }
};
const StabilityStableImageUltraNode = {
  description: "根据提示词和分辨率同步生成图像。",
  display_name: "Stability AI Stable Image Ultra",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio",
      tooltip: "生成图像的宽高比。"
    },
    control_after_generate: {
      name: "control after generate"
    },
    image: {
      name: "image"
    },
    image_denoise: {
      name: "image_denoise",
      tooltip: "输入图像的去噪强度；0.0 表示与输入图像完全相同，1.0 表示完全不参考输入图像。"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "描述你不希望在输出图像中出现内容的文本。这是一个高级功能。"
    },
    prompt: {
      name: "prompt",
      tooltip: "你希望在输出图像中看到的内容。一个强有力且描述清晰的提示词，能够明确界定元素、颜色和主题，将带来更好的结果。要控制某个词的权重，请使用格式 `(word:weight)`，其中 `word` 是你想要控制权重的词，`weight` 是介于 0 到 1 之间的数值。例如：`The sky was a crisp (blue:0.3) and (green:0.8)` 表示天空是蓝色和绿色，但绿色多于蓝色。"
    },
    seed: {
      name: "seed",
      tooltip: "用于生成噪声的随机种子。"
    },
    style_preset: {
      name: "style_preset",
      tooltip: "可选的生成图像风格。"
    }
  }
};
const StabilityUpscaleConservativeNode = {
  description: "以最小改动将图像放大至 4K 分辨率。",
  display_name: "Stability AI 保守放大",
  inputs: {
    control_after_generate: {
      name: "生成后控制"
    },
    creativity: {
      name: "创造性",
      tooltip: "控制生成与初始图像不强相关的额外细节的可能性。"
    },
    image: {
      name: "image"
    },
    negative_prompt: {
      name: "反向提示词",
      tooltip: "你不希望在输出图像中出现的关键词。此为高级功能。"
    },
    prompt: {
      name: "提示词",
      tooltip: "你希望在输出图像中看到什么。强有力且描述清晰的提示词，能更好地定义元素、颜色和主题，从而获得更佳效果。"
    },
    seed: {
      name: "种子",
      tooltip: "用于生成噪声的随机种子。"
    }
  }
};
const StabilityUpscaleCreativeNode = {
  description: "以最小改动将图像放大至4K分辨率。",
  display_name: "Stability AI 创意放大",
  inputs: {
    control_after_generate: {
      name: "生成后控制"
    },
    creativity: {
      name: "创造性",
      tooltip: "控制生成不受初始图像强烈约束的额外细节的可能性。"
    },
    image: {
      name: "图像"
    },
    negative_prompt: {
      name: "反向提示词",
      tooltip: "你不希望在输出图像中出现的关键词。此为高级功能。"
    },
    prompt: {
      name: "提示词",
      tooltip: "你希望在输出图像中看到什么。强有力且描述清晰的提示词，明确元素、颜色和主题，将获得更好的结果。"
    },
    seed: {
      name: "随机种子",
      tooltip: "用于生成噪声的随机种子。"
    },
    style_preset: {
      name: "风格预设",
      tooltip: "可选，生成图像的期望风格。"
    }
  }
};
const StabilityUpscaleFastNode = {
  description: "通过 Stability API 快速将图像放大至原始尺寸的 4 倍；适用于低质量或压缩图像的放大。",
  display_name: "Stability AI 极速放大",
  inputs: {
    image: {
      name: "图像"
    }
  }
};
const StableCascade_EmptyLatentImage = {
  display_name: "空Latent图像（Stable Cascade）",
  inputs: {
    batch_size: {
      name: "批量大小"
    },
    compression: {
      name: "压缩"
    },
    height: {
      name: "高度"
    },
    width: {
      name: "宽度"
    }
  },
  outputs: {
    "0": {
      name: "阶段C"
    },
    "1": {
      name: "阶段B"
    }
  }
};
const StableCascade_StageB_Conditioning = {
  display_name: "Stable Cascade_B阶段_条件",
  inputs: {
    conditioning: {
      name: "条件"
    },
    stage_c: {
      name: "阶段c"
    }
  }
};
const StableCascade_StageC_VAEEncode = {
  display_name: "Stable Cascade_C阶段_VAE编码",
  inputs: {
    compression: {
      name: "压缩"
    },
    image: {
      name: "图像"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "阶段C"
    },
    "1": {
      name: "阶段B"
    }
  }
};
const StableCascade_SuperResolutionControlnet = {
  display_name: "Stable Cascade_超分辨率ControlNet",
  inputs: {
    image: {
      name: "图像"
    },
    vae: {
      name: "vae"
    }
  },
  outputs: {
    "0": {
      name: "ControlNet"
    },
    "1": {
      name: "阶段C"
    },
    "2": {
      name: "阶段B"
    }
  }
};
const StableZero123_Conditioning = {
  display_name: "StableZero123条件",
  inputs: {
    azimuth: {
      name: "方位角"
    },
    batch_size: {
      name: "批量大小"
    },
    clip_vision: {
      name: "clip视觉"
    },
    elevation: {
      name: "俯仰角"
    },
    height: {
      name: "高度"
    },
    init_image: {
      name: "初始图像"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "宽度"
    }
  },
  outputs: {
    "0": {
      name: "正面条件"
    },
    "1": {
      name: "负面条件"
    },
    "2": {
      name: "Latent"
    }
  }
};
const StableZero123_Conditioning_Batched = {
  display_name: "StableZero123条件_批处理",
  inputs: {
    azimuth: {
      name: "方位角"
    },
    azimuth_batch_increment: {
      name: "方位角增量"
    },
    batch_size: {
      name: "批量大小"
    },
    clip_vision: {
      name: "clip视觉"
    },
    elevation: {
      name: "俯仰角"
    },
    elevation_batch_increment: {
      name: "俯仰角增量"
    },
    height: {
      name: "高度"
    },
    init_image: {
      name: "初始图像"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "宽度"
    }
  },
  outputs: {
    "0": {
      name: "正面条件"
    },
    "1": {
      name: "负面条件"
    },
    "2": {
      name: "Latent"
    }
  }
};
const StyleModelApply = {
  display_name: "应用风格模型",
  inputs: {
    clip_vision_output: {
      name: "clip视觉输出"
    },
    conditioning: {
      name: "条件"
    },
    strength: {
      name: "强度"
    },
    strength_type: {
      name: "强度类型"
    },
    style_model: {
      name: "风格模型"
    }
  }
};
const StyleModelLoader = {
  display_name: "加载风格模型",
  inputs: {
    style_model_name: {
      name: "风格模型名称"
    }
  }
};
const T5TokenizerOptions = {
  display_name: "T5TokenizerOptions",
  inputs: {
    clip: {
      name: "clip"
    },
    min_length: {
      name: "最小长度"
    },
    min_padding: {
      name: "最小填充"
    }
  }
};
const TextEncodeHunyuanVideo_ImageToVideo = {
  display_name: "文本编码Hunyuan视频_图像到视频",
  inputs: {
    clip: {
      name: "clip"
    },
    clip_vision_output: {
      name: "clip视觉输出"
    },
    image_interleave: {
      name: "图像交错",
      tooltip: "图像与文本提示的影响程度。数字越高，文本提示的影响越大。"
    },
    prompt: {
      name: "提示"
    }
  }
};
const ThresholdMask = {
  display_name: "遮罩阈值",
  inputs: {
    mask: {
      name: "遮罩"
    },
    value: {
      name: "值"
    }
  }
};
const TomePatchModel = {
  display_name: "Tome合并模型Token",
  inputs: {
    model: {
      name: "模型"
    },
    ratio: {
      name: "比率"
    }
  }
};
const TorchCompileModel = {
  display_name: "Torch编译模型",
  inputs: {
    backend: {
      name: "后端"
    },
    model: {
      name: "模型"
    }
  }
};
const TrimVideoLatent = {
  display_name: "TrimVideoLatent",
  inputs: {
    samples: {
      name: "samples"
    },
    trim_amount: {
      name: "trim_amount"
    }
  }
};
const TripleCLIPLoader = {
  description: "[配方]\n\nSD3：clip-l，clip-g，t5",
  display_name: "三重CLIP加载器",
  inputs: {
    clip_name1: {
      name: "CLIP名称1"
    },
    clip_name2: {
      name: "CLIP名称2"
    },
    clip_name3: {
      name: "CLIP名称3"
    }
  }
};
const UNETLoader = {
  display_name: "UNet加载器",
  inputs: {
    unet_name: {
      name: "UNet名称"
    },
    weight_dtype: {
      name: "数据类型"
    }
  }
};
const UNetCrossAttentionMultiply = {
  display_name: "UNet交叉注意力乘数",
  inputs: {
    k: {
      name: "k"
    },
    model: {
      name: "模型"
    },
    out: {
      name: "输出"
    },
    q: {
      name: "q"
    },
    v: {
      name: "v"
    }
  }
};
const UNetSelfAttentionMultiply = {
  display_name: "UNet自注意力乘数",
  inputs: {
    k: {
      name: "k"
    },
    model: {
      name: "模型"
    },
    out: {
      name: "输出"
    },
    q: {
      name: "q"
    },
    v: {
      name: "v"
    }
  }
};
const UNetTemporalAttentionMultiply = {
  display_name: "UNet时间注意力乘数",
  inputs: {
    cross_structural: {
      name: "交叉结构"
    },
    cross_temporal: {
      name: "交叉时间"
    },
    model: {
      name: "模型"
    },
    self_structural: {
      name: "自我结构"
    },
    self_temporal: {
      name: "自我时间"
    }
  }
};
const UpscaleModelLoader = {
  display_name: "加载放大模型",
  inputs: {
    model_name: {
      name: "模型名称"
    }
  }
};
const VAEDecode = {
  description: "将 Latent 图像解码为像素空间的图像。",
  display_name: "VAE解码",
  inputs: {
    samples: {
      name: "Latent",
      tooltip: "要解码的 Latent 图像。"
    },
    vae: {
      name: "vae",
      tooltip: "用于解码 Latent 图像的 VAE 模型。"
    }
  },
  outputs: {
    "0": {
      tooltip: "解码后的图像。"
    }
  }
};
const VAEDecodeAudio = {
  display_name: "VAE解码（音频）",
  inputs: {
    samples: {
      name: "Latent"
    },
    vae: {
      name: "vae"
    }
  }
};
const VAEDecodeHunyuan3D = {
  display_name: "VAEDecodeHunyuan3D",
  inputs: {
    num_chunks: {
      name: "块数"
    },
    octree_resolution: {
      name: "八叉树分辨率"
    },
    samples: {
      name: "样本"
    },
    vae: {
      name: "vae"
    }
  }
};
const VAEDecodeTiled = {
  display_name: "VAE解码（分块）",
  inputs: {
    overlap: {
      name: "重叠"
    },
    samples: {
      name: "Latent"
    },
    temporal_overlap: {
      name: "时间重叠",
      tooltip: "仅用于视频VAE：重叠的帧数。"
    },
    temporal_size: {
      name: "时间尺寸",
      tooltip: "仅用于视频VAE：一次解码的帧数。"
    },
    tile_size: {
      name: "分块尺寸"
    },
    vae: {
      name: "vae"
    }
  }
};
const VAEEncode = {
  display_name: "VAE编码",
  inputs: {
    pixels: {
      name: "像素"
    },
    vae: {
      name: "vae"
    }
  }
};
const VAEEncodeAudio = {
  display_name: "VAE编码（音频）",
  inputs: {
    audio: {
      name: "音频"
    },
    vae: {
      name: "vae"
    }
  }
};
const VAEEncodeForInpaint = {
  display_name: "VAE编码（局部重绘）",
  inputs: {
    grow_mask_by: {
      name: "扩展遮罩"
    },
    mask: {
      name: "遮罩"
    },
    pixels: {
      name: "像素"
    },
    vae: {
      name: "vae"
    }
  }
};
const VAEEncodeTiled = {
  display_name: "VAE编码分块）",
  inputs: {
    overlap: {
      name: "重叠"
    },
    pixels: {
      name: "像素"
    },
    temporal_overlap: {
      name: "时间重叠",
      tooltip: "仅用于视频VAE：重叠的帧数。"
    },
    temporal_size: {
      name: "时间尺寸",
      tooltip: "仅用于视频VAE：一次编码的帧数。"
    },
    tile_size: {
      name: "分块尺寸"
    },
    vae: {
      name: "vae"
    }
  }
};
const VAELoader = {
  display_name: "加载VAE",
  inputs: {
    vae_name: {
      name: "vae名称"
    }
  }
};
const VAESave = {
  display_name: "保存VAE",
  inputs: {
    filename_prefix: {
      name: "文件名前缀"
    },
    vae: {
      name: "vae"
    }
  }
};
const VPScheduler = {
  display_name: "VPS调度器",
  inputs: {
    beta_d: {
      name: "beta_d"
    },
    beta_min: {
      name: "beta_min"
    },
    eps_s: {
      name: "eps_s"
    },
    steps: {
      name: "步数"
    }
  }
};
const VeoVideoGenerationNode = {
  description: "使用 Google 的 Veo API 根据文本提示生成视频",
  display_name: "Google Veo2 视频生成",
  inputs: {
    aspect_ratio: {
      name: "aspect_ratio",
      tooltip: "输出视频的宽高比"
    },
    control_after_generate: {
      name: "control after generate"
    },
    duration_seconds: {
      name: "duration_seconds",
      tooltip: "输出视频的时长（秒）"
    },
    enhance_prompt: {
      name: "enhance_prompt",
      tooltip: "是否使用 AI 辅助增强提示词"
    },
    image: {
      name: "image",
      tooltip: "可选的参考图像，用于引导视频生成"
    },
    negative_prompt: {
      name: "negative_prompt",
      tooltip: "用于指导视频中应避免内容的负面文本提示"
    },
    person_generation: {
      name: "person_generation",
      tooltip: "是否允许在视频中生成人物"
    },
    prompt: {
      name: "prompt",
      tooltip: "视频的文本描述"
    },
    seed: {
      name: "seed",
      tooltip: "视频生成的种子（0 表示随机）"
    }
  }
};
const VideoLinearCFGGuidance = {
  display_name: "视频线性CFG引导",
  inputs: {
    min_cfg: {
      name: "最小配置"
    },
    model: {
      name: "模型"
    }
  }
};
const VideoTriangleCFGGuidance = {
  display_name: "视频三角形CFG引导",
  inputs: {
    min_cfg: {
      name: "最小配置"
    },
    model: {
      name: "模型"
    }
  }
};
const VoxelToMesh = {
  display_name: "VoxelToMesh",
  inputs: {
    algorithm: {
      name: "算法"
    },
    threshold: {
      name: "阈值"
    },
    voxel: {
      name: "voxel"
    }
  }
};
const VoxelToMeshBasic = {
  display_name: "VoxelToMeshBasic",
  inputs: {
    threshold: {
      name: "阈值"
    },
    voxel: {
      name: "体素"
    }
  }
};
const WanFirstLastFrameToVideo = {
  display_name: "WanFirstLastFrameToVideo",
  inputs: {
    batch_size: {
      name: "批量大小"
    },
    clip_vision_end_image: {
      name: "clip 视觉结束图像"
    },
    clip_vision_start_image: {
      name: "clip 视觉起始图像"
    },
    end_image: {
      name: "结束图像"
    },
    height: {
      name: "高度"
    },
    length: {
      name: "长度"
    },
    negative: {
      name: "负向"
    },
    positive: {
      name: "正向"
    },
    start_image: {
      name: "起始图像"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "宽度"
    }
  },
  outputs: {
    "0": {
      name: "正向"
    },
    "1": {
      name: "负向"
    },
    "2": {
      name: "latent"
    }
  }
};
const WanFunControlToVideo = {
  display_name: "WanFunControlToVideo",
  inputs: {
    batch_size: {
      name: "批量大小"
    },
    clip_vision_output: {
      name: "clip_vision_output"
    },
    control_video: {
      name: "控制视频"
    },
    height: {
      name: "高度"
    },
    length: {
      name: "长度"
    },
    negative: {
      name: "负向"
    },
    positive: {
      name: "正向"
    },
    start_image: {
      name: "起始图像"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "宽度"
    }
  },
  outputs: {
    "0": {
      name: "正向"
    },
    "1": {
      name: "负向"
    },
    "2": {
      name: "latent"
    }
  }
};
const WanFunInpaintToVideo = {
  display_name: "WanFunInpaintToVideo",
  inputs: {
    batch_size: {
      name: "批量大小"
    },
    clip_vision_output: {
      name: "clip_vision_output"
    },
    end_image: {
      name: "结束图像"
    },
    height: {
      name: "高度"
    },
    length: {
      name: "长度"
    },
    negative: {
      name: "负向"
    },
    positive: {
      name: "正向"
    },
    start_image: {
      name: "起始图像"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "宽度"
    }
  },
  outputs: {
    "0": {
      name: "正向"
    },
    "1": {
      name: "负向"
    },
    "2": {
      name: "latent"
    }
  }
};
const WanImageToVideo = {
  display_name: "Wan图像到视频",
  inputs: {
    batch_size: {
      name: "批量大小"
    },
    clip_vision_output: {
      name: "clip视觉输出"
    },
    height: {
      name: "高度"
    },
    length: {
      name: "长度"
    },
    negative: {
      name: "负面"
    },
    positive: {
      name: "正面"
    },
    start_image: {
      name: "开始图像"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "宽度"
    }
  },
  outputs: {
    "0": {
      name: "正面"
    },
    "1": {
      name: "负面"
    },
    "2": {
      name: "潜在"
    }
  }
};
const WanVaceToVideo = {
  display_name: "WanVaceToVideo",
  inputs: {
    batch_size: {
      name: "批量大小"
    },
    control_masks: {
      name: "控制mask"
    },
    control_video: {
      name: "控制视频"
    },
    height: {
      name: "高度"
    },
    length: {
      name: "长度"
    },
    negative: {
      name: "负向"
    },
    positive: {
      name: "正向"
    },
    reference_image: {
      name: "参考图像"
    },
    strength: {
      name: "强度"
    },
    vae: {
      name: "vae"
    },
    width: {
      name: "宽度"
    }
  },
  outputs: {
    "0": {
      name: "正向"
    },
    "1": {
      name: "负向"
    },
    "2": {
      name: "latent"
    },
    "3": {
      name: "裁剪latent"
    }
  }
};
const WebcamCapture = {
  display_name: "网络摄像头捕获",
  inputs: {
    capture_on_queue: {
      name: "执行时捕获"
    },
    height: {
      name: "高度"
    },
    image: {
      name: "图像"
    },
    "waiting for camera___": {},
    width: {
      name: "宽度"
    }
  }
};
const unCLIPCheckpointLoader = {
  display_name: "unCLIPCheckpoint加载器",
  inputs: {
    ckpt_name: {
      name: "Checkpoint名称"
    }
  }
};
const unCLIPConditioning = {
  display_name: "unCLIP条件",
  inputs: {
    clip_vision_output: {
      name: "CLIP视觉输出"
    },
    conditioning: {
      name: "条件"
    },
    noise_augmentation: {
      name: "噪波增强"
    },
    strength: {
      name: "强度"
    }
  }
};
const zhNodes = {
  AddNoise,
  AlignYourStepsScheduler,
  BasicGuider,
  BasicScheduler,
  BetaSamplingScheduler,
  CFGGuider,
  CFGZeroStar,
  CLIPAttentionMultiply,
  CLIPLoader,
  CLIPMergeAdd,
  CLIPMergeSimple,
  CLIPMergeSubtract,
  CLIPSave,
  CLIPSetLastLayer,
  CLIPTextEncode,
  CLIPTextEncodeControlnet,
  CLIPTextEncodeFlux,
  CLIPTextEncodeHiDream,
  CLIPTextEncodeHunyuanDiT,
  CLIPTextEncodeLumina2,
  CLIPTextEncodePixArtAlpha,
  CLIPTextEncodeSD3,
  CLIPTextEncodeSDXL,
  CLIPTextEncodeSDXLRefiner,
  CLIPVisionEncode,
  CLIPVisionLoader,
  Canny,
  CheckpointLoader,
  CheckpointLoaderSimple,
  CheckpointSave,
  CombineHooks2,
  CombineHooks4,
  CombineHooks8,
  ConditioningAverage,
  ConditioningCombine,
  ConditioningConcat,
  ConditioningSetArea,
  ConditioningSetAreaPercentage,
  ConditioningSetAreaPercentageVideo,
  ConditioningSetAreaStrength,
  ConditioningSetDefaultCombine,
  ConditioningSetMask,
  ConditioningSetProperties,
  ConditioningSetPropertiesAndCombine,
  ConditioningSetTimestepRange,
  ConditioningStableAudio,
  ConditioningTimestepsRange,
  ConditioningZeroOut,
  ControlNetApply,
  ControlNetApplyAdvanced,
  ControlNetApplySD3,
  ControlNetInpaintingAliMamaApply,
  ControlNetLoader,
  CosmosImageToVideoLatent,
  CreateHookKeyframe,
  CreateHookKeyframesFromFloats,
  CreateHookKeyframesInterpolated,
  CreateHookLora,
  CreateHookLoraModelOnly,
  CreateHookModelAsLora,
  CreateHookModelAsLoraModelOnly,
  CreateVideo,
  CropMask,
  DiffControlNetLoader,
  DifferentialDiffusion,
  DiffusersLoader,
  DisableNoise,
  DualCFGGuider,
  DualCLIPLoader,
  EmptyCosmosLatentVideo,
  EmptyHunyuanLatentVideo,
  EmptyImage,
  EmptyLTXVLatentVideo,
  EmptyLatentAudio,
  EmptyLatentHunyuan3Dv2,
  EmptyLatentImage,
  EmptyMochiLatentVideo,
  EmptySD3LatentImage,
  ExponentialScheduler,
  ExtendIntermediateSigmas,
  FeatherMask,
  FlipSigmas,
  FluxDisableGuidance,
  FluxGuidance,
  FluxProCannyNode,
  FluxProDepthNode,
  FluxProExpandNode,
  FluxProFillNode,
  FluxProUltraImageNode,
  FreSca,
  FreeU,
  FreeU_V2,
  GITSScheduler,
  GLIGENLoader,
  GLIGENTextBoxApply,
  GetVideoComponents,
  GrowMask,
  Hunyuan3Dv2Conditioning,
  Hunyuan3Dv2ConditioningMultiView,
  HunyuanImageToVideo,
  HyperTile,
  HypernetworkLoader,
  IdeogramV1,
  IdeogramV2,
  IdeogramV3,
  ImageBatch,
  ImageBlend,
  ImageBlur,
  ImageColorToMask,
  ImageCompositeMasked,
  ImageCrop,
  ImageFromBatch,
  ImageInvert,
  ImageOnlyCheckpointLoader,
  ImageOnlyCheckpointSave,
  ImagePadForOutpaint,
  ImageQuantize,
  ImageRGBToYUV,
  ImageScale,
  ImageScaleBy,
  ImageScaleToTotalPixels,
  ImageSharpen,
  ImageToMask,
  ImageUpscaleWithModel,
  ImageYUVToRGB,
  InpaintModelConditioning,
  InstructPixToPixConditioning,
  InvertMask,
  JoinImageWithAlpha,
  KSampler,
  KSamplerAdvanced,
  KSamplerSelect,
  KarrasScheduler,
  KlingCameraControlI2VNode,
  KlingCameraControlT2VNode,
  KlingCameraControls,
  KlingDualCharacterVideoEffectNode,
  KlingImage2VideoNode,
  KlingImageGenerationNode,
  KlingLipSyncAudioToVideoNode,
  KlingLipSyncTextToVideoNode,
  KlingSingleImageVideoEffectNode,
  KlingStartEndFrameNode,
  KlingTextToVideoNode,
  KlingVideoExtendNode,
  KlingVirtualTryOnNode,
  LTXVAddGuide,
  LTXVConditioning,
  LTXVCropGuides,
  LTXVImgToVideo,
  LTXVPreprocess,
  LTXVScheduler,
  LaplaceScheduler,
  LatentAdd,
  LatentApplyOperation,
  LatentApplyOperationCFG,
  LatentBatch,
  LatentBatchSeedBehavior,
  LatentBlend,
  LatentComposite,
  LatentCompositeMasked,
  LatentCrop,
  LatentFlip,
  LatentFromBatch,
  LatentInterpolate,
  LatentMultiply,
  LatentOperationSharpen,
  LatentOperationTonemapReinhard,
  LatentRotate,
  LatentSubtract,
  LatentUpscale,
  LatentUpscaleBy,
  Load3D,
  Load3DAnimation,
  LoadAudio,
  LoadImage,
  LoadImageMask,
  LoadImageOutput,
  LoadLatent,
  LoadVideo,
  LoraLoader,
  LoraLoaderModelOnly,
  LoraSave,
  LotusConditioning,
  LumaConceptsNode,
  LumaImageModifyNode,
  LumaImageNode,
  LumaImageToVideoNode,
  LumaReferenceNode,
  LumaVideoNode,
  Mahiro,
  MaskComposite,
  MaskPreview,
  MaskToImage,
  MinimaxImageToVideoNode,
  MinimaxTextToVideoNode,
  ModelComputeDtype,
  ModelMergeAdd,
  ModelMergeAuraflow,
  ModelMergeBlocks,
  ModelMergeCosmos14B,
  ModelMergeCosmos7B,
  ModelMergeFlux1,
  ModelMergeLTXV,
  ModelMergeMochiPreview,
  ModelMergeSD1,
  ModelMergeSD2,
  ModelMergeSD35_Large,
  ModelMergeSD3_2B,
  ModelMergeSDXL,
  ModelMergeSimple,
  ModelMergeSubtract,
  ModelMergeWAN2_1,
  ModelSamplingAuraFlow,
  ModelSamplingContinuousEDM,
  ModelSamplingContinuousV,
  ModelSamplingDiscrete,
  ModelSamplingFlux,
  ModelSamplingLTXV,
  ModelSamplingSD3,
  ModelSamplingStableCascade,
  ModelSave,
  Morphology,
  OpenAIDalle2,
  OpenAIDalle3,
  OpenAIGPTImage1,
  OptimalStepsScheduler,
  PairConditioningCombine,
  PairConditioningSetDefaultCombine,
  PairConditioningSetProperties,
  PairConditioningSetPropertiesAndCombine,
  PatchModelAddDownscale,
  PerpNeg,
  PerpNegGuider,
  PerturbedAttentionGuidance,
  PhotoMakerEncode,
  PhotoMakerLoader,
  PikaImageToVideoNode2_2,
  PikaScenesV2_2,
  PikaStartEndFrameNode2_2,
  PikaTextToVideoNode2_2,
  Pikadditions,
  Pikaffects,
  Pikaswaps,
  PixverseImageToVideoNode,
  PixverseTemplateNode,
  PixverseTextToVideoNode,
  PixverseTransitionVideoNode,
  PolyexponentialScheduler,
  PorterDuffImageComposite,
  Preview3D,
  Preview3DAnimation,
  PreviewAny,
  PreviewAudio,
  PreviewImage,
  PrimitiveBoolean,
  PrimitiveFloat,
  PrimitiveInt,
  PrimitiveString,
  PrimitiveStringMultiline,
  QuadrupleCLIPLoader,
  RandomNoise,
  RebatchImages,
  RebatchLatents,
  RecraftColorRGB,
  RecraftControls,
  RecraftCreativeUpscaleNode,
  RecraftCrispUpscaleNode,
  RecraftImageInpaintingNode,
  RecraftImageToImageNode,
  RecraftRemoveBackgroundNode,
  RecraftReplaceBackgroundNode,
  RecraftStyleV3DigitalIllustration,
  RecraftStyleV3InfiniteStyleLibrary,
  RecraftStyleV3LogoRaster,
  RecraftStyleV3RealisticImage,
  RecraftTextToImageNode,
  RecraftTextToVectorNode,
  RecraftVectorizeImageNode,
  RenormCFG,
  RepeatImageBatch,
  RepeatLatentBatch,
  RescaleCFG,
  SDTurboScheduler,
  SD_4XUpscale_Conditioning,
  SV3D_Conditioning,
  SVD_img2vid_Conditioning,
  SamplerCustom,
  SamplerCustomAdvanced,
  SamplerDPMAdaptative,
  SamplerDPMPP_2M_SDE,
  SamplerDPMPP_2S_Ancestral,
  SamplerDPMPP_3M_SDE,
  SamplerDPMPP_SDE,
  SamplerEulerAncestral,
  SamplerEulerAncestralCFGPP,
  SamplerEulerCFGpp,
  SamplerLCMUpscale,
  SamplerLMS,
  SaveAnimatedPNG,
  SaveAnimatedWEBP,
  SaveAudio,
  SaveGLB,
  SaveImage,
  SaveImageWebsocket,
  SaveLatent,
  SaveSVG,
  SaveVideo,
  SaveWEBM,
  SelfAttentionGuidance,
  SetClipHooks,
  SetFirstSigma,
  SetHookKeyframes,
  SetLatentNoiseMask,
  SetUnionControlNetType,
  SkipLayerGuidanceDiT,
  SkipLayerGuidanceSD3,
  SolidMask,
  SplitImageWithAlpha,
  SplitSigmas,
  SplitSigmasDenoise,
  StabilityStableImageSD_3_5Node,
  StabilityStableImageUltraNode,
  StabilityUpscaleConservativeNode,
  StabilityUpscaleCreativeNode,
  StabilityUpscaleFastNode,
  StableCascade_EmptyLatentImage,
  StableCascade_StageB_Conditioning,
  StableCascade_StageC_VAEEncode,
  StableCascade_SuperResolutionControlnet,
  StableZero123_Conditioning,
  StableZero123_Conditioning_Batched,
  StyleModelApply,
  StyleModelLoader,
  T5TokenizerOptions,
  TextEncodeHunyuanVideo_ImageToVideo,
  ThresholdMask,
  TomePatchModel,
  TorchCompileModel,
  TrimVideoLatent,
  TripleCLIPLoader,
  UNETLoader,
  UNetCrossAttentionMultiply,
  UNetSelfAttentionMultiply,
  UNetTemporalAttentionMultiply,
  UpscaleModelLoader,
  VAEDecode,
  VAEDecodeAudio,
  VAEDecodeHunyuan3D,
  VAEDecodeTiled,
  VAEEncode,
  VAEEncodeAudio,
  VAEEncodeForInpaint,
  VAEEncodeTiled,
  VAELoader,
  VAESave,
  VPScheduler,
  VeoVideoGenerationNode,
  VideoLinearCFGGuidance,
  VideoTriangleCFGGuidance,
  VoxelToMesh,
  VoxelToMeshBasic,
  WanFirstLastFrameToVideo,
  WanFunControlToVideo,
  WanFunInpaintToVideo,
  WanImageToVideo,
  WanVaceToVideo,
  WebcamCapture,
  unCLIPCheckpointLoader,
  unCLIPConditioning
};
const Comfy_Canvas_SelectionToolbox = {
  name: "显示选择工具箱"
};
const Comfy_ConfirmClear = {
  name: "清除工作流时需要确认"
};
const Comfy_DOMClippingEnabled = {
  name: "启用DOM元素裁剪（启用可能会降低性能）"
};
const Comfy_DevMode = {
  name: "启用开发模式选项（API保存等）"
};
const Comfy_DisableFloatRounding = {
  name: "禁用默认浮点组件四舍五入。",
  tooltip: "(需要重新加载页面) 当节点自身设置了四舍五入时，无法禁用该功能。"
};
const Comfy_DisableSliders = {
  name: "禁用节点组件滑块"
};
const Comfy_EditAttention_Delta = {
  name: "Ctrl+上/下 精度"
};
const Comfy_EnableTooltips = {
  name: "启用工具提示"
};
const Comfy_EnableWorkflowViewRestore = {
  name: "在工作流中保存和恢复视图位置及缩放"
};
const Comfy_FloatRoundingPrecision = {
  name: "浮点组件四舍五入的小数位数 [0 = 自动]。",
  tooltip: "(需要重新加载页面)"
};
const Comfy_Graph_CanvasInfo = {
  name: "在左下角显示画布信息（fps等）"
};
const Comfy_Graph_CanvasMenu = {
  name: "显示图形画布菜单"
};
const Comfy_Graph_CtrlShiftZoom = {
  name: "启用快速缩放快捷键（Ctrl + Shift + 拖动）"
};
const Comfy_Graph_LinkMarkers = {
  name: "连线中点标记",
  options: {
    Arrow: "箭头",
    Circle: "圆",
    None: "无"
  }
};
const Comfy_Graph_ZoomSpeed = {
  name: "画布缩放速度"
};
const Comfy_GroupSelectedNodes_Padding = {
  name: "选定节点的组内边距"
};
const Comfy_Group_DoubleClickTitleToEdit = {
  name: "双击组标题以编辑"
};
const Comfy_LinkRelease_Action = {
  name: "释放连线时的操作",
  options: {
    "context menu": "上下文菜单",
    "no action": "无操作",
    "search box": "搜索框"
  }
};
const Comfy_LinkRelease_ActionShift = {
  name: "释放连线时的操作（Shift）",
  options: {
    "context menu": "上下文菜单",
    "no action": "无操作",
    "search box": "搜索框"
  }
};
const Comfy_LinkRenderMode = {
  name: "连线渲染样式",
  options: {
    Hidden: "隐藏",
    Linear: "直线",
    Spline: "曲线",
    Straight: "直角线"
  }
};
const Comfy_Load3D_BackgroundColor = {
  name: "初始背景颜色",
  tooltip: "控制3D场景的默认背景颜色。此设置决定新建3D组件时的背景外观，但每个组件在创建后都可以单独调整。"
};
const Comfy_Load3D_CameraType = {
  name: "摄像机类型",
  options: {
    orthographic: "正交",
    perspective: "透视"
  },
  tooltip: "控制创建新的3D小部件时，默认的相机是透视还是正交。这个默认设置仍然可以在创建后为每个小部件单独切换。"
};
const Comfy_Load3D_LightAdjustmentIncrement = {
  name: "光照调整步长",
  tooltip: "控制在3D场景中调整光照强度时的步长。较小的步长值可以实现更精细的光照调整，较大的值则会使每次调整的变化更加明显。"
};
const Comfy_Load3D_LightIntensity = {
  name: "初始光照强度",
  tooltip: "设置3D场景中灯光的默认亮度级别。该数值决定新建3D控件时灯光照亮物体的强度，但每个控件在创建后都可以单独调整。"
};
const Comfy_Load3D_LightIntensityMaximum = {
  name: "最大光照强度",
  tooltip: "设置3D场景允许的最大光照强度值。此项定义了在调整任何3D控件照明时可设定的最高亮度上限。"
};
const Comfy_Load3D_LightIntensityMinimum = {
  name: "光照强度下限",
  tooltip: "设置3D场景允许的最小光照强度值。此项定义在调整任何3D控件照明时可设定的最低亮度。"
};
const Comfy_Load3D_ShowGrid = {
  name: "显示网格",
  tooltip: "默认显示网格开关"
};
const Comfy_Load3D_ShowPreview = {
  name: "显示预览",
  tooltip: "默认显示预览开关"
};
const Comfy_Locale = {
  name: "语言"
};
const Comfy_MaskEditor_BrushAdjustmentSpeed = {
  name: "画笔调整速度倍增器",
  tooltip: "控制调整时画笔大小和硬度变化的速度。更高的值意味着更快的变化。"
};
const Comfy_MaskEditor_UseDominantAxis = {
  name: "将画笔调整锁定到主轴",
  tooltip: "启用后，画笔调整将仅根据您移动的方向影响大小或硬度。"
};
const Comfy_MaskEditor_UseNewEditor = {
  name: "使用新画笔编辑器",
  tooltip: "切换到新的画笔编辑器界面"
};
const Comfy_ModelLibrary_AutoLoadAll = {
  name: "自动加载所有模型文件夹",
  tooltip: "开启后，打开模型库会加载所有文件夹内的模型（可能导致卡顿）。关闭后，仅加载当前文件夹内的模型。"
};
const Comfy_ModelLibrary_NameFormat = {
  name: "在模型库树视图中显示的名称",
  options: {
    filename: "文件名",
    title: "标题"
  },
  tooltip: "选择“文件名”以在模型列表中显示原始文件名的简化视图（不带目录和“.safetensors”后缀名）。选择“标题”以显示可配置的模型元数据标题。"
};
const Comfy_NodeBadge_NodeIdBadgeMode = {
  name: "节点ID标签",
  options: {
    None: "无",
    "Show all": "显示全部"
  }
};
const Comfy_NodeBadge_NodeLifeCycleBadgeMode = {
  name: "节点制作周期标签",
  options: {
    None: "无",
    "Show all": "显示全部"
  }
};
const Comfy_NodeBadge_NodeSourceBadgeMode = {
  name: "节点源标签",
  options: {
    "Hide built-in": "仅第三方",
    None: "无",
    "Show all": "显示全部"
  }
};
const Comfy_NodeSearchBoxImpl = {
  name: "节点搜索框",
  options: {
    "default": "默认",
    "litegraph (legacy)": "litegraph（旧版）"
  }
};
const Comfy_NodeSearchBoxImpl_NodePreview = {
  name: "显示节点预览",
  tooltip: "仅适用于默认框架"
};
const Comfy_NodeSearchBoxImpl_ShowCategory = {
  name: "显示节点类别",
  tooltip: "仅适用于默认框架"
};
const Comfy_NodeSearchBoxImpl_ShowIdName = {
  name: "显示节点ID名称",
  tooltip: "仅适用于默认框架"
};
const Comfy_NodeSearchBoxImpl_ShowNodeFrequency = {
  name: "显示节点频率",
  tooltip: "仅适用于默认框架"
};
const Comfy_NodeSuggestions_number = {
  name: "节点建议数量",
  tooltip: "仅适用于 litegraph"
};
const Comfy_Node_AllowImageSizeDraw = {
  name: "在图像预览下方显示宽度×高度"
};
const Comfy_Node_AutoSnapLinkToSlot = {
  name: "连线自动吸附到节点接口",
  tooltip: "在节点上拖动连线时，连线会自动吸附到节点的可用输入接口。"
};
const Comfy_Node_BypassAllLinksOnDelete = {
  name: "删除节点时保留连线",
  tooltip: "删除节点时，尝试重新连接其所有输入和输出连线（类似于忽略节点）。"
};
const Comfy_Node_DoubleClickTitleToEdit = {
  name: "双击节点标题以编辑"
};
const Comfy_Node_MiddleClickRerouteNode = {
  name: "中键单击创建新的转接点"
};
const Comfy_Node_Opacity = {
  name: "节点不透明度"
};
const Comfy_Node_ShowDeprecated = {
  name: "在搜索中显示已弃用的节点",
  tooltip: "弃用节点在UI中默认隐藏，但在工作流中仍然有效。"
};
const Comfy_Node_ShowExperimental = {
  name: "在搜索中显示实验性节点",
  tooltip: "实验节点在UI中标记为实验性，可能在未来版本中发生重大变化或被移除。在生产工作流中谨慎使用。"
};
const Comfy_Node_SnapHighlightsNode = {
  name: "吸附高亮节点",
  tooltip: "在拖动连线经过具有可用输入接口的节点时，高亮显示该节点。"
};
const Comfy_Pointer_ClickBufferTime = {
  name: "指针点击漂移延迟",
  tooltip: "按下指针按钮后，忽略指针移动的最大时间（毫秒）。\n\n有助于防止在点击时意外移动鼠标。"
};
const Comfy_Pointer_ClickDrift = {
  name: "指针点击漂移（距离）",
  tooltip: "如果指针在按住按钮时移动超过此距离，则视为拖动（而不是点击）。\n\n有助于防止在点击时意外移动鼠标"
};
const Comfy_Pointer_DoubleClickTime = {
  name: "双击间隔（最大）",
  tooltip: "双击的两次点击之间的最大时间（毫秒）。增加此值有助于解决双击有时未被识别的问题。"
};
const Comfy_PreviewFormat = {
  name: "预览图像格式",
  tooltip: "在图像组件中显示预览时，将其转换为轻量级图像，例如webp、jpeg、webp;50等。"
};
const Comfy_PromptFilename = {
  name: "保存工作流时提示文件名"
};
const Comfy_QueueButton_BatchCountLimit = {
  name: "批处理计数限制",
  tooltip: "单次添加到队列的最大任务数量"
};
const Comfy_Queue_MaxHistoryItems = {
  name: "队列历史大小",
  tooltip: "队列历史中显示的最大任务数量。"
};
const Comfy_Sidebar_Location = {
  name: "侧边栏位置",
  options: {
    left: "左侧",
    right: "右侧"
  }
};
const Comfy_Sidebar_Size = {
  name: "侧边栏大小",
  options: {
    normal: "正常",
    small: "小"
  }
};
const Comfy_Sidebar_UnifiedWidth = {
  name: "统一侧边栏宽度"
};
const Comfy_SnapToGrid_GridSize = {
  name: "吸附网格大小",
  tooltip: "在按住shift拖动和调整节点大小时，节点将对齐到网格，该选项控制网格。"
};
const Comfy_TextareaWidget_FontSize = {
  name: "文本框组件字体大小"
};
const Comfy_TextareaWidget_Spellcheck = {
  name: "文本框组件拼写检查"
};
const Comfy_TreeExplorer_ItemPadding = {
  name: "树形浏览器项目内边距"
};
const Comfy_UseNewMenu = {
  name: "使用新菜单",
  options: {
    Bottom: "底部",
    Disabled: "禁用",
    Top: "顶部"
  }
};
const Comfy_Validation_NodeDefs = {
  name: "校验节点定义（慢）",
  tooltip: "推荐给节点开发者。开启后会在 ComfyUI 启动时校验全部节点定义。"
};
const Comfy_Validation_Workflows = {
  name: "校验工作流"
};
const Comfy_WidgetControlMode = {
  name: "组件控制模式",
  options: {
    after: "之后",
    before: "之前"
  },
  tooltip: "控制组件值的更新时机（随机/增加/减少），可以在执行工作流之前或之后。"
};
const Comfy_Window_UnloadConfirmation = {
  name: "关闭窗口时显示确认"
};
const Comfy_Workflow_AutoSave = {
  name: "自动保存",
  options: {
    "after delay": "延迟后",
    off: "关闭"
  }
};
const Comfy_Workflow_AutoSaveDelay = {
  name: "自动保存延迟（毫秒）",
  tooltip: "仅在自动保存设置为“延迟后”时适用。"
};
const Comfy_Workflow_ConfirmDelete = {
  name: "删除工作流时显示确认"
};
const Comfy_Workflow_Persist = {
  name: "持久化工作流状态并在页面（重新）加载时恢复"
};
const Comfy_Workflow_ShowMissingModelsWarning = {
  name: "显示缺失模型警告"
};
const Comfy_Workflow_ShowMissingNodesWarning = {
  name: "显示缺失节点警告"
};
const Comfy_Workflow_SortNodeIdOnSave = {
  name: "保存节点ID到工作流"
};
const Comfy_Workflow_WorkflowTabsPosition = {
  name: "已打开工作流的位置",
  options: {
    Sidebar: "侧边栏",
    Topbar: "顶部栏",
    "Topbar (2nd-row)": "顶部栏 (第二行)"
  }
};
const LiteGraph_Canvas_LowQualityRenderingZoomThreshold = {
  name: "低质量渲染缩放阈值",
  tooltip: "在缩小时渲染低质量形状"
};
const LiteGraph_Canvas_MaximumFps = {
  name: "最大FPS",
  tooltip: "画布允许渲染的最大帧数。限制GPU使用以换取流畅度。如果为0，则使用屏幕刷新率。默认值：0"
};
const LiteGraph_ContextMenu_Scaling = {
  name: "放大时缩放节点组合部件菜单（列表）"
};
const LiteGraph_Node_DefaultPadding = {
  name: "始终收缩新节点",
  tooltip: "创建节点时将其缩小到最小可能尺寸。禁用后，新添加的节点会略微加宽以显示控件数值。"
};
const LiteGraph_Node_TooltipDelay = {
  name: "工具提示延迟"
};
const LiteGraph_Pointer_TrackpadGestures = {
  name: "启用触控板手势",
  tooltip: "此设置为画布启用触控板模式，允许使用双指捏合缩放和拖动。"
};
const LiteGraph_Reroute_SplineOffset = {
  name: "重新路由样条偏移",
  tooltip: "贝塞尔控制点从重新路由中心点的偏移"
};
const pysssss_SnapToGrid = {
  name: "始终吸附到网格"
};
const zhSettings = {
  "Comfy-Desktop_AutoUpdate": {
    name: "自动检查更新"
  },
  "Comfy-Desktop_SendStatistics": {
    name: "发送匿名使用情况统计"
  },
  "Comfy-Desktop_UV_PypiInstallMirror": {
    name: "Pypi 安装镜像",
    tooltip: "默认 pip 安装镜像"
  },
  "Comfy-Desktop_UV_PythonInstallMirror": {
    name: "Python安装镜像",
    tooltip: "管理的Python安装包从Astral python-build-standalone项目下载。此变量可以设置为镜像URL，以使用不同的Python安装源。提供的URL将替换https://github.com/astral-sh/python-build-standalone/releases/download，例如，在https://github.com/astral-sh/python-build-standalone/releases/download/20240713/cpython-3.12.4%2B20240713-aarch64-apple-darwin-install_only.tar.gz中。可以通过使用file:// URL方案从本地目录读取分发包。"
  },
  "Comfy-Desktop_UV_TorchInstallMirror": {
    name: "Torch安装镜像",
    tooltip: "用于pytorch的Pip安装镜像"
  },
  "Comfy-Desktop_WindowStyle": {
    name: "窗口样式",
    options: {
      custom: "自定义",
      "default": "默认"
    },
    tooltip: "选择自定义选项以隐藏系统标题栏"
  },
  Comfy_Canvas_SelectionToolbox,
  Comfy_ConfirmClear,
  Comfy_DOMClippingEnabled,
  Comfy_DevMode,
  Comfy_DisableFloatRounding,
  Comfy_DisableSliders,
  Comfy_EditAttention_Delta,
  Comfy_EnableTooltips,
  Comfy_EnableWorkflowViewRestore,
  Comfy_FloatRoundingPrecision,
  Comfy_Graph_CanvasInfo,
  Comfy_Graph_CanvasMenu,
  Comfy_Graph_CtrlShiftZoom,
  Comfy_Graph_LinkMarkers,
  Comfy_Graph_ZoomSpeed,
  Comfy_GroupSelectedNodes_Padding,
  Comfy_Group_DoubleClickTitleToEdit,
  Comfy_LinkRelease_Action,
  Comfy_LinkRelease_ActionShift,
  Comfy_LinkRenderMode,
  Comfy_Load3D_BackgroundColor,
  Comfy_Load3D_CameraType,
  Comfy_Load3D_LightAdjustmentIncrement,
  Comfy_Load3D_LightIntensity,
  Comfy_Load3D_LightIntensityMaximum,
  Comfy_Load3D_LightIntensityMinimum,
  Comfy_Load3D_ShowGrid,
  Comfy_Load3D_ShowPreview,
  Comfy_Locale,
  Comfy_MaskEditor_BrushAdjustmentSpeed,
  Comfy_MaskEditor_UseDominantAxis,
  Comfy_MaskEditor_UseNewEditor,
  Comfy_ModelLibrary_AutoLoadAll,
  Comfy_ModelLibrary_NameFormat,
  Comfy_NodeBadge_NodeIdBadgeMode,
  Comfy_NodeBadge_NodeLifeCycleBadgeMode,
  Comfy_NodeBadge_NodeSourceBadgeMode,
  Comfy_NodeSearchBoxImpl,
  Comfy_NodeSearchBoxImpl_NodePreview,
  Comfy_NodeSearchBoxImpl_ShowCategory,
  Comfy_NodeSearchBoxImpl_ShowIdName,
  Comfy_NodeSearchBoxImpl_ShowNodeFrequency,
  Comfy_NodeSuggestions_number,
  Comfy_Node_AllowImageSizeDraw,
  Comfy_Node_AutoSnapLinkToSlot,
  Comfy_Node_BypassAllLinksOnDelete,
  Comfy_Node_DoubleClickTitleToEdit,
  Comfy_Node_MiddleClickRerouteNode,
  Comfy_Node_Opacity,
  Comfy_Node_ShowDeprecated,
  Comfy_Node_ShowExperimental,
  Comfy_Node_SnapHighlightsNode,
  Comfy_Pointer_ClickBufferTime,
  Comfy_Pointer_ClickDrift,
  Comfy_Pointer_DoubleClickTime,
  Comfy_PreviewFormat,
  Comfy_PromptFilename,
  Comfy_QueueButton_BatchCountLimit,
  Comfy_Queue_MaxHistoryItems,
  Comfy_Sidebar_Location,
  Comfy_Sidebar_Size,
  Comfy_Sidebar_UnifiedWidth,
  Comfy_SnapToGrid_GridSize,
  Comfy_TextareaWidget_FontSize,
  Comfy_TextareaWidget_Spellcheck,
  Comfy_TreeExplorer_ItemPadding,
  Comfy_UseNewMenu,
  Comfy_Validation_NodeDefs,
  Comfy_Validation_Workflows,
  Comfy_WidgetControlMode,
  Comfy_Window_UnloadConfirmation,
  Comfy_Workflow_AutoSave,
  Comfy_Workflow_AutoSaveDelay,
  Comfy_Workflow_ConfirmDelete,
  Comfy_Workflow_Persist,
  Comfy_Workflow_ShowMissingModelsWarning,
  Comfy_Workflow_ShowMissingNodesWarning,
  Comfy_Workflow_SortNodeIdOnSave,
  Comfy_Workflow_WorkflowTabsPosition,
  LiteGraph_Canvas_LowQualityRenderingZoomThreshold,
  LiteGraph_Canvas_MaximumFps,
  LiteGraph_ContextMenu_Scaling,
  LiteGraph_Node_DefaultPadding,
  LiteGraph_Node_TooltipDelay,
  LiteGraph_Pointer_TrackpadGestures,
  LiteGraph_Reroute_SplineOffset,
  pysssss_SnapToGrid
};
function buildLocale(main, nodes, commands2, settings) {
  return {
    ...main,
    nodeDefs: nodes,
    commands: commands2,
    settings
  };
}
__name(buildLocale, "buildLocale");
const messages = {
  en: buildLocale(en, enNodes, enCommands, enSettings),
  zh: buildLocale(zh, zhNodes, zhCommands, zhSettings),
  ru: buildLocale(ru, ruNodes, ruCommands, ruSettings),
  ja: buildLocale(ja, jaNodes, jaCommands, jaSettings),
  ko: buildLocale(ko, koNodes, koCommands, koSettings),
  fr: buildLocale(fr, frNodes, frCommands, frSettings),
  es: buildLocale(es, esNodes, esCommands, esSettings)
};
const i18n = createI18n({
  // Must set `false`, as Vue I18n Legacy API is for Vue 2
  legacy: false,
  locale: navigator.language.split("-")[0] || "en",
  fallbackLocale: "en",
  messages,
  // Ignore warnings for locale options as each option is in its own language.
  // e.g. "English", "中文", "Русский", "日本語", "한국어", "Français", "Español"
  missingWarn: /^(?!settings\.Comfy_Locale\.options\.).+/,
  fallbackWarn: /^(?!settings\.Comfy_Locale\.options\.).+/
});
const { t, te } = i18n.global;
function st(key, fallbackMessage) {
  return te(key) ? t(key) : fallbackMessage;
}
__name(st, "st");
const useToastStore = /* @__PURE__ */ defineStore("toast", () => {
  const messagesToAdd = ref$3([]);
  const messagesToRemove = ref$3([]);
  const removeAllRequested = ref$3(false);
  function add3(message) {
    messagesToAdd.value = [...messagesToAdd.value, message];
  }
  __name(add3, "add");
  function remove2(message) {
    messagesToRemove.value = [...messagesToRemove.value, message];
  }
  __name(remove2, "remove");
  function removeAll() {
    removeAllRequested.value = true;
  }
  __name(removeAll, "removeAll");
  function addAlert(message) {
    add3({ severity: "warn", summary: "Alert", detail: message });
  }
  __name(addAlert, "addAlert");
  return {
    messagesToAdd,
    messagesToRemove,
    removeAllRequested,
    add: add3,
    remove: remove2,
    removeAll,
    addAlert
  };
});
function useErrorHandling() {
  const toast = useToastStore();
  const toastErrorHandler = /* @__PURE__ */ __name((error2) => {
    toast.add({
      severity: "error",
      summary: t("g.error"),
      detail: error2 instanceof Error ? error2.message : t("g.unknownError")
    });
  }, "toastErrorHandler");
  const wrapWithErrorHandling = /* @__PURE__ */ __name((action, errorHandler2, finallyHandler) => (...args) => {
    try {
      return action(...args);
    } catch (e2) {
      ;
      (errorHandler2 ?? toastErrorHandler)(e2);
    } finally {
      finallyHandler?.();
    }
  }, "wrapWithErrorHandling");
  const wrapWithErrorHandlingAsync = /* @__PURE__ */ __name((action, errorHandler2, finallyHandler) => async (...args) => {
    try {
      return await action(...args);
    } catch (e2) {
      ;
      (errorHandler2 ?? toastErrorHandler)(e2);
    } finally {
      finallyHandler?.();
    }
  }, "wrapWithErrorHandlingAsync");
  return {
    wrapWithErrorHandling,
    wrapWithErrorHandlingAsync,
    toastErrorHandler
  };
}
__name(useErrorHandling, "useErrorHandling");
const nodeSlotSchema = z.object({
  CLIP: z.string(),
  CLIP_VISION: z.string(),
  CLIP_VISION_OUTPUT: z.string(),
  CONDITIONING: z.string(),
  CONTROL_NET: z.string(),
  IMAGE: z.string(),
  LATENT: z.string(),
  MASK: z.string(),
  MODEL: z.string(),
  STYLE_MODEL: z.string(),
  VAE: z.string(),
  NOISE: z.string(),
  GUIDER: z.string(),
  SAMPLER: z.string(),
  SIGMAS: z.string(),
  TAESD: z.string()
});
const litegraphBaseSchema = z.object({
  BACKGROUND_IMAGE: z.string(),
  CLEAR_BACKGROUND_COLOR: z.string(),
  NODE_TITLE_COLOR: z.string(),
  NODE_SELECTED_TITLE_COLOR: z.string(),
  NODE_TEXT_SIZE: z.number(),
  NODE_TEXT_COLOR: z.string(),
  NODE_TEXT_HIGHLIGHT_COLOR: z.string(),
  NODE_SUBTEXT_SIZE: z.number(),
  NODE_DEFAULT_COLOR: z.string(),
  NODE_DEFAULT_BGCOLOR: z.string(),
  NODE_DEFAULT_BOXCOLOR: z.string(),
  NODE_DEFAULT_SHAPE: z.union([
    z.literal(LiteGraph.BOX_SHAPE),
    z.literal(LiteGraph.ROUND_SHAPE),
    z.literal(LiteGraph.CARD_SHAPE),
    // Legacy palettes have string field for NODE_DEFAULT_SHAPE.
    z.string()
  ]),
  NODE_BOX_OUTLINE_COLOR: z.string(),
  NODE_BYPASS_BGCOLOR: z.string(),
  NODE_ERROR_COLOUR: z.string(),
  DEFAULT_SHADOW_COLOR: z.string(),
  DEFAULT_GROUP_FONT: z.number(),
  WIDGET_BGCOLOR: z.string(),
  WIDGET_OUTLINE_COLOR: z.string(),
  WIDGET_TEXT_COLOR: z.string(),
  WIDGET_SECONDARY_TEXT_COLOR: z.string(),
  WIDGET_DISABLED_TEXT_COLOR: z.string(),
  LINK_COLOR: z.string(),
  EVENT_LINK_COLOR: z.string(),
  CONNECTING_LINK_COLOR: z.string(),
  BADGE_FG_COLOR: z.string(),
  BADGE_BG_COLOR: z.string()
});
const comfyBaseSchema = z.object({
  ["fg-color"]: z.string(),
  ["bg-color"]: z.string(),
  ["bg-img"]: z.string().optional(),
  ["comfy-menu-bg"]: z.string(),
  ["comfy-menu-secondary-bg"]: z.string(),
  ["comfy-input-bg"]: z.string(),
  ["input-text"]: z.string(),
  ["descrip-text"]: z.string(),
  ["drag-text"]: z.string(),
  ["error-text"]: z.string(),
  ["border-color"]: z.string(),
  ["tr-even-bg-color"]: z.string(),
  ["tr-odd-bg-color"]: z.string(),
  ["content-bg"]: z.string(),
  ["content-fg"]: z.string(),
  ["content-hover-bg"]: z.string(),
  ["content-hover-fg"]: z.string(),
  ["bar-shadow"]: z.string()
});
const colorsSchema = z.object({
  node_slot: nodeSlotSchema,
  litegraph_base: litegraphBaseSchema,
  comfy_base: comfyBaseSchema
});
const partialColorsSchema = z.object({
  node_slot: nodeSlotSchema.partial(),
  litegraph_base: litegraphBaseSchema.partial(),
  comfy_base: comfyBaseSchema.partial()
});
const paletteSchema = z.object({
  id: z.string(),
  name: z.string(),
  colors: partialColorsSchema,
  light_theme: z.boolean().optional()
}).passthrough();
const completedPaletteSchema = z.object({
  id: z.string(),
  name: z.string(),
  colors: colorsSchema
}).passthrough();
const colorPalettesSchema = z.record(paletteSchema);
const useCanvasPositionConversion = /* @__PURE__ */ __name((canvasElement, lgCanvas) => {
  const { left, top } = useElementBounding(canvasElement);
  const clientPosToCanvasPos = /* @__PURE__ */ __name((pos) => {
    const { offset, scale } = lgCanvas.ds;
    return [
      (pos[0] - left.value) / scale - offset[0],
      (pos[1] - top.value) / scale - offset[1]
    ];
  }, "clientPosToCanvasPos");
  const canvasPosToClientPos = /* @__PURE__ */ __name((pos) => {
    const { offset, scale } = lgCanvas.ds;
    return [
      (pos[0] + offset[0]) * scale + left.value,
      (pos[1] + offset[1]) * scale + top.value
    ];
  }, "canvasPosToClientPos");
  return {
    clientPosToCanvasPos,
    canvasPosToClientPos
  };
}, "useCanvasPositionConversion");
const zNodeId = z.union([z.number().int(), z.string()]);
const zNodeInputName = z.string();
const zSlotIndex = z.union([
  z.number().int(),
  z.string().transform((val) => parseInt(val)).refine((val) => !isNaN(val), {
    message: "Invalid number"
  })
]);
const zDataType = z.union([z.string(), z.array(z.string()), z.number()]);
const zVector2 = z.union([
  z.object({ 0: z.number(), 1: z.number() }).passthrough().transform((v2) => [v2[0], v2[1]]),
  z.tuple([z.number(), z.number()])
]);
const zModelFile = z.object({
  name: z.string(),
  url: z.string().url(),
  hash: z.string().optional(),
  hash_type: z.string().optional(),
  directory: z.string()
});
const zGraphState = z.object({
  lastGroupid: z.number().optional(),
  lastNodeId: z.number().optional(),
  lastLinkId: z.number().optional(),
  lastRerouteId: z.number().optional()
}).passthrough();
const zComfyLink = z.tuple([
  z.number(),
  // Link id
  zNodeId,
  // Node id of source node
  zSlotIndex,
  // Output slot# of source node
  zNodeId,
  // Node id of destination node
  zSlotIndex,
  // Input slot# of destination node
  zDataType
  // Data type
]);
const zComfyLinkExtension = z.object({
  id: z.number(),
  parentId: z.number()
}).passthrough();
const zComfyLinkObject = z.object({
  id: z.number(),
  origin_id: zNodeId,
  origin_slot: zSlotIndex,
  target_id: zNodeId,
  target_slot: zSlotIndex,
  type: zDataType,
  parentId: z.number().optional()
}).passthrough();
const zReroute = z.object({
  id: z.number(),
  parentId: z.number().optional(),
  pos: zVector2,
  linkIds: z.array(z.number()).nullish(),
  floating: z.object({
    slotType: z.enum(["input", "output"])
  }).optional()
}).passthrough();
const zNodeOutput = z.object({
  name: z.string(),
  type: zDataType,
  links: z.array(z.number()).nullable().optional(),
  slot_index: zSlotIndex.optional()
}).passthrough();
const zNodeInput = z.object({
  name: zNodeInputName,
  type: zDataType,
  link: z.number().nullable().optional(),
  slot_index: zSlotIndex.optional()
}).passthrough();
const zFlags = z.object({
  collapsed: z.boolean().optional(),
  pinned: z.boolean().optional(),
  allow_interaction: z.boolean().optional(),
  horizontal: z.boolean().optional(),
  skip_repeated_outputs: z.boolean().optional()
}).passthrough();
const repoLikeIdPattern = /^[a-zA-Z0-9](?:[a-zA-Z0-9._-]*[a-zA-Z0-9])?$/;
const githubUsernamePattern = /^(?!-)(?!.*--)[a-zA-Z0-9-]+(?<!-)$/;
const gitHashPattern = /^[0-9a-f]{4,40}$/i;
const semverPattern = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([\da-z-]+(?:\.[\da-z-]+)*))?(?:\+([\da-z-]+(?:\.[\da-z-]+)*))?$/;
const zRepoLikeId = z.string().min(1).max(100).regex(repoLikeIdPattern, {
  message: "ID can only contain ASCII letters, digits, '_', '-', and '.'"
}).refine((id2) => !/^[_\-.]|[_\-.]$/.test(id2), {
  message: "ID must not start or end with '_', '-', or '.'"
});
const zCnrId = zRepoLikeId;
const zGithubRepoName = zRepoLikeId;
const zGithubUsername = z.string().min(1).max(39).regex(githubUsernamePattern, "Invalid GitHub username/org");
const zAuxId = z.string().regex(/^[^/]+\/[^/]+$/, "Invalid format. Must be 'github-user/repo-name'").transform((id2) => id2.split("/")).refine(
  ([username, repo]) => zGithubUsername.safeParse(username).success && zGithubRepoName.safeParse(repo).success,
  "Invalid aux_id: Must be valid 'github-username/github-repo-name'"
).transform(([username, repo]) => `${username}/${repo}`);
const zGitHash = z.string().superRefine((val, ctx) => {
  if (!gitHashPattern.test(val)) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      message: `Node pack version has invalid Git commit hash: "${val}"`
    });
  }
});
const zSemVer = z.string().superRefine((val, ctx) => {
  if (!semverPattern.test(val)) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      message: `Node pack version has invalid semantic version: "${val}"`
    });
  }
});
const zVersion = z.union([
  z.string().transform((ver) => ver.replace(/^v/, "")).pipe(z.union([zSemVer, zGitHash])),
  z.literal("unknown")
]);
const zProperties = z.object({
  ["Node name for S&R"]: z.string().optional(),
  cnr_id: zCnrId.optional(),
  aux_id: zAuxId.optional(),
  ver: zVersion.optional(),
  models: z.array(zModelFile).optional()
}).passthrough();
const zWidgetValues = z.union([z.array(z.any()), z.record(z.any())]);
const zComfyNode = z.object({
  id: zNodeId,
  type: z.string(),
  pos: zVector2,
  size: zVector2,
  flags: zFlags,
  order: z.number(),
  mode: z.number(),
  inputs: z.array(zNodeInput).optional(),
  outputs: z.array(zNodeOutput).optional(),
  properties: zProperties,
  widgets_values: zWidgetValues.optional(),
  color: z.string().optional(),
  bgcolor: z.string().optional()
}).passthrough();
const zGroup = z.object({
  id: z.number().optional(),
  title: z.string(),
  bounding: z.tuple([z.number(), z.number(), z.number(), z.number()]),
  color: z.string().optional(),
  font_size: z.number().optional(),
  locked: z.boolean().optional()
}).passthrough();
const zDS = z.object({
  scale: z.number(),
  offset: zVector2
}).passthrough();
const zConfig = z.object({
  links_ontop: z.boolean().optional(),
  align_to_grid: z.boolean().optional()
}).passthrough();
const zExtra = z.object({
  ds: zDS.optional(),
  frontendVersion: z.string().optional(),
  linkExtensions: z.array(zComfyLinkExtension).optional(),
  reroutes: z.array(zReroute).optional()
}).passthrough();
const zComfyWorkflow = z.object({
  id: z.string().uuid().optional(),
  revision: z.number().optional(),
  last_node_id: zNodeId,
  last_link_id: z.number(),
  nodes: z.array(zComfyNode),
  links: z.array(zComfyLink),
  floatingLinks: z.array(zComfyLinkObject).optional(),
  groups: z.array(zGroup).optional(),
  config: zConfig.optional().nullable(),
  extra: zExtra.optional().nullable(),
  version: z.number(),
  models: z.array(zModelFile).optional()
}).passthrough();
const zComfyWorkflow1 = z.object({
  id: z.string().uuid().optional(),
  revision: z.number().optional(),
  version: z.literal(1),
  config: zConfig.optional().nullable(),
  state: zGraphState,
  groups: z.array(zGroup).optional(),
  nodes: z.array(zComfyNode),
  links: z.array(zComfyLinkObject).optional(),
  floatingLinks: z.array(zComfyLinkObject).optional(),
  reroutes: z.array(zReroute).optional(),
  extra: zExtra.optional().nullable(),
  models: z.array(zModelFile).optional()
}).passthrough();
const zWorkflowVersion = z.object({
  version: z.number()
});
async function validateComfyWorkflow(data, onError = console.warn) {
  const versionResult = zWorkflowVersion.safeParse(data);
  let result;
  if (!versionResult.success) {
    const error22 = fromZodError(versionResult.error);
    onError(`Workflow does not contain a valid version.  Zod error:
${error22}`);
    return null;
  } else if (versionResult.data.version === 1) {
    result = await zComfyWorkflow1.safeParseAsync(data);
  } else {
    result = await zComfyWorkflow.safeParseAsync(data);
  }
  if (result.success) return result.data;
  const error2 = fromZodError(result.error);
  onError(`Invalid workflow against zod schema:
${error2}`);
  return null;
}
__name(validateComfyWorkflow, "validateComfyWorkflow");
const zNodeInputValue = z.union([
  // For widget values (can be any type)
  z.any(),
  // For node links [nodeId, slotIndex]
  z.tuple([zNodeId, zSlotIndex])
]);
const zNodeData = z.object({
  inputs: z.record(zNodeInputName, zNodeInputValue),
  class_type: z.string(),
  _meta: z.object({
    title: z.string()
  })
});
const zComfyApiWorkflow = z.record(zNodeId, zNodeData);
var IoDirection = /* @__PURE__ */ ((IoDirection2) => {
  IoDirection2[IoDirection2["INPUT"] = 0] = "INPUT";
  IoDirection2[IoDirection2["OUTPUT"] = 1] = "OUTPUT";
  return IoDirection2;
})(IoDirection || {});
function getNodeById(graph, id2) {
  if (graph.getNodeById) {
    return graph.getNodeById(id2);
  }
  graph = graph;
  return graph.nodes.find((node2) => node2.id == id2);
}
__name(getNodeById, "getNodeById");
function extendLink(link2) {
  return {
    link: link2,
    id: link2[0],
    origin_id: link2[1],
    origin_slot: link2[2],
    target_id: link2[3],
    target_slot: link2[4],
    type: link2[5]
  };
}
__name(extendLink, "extendLink");
function fixBadLinks(graph, options2 = {}) {
  const { fix = false, silent = false, logger: _logger = console } = options2;
  const logger2 = {
    log: /* @__PURE__ */ __name((...args) => {
      if (!silent) {
        _logger.log(...args);
      }
    }, "log")
  };
  const patchedNodeSlots = {};
  const data = {
    patchedNodes: [],
    deletedLinks: []
  };
  function patchNodeSlot(node2, ioDir, slot, linkId, op) {
    patchedNodeSlots[node2.id] = patchedNodeSlots[node2.id] || {};
    const patchedNode = patchedNodeSlots[node2.id];
    if (ioDir == 0) {
      patchedNode["inputs"] = patchedNode["inputs"] || {};
      if (patchedNode["inputs"][slot] !== void 0) {
        logger2.log(
          ` > Already set ${node2.id}.inputs[${slot}] to ${patchedNode["inputs"][slot]} Skipping.`
        );
        return false;
      }
      const linkIdToSet = op === "REMOVE" ? null : linkId;
      patchedNode["inputs"][slot] = linkIdToSet;
      if (fix) {
      }
    } else {
      patchedNode["outputs"] = patchedNode["outputs"] || {};
      patchedNode["outputs"][slot] = patchedNode["outputs"][slot] || {
        links: [...node2.outputs?.[slot]?.links || []],
        changes: {}
      };
      if (patchedNode["outputs"][slot]["changes"][linkId] !== void 0) {
        logger2.log(
          ` > Already set ${node2.id}.outputs[${slot}] to ${patchedNode["inputs"][slot]}! Skipping.`
        );
        return false;
      }
      patchedNode["outputs"][slot]["changes"][linkId] = op;
      if (op === "ADD") {
        const linkIdIndex = patchedNode["outputs"][slot]["links"].indexOf(linkId);
        if (linkIdIndex !== -1) {
          logger2.log(
            ` > Hmmm.. asked to add ${linkId} but it is already in list...`
          );
          return false;
        }
        patchedNode["outputs"][slot]["links"].push(linkId);
        if (fix) {
          node2.outputs = node2.outputs || [];
          node2.outputs[slot] = node2.outputs[slot] || {};
          node2.outputs[slot].links = node2.outputs[slot].links || [];
          node2.outputs[slot].links.push(linkId);
        }
      } else {
        const linkIdIndex = patchedNode["outputs"][slot]["links"].indexOf(linkId);
        if (linkIdIndex === -1) {
          logger2.log(
            ` > Hmmm.. asked to remove ${linkId} but it doesn't exist...`
          );
          return false;
        }
        patchedNode["outputs"][slot]["links"].splice(linkIdIndex, 1);
        if (fix) {
          node2.outputs?.[slot].links.splice(linkIdIndex, 1);
        }
      }
    }
    data.patchedNodes.push(node2);
    return true;
  }
  __name(patchNodeSlot, "patchNodeSlot");
  function nodeHasLinkId(node2, ioDir, slot, linkId) {
    let has2 = false;
    if (ioDir === 0) {
      const nodeHasIt = node2.inputs?.[slot]?.link === linkId;
      if (patchedNodeSlots[node2.id]?.["inputs"]) {
        const patchedHasIt = patchedNodeSlots[node2.id]["inputs"][slot] === linkId;
        if (fix && nodeHasIt !== patchedHasIt) {
          throw Error("Error. Expected node to match patched data.");
        }
        has2 = patchedHasIt;
      } else {
        has2 = !!nodeHasIt;
      }
    } else {
      const nodeHasIt = node2.outputs?.[slot]?.links?.includes(linkId);
      if (patchedNodeSlots[node2.id]?.["outputs"]?.[slot]?.["changes"][linkId]) {
        const patchedHasIt = patchedNodeSlots[node2.id]["outputs"][slot]?.links.includes(linkId);
        if (fix && nodeHasIt !== patchedHasIt) {
          throw Error("Error. Expected node to match patched data.");
        }
        has2 = !!patchedHasIt;
      } else {
        has2 = !!nodeHasIt;
      }
    }
    return has2;
  }
  __name(nodeHasLinkId, "nodeHasLinkId");
  function nodeHasAnyLink(node2, ioDir, slot) {
    let hasAny = false;
    if (ioDir === 0) {
      const nodeHasAny = node2.inputs?.[slot]?.link != null;
      if (patchedNodeSlots[node2.id]?.["inputs"]) {
        const patchedHasAny = patchedNodeSlots[node2.id]["inputs"][slot] != null;
        if (fix && nodeHasAny !== patchedHasAny) {
          throw Error("Error. Expected node to match patched data.");
        }
        hasAny = patchedHasAny;
      } else {
        hasAny = !!nodeHasAny;
      }
    } else {
      const nodeHasAny = node2.outputs?.[slot]?.links?.length;
      if (patchedNodeSlots[node2.id]?.["outputs"]?.[slot]?.["changes"]) {
        const patchedHasAny = patchedNodeSlots[node2.id]["outputs"][slot]?.links.length;
        if (fix && nodeHasAny !== patchedHasAny) {
          throw Error("Error. Expected node to match patched data.");
        }
        hasAny = !!patchedHasAny;
      } else {
        hasAny = !!nodeHasAny;
      }
    }
    return hasAny;
  }
  __name(nodeHasAnyLink, "nodeHasAnyLink");
  let links = [];
  if (!Array.isArray(graph.links)) {
    links = Object.values(graph.links).reduce((acc, v2) => {
      acc[v2.id] = v2;
      return acc;
    }, links);
  } else {
    links = graph.links;
  }
  const linksReverse = [...links];
  linksReverse.reverse();
  for (const l2 of linksReverse) {
    if (!l2) continue;
    const link2 = l2.origin_slot != null ? l2 : extendLink(l2);
    const originNode = getNodeById(graph, link2.origin_id);
    const originHasLink = /* @__PURE__ */ __name(() => nodeHasLinkId(originNode, 1, link2.origin_slot, link2.id), "originHasLink");
    const patchOrigin = /* @__PURE__ */ __name((op, id2 = link2.id) => patchNodeSlot(originNode, 1, link2.origin_slot, id2, op), "patchOrigin");
    const targetNode = getNodeById(graph, link2.target_id);
    const targetHasLink = /* @__PURE__ */ __name(() => nodeHasLinkId(targetNode, 0, link2.target_slot, link2.id), "targetHasLink");
    const targetHasAnyLink = /* @__PURE__ */ __name(() => nodeHasAnyLink(targetNode, 0, link2.target_slot), "targetHasAnyLink");
    const patchTarget = /* @__PURE__ */ __name((op, id2 = link2.id) => patchNodeSlot(targetNode, 0, link2.target_slot, id2, op), "patchTarget");
    const originLog = `origin(${link2.origin_id}).outputs[${link2.origin_slot}].links`;
    const targetLog = `target(${link2.target_id}).inputs[${link2.target_slot}].link`;
    if (!originNode || !targetNode) {
      if (!originNode && !targetNode) {
        logger2.log(
          `Link ${link2.id} is invalid, both origin ${link2.origin_id} and target ${link2.target_id} do not exist`
        );
      } else if (!originNode) {
        logger2.log(
          `Link ${link2.id} is funky... origin ${link2.origin_id} does not exist, but target ${link2.target_id} does.`
        );
        if (targetHasLink()) {
          logger2.log(
            ` > [PATCH] ${targetLog} does have link, will remove the inputs' link first.`
          );
          patchTarget("REMOVE", -1);
        }
      } else if (!targetNode) {
        logger2.log(
          `Link ${link2.id} is funky... target ${link2.target_id} does not exist, but origin ${link2.origin_id} does.`
        );
        if (originHasLink()) {
          logger2.log(
            ` > [PATCH] Origin's links' has ${link2.id}; will remove the link first.`
          );
          patchOrigin("REMOVE");
        }
      }
      continue;
    }
    if (targetHasLink() || originHasLink()) {
      if (!originHasLink()) {
        logger2.log(
          `${link2.id} is funky... ${originLog} does NOT contain it, but ${targetLog} does.`
        );
        logger2.log(
          ` > [PATCH] Attempt a fix by adding this ${link2.id} to ${originLog}.`
        );
        patchOrigin("ADD");
      } else if (!targetHasLink()) {
        logger2.log(
          `${link2.id} is funky... ${targetLog} is NOT correct (is ${targetNode.inputs?.[link2.target_slot]?.link}), but ${originLog} contains it`
        );
        if (!targetHasAnyLink()) {
          logger2.log(
            ` > [PATCH] ${targetLog} is not defined, will set to ${link2.id}.`
          );
          let patched = patchTarget("ADD");
          if (!patched) {
            logger2.log(
              ` > [PATCH] Nvm, ${targetLog} already patched. Removing ${link2.id} from ${originLog}.`
            );
            patched = patchOrigin("REMOVE");
          }
        } else {
          logger2.log(
            ` > [PATCH] ${targetLog} is defined, removing ${link2.id} from ${originLog}.`
          );
          patchOrigin("REMOVE");
        }
      }
    }
  }
  for (const l2 of linksReverse) {
    if (!l2) continue;
    const link2 = l2.origin_slot != null ? l2 : extendLink(l2);
    const originNode = getNodeById(graph, link2.origin_id);
    const targetNode = getNodeById(graph, link2.target_id);
    if ((!originNode || !nodeHasLinkId(
      originNode,
      1,
      link2.origin_slot,
      link2.id
    )) && (!targetNode || !nodeHasLinkId(
      targetNode,
      0,
      link2.target_slot,
      link2.id
    ))) {
      logger2.log(
        `${link2.id} is def invalid; BOTH origin node ${link2.origin_id} ${!originNode ? "is removed" : `doesn't have ${link2.id}`} and ${link2.origin_id} target node ${!targetNode ? "is removed" : `doesn't have ${link2.id}`}.`
      );
      data.deletedLinks.push(link2.id);
      continue;
    }
  }
  if (fix) {
    for (let i2 = data.deletedLinks.length - 1; i2 >= 0; i2--) {
      logger2.log(`Deleting link #${data.deletedLinks[i2]}.`);
      if (graph.getNodeById) {
        delete graph.links[data.deletedLinks[i2]];
      } else {
        graph = graph;
        const idx = graph.links.findIndex(
          (l2) => l2 && (l2[0] === data.deletedLinks[i2] || l2.id === data.deletedLinks[i2])
        );
        if (idx === -1) {
          logger2.log(`INDEX NOT FOUND for #${data.deletedLinks[i2]}`);
        }
        logger2.log(`splicing ${idx} from links`);
        graph.links.splice(idx, 1);
      }
    }
    if (!graph.getNodeById) {
      graph.links = graph.links.filter((l2) => !!l2);
    }
  }
  if (!data.patchedNodes.length && !data.deletedLinks.length) {
    return {
      hasBadLinks: false,
      fixed: false,
      graph,
      patched: data.patchedNodes.length,
      deleted: data.deletedLinks.length
    };
  }
  logger2.log(
    `${fix ? "Made" : "Would make"} ${data.patchedNodes.length || "no"} node link patches, and ${data.deletedLinks.length || "no"} stale link removals.`
  );
  let hasBadLinks = !!(data.patchedNodes.length || data.deletedLinks.length);
  if (fix && !silent) {
    const rerun = fixBadLinks(graph, { fix: false, silent: true });
    hasBadLinks = rerun.hasBadLinks;
  }
  return {
    hasBadLinks,
    fixed: !!hasBadLinks && fix,
    graph,
    patched: data.patchedNodes.length,
    deleted: data.deletedLinks.length
  };
}
__name(fixBadLinks, "fixBadLinks");
function useWorkflowValidation() {
  const toastStore = useToastStore();
  function tryFixLinks(graphData, options2 = {}) {
    const { silent = false } = options2;
    const logs = [];
    const linkValidation = fixBadLinks(
      graphData,
      {
        fix: true,
        silent,
        logger: {
          log: /* @__PURE__ */ __name((message) => {
            logs.push(message);
          }, "log")
        }
      }
    );
    if (!silent && logs.length > 0) {
      toastStore.add({
        severity: "warn",
        summary: "Workflow Validation",
        detail: logs.join("\n")
      });
    }
    if (linkValidation.fixed) {
      if (!silent) {
        toastStore.add({
          severity: "success",
          summary: "Workflow Links Fixed",
          detail: `Fixed ${linkValidation.patched} node connections and removed ${linkValidation.deleted} invalid links.`
        });
      }
    }
    return linkValidation.graph;
  }
  __name(tryFixLinks, "tryFixLinks");
  async function validateWorkflow(graphData, options2 = {}) {
    const { silent = false } = options2;
    let validatedData = null;
    const validatedGraphData = await validateComfyWorkflow(
      graphData,
      /* onError=*/
      (err) => {
        if (!silent) {
          toastStore.addAlert(err);
        }
      }
    );
    if (validatedGraphData) {
      try {
        validatedData = tryFixLinks(validatedGraphData, { silent });
      } catch (err) {
        console.error(err);
      }
    }
    return {
      graphData: validatedData
    };
  }
  __name(validateWorkflow, "validateWorkflow");
  return {
    validateWorkflow
  };
}
__name(useWorkflowValidation, "useWorkflowValidation");
var ComfyMetadataTags = /* @__PURE__ */ ((ComfyMetadataTags2) => {
  ComfyMetadataTags2["PROMPT"] = "PROMPT";
  ComfyMetadataTags2["WORKFLOW"] = "WORKFLOW";
  return ComfyMetadataTags2;
})(ComfyMetadataTags || {});
var ASCII$1 = /* @__PURE__ */ ((ASCII2) => {
  ASCII2[ASCII2["GLTF"] = 1179937895] = "GLTF";
  ASCII2[ASCII2["JSON"] = 1313821514] = "JSON";
  ASCII2[ASCII2["OPEN_BRACE"] = 123] = "OPEN_BRACE";
  return ASCII2;
})(ASCII$1 || {});
var GltfSizeBytes = /* @__PURE__ */ ((GltfSizeBytes2) => {
  GltfSizeBytes2[GltfSizeBytes2["HEADER"] = 12] = "HEADER";
  GltfSizeBytes2[GltfSizeBytes2["CHUNK_HEADER"] = 8] = "CHUNK_HEADER";
  return GltfSizeBytes2;
})(GltfSizeBytes || {});
const WEBM_SIGNATURE = [26, 69, 223, 163];
const MAX_READ_BYTES$2 = 2 * 1024 * 1024;
const EBML_ID = {
  SIMPLE_TAG: new Uint8Array([103, 200]),
  TAG_NAME: new Uint8Array([69, 163]),
  TAG_VALUE: new Uint8Array([68, 135])
};
const ASCII = {
  OPEN_BRACE: 123,
  NULL: 0,
  PRINTABLE_MIN: 32,
  PRINTABLE_MAX: 126
};
const MASK = {
  MSB: 128,
  ALL_BITS_SET: -1
};
const hasWebmSignature = /* @__PURE__ */ __name((data) => WEBM_SIGNATURE.every((byte, index2) => data[index2] === byte), "hasWebmSignature");
const readVint = /* @__PURE__ */ __name((data, pos) => {
  if (pos >= data.length) return null;
  const byte = data[pos];
  if ((byte & MASK.MSB) === MASK.MSB) {
    return { value: byte & ~MASK.MSB, length: 1 };
  }
  const length = findFirstSetBitPosition(byte);
  if (length === 0 || pos + length > data.length) {
    return null;
  }
  return {
    value: calculateVintValue(data, pos, length),
    length
  };
}, "readVint");
const calculateVintValue = /* @__PURE__ */ __name((data, pos, length) => {
  let value = data[pos] & 255 >> length;
  for (let i2 = 1; i2 < length; i2++) {
    value = value << 8 | data[pos + i2];
  }
  const allBitsSet = Math.pow(2, 7 * length) - 1;
  return value === allBitsSet ? MASK.ALL_BITS_SET : value;
}, "calculateVintValue");
const findFirstSetBitPosition = /* @__PURE__ */ __name((byte) => {
  for (let mask = MASK.MSB, position = 1; mask !== 0; mask >>= 1, position++) {
    if ((byte & mask) !== 0) return position;
  }
  return 0;
}, "findFirstSetBitPosition");
const matchesId = /* @__PURE__ */ __name((data, pos, id2) => {
  if (pos + id2.length > data.length) return false;
  for (let i2 = 0; i2 < id2.length; i2++) {
    if (data[pos + i2] !== id2[i2]) return false;
  }
  return true;
}, "matchesId");
const findNextTag = /* @__PURE__ */ __name((data, pos) => {
  if (!matchesId(data, pos, EBML_ID.SIMPLE_TAG)) return null;
  const tagSize = readVint(data, pos + 2);
  if (!tagSize || tagSize.value <= 0) return null;
  const tagEnd = pos + 2 + tagSize.length + tagSize.value;
  if (tagEnd > data.length) return null;
  const contents = extractTagContents(data, pos + 2 + tagSize.length, tagEnd);
  return { tagEnd, contents };
}, "findNextTag");
const extractTagContents = /* @__PURE__ */ __name((data, start2, end) => {
  const nameInfo = findElementsInTag(data, start2, end, EBML_ID.TAG_NAME);
  const valueInfo = findElementsInTag(data, start2, end, EBML_ID.TAG_VALUE);
  if (!nameInfo || !valueInfo) return null;
  return {
    name: nameInfo,
    value: valueInfo
  };
}, "extractTagContents");
const findElementsInTag = /* @__PURE__ */ __name((data, start2, end, id2) => {
  for (let pos = start2; pos < end - 1; ) {
    if (matchesId(data, pos, id2)) {
      const size = readVint(data, pos + 2);
      if (size && size.value > 0) {
        const elementPos = pos + 2 + size.length;
        return { pos: elementPos, len: size.value };
      }
    }
    pos++;
  }
  return null;
}, "findElementsInTag");
const processTagContents = /* @__PURE__ */ __name((data, contents, meta) => {
  try {
    const name2 = extractEbmlTagName(data, contents.name.pos, contents.name.len);
    if (!name2) return;
    const value = extractEbmlTagValue(
      data,
      name2,
      contents.value.pos,
      contents.value.len
    );
    if (value !== null) {
      meta[name2.toLowerCase()] = value;
    }
  } catch {
  }
}, "processTagContents");
const extractEbmlTagValue = /* @__PURE__ */ __name((data, name2, pos, len) => {
  if (name2 === ComfyMetadataTags.PROMPT || name2 === ComfyMetadataTags.WORKFLOW) {
    return readJson(data, pos, len);
  }
  return ebmlToString(data, pos, len);
}, "extractEbmlTagValue");
const extractEbmlTagName = /* @__PURE__ */ __name((data, start2, length) => {
  if (length <= 0) return null;
  const textRange2 = findReadableTextRange(data, start2, length);
  if (!textRange2) return null;
  return new TextDecoder().decode(data.subarray(textRange2.start, textRange2.end)).trim();
}, "extractEbmlTagName");
const findReadableTextRange = /* @__PURE__ */ __name((data, start2, length) => {
  const isPrintableAscii = /* @__PURE__ */ __name((byte) => byte >= ASCII.PRINTABLE_MIN && byte <= ASCII.PRINTABLE_MAX, "isPrintableAscii");
  let textStart = start2;
  while (textStart < start2 + length && !isPrintableAscii(data[textStart])) {
    textStart++;
  }
  if (textStart >= start2 + length) return null;
  let textEnd = textStart;
  while (textEnd < start2 + length && data[textEnd] !== ASCII.NULL) {
    textEnd++;
  }
  return { start: textStart, end: textEnd };
}, "findReadableTextRange");
const readJson = /* @__PURE__ */ __name((data, start2, length) => {
  if (length <= 0) return null;
  const nullTerminatorPos = findNullTerminator(data, start2, length);
  const jsonStartPos = findJsonStart(data, start2, nullTerminatorPos - start2);
  if (jsonStartPos === null) return null;
  const jsonText = decodeJsonText(data, jsonStartPos, nullTerminatorPos);
  return parseJsonText(jsonText);
}, "readJson");
const decodeJsonText = /* @__PURE__ */ __name((data, start2, end) => {
  return new TextDecoder().decode(data.subarray(start2, end));
}, "decodeJsonText");
const parseJsonText = /* @__PURE__ */ __name((jsonText) => {
  const jsonEndPos = findJsonEnd(jsonText);
  if (jsonEndPos === null) return null;
  try {
    return JSON.parse(jsonText.substring(0, jsonEndPos));
  } catch {
    return null;
  }
}, "parseJsonText");
const findNullTerminator = /* @__PURE__ */ __name((data, start2, maxLength) => {
  const end = Math.min(start2 + maxLength, data.length);
  for (let pos = start2; pos < end; pos++) {
    if (data[pos] === ASCII.NULL) return pos;
  }
  return end;
}, "findNullTerminator");
const findJsonStart = /* @__PURE__ */ __name((data, start2, length) => {
  for (let pos = start2; pos < start2 + length; pos++) {
    if (data[pos] === ASCII.OPEN_BRACE) return pos;
  }
  return null;
}, "findJsonStart");
const findJsonEnd = /* @__PURE__ */ __name((text2) => {
  let braceCount = 1;
  let pos = 1;
  while (braceCount > 0 && pos < text2.length) {
    if (text2[pos] === "{") braceCount++;
    if (text2[pos] === "}") braceCount--;
    pos++;
  }
  return braceCount === 0 ? pos : null;
}, "findJsonEnd");
const ebmlToString = /* @__PURE__ */ __name((data, start2, length) => {
  if (length <= 0) return "";
  const endPos = findNullTerminator(data, start2, length);
  return new TextDecoder().decode(data.subarray(start2, endPos)).trim();
}, "ebmlToString");
const parseMetadata = /* @__PURE__ */ __name((data) => {
  const meta = {};
  for (let pos = 0; pos < data.length - 2; ) {
    const tagInfo = findNextTag(data, pos);
    if (!tagInfo) {
      pos++;
      continue;
    }
    const { tagEnd, contents } = tagInfo;
    if (contents) {
      processTagContents(data, contents, meta);
    }
    pos = tagEnd;
  }
  return meta;
}, "parseMetadata");
const handleFileLoad = /* @__PURE__ */ __name((event, resolve2) => {
  if (!event.target?.result) {
    resolve2({});
    return;
  }
  try {
    const data = new Uint8Array(event.target.result);
    if (data.length < 4 || !hasWebmSignature(data)) {
      resolve2({});
      return;
    }
    resolve2(parseMetadata(data));
  } catch {
    resolve2({});
  }
}, "handleFileLoad");
function getFromWebmFile(file) {
  return new Promise((resolve2) => {
    const reader = new FileReader();
    reader.onload = (event) => handleFileLoad(event, resolve2);
    reader.onerror = () => resolve2({});
    reader.readAsArrayBuffer(file.slice(0, MAX_READ_BYTES$2));
  });
}
__name(getFromWebmFile, "getFromWebmFile");
window.comfyAPI = window.comfyAPI || {};
window.comfyAPI.ebml = window.comfyAPI.ebml || {};
window.comfyAPI.ebml.getFromWebmFile = getFromWebmFile;
const MAX_READ_BYTES$1 = 1 << 20;
const isJsonChunk = /* @__PURE__ */ __name((chunk) => !!chunk && chunk.chunkTypeIdentifier === ASCII$1.JSON, "isJsonChunk");
const isValidChunkRange = /* @__PURE__ */ __name((start2, length, bufferSize) => start2 + length <= bufferSize, "isValidChunkRange");
const byteArrayToString = /* @__PURE__ */ __name((bytes) => new TextDecoder().decode(bytes), "byteArrayToString");
const parseGltfBinaryHeader = /* @__PURE__ */ __name((dataView) => {
  if (dataView.byteLength < GltfSizeBytes.HEADER) return null;
  const magicNumber = dataView.getUint32(0, true);
  if (magicNumber !== ASCII$1.GLTF) return null;
  return {
    magicNumber,
    gltfFormatVersion: dataView.getUint32(4, true),
    totalLengthBytes: dataView.getUint32(8, true)
  };
}, "parseGltfBinaryHeader");
const parseChunkHeaderAtOffset = /* @__PURE__ */ __name((dataView, offset) => {
  if (offset + GltfSizeBytes.CHUNK_HEADER > dataView.byteLength) return null;
  return {
    chunkLengthBytes: dataView.getUint32(offset, true),
    chunkTypeIdentifier: dataView.getUint32(offset + 4, true)
  };
}, "parseChunkHeaderAtOffset");
const extractJsonChunk = /* @__PURE__ */ __name((buffer) => {
  const dataView = new DataView(buffer);
  const header = parseGltfBinaryHeader(dataView);
  if (!header) return null;
  const chunkOffset = GltfSizeBytes.HEADER;
  const firstChunk = parseChunkHeaderAtOffset(dataView, chunkOffset);
  if (!firstChunk || !isJsonChunk(firstChunk)) return null;
  const jsonStart = chunkOffset + GltfSizeBytes.CHUNK_HEADER;
  const isValid2 = isValidChunkRange(
    jsonStart,
    firstChunk.chunkLengthBytes,
    dataView.byteLength
  );
  if (!isValid2) return null;
  return { start: jsonStart, length: firstChunk.chunkLengthBytes };
}, "extractJsonChunk");
const extractJsonChunkData = /* @__PURE__ */ __name((buffer) => {
  const chunkLocation = extractJsonChunk(buffer);
  if (!chunkLocation) return null;
  return new Uint8Array(buffer, chunkLocation.start, chunkLocation.length);
}, "extractJsonChunkData");
const parseJson = /* @__PURE__ */ __name((text2) => {
  try {
    return JSON.parse(text2);
  } catch {
    return null;
  }
}, "parseJson");
const parseJsonBytes = /* @__PURE__ */ __name((bytes) => {
  const jsonString = byteArrayToString(bytes);
  return parseJson(jsonString);
}, "parseJsonBytes");
const parseMetadataValue = /* @__PURE__ */ __name((value) => {
  if (typeof value !== "string")
    return value;
  const parsed = parseJson(value);
  if (!parsed) return void 0;
  return parsed;
}, "parseMetadataValue");
const extractComfyMetadata = /* @__PURE__ */ __name((jsonData) => {
  const metadata = {};
  if (!jsonData?.asset?.extras) return metadata;
  const { extras } = jsonData.asset;
  if (extras.workflow) {
    const parsedValue = parseMetadataValue(extras.workflow);
    if (parsedValue) {
      metadata[ComfyMetadataTags.WORKFLOW.toLowerCase()] = parsedValue;
    }
  }
  if (extras.prompt) {
    const parsedValue = parseMetadataValue(extras.prompt);
    if (parsedValue) {
      metadata[ComfyMetadataTags.PROMPT.toLowerCase()] = parsedValue;
    }
  }
  return metadata;
}, "extractComfyMetadata");
const processGltfFileBuffer = /* @__PURE__ */ __name((buffer) => {
  const jsonChunk = extractJsonChunkData(buffer);
  if (!jsonChunk) return {};
  const parsedJson = parseJsonBytes(jsonChunk);
  if (!parsedJson) return {};
  return extractComfyMetadata(parsedJson);
}, "processGltfFileBuffer");
function getGltfBinaryMetadata(file) {
  return new Promise((resolve2) => {
    if (!file) return Promise.resolve({});
    const bytesToRead = Math.min(file.size, MAX_READ_BYTES$1);
    const reader = new FileReader();
    reader.onload = (event) => {
      try {
        if (!event.target?.result) {
          resolve2({});
          return;
        }
        resolve2(processGltfFileBuffer(event.target.result));
      } catch {
        resolve2({});
      }
    };
    reader.onerror = () => resolve2({});
    reader.readAsArrayBuffer(file.slice(0, bytesToRead));
  });
}
__name(getGltfBinaryMetadata, "getGltfBinaryMetadata");
window.comfyAPI = window.comfyAPI || {};
window.comfyAPI.gltf = window.comfyAPI.gltf || {};
window.comfyAPI.gltf.getGltfBinaryMetadata = getGltfBinaryMetadata;
const MAX_READ_BYTES = 64 * 1024 * 1024;
const BOX_TYPES = {
  USER_DATA: [117, 100, 116, 97],
  META_DATA: [109, 101, 116, 97],
  ITEM_LIST: [105, 108, 115, 116],
  KEYS: [107, 101, 121, 115],
  DATA: [100, 97, 116, 97],
  MOVIE: [109, 111, 111, 118]
};
const SIZES = {
  HEADER: 8,
  VERSION: 4,
  LOCALE: 4,
  ITEM_MIN: 8
};
const bufferMatchesBoxType = /* @__PURE__ */ __name((data, pos, boxType) => {
  if (pos + 4 > data.length) return false;
  for (let i2 = 0; i2 < 4; i2++) {
    if (data[pos + i2] !== boxType[i2]) return false;
  }
  return true;
}, "bufferMatchesBoxType");
const readUint32 = /* @__PURE__ */ __name((data, pos) => {
  if (pos + 4 > data.length) return 0;
  return data[pos] << 24 | data[pos + 1] << 16 | data[pos + 2] << 8 | data[pos + 3];
}, "readUint32");
const findIsobmffBoxByType = /* @__PURE__ */ __name((data, startPos, endPos, boxType) => {
  for (let pos = startPos; pos < endPos - 8; pos++) {
    const size = readUint32(data, pos);
    if (size < SIZES.ITEM_MIN) continue;
    if (bufferMatchesBoxType(data, pos + 4, boxType))
      return { start: pos + SIZES.HEADER, end: pos + size };
    if (pos + size > endPos) return null;
    pos += size - 1;
  }
  return null;
}, "findIsobmffBoxByType");
const extractJson = /* @__PURE__ */ __name((data, start2, end) => {
  let jsonStart = start2;
  while (jsonStart < end && data[jsonStart] !== ASCII$1.OPEN_BRACE) {
    jsonStart++;
  }
  if (jsonStart >= end) return null;
  try {
    const jsonText = new TextDecoder().decode(data.slice(jsonStart, end));
    return JSON.parse(jsonText);
  } catch {
    return null;
  }
}, "extractJson");
const readUtf8String = /* @__PURE__ */ __name((data, start2, end) => new TextDecoder().decode(data.slice(start2, end)), "readUtf8String");
const parseKeysBox = /* @__PURE__ */ __name((data, keysBoxStart, keysBoxEnd) => {
  const keysMap = /* @__PURE__ */ new Map();
  let pos = keysBoxStart + 4;
  if (pos + 4 > keysBoxEnd) return keysMap;
  const entryCount = readUint32(data, pos);
  pos += 4;
  for (let i2 = 1; i2 <= entryCount; i2++) {
    if (pos + SIZES.HEADER > keysBoxEnd) break;
    const keySize = readUint32(data, pos);
    pos += SIZES.HEADER;
    const keyNameEnd = pos + keySize - SIZES.HEADER;
    if (keySize < SIZES.ITEM_MIN || keyNameEnd > keysBoxEnd) break;
    const keyName2 = readUtf8String(data, pos, keyNameEnd);
    keysMap.set(i2, keyName2);
    pos = keyNameEnd;
  }
  return keysMap;
}, "parseKeysBox");
const extractMetadataValueFromDataBox = /* @__PURE__ */ __name((data, dataBoxStart, dataBoxEnd, keyName2) => {
  const valueStart = dataBoxStart + SIZES.VERSION + SIZES.LOCALE;
  if (valueStart >= dataBoxEnd) return null;
  const lowerKeyName = keyName2.toLowerCase();
  if (lowerKeyName === ComfyMetadataTags.PROMPT.toLowerCase() || lowerKeyName === ComfyMetadataTags.WORKFLOW.toLowerCase()) {
    return extractJson(data, valueStart, dataBoxEnd) || null;
  }
  return null;
}, "extractMetadataValueFromDataBox");
const parseIlstItem = /* @__PURE__ */ __name((data, itemStart, itemEnd, keysMap, metadata) => {
  if (itemStart + SIZES.HEADER > itemEnd) return;
  const itemIndex = readUint32(data, itemStart + 4);
  const keyName2 = keysMap.get(itemIndex);
  if (!keyName2) return;
  const dataBox = findIsobmffBoxByType(
    data,
    itemStart + SIZES.HEADER,
    itemEnd,
    BOX_TYPES.DATA
  );
  if (dataBox) {
    const value = extractMetadataValueFromDataBox(
      data,
      dataBox.start,
      dataBox.end,
      keyName2
    );
    if (value !== null) {
      metadata[keyName2.toLowerCase()] = value;
    }
  }
}, "parseIlstItem");
const parseIlstBox = /* @__PURE__ */ __name((data, ilstStart, ilstEnd, keysMap, metadata) => {
  let pos = ilstStart;
  while (pos < ilstEnd - SIZES.HEADER) {
    const itemSize = readUint32(data, pos);
    if (itemSize <= SIZES.HEADER || pos + itemSize > ilstEnd) break;
    parseIlstItem(data, pos, pos + itemSize, keysMap, metadata);
    pos += itemSize;
  }
}, "parseIlstBox");
const findUserDataBox = /* @__PURE__ */ __name((data) => {
  let userDataBox = null;
  userDataBox = findIsobmffBoxByType(data, 0, data.length, BOX_TYPES.USER_DATA);
  if (!userDataBox) {
    const moovBox = findIsobmffBoxByType(data, 0, data.length, BOX_TYPES.MOVIE);
    if (moovBox) {
      userDataBox = findIsobmffBoxByType(
        data,
        moovBox.start,
        moovBox.end,
        BOX_TYPES.USER_DATA
      );
    }
  }
  return userDataBox;
}, "findUserDataBox");
const parseIsobmffMetadata = /* @__PURE__ */ __name((data) => {
  const metadata = {};
  const userDataBox = findUserDataBox(data);
  if (!userDataBox) return metadata;
  const metaBox = findIsobmffBoxByType(
    data,
    userDataBox.start,
    userDataBox.end,
    BOX_TYPES.META_DATA
  );
  if (!metaBox) return metadata;
  const metaContentStart = metaBox.start + SIZES.VERSION;
  const keysBox = findIsobmffBoxByType(
    data,
    metaContentStart,
    metaBox.end,
    BOX_TYPES.KEYS
  );
  if (!keysBox) return metadata;
  const keysMap = parseKeysBox(data, keysBox.start, keysBox.end);
  if (keysMap.size === 0) return metadata;
  const ilstBox = findIsobmffBoxByType(
    data,
    metaContentStart,
    metaBox.end,
    BOX_TYPES.ITEM_LIST
  );
  if (!ilstBox) return metadata;
  parseIlstBox(data, ilstBox.start, ilstBox.end, keysMap, metadata);
  return metadata;
}, "parseIsobmffMetadata");
function getFromIsobmffFile(file) {
  return new Promise((resolve2) => {
    const reader = new FileReader();
    reader.onload = (event) => {
      if (!event.target?.result) {
        resolve2({});
        return;
      }
      try {
        const data = new Uint8Array(event.target.result);
        resolve2(parseIsobmffMetadata(data));
      } catch (e2) {
        console.error("Parser: Error parsing ISOBMFF metadata:", e2);
        resolve2({});
      }
    };
    reader.onerror = (err) => {
      console.error("FileReader: Error reading ISOBMFF file:", err);
      resolve2({});
    };
    reader.readAsArrayBuffer(file.slice(0, MAX_READ_BYTES));
  });
}
__name(getFromIsobmffFile, "getFromIsobmffFile");
window.comfyAPI = window.comfyAPI || {};
window.comfyAPI.isobmff = window.comfyAPI.isobmff || {};
window.comfyAPI.isobmff.getFromIsobmffFile = getFromIsobmffFile;
async function getMp3Metadata(file) {
  const reader = new FileReader();
  const read_process = new Promise(
    (r2) => reader.onload = (event) => r2(event?.target?.result)
  );
  reader.readAsArrayBuffer(file);
  const arrayBuffer = await read_process;
  const sig_bytes = new Uint8Array(arrayBuffer, 0, 3);
  if (sig_bytes[0] != 255 && sig_bytes[1] != 251 || sig_bytes[0] != 73 && sig_bytes[1] != 68 && sig_bytes[2] != 51)
    console.error("Invalid file signature.");
  let header = "";
  while (header.length < arrayBuffer.byteLength) {
    const page = String.fromCharCode(
      ...new Uint8Array(arrayBuffer, header.length, header.length + 4096)
    );
    header += page;
    if (page.match("ÿû")) break;
  }
  let workflow, prompt;
  let prompt_s = header.match(/prompt\u0000(\{.*?\})\u0000/s)?.[1];
  if (prompt_s) prompt = JSON.parse(prompt_s);
  let workflow_s = header.match(/workflow\u0000(\{.*?\})\u0000/s)?.[1];
  if (workflow_s) workflow = JSON.parse(workflow_s);
  return { prompt, workflow };
}
__name(getMp3Metadata, "getMp3Metadata");
window.comfyAPI = window.comfyAPI || {};
window.comfyAPI.mp3 = window.comfyAPI.mp3 || {};
window.comfyAPI.mp3.getMp3Metadata = getMp3Metadata;
async function getOggMetadata(file) {
  const reader = new FileReader();
  const read_process = new Promise(
    (r2) => reader.onload = (event) => r2(event?.target?.result)
  );
  reader.readAsArrayBuffer(file);
  const arrayBuffer = await read_process;
  const signature = String.fromCharCode(...new Uint8Array(arrayBuffer, 0, 4));
  if (signature !== "OggS") console.error("Invalid file signature.");
  let oggs = 0;
  let header = "";
  while (header.length < arrayBuffer.byteLength) {
    const page = String.fromCharCode(
      ...new Uint8Array(arrayBuffer, header.length, header.length + 4096)
    );
    if (page.match("OggS\0")) oggs++;
    header += page;
    if (oggs > 1) break;
  }
  let workflow, prompt;
  let prompt_s = header.match(/prompt=(\{.*?(\}.*?\u0000))/s)?.[1]?.match(/\{.*\}/)?.[0];
  if (prompt_s) prompt = JSON.parse(prompt_s);
  let workflow_s = header.match(/workflow=(\{.*?(\}.*?\u0000))/s)?.[1]?.match(/\{.*\}/)?.[0];
  if (workflow_s) workflow = JSON.parse(workflow_s);
  return { prompt, workflow };
}
__name(getOggMetadata, "getOggMetadata");
window.comfyAPI = window.comfyAPI || {};
window.comfyAPI.ogg = window.comfyAPI.ogg || {};
window.comfyAPI.ogg.getOggMetadata = getOggMetadata;
async function getSvgMetadata(file) {
  const text2 = await file.text();
  const metadataMatch = /<metadata>\s*<!\[CDATA\[([\s\S]*?)\]\]>\s*<\/metadata>/i.exec(text2);
  if (metadataMatch && metadataMatch[1]) {
    try {
      return JSON.parse(metadataMatch[1].trim());
    } catch (error2) {
      console.error("Error parsing SVG metadata:", error2);
      return {};
    }
  }
  return {};
}
__name(getSvgMetadata, "getSvgMetadata");
window.comfyAPI = window.comfyAPI || {};
window.comfyAPI.svg = window.comfyAPI.svg || {};
window.comfyAPI.svg.getSvgMetadata = getSvgMetadata;
const _imports_0$2 = "" + new URL("api-nodes-news-TPe-hnxx.webp", import.meta.url).href;
const _hoisted_1$1u = { class: "flex flex-col gap-12 p-2 w-96" };
const _hoisted_2$15 = { class: "flex flex-col gap-2 justify-center items-center" };
const _hoisted_3$P = { class: "text-xl" };
const _hoisted_4$B = { class: "text-muted" };
const _hoisted_5$t = { class: "flex flex-col gap-4" };
const _hoisted_6$k = { class: "flex flex-col gap-2" };
const _hoisted_7$e = {
  key: 0,
  class: "text-muted"
};
const _hoisted_8$b = { class: "flex flex-row justify-between" };
const _sfc_main$1R = /* @__PURE__ */ defineComponent({
  __name: "ApiNodesNewsContent",
  props: {
    onClose: { type: Function }
  },
  setup(__props) {
    const { t: t2 } = useI18n();
    const steps = [
      {
        title: t2("apiNodesNews.steps.step1.title"),
        subtitle: t2("apiNodesNews.steps.step1.subtitle")
      },
      {
        title: t2("apiNodesNews.steps.step2.title"),
        subtitle: t2("apiNodesNews.steps.step2.subtitle")
      },
      {
        title: t2("apiNodesNews.steps.step3.title")
      },
      {
        title: t2("apiNodesNews.steps.step4.title")
      }
    ];
    const handleLearnMore = /* @__PURE__ */ __name(() => {
      window.open("https://blog.comfy.org/p/comfyui-native-api-nodes", "_blank");
    }, "handleLearnMore");
    onBeforeUnmount(() => {
      localStorage.setItem("api-nodes-news-seen", "true");
    });
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", _hoisted_1$1u, [
        _cache[1] || (_cache[1] = createBaseVNode("img", {
          src: _imports_0$2,
          alt: "API Nodes News"
        }, null, -1)),
        createBaseVNode("div", _hoisted_2$15, [
          createBaseVNode("div", _hoisted_3$P, [
            createTextVNode(toDisplayString(_ctx.$t("apiNodesNews.introducing")) + " ", 1),
            _cache[0] || (_cache[0] = createBaseVNode("span", { class: "text-amber-500" }, "API NODES", -1))
          ]),
          createBaseVNode("div", _hoisted_4$B, toDisplayString(_ctx.$t("apiNodesNews.subtitle")), 1)
        ]),
        createBaseVNode("div", _hoisted_5$t, [
          (openBlock(), createElementBlock(Fragment$1, null, renderList(steps, (step, index2) => {
            return createBaseVNode("div", {
              key: index2,
              class: "grid grid-cols-[auto_1fr] gap-2 items-center"
            }, [
              createVNode(unref(script$5), {
                class: "w-8 h-8",
                value: index2 + 1,
                rounded: ""
              }, null, 8, ["value"]),
              createBaseVNode("div", _hoisted_6$k, [
                createBaseVNode("div", null, toDisplayString(step.title), 1),
                step.subtitle ? (openBlock(), createElementBlock("div", _hoisted_7$e, toDisplayString(step.subtitle), 1)) : createCommentVNode("", true)
              ])
            ]);
          }), 64))
        ]),
        createBaseVNode("div", _hoisted_8$b, [
          createVNode(unref(script$6), {
            label: "Learn More",
            text: "",
            onClick: handleLearnMore
          }),
          createVNode(unref(script$6), {
            label: "Close",
            onClick: _ctx.onClose
          }, null, 8, ["onClick"])
        ])
      ]);
    };
  }
});
const _hoisted_1$1t = { class: "flex flex-col gap-3 h-full" };
const _hoisted_2$14 = { class: "flex text-xs" };
const _hoisted_3$O = { class: "flex flex-col gap-2" };
const _hoisted_4$A = { class: "flex items-center gap-2" };
const _hoisted_5$s = { class: "text-base font-medium leading-tight" };
const _sfc_main$1Q = /* @__PURE__ */ defineComponent({
  __name: "ApiNodesList",
  props: {
    nodeNames: {}
  },
  setup(__props) {
    const { t: t2 } = useI18n();
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", _hoisted_1$1t, [
        createBaseVNode("div", _hoisted_2$14, [
          createBaseVNode("div", null, toDisplayString(unref(t2)("apiNodesCostBreakdown.title")), 1)
        ]),
        createVNode(unref(script$7), { class: "flex-grow h-0" }, {
          default: withCtx(() => [
            createBaseVNode("div", _hoisted_3$O, [
              (openBlock(true), createElementBlock(Fragment$1, null, renderList(_ctx.nodeNames, (nodeName) => {
                return openBlock(), createElementBlock("div", {
                  key: nodeName,
                  class: "flex items-center justify-between px-3 py-2 rounded-md bg-[var(--p-content-border-color)]"
                }, [
                  createBaseVNode("div", _hoisted_4$A, [
                    createBaseVNode("span", _hoisted_5$s, toDisplayString(nodeName), 1)
                  ])
                ]);
              }), 128))
            ])
          ]),
          _: 1
        })
      ]);
    };
  }
});
const _hoisted_1$1s = { class: "flex flex-col gap-4 max-w-96 h-110 p-2" };
const _hoisted_2$13 = { class: "text-2xl font-medium mb-2" };
const _hoisted_3$N = { class: "text-base mb-4" };
const _hoisted_4$z = { class: "flex justify-between items-center" };
const _hoisted_5$r = { class: "flex gap-2" };
const _sfc_main$1P = /* @__PURE__ */ defineComponent({
  __name: "ApiNodesSignInContent",
  props: {
    apiNodeNames: {},
    onLogin: { type: Function },
    onCancel: { type: Function }
  },
  setup(__props) {
    const { t: t2 } = useI18n();
    const handleLearnMoreClick = /* @__PURE__ */ __name(() => {
      window.open("https://docs.comfy.org/tutorials/api-nodes/faq", "_blank");
    }, "handleLearnMoreClick");
    return (_ctx, _cache) => {
      const _component_ApiNodesList = _sfc_main$1Q;
      return openBlock(), createElementBlock("div", _hoisted_1$1s, [
        createBaseVNode("div", _hoisted_2$13, toDisplayString(unref(t2)("apiNodesSignInDialog.title")), 1),
        createBaseVNode("div", _hoisted_3$N, toDisplayString(unref(t2)("apiNodesSignInDialog.message")), 1),
        createVNode(_component_ApiNodesList, { "node-names": _ctx.apiNodeNames }, null, 8, ["node-names"]),
        createBaseVNode("div", _hoisted_4$z, [
          createVNode(unref(script$6), {
            label: unref(t2)("g.learnMore"),
            link: "",
            onClick: handleLearnMoreClick
          }, null, 8, ["label"]),
          createBaseVNode("div", _hoisted_5$r, [
            createVNode(unref(script$6), {
              label: unref(t2)("g.cancel"),
              outlined: "",
              severity: "secondary",
              onClick: _cache[0] || (_cache[0] = ($event) => _ctx.onCancel?.())
            }, null, 8, ["label"]),
            createVNode(unref(script$6), {
              label: unref(t2)("g.login"),
              onClick: _cache[1] || (_cache[1] = ($event) => _ctx.onLogin?.())
            }, null, 8, ["label"])
          ])
        ])
      ]);
    };
  }
});
const _hoisted_1$1r = { class: "prompt-dialog-content flex flex-col gap-6 m-2 mt-4" };
const _hoisted_2$12 = {
  key: 0,
  class: "pl-4 m-0 flex flex-col gap-2"
};
const _hoisted_3$M = { class: "flex gap-4 justify-end" };
const _sfc_main$1O = /* @__PURE__ */ defineComponent({
  __name: "ConfirmationDialogContent",
  props: {
    message: {},
    type: {},
    onConfirm: { type: Function },
    itemList: {},
    hint: {}
  },
  setup(__props) {
    const props = __props;
    const onCancel = /* @__PURE__ */ __name(() => useDialogStore().closeDialog(), "onCancel");
    const onDeny = /* @__PURE__ */ __name(() => {
      props.onConfirm(false);
      useDialogStore().closeDialog();
    }, "onDeny");
    const onConfirm = /* @__PURE__ */ __name(() => {
      props.onConfirm(true);
      useDialogStore().closeDialog();
    }, "onConfirm");
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("section", _hoisted_1$1r, [
        createBaseVNode("span", null, toDisplayString(_ctx.message), 1),
        _ctx.itemList?.length ? (openBlock(), createElementBlock("ul", _hoisted_2$12, [
          (openBlock(true), createElementBlock(Fragment$1, null, renderList(_ctx.itemList, (item) => {
            return openBlock(), createElementBlock("li", { key: item }, toDisplayString(item), 1);
          }), 128))
        ])) : createCommentVNode("", true),
        _ctx.hint ? (openBlock(), createBlock(unref(script$8), {
          key: 1,
          icon: "pi pi-info-circle",
          severity: "secondary",
          size: "small",
          variant: "simple"
        }, {
          default: withCtx(() => [
            createTextVNode(toDisplayString(_ctx.hint), 1)
          ]),
          _: 1
        })) : createCommentVNode("", true),
        createBaseVNode("div", _hoisted_3$M, [
          createVNode(unref(script$6), {
            label: _ctx.$t("g.cancel"),
            icon: "pi pi-undo",
            severity: "secondary",
            autofocus: "",
            onClick: onCancel
          }, null, 8, ["label"]),
          _ctx.type === "default" ? (openBlock(), createBlock(unref(script$6), {
            key: 0,
            label: _ctx.$t("g.confirm"),
            severity: "primary",
            icon: "pi pi-check",
            onClick: onConfirm
          }, null, 8, ["label"])) : _ctx.type === "delete" ? (openBlock(), createBlock(unref(script$6), {
            key: 1,
            label: _ctx.$t("g.delete"),
            severity: "danger",
            icon: "pi pi-trash",
            onClick: onConfirm
          }, null, 8, ["label"])) : _ctx.type === "overwrite" ? (openBlock(), createBlock(unref(script$6), {
            key: 2,
            label: _ctx.$t("g.overwrite"),
            severity: "warn",
            icon: "pi pi-save",
            onClick: onConfirm
          }, null, 8, ["label"])) : _ctx.type === "dirtyClose" ? (openBlock(), createElementBlock(Fragment$1, { key: 3 }, [
            createVNode(unref(script$6), {
              label: _ctx.$t("g.no"),
              severity: "secondary",
              icon: "pi pi-times",
              onClick: onDeny
            }, null, 8, ["label"]),
            createVNode(unref(script$6), {
              label: _ctx.$t("g.save"),
              icon: "pi pi-save",
              onClick: onConfirm
            }, null, 8, ["label"])
          ], 64)) : _ctx.type === "reinstall" ? (openBlock(), createBlock(unref(script$6), {
            key: 4,
            label: _ctx.$t("desktopMenu.reinstall"),
            severity: "warn",
            icon: "pi pi-eraser",
            onClick: onConfirm
          }, null, 8, ["label"])) : (openBlock(), createBlock(unref(script$6), {
            key: 5,
            label: _ctx.$t("g.close"),
            severity: "primary",
            icon: "pi pi-times",
            onClick: onCancel
          }, null, 8, ["label"]))
        ])
      ]);
    };
  }
});
const _export_sfc = /* @__PURE__ */ __name((sfc, props) => {
  const target = sfc.__vccOpts || sfc;
  for (const [key, val] of props) {
    target[key] = val;
  }
  return target;
}, "_export_sfc");
const ConfirmationDialogContent = /* @__PURE__ */ _export_sfc(_sfc_main$1O, [["__scopeId", "data-v-43e63241"]]);
const _hoisted_1$1q = { class: "flex flex-col items-center" };
const _sfc_main$1N = /* @__PURE__ */ defineComponent({
  __name: "NoResultsPlaceholder",
  props: {
    class: {},
    icon: {},
    title: {},
    message: {},
    textClass: {},
    buttonLabel: {}
  },
  emits: ["action"],
  setup(__props) {
    const props = __props;
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", {
        class: normalizeClass(["no-results-placeholder p-8 h-full", props.class])
      }, [
        createVNode(unref(script$9), null, {
          content: withCtx(() => [
            createBaseVNode("div", _hoisted_1$1q, [
              createBaseVNode("i", {
                class: normalizeClass(_ctx.icon),
                style: { "font-size": "3rem", "margin-bottom": "1rem" }
              }, null, 2),
              createBaseVNode("h3", null, toDisplayString(_ctx.title), 1),
              createBaseVNode("p", {
                class: normalizeClass([_ctx.textClass, "whitespace-pre-line text-center"])
              }, toDisplayString(_ctx.message), 3),
              _ctx.buttonLabel ? (openBlock(), createBlock(unref(script$6), {
                key: 0,
                label: _ctx.buttonLabel,
                class: "p-button-text",
                onClick: _cache[0] || (_cache[0] = ($event) => _ctx.$emit("action"))
              }, null, 8, ["label"])) : createCommentVNode("", true)
            ])
          ]),
          _: 1
        })
      ], 2);
    };
  }
});
const NoResultsPlaceholder = /* @__PURE__ */ _export_sfc(_sfc_main$1N, [["__scopeId", "data-v-498ea000"]]);
const _sfc_main$1M = /* @__PURE__ */ defineComponent({
  __name: "FindIssueButton",
  props: {
    errorMessage: {},
    repoOwner: {},
    repoName: {}
  },
  setup(__props) {
    const props = __props;
    const queryString = computed(() => props.errorMessage + " is:issue");
    const openGitHubIssues = /* @__PURE__ */ __name(() => {
      const query2 = encodeURIComponent(queryString.value);
      const url = `https://github.com/${props.repoOwner}/${props.repoName}/issues?q=${query2}`;
      window.open(url, "_blank");
    }, "openGitHubIssues");
    return (_ctx, _cache) => {
      return openBlock(), createBlock(unref(script$6), {
        label: _ctx.$t("g.findIssues"),
        severity: "secondary",
        icon: "pi pi-github",
        onClick: openGitHubIssues
      }, null, 8, ["label"]);
    };
  }
});
function useCopyToClipboard() {
  const { copy: copy2, isSupported } = useClipboard();
  const toast = useToast();
  const copyToClipboard = /* @__PURE__ */ __name(async (text2) => {
    if (isSupported) {
      try {
        await copy2(text2);
        toast.add({
          severity: "success",
          summary: t("g.success"),
          detail: t("clipboard.successMessage"),
          life: 3e3
        });
      } catch (err) {
        toast.add({
          severity: "error",
          summary: t("g.error"),
          detail: t("clipboard.errorMessage")
        });
      }
    } else {
      toast.add({
        severity: "error",
        summary: t("g.error"),
        detail: t("clipboard.errorNotSupported")
      });
    }
  }, "copyToClipboard");
  return {
    copyToClipboard
  };
}
__name(useCopyToClipboard, "useCopyToClipboard");
const RESERVED_BY_TEXT_INPUT = /* @__PURE__ */ new Set([
  "Ctrl + a",
  "Ctrl + c",
  "Ctrl + v",
  "Ctrl + x",
  "Ctrl + z",
  "Ctrl + y",
  "Ctrl + p",
  "Enter",
  "Shift + Enter",
  "Ctrl + Backspace",
  "Ctrl + Delete",
  "Home",
  "Ctrl + Home",
  "Ctrl + Shift + Home",
  "End",
  "Ctrl + End",
  "Ctrl + Shift + End",
  "PageUp",
  "PageDown",
  "Shift + PageUp",
  "Shift + PageDown",
  "ArrowLeft",
  "Ctrl + ArrowLeft",
  "Shift + ArrowLeft",
  "Ctrl + Shift + ArrowLeft",
  "ArrowRight",
  "Ctrl + ArrowRight",
  "Shift + ArrowRight",
  "Ctrl + Shift + ArrowRight",
  "ArrowUp",
  "Shift + ArrowUp",
  "ArrowDown",
  "Shift + ArrowDown"
]);
class KeybindingImpl {
  static {
    __name(this, "KeybindingImpl");
  }
  commandId;
  combo;
  targetElementId;
  constructor(obj) {
    this.commandId = obj.commandId;
    this.combo = new KeyComboImpl(obj.combo);
    this.targetElementId = obj.targetElementId;
  }
  equals(other) {
    const raw = toRaw(other);
    return raw instanceof KeybindingImpl ? this.commandId === raw.commandId && this.combo.equals(raw.combo) && this.targetElementId === raw.targetElementId : false;
  }
}
class KeyComboImpl {
  static {
    __name(this, "KeyComboImpl");
  }
  key;
  // ctrl or meta(cmd on mac)
  ctrl;
  alt;
  shift;
  constructor(obj) {
    this.key = obj.key;
    this.ctrl = obj.ctrl ?? false;
    this.alt = obj.alt ?? false;
    this.shift = obj.shift ?? false;
  }
  static fromEvent(event) {
    return new KeyComboImpl({
      key: event.key,
      ctrl: event.ctrlKey || event.metaKey,
      alt: event.altKey,
      shift: event.shiftKey
    });
  }
  equals(other) {
    const raw = toRaw(other);
    return raw instanceof KeyComboImpl ? this.key.toUpperCase() === raw.key.toUpperCase() && this.ctrl === raw.ctrl && this.alt === raw.alt && this.shift === raw.shift : false;
  }
  serialize() {
    return `${this.key.toUpperCase()}:${this.ctrl}:${this.alt}:${this.shift}`;
  }
  toString() {
    return this.getKeySequences().join(" + ");
  }
  get hasModifier() {
    return this.ctrl || this.alt || this.shift;
  }
  get isModifier() {
    return ["Control", "Meta", "Alt", "Shift"].includes(this.key);
  }
  get modifierCount() {
    const modifiers2 = [this.ctrl, this.alt, this.shift];
    return modifiers2.reduce((acc, cur) => acc + Number(cur), 0);
  }
  get isShiftOnly() {
    return this.shift && this.modifierCount === 1;
  }
  get isReservedByTextInput() {
    return !this.hasModifier || this.isShiftOnly || RESERVED_BY_TEXT_INPUT.has(this.toString());
  }
  getKeySequences() {
    const sequences = [];
    if (this.ctrl) {
      sequences.push("Ctrl");
    }
    if (this.alt) {
      sequences.push("Alt");
    }
    if (this.shift) {
      sequences.push("Shift");
    }
    sequences.push(this.key);
    return sequences;
  }
}
const useKeybindingStore = /* @__PURE__ */ defineStore("keybinding", () => {
  const defaultKeybindings = ref$3({});
  const userKeybindings = ref$3({});
  const userUnsetKeybindings = ref$3({});
  function getUserKeybindings() {
    return userKeybindings.value;
  }
  __name(getUserKeybindings, "getUserKeybindings");
  function getUserUnsetKeybindings() {
    return userUnsetKeybindings.value;
  }
  __name(getUserUnsetKeybindings, "getUserUnsetKeybindings");
  const keybindingByKeyCombo = computed(() => {
    const result = {
      ...defaultKeybindings.value
    };
    for (const keybinding of Object.values(userUnsetKeybindings.value)) {
      const serializedCombo = keybinding.combo.serialize();
      if (result[serializedCombo]?.equals(keybinding)) {
        delete result[serializedCombo];
      }
    }
    return {
      ...result,
      ...userKeybindings.value
    };
  });
  const keybindings = computed(
    () => Object.values(keybindingByKeyCombo.value)
  );
  function getKeybinding(combo) {
    return keybindingByKeyCombo.value[combo.serialize()];
  }
  __name(getKeybinding, "getKeybinding");
  const keybindingsByCommandId = computed(
    () => {
      return _.groupBy(keybindings.value, "commandId");
    }
  );
  function getKeybindingsByCommandId(commandId) {
    return keybindingsByCommandId.value[commandId] ?? [];
  }
  __name(getKeybindingsByCommandId, "getKeybindingsByCommandId");
  const defaultKeybindingsByCommandId = computed(() => {
    return _.groupBy(Object.values(defaultKeybindings.value), "commandId");
  });
  function getKeybindingByCommandId(commandId) {
    return getKeybindingsByCommandId(commandId)[0];
  }
  __name(getKeybindingByCommandId, "getKeybindingByCommandId");
  function addKeybinding(target, keybinding, { existOk = false }) {
    if (!existOk && keybinding.combo.serialize() in target.value) {
      throw new Error(
        `Keybinding on ${keybinding.combo} already exists on ${target.value[keybinding.combo.serialize()].commandId}`
      );
    }
    target.value[keybinding.combo.serialize()] = keybinding;
  }
  __name(addKeybinding, "addKeybinding");
  function addDefaultKeybinding(keybinding) {
    addKeybinding(defaultKeybindings, keybinding, { existOk: false });
  }
  __name(addDefaultKeybinding, "addDefaultKeybinding");
  function addUserKeybinding(keybinding) {
    const defaultKeybinding = defaultKeybindings.value[keybinding.combo.serialize()];
    const userUnsetKeybinding = userUnsetKeybindings.value[keybinding.combo.serialize()];
    if (keybinding.equals(defaultKeybinding) && keybinding.equals(userUnsetKeybinding)) {
      delete userUnsetKeybindings.value[keybinding.combo.serialize()];
      return;
    }
    if (defaultKeybinding && !defaultKeybinding.equals(userUnsetKeybinding)) {
      unsetKeybinding(defaultKeybinding);
    }
    addKeybinding(userKeybindings, keybinding, { existOk: true });
  }
  __name(addUserKeybinding, "addUserKeybinding");
  function unsetKeybinding(keybinding) {
    const serializedCombo = keybinding.combo.serialize();
    if (!(serializedCombo in keybindingByKeyCombo.value)) {
      console.warn(
        `Trying to unset non-exist keybinding: ${JSON.stringify(keybinding)}`
      );
      return;
    }
    if (userKeybindings.value[serializedCombo]?.equals(keybinding)) {
      delete userKeybindings.value[serializedCombo];
      return;
    }
    if (defaultKeybindings.value[serializedCombo]?.equals(keybinding)) {
      addKeybinding(userUnsetKeybindings, keybinding, { existOk: false });
      return;
    }
    console.warn(`Unset unknown keybinding: ${JSON.stringify(keybinding)}`);
  }
  __name(unsetKeybinding, "unsetKeybinding");
  function updateKeybindingOnCommand(keybinding) {
    const currentKeybinding = getKeybindingByCommandId(keybinding.commandId);
    if (currentKeybinding?.equals(keybinding)) {
      return false;
    }
    if (currentKeybinding) {
      unsetKeybinding(currentKeybinding);
    }
    addUserKeybinding(keybinding);
    return true;
  }
  __name(updateKeybindingOnCommand, "updateKeybindingOnCommand");
  function resetAllKeybindings() {
    userKeybindings.value = {};
    userUnsetKeybindings.value = {};
  }
  __name(resetAllKeybindings, "resetAllKeybindings");
  function resetKeybindingForCommand(commandId) {
    const currentKeybinding = getKeybindingByCommandId(commandId);
    const defaultKeybinding = defaultKeybindingsByCommandId.value[commandId]?.[0];
    if (!defaultKeybinding) {
      if (currentKeybinding) {
        unsetKeybinding(currentKeybinding);
        return true;
      }
      return false;
    }
    if (currentKeybinding?.equals(defaultKeybinding)) {
      return false;
    }
    if (currentKeybinding) {
      unsetKeybinding(currentKeybinding);
    }
    const serializedCombo = defaultKeybinding.combo.serialize();
    if (userUnsetKeybindings.value[serializedCombo]?.equals(defaultKeybinding)) {
      delete userUnsetKeybindings.value[serializedCombo];
    }
    return true;
  }
  __name(resetKeybindingForCommand, "resetKeybindingForCommand");
  function isCommandKeybindingModified(commandId) {
    const currentKeybinding = getKeybindingByCommandId(commandId);
    const defaultKeybinding = defaultKeybindingsByCommandId.value[commandId]?.[0];
    return !(currentKeybinding === void 0 && defaultKeybinding === void 0 || currentKeybinding?.equals(defaultKeybinding));
  }
  __name(isCommandKeybindingModified, "isCommandKeybindingModified");
  return {
    keybindings,
    getUserKeybindings,
    getUserUnsetKeybindings,
    getKeybinding,
    getKeybindingsByCommandId,
    getKeybindingByCommandId,
    addDefaultKeybinding,
    addUserKeybinding,
    unsetKeybinding,
    updateKeybindingOnCommand,
    resetAllKeybindings,
    resetKeybindingForCommand,
    isCommandKeybindingModified
  };
});
class ComfyCommandImpl {
  static {
    __name(this, "ComfyCommandImpl");
  }
  id;
  function;
  _label;
  _icon;
  _tooltip;
  _menubarLabel;
  versionAdded;
  confirmation;
  source;
  constructor(command2) {
    this.id = command2.id;
    this.function = command2.function;
    this._label = command2.label;
    this._icon = command2.icon;
    this._tooltip = command2.tooltip;
    this._menubarLabel = command2.menubarLabel ?? command2.label;
    this.versionAdded = command2.versionAdded;
    this.confirmation = command2.confirmation;
    this.source = command2.source;
  }
  get label() {
    return typeof this._label === "function" ? this._label() : this._label;
  }
  get icon() {
    return typeof this._icon === "function" ? this._icon() : this._icon;
  }
  get tooltip() {
    return typeof this._tooltip === "function" ? this._tooltip() : this._tooltip;
  }
  get menubarLabel() {
    return typeof this._menubarLabel === "function" ? this._menubarLabel() : this._menubarLabel;
  }
  get keybinding() {
    return useKeybindingStore().getKeybindingByCommandId(this.id);
  }
}
const useCommandStore = /* @__PURE__ */ defineStore("command", () => {
  const commandsById = ref$3({});
  const commands2 = computed(() => Object.values(commandsById.value));
  const registerCommand = /* @__PURE__ */ __name((command2) => {
    if (commandsById.value[command2.id]) {
      console.warn(`Command ${command2.id} already registered`);
    }
    commandsById.value[command2.id] = new ComfyCommandImpl(command2);
  }, "registerCommand");
  const registerCommands = /* @__PURE__ */ __name((commands22) => {
    for (const command2 of commands22) {
      registerCommand(command2);
    }
  }, "registerCommands");
  const getCommand = /* @__PURE__ */ __name((command2) => {
    return commandsById.value[command2];
  }, "getCommand");
  const { wrapWithErrorHandlingAsync } = useErrorHandling();
  const execute = /* @__PURE__ */ __name(async (commandId, errorHandler2) => {
    const command2 = getCommand(commandId);
    if (command2) {
      await wrapWithErrorHandlingAsync(command2.function, errorHandler2)();
    } else {
      throw new Error(`Command ${commandId} not found`);
    }
  }, "execute");
  const isRegistered = /* @__PURE__ */ __name((command2) => {
    return !!commandsById.value[command2];
  }, "isRegistered");
  const loadExtensionCommands = /* @__PURE__ */ __name((extension) => {
    if (extension.commands) {
      for (const command2 of extension.commands) {
        registerCommand({
          ...command2,
          source: extension.name
        });
      }
    }
  }, "loadExtensionCommands");
  return {
    commands: commands2,
    execute,
    getCommand,
    registerCommand,
    registerCommands,
    isRegistered,
    loadExtensionCommands
  };
});
const COMFY_API_BASE_URL = true ? "https://api.comfy.org" : "https://stagingapi.comfy.org";
const COMFY_PLATFORM_BASE_URL = true ? "https://platform.comfy.org" : "https://stagingplatform.comfy.org";
const STORAGE_KEY = "comfy_api_key";
const useApiKeyAuthStore = /* @__PURE__ */ defineStore("apiKeyAuth", () => {
  const firebaseAuthStore = useFirebaseAuthStore();
  const apiKey = useLocalStorage(STORAGE_KEY, null);
  const toastStore = useToastStore();
  const { wrapWithErrorHandlingAsync, toastErrorHandler } = useErrorHandling();
  const currentUser = ref$3(null);
  const isAuthenticated = computed(() => !!currentUser.value);
  const initializeUserFromApiKey = /* @__PURE__ */ __name(async () => {
    const createCustomerResponse = await firebaseAuthStore.createCustomer();
    if (!createCustomerResponse) {
      apiKey.value = null;
      throw new Error(t("auth.login.noAssociatedUser"));
    }
    currentUser.value = createCustomerResponse;
  }, "initializeUserFromApiKey");
  watch(
    apiKey,
    () => {
      if (apiKey.value) {
        void initializeUserFromApiKey();
      } else {
        currentUser.value = null;
      }
    },
    { immediate: true }
  );
  const reportError = /* @__PURE__ */ __name((error2) => {
    if (error2 instanceof Error && error2.message === "STORAGE_FAILED") {
      toastStore.add({
        severity: "error",
        summary: t("auth.apiKey.storageFailed"),
        detail: t("auth.apiKey.storageFailedDetail")
      });
    } else {
      toastErrorHandler(error2);
    }
  }, "reportError");
  const storeApiKey = wrapWithErrorHandlingAsync(async (newApiKey) => {
    apiKey.value = newApiKey;
    toastStore.add({
      severity: "success",
      summary: t("auth.apiKey.stored"),
      detail: t("auth.apiKey.storedDetail"),
      life: 5e3
    });
    return true;
  }, reportError);
  const clearStoredApiKey = wrapWithErrorHandlingAsync(async () => {
    apiKey.value = null;
    toastStore.add({
      severity: "success",
      summary: t("auth.apiKey.cleared"),
      detail: t("auth.apiKey.clearedDetail"),
      life: 5e3
    });
    return true;
  }, reportError);
  const getApiKey = /* @__PURE__ */ __name(() => apiKey.value, "getApiKey");
  const getAuthHeader = /* @__PURE__ */ __name(() => {
    const comfyOrgApiKey = getApiKey();
    if (comfyOrgApiKey) {
      return {
        "X-API-KEY": comfyOrgApiKey
      };
    }
    return null;
  }, "getAuthHeader");
  return {
    // State
    currentUser,
    isAuthenticated,
    // Actions
    storeApiKey,
    clearStoredApiKey,
    getAuthHeader,
    getApiKey
  };
});
class FirebaseAuthStoreError extends Error {
  static {
    __name(this, "FirebaseAuthStoreError");
  }
  constructor(message) {
    super(message);
    this.name = "FirebaseAuthStoreError";
  }
}
const useFirebaseAuthStore = /* @__PURE__ */ defineStore("firebaseAuth", () => {
  const loading = ref$3(false);
  const currentUser = ref$3(null);
  const isInitialized2 = ref$3(false);
  const customerCreated = ref$3(false);
  const isFetchingBalance = ref$3(false);
  const balance = ref$3(null);
  const lastBalanceUpdateTime = ref$3(null);
  const googleProvider = new GoogleAuthProvider();
  googleProvider.setCustomParameters({
    prompt: "select_account"
  });
  const githubProvider = new GithubAuthProvider();
  githubProvider.setCustomParameters({
    prompt: "select_account"
  });
  const isAuthenticated = computed(() => !!currentUser.value);
  const userEmail = computed(() => currentUser.value?.email);
  const userId = computed(() => currentUser.value?.uid);
  const auth2 = useFirebaseAuth();
  void setPersistence(auth2, browserLocalPersistence);
  onAuthStateChanged(auth2, (user) => {
    currentUser.value = user;
    isInitialized2.value = true;
    balance.value = null;
    lastBalanceUpdateTime.value = null;
  });
  const getIdToken2 = /* @__PURE__ */ __name(async () => {
    if (currentUser.value) {
      return currentUser.value.getIdToken();
    }
    return null;
  }, "getIdToken");
  const getAuthHeader = /* @__PURE__ */ __name(async () => {
    const token = await getIdToken2();
    if (token) {
      return {
        Authorization: `Bearer ${token}`
      };
    }
    return useApiKeyAuthStore().getAuthHeader();
  }, "getAuthHeader");
  const fetchBalance = /* @__PURE__ */ __name(async () => {
    isFetchingBalance.value = true;
    try {
      const authHeader = await getAuthHeader();
      if (!authHeader) {
        throw new FirebaseAuthStoreError(
          t("toastMessages.userNotAuthenticated")
        );
      }
      const response = await fetch(`${COMFY_API_BASE_URL}/customers/balance`, {
        headers: {
          ...authHeader,
          "Content-Type": "application/json"
        }
      });
      if (!response.ok) {
        if (response.status === 404) {
          return null;
        }
        const errorData = await response.json();
        throw new FirebaseAuthStoreError(
          t("toastMessages.failedToFetchBalance", {
            error: errorData.message
          })
        );
      }
      const balanceData = await response.json();
      lastBalanceUpdateTime.value = /* @__PURE__ */ new Date();
      balance.value = balanceData;
      return balanceData;
    } finally {
      isFetchingBalance.value = false;
    }
  }, "fetchBalance");
  const createCustomer = /* @__PURE__ */ __name(async () => {
    const authHeader = await getAuthHeader();
    if (!authHeader) {
      throw new FirebaseAuthStoreError(t("toastMessages.userNotAuthenticated"));
    }
    const createCustomerRes = await fetch(`${COMFY_API_BASE_URL}/customers`, {
      method: "POST",
      headers: {
        ...authHeader,
        "Content-Type": "application/json"
      }
    });
    if (!createCustomerRes.ok) {
      throw new FirebaseAuthStoreError(
        t("toastMessages.failedToCreateCustomer", {
          error: createCustomerRes.statusText
        })
      );
    }
    const createCustomerResJson = await createCustomerRes.json();
    if (!createCustomerResJson?.id) {
      throw new FirebaseAuthStoreError(
        t("toastMessages.failedToCreateCustomer", {
          error: "No customer ID returned"
        })
      );
    }
    return createCustomerResJson;
  }, "createCustomer");
  const executeAuthAction = /* @__PURE__ */ __name(async (action, options2 = {}) => {
    loading.value = true;
    try {
      const result = await action(auth2);
      if (options2?.createCustomer) {
        const token = await getIdToken2();
        if (!token) {
          throw new Error("Cannot create customer: User not authenticated");
        }
        await createCustomer();
      }
      return result;
    } finally {
      loading.value = false;
    }
  }, "executeAuthAction");
  const login = /* @__PURE__ */ __name(async (email, password) => executeAuthAction(
    (authInstance) => signInWithEmailAndPassword(authInstance, email, password),
    { createCustomer: true }
  ), "login");
  const register2 = /* @__PURE__ */ __name(async (email, password) => {
    return executeAuthAction(
      (authInstance) => createUserWithEmailAndPassword(authInstance, email, password),
      { createCustomer: true }
    );
  }, "register");
  const loginWithGoogle = /* @__PURE__ */ __name(async () => executeAuthAction(
    (authInstance) => signInWithPopup(authInstance, googleProvider),
    { createCustomer: true }
  ), "loginWithGoogle");
  const loginWithGithub = /* @__PURE__ */ __name(async () => executeAuthAction(
    (authInstance) => signInWithPopup(authInstance, githubProvider),
    { createCustomer: true }
  ), "loginWithGithub");
  const logout = /* @__PURE__ */ __name(async () => executeAuthAction((authInstance) => signOut(authInstance)), "logout");
  const sendPasswordReset = /* @__PURE__ */ __name(async (email) => executeAuthAction(
    (authInstance) => sendPasswordResetEmail(authInstance, email)
  ), "sendPasswordReset");
  const _updatePassword = /* @__PURE__ */ __name(async (newPassword) => {
    if (!currentUser.value) {
      throw new FirebaseAuthStoreError(t("toastMessages.userNotAuthenticated"));
    }
    await updatePassword(currentUser.value, newPassword);
  }, "_updatePassword");
  const addCredits = /* @__PURE__ */ __name(async (requestBodyContent) => {
    const authHeader = await getAuthHeader();
    if (!authHeader) {
      throw new FirebaseAuthStoreError(t("toastMessages.userNotAuthenticated"));
    }
    if (!customerCreated.value) {
      await createCustomer();
      customerCreated.value = true;
    }
    const response = await fetch(`${COMFY_API_BASE_URL}/customers/credit`, {
      method: "POST",
      headers: {
        ...authHeader,
        "Content-Type": "application/json"
      },
      body: JSON.stringify(requestBodyContent)
    });
    if (!response.ok) {
      const errorData = await response.json();
      throw new FirebaseAuthStoreError(
        t("toastMessages.failedToInitiateCreditPurchase", {
          error: errorData.message
        })
      );
    }
    return response.json();
  }, "addCredits");
  const initiateCreditPurchase = /* @__PURE__ */ __name(async (requestBodyContent) => executeAuthAction((_2) => addCredits(requestBodyContent)), "initiateCreditPurchase");
  const accessBillingPortal = /* @__PURE__ */ __name(async (requestBody) => {
    const authHeader = await getAuthHeader();
    if (!authHeader) {
      throw new FirebaseAuthStoreError(t("toastMessages.userNotAuthenticated"));
    }
    const response = await fetch(`${COMFY_API_BASE_URL}/customers/billing`, {
      method: "POST",
      headers: {
        ...authHeader,
        "Content-Type": "application/json"
      },
      ...requestBody && {
        body: JSON.stringify(requestBody)
      }
    });
    if (!response.ok) {
      const errorData = await response.json();
      throw new FirebaseAuthStoreError(
        t("toastMessages.failedToAccessBillingPortal", {
          error: errorData.message
        })
      );
    }
    return response.json();
  }, "accessBillingPortal");
  return {
    // State
    loading,
    currentUser,
    isInitialized: isInitialized2,
    balance,
    lastBalanceUpdateTime,
    isFetchingBalance,
    // Getters
    isAuthenticated,
    userEmail,
    userId,
    // Actions
    login,
    register: register2,
    logout,
    createCustomer,
    getIdToken: getIdToken2,
    loginWithGoogle,
    loginWithGithub,
    initiateCreditPurchase,
    fetchBalance,
    accessBillingPortal,
    sendPasswordReset,
    updatePassword: _updatePassword,
    getAuthHeader
  };
});
const useSystemStatsStore = /* @__PURE__ */ defineStore("systemStats", () => {
  const systemStats = ref$3(null);
  const isLoading = ref$3(false);
  const error2 = ref$3(null);
  async function fetchSystemStats() {
    isLoading.value = true;
    error2.value = null;
    try {
      systemStats.value = await api.getSystemStats();
    } catch (err) {
      error2.value = err instanceof Error ? err.message : "An error occurred while fetching system stats";
      console.error("Error fetching system stats:", err);
    } finally {
      isLoading.value = false;
    }
  }
  __name(fetchSystemStats, "fetchSystemStats");
  return {
    systemStats,
    isLoading,
    error: error2,
    fetchSystemStats
  };
});
function generateErrorReport(error2) {
  const MAX_JSON_LENGTH = 2e4;
  const workflowJSONString = JSON.stringify(error2.workflow);
  const workflowText = workflowJSONString.length > MAX_JSON_LENGTH ? "Workflow too large. Please manually upload the workflow from local file system." : workflowJSONString;
  const systemStats = error2.systemStats;
  return `
# ComfyUI Error Report
${error2 ? `## Error Details
- **Node ID:** ${error2.nodeId || "N/A"}
- **Node Type:** ${error2.nodeType || "N/A"}
- **Exception Type:** ${error2.exceptionType || "N/A"}
- **Exception Message:** ${error2.exceptionMessage || "N/A"}
## Stack Trace
\`\`\`
${error2.traceback || "No stack trace available"}
\`\`\`` : ""}
## System Information
- **ComfyUI Version:** ${systemStats.system.comfyui_version}
- **Arguments:** ${systemStats.system.argv.join(" ")}
- **OS:** ${systemStats.system.os}
- **Python Version:** ${systemStats.system.python_version}
- **Embedded Python:** ${systemStats.system.embedded_python}
- **PyTorch Version:** ${systemStats.system.pytorch_version}
## Devices
${systemStats.devices.map(
    (device) => `
- **Name:** ${device.name}
  - **Type:** ${device.type}
  - **VRAM Total:** ${device.vram_total}
  - **VRAM Free:** ${device.vram_free}
  - **Torch VRAM Total:** ${device.torch_vram_total}
  - **Torch VRAM Free:** ${device.torch_vram_free}
`
  ).join("\n")}
## Logs
\`\`\`
${error2.serverLogs}
\`\`\`
## Attached Workflow
Please make sure that workflow does not contain any sensitive information such as API keys or passwords.
\`\`\`
${workflowText}
\`\`\`

## Additional Context
(Please add any additional context or steps to reproduce the error here)
`;
}
__name(generateErrorReport, "generateErrorReport");
function classNames(...args) {
  if (args) {
    let classes2 = [];
    for (let i2 = 0; i2 < args.length; i2++) {
      let className = args[i2];
      if (!className) {
        continue;
      }
      const type = typeof className;
      if (type === "string" || type === "number") {
        classes2.push(className);
      } else if (type === "object") {
        const _classes = Array.isArray(className) ? [classNames(...className)] : Object.entries(className).map(([key, value]) => value ? key : void 0);
        classes2 = _classes.length ? classes2.concat(_classes.filter((c2) => !!c2)) : classes2;
      }
    }
    return classes2.join(" ").trim();
  }
  return void 0;
}
__name(classNames, "classNames");
function hasClass(element, className) {
  if (element) {
    if (element.classList) return element.classList.contains(className);
    else return new RegExp("(^| )" + className + "( |$)", "gi").test(element.className);
  }
  return false;
}
__name(hasClass, "hasClass");
function addClass(element, className) {
  if (element && className) {
    const fn = /* @__PURE__ */ __name((_className) => {
      if (!hasClass(element, _className)) {
        if (element.classList) element.classList.add(_className);
        else element.className += " " + _className;
      }
    }, "fn");
    [className].flat().filter(Boolean).forEach((_classNames) => _classNames.split(" ").forEach(fn));
  }
}
__name(addClass, "addClass");
function calculateBodyScrollbarWidth() {
  return window.innerWidth - document.documentElement.offsetWidth;
}
__name(calculateBodyScrollbarWidth, "calculateBodyScrollbarWidth");
function getCSSVariableByRegex(variableRegex) {
  for (const sheet of document == null ? void 0 : document.styleSheets) {
    try {
      for (const rule of sheet == null ? void 0 : sheet.cssRules) {
        for (const property of rule == null ? void 0 : rule.style) {
          if (variableRegex.test(property)) {
            return { name: property, value: rule.style.getPropertyValue(property).trim() };
          }
        }
      }
    } catch (e2) {
    }
  }
  return null;
}
__name(getCSSVariableByRegex, "getCSSVariableByRegex");
function blockBodyScroll(className = "p-overflow-hidden") {
  const variableData = getCSSVariableByRegex(/-scrollbar-width$/);
  (variableData == null ? void 0 : variableData.name) && document.body.style.setProperty(variableData.name, calculateBodyScrollbarWidth() + "px");
  addClass(document.body, className);
}
__name(blockBodyScroll, "blockBodyScroll");
function saveAs(file) {
  if (file) {
    let link2 = document.createElement("a");
    if (link2.download !== void 0) {
      const { name: name2, src } = file;
      link2.setAttribute("href", src);
      link2.setAttribute("download", name2);
      link2.style.display = "none";
      document.body.appendChild(link2);
      link2.click();
      document.body.removeChild(link2);
      return true;
    }
  }
  return false;
}
__name(saveAs, "saveAs");
function exportCSV(csv, filename) {
  let blob = new Blob([csv], {
    type: "application/csv;charset=utf-8;"
  });
  if (window.navigator.msSaveOrOpenBlob) {
    navigator.msSaveOrOpenBlob(blob, filename + ".csv");
  } else {
    const isDownloaded = saveAs({ name: filename + ".csv", src: URL.createObjectURL(blob) });
    if (!isDownloaded) {
      csv = "data:text/csv;charset=utf-8," + csv;
      window.open(encodeURI(csv));
    }
  }
}
__name(exportCSV, "exportCSV");
function removeClass(element, className) {
  if (element && className) {
    const fn = /* @__PURE__ */ __name((_className) => {
      if (element.classList) element.classList.remove(_className);
      else element.className = element.className.replace(new RegExp("(^|\\b)" + _className.split(" ").join("|") + "(\\b|$)", "gi"), " ");
    }, "fn");
    [className].flat().filter(Boolean).forEach((_classNames) => _classNames.split(" ").forEach(fn));
  }
}
__name(removeClass, "removeClass");
function unblockBodyScroll(className = "p-overflow-hidden") {
  const variableData = getCSSVariableByRegex(/-scrollbar-width$/);
  (variableData == null ? void 0 : variableData.name) && document.body.style.removeProperty(variableData.name);
  removeClass(document.body, className);
}
__name(unblockBodyScroll, "unblockBodyScroll");
function getHiddenElementDimensions(element) {
  let dimensions = { width: 0, height: 0 };
  if (element) {
    element.style.visibility = "hidden";
    element.style.display = "block";
    dimensions.width = element.offsetWidth;
    dimensions.height = element.offsetHeight;
    element.style.display = "none";
    element.style.visibility = "visible";
  }
  return dimensions;
}
__name(getHiddenElementDimensions, "getHiddenElementDimensions");
function getViewport() {
  let win = window, d2 = document, e2 = d2.documentElement, g2 = d2.getElementsByTagName("body")[0], w2 = win.innerWidth || e2.clientWidth || g2.clientWidth, h2 = win.innerHeight || e2.clientHeight || g2.clientHeight;
  return { width: w2, height: h2 };
}
__name(getViewport, "getViewport");
function getWindowScrollLeft() {
  let doc2 = document.documentElement;
  return (window.pageXOffset || doc2.scrollLeft) - (doc2.clientLeft || 0);
}
__name(getWindowScrollLeft, "getWindowScrollLeft");
function getWindowScrollTop() {
  let doc2 = document.documentElement;
  return (window.pageYOffset || doc2.scrollTop) - (doc2.clientTop || 0);
}
__name(getWindowScrollTop, "getWindowScrollTop");
function absolutePosition(element, target, gutter = true) {
  var _a2, _b, _c, _d;
  if (element) {
    const elementDimensions = element.offsetParent ? { width: element.offsetWidth, height: element.offsetHeight } : getHiddenElementDimensions(element);
    const elementOuterHeight = elementDimensions.height;
    const elementOuterWidth = elementDimensions.width;
    const targetOuterHeight = target.offsetHeight;
    const targetOuterWidth = target.offsetWidth;
    const targetOffset = target.getBoundingClientRect();
    const windowScrollTop = getWindowScrollTop();
    const windowScrollLeft = getWindowScrollLeft();
    const viewport = getViewport();
    let top, left, origin2 = "top";
    if (targetOffset.top + targetOuterHeight + elementOuterHeight > viewport.height) {
      top = targetOffset.top + windowScrollTop - elementOuterHeight;
      origin2 = "bottom";
      if (top < 0) {
        top = windowScrollTop;
      }
    } else {
      top = targetOuterHeight + targetOffset.top + windowScrollTop;
    }
    if (targetOffset.left + elementOuterWidth > viewport.width) left = Math.max(0, targetOffset.left + windowScrollLeft + targetOuterWidth - elementOuterWidth);
    else left = targetOffset.left + windowScrollLeft;
    element.style.top = top + "px";
    element.style.left = left + "px";
    element.style.transformOrigin = origin2;
    gutter && (element.style.marginTop = origin2 === "bottom" ? `calc(${(_b = (_a2 = getCSSVariableByRegex(/-anchor-gutter$/)) == null ? void 0 : _a2.value) != null ? _b : "2px"} * -1)` : (_d = (_c = getCSSVariableByRegex(/-anchor-gutter$/)) == null ? void 0 : _c.value) != null ? _d : "");
  }
}
__name(absolutePosition, "absolutePosition");
function addStyle(element, style2) {
  if (element) {
    if (typeof style2 === "string") {
      element.style.cssText = style2;
    } else {
      Object.entries(style2 || {}).forEach(([key, value]) => element.style[key] = value);
    }
  }
}
__name(addStyle, "addStyle");
function getOuterWidth(element, margin) {
  if (element instanceof HTMLElement) {
    let width2 = element.offsetWidth;
    if (margin) {
      let style2 = getComputedStyle(element);
      width2 += parseFloat(style2.marginLeft) + parseFloat(style2.marginRight);
    }
    return width2;
  }
  return 0;
}
__name(getOuterWidth, "getOuterWidth");
function relativePosition(element, target, gutter = true) {
  var _a2, _b, _c, _d;
  if (element) {
    const elementDimensions = element.offsetParent ? { width: element.offsetWidth, height: element.offsetHeight } : getHiddenElementDimensions(element);
    const targetHeight = target.offsetHeight;
    const targetOffset = target.getBoundingClientRect();
    const viewport = getViewport();
    let top, left, origin2 = "top";
    if (targetOffset.top + targetHeight + elementDimensions.height > viewport.height) {
      top = -1 * elementDimensions.height;
      origin2 = "bottom";
      if (targetOffset.top + top < 0) {
        top = -1 * targetOffset.top;
      }
    } else {
      top = targetHeight;
    }
    if (elementDimensions.width > viewport.width) {
      left = targetOffset.left * -1;
    } else if (targetOffset.left + elementDimensions.width > viewport.width) {
      left = (targetOffset.left + elementDimensions.width - viewport.width) * -1;
    } else {
      left = 0;
    }
    element.style.top = top + "px";
    element.style.left = left + "px";
    element.style.transformOrigin = origin2;
    gutter && (element.style.marginTop = origin2 === "bottom" ? `calc(${(_b = (_a2 = getCSSVariableByRegex(/-anchor-gutter$/)) == null ? void 0 : _a2.value) != null ? _b : "2px"} * -1)` : (_d = (_c = getCSSVariableByRegex(/-anchor-gutter$/)) == null ? void 0 : _c.value) != null ? _d : "");
  }
}
__name(relativePosition, "relativePosition");
function alignOverlay(overlay, target, appendTo, calculateMinWidth = true) {
  if (overlay && target) {
    if (appendTo === "self") {
      relativePosition(overlay, target);
    } else {
      calculateMinWidth && (overlay.style.minWidth = getOuterWidth(target) + "px");
      absolutePosition(overlay, target);
    }
  }
}
__name(alignOverlay, "alignOverlay");
function isElement(element) {
  return typeof HTMLElement === "object" ? element instanceof HTMLElement : element && typeof element === "object" && element !== null && element.nodeType === 1 && typeof element.nodeName === "string";
}
__name(isElement, "isElement");
function toElement(element) {
  let target = element;
  if (element && typeof element === "object") {
    if (element.hasOwnProperty("current")) {
      target = element.current;
    } else if (element.hasOwnProperty("el")) {
      if (element.el.hasOwnProperty("nativeElement")) {
        target = element.el.nativeElement;
      } else {
        target = element.el;
      }
    }
  }
  return isElement(target) ? target : void 0;
}
__name(toElement, "toElement");
function appendChild(element, child2) {
  const target = toElement(element);
  if (target) target.appendChild(child2);
  else throw new Error("Cannot append " + child2 + " to " + element);
}
__name(appendChild, "appendChild");
var calculatedScrollbarHeight = void 0;
function calculateScrollbarHeight(element) {
  if (element) {
    let style2 = getComputedStyle(element);
    return element.offsetHeight - element.clientHeight - parseFloat(style2.borderTopWidth) - parseFloat(style2.borderBottomWidth);
  } else {
    if (calculatedScrollbarHeight != null) return calculatedScrollbarHeight;
    let scrollDiv = document.createElement("div");
    addStyle(scrollDiv, {
      width: "100px",
      height: "100px",
      overflow: "scroll",
      position: "absolute",
      top: "-9999px"
    });
    document.body.appendChild(scrollDiv);
    let scrollbarHeight = scrollDiv.offsetHeight - scrollDiv.clientHeight;
    document.body.removeChild(scrollDiv);
    calculatedScrollbarHeight = scrollbarHeight;
    return scrollbarHeight;
  }
}
__name(calculateScrollbarHeight, "calculateScrollbarHeight");
var calculatedScrollbarWidth = void 0;
function calculateScrollbarWidth(element) {
  if (element) {
    let style2 = getComputedStyle(element);
    return element.offsetWidth - element.clientWidth - parseFloat(style2.borderLeftWidth) - parseFloat(style2.borderRightWidth);
  } else {
    if (calculatedScrollbarWidth != null) return calculatedScrollbarWidth;
    let scrollDiv = document.createElement("div");
    addStyle(scrollDiv, {
      width: "100px",
      height: "100px",
      overflow: "scroll",
      position: "absolute",
      top: "-9999px"
    });
    document.body.appendChild(scrollDiv);
    let scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;
    document.body.removeChild(scrollDiv);
    calculatedScrollbarWidth = scrollbarWidth;
    return scrollbarWidth;
  }
}
__name(calculateScrollbarWidth, "calculateScrollbarWidth");
function clearSelection() {
  if (window.getSelection) {
    const selection = window.getSelection() || {};
    if (selection.empty) {
      selection.empty();
    } else if (selection.removeAllRanges && selection.rangeCount > 0 && selection.getRangeAt(0).getClientRects().length > 0) {
      selection.removeAllRanges();
    }
  }
}
__name(clearSelection, "clearSelection");
function setAttributes(element, attributes = {}) {
  if (isElement(element)) {
    const computedStyles = /* @__PURE__ */ __name((rule, value) => {
      var _a2, _b;
      const styles = ((_a2 = element == null ? void 0 : element.$attrs) == null ? void 0 : _a2[rule]) ? [(_b = element == null ? void 0 : element.$attrs) == null ? void 0 : _b[rule]] : [];
      return [value].flat().reduce((cv, v2) => {
        if (v2 !== null && v2 !== void 0) {
          const type = typeof v2;
          if (type === "string" || type === "number") {
            cv.push(v2);
          } else if (type === "object") {
            const _cv = Array.isArray(v2) ? computedStyles(rule, v2) : Object.entries(v2).map(([_k, _v]) => rule === "style" && (!!_v || _v === 0) ? `${_k.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase()}:${_v}` : !!_v ? _k : void 0);
            cv = _cv.length ? cv.concat(_cv.filter((c2) => !!c2)) : cv;
          }
        }
        return cv;
      }, styles);
    }, "computedStyles");
    Object.entries(attributes).forEach(([key, value]) => {
      if (value !== void 0 && value !== null) {
        const matchedEvent = key.match(/^on(.+)/);
        if (matchedEvent) {
          element.addEventListener(matchedEvent[1].toLowerCase(), value);
        } else if (key === "p-bind" || key === "pBind") {
          setAttributes(element, value);
        } else {
          value = key === "class" ? [...new Set(computedStyles("class", value))].join(" ").trim() : key === "style" ? computedStyles("style", value).join(";").trim() : value;
          (element.$attrs = element.$attrs || {}) && (element.$attrs[key] = value);
          element.setAttribute(key, value);
        }
      }
    });
  }
}
__name(setAttributes, "setAttributes");
function createElement(type, attributes = {}, ...children) {
  if (type) {
    const element = document.createElement(type);
    setAttributes(element, attributes);
    element.append(...children);
    return element;
  }
  return void 0;
}
__name(createElement, "createElement");
function createStyleAsString(css3, options2 = {}) {
  return css3 ? `'<style ${Object.entries(options2).reduce((s2, [k2, v2]) => s2 + `${k2}="${v2}"`, " ")}>${css3}</style>'` : "";
}
__name(createStyleAsString, "createStyleAsString");
function createStyleTag$1(attributes = {}, container) {
  let element = document.createElement("style");
  setAttributes(element, attributes);
  if (!container) {
    container = document.head;
  }
  container.appendChild(element);
  return element;
}
__name(createStyleTag$1, "createStyleTag$1");
function fadeIn(element, duration) {
  if (element) {
    element.style.opacity = "0";
    let last = +/* @__PURE__ */ new Date();
    let opacity = "0";
    let tick = /* @__PURE__ */ __name(function() {
      opacity = `${+element.style.opacity + ((/* @__PURE__ */ new Date()).getTime() - last) / duration}`;
      element.style.opacity = opacity;
      last = +/* @__PURE__ */ new Date();
      if (+opacity < 1) {
        !!window.requestAnimationFrame && requestAnimationFrame(tick) || setTimeout(tick, 16);
      }
    }, "tick");
    tick();
  }
}
__name(fadeIn, "fadeIn");
function fadeOut(element, duration) {
  if (element) {
    let opacity = 1, interval = 50, gap = interval / duration;
    let fading = setInterval(() => {
      opacity -= gap;
      if (opacity <= 0) {
        opacity = 0;
        clearInterval(fading);
      }
      element.style.opacity = opacity.toString();
    }, interval);
  }
}
__name(fadeOut, "fadeOut");
function find$1(element, selector) {
  return isElement(element) ? Array.from(element.querySelectorAll(selector)) : [];
}
__name(find$1, "find$1");
function findSingle(element, selector) {
  return isElement(element) ? element.matches(selector) ? element : element.querySelector(selector) : null;
}
__name(findSingle, "findSingle");
function focus$1(element, options2) {
  element && document.activeElement !== element && element.focus(options2);
}
__name(focus$1, "focus$1");
function getAttribute(element, name2) {
  if (isElement(element)) {
    const value = element.getAttribute(name2);
    if (!isNaN(value)) {
      return +value;
    }
    if (value === "true" || value === "false") {
      return value === "true";
    }
    return value;
  }
  return void 0;
}
__name(getAttribute, "getAttribute");
function resolveUserAgent() {
  let ua = navigator.userAgent.toLowerCase();
  let match2 = /(chrome)[ ]([\w.]+)/.exec(ua) || /(webkit)[ ]([\w.]+)/.exec(ua) || /(opera)(?:.*version|)[ ]([\w.]+)/.exec(ua) || /(msie) ([\w.]+)/.exec(ua) || ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua) || [];
  return {
    browser: match2[1] || "",
    version: match2[2] || "0"
  };
}
__name(resolveUserAgent, "resolveUserAgent");
var browser$1 = null;
function getBrowser() {
  if (!browser$1) {
    browser$1 = {};
    let matched = resolveUserAgent();
    if (matched.browser) {
      browser$1[matched.browser] = true;
      browser$1["version"] = matched.version;
    }
    if (browser$1["chrome"]) {
      browser$1["webkit"] = true;
    } else if (browser$1["webkit"]) {
      browser$1["safari"] = true;
    }
  }
  return browser$1;
}
__name(getBrowser, "getBrowser");
function getBrowserLanguage() {
  return navigator.languages && navigator.languages.length && navigator.languages[0] || navigator.language || "en";
}
__name(getBrowserLanguage, "getBrowserLanguage");
function getCSSProperty(element, property, inline2) {
  var _a2;
  if (element && property) {
    return inline2 ? (_a2 = element == null ? void 0 : element.style) == null ? void 0 : _a2.getPropertyValue(property) : getComputedStyle(element).getPropertyValue(property);
  }
  return null;
}
__name(getCSSProperty, "getCSSProperty");
function getCursorOffset(element, prevText, nextText, currentText) {
  if (element) {
    let style2 = getComputedStyle(element);
    let ghostDiv = document.createElement("div");
    ghostDiv.style.position = "absolute";
    ghostDiv.style.top = "0px";
    ghostDiv.style.left = "0px";
    ghostDiv.style.visibility = "hidden";
    ghostDiv.style.pointerEvents = "none";
    ghostDiv.style.overflow = style2.overflow;
    ghostDiv.style.width = style2.width;
    ghostDiv.style.height = style2.height;
    ghostDiv.style.padding = style2.padding;
    ghostDiv.style.border = style2.border;
    ghostDiv.style.overflowWrap = style2.overflowWrap;
    ghostDiv.style.whiteSpace = style2.whiteSpace;
    ghostDiv.style.lineHeight = style2.lineHeight;
    ghostDiv.innerHTML = prevText.replace(/\r\n|\r|\n/g, "<br />");
    let ghostSpan = document.createElement("span");
    ghostSpan.textContent = currentText;
    ghostDiv.appendChild(ghostSpan);
    let text2 = document.createTextNode(nextText);
    ghostDiv.appendChild(text2);
    document.body.appendChild(ghostDiv);
    const { offsetLeft, offsetTop, clientHeight } = ghostSpan;
    document.body.removeChild(ghostDiv);
    return {
      left: Math.abs(offsetLeft - element.scrollLeft),
      top: Math.abs(offsetTop - element.scrollTop) + clientHeight
    };
  }
  return {
    top: "auto",
    left: "auto"
  };
}
__name(getCursorOffset, "getCursorOffset");
function getFocusableElements(element, selector = "") {
  let focusableElements = find$1(
    element,
    `button:not([tabindex = "-1"]):not([disabled]):not([style*="display:none"]):not([hidden])${selector},
            [href][clientHeight][clientWidth]:not([tabindex = "-1"]):not([disabled]):not([style*="display:none"]):not([hidden])${selector},
            input:not([tabindex = "-1"]):not([disabled]):not([style*="display:none"]):not([hidden])${selector},
            select:not([tabindex = "-1"]):not([disabled]):not([style*="display:none"]):not([hidden])${selector},
            textarea:not([tabindex = "-1"]):not([disabled]):not([style*="display:none"]):not([hidden])${selector},
            [tabIndex]:not([tabIndex = "-1"]):not([disabled]):not([style*="display:none"]):not([hidden])${selector},
            [contenteditable]:not([tabIndex = "-1"]):not([disabled]):not([style*="display:none"]):not([hidden])${selector}`
  );
  let visibleFocusableElements = [];
  for (let focusableElement of focusableElements) {
    if (getComputedStyle(focusableElement).display != "none" && getComputedStyle(focusableElement).visibility != "hidden") visibleFocusableElements.push(focusableElement);
  }
  return visibleFocusableElements;
}
__name(getFocusableElements, "getFocusableElements");
function getFirstFocusableElement(element, selector) {
  const focusableElements = getFocusableElements(element, selector);
  return focusableElements.length > 0 ? focusableElements[0] : null;
}
__name(getFirstFocusableElement, "getFirstFocusableElement");
function getHeight(element) {
  if (element) {
    let height = element.offsetHeight;
    let style2 = getComputedStyle(element);
    height -= parseFloat(style2.paddingTop) + parseFloat(style2.paddingBottom) + parseFloat(style2.borderTopWidth) + parseFloat(style2.borderBottomWidth);
    return height;
  }
  return 0;
}
__name(getHeight, "getHeight");
function getHiddenElementOuterHeight(element) {
  if (element) {
    element.style.visibility = "hidden";
    element.style.display = "block";
    let elementHeight = element.offsetHeight;
    element.style.display = "none";
    element.style.visibility = "visible";
    return elementHeight;
  }
  return 0;
}
__name(getHiddenElementOuterHeight, "getHiddenElementOuterHeight");
function getHiddenElementOuterWidth(element) {
  if (element) {
    element.style.visibility = "hidden";
    element.style.display = "block";
    let elementWidth = element.offsetWidth;
    element.style.display = "none";
    element.style.visibility = "visible";
    return elementWidth;
  }
  return 0;
}
__name(getHiddenElementOuterWidth, "getHiddenElementOuterWidth");
function getParentNode(element) {
  if (element) {
    let parent2 = element.parentNode;
    if (parent2 && parent2 instanceof ShadowRoot && parent2.host) {
      parent2 = parent2.host;
    }
    return parent2;
  }
  return null;
}
__name(getParentNode, "getParentNode");
function getIndex(element) {
  var _a2;
  if (element) {
    let children = (_a2 = getParentNode(element)) == null ? void 0 : _a2.childNodes;
    let num = 0;
    if (children) {
      for (let i2 = 0; i2 < children.length; i2++) {
        if (children[i2] === element) return num;
        if (children[i2].nodeType === 1) num++;
      }
    }
  }
  return -1;
}
__name(getIndex, "getIndex");
function getInnerWidth(element) {
  if (element) {
    let width2 = element.offsetWidth;
    let style2 = getComputedStyle(element);
    width2 -= parseFloat(style2.borderLeft) + parseFloat(style2.borderRight);
    return width2;
  }
  return 0;
}
__name(getInnerWidth, "getInnerWidth");
function getLastFocusableElement(element, selector) {
  const focusableElements = getFocusableElements(element, selector);
  return focusableElements.length > 0 ? focusableElements[focusableElements.length - 1] : null;
}
__name(getLastFocusableElement, "getLastFocusableElement");
function getNextElementSibling(element, selector) {
  let nextElement = element.nextElementSibling;
  while (nextElement) {
    if (nextElement.matches(selector)) {
      return nextElement;
    } else {
      nextElement = nextElement.nextElementSibling;
    }
  }
  return null;
}
__name(getNextElementSibling, "getNextElementSibling");
function getNextFocusableElement(container, element, selector) {
  const focusableElements = getFocusableElements(container, selector);
  const index2 = focusableElements.length > 0 ? focusableElements.findIndex((el) => el === element) : -1;
  const nextIndex = index2 > -1 && focusableElements.length >= index2 + 1 ? index2 + 1 : -1;
  return nextIndex > -1 ? focusableElements[nextIndex] : null;
}
__name(getNextFocusableElement, "getNextFocusableElement");
function getOffset(element) {
  if (element) {
    let rect = element.getBoundingClientRect();
    return {
      top: rect.top + (window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0),
      left: rect.left + (window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0)
    };
  }
  return {
    top: "auto",
    left: "auto"
  };
}
__name(getOffset, "getOffset");
function getOuterHeight(element, margin) {
  if (element) {
    let height = element.offsetHeight;
    if (margin) {
      let style2 = getComputedStyle(element);
      height += parseFloat(style2.marginTop) + parseFloat(style2.marginBottom);
    }
    return height;
  }
  return 0;
}
__name(getOuterHeight, "getOuterHeight");
function getParents(element, parents = []) {
  const parent2 = getParentNode(element);
  return parent2 === null ? parents : getParents(parent2, parents.concat([parent2]));
}
__name(getParents, "getParents");
function getPreviousElementSibling(element, selector) {
  let previousElement = element.previousElementSibling;
  while (previousElement) {
    if (previousElement.matches(selector)) {
      return previousElement;
    } else {
      previousElement = previousElement.previousElementSibling;
    }
  }
  return null;
}
__name(getPreviousElementSibling, "getPreviousElementSibling");
function getScrollableParents(element) {
  let scrollableParents = [];
  if (element) {
    let parents = getParents(element);
    const overflowRegex = /(auto|scroll)/;
    const overflowCheck = /* @__PURE__ */ __name((node2) => {
      try {
        let styleDeclaration = window["getComputedStyle"](node2, null);
        return overflowRegex.test(styleDeclaration.getPropertyValue("overflow")) || overflowRegex.test(styleDeclaration.getPropertyValue("overflowX")) || overflowRegex.test(styleDeclaration.getPropertyValue("overflowY"));
      } catch (err) {
        return false;
      }
    }, "overflowCheck");
    for (let parent2 of parents) {
      let scrollSelectors = parent2.nodeType === 1 && parent2.dataset["scrollselectors"];
      if (scrollSelectors) {
        let selectors = scrollSelectors.split(",");
        for (let selector of selectors) {
          let el = findSingle(parent2, selector);
          if (el && overflowCheck(el)) {
            scrollableParents.push(el);
          }
        }
      }
      if (parent2.nodeType !== 9 && overflowCheck(parent2)) {
        scrollableParents.push(parent2);
      }
    }
  }
  return scrollableParents;
}
__name(getScrollableParents, "getScrollableParents");
function getSelection$1() {
  if (window.getSelection) return window.getSelection().toString();
  else if (document.getSelection) return document.getSelection().toString();
  return void 0;
}
__name(getSelection$1, "getSelection$1");
function isExist(element) {
  return !!(element !== null && typeof element !== "undefined" && element.nodeName && getParentNode(element));
}
__name(isExist, "isExist");
function getTargetElement(target, currentElement) {
  var _a2;
  if (!target) return void 0;
  switch (target) {
    case "document":
      return document;
    case "window":
      return window;
    case "body":
      return document.body;
    case "@next":
      return currentElement == null ? void 0 : currentElement.nextElementSibling;
    case "@prev":
      return currentElement == null ? void 0 : currentElement.previousElementSibling;
    case "@parent":
      return currentElement == null ? void 0 : currentElement.parentElement;
    case "@grandparent":
      return (_a2 = currentElement == null ? void 0 : currentElement.parentElement) == null ? void 0 : _a2.parentElement;
    default:
      if (typeof target === "string") {
        return document.querySelector(target);
      }
      const isFunction2 = /* @__PURE__ */ __name((obj) => !!(obj && obj.constructor && obj.call && obj.apply), "isFunction");
      const element = toElement(isFunction2(target) ? target() : target);
      return (element == null ? void 0 : element.nodeType) === 9 || isExist(element) ? element : void 0;
  }
}
__name(getTargetElement, "getTargetElement");
function getUserAgent() {
  return navigator.userAgent;
}
__name(getUserAgent, "getUserAgent");
function getWidth(element) {
  if (element) {
    let width2 = element.offsetWidth;
    let style2 = getComputedStyle(element);
    width2 -= parseFloat(style2.paddingLeft) + parseFloat(style2.paddingRight) + parseFloat(style2.borderLeftWidth) + parseFloat(style2.borderRightWidth);
    return width2;
  }
  return 0;
}
__name(getWidth, "getWidth");
function hasCSSAnimation(element) {
  if (element) {
    const style2 = getComputedStyle(element);
    const animationDuration = parseFloat(style2.getPropertyValue("animation-duration") || "0");
    return animationDuration > 0;
  }
  return false;
}
__name(hasCSSAnimation, "hasCSSAnimation");
function hasCSSTransition(element) {
  if (element) {
    const style2 = getComputedStyle(element);
    const transitionDuration = parseFloat(style2.getPropertyValue("transition-duration") || "0");
    return transitionDuration > 0;
  }
  return false;
}
__name(hasCSSTransition, "hasCSSTransition");
function invokeElementMethod(element, methodName, args) {
  element[methodName].apply(element, args);
}
__name(invokeElementMethod, "invokeElementMethod");
function isAndroid$2() {
  return /(android)/i.test(navigator.userAgent);
}
__name(isAndroid$2, "isAndroid$2");
function isAttributeEquals(element, name2, value) {
  return isElement(element) ? getAttribute(element, name2) === value : false;
}
__name(isAttributeEquals, "isAttributeEquals");
function isAttributeNotEquals(element, name2, value) {
  return !isAttributeEquals(element, name2, value);
}
__name(isAttributeNotEquals, "isAttributeNotEquals");
function isClickable(element) {
  if (element) {
    const targetNode = element.nodeName;
    const parentNode2 = element.parentElement && element.parentElement.nodeName;
    return targetNode === "INPUT" || targetNode === "TEXTAREA" || targetNode === "BUTTON" || targetNode === "A" || parentNode2 === "INPUT" || parentNode2 === "TEXTAREA" || parentNode2 === "BUTTON" || parentNode2 === "A" || !!element.closest(".p-button, .p-checkbox, .p-radiobutton");
  }
  return false;
}
__name(isClickable, "isClickable");
function isClient() {
  return !!(typeof window !== "undefined" && window.document && window.document.createElement);
}
__name(isClient, "isClient");
function isFocusableElement(element, selector = "") {
  return isElement(element) ? element.matches(`button:not([tabindex = "-1"]):not([disabled]):not([style*="display:none"]):not([hidden])${selector},
            [href][clientHeight][clientWidth]:not([tabindex = "-1"]):not([disabled]):not([style*="display:none"]):not([hidden])${selector},
            input:not([tabindex = "-1"]):not([disabled]):not([style*="display:none"]):not([hidden])${selector},
            select:not([tabindex = "-1"]):not([disabled]):not([style*="display:none"]):not([hidden])${selector},
            textarea:not([tabindex = "-1"]):not([disabled]):not([style*="display:none"]):not([hidden])${selector},
            [tabIndex]:not([tabIndex = "-1"]):not([disabled]):not([style*="display:none"]):not([hidden])${selector},
            [contenteditable]:not([tabIndex = "-1"]):not([disabled]):not([style*="display:none"]):not([hidden])${selector}`) : false;
}
__name(isFocusableElement, "isFocusableElement");
function isVisible(element) {
  return !!(element && element.offsetParent != null);
}
__name(isVisible, "isVisible");
function isHidden(element) {
  return !isVisible(element);
}
__name(isHidden, "isHidden");
function isIOS() {
  return /iPad|iPhone|iPod/.test(navigator.userAgent) && !window["MSStream"];
}
__name(isIOS, "isIOS");
function isRTL(element) {
  return element ? getComputedStyle(element).direction === "rtl" : false;
}
__name(isRTL, "isRTL");
function isServer() {
  return !isClient();
}
__name(isServer, "isServer");
function isTouchDevice() {
  return "ontouchstart" in window || navigator.maxTouchPoints > 0 || navigator.msMaxTouchPoints > 0;
}
__name(isTouchDevice, "isTouchDevice");
function nestedPosition(element, level) {
  var _a2, _b;
  if (element) {
    const parentItem = element.parentElement;
    const elementOffset = getOffset(parentItem);
    const viewport = getViewport();
    const sublistWidth = element.offsetParent ? element.offsetWidth : getHiddenElementOuterWidth(element);
    const sublistHeight = element.offsetParent ? element.offsetHeight : getHiddenElementOuterHeight(element);
    const itemOuterWidth = getOuterWidth((_a2 = parentItem == null ? void 0 : parentItem.children) == null ? void 0 : _a2[0]);
    const itemOuterHeight = getOuterHeight((_b = parentItem == null ? void 0 : parentItem.children) == null ? void 0 : _b[0]);
    let left = "";
    let top = "";
    if (elementOffset.left + itemOuterWidth + sublistWidth > viewport.width - calculateScrollbarWidth()) {
      if (elementOffset.left < sublistWidth) {
        if (level % 2 === 1) {
          left = elementOffset.left ? "-" + elementOffset.left + "px" : "100%";
        } else if (level % 2 === 0) {
          left = viewport.width - sublistWidth - calculateScrollbarWidth() + "px";
        }
      } else {
        left = "-100%";
      }
    } else {
      left = "100%";
    }
    if (element.getBoundingClientRect().top + itemOuterHeight + sublistHeight > viewport.height) {
      top = `-${sublistHeight - itemOuterHeight}px`;
    } else {
      top = "0px";
    }
    element.style.top = top;
    element.style.left = left;
  }
}
__name(nestedPosition, "nestedPosition");
function remove(element) {
  var _a2;
  if (element) {
    if (!("remove" in Element.prototype)) (_a2 = element.parentNode) == null ? void 0 : _a2.removeChild(element);
    else element.remove();
  }
}
__name(remove, "remove");
function removeChild(element, child2) {
  const target = toElement(element);
  if (target) target.removeChild(child2);
  else throw new Error("Cannot remove " + child2 + " from " + element);
}
__name(removeChild, "removeChild");
function removeStyleTag(element) {
  var _a2;
  if (isExist(element)) {
    try {
      (_a2 = element.parentNode) == null ? void 0 : _a2.removeChild(element);
    } catch (error2) {
    }
    return null;
  }
  return element;
}
__name(removeStyleTag, "removeStyleTag");
function scrollInView(container, item) {
  let borderTopValue = getComputedStyle(container).getPropertyValue("borderTopWidth");
  let borderTop = borderTopValue ? parseFloat(borderTopValue) : 0;
  let paddingTopValue = getComputedStyle(container).getPropertyValue("paddingTop");
  let paddingTop = paddingTopValue ? parseFloat(paddingTopValue) : 0;
  let containerRect = container.getBoundingClientRect();
  let itemRect = item.getBoundingClientRect();
  let offset = itemRect.top + document.body.scrollTop - (containerRect.top + document.body.scrollTop) - borderTop - paddingTop;
  let scroll = container.scrollTop;
  let elementHeight = container.clientHeight;
  let itemHeight = getOuterHeight(item);
  if (offset < 0) {
    container.scrollTop = scroll + offset;
  } else if (offset + itemHeight > elementHeight) {
    container.scrollTop = scroll + offset - elementHeight + itemHeight;
  }
}
__name(scrollInView, "scrollInView");
function setAttribute(element, attribute2 = "", value) {
  if (isElement(element) && value !== null && value !== void 0) {
    element.setAttribute(attribute2, value);
  }
}
__name(setAttribute, "setAttribute");
function setCSSProperty(element, property, value = null, priority) {
  var _a2;
  property && ((_a2 = element == null ? void 0 : element.style) == null ? void 0 : _a2.setProperty(property, value, priority));
}
__name(setCSSProperty, "setCSSProperty");
function EventBus() {
  const allHandlers = /* @__PURE__ */ new Map();
  return {
    on(type, handler5) {
      let handlers2 = allHandlers.get(type);
      if (!handlers2) handlers2 = [handler5];
      else handlers2.push(handler5);
      allHandlers.set(type, handlers2);
      return this;
    },
    off(type, handler5) {
      let handlers2 = allHandlers.get(type);
      if (handlers2) {
        handlers2.splice(handlers2.indexOf(handler5) >>> 0, 1);
      }
      return this;
    },
    emit(type, evt) {
      let handlers2 = allHandlers.get(type);
      if (handlers2) {
        handlers2.slice().map((handler5) => {
          handler5(evt);
        });
      }
    },
    clear() {
      allHandlers.clear();
    }
  };
}
__name(EventBus, "EventBus");
var __defProp$4 = Object.defineProperty;
var __getOwnPropSymbols$3 = Object.getOwnPropertySymbols;
var __hasOwnProp$3 = Object.prototype.hasOwnProperty;
var __propIsEnum$3 = Object.prototype.propertyIsEnumerable;
var __defNormalProp$4 = /* @__PURE__ */ __name((obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value, "__defNormalProp$4");
var __spreadValues$3 = /* @__PURE__ */ __name((a2, b2) => {
  for (var prop2 in b2 || (b2 = {}))
    if (__hasOwnProp$3.call(b2, prop2))
      __defNormalProp$4(a2, prop2, b2[prop2]);
  if (__getOwnPropSymbols$3)
    for (var prop2 of __getOwnPropSymbols$3(b2)) {
      if (__propIsEnum$3.call(b2, prop2))
        __defNormalProp$4(a2, prop2, b2[prop2]);
    }
  return a2;
}, "__spreadValues$3");
function isFunction$8(value) {
  return !!(value && value.constructor && value.call && value.apply);
}
__name(isFunction$8, "isFunction$8");
function mergeProps(...props) {
  return props == null ? void 0 : props.reduce((merged, ps = {}) => {
    for (const key in ps) {
      const value = ps[key];
      if (key === "style") {
        merged["style"] = __spreadValues$3(__spreadValues$3({}, merged["style"]), ps["style"]);
      } else if (key === "class") {
        merged["class"] = [merged["class"], ps["class"]].join(" ").trim() || void 0;
      } else if (key === "className") {
        merged["className"] = [merged["className"], ps["className"]].join(" ").trim() || void 0;
      } else if (isFunction$8(value)) {
        const fn = merged[key];
        merged[key] = fn ? (...args) => {
          fn(...args);
          value(...args);
        } : value;
      } else {
        merged[key] = value;
      }
    }
    return merged;
  }, {});
}
__name(mergeProps, "mergeProps");
var __defProp$3 = Object.defineProperty;
var __getOwnPropSymbols$2 = Object.getOwnPropertySymbols;
var __hasOwnProp$2 = Object.prototype.hasOwnProperty;
var __propIsEnum$2 = Object.prototype.propertyIsEnumerable;
var __defNormalProp$3 = /* @__PURE__ */ __name((obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value, "__defNormalProp$3");
var __spreadValues$2 = /* @__PURE__ */ __name((a2, b2) => {
  for (var prop2 in b2 || (b2 = {}))
    if (__hasOwnProp$2.call(b2, prop2))
      __defNormalProp$3(a2, prop2, b2[prop2]);
  if (__getOwnPropSymbols$2)
    for (var prop2 of __getOwnPropSymbols$2(b2)) {
      if (__propIsEnum$2.call(b2, prop2))
        __defNormalProp$3(a2, prop2, b2[prop2]);
    }
  return a2;
}, "__spreadValues$2");
function isEmpty$2(value) {
  return value === null || value === void 0 || value === "" || Array.isArray(value) && value.length === 0 || !(value instanceof Date) && typeof value === "object" && Object.keys(value).length === 0;
}
__name(isEmpty$2, "isEmpty$2");
function compare$2(value1, value2, comparator, order = 1) {
  let result = -1;
  const emptyValue1 = isEmpty$2(value1);
  const emptyValue2 = isEmpty$2(value2);
  if (emptyValue1 && emptyValue2) result = 0;
  else if (emptyValue1) result = order;
  else if (emptyValue2) result = -order;
  else if (typeof value1 === "string" && typeof value2 === "string") result = comparator(value1, value2);
  else result = value1 < value2 ? -1 : value1 > value2 ? 1 : 0;
  return result;
}
__name(compare$2, "compare$2");
function _deepEquals$1(obj1, obj2, visited = /* @__PURE__ */ new WeakSet()) {
  if (obj1 === obj2) return true;
  if (!obj1 || !obj2 || typeof obj1 !== "object" || typeof obj2 !== "object") return false;
  if (visited.has(obj1) || visited.has(obj2)) return false;
  visited.add(obj1).add(obj2);
  let arrObj1 = Array.isArray(obj1), arrObj2 = Array.isArray(obj2), i2, length, key;
  if (arrObj1 && arrObj2) {
    length = obj1.length;
    if (length != obj2.length) return false;
    for (i2 = length; i2-- !== 0; ) if (!_deepEquals$1(obj1[i2], obj2[i2], visited)) return false;
    return true;
  }
  if (arrObj1 != arrObj2) return false;
  let dateObj1 = obj1 instanceof Date, dateObj2 = obj2 instanceof Date;
  if (dateObj1 != dateObj2) return false;
  if (dateObj1 && dateObj2) return obj1.getTime() == obj2.getTime();
  let regexpObj1 = obj1 instanceof RegExp, regexpObj2 = obj2 instanceof RegExp;
  if (regexpObj1 != regexpObj2) return false;
  if (regexpObj1 && regexpObj2) return obj1.toString() == obj2.toString();
  let keys2 = Object.keys(obj1);
  length = keys2.length;
  if (length !== Object.keys(obj2).length) return false;
  for (i2 = length; i2-- !== 0; ) if (!Object.prototype.hasOwnProperty.call(obj2, keys2[i2])) return false;
  for (i2 = length; i2-- !== 0; ) {
    key = keys2[i2];
    if (!_deepEquals$1(obj1[key], obj2[key], visited)) return false;
  }
  return true;
}
__name(_deepEquals$1, "_deepEquals$1");
function deepEquals$1(obj1, obj2) {
  return _deepEquals$1(obj1, obj2);
}
__name(deepEquals$1, "deepEquals$1");
function isFunction$7(value) {
  return !!(value && value.constructor && value.call && value.apply);
}
__name(isFunction$7, "isFunction$7");
function isNotEmpty$1(value) {
  return !isEmpty$2(value);
}
__name(isNotEmpty$1, "isNotEmpty$1");
function resolveFieldData$1(data, field2) {
  if (!data || !field2) {
    return null;
  }
  try {
    const value = data[field2];
    if (isNotEmpty$1(value)) return value;
  } catch (e2) {
  }
  if (Object.keys(data).length) {
    if (isFunction$7(field2)) {
      return field2(data);
    } else if (field2.indexOf(".") === -1) {
      return data[field2];
    } else {
      let fields = field2.split(".");
      let value = data;
      for (let i2 = 0, len = fields.length; i2 < len; ++i2) {
        if (value == null) {
          return null;
        }
        value = value[fields[i2]];
      }
      return value;
    }
  }
  return null;
}
__name(resolveFieldData$1, "resolveFieldData$1");
function equals$1(obj1, obj2, field2) {
  if (field2) return resolveFieldData$1(obj1, field2) === resolveFieldData$1(obj2, field2);
  else return deepEquals$1(obj1, obj2);
}
__name(equals$1, "equals$1");
function contains$1(value, list2) {
  if (value != null && list2 && list2.length) {
    for (let val of list2) {
      if (equals$1(value, val)) return true;
    }
  }
  return false;
}
__name(contains$1, "contains$1");
function filter$1(value, fields, filterValue) {
  let filteredItems = [];
  if (value) {
    for (let item of value) {
      for (let field2 of fields) {
        if (String(resolveFieldData$1(item, field2)).toLowerCase().indexOf(filterValue.toLowerCase()) > -1) {
          filteredItems.push(item);
          break;
        }
      }
    }
  }
  return filteredItems;
}
__name(filter$1, "filter$1");
function findIndexInList$1(value, list2) {
  let index2 = -1;
  if (list2) {
    for (let i2 = 0; i2 < list2.length; i2++) {
      if (list2[i2] === value) {
        index2 = i2;
        break;
      }
    }
  }
  return index2;
}
__name(findIndexInList$1, "findIndexInList$1");
function findLast$1(arr, callback) {
  let item;
  if (isNotEmpty$1(arr)) {
    try {
      item = arr.findLast(callback);
    } catch (e2) {
      item = [...arr].reverse().find(callback);
    }
  }
  return item;
}
__name(findLast$1, "findLast$1");
function findLastIndex$1(arr, callback) {
  let index2 = -1;
  if (isNotEmpty$1(arr)) {
    try {
      index2 = arr.findLastIndex(callback);
    } catch (e2) {
      index2 = arr.lastIndexOf([...arr].reverse().find(callback));
    }
  }
  return index2;
}
__name(findLastIndex$1, "findLastIndex$1");
function isObject$a(value, empty2 = true) {
  return value instanceof Object && value.constructor === Object && (empty2 || Object.keys(value).length !== 0);
}
__name(isObject$a, "isObject$a");
function resolve$1(obj, ...params) {
  return isFunction$7(obj) ? obj(...params) : obj;
}
__name(resolve$1, "resolve$1");
function isString$5(value, empty2 = true) {
  return typeof value === "string" && (empty2 || value !== "");
}
__name(isString$5, "isString$5");
function toFlatCase$1(str) {
  return isString$5(str) ? str.replace(/(-|_)/g, "").toLowerCase() : str;
}
__name(toFlatCase$1, "toFlatCase$1");
function getKeyValue$1(obj, key = "", params = {}) {
  const fKeys = toFlatCase$1(key).split(".");
  const fKey = fKeys.shift();
  return fKey ? isObject$a(obj) ? getKeyValue$1(resolve$1(obj[Object.keys(obj).find((k2) => toFlatCase$1(k2) === fKey) || ""], params), fKeys.join("."), params) : void 0 : resolve$1(obj, params);
}
__name(getKeyValue$1, "getKeyValue$1");
function insertIntoOrderedArray$1(item, index2, arr, sourceArr) {
  if (arr.length > 0) {
    let injected = false;
    for (let i2 = 0; i2 < arr.length; i2++) {
      let currentItemIndex = findIndexInList$1(arr[i2], sourceArr);
      if (currentItemIndex > index2) {
        arr.splice(i2, 0, item);
        injected = true;
        break;
      }
    }
    if (!injected) {
      arr.push(item);
    }
  } else {
    arr.push(item);
  }
}
__name(insertIntoOrderedArray$1, "insertIntoOrderedArray$1");
function isArray$7(value, empty2 = true) {
  return Array.isArray(value) && (empty2 || value.length !== 0);
}
__name(isArray$7, "isArray$7");
function isDate$1(value) {
  return value instanceof Date && value.constructor === Date;
}
__name(isDate$1, "isDate$1");
function isLetter$2(char) {
  return /^[a-zA-Z\u00C0-\u017F]$/.test(char);
}
__name(isLetter$2, "isLetter$2");
function isNumber$4(value) {
  return isNotEmpty$1(value) && !isNaN(value);
}
__name(isNumber$4, "isNumber$4");
function isPrintableCharacter$1(char = "") {
  return isNotEmpty$1(char) && char.length === 1 && !!char.match(/\S| /);
}
__name(isPrintableCharacter$1, "isPrintableCharacter$1");
function isScalar$1(value) {
  return value != null && (typeof value === "string" || typeof value === "number" || typeof value === "bigint" || typeof value === "boolean");
}
__name(isScalar$1, "isScalar$1");
function localeComparator$1() {
  return new Intl.Collator(void 0, { numeric: true }).compare;
}
__name(localeComparator$1, "localeComparator$1");
function matchRegex$1(str, regex2) {
  if (regex2) {
    const match2 = regex2.test(str);
    regex2.lastIndex = 0;
    return match2;
  }
  return false;
}
__name(matchRegex$1, "matchRegex$1");
function mergeKeys$1(...args) {
  const _mergeKeys = /* @__PURE__ */ __name((target = {}, source = {}) => {
    const mergedObj = __spreadValues$2({}, target);
    Object.keys(source).forEach((key) => {
      if (isObject$a(source[key]) && key in target && isObject$a(target[key])) {
        mergedObj[key] = _mergeKeys(target[key], source[key]);
      } else {
        mergedObj[key] = source[key];
      }
    });
    return mergedObj;
  }, "_mergeKeys");
  return args.reduce((acc, obj, i2) => i2 === 0 ? obj : _mergeKeys(acc, obj), {});
}
__name(mergeKeys$1, "mergeKeys$1");
function minifyCSS$1(css3) {
  return css3 ? css3.replace(/\/\*(?:(?!\*\/)[\s\S])*\*\/|[\r\n\t]+/g, "").replace(/ {2,}/g, " ").replace(/ ([{:}]) /g, "$1").replace(/([;,]) /g, "$1").replace(/ !/g, "!").replace(/: /g, ":") : css3;
}
__name(minifyCSS$1, "minifyCSS$1");
function nestedKeys$1(obj = {}, parentKey = "") {
  return Object.entries(obj).reduce((o2, [key, value]) => {
    const currentKey = parentKey ? `${parentKey}.${key}` : key;
    isObject$a(value) ? o2 = o2.concat(nestedKeys$1(value, currentKey)) : o2.push(currentKey);
    return o2;
  }, []);
}
__name(nestedKeys$1, "nestedKeys$1");
function omit$1(obj, ...keys2) {
  if (!isObject$a(obj)) return obj;
  const copy2 = __spreadValues$2({}, obj);
  keys2 == null ? void 0 : keys2.flat().forEach((key) => delete copy2[key]);
  return copy2;
}
__name(omit$1, "omit$1");
function removeAccents$1(str) {
  const accentCheckRegex = /[\xC0-\xFF\u0100-\u017E]/;
  if (str && accentCheckRegex.test(str)) {
    const accentsMap = {
      A: /[\xC0-\xC5\u0100\u0102\u0104]/g,
      AE: /[\xC6]/g,
      C: /[\xC7\u0106\u0108\u010A\u010C]/g,
      D: /[\xD0\u010E\u0110]/g,
      E: /[\xC8-\xCB\u0112\u0114\u0116\u0118\u011A]/g,
      G: /[\u011C\u011E\u0120\u0122]/g,
      H: /[\u0124\u0126]/g,
      I: /[\xCC-\xCF\u0128\u012A\u012C\u012E\u0130]/g,
      IJ: /[\u0132]/g,
      J: /[\u0134]/g,
      K: /[\u0136]/g,
      L: /[\u0139\u013B\u013D\u013F\u0141]/g,
      N: /[\xD1\u0143\u0145\u0147\u014A]/g,
      O: /[\xD2-\xD6\xD8\u014C\u014E\u0150]/g,
      OE: /[\u0152]/g,
      R: /[\u0154\u0156\u0158]/g,
      S: /[\u015A\u015C\u015E\u0160]/g,
      T: /[\u0162\u0164\u0166]/g,
      U: /[\xD9-\xDC\u0168\u016A\u016C\u016E\u0170\u0172]/g,
      W: /[\u0174]/g,
      Y: /[\xDD\u0176\u0178]/g,
      Z: /[\u0179\u017B\u017D]/g,
      a: /[\xE0-\xE5\u0101\u0103\u0105]/g,
      ae: /[\xE6]/g,
      c: /[\xE7\u0107\u0109\u010B\u010D]/g,
      d: /[\u010F\u0111]/g,
      e: /[\xE8-\xEB\u0113\u0115\u0117\u0119\u011B]/g,
      g: /[\u011D\u011F\u0121\u0123]/g,
      i: /[\xEC-\xEF\u0129\u012B\u012D\u012F\u0131]/g,
      ij: /[\u0133]/g,
      j: /[\u0135]/g,
      k: /[\u0137,\u0138]/g,
      l: /[\u013A\u013C\u013E\u0140\u0142]/g,
      n: /[\xF1\u0144\u0146\u0148\u014B]/g,
      p: /[\xFE]/g,
      o: /[\xF2-\xF6\xF8\u014D\u014F\u0151]/g,
      oe: /[\u0153]/g,
      r: /[\u0155\u0157\u0159]/g,
      s: /[\u015B\u015D\u015F\u0161]/g,
      t: /[\u0163\u0165\u0167]/g,
      u: /[\xF9-\xFC\u0169\u016B\u016D\u016F\u0171\u0173]/g,
      w: /[\u0175]/g,
      y: /[\xFD\xFF\u0177]/g,
      z: /[\u017A\u017C\u017E]/g
    };
    for (let key in accentsMap) {
      str = str.replace(accentsMap[key], key);
    }
  }
  return str;
}
__name(removeAccents$1, "removeAccents$1");
function reorderArray$1(value, from2, to) {
  if (value && from2 !== to) {
    if (to >= value.length) {
      to %= value.length;
      from2 %= value.length;
    }
    value.splice(to, 0, value.splice(from2, 1)[0]);
  }
}
__name(reorderArray$1, "reorderArray$1");
function sort$1(value1, value2, order = 1, comparator, nullSortOrder = 1) {
  const result = compare$2(value1, value2, comparator, order);
  let finalSortOrder = order;
  if (isEmpty$2(value1) || isEmpty$2(value2)) {
    finalSortOrder = nullSortOrder === 1 ? order : nullSortOrder;
  }
  return finalSortOrder * result;
}
__name(sort$1, "sort$1");
function stringify$1(value, indent = 2, currentIndent = 0) {
  const currentIndentStr = " ".repeat(currentIndent);
  const nextIndentStr = " ".repeat(currentIndent + indent);
  if (isArray$7(value)) {
    return "[" + value.map((v2) => stringify$1(v2, indent, currentIndent + indent)).join(", ") + "]";
  } else if (isDate$1(value)) {
    return value.toISOString();
  } else if (isFunction$7(value)) {
    return value.toString();
  } else if (isObject$a(value)) {
    return "{\n" + Object.entries(value).map(([k2, v2]) => `${nextIndentStr}${k2}: ${stringify$1(v2, indent, currentIndent + indent)}`).join(",\n") + `
${currentIndentStr}}`;
  } else {
    return JSON.stringify(value);
  }
}
__name(stringify$1, "stringify$1");
function toCapitalCase$1(str) {
  return isString$5(str, false) ? str[0].toUpperCase() + str.slice(1) : str;
}
__name(toCapitalCase$1, "toCapitalCase$1");
function toKebabCase$1(str) {
  return isString$5(str) ? str.replace(/(_)/g, "-").replace(/[A-Z]/g, (c2, i2) => i2 === 0 ? c2 : "-" + c2.toLowerCase()).toLowerCase() : str;
}
__name(toKebabCase$1, "toKebabCase$1");
function toTokenKey$2(str) {
  return isString$5(str) ? str.replace(/[A-Z]/g, (c2, i2) => i2 === 0 ? c2 : "." + c2.toLowerCase()).toLowerCase() : str;
}
__name(toTokenKey$2, "toTokenKey$2");
function toValue$2(value) {
  if (value && typeof value === "object") {
    if (value.hasOwnProperty("current")) {
      return value.current;
    } else if (value.hasOwnProperty("value")) {
      return value.value;
    }
  }
  return resolve$1(value);
}
__name(toValue$2, "toValue$2");
var lastIds = {};
function uuid(prefix = "pui_id_") {
  if (!lastIds.hasOwnProperty(prefix)) {
    lastIds[prefix] = 0;
  }
  lastIds[prefix]++;
  return `${prefix}${lastIds[prefix]}`;
}
__name(uuid, "uuid");
function handler() {
  let zIndexes = [];
  const generateZIndex = /* @__PURE__ */ __name((key, autoZIndex, baseZIndex = 999) => {
    const lastZIndex = getLastZIndex(key, autoZIndex, baseZIndex);
    const newZIndex = lastZIndex.value + (lastZIndex.key === key ? 0 : baseZIndex) + 1;
    zIndexes.push({ key, value: newZIndex });
    return newZIndex;
  }, "generateZIndex");
  const revertZIndex = /* @__PURE__ */ __name((zIndex) => {
    zIndexes = zIndexes.filter((obj) => obj.value !== zIndex);
  }, "revertZIndex");
  const getCurrentZIndex = /* @__PURE__ */ __name((key, autoZIndex) => {
    return getLastZIndex(key, autoZIndex).value;
  }, "getCurrentZIndex");
  const getLastZIndex = /* @__PURE__ */ __name((key, autoZIndex, baseZIndex = 0) => {
    return [...zIndexes].reverse().find((obj) => autoZIndex ? true : obj.key === key) || { key, value: baseZIndex };
  }, "getLastZIndex");
  const getZIndex = /* @__PURE__ */ __name((element) => {
    return element ? parseInt(element.style.zIndex, 10) || 0 : 0;
  }, "getZIndex");
  return {
    get: getZIndex,
    set: /* @__PURE__ */ __name((key, element, baseZIndex) => {
      if (element) {
        element.style.zIndex = String(generateZIndex(key, true, baseZIndex));
      }
    }, "set"),
    clear: /* @__PURE__ */ __name((element) => {
      if (element) {
        revertZIndex(getZIndex(element));
        element.style.zIndex = "";
      }
    }, "clear"),
    getCurrent: /* @__PURE__ */ __name((key) => getCurrentZIndex(key, true), "getCurrent")
  };
}
__name(handler, "handler");
var ZIndex = handler();
function _typeof$6(o2) {
  "@babel/helpers - typeof";
  return _typeof$6 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o3) {
    return typeof o3;
  } : function(o3) {
    return o3 && "function" == typeof Symbol && o3.constructor === Symbol && o3 !== Symbol.prototype ? "symbol" : typeof o3;
  }, _typeof$6(o2);
}
__name(_typeof$6, "_typeof$6");
function _slicedToArray$4(r2, e2) {
  return _arrayWithHoles$4(r2) || _iterableToArrayLimit$4(r2, e2) || _unsupportedIterableToArray$6(r2, e2) || _nonIterableRest$4();
}
__name(_slicedToArray$4, "_slicedToArray$4");
function _nonIterableRest$4() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
__name(_nonIterableRest$4, "_nonIterableRest$4");
function _unsupportedIterableToArray$6(r2, a2) {
  if (r2) {
    if ("string" == typeof r2) return _arrayLikeToArray$6(r2, a2);
    var t2 = {}.toString.call(r2).slice(8, -1);
    return "Object" === t2 && r2.constructor && (t2 = r2.constructor.name), "Map" === t2 || "Set" === t2 ? Array.from(r2) : "Arguments" === t2 || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t2) ? _arrayLikeToArray$6(r2, a2) : void 0;
  }
}
__name(_unsupportedIterableToArray$6, "_unsupportedIterableToArray$6");
function _arrayLikeToArray$6(r2, a2) {
  (null == a2 || a2 > r2.length) && (a2 = r2.length);
  for (var e2 = 0, n2 = Array(a2); e2 < a2; e2++) n2[e2] = r2[e2];
  return n2;
}
__name(_arrayLikeToArray$6, "_arrayLikeToArray$6");
function _iterableToArrayLimit$4(r2, l2) {
  var t2 = null == r2 ? null : "undefined" != typeof Symbol && r2[Symbol.iterator] || r2["@@iterator"];
  if (null != t2) {
    var e2, n2, i2, u2, a2 = [], f2 = true, o2 = false;
    try {
      if (i2 = (t2 = t2.call(r2)).next, 0 === l2) ;
      else for (; !(f2 = (e2 = i2.call(t2)).done) && (a2.push(e2.value), a2.length !== l2); f2 = true) ;
    } catch (r3) {
      o2 = true, n2 = r3;
    } finally {
      try {
        if (!f2 && null != t2["return"] && (u2 = t2["return"](), Object(u2) !== u2)) return;
      } finally {
        if (o2) throw n2;
      }
    }
    return a2;
  }
}
__name(_iterableToArrayLimit$4, "_iterableToArrayLimit$4");
function _arrayWithHoles$4(r2) {
  if (Array.isArray(r2)) return r2;
}
__name(_arrayWithHoles$4, "_arrayWithHoles$4");
function ownKeys$8(e2, r2) {
  var t2 = Object.keys(e2);
  if (Object.getOwnPropertySymbols) {
    var o2 = Object.getOwnPropertySymbols(e2);
    r2 && (o2 = o2.filter(function(r3) {
      return Object.getOwnPropertyDescriptor(e2, r3).enumerable;
    })), t2.push.apply(t2, o2);
  }
  return t2;
}
__name(ownKeys$8, "ownKeys$8");
function _objectSpread$8(e2) {
  for (var r2 = 1; r2 < arguments.length; r2++) {
    var t2 = null != arguments[r2] ? arguments[r2] : {};
    r2 % 2 ? ownKeys$8(Object(t2), true).forEach(function(r3) {
      _defineProperty$8(e2, r3, t2[r3]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e2, Object.getOwnPropertyDescriptors(t2)) : ownKeys$8(Object(t2)).forEach(function(r3) {
      Object.defineProperty(e2, r3, Object.getOwnPropertyDescriptor(t2, r3));
    });
  }
  return e2;
}
__name(_objectSpread$8, "_objectSpread$8");
function _defineProperty$8(e2, r2, t2) {
  return (r2 = _toPropertyKey$5(r2)) in e2 ? Object.defineProperty(e2, r2, { value: t2, enumerable: true, configurable: true, writable: true }) : e2[r2] = t2, e2;
}
__name(_defineProperty$8, "_defineProperty$8");
function _toPropertyKey$5(t2) {
  var i2 = _toPrimitive$5(t2, "string");
  return "symbol" == _typeof$6(i2) ? i2 : i2 + "";
}
__name(_toPropertyKey$5, "_toPropertyKey$5");
function _toPrimitive$5(t2, r2) {
  if ("object" != _typeof$6(t2) || !t2) return t2;
  var e2 = t2[Symbol.toPrimitive];
  if (void 0 !== e2) {
    var i2 = e2.call(t2, r2 || "default");
    if ("object" != _typeof$6(i2)) return i2;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return ("string" === r2 ? String : Number)(t2);
}
__name(_toPrimitive$5, "_toPrimitive$5");
function _regeneratorRuntime() {
  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  _regeneratorRuntime = /* @__PURE__ */ __name(function _regeneratorRuntime2() {
    return e2;
  }, "_regeneratorRuntime");
  var t2, e2 = {}, r2 = Object.prototype, n2 = r2.hasOwnProperty, o2 = Object.defineProperty || function(t3, e3, r3) {
    t3[e3] = r3.value;
  }, i2 = "function" == typeof Symbol ? Symbol : {}, a2 = i2.iterator || "@@iterator", c2 = i2.asyncIterator || "@@asyncIterator", u2 = i2.toStringTag || "@@toStringTag";
  function define(t3, e3, r3) {
    return Object.defineProperty(t3, e3, { value: r3, enumerable: true, configurable: true, writable: true }), t3[e3];
  }
  __name(define, "define");
  try {
    define({}, "");
  } catch (t3) {
    define = /* @__PURE__ */ __name(function define2(t4, e3, r3) {
      return t4[e3] = r3;
    }, "define");
  }
  function wrap2(t3, e3, r3, n3) {
    var i3 = e3 && e3.prototype instanceof Generator ? e3 : Generator, a3 = Object.create(i3.prototype), c3 = new Context2(n3 || []);
    return o2(a3, "_invoke", { value: makeInvokeMethod(t3, r3, c3) }), a3;
  }
  __name(wrap2, "wrap");
  function tryCatch(t3, e3, r3) {
    try {
      return { type: "normal", arg: t3.call(e3, r3) };
    } catch (t4) {
      return { type: "throw", arg: t4 };
    }
  }
  __name(tryCatch, "tryCatch");
  e2.wrap = wrap2;
  var h2 = "suspendedStart", l2 = "suspendedYield", f2 = "executing", s2 = "completed", y2 = {};
  function Generator() {
  }
  __name(Generator, "Generator");
  function GeneratorFunction() {
  }
  __name(GeneratorFunction, "GeneratorFunction");
  function GeneratorFunctionPrototype() {
  }
  __name(GeneratorFunctionPrototype, "GeneratorFunctionPrototype");
  var p2 = {};
  define(p2, a2, function() {
    return this;
  });
  var d2 = Object.getPrototypeOf, v2 = d2 && d2(d2(values([])));
  v2 && v2 !== r2 && n2.call(v2, a2) && (p2 = v2);
  var g2 = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p2);
  function defineIteratorMethods(t3) {
    ["next", "throw", "return"].forEach(function(e3) {
      define(t3, e3, function(t4) {
        return this._invoke(e3, t4);
      });
    });
  }
  __name(defineIteratorMethods, "defineIteratorMethods");
  function AsyncIterator2(t3, e3) {
    function invoke2(r4, o3, i3, a3) {
      var c3 = tryCatch(t3[r4], t3, o3);
      if ("throw" !== c3.type) {
        var u3 = c3.arg, h3 = u3.value;
        return h3 && "object" == _typeof$6(h3) && n2.call(h3, "__await") ? e3.resolve(h3.__await).then(function(t4) {
          invoke2("next", t4, i3, a3);
        }, function(t4) {
          invoke2("throw", t4, i3, a3);
        }) : e3.resolve(h3).then(function(t4) {
          u3.value = t4, i3(u3);
        }, function(t4) {
          return invoke2("throw", t4, i3, a3);
        });
      }
      a3(c3.arg);
    }
    __name(invoke2, "invoke");
    var r3;
    o2(this, "_invoke", { value: /* @__PURE__ */ __name(function value(t4, n3) {
      function callInvokeWithMethodAndArg() {
        return new e3(function(e4, r4) {
          invoke2(t4, n3, e4, r4);
        });
      }
      __name(callInvokeWithMethodAndArg, "callInvokeWithMethodAndArg");
      return r3 = r3 ? r3.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
    }, "value") });
  }
  __name(AsyncIterator2, "AsyncIterator");
  function makeInvokeMethod(e3, r3, n3) {
    var o3 = h2;
    return function(i3, a3) {
      if (o3 === f2) throw Error("Generator is already running");
      if (o3 === s2) {
        if ("throw" === i3) throw a3;
        return { value: t2, done: true };
      }
      for (n3.method = i3, n3.arg = a3; ; ) {
        var c3 = n3.delegate;
        if (c3) {
          var u3 = maybeInvokeDelegate(c3, n3);
          if (u3) {
            if (u3 === y2) continue;
            return u3;
          }
        }
        if ("next" === n3.method) n3.sent = n3._sent = n3.arg;
        else if ("throw" === n3.method) {
          if (o3 === h2) throw o3 = s2, n3.arg;
          n3.dispatchException(n3.arg);
        } else "return" === n3.method && n3.abrupt("return", n3.arg);
        o3 = f2;
        var p3 = tryCatch(e3, r3, n3);
        if ("normal" === p3.type) {
          if (o3 = n3.done ? s2 : l2, p3.arg === y2) continue;
          return { value: p3.arg, done: n3.done };
        }
        "throw" === p3.type && (o3 = s2, n3.method = "throw", n3.arg = p3.arg);
      }
    };
  }
  __name(makeInvokeMethod, "makeInvokeMethod");
  function maybeInvokeDelegate(e3, r3) {
    var n3 = r3.method, o3 = e3.iterator[n3];
    if (o3 === t2) return r3.delegate = null, "throw" === n3 && e3.iterator["return"] && (r3.method = "return", r3.arg = t2, maybeInvokeDelegate(e3, r3), "throw" === r3.method) || "return" !== n3 && (r3.method = "throw", r3.arg = new TypeError("The iterator does not provide a '" + n3 + "' method")), y2;
    var i3 = tryCatch(o3, e3.iterator, r3.arg);
    if ("throw" === i3.type) return r3.method = "throw", r3.arg = i3.arg, r3.delegate = null, y2;
    var a3 = i3.arg;
    return a3 ? a3.done ? (r3[e3.resultName] = a3.value, r3.next = e3.nextLoc, "return" !== r3.method && (r3.method = "next", r3.arg = t2), r3.delegate = null, y2) : a3 : (r3.method = "throw", r3.arg = new TypeError("iterator result is not an object"), r3.delegate = null, y2);
  }
  __name(maybeInvokeDelegate, "maybeInvokeDelegate");
  function pushTryEntry(t3) {
    var e3 = { tryLoc: t3[0] };
    1 in t3 && (e3.catchLoc = t3[1]), 2 in t3 && (e3.finallyLoc = t3[2], e3.afterLoc = t3[3]), this.tryEntries.push(e3);
  }
  __name(pushTryEntry, "pushTryEntry");
  function resetTryEntry(t3) {
    var e3 = t3.completion || {};
    e3.type = "normal", delete e3.arg, t3.completion = e3;
  }
  __name(resetTryEntry, "resetTryEntry");
  function Context2(t3) {
    this.tryEntries = [{ tryLoc: "root" }], t3.forEach(pushTryEntry, this), this.reset(true);
  }
  __name(Context2, "Context");
  function values(e3) {
    if (e3 || "" === e3) {
      var r3 = e3[a2];
      if (r3) return r3.call(e3);
      if ("function" == typeof e3.next) return e3;
      if (!isNaN(e3.length)) {
        var o3 = -1, i3 = /* @__PURE__ */ __name(function next() {
          for (; ++o3 < e3.length; ) if (n2.call(e3, o3)) return next.value = e3[o3], next.done = false, next;
          return next.value = t2, next.done = true, next;
        }, "next");
        return i3.next = i3;
      }
    }
    throw new TypeError(_typeof$6(e3) + " is not iterable");
  }
  __name(values, "values");
  return GeneratorFunction.prototype = GeneratorFunctionPrototype, o2(g2, "constructor", { value: GeneratorFunctionPrototype, configurable: true }), o2(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: true }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u2, "GeneratorFunction"), e2.isGeneratorFunction = function(t3) {
    var e3 = "function" == typeof t3 && t3.constructor;
    return !!e3 && (e3 === GeneratorFunction || "GeneratorFunction" === (e3.displayName || e3.name));
  }, e2.mark = function(t3) {
    return Object.setPrototypeOf ? Object.setPrototypeOf(t3, GeneratorFunctionPrototype) : (t3.__proto__ = GeneratorFunctionPrototype, define(t3, u2, "GeneratorFunction")), t3.prototype = Object.create(g2), t3;
  }, e2.awrap = function(t3) {
    return { __await: t3 };
  }, defineIteratorMethods(AsyncIterator2.prototype), define(AsyncIterator2.prototype, c2, function() {
    return this;
  }), e2.AsyncIterator = AsyncIterator2, e2.async = function(t3, r3, n3, o3, i3) {
    void 0 === i3 && (i3 = Promise);
    var a3 = new AsyncIterator2(wrap2(t3, r3, n3, o3), i3);
    return e2.isGeneratorFunction(r3) ? a3 : a3.next().then(function(t4) {
      return t4.done ? t4.value : a3.next();
    });
  }, defineIteratorMethods(g2), define(g2, u2, "Generator"), define(g2, a2, function() {
    return this;
  }), define(g2, "toString", function() {
    return "[object Generator]";
  }), e2.keys = function(t3) {
    var e3 = Object(t3), r3 = [];
    for (var n3 in e3) r3.push(n3);
    return r3.reverse(), /* @__PURE__ */ __name(function next() {
      for (; r3.length; ) {
        var t4 = r3.pop();
        if (t4 in e3) return next.value = t4, next.done = false, next;
      }
      return next.done = true, next;
    }, "next");
  }, e2.values = values, Context2.prototype = { constructor: Context2, reset: /* @__PURE__ */ __name(function reset2(e3) {
    if (this.prev = 0, this.next = 0, this.sent = this._sent = t2, this.done = false, this.delegate = null, this.method = "next", this.arg = t2, this.tryEntries.forEach(resetTryEntry), !e3) for (var r3 in this) "t" === r3.charAt(0) && n2.call(this, r3) && !isNaN(+r3.slice(1)) && (this[r3] = t2);
  }, "reset"), stop: /* @__PURE__ */ __name(function stop2() {
    this.done = true;
    var t3 = this.tryEntries[0].completion;
    if ("throw" === t3.type) throw t3.arg;
    return this.rval;
  }, "stop"), dispatchException: /* @__PURE__ */ __name(function dispatchException(e3) {
    if (this.done) throw e3;
    var r3 = this;
    function handle(n3, o4) {
      return a3.type = "throw", a3.arg = e3, r3.next = n3, o4 && (r3.method = "next", r3.arg = t2), !!o4;
    }
    __name(handle, "handle");
    for (var o3 = this.tryEntries.length - 1; o3 >= 0; --o3) {
      var i3 = this.tryEntries[o3], a3 = i3.completion;
      if ("root" === i3.tryLoc) return handle("end");
      if (i3.tryLoc <= this.prev) {
        var c3 = n2.call(i3, "catchLoc"), u3 = n2.call(i3, "finallyLoc");
        if (c3 && u3) {
          if (this.prev < i3.catchLoc) return handle(i3.catchLoc, true);
          if (this.prev < i3.finallyLoc) return handle(i3.finallyLoc);
        } else if (c3) {
          if (this.prev < i3.catchLoc) return handle(i3.catchLoc, true);
        } else {
          if (!u3) throw Error("try statement without catch or finally");
          if (this.prev < i3.finallyLoc) return handle(i3.finallyLoc);
        }
      }
    }
  }, "dispatchException"), abrupt: /* @__PURE__ */ __name(function abrupt(t3, e3) {
    for (var r3 = this.tryEntries.length - 1; r3 >= 0; --r3) {
      var o3 = this.tryEntries[r3];
      if (o3.tryLoc <= this.prev && n2.call(o3, "finallyLoc") && this.prev < o3.finallyLoc) {
        var i3 = o3;
        break;
      }
    }
    i3 && ("break" === t3 || "continue" === t3) && i3.tryLoc <= e3 && e3 <= i3.finallyLoc && (i3 = null);
    var a3 = i3 ? i3.completion : {};
    return a3.type = t3, a3.arg = e3, i3 ? (this.method = "next", this.next = i3.finallyLoc, y2) : this.complete(a3);
  }, "abrupt"), complete: /* @__PURE__ */ __name(function complete(t3, e3) {
    if ("throw" === t3.type) throw t3.arg;
    return "break" === t3.type || "continue" === t3.type ? this.next = t3.arg : "return" === t3.type ? (this.rval = this.arg = t3.arg, this.method = "return", this.next = "end") : "normal" === t3.type && e3 && (this.next = e3), y2;
  }, "complete"), finish: /* @__PURE__ */ __name(function finish(t3) {
    for (var e3 = this.tryEntries.length - 1; e3 >= 0; --e3) {
      var r3 = this.tryEntries[e3];
      if (r3.finallyLoc === t3) return this.complete(r3.completion, r3.afterLoc), resetTryEntry(r3), y2;
    }
  }, "finish"), "catch": /* @__PURE__ */ __name(function _catch(t3) {
    for (var e3 = this.tryEntries.length - 1; e3 >= 0; --e3) {
      var r3 = this.tryEntries[e3];
      if (r3.tryLoc === t3) {
        var n3 = r3.completion;
        if ("throw" === n3.type) {
          var o3 = n3.arg;
          resetTryEntry(r3);
        }
        return o3;
      }
    }
    throw Error("illegal catch attempt");
  }, "_catch"), delegateYield: /* @__PURE__ */ __name(function delegateYield(e3, r3, n3) {
    return this.delegate = { iterator: values(e3), resultName: r3, nextLoc: n3 }, "next" === this.method && (this.arg = t2), y2;
  }, "delegateYield") }, e2;
}
__name(_regeneratorRuntime, "_regeneratorRuntime");
function asyncGeneratorStep(n2, t2, e2, r2, o2, a2, c2) {
  try {
    var i2 = n2[a2](c2), u2 = i2.value;
  } catch (n3) {
    return void e2(n3);
  }
  i2.done ? t2(u2) : Promise.resolve(u2).then(r2, o2);
}
__name(asyncGeneratorStep, "asyncGeneratorStep");
function _asyncToGenerator(n2) {
  return function() {
    var t2 = this, e2 = arguments;
    return new Promise(function(r2, o2) {
      var a2 = n2.apply(t2, e2);
      function _next(n3) {
        asyncGeneratorStep(a2, r2, o2, _next, _throw, "next", n3);
      }
      __name(_next, "_next");
      function _throw(n3) {
        asyncGeneratorStep(a2, r2, o2, _next, _throw, "throw", n3);
      }
      __name(_throw, "_throw");
      _next(void 0);
    });
  };
}
__name(_asyncToGenerator, "_asyncToGenerator");
function tryOnMounted$1(fn) {
  var sync = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : true;
  if (getCurrentInstance()) onMounted(fn);
  else if (sync) fn();
  else nextTick(fn);
}
__name(tryOnMounted$1, "tryOnMounted$1");
var useForm = /* @__PURE__ */ __name(function useForm2() {
  var options2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
  var states = reactive({});
  var fields = reactive({});
  var valid = computed(function() {
    return Object.values(states).every(function(field2) {
      return !field2.invalid;
    });
  });
  var getInitialState = /* @__PURE__ */ __name(function getInitialState2(field2, initialValue) {
    var _options$initialValue;
    return {
      value: initialValue !== null && initialValue !== void 0 ? initialValue : (_options$initialValue = options2.initialValues) === null || _options$initialValue === void 0 ? void 0 : _options$initialValue[field2],
      touched: false,
      dirty: false,
      pristine: true,
      valid: true,
      invalid: false,
      error: null,
      errors: []
    };
  }, "getInitialState");
  var isFieldValidate = /* @__PURE__ */ __name(function isFieldValidate2(field2, validateOn2) {
    var value = resolve$1(validateOn2, field2);
    return value === true || isArray$7(value) && value.includes(field2);
  }, "isFieldValidate");
  var validateOn = /* @__PURE__ */ function() {
    var _ref = _asyncToGenerator(/* @__PURE__ */ _regeneratorRuntime().mark(/* @__PURE__ */ __name(function _callee(option, defaultValue) {
      var _options$option;
      var results, fieldArr;
      return _regeneratorRuntime().wrap(/* @__PURE__ */ __name(function _callee$(_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            results = {};
            if (!isArray$7(options2[option])) {
              _context.next = 7;
              break;
            }
            _context.next = 4;
            return validate(options2[option]);
          case 4:
            results = _context.sent;
            _context.next = 12;
            break;
          case 7:
            _context.t0 = (_options$option = options2[option]) !== null && _options$option !== void 0 ? _options$option : defaultValue;
            if (!_context.t0) {
              _context.next = 12;
              break;
            }
            _context.next = 11;
            return validate();
          case 11:
            results = _context.sent;
          case 12:
            fieldArr = Object.keys(fields).filter(function(field2) {
              var _fields$field;
              return (_fields$field = fields[field2]) === null || _fields$field === void 0 || (_fields$field = _fields$field.options) === null || _fields$field === void 0 ? void 0 : _fields$field[option];
            }) || [];
            _context.t1 = isNotEmpty$1(fieldArr);
            if (!_context.t1) {
              _context.next = 18;
              break;
            }
            _context.next = 17;
            return validate(fieldArr);
          case 17:
            results = _context.sent;
          case 18:
            return _context.abrupt("return", results);
          case 19:
          case "end":
            return _context.stop();
        }
      }, "_callee$"), _callee);
    }, "_callee")));
    return /* @__PURE__ */ __name(function validateOn2(_x, _x2) {
      return _ref.apply(this, arguments);
    }, "validateOn");
  }();
  var validateFieldOn = /* @__PURE__ */ __name(function validateFieldOn2(field2, fieldOptions, option, defaultValue) {
    var _fieldOptions$option, _options$option2;
    ((_fieldOptions$option = fieldOptions === null || fieldOptions === void 0 ? void 0 : fieldOptions[option]) !== null && _fieldOptions$option !== void 0 ? _fieldOptions$option : isFieldValidate(field2, (_options$option2 = options2[option]) !== null && _options$option2 !== void 0 ? _options$option2 : defaultValue)) && validate(field2);
  }, "validateFieldOn");
  var defineField = /* @__PURE__ */ __name(function defineField2(field2, fieldOptions) {
    var _resolve;
    states[field2] || (states[field2] = getInitialState(field2, fieldOptions === null || fieldOptions === void 0 ? void 0 : fieldOptions.initialValue));
    var props = mergeProps$1((_resolve = resolve$1(fieldOptions, states[field2])) === null || _resolve === void 0 ? void 0 : _resolve.props, resolve$1(fieldOptions === null || fieldOptions === void 0 ? void 0 : fieldOptions.props, states[field2]), {
      name: field2,
      onBlur: /* @__PURE__ */ __name(function onBlur() {
        states[field2].touched = true;
        validateFieldOn(field2, fieldOptions, "validateOnBlur");
      }, "onBlur"),
      onInput: /* @__PURE__ */ __name(function onInput(event) {
        states[field2].value = event.hasOwnProperty("value") ? event.value : event.target.value;
      }, "onInput"),
      onChange: /* @__PURE__ */ __name(function onChange2(event) {
        states[field2].value = event.hasOwnProperty("value") ? event.value : event.target.type === "checkbox" || event.target.type === "radio" ? event.target.checked : event.target.value;
      }, "onChange"),
      onInvalid: /* @__PURE__ */ __name(function onInvalid(errors2) {
        var _errors$;
        states[field2].invalid = true;
        states[field2].errors = errors2;
        states[field2].error = (_errors$ = errors2 === null || errors2 === void 0 ? void 0 : errors2[0]) !== null && _errors$ !== void 0 ? _errors$ : null;
      }, "onInvalid")
    });
    fields[field2] = {
      props,
      states: states[field2],
      options: fieldOptions
    };
    watch(function() {
      return states[field2].value;
    }, function(newValue2, oldValue) {
      if (states[field2].pristine) {
        states[field2].pristine = false;
      }
      if (newValue2 !== oldValue) {
        states[field2].dirty = true;
      }
      validateFieldOn(field2, fieldOptions, "validateOnValueUpdate", true);
    });
    return [states[field2], props];
  }, "defineField");
  var handleSubmit = /* @__PURE__ */ __name(function handleSubmit2(callback) {
    return /* @__PURE__ */ function() {
      var _ref2 = _asyncToGenerator(/* @__PURE__ */ _regeneratorRuntime().mark(/* @__PURE__ */ __name(function _callee2(event) {
        var results;
        return _regeneratorRuntime().wrap(/* @__PURE__ */ __name(function _callee2$(_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              _context2.next = 2;
              return validateOn("validateOnSubmit", true);
            case 2:
              results = _context2.sent;
              return _context2.abrupt("return", callback(_objectSpread$8({
                originalEvent: event,
                valid: toValue$4(valid),
                states: toValue$4(states),
                reset: reset2
              }, results)));
            case 4:
            case "end":
              return _context2.stop();
          }
        }, "_callee2$"), _callee2);
      }, "_callee2")));
      return function(_x3) {
        return _ref2.apply(this, arguments);
      };
    }();
  }, "handleSubmit");
  var validate = /* @__PURE__ */ function() {
    var _ref3 = _asyncToGenerator(/* @__PURE__ */ _regeneratorRuntime().mark(/* @__PURE__ */ __name(function _callee3(field2) {
      var _yield$options$resolv, _options$resolver, _result, _result$errors;
      var resolverOptions, result, flattenFields, _i, _Object$entries, _Object$entries$_i, fieldName, fieldInst, _fieldInst$options, _result$errors$fieldN, _errors$2, fieldResolver, _yield$fieldResolver, fieldValue, fieldResult, errors2;
      return _regeneratorRuntime().wrap(/* @__PURE__ */ __name(function _callee3$(_context3) {
        while (1) switch (_context3.prev = _context3.next) {
          case 0:
            resolverOptions = Object.entries(states).reduce(function(acc, _ref4) {
              var _ref5 = _slicedToArray$4(_ref4, 2), key = _ref5[0], val = _ref5[1];
              acc.names.push(key);
              acc.values[key] = val.value;
              return acc;
            }, {
              names: [],
              values: {}
            });
            _context3.next = 3;
            return (_options$resolver = options2.resolver) === null || _options$resolver === void 0 ? void 0 : _options$resolver.call(options2, resolverOptions);
          case 3:
            _context3.t1 = _yield$options$resolv = _context3.sent;
            _context3.t0 = _context3.t1 !== null;
            if (!_context3.t0) {
              _context3.next = 7;
              break;
            }
            _context3.t0 = _yield$options$resolv !== void 0;
          case 7:
            if (!_context3.t0) {
              _context3.next = 11;
              break;
            }
            _context3.t2 = _yield$options$resolv;
            _context3.next = 12;
            break;
          case 11:
            _context3.t2 = {};
          case 12:
            result = _context3.t2;
            (_result$errors = (_result = result).errors) !== null && _result$errors !== void 0 ? _result$errors : _result.errors = {};
            flattenFields = [field2].flat();
            _i = 0, _Object$entries = Object.entries(fields);
          case 16:
            if (!(_i < _Object$entries.length)) {
              _context3.next = 44;
              break;
            }
            _Object$entries$_i = _slicedToArray$4(_Object$entries[_i], 2), fieldName = _Object$entries$_i[0], fieldInst = _Object$entries$_i[1];
            if (!(flattenFields.includes(fieldName) || !field2)) {
              _context3.next = 41;
              break;
            }
            fieldResolver = (_fieldInst$options = fieldInst.options) === null || _fieldInst$options === void 0 ? void 0 : _fieldInst$options.resolver;
            if (!fieldResolver) {
              _context3.next = 36;
              break;
            }
            fieldValue = fieldInst.states.value;
            _context3.next = 24;
            return fieldResolver({
              values: fieldValue,
              value: fieldValue,
              name: fieldName
            });
          case 24:
            _context3.t4 = _yield$fieldResolver = _context3.sent;
            _context3.t3 = _context3.t4 !== null;
            if (!_context3.t3) {
              _context3.next = 28;
              break;
            }
            _context3.t3 = _yield$fieldResolver !== void 0;
          case 28:
            if (!_context3.t3) {
              _context3.next = 32;
              break;
            }
            _context3.t5 = _yield$fieldResolver;
            _context3.next = 33;
            break;
          case 32:
            _context3.t5 = {};
          case 33:
            fieldResult = _context3.t5;
            isArray$7(fieldResult.errors) && (fieldResult.errors = _defineProperty$8({}, fieldName, fieldResult.errors));
            result = mergeKeys$1(result, fieldResult);
          case 36:
            errors2 = (_result$errors$fieldN = result.errors[fieldName]) !== null && _result$errors$fieldN !== void 0 ? _result$errors$fieldN : [];
            states[fieldName].invalid = errors2.length > 0;
            states[fieldName].valid = !states[fieldName].invalid;
            states[fieldName].errors = errors2;
            states[fieldName].error = (_errors$2 = errors2 === null || errors2 === void 0 ? void 0 : errors2[0]) !== null && _errors$2 !== void 0 ? _errors$2 : null;
          case 41:
            _i++;
            _context3.next = 16;
            break;
          case 44:
            return _context3.abrupt("return", result);
          case 45:
          case "end":
            return _context3.stop();
        }
      }, "_callee3$"), _callee3);
    }, "_callee3")));
    return /* @__PURE__ */ __name(function validate2(_x4) {
      return _ref3.apply(this, arguments);
    }, "validate");
  }();
  var reset2 = /* @__PURE__ */ __name(function reset3() {
    Object.keys(states).forEach(function(field2) {
      var _fields$field2;
      return fields[field2].states = states[field2] = getInitialState(field2, (_fields$field2 = fields[field2]) === null || _fields$field2 === void 0 || (_fields$field2 = _fields$field2.options) === null || _fields$field2 === void 0 ? void 0 : _fields$field2.initialValue);
    });
  }, "reset");
  var validateOnMounted = /* @__PURE__ */ __name(function validateOnMounted2() {
    validateOn("validateOnMount");
  }, "validateOnMounted");
  tryOnMounted$1(validateOnMounted);
  return {
    defineField,
    handleSubmit,
    validate,
    reset: reset2,
    valid,
    states,
    fields
  };
}, "useForm");
var __defProp$2 = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols;
var __hasOwnProp$1 = Object.prototype.hasOwnProperty;
var __propIsEnum$1 = Object.prototype.propertyIsEnumerable;
var __defNormalProp$2 = /* @__PURE__ */ __name((obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value, "__defNormalProp$2");
var __spreadValues$1 = /* @__PURE__ */ __name((a2, b2) => {
  for (var prop2 in b2 || (b2 = {}))
    if (__hasOwnProp$1.call(b2, prop2))
      __defNormalProp$2(a2, prop2, b2[prop2]);
  if (__getOwnPropSymbols$1)
    for (var prop2 of __getOwnPropSymbols$1(b2)) {
      if (__propIsEnum$1.call(b2, prop2))
        __defNormalProp$2(a2, prop2, b2[prop2]);
    }
  return a2;
}, "__spreadValues$1");
var __spreadProps = /* @__PURE__ */ __name((a2, b2) => __defProps(a2, __getOwnPropDescs(b2)), "__spreadProps");
var __objRest = /* @__PURE__ */ __name((source, exclude) => {
  var target = {};
  for (var prop2 in source)
    if (__hasOwnProp$1.call(source, prop2) && exclude.indexOf(prop2) < 0)
      target[prop2] = source[prop2];
  if (source != null && __getOwnPropSymbols$1)
    for (var prop2 of __getOwnPropSymbols$1(source)) {
      if (exclude.indexOf(prop2) < 0 && __propIsEnum$1.call(source, prop2))
        target[prop2] = source[prop2];
    }
  return target;
}, "__objRest");
function definePreset(...presets) {
  return mergeKeys$1(...presets);
}
__name(definePreset, "definePreset");
var ThemeService = EventBus();
var service_default = ThemeService;
function toTokenKey$1(str) {
  return isString$5(str) ? str.replace(/[A-Z]/g, (c2, i2) => i2 === 0 ? c2 : "." + c2.toLowerCase()).toLowerCase() : str;
}
__name(toTokenKey$1, "toTokenKey$1");
function merge(value1, value2) {
  if (isArray$7(value1)) {
    value1.push(...value2 || []);
  } else if (isObject$a(value1)) {
    Object.assign(value1, value2);
  }
}
__name(merge, "merge");
function toValue$1(value) {
  return isObject$a(value) && value.hasOwnProperty("value") && value.hasOwnProperty("type") ? value.value : value;
}
__name(toValue$1, "toValue$1");
function toUnit(value, variable = "") {
  const excludedProperties = ["opacity", "z-index", "line-height", "font-weight", "flex", "flex-grow", "flex-shrink", "order"];
  if (!excludedProperties.some((property) => variable.endsWith(property))) {
    const val = `${value}`.trim();
    const valArr = val.split(" ");
    return valArr.map((v2) => isNumber$4(v2) ? `${v2}px` : v2).join(" ");
  }
  return value;
}
__name(toUnit, "toUnit");
function toNormalizePrefix(prefix) {
  return prefix.replaceAll(/ /g, "").replace(/[^\w]/g, "-");
}
__name(toNormalizePrefix, "toNormalizePrefix");
function toNormalizeVariable(prefix = "", variable = "") {
  return toNormalizePrefix(`${isString$5(prefix, false) && isString$5(variable, false) ? `${prefix}-` : prefix}${variable}`);
}
__name(toNormalizeVariable, "toNormalizeVariable");
function getVariableName(prefix = "", variable = "") {
  return `--${toNormalizeVariable(prefix, variable)}`;
}
__name(getVariableName, "getVariableName");
function hasOddBraces(str = "") {
  const openBraces = (str.match(/{/g) || []).length;
  const closeBraces = (str.match(/}/g) || []).length;
  return (openBraces + closeBraces) % 2 !== 0;
}
__name(hasOddBraces, "hasOddBraces");
function getVariableValue(value, variable = "", prefix = "", excludedKeyRegexes = [], fallback) {
  if (isString$5(value)) {
    const regex2 = /{([^}]*)}/g;
    const val = value.trim();
    if (hasOddBraces(val)) {
      return void 0;
    } else if (matchRegex$1(val, regex2)) {
      const _val = val.replaceAll(regex2, (v2) => {
        const path = v2.replace(/{|}/g, "");
        const keys2 = path.split(".").filter((_v) => !excludedKeyRegexes.some((_r) => matchRegex$1(_v, _r)));
        return `var(${getVariableName(prefix, toKebabCase$1(keys2.join("-")))}${isNotEmpty$1(fallback) ? `, ${fallback}` : ""})`;
      });
      const calculationRegex = /(\d+\s+[\+\-\*\/]\s+\d+)/g;
      const cleanedVarRegex = /var\([^)]+\)/g;
      return matchRegex$1(_val.replace(cleanedVarRegex, "0"), calculationRegex) ? `calc(${_val})` : _val;
    }
    return val;
  } else if (isNumber$4(value)) {
    return value;
  }
  return void 0;
}
__name(getVariableValue, "getVariableValue");
function getComputedValue(obj = {}, value) {
  if (isString$5(value)) {
    const regex2 = /{([^}]*)}/g;
    const val = value.trim();
    return matchRegex$1(val, regex2) ? val.replaceAll(regex2, (v2) => getKeyValue$1(obj, v2.replace(/{|}/g, ""))) : val;
  } else if (isNumber$4(value)) {
    return value;
  }
  return void 0;
}
__name(getComputedValue, "getComputedValue");
function setProperty(properties, key, value) {
  if (isString$5(key, false)) {
    properties.push(`${key}:${value};`);
  }
}
__name(setProperty, "setProperty");
function getRule(selector, properties) {
  if (selector) {
    return `${selector}{${properties}}`;
  }
  return "";
}
__name(getRule, "getRule");
function normalizeColor(color2) {
  if (color2.length === 4) {
    return `#${color2[1]}${color2[1]}${color2[2]}${color2[2]}${color2[3]}${color2[3]}`;
  }
  return color2;
}
__name(normalizeColor, "normalizeColor");
function hexToRgb$1(hex) {
  var bigint = parseInt(hex.substring(1), 16);
  var r2 = bigint >> 16 & 255;
  var g2 = bigint >> 8 & 255;
  var b2 = bigint & 255;
  return { r: r2, g: g2, b: b2 };
}
__name(hexToRgb$1, "hexToRgb$1");
function rgbToHex(r2, g2, b2) {
  return `#${r2.toString(16).padStart(2, "0")}${g2.toString(16).padStart(2, "0")}${b2.toString(16).padStart(2, "0")}`;
}
__name(rgbToHex, "rgbToHex");
var mix_default = /* @__PURE__ */ __name((color1, color2, weight) => {
  color1 = normalizeColor(color1);
  color2 = normalizeColor(color2);
  var p2 = weight / 100;
  var w2 = p2 * 2 - 1;
  var w1 = (w2 + 1) / 2;
  var w22 = 1 - w1;
  var rgb1 = hexToRgb$1(color1);
  var rgb2 = hexToRgb$1(color2);
  var r2 = Math.round(rgb1.r * w1 + rgb2.r * w22);
  var g2 = Math.round(rgb1.g * w1 + rgb2.g * w22);
  var b2 = Math.round(rgb1.b * w1 + rgb2.b * w22);
  return rgbToHex(r2, g2, b2);
}, "mix_default");
var shade_default = /* @__PURE__ */ __name((color2, percent) => mix_default("#000000", color2, percent), "shade_default");
var tint_default = /* @__PURE__ */ __name((color2, percent) => mix_default("#ffffff", color2, percent), "tint_default");
var scales = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 950];
var palette_default = /* @__PURE__ */ __name((color2) => {
  if (/{([^}]*)}/g.test(color2)) {
    const token = color2.replace(/{|}/g, "");
    return scales.reduce((acc, scale) => (acc[scale] = `{${token}.${scale}}`, acc), {});
  }
  return typeof color2 === "string" ? scales.reduce((acc, scale, i2) => (acc[scale] = i2 <= 5 ? tint_default(color2, (5 - i2) * 19) : shade_default(color2, (i2 - 5) * 15), acc), {}) : color2;
}, "palette_default");
var $dt = /* @__PURE__ */ __name((tokenPath) => {
  var _a2;
  const theme3 = config_default.getTheme();
  const variable = dtwt(theme3, tokenPath, void 0, "variable");
  const name2 = (_a2 = variable == null ? void 0 : variable.match(/--[\w-]+/g)) == null ? void 0 : _a2[0];
  const value = dtwt(theme3, tokenPath, void 0, "value");
  return {
    name: name2,
    variable,
    value
  };
}, "$dt");
var dt = /* @__PURE__ */ __name((...args) => {
  return dtwt(config_default.getTheme(), ...args);
}, "dt");
var dtwt = /* @__PURE__ */ __name((theme3 = {}, tokenPath, fallback, type) => {
  if (tokenPath) {
    const { variable: VARIABLE, options: OPTIONS } = config_default.defaults || {};
    const { prefix, transform } = (theme3 == null ? void 0 : theme3.options) || OPTIONS || {};
    const regex2 = /{([^}]*)}/g;
    const token = matchRegex$1(tokenPath, regex2) ? tokenPath : `{${tokenPath}}`;
    const isStrictTransform = type === "value" || isEmpty$2(type) && transform === "strict";
    return isStrictTransform ? config_default.getTokenValue(tokenPath) : getVariableValue(token, void 0, prefix, [VARIABLE.excludedKeyRegex], fallback);
  }
  return "";
}, "dtwt");
function css$1(style2) {
  return resolve$1(style2, { dt });
}
__name(css$1, "css$1");
var $t = /* @__PURE__ */ __name((theme3 = {}) => {
  let { preset: _preset, options: _options } = theme3;
  return {
    preset(value) {
      _preset = _preset ? mergeKeys$1(_preset, value) : value;
      return this;
    },
    options(value) {
      _options = _options ? __spreadValues$1(__spreadValues$1({}, _options), value) : value;
      return this;
    },
    // features
    primaryPalette(primary) {
      const { semantic } = _preset || {};
      _preset = __spreadProps(__spreadValues$1({}, _preset), { semantic: __spreadProps(__spreadValues$1({}, semantic), { primary }) });
      return this;
    },
    surfacePalette(surface) {
      var _a2, _b;
      const { semantic } = _preset || {};
      const lightSurface = (surface == null ? void 0 : surface.hasOwnProperty("light")) ? surface == null ? void 0 : surface.light : surface;
      const darkSurface = (surface == null ? void 0 : surface.hasOwnProperty("dark")) ? surface == null ? void 0 : surface.dark : surface;
      const newColorScheme = {
        colorScheme: {
          light: __spreadValues$1(__spreadValues$1({}, (_a2 = semantic == null ? void 0 : semantic.colorScheme) == null ? void 0 : _a2.light), !!lightSurface && { surface: lightSurface }),
          dark: __spreadValues$1(__spreadValues$1({}, (_b = semantic == null ? void 0 : semantic.colorScheme) == null ? void 0 : _b.dark), !!darkSurface && { surface: darkSurface })
        }
      };
      _preset = __spreadProps(__spreadValues$1({}, _preset), { semantic: __spreadValues$1(__spreadValues$1({}, semantic), newColorScheme) });
      return this;
    },
    // actions
    define({ useDefaultPreset = false, useDefaultOptions = false } = {}) {
      return {
        preset: useDefaultPreset ? config_default.getPreset() : _preset,
        options: useDefaultOptions ? config_default.getOptions() : _options
      };
    },
    update({ mergePresets = true, mergeOptions: mergeOptions2 = true } = {}) {
      const newTheme = {
        preset: mergePresets ? mergeKeys$1(config_default.getPreset(), _preset) : _preset,
        options: mergeOptions2 ? __spreadValues$1(__spreadValues$1({}, config_default.getOptions()), _options) : _options
      };
      config_default.setTheme(newTheme);
      return newTheme;
    },
    use(options2) {
      const newTheme = this.define(options2);
      config_default.setTheme(newTheme);
      return newTheme;
    }
  };
}, "$t");
function toVariables_default(theme3, options2 = {}) {
  const VARIABLE = config_default.defaults.variable;
  const { prefix = VARIABLE.prefix, selector = VARIABLE.selector, excludedKeyRegex = VARIABLE.excludedKeyRegex } = options2;
  const _toVariables = /* @__PURE__ */ __name((_theme, _prefix = "") => {
    return Object.entries(_theme).reduce(
      (acc, [key, value]) => {
        const px = matchRegex$1(key, excludedKeyRegex) ? toNormalizeVariable(_prefix) : toNormalizeVariable(_prefix, toKebabCase$1(key));
        const v2 = toValue$1(value);
        if (isObject$a(v2)) {
          const { variables: variables2, tokens: tokens2 } = _toVariables(v2, px);
          merge(acc["tokens"], tokens2);
          merge(acc["variables"], variables2);
        } else {
          acc["tokens"].push((prefix ? px.replace(`${prefix}-`, "") : px).replaceAll("-", "."));
          setProperty(acc["variables"], getVariableName(px), getVariableValue(v2, px, prefix, [excludedKeyRegex]));
        }
        return acc;
      },
      { variables: [], tokens: [] }
    );
  }, "_toVariables");
  const { variables, tokens } = _toVariables(theme3, prefix);
  return {
    value: variables,
    tokens,
    declarations: variables.join(""),
    css: getRule(selector, variables.join(""))
  };
}
__name(toVariables_default, "toVariables_default");
var themeUtils_default = {
  regex: {
    rules: {
      class: {
        pattern: /^\.([a-zA-Z][\w-]*)$/,
        resolve(value) {
          return { type: "class", selector: value, matched: this.pattern.test(value.trim()) };
        }
      },
      attr: {
        pattern: /^\[(.*)\]$/,
        resolve(value) {
          return { type: "attr", selector: `:root${value}`, matched: this.pattern.test(value.trim()) };
        }
      },
      media: {
        pattern: /^@media (.*)$/,
        resolve(value) {
          return { type: "media", selector: `${value}{:root{[CSS]}}`, matched: this.pattern.test(value.trim()) };
        }
      },
      system: {
        pattern: /^system$/,
        resolve(value) {
          return { type: "system", selector: "@media (prefers-color-scheme: dark){:root{[CSS]}}", matched: this.pattern.test(value.trim()) };
        }
      },
      custom: {
        resolve(value) {
          return { type: "custom", selector: value, matched: true };
        }
      }
    },
    resolve(value) {
      const rules = Object.keys(this.rules).filter((k2) => k2 !== "custom").map((r2) => this.rules[r2]);
      return [value].flat().map((v2) => {
        var _a2;
        return (_a2 = rules.map((r2) => r2.resolve(v2)).find((rr) => rr.matched)) != null ? _a2 : this.rules.custom.resolve(v2);
      });
    }
  },
  _toVariables(theme3, options2) {
    return toVariables_default(theme3, { prefix: options2 == null ? void 0 : options2.prefix });
  },
  getCommon({ name: name2 = "", theme: theme3 = {}, params, set: set3, defaults: defaults2 }) {
    var _e2, _f, _g, _h, _i, _j, _k;
    const { preset, options: options2 } = theme3;
    let primitive_css, primitive_tokens, semantic_css, semantic_tokens, global_css, global_tokens, style2;
    if (isNotEmpty$1(preset) && options2.transform !== "strict") {
      const { primitive, semantic, extend: extend3 } = preset;
      const _a2 = semantic || {}, { colorScheme } = _a2, sRest = __objRest(_a2, ["colorScheme"]);
      const _b = extend3 || {}, { colorScheme: eColorScheme } = _b, eRest = __objRest(_b, ["colorScheme"]);
      const _c = colorScheme || {}, { dark: dark2 } = _c, csRest = __objRest(_c, ["dark"]);
      const _d = eColorScheme || {}, { dark: eDark } = _d, ecsRest = __objRest(_d, ["dark"]);
      const prim_var = isNotEmpty$1(primitive) ? this._toVariables({ primitive }, options2) : {};
      const sRest_var = isNotEmpty$1(sRest) ? this._toVariables({ semantic: sRest }, options2) : {};
      const csRest_var = isNotEmpty$1(csRest) ? this._toVariables({ light: csRest }, options2) : {};
      const csDark_var = isNotEmpty$1(dark2) ? this._toVariables({ dark: dark2 }, options2) : {};
      const eRest_var = isNotEmpty$1(eRest) ? this._toVariables({ semantic: eRest }, options2) : {};
      const ecsRest_var = isNotEmpty$1(ecsRest) ? this._toVariables({ light: ecsRest }, options2) : {};
      const ecsDark_var = isNotEmpty$1(eDark) ? this._toVariables({ dark: eDark }, options2) : {};
      const [prim_css, prim_tokens] = [(_e2 = prim_var.declarations) != null ? _e2 : "", prim_var.tokens];
      const [sRest_css, sRest_tokens] = [(_f = sRest_var.declarations) != null ? _f : "", sRest_var.tokens || []];
      const [csRest_css, csRest_tokens] = [(_g = csRest_var.declarations) != null ? _g : "", csRest_var.tokens || []];
      const [csDark_css, csDark_tokens] = [(_h = csDark_var.declarations) != null ? _h : "", csDark_var.tokens || []];
      const [eRest_css, eRest_tokens] = [(_i = eRest_var.declarations) != null ? _i : "", eRest_var.tokens || []];
      const [ecsRest_css, ecsRest_tokens] = [(_j = ecsRest_var.declarations) != null ? _j : "", ecsRest_var.tokens || []];
      const [ecsDark_css, ecsDark_tokens] = [(_k = ecsDark_var.declarations) != null ? _k : "", ecsDark_var.tokens || []];
      primitive_css = this.transformCSS(name2, prim_css, "light", "variable", options2, set3, defaults2);
      primitive_tokens = prim_tokens;
      const semantic_light_css = this.transformCSS(name2, `${sRest_css}${csRest_css}`, "light", "variable", options2, set3, defaults2);
      const semantic_dark_css = this.transformCSS(name2, `${csDark_css}`, "dark", "variable", options2, set3, defaults2);
      semantic_css = `${semantic_light_css}${semantic_dark_css}`;
      semantic_tokens = [.../* @__PURE__ */ new Set([...sRest_tokens, ...csRest_tokens, ...csDark_tokens])];
      const global_light_css = this.transformCSS(name2, `${eRest_css}${ecsRest_css}color-scheme:light`, "light", "variable", options2, set3, defaults2);
      const global_dark_css = this.transformCSS(name2, `${ecsDark_css}color-scheme:dark`, "dark", "variable", options2, set3, defaults2);
      global_css = `${global_light_css}${global_dark_css}`;
      global_tokens = [.../* @__PURE__ */ new Set([...eRest_tokens, ...ecsRest_tokens, ...ecsDark_tokens])];
      style2 = resolve$1(preset.css, { dt });
    }
    return {
      primitive: {
        css: primitive_css,
        tokens: primitive_tokens
      },
      semantic: {
        css: semantic_css,
        tokens: semantic_tokens
      },
      global: {
        css: global_css,
        tokens: global_tokens
      },
      style: style2
    };
  },
  getPreset({ name: name2 = "", preset = {}, options: options2, params, set: set3, defaults: defaults2, selector }) {
    var _e2, _f, _g;
    let p_css, p_tokens, p_style;
    if (isNotEmpty$1(preset) && options2.transform !== "strict") {
      const _name = name2.replace("-directive", "");
      const _a2 = preset, { colorScheme, extend: extend3, css: css22 } = _a2, vRest = __objRest(_a2, ["colorScheme", "extend", "css"]);
      const _b = extend3 || {}, { colorScheme: eColorScheme } = _b, evRest = __objRest(_b, ["colorScheme"]);
      const _c = colorScheme || {}, { dark: dark2 } = _c, csRest = __objRest(_c, ["dark"]);
      const _d = eColorScheme || {}, { dark: ecsDark } = _d, ecsRest = __objRest(_d, ["dark"]);
      const vRest_var = isNotEmpty$1(vRest) ? this._toVariables({ [_name]: __spreadValues$1(__spreadValues$1({}, vRest), evRest) }, options2) : {};
      const csRest_var = isNotEmpty$1(csRest) ? this._toVariables({ [_name]: __spreadValues$1(__spreadValues$1({}, csRest), ecsRest) }, options2) : {};
      const csDark_var = isNotEmpty$1(dark2) ? this._toVariables({ [_name]: __spreadValues$1(__spreadValues$1({}, dark2), ecsDark) }, options2) : {};
      const [vRest_css, vRest_tokens] = [(_e2 = vRest_var.declarations) != null ? _e2 : "", vRest_var.tokens || []];
      const [csRest_css, csRest_tokens] = [(_f = csRest_var.declarations) != null ? _f : "", csRest_var.tokens || []];
      const [csDark_css, csDark_tokens] = [(_g = csDark_var.declarations) != null ? _g : "", csDark_var.tokens || []];
      const light_variable_css = this.transformCSS(_name, `${vRest_css}${csRest_css}`, "light", "variable", options2, set3, defaults2, selector);
      const dark_variable_css = this.transformCSS(_name, csDark_css, "dark", "variable", options2, set3, defaults2, selector);
      p_css = `${light_variable_css}${dark_variable_css}`;
      p_tokens = [.../* @__PURE__ */ new Set([...vRest_tokens, ...csRest_tokens, ...csDark_tokens])];
      p_style = resolve$1(css22, { dt });
    }
    return {
      css: p_css,
      tokens: p_tokens,
      style: p_style
    };
  },
  getPresetC({ name: name2 = "", theme: theme3 = {}, params, set: set3, defaults: defaults2 }) {
    var _a2;
    const { preset, options: options2 } = theme3;
    const cPreset = (_a2 = preset == null ? void 0 : preset.components) == null ? void 0 : _a2[name2];
    return this.getPreset({ name: name2, preset: cPreset, options: options2, params, set: set3, defaults: defaults2 });
  },
  getPresetD({ name: name2 = "", theme: theme3 = {}, params, set: set3, defaults: defaults2 }) {
    var _a2;
    const dName = name2.replace("-directive", "");
    const { preset, options: options2 } = theme3;
    const dPreset = (_a2 = preset == null ? void 0 : preset.directives) == null ? void 0 : _a2[dName];
    return this.getPreset({ name: dName, preset: dPreset, options: options2, params, set: set3, defaults: defaults2 });
  },
  applyDarkColorScheme(options2) {
    return !(options2.darkModeSelector === "none" || options2.darkModeSelector === false);
  },
  getColorSchemeOption(options2, defaults2) {
    var _a2;
    return this.applyDarkColorScheme(options2) ? this.regex.resolve(options2.darkModeSelector === true ? defaults2.options.darkModeSelector : (_a2 = options2.darkModeSelector) != null ? _a2 : defaults2.options.darkModeSelector) : [];
  },
  getLayerOrder(name2, options2 = {}, params, defaults2) {
    const { cssLayer } = options2;
    if (cssLayer) {
      const order = resolve$1(cssLayer.order || "primeui", params);
      return `@layer ${order}`;
    }
    return "";
  },
  getCommonStyleSheet({ name: name2 = "", theme: theme3 = {}, params, props = {}, set: set3, defaults: defaults2 }) {
    const common = this.getCommon({ name: name2, theme: theme3, params, set: set3, defaults: defaults2 });
    const _props = Object.entries(props).reduce((acc, [k2, v2]) => acc.push(`${k2}="${v2}"`) && acc, []).join(" ");
    return Object.entries(common || {}).reduce((acc, [key, value]) => {
      if (value == null ? void 0 : value.css) {
        const _css = minifyCSS$1(value == null ? void 0 : value.css);
        const id2 = `${key}-variables`;
        acc.push(`<style type="text/css" data-primevue-style-id="${id2}" ${_props}>${_css}</style>`);
      }
      return acc;
    }, []).join("");
  },
  getStyleSheet({ name: name2 = "", theme: theme3 = {}, params, props = {}, set: set3, defaults: defaults2 }) {
    var _a2;
    const options2 = { name: name2, theme: theme3, params, set: set3, defaults: defaults2 };
    const preset_css = (_a2 = name2.includes("-directive") ? this.getPresetD(options2) : this.getPresetC(options2)) == null ? void 0 : _a2.css;
    const _props = Object.entries(props).reduce((acc, [k2, v2]) => acc.push(`${k2}="${v2}"`) && acc, []).join(" ");
    return preset_css ? `<style type="text/css" data-primevue-style-id="${name2}-variables" ${_props}>${minifyCSS$1(preset_css)}</style>` : "";
  },
  createTokens(obj = {}, defaults2, parentKey = "", parentPath = "", tokens = {}) {
    Object.entries(obj).forEach(([key, value]) => {
      const currentKey = matchRegex$1(key, defaults2.variable.excludedKeyRegex) ? parentKey : parentKey ? `${parentKey}.${toTokenKey$2(key)}` : toTokenKey$2(key);
      const currentPath = parentPath ? `${parentPath}.${key}` : key;
      if (isObject$a(value)) {
        this.createTokens(value, defaults2, currentKey, currentPath, tokens);
      } else {
        tokens[currentKey] || (tokens[currentKey] = {
          paths: [],
          computed(colorScheme, tokenPathMap = {}) {
            var _a2, _b;
            if (this.paths.length === 1) {
              return (_a2 = this.paths[0]) == null ? void 0 : _a2.computed(this.paths[0].scheme, tokenPathMap["binding"]);
            } else if (colorScheme && colorScheme !== "none") {
              return (_b = this.paths.find((p2) => p2.scheme === colorScheme)) == null ? void 0 : _b.computed(colorScheme, tokenPathMap["binding"]);
            }
            return this.paths.map((p2) => p2.computed(p2.scheme, tokenPathMap[p2.scheme]));
          }
        });
        tokens[currentKey].paths.push({
          path: currentPath,
          value,
          scheme: currentPath.includes("colorScheme.light") ? "light" : currentPath.includes("colorScheme.dark") ? "dark" : "none",
          computed(colorScheme, tokenPathMap = {}) {
            const regex2 = /{([^}]*)}/g;
            let computedValue = value;
            tokenPathMap["name"] = this.path;
            tokenPathMap["binding"] || (tokenPathMap["binding"] = {});
            if (matchRegex$1(value, regex2)) {
              const val = value.trim();
              const _val = val.replaceAll(regex2, (v2) => {
                var _a2;
                const path = v2.replace(/{|}/g, "");
                const computed2 = (_a2 = tokens[path]) == null ? void 0 : _a2.computed(colorScheme, tokenPathMap);
                return isArray$7(computed2) && computed2.length === 2 ? `light-dark(${computed2[0].value},${computed2[1].value})` : computed2 == null ? void 0 : computed2.value;
              });
              const calculationRegex = /(\d+\w*\s+[\+\-\*\/]\s+\d+\w*)/g;
              const cleanedVarRegex = /var\([^)]+\)/g;
              computedValue = matchRegex$1(_val.replace(cleanedVarRegex, "0"), calculationRegex) ? `calc(${_val})` : _val;
            }
            isEmpty$2(tokenPathMap["binding"]) && delete tokenPathMap["binding"];
            return {
              colorScheme,
              path: this.path,
              paths: tokenPathMap,
              value: computedValue.includes("undefined") ? void 0 : computedValue
            };
          }
        });
      }
    });
    return tokens;
  },
  getTokenValue(tokens, path, defaults2) {
    var _a2;
    const normalizePath2 = /* @__PURE__ */ __name((str) => {
      const strArr = str.split(".");
      return strArr.filter((s2) => !matchRegex$1(s2.toLowerCase(), defaults2.variable.excludedKeyRegex)).join(".");
    }, "normalizePath");
    const token = normalizePath2(path);
    const colorScheme = path.includes("colorScheme.light") ? "light" : path.includes("colorScheme.dark") ? "dark" : void 0;
    const computedValues = [(_a2 = tokens[token]) == null ? void 0 : _a2.computed(colorScheme)].flat().filter((computed2) => computed2);
    return computedValues.length === 1 ? computedValues[0].value : computedValues.reduce((acc = {}, computed2) => {
      const _a22 = computed2, { colorScheme: cs } = _a22, rest = __objRest(_a22, ["colorScheme"]);
      acc[cs] = rest;
      return acc;
    }, void 0);
  },
  getSelectorRule(selector1, selector2, type, css22) {
    return type === "class" || type === "attr" ? getRule(isNotEmpty$1(selector2) ? `${selector1}${selector2},${selector1} ${selector2}` : selector1, css22) : getRule(selector1, isNotEmpty$1(selector2) ? getRule(selector2, css22) : css22);
  },
  transformCSS(name2, css22, mode, type, options2 = {}, set3, defaults2, selector) {
    if (isNotEmpty$1(css22)) {
      const { cssLayer } = options2;
      if (type !== "style") {
        const colorSchemeOption = this.getColorSchemeOption(options2, defaults2);
        css22 = mode === "dark" ? colorSchemeOption.reduce((acc, { type: type2, selector: _selector }) => {
          if (isNotEmpty$1(_selector)) {
            acc += _selector.includes("[CSS]") ? _selector.replace("[CSS]", css22) : this.getSelectorRule(_selector, selector, type2, css22);
          }
          return acc;
        }, "") : getRule(selector != null ? selector : ":root", css22);
      }
      if (cssLayer) {
        const layerOptions = {
          name: "primeui",
          order: "primeui"
        };
        isObject$a(cssLayer) && (layerOptions.name = resolve$1(cssLayer.name, { name: name2, type }));
        if (isNotEmpty$1(layerOptions.name)) {
          css22 = getRule(`@layer ${layerOptions.name}`, css22);
          set3 == null ? void 0 : set3.layerNames(layerOptions.name);
        }
      }
      return css22;
    }
    return "";
  }
};
var config_default = {
  defaults: {
    variable: {
      prefix: "p",
      selector: ":root",
      excludedKeyRegex: /^(primitive|semantic|components|directives|variables|colorscheme|light|dark|common|root|states|extend|css)$/gi
    },
    options: {
      prefix: "p",
      darkModeSelector: "system",
      cssLayer: false
    }
  },
  _theme: void 0,
  _layerNames: /* @__PURE__ */ new Set(),
  _loadedStyleNames: /* @__PURE__ */ new Set(),
  _loadingStyles: /* @__PURE__ */ new Set(),
  _tokens: {},
  update(newValues = {}) {
    const { theme: theme3 } = newValues;
    if (theme3) {
      this._theme = __spreadProps(__spreadValues$1({}, theme3), {
        options: __spreadValues$1(__spreadValues$1({}, this.defaults.options), theme3.options)
      });
      this._tokens = themeUtils_default.createTokens(this.preset, this.defaults);
      this.clearLoadedStyleNames();
    }
  },
  get theme() {
    return this._theme;
  },
  get preset() {
    var _a2;
    return ((_a2 = this.theme) == null ? void 0 : _a2.preset) || {};
  },
  get options() {
    var _a2;
    return ((_a2 = this.theme) == null ? void 0 : _a2.options) || {};
  },
  get tokens() {
    return this._tokens;
  },
  getTheme() {
    return this.theme;
  },
  setTheme(newValue2) {
    this.update({ theme: newValue2 });
    service_default.emit("theme:change", newValue2);
  },
  getPreset() {
    return this.preset;
  },
  setPreset(newValue2) {
    this._theme = __spreadProps(__spreadValues$1({}, this.theme), { preset: newValue2 });
    this._tokens = themeUtils_default.createTokens(newValue2, this.defaults);
    this.clearLoadedStyleNames();
    service_default.emit("preset:change", newValue2);
    service_default.emit("theme:change", this.theme);
  },
  getOptions() {
    return this.options;
  },
  setOptions(newValue2) {
    this._theme = __spreadProps(__spreadValues$1({}, this.theme), { options: newValue2 });
    this.clearLoadedStyleNames();
    service_default.emit("options:change", newValue2);
    service_default.emit("theme:change", this.theme);
  },
  getLayerNames() {
    return [...this._layerNames];
  },
  setLayerNames(layerName) {
    this._layerNames.add(layerName);
  },
  getLoadedStyleNames() {
    return this._loadedStyleNames;
  },
  isStyleNameLoaded(name2) {
    return this._loadedStyleNames.has(name2);
  },
  setLoadedStyleName(name2) {
    this._loadedStyleNames.add(name2);
  },
  deleteLoadedStyleName(name2) {
    this._loadedStyleNames.delete(name2);
  },
  clearLoadedStyleNames() {
    this._loadedStyleNames.clear();
  },
  getTokenValue(tokenPath) {
    return themeUtils_default.getTokenValue(this.tokens, tokenPath, this.defaults);
  },
  getCommon(name2 = "", params) {
    return themeUtils_default.getCommon({ name: name2, theme: this.theme, params, defaults: this.defaults, set: { layerNames: this.setLayerNames.bind(this) } });
  },
  getComponent(name2 = "", params) {
    const options2 = { name: name2, theme: this.theme, params, defaults: this.defaults, set: { layerNames: this.setLayerNames.bind(this) } };
    return themeUtils_default.getPresetC(options2);
  },
  getDirective(name2 = "", params) {
    const options2 = { name: name2, theme: this.theme, params, defaults: this.defaults, set: { layerNames: this.setLayerNames.bind(this) } };
    return themeUtils_default.getPresetD(options2);
  },
  getCustomPreset(name2 = "", preset, selector, params) {
    const options2 = { name: name2, preset, options: this.options, selector, params, defaults: this.defaults, set: { layerNames: this.setLayerNames.bind(this) } };
    return themeUtils_default.getPreset(options2);
  },
  getLayerOrderCSS(name2 = "") {
    return themeUtils_default.getLayerOrder(name2, this.options, { names: this.getLayerNames() }, this.defaults);
  },
  transformCSS(name2 = "", css22, type = "style", mode) {
    return themeUtils_default.transformCSS(name2, css22, mode, type, this.options, { layerNames: this.setLayerNames.bind(this) }, this.defaults);
  },
  getCommonStyleSheet(name2 = "", params, props = {}) {
    return themeUtils_default.getCommonStyleSheet({ name: name2, theme: this.theme, params, props, defaults: this.defaults, set: { layerNames: this.setLayerNames.bind(this) } });
  },
  getStyleSheet(name2, params, props = {}) {
    return themeUtils_default.getStyleSheet({ name: name2, theme: this.theme, params, props, defaults: this.defaults, set: { layerNames: this.setLayerNames.bind(this) } });
  },
  onStyleMounted(name2) {
    this._loadingStyles.add(name2);
  },
  onStyleUpdated(name2) {
    this._loadingStyles.add(name2);
  },
  onStyleLoaded(event, { name: name2 }) {
    if (this._loadingStyles.size) {
      this._loadingStyles.delete(name2);
      service_default.emit(`theme:${name2}:load`, event);
      !this._loadingStyles.size && service_default.emit("theme:load");
    }
  }
};
function updatePreset(...presets) {
  const newPreset = mergeKeys$1(config_default.getPreset(), ...presets);
  config_default.setPreset(newPreset);
  return newPreset;
}
__name(updatePreset, "updatePreset");
function updatePrimaryPalette(primary) {
  return $t().primaryPalette(primary).update().preset;
}
__name(updatePrimaryPalette, "updatePrimaryPalette");
function updateSurfacePalette(palette) {
  return $t().surfacePalette(palette).update().preset;
}
__name(updateSurfacePalette, "updateSurfacePalette");
function usePreset(...presets) {
  const newPreset = mergeKeys$1(...presets);
  config_default.setPreset(newPreset);
  return newPreset;
}
__name(usePreset, "usePreset");
function useTheme(theme3) {
  return $t(theme3).update({ mergePresets: false });
}
__name(useTheme, "useTheme");
var Base = {
  _loadedStyleNames: /* @__PURE__ */ new Set(),
  getLoadedStyleNames: /* @__PURE__ */ __name(function getLoadedStyleNames() {
    return this._loadedStyleNames;
  }, "getLoadedStyleNames"),
  isStyleNameLoaded: /* @__PURE__ */ __name(function isStyleNameLoaded(name2) {
    return this._loadedStyleNames.has(name2);
  }, "isStyleNameLoaded"),
  setLoadedStyleName: /* @__PURE__ */ __name(function setLoadedStyleName(name2) {
    this._loadedStyleNames.add(name2);
  }, "setLoadedStyleName"),
  deleteLoadedStyleName: /* @__PURE__ */ __name(function deleteLoadedStyleName(name2) {
    this._loadedStyleNames["delete"](name2);
  }, "deleteLoadedStyleName"),
  clearLoadedStyleNames: /* @__PURE__ */ __name(function clearLoadedStyleNames() {
    this._loadedStyleNames.clear();
  }, "clearLoadedStyleNames")
};
function _typeof$5(o2) {
  "@babel/helpers - typeof";
  return _typeof$5 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o3) {
    return typeof o3;
  } : function(o3) {
    return o3 && "function" == typeof Symbol && o3.constructor === Symbol && o3 !== Symbol.prototype ? "symbol" : typeof o3;
  }, _typeof$5(o2);
}
__name(_typeof$5, "_typeof$5");
function ownKeys$7(e2, r2) {
  var t2 = Object.keys(e2);
  if (Object.getOwnPropertySymbols) {
    var o2 = Object.getOwnPropertySymbols(e2);
    r2 && (o2 = o2.filter(function(r3) {
      return Object.getOwnPropertyDescriptor(e2, r3).enumerable;
    })), t2.push.apply(t2, o2);
  }
  return t2;
}
__name(ownKeys$7, "ownKeys$7");
function _objectSpread$7(e2) {
  for (var r2 = 1; r2 < arguments.length; r2++) {
    var t2 = null != arguments[r2] ? arguments[r2] : {};
    r2 % 2 ? ownKeys$7(Object(t2), true).forEach(function(r3) {
      _defineProperty$7(e2, r3, t2[r3]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e2, Object.getOwnPropertyDescriptors(t2)) : ownKeys$7(Object(t2)).forEach(function(r3) {
      Object.defineProperty(e2, r3, Object.getOwnPropertyDescriptor(t2, r3));
    });
  }
  return e2;
}
__name(_objectSpread$7, "_objectSpread$7");
function _defineProperty$7(e2, r2, t2) {
  return (r2 = _toPropertyKey$4(r2)) in e2 ? Object.defineProperty(e2, r2, { value: t2, enumerable: true, configurable: true, writable: true }) : e2[r2] = t2, e2;
}
__name(_defineProperty$7, "_defineProperty$7");
function _toPropertyKey$4(t2) {
  var i2 = _toPrimitive$4(t2, "string");
  return "symbol" == _typeof$5(i2) ? i2 : i2 + "";
}
__name(_toPropertyKey$4, "_toPropertyKey$4");
function _toPrimitive$4(t2, r2) {
  if ("object" != _typeof$5(t2) || !t2) return t2;
  var e2 = t2[Symbol.toPrimitive];
  if (void 0 !== e2) {
    var i2 = e2.call(t2, r2 || "default");
    if ("object" != _typeof$5(i2)) return i2;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return ("string" === r2 ? String : Number)(t2);
}
__name(_toPrimitive$4, "_toPrimitive$4");
function tryOnMounted(fn) {
  var sync = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : true;
  if (getCurrentInstance()) onMounted(fn);
  else if (sync) fn();
  else nextTick(fn);
}
__name(tryOnMounted, "tryOnMounted");
var _id = 0;
function useStyle(css3) {
  var options2 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
  var isLoaded = ref$3(false);
  var cssRef = ref$3(css3);
  var styleRef = ref$3(null);
  var defaultDocument2 = isClient() ? window.document : void 0;
  var _options$document = options2.document, document2 = _options$document === void 0 ? defaultDocument2 : _options$document, _options$immediate = options2.immediate, immediate = _options$immediate === void 0 ? true : _options$immediate, _options$manual = options2.manual, manual = _options$manual === void 0 ? false : _options$manual, _options$name = options2.name, name2 = _options$name === void 0 ? "style_".concat(++_id) : _options$name, _options$id = options2.id, id2 = _options$id === void 0 ? void 0 : _options$id, _options$media = options2.media, media = _options$media === void 0 ? void 0 : _options$media, _options$nonce = options2.nonce, nonce = _options$nonce === void 0 ? void 0 : _options$nonce, _options$first = options2.first, first2 = _options$first === void 0 ? false : _options$first, _options$onMounted = options2.onMounted, onStyleMounted = _options$onMounted === void 0 ? void 0 : _options$onMounted, _options$onUpdated = options2.onUpdated, onStyleUpdated = _options$onUpdated === void 0 ? void 0 : _options$onUpdated, _options$onLoad = options2.onLoad, onStyleLoaded = _options$onLoad === void 0 ? void 0 : _options$onLoad, _options$props = options2.props, props = _options$props === void 0 ? {} : _options$props;
  var stop2 = /* @__PURE__ */ __name(function stop3() {
  }, "stop");
  var load2 = /* @__PURE__ */ __name(function load3(_css) {
    var _props = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
    if (!document2) return;
    var _styleProps = _objectSpread$7(_objectSpread$7({}, props), _props);
    var _name = _styleProps.name || name2, _id2 = _styleProps.id || id2, _nonce = _styleProps.nonce || nonce;
    styleRef.value = document2.querySelector('style[data-primevue-style-id="'.concat(_name, '"]')) || document2.getElementById(_id2) || document2.createElement("style");
    if (!styleRef.value.isConnected) {
      cssRef.value = _css || css3;
      setAttributes(styleRef.value, {
        type: "text/css",
        id: _id2,
        media,
        nonce: _nonce
      });
      first2 ? document2.head.prepend(styleRef.value) : document2.head.appendChild(styleRef.value);
      setAttribute(styleRef.value, "data-primevue-style-id", _name);
      setAttributes(styleRef.value, _styleProps);
      styleRef.value.onload = function(event) {
        return onStyleLoaded === null || onStyleLoaded === void 0 ? void 0 : onStyleLoaded(event, {
          name: _name
        });
      };
      onStyleMounted === null || onStyleMounted === void 0 || onStyleMounted(_name);
    }
    if (isLoaded.value) return;
    stop2 = watch(cssRef, function(value) {
      styleRef.value.textContent = value;
      onStyleUpdated === null || onStyleUpdated === void 0 || onStyleUpdated(_name);
    }, {
      immediate: true
    });
    isLoaded.value = true;
  }, "load");
  var unload = /* @__PURE__ */ __name(function unload2() {
    if (!document2 || !isLoaded.value) return;
    stop2();
    isExist(styleRef.value) && document2.head.removeChild(styleRef.value);
    isLoaded.value = false;
  }, "unload");
  if (immediate && !manual) tryOnMounted(load2);
  return {
    id: id2,
    name: name2,
    el: styleRef,
    css: cssRef,
    unload,
    load: load2,
    isLoaded: readonly(isLoaded)
  };
}
__name(useStyle, "useStyle");
function _typeof$4(o2) {
  "@babel/helpers - typeof";
  return _typeof$4 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o3) {
    return typeof o3;
  } : function(o3) {
    return o3 && "function" == typeof Symbol && o3.constructor === Symbol && o3 !== Symbol.prototype ? "symbol" : typeof o3;
  }, _typeof$4(o2);
}
__name(_typeof$4, "_typeof$4");
function _slicedToArray$3(r2, e2) {
  return _arrayWithHoles$3(r2) || _iterableToArrayLimit$3(r2, e2) || _unsupportedIterableToArray$5(r2, e2) || _nonIterableRest$3();
}
__name(_slicedToArray$3, "_slicedToArray$3");
function _nonIterableRest$3() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
__name(_nonIterableRest$3, "_nonIterableRest$3");
function _unsupportedIterableToArray$5(r2, a2) {
  if (r2) {
    if ("string" == typeof r2) return _arrayLikeToArray$5(r2, a2);
    var t2 = {}.toString.call(r2).slice(8, -1);
    return "Object" === t2 && r2.constructor && (t2 = r2.constructor.name), "Map" === t2 || "Set" === t2 ? Array.from(r2) : "Arguments" === t2 || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t2) ? _arrayLikeToArray$5(r2, a2) : void 0;
  }
}
__name(_unsupportedIterableToArray$5, "_unsupportedIterableToArray$5");
function _arrayLikeToArray$5(r2, a2) {
  (null == a2 || a2 > r2.length) && (a2 = r2.length);
  for (var e2 = 0, n2 = Array(a2); e2 < a2; e2++) n2[e2] = r2[e2];
  return n2;
}
__name(_arrayLikeToArray$5, "_arrayLikeToArray$5");
function _iterableToArrayLimit$3(r2, l2) {
  var t2 = null == r2 ? null : "undefined" != typeof Symbol && r2[Symbol.iterator] || r2["@@iterator"];
  if (null != t2) {
    var e2, n2, i2, u2, a2 = [], f2 = true, o2 = false;
    try {
      if (i2 = (t2 = t2.call(r2)).next, 0 === l2) ;
      else for (; !(f2 = (e2 = i2.call(t2)).done) && (a2.push(e2.value), a2.length !== l2); f2 = true) ;
    } catch (r3) {
      o2 = true, n2 = r3;
    } finally {
      try {
        if (!f2 && null != t2["return"] && (u2 = t2["return"](), Object(u2) !== u2)) return;
      } finally {
        if (o2) throw n2;
      }
    }
    return a2;
  }
}
__name(_iterableToArrayLimit$3, "_iterableToArrayLimit$3");
function _arrayWithHoles$3(r2) {
  if (Array.isArray(r2)) return r2;
}
__name(_arrayWithHoles$3, "_arrayWithHoles$3");
function ownKeys$6(e2, r2) {
  var t2 = Object.keys(e2);
  if (Object.getOwnPropertySymbols) {
    var o2 = Object.getOwnPropertySymbols(e2);
    r2 && (o2 = o2.filter(function(r3) {
      return Object.getOwnPropertyDescriptor(e2, r3).enumerable;
    })), t2.push.apply(t2, o2);
  }
  return t2;
}
__name(ownKeys$6, "ownKeys$6");
function _objectSpread$6(e2) {
  for (var r2 = 1; r2 < arguments.length; r2++) {
    var t2 = null != arguments[r2] ? arguments[r2] : {};
    r2 % 2 ? ownKeys$6(Object(t2), true).forEach(function(r3) {
      _defineProperty$6(e2, r3, t2[r3]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e2, Object.getOwnPropertyDescriptors(t2)) : ownKeys$6(Object(t2)).forEach(function(r3) {
      Object.defineProperty(e2, r3, Object.getOwnPropertyDescriptor(t2, r3));
    });
  }
  return e2;
}
__name(_objectSpread$6, "_objectSpread$6");
function _defineProperty$6(e2, r2, t2) {
  return (r2 = _toPropertyKey$3(r2)) in e2 ? Object.defineProperty(e2, r2, { value: t2, enumerable: true, configurable: true, writable: true }) : e2[r2] = t2, e2;
}
__name(_defineProperty$6, "_defineProperty$6");
function _toPropertyKey$3(t2) {
  var i2 = _toPrimitive$3(t2, "string");
  return "symbol" == _typeof$4(i2) ? i2 : i2 + "";
}
__name(_toPropertyKey$3, "_toPropertyKey$3");
function _toPrimitive$3(t2, r2) {
  if ("object" != _typeof$4(t2) || !t2) return t2;
  var e2 = t2[Symbol.toPrimitive];
  if (void 0 !== e2) {
    var i2 = e2.call(t2, r2 || "default");
    if ("object" != _typeof$4(i2)) return i2;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return ("string" === r2 ? String : Number)(t2);
}
__name(_toPrimitive$3, "_toPrimitive$3");
var theme = /* @__PURE__ */ __name(function theme2(_ref) {
  var dt2 = _ref.dt;
  return "\n*,\n::before,\n::after {\n    box-sizing: border-box;\n}\n\n/* Non vue overlay animations */\n.p-connected-overlay {\n    opacity: 0;\n    transform: scaleY(0.8);\n    transition: transform 0.12s cubic-bezier(0, 0, 0.2, 1),\n        opacity 0.12s cubic-bezier(0, 0, 0.2, 1);\n}\n\n.p-connected-overlay-visible {\n    opacity: 1;\n    transform: scaleY(1);\n}\n\n.p-connected-overlay-hidden {\n    opacity: 0;\n    transform: scaleY(1);\n    transition: opacity 0.1s linear;\n}\n\n/* Vue based overlay animations */\n.p-connected-overlay-enter-from {\n    opacity: 0;\n    transform: scaleY(0.8);\n}\n\n.p-connected-overlay-leave-to {\n    opacity: 0;\n}\n\n.p-connected-overlay-enter-active {\n    transition: transform 0.12s cubic-bezier(0, 0, 0.2, 1),\n        opacity 0.12s cubic-bezier(0, 0, 0.2, 1);\n}\n\n.p-connected-overlay-leave-active {\n    transition: opacity 0.1s linear;\n}\n\n/* Toggleable Content */\n.p-toggleable-content-enter-from,\n.p-toggleable-content-leave-to {\n    max-height: 0;\n}\n\n.p-toggleable-content-enter-to,\n.p-toggleable-content-leave-from {\n    max-height: 1000px;\n}\n\n.p-toggleable-content-leave-active {\n    overflow: hidden;\n    transition: max-height 0.45s cubic-bezier(0, 1, 0, 1);\n}\n\n.p-toggleable-content-enter-active {\n    overflow: hidden;\n    transition: max-height 1s ease-in-out;\n}\n\n.p-disabled,\n.p-disabled * {\n    cursor: default;\n    pointer-events: none;\n    user-select: none;\n}\n\n.p-disabled,\n.p-component:disabled {\n    opacity: ".concat(dt2("disabled.opacity"), ";\n}\n\n.pi {\n    font-size: ").concat(dt2("icon.size"), ";\n}\n\n.p-icon {\n    width: ").concat(dt2("icon.size"), ";\n    height: ").concat(dt2("icon.size"), ";\n}\n\n.p-overlay-mask {\n    background: ").concat(dt2("mask.background"), ";\n    color: ").concat(dt2("mask.color"), ";\n    position: fixed;\n    top: 0;\n    left: 0;\n    width: 100%;\n    height: 100%;\n}\n\n.p-overlay-mask-enter {\n    animation: p-overlay-mask-enter-animation ").concat(dt2("mask.transition.duration"), " forwards;\n}\n\n.p-overlay-mask-leave {\n    animation: p-overlay-mask-leave-animation ").concat(dt2("mask.transition.duration"), " forwards;\n}\n\n@keyframes p-overlay-mask-enter-animation {\n    from {\n        background: transparent;\n    }\n    to {\n        background: ").concat(dt2("mask.background"), ";\n    }\n}\n@keyframes p-overlay-mask-leave-animation {\n    from {\n        background: ").concat(dt2("mask.background"), ";\n    }\n    to {\n        background: transparent;\n    }\n}\n");
}, "theme");
var css = /* @__PURE__ */ __name(function css2(_ref2) {
  var dt2 = _ref2.dt;
  return "\n.p-hidden-accessible {\n    border: 0;\n    clip: rect(0 0 0 0);\n    height: 1px;\n    margin: -1px;\n    overflow: hidden;\n    padding: 0;\n    position: absolute;\n    width: 1px;\n}\n\n.p-hidden-accessible input,\n.p-hidden-accessible select {\n    transform: scale(0);\n}\n\n.p-overflow-hidden {\n    overflow: hidden;\n    padding-right: ".concat(dt2("scrollbar.width"), ";\n}\n");
}, "css");
var classes$2 = {};
var inlineStyles = {};
var BaseStyle = {
  name: "base",
  css,
  theme,
  classes: classes$2,
  inlineStyles,
  load: /* @__PURE__ */ __name(function load(style2) {
    var options2 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
    var transform = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : function(cs) {
      return cs;
    };
    var computedStyle = transform(resolve$1(style2, {
      dt
    }));
    return isNotEmpty$1(computedStyle) ? useStyle(minifyCSS$1(computedStyle), _objectSpread$6({
      name: this.name
    }, options2)) : {};
  }, "load"),
  loadCSS: /* @__PURE__ */ __name(function loadCSS() {
    var options2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
    return this.load(this.css, options2);
  }, "loadCSS"),
  loadTheme: /* @__PURE__ */ __name(function loadTheme() {
    var _this = this;
    var options2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
    var style2 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "";
    return this.load(this.theme, options2, function() {
      var computedStyle = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : "";
      return config_default.transformCSS(options2.name || _this.name, "".concat(computedStyle).concat(style2));
    });
  }, "loadTheme"),
  getCommonTheme: /* @__PURE__ */ __name(function getCommonTheme(params) {
    return config_default.getCommon(this.name, params);
  }, "getCommonTheme"),
  getComponentTheme: /* @__PURE__ */ __name(function getComponentTheme(params) {
    return config_default.getComponent(this.name, params);
  }, "getComponentTheme"),
  getDirectiveTheme: /* @__PURE__ */ __name(function getDirectiveTheme(params) {
    return config_default.getDirective(this.name, params);
  }, "getDirectiveTheme"),
  getPresetTheme: /* @__PURE__ */ __name(function getPresetTheme(preset, selector, params) {
    return config_default.getCustomPreset(this.name, preset, selector, params);
  }, "getPresetTheme"),
  getLayerOrderThemeCSS: /* @__PURE__ */ __name(function getLayerOrderThemeCSS() {
    return config_default.getLayerOrderCSS(this.name);
  }, "getLayerOrderThemeCSS"),
  getStyleSheet: /* @__PURE__ */ __name(function getStyleSheet() {
    var extendedCSS = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : "";
    var props = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
    if (this.css) {
      var _css = resolve$1(this.css, {
        dt
      }) || "";
      var _style = minifyCSS$1("".concat(_css).concat(extendedCSS));
      var _props = Object.entries(props).reduce(function(acc, _ref3) {
        var _ref4 = _slicedToArray$3(_ref3, 2), k2 = _ref4[0], v2 = _ref4[1];
        return acc.push("".concat(k2, '="').concat(v2, '"')) && acc;
      }, []).join(" ");
      return isNotEmpty$1(_style) ? '<style type="text/css" data-primevue-style-id="'.concat(this.name, '" ').concat(_props, ">").concat(_style, "</style>") : "";
    }
    return "";
  }, "getStyleSheet"),
  getCommonThemeStyleSheet: /* @__PURE__ */ __name(function getCommonThemeStyleSheet(params) {
    var props = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
    return config_default.getCommonStyleSheet(this.name, params, props);
  }, "getCommonThemeStyleSheet"),
  getThemeStyleSheet: /* @__PURE__ */ __name(function getThemeStyleSheet(params) {
    var props = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
    var css3 = [config_default.getStyleSheet(this.name, params, props)];
    if (this.theme) {
      var name2 = this.name === "base" ? "global-style" : "".concat(this.name, "-style");
      var _css = resolve$1(this.theme, {
        dt
      });
      var _style = minifyCSS$1(config_default.transformCSS(name2, _css));
      var _props = Object.entries(props).reduce(function(acc, _ref5) {
        var _ref6 = _slicedToArray$3(_ref5, 2), k2 = _ref6[0], v2 = _ref6[1];
        return acc.push("".concat(k2, '="').concat(v2, '"')) && acc;
      }, []).join(" ");
      isNotEmpty$1(_style) && css3.push('<style type="text/css" data-primevue-style-id="'.concat(name2, '" ').concat(_props, ">").concat(_style, "</style>"));
    }
    return css3.join("");
  }, "getThemeStyleSheet"),
  extend: /* @__PURE__ */ __name(function extend2(style2) {
    return _objectSpread$6(_objectSpread$6({}, this), {}, {
      css: void 0,
      theme: void 0
    }, style2);
  }, "extend")
};
var BaseComponentStyle = BaseStyle.extend({
  name: "common"
});
function _typeof$3(o2) {
  "@babel/helpers - typeof";
  return _typeof$3 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o3) {
    return typeof o3;
  } : function(o3) {
    return o3 && "function" == typeof Symbol && o3.constructor === Symbol && o3 !== Symbol.prototype ? "symbol" : typeof o3;
  }, _typeof$3(o2);
}
__name(_typeof$3, "_typeof$3");
function _toArray(r2) {
  return _arrayWithHoles$2(r2) || _iterableToArray$1(r2) || _unsupportedIterableToArray$4(r2) || _nonIterableRest$2();
}
__name(_toArray, "_toArray");
function _iterableToArray$1(r2) {
  if ("undefined" != typeof Symbol && null != r2[Symbol.iterator] || null != r2["@@iterator"]) return Array.from(r2);
}
__name(_iterableToArray$1, "_iterableToArray$1");
function _slicedToArray$2(r2, e2) {
  return _arrayWithHoles$2(r2) || _iterableToArrayLimit$2(r2, e2) || _unsupportedIterableToArray$4(r2, e2) || _nonIterableRest$2();
}
__name(_slicedToArray$2, "_slicedToArray$2");
function _nonIterableRest$2() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
__name(_nonIterableRest$2, "_nonIterableRest$2");
function _unsupportedIterableToArray$4(r2, a2) {
  if (r2) {
    if ("string" == typeof r2) return _arrayLikeToArray$4(r2, a2);
    var t2 = {}.toString.call(r2).slice(8, -1);
    return "Object" === t2 && r2.constructor && (t2 = r2.constructor.name), "Map" === t2 || "Set" === t2 ? Array.from(r2) : "Arguments" === t2 || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t2) ? _arrayLikeToArray$4(r2, a2) : void 0;
  }
}
__name(_unsupportedIterableToArray$4, "_unsupportedIterableToArray$4");
function _arrayLikeToArray$4(r2, a2) {
  (null == a2 || a2 > r2.length) && (a2 = r2.length);
  for (var e2 = 0, n2 = Array(a2); e2 < a2; e2++) n2[e2] = r2[e2];
  return n2;
}
__name(_arrayLikeToArray$4, "_arrayLikeToArray$4");
function _iterableToArrayLimit$2(r2, l2) {
  var t2 = null == r2 ? null : "undefined" != typeof Symbol && r2[Symbol.iterator] || r2["@@iterator"];
  if (null != t2) {
    var e2, n2, i2, u2, a2 = [], f2 = true, o2 = false;
    try {
      if (i2 = (t2 = t2.call(r2)).next, 0 === l2) {
        if (Object(t2) !== t2) return;
        f2 = false;
      } else for (; !(f2 = (e2 = i2.call(t2)).done) && (a2.push(e2.value), a2.length !== l2); f2 = true) ;
    } catch (r3) {
      o2 = true, n2 = r3;
    } finally {
      try {
        if (!f2 && null != t2["return"] && (u2 = t2["return"](), Object(u2) !== u2)) return;
      } finally {
        if (o2) throw n2;
      }
    }
    return a2;
  }
}
__name(_iterableToArrayLimit$2, "_iterableToArrayLimit$2");
function _arrayWithHoles$2(r2) {
  if (Array.isArray(r2)) return r2;
}
__name(_arrayWithHoles$2, "_arrayWithHoles$2");
function ownKeys$5(e2, r2) {
  var t2 = Object.keys(e2);
  if (Object.getOwnPropertySymbols) {
    var o2 = Object.getOwnPropertySymbols(e2);
    r2 && (o2 = o2.filter(function(r3) {
      return Object.getOwnPropertyDescriptor(e2, r3).enumerable;
    })), t2.push.apply(t2, o2);
  }
  return t2;
}
__name(ownKeys$5, "ownKeys$5");
function _objectSpread$5(e2) {
  for (var r2 = 1; r2 < arguments.length; r2++) {
    var t2 = null != arguments[r2] ? arguments[r2] : {};
    r2 % 2 ? ownKeys$5(Object(t2), true).forEach(function(r3) {
      _defineProperty$5(e2, r3, t2[r3]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e2, Object.getOwnPropertyDescriptors(t2)) : ownKeys$5(Object(t2)).forEach(function(r3) {
      Object.defineProperty(e2, r3, Object.getOwnPropertyDescriptor(t2, r3));
    });
  }
  return e2;
}
__name(_objectSpread$5, "_objectSpread$5");
function _defineProperty$5(e2, r2, t2) {
  return (r2 = _toPropertyKey$2(r2)) in e2 ? Object.defineProperty(e2, r2, { value: t2, enumerable: true, configurable: true, writable: true }) : e2[r2] = t2, e2;
}
__name(_defineProperty$5, "_defineProperty$5");
function _toPropertyKey$2(t2) {
  var i2 = _toPrimitive$2(t2, "string");
  return "symbol" == _typeof$3(i2) ? i2 : i2 + "";
}
__name(_toPropertyKey$2, "_toPropertyKey$2");
function _toPrimitive$2(t2, r2) {
  if ("object" != _typeof$3(t2) || !t2) return t2;
  var e2 = t2[Symbol.toPrimitive];
  if (void 0 !== e2) {
    var i2 = e2.call(t2, r2 || "default");
    if ("object" != _typeof$3(i2)) return i2;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return ("string" === r2 ? String : Number)(t2);
}
__name(_toPrimitive$2, "_toPrimitive$2");
var script$3 = {
  name: "BaseComponent",
  props: {
    pt: {
      type: Object,
      "default": void 0
    },
    ptOptions: {
      type: Object,
      "default": void 0
    },
    unstyled: {
      type: Boolean,
      "default": void 0
    },
    dt: {
      type: Object,
      "default": void 0
    }
  },
  inject: {
    $parentInstance: {
      "default": void 0
    }
  },
  watch: {
    isUnstyled: {
      immediate: true,
      handler: /* @__PURE__ */ __name(function handler2(newValue2) {
        if (!newValue2) {
          this._loadCoreStyles();
          this._themeChangeListener(this._loadCoreStyles);
        }
      }, "handler")
    },
    dt: {
      immediate: true,
      handler: /* @__PURE__ */ __name(function handler3(newValue2) {
        var _this = this;
        if (newValue2) {
          this._loadScopedThemeStyles(newValue2);
          this._themeChangeListener(function() {
            return _this._loadScopedThemeStyles(newValue2);
          });
        } else {
          this._unloadScopedThemeStyles();
        }
      }, "handler")
    }
  },
  scopedStyleEl: void 0,
  rootEl: void 0,
  $attrSelector: void 0,
  beforeCreate: /* @__PURE__ */ __name(function beforeCreate() {
    var _this$pt, _this$pt2, _this$pt3, _ref, _ref$onBeforeCreate, _this$$primevueConfig, _this$$primevue, _this$$primevue2, _this$$primevue3, _ref2, _ref2$onBeforeCreate;
    var _usept = (_this$pt = this.pt) === null || _this$pt === void 0 ? void 0 : _this$pt["_usept"];
    var originalValue = _usept ? (_this$pt2 = this.pt) === null || _this$pt2 === void 0 || (_this$pt2 = _this$pt2.originalValue) === null || _this$pt2 === void 0 ? void 0 : _this$pt2[this.$.type.name] : void 0;
    var value = _usept ? (_this$pt3 = this.pt) === null || _this$pt3 === void 0 || (_this$pt3 = _this$pt3.value) === null || _this$pt3 === void 0 ? void 0 : _this$pt3[this.$.type.name] : this.pt;
    (_ref = value || originalValue) === null || _ref === void 0 || (_ref = _ref.hooks) === null || _ref === void 0 || (_ref$onBeforeCreate = _ref["onBeforeCreate"]) === null || _ref$onBeforeCreate === void 0 || _ref$onBeforeCreate.call(_ref);
    var _useptInConfig = (_this$$primevueConfig = this.$primevueConfig) === null || _this$$primevueConfig === void 0 || (_this$$primevueConfig = _this$$primevueConfig.pt) === null || _this$$primevueConfig === void 0 ? void 0 : _this$$primevueConfig["_usept"];
    var originalValueInConfig = _useptInConfig ? (_this$$primevue = this.$primevue) === null || _this$$primevue === void 0 || (_this$$primevue = _this$$primevue.config) === null || _this$$primevue === void 0 || (_this$$primevue = _this$$primevue.pt) === null || _this$$primevue === void 0 ? void 0 : _this$$primevue.originalValue : void 0;
    var valueInConfig = _useptInConfig ? (_this$$primevue2 = this.$primevue) === null || _this$$primevue2 === void 0 || (_this$$primevue2 = _this$$primevue2.config) === null || _this$$primevue2 === void 0 || (_this$$primevue2 = _this$$primevue2.pt) === null || _this$$primevue2 === void 0 ? void 0 : _this$$primevue2.value : (_this$$primevue3 = this.$primevue) === null || _this$$primevue3 === void 0 || (_this$$primevue3 = _this$$primevue3.config) === null || _this$$primevue3 === void 0 ? void 0 : _this$$primevue3.pt;
    (_ref2 = valueInConfig || originalValueInConfig) === null || _ref2 === void 0 || (_ref2 = _ref2[this.$.type.name]) === null || _ref2 === void 0 || (_ref2 = _ref2.hooks) === null || _ref2 === void 0 || (_ref2$onBeforeCreate = _ref2["onBeforeCreate"]) === null || _ref2$onBeforeCreate === void 0 || _ref2$onBeforeCreate.call(_ref2);
    this.$attrSelector = uuid("pc");
  }, "beforeCreate"),
  created: /* @__PURE__ */ __name(function created() {
    this._hook("onCreated");
  }, "created"),
  beforeMount: /* @__PURE__ */ __name(function beforeMount() {
    this.rootEl = findSingle(this.$el, '[data-pc-name="'.concat(toFlatCase$1(this.$.type.name), '"]'));
    if (this.rootEl) {
      this.$attrSelector && !this.rootEl.hasAttribute(this.$attrSelector) && this.rootEl.setAttribute(this.$attrSelector, "");
      this.rootEl.$pc = _objectSpread$5({
        name: this.$.type.name,
        attrSelector: this.$attrSelector
      }, this.$params);
    }
    this._loadStyles();
    this._hook("onBeforeMount");
  }, "beforeMount"),
  mounted: /* @__PURE__ */ __name(function mounted() {
    this._hook("onMounted");
  }, "mounted"),
  beforeUpdate: /* @__PURE__ */ __name(function beforeUpdate() {
    this._hook("onBeforeUpdate");
  }, "beforeUpdate"),
  updated: /* @__PURE__ */ __name(function updated() {
    this._hook("onUpdated");
  }, "updated"),
  beforeUnmount: /* @__PURE__ */ __name(function beforeUnmount() {
    this._hook("onBeforeUnmount");
  }, "beforeUnmount"),
  unmounted: /* @__PURE__ */ __name(function unmounted() {
    this._unloadScopedThemeStyles();
    this._hook("onUnmounted");
  }, "unmounted"),
  methods: {
    _hook: /* @__PURE__ */ __name(function _hook(hookName) {
      if (!this.$options.hostName) {
        var selfHook = this._usePT(this._getPT(this.pt, this.$.type.name), this._getOptionValue, "hooks.".concat(hookName));
        var defaultHook = this._useDefaultPT(this._getOptionValue, "hooks.".concat(hookName));
        selfHook === null || selfHook === void 0 || selfHook();
        defaultHook === null || defaultHook === void 0 || defaultHook();
      }
    }, "_hook"),
    _mergeProps: /* @__PURE__ */ __name(function _mergeProps(fn) {
      for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key2 = 1; _key2 < _len; _key2++) {
        args[_key2 - 1] = arguments[_key2];
      }
      return isFunction$7(fn) ? fn.apply(void 0, args) : mergeProps$1.apply(void 0, args);
    }, "_mergeProps"),
    _loadStyles: /* @__PURE__ */ __name(function _loadStyles() {
      var _this2 = this;
      var _load = /* @__PURE__ */ __name(function _load2() {
        if (!Base.isStyleNameLoaded("base")) {
          BaseStyle.loadCSS(_this2.$styleOptions);
          _this2._loadGlobalStyles();
          Base.setLoadedStyleName("base");
        }
        _this2._loadThemeStyles();
      }, "_load");
      _load();
      this._themeChangeListener(_load);
    }, "_loadStyles"),
    _loadCoreStyles: /* @__PURE__ */ __name(function _loadCoreStyles() {
      var _this$$style, _this$$style2;
      if (!Base.isStyleNameLoaded((_this$$style = this.$style) === null || _this$$style === void 0 ? void 0 : _this$$style.name) && (_this$$style2 = this.$style) !== null && _this$$style2 !== void 0 && _this$$style2.name) {
        BaseComponentStyle.loadCSS(this.$styleOptions);
        this.$options.style && this.$style.loadCSS(this.$styleOptions);
        Base.setLoadedStyleName(this.$style.name);
      }
    }, "_loadCoreStyles"),
    _loadGlobalStyles: /* @__PURE__ */ __name(function _loadGlobalStyles() {
      var globalCSS = this._useGlobalPT(this._getOptionValue, "global.css", this.$params);
      isNotEmpty$1(globalCSS) && BaseStyle.load(globalCSS, _objectSpread$5({
        name: "global"
      }, this.$styleOptions));
    }, "_loadGlobalStyles"),
    _loadThemeStyles: /* @__PURE__ */ __name(function _loadThemeStyles() {
      var _this$$style4, _this$$style5;
      if (this.isUnstyled || this.$theme === "none") return;
      if (!config_default.isStyleNameLoaded("common")) {
        var _this$$style3, _this$$style3$getComm;
        var _ref3 = ((_this$$style3 = this.$style) === null || _this$$style3 === void 0 || (_this$$style3$getComm = _this$$style3.getCommonTheme) === null || _this$$style3$getComm === void 0 ? void 0 : _this$$style3$getComm.call(_this$$style3)) || {}, primitive = _ref3.primitive, semantic = _ref3.semantic, global2 = _ref3.global, style2 = _ref3.style;
        BaseStyle.load(primitive === null || primitive === void 0 ? void 0 : primitive.css, _objectSpread$5({
          name: "primitive-variables"
        }, this.$styleOptions));
        BaseStyle.load(semantic === null || semantic === void 0 ? void 0 : semantic.css, _objectSpread$5({
          name: "semantic-variables"
        }, this.$styleOptions));
        BaseStyle.load(global2 === null || global2 === void 0 ? void 0 : global2.css, _objectSpread$5({
          name: "global-variables"
        }, this.$styleOptions));
        BaseStyle.loadTheme(_objectSpread$5({
          name: "global-style"
        }, this.$styleOptions), style2);
        config_default.setLoadedStyleName("common");
      }
      if (!config_default.isStyleNameLoaded((_this$$style4 = this.$style) === null || _this$$style4 === void 0 ? void 0 : _this$$style4.name) && (_this$$style5 = this.$style) !== null && _this$$style5 !== void 0 && _this$$style5.name) {
        var _this$$style6, _this$$style6$getComp, _this$$style7, _this$$style8;
        var _ref4 = ((_this$$style6 = this.$style) === null || _this$$style6 === void 0 || (_this$$style6$getComp = _this$$style6.getComponentTheme) === null || _this$$style6$getComp === void 0 ? void 0 : _this$$style6$getComp.call(_this$$style6)) || {}, css3 = _ref4.css, _style = _ref4.style;
        (_this$$style7 = this.$style) === null || _this$$style7 === void 0 || _this$$style7.load(css3, _objectSpread$5({
          name: "".concat(this.$style.name, "-variables")
        }, this.$styleOptions));
        (_this$$style8 = this.$style) === null || _this$$style8 === void 0 || _this$$style8.loadTheme(_objectSpread$5({
          name: "".concat(this.$style.name, "-style")
        }, this.$styleOptions), _style);
        config_default.setLoadedStyleName(this.$style.name);
      }
      if (!config_default.isStyleNameLoaded("layer-order")) {
        var _this$$style9, _this$$style9$getLaye;
        var layerOrder = (_this$$style9 = this.$style) === null || _this$$style9 === void 0 || (_this$$style9$getLaye = _this$$style9.getLayerOrderThemeCSS) === null || _this$$style9$getLaye === void 0 ? void 0 : _this$$style9$getLaye.call(_this$$style9);
        BaseStyle.load(layerOrder, _objectSpread$5({
          name: "layer-order",
          first: true
        }, this.$styleOptions));
        config_default.setLoadedStyleName("layer-order");
      }
    }, "_loadThemeStyles"),
    _loadScopedThemeStyles: /* @__PURE__ */ __name(function _loadScopedThemeStyles(preset) {
      var _this$$style10, _this$$style10$getPre, _this$$style11;
      var _ref5 = ((_this$$style10 = this.$style) === null || _this$$style10 === void 0 || (_this$$style10$getPre = _this$$style10.getPresetTheme) === null || _this$$style10$getPre === void 0 ? void 0 : _this$$style10$getPre.call(_this$$style10, preset, "[".concat(this.$attrSelector, "]"))) || {}, css3 = _ref5.css;
      var scopedStyle = (_this$$style11 = this.$style) === null || _this$$style11 === void 0 ? void 0 : _this$$style11.load(css3, _objectSpread$5({
        name: "".concat(this.$attrSelector, "-").concat(this.$style.name)
      }, this.$styleOptions));
      this.scopedStyleEl = scopedStyle.el;
    }, "_loadScopedThemeStyles"),
    _unloadScopedThemeStyles: /* @__PURE__ */ __name(function _unloadScopedThemeStyles() {
      var _this$scopedStyleEl;
      (_this$scopedStyleEl = this.scopedStyleEl) === null || _this$scopedStyleEl === void 0 || (_this$scopedStyleEl = _this$scopedStyleEl.value) === null || _this$scopedStyleEl === void 0 || _this$scopedStyleEl.remove();
    }, "_unloadScopedThemeStyles"),
    _themeChangeListener: /* @__PURE__ */ __name(function _themeChangeListener() {
      var callback = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : function() {
      };
      Base.clearLoadedStyleNames();
      service_default.on("theme:change", callback);
    }, "_themeChangeListener"),
    _getHostInstance: /* @__PURE__ */ __name(function _getHostInstance(instance) {
      return instance ? this.$options.hostName ? instance.$.type.name === this.$options.hostName ? instance : this._getHostInstance(instance.$parentInstance) : instance.$parentInstance : void 0;
    }, "_getHostInstance"),
    _getPropValue: /* @__PURE__ */ __name(function _getPropValue(name2) {
      var _this$_getHostInstanc;
      return this[name2] || ((_this$_getHostInstanc = this._getHostInstance(this)) === null || _this$_getHostInstanc === void 0 ? void 0 : _this$_getHostInstanc[name2]);
    }, "_getPropValue"),
    _getOptionValue: /* @__PURE__ */ __name(function _getOptionValue(options2) {
      var key = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "";
      var params = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
      return getKeyValue$1(options2, key, params);
    }, "_getOptionValue"),
    _getPTValue: /* @__PURE__ */ __name(function _getPTValue() {
      var _this$$primevueConfig2;
      var obj = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
      var key = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "";
      var params = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
      var searchInDefaultPT = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : true;
      var searchOut = /./g.test(key) && !!params[key.split(".")[0]];
      var _ref6 = this._getPropValue("ptOptions") || ((_this$$primevueConfig2 = this.$primevueConfig) === null || _this$$primevueConfig2 === void 0 ? void 0 : _this$$primevueConfig2.ptOptions) || {}, _ref6$mergeSections = _ref6.mergeSections, mergeSections = _ref6$mergeSections === void 0 ? true : _ref6$mergeSections, _ref6$mergeProps = _ref6.mergeProps, useMergeProps = _ref6$mergeProps === void 0 ? false : _ref6$mergeProps;
      var global2 = searchInDefaultPT ? searchOut ? this._useGlobalPT(this._getPTClassValue, key, params) : this._useDefaultPT(this._getPTClassValue, key, params) : void 0;
      var self2 = searchOut ? void 0 : this._getPTSelf(obj, this._getPTClassValue, key, _objectSpread$5(_objectSpread$5({}, params), {}, {
        global: global2 || {}
      }));
      var datasets = this._getPTDatasets(key);
      return mergeSections || !mergeSections && self2 ? useMergeProps ? this._mergeProps(useMergeProps, global2, self2, datasets) : _objectSpread$5(_objectSpread$5(_objectSpread$5({}, global2), self2), datasets) : _objectSpread$5(_objectSpread$5({}, self2), datasets);
    }, "_getPTValue"),
    _getPTSelf: /* @__PURE__ */ __name(function _getPTSelf() {
      var obj = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
      for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key3 = 1; _key3 < _len2; _key3++) {
        args[_key3 - 1] = arguments[_key3];
      }
      return mergeProps$1(
        this._usePT.apply(this, [this._getPT(obj, this.$name)].concat(args)),
        // Exp; <component :pt="{}"
        this._usePT.apply(this, [this.$_attrsPT].concat(args))
        // Exp; <component :pt:[passthrough_key]:[attribute]="{value}" or <component :pt:[passthrough_key]="() =>{value}"
      );
    }, "_getPTSelf"),
    _getPTDatasets: /* @__PURE__ */ __name(function _getPTDatasets() {
      var _this$pt4, _this$pt5;
      var key = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : "";
      var datasetPrefix = "data-pc-";
      var isExtended = key === "root" && isNotEmpty$1((_this$pt4 = this.pt) === null || _this$pt4 === void 0 ? void 0 : _this$pt4["data-pc-section"]);
      return key !== "transition" && _objectSpread$5(_objectSpread$5({}, key === "root" && _objectSpread$5(_objectSpread$5(_defineProperty$5({}, "".concat(datasetPrefix, "name"), toFlatCase$1(isExtended ? (_this$pt5 = this.pt) === null || _this$pt5 === void 0 ? void 0 : _this$pt5["data-pc-section"] : this.$.type.name)), isExtended && _defineProperty$5({}, "".concat(datasetPrefix, "extend"), toFlatCase$1(this.$.type.name))), isClient() && _defineProperty$5({}, "".concat(this.$attrSelector), ""))), {}, _defineProperty$5({}, "".concat(datasetPrefix, "section"), toFlatCase$1(key)));
    }, "_getPTDatasets"),
    _getPTClassValue: /* @__PURE__ */ __name(function _getPTClassValue() {
      var value = this._getOptionValue.apply(this, arguments);
      return isString$5(value) || isArray$7(value) ? {
        "class": value
      } : value;
    }, "_getPTClassValue"),
    _getPT: /* @__PURE__ */ __name(function _getPT(pt2) {
      var _this3 = this;
      var key = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "";
      var callback = arguments.length > 2 ? arguments[2] : void 0;
      var getValue2 = /* @__PURE__ */ __name(function getValue3(value) {
        var _ref9;
        var checkSameKey = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false;
        var computedValue = callback ? callback(value) : value;
        var _key = toFlatCase$1(key);
        var _cKey = toFlatCase$1(_this3.$name);
        return (_ref9 = checkSameKey ? _key !== _cKey ? computedValue === null || computedValue === void 0 ? void 0 : computedValue[_key] : void 0 : computedValue === null || computedValue === void 0 ? void 0 : computedValue[_key]) !== null && _ref9 !== void 0 ? _ref9 : computedValue;
      }, "getValue");
      return pt2 !== null && pt2 !== void 0 && pt2.hasOwnProperty("_usept") ? {
        _usept: pt2["_usept"],
        originalValue: getValue2(pt2.originalValue),
        value: getValue2(pt2.value)
      } : getValue2(pt2, true);
    }, "_getPT"),
    _usePT: /* @__PURE__ */ __name(function _usePT(pt2, callback, key, params) {
      var fn = /* @__PURE__ */ __name(function fn2(value2) {
        return callback(value2, key, params);
      }, "fn");
      if (pt2 !== null && pt2 !== void 0 && pt2.hasOwnProperty("_usept")) {
        var _this$$primevueConfig3;
        var _ref10 = pt2["_usept"] || ((_this$$primevueConfig3 = this.$primevueConfig) === null || _this$$primevueConfig3 === void 0 ? void 0 : _this$$primevueConfig3.ptOptions) || {}, _ref10$mergeSections = _ref10.mergeSections, mergeSections = _ref10$mergeSections === void 0 ? true : _ref10$mergeSections, _ref10$mergeProps = _ref10.mergeProps, useMergeProps = _ref10$mergeProps === void 0 ? false : _ref10$mergeProps;
        var originalValue = fn(pt2.originalValue);
        var value = fn(pt2.value);
        if (originalValue === void 0 && value === void 0) return void 0;
        else if (isString$5(value)) return value;
        else if (isString$5(originalValue)) return originalValue;
        return mergeSections || !mergeSections && value ? useMergeProps ? this._mergeProps(useMergeProps, originalValue, value) : _objectSpread$5(_objectSpread$5({}, originalValue), value) : value;
      }
      return fn(pt2);
    }, "_usePT"),
    _useGlobalPT: /* @__PURE__ */ __name(function _useGlobalPT(callback, key, params) {
      return this._usePT(this.globalPT, callback, key, params);
    }, "_useGlobalPT"),
    _useDefaultPT: /* @__PURE__ */ __name(function _useDefaultPT(callback, key, params) {
      return this._usePT(this.defaultPT, callback, key, params);
    }, "_useDefaultPT"),
    ptm: /* @__PURE__ */ __name(function ptm() {
      var key = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : "";
      var params = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
      return this._getPTValue(this.pt, key, _objectSpread$5(_objectSpread$5({}, this.$params), params));
    }, "ptm"),
    ptmi: /* @__PURE__ */ __name(function ptmi() {
      var key = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : "";
      var params = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
      return mergeProps$1(this.$_attrsWithoutPT, this.ptm(key, params));
    }, "ptmi"),
    ptmo: /* @__PURE__ */ __name(function ptmo() {
      var obj = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
      var key = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "";
      var params = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
      return this._getPTValue(obj, key, _objectSpread$5({
        instance: this
      }, params), false);
    }, "ptmo"),
    cx: /* @__PURE__ */ __name(function cx() {
      var key = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : "";
      var params = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
      return !this.isUnstyled ? this._getOptionValue(this.$style.classes, key, _objectSpread$5(_objectSpread$5({}, this.$params), params)) : void 0;
    }, "cx"),
    sx: /* @__PURE__ */ __name(function sx() {
      var key = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : "";
      var when = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : true;
      var params = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
      if (when) {
        var self2 = this._getOptionValue(this.$style.inlineStyles, key, _objectSpread$5(_objectSpread$5({}, this.$params), params));
        var base2 = this._getOptionValue(BaseComponentStyle.inlineStyles, key, _objectSpread$5(_objectSpread$5({}, this.$params), params));
        return [base2, self2];
      }
      return void 0;
    }, "sx")
  },
  computed: {
    globalPT: /* @__PURE__ */ __name(function globalPT() {
      var _this$$primevueConfig4, _this4 = this;
      return this._getPT((_this$$primevueConfig4 = this.$primevueConfig) === null || _this$$primevueConfig4 === void 0 ? void 0 : _this$$primevueConfig4.pt, void 0, function(value) {
        return resolve$1(value, {
          instance: _this4
        });
      });
    }, "globalPT"),
    defaultPT: /* @__PURE__ */ __name(function defaultPT() {
      var _this$$primevueConfig5, _this5 = this;
      return this._getPT((_this$$primevueConfig5 = this.$primevueConfig) === null || _this$$primevueConfig5 === void 0 ? void 0 : _this$$primevueConfig5.pt, void 0, function(value) {
        return _this5._getOptionValue(value, _this5.$name, _objectSpread$5({}, _this5.$params)) || resolve$1(value, _objectSpread$5({}, _this5.$params));
      });
    }, "defaultPT"),
    isUnstyled: /* @__PURE__ */ __name(function isUnstyled() {
      var _this$$primevueConfig6;
      return this.unstyled !== void 0 ? this.unstyled : (_this$$primevueConfig6 = this.$primevueConfig) === null || _this$$primevueConfig6 === void 0 ? void 0 : _this$$primevueConfig6.unstyled;
    }, "isUnstyled"),
    $inProps: /* @__PURE__ */ __name(function $inProps() {
      var _this$$$vnode;
      var nodePropKeys = Object.keys(((_this$$$vnode = this.$.vnode) === null || _this$$$vnode === void 0 ? void 0 : _this$$$vnode.props) || {});
      return Object.fromEntries(Object.entries(this.$props).filter(function(_ref11) {
        var _ref12 = _slicedToArray$2(_ref11, 1), k2 = _ref12[0];
        return nodePropKeys === null || nodePropKeys === void 0 ? void 0 : nodePropKeys.includes(k2);
      }));
    }, "$inProps"),
    $theme: /* @__PURE__ */ __name(function $theme() {
      var _this$$primevueConfig7;
      return (_this$$primevueConfig7 = this.$primevueConfig) === null || _this$$primevueConfig7 === void 0 ? void 0 : _this$$primevueConfig7.theme;
    }, "$theme"),
    $style: /* @__PURE__ */ __name(function $style() {
      return _objectSpread$5(_objectSpread$5({
        classes: void 0,
        inlineStyles: void 0,
        load: /* @__PURE__ */ __name(function load2() {
        }, "load"),
        loadCSS: /* @__PURE__ */ __name(function loadCSS2() {
        }, "loadCSS"),
        loadTheme: /* @__PURE__ */ __name(function loadTheme2() {
        }, "loadTheme")
      }, (this._getHostInstance(this) || {}).$style), this.$options.style);
    }, "$style"),
    $styleOptions: /* @__PURE__ */ __name(function $styleOptions() {
      var _this$$primevueConfig8;
      return {
        nonce: (_this$$primevueConfig8 = this.$primevueConfig) === null || _this$$primevueConfig8 === void 0 || (_this$$primevueConfig8 = _this$$primevueConfig8.csp) === null || _this$$primevueConfig8 === void 0 ? void 0 : _this$$primevueConfig8.nonce
      };
    }, "$styleOptions"),
    $primevueConfig: /* @__PURE__ */ __name(function $primevueConfig() {
      var _this$$primevue4;
      return (_this$$primevue4 = this.$primevue) === null || _this$$primevue4 === void 0 ? void 0 : _this$$primevue4.config;
    }, "$primevueConfig"),
    $name: /* @__PURE__ */ __name(function $name() {
      return this.$options.hostName || this.$.type.name;
    }, "$name"),
    $params: /* @__PURE__ */ __name(function $params() {
      var parentInstance = this._getHostInstance(this) || this.$parent;
      return {
        instance: this,
        props: this.$props,
        state: this.$data,
        attrs: this.$attrs,
        parent: {
          instance: parentInstance,
          props: parentInstance === null || parentInstance === void 0 ? void 0 : parentInstance.$props,
          state: parentInstance === null || parentInstance === void 0 ? void 0 : parentInstance.$data,
          attrs: parentInstance === null || parentInstance === void 0 ? void 0 : parentInstance.$attrs
        }
      };
    }, "$params"),
    $_attrsPT: /* @__PURE__ */ __name(function $_attrsPT() {
      return Object.entries(this.$attrs || {}).filter(function(_ref13) {
        var _ref14 = _slicedToArray$2(_ref13, 1), key = _ref14[0];
        return key === null || key === void 0 ? void 0 : key.startsWith("pt:");
      }).reduce(function(result, _ref15) {
        var _ref16 = _slicedToArray$2(_ref15, 2), key = _ref16[0], value = _ref16[1];
        var _key$split = key.split(":"), _key$split2 = _toArray(_key$split), rest = _key$split2.slice(1);
        rest === null || rest === void 0 || rest.reduce(function(currentObj, nestedKey, index2, array) {
          !currentObj[nestedKey] && (currentObj[nestedKey] = index2 === array.length - 1 ? value : {});
          return currentObj[nestedKey];
        }, result);
        return result;
      }, {});
    }, "$_attrsPT"),
    $_attrsWithoutPT: /* @__PURE__ */ __name(function $_attrsWithoutPT() {
      return Object.entries(this.$attrs || {}).filter(function(_ref17) {
        var _ref18 = _slicedToArray$2(_ref17, 1), key = _ref18[0];
        return !(key !== null && key !== void 0 && key.startsWith("pt:"));
      }).reduce(function(acc, _ref19) {
        var _ref20 = _slicedToArray$2(_ref19, 2), key = _ref20[0], value = _ref20[1];
        acc[key] = value;
        return acc;
      }, {});
    }, "$_attrsWithoutPT")
  }
};
var classes$1 = {
  root: "p-form p-component"
};
var FormStyle = BaseStyle.extend({
  name: "form",
  classes: classes$1
});
var script$1$1 = {
  name: "BaseForm",
  "extends": script$3,
  style: FormStyle,
  props: {
    resolver: {
      type: Function,
      "default": null
    },
    initialValues: {
      type: Object,
      "default": null
    },
    validateOnValueUpdate: {
      type: [Boolean, Array],
      "default": true
    },
    validateOnBlur: {
      type: [Boolean, Array],
      "default": false
    },
    validateOnMount: {
      type: [Boolean, Array],
      "default": false
    },
    validateOnSubmit: {
      type: [Boolean, Array],
      "default": true
    }
  },
  provide: /* @__PURE__ */ __name(function provide2() {
    return {
      $pcForm: this,
      $parentInstance: this
    };
  }, "provide")
};
function _typeof$2(o2) {
  "@babel/helpers - typeof";
  return _typeof$2 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o3) {
    return typeof o3;
  } : function(o3) {
    return o3 && "function" == typeof Symbol && o3.constructor === Symbol && o3 !== Symbol.prototype ? "symbol" : typeof o3;
  }, _typeof$2(o2);
}
__name(_typeof$2, "_typeof$2");
function ownKeys$4(e2, r2) {
  var t2 = Object.keys(e2);
  if (Object.getOwnPropertySymbols) {
    var o2 = Object.getOwnPropertySymbols(e2);
    r2 && (o2 = o2.filter(function(r3) {
      return Object.getOwnPropertyDescriptor(e2, r3).enumerable;
    })), t2.push.apply(t2, o2);
  }
  return t2;
}
__name(ownKeys$4, "ownKeys$4");
function _objectSpread$4(e2) {
  for (var r2 = 1; r2 < arguments.length; r2++) {
    var t2 = null != arguments[r2] ? arguments[r2] : {};
    r2 % 2 ? ownKeys$4(Object(t2), true).forEach(function(r3) {
      _defineProperty$4(e2, r3, t2[r3]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e2, Object.getOwnPropertyDescriptors(t2)) : ownKeys$4(Object(t2)).forEach(function(r3) {
      Object.defineProperty(e2, r3, Object.getOwnPropertyDescriptor(t2, r3));
    });
  }
  return e2;
}
__name(_objectSpread$4, "_objectSpread$4");
function _defineProperty$4(e2, r2, t2) {
  return (r2 = _toPropertyKey$1(r2)) in e2 ? Object.defineProperty(e2, r2, { value: t2, enumerable: true, configurable: true, writable: true }) : e2[r2] = t2, e2;
}
__name(_defineProperty$4, "_defineProperty$4");
function _toPropertyKey$1(t2) {
  var i2 = _toPrimitive$1(t2, "string");
  return "symbol" == _typeof$2(i2) ? i2 : i2 + "";
}
__name(_toPropertyKey$1, "_toPropertyKey$1");
function _toPrimitive$1(t2, r2) {
  if ("object" != _typeof$2(t2) || !t2) return t2;
  var e2 = t2[Symbol.toPrimitive];
  if (void 0 !== e2) {
    var i2 = e2.call(t2, r2 || "default");
    if ("object" != _typeof$2(i2)) return i2;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return ("string" === r2 ? String : Number)(t2);
}
__name(_toPrimitive$1, "_toPrimitive$1");
function _slicedToArray$1(r2, e2) {
  return _arrayWithHoles$1(r2) || _iterableToArrayLimit$1(r2, e2) || _unsupportedIterableToArray$3(r2, e2) || _nonIterableRest$1();
}
__name(_slicedToArray$1, "_slicedToArray$1");
function _nonIterableRest$1() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
__name(_nonIterableRest$1, "_nonIterableRest$1");
function _unsupportedIterableToArray$3(r2, a2) {
  if (r2) {
    if ("string" == typeof r2) return _arrayLikeToArray$3(r2, a2);
    var t2 = {}.toString.call(r2).slice(8, -1);
    return "Object" === t2 && r2.constructor && (t2 = r2.constructor.name), "Map" === t2 || "Set" === t2 ? Array.from(r2) : "Arguments" === t2 || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t2) ? _arrayLikeToArray$3(r2, a2) : void 0;
  }
}
__name(_unsupportedIterableToArray$3, "_unsupportedIterableToArray$3");
function _arrayLikeToArray$3(r2, a2) {
  (null == a2 || a2 > r2.length) && (a2 = r2.length);
  for (var e2 = 0, n2 = Array(a2); e2 < a2; e2++) n2[e2] = r2[e2];
  return n2;
}
__name(_arrayLikeToArray$3, "_arrayLikeToArray$3");
function _iterableToArrayLimit$1(r2, l2) {
  var t2 = null == r2 ? null : "undefined" != typeof Symbol && r2[Symbol.iterator] || r2["@@iterator"];
  if (null != t2) {
    var e2, n2, i2, u2, a2 = [], f2 = true, o2 = false;
    try {
      if (i2 = (t2 = t2.call(r2)).next, 0 === l2) ;
      else for (; !(f2 = (e2 = i2.call(t2)).done) && (a2.push(e2.value), a2.length !== l2); f2 = true) ;
    } catch (r3) {
      o2 = true, n2 = r3;
    } finally {
      try {
        if (!f2 && null != t2["return"] && (u2 = t2["return"](), Object(u2) !== u2)) return;
      } finally {
        if (o2) throw n2;
      }
    }
    return a2;
  }
}
__name(_iterableToArrayLimit$1, "_iterableToArrayLimit$1");
function _arrayWithHoles$1(r2) {
  if (Array.isArray(r2)) return r2;
}
__name(_arrayWithHoles$1, "_arrayWithHoles$1");
var script$2 = {
  name: "Form",
  "extends": script$1$1,
  inheritAttrs: false,
  emits: ["submit"],
  setup: /* @__PURE__ */ __name(function setup(props, _ref) {
    var emit = _ref.emit;
    var $form = useForm(props);
    var register2 = /* @__PURE__ */ __name(function register3(field2, options2) {
      var _$form$defineField = $form.defineField(field2, options2), _$form$defineField2 = _slicedToArray$1(_$form$defineField, 2), fieldProps = _$form$defineField2[1];
      return fieldProps;
    }, "register");
    var onSubmit = $form.handleSubmit(function(e2) {
      emit("submit", e2);
    });
    return _objectSpread$4({
      register: register2,
      onSubmit
    }, omit$1($form, ["handleSubmit"]));
  }, "setup")
};
function render$2(_ctx, _cache, $props, $setup, $data, $options) {
  return openBlock(), createElementBlock("form", mergeProps$1({
    onSubmit: _cache[0] || (_cache[0] = withModifiers(function() {
      return $setup.onSubmit && $setup.onSubmit.apply($setup, arguments);
    }, ["prevent"])),
    "class": _ctx.cx("root")
  }, _ctx.ptmi("root")), [renderSlot(_ctx.$slots, "default", mergeProps$1({
    register: $setup.register,
    valid: _ctx.valid,
    reset: _ctx.reset
  }, _ctx.states))], 16);
}
__name(render$2, "render$2");
script$2.render = render$2;
var classes = {
  root: "p-formfield p-component"
};
var FormFieldStyle = BaseStyle.extend({
  name: "formfield",
  classes
});
var script$1 = {
  name: "BaseFormField",
  "extends": script$3,
  style: FormFieldStyle,
  props: {
    name: {
      type: String,
      "default": void 0
    },
    resolver: {
      type: Function,
      "default": void 0
    },
    initialValue: {
      type: null,
      "default": void 0
    },
    validateOnValueUpdate: {
      type: Boolean,
      "default": void 0
    },
    validateOnBlur: {
      type: Boolean,
      "default": void 0
    },
    validateOnMount: {
      type: Boolean,
      "default": void 0
    },
    validateOnSubmit: {
      type: Boolean,
      "default": void 0
    },
    as: {
      type: [String, Object],
      "default": "DIV"
    },
    asChild: {
      type: Boolean,
      "default": false
    }
  },
  provide: /* @__PURE__ */ __name(function provide3() {
    return {
      $pcFormField: this,
      $parentInstance: this
    };
  }, "provide")
};
function _typeof$1(o2) {
  "@babel/helpers - typeof";
  return _typeof$1 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o3) {
    return typeof o3;
  } : function(o3) {
    return o3 && "function" == typeof Symbol && o3.constructor === Symbol && o3 !== Symbol.prototype ? "symbol" : typeof o3;
  }, _typeof$1(o2);
}
__name(_typeof$1, "_typeof$1");
function ownKeys$3(e2, r2) {
  var t2 = Object.keys(e2);
  if (Object.getOwnPropertySymbols) {
    var o2 = Object.getOwnPropertySymbols(e2);
    r2 && (o2 = o2.filter(function(r3) {
      return Object.getOwnPropertyDescriptor(e2, r3).enumerable;
    })), t2.push.apply(t2, o2);
  }
  return t2;
}
__name(ownKeys$3, "ownKeys$3");
function _objectSpread$3(e2) {
  for (var r2 = 1; r2 < arguments.length; r2++) {
    var t2 = null != arguments[r2] ? arguments[r2] : {};
    r2 % 2 ? ownKeys$3(Object(t2), true).forEach(function(r3) {
      _defineProperty$3(e2, r3, t2[r3]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e2, Object.getOwnPropertyDescriptors(t2)) : ownKeys$3(Object(t2)).forEach(function(r3) {
      Object.defineProperty(e2, r3, Object.getOwnPropertyDescriptor(t2, r3));
    });
  }
  return e2;
}
__name(_objectSpread$3, "_objectSpread$3");
function _defineProperty$3(e2, r2, t2) {
  return (r2 = _toPropertyKey(r2)) in e2 ? Object.defineProperty(e2, r2, { value: t2, enumerable: true, configurable: true, writable: true }) : e2[r2] = t2, e2;
}
__name(_defineProperty$3, "_defineProperty$3");
function _toPropertyKey(t2) {
  var i2 = _toPrimitive(t2, "string");
  return "symbol" == _typeof$1(i2) ? i2 : i2 + "";
}
__name(_toPropertyKey, "_toPropertyKey");
function _toPrimitive(t2, r2) {
  if ("object" != _typeof$1(t2) || !t2) return t2;
  var e2 = t2[Symbol.toPrimitive];
  if (void 0 !== e2) {
    var i2 = e2.call(t2, r2 || "default");
    if ("object" != _typeof$1(i2)) return i2;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return ("string" === r2 ? String : Number)(t2);
}
__name(_toPrimitive, "_toPrimitive");
var script = {
  name: "FormField",
  "extends": script$1,
  inheritAttrs: false,
  inject: {
    $pcForm: {
      "default": void 0
    }
  },
  watch: {
    formControl: {
      immediate: true,
      handler: /* @__PURE__ */ __name(function handler4(newValue2) {
        var _this$$pcForm, _this$$pcForm$registe;
        (_this$$pcForm = this.$pcForm) === null || _this$$pcForm === void 0 || (_this$$pcForm$registe = _this$$pcForm.register) === null || _this$$pcForm$registe === void 0 || _this$$pcForm$registe.call(_this$$pcForm, this.name, newValue2);
      }, "handler")
    }
  },
  computed: {
    formControl: /* @__PURE__ */ __name(function formControl() {
      return {
        name: this.name,
        resolver: this.resolver,
        initialValue: this.initialValue,
        validateOnValueUpdate: this.validateOnValueUpdate,
        validateOnBlur: this.validateOnBlur,
        validateOnMount: this.validateOnMount,
        validateOnSubmit: this.validateOnSubmit
      };
    }, "formControl"),
    field: /* @__PURE__ */ __name(function field() {
      var _this$$pcForm2;
      return ((_this$$pcForm2 = this.$pcForm) === null || _this$$pcForm2 === void 0 || (_this$$pcForm2 = _this$$pcForm2.fields) === null || _this$$pcForm2 === void 0 ? void 0 : _this$$pcForm2[this.name]) || {};
    }, "field"),
    fieldAttrs: /* @__PURE__ */ __name(function fieldAttrs() {
      return _objectSpread$3(_objectSpread$3({}, this.field.props), this.field.states);
    }, "fieldAttrs")
  }
};
function render$1(_ctx, _cache, $props, $setup, $data, $options) {
  return !_ctx.asChild ? (openBlock(), createBlock(resolveDynamicComponent(_ctx.as), mergeProps$1({
    key: 0,
    "class": _ctx.cx("root")
  }, _ctx.ptmi("root")), {
    "default": withCtx(function() {
      return [renderSlot(_ctx.$slots, "default", mergeProps$1({
        props: $options.field.props
      }, $options.fieldAttrs))];
    }),
    _: 3
  }, 16, ["class"])) : renderSlot(_ctx.$slots, "default", mergeProps$1({
    key: 1,
    "class": _ctx.cx("root"),
    props: $options.field.props
  }, $options.fieldAttrs));
}
__name(render$1, "render$1");
script.render = render$1;
var __defProp$1 = Object.defineProperty;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp$1 = /* @__PURE__ */ __name((obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value, "__defNormalProp$1");
var __spreadValues = /* @__PURE__ */ __name((a2, b2) => {
  for (var prop2 in b2 || (b2 = {}))
    if (__hasOwnProp.call(b2, prop2))
      __defNormalProp$1(a2, prop2, b2[prop2]);
  if (__getOwnPropSymbols)
    for (var prop2 of __getOwnPropSymbols(b2)) {
      if (__propIsEnum.call(b2, prop2))
        __defNormalProp$1(a2, prop2, b2[prop2]);
    }
  return a2;
}, "__spreadValues");
function isEmpty$1(value) {
  return value === null || value === void 0 || value === "" || Array.isArray(value) && value.length === 0 || !(value instanceof Date) && typeof value === "object" && Object.keys(value).length === 0;
}
__name(isEmpty$1, "isEmpty$1");
function compare$1(value1, value2, comparator, order = 1) {
  let result = -1;
  const emptyValue1 = isEmpty$1(value1);
  const emptyValue2 = isEmpty$1(value2);
  if (emptyValue1 && emptyValue2) result = 0;
  else if (emptyValue1) result = order;
  else if (emptyValue2) result = -order;
  else if (typeof value1 === "string" && typeof value2 === "string") result = comparator(value1, value2);
  else result = value1 < value2 ? -1 : value1 > value2 ? 1 : 0;
  return result;
}
__name(compare$1, "compare$1");
function _deepEquals(obj1, obj2, visited = /* @__PURE__ */ new WeakSet()) {
  if (obj1 === obj2) return true;
  if (!obj1 || !obj2 || typeof obj1 !== "object" || typeof obj2 !== "object") return false;
  if (visited.has(obj1) || visited.has(obj2)) return false;
  visited.add(obj1).add(obj2);
  let arrObj1 = Array.isArray(obj1), arrObj2 = Array.isArray(obj2), i2, length, key;
  if (arrObj1 && arrObj2) {
    length = obj1.length;
    if (length != obj2.length) return false;
    for (i2 = length; i2-- !== 0; ) if (!_deepEquals(obj1[i2], obj2[i2], visited)) return false;
    return true;
  }
  if (arrObj1 != arrObj2) return false;
  let dateObj1 = obj1 instanceof Date, dateObj2 = obj2 instanceof Date;
  if (dateObj1 != dateObj2) return false;
  if (dateObj1 && dateObj2) return obj1.getTime() == obj2.getTime();
  let regexpObj1 = obj1 instanceof RegExp, regexpObj2 = obj2 instanceof RegExp;
  if (regexpObj1 != regexpObj2) return false;
  if (regexpObj1 && regexpObj2) return obj1.toString() == obj2.toString();
  let keys2 = Object.keys(obj1);
  length = keys2.length;
  if (length !== Object.keys(obj2).length) return false;
  for (i2 = length; i2-- !== 0; ) if (!Object.prototype.hasOwnProperty.call(obj2, keys2[i2])) return false;
  for (i2 = length; i2-- !== 0; ) {
    key = keys2[i2];
    if (!_deepEquals(obj1[key], obj2[key], visited)) return false;
  }
  return true;
}
__name(_deepEquals, "_deepEquals");
function deepEquals(obj1, obj2) {
  return _deepEquals(obj1, obj2);
}
__name(deepEquals, "deepEquals");
function isFunction$6(value) {
  return !!(value && value.constructor && value.call && value.apply);
}
__name(isFunction$6, "isFunction$6");
function isNotEmpty(value) {
  return !isEmpty$1(value);
}
__name(isNotEmpty, "isNotEmpty");
function resolveFieldData(data, field2) {
  if (!data || !field2) {
    return null;
  }
  try {
    const value = data[field2];
    if (isNotEmpty(value)) return value;
  } catch (e2) {
  }
  if (Object.keys(data).length) {
    if (isFunction$6(field2)) {
      return field2(data);
    } else if (field2.indexOf(".") === -1) {
      return data[field2];
    } else {
      let fields = field2.split(".");
      let value = data;
      for (let i2 = 0, len = fields.length; i2 < len; ++i2) {
        if (value == null) {
          return null;
        }
        value = value[fields[i2]];
      }
      return value;
    }
  }
  return null;
}
__name(resolveFieldData, "resolveFieldData");
function equals(obj1, obj2, field2) {
  if (field2) return resolveFieldData(obj1, field2) === resolveFieldData(obj2, field2);
  else return deepEquals(obj1, obj2);
}
__name(equals, "equals");
function contains(value, list2) {
  if (value != null && list2 && list2.length) {
    for (let val of list2) {
      if (equals(value, val)) return true;
    }
  }
  return false;
}
__name(contains, "contains");
function filter(value, fields, filterValue) {
  let filteredItems = [];
  if (value) {
    for (let item of value) {
      for (let field2 of fields) {
        if (String(resolveFieldData(item, field2)).toLowerCase().indexOf(filterValue.toLowerCase()) > -1) {
          filteredItems.push(item);
          break;
        }
      }
    }
  }
  return filteredItems;
}
__name(filter, "filter");
function findIndexInList(value, list2) {
  let index2 = -1;
  if (list2) {
    for (let i2 = 0; i2 < list2.length; i2++) {
      if (list2[i2] === value) {
        index2 = i2;
        break;
      }
    }
  }
  return index2;
}
__name(findIndexInList, "findIndexInList");
function findLast(arr, callback) {
  let item;
  if (isNotEmpty(arr)) {
    try {
      item = arr.findLast(callback);
    } catch (e2) {
      item = [...arr].reverse().find(callback);
    }
  }
  return item;
}
__name(findLast, "findLast");
function findLastIndex(arr, callback) {
  let index2 = -1;
  if (isNotEmpty(arr)) {
    try {
      index2 = arr.findLastIndex(callback);
    } catch (e2) {
      index2 = arr.lastIndexOf([...arr].reverse().find(callback));
    }
  }
  return index2;
}
__name(findLastIndex, "findLastIndex");
function isObject$9(value, empty2 = true) {
  return value instanceof Object && value.constructor === Object && (empty2 || Object.keys(value).length !== 0);
}
__name(isObject$9, "isObject$9");
function resolve(obj, ...params) {
  return isFunction$6(obj) ? obj(...params) : obj;
}
__name(resolve, "resolve");
function isString$4(value, empty2 = true) {
  return typeof value === "string" && (empty2 || value !== "");
}
__name(isString$4, "isString$4");
function toFlatCase(str) {
  return isString$4(str) ? str.replace(/(-|_)/g, "").toLowerCase() : str;
}
__name(toFlatCase, "toFlatCase");
function getKeyValue(obj, key = "", params = {}) {
  const fKeys = toFlatCase(key).split(".");
  const fKey = fKeys.shift();
  return fKey ? isObject$9(obj) ? getKeyValue(resolve(obj[Object.keys(obj).find((k2) => toFlatCase(k2) === fKey) || ""], params), fKeys.join("."), params) : void 0 : resolve(obj, params);
}
__name(getKeyValue, "getKeyValue");
function insertIntoOrderedArray(item, index2, arr, sourceArr) {
  if (arr.length > 0) {
    let injected = false;
    for (let i2 = 0; i2 < arr.length; i2++) {
      let currentItemIndex = findIndexInList(arr[i2], sourceArr);
      if (currentItemIndex > index2) {
        arr.splice(i2, 0, item);
        injected = true;
        break;
      }
    }
    if (!injected) {
      arr.push(item);
    }
  } else {
    arr.push(item);
  }
}
__name(insertIntoOrderedArray, "insertIntoOrderedArray");
function isArray$6(value, empty2 = true) {
  return Array.isArray(value) && (empty2 || value.length !== 0);
}
__name(isArray$6, "isArray$6");
function isDate(value) {
  return value instanceof Date && value.constructor === Date;
}
__name(isDate, "isDate");
function isLetter$1(char) {
  return /^[a-zA-Z\u00C0-\u017F]$/.test(char);
}
__name(isLetter$1, "isLetter$1");
function isNumber$3(value) {
  return isNotEmpty(value) && !isNaN(value);
}
__name(isNumber$3, "isNumber$3");
function isPrintableCharacter(char = "") {
  return isNotEmpty(char) && char.length === 1 && !!char.match(/\S| /);
}
__name(isPrintableCharacter, "isPrintableCharacter");
function isScalar(value) {
  return value != null && (typeof value === "string" || typeof value === "number" || typeof value === "bigint" || typeof value === "boolean");
}
__name(isScalar, "isScalar");
function localeComparator() {
  return new Intl.Collator(void 0, { numeric: true }).compare;
}
__name(localeComparator, "localeComparator");
function matchRegex(str, regex2) {
  if (regex2) {
    const match2 = regex2.test(str);
    regex2.lastIndex = 0;
    return match2;
  }
  return false;
}
__name(matchRegex, "matchRegex");
function mergeKeys(...args) {
  const _mergeKeys = /* @__PURE__ */ __name((target = {}, source = {}) => {
    const mergedObj = __spreadValues({}, target);
    Object.keys(source).forEach((key) => {
      if (isObject$9(source[key]) && key in target && isObject$9(target[key])) {
        mergedObj[key] = _mergeKeys(target[key], source[key]);
      } else {
        mergedObj[key] = source[key];
      }
    });
    return mergedObj;
  }, "_mergeKeys");
  return args.reduce((acc, obj, i2) => i2 === 0 ? obj : _mergeKeys(acc, obj), {});
}
__name(mergeKeys, "mergeKeys");
function minifyCSS(css3) {
  return css3 ? css3.replace(/\/\*(?:(?!\*\/)[\s\S])*\*\/|[\r\n\t]+/g, "").replace(/ {2,}/g, " ").replace(/ ([{:}]) /g, "$1").replace(/([;,]) /g, "$1").replace(/ !/g, "!").replace(/: /g, ":") : css3;
}
__name(minifyCSS, "minifyCSS");
function nestedKeys(obj = {}, parentKey = "") {
  return Object.entries(obj).reduce((o2, [key, value]) => {
    const currentKey = parentKey ? `${parentKey}.${key}` : key;
    isObject$9(value) ? o2 = o2.concat(nestedKeys(value, currentKey)) : o2.push(currentKey);
    return o2;
  }, []);
}
__name(nestedKeys, "nestedKeys");
function omit(obj, ...keys2) {
  if (!isObject$9(obj)) return obj;
  const copy2 = __spreadValues({}, obj);
  keys2 == null ? void 0 : keys2.flat().forEach((key) => delete copy2[key]);
  return copy2;
}
__name(omit, "omit");
function removeAccents(str) {
  const accentCheckRegex = /[\xC0-\xFF\u0100-\u017E]/;
  if (str && accentCheckRegex.test(str)) {
    const accentsMap = {
      A: /[\xC0-\xC5\u0100\u0102\u0104]/g,
      AE: /[\xC6]/g,
      C: /[\xC7\u0106\u0108\u010A\u010C]/g,
      D: /[\xD0\u010E\u0110]/g,
      E: /[\xC8-\xCB\u0112\u0114\u0116\u0118\u011A]/g,
      G: /[\u011C\u011E\u0120\u0122]/g,
      H: /[\u0124\u0126]/g,
      I: /[\xCC-\xCF\u0128\u012A\u012C\u012E\u0130]/g,
      IJ: /[\u0132]/g,
      J: /[\u0134]/g,
      K: /[\u0136]/g,
      L: /[\u0139\u013B\u013D\u013F\u0141]/g,
      N: /[\xD1\u0143\u0145\u0147\u014A]/g,
      O: /[\xD2-\xD6\xD8\u014C\u014E\u0150]/g,
      OE: /[\u0152]/g,
      R: /[\u0154\u0156\u0158]/g,
      S: /[\u015A\u015C\u015E\u0160]/g,
      T: /[\u0162\u0164\u0166]/g,
      U: /[\xD9-\xDC\u0168\u016A\u016C\u016E\u0170\u0172]/g,
      W: /[\u0174]/g,
      Y: /[\xDD\u0176\u0178]/g,
      Z: /[\u0179\u017B\u017D]/g,
      a: /[\xE0-\xE5\u0101\u0103\u0105]/g,
      ae: /[\xE6]/g,
      c: /[\xE7\u0107\u0109\u010B\u010D]/g,
      d: /[\u010F\u0111]/g,
      e: /[\xE8-\xEB\u0113\u0115\u0117\u0119\u011B]/g,
      g: /[\u011D\u011F\u0121\u0123]/g,
      i: /[\xEC-\xEF\u0129\u012B\u012D\u012F\u0131]/g,
      ij: /[\u0133]/g,
      j: /[\u0135]/g,
      k: /[\u0137,\u0138]/g,
      l: /[\u013A\u013C\u013E\u0140\u0142]/g,
      n: /[\xF1\u0144\u0146\u0148\u014B]/g,
      p: /[\xFE]/g,
      o: /[\xF2-\xF6\xF8\u014D\u014F\u0151]/g,
      oe: /[\u0153]/g,
      r: /[\u0155\u0157\u0159]/g,
      s: /[\u015B\u015D\u015F\u0161]/g,
      t: /[\u0163\u0165\u0167]/g,
      u: /[\xF9-\xFC\u0169\u016B\u016D\u016F\u0171\u0173]/g,
      w: /[\u0175]/g,
      y: /[\xFD\xFF\u0177]/g,
      z: /[\u017A\u017C\u017E]/g
    };
    for (let key in accentsMap) {
      str = str.replace(accentsMap[key], key);
    }
  }
  return str;
}
__name(removeAccents, "removeAccents");
function reorderArray(value, from2, to) {
  if (value && from2 !== to) {
    if (to >= value.length) {
      to %= value.length;
      from2 %= value.length;
    }
    value.splice(to, 0, value.splice(from2, 1)[0]);
  }
}
__name(reorderArray, "reorderArray");
function sort(value1, value2, order = 1, comparator, nullSortOrder = 1) {
  const result = compare$1(value1, value2, comparator, order);
  let finalSortOrder = order;
  if (isEmpty$1(value1) || isEmpty$1(value2)) {
    finalSortOrder = nullSortOrder === 1 ? order : nullSortOrder;
  }
  return finalSortOrder * result;
}
__name(sort, "sort");
function stringify(value, indent = 2, currentIndent = 0) {
  const currentIndentStr = " ".repeat(currentIndent);
  const nextIndentStr = " ".repeat(currentIndent + indent);
  if (isArray$6(value)) {
    return "[" + value.map((v2) => stringify(v2, indent, currentIndent + indent)).join(", ") + "]";
  } else if (isDate(value)) {
    return value.toISOString();
  } else if (isFunction$6(value)) {
    return value.toString();
  } else if (isObject$9(value)) {
    return "{\n" + Object.entries(value).map(([k2, v2]) => `${nextIndentStr}${k2}: ${stringify(v2, indent, currentIndent + indent)}`).join(",\n") + `
${currentIndentStr}}`;
  } else {
    return JSON.stringify(value);
  }
}
__name(stringify, "stringify");
function toCapitalCase(str) {
  return isString$4(str, false) ? str[0].toUpperCase() + str.slice(1) : str;
}
__name(toCapitalCase, "toCapitalCase");
function toKebabCase(str) {
  return isString$4(str) ? str.replace(/(_)/g, "-").replace(/[A-Z]/g, (c2, i2) => i2 === 0 ? c2 : "-" + c2.toLowerCase()).toLowerCase() : str;
}
__name(toKebabCase, "toKebabCase");
function toTokenKey(str) {
  return isString$4(str) ? str.replace(/[A-Z]/g, (c2, i2) => i2 === 0 ? c2 : "." + c2.toLowerCase()).toLowerCase() : str;
}
__name(toTokenKey, "toTokenKey");
function toValue(value) {
  if (value && typeof value === "object") {
    if (value.hasOwnProperty("current")) {
      return value.current;
    } else if (value.hasOwnProperty("value")) {
      return value.value;
    }
  }
  return resolve(value);
}
__name(toValue, "toValue");
var toValues = /* @__PURE__ */ __name((value, name2) => {
  if (isObject$9(value) && value.hasOwnProperty(name2)) {
    return value;
  }
  return name2 ? { [name2]: value } : value;
}, "toValues");
var zodResolver = /* @__PURE__ */ __name((schema2, schemaOptions, resolverOptions) => async ({ values, name: name2 }) => {
  const { sync = false, raw = false } = resolverOptions || {};
  try {
    const result = await schema2[sync ? "parse" : "parseAsync"](values, schemaOptions);
    return {
      values: toValues(raw ? values : result, name2),
      errors: {}
    };
  } catch (e2) {
    if (Array.isArray(e2?.errors)) {
      return {
        values: toValues(raw ? values : void 0, name2),
        errors: e2.errors.reduce((acc, error2) => {
          const pathKey = isNotEmpty(error2.path) ? error2.path[0] : name2;
          if (pathKey) {
            acc[pathKey] ||= [];
            acc[pathKey].push(error2);
          }
          return acc;
        }, {})
      };
    }
    throw e2;
  }
}, "zodResolver");
function listCacheClear$1() {
  this.__data__ = [];
  this.size = 0;
}
__name(listCacheClear$1, "listCacheClear$1");
var _listCacheClear = listCacheClear$1;
const _listCacheClear$1 = /* @__PURE__ */ getDefaultExportFromCjs(_listCacheClear);
function eq$2(value, other) {
  return value === other || value !== value && other !== other;
}
__name(eq$2, "eq$2");
var eq_1 = eq$2;
const eq$3 = /* @__PURE__ */ getDefaultExportFromCjs(eq_1);
var eq$1 = eq_1;
function assocIndexOf$4(array, key) {
  var length = array.length;
  while (length--) {
    if (eq$1(array[length][0], key)) {
      return length;
    }
  }
  return -1;
}
__name(assocIndexOf$4, "assocIndexOf$4");
var _assocIndexOf = assocIndexOf$4;
const _assocIndexOf$1 = /* @__PURE__ */ getDefaultExportFromCjs(_assocIndexOf);
var assocIndexOf$3 = _assocIndexOf;
var arrayProto = Array.prototype;
var splice = arrayProto.splice;
function listCacheDelete$1(key) {
  var data = this.__data__, index2 = assocIndexOf$3(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;
}
__name(listCacheDelete$1, "listCacheDelete$1");
var _listCacheDelete = listCacheDelete$1;
const _listCacheDelete$1 = /* @__PURE__ */ getDefaultExportFromCjs(_listCacheDelete);
var assocIndexOf$2 = _assocIndexOf;
function listCacheGet$1(key) {
  var data = this.__data__, index2 = assocIndexOf$2(data, key);
  return index2 < 0 ? void 0 : data[index2][1];
}
__name(listCacheGet$1, "listCacheGet$1");
var _listCacheGet = listCacheGet$1;
const _listCacheGet$1 = /* @__PURE__ */ getDefaultExportFromCjs(_listCacheGet);
var assocIndexOf$1 = _assocIndexOf;
function listCacheHas$1(key) {
  return assocIndexOf$1(this.__data__, key) > -1;
}
__name(listCacheHas$1, "listCacheHas$1");
var _listCacheHas = listCacheHas$1;
const _listCacheHas$1 = /* @__PURE__ */ getDefaultExportFromCjs(_listCacheHas);
var assocIndexOf = _assocIndexOf;
function listCacheSet$1(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;
}
__name(listCacheSet$1, "listCacheSet$1");
var _listCacheSet = listCacheSet$1;
const _listCacheSet$1 = /* @__PURE__ */ getDefaultExportFromCjs(_listCacheSet);
var listCacheClear = _listCacheClear, listCacheDelete = _listCacheDelete, listCacheGet = _listCacheGet, listCacheHas = _listCacheHas, listCacheSet = _listCacheSet;
function ListCache$4(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]);
  }
}
__name(ListCache$4, "ListCache$4");
ListCache$4.prototype.clear = listCacheClear;
ListCache$4.prototype["delete"] = listCacheDelete;
ListCache$4.prototype.get = listCacheGet;
ListCache$4.prototype.has = listCacheHas;
ListCache$4.prototype.set = listCacheSet;
var _ListCache = ListCache$4;
const _ListCache$1 = /* @__PURE__ */ getDefaultExportFromCjs(_ListCache);
var ListCache$3 = _ListCache;
function stackClear$1() {
  this.__data__ = new ListCache$3();
  this.size = 0;
}
__name(stackClear$1, "stackClear$1");
var _stackClear = stackClear$1;
const _stackClear$1 = /* @__PURE__ */ getDefaultExportFromCjs(_stackClear);
function stackDelete$1(key) {
  var data = this.__data__, result = data["delete"](key);
  this.size = data.size;
  return result;
}
__name(stackDelete$1, "stackDelete$1");
var _stackDelete = stackDelete$1;
const _stackDelete$1 = /* @__PURE__ */ getDefaultExportFromCjs(_stackDelete);
function stackGet$1(key) {
  return this.__data__.get(key);
}
__name(stackGet$1, "stackGet$1");
var _stackGet = stackGet$1;
const _stackGet$1 = /* @__PURE__ */ getDefaultExportFromCjs(_stackGet);
function stackHas$1(key) {
  return this.__data__.has(key);
}
__name(stackHas$1, "stackHas$1");
var _stackHas = stackHas$1;
const _stackHas$1 = /* @__PURE__ */ getDefaultExportFromCjs(_stackHas);
var freeGlobal$1 = typeof commonjsGlobal == "object" && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
var _freeGlobal = freeGlobal$1;
const _freeGlobal$1 = /* @__PURE__ */ getDefaultExportFromCjs(_freeGlobal);
var freeGlobal = _freeGlobal;
var freeSelf = typeof self == "object" && self && self.Object === Object && self;
var root$8 = freeGlobal || freeSelf || Function("return this")();
var _root = root$8;
const _root$1 = /* @__PURE__ */ getDefaultExportFromCjs(_root);
var root$7 = _root;
var Symbol$4 = root$7.Symbol;
var _Symbol = Symbol$4;
const _Symbol$1 = /* @__PURE__ */ getDefaultExportFromCjs(_Symbol);
var Symbol$3 = _Symbol;
var objectProto$c = Object.prototype;
var hasOwnProperty$9 = objectProto$c.hasOwnProperty;
var nativeObjectToString$1 = objectProto$c.toString;
var symToStringTag$1 = Symbol$3 ? Symbol$3.toStringTag : void 0;
function getRawTag$1(value) {
  var isOwn = hasOwnProperty$9.call(value, symToStringTag$1), tag = value[symToStringTag$1];
  try {
    value[symToStringTag$1] = void 0;
    var unmasked = true;
  } catch (e2) {
  }
  var result = nativeObjectToString$1.call(value);
  if (unmasked) {
    if (isOwn) {
      value[symToStringTag$1] = tag;
    } else {
      delete value[symToStringTag$1];
    }
  }
  return result;
}
__name(getRawTag$1, "getRawTag$1");
var _getRawTag = getRawTag$1;
const _getRawTag$1 = /* @__PURE__ */ getDefaultExportFromCjs(_getRawTag);
var objectProto$b = Object.prototype;
var nativeObjectToString = objectProto$b.toString;
function objectToString$1(value) {
  return nativeObjectToString.call(value);
}
__name(objectToString$1, "objectToString$1");
var _objectToString = objectToString$1;
const _objectToString$1 = /* @__PURE__ */ getDefaultExportFromCjs(_objectToString);
var Symbol$2 = _Symbol, getRawTag = _getRawTag, objectToString = _objectToString;
var nullTag = "[object Null]", undefinedTag = "[object Undefined]";
var symToStringTag = Symbol$2 ? Symbol$2.toStringTag : void 0;
function baseGetTag$4(value) {
  if (value == null) {
    return value === void 0 ? undefinedTag : nullTag;
  }
  return symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString(value);
}
__name(baseGetTag$4, "baseGetTag$4");
var _baseGetTag = baseGetTag$4;
const _baseGetTag$1 = /* @__PURE__ */ getDefaultExportFromCjs(_baseGetTag);
function isObject$7(value) {
  var type = typeof value;
  return value != null && (type == "object" || type == "function");
}
__name(isObject$7, "isObject$7");
var isObject_1 = isObject$7;
const isObject$8 = /* @__PURE__ */ getDefaultExportFromCjs(isObject_1);
var baseGetTag$3 = _baseGetTag, isObject$6 = isObject_1;
var asyncTag = "[object AsyncFunction]", funcTag$2 = "[object Function]", genTag$1 = "[object GeneratorFunction]", proxyTag = "[object Proxy]";
function isFunction$4(value) {
  if (!isObject$6(value)) {
    return false;
  }
  var tag = baseGetTag$3(value);
  return tag == funcTag$2 || tag == genTag$1 || tag == asyncTag || tag == proxyTag;
}
__name(isFunction$4, "isFunction$4");
var isFunction_1 = isFunction$4;
const isFunction$5 = /* @__PURE__ */ getDefaultExportFromCjs(isFunction_1);
var root$6 = _root;
var coreJsData$1 = root$6["__core-js_shared__"];
var _coreJsData = coreJsData$1;
const _coreJsData$1 = /* @__PURE__ */ getDefaultExportFromCjs(_coreJsData);
var coreJsData = _coreJsData;
var maskSrcKey = function() {
  var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || "");
  return uid ? "Symbol(src)_1." + uid : "";
}();
function isMasked$1(func) {
  return !!maskSrcKey && maskSrcKey in func;
}
__name(isMasked$1, "isMasked$1");
var _isMasked = isMasked$1;
const _isMasked$1 = /* @__PURE__ */ getDefaultExportFromCjs(_isMasked);
var funcProto$1 = Function.prototype;
var funcToString$1 = funcProto$1.toString;
function toSource$2(func) {
  if (func != null) {
    try {
      return funcToString$1.call(func);
    } catch (e2) {
    }
    try {
      return func + "";
    } catch (e2) {
    }
  }
  return "";
}
__name(toSource$2, "toSource$2");
var _toSource = toSource$2;
const _toSource$1 = /* @__PURE__ */ getDefaultExportFromCjs(_toSource);
var isFunction$3 = isFunction_1, isMasked = _isMasked, isObject$5 = isObject_1, toSource$1 = _toSource;
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
var reIsHostCtor = /^\[object .+?Constructor\]$/;
var funcProto = Function.prototype, objectProto$a = Object.prototype;
var funcToString = funcProto.toString;
var hasOwnProperty$8 = objectProto$a.hasOwnProperty;
var reIsNative = RegExp(
  "^" + funcToString.call(hasOwnProperty$8).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$"
);
function baseIsNative$1(value) {
  if (!isObject$5(value) || isMasked(value)) {
    return false;
  }
  var pattern = isFunction$3(value) ? reIsNative : reIsHostCtor;
  return pattern.test(toSource$1(value));
}
__name(baseIsNative$1, "baseIsNative$1");
var _baseIsNative = baseIsNative$1;
const _baseIsNative$1 = /* @__PURE__ */ getDefaultExportFromCjs(_baseIsNative);
function getValue$1(object, key) {
  return object == null ? void 0 : object[key];
}
__name(getValue$1, "getValue$1");
var _getValue = getValue$1;
const _getValue$1 = /* @__PURE__ */ getDefaultExportFromCjs(_getValue);
var baseIsNative = _baseIsNative, getValue = _getValue;
function getNative$7(object, key) {
  var value = getValue(object, key);
  return baseIsNative(value) ? value : void 0;
}
__name(getNative$7, "getNative$7");
var _getNative = getNative$7;
const _getNative$1 = /* @__PURE__ */ getDefaultExportFromCjs(_getNative);
var getNative$6 = _getNative, root$5 = _root;
var Map$4 = getNative$6(root$5, "Map");
var _Map = Map$4;
const _Map$1 = /* @__PURE__ */ getDefaultExportFromCjs(_Map);
var getNative$5 = _getNative;
var nativeCreate$4 = getNative$5(Object, "create");
var _nativeCreate = nativeCreate$4;
const _nativeCreate$1 = /* @__PURE__ */ getDefaultExportFromCjs(_nativeCreate);
var nativeCreate$3 = _nativeCreate;
function hashClear$1() {
  this.__data__ = nativeCreate$3 ? nativeCreate$3(null) : {};
  this.size = 0;
}
__name(hashClear$1, "hashClear$1");
var _hashClear = hashClear$1;
const _hashClear$1 = /* @__PURE__ */ getDefaultExportFromCjs(_hashClear);
function hashDelete$1(key) {
  var result = this.has(key) && delete this.__data__[key];
  this.size -= result ? 1 : 0;
  return result;
}
__name(hashDelete$1, "hashDelete$1");
var _hashDelete = hashDelete$1;
const _hashDelete$1 = /* @__PURE__ */ getDefaultExportFromCjs(_hashDelete);
var nativeCreate$2 = _nativeCreate;
var HASH_UNDEFINED$1 = "__lodash_hash_undefined__";
var objectProto$9 = Object.prototype;
var hasOwnProperty$7 = objectProto$9.hasOwnProperty;
function hashGet$1(key) {
  var data = this.__data__;
  if (nativeCreate$2) {
    var result = data[key];
    return result === HASH_UNDEFINED$1 ? void 0 : result;
  }
  return hasOwnProperty$7.call(data, key) ? data[key] : void 0;
}
__name(hashGet$1, "hashGet$1");
var _hashGet = hashGet$1;
const _hashGet$1 = /* @__PURE__ */ getDefaultExportFromCjs(_hashGet);
var nativeCreate$1 = _nativeCreate;
var objectProto$8 = Object.prototype;
var hasOwnProperty$6 = objectProto$8.hasOwnProperty;
function hashHas$1(key) {
  var data = this.__data__;
  return nativeCreate$1 ? data[key] !== void 0 : hasOwnProperty$6.call(data, key);
}
__name(hashHas$1, "hashHas$1");
var _hashHas = hashHas$1;
const _hashHas$1 = /* @__PURE__ */ getDefaultExportFromCjs(_hashHas);
var nativeCreate = _nativeCreate;
var HASH_UNDEFINED = "__lodash_hash_undefined__";
function hashSet$1(key, value) {
  var data = this.__data__;
  this.size += this.has(key) ? 0 : 1;
  data[key] = nativeCreate && value === void 0 ? HASH_UNDEFINED : value;
  return this;
}
__name(hashSet$1, "hashSet$1");
var _hashSet = hashSet$1;
const _hashSet$1 = /* @__PURE__ */ getDefaultExportFromCjs(_hashSet);
var hashClear = _hashClear, hashDelete = _hashDelete, hashGet = _hashGet, hashHas = _hashHas, hashSet = _hashSet;
function Hash$1(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]);
  }
}
__name(Hash$1, "Hash$1");
Hash$1.prototype.clear = hashClear;
Hash$1.prototype["delete"] = hashDelete;
Hash$1.prototype.get = hashGet;
Hash$1.prototype.has = hashHas;
Hash$1.prototype.set = hashSet;
var _Hash = Hash$1;
const _Hash$1 = /* @__PURE__ */ getDefaultExportFromCjs(_Hash);
var Hash = _Hash, ListCache$2 = _ListCache, Map$3 = _Map;
function mapCacheClear$1() {
  this.size = 0;
  this.__data__ = {
    "hash": new Hash(),
    "map": new (Map$3 || ListCache$2)(),
    "string": new Hash()
  };
}
__name(mapCacheClear$1, "mapCacheClear$1");
var _mapCacheClear = mapCacheClear$1;
const _mapCacheClear$1 = /* @__PURE__ */ getDefaultExportFromCjs(_mapCacheClear);
function isKeyable$1(value) {
  var type = typeof value;
  return type == "string" || type == "number" || type == "symbol" || type == "boolean" ? value !== "__proto__" : value === null;
}
__name(isKeyable$1, "isKeyable$1");
var _isKeyable = isKeyable$1;
const _isKeyable$1 = /* @__PURE__ */ getDefaultExportFromCjs(_isKeyable);
var isKeyable = _isKeyable;
function getMapData$4(map3, key) {
  var data = map3.__data__;
  return isKeyable(key) ? data[typeof key == "string" ? "string" : "hash"] : data.map;
}
__name(getMapData$4, "getMapData$4");
var _getMapData = getMapData$4;
const _getMapData$1 = /* @__PURE__ */ getDefaultExportFromCjs(_getMapData);
var getMapData$3 = _getMapData;
function mapCacheDelete$1(key) {
  var result = getMapData$3(this, key)["delete"](key);
  this.size -= result ? 1 : 0;
  return result;
}
__name(mapCacheDelete$1, "mapCacheDelete$1");
var _mapCacheDelete = mapCacheDelete$1;
const _mapCacheDelete$1 = /* @__PURE__ */ getDefaultExportFromCjs(_mapCacheDelete);
var getMapData$2 = _getMapData;
function mapCacheGet$1(key) {
  return getMapData$2(this, key).get(key);
}
__name(mapCacheGet$1, "mapCacheGet$1");
var _mapCacheGet = mapCacheGet$1;
const _mapCacheGet$1 = /* @__PURE__ */ getDefaultExportFromCjs(_mapCacheGet);
var getMapData$1 = _getMapData;
function mapCacheHas$1(key) {
  return getMapData$1(this, key).has(key);
}
__name(mapCacheHas$1, "mapCacheHas$1");
var _mapCacheHas = mapCacheHas$1;
const _mapCacheHas$1 = /* @__PURE__ */ getDefaultExportFromCjs(_mapCacheHas);
var getMapData = _getMapData;
function mapCacheSet$1(key, value) {
  var data = getMapData(this, key), size = data.size;
  data.set(key, value);
  this.size += data.size == size ? 0 : 1;
  return this;
}
__name(mapCacheSet$1, "mapCacheSet$1");
var _mapCacheSet = mapCacheSet$1;
const _mapCacheSet$1 = /* @__PURE__ */ getDefaultExportFromCjs(_mapCacheSet);
var mapCacheClear = _mapCacheClear, mapCacheDelete = _mapCacheDelete, mapCacheGet = _mapCacheGet, mapCacheHas = _mapCacheHas, mapCacheSet = _mapCacheSet;
function MapCache$1(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]);
  }
}
__name(MapCache$1, "MapCache$1");
MapCache$1.prototype.clear = mapCacheClear;
MapCache$1.prototype["delete"] = mapCacheDelete;
MapCache$1.prototype.get = mapCacheGet;
MapCache$1.prototype.has = mapCacheHas;
MapCache$1.prototype.set = mapCacheSet;
var _MapCache = MapCache$1;
const _MapCache$1 = /* @__PURE__ */ getDefaultExportFromCjs(_MapCache);
var ListCache$1 = _ListCache, Map$2 = _Map, MapCache = _MapCache;
var LARGE_ARRAY_SIZE = 200;
function stackSet$1(key, value) {
  var data = this.__data__;
  if (data instanceof ListCache$1) {
    var pairs = data.__data__;
    if (!Map$2 || 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;
}
__name(stackSet$1, "stackSet$1");
var _stackSet = stackSet$1;
const _stackSet$1 = /* @__PURE__ */ getDefaultExportFromCjs(_stackSet);
var ListCache = _ListCache, stackClear = _stackClear, stackDelete = _stackDelete, stackGet = _stackGet, stackHas = _stackHas, stackSet = _stackSet;
function Stack$1(entries) {
  var data = this.__data__ = new ListCache(entries);
  this.size = data.size;
}
__name(Stack$1, "Stack$1");
Stack$1.prototype.clear = stackClear;
Stack$1.prototype["delete"] = stackDelete;
Stack$1.prototype.get = stackGet;
Stack$1.prototype.has = stackHas;
Stack$1.prototype.set = stackSet;
var _Stack = Stack$1;
const _Stack$1 = /* @__PURE__ */ getDefaultExportFromCjs(_Stack);
function arrayEach$1(array, iteratee) {
  var index2 = -1, length = array == null ? 0 : array.length;
  while (++index2 < length) {
    if (iteratee(array[index2], index2, array) === false) {
      break;
    }
  }
  return array;
}
__name(arrayEach$1, "arrayEach$1");
var _arrayEach = arrayEach$1;
const _arrayEach$1 = /* @__PURE__ */ getDefaultExportFromCjs(_arrayEach);
var getNative$4 = _getNative;
var defineProperty$1 = function() {
  try {
    var func = getNative$4(Object, "defineProperty");
    func({}, "", {});
    return func;
  } catch (e2) {
  }
}();
var _defineProperty$1 = defineProperty$1;
const _defineProperty$2 = /* @__PURE__ */ getDefaultExportFromCjs(_defineProperty$1);
var defineProperty = _defineProperty$1;
function baseAssignValue$2(object, key, value) {
  if (key == "__proto__" && defineProperty) {
    defineProperty(object, key, {
      "configurable": true,
      "enumerable": true,
      "value": value,
      "writable": true
    });
  } else {
    object[key] = value;
  }
}
__name(baseAssignValue$2, "baseAssignValue$2");
var _baseAssignValue = baseAssignValue$2;
const _baseAssignValue$1 = /* @__PURE__ */ getDefaultExportFromCjs(_baseAssignValue);
var baseAssignValue$1 = _baseAssignValue, eq = eq_1;
var objectProto$7 = Object.prototype;
var hasOwnProperty$5 = objectProto$7.hasOwnProperty;
function assignValue$2(object, key, value) {
  var objValue = object[key];
  if (!(hasOwnProperty$5.call(object, key) && eq(objValue, value)) || value === void 0 && !(key in object)) {
    baseAssignValue$1(object, key, value);
  }
}
__name(assignValue$2, "assignValue$2");
var _assignValue = assignValue$2;
const _assignValue$1 = /* @__PURE__ */ getDefaultExportFromCjs(_assignValue);
var assignValue$1 = _assignValue, baseAssignValue = _baseAssignValue;
function copyObject$4(source, props, object, customizer) {
  var isNew = !object;
  object || (object = {});
  var index2 = -1, length = props.length;
  while (++index2 < length) {
    var key = props[index2];
    var newValue2 = customizer ? customizer(object[key], source[key], key, object, source) : void 0;
    if (newValue2 === void 0) {
      newValue2 = source[key];
    }
    if (isNew) {
      baseAssignValue(object, key, newValue2);
    } else {
      assignValue$1(object, key, newValue2);
    }
  }
  return object;
}
__name(copyObject$4, "copyObject$4");
var _copyObject = copyObject$4;
const _copyObject$1 = /* @__PURE__ */ getDefaultExportFromCjs(_copyObject);
function baseTimes$1(n2, iteratee) {
  var index2 = -1, result = Array(n2);
  while (++index2 < n2) {
    result[index2] = iteratee(index2);
  }
  return result;
}
__name(baseTimes$1, "baseTimes$1");
var _baseTimes = baseTimes$1;
const _baseTimes$1 = /* @__PURE__ */ getDefaultExportFromCjs(_baseTimes);
function isObjectLike$6(value) {
  return value != null && typeof value == "object";
}
__name(isObjectLike$6, "isObjectLike$6");
var isObjectLike_1 = isObjectLike$6;
const isObjectLike$7 = /* @__PURE__ */ getDefaultExportFromCjs(isObjectLike_1);
var baseGetTag$2 = _baseGetTag, isObjectLike$5 = isObjectLike_1;
var argsTag$2 = "[object Arguments]";
function baseIsArguments$1(value) {
  return isObjectLike$5(value) && baseGetTag$2(value) == argsTag$2;
}
__name(baseIsArguments$1, "baseIsArguments$1");
var _baseIsArguments = baseIsArguments$1;
const _baseIsArguments$1 = /* @__PURE__ */ getDefaultExportFromCjs(_baseIsArguments);
var baseIsArguments = _baseIsArguments, isObjectLike$4 = isObjectLike_1;
var objectProto$6 = Object.prototype;
var hasOwnProperty$4 = objectProto$6.hasOwnProperty;
var propertyIsEnumerable$1 = objectProto$6.propertyIsEnumerable;
var isArguments$1 = baseIsArguments(/* @__PURE__ */ function() {
  return arguments;
}()) ? baseIsArguments : function(value) {
  return isObjectLike$4(value) && hasOwnProperty$4.call(value, "callee") && !propertyIsEnumerable$1.call(value, "callee");
};
var isArguments_1 = isArguments$1;
const isArguments$2 = /* @__PURE__ */ getDefaultExportFromCjs(isArguments_1);
var isArray$4 = Array.isArray;
var isArray_1 = isArray$4;
const isArray$5 = /* @__PURE__ */ getDefaultExportFromCjs(isArray_1);
var isBuffer$3 = { exports: {} };
function stubFalse() {
  return false;
}
__name(stubFalse, "stubFalse");
var stubFalse_1 = stubFalse;
const stubFalse$1 = /* @__PURE__ */ getDefaultExportFromCjs(stubFalse_1);
var isBuffer_1 = isBuffer$3.exports;
(function(module2, exports) {
  var root2 = _root, stubFalse2 = stubFalse_1;
  var freeExports = exports && !exports.nodeType && exports;
  var freeModule = freeExports && true && module2 && !module2.nodeType && module2;
  var moduleExports = freeModule && freeModule.exports === freeExports;
  var Buffer2 = moduleExports ? root2.Buffer : void 0;
  var nativeIsBuffer = Buffer2 ? Buffer2.isBuffer : void 0;
  var isBuffer2 = nativeIsBuffer || stubFalse2;
  module2.exports = isBuffer2;
})(isBuffer$3, isBuffer$3.exports);
var isBufferExports = isBuffer$3.exports;
const isBuffer$2 = /* @__PURE__ */ getDefaultExportFromCjs(isBufferExports);
var MAX_SAFE_INTEGER$1 = 9007199254740991;
var reIsUint = /^(?:0|[1-9]\d*)$/;
function isIndex$1(value, length) {
  var type = typeof value;
  length = length == null ? MAX_SAFE_INTEGER$1 : length;
  return !!length && (type == "number" || type != "symbol" && reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length);
}
__name(isIndex$1, "isIndex$1");
var _isIndex = isIndex$1;
const _isIndex$1 = /* @__PURE__ */ getDefaultExportFromCjs(_isIndex);
var MAX_SAFE_INTEGER = 9007199254740991;
function isLength$2(value) {
  return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
__name(isLength$2, "isLength$2");
var isLength_1 = isLength$2;
const isLength$3 = /* @__PURE__ */ getDefaultExportFromCjs(isLength_1);
var baseGetTag$1 = _baseGetTag, isLength$1 = isLength_1, isObjectLike$3 = isObjectLike_1;
var argsTag$1 = "[object Arguments]", arrayTag$1 = "[object Array]", boolTag$2 = "[object Boolean]", dateTag$2 = "[object Date]", errorTag$1 = "[object Error]", funcTag$1 = "[object Function]", mapTag$4 = "[object Map]", numberTag$2 = "[object Number]", objectTag$2 = "[object Object]", regexpTag$2 = "[object RegExp]", setTag$4 = "[object Set]", stringTag$2 = "[object String]", weakMapTag$2 = "[object WeakMap]";
var arrayBufferTag$2 = "[object ArrayBuffer]", dataViewTag$3 = "[object DataView]", float32Tag$2 = "[object Float32Array]", float64Tag$2 = "[object Float64Array]", int8Tag$2 = "[object Int8Array]", int16Tag$2 = "[object Int16Array]", int32Tag$2 = "[object Int32Array]", uint8Tag$2 = "[object Uint8Array]", uint8ClampedTag$2 = "[object Uint8ClampedArray]", uint16Tag$2 = "[object Uint16Array]", uint32Tag$2 = "[object Uint32Array]";
var typedArrayTags = {};
typedArrayTags[float32Tag$2] = typedArrayTags[float64Tag$2] = typedArrayTags[int8Tag$2] = typedArrayTags[int16Tag$2] = typedArrayTags[int32Tag$2] = typedArrayTags[uint8Tag$2] = typedArrayTags[uint8ClampedTag$2] = typedArrayTags[uint16Tag$2] = typedArrayTags[uint32Tag$2] = true;
typedArrayTags[argsTag$1] = typedArrayTags[arrayTag$1] = typedArrayTags[arrayBufferTag$2] = typedArrayTags[boolTag$2] = typedArrayTags[dataViewTag$3] = typedArrayTags[dateTag$2] = typedArrayTags[errorTag$1] = typedArrayTags[funcTag$1] = typedArrayTags[mapTag$4] = typedArrayTags[numberTag$2] = typedArrayTags[objectTag$2] = typedArrayTags[regexpTag$2] = typedArrayTags[setTag$4] = typedArrayTags[stringTag$2] = typedArrayTags[weakMapTag$2] = false;
function baseIsTypedArray$1(value) {
  return isObjectLike$3(value) && isLength$1(value.length) && !!typedArrayTags[baseGetTag$1(value)];
}
__name(baseIsTypedArray$1, "baseIsTypedArray$1");
var _baseIsTypedArray = baseIsTypedArray$1;
const _baseIsTypedArray$1 = /* @__PURE__ */ getDefaultExportFromCjs(_baseIsTypedArray);
function baseUnary$3(func) {
  return function(value) {
    return func(value);
  };
}
__name(baseUnary$3, "baseUnary$3");
var _baseUnary = baseUnary$3;
const _baseUnary$1 = /* @__PURE__ */ getDefaultExportFromCjs(_baseUnary);
var _nodeUtil$2 = { exports: {} };
var _nodeUtil = _nodeUtil$2.exports;
(function(module2, exports) {
  var freeGlobal2 = _freeGlobal;
  var freeExports = exports && !exports.nodeType && exports;
  var freeModule = freeExports && true && module2 && !module2.nodeType && module2;
  var moduleExports = freeModule && freeModule.exports === freeExports;
  var freeProcess = moduleExports && freeGlobal2.process;
  var nodeUtil2 = function() {
    try {
      var types = freeModule && freeModule.require && freeModule.require("util").types;
      if (types) {
        return types;
      }
      return freeProcess && freeProcess.binding && freeProcess.binding("util");
    } catch (e2) {
    }
  }();
  module2.exports = nodeUtil2;
})(_nodeUtil$2, _nodeUtil$2.exports);
var _nodeUtilExports = _nodeUtil$2.exports;
const _nodeUtil$1 = /* @__PURE__ */ getDefaultExportFromCjs(_nodeUtilExports);
var baseIsTypedArray = _baseIsTypedArray, baseUnary$2 = _baseUnary, nodeUtil$2 = _nodeUtilExports;
var nodeIsTypedArray = nodeUtil$2 && nodeUtil$2.isTypedArray;
var isTypedArray$1 = nodeIsTypedArray ? baseUnary$2(nodeIsTypedArray) : baseIsTypedArray;
var isTypedArray_1 = isTypedArray$1;
const isTypedArray$2 = /* @__PURE__ */ getDefaultExportFromCjs(isTypedArray_1);
var baseTimes = _baseTimes, isArguments = isArguments_1, isArray$3 = isArray_1, isBuffer$1 = isBufferExports, isIndex = _isIndex, isTypedArray = isTypedArray_1;
var objectProto$5 = Object.prototype;
var hasOwnProperty$3 = objectProto$5.hasOwnProperty;
function arrayLikeKeys$2(value, inherited) {
  var isArr = isArray$3(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer$1(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes(value.length, String) : [], length = result.length;
  for (var key in value) {
    if ((inherited || hasOwnProperty$3.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)))) {
      result.push(key);
    }
  }
  return result;
}
__name(arrayLikeKeys$2, "arrayLikeKeys$2");
var _arrayLikeKeys = arrayLikeKeys$2;
const _arrayLikeKeys$1 = /* @__PURE__ */ getDefaultExportFromCjs(_arrayLikeKeys);
var objectProto$4 = Object.prototype;
function isPrototype$3(value) {
  var Ctor = value && value.constructor, proto = typeof Ctor == "function" && Ctor.prototype || objectProto$4;
  return value === proto;
}
__name(isPrototype$3, "isPrototype$3");
var _isPrototype = isPrototype$3;
const _isPrototype$1 = /* @__PURE__ */ getDefaultExportFromCjs(_isPrototype);
function overArg$2(func, transform) {
  return function(arg) {
    return func(transform(arg));
  };
}
__name(overArg$2, "overArg$2");
var _overArg = overArg$2;
const _overArg$1 = /* @__PURE__ */ getDefaultExportFromCjs(_overArg);
var overArg$1 = _overArg;
var nativeKeys$1 = overArg$1(Object.keys, Object);
var _nativeKeys = nativeKeys$1;
const _nativeKeys$1 = /* @__PURE__ */ getDefaultExportFromCjs(_nativeKeys);
var isPrototype$2 = _isPrototype, nativeKeys = _nativeKeys;
var objectProto$3 = Object.prototype;
var hasOwnProperty$2 = objectProto$3.hasOwnProperty;
function baseKeys$1(object) {
  if (!isPrototype$2(object)) {
    return nativeKeys(object);
  }
  var result = [];
  for (var key in Object(object)) {
    if (hasOwnProperty$2.call(object, key) && key != "constructor") {
      result.push(key);
    }
  }
  return result;
}
__name(baseKeys$1, "baseKeys$1");
var _baseKeys = baseKeys$1;
const _baseKeys$1 = /* @__PURE__ */ getDefaultExportFromCjs(_baseKeys);
var isFunction$2 = isFunction_1, isLength = isLength_1;
function isArrayLike$2(value) {
  return value != null && isLength(value.length) && !isFunction$2(value);
}
__name(isArrayLike$2, "isArrayLike$2");
var isArrayLike_1 = isArrayLike$2;
const isArrayLike$3 = /* @__PURE__ */ getDefaultExportFromCjs(isArrayLike_1);
var arrayLikeKeys$1 = _arrayLikeKeys, baseKeys = _baseKeys, isArrayLike$1 = isArrayLike_1;
function keys$4(object) {
  return isArrayLike$1(object) ? arrayLikeKeys$1(object) : baseKeys(object);
}
__name(keys$4, "keys$4");
var keys_1 = keys$4;
const keys$5 = /* @__PURE__ */ getDefaultExportFromCjs(keys_1);
var copyObject$3 = _copyObject, keys$3 = keys_1;
function baseAssign$1(object, source) {
  return object && copyObject$3(source, keys$3(source), object);
}
__name(baseAssign$1, "baseAssign$1");
var _baseAssign = baseAssign$1;
const _baseAssign$1 = /* @__PURE__ */ getDefaultExportFromCjs(_baseAssign);
function nativeKeysIn$1(object) {
  var result = [];
  if (object != null) {
    for (var key in Object(object)) {
      result.push(key);
    }
  }
  return result;
}
__name(nativeKeysIn$1, "nativeKeysIn$1");
var _nativeKeysIn = nativeKeysIn$1;
const _nativeKeysIn$1 = /* @__PURE__ */ getDefaultExportFromCjs(_nativeKeysIn);
var isObject$4 = isObject_1, isPrototype$1 = _isPrototype, nativeKeysIn = _nativeKeysIn;
var objectProto$2 = Object.prototype;
var hasOwnProperty$1 = objectProto$2.hasOwnProperty;
function baseKeysIn$1(object) {
  if (!isObject$4(object)) {
    return nativeKeysIn(object);
  }
  var isProto = isPrototype$1(object), result = [];
  for (var key in object) {
    if (!(key == "constructor" && (isProto || !hasOwnProperty$1.call(object, key)))) {
      result.push(key);
    }
  }
  return result;
}
__name(baseKeysIn$1, "baseKeysIn$1");
var _baseKeysIn = baseKeysIn$1;
const _baseKeysIn$1 = /* @__PURE__ */ getDefaultExportFromCjs(_baseKeysIn);
var arrayLikeKeys = _arrayLikeKeys, baseKeysIn = _baseKeysIn, isArrayLike = isArrayLike_1;
function keysIn$3(object) {
  return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);
}
__name(keysIn$3, "keysIn$3");
var keysIn_1 = keysIn$3;
const keysIn$4 = /* @__PURE__ */ getDefaultExportFromCjs(keysIn_1);
var copyObject$2 = _copyObject, keysIn$2 = keysIn_1;
function baseAssignIn$1(object, source) {
  return object && copyObject$2(source, keysIn$2(source), object);
}
__name(baseAssignIn$1, "baseAssignIn$1");
var _baseAssignIn = baseAssignIn$1;
const _baseAssignIn$1 = /* @__PURE__ */ getDefaultExportFromCjs(_baseAssignIn);
var _cloneBuffer$2 = { exports: {} };
var _cloneBuffer = _cloneBuffer$2.exports;
(function(module2, exports) {
  var root2 = _root;
  var freeExports = exports && !exports.nodeType && exports;
  var freeModule = freeExports && true && module2 && !module2.nodeType && module2;
  var moduleExports = freeModule && freeModule.exports === freeExports;
  var Buffer2 = moduleExports ? root2.Buffer : void 0, allocUnsafe = Buffer2 ? Buffer2.allocUnsafe : void 0;
  function cloneBuffer2(buffer, isDeep) {
    if (isDeep) {
      return buffer.slice();
    }
    var length = buffer.length, result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
    buffer.copy(result);
    return result;
  }
  __name(cloneBuffer2, "cloneBuffer");
  module2.exports = cloneBuffer2;
})(_cloneBuffer$2, _cloneBuffer$2.exports);
var _cloneBufferExports = _cloneBuffer$2.exports;
const _cloneBuffer$1 = /* @__PURE__ */ getDefaultExportFromCjs(_cloneBufferExports);
function copyArray$1(source, array) {
  var index2 = -1, length = source.length;
  array || (array = Array(length));
  while (++index2 < length) {
    array[index2] = source[index2];
  }
  return array;
}
__name(copyArray$1, "copyArray$1");
var _copyArray = copyArray$1;
const _copyArray$1 = /* @__PURE__ */ getDefaultExportFromCjs(_copyArray);
function arrayFilter$1(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;
}
__name(arrayFilter$1, "arrayFilter$1");
var _arrayFilter = arrayFilter$1;
const _arrayFilter$1 = /* @__PURE__ */ getDefaultExportFromCjs(_arrayFilter);
function stubArray$2() {
  return [];
}
__name(stubArray$2, "stubArray$2");
var stubArray_1 = stubArray$2;
const stubArray$3 = /* @__PURE__ */ getDefaultExportFromCjs(stubArray_1);
var arrayFilter = _arrayFilter, stubArray$1 = stubArray_1;
var objectProto$1 = Object.prototype;
var propertyIsEnumerable = objectProto$1.propertyIsEnumerable;
var nativeGetSymbols$1 = Object.getOwnPropertySymbols;
var getSymbols$3 = !nativeGetSymbols$1 ? stubArray$1 : function(object) {
  if (object == null) {
    return [];
  }
  object = Object(object);
  return arrayFilter(nativeGetSymbols$1(object), function(symbol) {
    return propertyIsEnumerable.call(object, symbol);
  });
};
var _getSymbols = getSymbols$3;
const _getSymbols$1 = /* @__PURE__ */ getDefaultExportFromCjs(_getSymbols);
var copyObject$1 = _copyObject, getSymbols$2 = _getSymbols;
function copySymbols$1(source, object) {
  return copyObject$1(source, getSymbols$2(source), object);
}
__name(copySymbols$1, "copySymbols$1");
var _copySymbols = copySymbols$1;
const _copySymbols$1 = /* @__PURE__ */ getDefaultExportFromCjs(_copySymbols);
function arrayPush$2(array, values) {
  var index2 = -1, length = values.length, offset = array.length;
  while (++index2 < length) {
    array[offset + index2] = values[index2];
  }
  return array;
}
__name(arrayPush$2, "arrayPush$2");
var _arrayPush = arrayPush$2;
const _arrayPush$1 = /* @__PURE__ */ getDefaultExportFromCjs(_arrayPush);
var overArg = _overArg;
var getPrototype$2 = overArg(Object.getPrototypeOf, Object);
var _getPrototype = getPrototype$2;
const _getPrototype$1 = /* @__PURE__ */ getDefaultExportFromCjs(_getPrototype);
var arrayPush$1 = _arrayPush, getPrototype$1 = _getPrototype, getSymbols$1 = _getSymbols, stubArray = stubArray_1;
var nativeGetSymbols = Object.getOwnPropertySymbols;
var getSymbolsIn$2 = !nativeGetSymbols ? stubArray : function(object) {
  var result = [];
  while (object) {
    arrayPush$1(result, getSymbols$1(object));
    object = getPrototype$1(object);
  }
  return result;
};
var _getSymbolsIn = getSymbolsIn$2;
const _getSymbolsIn$1 = /* @__PURE__ */ getDefaultExportFromCjs(_getSymbolsIn);
var copyObject = _copyObject, getSymbolsIn$1 = _getSymbolsIn;
function copySymbolsIn$1(source, object) {
  return copyObject(source, getSymbolsIn$1(source), object);
}
__name(copySymbolsIn$1, "copySymbolsIn$1");
var _copySymbolsIn = copySymbolsIn$1;
const _copySymbolsIn$1 = /* @__PURE__ */ getDefaultExportFromCjs(_copySymbolsIn);
var arrayPush = _arrayPush, isArray$2 = isArray_1;
function baseGetAllKeys$2(object, keysFunc, symbolsFunc) {
  var result = keysFunc(object);
  return isArray$2(object) ? result : arrayPush(result, symbolsFunc(object));
}
__name(baseGetAllKeys$2, "baseGetAllKeys$2");
var _baseGetAllKeys = baseGetAllKeys$2;
const _baseGetAllKeys$1 = /* @__PURE__ */ getDefaultExportFromCjs(_baseGetAllKeys);
var baseGetAllKeys$1 = _baseGetAllKeys, getSymbols = _getSymbols, keys$2 = keys_1;
function getAllKeys$1(object) {
  return baseGetAllKeys$1(object, keys$2, getSymbols);
}
__name(getAllKeys$1, "getAllKeys$1");
var _getAllKeys = getAllKeys$1;
const _getAllKeys$1 = /* @__PURE__ */ getDefaultExportFromCjs(_getAllKeys);
var baseGetAllKeys = _baseGetAllKeys, getSymbolsIn = _getSymbolsIn, keysIn$1 = keysIn_1;
function getAllKeysIn$1(object) {
  return baseGetAllKeys(object, keysIn$1, getSymbolsIn);
}
__name(getAllKeysIn$1, "getAllKeysIn$1");
var _getAllKeysIn = getAllKeysIn$1;
const _getAllKeysIn$1 = /* @__PURE__ */ getDefaultExportFromCjs(_getAllKeysIn);
var getNative$3 = _getNative, root$4 = _root;
var DataView$2 = getNative$3(root$4, "DataView");
var _DataView = DataView$2;
const _DataView$1 = /* @__PURE__ */ getDefaultExportFromCjs(_DataView);
var getNative$2 = _getNative, root$3 = _root;
var Promise$2 = getNative$2(root$3, "Promise");
var _Promise = Promise$2;
const _Promise$1 = /* @__PURE__ */ getDefaultExportFromCjs(_Promise);
var getNative$1 = _getNative, root$2 = _root;
var Set$2 = getNative$1(root$2, "Set");
var _Set = Set$2;
const _Set$1 = /* @__PURE__ */ getDefaultExportFromCjs(_Set);
var getNative = _getNative, root$1 = _root;
var WeakMap$2 = getNative(root$1, "WeakMap");
var _WeakMap = WeakMap$2;
const _WeakMap$1 = /* @__PURE__ */ getDefaultExportFromCjs(_WeakMap);
var DataView$1 = _DataView, Map$1 = _Map, Promise$1 = _Promise, Set$1 = _Set, WeakMap$1 = _WeakMap, baseGetTag = _baseGetTag, toSource = _toSource;
var mapTag$3 = "[object Map]", objectTag$1 = "[object Object]", promiseTag = "[object Promise]", setTag$3 = "[object Set]", weakMapTag$1 = "[object WeakMap]";
var dataViewTag$2 = "[object DataView]";
var dataViewCtorString = toSource(DataView$1), mapCtorString = toSource(Map$1), promiseCtorString = toSource(Promise$1), setCtorString = toSource(Set$1), weakMapCtorString = toSource(WeakMap$1);
var getTag$4 = baseGetTag;
if (DataView$1 && getTag$4(new DataView$1(new ArrayBuffer(1))) != dataViewTag$2 || Map$1 && getTag$4(new Map$1()) != mapTag$3 || Promise$1 && getTag$4(Promise$1.resolve()) != promiseTag || Set$1 && getTag$4(new Set$1()) != setTag$3 || WeakMap$1 && getTag$4(new WeakMap$1()) != weakMapTag$1) {
  getTag$4 = /* @__PURE__ */ __name(function(value) {
    var result = baseGetTag(value), Ctor = result == objectTag$1 ? value.constructor : void 0, ctorString = Ctor ? toSource(Ctor) : "";
    if (ctorString) {
      switch (ctorString) {
        case dataViewCtorString:
          return dataViewTag$2;
        case mapCtorString:
          return mapTag$3;
        case promiseCtorString:
          return promiseTag;
        case setCtorString:
          return setTag$3;
        case weakMapCtorString:
          return weakMapTag$1;
      }
    }
    return result;
  }, "getTag$4");
}
var _getTag = getTag$4;
const _getTag$1 = /* @__PURE__ */ getDefaultExportFromCjs(_getTag);
var objectProto = Object.prototype;
var hasOwnProperty = objectProto.hasOwnProperty;
function initCloneArray$1(array) {
  var length = array.length, result = new array.constructor(length);
  if (length && typeof array[0] == "string" && hasOwnProperty.call(array, "index")) {
    result.index = array.index;
    result.input = array.input;
  }
  return result;
}
__name(initCloneArray$1, "initCloneArray$1");
var _initCloneArray = initCloneArray$1;
const _initCloneArray$1 = /* @__PURE__ */ getDefaultExportFromCjs(_initCloneArray);
var root = _root;
var Uint8Array$2 = root.Uint8Array;
var _Uint8Array = Uint8Array$2;
const _Uint8Array$1 = /* @__PURE__ */ getDefaultExportFromCjs(_Uint8Array);
var Uint8Array$1 = _Uint8Array;
function cloneArrayBuffer$3(arrayBuffer) {
  var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
  new Uint8Array$1(result).set(new Uint8Array$1(arrayBuffer));
  return result;
}
__name(cloneArrayBuffer$3, "cloneArrayBuffer$3");
var _cloneArrayBuffer = cloneArrayBuffer$3;
const _cloneArrayBuffer$1 = /* @__PURE__ */ getDefaultExportFromCjs(_cloneArrayBuffer);
var cloneArrayBuffer$2 = _cloneArrayBuffer;
function cloneDataView$1(dataView, isDeep) {
  var buffer = isDeep ? cloneArrayBuffer$2(dataView.buffer) : dataView.buffer;
  return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
}
__name(cloneDataView$1, "cloneDataView$1");
var _cloneDataView = cloneDataView$1;
const _cloneDataView$1 = /* @__PURE__ */ getDefaultExportFromCjs(_cloneDataView);
var reFlags = /\w*$/;
function cloneRegExp$2(regexp2) {
  var result = new regexp2.constructor(regexp2.source, reFlags.exec(regexp2));
  result.lastIndex = regexp2.lastIndex;
  return result;
}
__name(cloneRegExp$2, "cloneRegExp$2");
var _cloneRegExp = cloneRegExp$2;
const _cloneRegExp$1 = /* @__PURE__ */ getDefaultExportFromCjs(_cloneRegExp);
var Symbol$1 = _Symbol;
var symbolProto = Symbol$1 ? Symbol$1.prototype : void 0, symbolValueOf = symbolProto ? symbolProto.valueOf : void 0;
function cloneSymbol$1(symbol) {
  return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
}
__name(cloneSymbol$1, "cloneSymbol$1");
var _cloneSymbol = cloneSymbol$1;
const _cloneSymbol$1 = /* @__PURE__ */ getDefaultExportFromCjs(_cloneSymbol);
var cloneArrayBuffer$1 = _cloneArrayBuffer;
function cloneTypedArray$1(typedArray, isDeep) {
  var buffer = isDeep ? cloneArrayBuffer$1(typedArray.buffer) : typedArray.buffer;
  return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
}
__name(cloneTypedArray$1, "cloneTypedArray$1");
var _cloneTypedArray = cloneTypedArray$1;
const _cloneTypedArray$1 = /* @__PURE__ */ getDefaultExportFromCjs(_cloneTypedArray);
var cloneArrayBuffer = _cloneArrayBuffer, cloneDataView = _cloneDataView, cloneRegExp$1 = _cloneRegExp, cloneSymbol = _cloneSymbol, cloneTypedArray = _cloneTypedArray;
var boolTag$1 = "[object Boolean]", dateTag$1 = "[object Date]", mapTag$2 = "[object Map]", numberTag$1 = "[object Number]", regexpTag$1 = "[object RegExp]", setTag$2 = "[object Set]", stringTag$1 = "[object String]", symbolTag$1 = "[object Symbol]";
var arrayBufferTag$1 = "[object ArrayBuffer]", dataViewTag$1 = "[object DataView]", float32Tag$1 = "[object Float32Array]", float64Tag$1 = "[object Float64Array]", int8Tag$1 = "[object Int8Array]", int16Tag$1 = "[object Int16Array]", int32Tag$1 = "[object Int32Array]", uint8Tag$1 = "[object Uint8Array]", uint8ClampedTag$1 = "[object Uint8ClampedArray]", uint16Tag$1 = "[object Uint16Array]", uint32Tag$1 = "[object Uint32Array]";
function initCloneByTag$1(object, tag, isDeep) {
  var Ctor = object.constructor;
  switch (tag) {
    case arrayBufferTag$1:
      return cloneArrayBuffer(object);
    case boolTag$1:
    case dateTag$1:
      return new Ctor(+object);
    case dataViewTag$1:
      return cloneDataView(object, isDeep);
    case float32Tag$1:
    case float64Tag$1:
    case int8Tag$1:
    case int16Tag$1:
    case int32Tag$1:
    case uint8Tag$1:
    case uint8ClampedTag$1:
    case uint16Tag$1:
    case uint32Tag$1:
      return cloneTypedArray(object, isDeep);
    case mapTag$2:
      return new Ctor();
    case numberTag$1:
    case stringTag$1:
      return new Ctor(object);
    case regexpTag$1:
      return cloneRegExp$1(object);
    case setTag$2:
      return new Ctor();
    case symbolTag$1:
      return cloneSymbol(object);
  }
}
__name(initCloneByTag$1, "initCloneByTag$1");
var _initCloneByTag = initCloneByTag$1;
const _initCloneByTag$1 = /* @__PURE__ */ getDefaultExportFromCjs(_initCloneByTag);
var isObject$3 = isObject_1;
var objectCreate = Object.create;
var baseCreate$1 = /* @__PURE__ */ function() {
  function object() {
  }
  __name(object, "object");
  return function(proto) {
    if (!isObject$3(proto)) {
      return {};
    }
    if (objectCreate) {
      return objectCreate(proto);
    }
    object.prototype = proto;
    var result = new object();
    object.prototype = void 0;
    return result;
  };
}();
var _baseCreate = baseCreate$1;
const _baseCreate$1 = /* @__PURE__ */ getDefaultExportFromCjs(_baseCreate);
var baseCreate = _baseCreate, getPrototype = _getPrototype, isPrototype = _isPrototype;
function initCloneObject$1(object) {
  return typeof object.constructor == "function" && !isPrototype(object) ? baseCreate(getPrototype(object)) : {};
}
__name(initCloneObject$1, "initCloneObject$1");
var _initCloneObject = initCloneObject$1;
const _initCloneObject$1 = /* @__PURE__ */ getDefaultExportFromCjs(_initCloneObject);
var getTag$3 = _getTag, isObjectLike$2 = isObjectLike_1;
var mapTag$1 = "[object Map]";
function baseIsMap$1(value) {
  return isObjectLike$2(value) && getTag$3(value) == mapTag$1;
}
__name(baseIsMap$1, "baseIsMap$1");
var _baseIsMap = baseIsMap$1;
const _baseIsMap$1 = /* @__PURE__ */ getDefaultExportFromCjs(_baseIsMap);
var baseIsMap = _baseIsMap, baseUnary$1 = _baseUnary, nodeUtil$1 = _nodeUtilExports;
var nodeIsMap = nodeUtil$1 && nodeUtil$1.isMap;
var isMap$1 = nodeIsMap ? baseUnary$1(nodeIsMap) : baseIsMap;
var isMap_1 = isMap$1;
const isMap$2 = /* @__PURE__ */ getDefaultExportFromCjs(isMap_1);
var getTag$2 = _getTag, isObjectLike$1 = isObjectLike_1;
var setTag$1 = "[object Set]";
function baseIsSet$1(value) {
  return isObjectLike$1(value) && getTag$2(value) == setTag$1;
}
__name(baseIsSet$1, "baseIsSet$1");
var _baseIsSet = baseIsSet$1;
const _baseIsSet$1 = /* @__PURE__ */ getDefaultExportFromCjs(_baseIsSet);
var baseIsSet = _baseIsSet, baseUnary = _baseUnary, nodeUtil = _nodeUtilExports;
var nodeIsSet = nodeUtil && nodeUtil.isSet;
var isSet$1 = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet;
var isSet_1 = isSet$1;
const isSet$2 = /* @__PURE__ */ getDefaultExportFromCjs(isSet_1);
var Stack = _Stack, arrayEach = _arrayEach, assignValue = _assignValue, baseAssign = _baseAssign, baseAssignIn = _baseAssignIn, cloneBuffer = _cloneBufferExports, copyArray = _copyArray, copySymbols = _copySymbols, copySymbolsIn = _copySymbolsIn, getAllKeys = _getAllKeys, getAllKeysIn = _getAllKeysIn, getTag$1 = _getTag, initCloneArray = _initCloneArray, initCloneByTag = _initCloneByTag, initCloneObject = _initCloneObject, isArray$1 = isArray_1, isBuffer = isBufferExports, isMap = isMap_1, isObject$2 = isObject_1, isSet = isSet_1, keys$1 = keys_1, keysIn = keysIn_1;
var CLONE_DEEP_FLAG$1 = 1, CLONE_FLAT_FLAG = 2, CLONE_SYMBOLS_FLAG$1 = 4;
var argsTag = "[object Arguments]", arrayTag = "[object Array]", boolTag = "[object Boolean]", dateTag = "[object Date]", errorTag = "[object Error]", funcTag = "[object Function]", genTag = "[object GeneratorFunction]", mapTag = "[object Map]", numberTag = "[object Number]", objectTag = "[object Object]", regexpTag = "[object RegExp]", setTag = "[object Set]", stringTag = "[object String]", symbolTag = "[object Symbol]", weakMapTag = "[object WeakMap]";
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 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;
function baseClone$1(value, bitmask, customizer, key, object, stack) {
  var result, isDeep = bitmask & CLONE_DEEP_FLAG$1, isFlat = bitmask & CLONE_FLAT_FLAG, isFull = bitmask & CLONE_SYMBOLS_FLAG$1;
  if (customizer) {
    result = object ? customizer(value, key, object, stack) : customizer(value);
  }
  if (result !== void 0) {
    return result;
  }
  if (!isObject$2(value)) {
    return value;
  }
  var isArr = isArray$1(value);
  if (isArr) {
    result = initCloneArray(value);
    if (!isDeep) {
      return copyArray(value, result);
    }
  } else {
    var tag = getTag$1(value), isFunc = tag == funcTag || tag == genTag;
    if (isBuffer(value)) {
      return cloneBuffer(value, isDeep);
    }
    if (tag == objectTag || tag == argsTag || isFunc && !object) {
      result = isFlat || isFunc ? {} : initCloneObject(value);
      if (!isDeep) {
        return isFlat ? copySymbolsIn(value, baseAssignIn(result, value)) : copySymbols(value, baseAssign(result, value));
      }
    } else {
      if (!cloneableTags[tag]) {
        return object ? value : {};
      }
      result = initCloneByTag(value, tag, isDeep);
    }
  }
  stack || (stack = new Stack());
  var stacked = stack.get(value);
  if (stacked) {
    return stacked;
  }
  stack.set(value, result);
  if (isSet(value)) {
    value.forEach(function(subValue) {
      result.add(baseClone$1(subValue, bitmask, customizer, subValue, value, stack));
    });
  } else if (isMap(value)) {
    value.forEach(function(subValue, key2) {
      result.set(key2, baseClone$1(subValue, bitmask, customizer, key2, value, stack));
    });
  }
  var keysFunc = isFull ? isFlat ? getAllKeysIn : getAllKeys : isFlat ? keysIn : keys$1;
  var props = isArr ? void 0 : keysFunc(value);
  arrayEach(props || value, function(subValue, key2) {
    if (props) {
      key2 = subValue;
      subValue = value[key2];
    }
    assignValue(result, key2, baseClone$1(subValue, bitmask, customizer, key2, value, stack));
  });
  return result;
}
__name(baseClone$1, "baseClone$1");
var _baseClone = baseClone$1;
const _baseClone$1 = /* @__PURE__ */ getDefaultExportFromCjs(_baseClone);
var baseClone = _baseClone;
var CLONE_DEEP_FLAG = 1, CLONE_SYMBOLS_FLAG = 4;
function cloneDeep(value) {
  return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG);
}
__name(cloneDeep, "cloneDeep");
var cloneDeep_1 = cloneDeep;
const cloneDeep$1 = /* @__PURE__ */ getDefaultExportFromCjs(cloneDeep_1);
const checkboxField = z.boolean().optional();
const issueReportSchema = z.object({
  contactInfo: z.string().email().max(320).optional().or(z.literal("")),
  details: z.string().max(5e3).optional(),
  helpType: z.string().optional()
}).catchall(checkboxField).refine((data) => Object.values(data).some((value) => value), {
  path: ["details", "helpType"]
}).refine((data) => data.helpType !== void 0 && data.helpType !== "", {
  message: "Help type is required",
  path: ["helpType"]
});
function formatCamelCase(str) {
  const isCamelCase = /^([A-Z][a-z]*)+$/.test(str);
  if (!isCamelCase) {
    return str;
  }
  const words = str.split(/(?=[A-Z][a-z])|\d+/);
  const processedWords = words.map((word) => {
    if (word.length > 1 && word === word.toUpperCase()) {
      return word;
    }
    return word.charAt(0).toUpperCase() + word.slice(1);
  });
  return processedWords.join(" ");
}
__name(formatCamelCase, "formatCamelCase");
function appendJsonExt(path) {
  if (!path.toLowerCase().endsWith(".json")) {
    path += ".json";
  }
  return path;
}
__name(appendJsonExt, "appendJsonExt");
function trimJsonExt(path) {
  return path?.replace(/\.json$/, "");
}
__name(trimJsonExt, "trimJsonExt");
function highlightQuery(text2, query2) {
  if (!query2) return text2;
  const regex2 = new RegExp(`(${query2})`, "gi");
  return text2.replace(regex2, '<span class="highlight">$1</span>');
}
__name(highlightQuery, "highlightQuery");
function formatNumberWithSuffix(num, {
  precision = 1,
  roundToInt = false
} = {}) {
  const suffixes = ["", "k", "m", "b", "t"];
  const absNum = Math.abs(num);
  if (absNum < 1e3) {
    return roundToInt ? Math.round(num).toString() : num.toFixed(precision);
  }
  const exp = Math.min(Math.floor(Math.log10(absNum) / 3), suffixes.length - 1);
  const formattedNum = (num / Math.pow(1e3, exp)).toFixed(precision);
  return `${formattedNum}${suffixes[exp]}`;
}
__name(formatNumberWithSuffix, "formatNumberWithSuffix");
function formatSize(value) {
  if (value === null || value === void 0) {
    return "-";
  }
  const bytes = value;
  if (bytes === 0) return "0 B";
  const k2 = 1024;
  const sizes = ["B", "KB", "MB", "GB"];
  const i2 = Math.floor(Math.log(bytes) / Math.log(k2));
  return `${parseFloat((bytes / Math.pow(k2, i2)).toFixed(2))} ${sizes[i2]}`;
}
__name(formatSize, "formatSize");
function findCommonPrefix(path1, path2) {
  const parts1 = path1.split("/");
  const parts2 = path2.split("/");
  const commonParts = [];
  for (let i2 = 0; i2 < Math.min(parts1.length, parts2.length); i2++) {
    if (parts1[i2] === parts2[i2]) {
      commonParts.push(parts1[i2]);
    } else {
      break;
    }
  }
  return commonParts.join("/");
}
__name(findCommonPrefix, "findCommonPrefix");
function getFilenameDetails(fullFilename) {
  if (fullFilename.includes(".")) {
    return {
      filename: fullFilename.split(".").slice(0, -1).join("."),
      suffix: fullFilename.split(".").pop() ?? null
    };
  } else {
    return { filename: fullFilename, suffix: null };
  }
}
__name(getFilenameDetails, "getFilenameDetails");
function getPathDetails(path) {
  const directory = path.split("/").slice(0, -1).join("/");
  const fullFilename = path.split("/").pop() ?? path;
  return { directory, fullFilename, ...getFilenameDetails(fullFilename) };
}
__name(getPathDetails, "getPathDetails");
function normalizeI18nKey(key) {
  return typeof key === "string" ? key.replace(/\./g, "_") : "";
}
__name(normalizeI18nKey, "normalizeI18nKey");
function processDynamicPrompt(input) {
  function stripComments(str) {
    return str.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g, "");
  }
  __name(stripComments, "stripComments");
  let i2 = 0;
  let result = "";
  input = stripComments(input);
  const handleEscape = /* @__PURE__ */ __name(() => {
    const nextChar = input[i2++];
    return "\\" + nextChar;
  }, "handleEscape");
  function parseChoiceBlock() {
    const options2 = [];
    let choice = "";
    let depth = 0;
    while (i2 < input.length) {
      const char = input[i2++];
      if (char === "\\") {
        choice += handleEscape();
        continue;
      } else if (char === "{") {
        depth++;
      } else if (char === "}") {
        if (!depth) break;
        depth--;
      } else if (char === "|") {
        if (!depth) {
          options2.push(choice);
          choice = "";
          continue;
        }
      }
      choice += char;
    }
    options2.push(choice);
    const chosenOption = options2[Math.floor(Math.random() * options2.length)];
    return processDynamicPrompt(chosenOption);
  }
  __name(parseChoiceBlock, "parseChoiceBlock");
  while (i2 < input.length) {
    const char = input[i2++];
    if (char === "\\") {
      result += handleEscape();
    } else if (char === "{") {
      result += parseChoiceBlock();
    } else {
      result += char;
    }
  }
  return result.replace(/\\([{}|])/g, "$1");
}
__name(processDynamicPrompt, "processDynamicPrompt");
function isValidUrl(url) {
  try {
    new URL(url);
    return true;
  } catch {
    return false;
  }
}
__name(isValidUrl, "isValidUrl");
const hasAnnotation = /* @__PURE__ */ __name((filepath) => /\[(input|output|temp)\]/i.test(filepath), "hasAnnotation");
const createAnnotation = /* @__PURE__ */ __name((filepath, rootFolder = "input") => !hasAnnotation(filepath) && rootFolder !== "input" ? ` [${rootFolder}]` : "", "createAnnotation");
const createPath = /* @__PURE__ */ __name((filename, subfolder = "") => subfolder ? `${subfolder}/${filename}` : filename, "createPath");
function createAnnotatedPath(item, options2 = {}) {
  const { rootFolder = "input", subfolder } = options2;
  if (typeof item === "string")
    return `${createPath(item, subfolder)}${createAnnotation(item, rootFolder)}`;
  return `${createPath(item.filename ?? "", item.subfolder)}${item.type ? createAnnotation(item.type, rootFolder) : ""}`;
}
__name(createAnnotatedPath, "createAnnotatedPath");
function parseFilePath(filepath) {
  if (!filepath?.trim()) return { filename: "", subfolder: "" };
  const normalizedPath = filepath.replace(/[\\/]+/g, "/").replace(/^\//, "").replace(/\/$/, "");
  const lastSlashIndex = normalizedPath.lastIndexOf("/");
  if (lastSlashIndex === -1) {
    return {
      filename: normalizedPath,
      subfolder: ""
    };
  }
  return {
    filename: normalizedPath.slice(lastSlashIndex + 1),
    subfolder: normalizedPath.slice(0, lastSlashIndex)
  };
}
__name(parseFilePath, "parseFilePath");
const parts = {
  d: /* @__PURE__ */ __name((d2) => d2.getDate(), "d"),
  M: /* @__PURE__ */ __name((d2) => d2.getMonth() + 1, "M"),
  h: /* @__PURE__ */ __name((d2) => d2.getHours(), "h"),
  m: /* @__PURE__ */ __name((d2) => d2.getMinutes(), "m"),
  s: /* @__PURE__ */ __name((d2) => d2.getSeconds(), "s")
};
const format$2 = Object.keys(parts).map((k2) => k2 + k2 + "?").join("|") + "|yyy?y?";
function formatDate(text2, date) {
  return text2.replace(new RegExp(format$2, "g"), (text22) => {
    if (text22 === "yy") return (date.getFullYear() + "").substring(2);
    if (text22 === "yyyy") return date.getFullYear().toString();
    if (text22[0] in parts) {
      const p2 = parts[text22[0]](date);
      return (p2 + "").padStart(text22.length, "0");
    }
    return text22;
  });
}
__name(formatDate, "formatDate");
const paramsToCacheKey = /* @__PURE__ */ __name((params) => {
  if (typeof params === "string") return params;
  if (typeof params === "object" && params !== null)
    return Object.keys(params).sort((a2, b2) => a2.localeCompare(b2)).map((key) => `${key}:${params[key]}`).join("&");
  return String(params);
}, "paramsToCacheKey");
const generateUUID = /* @__PURE__ */ __name(() => {
  if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
    return crypto.randomUUID();
  }
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c2) => {
    const r2 = Math.random() * 16 | 0;
    const v2 = c2 === "x" ? r2 : r2 & 3 | 8;
    return v2.toString(16);
  });
}, "generateUUID");
const isCivitaiModelUrl = /* @__PURE__ */ __name((url) => {
  if (!isValidUrl(url)) return false;
  if (!url.includes("civitai.com")) return false;
  const urlObj = new URL(url);
  const pathname = urlObj.pathname;
  return /^\/api\/download\/models\/(\d+)$/.test(pathname) || /^\/api\/v1\/models\/(\d+)$/.test(pathname) || /^\/api\/v1\/models-versions\/(\d+)$/.test(pathname);
}, "isCivitaiModelUrl");
const downloadUrlToHfRepoUrl = /* @__PURE__ */ __name((url) => {
  try {
    const urlObj = new URL(url);
    const pathname = urlObj.pathname;
    const regex2 = /^(.*?)(?:\/resolve\/|\/blob\/|$)/;
    const repoPathMatch = regex2.exec(pathname);
    const repoPath = repoPathMatch?.[1]?.replace(/^\//, "") || "";
    return `https://huggingface.co/${repoPath}`;
  } catch (error2) {
    return url;
  }
}, "downloadUrlToHfRepoUrl");
const isSemVer = /* @__PURE__ */ __name((version2) => {
  const regex2 = /^(\d+)\.(\d+)\.(\d+)$/;
  return regex2.test(version2);
}, "isSemVer");
const normalizeVersion = /* @__PURE__ */ __name((version2) => version2.split(/[+.-]/).map(Number).filter((part) => !Number.isNaN(part)), "normalizeVersion");
function compareVersions(versionA, versionB) {
  versionA ??= "0.0.0";
  versionB ??= "0.0.0";
  const aParts = normalizeVersion(versionA);
  const bParts = normalizeVersion(versionB);
  for (let i2 = 0; i2 < Math.max(aParts.length, bParts.length); i2++) {
    const aPart = aParts[i2] ?? 0;
    const bPart = bParts[i2] ?? 0;
    if (aPart < bPart) return -1;
    if (aPart > bPart) return 1;
  }
  return 0;
}
__name(compareVersions, "compareVersions");
function toMetronomeCurrency(amount, currency) {
  if (currency === "usd") {
    return Math.round(amount * 100);
  }
  return amount;
}
__name(toMetronomeCurrency, "toMetronomeCurrency");
function formatMetronomeCurrency(amount, currency) {
  if (currency === "usd") {
    return (amount / 100).toFixed(2);
  }
  return amount.toString();
}
__name(formatMetronomeCurrency, "formatMetronomeCurrency");
function usdToMicros(usd) {
  return Math.round(usd * 1e6);
}
__name(usdToMicros, "usdToMicros");
function linkifyHtml(text2) {
  if (!text2) return "";
  const urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%?=~_|])|(\bwww\.[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%?=~_|])/gi;
  return text2.replace(urlRegex, (_match, p1, _p2, p3) => {
    const url = p1 || p3;
    const href = p3 ? `http://${url}` : url;
    return `<a href="${href}" target="_blank" rel="noopener noreferrer" class="text-primary-400 hover:underline">${url}</a>`;
  });
}
__name(linkifyHtml, "linkifyHtml");
function nl2br(text2) {
  if (!text2) return "";
  return text2.replace(/\n/g, "<br />");
}
__name(nl2br, "nl2br");
const _hoisted_1$1p = { class: "flex items-center gap-2" };
const _hoisted_2$11 = { class: "font-bold" };
const _hoisted_3$L = { class: "flex justify-end gap-4" };
const _hoisted_4$y = { class: "p-4 mt-2 border border-round surface-border shadow-1" };
const _hoisted_5$q = { class: "flex flex-col gap-6" };
const _hoisted_6$j = { class: "self-stretch inline-flex justify-start items-center" };
const _hoisted_7$d = {
  for: "contactInfo",
  class: "pb-2 pt-0 opacity-80"
};
const _hoisted_8$a = { class: "flex flex-col gap-2" };
const _hoisted_9$8 = { class: "self-stretch inline-flex justify-start items-center gap-2.5" };
const _hoisted_10$7 = {
  for: "helpType",
  class: "pb-2 pt-0 opacity-80"
};
const _hoisted_11$6 = { class: "flex flex-col gap-2" };
const _hoisted_12$4 = { class: "self-stretch inline-flex justify-start items-center gap-2.5" };
const _hoisted_13$2 = { class: "pb-2 pt-0 opacity-80" };
const _hoisted_14 = { class: "flex flex-row gap-3" };
const _hoisted_15 = ["for"];
const _hoisted_16 = { class: "flex flex-col gap-2" };
const _hoisted_17 = { class: "self-stretch inline-flex justify-start items-center gap-2.5" };
const _hoisted_18 = {
  for: "details",
  class: "pb-2 pt-0 opacity-80"
};
const _hoisted_19 = { class: "flex flex-col gap-3 mt-2" };
const _hoisted_20 = ["for"];
const DEFAULT_ISSUE_NAME = "User reported issue";
const _sfc_main$1L = /* @__PURE__ */ defineComponent({
  __name: "ReportIssuePanel",
  props: {
    errorType: {},
    defaultFields: {},
    extraFields: {},
    tags: {},
    title: {}
  },
  setup(__props) {
    const props = __props;
    const { defaultFields = ["Workflow", "Logs", "SystemStats", "Settings"] } = props;
    const { t: t2 } = useI18n();
    const toast = useToast();
    const authStore = useFirebaseAuthStore();
    const selection = ref$3([]);
    const contactPrefs = ref$3([]);
    const submitted = ref$3(false);
    const contactCheckboxes = [
      { label: t2("issueReport.contactFollowUp"), value: "followUp" },
      { label: t2("issueReport.notifyResolve"), value: "notifyOnResolution" }
    ];
    const helpTypes = [
      {
        label: t2("issueReport.helpTypes.billingPayments"),
        value: "billingPayments"
      },
      {
        label: t2("issueReport.helpTypes.loginAccessIssues"),
        value: "loginAccessIssues"
      },
      { label: t2("issueReport.helpTypes.giveFeedback"), value: "giveFeedback" },
      { label: t2("issueReport.helpTypes.bugReport"), value: "bugReport" },
      { label: t2("issueReport.helpTypes.somethingElse"), value: "somethingElse" }
    ];
    const defaultFieldsConfig = [
      {
        label: t2("issueReport.systemStats"),
        value: "SystemStats",
        getData: /* @__PURE__ */ __name(() => api.getSystemStats(), "getData"),
        optIn: true
      },
      {
        label: t2("g.workflow"),
        value: "Workflow",
        getData: /* @__PURE__ */ __name(() => cloneDeep$1(app$1.graph.asSerialisable()), "getData"),
        optIn: true
      },
      {
        label: t2("g.logs"),
        value: "Logs",
        getData: /* @__PURE__ */ __name(() => api.getLogs(), "getData"),
        optIn: true
      },
      {
        label: t2("g.settings"),
        value: "Settings",
        getData: /* @__PURE__ */ __name(() => api.getSettings(), "getData"),
        optIn: true
      }
    ];
    const fields = computed(() => [
      ...defaultFieldsConfig.filter(
        ({ value }) => defaultFields.includes(value)
      ),
      ...props.extraFields ?? []
    ]);
    const createUser = /* @__PURE__ */ __name((formData) => ({
      email: formData.contactInfo || void 0
    }), "createUser");
    const createExtraData = /* @__PURE__ */ __name(async (formData) => {
      const result = {};
      const isChecked = /* @__PURE__ */ __name((fieldValue) => formData[fieldValue], "isChecked");
      await Promise.all(
        fields.value.filter((field2) => !field2.optIn || isChecked(field2.value)).map(async (field2) => {
          try {
            result[field2.value] = await field2.getData();
          } catch (error2) {
            console.error(`Failed to collect ${field2.value}:`, error2);
            result[field2.value] = { error: String(error2) };
          }
        })
      );
      return result;
    }, "createExtraData");
    const createCaptureContext = /* @__PURE__ */ __name(async (formData) => {
      return {
        user: createUser(formData),
        level: "error",
        tags: {
          errorType: props.errorType,
          helpType: formData.helpType,
          followUp: formData.contactInfo ? formData.followUp : false,
          notifyOnResolution: formData.contactInfo ? formData.notifyOnResolution : false,
          isElectron: isElectron(),
          ..._.mapValues(props.tags, (tag) => _.trim(tag).replace(/[\n\r\t]/g, " "))
        },
        extra: {
          details: formData.details,
          ...await createExtraData(formData)
        }
      };
    }, "createCaptureContext");
    const generateUniqueTicketId = /* @__PURE__ */ __name((type) => `${type}-${generateUUID()}`, "generateUniqueTicketId");
    const submit = /* @__PURE__ */ __name(async (event) => {
      if (event.valid) {
        try {
          const captureContext = await createCaptureContext(event.values);
          const isValidContactInfo = event.values.contactInfo?.length;
          const isCustomerServiceIssue = isValidContactInfo && ["billingPayments", "loginAccessIssues"].includes(
            event.values.helpType || ""
          );
          const issueName = isCustomerServiceIssue ? `ticket-${generateUniqueTicketId(event.values.helpType || "")}` : DEFAULT_ISSUE_NAME;
          captureMessage(issueName, captureContext);
          submitted.value = true;
          toast.add({
            severity: "success",
            summary: t2("g.reportSent"),
            life: 3e3
          });
        } catch (error2) {
          toast.add({
            severity: "error",
            summary: t2("g.error"),
            detail: error2 instanceof Error ? error2.message : String(error2),
            life: 3e3
          });
        }
      }
    }, "submit");
    return (_ctx, _cache) => {
      const _directive_tooltip = resolveDirective("tooltip");
      return openBlock(), createBlock(unref(script$2), {
        resolver: unref(zodResolver)(unref(issueReportSchema)),
        onSubmit: submit
      }, {
        default: withCtx(($form) => [
          createVNode(unref(script$a), {
            pt: _ctx.$attrs.pt
          }, {
            header: withCtx(() => [
              createBaseVNode("div", _hoisted_1$1p, [
                createBaseVNode("span", _hoisted_2$11, toDisplayString(_ctx.title), 1)
              ])
            ]),
            footer: withCtx(() => [
              createBaseVNode("div", _hoisted_3$L, [
                withDirectives(createVNode(unref(script$6), {
                  label: submitted.value ? _ctx.$t("g.reportSent") : _ctx.$t("g.reportIssue"),
                  severity: submitted.value ? "secondary" : "primary",
                  icon: submitted.value ? "pi pi-check" : "pi pi-send",
                  disabled: submitted.value,
                  type: "submit"
                }, null, 8, ["label", "severity", "icon", "disabled"]), [
                  [_directive_tooltip, !submitted.value ? _ctx.$t("g.reportIssueTooltip") : void 0]
                ])
              ])
            ]),
            default: withCtx(() => [
              createBaseVNode("div", _hoisted_4$y, [
                createBaseVNode("div", _hoisted_5$q, [
                  createVNode(unref(script), {
                    name: "contactInfo",
                    "initial-value": unref(authStore).currentUser?.email
                  }, {
                    default: withCtx(($field) => [
                      createBaseVNode("div", _hoisted_6$j, [
                        createBaseVNode("label", _hoisted_7$d, toDisplayString(_ctx.$t("issueReport.email")), 1)
                      ]),
                      createVNode(unref(script$b), mergeProps$1({ id: "contactInfo" }, $field, {
                        class: "w-full",
                        placeholder: _ctx.$t("issueReport.provideEmail")
                      }), null, 16, ["placeholder"]),
                      $field?.error && $field.touched && $field.value !== "" ? (openBlock(), createBlock(unref(script$8), {
                        key: 0,
                        severity: "error",
                        size: "small",
                        variant: "simple"
                      }, {
                        default: withCtx(() => [
                          createTextVNode(toDisplayString(unref(t2)("issueReport.validation.invalidEmail")), 1)
                        ]),
                        _: 1
                      })) : createCommentVNode("", true)
                    ]),
                    _: 1
                  }, 8, ["initial-value"]),
                  createVNode(unref(script), { name: "helpType" }, {
                    default: withCtx(($field) => [
                      createBaseVNode("div", _hoisted_8$a, [
                        createBaseVNode("div", _hoisted_9$8, [
                          createBaseVNode("label", _hoisted_10$7, toDisplayString(_ctx.$t("issueReport.whatDoYouNeedHelpWith")), 1)
                        ]),
                        createVNode(unref(script$c), mergeProps$1($field, {
                          modelValue: $field.value,
                          "onUpdate:modelValue": /* @__PURE__ */ __name(($event) => $field.value = $event, "onUpdate:modelValue"),
                          options: helpTypes,
                          "option-label": "label",
                          "option-value": "value",
                          placeholder: _ctx.$t("issueReport.selectIssue"),
                          class: "w-full"
                        }), null, 16, ["modelValue", "onUpdate:modelValue", "placeholder"]),
                        $field?.error ? (openBlock(), createBlock(unref(script$8), {
                          key: 0,
                          severity: "error",
                          size: "small",
                          variant: "simple"
                        }, {
                          default: withCtx(() => [
                            createTextVNode(toDisplayString(unref(t2)("issueReport.validation.selectIssueType")), 1)
                          ]),
                          _: 1
                        })) : createCommentVNode("", true)
                      ])
                    ]),
                    _: 1
                  }),
                  createBaseVNode("div", _hoisted_11$6, [
                    createBaseVNode("div", _hoisted_12$4, [
                      createBaseVNode("span", _hoisted_13$2, toDisplayString(_ctx.$t("issueReport.whatCanWeInclude")), 1)
                    ]),
                    createBaseVNode("div", _hoisted_14, [
                      (openBlock(true), createElementBlock(Fragment$1, null, renderList(fields.value, (field2) => {
                        return openBlock(), createElementBlock("div", {
                          key: field2.value
                        }, [
                          field2.optIn ? (openBlock(), createBlock(unref(script), {
                            key: 0,
                            name: field2.value,
                            class: "flex space-x-1"
                          }, {
                            default: withCtx(($field) => [
                              createVNode(unref(script$d), mergeProps$1({ ref_for: true }, $field, {
                                modelValue: selection.value,
                                "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => selection.value = $event),
                                "input-id": field2.value,
                                value: field2.value
                              }), null, 16, ["modelValue", "input-id", "value"]),
                              createBaseVNode("label", {
                                for: field2.value
                              }, toDisplayString(field2.label), 9, _hoisted_15)
                            ]),
                            _: 2
                          }, 1032, ["name"])) : createCommentVNode("", true)
                        ]);
                      }), 128))
                    ])
                  ]),
                  createBaseVNode("div", _hoisted_16, [
                    createVNode(unref(script), { name: "details" }, {
                      default: withCtx(($field) => [
                        createBaseVNode("div", _hoisted_17, [
                          createBaseVNode("label", _hoisted_18, toDisplayString(_ctx.$t("issueReport.describeTheProblem")), 1)
                        ]),
                        createVNode(unref(script$e), mergeProps$1($field, {
                          id: "details",
                          class: "w-full",
                          rows: "5",
                          placeholder: _ctx.$t("issueReport.provideAdditionalDetails"),
                          "aria-label": _ctx.$t("issueReport.provideAdditionalDetails")
                        }), null, 16, ["placeholder", "aria-label"]),
                        $field?.error && $field.touched && $field.value ? (openBlock(), createBlock(unref(script$8), {
                          key: 0,
                          severity: "error",
                          size: "small",
                          variant: "simple"
                        }, {
                          default: withCtx(() => [
                            createTextVNode(toDisplayString(unref(t2)("issueReport.validation.maxLength")), 1)
                          ]),
                          _: 1
                        })) : createCommentVNode("", true)
                      ]),
                      _: 1
                    })
                  ]),
                  createBaseVNode("div", _hoisted_19, [
                    (openBlock(), createElementBlock(Fragment$1, null, renderList(contactCheckboxes, (checkbox) => {
                      return createBaseVNode("div", {
                        key: checkbox.value
                      }, [
                        createVNode(unref(script), {
                          name: checkbox.value,
                          class: "flex space-x-1"
                        }, {
                          default: withCtx(($field) => [
                            createVNode(unref(script$d), mergeProps$1({ ref_for: true }, $field, {
                              modelValue: contactPrefs.value,
                              "onUpdate:modelValue": _cache[1] || (_cache[1] = ($event) => contactPrefs.value = $event),
                              "input-id": checkbox.value,
                              value: checkbox.value,
                              disabled: $form.contactInfo?.error || !$form.contactInfo?.value
                            }), null, 16, ["modelValue", "input-id", "value", "disabled"]),
                            createBaseVNode("label", {
                              for: checkbox.value
                            }, toDisplayString(checkbox.label), 9, _hoisted_20)
                          ]),
                          _: 2
                        }, 1032, ["name"])
                      ]);
                    }), 64))
                  ])
                ])
              ])
            ]),
            _: 2
          }, 1032, ["pt"])
        ]),
        _: 1
      }, 8, ["resolver"]);
    };
  }
});
const _hoisted_1$1o = { class: "comfy-error-report flex flex-col gap-4" };
const _hoisted_2$10 = { class: "font-bold" };
const _hoisted_3$K = { class: "flex gap-2 justify-center" };
const _hoisted_4$x = { class: "whitespace-pre-wrap break-words" };
const _hoisted_5$p = { class: "flex gap-4 justify-end" };
const repoOwner = "comfyanonymous";
const repoName = "ComfyUI";
const _sfc_main$1K = /* @__PURE__ */ defineComponent({
  __name: "ErrorDialogContent",
  props: {
    error: {}
  },
  setup(__props) {
    const authStore = useFirebaseAuthStore();
    const reportContent = ref$3("");
    const reportOpen = ref$3(false);
    const showReport = /* @__PURE__ */ __name(() => {
      reportOpen.value = true;
    }, "showReport");
    const sendReportOpen = ref$3(false);
    const showSendReport = /* @__PURE__ */ __name(() => {
      sendReportOpen.value = true;
    }, "showSendReport");
    const toast = useToast();
    const { t: t2 } = useI18n();
    const systemStatsStore = useSystemStatsStore();
    const title = computed(
      () => __props.error.nodeType ?? __props.error.exceptionType ?? t2("errorDialog.defaultTitle")
    );
    const stackTraceField = computed(() => {
      return {
        label: t2("issueReport.stackTrace"),
        value: "StackTrace",
        optIn: true,
        getData: /* @__PURE__ */ __name(() => __props.error.traceback, "getData")
      };
    });
    const showContactSupport = /* @__PURE__ */ __name(async () => {
      await useCommandStore().execute("Comfy.ContactSupport");
    }, "showContactSupport");
    onMounted(async () => {
      if (!systemStatsStore.systemStats) {
        await systemStatsStore.fetchSystemStats();
      }
      try {
        const [logs] = await Promise.all([api.getLogs()]);
        reportContent.value = generateErrorReport({
          systemStats: systemStatsStore.systemStats,
          serverLogs: logs,
          workflow: app$1.graph.serialize(),
          exceptionType: __props.error.exceptionType,
          exceptionMessage: __props.error.exceptionMessage,
          traceback: __props.error.traceback,
          nodeId: __props.error.nodeId,
          nodeType: __props.error.nodeType
        });
      } catch (error2) {
        console.error("Error fetching logs:", error2);
        toast.add({
          severity: "error",
          summary: t2("g.error"),
          detail: t2("toastMessages.failedToFetchLogs"),
          life: 5e3
        });
      }
    });
    const { copyToClipboard } = useCopyToClipboard();
    const copyReportToClipboard = /* @__PURE__ */ __name(async () => {
      await copyToClipboard(reportContent.value);
    }, "copyReportToClipboard");
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", _hoisted_1$1o, [
        createVNode(NoResultsPlaceholder, {
          class: "pb-0",
          icon: "pi pi-exclamation-circle",
          title: title.value,
          message: _ctx.error.exceptionMessage,
          "text-class": "break-words max-w-[60vw]"
        }, null, 8, ["title", "message"]),
        _ctx.error.extensionFile ? (openBlock(), createElementBlock(Fragment$1, { key: 0 }, [
          createBaseVNode("span", null, toDisplayString(unref(t2)("errorDialog.extensionFileHint")) + ":", 1),
          _cache[0] || (_cache[0] = createBaseVNode("br", null, null, -1)),
          createBaseVNode("span", _hoisted_2$10, toDisplayString(_ctx.error.extensionFile), 1)
        ], 64)) : createCommentVNode("", true),
        createBaseVNode("div", _hoisted_3$K, [
          withDirectives(createVNode(unref(script$6), {
            text: "",
            label: _ctx.$t("g.showReport"),
            onClick: showReport
          }, null, 8, ["label"]), [
            [vShow, !reportOpen.value]
          ]),
          withDirectives(createVNode(unref(script$6), {
            text: "",
            label: _ctx.$t("issueReport.helpFix"),
            onClick: showSendReport
          }, null, 8, ["label"]), [
            [vShow, !sendReportOpen.value]
          ]),
          unref(authStore).currentUser ? withDirectives((openBlock(), createBlock(unref(script$6), {
            key: 0,
            text: "",
            label: _ctx.$t("issueReport.contactSupportTitle"),
            onClick: showContactSupport
          }, null, 8, ["label"])), [
            [vShow, !reportOpen.value]
          ]) : createCommentVNode("", true)
        ]),
        reportOpen.value ? (openBlock(), createElementBlock(Fragment$1, { key: 1 }, [
          createVNode(unref(script$f)),
          createVNode(unref(script$7), { class: "w-full h-[400px] max-w-[80vw]" }, {
            default: withCtx(() => [
              createBaseVNode("pre", _hoisted_4$x, toDisplayString(reportContent.value), 1)
            ]),
            _: 1
          }),
          createVNode(unref(script$f))
        ], 64)) : createCommentVNode("", true),
        sendReportOpen.value ? (openBlock(), createBlock(_sfc_main$1L, {
          key: 2,
          title: _ctx.$t("issueReport.submitErrorReport"),
          "error-type": _ctx.error.reportType ?? "unknownError",
          "extra-fields": [stackTraceField.value],
          tags: {
            exceptionMessage: _ctx.error.exceptionMessage,
            nodeType: _ctx.error.nodeType ?? "UNKNOWN"
          }
        }, null, 8, ["title", "error-type", "extra-fields", "tags"])) : createCommentVNode("", true),
        createBaseVNode("div", _hoisted_5$p, [
          createVNode(_sfc_main$1M, {
            "error-message": _ctx.error.exceptionMessage,
            "repo-owner": repoOwner,
            "repo-name": repoName
          }, null, 8, ["error-message"]),
          reportOpen.value ? (openBlock(), createBlock(unref(script$6), {
            key: 0,
            label: _ctx.$t("g.copyToClipboard"),
            icon: "pi pi-copy",
            onClick: copyReportToClipboard
          }, null, 8, ["label"])) : createCommentVNode("", true)
        ])
      ]);
    };
  }
});
const _hoisted_1$1n = {
  class: "p-2 h-full",
  "aria-labelledby": "issue-report-title"
};
const _hoisted_2$$ = { class: "flex flex-col items-center w-full" };
const _hoisted_3$J = {
  id: "issue-report-title",
  class: "text-4xl"
};
const _hoisted_4$w = {
  key: 0,
  class: "text-muted mt-0"
};
const _sfc_main$1J = /* @__PURE__ */ defineComponent({
  __name: "IssueReportDialogContent",
  props: {
    title: {},
    subtitle: {},
    panelProps: {}
  },
  setup(__props) {
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", _hoisted_1$1n, [
        createVNode(unref(script$a), { pt: {
          root: "border-none",
          content: "p-0"
        } }, {
          header: withCtx(() => [
            createBaseVNode("header", _hoisted_2$$, [
              createBaseVNode("h2", _hoisted_3$J, toDisplayString(_ctx.title), 1),
              _ctx.subtitle ? (openBlock(), createElementBlock("span", _hoisted_4$w, toDisplayString(_ctx.subtitle), 1)) : createCommentVNode("", true)
            ])
          ]),
          default: withCtx(() => [
            createVNode(_sfc_main$1L, mergeProps$1(_ctx.panelProps, { pt: { root: "border-none" } }), null, 16)
          ]),
          _: 1
        })
      ]);
    };
  }
});
const IsInstallingKey = Symbol("isInstalling");
var ManagerWsQueueStatus = /* @__PURE__ */ ((ManagerWsQueueStatus2) => {
  ManagerWsQueueStatus2["DONE"] = "done";
  ManagerWsQueueStatus2["IN_PROGRESS"] = "in_progress";
  return ManagerWsQueueStatus2;
})(ManagerWsQueueStatus || {});
var ManagerTab = /* @__PURE__ */ ((ManagerTab2) => {
  ManagerTab2["All"] = "all";
  ManagerTab2["Installed"] = "installed";
  ManagerTab2["Workflow"] = "workflow";
  ManagerTab2["Missing"] = "missing";
  ManagerTab2["UpdateAvailable"] = "updateAvailable";
  return ManagerTab2;
})(ManagerTab || {});
var SortableAlgoliaField = /* @__PURE__ */ ((SortableAlgoliaField2) => {
  SortableAlgoliaField2["Downloads"] = "total_install";
  SortableAlgoliaField2["Created"] = "create_time";
  SortableAlgoliaField2["Updated"] = "update_time";
  SortableAlgoliaField2["Publisher"] = "publisher_id";
  SortableAlgoliaField2["Name"] = "name";
  return SortableAlgoliaField2;
})(SortableAlgoliaField || {});
var ManagerPackState = /* @__PURE__ */ ((ManagerPackState2) => {
  ManagerPackState2["INSTALLED"] = "installed";
  ManagerPackState2["DISABLED"] = "disabled";
  ManagerPackState2["NOT_INSTALLED"] = "not_installed";
  ManagerPackState2["IMPORT_FAILED"] = "import_failed";
  ManagerPackState2["NEEDS_UPDATE"] = "needs_update";
  return ManagerPackState2;
})(ManagerPackState || {});
var ManagerPackInstallType = /* @__PURE__ */ ((ManagerPackInstallType2) => {
  ManagerPackInstallType2["GIT"] = "git-clone";
  ManagerPackInstallType2["COPY"] = "copy";
  ManagerPackInstallType2["REGISTRY"] = "cnr";
  return ManagerPackInstallType2;
})(ManagerPackInstallType || {});
var SelectedVersion = /* @__PURE__ */ ((SelectedVersion2) => {
  SelectedVersion2["LATEST"] = "latest";
  SelectedVersion2["NIGHTLY"] = "nightly";
  return SelectedVersion2;
})(SelectedVersion || {});
var ManagerChannel = /* @__PURE__ */ ((ManagerChannel2) => {
  ManagerChannel2["DEFAULT"] = "default";
  ManagerChannel2["RECENT"] = "recent";
  ManagerChannel2["LEGACY"] = "legacy";
  ManagerChannel2["FORKED"] = "forked";
  ManagerChannel2["DEV"] = "dev";
  ManagerChannel2["TUTORIAL"] = "tutorial";
  return ManagerChannel2;
})(ManagerChannel || {});
var ManagerDatabaseSource = /* @__PURE__ */ ((ManagerDatabaseSource2) => {
  ManagerDatabaseSource2["REMOTE"] = "remote";
  ManagerDatabaseSource2["LOCAL"] = "local";
  ManagerDatabaseSource2["CACHE"] = "cache";
  return ManagerDatabaseSource2;
})(ManagerDatabaseSource || {});
const _hoisted_1$1m = { class: "flex align-items-center" };
const _hoisted_2$_ = { class: "node-type" };
const _hoisted_3$I = {
  key: 0,
  class: "node-hint"
};
const _hoisted_4$v = { class: "flex justify-end py-3" };
const _sfc_main$1I = /* @__PURE__ */ defineComponent({
  __name: "LoadWorkflowWarning",
  props: {
    missingNodeTypes: {}
  },
  setup(__props) {
    const props = __props;
    const uniqueNodes = computed(() => {
      const seenTypes = /* @__PURE__ */ new Set();
      return props.missingNodeTypes.filter((node2) => {
        const type = typeof node2 === "object" ? node2.type : node2;
        if (seenTypes.has(type)) return false;
        seenTypes.add(type);
        return true;
      }).map((node2) => {
        if (typeof node2 === "object") {
          return {
            label: node2.type,
            hint: node2.hint,
            action: node2.action
          };
        }
        return { label: node2 };
      });
    });
    const openManager = /* @__PURE__ */ __name(() => {
      useDialogService().showManagerDialog({
        initialTab: ManagerTab.Missing
      });
    }, "openManager");
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock(Fragment$1, null, [
        createVNode(NoResultsPlaceholder, {
          class: "pb-0",
          icon: "pi pi-exclamation-circle",
          title: "Missing Node Types",
          message: "When loading the graph, the following node types were not found"
        }),
        createVNode(unref(script$g), {
          options: uniqueNodes.value,
          "option-label": "label",
          "scroll-height": "100%",
          class: "comfy-missing-nodes",
          pt: {
            list: { class: "border-none" }
          }
        }, {
          option: withCtx((slotProps) => [
            createBaseVNode("div", _hoisted_1$1m, [
              createBaseVNode("span", _hoisted_2$_, toDisplayString(slotProps.option.label), 1),
              slotProps.option.hint ? (openBlock(), createElementBlock("span", _hoisted_3$I, toDisplayString(slotProps.option.hint), 1)) : createCommentVNode("", true),
              slotProps.option.action ? (openBlock(), createBlock(unref(script$6), {
                key: 1,
                label: slotProps.option.action.text,
                size: "small",
                outlined: "",
                onClick: slotProps.option.action.callback
              }, null, 8, ["label", "onClick"])) : createCommentVNode("", true)
            ])
          ]),
          _: 1
        }, 8, ["options"]),
        createBaseVNode("div", _hoisted_4$v, [
          createVNode(unref(script$6), {
            label: "Open Manager",
            size: "small",
            outlined: "",
            onClick: openManager
          })
        ])
      ], 64);
    };
  }
});
const LoadWorkflowWarning = /* @__PURE__ */ _export_sfc(_sfc_main$1I, [["__scopeId", "data-v-cd1d5e25"]]);
"use strict";
class QuickLRU {
  static {
    __name(this, "QuickLRU");
  }
  constructor(options2 = {}) {
    if (!(options2.maxSize && options2.maxSize > 0)) {
      throw new TypeError("`maxSize` must be a number greater than 0");
    }
    if (typeof options2.maxAge === "number" && options2.maxAge === 0) {
      throw new TypeError("`maxAge` must be a number greater than 0");
    }
    this.maxSize = options2.maxSize;
    this.maxAge = options2.maxAge || Infinity;
    this.onEviction = options2.onEviction;
    this.cache = /* @__PURE__ */ new Map();
    this.oldCache = /* @__PURE__ */ new Map();
    this._size = 0;
  }
  _emitEvictions(cache) {
    if (typeof this.onEviction !== "function") {
      return;
    }
    for (const [key, item] of cache) {
      this.onEviction(key, item.value);
    }
  }
  _deleteIfExpired(key, item) {
    if (typeof item.expiry === "number" && item.expiry <= Date.now()) {
      if (typeof this.onEviction === "function") {
        this.onEviction(key, item.value);
      }
      return this.delete(key);
    }
    return false;
  }
  _getOrDeleteIfExpired(key, item) {
    const deleted = this._deleteIfExpired(key, item);
    if (deleted === false) {
      return item.value;
    }
  }
  _getItemValue(key, item) {
    return item.expiry ? this._getOrDeleteIfExpired(key, item) : item.value;
  }
  _peek(key, cache) {
    const item = cache.get(key);
    return this._getItemValue(key, item);
  }
  _set(key, value) {
    this.cache.set(key, value);
    this._size++;
    if (this._size >= this.maxSize) {
      this._size = 0;
      this._emitEvictions(this.oldCache);
      this.oldCache = this.cache;
      this.cache = /* @__PURE__ */ new Map();
    }
  }
  _moveToRecent(key, item) {
    this.oldCache.delete(key);
    this._set(key, item);
  }
  *_entriesAscending() {
    for (const item of this.oldCache) {
      const [key, value] = item;
      if (!this.cache.has(key)) {
        const deleted = this._deleteIfExpired(key, value);
        if (deleted === false) {
          yield item;
        }
      }
    }
    for (const item of this.cache) {
      const [key, value] = item;
      const deleted = this._deleteIfExpired(key, value);
      if (deleted === false) {
        yield item;
      }
    }
  }
  get(key) {
    if (this.cache.has(key)) {
      const item = this.cache.get(key);
      return this._getItemValue(key, item);
    }
    if (this.oldCache.has(key)) {
      const item = this.oldCache.get(key);
      if (this._deleteIfExpired(key, item) === false) {
        this._moveToRecent(key, item);
        return item.value;
      }
    }
  }
  set(key, value, { maxAge = this.maxAge === Infinity ? void 0 : Date.now() + this.maxAge } = {}) {
    if (this.cache.has(key)) {
      this.cache.set(key, {
        value,
        maxAge
      });
    } else {
      this._set(key, { value, expiry: maxAge });
    }
  }
  has(key) {
    if (this.cache.has(key)) {
      return !this._deleteIfExpired(key, this.cache.get(key));
    }
    if (this.oldCache.has(key)) {
      return !this._deleteIfExpired(key, this.oldCache.get(key));
    }
    return false;
  }
  peek(key) {
    if (this.cache.has(key)) {
      return this._peek(key, this.cache);
    }
    if (this.oldCache.has(key)) {
      return this._peek(key, this.oldCache);
    }
  }
  delete(key) {
    const deleted = this.cache.delete(key);
    if (deleted) {
      this._size--;
    }
    return this.oldCache.delete(key) || deleted;
  }
  clear() {
    this.cache.clear();
    this.oldCache.clear();
    this._size = 0;
  }
  resize(newSize) {
    if (!(newSize && newSize > 0)) {
      throw new TypeError("`maxSize` must be a number greater than 0");
    }
    const items = [...this._entriesAscending()];
    const removeCount = items.length - newSize;
    if (removeCount < 0) {
      this.cache = new Map(items);
      this.oldCache = /* @__PURE__ */ new Map();
      this._size = items.length;
    } else {
      if (removeCount > 0) {
        this._emitEvictions(items.slice(0, removeCount));
      }
      this.oldCache = new Map(items.slice(removeCount));
      this.cache = /* @__PURE__ */ new Map();
      this._size = 0;
    }
    this.maxSize = newSize;
  }
  *keys() {
    for (const [key] of this) {
      yield key;
    }
  }
  *values() {
    for (const [, value] of this) {
      yield value;
    }
  }
  *[Symbol.iterator]() {
    for (const item of this.cache) {
      const [key, value] = item;
      const deleted = this._deleteIfExpired(key, value);
      if (deleted === false) {
        yield [key, value.value];
      }
    }
    for (const item of this.oldCache) {
      const [key, value] = item;
      if (!this.cache.has(key)) {
        const deleted = this._deleteIfExpired(key, value);
        if (deleted === false) {
          yield [key, value.value];
        }
      }
    }
  }
  *entriesDescending() {
    let items = [...this.cache];
    for (let i2 = items.length - 1; i2 >= 0; --i2) {
      const item = items[i2];
      const [key, value] = item;
      const deleted = this._deleteIfExpired(key, value);
      if (deleted === false) {
        yield [key, value.value];
      }
    }
    items = [...this.oldCache];
    for (let i2 = items.length - 1; i2 >= 0; --i2) {
      const item = items[i2];
      const [key, value] = item;
      if (!this.cache.has(key)) {
        const deleted = this._deleteIfExpired(key, value);
        if (deleted === false) {
          yield [key, value.value];
        }
      }
    }
  }
  *entriesAscending() {
    for (const [key, value] of this._entriesAscending()) {
      yield [key, value.value];
    }
  }
  get size() {
    if (!this._size) {
      return this.oldCache.size;
    }
    let oldCacheSize = 0;
    for (const key of this.oldCache.keys()) {
      if (!this.cache.has(key)) {
        oldCacheSize++;
      }
    }
    return Math.min(this._size + oldCacheSize, this.maxSize);
  }
}
var quickLru = QuickLRU;
const QuickLRU$1 = /* @__PURE__ */ getDefaultExportFromCjs(quickLru);
const DEFAULT_MAX_SIZE = 50;
function useCachedRequest(requestFunction, options2 = {}) {
  const { maxSize = DEFAULT_MAX_SIZE, cacheKeyFn = paramsToCacheKey } = options2;
  const cache = new QuickLRU$1({ maxSize });
  const pendingRequests = /* @__PURE__ */ new Map();
  const abortControllers = /* @__PURE__ */ new Map();
  const executeAndCacheCall = /* @__PURE__ */ __name(async (params, cacheKey) => {
    try {
      const controller = new AbortController();
      abortControllers.set(cacheKey, controller);
      const responsePromise = requestFunction(params, controller.signal);
      pendingRequests.set(cacheKey, responsePromise);
      const result = await responsePromise;
      cache.set(cacheKey, result);
      return result;
    } catch (err) {
      cache.set(cacheKey, null);
      return null;
    } finally {
      pendingRequests.delete(cacheKey);
      abortControllers.delete(cacheKey);
    }
  }, "executeAndCacheCall");
  const handlePendingRequest = /* @__PURE__ */ __name(async (pendingRequest) => {
    try {
      return await pendingRequest;
    } catch (err) {
      console.error("Error in pending request:", err);
      return null;
    }
  }, "handlePendingRequest");
  const abortAllRequests = /* @__PURE__ */ __name(() => {
    for (const controller of abortControllers.values()) {
      controller.abort();
    }
  }, "abortAllRequests");
  const cancel = /* @__PURE__ */ __name(() => {
    abortAllRequests();
    abortControllers.clear();
    pendingRequests.clear();
  }, "cancel");
  const call = /* @__PURE__ */ __name(async (params) => {
    const cacheKey = cacheKeyFn(params);
    const cachedResult2 = cache.get(cacheKey);
    if (cachedResult2 !== void 0) return cachedResult2;
    const pendingRequest = pendingRequests.get(cacheKey);
    if (pendingRequest) return handlePendingRequest(pendingRequest);
    return executeAndCacheCall(params, cacheKey);
  }, "call");
  return {
    call,
    cancel,
    clear: /* @__PURE__ */ __name(() => cache.clear(), "clear")
  };
}
__name(useCachedRequest, "useCachedRequest");
const MANAGER_WS_MSG_TYPE = "cm-queue-status";
const useManagerQueue = /* @__PURE__ */ __name(() => {
  const clientQueueItems = ref$3([]);
  const clientQueueLength = computed(() => clientQueueItems.value.length);
  const onCompletedQueue = ref$3([]);
  const onCompleteWaitingCount = ref$3(0);
  const uncompletedCount = computed(
    () => clientQueueLength.value + onCompleteWaitingCount.value
  );
  const serverQueueStatus = ref$3(ManagerWsQueueStatus.DONE);
  const isServerIdle = computed(
    () => serverQueueStatus.value === ManagerWsQueueStatus.DONE
  );
  const allTasksDone = computed(
    () => isServerIdle.value && clientQueueLength.value === 0
  );
  const nextTaskReady = computed(
    () => isServerIdle.value && clientQueueLength.value > 0
  );
  const cleanupListener = useEventListener(
    api,
    MANAGER_WS_MSG_TYPE,
    (event) => {
      if (event?.type === MANAGER_WS_MSG_TYPE && event.detail?.status) {
        serverQueueStatus.value = event.detail.status;
      }
    }
  );
  const startNextTask = /* @__PURE__ */ __name(() => {
    const nextTask = clientQueueItems.value.shift();
    if (!nextTask) return;
    const { task, onComplete } = nextTask;
    if (onComplete) {
      onCompletedQueue.value.push(onComplete);
      onCompleteWaitingCount.value++;
    }
    task().catch((e2) => {
      const message = `Error enqueuing task for ComfyUI Manager: ${e2}`;
      console.error(message);
    });
  }, "startNextTask");
  const enqueueTask = /* @__PURE__ */ __name((task) => {
    clientQueueItems.value.push(task);
  }, "enqueueTask");
  const clearQueue = /* @__PURE__ */ __name(() => {
    clientQueueItems.value = [];
    onCompletedQueue.value = [];
    onCompleteWaitingCount.value = 0;
  }, "clearQueue");
  const cleanup = /* @__PURE__ */ __name(() => {
    clearQueue();
    cleanupListener();
  }, "cleanup");
  whenever(nextTaskReady, startNextTask);
  whenever(isServerIdle, () => {
    if (onCompletedQueue.value?.length) {
      while (onCompleteWaitingCount.value > 0 && onCompletedQueue.value.length > 0) {
        const onComplete = onCompletedQueue.value.shift();
        onComplete?.();
        onCompleteWaitingCount.value--;
      }
    }
  });
  return {
    allTasksDone,
    statusMessage: readonly(serverQueueStatus),
    queueLength: clientQueueLength,
    uncompletedCount,
    enqueueTask,
    clearQueue,
    cleanup
  };
}, "useManagerQueue");
const LOGS_MESSAGE_TYPE = "logs";
const useServerLogs = /* @__PURE__ */ __name((options2 = {}) => {
  const {
    immediate = false,
    messageFilter = /* @__PURE__ */ __name((msg) => Boolean(msg.trim()), "messageFilter")
  } = options2;
  const logs = ref$3([]);
  let stop2 = null;
  const isValidLogEvent = /* @__PURE__ */ __name((event) => event?.type === LOGS_MESSAGE_TYPE && event.detail?.entries?.length > 0, "isValidLogEvent");
  const parseLogMessage = /* @__PURE__ */ __name((event) => event.detail.entries.map((e2) => e2.m).filter(messageFilter), "parseLogMessage");
  const handleLogMessage = /* @__PURE__ */ __name((event) => {
    if (isValidLogEvent(event)) {
      logs.value.push(...parseLogMessage(event));
    }
  }, "handleLogMessage");
  const start2 = /* @__PURE__ */ __name(async () => {
    await api.subscribeLogs(true);
    stop2 = useEventListener(api, LOGS_MESSAGE_TYPE, handleLogMessage);
  }, "start");
  const stopListening = /* @__PURE__ */ __name(async () => {
    stop2?.();
    stop2 = null;
    await api.subscribeLogs(false);
  }, "stopListening");
  if (immediate) {
    void start2();
  }
  onUnmounted(async () => {
    await stopListening();
    logs.value = [];
  });
  return {
    logs,
    startListening: start2,
    stopListening
  };
}, "useServerLogs");
function isPrimitiveNode(node2) {
  return node2.type === "PrimitiveNode";
}
__name(isPrimitiveNode, "isPrimitiveNode");
const isAbortError = /* @__PURE__ */ __name((err) => err instanceof DOMException && err.name === "AbortError", "isAbortError");
const isSubgraph = /* @__PURE__ */ __name((item) => item?.isRootGraph === false, "isSubgraph");
const GENERIC_SECURITY_ERR_MSG = "Forbidden: A security error has occurred. Please check the terminal logs";
var ManagerRoute = /* @__PURE__ */ ((ManagerRoute2) => {
  ManagerRoute2["START_QUEUE"] = "manager/queue/start";
  ManagerRoute2["RESET_QUEUE"] = "manager/queue/reset";
  ManagerRoute2["QUEUE_STATUS"] = "manager/queue/status";
  ManagerRoute2["INSTALL"] = "manager/queue/install";
  ManagerRoute2["UPDATE"] = "manager/queue/update";
  ManagerRoute2["UPDATE_ALL"] = "manager/queue/update_all";
  ManagerRoute2["UNINSTALL"] = "manager/queue/uninstall";
  ManagerRoute2["DISABLE"] = "manager/queue/disable";
  ManagerRoute2["FIX_NODE"] = "manager/queue/fix";
  ManagerRoute2["LIST_INSTALLED"] = "customnode/installed";
  ManagerRoute2["GET_NODES"] = "customnode/getmappings";
  ManagerRoute2["GET_PACKS"] = "customnode/getlist";
  ManagerRoute2["IMPORT_FAIL_INFO"] = "customnode/import_fail_info";
  ManagerRoute2["REBOOT"] = "manager/reboot";
  return ManagerRoute2;
})(ManagerRoute || {});
const managerApiClient = axios.create({
  baseURL: api.apiURL(""),
  headers: {
    "Content-Type": "application/json"
  }
});
const useComfyManagerService = /* @__PURE__ */ __name(() => {
  const isLoading = ref$3(false);
  const error2 = ref$3(null);
  const didStartQueue = ref$3(false);
  const handleRequestError = /* @__PURE__ */ __name((err, context, routeSpecificErrors) => {
    if (isAbortError(err)) return;
    let message;
    if (!axios.isAxiosError(err)) {
      message = `${context} failed: ${err instanceof Error ? err.message : String(err)}`;
    } else {
      const axiosError = err;
      const status = axiosError.response?.status;
      if (status && routeSpecificErrors?.[status]) {
        message = routeSpecificErrors[status];
      } else if (status === 404) {
        message = "Could not connect to ComfyUI-Manager";
      } else {
        message = axiosError.response?.data?.message ?? `${context} failed with status ${status}`;
      }
    }
    error2.value = message;
  }, "handleRequestError");
  const executeRequest = /* @__PURE__ */ __name(async (requestCall, options2) => {
    const { errorContext, routeSpecificErrors, isQueueOperation } = options2;
    isLoading.value = true;
    error2.value = null;
    try {
      const response = await requestCall();
      if (isQueueOperation) await startQueue();
      return response.data;
    } catch (err) {
      handleRequestError(err, errorContext, routeSpecificErrors);
      return null;
    } finally {
      isLoading.value = false;
    }
  }, "executeRequest");
  const startQueue = /* @__PURE__ */ __name(async (signal) => {
    const errorContext = "Starting ComfyUI-Manager job queue";
    const routeSpecificErrors = {
      201: "Created: ComfyUI-Manager job queue is already running"
    };
    didStartQueue.value = true;
    return executeRequest(
      () => managerApiClient.get("manager/queue/start", { signal }),
      { errorContext, routeSpecificErrors }
    );
  }, "startQueue");
  const getQueueStatus = /* @__PURE__ */ __name(async (signal) => {
    const errorContext = "Getting ComfyUI-Manager queue status";
    return executeRequest(
      () => managerApiClient.get("manager/queue/status", { signal }),
      { errorContext }
    );
  }, "getQueueStatus");
  const resetQueue = /* @__PURE__ */ __name(async (signal) => {
    const errorContext = "Resetting ComfyUI-Manager queue";
    return executeRequest(
      () => managerApiClient.get("manager/queue/reset", { signal }),
      { errorContext }
    );
  }, "resetQueue");
  const listInstalledPacks = /* @__PURE__ */ __name(async (signal) => {
    const errorContext = "Fetching installed packs";
    return executeRequest(
      () => managerApiClient.get("customnode/installed", { signal }),
      { errorContext }
    );
  }, "listInstalledPacks");
  const getImportFailInfo = /* @__PURE__ */ __name(async (signal) => {
    const errorContext = "Fetching import failure information";
    return executeRequest(
      () => managerApiClient.get("customnode/import_fail_info", { signal }),
      { errorContext }
    );
  }, "getImportFailInfo");
  const installPack = /* @__PURE__ */ __name(async (params, signal) => {
    const errorContext = `Installing pack ${params.id}`;
    const routeSpecificErrors = {
      403: GENERIC_SECURITY_ERR_MSG,
      404: params.selected_version === SelectedVersion.NIGHTLY ? `Not Found: Node pack ${params.id} does not provide nightly version` : GENERIC_SECURITY_ERR_MSG
    };
    return executeRequest(
      () => managerApiClient.post("manager/queue/install", params, { signal }),
      { errorContext, routeSpecificErrors, isQueueOperation: true }
    );
  }, "installPack");
  const uninstallPack = /* @__PURE__ */ __name(async (params, signal) => {
    const errorContext = `Uninstalling pack ${params.id}`;
    const routeSpecificErrors = {
      403: GENERIC_SECURITY_ERR_MSG
    };
    return executeRequest(
      () => managerApiClient.post("manager/queue/uninstall", params, { signal }),
      { errorContext, routeSpecificErrors, isQueueOperation: true }
    );
  }, "uninstallPack");
  const disablePack = /* @__PURE__ */ __name(async (params, signal) => {
    const errorContext = `Disabling pack ${params.id}`;
    const routeSpecificErrors = {
      404: `Pack ${params.id} not found or not installed`,
      409: `Pack ${params.id} is already disabled`
    };
    return executeRequest(
      () => managerApiClient.post("manager/queue/disable", params, { signal }),
      { errorContext, routeSpecificErrors, isQueueOperation: true }
    );
  }, "disablePack");
  const updatePack = /* @__PURE__ */ __name(async (params, signal) => {
    const errorContext = `Updating pack ${params.id}`;
    const routeSpecificErrors = {
      403: GENERIC_SECURITY_ERR_MSG
    };
    return executeRequest(
      () => managerApiClient.post("manager/queue/update", params, { signal }),
      { errorContext, routeSpecificErrors, isQueueOperation: true }
    );
  }, "updatePack");
  const updateAllPacks = /* @__PURE__ */ __name(async (params, signal) => {
    const errorContext = "Updating all packs";
    const routeSpecificErrors = {
      403: "Forbidden: To use this action, a security_level of `middle or below` is required",
      401: "Unauthorized: ComfyUI-Manager job queue is busy"
    };
    return executeRequest(
      () => managerApiClient.get("manager/queue/update_all", { params, signal }),
      { errorContext, routeSpecificErrors, isQueueOperation: true }
    );
  }, "updateAllPacks");
  const rebootComfyUI = /* @__PURE__ */ __name(async (signal) => {
    const errorContext = "Rebooting ComfyUI";
    const routeSpecificErrors = {
      403: "Forbidden: Rebooting ComfyUI requires security_level of middle or below"
    };
    return executeRequest(
      () => managerApiClient.get("manager/reboot", { signal }),
      { errorContext, routeSpecificErrors }
    );
  }, "rebootComfyUI");
  return {
    // State
    isLoading,
    error: error2,
    // Queue operations
    startQueue,
    resetQueue,
    getQueueStatus,
    // Pack management
    listInstalledPacks,
    getImportFailInfo,
    installPack,
    uninstallPack,
    enablePack: installPack,
    // enable is done via install
    disablePack,
    updatePack,
    updateAllPacks,
    // System operations
    rebootComfyUI
  };
}, "useComfyManagerService");
const useComfyManagerStore = /* @__PURE__ */ defineStore("comfyManager", () => {
  const { t: t2 } = useI18n();
  const managerService = useComfyManagerService();
  const { showManagerProgressDialog } = useDialogService();
  const installedPacks = ref$3({});
  const enabledPacksIds = ref$3(/* @__PURE__ */ new Set());
  const disabledPacksIds = ref$3(/* @__PURE__ */ new Set());
  const installedPacksIds = ref$3(/* @__PURE__ */ new Set());
  const isStale2 = ref$3(true);
  const taskLogs = ref$3([]);
  const { statusMessage, allTasksDone, enqueueTask, uncompletedCount } = useManagerQueue();
  const setStale = /* @__PURE__ */ __name(() => {
    isStale2.value = true;
  }, "setStale");
  const getPackId = /* @__PURE__ */ __name((pack) => pack.cnr_id || pack.aux_id, "getPackId");
  const isInstalledPackId = /* @__PURE__ */ __name((packName) => !!packName && installedPacksIds.value.has(packName), "isInstalledPackId");
  const isEnabledPackId = /* @__PURE__ */ __name((packName) => !!packName && isInstalledPackId(packName) && enabledPacksIds.value.has(packName), "isEnabledPackId");
  const packsToIdSet = /* @__PURE__ */ __name((packs) => packs.reduce((acc, pack) => {
    const id2 = pack.cnr_id || pack.aux_id;
    if (id2) acc.add(id2);
    return acc;
  }, /* @__PURE__ */ new Set()), "packsToIdSet");
  const updateDisabledIds = /* @__PURE__ */ __name((packs) => {
    const enabledIds = /* @__PURE__ */ new Set();
    const disabledIds = /* @__PURE__ */ new Set();
    for (const pack of packs) {
      const id2 = getPackId(pack);
      if (!id2) continue;
      const { enabled } = pack;
      if (enabled === true) enabledIds.add(id2);
      else if (enabled === false) disabledIds.add(id2);
      const inBothSets = enabledIds.has(id2) && disabledIds.has(id2);
      if (inBothSets) disabledIds.delete(id2);
    }
    enabledPacksIds.value = enabledIds;
    disabledPacksIds.value = disabledIds;
  }, "updateDisabledIds");
  const updateInstalledIds = /* @__PURE__ */ __name((packs) => {
    installedPacksIds.value = packsToIdSet(packs);
  }, "updateInstalledIds");
  const onPacksChanged = /* @__PURE__ */ __name(() => {
    const packs = Object.values(installedPacks.value);
    updateDisabledIds(packs);
    updateInstalledIds(packs);
  }, "onPacksChanged");
  watch(installedPacks, onPacksChanged, { deep: true });
  const refreshInstalledList = /* @__PURE__ */ __name(async () => {
    const packs = await managerService.listInstalledPacks();
    if (packs) installedPacks.value = packs;
    isStale2.value = false;
  }, "refreshInstalledList");
  whenever(isStale2, refreshInstalledList, { immediate: true });
  whenever(uncompletedCount, () => showManagerProgressDialog());
  const withLogs = /* @__PURE__ */ __name((task, taskName) => {
    const { startListening, stopListening, logs } = useServerLogs();
    const loggedTask = /* @__PURE__ */ __name(async () => {
      taskLogs.value.push({ taskName, logs: logs.value });
      await startListening();
      return task();
    }, "loggedTask");
    const onComplete = /* @__PURE__ */ __name(async () => {
      await stopListening();
      setStale();
    }, "onComplete");
    return { task: loggedTask, onComplete };
  }, "withLogs");
  const installPack = useCachedRequest(
    async (params, signal) => {
      if (!params.id) return;
      let actionDescription = t2("g.installing");
      if (installedPacksIds.value.has(params.id)) {
        const installedPack = installedPacks.value[params.id];
        if (installedPack && installedPack.ver !== params.selected_version) {
          actionDescription = t2("manager.changingVersion", {
            from: installedPack.ver,
            to: params.selected_version
          });
        } else {
          actionDescription = t2("g.enabling");
        }
      }
      const task = /* @__PURE__ */ __name(() => managerService.installPack(params, signal), "task");
      enqueueTask(withLogs(task, `${actionDescription} ${params.id}`));
    },
    { maxSize: 1 }
  );
  const uninstallPack = /* @__PURE__ */ __name((params, signal) => {
    installPack.clear();
    installPack.cancel();
    const task = /* @__PURE__ */ __name(() => managerService.uninstallPack(params, signal), "task");
    enqueueTask(withLogs(task, t2("manager.uninstalling", { id: params.id })));
  }, "uninstallPack");
  const updatePack = useCachedRequest(
    async (params, signal) => {
      updateAllPacks.cancel();
      const task = /* @__PURE__ */ __name(() => managerService.updatePack(params, signal), "task");
      enqueueTask(withLogs(task, t2("g.updating", { id: params.id })));
    },
    { maxSize: 1 }
  );
  const updateAllPacks = useCachedRequest(
    async (params, signal) => {
      const task = /* @__PURE__ */ __name(() => managerService.updateAllPacks(params, signal), "task");
      enqueueTask(withLogs(task, t2("manager.updatingAllPacks")));
    },
    { maxSize: 1 }
  );
  const disablePack = /* @__PURE__ */ __name((params, signal) => {
    const task = /* @__PURE__ */ __name(() => managerService.disablePack(params, signal), "task");
    enqueueTask(withLogs(task, t2("g.disabling", { id: params.id })));
  }, "disablePack");
  const getInstalledPackVersion = /* @__PURE__ */ __name((packId) => {
    const pack = installedPacks.value[packId];
    return pack?.ver;
  }, "getInstalledPackVersion");
  const clearLogs = /* @__PURE__ */ __name(() => {
    taskLogs.value = [];
  }, "clearLogs");
  return {
    // Manager state
    isLoading: managerService.isLoading,
    error: managerService.error,
    statusMessage,
    allTasksDone,
    uncompletedCount,
    taskLogs,
    clearLogs,
    setStale,
    // Installed packs state
    installedPacks,
    installedPacksIds,
    isPackInstalled: isInstalledPackId,
    isPackEnabled: isEnabledPackId,
    getInstalledPackVersion,
    // Pack actions
    installPack,
    uninstallPack,
    updatePack,
    updateAllPacks,
    disablePack,
    enablePack: installPack
    // Enable is done via install endpoint with a disabled pack
  };
});
const useManagerProgressDialogStore = /* @__PURE__ */ defineStore(
  "managerProgressDialog",
  () => {
    const isExpanded = ref$3(false);
    const toggle = /* @__PURE__ */ __name(() => {
      isExpanded.value = !isExpanded.value;
    }, "toggle");
    const collapse = /* @__PURE__ */ __name(() => {
      isExpanded.value = false;
    }, "collapse");
    const expand = /* @__PURE__ */ __name(() => {
      isExpanded.value = true;
    }, "expand");
    return {
      isExpanded,
      toggle,
      collapse,
      expand
    };
  }
);
const _hoisted_1$1l = { class: "flex items-center justify-between w-full py-2" };
const _hoisted_2$Z = { class: "flex flex-col text-sm font-medium leading-normal" };
const _hoisted_3$H = { class: "text-muted" };
const _hoisted_4$u = { class: "h-full" };
const _hoisted_5$o = { class: "whitespace-pre-wrap break-words" };
const _sfc_main$1H = /* @__PURE__ */ defineComponent({
  __name: "ManagerProgressDialogContent",
  setup(__props) {
    const { taskLogs } = useComfyManagerStore();
    const progressDialogContent = useManagerProgressDialogStore();
    const managerStore = useComfyManagerStore();
    const isInProgress = /* @__PURE__ */ __name((index2) => index2 === taskPanels.value.length - 1 && managerStore.uncompletedCount > 0, "isInProgress");
    const taskPanels = computed(() => taskLogs);
    const isExpanded = computed(() => progressDialogContent.isExpanded);
    const isCollapsed = computed(() => !isExpanded.value);
    const collapsedPanels = ref$3({});
    const togglePanel = /* @__PURE__ */ __name((index2) => {
      collapsedPanels.value[index2] = !collapsedPanels.value[index2];
    }, "togglePanel");
    const sectionsContainerRef = ref$3(null);
    const { y: scrollY } = useScroll(sectionsContainerRef, {
      eventListenerOptions: {
        passive: true
      }
    });
    const lastPanelRef = ref$3(null);
    const isUserScrolling = ref$3(false);
    const lastPanelLogs = computed(() => taskPanels.value?.at(-1)?.logs);
    const isAtBottom = /* @__PURE__ */ __name((el) => {
      if (!el) return false;
      const threshold = 20;
      return Math.abs(el.scrollHeight - el.scrollTop - el.clientHeight) < threshold;
    }, "isAtBottom");
    const scrollLastPanelToBottom = /* @__PURE__ */ __name(() => {
      if (!lastPanelRef.value || isUserScrolling.value) return;
      lastPanelRef.value.scrollTop = lastPanelRef.value.scrollHeight;
    }, "scrollLastPanelToBottom");
    const scrollContentToBottom = /* @__PURE__ */ __name(() => {
      scrollY.value = sectionsContainerRef.value?.scrollHeight ?? 0;
    }, "scrollContentToBottom");
    const resetUserScrolling = /* @__PURE__ */ __name(() => {
      isUserScrolling.value = false;
    }, "resetUserScrolling");
    const handleScroll = /* @__PURE__ */ __name((e2) => {
      const target = e2.target;
      if (target !== lastPanelRef.value) return;
      isUserScrolling.value = !isAtBottom(target);
    }, "handleScroll");
    const onLogsAdded = /* @__PURE__ */ __name(() => {
      if (isUserScrolling.value) return;
      scrollLastPanelToBottom();
    }, "onLogsAdded");
    whenever(lastPanelLogs, onLogsAdded, { flush: "post", deep: true });
    whenever(() => isExpanded.value, scrollContentToBottom);
    whenever(isCollapsed, resetUserScrolling);
    onMounted(() => {
      scrollContentToBottom();
    });
    onBeforeUnmount(() => {
      progressDialogContent.collapse();
    });
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", {
        class: normalizeClass(["overflow-hidden transition-all duration-300", {
          "max-h-[500px]": isExpanded.value,
          "max-h-0 p-0 m-0": !isExpanded.value
        }])
      }, [
        createBaseVNode("div", {
          ref_key: "sectionsContainerRef",
          ref: sectionsContainerRef,
          class: normalizeClass(["px-6 py-4 overflow-y-auto max-h-[450px] scroll-container", {
            "max-h-[450px]": isExpanded.value,
            "max-h-0": !isExpanded.value
          }]),
          style: {
            scrollbarWidth: "thin",
            scrollbarColor: "rgba(156, 163, 175, 0.5) transparent"
          }
        }, [
          (openBlock(true), createElementBlock(Fragment$1, null, renderList(taskPanels.value, (panel, index2) => {
            return openBlock(), createElementBlock("div", { key: index2 }, [
              createVNode(unref(script$a), {
                expanded: collapsedPanels.value[index2] || false,
                toggleable: "",
                class: "shadow-elevation-1 rounded-lg mt-2 dark-theme:bg-black dark-theme:border-black"
              }, {
                header: withCtx(() => [
                  createBaseVNode("div", _hoisted_1$1l, [
                    createBaseVNode("div", _hoisted_2$Z, [
                      createBaseVNode("span", null, toDisplayString(panel.taskName), 1),
                      createBaseVNode("span", _hoisted_3$H, toDisplayString(isInProgress(index2) ? _ctx.$t("g.inProgress") : _ctx.$t("g.completed") + " ✓"), 1)
                    ])
                  ])
                ]),
                toggleicon: withCtx(() => [
                  createVNode(unref(script$6), {
                    icon: collapsedPanels.value[index2] ? "pi pi-chevron-right" : "pi pi-chevron-down",
                    text: "",
                    class: "text-neutral-300",
                    onClick: /* @__PURE__ */ __name(($event) => togglePanel(index2), "onClick")
                  }, null, 8, ["icon", "onClick"])
                ]),
                default: withCtx(() => [
                  createBaseVNode("div", {
                    ref_for: true,
                    ref: index2 === taskPanels.value.length - 1 ? (el) => lastPanelRef.value = el : void 0,
                    class: normalizeClass(["overflow-y-auto h-64 rounded-lg bg-black", {
                      "h-64": index2 !== taskPanels.value.length - 1,
                      "flex-grow": index2 === taskPanels.value.length - 1
                    }]),
                    onScroll: handleScroll
                  }, [
                    createBaseVNode("div", _hoisted_4$u, [
                      (openBlock(true), createElementBlock(Fragment$1, null, renderList(panel.logs, (log2, logIndex) => {
                        return openBlock(), createElementBlock("div", {
                          key: logIndex,
                          class: "text-neutral-400 dark-theme:text-muted"
                        }, [
                          createBaseVNode("pre", _hoisted_5$o, toDisplayString(log2), 1)
                        ]);
                      }), 128))
                    ])
                  ], 34)
                ]),
                _: 2
              }, 1032, ["expanded"])
            ]);
          }), 128))
        ], 2)
      ], 2);
    };
  }
});
function useCivitaiModel(url) {
  const createModelVersionUrl = /* @__PURE__ */ __name((modelId) => `https://civitai.com/api/v1/model-versions/${modelId}`, "createModelVersionUrl");
  const extractModelIdFromUrl = /* @__PURE__ */ __name(() => {
    const urlObj = new URL(url);
    return urlObj.pathname.split("/").pop() || null;
  }, "extractModelIdFromUrl");
  const fetchModelData = /* @__PURE__ */ __name(async () => {
    const modelId = extractModelIdFromUrl();
    if (!modelId) return null;
    const apiUrl = createModelVersionUrl(modelId);
    const res = await fetch(apiUrl);
    return res.json();
  }, "fetchModelData");
  const findMatchingFileSize = /* @__PURE__ */ __name(() => {
    const matchingFile = modelData.value?.files?.find(
      (file) => file.downloadUrl && url.startsWith(file.downloadUrl)
    );
    return matchingFile?.sizeKB ? matchingFile.sizeKB << 10 : null;
  }, "findMatchingFileSize");
  const {
    state: modelData,
    isLoading,
    error: error2
  } = useAsyncState(fetchModelData, null, {
    immediate: true
  });
  const fileSize = computed(
    () => !isLoading.value ? findMatchingFileSize() : null
  );
  return {
    fileSize,
    isLoading,
    error: error2,
    modelData
  };
}
__name(useCivitaiModel, "useCivitaiModel");
function useDownload(url, fileName) {
  const fileSize = ref$3(null);
  const error2 = ref$3(null);
  const setFileSize = /* @__PURE__ */ __name((size) => {
    fileSize.value = size;
  }, "setFileSize");
  const fetchFileSize = /* @__PURE__ */ __name(async () => {
    try {
      const response = await fetch(url, { method: "HEAD" });
      if (!response.ok) throw new Error("Failed to fetch file size");
      const size = response.headers.get("content-length");
      if (size) {
        setFileSize(parseInt(size));
      } else {
        console.error('"content-length" header not found');
        return null;
      }
    } catch (e2) {
      console.error("Error fetching file size:", e2);
      error2.value = e2 instanceof Error ? e2 : new Error(String(e2));
      return null;
    }
  }, "fetchFileSize");
  const triggerBrowserDownload = /* @__PURE__ */ __name(() => {
    const link2 = document.createElement("a");
    if (url.includes("huggingface.co") && error2.value) {
      link2.href = downloadUrlToHfRepoUrl(url);
    } else {
      link2.href = url;
      link2.download = fileName || url.split("/").pop() || "download";
    }
    link2.target = "_blank";
    link2.rel = "noopener noreferrer";
    link2.click();
  }, "triggerBrowserDownload");
  onMounted(() => {
    if (isCivitaiModelUrl(url)) {
      const { fileSize: civitaiSize, error: civitaiErr } = useCivitaiModel(url);
      whenever(civitaiSize, setFileSize);
      whenever(civitaiErr, fetchFileSize, { once: true });
    } else {
      void fetchFileSize();
    }
  });
  return {
    triggerBrowserDownload,
    fileSize
  };
}
__name(useDownload, "useDownload");
const IPC_CHANNELS = {
  LOADING_PROGRESS: "loading-progress",
  IS_PACKAGED: "is-packaged",
  RENDERER_READY: "renderer-ready",
  RESTART_APP: "restart-app",
  REINSTALL: "reinstall",
  QUIT: "quit",
  LOG_MESSAGE: "log-message",
  DOWNLOAD_PROGRESS: "download-progress",
  START_DOWNLOAD: "start-download",
  PAUSE_DOWNLOAD: "pause-download",
  RESUME_DOWNLOAD: "resume-download",
  CANCEL_DOWNLOAD: "cancel-download",
  DELETE_MODEL: "delete-model",
  GET_ALL_DOWNLOADS: "get-all-downloads",
  GET_ELECTRON_VERSION: "get-electron-version",
  GET_BASE_PATH: "get-base-path",
  SET_BASE_PATH: "set-base-path",
  GET_MODEL_CONFIG_PATH: "get-model-config-path",
  OPEN_PATH: "open-path",
  OPEN_LOGS_PATH: "open-logs-path",
  OPEN_DEV_TOOLS: "open-dev-tools",
  TERMINAL_WRITE: "execute-terminal-command",
  TERMINAL_RESIZE: "resize-terminal",
  TERMINAL_RESTORE: "restore-terminal",
  TERMINAL_ON_OUTPUT: "terminal-output",
  GET_SYSTEM_PATHS: "get-system-paths",
  VALIDATE_INSTALL_PATH: "validate-install-path",
  VALIDATE_COMFYUI_SOURCE: "validate-comfyui-source",
  SHOW_DIRECTORY_PICKER: "show-directory-picker",
  INSTALL_COMFYUI: "install-comfyui",
  CHANGE_THEME: "change-theme",
  SHOW_CONTEXT_MENU: "show-context-menu",
  RESTART_CORE: "restart-core",
  GET_GPU: "get-gpu",
  SET_WINDOW_STYLE: "set-window-style",
  GET_VALIDATION_STATE: "get-validation-state",
  VALIDATION_UPDATE: "validation-update",
  COMPLETE_VALIDATION: "complete-validation",
  CANCEL_VALIDATION: "cancel-validation",
  VALIDATE_INSTALLATION: "start-validation",
  UV_INSTALL_REQUIREMENTS: "uv-install-requirements",
  GET_WINDOW_STYLE: "get-window-style",
  TRACK_EVENT: "track-event",
  SET_METRICS_CONSENT: "set-metrics-consent",
  INCREMENT_USER_PROPERTY: "increment-user-property",
  UV_CLEAR_CACHE: "uv-clear-cache",
  UV_RESET_VENV: "uv-delete-venv",
  CAN_ACCESS_URL: "can-access-url",
  START_TROUBLESHOOTING: "start-troubleshooting",
  DISABLE_CUSTOM_NODES: "disable-custom-nodes",
  CHECK_FOR_UPDATES: "check-for-updates",
  RESTART_AND_INSTALL: "restart-and-install",
  CHECK_BLACKWELL: "check-blackwell"
};
var ProgressStatus = /* @__PURE__ */ ((ProgressStatus2) => {
  ProgressStatus2["INITIAL_STATE"] = "initial-state";
  ProgressStatus2["PYTHON_SETUP"] = "python-setup";
  ProgressStatus2["STARTING_SERVER"] = "starting-server";
  ProgressStatus2["READY"] = "ready";
  ProgressStatus2["ERROR"] = "error";
  return ProgressStatus2;
})(ProgressStatus || {});
const ELECTRON_BRIDGE_API = "electronAPI";
const SENTRY_URL_ENDPOINT = "https://942cadba58d247c9cab96f45221aa813@o4507954455314432.ingest.us.sentry.io/4508007940685824";
const MigrationItems = [
  {
    id: "user_files",
    label: "User Files",
    description: "Settings and user-created workflows"
  },
  {
    id: "models",
    label: "Models",
    description: "Reference model files from existing ComfyUI installations. (No copy)"
  },
  {
    id: "custom_nodes",
    label: "Custom Nodes",
    description: "Reinstall custom nodes from existing ComfyUI installations."
  }
];
const DEFAULT_SERVER_ARGS = {
  listen: "127.0.0.1",
  port: "8000"
};
var DownloadStatus = /* @__PURE__ */ ((DownloadStatus2) => {
  DownloadStatus2["PENDING"] = "pending";
  DownloadStatus2["IN_PROGRESS"] = "in_progress";
  DownloadStatus2["COMPLETED"] = "completed";
  DownloadStatus2["PAUSED"] = "paused";
  DownloadStatus2["ERROR"] = "error";
  DownloadStatus2["CANCELLED"] = "cancelled";
  return DownloadStatus2;
})(DownloadStatus || {});
var TorchMirrorUrl = /* @__PURE__ */ ((TorchMirrorUrl2) => {
  TorchMirrorUrl2["Default"] = "https://pypi.org/simple/";
  TorchMirrorUrl2["Cuda"] = "https://download.pytorch.org/whl/cu128";
  TorchMirrorUrl2["NightlyCuda"] = "https://download.pytorch.org/whl/nightly/cu128";
  TorchMirrorUrl2["NightlyCpu"] = "https://download.pytorch.org/whl/nightly/cpu";
  return TorchMirrorUrl2;
})(TorchMirrorUrl || {});
const CUDA_TORCH_URL = "https://download.pytorch.org/whl/cu128";
const NIGHTLY_CPU_TORCH_URL = "https://download.pytorch.org/whl/nightly/cpu";
const DEFAULT_PYPI_INDEX_URL = "https://pypi.org/simple/";
var LogFile = /* @__PURE__ */ ((LogFile2) => {
  LogFile2["ComfyUI"] = "comfyui.log";
  LogFile2["Main"] = "main.log";
  return LogFile2;
})(LogFile || {});
const useElectronDownloadStore = /* @__PURE__ */ defineStore("downloads", () => {
  const downloads = ref$3([]);
  const { DownloadManager } = electronAPI();
  const findByUrl = /* @__PURE__ */ __name((url) => downloads.value.find((download2) => url === download2.url), "findByUrl");
  const initialize = /* @__PURE__ */ __name(async () => {
    if (isElectron()) {
      const allDownloads = await DownloadManager.getAllDownloads();
      for (const download2 of allDownloads) {
        downloads.value.push(download2);
      }
      DownloadManager.onDownloadProgress((data) => {
        if (!findByUrl(data.url)) {
          downloads.value.push(data);
        }
        const download2 = findByUrl(data.url);
        if (download2) {
          download2.progress = data.progress;
          download2.status = data.status;
          download2.filename = data.filename;
          download2.savePath = data.savePath;
        }
      });
    }
  }, "initialize");
  void initialize();
  const start2 = /* @__PURE__ */ __name(({
    url,
    savePath,
    filename
  }) => DownloadManager.startDownload(url, savePath, filename), "start");
  const pause = /* @__PURE__ */ __name((url) => DownloadManager.pauseDownload(url), "pause");
  const resume = /* @__PURE__ */ __name((url) => DownloadManager.resumeDownload(url), "resume");
  const cancel = /* @__PURE__ */ __name((url) => DownloadManager.cancelDownload(url), "cancel");
  return {
    downloads,
    start: start2,
    pause,
    resume,
    cancel,
    findByUrl,
    initialize,
    inProgressDownloads: computed(
      () => downloads.value.filter(
        ({ status }) => status !== DownloadStatus.COMPLETED
      )
    )
  };
});
const _hoisted_1$1k = { class: "flex flex-col" };
const _hoisted_2$Y = { class: "flex flex-row items-center gap-2" };
const _hoisted_3$G = {
  key: 0,
  class: "pi pi-check text-green-500"
};
const _hoisted_4$t = { class: "file-info" };
const _hoisted_5$n = { class: "file-details" };
const _hoisted_6$i = ["title"];
const _hoisted_7$c = {
  key: 0,
  class: "file-error"
};
const _hoisted_8$9 = { class: "file-action" };
const _hoisted_9$7 = {
  key: 0,
  class: "flex flex-row items-center gap-2"
};
const _sfc_main$1G = /* @__PURE__ */ defineComponent({
  __name: "ElectronFileDownload",
  props: {
    url: {},
    hint: {},
    label: {},
    error: {}
  },
  setup(__props) {
    const props = __props;
    const { t: t2 } = useI18n();
    const label = computed(() => props.label || props.url.split("/").pop());
    const hint = computed(() => props.hint || props.url);
    const download2 = useDownload(props.url);
    const downloadProgress = ref$3(0);
    const status = ref$3(null);
    const fileSize = computed(
      () => download2.fileSize.value ? formatSize(download2.fileSize.value) : "?"
    );
    const electronDownloadStore = useElectronDownloadStore();
    const [savePath, filename] = props.label.split("/");
    electronDownloadStore.$subscribe((_2, { downloads }) => {
      const download22 = downloads.find((download3) => props.url === download3.url);
      if (download22) {
        downloadProgress.value = Number((download22.progress * 100).toFixed(1));
        status.value = download22.status;
      }
    });
    const triggerDownload = /* @__PURE__ */ __name(async () => {
      await electronDownloadStore.start({
        url: props.url,
        savePath: savePath.trim(),
        filename: filename.trim()
      });
    }, "triggerDownload");
    const triggerCancelDownload = /* @__PURE__ */ __name(() => electronDownloadStore.cancel(props.url), "triggerCancelDownload");
    const triggerPauseDownload = /* @__PURE__ */ __name(() => electronDownloadStore.pause(props.url), "triggerPauseDownload");
    const triggerResumeDownload = /* @__PURE__ */ __name(() => electronDownloadStore.resume(props.url), "triggerResumeDownload");
    return (_ctx, _cache) => {
      const _directive_tooltip = resolveDirective("tooltip");
      return openBlock(), createElementBlock("div", _hoisted_1$1k, [
        createBaseVNode("div", _hoisted_2$Y, [
          status.value === "completed" ? (openBlock(), createElementBlock("i", _hoisted_3$G)) : createCommentVNode("", true),
          createBaseVNode("div", _hoisted_4$t, [
            createBaseVNode("div", _hoisted_5$n, [
              createBaseVNode("span", {
                class: "file-type",
                title: hint.value
              }, toDisplayString(label.value), 9, _hoisted_6$i)
            ]),
            props.error ? (openBlock(), createElementBlock("div", _hoisted_7$c, toDisplayString(props.error), 1)) : createCommentVNode("", true)
          ]),
          createBaseVNode("div", _hoisted_8$9, [
            status.value === null || status.value === "error" ? (openBlock(), createBlock(unref(script$6), {
              key: 0,
              class: "file-action-button",
              label: _ctx.$t("g.download") + " (" + fileSize.value + ")",
              size: "small",
              outlined: "",
              disabled: !!props.error,
              icon: "pi pi-download",
              onClick: triggerDownload
            }, null, 8, ["label", "disabled"])) : createCommentVNode("", true)
          ])
        ]),
        status.value === "in_progress" || status.value === "paused" ? (openBlock(), createElementBlock("div", _hoisted_9$7, [
          createVNode(unref(script$h), {
            class: "flex-1",
            value: downloadProgress.value,
            "show-value": downloadProgress.value > 10
          }, null, 8, ["value", "show-value"]),
          status.value === "in_progress" ? withDirectives((openBlock(), createBlock(unref(script$6), {
            key: 0,
            class: "file-action-button",
            size: "small",
            outlined: "",
            disabled: !!props.error,
            icon: "pi pi-pause-circle",
            onClick: triggerPauseDownload
          }, null, 8, ["disabled"])), [
            [
              _directive_tooltip,
              unref(t2)("electronFileDownload.pause"),
              void 0,
              { top: true }
            ]
          ]) : createCommentVNode("", true),
          status.value === "paused" ? withDirectives((openBlock(), createBlock(unref(script$6), {
            key: 1,
            class: "file-action-button",
            size: "small",
            outlined: "",
            disabled: !!props.error,
            icon: "pi pi-play-circle",
            onClick: triggerResumeDownload
          }, null, 8, ["disabled"])), [
            [
              _directive_tooltip,
              unref(t2)("electronFileDownload.resume"),
              void 0,
              { top: true }
            ]
          ]) : createCommentVNode("", true),
          withDirectives(createVNode(unref(script$6), {
            class: "file-action-button",
            size: "small",
            outlined: "",
            disabled: !!props.error,
            icon: "pi pi-times-circle",
            severity: "danger",
            onClick: triggerCancelDownload
          }, null, 8, ["disabled"]), [
            [
              _directive_tooltip,
              unref(t2)("electronFileDownload.cancel"),
              void 0,
              { top: true }
            ]
          ])
        ])) : createCommentVNode("", true)
      ]);
    };
  }
});
const _hoisted_1$1j = { class: "flex flex-row items-center gap-2" };
const _hoisted_2$X = ["title"];
const _sfc_main$1F = /* @__PURE__ */ defineComponent({
  __name: "FileDownload",
  props: {
    url: {},
    hint: {},
    label: {},
    error: {}
  },
  setup(__props) {
    const props = __props;
    const label = computed(() => props.label || props.url.split("/").pop());
    const hint = computed(() => props.hint || props.url);
    const download2 = useDownload(props.url);
    const fileSize = computed(
      () => download2.fileSize.value ? formatSize(download2.fileSize.value) : "?"
    );
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", _hoisted_1$1j, [
        createBaseVNode("div", null, [
          createBaseVNode("div", null, [
            createBaseVNode("span", { title: hint.value }, toDisplayString(label.value), 9, _hoisted_2$X)
          ]),
          props.error ? (openBlock(), createBlock(unref(script$8), {
            key: 0,
            severity: "error",
            icon: "pi pi-exclamation-triangle",
            size: "small",
            variant: "outlined",
            class: "h-min my-2 px-1 max-w-xs",
            title: props.error,
            pt: {
              text: { class: "overflow-hidden text-ellipsis" }
            }
          }, {
            default: withCtx(() => [
              createTextVNode(toDisplayString(props.error), 1)
            ]),
            _: 1
          }, 8, ["title"])) : createCommentVNode("", true)
        ]),
        createBaseVNode("div", null, [
          createVNode(unref(script$6), {
            label: _ctx.$t("g.download") + " (" + fileSize.value + ")",
            size: "small",
            outlined: "",
            disabled: !!props.error,
            title: props.url,
            onClick: unref(download2).triggerBrowserDownload
          }, null, 8, ["label", "disabled", "title", "onClick"])
        ])
      ]);
    };
  }
});
const getSettingInfo = /* @__PURE__ */ __name((setting) => {
  const parts2 = setting.category || setting.id.split(".");
  return {
    category: parts2[0] ?? "Other",
    subCategory: parts2[1] ?? "Other"
  };
}, "getSettingInfo");
function tryMigrateDeprecatedValue(setting, value) {
  return setting?.migrateDeprecatedValue?.(value) ?? value;
}
__name(tryMigrateDeprecatedValue, "tryMigrateDeprecatedValue");
function onChange(setting, newValue2, oldValue) {
  if (setting?.onChange) {
    setting.onChange(newValue2, oldValue);
  }
  app$1.ui.settings.dispatchChange(setting.id, newValue2, oldValue);
}
__name(onChange, "onChange");
const useSettingStore = /* @__PURE__ */ defineStore("setting", () => {
  const settingValues = ref$3({});
  const settingsById = ref$3({});
  function exists(key) {
    return settingValues.value[key] !== void 0;
  }
  __name(exists, "exists");
  async function set3(key, value) {
    const clonedValue = _.cloneDeep(value);
    const newValue2 = tryMigrateDeprecatedValue(
      settingsById.value[key],
      clonedValue
    );
    const oldValue = get3(key);
    if (newValue2 === oldValue) return;
    onChange(settingsById.value[key], newValue2, oldValue);
    settingValues.value[key] = newValue2;
    await api.storeSetting(key, newValue2);
  }
  __name(set3, "set");
  function get3(key) {
    return _.cloneDeep(settingValues.value[key] ?? getDefaultValue2(key));
  }
  __name(get3, "get");
  function getDefaultValue2(key) {
    const param = settingsById.value[key];
    return typeof param?.defaultValue === "function" ? param.defaultValue() : param?.defaultValue;
  }
  __name(getDefaultValue2, "getDefaultValue");
  function addSetting(setting) {
    if (!setting.id) {
      throw new Error("Settings must have an ID");
    }
    if (setting.id in settingsById.value) {
      throw new Error(`Setting ${setting.id} must have a unique ID.`);
    }
    settingsById.value[setting.id] = setting;
    if (settingValues.value[setting.id] !== void 0) {
      settingValues.value[setting.id] = tryMigrateDeprecatedValue(
        setting,
        settingValues.value[setting.id]
      );
    }
    onChange(setting, get3(setting.id), void 0);
  }
  __name(addSetting, "addSetting");
  async function loadSettingValues() {
    if (Object.keys(settingsById.value).length) {
      throw new Error(
        "Setting values must be loaded before any setting is registered."
      );
    }
    settingValues.value = await api.getSettings();
  }
  __name(loadSettingValues, "loadSettingValues");
  return {
    settingValues,
    settingsById,
    addSetting,
    loadSettingValues,
    set: set3,
    get: get3,
    exists,
    getDefaultValue: getDefaultValue2
  };
});
const _hoisted_1$1i = { class: "flex gap-1 mb-4" };
const _hoisted_2$W = { for: "doNotAskAgain" };
const _sfc_main$1E = /* @__PURE__ */ defineComponent({
  __name: "MissingModelsWarning",
  props: {
    missingModels: {},
    paths: {}
  },
  setup(__props) {
    const allowedSources = [
      "https://civitai.com/",
      "https://huggingface.co/",
      "http://localhost:"
      // Included for testing usage only
    ];
    const allowedSuffixes = [".safetensors", ".sft"];
    const whiteListedUrls = /* @__PURE__ */ new Set([
      "https://huggingface.co/stabilityai/stable-zero123/resolve/main/stable_zero123.ckpt",
      "https://huggingface.co/TencentARC/T2I-Adapter/resolve/main/models/t2iadapter_depth_sd14v1.pth?download=true",
      "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth"
    ]);
    const props = __props;
    const { t: t2 } = useI18n();
    const doNotAskAgain = ref$3(false);
    const modelDownloads = ref$3({});
    const missingModels = computed(() => {
      return props.missingModels.map((model) => {
        const paths = props.paths[model.directory];
        if (model.directory_invalid || !paths) {
          return {
            label: `${model.directory} / ${model.name}`,
            url: model.url,
            error: "Invalid directory specified (does this require custom nodes?)"
          };
        }
        const downloadInfo = modelDownloads.value[model.name] ?? {
          downloading: false,
          completed: false,
          progress: 0,
          error: null,
          name: model.name,
          directory: model.directory,
          url: model.url,
          folder_path: paths[0]
        };
        modelDownloads.value[model.name] = downloadInfo;
        if (!whiteListedUrls.has(model.url)) {
          if (!allowedSources.some((source) => model.url.startsWith(source))) {
            return {
              label: `${model.directory} / ${model.name}`,
              url: model.url,
              error: `Download not allowed from source '${model.url}', only allowed from '${allowedSources.join("', '")}'`
            };
          }
          if (!allowedSuffixes.some((suffix) => model.name.endsWith(suffix))) {
            return {
              label: `${model.directory} / ${model.name}`,
              url: model.url,
              error: `Only allowed suffixes are: '${allowedSuffixes.join("', '")}'`
            };
          }
        }
        return {
          url: model.url,
          label: `${model.directory} / ${model.name}`,
          downloading: downloadInfo.downloading,
          completed: downloadInfo.completed,
          progress: downloadInfo.progress,
          error: downloadInfo.error,
          name: model.name,
          paths,
          folderPath: downloadInfo.folder_path
        };
      });
    });
    onBeforeUnmount(async () => {
      if (doNotAskAgain.value) {
        await useSettingStore().set(
          "Comfy.Workflow.ShowMissingModelsWarning",
          false
        );
      }
    });
    return (_ctx, _cache) => {
      const _component_ElectronFileDownload = _sfc_main$1G;
      return openBlock(), createElementBlock(Fragment$1, null, [
        createVNode(NoResultsPlaceholder, {
          class: "pb-0",
          icon: "pi pi-exclamation-circle",
          title: unref(t2)("missingModelsDialog.missingModels"),
          message: unref(t2)("missingModelsDialog.missingModelsMessage")
        }, null, 8, ["title", "message"]),
        createBaseVNode("div", _hoisted_1$1i, [
          createVNode(unref(script$d), {
            modelValue: doNotAskAgain.value,
            "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => doNotAskAgain.value = $event),
            binary: "",
            "input-id": "doNotAskAgain"
          }, null, 8, ["modelValue"]),
          createBaseVNode("label", _hoisted_2$W, toDisplayString(unref(t2)("missingModelsDialog.doNotAskAgain")), 1)
        ]),
        createVNode(unref(script$g), {
          options: missingModels.value,
          class: "comfy-missing-models"
        }, {
          option: withCtx(({ option }) => [
            unref(isElectron)() ? (openBlock(), createBlock(Suspense, { key: 0 }, {
              default: withCtx(() => [
                createVNode(_component_ElectronFileDownload, {
                  url: option.url,
                  label: option.label,
                  error: option.error
                }, null, 8, ["url", "label", "error"])
              ]),
              _: 2
            }, 1024)) : (openBlock(), createBlock(_sfc_main$1F, {
              key: 1,
              url: option.url,
              label: option.label,
              error: option.error
            }, null, 8, ["url", "label", "error"]))
          ]),
          _: 1
        }, 8, ["options"])
      ], 64);
    };
  }
});
const MissingModelsWarning = /* @__PURE__ */ _export_sfc(_sfc_main$1E, [["__scopeId", "data-v-7a5ec643"]]);
const _hoisted_1$1h = { class: "prompt-dialog-content flex flex-col gap-2 pt-8" };
const _sfc_main$1D = /* @__PURE__ */ defineComponent({
  __name: "PromptDialogContent",
  props: {
    message: {},
    defaultValue: {},
    onConfirm: { type: Function }
  },
  setup(__props) {
    const props = __props;
    const inputValue = ref$3(props.defaultValue);
    const onConfirm = /* @__PURE__ */ __name(() => {
      props.onConfirm(inputValue.value);
      useDialogStore().closeDialog();
    }, "onConfirm");
    const inputRef = ref$3();
    const selectAllText = /* @__PURE__ */ __name(() => {
      if (!inputRef.value) return;
      const inputElement = inputRef.value.$el;
      inputElement.setSelectionRange(0, inputElement.value.length);
    }, "selectAllText");
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", _hoisted_1$1h, [
        createVNode(unref(script$i), null, {
          default: withCtx(() => [
            createVNode(unref(script$b), {
              ref_key: "inputRef",
              ref: inputRef,
              modelValue: inputValue.value,
              "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => inputValue.value = $event),
              autofocus: "",
              onKeyup: withKeys(onConfirm, ["enter"]),
              onFocus: selectAllText
            }, null, 8, ["modelValue"]),
            createBaseVNode("label", null, toDisplayString(_ctx.message), 1)
          ]),
          _: 1
        }),
        createVNode(unref(script$6), { onClick: onConfirm }, {
          default: withCtx(() => [
            createTextVNode(toDisplayString(_ctx.$t("g.confirm")), 1)
          ]),
          _: 1
        })
      ]);
    };
  }
});
const _sfc_main$1C = /* @__PURE__ */ defineComponent({
  __name: "SearchFilterChip",
  props: {
    text: {},
    badge: {},
    badgeClass: {}
  },
  emits: ["remove"],
  setup(__props) {
    return (_ctx, _cache) => {
      return openBlock(), createBlock(unref(script$k), {
        removable: "",
        onRemove: _cache[0] || (_cache[0] = ($event) => _ctx.$emit("remove", $event))
      }, {
        default: withCtx(() => [
          createVNode(unref(script$j), {
            size: "small",
            class: normalizeClass(_ctx.badgeClass)
          }, {
            default: withCtx(() => [
              createTextVNode(toDisplayString(_ctx.badge), 1)
            ]),
            _: 1
          }, 8, ["class"]),
          createTextVNode(" " + toDisplayString(_ctx.text), 1)
        ]),
        _: 1
      });
    };
  }
});
const SearchFilterChip = /* @__PURE__ */ _export_sfc(_sfc_main$1C, [["__scopeId", "data-v-53692f7e"]]);
const _hoisted_1$1g = {
  key: 0,
  class: "search-filters pt-2 flex flex-wrap gap-2"
};
const _sfc_main$1B = /* @__PURE__ */ defineComponent({
  __name: "SearchBox",
  props: {
    modelValue: {},
    placeholder: { default: "Search..." },
    icon: { default: "pi pi-search" },
    debounceTime: { default: 300 },
    filterIcon: {},
    filters: { default: /* @__PURE__ */ __name(() => [], "default") }
  },
  emits: ["update:modelValue", "search", "showFilter", "removeFilter"],
  setup(__props, { emit: __emit }) {
    const emit = __emit;
    const emitSearch = lodashExports.debounce((value) => {
      emit("search", value, __props.filters);
    }, __props.debounceTime);
    const handleInput = /* @__PURE__ */ __name((event) => {
      const target = event.target;
      emit("update:modelValue", target.value);
      emitSearch(target.value);
    }, "handleInput");
    const clearSearch = /* @__PURE__ */ __name(() => {
      emit("update:modelValue", "");
      emitSearch("");
    }, "clearSearch");
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", null, [
        createVNode(unref(script$l), null, {
          default: withCtx(() => [
            _ctx.filterIcon ? (openBlock(), createBlock(unref(script$6), {
              key: 0,
              class: "p-inputicon filter-button",
              icon: _ctx.filterIcon,
              text: "",
              severity: "contrast",
              onClick: _cache[0] || (_cache[0] = ($event) => _ctx.$emit("showFilter", $event))
            }, null, 8, ["icon"])) : createCommentVNode("", true),
            createVNode(unref(script$b), {
              class: "search-box-input w-full",
              "model-value": _ctx.modelValue,
              placeholder: _ctx.placeholder,
              onInput: handleInput
            }, null, 8, ["model-value", "placeholder"]),
            !_ctx.modelValue ? (openBlock(), createBlock(unref(script$m), {
              key: 1,
              class: normalizeClass(_ctx.icon)
            }, null, 8, ["class"])) : createCommentVNode("", true),
            _ctx.modelValue ? (openBlock(), createBlock(unref(script$6), {
              key: 2,
              class: "p-inputicon clear-button",
              icon: "pi pi-times",
              text: "",
              severity: "contrast",
              onClick: clearSearch
            })) : createCommentVNode("", true)
          ]),
          _: 1
        }),
        _ctx.filters?.length ? (openBlock(), createElementBlock("div", _hoisted_1$1g, [
          (openBlock(true), createElementBlock(Fragment$1, null, renderList(_ctx.filters, (filter3) => {
            return openBlock(), createBlock(SearchFilterChip, {
              key: filter3.id,
              text: filter3.text,
              badge: filter3.badge,
              "badge-class": filter3.badgeClass,
              onRemove: /* @__PURE__ */ __name(($event) => _ctx.$emit("removeFilter", filter3), "onRemove")
            }, null, 8, ["text", "badge", "badge-class", "onRemove"]);
          }), 128))
        ])) : createCommentVNode("", true)
      ]);
    };
  }
});
const SearchBox = /* @__PURE__ */ _export_sfc(_sfc_main$1B, [["__scopeId", "data-v-dada3cdf"]]);
const useFirebaseAuthActions = /* @__PURE__ */ __name(() => {
  const authStore = useFirebaseAuthStore();
  const toastStore = useToastStore();
  const { wrapWithErrorHandlingAsync, toastErrorHandler } = useErrorHandling();
  const accessError = ref$3(false);
  const reportError = /* @__PURE__ */ __name((error2) => {
    if (error2 instanceof FirebaseError && [
      "auth/unauthorized-domain",
      "auth/invalid-dynamic-link-domain",
      "auth/unauthorized-continue-uri"
    ].includes(error2.code)) {
      accessError.value = true;
      toastStore.add({
        severity: "error",
        summary: t("g.error"),
        detail: t("toastMessages.unauthorizedDomain", {
          domain: window.location.hostname,
          email: "support@comfy.org"
        })
      });
    } else {
      toastErrorHandler(error2);
    }
  }, "reportError");
  const logout = wrapWithErrorHandlingAsync(async () => {
    await authStore.logout();
    toastStore.add({
      severity: "success",
      summary: t("auth.signOut.success"),
      detail: t("auth.signOut.successDetail"),
      life: 5e3
    });
  }, reportError);
  const sendPasswordReset = wrapWithErrorHandlingAsync(
    async (email) => {
      await authStore.sendPasswordReset(email);
      toastStore.add({
        severity: "success",
        summary: t("auth.login.passwordResetSent"),
        detail: t("auth.login.passwordResetSentDetail"),
        life: 5e3
      });
    },
    reportError
  );
  const purchaseCredits = wrapWithErrorHandlingAsync(async (amount) => {
    const response = await authStore.initiateCreditPurchase({
      amount_micros: usdToMicros(amount),
      currency: "usd"
    });
    if (!response.checkout_url) {
      throw new Error(
        t("toastMessages.failedToPurchaseCredits", {
          error: "No checkout URL returned"
        })
      );
    }
    window.open(response.checkout_url, "_blank");
  }, reportError);
  const accessBillingPortal = wrapWithErrorHandlingAsync(async () => {
    const response = await authStore.accessBillingPortal();
    if (!response.billing_portal_url) {
      throw new Error(
        t("toastMessages.failedToAccessBillingPortal", {
          error: "No billing portal URL returned"
        })
      );
    }
    window.open(response.billing_portal_url, "_blank");
  }, reportError);
  const fetchBalance = wrapWithErrorHandlingAsync(async () => {
    return await authStore.fetchBalance();
  }, reportError);
  const signInWithGoogle = wrapWithErrorHandlingAsync(async () => {
    return await authStore.loginWithGoogle();
  }, reportError);
  const signInWithGithub = wrapWithErrorHandlingAsync(async () => {
    return await authStore.loginWithGithub();
  }, reportError);
  const signInWithEmail = wrapWithErrorHandlingAsync(
    async (email, password) => {
      return await authStore.login(email, password);
    },
    reportError
  );
  const signUpWithEmail = wrapWithErrorHandlingAsync(
    async (email, password) => {
      return await authStore.register(email, password);
    },
    reportError
  );
  const updatePassword2 = wrapWithErrorHandlingAsync(
    async (newPassword) => {
      await authStore.updatePassword(newPassword);
      toastStore.add({
        severity: "success",
        summary: t("auth.passwordUpdate.success"),
        detail: t("auth.passwordUpdate.successDetail"),
        life: 5e3
      });
    },
    reportError
  );
  return {
    logout,
    sendPasswordReset,
    purchaseCredits,
    accessBillingPortal,
    fetchBalance,
    signInWithGoogle,
    signInWithGithub,
    signInWithEmail,
    signUpWithEmail,
    updatePassword: updatePassword2,
    accessError
  };
}, "useFirebaseAuthActions");
function useSettingSearch() {
  const settingStore = useSettingStore();
  const searchQuery = ref$3("");
  const filteredSettingIds = ref$3([]);
  const searchInProgress = ref$3(false);
  watch(searchQuery, () => searchInProgress.value = true);
  const searchResultsCategories = computed(() => {
    return new Set(
      filteredSettingIds.value.map(
        (id2) => getSettingInfo(settingStore.settingsById[id2]).category
      )
    );
  });
  const queryIsEmpty = computed(() => searchQuery.value.length === 0);
  const inSearch = computed(
    () => !queryIsEmpty.value && !searchInProgress.value
  );
  const handleSearch = /* @__PURE__ */ __name((query2) => {
    if (!query2) {
      filteredSettingIds.value = [];
      return;
    }
    const queryLower = query2.toLocaleLowerCase();
    const allSettings = Object.values(settingStore.settingsById);
    const filteredSettings = allSettings.filter((setting) => {
      const idLower = setting.id.toLowerCase();
      const nameLower = setting.name.toLowerCase();
      const translatedName = st(
        `settings.${normalizeI18nKey(setting.id)}.name`,
        setting.name
      ).toLocaleLowerCase();
      const info = getSettingInfo(setting);
      const translatedCategory = st(
        `settingsCategories.${normalizeI18nKey(info.category)}`,
        info.category
      ).toLocaleLowerCase();
      const translatedSubCategory = st(
        `settingsCategories.${normalizeI18nKey(info.subCategory)}`,
        info.subCategory
      ).toLocaleLowerCase();
      return idLower.includes(queryLower) || nameLower.includes(queryLower) || translatedName.includes(queryLower) || translatedCategory.includes(queryLower) || translatedSubCategory.includes(queryLower);
    });
    filteredSettingIds.value = filteredSettings.map((x2) => x2.id);
    searchInProgress.value = false;
  }, "handleSearch");
  const getSearchResults = /* @__PURE__ */ __name((activeCategory) => {
    const groupedSettings = {};
    filteredSettingIds.value.forEach((id2) => {
      const setting = settingStore.settingsById[id2];
      const info = getSettingInfo(setting);
      const groupLabel = info.subCategory;
      if (activeCategory === null || activeCategory.label === info.category) {
        if (!groupedSettings[groupLabel]) {
          groupedSettings[groupLabel] = [];
        }
        groupedSettings[groupLabel].push(setting);
      }
    });
    return Object.entries(groupedSettings).map(([label, settings]) => ({
      label,
      settings
    }));
  }, "getSearchResults");
  return {
    searchQuery,
    filteredSettingIds,
    searchInProgress,
    searchResultsCategories,
    queryIsEmpty,
    inSearch,
    handleSearch,
    getSearchResults
  };
}
__name(useSettingSearch, "useSettingSearch");
function buildTree$1(items, key) {
  const root2 = {
    key: "root",
    label: "root",
    children: []
  };
  const map3 = {
    root: root2
  };
  for (const item of items) {
    const keys2 = key(item);
    let parent2 = root2;
    for (let i2 = 0; i2 < keys2.length; i2++) {
      const k2 = keys2[i2];
      if (k2 === "" && i2 === keys2.length - 1) break;
      const id2 = parent2.key + "/" + k2;
      if (!map3[id2]) {
        const node2 = {
          key: id2,
          label: k2,
          leaf: false,
          children: []
        };
        map3[id2] = node2;
        parent2.children?.push(node2);
      }
      parent2 = map3[id2];
    }
    parent2.leaf = keys2[keys2.length - 1] !== "";
    parent2.data = item;
  }
  return root2;
}
__name(buildTree$1, "buildTree$1");
function flattenTree(tree) {
  const result = [];
  const stack = [tree];
  while (stack.length) {
    const node2 = stack.pop();
    if (node2.leaf && node2.data) result.push(node2.data);
    stack.push(...node2.children ?? []);
  }
  return result;
}
__name(flattenTree, "flattenTree");
function sortedTree(node2, {
  groupLeaf = false
} = {}) {
  const newNode = {
    ...node2
  };
  if (node2.children) {
    if (groupLeaf) {
      const folders = node2.children.filter((child2) => !child2.leaf);
      const files = node2.children.filter((child2) => child2.leaf);
      const sortedFolders = folders.sort(
        (a2, b2) => (a2.label ?? "").localeCompare(b2.label ?? "")
      );
      const sortedFiles = files.sort(
        (a2, b2) => (a2.label ?? "").localeCompare(b2.label ?? "")
      );
      newNode.children = [
        ...sortedFolders.map(
          (folder) => sortedTree(folder, { groupLeaf: true })
        ),
        ...sortedFiles
      ];
    } else {
      const sortedChildren = [...node2.children].sort(
        (a2, b2) => (a2.label ?? "").localeCompare(b2.label ?? "")
      );
      newNode.children = [
        ...sortedChildren.map(
          (child2) => sortedTree(child2, { groupLeaf: false })
        )
      ];
    }
  }
  return newNode;
}
__name(sortedTree, "sortedTree");
const findNodeByKey = /* @__PURE__ */ __name((root2, key) => {
  if (root2.key === key) {
    return root2;
  }
  if (!root2.children) {
    return null;
  }
  for (const child2 of root2.children) {
    const result = findNodeByKey(child2, key);
    if (result) {
      return result;
    }
  }
  return null;
}, "findNodeByKey");
function cloneTree(node2) {
  const clone2 = { ...node2 };
  if (node2.children && node2.children.length > 0) {
    clone2.children = node2.children.map((child2) => cloneTree(child2));
  }
  return clone2;
}
__name(cloneTree, "cloneTree");
const combineTrees = /* @__PURE__ */ __name((root2, subtree) => {
  const newRoot = cloneTree(root2);
  const parentKey = subtree.key.slice(0, subtree.key.lastIndexOf("/"));
  const parent2 = findNodeByKey(newRoot, parentKey);
  if (parent2) {
    parent2.children ??= [];
    parent2.children.push(cloneTree(subtree));
  }
  return newRoot;
}, "combineTrees");
const useCurrentUser = /* @__PURE__ */ __name(() => {
  const authStore = useFirebaseAuthStore();
  const commandStore = useCommandStore();
  const apiKeyStore = useApiKeyAuthStore();
  const firebaseUser = computed(() => authStore.currentUser);
  const isApiKeyLogin = computed(() => apiKeyStore.isAuthenticated);
  const isLoggedIn = computed(
    () => !!isApiKeyLogin.value || firebaseUser.value !== null
  );
  const userDisplayName = computed(() => {
    if (isApiKeyLogin.value) {
      return apiKeyStore.currentUser?.name;
    }
    return firebaseUser.value?.displayName;
  });
  const userEmail = computed(() => {
    if (isApiKeyLogin.value) {
      return apiKeyStore.currentUser?.email;
    }
    return firebaseUser.value?.email;
  });
  const providerName = computed(() => {
    if (isApiKeyLogin.value) {
      return "Comfy API Key";
    }
    const providerId = firebaseUser.value?.providerData[0]?.providerId;
    if (providerId?.includes("google")) {
      return "Google";
    }
    if (providerId?.includes("github")) {
      return "GitHub";
    }
    return providerId;
  });
  const providerIcon = computed(() => {
    if (isApiKeyLogin.value) {
      return "pi pi-key";
    }
    const providerId = firebaseUser.value?.providerData[0]?.providerId;
    if (providerId?.includes("google")) {
      return "pi pi-google";
    }
    if (providerId?.includes("github")) {
      return "pi pi-github";
    }
    return "pi pi-user";
  });
  const isEmailProvider = computed(() => {
    if (isApiKeyLogin.value) {
      return false;
    }
    const providerId = firebaseUser.value?.providerData[0]?.providerId;
    return providerId === "password";
  });
  const userPhotoUrl = computed(() => {
    if (isApiKeyLogin.value) return null;
    return firebaseUser.value?.photoURL;
  });
  const handleSignOut = /* @__PURE__ */ __name(async () => {
    if (isApiKeyLogin.value) {
      await apiKeyStore.clearStoredApiKey();
    } else {
      await commandStore.execute("Comfy.User.SignOut");
    }
  }, "handleSignOut");
  const handleSignIn = /* @__PURE__ */ __name(async () => {
    await commandStore.execute("Comfy.User.OpenSignInDialog");
  }, "handleSignIn");
  return {
    loading: authStore.loading,
    isLoggedIn,
    isApiKeyLogin,
    isEmailProvider,
    userDisplayName,
    userEmail,
    userPhotoUrl,
    providerName,
    providerIcon,
    handleSignOut,
    handleSignIn
  };
}, "useCurrentUser");
function useSettingUI(defaultPanel) {
  const { t: t2 } = useI18n();
  const { isLoggedIn } = useCurrentUser();
  const settingStore = useSettingStore();
  const activeCategory = ref$3(null);
  const settingRoot = computed(() => {
    const root2 = buildTree$1(
      Object.values(settingStore.settingsById).filter(
        (setting) => setting.type !== "hidden"
      ),
      (setting) => setting.category || setting.id.split(".")
    );
    const floatingSettings = (root2.children ?? []).filter((node2) => node2.leaf);
    if (floatingSettings.length) {
      root2.children = (root2.children ?? []).filter((node2) => !node2.leaf);
      root2.children.push({
        key: "Other",
        label: "Other",
        leaf: false,
        children: floatingSettings
      });
    }
    return root2;
  });
  const settingCategories = computed(
    () => settingRoot.value.children ?? []
  );
  const aboutPanel = {
    node: {
      key: "about",
      label: "About",
      children: []
    },
    component: defineAsyncComponent(
      () => __vitePreload(() => import("./AboutPanel-Cq6ejTBZ.js"), true ? __vite__mapDeps([29,1,2,3]) : void 0, import.meta.url)
    )
  };
  const creditsPanel = {
    node: {
      key: "credits",
      label: "Credits",
      children: []
    },
    component: defineAsyncComponent(
      () => __vitePreload(() => import("./CreditsPanel-BnuIPg_X.js"), true ? __vite__mapDeps([30,1,2,3]) : void 0, import.meta.url)
    )
  };
  const userPanel = {
    node: {
      key: "user",
      label: "User",
      children: []
    },
    component: defineAsyncComponent(
      () => __vitePreload(() => import("./UserPanel-B_YCqmUQ.js"), true ? __vite__mapDeps([31,1,2,4,3]) : void 0, import.meta.url)
    )
  };
  const keybindingPanel = {
    node: {
      key: "keybinding",
      label: "Keybinding",
      children: []
    },
    component: defineAsyncComponent(
      () => __vitePreload(() => import("./KeybindingPanel-DH9CRsRH.js"), true ? __vite__mapDeps([32,1,2,3,5,33]) : void 0, import.meta.url)
    )
  };
  const extensionPanel = {
    node: {
      key: "extension",
      label: "Extension",
      children: []
    },
    component: defineAsyncComponent(
      () => __vitePreload(() => import("./ExtensionPanel-GFGmjfDu.js"), true ? __vite__mapDeps([34,1,2,3]) : void 0, import.meta.url)
    )
  };
  const serverConfigPanel = {
    node: {
      key: "server-config",
      label: "Server-Config",
      children: []
    },
    component: defineAsyncComponent(
      () => __vitePreload(() => import("./ServerConfigPanel-De4zH79o.js"), true ? __vite__mapDeps([35,1,2,3,6]) : void 0, import.meta.url)
    )
  };
  const panels = computed(
    () => [
      aboutPanel,
      creditsPanel,
      userPanel,
      keybindingPanel,
      extensionPanel,
      ...isElectron() ? [serverConfigPanel] : []
    ].filter((panel) => panel.component)
  );
  const defaultCategory = computed(() => {
    if (!defaultPanel) return settingCategories.value[0];
    for (const group of groupedMenuTreeNodes.value) {
      const found2 = group.children?.find((node2) => node2.key === defaultPanel);
      if (found2) return found2;
    }
    return settingCategories.value[0];
  });
  const translateCategory = /* @__PURE__ */ __name((node2) => ({
    ...node2,
    translatedLabel: t2(
      `settingsCategories.${normalizeI18nKey(node2.label)}`,
      node2.label
    )
  }), "translateCategory");
  const groupedMenuTreeNodes = computed(() => [
    // Account settings - only show credits when user is authenticated
    {
      key: "account",
      label: "Account",
      children: [
        userPanel.node,
        ...isLoggedIn.value ? [creditsPanel.node] : []
      ].map(translateCategory)
    },
    // Normal settings stored in the settingStore
    {
      key: "settings",
      label: "Application Settings",
      children: settingCategories.value.map(translateCategory)
    },
    // Special settings such as about, keybinding, extension, server-config
    {
      key: "specialSettings",
      label: "Special Settings",
      children: [
        keybindingPanel.node,
        extensionPanel.node,
        aboutPanel.node,
        ...isElectron() ? [serverConfigPanel.node] : []
      ].map(translateCategory)
    }
  ]);
  onMounted(() => {
    activeCategory.value = defaultCategory.value;
  });
  return {
    panels,
    activeCategory,
    defaultCategory,
    groupedMenuTreeNodes,
    settingCategories
  };
}
__name(useSettingUI, "useSettingUI");
const id$5 = "arc";
const name$5 = "Arc";
const colors$5 = {
  node_slot: {
    BOOLEAN: "",
    CLIP: "#eacb8b",
    CLIP_VISION: "#A8DADC",
    CLIP_VISION_OUTPUT: "#ad7452",
    CONDITIONING: "#cf876f",
    CONTROL_NET: "#00d78d",
    CONTROL_NET_WEIGHTS: "",
    FLOAT: "",
    GLIGEN: "",
    IMAGE: "#80a1c0",
    IMAGEUPLOAD: "",
    INT: "",
    LATENT: "#b38ead",
    LATENT_KEYFRAME: "",
    MASK: "#a3bd8d",
    MODEL: "#8978a7",
    SAMPLER: "",
    SIGMAS: "",
    STRING: "",
    STYLE_MODEL: "#C2FFAE",
    T2I_ADAPTER_WEIGHTS: "",
    TAESD: "#DCC274",
    TIMESTEP_KEYFRAME: "",
    UPSCALE_MODEL: "",
    VAE: "#be616b"
  },
  litegraph_base: {
    BACKGROUND_IMAGE: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAACXBIWXMAAAsTAAALEwEAmpwYAAABcklEQVR4nO3YMUoDARgF4RfxBqZI6/0vZqFn0MYtrLIQMFN8U6V4LAtD+Jm9XG/v30OGl2e/AP7yevz4+vx45nvgF/+QGITEICQGITEIiUFIjNNC3q43u3/YnRJyPOzeQ+0e220nhRzReC8e7R7bbdvl+Jal1Bs46jEIiUFIDEJiEBKDkBhKPbZT6qHdptRTu02p53DUYxASg5AYhMQgJAYhMZR6bKfUQ7tNqad2m1LP4ajHICQGITEIiUFIDEJiKPXYTqmHdptST+02pZ7DUY9BSAxCYhASg5AYhMRQ6rGdUg/tNqWe2m1KPYejHoOQGITEICQGITEIiaHUYzulHtptSj2125R6Dkc9BiExCIlBSAxCYhASQ6nHdko9tNuUemq3KfUcjnoMQmIQEoOQGITEICSGUo/tlHpotyn11G5T6jkc9RiExCAkBiExCIlBSAylHtsp9dBuU+qp3abUczjqMQiJQUgMQmIQEoOQGITE+AHFISNQrFTGuwAAAABJRU5ErkJggg==",
    CLEAR_BACKGROUND_COLOR: "#2b2f38",
    NODE_TITLE_COLOR: "#b2b7bd",
    NODE_SELECTED_TITLE_COLOR: "#FFF",
    NODE_TEXT_SIZE: 14,
    NODE_TEXT_COLOR: "#AAA",
    NODE_SUBTEXT_SIZE: 12,
    NODE_DEFAULT_COLOR: "#2b2f38",
    NODE_DEFAULT_BGCOLOR: "#242730",
    NODE_DEFAULT_BOXCOLOR: "#6e7581",
    NODE_DEFAULT_SHAPE: 2,
    NODE_BOX_OUTLINE_COLOR: "#FFF",
    NODE_BYPASS_BGCOLOR: "#FF00FF",
    NODE_ERROR_COLOUR: "#E00",
    DEFAULT_SHADOW_COLOR: "rgba(0,0,0,0.5)",
    DEFAULT_GROUP_FONT: 22,
    WIDGET_BGCOLOR: "#2b2f38",
    WIDGET_OUTLINE_COLOR: "#6e7581",
    WIDGET_TEXT_COLOR: "#DDD",
    WIDGET_SECONDARY_TEXT_COLOR: "#b2b7bd",
    WIDGET_DISABLED_TEXT_COLOR: "#5c626d",
    LINK_COLOR: "#9A9",
    EVENT_LINK_COLOR: "#A86",
    CONNECTING_LINK_COLOR: "#AFA"
  },
  comfy_base: {
    "fg-color": "#fff",
    "bg-color": "#2b2f38",
    "comfy-menu-bg": "#242730",
    "comfy-menu-secondary-bg": "#22252E",
    "comfy-input-bg": "#2b2f38",
    "input-text": "#ddd",
    "descrip-text": "#b2b7bd",
    "drag-text": "#ccc",
    "error-text": "#ff4444",
    "border-color": "#6e7581",
    "tr-even-bg-color": "#2b2f38",
    "tr-odd-bg-color": "#242730",
    "content-bg": "#6e7581",
    "content-fg": "#fff",
    "content-hover-bg": "#2b2f38",
    "content-hover-fg": "#fff",
    "bar-shadow": "rgba(8, 8, 8, 0.75) 0 0 0.5rem"
  }
};
const arc = {
  id: id$5,
  name: name$5,
  colors: colors$5
};
const id$4 = "dark";
const name$4 = "Dark (Default)";
const colors$4 = {
  node_slot: {
    CLIP: "#FFD500",
    CLIP_VISION: "#A8DADC",
    CLIP_VISION_OUTPUT: "#ad7452",
    CONDITIONING: "#FFA931",
    CONTROL_NET: "#6EE7B7",
    IMAGE: "#64B5F6",
    LATENT: "#FF9CF9",
    MASK: "#81C784",
    MODEL: "#B39DDB",
    STYLE_MODEL: "#C2FFAE",
    VAE: "#FF6E6E",
    NOISE: "#B0B0B0",
    GUIDER: "#66FFFF",
    SAMPLER: "#ECB4B4",
    SIGMAS: "#CDFFCD",
    TAESD: "#DCC274"
  },
  litegraph_base: {
    BACKGROUND_IMAGE: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAIAAAD/gAIDAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAQBJREFUeNrs1rEKwjAUhlETUkj3vP9rdmr1Ysammk2w5wdxuLgcMHyptfawuZX4pJSWZTnfnu/lnIe/jNNxHHGNn//HNbbv+4dr6V+11uF527arU7+u63qfa/bnmh8sWLBgwYJlqRf8MEptXPBXJXa37BSl3ixYsGDBMliwFLyCV/DeLIMFCxYsWLBMwSt4Be/NggXLYMGCBUvBK3iNruC9WbBgwYJlsGApeAWv4L1ZBgsWLFiwYJmCV/AK3psFC5bBggULloJX8BpdwXuzYMGCBctgwVLwCl7Be7MMFixYsGDBsu8FH1FaSmExVfAxBa/gvVmwYMGCZbBg/W4vAQYA5tRF9QYlv/QAAAAASUVORK5CYII=",
    CLEAR_BACKGROUND_COLOR: "#222",
    NODE_TITLE_COLOR: "#999",
    NODE_SELECTED_TITLE_COLOR: "#FFF",
    NODE_TEXT_SIZE: 14,
    NODE_TEXT_COLOR: "#AAA",
    NODE_TEXT_HIGHLIGHT_COLOR: "#FFF",
    NODE_SUBTEXT_SIZE: 12,
    NODE_DEFAULT_COLOR: "#333",
    NODE_DEFAULT_BGCOLOR: "#353535",
    NODE_DEFAULT_BOXCOLOR: "#666",
    NODE_DEFAULT_SHAPE: 2,
    NODE_BOX_OUTLINE_COLOR: "#FFF",
    NODE_BYPASS_BGCOLOR: "#FF00FF",
    NODE_ERROR_COLOUR: "#E00",
    DEFAULT_SHADOW_COLOR: "rgba(0,0,0,0.5)",
    DEFAULT_GROUP_FONT: 24,
    WIDGET_BGCOLOR: "#222",
    WIDGET_OUTLINE_COLOR: "#666",
    WIDGET_TEXT_COLOR: "#DDD",
    WIDGET_SECONDARY_TEXT_COLOR: "#999",
    WIDGET_DISABLED_TEXT_COLOR: "#666",
    LINK_COLOR: "#9A9",
    EVENT_LINK_COLOR: "#A86",
    CONNECTING_LINK_COLOR: "#AFA",
    BADGE_FG_COLOR: "#FFF",
    BADGE_BG_COLOR: "#0F1F0F"
  },
  comfy_base: {
    "fg-color": "#fff",
    "bg-color": "#202020",
    "comfy-menu-bg": "#353535",
    "comfy-menu-secondary-bg": "#303030",
    "comfy-input-bg": "#222",
    "input-text": "#ddd",
    "descrip-text": "#999",
    "drag-text": "#ccc",
    "error-text": "#ff4444",
    "border-color": "#4e4e4e",
    "tr-even-bg-color": "#222",
    "tr-odd-bg-color": "#353535",
    "content-bg": "#4e4e4e",
    "content-fg": "#fff",
    "content-hover-bg": "#222",
    "content-hover-fg": "#fff",
    "bar-shadow": "rgba(16, 16, 16, 0.5) 0 0 0.5rem"
  }
};
const dark = {
  id: id$4,
  name: name$4,
  colors: colors$4
};
const id$3 = "github";
const name$3 = "Github";
const colors$3 = {
  node_slot: {
    BOOLEAN: "",
    CLIP: "#eacb8b",
    CLIP_VISION: "#A8DADC",
    CLIP_VISION_OUTPUT: "#ad7452",
    CONDITIONING: "#cf876f",
    CONTROL_NET: "#00d78d",
    CONTROL_NET_WEIGHTS: "",
    FLOAT: "",
    GLIGEN: "",
    IMAGE: "#80a1c0",
    IMAGEUPLOAD: "",
    INT: "",
    LATENT: "#b38ead",
    LATENT_KEYFRAME: "",
    MASK: "#a3bd8d",
    MODEL: "#8978a7",
    SAMPLER: "",
    SIGMAS: "",
    STRING: "",
    STYLE_MODEL: "#C2FFAE",
    T2I_ADAPTER_WEIGHTS: "",
    TAESD: "#DCC274",
    TIMESTEP_KEYFRAME: "",
    UPSCALE_MODEL: "",
    VAE: "#be616b"
  },
  litegraph_base: {
    BACKGROUND_IMAGE: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAIAAAD/gAIDAAAACXBIWXMAAAsTAAALEwEAmpwYAAAGlmlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4gPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iQWRvYmUgWE1QIENvcmUgOS4xLWMwMDEgNzkuMTQ2Mjg5OSwgMjAyMy8wNi8yNS0yMDowMTo1NSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczpkYz0iaHR0cDovL3B1cmwub3JnL2RjL2VsZW1lbnRzLzEuMS8iIHhtbG5zOnBob3Rvc2hvcD0iaHR0cDovL25zLmFkb2JlLmNvbS9waG90b3Nob3AvMS4wLyIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0RXZ0PSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VFdmVudCMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIDI1LjEgKFdpbmRvd3MpIiB4bXA6Q3JlYXRlRGF0ZT0iMjAyMy0xMS0xM1QwMDoxODowMiswMTowMCIgeG1wOk1vZGlmeURhdGU9IjIwMjMtMTEtMTVUMDI6MDQ6NTkrMDE6MDAiIHhtcDpNZXRhZGF0YURhdGU9IjIwMjMtMTEtMTVUMDI6MDQ6NTkrMDE6MDAiIGRjOmZvcm1hdD0iaW1hZ2UvcG5nIiBwaG90b3Nob3A6Q29sb3JNb2RlPSIzIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOmIyYzRhNjA5LWJmYTctYTg0MC1iOGFlLTk3MzE2ZjM1ZGIyNyIgeG1wTU06RG9jdW1lbnRJRD0iYWRvYmU6ZG9jaWQ6cGhvdG9zaG9wOjk0ZmNlZGU4LTE1MTctZmQ0MC04ZGU3LWYzOTgxM2E3ODk5ZiIgeG1wTU06T3JpZ2luYWxEb2N1bWVudElEPSJ4bXAuZGlkOjIzMWIxMGIwLWI0ZmItMDI0ZS1iMTJlLTMwNTMwM2NkMDdjOCI+IDx4bXBNTTpIaXN0b3J5PiA8cmRmOlNlcT4gPHJkZjpsaSBzdEV2dDphY3Rpb249ImNyZWF0ZWQiIHN0RXZ0Omluc3RhbmNlSUQ9InhtcC5paWQ6MjMxYjEwYjAtYjRmYi0wMjRlLWIxMmUtMzA1MzAzY2QwN2M4IiBzdEV2dDp3aGVuPSIyMDIzLTExLTEzVDAwOjE4OjAyKzAxOjAwIiBzdEV2dDpzb2Z0d2FyZUFnZW50PSJBZG9iZSBQaG90b3Nob3AgMjUuMSAoV2luZG93cykiLz4gPHJkZjpsaSBzdEV2dDphY3Rpb249InNhdmVkIiBzdEV2dDppbnN0YW5jZUlEPSJ4bXAuaWlkOjQ4OWY1NzlmLTJkNjUtZWQ0Zi04OTg0LTA4NGE2MGE1ZTMzNSIgc3RFdnQ6d2hlbj0iMjAyMy0xMS0xNVQwMjowNDo1OSswMTowMCIgc3RFdnQ6c29mdHdhcmVBZ2VudD0iQWRvYmUgUGhvdG9zaG9wIDI1LjEgKFdpbmRvd3MpIiBzdEV2dDpjaGFuZ2VkPSIvIi8+IDxyZGY6bGkgc3RFdnQ6YWN0aW9uPSJzYXZlZCIgc3RFdnQ6aW5zdGFuY2VJRD0ieG1wLmlpZDpiMmM0YTYwOS1iZmE3LWE4NDAtYjhhZS05NzMxNmYzNWRiMjciIHN0RXZ0OndoZW49IjIwMjMtMTEtMTVUMDI6MDQ6NTkrMDE6MDAiIHN0RXZ0OnNvZnR3YXJlQWdlbnQ9IkFkb2JlIFBob3Rvc2hvcCAyNS4xIChXaW5kb3dzKSIgc3RFdnQ6Y2hhbmdlZD0iLyIvPiA8L3JkZjpTZXE+IDwveG1wTU06SGlzdG9yeT4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz4OTe6GAAAAx0lEQVR42u3WMQoAIQxFwRzJys77X8vSLiRgITif7bYbgrwYc/mKXyBoY4VVBgsWLFiwYFmOlTv+9jfDOjHmr8u6eVkGCxYsWLBgmc5S8ApewXvgYRksWLBgKXidpeBdloL3wMOCBctgwVLwCl7BuyyDBQsWLFiwTGcpeAWv4D3wsAwWLFiwFLzOUvAuS8F74GHBgmWwYCl4Ba/gXZbBggULFixYprMUvIJX8B54WAYLFixYCl5nKXiXpeA98LBgwTJYsGC9tg1o8f4TTtqzNQAAAABJRU5ErkJggg==",
    CLEAR_BACKGROUND_COLOR: "#040506",
    NODE_TITLE_COLOR: "#999",
    NODE_SELECTED_TITLE_COLOR: "#e5eaf0",
    NODE_TEXT_SIZE: 14,
    NODE_TEXT_COLOR: "#bcc2c8",
    NODE_SUBTEXT_SIZE: 12,
    NODE_DEFAULT_COLOR: "#161b22",
    NODE_DEFAULT_BGCOLOR: "#13171d",
    NODE_DEFAULT_BOXCOLOR: "#30363d",
    NODE_DEFAULT_SHAPE: 2,
    NODE_BOX_OUTLINE_COLOR: "#e5eaf0",
    NODE_BYPASS_BGCOLOR: "#FF00FF",
    NODE_ERROR_COLOUR: "#E00",
    DEFAULT_SHADOW_COLOR: "rgba(0,0,0,0.5)",
    DEFAULT_GROUP_FONT: 24,
    WIDGET_BGCOLOR: "#161b22",
    WIDGET_OUTLINE_COLOR: "#30363d",
    WIDGET_TEXT_COLOR: "#bcc2c8",
    WIDGET_SECONDARY_TEXT_COLOR: "#999",
    WIDGET_DISABLED_TEXT_COLOR: "#30363d",
    LINK_COLOR: "#9A9",
    EVENT_LINK_COLOR: "#A86",
    CONNECTING_LINK_COLOR: "#AFA"
  },
  comfy_base: {
    "fg-color": "#e5eaf0",
    "bg-color": "#161b22",
    "comfy-menu-bg": "#13171d",
    "comfy-menu-secondary-bg": "#11141A",
    "comfy-input-bg": "#161b22",
    "input-text": "#bcc2c8",
    "descrip-text": "#999",
    "drag-text": "#ccc",
    "error-text": "#ff4444",
    "border-color": "#30363d",
    "tr-even-bg-color": "#161b22",
    "tr-odd-bg-color": "#13171d",
    "content-bg": "#30363d",
    "content-fg": "#e5eaf0",
    "content-hover-bg": "#161b22",
    "content-hover-fg": "#e5eaf0",
    "bar-shadow": "rgba(0, 0, 0, 1) 0 0 0.5rem"
  }
};
const github = {
  id: id$3,
  name: name$3,
  colors: colors$3
};
const id$2 = "light";
const name$2 = "Light";
const light_theme = true;
const colors$2 = {
  node_slot: {
    CLIP: "#FFA726",
    CLIP_VISION: "#5C6BC0",
    CLIP_VISION_OUTPUT: "#8D6E63",
    CONDITIONING: "#EF5350",
    CONTROL_NET: "#66BB6A",
    IMAGE: "#42A5F5",
    LATENT: "#AB47BC",
    MASK: "#9CCC65",
    MODEL: "#7E57C2",
    STYLE_MODEL: "#D4E157",
    VAE: "#FF7043",
    NOISE: "#B0B0B0",
    GUIDER: "#66FFFF",
    SAMPLER: "#ECB4B4",
    SIGMAS: "#CDFFCD",
    TAESD: "#DCC274"
  },
  litegraph_base: {
    BACKGROUND_IMAGE: "data:image/gif;base64,R0lGODlhZABkALMAAAAAAP///+vr6+rq6ujo6Ofn5+bm5uXl5d3d3f///wAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAAkALAAAAABkAGQAAAT/UMhJq7046827HkcoHkYxjgZhnGG6si5LqnIM0/fL4qwwIMAg0CAsEovBIxKhRDaNy2GUOX0KfVFrssrNdpdaqTeKBX+dZ+jYvEaTf+y4W66mC8PUdrE879f9d2mBeoNLfH+IhYBbhIx2jkiHiomQlGKPl4uZe3CaeZifnnijgkESBqipqqusra6vsLGys62SlZO4t7qbuby7CLa+wqGWxL3Gv3jByMOkjc2lw8vOoNSi0czAncXW3Njdx9Pf48/Z4Kbbx+fQ5evZ4u3k1fKR6cn03vHlp7T9/v8A/8Gbp4+gwXoFryXMB2qgwoMMHyKEqA5fxX322FG8tzBcRnMW/zlulPbRncmQGidKjMjyYsOSKEF2FBlJQMCbOHP6c9iSZs+UnGYCdbnSo1CZI5F64kn0p1KnTH02nSoV3dGTV7FFHVqVq1dtWcMmVQZTbNGu72zqXMuW7danVL+6e4t1bEy6MeueBYLXrNO5Ze36jQtWsOG97wIj1vt3St/DjTEORss4nNq2mDP3e7w4r1bFkSET5hy6s2TRlD2/mSxXtSHQhCunXo26NevCpmvD/UU6tuullzULH76q92zdZG/Ltv1a+W+osI/nRmyc+fRi1Xdbh+68+0vv10dH3+77KD/i6IdnX669/frn5Zsjh4/2PXju8+8bzc9/6fj27LFnX11/+IUnXWl7BJfegm79FyB9JOl3oHgSklefgxAC+FmFGpqHIYcCfkhgfCohSKKJVo044YUMttggiBkmp6KFXw1oII24oYhjiDByaKOOHcp3Y5BD/njikSkO+eBREQAAOw==",
    CLEAR_BACKGROUND_COLOR: "lightgray",
    NODE_TITLE_COLOR: "#222",
    NODE_SELECTED_TITLE_COLOR: "#000",
    NODE_TEXT_SIZE: 14,
    NODE_TEXT_COLOR: "#444",
    NODE_TEXT_HIGHLIGHT_COLOR: "#1e293b",
    NODE_SUBTEXT_SIZE: 12,
    NODE_DEFAULT_COLOR: "#F7F7F7",
    NODE_DEFAULT_BGCOLOR: "#F5F5F5",
    NODE_DEFAULT_BOXCOLOR: "#CCC",
    NODE_DEFAULT_SHAPE: 2,
    NODE_BOX_OUTLINE_COLOR: "#000",
    NODE_BYPASS_BGCOLOR: "#FF00FF",
    NODE_ERROR_COLOUR: "#E00",
    DEFAULT_SHADOW_COLOR: "rgba(0,0,0,0.1)",
    DEFAULT_GROUP_FONT: 24,
    WIDGET_BGCOLOR: "#D4D4D4",
    WIDGET_OUTLINE_COLOR: "#999",
    WIDGET_TEXT_COLOR: "#222",
    WIDGET_SECONDARY_TEXT_COLOR: "#555",
    WIDGET_DISABLED_TEXT_COLOR: "#999",
    LINK_COLOR: "#4CAF50",
    EVENT_LINK_COLOR: "#FF9800",
    CONNECTING_LINK_COLOR: "#2196F3",
    BADGE_FG_COLOR: "#000",
    BADGE_BG_COLOR: "#FFF"
  },
  comfy_base: {
    "fg-color": "#222",
    "bg-color": "#DDD",
    "comfy-menu-bg": "#F5F5F5",
    "comfy-menu-hover-bg": "#ccc",
    "comfy-menu-secondary-bg": "#EEE",
    "comfy-input-bg": "#C9C9C9",
    "input-text": "#222",
    "descrip-text": "#444",
    "drag-text": "#555",
    "error-text": "#F44336",
    "border-color": "#888",
    "tr-even-bg-color": "#f9f9f9",
    "tr-odd-bg-color": "#fff",
    "content-bg": "#e0e0e0",
    "content-fg": "#222",
    "content-hover-bg": "#adadad",
    "content-hover-fg": "#222",
    "bar-shadow": "rgba(16, 16, 16, 0.25) 0 0 0.5rem"
  }
};
const light = {
  id: id$2,
  name: name$2,
  light_theme,
  colors: colors$2
};
const id$1 = "nord";
const name$1 = "Nord";
const colors$1 = {
  node_slot: {
    BOOLEAN: "",
    CLIP: "#eacb8b",
    CLIP_VISION: "#A8DADC",
    CLIP_VISION_OUTPUT: "#ad7452",
    CONDITIONING: "#cf876f",
    CONTROL_NET: "#00d78d",
    CONTROL_NET_WEIGHTS: "",
    FLOAT: "",
    GLIGEN: "",
    IMAGE: "#80a1c0",
    IMAGEUPLOAD: "",
    INT: "",
    LATENT: "#b38ead",
    LATENT_KEYFRAME: "",
    MASK: "#a3bd8d",
    MODEL: "#8978a7",
    SAMPLER: "",
    SIGMAS: "",
    STRING: "",
    STYLE_MODEL: "#C2FFAE",
    T2I_ADAPTER_WEIGHTS: "",
    TAESD: "#DCC274",
    TIMESTEP_KEYFRAME: "",
    UPSCALE_MODEL: "",
    VAE: "#be616b"
  },
  litegraph_base: {
    BACKGROUND_IMAGE: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAIAAAD/gAIDAAAACXBIWXMAAAsTAAALEwEAmpwYAAAFu2lUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4gPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iQWRvYmUgWE1QIENvcmUgOS4xLWMwMDEgNzkuMTQ2Mjg5OSwgMjAyMy8wNi8yNS0yMDowMTo1NSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczpkYz0iaHR0cDovL3B1cmwub3JnL2RjL2VsZW1lbnRzLzEuMS8iIHhtbG5zOnBob3Rvc2hvcD0iaHR0cDovL25zLmFkb2JlLmNvbS9waG90b3Nob3AvMS4wLyIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0RXZ0PSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VFdmVudCMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIDI1LjEgKFdpbmRvd3MpIiB4bXA6Q3JlYXRlRGF0ZT0iMjAyMy0xMS0xM1QwMDoxODowMiswMTowMCIgeG1wOk1vZGlmeURhdGU9IjIwMjMtMTEtMTVUMDE6MjA6NDUrMDE6MDAiIHhtcDpNZXRhZGF0YURhdGU9IjIwMjMtMTEtMTVUMDE6MjA6NDUrMDE6MDAiIGRjOmZvcm1hdD0iaW1hZ2UvcG5nIiBwaG90b3Nob3A6Q29sb3JNb2RlPSIzIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOjUwNDFhMmZjLTEzNzQtMTk0ZC1hZWY4LTYxMzM1MTVmNjUwMCIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDoyMzFiMTBiMC1iNGZiLTAyNGUtYjEyZS0zMDUzMDNjZDA3YzgiIHhtcE1NOk9yaWdpbmFsRG9jdW1lbnRJRD0ieG1wLmRpZDoyMzFiMTBiMC1iNGZiLTAyNGUtYjEyZS0zMDUzMDNjZDA3YzgiPiA8eG1wTU06SGlzdG9yeT4gPHJkZjpTZXE+IDxyZGY6bGkgc3RFdnQ6YWN0aW9uPSJjcmVhdGVkIiBzdEV2dDppbnN0YW5jZUlEPSJ4bXAuaWlkOjIzMWIxMGIwLWI0ZmItMDI0ZS1iMTJlLTMwNTMwM2NkMDdjOCIgc3RFdnQ6d2hlbj0iMjAyMy0xMS0xM1QwMDoxODowMiswMTowMCIgc3RFdnQ6c29mdHdhcmVBZ2VudD0iQWRvYmUgUGhvdG9zaG9wIDI1LjEgKFdpbmRvd3MpIi8+IDxyZGY6bGkgc3RFdnQ6YWN0aW9uPSJzYXZlZCIgc3RFdnQ6aW5zdGFuY2VJRD0ieG1wLmlpZDo1MDQxYTJmYy0xMzc0LTE5NGQtYWVmOC02MTMzNTE1ZjY1MDAiIHN0RXZ0OndoZW49IjIwMjMtMTEtMTVUMDE6MjA6NDUrMDE6MDAiIHN0RXZ0OnNvZnR3YXJlQWdlbnQ9IkFkb2JlIFBob3Rvc2hvcCAyNS4xIChXaW5kb3dzKSIgc3RFdnQ6Y2hhbmdlZD0iLyIvPiA8L3JkZjpTZXE+IDwveG1wTU06SGlzdG9yeT4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz73jWg/AAAAyUlEQVR42u3WKwoAIBRFQRdiMb1idv9Lsxn9gEFw4Dbb8JCTojbbXEJwjJVL2HKwYMGCBQuWLbDmjr+9zrBGjHl1WVcvy2DBggULFizTWQpewSt4HzwsgwULFiwFr7MUvMtS8D54WLBgGSxYCl7BK3iXZbBgwYIFC5bpLAWv4BW8Dx6WwYIFC5aC11kK3mUpeB88LFiwDBYsBa/gFbzLMliwYMGCBct0loJX8AreBw/LYMGCBUvB6ywF77IUvA8eFixYBgsWrNfWAZPltufdad+1AAAAAElFTkSuQmCC",
    CLEAR_BACKGROUND_COLOR: "#212732",
    NODE_TITLE_COLOR: "#999",
    NODE_SELECTED_TITLE_COLOR: "#e5eaf0",
    NODE_TEXT_SIZE: 14,
    NODE_TEXT_COLOR: "#bcc2c8",
    NODE_SUBTEXT_SIZE: 12,
    NODE_DEFAULT_COLOR: "#2e3440",
    NODE_DEFAULT_BGCOLOR: "#161b22",
    NODE_DEFAULT_BOXCOLOR: "#545d70",
    NODE_DEFAULT_SHAPE: 2,
    NODE_BOX_OUTLINE_COLOR: "#e5eaf0",
    NODE_BYPASS_BGCOLOR: "#FF00FF",
    NODE_ERROR_COLOUR: "#E00",
    DEFAULT_SHADOW_COLOR: "rgba(0,0,0,0.5)",
    DEFAULT_GROUP_FONT: 24,
    WIDGET_BGCOLOR: "#2e3440",
    WIDGET_OUTLINE_COLOR: "#545d70",
    WIDGET_TEXT_COLOR: "#bcc2c8",
    WIDGET_SECONDARY_TEXT_COLOR: "#999",
    WIDGET_DISABLED_TEXT_COLOR: "#545d70",
    LINK_COLOR: "#9A9",
    EVENT_LINK_COLOR: "#A86",
    CONNECTING_LINK_COLOR: "#AFA"
  },
  comfy_base: {
    "fg-color": "#e5eaf0",
    "bg-color": "#2e3440",
    "comfy-menu-bg": "#161b22",
    "comfy-menu-secondary-bg": "#14181F",
    "comfy-input-bg": "#2e3440",
    "input-text": "#bcc2c8",
    "descrip-text": "#999",
    "drag-text": "#ccc",
    "error-text": "#ff4444",
    "border-color": "#545d70",
    "tr-even-bg-color": "#2e3440",
    "tr-odd-bg-color": "#161b22",
    "content-bg": "#545d70",
    "content-fg": "#e5eaf0",
    "content-hover-bg": "#2e3440",
    "content-hover-fg": "#e5eaf0",
    "bar-shadow": "rgba(0, 0, 0, 0.75) 0 0 0.5rem"
  }
};
const nord = {
  id: id$1,
  name: name$1,
  colors: colors$1
};
const id = "solarized";
const name = "Solarized";
const colors = {
  node_slot: {
    CLIP: "#2AB7CA",
    CLIP_VISION: "#6c71c4",
    CLIP_VISION_OUTPUT: "#859900",
    CONDITIONING: "#d33682",
    CONTROL_NET: "#d1ffd7",
    IMAGE: "#5940bb",
    LATENT: "#268bd2",
    MASK: "#CCC9E7",
    MODEL: "#dc322f",
    STYLE_MODEL: "#1a998a",
    UPSCALE_MODEL: "#054A29",
    VAE: "#facfad"
  },
  litegraph_base: {
    NODE_TITLE_COLOR: "#fdf6e3",
    NODE_SELECTED_TITLE_COLOR: "#A9D400",
    NODE_TEXT_SIZE: 14,
    NODE_TEXT_COLOR: "#657b83",
    NODE_SUBTEXT_SIZE: 12,
    NODE_DEFAULT_COLOR: "#094656",
    NODE_DEFAULT_BGCOLOR: "#073642",
    NODE_DEFAULT_BOXCOLOR: "#839496",
    NODE_DEFAULT_SHAPE: 2,
    NODE_BOX_OUTLINE_COLOR: "#fdf6e3",
    NODE_BYPASS_BGCOLOR: "#FF00FF",
    NODE_ERROR_COLOUR: "#E00",
    DEFAULT_SHADOW_COLOR: "rgba(0,0,0,0.5)",
    DEFAULT_GROUP_FONT: 24,
    WIDGET_BGCOLOR: "#002b36",
    WIDGET_OUTLINE_COLOR: "#839496",
    WIDGET_TEXT_COLOR: "#fdf6e3",
    WIDGET_SECONDARY_TEXT_COLOR: "#93a1a1",
    WIDGET_DISABLED_TEXT_COLOR: "#657b83",
    LINK_COLOR: "#2aa198",
    EVENT_LINK_COLOR: "#268bd2",
    CONNECTING_LINK_COLOR: "#859900"
  },
  comfy_base: {
    "fg-color": "#fdf6e3",
    "bg-color": "#002b36",
    "comfy-menu-bg": "#073642",
    "comfy-menu-secondary-bg": "#06323D",
    "comfy-input-bg": "#002b36",
    "input-text": "#93a1a1",
    "descrip-text": "#586e75",
    "drag-text": "#839496",
    "error-text": "#dc322f",
    "border-color": "#657b83",
    "tr-even-bg-color": "#002b36",
    "tr-odd-bg-color": "#073642",
    "content-bg": "#657b83",
    "content-fg": "#fdf6e3",
    "content-hover-bg": "#002b36",
    "content-hover-fg": "#fdf6e3",
    "bar-shadow": "rgba(16, 16, 16, 0.5) 0 0 0.5rem"
  }
};
const solarized = {
  id,
  name,
  colors
};
const CORE_COLOR_PALETTES = {
  dark,
  light,
  solarized,
  arc,
  nord,
  github
};
const DEFAULT_COLOR_PALETTE = dark;
const DEFAULT_DARK_COLOR_PALETTE = dark;
const DEFAULT_LIGHT_COLOR_PALETTE = light;
const useColorPaletteStore = /* @__PURE__ */ defineStore("colorPalette", () => {
  const customPalettes = ref$3({});
  const activePaletteId = ref$3(DEFAULT_COLOR_PALETTE.id);
  const palettesLookup = computed(() => ({
    ...CORE_COLOR_PALETTES,
    ...customPalettes.value
  }));
  const palettes = computed(() => Object.values(palettesLookup.value));
  const completedActivePalette = computed(
    () => completePalette(palettesLookup.value[activePaletteId.value])
  );
  const addCustomPalette = /* @__PURE__ */ __name((palette) => {
    if (palette.id in palettesLookup.value) {
      throw new Error(`Palette with id ${palette.id} already exists`);
    }
    customPalettes.value[palette.id] = palette;
    activePaletteId.value = palette.id;
  }, "addCustomPalette");
  const deleteCustomPalette = /* @__PURE__ */ __name((id2) => {
    if (!(id2 in customPalettes.value)) {
      throw new Error(`Palette with id ${id2} does not exist`);
    }
    delete customPalettes.value[id2];
    activePaletteId.value = CORE_COLOR_PALETTES.dark.id;
  }, "deleteCustomPalette");
  const isCustomPalette = /* @__PURE__ */ __name((id2) => {
    return id2 in customPalettes.value;
  }, "isCustomPalette");
  const completePalette = /* @__PURE__ */ __name((palette) => {
    if (palette.colors.comfy_base["comfy-menu-bg"] && !palette.colors.comfy_base["comfy-menu-secondary-bg"]) {
      palette.colors.comfy_base["comfy-menu-secondary-bg"] = palette.colors.comfy_base["comfy-menu-bg"];
    }
    const defaultPalette = palette.light_theme ? DEFAULT_LIGHT_COLOR_PALETTE : DEFAULT_DARK_COLOR_PALETTE;
    return {
      ...palette,
      colors: {
        ...palette.colors,
        node_slot: {
          ...defaultPalette.colors.node_slot,
          ...palette.colors.node_slot
        },
        litegraph_base: {
          ...defaultPalette.colors.litegraph_base,
          ...palette.colors.litegraph_base
        },
        comfy_base: {
          ...defaultPalette.colors.comfy_base,
          ...palette.colors.comfy_base
        }
      }
    };
  }, "completePalette");
  return {
    // State
    customPalettes,
    activePaletteId,
    // Getters
    palettesLookup,
    palettes,
    completedActivePalette,
    // Actions
    isCustomPalette,
    addCustomPalette,
    deleteCustomPalette,
    completePalette
  };
});
const _hoisted_1$1f = { class: "flex items-center justify-between" };
const _hoisted_2$V = { class: "actions" };
const _sfc_main$1A = /* @__PURE__ */ defineComponent({
  __name: "ColorPaletteMessage",
  setup(__props) {
    const settingStore = useSettingStore();
    const colorPaletteStore = useColorPaletteStore();
    const colorPaletteService = useColorPaletteService();
    const { palettes, activePaletteId } = storeToRefs(colorPaletteStore);
    const importCustomPalette = /* @__PURE__ */ __name(async () => {
      const palette = await colorPaletteService.importColorPalette();
      if (palette) {
        await settingStore.set("Comfy.ColorPalette", palette.id);
      }
    }, "importCustomPalette");
    return (_ctx, _cache) => {
      return openBlock(), createBlock(unref(script$8), {
        severity: "info",
        icon: "pi pi-palette",
        "pt:text": "w-full"
      }, {
        default: withCtx(() => [
          createBaseVNode("div", _hoisted_1$1f, [
            createBaseVNode("div", null, toDisplayString(_ctx.$t("settingsCategories.ColorPalette")), 1),
            createBaseVNode("div", _hoisted_2$V, [
              createVNode(unref(script$n), {
                modelValue: unref(activePaletteId),
                "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => isRef(activePaletteId) ? activePaletteId.value = $event : null),
                class: "w-44",
                options: unref(palettes),
                "option-label": "name",
                "option-value": "id"
              }, null, 8, ["modelValue", "options"]),
              createVNode(unref(script$6), {
                icon: "pi pi-file-export",
                text: "",
                title: _ctx.$t("g.export"),
                onClick: _cache[1] || (_cache[1] = ($event) => unref(colorPaletteService).exportColorPalette(unref(activePaletteId)))
              }, null, 8, ["title"]),
              createVNode(unref(script$6), {
                icon: "pi pi-file-import",
                text: "",
                title: _ctx.$t("g.import"),
                onClick: importCustomPalette
              }, null, 8, ["title"]),
              createVNode(unref(script$6), {
                icon: "pi pi-trash",
                severity: "danger",
                text: "",
                title: _ctx.$t("g.delete"),
                disabled: !unref(colorPaletteStore).isCustomPalette(unref(activePaletteId)),
                onClick: _cache[2] || (_cache[2] = ($event) => unref(colorPaletteService).deleteCustomColorPalette(unref(activePaletteId)))
              }, null, 8, ["title", "disabled"])
            ])
          ])
        ]),
        _: 1
      });
    };
  }
});
const _hoisted_1$1e = { class: "flex items-center justify-between" };
const _sfc_main$1z = /* @__PURE__ */ defineComponent({
  __name: "CurrentUserMessage",
  setup(__props) {
    const userStore = useUserStore();
    const logout = /* @__PURE__ */ __name(async () => {
      await userStore.logout();
      window.location.reload();
    }, "logout");
    return (_ctx, _cache) => {
      return unref(userStore).isMultiUserServer ? (openBlock(), createBlock(unref(script$8), {
        key: 0,
        severity: "info",
        icon: "pi pi-user",
        "pt:text": "w-full"
      }, {
        default: withCtx(() => [
          createBaseVNode("div", _hoisted_1$1e, [
            createBaseVNode("div", null, toDisplayString(_ctx.$t("g.currentUser")) + ": " + toDisplayString(unref(userStore).currentUser?.username), 1),
            createVNode(unref(script$6), {
              icon: "pi pi-sign-out",
              text: "",
              onClick: logout
            })
          ])
        ]),
        _: 1
      })) : createCommentVNode("", true);
    };
  }
});
const _sfc_main$1y = /* @__PURE__ */ defineComponent({
  __name: "FirstTimeUIMessage",
  setup(__props) {
    const settingStore = useSettingStore();
    const show = computed(() => !settingStore.exists("Comfy.UseNewMenu"));
    const handleClose = /* @__PURE__ */ __name(async () => {
      const currentValue = settingStore.get("Comfy.UseNewMenu");
      await settingStore.set("Comfy.UseNewMenu", currentValue);
    }, "handleClose");
    return (_ctx, _cache) => {
      return show.value ? (openBlock(), createBlock(unref(script$8), {
        key: 0,
        class: "first-time-ui-message",
        severity: "info",
        closable: true,
        onClose: handleClose
      }, {
        default: withCtx(() => [
          createTextVNode(toDisplayString(_ctx.$t("g.firstTimeUIMessage")), 1)
        ]),
        _: 1
      })) : createCommentVNode("", true);
    };
  }
});
const _hoisted_1$1d = { class: "flex flex-col h-full w-full gap-2" };
const _sfc_main$1x = /* @__PURE__ */ defineComponent({
  __name: "PanelTemplate",
  props: {
    value: {},
    class: {}
  },
  setup(__props) {
    const props = __props;
    return (_ctx, _cache) => {
      return openBlock(), createBlock(unref(script$o), {
        value: props.value,
        class: normalizeClass(["h-full w-full", props.class])
      }, {
        default: withCtx(() => [
          createBaseVNode("div", _hoisted_1$1d, [
            renderSlot(_ctx.$slots, "header"),
            createVNode(unref(script$7), { class: "flex-grow h-0 pr-2" }, {
              default: withCtx(() => [
                renderSlot(_ctx.$slots, "default")
              ]),
              _: 3
            }),
            renderSlot(_ctx.$slots, "footer")
          ])
        ]),
        _: 3
      }, 8, ["value", "class"]);
    };
  }
});
const _hoisted_1$1c = {
  viewBox: "0 0 24 24",
  width: "1.2em",
  height: "1.2em"
};
function render(_ctx, _cache) {
  return openBlock(), createElementBlock("svg", _hoisted_1$1c, _cache[0] || (_cache[0] = [
    createBaseVNode("path", {
      fill: "currentColor",
      d: "M5 21q-1.275 0-1.812-1.137t.262-2.113L9 11V5H8q-.425 0-.712-.288T7 4t.288-.712T8 3h8q.425 0 .713.288T17 4t-.288.713T16 5h-1v6l5.55 6.75q.8.975.263 2.113T19 21zm2-3h10l-3.4-4h-3.2zm-2 1h14l-6-7.3V5h-2v6.7zm7-7"
    }, null, -1)
  ]));
}
__name(render, "render");
const __unplugin_components_0 = markRaw({ name: "material-symbols-experiment-outline", render });
const _sfc_main$1w = /* @__PURE__ */ defineComponent({
  __name: "CustomFormValue",
  props: {
    renderFunction: { type: Function }
  },
  setup(__props) {
    const props = __props;
    const container = ref$3(null);
    function renderContent() {
      if (container.value) {
        container.value.innerHTML = "";
        const element = props.renderFunction();
        container.value.appendChild(element);
      }
    }
    __name(renderContent, "renderContent");
    onMounted(renderContent);
    watch(() => props.renderFunction, renderContent);
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", {
        ref_key: "container",
        ref: container
      }, null, 512);
    };
  }
});
const _hoisted_1$1b = { class: "color-picker-wrapper flex items-center gap-2" };
const _sfc_main$1v = /* @__PURE__ */ defineComponent({
  ...{
    inheritAttrs: false
  },
  __name: "FormColorPicker",
  props: /* @__PURE__ */ mergeModels({
    defaultValue: {},
    label: {}
  }, {
    "modelValue": {},
    "modelModifiers": {}
  }),
  emits: ["update:modelValue"],
  setup(__props) {
    const modelValue = useModel(__props, "modelValue");
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", _hoisted_1$1b, [
        createVNode(unref(script$p), mergeProps$1({
          modelValue: modelValue.value,
          "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => modelValue.value = $event)
        }, _ctx.$attrs), null, 16, ["modelValue"]),
        createVNode(unref(script$b), {
          modelValue: modelValue.value,
          "onUpdate:modelValue": _cache[1] || (_cache[1] = ($event) => modelValue.value = $event),
          class: "w-28",
          placeholder: _ctx.label
        }, null, 8, ["modelValue", "placeholder"])
      ]);
    };
  }
});
const _hoisted_1$1a = { class: "image-upload-wrapper" };
const _hoisted_2$U = { class: "flex gap-2 items-center" };
const _hoisted_3$F = ["src"];
const _hoisted_4$s = {
  key: 1,
  class: "pi pi-image text-gray-400 text-xl"
};
const _hoisted_5$m = { class: "flex flex-col gap-2" };
const _sfc_main$1u = /* @__PURE__ */ defineComponent({
  __name: "FormImageUpload",
  props: {
    modelValue: {}
  },
  emits: ["update:modelValue"],
  setup(__props, { emit: __emit }) {
    const emit = __emit;
    const fileInput2 = ref$3(null);
    const triggerFileInput = /* @__PURE__ */ __name(() => {
      fileInput2.value?.click();
    }, "triggerFileInput");
    const handleFileUpload = /* @__PURE__ */ __name((event) => {
      const target = event.target;
      if (target.files && target.files[0]) {
        const file = target.files[0];
        const reader = new FileReader();
        reader.onload = (e2) => {
          emit("update:modelValue", e2.target?.result);
        };
        reader.readAsDataURL(file);
      }
    }, "handleFileUpload");
    const clearImage = /* @__PURE__ */ __name(() => {
      emit("update:modelValue", "");
      if (fileInput2.value) {
        fileInput2.value.value = "";
      }
    }, "clearImage");
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", _hoisted_1$1a, [
        createBaseVNode("div", _hoisted_2$U, [
          createBaseVNode("div", {
            class: normalizeClass(["preview-box border rounded p-2 w-16 h-16 flex items-center justify-center", { "bg-gray-100 dark:bg-gray-800": !_ctx.modelValue }])
          }, [
            _ctx.modelValue ? (openBlock(), createElementBlock("img", {
              key: 0,
              src: _ctx.modelValue,
              class: "max-w-full max-h-full object-contain"
            }, null, 8, _hoisted_3$F)) : (openBlock(), createElementBlock("i", _hoisted_4$s))
          ], 2),
          createBaseVNode("div", _hoisted_5$m, [
            createVNode(unref(script$6), {
              icon: "pi pi-upload",
              label: _ctx.$t("g.upload"),
              size: "small",
              onClick: triggerFileInput
            }, null, 8, ["label"]),
            _ctx.modelValue ? (openBlock(), createBlock(unref(script$6), {
              key: 0,
              class: "w-full",
              outlined: "",
              icon: "pi pi-trash",
              severity: "danger",
              size: "small",
              onClick: clearImage
            })) : createCommentVNode("", true)
          ])
        ]),
        createBaseVNode("input", {
          ref_key: "fileInput",
          ref: fileInput2,
          type: "file",
          class: "hidden",
          accept: "image/*",
          onChange: handleFileUpload
        }, null, 544)
      ]);
    };
  }
});
const _hoisted_1$19 = { class: "input-knob flex flex-row items-center gap-2" };
const _sfc_main$1t = /* @__PURE__ */ defineComponent({
  ...{
    inheritAttrs: false
  },
  __name: "InputKnob",
  props: {
    modelValue: {},
    inputClass: {},
    knobClass: {},
    min: {},
    max: {},
    step: {},
    resolution: {}
  },
  emits: ["update:modelValue"],
  setup(__props, { emit: __emit }) {
    const props = __props;
    const emit = __emit;
    const localValue = ref$3(props.modelValue);
    watch(
      () => props.modelValue,
      (newValue2) => {
        localValue.value = newValue2;
      }
    );
    const updateValue = /* @__PURE__ */ __name((newValue2) => {
      if (newValue2 === null) {
        newValue2 = Number(props.min) || 0;
      }
      const min = Number(props.min ?? Number.NEGATIVE_INFINITY);
      const max = Number(props.max ?? Number.POSITIVE_INFINITY);
      const step = Number(props.step) || 1;
      newValue2 = Math.max(min, Math.min(max, newValue2));
      newValue2 = Math.round(newValue2 / step) * step;
      localValue.value = newValue2;
      emit("update:modelValue", newValue2);
    }, "updateValue");
    const displayValue = /* @__PURE__ */ __name((value) => {
      updateValue(value);
      const stepString = (props.step ?? 1).toString();
      const resolution = stepString.includes(".") ? stepString.split(".")[1].length : 0;
      return value.toFixed(props.resolution ?? resolution);
    }, "displayValue");
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", _hoisted_1$19, [
        createVNode(unref(script$q), mergeProps$1({
          "model-value": _ctx.modelValue,
          "value-template": displayValue,
          class: ["knob-part", _ctx.knobClass],
          min: _ctx.min,
          max: _ctx.max,
          step: _ctx.step
        }, _ctx.$attrs, { "onUpdate:modelValue": updateValue }), null, 16, ["model-value", "class", "min", "max", "step"]),
        createVNode(unref(script$r), {
          "model-value": _ctx.modelValue,
          class: normalizeClass(["input-part", _ctx.inputClass]),
          "max-fraction-digits": 3,
          min: _ctx.min,
          max: _ctx.max,
          step: _ctx.step,
          "allow-empty": false,
          "onUpdate:modelValue": updateValue
        }, null, 8, ["model-value", "class", "min", "max", "step"])
      ]);
    };
  }
});
const _hoisted_1$18 = { class: "input-slider flex flex-row items-center gap-2" };
const _sfc_main$1s = /* @__PURE__ */ defineComponent({
  ...{
    inheritAttrs: false
  },
  __name: "InputSlider",
  props: {
    modelValue: {},
    inputClass: {},
    sliderClass: {},
    min: {},
    max: {},
    step: {}
  },
  emits: ["update:modelValue"],
  setup(__props, { emit: __emit }) {
    const props = __props;
    const emit = __emit;
    const localValue = ref$3(props.modelValue);
    watch(
      () => props.modelValue,
      (newValue2) => {
        localValue.value = newValue2;
      }
    );
    const updateValue = /* @__PURE__ */ __name((newValue2) => {
      if (newValue2 === null) {
        newValue2 = Number(props.min) || 0;
      }
      const min = Number(props.min ?? Number.NEGATIVE_INFINITY);
      const max = Number(props.max ?? Number.POSITIVE_INFINITY);
      const step = Number(props.step) || 1;
      newValue2 = Math.max(min, Math.min(max, newValue2));
      newValue2 = Math.round(newValue2 / step) * step;
      localValue.value = newValue2;
      emit("update:modelValue", newValue2);
    }, "updateValue");
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", _hoisted_1$18, [
        createVNode(unref(script$s), mergeProps$1({
          "model-value": _ctx.modelValue,
          class: ["slider-part", _ctx.sliderClass],
          min: _ctx.min,
          max: _ctx.max,
          step: _ctx.step
        }, _ctx.$attrs, {
          "onUpdate:modelValue": _cache[0] || (_cache[0] = (value) => updateValue(value))
        }), null, 16, ["model-value", "class", "min", "max", "step"]),
        createVNode(unref(script$r), {
          "model-value": _ctx.modelValue,
          class: normalizeClass(["input-part", _ctx.inputClass]),
          "max-fraction-digits": 3,
          min: _ctx.min,
          max: _ctx.max,
          step: _ctx.step,
          "allow-empty": false,
          "onUpdate:modelValue": updateValue
        }, null, 8, ["model-value", "class", "min", "max", "step"])
      ]);
    };
  }
});
const VALID_STATUS_CODES = [200, 201, 301, 302, 307, 308];
const checkUrlReachable = /* @__PURE__ */ __name(async (url) => {
  try {
    const response = await axios.head(url);
    return VALID_STATUS_CODES.includes(response.status);
  } catch {
    return false;
  }
}, "checkUrlReachable");
const checkMirrorReachable = /* @__PURE__ */ __name(async (mirror2) => {
  return isValidUrl(mirror2) && await electronAPI().NetWork.canAccessUrl(mirror2);
}, "checkMirrorReachable");
async function isInChina() {
  const isChineseLocale = navigator.language.toLowerCase().startsWith("zh-cn");
  try {
    const googleTest = await Promise.race([
      fetch("https://www.google.com", {
        mode: "no-cors",
        cache: "no-cache"
      }),
      new Promise((_2, reject) => setTimeout(() => reject(), 2e3))
    ]);
    if (googleTest) {
      return false;
    }
  } catch {
    if (isChineseLocale) {
      return true;
    }
    try {
      const start2 = performance.now();
      await fetch("https://www.baidu.com", {
        mode: "no-cors",
        cache: "no-cache"
      });
      const latency = performance.now() - start2;
      return latency < 150;
    } catch {
      return isChineseLocale;
    }
  }
  return false;
}
__name(isInChina, "isInChina");
var ValidationState = /* @__PURE__ */ ((ValidationState2) => {
  ValidationState2["IDLE"] = "IDLE";
  ValidationState2["LOADING"] = "LOADING";
  ValidationState2["VALID"] = "VALID";
  ValidationState2["INVALID"] = "INVALID";
  return ValidationState2;
})(ValidationState || {});
const mergeValidationStates = /* @__PURE__ */ __name((states) => {
  if (states.some(
    (state) => state === "INVALID"
    /* INVALID */
  )) {
    return "INVALID";
  }
  if (states.some(
    (state) => state === "LOADING"
    /* LOADING */
  )) {
    return "LOADING";
  }
  if (states.every(
    (state) => state === "VALID"
    /* VALID */
  )) {
    return "VALID";
  }
  return "IDLE";
}, "mergeValidationStates");
const _sfc_main$1r = /* @__PURE__ */ defineComponent({
  ...{
    inheritAttrs: false
  },
  __name: "UrlInput",
  props: {
    modelValue: {},
    validateUrlFn: { type: Function }
  },
  emits: ["update:modelValue", "state-change"],
  setup(__props, { emit: __emit }) {
    const props = __props;
    const emit = __emit;
    const validationState = ref$3(ValidationState.IDLE);
    const cleanInput = /* @__PURE__ */ __name((value) => value ? value.replace(/\s+/g, "") : "", "cleanInput");
    const internalValue = ref$3(cleanInput(props.modelValue));
    watch(
      () => props.modelValue,
      async (newValue2) => {
        internalValue.value = cleanInput(newValue2);
        await validateUrl2(newValue2);
      }
    );
    watch(validationState, (newState) => {
      emit("state-change", newState);
    });
    onMounted(async () => {
      await validateUrl2(props.modelValue);
    });
    const handleInput = /* @__PURE__ */ __name((value) => {
      internalValue.value = cleanInput(value ?? "");
      validationState.value = ValidationState.IDLE;
    }, "handleInput");
    const handleBlur = /* @__PURE__ */ __name(async () => {
      const input = cleanInput(internalValue.value);
      let normalizedUrl = input;
      try {
        const url = new URL(input);
        normalizedUrl = url.toString();
      } catch {
      }
      emit("update:modelValue", normalizedUrl);
    }, "handleBlur");
    const defaultValidateUrl = /* @__PURE__ */ __name(async (url) => {
      if (!isValidUrl(url)) return false;
      try {
        return await checkUrlReachable(url);
      } catch {
        return false;
      }
    }, "defaultValidateUrl");
    const validateUrl2 = /* @__PURE__ */ __name(async (value) => {
      if (validationState.value === ValidationState.LOADING) return;
      const url = cleanInput(value);
      validationState.value = ValidationState.IDLE;
      if (!url) return;
      validationState.value = ValidationState.LOADING;
      try {
        const isValid2 = await (props.validateUrlFn ?? defaultValidateUrl)(url);
        validationState.value = isValid2 ? ValidationState.VALID : ValidationState.INVALID;
      } catch {
        validationState.value = ValidationState.INVALID;
      }
    }, "validateUrl");
    return (_ctx, _cache) => {
      return openBlock(), createBlock(unref(script$l), { class: "w-full" }, {
        default: withCtx(() => [
          createVNode(unref(script$b), mergeProps$1(_ctx.$attrs, {
            "model-value": internalValue.value,
            class: "w-full",
            invalid: validationState.value === unref(ValidationState).INVALID,
            "onUpdate:modelValue": handleInput,
            onBlur: handleBlur
          }), null, 16, ["model-value", "invalid"]),
          createVNode(unref(script$m), {
            class: normalizeClass({
              "pi pi-spin pi-spinner text-neutral-400": validationState.value === unref(ValidationState).LOADING,
              "pi pi-check text-green-500 cursor-pointer": validationState.value === unref(ValidationState).VALID,
              "pi pi-times text-red-500 cursor-pointer": validationState.value === unref(ValidationState).INVALID
            }),
            onClick: _cache[0] || (_cache[0] = ($event) => validateUrl2(props.modelValue))
          }, null, 8, ["class"])
        ]),
        _: 1
      });
    };
  }
});
const _hoisted_1$17 = { class: "flex flex-row items-center gap-2" };
const _hoisted_2$T = { class: "form-label flex flex-grow items-center" };
const _hoisted_3$E = ["id"];
const _hoisted_4$r = {
  key: 0,
  class: "pi pi-info-circle bg-transparent"
};
const _hoisted_5$l = { class: "form-input flex justify-end" };
const _sfc_main$1q = /* @__PURE__ */ defineComponent({
  __name: "FormItem",
  props: /* @__PURE__ */ mergeModels({
    item: {},
    id: {},
    labelClass: {}
  }, {
    "formValue": {},
    "formValueModifiers": {}
  }),
  emits: ["update:formValue"],
  setup(__props) {
    const formValue = useModel(__props, "formValue");
    const props = __props;
    function getFormAttrs(item) {
      const attrs2 = { ...item.attrs || {} };
      const inputType = item.type;
      if (typeof inputType === "function") {
        attrs2["renderFunction"] = () => inputType(
          props.item.name,
          (v2) => formValue.value = v2,
          formValue.value,
          item.attrs
        );
      }
      switch (item.type) {
        case "combo":
          attrs2["options"] = typeof item.options === "function" ? (
            // @ts-expect-error: Audit and deprecate usage of legacy options type:
            // (value) => [string | {text: string, value: string}]
            item.options(formValue.value)
          ) : item.options;
          if (typeof item.options?.[0] !== "string") {
            attrs2["optionLabel"] = "text";
            attrs2["optionValue"] = "value";
          }
          break;
      }
      return attrs2;
    }
    __name(getFormAttrs, "getFormAttrs");
    function getFormComponent(item) {
      if (typeof item.type === "function") {
        return _sfc_main$1w;
      }
      switch (item.type) {
        case "boolean":
          return script$t;
        case "number":
          return script$r;
        case "slider":
          return _sfc_main$1s;
        case "knob":
          return _sfc_main$1t;
        case "combo":
          return script$n;
        case "image":
          return _sfc_main$1u;
        case "color":
          return _sfc_main$1v;
        case "url":
          return _sfc_main$1r;
        default:
          return script$b;
      }
    }
    __name(getFormComponent, "getFormComponent");
    return (_ctx, _cache) => {
      const _directive_tooltip = resolveDirective("tooltip");
      return openBlock(), createElementBlock("div", _hoisted_1$17, [
        createBaseVNode("div", _hoisted_2$T, [
          createBaseVNode("span", {
            id: `${props.id}-label`,
            class: normalizeClass(["text-muted", props.labelClass])
          }, [
            renderSlot(_ctx.$slots, "name-prefix", {}, void 0, true),
            createTextVNode(" " + toDisplayString(props.item.name) + " ", 1),
            props.item.tooltip ? withDirectives((openBlock(), createElementBlock("i", _hoisted_4$r, null, 512)), [
              [_directive_tooltip, props.item.tooltip]
            ]) : createCommentVNode("", true),
            renderSlot(_ctx.$slots, "name-suffix", {}, void 0, true)
          ], 10, _hoisted_3$E)
        ]),
        createBaseVNode("div", _hoisted_5$l, [
          (openBlock(), createBlock(resolveDynamicComponent(markRaw(getFormComponent(props.item))), mergeProps$1({
            id: props.id,
            modelValue: formValue.value,
            "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => formValue.value = $event),
            "aria-labelledby": `${props.id}-label`
          }, getFormAttrs(props.item)), null, 16, ["id", "modelValue", "aria-labelledby"]))
        ])
      ]);
    };
  }
});
const FormItem = /* @__PURE__ */ _export_sfc(_sfc_main$1q, [["__scopeId", "data-v-6a06131d"]]);
const _sfc_main$1p = /* @__PURE__ */ defineComponent({
  __name: "SettingItem",
  props: {
    setting: {}
  },
  setup(__props) {
    const props = __props;
    const { t: t2 } = useI18n();
    function translateOptions(options2) {
      if (typeof options2 === "function") {
        return translateOptions(options2(props.setting.value ?? ""));
      }
      return options2.map((option) => {
        const optionLabel = typeof option === "string" ? option : option.text;
        const optionValue = typeof option === "string" ? option : option.value;
        return {
          text: t2(
            `settings.${normalizeI18nKey(props.setting.id)}.options.${normalizeI18nKey(optionLabel)}`,
            optionLabel
          ),
          value: optionValue
        };
      });
    }
    __name(translateOptions, "translateOptions");
    const formItem = computed(() => {
      const normalizedId = normalizeI18nKey(props.setting.id);
      return {
        ...props.setting,
        name: t2(`settings.${normalizedId}.name`, props.setting.name),
        tooltip: props.setting.tooltip ? t2(`settings.${normalizedId}.tooltip`, props.setting.tooltip) : void 0,
        options: props.setting.options ? translateOptions(props.setting.options) : void 0
      };
    });
    const settingStore = useSettingStore();
    const settingValue = computed(() => settingStore.get(props.setting.id));
    const updateSettingValue = /* @__PURE__ */ __name(async (value) => {
      await settingStore.set(props.setting.id, value);
    }, "updateSettingValue");
    return (_ctx, _cache) => {
      const _component_i_material_symbols58experiment_outline = __unplugin_components_0;
      const _directive_tooltip = resolveDirective("tooltip");
      return openBlock(), createBlock(FormItem, {
        id: _ctx.setting.id,
        item: formItem.value,
        "form-value": settingValue.value,
        "onUpdate:formValue": updateSettingValue
      }, {
        "name-prefix": withCtx(() => [
          _ctx.setting.id === "Comfy.Locale" ? (openBlock(), createBlock(unref(script$5), {
            key: 0,
            class: "pi pi-language"
          })) : createCommentVNode("", true),
          _ctx.setting.experimental ? withDirectives((openBlock(), createBlock(unref(script$5), { key: 1 }, {
            icon: withCtx(() => [
              createVNode(_component_i_material_symbols58experiment_outline)
            ]),
            _: 1
          })), [
            [_directive_tooltip, {
              value: _ctx.$t("g.experimental"),
              showDelay: 600
            }]
          ]) : createCommentVNode("", true)
        ]),
        _: 1
      }, 8, ["id", "item", "form-value"]);
    };
  }
});
const _hoisted_1$16 = { class: "setting-group" };
const _sfc_main$1o = /* @__PURE__ */ defineComponent({
  __name: "SettingGroup",
  props: {
    group: {},
    divider: { type: Boolean }
  },
  setup(__props) {
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", _hoisted_1$16, [
        _ctx.divider ? (openBlock(), createBlock(unref(script$f), { key: 0 })) : createCommentVNode("", true),
        createBaseVNode("h3", null, toDisplayString(_ctx.$t(`settingsCategories.${unref(normalizeI18nKey)(_ctx.group.label)}`, _ctx.group.label)), 1),
        (openBlock(true), createElementBlock(Fragment$1, null, renderList(_ctx.group.settings.filter((s2) => !s2.deprecated), (setting) => {
          return openBlock(), createElementBlock("div", {
            key: setting.id,
            class: "setting-item mb-4"
          }, [
            createVNode(_sfc_main$1p, { setting }, null, 8, ["setting"])
          ]);
        }), 128))
      ]);
    };
  }
});
const _hoisted_1$15 = { key: 0 };
const _sfc_main$1n = /* @__PURE__ */ defineComponent({
  __name: "SettingsPanel",
  props: {
    settingGroups: {}
  },
  setup(__props) {
    const props = __props;
    return (_ctx, _cache) => {
      return props.settingGroups.length > 0 ? (openBlock(), createElementBlock("div", _hoisted_1$15, [
        (openBlock(true), createElementBlock(Fragment$1, null, renderList(props.settingGroups, (group, i2) => {
          return openBlock(), createBlock(_sfc_main$1o, {
            key: group.label,
            divider: i2 !== 0,
            group
          }, null, 8, ["divider", "group"]);
        }), 128))
      ])) : (openBlock(), createBlock(NoResultsPlaceholder, {
        key: 1,
        icon: "pi pi-search",
        title: _ctx.$t("g.noResultsFound"),
        message: _ctx.$t("g.searchFailedMessage")
      }, null, 8, ["title", "message"]));
    };
  }
});
const _hoisted_1$14 = { class: "settings-container" };
const _sfc_main$1m = /* @__PURE__ */ defineComponent({
  __name: "SettingDialogContent",
  props: {
    defaultPanel: {}
  },
  setup(__props) {
    const {
      activeCategory,
      defaultCategory,
      settingCategories,
      groupedMenuTreeNodes,
      panels
    } = useSettingUI(__props.defaultPanel);
    const {
      searchQuery,
      searchResultsCategories,
      queryIsEmpty,
      inSearch,
      handleSearch: handleSearchBase,
      getSearchResults
    } = useSettingSearch();
    const authActions = useFirebaseAuthActions();
    const sortedGroups = /* @__PURE__ */ __name((category) => {
      return [...category.children ?? []].sort((a2, b2) => a2.label.localeCompare(b2.label)).map((group) => ({
        label: group.label,
        settings: flattenTree(group)
      }));
    }, "sortedGroups");
    const handleSearch = /* @__PURE__ */ __name((query2) => {
      handleSearchBase(query2);
      activeCategory.value = query2 ? null : defaultCategory.value;
    }, "handleSearch");
    const searchResults = computed(
      () => getSearchResults(activeCategory.value)
    );
    const tabValue = computed(
      () => inSearch.value ? "Search Results" : activeCategory.value?.label ?? ""
    );
    watch(activeCategory, (_2, oldValue) => {
      if (!tabValue.value) {
        activeCategory.value = oldValue;
      }
      if (activeCategory.value?.key === "credits") {
        void authActions.fetchBalance();
      }
    });
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", _hoisted_1$14, [
        createVNode(unref(script$7), { class: "settings-sidebar flex-shrink-0 p-2 w-48 2xl:w-64" }, {
          default: withCtx(() => [
            createVNode(SearchBox, {
              modelValue: unref(searchQuery),
              "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => isRef(searchQuery) ? searchQuery.value = $event : null),
              class: "settings-search-box w-full mb-2",
              placeholder: _ctx.$t("g.searchSettings") + "...",
              "debounce-time": 128,
              onSearch: handleSearch
            }, null, 8, ["modelValue", "placeholder"]),
            createVNode(unref(script$g), {
              modelValue: unref(activeCategory),
              "onUpdate:modelValue": _cache[1] || (_cache[1] = ($event) => isRef(activeCategory) ? activeCategory.value = $event : null),
              options: unref(groupedMenuTreeNodes),
              "option-label": "translatedLabel",
              "option-group-label": "label",
              "option-group-children": "children",
              "scroll-height": "100%",
              "option-disabled": /* @__PURE__ */ __name((option) => !unref(queryIsEmpty) && !unref(searchResultsCategories).has(option.label ?? ""), "option-disabled"),
              class: "border-none w-full"
            }, {
              optiongroup: withCtx(() => [
                createVNode(unref(script$f), { class: "my-0" })
              ]),
              _: 1
            }, 8, ["modelValue", "options", "option-disabled"])
          ]),
          _: 1
        }),
        createVNode(unref(script$f), {
          layout: "vertical",
          class: "mx-1 2xl:mx-4 hidden md:flex"
        }),
        createVNode(unref(script$f), {
          layout: "horizontal",
          class: "flex md:hidden"
        }),
        createVNode(unref(script$u), {
          value: tabValue.value,
          lazy: true,
          class: "settings-content h-full w-full"
        }, {
          default: withCtx(() => [
            createVNode(unref(script$v), { class: "settings-tab-panels h-full w-full pr-0" }, {
              default: withCtx(() => [
                createVNode(_sfc_main$1x, { value: "Search Results" }, {
                  default: withCtx(() => [
                    createVNode(_sfc_main$1n, { "setting-groups": searchResults.value }, null, 8, ["setting-groups"])
                  ]),
                  _: 1
                }),
                (openBlock(true), createElementBlock(Fragment$1, null, renderList(unref(settingCategories), (category) => {
                  return openBlock(), createBlock(_sfc_main$1x, {
                    key: category.key,
                    value: category.label ?? ""
                  }, {
                    header: withCtx(() => [
                      tabValue.value === "Comfy" ? (openBlock(), createBlock(_sfc_main$1z, { key: 0 })) : createCommentVNode("", true),
                      tabValue.value === "Comfy" ? (openBlock(), createBlock(_sfc_main$1y, { key: 1 })) : createCommentVNode("", true),
                      tabValue.value === "Appearance" ? (openBlock(), createBlock(_sfc_main$1A, { key: 2 })) : createCommentVNode("", true)
                    ]),
                    default: withCtx(() => [
                      createVNode(_sfc_main$1n, {
                        "setting-groups": sortedGroups(category)
                      }, null, 8, ["setting-groups"])
                    ]),
                    _: 2
                  }, 1032, ["value"]);
                }), 128)),
                (openBlock(true), createElementBlock(Fragment$1, null, renderList(unref(panels), (panel) => {
                  return openBlock(), createBlock(Suspense, {
                    key: panel.node.key
                  }, {
                    fallback: withCtx(() => [
                      createBaseVNode("div", null, "Loading " + toDisplayString(panel.node.label) + " panel...", 1)
                    ]),
                    default: withCtx(() => [
                      (openBlock(), createBlock(resolveDynamicComponent(panel.component)))
                    ]),
                    _: 2
                  }, 1024);
                }), 128))
              ]),
              _: 1
            })
          ]),
          _: 1
        }, 8, ["value"])
      ]);
    };
  }
});
const SettingDialogContent = /* @__PURE__ */ _export_sfc(_sfc_main$1m, [["__scopeId", "data-v-720e4b9a"]]);
const _imports_0$1 = "" + new URL("images/comfy-logo-mono.svg", import.meta.url).href;
const apiKeySchema = z.object({
  apiKey: z.string().trim().startsWith("comfyui-", t("validation.prefix", { prefix: "comfyui-" })).length(72, t("validation.length", { length: 72 }))
});
const signInSchema = z.object({
  email: z.string().email(t("validation.invalidEmail")).min(1, t("validation.required")),
  password: z.string().min(1, t("validation.required"))
});
const passwordSchema = z.object({
  password: z.string().min(8, t("validation.minLength", { length: 8 })).max(32, t("validation.maxLength", { length: 32 })).regex(/[A-Z]/, t("validation.password.uppercase")).regex(/[a-z]/, t("validation.password.lowercase")).regex(/\d/, t("validation.password.number")).regex(/[^A-Za-z0-9]/, t("validation.password.special")),
  confirmPassword: z.string().min(1, t("validation.required"))
});
const updatePasswordSchema = passwordSchema.refine(
  (data) => data.password === data.confirmPassword,
  {
    message: t("validation.password.match"),
    path: ["confirmPassword"]
  }
);
const signUpSchema = passwordSchema.extend({
  email: z.string().email(t("validation.invalidEmail")).min(1, t("validation.required")),
  personalDataConsent: z.boolean()
}).refine((data) => data.password === data.confirmPassword, {
  message: t("validation.password.match"),
  path: ["confirmPassword"]
}).refine((data) => data.personalDataConsent === true, {
  message: t("validation.personalDataConsentRequired"),
  path: ["personalDataConsent"]
});
const _hoisted_1$13 = { class: "flex flex-col gap-6" };
const _hoisted_2$S = { class: "flex flex-col gap-4 mb-8" };
const _hoisted_3$D = { class: "text-2xl font-medium leading-normal my-0" };
const _hoisted_4$q = { class: "flex flex-col gap-2" };
const _hoisted_5$k = { class: "text-base my-0 text-muted" };
const _hoisted_6$h = {
  href: "https://docs.comfy.org/interface/user#logging-in-with-an-api-key",
  target: "_blank",
  class: "text-blue-500 cursor-pointer"
};
const _hoisted_7$b = { class: "flex flex-col gap-2" };
const _hoisted_8$8 = {
  class: "opacity-80 text-base font-medium mb-2",
  for: "comfy-org-api-key"
};
const _hoisted_9$6 = { class: "flex flex-col gap-2" };
const _hoisted_10$6 = { class: "text-muted" };
const _hoisted_11$5 = ["href"];
const _hoisted_12$3 = {
  href: "https://docs.comfy.org/tutorials/api-nodes/overview#log-in-with-api-key-on-non-whitelisted-websites",
  target: "_blank",
  class: "text-blue-500 cursor-pointer"
};
const _hoisted_13$1 = { class: "flex justify-between items-center mt-4" };
const _sfc_main$1l = /* @__PURE__ */ defineComponent({
  __name: "ApiKeyForm",
  emits: ["back", "success"],
  setup(__props, { emit: __emit }) {
    const authStore = useFirebaseAuthStore();
    const apiKeyStore = useApiKeyAuthStore();
    const loading = computed(() => authStore.loading);
    const { t: t2 } = useI18n();
    const emit = __emit;
    const onSubmit = /* @__PURE__ */ __name(async (event) => {
      if (event.valid) {
        await apiKeyStore.storeApiKey(event.values.apiKey);
        emit("success");
      }
    }, "onSubmit");
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", _hoisted_1$13, [
        createBaseVNode("div", _hoisted_2$S, [
          createBaseVNode("h1", _hoisted_3$D, toDisplayString(unref(t2)("auth.apiKey.title")), 1),
          createBaseVNode("div", _hoisted_4$q, [
            createBaseVNode("p", _hoisted_5$k, toDisplayString(unref(t2)("auth.apiKey.description")), 1),
            createBaseVNode("a", _hoisted_6$h, toDisplayString(unref(t2)("g.learnMore")), 1)
          ])
        ]),
        createVNode(unref(script$2), {
          class: "flex flex-col gap-6",
          resolver: unref(zodResolver)(unref(apiKeySchema)),
          onSubmit
        }, {
          default: withCtx(($form) => [
            $form.apiKey?.invalid ? (openBlock(), createBlock(unref(script$8), {
              key: 0,
              severity: "error",
              class: "mb-4"
            }, {
              default: withCtx(() => [
                createTextVNode(toDisplayString($form.apiKey.error.message), 1)
              ]),
              _: 2
            }, 1024)) : createCommentVNode("", true),
            createBaseVNode("div", _hoisted_7$b, [
              createBaseVNode("label", _hoisted_8$8, toDisplayString(unref(t2)("auth.apiKey.label")), 1),
              createBaseVNode("div", _hoisted_9$6, [
                createVNode(unref(script$b), {
                  "pt:root:id": "comfy-org-api-key",
                  "pt:root:autocomplete": "off",
                  class: "h-10",
                  name: "apiKey",
                  type: "password",
                  placeholder: unref(t2)("auth.apiKey.placeholder"),
                  invalid: $form.apiKey?.invalid
                }, null, 8, ["placeholder", "invalid"]),
                createBaseVNode("small", _hoisted_10$6, [
                  createTextVNode(toDisplayString(unref(t2)("auth.apiKey.helpText")) + " ", 1),
                  createBaseVNode("a", {
                    href: `${unref(COMFY_PLATFORM_BASE_URL)}/login`,
                    target: "_blank",
                    class: "text-blue-500 cursor-pointer"
                  }, toDisplayString(unref(t2)("auth.apiKey.generateKey")), 9, _hoisted_11$5),
                  _cache[1] || (_cache[1] = createBaseVNode("span", { class: "mx-1" }, "•", -1)),
                  createBaseVNode("a", _hoisted_12$3, toDisplayString(unref(t2)("auth.apiKey.whitelistInfo")), 1)
                ])
              ])
            ]),
            createBaseVNode("div", _hoisted_13$1, [
              createVNode(unref(script$6), {
                type: "button",
                link: "",
                onClick: _cache[0] || (_cache[0] = ($event) => _ctx.$emit("back"))
              }, {
                default: withCtx(() => [
                  createTextVNode(toDisplayString(unref(t2)("g.back")), 1)
                ]),
                _: 1
              }),
              createVNode(unref(script$6), {
                type: "submit",
                loading: loading.value,
                disabled: loading.value
              }, {
                default: withCtx(() => [
                  createTextVNode(toDisplayString(unref(t2)("g.save")), 1)
                ]),
                _: 1
              }, 8, ["loading", "disabled"])
            ])
          ]),
          _: 1
        }, 8, ["resolver"])
      ]);
    };
  }
});
const _hoisted_1$12 = { class: "flex flex-col gap-2" };
const _hoisted_2$R = {
  class: "opacity-80 text-base font-medium mb-2",
  for: "comfy-org-sign-in-email"
};
const _hoisted_3$C = {
  key: 0,
  class: "text-red-500"
};
const _hoisted_4$p = { class: "flex flex-col gap-2" };
const _hoisted_5$j = { class: "flex justify-between items-center mb-2" };
const _hoisted_6$g = {
  class: "opacity-80 text-base font-medium",
  for: "comfy-org-sign-in-password"
};
const _hoisted_7$a = ["onClick"];
const _hoisted_8$7 = {
  key: 0,
  class: "text-red-500"
};
const _sfc_main$1k = /* @__PURE__ */ defineComponent({
  __name: "SignInForm",
  emits: ["submit"],
  setup(__props, { emit: __emit }) {
    const authStore = useFirebaseAuthStore();
    const firebaseAuthActions = useFirebaseAuthActions();
    const loading = computed(() => authStore.loading);
    const { t: t2 } = useI18n();
    const emit = __emit;
    const onSubmit = /* @__PURE__ */ __name((event) => {
      if (event.valid) {
        emit("submit", event.values);
      }
    }, "onSubmit");
    const handleForgotPassword = /* @__PURE__ */ __name(async (email) => {
      if (!email) return;
      await firebaseAuthActions.sendPasswordReset(email);
    }, "handleForgotPassword");
    return (_ctx, _cache) => {
      return openBlock(), createBlock(unref(script$2), {
        class: "flex flex-col gap-6",
        resolver: unref(zodResolver)(unref(signInSchema)),
        onSubmit
      }, {
        default: withCtx(($form) => [
          createBaseVNode("div", _hoisted_1$12, [
            createBaseVNode("label", _hoisted_2$R, toDisplayString(unref(t2)("auth.login.emailLabel")), 1),
            createVNode(unref(script$b), {
              "pt:root:id": "comfy-org-sign-in-email",
              "pt:root:autocomplete": "email",
              class: "h-10",
              name: "email",
              type: "text",
              placeholder: unref(t2)("auth.login.emailPlaceholder"),
              invalid: $form.email?.invalid
            }, null, 8, ["placeholder", "invalid"]),
            $form.email?.invalid ? (openBlock(), createElementBlock("small", _hoisted_3$C, toDisplayString($form.email.error.message), 1)) : createCommentVNode("", true)
          ]),
          createBaseVNode("div", _hoisted_4$p, [
            createBaseVNode("div", _hoisted_5$j, [
              createBaseVNode("label", _hoisted_6$g, toDisplayString(unref(t2)("auth.login.passwordLabel")), 1),
              createBaseVNode("span", {
                class: "text-muted text-base font-medium cursor-pointer",
                onClick: /* @__PURE__ */ __name(($event) => handleForgotPassword($form.email?.value), "onClick")
              }, toDisplayString(unref(t2)("auth.login.forgotPassword")), 9, _hoisted_7$a)
            ]),
            createVNode(unref(script$w), {
              "input-id": "comfy-org-sign-in-password",
              "pt:pc-input-text:root:autocomplete": "current-password",
              name: "password",
              feedback: false,
              "toggle-mask": "",
              placeholder: unref(t2)("auth.login.passwordPlaceholder"),
              class: normalizeClass([{ "p-invalid": $form.password?.invalid }, "h-10"]),
              fluid: ""
            }, null, 8, ["placeholder", "class"]),
            $form.password?.invalid ? (openBlock(), createElementBlock("small", _hoisted_8$7, toDisplayString($form.password.error.message), 1)) : createCommentVNode("", true)
          ]),
          loading.value ? (openBlock(), createBlock(unref(script$x), {
            key: 0,
            class: "w-8 h-8"
          })) : (openBlock(), createBlock(unref(script$6), {
            key: 1,
            type: "submit",
            label: unref(t2)("auth.login.loginButton"),
            class: "h-10 font-medium mt-4"
          }, null, 8, ["label"]))
        ]),
        _: 1
      }, 8, ["resolver"]);
    };
  }
});
const _hoisted_1$11 = { class: "flex justify-between items-center mb-2" };
const _hoisted_2$Q = {
  class: "opacity-80 text-base font-medium",
  for: "comfy-org-sign-up-password"
};
const _hoisted_3$B = { class: "flex flex-col gap-1" };
const _hoisted_4$o = {
  key: 0,
  class: "text-sm"
};
const _hoisted_5$i = { class: "mt-1 space-y-1" };
const _hoisted_6$f = {
  class: "opacity-80 text-base font-medium mb-2",
  for: "comfy-org-sign-up-confirm-password"
};
const _hoisted_7$9 = {
  key: 0,
  class: "text-red-500"
};
const _sfc_main$1j = /* @__PURE__ */ defineComponent({
  __name: "PasswordFields",
  setup(__props) {
    const { t: t2 } = useI18n();
    const password = ref$3("");
    const passwordChecks = computed(() => ({
      length: password.value.length >= 8 && password.value.length <= 32,
      uppercase: /[A-Z]/.test(password.value),
      lowercase: /[a-z]/.test(password.value),
      number: /\d/.test(password.value),
      special: /[^A-Za-z0-9]/.test(password.value)
    }));
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock(Fragment$1, null, [
        createVNode(unref(script), {
          name: "password",
          class: "flex flex-col gap-2"
        }, {
          default: withCtx(($field) => [
            createBaseVNode("div", _hoisted_1$11, [
              createBaseVNode("label", _hoisted_2$Q, toDisplayString(unref(t2)("auth.signup.passwordLabel")), 1)
            ]),
            createVNode(unref(script$w), {
              modelValue: password.value,
              "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => password.value = $event),
              "input-id": "comfy-org-sign-up-password",
              "pt:pc-input-text:root:autocomplete": "new-password",
              name: "password",
              feedback: false,
              "toggle-mask": "",
              placeholder: unref(t2)("auth.signup.passwordPlaceholder"),
              class: normalizeClass([{ "p-invalid": $field.invalid }, "h-10"]),
              fluid: ""
            }, null, 8, ["modelValue", "placeholder", "class"]),
            createBaseVNode("div", _hoisted_3$B, [
              $field.dirty || $field.invalid ? (openBlock(), createElementBlock("small", _hoisted_4$o, [
                createTextVNode(toDisplayString(unref(t2)("validation.password.requirements")) + ": ", 1),
                createBaseVNode("ul", _hoisted_5$i, [
                  createBaseVNode("li", {
                    class: normalizeClass({
                      "text-red-500": !passwordChecks.value.length
                    })
                  }, toDisplayString(unref(t2)("validation.password.minLength")), 3),
                  createBaseVNode("li", {
                    class: normalizeClass({
                      "text-red-500": !passwordChecks.value.uppercase
                    })
                  }, toDisplayString(unref(t2)("validation.password.uppercase")), 3),
                  createBaseVNode("li", {
                    class: normalizeClass({
                      "text-red-500": !passwordChecks.value.lowercase
                    })
                  }, toDisplayString(unref(t2)("validation.password.lowercase")), 3),
                  createBaseVNode("li", {
                    class: normalizeClass({
                      "text-red-500": !passwordChecks.value.number
                    })
                  }, toDisplayString(unref(t2)("validation.password.number")), 3),
                  createBaseVNode("li", {
                    class: normalizeClass({
                      "text-red-500": !passwordChecks.value.special
                    })
                  }, toDisplayString(unref(t2)("validation.password.special")), 3)
                ])
              ])) : createCommentVNode("", true)
            ])
          ]),
          _: 1
        }),
        createVNode(unref(script), {
          name: "confirmPassword",
          class: "flex flex-col gap-2"
        }, {
          default: withCtx(($field) => [
            createBaseVNode("label", _hoisted_6$f, toDisplayString(unref(t2)("auth.login.confirmPasswordLabel")), 1),
            createVNode(unref(script$w), {
              name: "confirmPassword",
              "input-id": "comfy-org-sign-up-confirm-password",
              "pt:pc-input-text:root:autocomplete": "new-password",
              feedback: false,
              "toggle-mask": "",
              placeholder: unref(t2)("auth.login.confirmPasswordPlaceholder"),
              class: normalizeClass([{ "p-invalid": $field.invalid }, "h-10"]),
              fluid: ""
            }, null, 8, ["placeholder", "class"]),
            $field.error ? (openBlock(), createElementBlock("small", _hoisted_7$9, toDisplayString($field.error.message), 1)) : createCommentVNode("", true)
          ]),
          _: 1
        })
      ], 64);
    };
  }
});
const _hoisted_1$10 = {
  class: "opacity-80 text-base font-medium mb-2",
  for: "comfy-org-sign-up-email"
};
const _hoisted_2$P = {
  key: 0,
  class: "text-red-500"
};
const _hoisted_3$A = {
  for: "comfy-org-sign-up-personal-data-consent",
  class: "opacity-80 text-base font-medium"
};
const _hoisted_4$n = {
  key: 0,
  class: "text-red-500 -mt-4"
};
const _sfc_main$1i = /* @__PURE__ */ defineComponent({
  __name: "SignUpForm",
  emits: ["submit"],
  setup(__props, { emit: __emit }) {
    const { t: t2 } = useI18n();
    const emit = __emit;
    const onSubmit = /* @__PURE__ */ __name((event) => {
      if (event.valid) {
        emit("submit", event.values);
      }
    }, "onSubmit");
    return (_ctx, _cache) => {
      return openBlock(), createBlock(unref(script$2), {
        class: "flex flex-col gap-6",
        resolver: unref(zodResolver)(unref(signUpSchema)),
        onSubmit
      }, {
        default: withCtx(() => [
          createVNode(unref(script), {
            name: "email",
            class: "flex flex-col gap-2"
          }, {
            default: withCtx(($field) => [
              createBaseVNode("label", _hoisted_1$10, toDisplayString(unref(t2)("auth.signup.emailLabel")), 1),
              createVNode(unref(script$b), {
                "pt:root:id": "comfy-org-sign-up-email",
                "pt:root:autocomplete": "email",
                class: "h-10",
                type: "text",
                placeholder: unref(t2)("auth.signup.emailPlaceholder"),
                invalid: $field.invalid
              }, null, 8, ["placeholder", "invalid"]),
              $field.error ? (openBlock(), createElementBlock("small", _hoisted_2$P, toDisplayString($field.error.message), 1)) : createCommentVNode("", true)
            ]),
            _: 1
          }),
          createVNode(_sfc_main$1j),
          createVNode(unref(script), {
            name: "personalDataConsent",
            class: "flex items-center gap-2"
          }, {
            default: withCtx(($field) => [
              createVNode(unref(script$d), {
                "input-id": "comfy-org-sign-up-personal-data-consent",
                binary: true,
                invalid: $field.invalid
              }, null, 8, ["invalid"]),
              createBaseVNode("label", _hoisted_3$A, toDisplayString(unref(t2)("auth.signup.personalDataConsentLabel")), 1),
              $field.error ? (openBlock(), createElementBlock("small", _hoisted_4$n, toDisplayString($field.error.message), 1)) : createCommentVNode("", true)
            ]),
            _: 1
          }),
          createVNode(unref(script$6), {
            type: "submit",
            label: unref(t2)("auth.signup.signUpButton"),
            class: "h-10 font-medium mt-4"
          }, null, 8, ["label"])
        ]),
        _: 1
      }, 8, ["resolver"]);
    };
  }
});
const _hoisted_1$$ = { class: "w-96 p-2 overflow-x-hidden" };
const _hoisted_2$O = { class: "flex flex-col gap-4 mb-8" };
const _hoisted_3$z = { class: "text-2xl font-medium leading-normal my-0" };
const _hoisted_4$m = { class: "text-base my-0" };
const _hoisted_5$h = { class: "text-muted" };
const _hoisted_6$e = { class: "text-muted" };
const _hoisted_7$8 = { class: "flex flex-col gap-6" };
const _hoisted_8$6 = { class: "text-muted text-center" };
const _hoisted_9$5 = ["href"];
const _hoisted_10$5 = { class: "text-xs text-muted mt-8" };
const _hoisted_11$4 = {
  href: "https://www.comfy.org/terms-of-service",
  target: "_blank",
  class: "text-blue-500 cursor-pointer"
};
const _hoisted_12$2 = {
  href: "https://www.comfy.org/privacy",
  target: "_blank",
  class: "text-blue-500 cursor-pointer"
};
const _sfc_main$1h = /* @__PURE__ */ defineComponent({
  __name: "SignInContent",
  props: {
    onSuccess: { type: Function }
  },
  setup(__props) {
    const { t: t2 } = useI18n();
    const authActions = useFirebaseAuthActions();
    const isSecureContext2 = window.isSecureContext;
    const isSignIn = ref$3(true);
    const showApiKeyForm = ref$3(false);
    const toggleState = /* @__PURE__ */ __name(() => {
      isSignIn.value = !isSignIn.value;
      showApiKeyForm.value = false;
    }, "toggleState");
    const signInWithGoogle = /* @__PURE__ */ __name(async () => {
      if (await authActions.signInWithGoogle()) {
        __props.onSuccess();
      }
    }, "signInWithGoogle");
    const signInWithGithub = /* @__PURE__ */ __name(async () => {
      if (await authActions.signInWithGithub()) {
        __props.onSuccess();
      }
    }, "signInWithGithub");
    const signInWithEmail = /* @__PURE__ */ __name(async (values) => {
      if (await authActions.signInWithEmail(values.email, values.password)) {
        __props.onSuccess();
      }
    }, "signInWithEmail");
    const signUpWithEmail = /* @__PURE__ */ __name(async (values) => {
      if (await authActions.signUpWithEmail(values.email, values.password)) {
        __props.onSuccess();
      }
    }, "signUpWithEmail");
    const userIsInChina = ref$3(false);
    onMounted(async () => {
      userIsInChina.value = await isInChina();
    });
    onUnmounted(() => {
      authActions.accessError.value = false;
    });
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", _hoisted_1$$, [
        showApiKeyForm.value ? (openBlock(), createBlock(_sfc_main$1l, {
          key: 0,
          onBack: _cache[0] || (_cache[0] = ($event) => showApiKeyForm.value = false),
          onSuccess: _ctx.onSuccess
        }, null, 8, ["onSuccess"])) : (openBlock(), createElementBlock(Fragment$1, { key: 1 }, [
          createBaseVNode("div", _hoisted_2$O, [
            createBaseVNode("h1", _hoisted_3$z, toDisplayString(isSignIn.value ? unref(t2)("auth.login.title") : unref(t2)("auth.signup.title")), 1),
            createBaseVNode("p", _hoisted_4$m, [
              createBaseVNode("span", _hoisted_5$h, toDisplayString(isSignIn.value ? unref(t2)("auth.login.newUser") : unref(t2)("auth.signup.alreadyHaveAccount")), 1),
              createBaseVNode("span", {
                class: "ml-1 cursor-pointer text-blue-500",
                onClick: toggleState
              }, toDisplayString(isSignIn.value ? unref(t2)("auth.login.signUp") : unref(t2)("auth.signup.signIn")), 1)
            ])
          ]),
          !unref(isSecureContext2) ? (openBlock(), createBlock(unref(script$8), {
            key: 0,
            severity: "warn",
            class: "mb-4"
          }, {
            default: withCtx(() => [
              createTextVNode(toDisplayString(unref(t2)("auth.login.insecureContextWarning")), 1)
            ]),
            _: 1
          })) : createCommentVNode("", true),
          isSignIn.value ? (openBlock(), createBlock(_sfc_main$1k, {
            key: 1,
            onSubmit: signInWithEmail
          })) : (openBlock(), createElementBlock(Fragment$1, { key: 2 }, [
            userIsInChina.value ? (openBlock(), createBlock(unref(script$8), {
              key: 0,
              severity: "warn",
              class: "mb-4"
            }, {
              default: withCtx(() => [
                createTextVNode(toDisplayString(unref(t2)("auth.signup.regionRestrictionChina")), 1)
              ]),
              _: 1
            })) : (openBlock(), createBlock(_sfc_main$1i, {
              key: 1,
              onSubmit: signUpWithEmail
            }))
          ], 64)),
          createVNode(unref(script$f), {
            align: "center",
            layout: "horizontal",
            class: "my-8"
          }, {
            default: withCtx(() => [
              createBaseVNode("span", _hoisted_6$e, toDisplayString(unref(t2)("auth.login.orContinueWith")), 1)
            ]),
            _: 1
          }),
          createBaseVNode("div", _hoisted_7$8, [
            createVNode(unref(script$6), {
              type: "button",
              class: "h-10",
              severity: "secondary",
              outlined: "",
              onClick: signInWithGoogle
            }, {
              default: withCtx(() => [
                _cache[2] || (_cache[2] = createBaseVNode("i", { class: "pi pi-google mr-2" }, null, -1)),
                createTextVNode(" " + toDisplayString(isSignIn.value ? unref(t2)("auth.login.loginWithGoogle") : unref(t2)("auth.signup.signUpWithGoogle")), 1)
              ]),
              _: 1
            }),
            createVNode(unref(script$6), {
              type: "button",
              class: "h-10",
              severity: "secondary",
              outlined: "",
              onClick: signInWithGithub
            }, {
              default: withCtx(() => [
                _cache[3] || (_cache[3] = createBaseVNode("i", { class: "pi pi-github mr-2" }, null, -1)),
                createTextVNode(" " + toDisplayString(isSignIn.value ? unref(t2)("auth.login.loginWithGithub") : unref(t2)("auth.signup.signUpWithGithub")), 1)
              ]),
              _: 1
            }),
            createVNode(unref(script$6), {
              type: "button",
              class: "h-10",
              severity: "secondary",
              outlined: "",
              onClick: _cache[1] || (_cache[1] = ($event) => showApiKeyForm.value = true)
            }, {
              default: withCtx(() => [
                _cache[4] || (_cache[4] = createBaseVNode("img", {
                  src: _imports_0$1,
                  class: "w-5 h-5 mr-2",
                  alt: "Comfy"
                }, null, -1)),
                createTextVNode(" " + toDisplayString(unref(t2)("auth.login.useApiKey")), 1)
              ]),
              _: 1
            }),
            createBaseVNode("small", _hoisted_8$6, [
              createTextVNode(toDisplayString(unref(t2)("auth.apiKey.helpText")) + " ", 1),
              createBaseVNode("a", {
                href: `${unref(COMFY_PLATFORM_BASE_URL)}/login`,
                target: "_blank",
                class: "text-blue-500 cursor-pointer"
              }, toDisplayString(unref(t2)("auth.apiKey.generateKey")), 9, _hoisted_9$5)
            ]),
            unref(authActions).accessError.value ? (openBlock(), createBlock(unref(script$8), {
              key: 0,
              severity: "info",
              icon: "pi pi-info-circle",
              variant: "outlined",
              closable: ""
            }, {
              default: withCtx(() => [
                createTextVNode(toDisplayString(unref(t2)("toastMessages.useApiKeyTip")), 1)
              ]),
              _: 1
            })) : createCommentVNode("", true)
          ]),
          createBaseVNode("p", _hoisted_10$5, [
            createTextVNode(toDisplayString(unref(t2)("auth.login.termsText")) + " ", 1),
            createBaseVNode("a", _hoisted_11$4, toDisplayString(unref(t2)("auth.login.termsLink")), 1),
            createTextVNode(" " + toDisplayString(unref(t2)("auth.login.andText")) + " ", 1),
            createBaseVNode("a", _hoisted_12$2, toDisplayString(unref(t2)("auth.login.privacyLink")), 1),
            createTextVNode(". " + toDisplayString(unref(t2)("auth.login.questionsContactPrefix")) + " ", 1),
            _cache[5] || (_cache[5] = createBaseVNode("a", {
              href: "mailto:hello@comfy.org",
              class: "text-blue-500 cursor-pointer"
            }, " hello@comfy.org", -1)),
            _cache[6] || (_cache[6] = createTextVNode(". "))
          ])
        ], 64))
      ]);
    };
  }
});
const _hoisted_1$_ = {
  key: 0,
  class: "flex items-center gap-1"
};
const _hoisted_2$N = { class: "flex items-center gap-2" };
const _hoisted_3$y = {
  key: 1,
  class: "flex items-center gap-1"
};
const _sfc_main$1g = /* @__PURE__ */ defineComponent({
  __name: "UserCredit",
  props: {
    textClass: {}
  },
  setup(__props) {
    const authStore = useFirebaseAuthStore();
    const balanceLoading = computed(() => authStore.isFetchingBalance);
    const formattedBalance = computed(() => {
      if (!authStore.balance) return "0.00";
      return formatMetronomeCurrency(authStore.balance.amount_micros, "usd");
    });
    return (_ctx, _cache) => {
      return balanceLoading.value ? (openBlock(), createElementBlock("div", _hoisted_1$_, [
        createBaseVNode("div", _hoisted_2$N, [
          createVNode(unref(script$y), {
            shape: "circle",
            width: "1.5rem",
            height: "1.5rem"
          })
        ]),
        _cache[0] || (_cache[0] = createBaseVNode("div", { class: "flex-1" }, null, -1)),
        createVNode(unref(script$y), {
          width: "8rem",
          height: "2rem"
        })
      ])) : (openBlock(), createElementBlock("div", _hoisted_3$y, [
        createVNode(unref(script$5), {
          severity: "secondary",
          icon: "pi pi-dollar",
          rounded: "",
          class: "text-amber-400 p-1"
        }),
        createBaseVNode("div", {
          class: normalizeClass(_ctx.textClass)
        }, toDisplayString(formattedBalance.value), 3)
      ]));
    };
  }
});
const _hoisted_1$Z = { class: "flex items-center gap-2" };
const _hoisted_2$M = {
  key: 1,
  class: "text-xl"
};
const _sfc_main$1f = /* @__PURE__ */ defineComponent({
  __name: "CreditTopUpOption",
  props: {
    amount: {},
    preselected: { type: Boolean },
    editable: { type: Boolean, default: false }
  },
  setup(__props) {
    const authActions = useFirebaseAuthActions();
    const customAmount = ref$3(__props.amount);
    const didClickBuyNow = ref$3(false);
    const loading = ref$3(false);
    const handleBuyNow = /* @__PURE__ */ __name(async () => {
      loading.value = true;
      await authActions.purchaseCredits(__props.editable ? customAmount.value : __props.amount);
      loading.value = false;
      didClickBuyNow.value = true;
    }, "handleBuyNow");
    onBeforeUnmount(() => {
      if (didClickBuyNow.value) {
        void authActions.fetchBalance();
      }
    });
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock(Fragment$1, null, [
        createBaseVNode("div", _hoisted_1$Z, [
          createVNode(unref(script$5), {
            severity: "secondary",
            icon: "pi pi-dollar",
            rounded: "",
            class: "text-amber-400 p-1"
          }),
          _ctx.editable ? (openBlock(), createBlock(unref(script$r), {
            key: 0,
            modelValue: customAmount.value,
            "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => customAmount.value = $event),
            min: 1,
            max: 1e3,
            step: 1,
            "show-buttons": "",
            "allow-empty": false,
            "highlight-on-focus": true,
            "pt:pc-input-text:root": "w-24",
            onBlur: _cache[1] || (_cache[1] = (e2) => customAmount.value = Number(e2.value)),
            onInput: _cache[2] || (_cache[2] = (e2) => customAmount.value = Number(e2.value))
          }, null, 8, ["modelValue"])) : (openBlock(), createElementBlock("span", _hoisted_2$M, toDisplayString(_ctx.amount), 1))
        ]),
        loading.value ? (openBlock(), createBlock(unref(script$x), {
          key: 0,
          class: "w-8 h-8"
        })) : (openBlock(), createBlock(unref(script$6), {
          key: 1,
          severity: _ctx.preselected ? "primary" : "secondary",
          outlined: !_ctx.preselected,
          label: _ctx.$t("credits.topUp.buyNow"),
          onClick: handleBuyNow
        }, null, 8, ["severity", "outlined", "label"]))
      ], 64);
    };
  }
});
const _hoisted_1$Y = { class: "flex flex-col w-96 p-2 gap-10" };
const _hoisted_2$L = {
  key: 0,
  class: "flex flex-col gap-4"
};
const _hoisted_3$x = { class: "text-2xl font-medium leading-normal my-0" };
const _hoisted_4$l = { class: "text-base my-0" };
const _hoisted_5$g = { class: "flex justify-between items-center" };
const _hoisted_6$d = { class: "flex flex-col gap-2 w-full" };
const _hoisted_7$7 = { class: "text-muted text-base" };
const _hoisted_8$5 = { class: "flex items-center justify-between w-full" };
const _hoisted_9$4 = { class: "flex flex-col gap-2" };
const _hoisted_10$4 = { class: "text-muted text-sm" };
const _hoisted_11$3 = { class: "grid grid-cols-[2fr_1fr] gap-2" };
const _sfc_main$1e = /* @__PURE__ */ defineComponent({
  __name: "TopUpCreditsDialogContent",
  props: {
    isInsufficientCredits: { type: Boolean, default: false },
    amountOptions: { default: /* @__PURE__ */ __name(() => [5, 10, 20, 50], "default") },
    preselectedAmountOption: { default: 10 }
  },
  setup(__props) {
    const authActions = useFirebaseAuthActions();
    const handleSeeDetails = /* @__PURE__ */ __name(async () => {
      await authActions.accessBillingPortal();
    }, "handleSeeDetails");
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", _hoisted_1$Y, [
        _ctx.isInsufficientCredits ? (openBlock(), createElementBlock("div", _hoisted_2$L, [
          createBaseVNode("h1", _hoisted_3$x, toDisplayString(_ctx.$t("credits.topUp.insufficientTitle")), 1),
          createBaseVNode("p", _hoisted_4$l, toDisplayString(_ctx.$t("credits.topUp.insufficientMessage")), 1)
        ])) : createCommentVNode("", true),
        createBaseVNode("div", _hoisted_5$g, [
          createBaseVNode("div", _hoisted_6$d, [
            createBaseVNode("div", _hoisted_7$7, toDisplayString(_ctx.$t("credits.yourCreditBalance")), 1),
            createBaseVNode("div", _hoisted_8$5, [
              createVNode(_sfc_main$1g, { "text-class": "text-2xl" }),
              createVNode(unref(script$6), {
                outlined: "",
                severity: "secondary",
                label: _ctx.$t("credits.topUp.seeDetails"),
                icon: "pi pi-arrow-up-right",
                onClick: handleSeeDetails
              }, null, 8, ["label"])
            ])
          ])
        ]),
        createBaseVNode("div", _hoisted_9$4, [
          createBaseVNode("span", _hoisted_10$4, toDisplayString(_ctx.$t("credits.topUp.quickPurchase")) + ":", 1),
          createBaseVNode("div", _hoisted_11$3, [
            (openBlock(true), createElementBlock(Fragment$1, null, renderList(_ctx.amountOptions, (amount) => {
              return openBlock(), createBlock(_sfc_main$1f, {
                key: amount,
                amount,
                preselected: amount === _ctx.preselectedAmountOption
              }, null, 8, ["amount", "preselected"]);
            }), 128)),
            createVNode(_sfc_main$1f, {
              amount: 100,
              preselected: false,
              editable: ""
            })
          ])
        ])
      ]);
    };
  }
});
const _sfc_main$1d = /* @__PURE__ */ defineComponent({
  __name: "UpdatePasswordContent",
  props: {
    onSuccess: { type: Function }
  },
  setup(__props) {
    const authActions = useFirebaseAuthActions();
    const loading = ref$3(false);
    const onSubmit = /* @__PURE__ */ __name(async (event) => {
      if (event.valid) {
        loading.value = true;
        try {
          await authActions.updatePassword(event.values.password);
          __props.onSuccess();
        } finally {
          loading.value = false;
        }
      }
    }, "onSubmit");
    return (_ctx, _cache) => {
      return openBlock(), createBlock(unref(script$2), {
        class: "flex flex-col gap-6 w-96",
        resolver: unref(zodResolver)(unref(updatePasswordSchema)),
        onSubmit
      }, {
        default: withCtx(() => [
          createVNode(_sfc_main$1j),
          createVNode(unref(script$6), {
            type: "submit",
            label: _ctx.$t("userSettings.updatePassword"),
            class: "h-10 font-medium mt-4",
            loading: loading.value
          }, null, 8, ["label", "loading"])
        ]),
        _: 1
      }, 8, ["resolver"]);
    };
  }
});
const _sfc_main$1c = /* @__PURE__ */ defineComponent({
  __name: "ContentDivider",
  props: {
    orientation: { default: "horizontal" },
    width: { default: 0.3 }
  },
  setup(__props) {
    const colorPaletteStore = useColorPaletteStore();
    const isLightTheme = computed(
      () => colorPaletteStore.completedActivePalette.light_theme
    );
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("hr", {
        class: normalizeClass({
          "m-0": true,
          "border-t": _ctx.orientation === "horizontal",
          "border-l": _ctx.orientation === "vertical",
          "h-full": _ctx.orientation === "vertical",
          "w-full": _ctx.orientation === "horizontal"
        }),
        style: normalizeStyle({
          borderColor: isLightTheme.value ? "#DCDAE1" : "#2C2C2C",
          borderWidth: `${_ctx.width}px !important`
        })
      }, null, 6);
    };
  }
});
const _sfc_main$1b = /* @__PURE__ */ defineComponent({
  __name: "VirtualGrid",
  props: {
    items: {},
    gridStyle: {},
    bufferRows: { default: 1 },
    scrollThrottle: { default: 64 },
    resizeDebounce: { default: 64 },
    defaultItemHeight: { default: 200 },
    defaultItemWidth: { default: 200 }
  },
  emits: ["approach-end"],
  setup(__props, { emit: __emit }) {
    const emit = __emit;
    const itemHeight = ref$3(__props.defaultItemHeight);
    const itemWidth = ref$3(__props.defaultItemWidth);
    const container = ref$3(null);
    const { width: width2, height } = useElementSize(container);
    const { y: scrollY } = useScroll(container, {
      throttle: __props.scrollThrottle,
      eventListenerOptions: { passive: true }
    });
    const cols = computed(() => Math.floor(width2.value / itemWidth.value) || 1);
    const viewRows = computed(() => Math.ceil(height.value / itemHeight.value));
    const offsetRows = computed(() => Math.floor(scrollY.value / itemHeight.value));
    const isValidGrid = computed(() => height.value && width2.value && __props.items?.length);
    const state = computed(() => {
      const fromRow = offsetRows.value - __props.bufferRows;
      const toRow = offsetRows.value + __props.bufferRows + viewRows.value;
      const fromCol = fromRow * cols.value;
      const toCol = toRow * cols.value;
      const remainingCol = __props.items.length - toCol;
      const hasMoreToRender = remainingCol >= 0;
      return {
        start: lodashExports.clamp(fromCol, 0, __props.items?.length),
        end: lodashExports.clamp(toCol, fromCol, __props.items?.length),
        isNearEnd: hasMoreToRender && remainingCol <= cols.value * __props.bufferRows
      };
    });
    const renderedItems = computed(
      () => isValidGrid.value ? __props.items.slice(state.value.start, state.value.end) : []
    );
    whenever(
      () => state.value.isNearEnd,
      () => {
        emit("approach-end");
      }
    );
    const updateItemSize = /* @__PURE__ */ __name(() => {
      if (container.value) {
        const firstItem = container.value.querySelector("[data-virtual-grid-item]");
        itemHeight.value = firstItem?.clientHeight || __props.defaultItemHeight;
        itemWidth.value = firstItem?.clientWidth || __props.defaultItemWidth;
      }
    }, "updateItemSize");
    const onResize = lodashExports.debounce(updateItemSize, __props.resizeDebounce);
    watch([width2, height], onResize, { flush: "post" });
    onBeforeUnmount(() => {
      onResize.cancel();
    });
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", {
        ref_key: "container",
        ref: container,
        class: "scroll-container"
      }, [
        createBaseVNode("div", {
          style: normalizeStyle({ height: `${state.value.start / cols.value * itemHeight.value}px` })
        }, null, 4),
        createBaseVNode("div", {
          style: normalizeStyle(_ctx.gridStyle)
        }, [
          (openBlock(true), createElementBlock(Fragment$1, null, renderList(renderedItems.value, (item) => {
            return openBlock(), createElementBlock("div", {
              key: item.key,
              "data-virtual-grid-item": ""
            }, [
              renderSlot(_ctx.$slots, "item", { item }, void 0, true)
            ]);
          }), 128))
        ], 4),
        createBaseVNode("div", {
          style: normalizeStyle({
            height: `${(_ctx.items.length - state.value.end) / cols.value * itemHeight.value}px`
          })
        }, null, 4)
      ], 512);
    };
  }
});
const VirtualGrid = /* @__PURE__ */ _export_sfc(_sfc_main$1b, [["__scopeId", "data-v-80d61f4c"]]);
const _hoisted_1$X = { class: "absolute translate-x-0 top-0 left-0 h-full w-80 shadow-md z-5 transition-transform duration-300 ease-in-out flex" };
const _hoisted_2$K = { class: "text-left flex items-center" };
const _hoisted_3$w = { class: "text-lg" };
const _sfc_main$1a = /* @__PURE__ */ defineComponent({
  __name: "ManagerNavSidebar",
  props: /* @__PURE__ */ mergeModels({
    tabs: {}
  }, {
    "selectedTab": {},
    "selectedTabModifiers": {}
  }),
  emits: ["update:selectedTab"],
  setup(__props) {
    const selectedTab = useModel(__props, "selectedTab");
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("aside", _hoisted_1$X, [
        createVNode(unref(script$7), { class: "w-80 mt-7" }, {
          default: withCtx(() => [
            createVNode(unref(script$g), {
              modelValue: selectedTab.value,
              "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => selectedTab.value = $event),
              options: _ctx.tabs,
              "option-label": "label",
              "list-style": "max-height:unset",
              class: "w-full border-0 bg-transparent shadow-none",
              pt: {
                list: { class: "p-5" },
                option: { class: "px-8 py-3 text-lg rounded-xl" },
                optionGroup: { class: "p-0 text-left text-inherit" }
              }
            }, {
              option: withCtx((slotProps) => [
                createBaseVNode("div", _hoisted_2$K, [
                  createBaseVNode("i", {
                    class: normalizeClass(["pi", slotProps.option.icon, "mr-3"])
                  }, null, 2),
                  createBaseVNode("span", _hoisted_3$w, toDisplayString(slotProps.option.label), 1)
                ])
              ]),
              _: 1
            }, 8, ["modelValue", "options"])
          ]),
          _: 1
        }),
        createVNode(_sfc_main$1c, { orientation: "vertical" })
      ]);
    };
  }
});
const _sfc_main$19 = /* @__PURE__ */ defineComponent({
  __name: "PackStatusMessage",
  props: {
    statusType: {}
  },
  setup(__props) {
    const statusPropsMap = {
      NodeStatusActive: {
        label: "active",
        severity: "success"
      },
      NodeStatusDeleted: {
        label: "deleted",
        severity: "warn"
      },
      NodeStatusBanned: {
        label: "banned",
        severity: "error"
      },
      NodeVersionStatusActive: {
        label: "active",
        severity: "success"
      },
      NodeVersionStatusPending: {
        label: "pending",
        severity: "warn"
      },
      NodeVersionStatusDeleted: {
        label: "deleted",
        severity: "warn"
      },
      NodeVersionStatusFlagged: {
        label: "flagged",
        severity: "error"
      },
      NodeVersionStatusBanned: {
        label: "banned",
        severity: "error"
      }
    };
    const statusLabel = computed(
      () => statusPropsMap[__props.statusType]?.label || "unknown"
    );
    const statusSeverity = computed(
      () => statusPropsMap[__props.statusType]?.severity || "secondary"
    );
    return (_ctx, _cache) => {
      return openBlock(), createBlock(unref(script$8), {
        severity: statusSeverity.value,
        class: "p-0 flex items-center rounded-xl break-words w-fit",
        pt: {
          text: { class: "text-xs" },
          content: { class: "px-2 py-0.5" }
        }
      }, {
        default: withCtx(() => [
          _cache[0] || (_cache[0] = createBaseVNode("i", {
            class: "pi pi-circle-fill mr-1.5 text-[0.6rem] p-0",
            style: { opacity: 0.8 }
          }, null, -1)),
          createTextVNode(" " + toDisplayString(_ctx.$t(`manager.status.${statusLabel.value}`)), 1)
        ]),
        _: 1
      }, 8, ["severity"]);
    };
  }
});
const API_BASE_URL = "https://api.comfy.org";
const registryApiClient = axios.create({
  baseURL: API_BASE_URL,
  headers: {
    "Content-Type": "application/json"
  },
  paramsSerializer: {
    // Disables PHP-style notation (e.g. param[]=value) in favor of repeated params (e.g. param=value1&param=value2)
    indexes: null
  }
});
const useComfyRegistryService = /* @__PURE__ */ __name(() => {
  const isLoading = ref$3(false);
  const error2 = ref$3(null);
  const handleApiError = /* @__PURE__ */ __name((err, context, routeSpecificErrors) => {
    if (!axios.isAxiosError(err))
      return err instanceof Error ? `${context}: ${err.message}` : `${context}: Unknown error occurred`;
    const axiosError = err;
    if (axiosError.response) {
      const { status, data } = axiosError.response;
      if (routeSpecificErrors && routeSpecificErrors[status])
        return routeSpecificErrors[status];
      switch (status) {
        case 400:
          return `Bad request: ${data?.message || "Invalid input"}`;
        case 401:
          return "Unauthorized: Authentication required";
        case 403:
          return `Forbidden: ${data?.message || "Access denied"}`;
        case 404:
          return `Not found: ${data?.message || "Resource not found"}`;
        case 409:
          return `Conflict: ${data?.message || "Resource conflict"}`;
        case 500:
          return `Server error: ${data?.message || "Internal server error"}`;
        default:
          return `${context}: ${data?.message || axiosError.message}`;
      }
    }
    return `${context}: ${axiosError.message}`;
  }, "handleApiError");
  const executeApiRequest = /* @__PURE__ */ __name(async (apiCall, errorContext, routeSpecificErrors) => {
    isLoading.value = true;
    error2.value = null;
    try {
      const response = await apiCall();
      return response.data;
    } catch (err) {
      if (isAbortError(err)) return null;
      error2.value = handleApiError(err, errorContext, routeSpecificErrors);
      return null;
    } finally {
      isLoading.value = false;
    }
  }, "executeApiRequest");
  const getNodeDefs = /* @__PURE__ */ __name(async (params, signal) => {
    const { packId, version: versionId, ...queryParams } = params;
    if (!packId || !versionId) return null;
    const endpoint = `/nodes/${packId}/versions/${versionId}/comfy-nodes`;
    const errorContext = "Failed to get node definitions";
    const routeSpecificErrors = {
      403: "This pack has been banned and its definition is not available",
      404: "The requested node, version, or comfy node does not exist"
    };
    return executeApiRequest(
      () => registryApiClient.get(endpoint, {
        params: queryParams,
        signal
      }),
      errorContext,
      routeSpecificErrors
    );
  }, "getNodeDefs");
  const search2 = /* @__PURE__ */ __name(async (params, signal) => {
    const endpoint = "/nodes/search";
    const errorContext = "Failed to perform search";
    return executeApiRequest(
      () => registryApiClient.get(endpoint, { params, signal }),
      errorContext
    );
  }, "search");
  const getPublisherById = /* @__PURE__ */ __name(async (publisherId, signal) => {
    const endpoint = `/publishers/${publisherId}`;
    const errorContext = "Failed to get publisher";
    const routeSpecificErrors = {
      404: `Publisher not found: The publisher with ID ${publisherId} does not exist`
    };
    return executeApiRequest(
      () => registryApiClient.get(endpoint, {
        signal
      }),
      errorContext,
      routeSpecificErrors
    );
  }, "getPublisherById");
  const listPacksForPublisher = /* @__PURE__ */ __name(async (publisherId, includeBanned, signal) => {
    const params = includeBanned ? { include_banned: true } : void 0;
    const endpoint = `/publishers/${publisherId}/nodes`;
    const errorContext = "Failed to list packs for publisher";
    const routeSpecificErrors = {
      400: "Bad request: Invalid input data",
      404: `Publisher not found: The publisher with ID ${publisherId} does not exist`
    };
    return executeApiRequest(
      () => registryApiClient.get(endpoint, {
        params,
        signal
      }),
      errorContext,
      routeSpecificErrors
    );
  }, "listPacksForPublisher");
  const postPackReview = /* @__PURE__ */ __name(async (packId, star, signal) => {
    const endpoint = `/nodes/${packId}/reviews`;
    const params = { star };
    const errorContext = "Failed to add review";
    const routeSpecificErrors = {
      400: "Bad request: Invalid review",
      404: `Pack not found: Pack with ID ${packId} does not exist`
    };
    return executeApiRequest(
      () => registryApiClient.post(endpoint, null, {
        params,
        signal
      }),
      errorContext,
      routeSpecificErrors
    );
  }, "postPackReview");
  const listAllPacks = /* @__PURE__ */ __name(async (params, signal) => {
    const endpoint = "/nodes";
    const errorContext = "Failed to list packs";
    return executeApiRequest(
      () => registryApiClient.get(endpoint, { params, signal }),
      errorContext
    );
  }, "listAllPacks");
  const getPackVersions = /* @__PURE__ */ __name(async (packId, params, signal) => {
    const endpoint = `/nodes/${packId}/versions`;
    const errorContext = "Failed to get pack versions";
    const routeSpecificErrors = {
      403: "This pack has been banned and its versions are not available",
      404: `Pack not found: Pack with ID ${packId} does not exist`
    };
    return executeApiRequest(
      () => registryApiClient.get(
        endpoint,
        { params, signal }
      ),
      errorContext,
      routeSpecificErrors
    );
  }, "getPackVersions");
  const getPackByVersion = /* @__PURE__ */ __name(async (packId, versionId, signal) => {
    const endpoint = `/nodes/${packId}/versions/${versionId}`;
    const errorContext = "Failed to get pack version";
    const routeSpecificErrors = {
      403: "This pack has been banned and its versions are not available",
      404: `Pack not found: Pack with ID ${packId} does not exist`
    };
    return executeApiRequest(
      () => registryApiClient.get(endpoint, {
        signal
      }),
      errorContext,
      routeSpecificErrors
    );
  }, "getPackByVersion");
  const getPackById = /* @__PURE__ */ __name(async (packId, signal) => {
    const endpoint = `/nodes/${packId}`;
    const errorContext = "Failed to get pack";
    const routeSpecificErrors = {
      404: `Pack not found: The pack with ID ${packId} does not exist`
    };
    return executeApiRequest(
      () => registryApiClient.get(endpoint, {
        signal
      }),
      errorContext,
      routeSpecificErrors
    );
  }, "getPackById");
  return {
    isLoading,
    error: error2,
    listAllPacks,
    search: search2,
    getPackById,
    getPackVersions,
    getPackByVersion,
    getPublisherById,
    listPacksForPublisher,
    getNodeDefs,
    postPackReview
  };
}, "useComfyRegistryService");
const _hoisted_1$W = { class: "w-64 mt-2" };
const _hoisted_2$J = { class: "pl-3 text-muted text-md font-semibold opacity-70" };
const _hoisted_3$v = {
  key: 0,
  class: "text-center text-muted py-4 flex flex-col items-center"
};
const _hoisted_4$k = {
  key: 1,
  class: "py-2"
};
const _hoisted_5$f = { class: "flex justify-between items-center w-full p-1" };
const _hoisted_6$c = {
  key: 0,
  class: "pi pi-check text-highlight"
};
const _hoisted_7$6 = { class: "flex justify-end gap-2 p-1 px-3" };
const _sfc_main$18 = /* @__PURE__ */ defineComponent({
  __name: "PackVersionSelectorPopover",
  props: {
    nodePack: {}
  },
  emits: ["cancel", "submit"],
  setup(__props, { emit: __emit }) {
    const emit = __emit;
    const { t: t2 } = useI18n();
    const registryService = useComfyRegistryService();
    const managerStore = useComfyManagerStore();
    const isQueueing = ref$3(false);
    const selectedVersion = ref$3(SelectedVersion.LATEST);
    onMounted(() => {
      const initialVersion = getInitialSelectedVersion() ?? SelectedVersion.LATEST;
      selectedVersion.value = // Use NIGHTLY when version is a Git hash
      isSemVer(initialVersion) ? initialVersion : SelectedVersion.NIGHTLY;
    });
    const getInitialSelectedVersion = /* @__PURE__ */ __name(() => {
      if (!__props.nodePack.id) return;
      if (__props.nodePack.publisher?.name === "Unclaimed") return SelectedVersion.NIGHTLY;
      if (managerStore.isPackInstalled(__props.nodePack.id))
        return managerStore.getInstalledPackVersion(__props.nodePack.id);
      return __props.nodePack.latest_version?.version;
    }, "getInitialSelectedVersion");
    const fetchVersions = /* @__PURE__ */ __name(async () => {
      if (!__props.nodePack?.id) return [];
      return await registryService.getPackVersions(__props.nodePack.id) || [];
    }, "fetchVersions");
    const versionOptions = ref$3([]);
    const isLoadingVersions = ref$3(false);
    const onNodePackChange = /* @__PURE__ */ __name(async () => {
      isLoadingVersions.value = true;
      const versions = await fetchVersions();
      const availableVersionOptions = versions.map((version2) => ({
        value: version2.version ?? "",
        label: version2.version ?? ""
      })).filter((option) => option.value);
      const defaultVersions = [
        {
          value: SelectedVersion.LATEST,
          label: t2("manager.latestVersion")
        }
      ];
      if (__props.nodePack.repository?.length) {
        defaultVersions.push({
          value: SelectedVersion.NIGHTLY,
          label: t2("manager.nightlyVersion")
        });
      }
      versionOptions.value = [...defaultVersions, ...availableVersionOptions];
      isLoadingVersions.value = false;
    }, "onNodePackChange");
    whenever(
      () => __props.nodePack,
      () => {
        void onNodePackChange();
      },
      { deep: true, immediate: true }
    );
    const handleSubmit = /* @__PURE__ */ __name(async () => {
      isQueueing.value = true;
      await managerStore.installPack.call({
        id: __props.nodePack.id,
        repository: __props.nodePack.repository ?? "",
        channel: ManagerChannel.DEFAULT,
        mode: ManagerDatabaseSource.CACHE,
        version: selectedVersion.value,
        selected_version: selectedVersion.value
      });
      isQueueing.value = false;
      emit("submit");
    }, "handleSubmit");
    onUnmounted(() => {
      managerStore.installPack.clear();
    });
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", _hoisted_1$W, [
        createBaseVNode("span", _hoisted_2$J, toDisplayString(_ctx.$t("manager.selectVersion")), 1),
        isLoadingVersions.value || isQueueing.value ? (openBlock(), createElementBlock("div", _hoisted_3$v, [
          createVNode(unref(script$x), { class: "w-8 h-8 mb-2" }),
          createTextVNode(" " + toDisplayString(_ctx.$t("manager.loadingVersions")), 1)
        ])) : versionOptions.value.length === 0 ? (openBlock(), createElementBlock("div", _hoisted_4$k, [
          createVNode(NoResultsPlaceholder, {
            title: _ctx.$t("g.noResultsFound"),
            message: _ctx.$t("manager.tryAgainLater"),
            icon: "pi pi-exclamation-circle",
            class: "p-0"
          }, null, 8, ["title", "message"])
        ])) : (openBlock(), createBlock(unref(script$g), {
          key: 2,
          modelValue: selectedVersion.value,
          "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => selectedVersion.value = $event),
          "option-label": "label",
          "option-value": "value",
          options: versionOptions.value,
          "highlight-on-select": false,
          class: "my-3 w-full max-h-[50vh] border-none shadow-none"
        }, {
          option: withCtx((slotProps) => [
            createBaseVNode("div", _hoisted_5$f, [
              createBaseVNode("span", null, toDisplayString(slotProps.option.label), 1),
              selectedVersion.value === slotProps.option.value ? (openBlock(), createElementBlock("i", _hoisted_6$c)) : createCommentVNode("", true)
            ])
          ]),
          _: 1
        }, 8, ["modelValue", "options"])),
        createVNode(_sfc_main$1c, { class: "my-2" }),
        createBaseVNode("div", _hoisted_7$6, [
          createVNode(unref(script$6), {
            text: "",
            severity: "secondary",
            label: _ctx.$t("g.cancel"),
            disabled: isQueueing.value,
            onClick: _cache[1] || (_cache[1] = ($event) => emit("cancel"))
          }, null, 8, ["label", "disabled"]),
          createVNode(unref(script$6), {
            severity: "secondary",
            label: _ctx.$t("g.install"),
            class: "py-3 px-4 dark-theme:bg-unset bg-black/80 dark-theme:text-unset text-neutral-100 rounded-lg",
            disabled: isQueueing.value,
            onClick: handleSubmit
          }, null, 8, ["label", "disabled"])
        ])
      ]);
    };
  }
});
const _hoisted_1$V = { class: "relative" };
const TRUNCATED_HASH_LENGTH = 7;
const _sfc_main$17 = /* @__PURE__ */ defineComponent({
  __name: "PackVersionBadge",
  props: {
    nodePack: {}
  },
  setup(__props) {
    const popoverRef = ref$3();
    const managerStore = useComfyManagerStore();
    const installedVersion = computed(() => {
      if (!__props.nodePack.id) return SelectedVersion.NIGHTLY;
      const version2 = managerStore.installedPacks[__props.nodePack.id]?.ver ?? __props.nodePack.latest_version?.version ?? SelectedVersion.NIGHTLY;
      return isSemVer(version2) ? version2 : version2.slice(0, TRUNCATED_HASH_LENGTH);
    });
    const toggleVersionSelector = /* @__PURE__ */ __name((event) => {
      popoverRef.value.toggle(event);
    }, "toggleVersionSelector");
    const closeVersionSelector = /* @__PURE__ */ __name(() => {
      popoverRef.value.hide();
    }, "closeVersionSelector");
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", _hoisted_1$V, [
        createVNode(unref(script$6), {
          label: installedVersion.value,
          severity: "secondary",
          icon: "pi pi-chevron-right",
          "icon-pos": "right",
          class: "rounded-xl text-xs tracking-tighter p-0",
          pt: {
            label: { class: "pl-2 pr-0 py-0.5" },
            icon: { class: "text-xs pl-0 pr-2 py-0.5" }
          },
          "aria-haspopup": "true",
          onClick: toggleVersionSelector
        }, null, 8, ["label"]),
        createVNode(unref(script$z), {
          ref_key: "popoverRef",
          ref: popoverRef,
          pt: {
            content: { class: "px-0" }
          }
        }, {
          default: withCtx(() => [
            createVNode(_sfc_main$18, {
              "installed-version": installedVersion.value,
              "node-pack": _ctx.nodePack,
              onCancel: closeVersionSelector,
              onSubmit: closeVersionSelector
            }, null, 8, ["installed-version", "node-pack"])
          ]),
          _: 1
        }, 512)
      ]);
    };
  }
});
const _hoisted_1$U = { class: "flex items-center" };
const TOGGLE_DEBOUNCE_MS = 256;
const _sfc_main$16 = /* @__PURE__ */ defineComponent({
  __name: "PackEnableToggle",
  props: {
    nodePack: {}
  },
  setup(__props) {
    const { isPackEnabled, enablePack, disablePack, installedPacks } = useComfyManagerStore();
    const isLoading = ref$3(false);
    const isEnabled2 = computed(() => isPackEnabled(__props.nodePack.id));
    const version2 = computed(() => {
      const id2 = __props.nodePack.id;
      if (!id2) return SelectedVersion.NIGHTLY;
      return installedPacks[id2]?.ver ?? __props.nodePack.latest_version?.version ?? SelectedVersion.NIGHTLY;
    });
    const handleEnable = /* @__PURE__ */ __name(() => enablePack.call({
      id: __props.nodePack.id,
      version: version2.value,
      selected_version: version2.value,
      repository: __props.nodePack.repository ?? "",
      channel: ManagerChannel.DEFAULT,
      mode: "default"
    }), "handleEnable");
    const handleDisable = /* @__PURE__ */ __name(() => disablePack({
      id: __props.nodePack.id,
      version: version2.value
    }), "handleDisable");
    const handleToggle = /* @__PURE__ */ __name(async (enable) => {
      if (isLoading.value) return;
      isLoading.value = true;
      if (enable) {
        await handleEnable();
      } else {
        handleDisable();
      }
      isLoading.value = false;
    }, "handleToggle");
    const onToggle = lodashExports.debounce(handleToggle, TOGGLE_DEBOUNCE_MS, { trailing: true });
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", _hoisted_1$U, [
        createVNode(unref(script$t), {
          "model-value": isEnabled2.value,
          disabled: isLoading.value,
          "aria-label": "Enable or disable pack",
          "onUpdate:modelValue": unref(onToggle)
        }, null, 8, ["model-value", "disabled", "onUpdate:modelValue"])
      ]);
    };
  }
});
const _hoisted_1$T = { class: "py-2.5 px-3" };
const _sfc_main$15 = /* @__PURE__ */ defineComponent({
  ...{
    inheritAttrs: false
  },
  __name: "PackActionButton",
  props: {
    label: {},
    loading: { type: Boolean },
    loadingMessage: {},
    fullWidth: { type: Boolean, default: false }
  },
  emits: ["action"],
  setup(__props, { emit: __emit }) {
    const emit = __emit;
    const onClick = /* @__PURE__ */ __name(() => {
      emit("action");
    }, "onClick");
    return (_ctx, _cache) => {
      return openBlock(), createBlock(unref(script$6), mergeProps$1({
        outlined: "",
        class: ["m-0 p-0 rounded-lg border-neutral-700", {
          "w-full": _ctx.fullWidth,
          "w-min-content": !_ctx.fullWidth
        }],
        disabled: _ctx.loading
      }, _ctx.$attrs, { onClick }), {
        default: withCtx(() => [
          createBaseVNode("span", _hoisted_1$T, [
            _ctx.loading ? (openBlock(), createElementBlock(Fragment$1, { key: 0 }, [
              createTextVNode(toDisplayString(_ctx.loadingMessage ?? _ctx.$t("g.loading")), 1)
            ], 64)) : (openBlock(), createElementBlock(Fragment$1, { key: 1 }, [
              createTextVNode(toDisplayString(_ctx.label), 1)
            ], 64))
          ])
        ]),
        _: 1
      }, 16, ["class", "disabled"]);
    };
  }
});
const _sfc_main$14 = /* @__PURE__ */ defineComponent({
  __name: "PackInstallButton",
  props: {
    nodePacks: {}
  },
  setup(__props) {
    const isInstalling = inject(IsInstallingKey, ref$3(false));
    const onClick = /* @__PURE__ */ __name(() => {
      isInstalling.value = true;
    }, "onClick");
    const managerStore = useComfyManagerStore();
    const createPayload = /* @__PURE__ */ __name((installItem) => {
      const isUnclaimedPack = installItem.publisher?.name === "Unclaimed";
      const versionToInstall = isUnclaimedPack ? SelectedVersion.NIGHTLY : installItem.latest_version?.version ?? SelectedVersion.LATEST;
      return {
        id: installItem.id,
        repository: installItem.repository ?? "",
        channel: ManagerChannel.DEV,
        mode: ManagerDatabaseSource.CACHE,
        selected_version: versionToInstall,
        version: versionToInstall
      };
    }, "createPayload");
    const installPack = /* @__PURE__ */ __name((item) => managerStore.installPack.call(createPayload(item)), "installPack");
    const installAllPacks = /* @__PURE__ */ __name(async () => {
      if (!__props.nodePacks?.length) return;
      isInstalling.value = true;
      const uninstalledPacks = __props.nodePacks.filter(
        (pack) => !managerStore.isPackInstalled(pack.id)
      );
      if (!uninstalledPacks.length) return;
      await Promise.all(uninstalledPacks.map(installPack));
      managerStore.installPack.clear();
    }, "installAllPacks");
    return (_ctx, _cache) => {
      return openBlock(), createBlock(_sfc_main$15, mergeProps$1(_ctx.$attrs, {
        label: _ctx.nodePacks.length > 1 ? _ctx.$t("manager.installSelected") : _ctx.$t("g.install"),
        severity: "secondary",
        loading: unref(isInstalling),
        "loading-message": _ctx.$t("g.installing"),
        onAction: installAllPacks,
        onClick
      }), null, 16, ["label", "loading", "loading-message"]);
    };
  }
});
const _sfc_main$13 = /* @__PURE__ */ defineComponent({
  __name: "PackUninstallButton",
  props: {
    nodePacks: {}
  },
  setup(__props) {
    const managerStore = useComfyManagerStore();
    const createPayload = /* @__PURE__ */ __name((uninstallItem) => {
      return {
        id: uninstallItem.id,
        version: uninstallItem.latest_version?.version
      };
    }, "createPayload");
    const uninstallPack = /* @__PURE__ */ __name((item) => managerStore.uninstallPack(createPayload(item)), "uninstallPack");
    const uninstallItems = /* @__PURE__ */ __name(async () => {
      if (!__props.nodePacks?.length) return;
      await Promise.all(__props.nodePacks.map(uninstallPack));
    }, "uninstallItems");
    return (_ctx, _cache) => {
      return openBlock(), createBlock(_sfc_main$15, mergeProps$1(_ctx.$attrs, {
        label: _ctx.nodePacks.length > 1 ? _ctx.$t("manager.uninstallSelected") : _ctx.$t("manager.uninstall"),
        severity: "danger",
        "loading-message": _ctx.$t("manager.uninstalling"),
        onAction: uninstallItems
      }), null, 16, ["label", "loading-message"]);
    };
  }
});
const _hoisted_1$S = ["src", "alt"];
const DEFAULT_ICON = "/assets/images/fallback-gradient-avatar.svg";
const _sfc_main$12 = /* @__PURE__ */ defineComponent({
  __name: "PackIcon",
  props: {
    nodePack: {},
    width: { default: "4.5rem" },
    height: { default: "4.5rem" }
  },
  setup(__props) {
    const isImageError = ref$3(false);
    const shouldShowFallback = computed(
      () => !__props.nodePack.icon || __props.nodePack.icon.trim() === "" || isImageError.value
    );
    const imgSrc = computed(
      () => shouldShowFallback.value ? DEFAULT_ICON : __props.nodePack.icon
    );
    const convertToCssValue = /* @__PURE__ */ __name((value) => typeof value === "number" ? `${value}rem` : value, "convertToCssValue");
    const cssWidth = computed(() => convertToCssValue(__props.width));
    const cssHeight = computed(() => convertToCssValue(__props.height));
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("img", {
        src: isImageError.value ? DEFAULT_ICON : imgSrc.value,
        alt: _ctx.nodePack.name + " icon",
        class: "object-contain rounded-lg max-h-72 max-w-72",
        style: normalizeStyle({ width: cssWidth.value, height: cssHeight.value }),
        onError: _cache[0] || (_cache[0] = ($event) => isImageError.value = true)
      }, null, 44, _hoisted_1$S);
    };
  }
});
const _hoisted_1$R = {
  key: 0,
  class: "flex flex-col items-center mb-6"
};
const _hoisted_2$I = {
  class: "text-2xl font-bold text-center mt-4 mb-2",
  style: { "word-break": "break-all" }
};
const _hoisted_3$u = { class: "mt-2 mb-4 w-full max-w-xs flex justify-center" };
const _hoisted_4$j = {
  key: 1,
  class: "flex flex-col items-center mb-6"
};
const _sfc_main$11 = /* @__PURE__ */ defineComponent({
  __name: "InfoPanelHeader",
  props: {
    nodePacks: {}
  },
  setup(__props) {
    const managerStore = useComfyManagerStore();
    const isAllInstalled = ref$3(false);
    watch(
      [() => __props.nodePacks, () => managerStore.installedPacks],
      () => {
        isAllInstalled.value = __props.nodePacks.every(
          (nodePack) => managerStore.isPackInstalled(nodePack.id)
        );
      },
      { immediate: true }
    );
    return (_ctx, _cache) => {
      return _ctx.nodePacks?.length ? (openBlock(), createElementBlock("div", _hoisted_1$R, [
        renderSlot(_ctx.$slots, "thumbnail", {}, () => [
          createVNode(_sfc_main$12, {
            "node-pack": _ctx.nodePacks[0],
            width: "24",
            height: "24"
          }, null, 8, ["node-pack"])
        ]),
        createBaseVNode("h2", _hoisted_2$I, [
          renderSlot(_ctx.$slots, "title", {}, () => [
            createTextVNode(toDisplayString(_ctx.nodePacks[0].name), 1)
          ])
        ]),
        createBaseVNode("div", _hoisted_3$u, [
          renderSlot(_ctx.$slots, "install-button", {}, () => [
            isAllInstalled.value ? (openBlock(), createBlock(_sfc_main$13, mergeProps$1({ key: 0 }, _ctx.$attrs, { "node-packs": _ctx.nodePacks }), null, 16, ["node-packs"])) : (openBlock(), createBlock(_sfc_main$14, mergeProps$1({ key: 1 }, _ctx.$attrs, { "node-packs": _ctx.nodePacks }), null, 16, ["node-packs"]))
          ])
        ])
      ])) : (openBlock(), createElementBlock("div", _hoisted_4$j, [
        createVNode(NoResultsPlaceholder, {
          message: _ctx.$t("manager.status.unknown"),
          title: _ctx.$t("manager.tryAgainLater")
        }, null, 8, ["message", "title"])
      ]));
    };
  }
});
const _hoisted_1$Q = ["textContent"];
const _hoisted_2$H = {
  key: 1,
  class: "break-words"
};
const _hoisted_3$t = ["href"];
const _hoisted_4$i = { class: "text-blue-600" };
const _hoisted_5$e = { key: 1 };
const _hoisted_6$b = { key: 2 };
const _hoisted_7$5 = {
  key: 3,
  class: "px-1 py-0.5 rounded text-xs"
};
const _hoisted_8$4 = { key: 4 };
const _sfc_main$10 = /* @__PURE__ */ defineComponent({
  __name: "MarkdownText",
  props: {
    text: {}
  },
  setup(__props) {
    const hasMarkdown = computed(() => {
      const hasMarkdown2 = /(\[.*?\]\(.*?\)|(\*\*|__)(.*?)(\*\*|__)|(\*|_)(.*?)(\*|_)|`(.*?)`)/.test(
        __props.text
      );
      return hasMarkdown2;
    });
    const parsedSegments = computed(() => {
      if (!hasMarkdown.value) return [{ type: "text", text: __props.text }];
      const segments = [];
      const remainingText = __props.text;
      let lastIndex = 0;
      const linkRegex = /\[(.*?)\]\((.*?)\)/g;
      let linkMatch;
      while ((linkMatch = linkRegex.exec(remainingText)) !== null) {
        if (linkMatch.index > lastIndex) {
          segments.push({
            type: "text",
            text: remainingText.substring(lastIndex, linkMatch.index)
          });
        }
        segments.push({
          type: "link",
          text: linkMatch[1],
          url: linkMatch[2]
        });
        lastIndex = linkMatch.index + linkMatch[0].length;
      }
      if (lastIndex < remainingText.length) {
        let rest = remainingText.substring(lastIndex);
        rest = rest.replace(/(\*\*|__)(.*?)(\*\*|__)/g, (_2, __, p2) => {
          segments.push({ type: "bold", text: p2 });
          return "";
        });
        rest = rest.replace(/(\*|_)(.*?)(\*|_)/g, (_2, __, p2) => {
          segments.push({ type: "italic", text: p2 });
          return "";
        });
        rest = rest.replace(/`(.*?)`/g, (_2, p1) => {
          segments.push({ type: "code", text: p1 });
          return "";
        });
        if (rest) {
          segments.push({ type: "text", text: rest });
        }
      }
      return segments;
    });
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", null, [
        !hasMarkdown.value ? (openBlock(), createElementBlock("div", {
          key: 0,
          class: "break-words",
          textContent: toDisplayString(_ctx.text)
        }, null, 8, _hoisted_1$Q)) : (openBlock(), createElementBlock("div", _hoisted_2$H, [
          (openBlock(true), createElementBlock(Fragment$1, null, renderList(parsedSegments.value, (segment, index2) => {
            return openBlock(), createElementBlock(Fragment$1, { key: index2 }, [
              segment.type === "link" && "url" in segment ? (openBlock(), createElementBlock("a", {
                key: 0,
                href: segment.url,
                target: "_blank",
                rel: "noopener noreferrer",
                class: "hover:underline"
              }, [
                createBaseVNode("span", _hoisted_4$i, toDisplayString(segment.text), 1)
              ], 8, _hoisted_3$t)) : segment.type === "bold" ? (openBlock(), createElementBlock("strong", _hoisted_5$e, toDisplayString(segment.text), 1)) : segment.type === "italic" ? (openBlock(), createElementBlock("em", _hoisted_6$b, toDisplayString(segment.text), 1)) : segment.type === "code" ? (openBlock(), createElementBlock("code", _hoisted_7$5, toDisplayString(segment.text), 1)) : (openBlock(), createElementBlock("span", _hoisted_8$4, toDisplayString(segment.text), 1))
            ], 64);
          }), 128))
        ]))
      ]);
    };
  }
});
const _hoisted_1$P = { class: "flex flex-col gap-4 text-sm" };
const _hoisted_2$G = { class: "mb-1" };
const _hoisted_3$s = { class: "text-muted break-words" };
const _hoisted_4$h = ["href"];
const _hoisted_5$d = {
  key: 0,
  class: "pi pi-github text-base"
};
const _hoisted_6$a = { class: "break-all" };
const _sfc_main$$ = /* @__PURE__ */ defineComponent({
  __name: "InfoTextSection",
  props: {
    sections: {}
  },
  setup(__props) {
    const isGitHubLink = /* @__PURE__ */ __name((url) => url.includes("github.com"), "isGitHubLink");
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", _hoisted_1$P, [
        (openBlock(true), createElementBlock(Fragment$1, null, renderList(_ctx.sections, (section, index2) => {
          return openBlock(), createElementBlock("div", {
            key: index2,
            class: "mb-4"
          }, [
            createBaseVNode("div", _hoisted_2$G, toDisplayString(section.title), 1),
            createBaseVNode("div", _hoisted_3$s, [
              section.isUrl ? (openBlock(), createElementBlock("a", {
                key: 0,
                href: section.text,
                target: "_blank",
                rel: "noopener noreferrer",
                class: "flex items-center gap-2"
              }, [
                isGitHubLink(section.text) ? (openBlock(), createElementBlock("i", _hoisted_5$d)) : createCommentVNode("", true),
                createBaseVNode("span", _hoisted_6$a, toDisplayString(section.text), 1)
              ], 8, _hoisted_4$h)) : (openBlock(), createBlock(_sfc_main$10, {
                key: 1,
                text: section.text,
                class: "text-muted"
              }, null, 8, ["text"]))
            ])
          ]);
        }), 128))
      ]);
    };
  }
});
const _hoisted_1$O = { class: "mt-4 overflow-hidden" };
const _hoisted_2$F = {
  key: 1,
  class: "text-muted italic text-sm"
};
const _hoisted_3$r = { key: 2 };
const _hoisted_4$g = { class: "mb-1" };
const _sfc_main$_ = /* @__PURE__ */ defineComponent({
  __name: "DescriptionTabPanel",
  props: {
    nodePack: {}
  },
  setup(__props) {
    const { t: t2 } = useI18n();
    const isLicenseFile = /* @__PURE__ */ __name((filename) => {
      const licensePattern = /^license(\.md|\.txt)?$/i;
      return licensePattern.test(filename);
    }, "isLicenseFile");
    const extractBaseRepoUrl = /* @__PURE__ */ __name((repoUrl) => {
      const githubRepoPattern = /^(https?:\/\/github\.com\/[^/]+\/[^/]+)/i;
      const match2 = repoUrl.match(githubRepoPattern);
      return match2 ? match2[1] : repoUrl;
    }, "extractBaseRepoUrl");
    const createLicenseUrl = /* @__PURE__ */ __name((filename, repoUrl) => {
      if (!repoUrl || !filename) return "";
      const licenseFile = isLicenseFile(filename) ? filename : "LICENSE";
      const baseRepoUrl = extractBaseRepoUrl(repoUrl);
      return `${baseRepoUrl}/blob/main/${licenseFile}`;
    }, "createLicenseUrl");
    const parseLicenseObject = /* @__PURE__ */ __name((licenseObj) => {
      const licenseFile = licenseObj.file || licenseObj.text;
      if (typeof licenseFile === "string" && isLicenseFile(licenseFile) && __props.nodePack.repository) {
        const url = createLicenseUrl(licenseFile, __props.nodePack.repository);
        return {
          text: url,
          isUrl: !!url && isValidUrl(url)
        };
      } else if (licenseObj.text) {
        return {
          text: licenseObj.text,
          isUrl: false
        };
      } else if (typeof licenseFile === "string") {
        return {
          text: licenseFile,
          isUrl: false
        };
      }
      return {
        text: JSON.stringify(licenseObj),
        isUrl: false
      };
    }, "parseLicenseObject");
    const formatLicense = /* @__PURE__ */ __name((license) => {
      if (license === "{}") return null;
      try {
        const licenseObj = JSON.parse(license);
        if (Object.keys(licenseObj).length === 0) {
          return null;
        }
        return parseLicenseObject(licenseObj);
      } catch (e2) {
        if (isLicenseFile(license) && __props.nodePack.repository) {
          const url = createLicenseUrl(license, __props.nodePack.repository);
          return {
            text: url,
            isUrl: !!url && isValidUrl(url)
          };
        }
        return {
          text: license,
          isUrl: false
        };
      }
    }, "formatLicense");
    const descriptionSections = computed(() => {
      const sections = [
        {
          title: t2("g.description"),
          text: __props.nodePack.description || t2("manager.noDescription")
        }
      ];
      if (__props.nodePack.repository) {
        sections.push({
          title: t2("manager.repository"),
          text: __props.nodePack.repository,
          isUrl: isValidUrl(__props.nodePack.repository)
        });
      }
      if (__props.nodePack.license) {
        const licenseInfo = formatLicense(__props.nodePack.license);
        if (licenseInfo && licenseInfo.text) {
          sections.push({
            title: t2("manager.license"),
            text: licenseInfo.text,
            isUrl: licenseInfo.isUrl
          });
        }
      }
      return sections;
    });
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", _hoisted_1$O, [
        _ctx.nodePack?.description ? (openBlock(), createBlock(_sfc_main$$, {
          key: 0,
          sections: descriptionSections.value
        }, null, 8, ["sections"])) : (openBlock(), createElementBlock("p", _hoisted_2$F, toDisplayString(_ctx.$t("manager.noDescription")), 1)),
        _ctx.nodePack?.latest_version?.dependencies?.length ? (openBlock(), createElementBlock("div", _hoisted_3$r, [
          createBaseVNode("p", _hoisted_4$g, toDisplayString(_ctx.$t("manager.dependencies")), 1),
          (openBlock(true), createElementBlock(Fragment$1, null, renderList(_ctx.nodePack.latest_version.dependencies, (dep, index2) => {
            return openBlock(), createElementBlock("div", {
              key: index2,
              class: "text-muted break-words"
            }, toDisplayString(dep), 1);
          }), 128))
        ])) : createCommentVNode("", true)
      ]);
    };
  }
});
const zIntInputSpec = zIntInputOptions.extend({
  type: z.literal("INT"),
  name: z.string(),
  isOptional: z.boolean().optional()
});
const zFloatInputSpec = zFloatInputOptions.extend({
  type: z.literal("FLOAT"),
  name: z.string(),
  isOptional: z.boolean().optional()
});
const zBooleanInputSpec = zBooleanInputOptions.extend({
  type: z.literal("BOOLEAN"),
  name: z.string(),
  isOptional: z.boolean().optional()
});
const zStringInputSpec = zStringInputOptions.extend({
  type: z.literal("STRING"),
  name: z.string(),
  isOptional: z.boolean().optional()
});
const zComboInputSpec = zComboInputOptions.extend({
  type: z.literal("COMBO"),
  name: z.string(),
  isOptional: z.boolean().optional()
});
const zCustomInputSpec = zBaseInputOptions.extend({
  type: z.string(),
  name: z.string(),
  isOptional: z.boolean().optional()
});
const zInputSpec = z.union([
  zIntInputSpec,
  zFloatInputSpec,
  zBooleanInputSpec,
  zStringInputSpec,
  zComboInputSpec,
  zCustomInputSpec
]);
const zOutputSpec = z.object({
  index: z.number(),
  name: z.string(),
  type: z.string(),
  is_list: z.boolean(),
  options: z.array(z.any()).optional(),
  tooltip: z.string().optional()
});
const zComfyNodeDef = z.object({
  inputs: z.record(zInputSpec),
  outputs: z.array(zOutputSpec),
  hidden: z.record(z.any()).optional(),
  name: z.string(),
  display_name: z.string(),
  description: z.string(),
  category: z.string(),
  output_node: z.boolean(),
  python_module: z.string(),
  deprecated: z.boolean().optional(),
  experimental: z.boolean().optional(),
  api_node: z.boolean().optional()
});
const isIntInputSpec = /* @__PURE__ */ __name((inputSpec) => {
  return inputSpec.type === "INT";
}, "isIntInputSpec");
const isFloatInputSpec = /* @__PURE__ */ __name((inputSpec) => {
  return inputSpec.type === "FLOAT";
}, "isFloatInputSpec");
const isBooleanInputSpec = /* @__PURE__ */ __name((inputSpec) => {
  return inputSpec.type === "BOOLEAN";
}, "isBooleanInputSpec");
const isStringInputSpec = /* @__PURE__ */ __name((inputSpec) => {
  return inputSpec.type === "STRING";
}, "isStringInputSpec");
const isComboInputSpec = /* @__PURE__ */ __name((inputSpec) => {
  return inputSpec.type === "COMBO";
}, "isComboInputSpec");
const isComfyNodeDef = /* @__PURE__ */ __name((nodeDef) => {
  return !!nodeDef && typeof nodeDef === "object" && ["inputs", "outputs"].every((key) => key in nodeDef);
}, "isComfyNodeDef");
const useBooleanWidget = /* @__PURE__ */ __name(() => {
  const widgetConstructor = /* @__PURE__ */ __name((node2, inputSpec) => {
    if (!isBooleanInputSpec(inputSpec)) {
      throw new Error(`Invalid input data: ${inputSpec}`);
    }
    const defaultVal = inputSpec.default ?? false;
    const options2 = {
      on: inputSpec.label_on,
      off: inputSpec.label_off
    };
    return node2.addWidget(
      "toggle",
      inputSpec.name,
      defaultVal,
      () => {
      },
      options2
    );
  }, "widgetConstructor");
  return widgetConstructor;
}, "useBooleanWidget");
const _sfc_main$Z = /* @__PURE__ */ defineComponent({
  __name: "MultiSelectWidget",
  props: /* @__PURE__ */ mergeModels({
    widget: {}
  }, {
    "modelValue": { required: true },
    "modelModifiers": {}
  }),
  emits: ["update:modelValue"],
  setup(__props) {
    const selectedItems = useModel(__props, "modelValue");
    const inputSpec = __props.widget.inputSpec;
    const options2 = inputSpec.options ?? [];
    const placeholder = inputSpec.multi_select?.placeholder ?? "Select items";
    const display = inputSpec.multi_select?.chip ? "chip" : "comma";
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", null, [
        createVNode(unref(script$A), {
          modelValue: selectedItems.value,
          "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => selectedItems.value = $event),
          options: unref(options2),
          filter: "",
          placeholder: unref(placeholder),
          "max-selected-labels": 3,
          display: unref(display),
          class: "w-full"
        }, null, 8, ["modelValue", "options", "placeholder", "display"])
      ]);
    };
  }
});
function transformNodeDefV1ToV2(nodeDefV1) {
  const inputs = {};
  if (nodeDefV1.input?.required) {
    Object.entries(nodeDefV1.input.required).forEach(([name2, inputSpecV1]) => {
      inputs[name2] = transformInputSpecV1ToV2(inputSpecV1, {
        name: name2,
        isOptional: false
      });
    });
  }
  if (nodeDefV1.input?.optional) {
    Object.entries(nodeDefV1.input.optional).forEach(([name2, inputSpecV1]) => {
      inputs[name2] = transformInputSpecV1ToV2(inputSpecV1, {
        name: name2,
        isOptional: true
      });
    });
  }
  const outputs = [];
  if (nodeDefV1.output) {
    nodeDefV1.output.forEach((outputType, index2) => {
      const outputSpec = {
        index: index2,
        name: nodeDefV1.output_name?.[index2] || `output_${index2}`,
        type: Array.isArray(outputType) ? "COMBO" : outputType,
        is_list: nodeDefV1.output_is_list?.[index2] || false,
        tooltip: nodeDefV1.output_tooltips?.[index2]
      };
      if (Array.isArray(outputType)) {
        outputSpec.options = outputType;
      }
      outputs.push(outputSpec);
    });
  }
  return {
    inputs,
    outputs,
    hidden: nodeDefV1.input?.hidden,
    name: nodeDefV1.name,
    display_name: nodeDefV1.display_name,
    description: nodeDefV1.description,
    category: nodeDefV1.category,
    output_node: nodeDefV1.output_node,
    python_module: nodeDefV1.python_module,
    deprecated: nodeDefV1.deprecated,
    experimental: nodeDefV1.experimental
  };
}
__name(transformNodeDefV1ToV2, "transformNodeDefV1ToV2");
function transformInputSpecV1ToV2(inputSpecV1, kwargs) {
  const { name: name2, isOptional = false } = kwargs;
  const options2 = inputSpecV1[1] || {};
  const baseProps = {
    name: name2,
    isOptional,
    ...options2
  };
  if (isComboInputSpec$1(inputSpecV1)) {
    return {
      type: "COMBO",
      ...baseProps,
      options: isComboInputSpecV1(inputSpecV1) ? inputSpecV1[0] : getComboSpecComboOptions(inputSpecV1)
    };
  } else if (typeof inputSpecV1[0] === "string") {
    return {
      type: inputSpecV1[0],
      ...baseProps
    };
  }
  return {
    type: "UNKNOWN",
    ...baseProps
  };
}
__name(transformInputSpecV1ToV2, "transformInputSpecV1ToV2");
function transformInputSpecV2ToV1(inputSpecV2) {
  return [inputSpecV2.type, inputSpecV2];
}
__name(transformInputSpecV2ToV1, "transformInputSpecV2ToV1");
const useChainCallback = /* @__PURE__ */ __name((originalCallback, ...callbacks) => {
  return function(...args) {
    originalCallback?.call(this, ...args);
    for (const callback of callbacks) callback.call(this, ...args);
  };
}, "useChainCallback");
const useDomWidgetStore = /* @__PURE__ */ defineStore("domWidget", () => {
  const widgetStates = ref$3(/* @__PURE__ */ new Map());
  const registerWidget = /* @__PURE__ */ __name((widget) => {
    widgetStates.value.set(widget.id, {
      widget: markRaw(widget),
      visible: true,
      readonly: false,
      zIndex: 0,
      pos: [0, 0],
      size: [0, 0]
    });
  }, "registerWidget");
  const unregisterWidget = /* @__PURE__ */ __name((widgetId) => {
    widgetStates.value.delete(widgetId);
  }, "unregisterWidget");
  return {
    widgetStates,
    registerWidget,
    unregisterWidget
  };
});
const isDOMWidget = /* @__PURE__ */ __name((widget) => "element" in widget && !!widget.element, "isDOMWidget");
const isComponentWidget = /* @__PURE__ */ __name((widget) => "component" in widget && !!widget.component, "isComponentWidget");
class BaseDOMWidgetImpl extends LegacyWidget {
  static {
    __name(this, "BaseDOMWidgetImpl");
  }
  static DEFAULT_MARGIN = 10;
  id;
  constructor(obj) {
    const { node: node2, name: name2, type, options: options2 } = obj;
    super({ y: 0, name: name2, type, options: options2 }, node2);
    this.id = generateUUID();
  }
  get value() {
    return this.options.getValue?.() ?? "";
  }
  set value(v2) {
    this.options.setValue?.(v2);
    this.callback?.(this.value);
  }
  get margin() {
    return this.options.margin ?? BaseDOMWidgetImpl.DEFAULT_MARGIN;
  }
  isVisible() {
    return !["hidden"].includes(this.type) && this.node.isWidgetVisible(this);
  }
  draw(ctx, _node, widget_width, y2, widget_height, lowQuality) {
    if (this.options.hideOnZoom && lowQuality && this.isVisible()) {
      const originalFillStyle = ctx.fillStyle;
      ctx.beginPath();
      ctx.fillStyle = LiteGraph.WIDGET_BGCOLOR;
      ctx.rect(
        this.margin,
        y2 + this.margin,
        widget_width - this.margin * 2,
        (this.computedHeight ?? widget_height) - 2 * this.margin
      );
      ctx.fill();
      ctx.fillStyle = originalFillStyle;
    }
    this.options.onDraw?.(this);
  }
  onRemove() {
    useDomWidgetStore().unregisterWidget(this.id);
  }
}
class DOMWidgetImpl extends BaseDOMWidgetImpl {
  static {
    __name(this, "DOMWidgetImpl");
  }
  element;
  constructor(obj) {
    super(obj);
    this.element = obj.element;
  }
  /** Extract DOM widget size info */
  computeLayoutSize(node2) {
    if (this.type === "hidden") {
      return {
        minHeight: 0,
        maxHeight: 0,
        minWidth: 0
      };
    }
    const styles = getComputedStyle(this.element);
    let minHeight = this.options.getMinHeight?.() ?? parseInt(styles.getPropertyValue("--comfy-widget-min-height"));
    let maxHeight = this.options.getMaxHeight?.() ?? parseInt(styles.getPropertyValue("--comfy-widget-max-height"));
    let prefHeight = this.options.getHeight?.() ?? styles.getPropertyValue("--comfy-widget-height");
    if (typeof prefHeight === "string" && prefHeight.endsWith?.("%")) {
      prefHeight = node2.size[1] * (parseFloat(prefHeight.substring(0, prefHeight.length - 1)) / 100);
    } else {
      prefHeight = typeof prefHeight === "number" ? prefHeight : parseInt(prefHeight);
      if (isNaN(minHeight)) {
        minHeight = prefHeight;
      }
    }
    return {
      minHeight: isNaN(minHeight) ? 50 : minHeight,
      maxHeight: isNaN(maxHeight) ? void 0 : maxHeight,
      minWidth: 0
    };
  }
}
class ComponentWidgetImpl extends BaseDOMWidgetImpl {
  static {
    __name(this, "ComponentWidgetImpl");
  }
  component;
  inputSpec;
  constructor(obj) {
    super({
      ...obj,
      type: "custom"
    });
    this.component = obj.component;
    this.inputSpec = obj.inputSpec;
  }
  computeLayoutSize() {
    const minHeight = this.options.getMinHeight?.() ?? 50;
    const maxHeight = this.options.getMaxHeight?.();
    return {
      minHeight,
      maxHeight,
      minWidth: 0
    };
  }
  serializeValue() {
    return toRaw(this.value);
  }
}
const addWidget = /* @__PURE__ */ __name((node2, widget) => {
  node2.addCustomWidget(widget);
  if (node2.graph) {
    useDomWidgetStore().registerWidget(widget);
  }
  node2.onAdded = useChainCallback(node2.onAdded, () => {
    useDomWidgetStore().registerWidget(widget);
  });
  node2.onRemoved = useChainCallback(node2.onRemoved, () => {
    widget.onRemove?.();
  });
  node2.onResize = useChainCallback(node2.onResize, () => {
    widget.options.beforeResize?.call(widget, node2);
    widget.options.afterResize?.call(widget, node2);
  });
}, "addWidget");
LGraphNode.prototype.addDOMWidget = function(name2, type, element, options2 = {}) {
  const widget = new DOMWidgetImpl({
    node: this,
    name: name2,
    type,
    element,
    options: { hideOnZoom: true, ...options2 }
  });
  addWidget(this, widget);
  Object.defineProperty(widget, "value", {
    get() {
      return this.options.getValue?.() ?? "";
    },
    set(v2) {
      this.options.setValue?.(v2);
      this.callback?.(this.value);
    }
  });
  return widget;
};
const pruneWidgets = /* @__PURE__ */ __name((nodes) => {
  const nodeSet = new Set(nodes);
  const domWidgetStore = useDomWidgetStore();
  for (const widgetState of domWidgetStore.widgetStates.values()) {
    const widget = widgetState.widget;
    if (!nodeSet.has(widget.node)) {
      domWidgetStore.unregisterWidget(widget.id);
    }
  }
}, "pruneWidgets");
window.comfyAPI = window.comfyAPI || {};
window.comfyAPI.domWidget = window.comfyAPI.domWidget || {};
window.comfyAPI.domWidget.isDOMWidget = isDOMWidget;
window.comfyAPI.domWidget.isComponentWidget = isComponentWidget;
window.comfyAPI.domWidget.DOMWidgetImpl = DOMWidgetImpl;
window.comfyAPI.domWidget.ComponentWidgetImpl = ComponentWidgetImpl;
window.comfyAPI.domWidget.addWidget = addWidget;
window.comfyAPI.domWidget.pruneWidgets = pruneWidgets;
const MAX_RETRIES$1 = 5;
const TIMEOUT = 4096;
const dataCache = /* @__PURE__ */ new Map();
const createCacheKey = /* @__PURE__ */ __name((config2) => {
  const { route, query_params = {}, refresh = 0 } = config2;
  const paramsKey = Object.entries(query_params).sort(([a2], [b2]) => a2.localeCompare(b2)).map(([k2, v2]) => `${k2}=${v2}`).join("&");
  return [route, `r=${refresh}`, paramsKey].join(";");
}, "createCacheKey");
const getBackoff = /* @__PURE__ */ __name((retryCount) => Math.min(1e3 * Math.pow(2, retryCount), 512), "getBackoff");
const isInitialized = /* @__PURE__ */ __name((entry) => entry?.data && entry?.timestamp && entry.timestamp > 0, "isInitialized");
const isStale = /* @__PURE__ */ __name((entry, ttl) => entry?.timestamp && Date.now() - entry.timestamp >= ttl, "isStale");
const isFetching = /* @__PURE__ */ __name((entry) => entry?.fetchPromise !== void 0, "isFetching");
const isFailed = /* @__PURE__ */ __name((entry) => entry?.failed === true, "isFailed");
const isBackingOff = /* @__PURE__ */ __name((entry) => entry?.error && entry?.lastErrorTime && Date.now() - entry.lastErrorTime < getBackoff(entry.retryCount || 0), "isBackingOff");
const fetchData = /* @__PURE__ */ __name(async (config2, controller) => {
  const { route, response_key, query_params, timeout = TIMEOUT } = config2;
  const res = await axios.get(route, {
    params: query_params,
    signal: controller.signal,
    timeout
  });
  return response_key ? res.data[response_key] : res.data;
}, "fetchData");
function useRemoteWidget(options2) {
  const { remoteConfig, defaultValue, node: node2, widget } = options2;
  const { refresh = 0, max_retries = MAX_RETRIES$1 } = remoteConfig;
  const isPermanent = refresh <= 0;
  const cacheKey = createCacheKey(remoteConfig);
  let isLoaded = false;
  let refreshQueued = false;
  const setSuccess = /* @__PURE__ */ __name((entry, data) => {
    entry.retryCount = 0;
    entry.lastErrorTime = 0;
    entry.error = null;
    entry.timestamp = Date.now();
    entry.data = data ?? defaultValue;
  }, "setSuccess");
  const setError = /* @__PURE__ */ __name((entry, error2) => {
    entry.retryCount = (entry.retryCount || 0) + 1;
    entry.lastErrorTime = Date.now();
    entry.error = error2 instanceof Error ? error2 : new Error(String(error2));
    entry.data ??= defaultValue;
    entry.fetchPromise = void 0;
    if (entry.retryCount >= max_retries) {
      setFailed(entry);
    }
  }, "setError");
  const setFailed = /* @__PURE__ */ __name((entry) => {
    dataCache.set(cacheKey, {
      data: entry.data ?? defaultValue,
      failed: true
    });
  }, "setFailed");
  const isFirstLoad = /* @__PURE__ */ __name(() => {
    return !isLoaded && isInitialized(dataCache.get(cacheKey));
  }, "isFirstLoad");
  const onFirstLoad = /* @__PURE__ */ __name((data) => {
    isLoaded = true;
    widget.value = data[0];
    widget.callback?.(widget.value);
    node2.graph?.setDirtyCanvas(true);
  }, "onFirstLoad");
  const fetchValue = /* @__PURE__ */ __name(async () => {
    const entry = dataCache.get(cacheKey);
    if (isFailed(entry)) return entry.data;
    const isValid2 = isInitialized(entry) && (isPermanent || !isStale(entry, refresh));
    if (isValid2 || isBackingOff(entry) || isFetching(entry)) return entry.data;
    const currentEntry = entry || { data: defaultValue };
    dataCache.set(cacheKey, currentEntry);
    try {
      currentEntry.controller = new AbortController();
      currentEntry.fetchPromise = fetchData(
        remoteConfig,
        currentEntry.controller
      );
      const data = await currentEntry.fetchPromise;
      setSuccess(currentEntry, data);
      return currentEntry.data;
    } catch (err) {
      setError(currentEntry, err);
      return currentEntry.data;
    } finally {
      currentEntry.fetchPromise = void 0;
      currentEntry.controller = void 0;
    }
  }, "fetchValue");
  const onRefresh = /* @__PURE__ */ __name(() => {
    if (remoteConfig.control_after_refresh) {
      const data = getCachedValue();
      if (!Array.isArray(data)) return;
      switch (remoteConfig.control_after_refresh) {
        case "first":
          widget.value = data[0] ?? defaultValue;
          break;
        case "last":
          widget.value = data.at(-1) ?? defaultValue;
          break;
      }
      widget.callback?.(widget.value);
      node2.graph?.setDirtyCanvas(true);
    }
  }, "onRefresh");
  const clearCachedValue = /* @__PURE__ */ __name(() => {
    const entry = dataCache.get(cacheKey);
    if (!entry) return;
    if (entry.fetchPromise) entry.controller?.abort();
    dataCache.delete(cacheKey);
  }, "clearCachedValue");
  function getCachedValue() {
    return dataCache.get(cacheKey)?.data;
  }
  __name(getCachedValue, "getCachedValue");
  function getValue2(onFulfilled) {
    void fetchValue().then((data) => {
      if (isFirstLoad()) onFirstLoad(data);
      if (refreshQueued && data !== defaultValue) {
        onRefresh();
        refreshQueued = false;
      }
      onFulfilled?.();
    }).catch((err) => {
      console.error(err);
    });
    return getCachedValue() ?? defaultValue;
  }
  __name(getValue2, "getValue");
  widget.refresh = function() {
    refreshQueued = true;
    clearCachedValue();
    getValue2();
  };
  function addRefreshButton() {
    node2.addWidget("button", "refresh", "refresh", widget.refresh);
  }
  __name(addRefreshButton, "addRefreshButton");
  return {
    getCachedValue,
    getValue: getValue2,
    refreshValue: widget.refresh,
    addRefreshButton,
    getCacheEntry: /* @__PURE__ */ __name(() => dataCache.get(cacheKey), "getCacheEntry"),
    cacheKey
  };
}
__name(useRemoteWidget, "useRemoteWidget");
const getDefaultValue = /* @__PURE__ */ __name((inputSpec) => {
  if (inputSpec.default) return inputSpec.default;
  if (inputSpec.options?.length) return inputSpec.options[0];
  if (inputSpec.remote) return "Loading...";
  return void 0;
}, "getDefaultValue");
const addMultiSelectWidget = /* @__PURE__ */ __name((node2, inputSpec) => {
  const widgetValue = ref$3([]);
  const widget = new ComponentWidgetImpl({
    node: node2,
    name: inputSpec.name,
    component: _sfc_main$Z,
    inputSpec,
    options: {
      getValue: /* @__PURE__ */ __name(() => widgetValue.value, "getValue"),
      setValue: /* @__PURE__ */ __name((value) => {
        widgetValue.value = value;
      }, "setValue")
    }
  });
  addWidget(node2, widget);
  return widget;
}, "addMultiSelectWidget");
const addComboWidget = /* @__PURE__ */ __name((node2, inputSpec) => {
  const defaultValue = getDefaultValue(inputSpec);
  const comboOptions = inputSpec.options ?? [];
  const widget = node2.addWidget(
    "combo",
    inputSpec.name,
    defaultValue,
    () => {
    },
    {
      values: comboOptions
    }
  );
  if (inputSpec.remote) {
    const remoteWidget = useRemoteWidget({
      remoteConfig: inputSpec.remote,
      defaultValue,
      node: node2,
      widget
    });
    if (inputSpec.remote.refresh_button) remoteWidget.addRefreshButton();
    const origOptions = widget.options;
    widget.options = new Proxy(origOptions, {
      get(target, prop2) {
        return prop2 !== "values" ? target[prop2] : remoteWidget.getValue();
      }
    });
  }
  if (inputSpec.control_after_generate) {
    widget.linkedWidgets = addValueControlWidgets(
      node2,
      widget,
      void 0,
      void 0,
      transformInputSpecV2ToV1(inputSpec)
    );
  }
  return widget;
}, "addComboWidget");
const useComboWidget = /* @__PURE__ */ __name(() => {
  const widgetConstructor = /* @__PURE__ */ __name((node2, inputSpec) => {
    if (!isComboInputSpec(inputSpec)) {
      throw new Error(`Invalid input data: ${inputSpec}`);
    }
    return inputSpec.multi_select ? addMultiSelectWidget(node2, inputSpec) : addComboWidget(node2, inputSpec);
  }, "widgetConstructor");
  return widgetConstructor;
}, "useComboWidget");
function onFloatValueChange(v2) {
  this.value = this.options.round ? _.clamp(
    Math.round((v2 + Number.EPSILON) / this.options.round) * this.options.round,
    this.options.min ?? -Infinity,
    this.options.max ?? Infinity
  ) : v2;
}
__name(onFloatValueChange, "onFloatValueChange");
const _for_testing$1 = {
  onFloatValueChange
};
const useFloatWidget = /* @__PURE__ */ __name(() => {
  const widgetConstructor = /* @__PURE__ */ __name((node2, inputSpec) => {
    if (!isFloatInputSpec(inputSpec)) {
      throw new Error(`Invalid input data: ${inputSpec}`);
    }
    const settingStore = useSettingStore();
    const sliderEnabled = !settingStore.get("Comfy.DisableSliders");
    const display_type = inputSpec.display;
    const widgetType = sliderEnabled && display_type == "slider" ? "slider" : display_type == "knob" ? "knob" : "number";
    const step = inputSpec.step ?? 0.5;
    const precision = settingStore.get("Comfy.FloatRoundingPrecision") || Math.max(0, -Math.floor(Math.log10(step)));
    const enableRounding = !settingStore.get("Comfy.DisableFloatRounding");
    const defaultValue = inputSpec.default ?? 0;
    return node2.addWidget(
      widgetType,
      inputSpec.name,
      defaultValue,
      onFloatValueChange,
      {
        min: inputSpec.min ?? 0,
        max: inputSpec.max ?? 2048,
        round: enableRounding && precision && !inputSpec.round ? 1e6 * Math.pow(0.1, precision) / 1e6 : inputSpec.round,
        /** @deprecated Use step2 instead. The 10x value is a legacy implementation. */
        step: step * 10,
        step2: step,
        precision
      }
    );
  }, "widgetConstructor");
  return widgetConstructor;
}, "useFloatWidget");
function isImageNode(node2) {
  if (!node2) return false;
  return node2.previewMediaType === "image" || node2.previewMediaType !== "video" && !!node2.imgs?.length;
}
__name(isImageNode, "isImageNode");
function isVideoNode(node2) {
  if (!node2) return false;
  return node2.previewMediaType === "video" || !!node2.videoContainer;
}
__name(isVideoNode, "isVideoNode");
function isAudioNode(node2) {
  return !!node2 && node2.previewMediaType === "audio";
}
__name(isAudioNode, "isAudioNode");
function addToComboValues(widget, value) {
  if (!widget.options) widget.options = { values: [] };
  if (!widget.options.values) widget.options.values = [];
  if (!widget.options.values.includes(value)) {
    widget.options.values.push(value);
  }
}
__name(addToComboValues, "addToComboValues");
const isLGraphNode = /* @__PURE__ */ __name((item) => {
  return item instanceof LGraphNode;
}, "isLGraphNode");
const isLGraphGroup = /* @__PURE__ */ __name((item) => {
  return item instanceof LGraphGroup;
}, "isLGraphGroup");
const getItemsColorOption = /* @__PURE__ */ __name((items) => {
  const validItems = _.filter(items, isColorable);
  if (_.isEmpty(validItems)) return null;
  const colorOptions = _.map(validItems, (item) => item.getColorOption());
  return _.every(
    colorOptions,
    (option) => _.isEqual(option, _.head(colorOptions))
  ) ? _.head(colorOptions) : null;
}, "getItemsColorOption");
function executeWidgetsCallback(nodes, callbackName) {
  for (const node2 of nodes) {
    for (const widget of node2.widgets ?? []) {
      widget[callbackName]?.();
    }
  }
}
__name(executeWidgetsCallback, "executeWidgetsCallback");
function migrateWidgetsValues(inputDefs, widgets, widgetsValues) {
  const widgetNames = new Set(widgets.map((w2) => w2.name));
  const originalWidgetsInputs = Object.values(inputDefs).filter(
    (input) => widgetNames.has(input.name) || input.forceInput
  );
  const numOriginalWidgets = _.sum(
    originalWidgetsInputs.map(
      (input) => (
        // If the input has control, it will have 2 widgets.
        input.control_after_generate || ["seed", "noise_seed"].includes(input.name) ? 2 : 1
      )
    )
  );
  if (numOriginalWidgets === widgetsValues?.length) {
    return _.zip(originalWidgetsInputs, widgetsValues).filter(([input]) => !input?.forceInput).map(([_2, value]) => value);
  }
  return widgetsValues;
}
__name(migrateWidgetsValues, "migrateWidgetsValues");
function fixLinkInputSlots(graph) {
  for (const node2 of graph.nodes) {
    for (const [inputIndex, input] of node2.inputs.entries()) {
      const linkId = input.link;
      if (!linkId) continue;
      const link2 = graph.links.get(linkId);
      if (!link2) continue;
      link2.target_slot = inputIndex;
    }
  }
}
__name(fixLinkInputSlots, "fixLinkInputSlots");
function compressWidgetInputSlots(graph) {
  for (const node2 of graph.nodes) {
    node2.inputs = node2.inputs?.filter(
      (input) => !(input.widget && input.link === null)
    );
    for (const [inputIndex, input] of node2.inputs?.entries() ?? []) {
      if (input.link) {
        const link2 = graph.links.find((link22) => link22[0] === input.link);
        if (link2) {
          link2[4] = inputIndex;
        }
      }
    }
  }
}
__name(compressWidgetInputSlots, "compressWidgetInputSlots");
const createOutputs = /* @__PURE__ */ __name((filenames, type, isAnimated) => {
  return {
    images: filenames.map((image2) => ({ type, ...parseFilePath(image2) })),
    animated: filenames.map((image2) => isAnimated && image2.endsWith(".webp"))
  };
}, "createOutputs");
const useNodeOutputStore = /* @__PURE__ */ defineStore("nodeOutput", () => {
  const getNodeId = /* @__PURE__ */ __name((node2) => node2.id.toString(), "getNodeId");
  function getNodeOutputs(node2) {
    return app$1.nodeOutputs[getNodeId(node2)];
  }
  __name(getNodeOutputs, "getNodeOutputs");
  function getNodePreviews(node2) {
    return app$1.nodePreviewImages[getNodeId(node2)];
  }
  __name(getNodePreviews, "getNodePreviews");
  const isImageOutputs = /* @__PURE__ */ __name((node2, outputs) => {
    if (node2.animatedImages || isVideoNode(node2)) return false;
    if (!outputs?.images?.length) return false;
    if (outputs.images.some((image2) => image2.filename?.endsWith("svg")))
      return false;
    return true;
  }, "isImageOutputs");
  function getPreviewParam(node2, outputs) {
    return isImageOutputs(node2, outputs) ? app$1.getPreviewFormatParam() : "";
  }
  __name(getPreviewParam, "getPreviewParam");
  function getNodeImageUrls(node2) {
    const previews = getNodePreviews(node2);
    if (previews?.length) return previews;
    const outputs = getNodeOutputs(node2);
    if (!outputs?.images?.length) return;
    const rand2 = app$1.getRandParam();
    const previewParam = getPreviewParam(node2, outputs);
    return outputs.images.map((image2) => {
      const imgUrlPart = new URLSearchParams(image2);
      return api.apiURL(`/view?${imgUrlPart}${previewParam}${rand2}`);
    });
  }
  __name(getNodeImageUrls, "getNodeImageUrls");
  function setNodeOutputs(node2, filenames, {
    folder = "input",
    isAnimated = false
  } = {}) {
    if (!filenames || !node2) return;
    const nodeId = getNodeId(node2);
    if (typeof filenames === "string") {
      app$1.nodeOutputs[nodeId] = createOutputs([filenames], folder, isAnimated);
    } else if (!Array.isArray(filenames)) {
      app$1.nodeOutputs[nodeId] = filenames;
    } else {
      const resultItems = createOutputs(filenames, folder, isAnimated);
      if (!resultItems?.images?.length) return;
      app$1.nodeOutputs[nodeId] = resultItems;
    }
  }
  __name(setNodeOutputs, "setNodeOutputs");
  return {
    getNodeOutputs,
    getNodeImageUrls,
    getNodePreviews,
    setNodeOutputs,
    getPreviewParam
  };
});
const is_all_same_aspect_ratio = /* @__PURE__ */ __name((imgs) => {
  if (!imgs.length || imgs.length === 1) return true;
  const ratio = imgs[0].naturalWidth / imgs[0].naturalHeight;
  for (let i2 = 1; i2 < imgs.length; i2++) {
    const this_ratio = imgs[i2].naturalWidth / imgs[i2].naturalHeight;
    if (ratio != this_ratio) return false;
  }
  return true;
}, "is_all_same_aspect_ratio");
const fitDimensionsToNodeWidth = /* @__PURE__ */ __name((width2, height, nodeWidth, minHeight = 64) => {
  const intrinsicAspectRatio = width2 / height;
  if (!intrinsicAspectRatio || isNaN(intrinsicAspectRatio))
    return { minHeight: 0, minWidth: 0 };
  const minWidth = nodeWidth;
  const calculatedHeight = Math.max(minWidth / intrinsicAspectRatio, minHeight);
  return { minHeight: calculatedHeight, minWidth };
}, "fitDimensionsToNodeWidth");
const VIDEO_WIDGET_NAME = "video-preview";
const VIDEO_DEFAULT_OPTIONS = {
  playsInline: true,
  controls: true,
  loop: true
};
const MEDIA_LOAD_TIMEOUT = 8192;
const MAX_RETRIES = 1;
const DEFAULT_VIDEO_SIZE = 256;
const createContainer = /* @__PURE__ */ __name(() => {
  const container = document.createElement("div");
  container.classList.add("comfy-img-preview");
  return container;
}, "createContainer");
const createTimeout = /* @__PURE__ */ __name((ms) => new Promise((resolve2) => setTimeout(() => resolve2(null), ms)), "createTimeout");
const useNodePreview = /* @__PURE__ */ __name((node2, options2) => {
  const { loadElement, onLoaded, onFailedLoading } = options2;
  const nodeOutputStore = useNodeOutputStore();
  const loadElementWithTimeout = /* @__PURE__ */ __name(async (url, retryCount = 0) => {
    const result = await Promise.race([
      loadElement(url),
      createTimeout(MEDIA_LOAD_TIMEOUT)
    ]);
    if (result === null && retryCount < MAX_RETRIES) {
      return loadElementWithTimeout(url, retryCount + 1);
    }
    return result;
  }, "loadElementWithTimeout");
  const loadElements = /* @__PURE__ */ __name(async (urls) => Promise.all(urls.map((url) => loadElementWithTimeout(url))), "loadElements");
  function showPreview(options22 = {}) {
    if (node2.isLoading) return;
    const outputUrls = nodeOutputStore.getNodeImageUrls(node2);
    if (!outputUrls?.length) return;
    if (options22?.block) node2.isLoading = true;
    loadElements(outputUrls).then((elements) => {
      const validElements = elements.filter(
        (el) => el !== null
      );
      if (validElements.length) {
        onLoaded?.(validElements);
        node2.graph?.setDirtyCanvas(true);
      }
    }).catch(() => {
      onFailedLoading?.();
    }).finally(() => {
      node2.isLoading = false;
    });
  }
  __name(showPreview, "showPreview");
  return {
    showPreview
  };
}, "useNodePreview");
const useNodeImage = /* @__PURE__ */ __name((node2) => {
  node2.previewMediaType = "image";
  const loadElement = /* @__PURE__ */ __name((url) => new Promise((resolve2) => {
    const img = new Image();
    img.onload = () => resolve2(img);
    img.onerror = () => resolve2(null);
    img.src = url;
  }), "loadElement");
  const onLoaded = /* @__PURE__ */ __name((elements) => {
    node2.imageIndex = null;
    node2.imgs = elements;
  }, "onLoaded");
  return useNodePreview(node2, {
    loadElement,
    onLoaded,
    onFailedLoading: /* @__PURE__ */ __name(() => {
      node2.imgs = void 0;
    }, "onFailedLoading")
  });
}, "useNodeImage");
const useNodeVideo = /* @__PURE__ */ __name((node2) => {
  node2.previewMediaType = "video";
  let minHeight = DEFAULT_VIDEO_SIZE;
  let minWidth = DEFAULT_VIDEO_SIZE;
  const setMinDimensions = /* @__PURE__ */ __name((video) => {
    const { minHeight: calculatedHeight, minWidth: calculatedWidth } = fitDimensionsToNodeWidth(
      video.videoWidth,
      video.videoHeight,
      node2.size?.[0] || DEFAULT_VIDEO_SIZE
    );
    minWidth = calculatedWidth;
    minHeight = calculatedHeight;
  }, "setMinDimensions");
  const loadElement = /* @__PURE__ */ __name((url) => new Promise((resolve2) => {
    const video = document.createElement("video");
    Object.assign(video, VIDEO_DEFAULT_OPTIONS);
    video.onloadeddata = () => {
      setMinDimensions(video);
      resolve2(video);
    };
    video.onerror = () => resolve2(null);
    video.src = url;
  }), "loadElement");
  const addVideoDomWidget = /* @__PURE__ */ __name((container) => {
    const hasWidget = node2.widgets?.some((w2) => w2.name === VIDEO_WIDGET_NAME);
    if (!hasWidget) {
      const widget = node2.addDOMWidget(VIDEO_WIDGET_NAME, "video", container, {
        hideOnZoom: false
      });
      widget.serialize = false;
      widget.computeLayoutSize = () => ({
        minHeight,
        minWidth
      });
    }
  }, "addVideoDomWidget");
  const onLoaded = /* @__PURE__ */ __name((videoElements) => {
    const videoElement = videoElements[0];
    if (!videoElement) return;
    if (!node2.videoContainer) {
      node2.videoContainer = createContainer();
      addVideoDomWidget(node2.videoContainer);
    }
    node2.videoContainer.replaceChildren(videoElement);
  }, "onLoaded");
  return useNodePreview(node2, {
    loadElement,
    onLoaded,
    onFailedLoading: /* @__PURE__ */ __name(() => {
      node2.videoContainer = void 0;
    }, "onFailedLoading")
  });
}, "useNodeVideo");
const useNodeDragAndDrop = /* @__PURE__ */ __name((node2, options2) => {
  const { onDragOver, onDrop, fileFilter = /* @__PURE__ */ __name(() => true, "fileFilter") } = options2;
  const hasFiles = /* @__PURE__ */ __name((items) => !!Array.from(items).find((f2) => f2.kind === "file"), "hasFiles");
  const filterFiles = /* @__PURE__ */ __name((files) => Array.from(files).filter(fileFilter), "filterFiles");
  const hasValidFiles = /* @__PURE__ */ __name((files) => filterFiles(files).length > 0, "hasValidFiles");
  const isDraggingFiles = /* @__PURE__ */ __name((e2) => {
    if (!e2?.dataTransfer?.items) return false;
    return onDragOver?.(e2) ?? hasFiles(e2.dataTransfer.items);
  }, "isDraggingFiles");
  const isDraggingValidFiles = /* @__PURE__ */ __name((e2) => {
    if (!e2?.dataTransfer?.files) return false;
    return hasValidFiles(e2.dataTransfer.files);
  }, "isDraggingValidFiles");
  node2.onDragOver = isDraggingFiles;
  node2.onDragDrop = function(e2) {
    if (!isDraggingValidFiles(e2)) return false;
    const files = filterFiles(e2.dataTransfer.files);
    void onDrop(files);
    return true;
  };
}, "useNodeDragAndDrop");
function useNodeFileInput(node2, options2) {
  const {
    accept,
    allow_batch = false,
    fileFilter = /* @__PURE__ */ __name(() => true, "fileFilter"),
    onSelect
  } = options2;
  let fileInput2 = document.createElement("input");
  fileInput2.type = "file";
  fileInput2.accept = accept ?? "*";
  fileInput2.multiple = allow_batch;
  fileInput2.onchange = () => {
    if (fileInput2?.files?.length) {
      const files = Array.from(fileInput2.files).filter(fileFilter);
      if (files.length) onSelect(files);
    }
  };
  node2.onRemoved = useChainCallback(node2.onRemoved, () => {
    if (fileInput2) {
      fileInput2.onchange = null;
      fileInput2 = null;
    }
  });
  return {
    openFileSelection: /* @__PURE__ */ __name(() => fileInput2?.click(), "openFileSelection")
  };
}
__name(useNodeFileInput, "useNodeFileInput");
const useNodePaste = /* @__PURE__ */ __name((node2, options2) => {
  const { onPaste, fileFilter = /* @__PURE__ */ __name(() => true, "fileFilter"), allow_batch = false } = options2;
  node2.pasteFiles = function(files) {
    const filteredFiles = Array.from(files).filter(fileFilter);
    if (!filteredFiles.length) return false;
    const paste = allow_batch ? filteredFiles : filteredFiles.slice(0, 1);
    void onPaste(paste);
    return true;
  };
}, "useNodePaste");
const PASTED_IMAGE_EXPIRY_MS = 2e3;
const uploadFile$1 = /* @__PURE__ */ __name(async (file, isPasted) => {
  const body = new FormData();
  body.append("image", file);
  if (isPasted) body.append("subfolder", "pasted");
  const resp = await api.fetchApi("/upload/image", {
    method: "POST",
    body
  });
  if (resp.status !== 200) {
    useToastStore().addAlert(resp.status + " - " + resp.statusText);
    return;
  }
  const data = await resp.json();
  return data.subfolder ? `${data.subfolder}/${data.name}` : data.name;
}, "uploadFile$1");
const useNodeImageUpload = /* @__PURE__ */ __name((node2, options2) => {
  const { fileFilter, onUploadComplete, allow_batch, accept } = options2;
  const isPastedFile = /* @__PURE__ */ __name((file) => file.name === "image.png" && file.lastModified - Date.now() < PASTED_IMAGE_EXPIRY_MS, "isPastedFile");
  const handleUpload = /* @__PURE__ */ __name(async (file) => {
    try {
      const path = await uploadFile$1(file, isPastedFile(file));
      if (!path) return;
      return path;
    } catch (error2) {
      useToastStore().addAlert(String(error2));
    }
  }, "handleUpload");
  const handleUploadBatch = /* @__PURE__ */ __name(async (files) => {
    const paths = await Promise.all(files.map(handleUpload));
    const validPaths = paths.filter((p2) => !!p2);
    if (validPaths.length) onUploadComplete(validPaths);
    return validPaths;
  }, "handleUploadBatch");
  useNodeDragAndDrop(node2, {
    fileFilter,
    onDrop: handleUploadBatch
  });
  useNodePaste(node2, {
    fileFilter,
    allow_batch,
    onPaste: handleUploadBatch
  });
  const { openFileSelection } = useNodeFileInput(node2, {
    fileFilter,
    allow_batch,
    accept,
    onSelect: handleUploadBatch
  });
  return { openFileSelection, handleUpload };
}, "useNodeImageUpload");
function useValueTransform(transform, initialValue) {
  let internalValue = initialValue;
  let cachedValue = transform(initialValue);
  let isChanged = false;
  return {
    get: /* @__PURE__ */ __name(() => {
      if (!isChanged) return cachedValue;
      cachedValue = transform(internalValue);
      return cachedValue;
    }, "get"),
    set: /* @__PURE__ */ __name((value) => {
      isChanged = true;
      internalValue = value;
    }, "set")
  };
}
__name(useValueTransform, "useValueTransform");
const ACCEPTED_IMAGE_TYPES = "image/png,image/jpeg,image/webp";
const ACCEPTED_VIDEO_TYPES = "video/webm,video/mp4";
const isImageFile = /* @__PURE__ */ __name((file) => file.type.startsWith("image/"), "isImageFile");
const isVideoFile = /* @__PURE__ */ __name((file) => file.type.startsWith("video/"), "isVideoFile");
const findFileComboWidget = /* @__PURE__ */ __name((node2, inputName) => node2.widgets.find((w2) => w2.name === inputName), "findFileComboWidget");
const useImageUploadWidget = /* @__PURE__ */ __name(() => {
  const widgetConstructor = /* @__PURE__ */ __name((node2, inputName, inputData) => {
    const inputOptions = inputData[1] ?? {};
    const { imageInputName, allow_batch, image_folder = "input" } = inputOptions;
    const nodeOutputStore = useNodeOutputStore();
    const isAnimated = !!inputOptions.animated_image_upload;
    const isVideo = !!inputOptions.video_upload;
    const accept = isVideo ? ACCEPTED_VIDEO_TYPES : ACCEPTED_IMAGE_TYPES;
    const { showPreview } = isVideo ? useNodeVideo(node2) : useNodeImage(node2);
    const fileFilter = isVideo ? isVideoFile : isImageFile;
    const fileComboWidget = findFileComboWidget(node2, imageInputName);
    const initialFile = `${fileComboWidget.value}`;
    const formatPath = /* @__PURE__ */ __name((value) => (
      // @ts-expect-error InputSpec is not typed correctly
      createAnnotatedPath(value, { rootFolder: image_folder })
    ), "formatPath");
    const transform = /* @__PURE__ */ __name((internalValue) => {
      if (!internalValue) return initialFile;
      if (Array.isArray(internalValue))
        return allow_batch ? internalValue.map(formatPath) : formatPath(internalValue[0]);
      return formatPath(internalValue);
    }, "transform");
    Object.defineProperty(
      fileComboWidget,
      "value",
      useValueTransform(transform, initialFile)
    );
    const { openFileSelection } = useNodeImageUpload(node2, {
      // @ts-expect-error InputSpec is not typed correctly
      allow_batch,
      fileFilter,
      accept,
      onUploadComplete: /* @__PURE__ */ __name((output) => {
        output.forEach((path) => addToComboValues(fileComboWidget, path));
        fileComboWidget.value = output;
        fileComboWidget.callback?.(output);
      }, "onUploadComplete")
    });
    const uploadWidget = node2.addWidget(
      "button",
      inputName,
      "image",
      () => openFileSelection(),
      {
        serialize: false
      }
    );
    uploadWidget.label = t("g.choose_file_to_upload");
    fileComboWidget.callback = function() {
      nodeOutputStore.setNodeOutputs(node2, fileComboWidget.value, {
        isAnimated
      });
      node2.graph?.setDirtyCanvas(true);
    };
    requestAnimationFrame(() => {
      nodeOutputStore.setNodeOutputs(node2, fileComboWidget.value, {
        isAnimated
      });
      showPreview({ block: false });
    });
    return { widget: uploadWidget };
  }, "widgetConstructor");
  return widgetConstructor;
}, "useImageUploadWidget");
function onValueChange(v2) {
  const step = this.options.step2 || 1;
  if (step === 1) {
    this.value = Math.round(v2);
  } else {
    const min = this.options.min ?? 0;
    const offset = min % step;
    this.value = Math.round((v2 - offset) / step) * step + offset;
  }
}
__name(onValueChange, "onValueChange");
const _for_testing = {
  onValueChange
};
const useIntWidget = /* @__PURE__ */ __name(() => {
  const widgetConstructor = /* @__PURE__ */ __name((node2, inputSpec) => {
    if (!isIntInputSpec(inputSpec)) {
      throw new Error(`Invalid input data: ${inputSpec}`);
    }
    const settingStore = useSettingStore();
    const sliderEnabled = !settingStore.get("Comfy.DisableSliders");
    const display_type = inputSpec.display;
    const widgetType = sliderEnabled && display_type == "slider" ? "slider" : display_type == "knob" ? "knob" : "number";
    const step = inputSpec.step ?? 1;
    const defaultValue = inputSpec.default ?? 0;
    const widget = node2.addWidget(
      widgetType,
      inputSpec.name,
      defaultValue,
      onValueChange,
      {
        min: inputSpec.min ?? 0,
        max: inputSpec.max ?? 2048,
        /** @deprecated Use step2 instead. The 10x value is a legacy implementation. */
        step: step * 10,
        step2: step,
        precision: 0
      }
    );
    const controlAfterGenerate = inputSpec.control_after_generate ?? /**
    * Compatibility with legacy node convention. Int input with name
    * 'seed' or 'noise_seed' get automatically added a control widget.
    */
    ["seed", "noise_seed"].includes(inputSpec.name);
    if (controlAfterGenerate) {
      const seedControl = addValueControlWidget(
        node2,
        widget,
        "randomize",
        void 0,
        void 0,
        transformInputSpecV2ToV1(inputSpec)
      );
      widget.linkedWidgets = [seedControl];
    }
    return widget;
  }, "widgetConstructor");
  return widgetConstructor;
}, "useIntWidget");
function OrderedMap(content) {
  this.content = content;
}
__name(OrderedMap, "OrderedMap");
OrderedMap.prototype = {
  constructor: OrderedMap,
  find: /* @__PURE__ */ __name(function(key) {
    for (var i2 = 0; i2 < this.content.length; i2 += 2)
      if (this.content[i2] === key) return i2;
    return -1;
  }, "find"),
  // :: (string) → ?any
  // Retrieve the value stored under `key`, or return undefined when
  // no such key exists.
  get: /* @__PURE__ */ __name(function(key) {
    var found2 = this.find(key);
    return found2 == -1 ? void 0 : this.content[found2 + 1];
  }, "get"),
  // :: (string, any, ?string) → OrderedMap
  // Create a new map by replacing the value of `key` with a new
  // value, or adding a binding to the end of the map. If `newKey` is
  // given, the key of the binding will be replaced with that key.
  update: /* @__PURE__ */ __name(function(key, value, newKey) {
    var self2 = newKey && newKey != key ? this.remove(newKey) : this;
    var found2 = self2.find(key), content = self2.content.slice();
    if (found2 == -1) {
      content.push(newKey || key, value);
    } else {
      content[found2 + 1] = value;
      if (newKey) content[found2] = newKey;
    }
    return new OrderedMap(content);
  }, "update"),
  // :: (string) → OrderedMap
  // Return a map with the given key removed, if it existed.
  remove: /* @__PURE__ */ __name(function(key) {
    var found2 = this.find(key);
    if (found2 == -1) return this;
    var content = this.content.slice();
    content.splice(found2, 2);
    return new OrderedMap(content);
  }, "remove"),
  // :: (string, any) → OrderedMap
  // Add a new key to the start of the map.
  addToStart: /* @__PURE__ */ __name(function(key, value) {
    return new OrderedMap([key, value].concat(this.remove(key).content));
  }, "addToStart"),
  // :: (string, any) → OrderedMap
  // Add a new key to the end of the map.
  addToEnd: /* @__PURE__ */ __name(function(key, value) {
    var content = this.remove(key).content.slice();
    content.push(key, value);
    return new OrderedMap(content);
  }, "addToEnd"),
  // :: (string, string, any) → OrderedMap
  // Add a key after the given key. If `place` is not found, the new
  // key is added to the end.
  addBefore: /* @__PURE__ */ __name(function(place, key, value) {
    var without = this.remove(key), content = without.content.slice();
    var found2 = without.find(place);
    content.splice(found2 == -1 ? content.length : found2, 0, key, value);
    return new OrderedMap(content);
  }, "addBefore"),
  // :: ((key: string, value: any))
  // Call the given function for each key/value pair in the map, in
  // order.
  forEach: /* @__PURE__ */ __name(function(f2) {
    for (var i2 = 0; i2 < this.content.length; i2 += 2)
      f2(this.content[i2], this.content[i2 + 1]);
  }, "forEach"),
  // :: (union<Object, OrderedMap>) → OrderedMap
  // Create a new map by prepending the keys in this map that don't
  // appear in `map` before the keys in `map`.
  prepend: /* @__PURE__ */ __name(function(map3) {
    map3 = OrderedMap.from(map3);
    if (!map3.size) return this;
    return new OrderedMap(map3.content.concat(this.subtract(map3).content));
  }, "prepend"),
  // :: (union<Object, OrderedMap>) → OrderedMap
  // Create a new map by appending the keys in this map that don't
  // appear in `map` after the keys in `map`.
  append: /* @__PURE__ */ __name(function(map3) {
    map3 = OrderedMap.from(map3);
    if (!map3.size) return this;
    return new OrderedMap(this.subtract(map3).content.concat(map3.content));
  }, "append"),
  // :: (union<Object, OrderedMap>) → OrderedMap
  // Create a map containing all the keys in this map that don't
  // appear in `map`.
  subtract: /* @__PURE__ */ __name(function(map3) {
    var result = this;
    map3 = OrderedMap.from(map3);
    for (var i2 = 0; i2 < map3.content.length; i2 += 2)
      result = result.remove(map3.content[i2]);
    return result;
  }, "subtract"),
  // :: () → Object
  // Turn ordered map into a plain object.
  toObject: /* @__PURE__ */ __name(function() {
    var result = {};
    this.forEach(function(key, value) {
      result[key] = value;
    });
    return result;
  }, "toObject"),
  // :: number
  // The amount of keys in this map.
  get size() {
    return this.content.length >> 1;
  }
};
OrderedMap.from = function(value) {
  if (value instanceof OrderedMap) return value;
  var content = [];
  if (value) for (var prop2 in value) content.push(prop2, value[prop2]);
  return new OrderedMap(content);
};
function findDiffStart(a2, b2, pos) {
  for (let i2 = 0; ; i2++) {
    if (i2 == a2.childCount || i2 == b2.childCount)
      return a2.childCount == b2.childCount ? null : pos;
    let childA = a2.child(i2), childB = b2.child(i2);
    if (childA == childB) {
      pos += childA.nodeSize;
      continue;
    }
    if (!childA.sameMarkup(childB))
      return pos;
    if (childA.isText && childA.text != childB.text) {
      for (let j2 = 0; childA.text[j2] == childB.text[j2]; j2++)
        pos++;
      return pos;
    }
    if (childA.content.size || childB.content.size) {
      let inner = findDiffStart(childA.content, childB.content, pos + 1);
      if (inner != null)
        return inner;
    }
    pos += childA.nodeSize;
  }
}
__name(findDiffStart, "findDiffStart");
function findDiffEnd(a2, b2, posA, posB) {
  for (let iA = a2.childCount, iB = b2.childCount; ; ) {
    if (iA == 0 || iB == 0)
      return iA == iB ? null : { a: posA, b: posB };
    let childA = a2.child(--iA), childB = b2.child(--iB), size = childA.nodeSize;
    if (childA == childB) {
      posA -= size;
      posB -= size;
      continue;
    }
    if (!childA.sameMarkup(childB))
      return { a: posA, b: posB };
    if (childA.isText && childA.text != childB.text) {
      let same = 0, minSize = Math.min(childA.text.length, childB.text.length);
      while (same < minSize && childA.text[childA.text.length - same - 1] == childB.text[childB.text.length - same - 1]) {
        same++;
        posA--;
        posB--;
      }
      return { a: posA, b: posB };
    }
    if (childA.content.size || childB.content.size) {
      let inner = findDiffEnd(childA.content, childB.content, posA - 1, posB - 1);
      if (inner)
        return inner;
    }
    posA -= size;
    posB -= size;
  }
}
__name(findDiffEnd, "findDiffEnd");
class Fragment {
  static {
    __name(this, "Fragment");
  }
  /**
  @internal
  */
  constructor(content, size) {
    this.content = content;
    this.size = size || 0;
    if (size == null)
      for (let i2 = 0; i2 < content.length; i2++)
        this.size += content[i2].nodeSize;
  }
  /**
  Invoke a callback for all descendant nodes between the given two
  positions (relative to start of this fragment). Doesn't descend
  into a node when the callback returns `false`.
  */
  nodesBetween(from2, to, f2, nodeStart = 0, parent2) {
    for (let i2 = 0, pos = 0; pos < to; i2++) {
      let child2 = this.content[i2], end = pos + child2.nodeSize;
      if (end > from2 && f2(child2, nodeStart + pos, parent2 || null, i2) !== false && child2.content.size) {
        let start2 = pos + 1;
        child2.nodesBetween(Math.max(0, from2 - start2), Math.min(child2.content.size, to - start2), f2, nodeStart + start2);
      }
      pos = end;
    }
  }
  /**
  Call the given callback for every descendant node. `pos` will be
  relative to the start of the fragment. The callback may return
  `false` to prevent traversal of a given node's children.
  */
  descendants(f2) {
    this.nodesBetween(0, this.size, f2);
  }
  /**
  Extract the text between `from` and `to`. See the same method on
  [`Node`](https://prosemirror.net/docs/ref/#model.Node.textBetween).
  */
  textBetween(from2, to, blockSeparator, leafText) {
    let text2 = "", first2 = true;
    this.nodesBetween(from2, to, (node2, pos) => {
      let nodeText = node2.isText ? node2.text.slice(Math.max(from2, pos) - pos, to - pos) : !node2.isLeaf ? "" : leafText ? typeof leafText === "function" ? leafText(node2) : leafText : node2.type.spec.leafText ? node2.type.spec.leafText(node2) : "";
      if (node2.isBlock && (node2.isLeaf && nodeText || node2.isTextblock) && blockSeparator) {
        if (first2)
          first2 = false;
        else
          text2 += blockSeparator;
      }
      text2 += nodeText;
    }, 0);
    return text2;
  }
  /**
  Create a new fragment containing the combined content of this
  fragment and the other.
  */
  append(other) {
    if (!other.size)
      return this;
    if (!this.size)
      return other;
    let last = this.lastChild, first2 = other.firstChild, content = this.content.slice(), i2 = 0;
    if (last.isText && last.sameMarkup(first2)) {
      content[content.length - 1] = last.withText(last.text + first2.text);
      i2 = 1;
    }
    for (; i2 < other.content.length; i2++)
      content.push(other.content[i2]);
    return new Fragment(content, this.size + other.size);
  }
  /**
  Cut out the sub-fragment between the two given positions.
  */
  cut(from2, to = this.size) {
    if (from2 == 0 && to == this.size)
      return this;
    let result = [], size = 0;
    if (to > from2)
      for (let i2 = 0, pos = 0; pos < to; i2++) {
        let child2 = this.content[i2], end = pos + child2.nodeSize;
        if (end > from2) {
          if (pos < from2 || end > to) {
            if (child2.isText)
              child2 = child2.cut(Math.max(0, from2 - pos), Math.min(child2.text.length, to - pos));
            else
              child2 = child2.cut(Math.max(0, from2 - pos - 1), Math.min(child2.content.size, to - pos - 1));
          }
          result.push(child2);
          size += child2.nodeSize;
        }
        pos = end;
      }
    return new Fragment(result, size);
  }
  /**
  @internal
  */
  cutByIndex(from2, to) {
    if (from2 == to)
      return Fragment.empty;
    if (from2 == 0 && to == this.content.length)
      return this;
    return new Fragment(this.content.slice(from2, to));
  }
  /**
  Create a new fragment in which the node at the given index is
  replaced by the given node.
  */
  replaceChild(index2, node2) {
    let current = this.content[index2];
    if (current == node2)
      return this;
    let copy2 = this.content.slice();
    let size = this.size + node2.nodeSize - current.nodeSize;
    copy2[index2] = node2;
    return new Fragment(copy2, size);
  }
  /**
  Create a new fragment by prepending the given node to this
  fragment.
  */
  addToStart(node2) {
    return new Fragment([node2].concat(this.content), this.size + node2.nodeSize);
  }
  /**
  Create a new fragment by appending the given node to this
  fragment.
  */
  addToEnd(node2) {
    return new Fragment(this.content.concat(node2), this.size + node2.nodeSize);
  }
  /**
  Compare this fragment to another one.
  */
  eq(other) {
    if (this.content.length != other.content.length)
      return false;
    for (let i2 = 0; i2 < this.content.length; i2++)
      if (!this.content[i2].eq(other.content[i2]))
        return false;
    return true;
  }
  /**
  The first child of the fragment, or `null` if it is empty.
  */
  get firstChild() {
    return this.content.length ? this.content[0] : null;
  }
  /**
  The last child of the fragment, or `null` if it is empty.
  */
  get lastChild() {
    return this.content.length ? this.content[this.content.length - 1] : null;
  }
  /**
  The number of child nodes in this fragment.
  */
  get childCount() {
    return this.content.length;
  }
  /**
  Get the child node at the given index. Raise an error when the
  index is out of range.
  */
  child(index2) {
    let found2 = this.content[index2];
    if (!found2)
      throw new RangeError("Index " + index2 + " out of range for " + this);
    return found2;
  }
  /**
  Get the child node at the given index, if it exists.
  */
  maybeChild(index2) {
    return this.content[index2] || null;
  }
  /**
  Call `f` for every child node, passing the node, its offset
  into this parent node, and its index.
  */
  forEach(f2) {
    for (let i2 = 0, p2 = 0; i2 < this.content.length; i2++) {
      let child2 = this.content[i2];
      f2(child2, p2, i2);
      p2 += child2.nodeSize;
    }
  }
  /**
  Find the first position at which this fragment and another
  fragment differ, or `null` if they are the same.
  */
  findDiffStart(other, pos = 0) {
    return findDiffStart(this, other, pos);
  }
  /**
  Find the first position, searching from the end, at which this
  fragment and the given fragment differ, or `null` if they are
  the same. Since this position will not be the same in both
  nodes, an object with two separate positions is returned.
  */
  findDiffEnd(other, pos = this.size, otherPos = other.size) {
    return findDiffEnd(this, other, pos, otherPos);
  }
  /**
  Find the index and inner offset corresponding to a given relative
  position in this fragment. The result object will be reused
  (overwritten) the next time the function is called. @internal
  */
  findIndex(pos, round = -1) {
    if (pos == 0)
      return retIndex(0, pos);
    if (pos == this.size)
      return retIndex(this.content.length, pos);
    if (pos > this.size || pos < 0)
      throw new RangeError(`Position ${pos} outside of fragment (${this})`);
    for (let i2 = 0, curPos = 0; ; i2++) {
      let cur = this.child(i2), end = curPos + cur.nodeSize;
      if (end >= pos) {
        if (end == pos || round > 0)
          return retIndex(i2 + 1, end);
        return retIndex(i2, curPos);
      }
      curPos = end;
    }
  }
  /**
  Return a debugging string that describes this fragment.
  */
  toString() {
    return "<" + this.toStringInner() + ">";
  }
  /**
  @internal
  */
  toStringInner() {
    return this.content.join(", ");
  }
  /**
  Create a JSON-serializeable representation of this fragment.
  */
  toJSON() {
    return this.content.length ? this.content.map((n2) => n2.toJSON()) : null;
  }
  /**
  Deserialize a fragment from its JSON representation.
  */
  static fromJSON(schema2, value) {
    if (!value)
      return Fragment.empty;
    if (!Array.isArray(value))
      throw new RangeError("Invalid input for Fragment.fromJSON");
    return new Fragment(value.map(schema2.nodeFromJSON));
  }
  /**
  Build a fragment from an array of nodes. Ensures that adjacent
  text nodes with the same marks are joined together.
  */
  static fromArray(array) {
    if (!array.length)
      return Fragment.empty;
    let joined, size = 0;
    for (let i2 = 0; i2 < array.length; i2++) {
      let node2 = array[i2];
      size += node2.nodeSize;
      if (i2 && node2.isText && array[i2 - 1].sameMarkup(node2)) {
        if (!joined)
          joined = array.slice(0, i2);
        joined[joined.length - 1] = node2.withText(joined[joined.length - 1].text + node2.text);
      } else if (joined) {
        joined.push(node2);
      }
    }
    return new Fragment(joined || array, size);
  }
  /**
  Create a fragment from something that can be interpreted as a
  set of nodes. For `null`, it returns the empty fragment. For a
  fragment, the fragment itself. For a node or array of nodes, a
  fragment containing those nodes.
  */
  static from(nodes) {
    if (!nodes)
      return Fragment.empty;
    if (nodes instanceof Fragment)
      return nodes;
    if (Array.isArray(nodes))
      return this.fromArray(nodes);
    if (nodes.attrs)
      return new Fragment([nodes], nodes.nodeSize);
    throw new RangeError("Can not convert " + nodes + " to a Fragment" + (nodes.nodesBetween ? " (looks like multiple versions of prosemirror-model were loaded)" : ""));
  }
}
Fragment.empty = new Fragment([], 0);
const found = { index: 0, offset: 0 };
function retIndex(index2, offset) {
  found.index = index2;
  found.offset = offset;
  return found;
}
__name(retIndex, "retIndex");
function compareDeep(a2, b2) {
  if (a2 === b2)
    return true;
  if (!(a2 && typeof a2 == "object") || !(b2 && typeof b2 == "object"))
    return false;
  let array = Array.isArray(a2);
  if (Array.isArray(b2) != array)
    return false;
  if (array) {
    if (a2.length != b2.length)
      return false;
    for (let i2 = 0; i2 < a2.length; i2++)
      if (!compareDeep(a2[i2], b2[i2]))
        return false;
  } else {
    for (let p2 in a2)
      if (!(p2 in b2) || !compareDeep(a2[p2], b2[p2]))
        return false;
    for (let p2 in b2)
      if (!(p2 in a2))
        return false;
  }
  return true;
}
__name(compareDeep, "compareDeep");
let Mark$1 = class Mark2 {
  static {
    __name(this, "Mark");
  }
  /**
  @internal
  */
  constructor(type, attrs2) {
    this.type = type;
    this.attrs = attrs2;
  }
  /**
  Given a set of marks, create a new set which contains this one as
  well, in the right position. If this mark is already in the set,
  the set itself is returned. If any marks that are set to be
  [exclusive](https://prosemirror.net/docs/ref/#model.MarkSpec.excludes) with this mark are present,
  those are replaced by this one.
  */
  addToSet(set3) {
    let copy2, placed = false;
    for (let i2 = 0; i2 < set3.length; i2++) {
      let other = set3[i2];
      if (this.eq(other))
        return set3;
      if (this.type.excludes(other.type)) {
        if (!copy2)
          copy2 = set3.slice(0, i2);
      } else if (other.type.excludes(this.type)) {
        return set3;
      } else {
        if (!placed && other.type.rank > this.type.rank) {
          if (!copy2)
            copy2 = set3.slice(0, i2);
          copy2.push(this);
          placed = true;
        }
        if (copy2)
          copy2.push(other);
      }
    }
    if (!copy2)
      copy2 = set3.slice();
    if (!placed)
      copy2.push(this);
    return copy2;
  }
  /**
  Remove this mark from the given set, returning a new set. If this
  mark is not in the set, the set itself is returned.
  */
  removeFromSet(set3) {
    for (let i2 = 0; i2 < set3.length; i2++)
      if (this.eq(set3[i2]))
        return set3.slice(0, i2).concat(set3.slice(i2 + 1));
    return set3;
  }
  /**
  Test whether this mark is in the given set of marks.
  */
  isInSet(set3) {
    for (let i2 = 0; i2 < set3.length; i2++)
      if (this.eq(set3[i2]))
        return true;
    return false;
  }
  /**
  Test whether this mark has the same type and attributes as
  another mark.
  */
  eq(other) {
    return this == other || this.type == other.type && compareDeep(this.attrs, other.attrs);
  }
  /**
  Convert this mark to a JSON-serializeable representation.
  */
  toJSON() {
    let obj = { type: this.type.name };
    for (let _2 in this.attrs) {
      obj.attrs = this.attrs;
      break;
    }
    return obj;
  }
  /**
  Deserialize a mark from JSON.
  */
  static fromJSON(schema2, json) {
    if (!json)
      throw new RangeError("Invalid input for Mark.fromJSON");
    let type = schema2.marks[json.type];
    if (!type)
      throw new RangeError(`There is no mark type ${json.type} in this schema`);
    let mark = type.create(json.attrs);
    type.checkAttrs(mark.attrs);
    return mark;
  }
  /**
  Test whether two sets of marks are identical.
  */
  static sameSet(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].eq(b2[i2]))
        return false;
    return true;
  }
  /**
  Create a properly sorted mark set from null, a single mark, or an
  unsorted array of marks.
  */
  static setFrom(marks) {
    if (!marks || Array.isArray(marks) && marks.length == 0)
      return Mark2.none;
    if (marks instanceof Mark2)
      return [marks];
    let copy2 = marks.slice();
    copy2.sort((a2, b2) => a2.type.rank - b2.type.rank);
    return copy2;
  }
};
Mark$1.none = [];
class ReplaceError extends Error {
  static {
    __name(this, "ReplaceError");
  }
}
class Slice {
  static {
    __name(this, "Slice");
  }
  /**
  Create a slice. When specifying a non-zero open depth, you must
  make sure that there are nodes of at least that depth at the
  appropriate side of the fragment—i.e. if the fragment is an
  empty paragraph node, `openStart` and `openEnd` can't be greater
  than 1.
  
  It is not necessary for the content of open nodes to conform to
  the schema's content constraints, though it should be a valid
  start/end/middle for such a node, depending on which sides are
  open.
  */
  constructor(content, openStart, openEnd) {
    this.content = content;
    this.openStart = openStart;
    this.openEnd = openEnd;
  }
  /**
  The size this slice would add when inserted into a document.
  */
  get size() {
    return this.content.size - this.openStart - this.openEnd;
  }
  /**
  @internal
  */
  insertAt(pos, fragment) {
    let content = insertInto(this.content, pos + this.openStart, fragment);
    return content && new Slice(content, this.openStart, this.openEnd);
  }
  /**
  @internal
  */
  removeBetween(from2, to) {
    return new Slice(removeRange(this.content, from2 + this.openStart, to + this.openStart), this.openStart, this.openEnd);
  }
  /**
  Tests whether this slice is equal to another slice.
  */
  eq(other) {
    return this.content.eq(other.content) && this.openStart == other.openStart && this.openEnd == other.openEnd;
  }
  /**
  @internal
  */
  toString() {
    return this.content + "(" + this.openStart + "," + this.openEnd + ")";
  }
  /**
  Convert a slice to a JSON-serializable representation.
  */
  toJSON() {
    if (!this.content.size)
      return null;
    let json = { content: this.content.toJSON() };
    if (this.openStart > 0)
      json.openStart = this.openStart;
    if (this.openEnd > 0)
      json.openEnd = this.openEnd;
    return json;
  }
  /**
  Deserialize a slice from its JSON representation.
  */
  static fromJSON(schema2, json) {
    if (!json)
      return Slice.empty;
    let openStart = json.openStart || 0, openEnd = json.openEnd || 0;
    if (typeof openStart != "number" || typeof openEnd != "number")
      throw new RangeError("Invalid input for Slice.fromJSON");
    return new Slice(Fragment.fromJSON(schema2, json.content), openStart, openEnd);
  }
  /**
  Create a slice from a fragment by taking the maximum possible
  open value on both side of the fragment.
  */
  static maxOpen(fragment, openIsolating = true) {
    let openStart = 0, openEnd = 0;
    for (let n2 = fragment.firstChild; n2 && !n2.isLeaf && (openIsolating || !n2.type.spec.isolating); n2 = n2.firstChild)
      openStart++;
    for (let n2 = fragment.lastChild; n2 && !n2.isLeaf && (openIsolating || !n2.type.spec.isolating); n2 = n2.lastChild)
      openEnd++;
    return new Slice(fragment, openStart, openEnd);
  }
}
Slice.empty = new Slice(Fragment.empty, 0, 0);
function removeRange(content, from2, to) {
  let { index: index2, offset } = content.findIndex(from2), child2 = content.maybeChild(index2);
  let { index: indexTo, offset: offsetTo } = content.findIndex(to);
  if (offset == from2 || child2.isText) {
    if (offsetTo != to && !content.child(indexTo).isText)
      throw new RangeError("Removing non-flat range");
    return content.cut(0, from2).append(content.cut(to));
  }
  if (index2 != indexTo)
    throw new RangeError("Removing non-flat range");
  return content.replaceChild(index2, child2.copy(removeRange(child2.content, from2 - offset - 1, to - offset - 1)));
}
__name(removeRange, "removeRange");
function insertInto(content, dist3, insert, parent2) {
  let { index: index2, offset } = content.findIndex(dist3), child2 = content.maybeChild(index2);
  if (offset == dist3 || child2.isText) {
    if (parent2 && !parent2.canReplace(index2, index2, insert))
      return null;
    return content.cut(0, dist3).append(insert).append(content.cut(dist3));
  }
  let inner = insertInto(child2.content, dist3 - offset - 1, insert);
  return inner && content.replaceChild(index2, child2.copy(inner));
}
__name(insertInto, "insertInto");
function replace$1($from, $to, slice2) {
  if (slice2.openStart > $from.depth)
    throw new ReplaceError("Inserted content deeper than insertion position");
  if ($from.depth - slice2.openStart != $to.depth - slice2.openEnd)
    throw new ReplaceError("Inconsistent open depths");
  return replaceOuter($from, $to, slice2, 0);
}
__name(replace$1, "replace$1");
function replaceOuter($from, $to, slice2, depth) {
  let index2 = $from.index(depth), node2 = $from.node(depth);
  if (index2 == $to.index(depth) && depth < $from.depth - slice2.openStart) {
    let inner = replaceOuter($from, $to, slice2, depth + 1);
    return node2.copy(node2.content.replaceChild(index2, inner));
  } else if (!slice2.content.size) {
    return close(node2, replaceTwoWay($from, $to, depth));
  } else if (!slice2.openStart && !slice2.openEnd && $from.depth == depth && $to.depth == depth) {
    let parent2 = $from.parent, content = parent2.content;
    return close(parent2, content.cut(0, $from.parentOffset).append(slice2.content).append(content.cut($to.parentOffset)));
  } else {
    let { start: start2, end } = prepareSliceForReplace(slice2, $from);
    return close(node2, replaceThreeWay($from, start2, end, $to, depth));
  }
}
__name(replaceOuter, "replaceOuter");
function checkJoin(main, sub) {
  if (!sub.type.compatibleContent(main.type))
    throw new ReplaceError("Cannot join " + sub.type.name + " onto " + main.type.name);
}
__name(checkJoin, "checkJoin");
function joinable$1($before, $after, depth) {
  let node2 = $before.node(depth);
  checkJoin(node2, $after.node(depth));
  return node2;
}
__name(joinable$1, "joinable$1");
function addNode(child2, target) {
  let last = target.length - 1;
  if (last >= 0 && child2.isText && child2.sameMarkup(target[last]))
    target[last] = child2.withText(target[last].text + child2.text);
  else
    target.push(child2);
}
__name(addNode, "addNode");
function addRange($start, $end, depth, target) {
  let node2 = ($end || $start).node(depth);
  let startIndex = 0, endIndex = $end ? $end.index(depth) : node2.childCount;
  if ($start) {
    startIndex = $start.index(depth);
    if ($start.depth > depth) {
      startIndex++;
    } else if ($start.textOffset) {
      addNode($start.nodeAfter, target);
      startIndex++;
    }
  }
  for (let i2 = startIndex; i2 < endIndex; i2++)
    addNode(node2.child(i2), target);
  if ($end && $end.depth == depth && $end.textOffset)
    addNode($end.nodeBefore, target);
}
__name(addRange, "addRange");
function close(node2, content) {
  node2.type.checkContent(content);
  return node2.copy(content);
}
__name(close, "close");
function replaceThreeWay($from, $start, $end, $to, depth) {
  let openStart = $from.depth > depth && joinable$1($from, $start, depth + 1);
  let openEnd = $to.depth > depth && joinable$1($end, $to, depth + 1);
  let content = [];
  addRange(null, $from, depth, content);
  if (openStart && openEnd && $start.index(depth) == $end.index(depth)) {
    checkJoin(openStart, openEnd);
    addNode(close(openStart, replaceThreeWay($from, $start, $end, $to, depth + 1)), content);
  } else {
    if (openStart)
      addNode(close(openStart, replaceTwoWay($from, $start, depth + 1)), content);
    addRange($start, $end, depth, content);
    if (openEnd)
      addNode(close(openEnd, replaceTwoWay($end, $to, depth + 1)), content);
  }
  addRange($to, null, depth, content);
  return new Fragment(content);
}
__name(replaceThreeWay, "replaceThreeWay");
function replaceTwoWay($from, $to, depth) {
  let content = [];
  addRange(null, $from, depth, content);
  if ($from.depth > depth) {
    let type = joinable$1($from, $to, depth + 1);
    addNode(close(type, replaceTwoWay($from, $to, depth + 1)), content);
  }
  addRange($to, null, depth, content);
  return new Fragment(content);
}
__name(replaceTwoWay, "replaceTwoWay");
function prepareSliceForReplace(slice2, $along) {
  let extra = $along.depth - slice2.openStart, parent2 = $along.node(extra);
  let node2 = parent2.copy(slice2.content);
  for (let i2 = extra - 1; i2 >= 0; i2--)
    node2 = $along.node(i2).copy(Fragment.from(node2));
  return {
    start: node2.resolveNoCache(slice2.openStart + extra),
    end: node2.resolveNoCache(node2.content.size - slice2.openEnd - extra)
  };
}
__name(prepareSliceForReplace, "prepareSliceForReplace");
class ResolvedPos {
  static {
    __name(this, "ResolvedPos");
  }
  /**
  @internal
  */
  constructor(pos, path, parentOffset) {
    this.pos = pos;
    this.path = path;
    this.parentOffset = parentOffset;
    this.depth = path.length / 3 - 1;
  }
  /**
  @internal
  */
  resolveDepth(val) {
    if (val == null)
      return this.depth;
    if (val < 0)
      return this.depth + val;
    return val;
  }
  /**
  The parent node that the position points into. Note that even if
  a position points into a text node, that node is not considered
  the parent—text nodes are ‘flat’ in this model, and have no content.
  */
  get parent() {
    return this.node(this.depth);
  }
  /**
  The root node in which the position was resolved.
  */
  get doc() {
    return this.node(0);
  }
  /**
  The ancestor node at the given level. `p.node(p.depth)` is the
  same as `p.parent`.
  */
  node(depth) {
    return this.path[this.resolveDepth(depth) * 3];
  }
  /**
  The index into the ancestor at the given level. If this points
  at the 3rd node in the 2nd paragraph on the top level, for
  example, `p.index(0)` is 1 and `p.index(1)` is 2.
  */
  index(depth) {
    return this.path[this.resolveDepth(depth) * 3 + 1];
  }
  /**
  The index pointing after this position into the ancestor at the
  given level.
  */
  indexAfter(depth) {
    depth = this.resolveDepth(depth);
    return this.index(depth) + (depth == this.depth && !this.textOffset ? 0 : 1);
  }
  /**
  The (absolute) position at the start of the node at the given
  level.
  */
  start(depth) {
    depth = this.resolveDepth(depth);
    return depth == 0 ? 0 : this.path[depth * 3 - 1] + 1;
  }
  /**
  The (absolute) position at the end of the node at the given
  level.
  */
  end(depth) {
    depth = this.resolveDepth(depth);
    return this.start(depth) + this.node(depth).content.size;
  }
  /**
  The (absolute) position directly before the wrapping node at the
  given level, or, when `depth` is `this.depth + 1`, the original
  position.
  */
  before(depth) {
    depth = this.resolveDepth(depth);
    if (!depth)
      throw new RangeError("There is no position before the top-level node");
    return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1];
  }
  /**
  The (absolute) position directly after the wrapping node at the
  given level, or the original position when `depth` is `this.depth + 1`.
  */
  after(depth) {
    depth = this.resolveDepth(depth);
    if (!depth)
      throw new RangeError("There is no position after the top-level node");
    return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1] + this.path[depth * 3].nodeSize;
  }
  /**
  When this position points into a text node, this returns the
  distance between the position and the start of the text node.
  Will be zero for positions that point between nodes.
  */
  get textOffset() {
    return this.pos - this.path[this.path.length - 1];
  }
  /**
  Get the node directly after the position, if any. If the position
  points into a text node, only the part of that node after the
  position is returned.
  */
  get nodeAfter() {
    let parent2 = this.parent, index2 = this.index(this.depth);
    if (index2 == parent2.childCount)
      return null;
    let dOff = this.pos - this.path[this.path.length - 1], child2 = parent2.child(index2);
    return dOff ? parent2.child(index2).cut(dOff) : child2;
  }
  /**
  Get the node directly before the position, if any. If the
  position points into a text node, only the part of that node
  before the position is returned.
  */
  get nodeBefore() {
    let index2 = this.index(this.depth);
    let dOff = this.pos - this.path[this.path.length - 1];
    if (dOff)
      return this.parent.child(index2).cut(0, dOff);
    return index2 == 0 ? null : this.parent.child(index2 - 1);
  }
  /**
  Get the position at the given index in the parent node at the
  given depth (which defaults to `this.depth`).
  */
  posAtIndex(index2, depth) {
    depth = this.resolveDepth(depth);
    let node2 = this.path[depth * 3], pos = depth == 0 ? 0 : this.path[depth * 3 - 1] + 1;
    for (let i2 = 0; i2 < index2; i2++)
      pos += node2.child(i2).nodeSize;
    return pos;
  }
  /**
  Get the marks at this position, factoring in the surrounding
  marks' [`inclusive`](https://prosemirror.net/docs/ref/#model.MarkSpec.inclusive) property. If the
  position is at the start of a non-empty node, the marks of the
  node after it (if any) are returned.
  */
  marks() {
    let parent2 = this.parent, index2 = this.index();
    if (parent2.content.size == 0)
      return Mark$1.none;
    if (this.textOffset)
      return parent2.child(index2).marks;
    let main = parent2.maybeChild(index2 - 1), other = parent2.maybeChild(index2);
    if (!main) {
      let tmp = main;
      main = other;
      other = tmp;
    }
    let marks = main.marks;
    for (var i2 = 0; i2 < marks.length; i2++)
      if (marks[i2].type.spec.inclusive === false && (!other || !marks[i2].isInSet(other.marks)))
        marks = marks[i2--].removeFromSet(marks);
    return marks;
  }
  /**
  Get the marks after the current position, if any, except those
  that are non-inclusive and not present at position `$end`. This
  is mostly useful for getting the set of marks to preserve after a
  deletion. Will return `null` if this position is at the end of
  its parent node or its parent node isn't a textblock (in which
  case no marks should be preserved).
  */
  marksAcross($end) {
    let after = this.parent.maybeChild(this.index());
    if (!after || !after.isInline)
      return null;
    let marks = after.marks, next = $end.parent.maybeChild($end.index());
    for (var i2 = 0; i2 < marks.length; i2++)
      if (marks[i2].type.spec.inclusive === false && (!next || !marks[i2].isInSet(next.marks)))
        marks = marks[i2--].removeFromSet(marks);
    return marks;
  }
  /**
  The depth up to which this position and the given (non-resolved)
  position share the same parent nodes.
  */
  sharedDepth(pos) {
    for (let depth = this.depth; depth > 0; depth--)
      if (this.start(depth) <= pos && this.end(depth) >= pos)
        return depth;
    return 0;
  }
  /**
  Returns a range based on the place where this position and the
  given position diverge around block content. If both point into
  the same textblock, for example, a range around that textblock
  will be returned. If they point into different blocks, the range
  around those blocks in their shared ancestor is returned. You can
  pass in an optional predicate that will be called with a parent
  node to see if a range into that parent is acceptable.
  */
  blockRange(other = this, pred) {
    if (other.pos < this.pos)
      return other.blockRange(this);
    for (let d2 = this.depth - (this.parent.inlineContent || this.pos == other.pos ? 1 : 0); d2 >= 0; d2--)
      if (other.pos <= this.end(d2) && (!pred || pred(this.node(d2))))
        return new NodeRange(this, other, d2);
    return null;
  }
  /**
  Query whether the given position shares the same parent node.
  */
  sameParent(other) {
    return this.pos - this.parentOffset == other.pos - other.parentOffset;
  }
  /**
  Return the greater of this and the given position.
  */
  max(other) {
    return other.pos > this.pos ? other : this;
  }
  /**
  Return the smaller of this and the given position.
  */
  min(other) {
    return other.pos < this.pos ? other : this;
  }
  /**
  @internal
  */
  toString() {
    let str = "";
    for (let i2 = 1; i2 <= this.depth; i2++)
      str += (str ? "/" : "") + this.node(i2).type.name + "_" + this.index(i2 - 1);
    return str + ":" + this.parentOffset;
  }
  /**
  @internal
  */
  static resolve(doc2, pos) {
    if (!(pos >= 0 && pos <= doc2.content.size))
      throw new RangeError("Position " + pos + " out of range");
    let path = [];
    let start2 = 0, parentOffset = pos;
    for (let node2 = doc2; ; ) {
      let { index: index2, offset } = node2.content.findIndex(parentOffset);
      let rem = parentOffset - offset;
      path.push(node2, index2, start2 + offset);
      if (!rem)
        break;
      node2 = node2.child(index2);
      if (node2.isText)
        break;
      parentOffset = rem - 1;
      start2 += offset + 1;
    }
    return new ResolvedPos(pos, path, parentOffset);
  }
  /**
  @internal
  */
  static resolveCached(doc2, pos) {
    let cache = resolveCache.get(doc2);
    if (cache) {
      for (let i2 = 0; i2 < cache.elts.length; i2++) {
        let elt = cache.elts[i2];
        if (elt.pos == pos)
          return elt;
      }
    } else {
      resolveCache.set(doc2, cache = new ResolveCache());
    }
    let result = cache.elts[cache.i] = ResolvedPos.resolve(doc2, pos);
    cache.i = (cache.i + 1) % resolveCacheSize;
    return result;
  }
}
class ResolveCache {
  static {
    __name(this, "ResolveCache");
  }
  constructor() {
    this.elts = [];
    this.i = 0;
  }
}
const resolveCacheSize = 12, resolveCache = /* @__PURE__ */ new WeakMap();
class NodeRange {
  static {
    __name(this, "NodeRange");
  }
  /**
  Construct a node range. `$from` and `$to` should point into the
  same node until at least the given `depth`, since a node range
  denotes an adjacent set of nodes in a single parent node.
  */
  constructor($from, $to, depth) {
    this.$from = $from;
    this.$to = $to;
    this.depth = depth;
  }
  /**
  The position at the start of the range.
  */
  get start() {
    return this.$from.before(this.depth + 1);
  }
  /**
  The position at the end of the range.
  */
  get end() {
    return this.$to.after(this.depth + 1);
  }
  /**
  The parent node that the range points into.
  */
  get parent() {
    return this.$from.node(this.depth);
  }
  /**
  The start index of the range in the parent node.
  */
  get startIndex() {
    return this.$from.index(this.depth);
  }
  /**
  The end index of the range in the parent node.
  */
  get endIndex() {
    return this.$to.indexAfter(this.depth);
  }
}
const emptyAttrs = /* @__PURE__ */ Object.create(null);
let Node$2 = class Node2 {
  static {
    __name(this, "Node");
  }
  /**
  @internal
  */
  constructor(type, attrs2, content, marks = Mark$1.none) {
    this.type = type;
    this.attrs = attrs2;
    this.marks = marks;
    this.content = content || Fragment.empty;
  }
  /**
  The array of this node's child nodes.
  */
  get children() {
    return this.content.content;
  }
  /**
  The size of this node, as defined by the integer-based [indexing
  scheme](/docs/guide/#doc.indexing). For text nodes, this is the
  amount of characters. For other leaf nodes, it is one. For
  non-leaf nodes, it is the size of the content plus two (the
  start and end token).
  */
  get nodeSize() {
    return this.isLeaf ? 1 : 2 + this.content.size;
  }
  /**
  The number of children that the node has.
  */
  get childCount() {
    return this.content.childCount;
  }
  /**
  Get the child node at the given index. Raises an error when the
  index is out of range.
  */
  child(index2) {
    return this.content.child(index2);
  }
  /**
  Get the child node at the given index, if it exists.
  */
  maybeChild(index2) {
    return this.content.maybeChild(index2);
  }
  /**
  Call `f` for every child node, passing the node, its offset
  into this parent node, and its index.
  */
  forEach(f2) {
    this.content.forEach(f2);
  }
  /**
  Invoke a callback for all descendant nodes recursively between
  the given two positions that are relative to start of this
  node's content. The callback is invoked with the node, its
  position relative to the original node (method receiver),
  its parent node, and its child index. When the callback returns
  false for a given node, that node's children will not be
  recursed over. The last parameter can be used to specify a
  starting position to count from.
  */
  nodesBetween(from2, to, f2, startPos = 0) {
    this.content.nodesBetween(from2, to, f2, startPos, this);
  }
  /**
  Call the given callback for every descendant node. Doesn't
  descend into a node when the callback returns `false`.
  */
  descendants(f2) {
    this.nodesBetween(0, this.content.size, f2);
  }
  /**
  Concatenates all the text nodes found in this fragment and its
  children.
  */
  get textContent() {
    return this.isLeaf && this.type.spec.leafText ? this.type.spec.leafText(this) : this.textBetween(0, this.content.size, "");
  }
  /**
  Get all text between positions `from` and `to`. When
  `blockSeparator` is given, it will be inserted to separate text
  from different block nodes. If `leafText` is given, it'll be
  inserted for every non-text leaf node encountered, otherwise
  [`leafText`](https://prosemirror.net/docs/ref/#model.NodeSpec^leafText) will be used.
  */
  textBetween(from2, to, blockSeparator, leafText) {
    return this.content.textBetween(from2, to, blockSeparator, leafText);
  }
  /**
  Returns this node's first child, or `null` if there are no
  children.
  */
  get firstChild() {
    return this.content.firstChild;
  }
  /**
  Returns this node's last child, or `null` if there are no
  children.
  */
  get lastChild() {
    return this.content.lastChild;
  }
  /**
  Test whether two nodes represent the same piece of document.
  */
  eq(other) {
    return this == other || this.sameMarkup(other) && this.content.eq(other.content);
  }
  /**
  Compare the markup (type, attributes, and marks) of this node to
  those of another. Returns `true` if both have the same markup.
  */
  sameMarkup(other) {
    return this.hasMarkup(other.type, other.attrs, other.marks);
  }
  /**
  Check whether this node's markup correspond to the given type,
  attributes, and marks.
  */
  hasMarkup(type, attrs2, marks) {
    return this.type == type && compareDeep(this.attrs, attrs2 || type.defaultAttrs || emptyAttrs) && Mark$1.sameSet(this.marks, marks || Mark$1.none);
  }
  /**
  Create a new node with the same markup as this node, containing
  the given content (or empty, if no content is given).
  */
  copy(content = null) {
    if (content == this.content)
      return this;
    return new Node2(this.type, this.attrs, content, this.marks);
  }
  /**
  Create a copy of this node, with the given set of marks instead
  of the node's own marks.
  */
  mark(marks) {
    return marks == this.marks ? this : new Node2(this.type, this.attrs, this.content, marks);
  }
  /**
  Create a copy of this node with only the content between the
  given positions. If `to` is not given, it defaults to the end of
  the node.
  */
  cut(from2, to = this.content.size) {
    if (from2 == 0 && to == this.content.size)
      return this;
    return this.copy(this.content.cut(from2, to));
  }
  /**
  Cut out the part of the document between the given positions, and
  return it as a `Slice` object.
  */
  slice(from2, to = this.content.size, includeParents = false) {
    if (from2 == to)
      return Slice.empty;
    let $from = this.resolve(from2), $to = this.resolve(to);
    let depth = includeParents ? 0 : $from.sharedDepth(to);
    let start2 = $from.start(depth), node2 = $from.node(depth);
    let content = node2.content.cut($from.pos - start2, $to.pos - start2);
    return new Slice(content, $from.depth - depth, $to.depth - depth);
  }
  /**
  Replace the part of the document between the given positions with
  the given slice. The slice must 'fit', meaning its open sides
  must be able to connect to the surrounding content, and its
  content nodes must be valid children for the node they are placed
  into. If any of this is violated, an error of type
  [`ReplaceError`](https://prosemirror.net/docs/ref/#model.ReplaceError) is thrown.
  */
  replace(from2, to, slice2) {
    return replace$1(this.resolve(from2), this.resolve(to), slice2);
  }
  /**
  Find the node directly after the given position.
  */
  nodeAt(pos) {
    for (let node2 = this; ; ) {
      let { index: index2, offset } = node2.content.findIndex(pos);
      node2 = node2.maybeChild(index2);
      if (!node2)
        return null;
      if (offset == pos || node2.isText)
        return node2;
      pos -= offset + 1;
    }
  }
  /**
  Find the (direct) child node after the given offset, if any,
  and return it along with its index and offset relative to this
  node.
  */
  childAfter(pos) {
    let { index: index2, offset } = this.content.findIndex(pos);
    return { node: this.content.maybeChild(index2), index: index2, offset };
  }
  /**
  Find the (direct) child node before the given offset, if any,
  and return it along with its index and offset relative to this
  node.
  */
  childBefore(pos) {
    if (pos == 0)
      return { node: null, index: 0, offset: 0 };
    let { index: index2, offset } = this.content.findIndex(pos);
    if (offset < pos)
      return { node: this.content.child(index2), index: index2, offset };
    let node2 = this.content.child(index2 - 1);
    return { node: node2, index: index2 - 1, offset: offset - node2.nodeSize };
  }
  /**
  Resolve the given position in the document, returning an
  [object](https://prosemirror.net/docs/ref/#model.ResolvedPos) with information about its context.
  */
  resolve(pos) {
    return ResolvedPos.resolveCached(this, pos);
  }
  /**
  @internal
  */
  resolveNoCache(pos) {
    return ResolvedPos.resolve(this, pos);
  }
  /**
  Test whether a given mark or mark type occurs in this document
  between the two given positions.
  */
  rangeHasMark(from2, to, type) {
    let found2 = false;
    if (to > from2)
      this.nodesBetween(from2, to, (node2) => {
        if (type.isInSet(node2.marks))
          found2 = true;
        return !found2;
      });
    return found2;
  }
  /**
  True when this is a block (non-inline node)
  */
  get isBlock() {
    return this.type.isBlock;
  }
  /**
  True when this is a textblock node, a block node with inline
  content.
  */
  get isTextblock() {
    return this.type.isTextblock;
  }
  /**
  True when this node allows inline content.
  */
  get inlineContent() {
    return this.type.inlineContent;
  }
  /**
  True when this is an inline node (a text node or a node that can
  appear among text).
  */
  get isInline() {
    return this.type.isInline;
  }
  /**
  True when this is a text node.
  */
  get isText() {
    return this.type.isText;
  }
  /**
  True when this is a leaf node.
  */
  get isLeaf() {
    return this.type.isLeaf;
  }
  /**
  True when this is an atom, i.e. when it does not have directly
  editable content. This is usually the same as `isLeaf`, but can
  be configured with the [`atom` property](https://prosemirror.net/docs/ref/#model.NodeSpec.atom)
  on a node's spec (typically used when the node is displayed as
  an uneditable [node view](https://prosemirror.net/docs/ref/#view.NodeView)).
  */
  get isAtom() {
    return this.type.isAtom;
  }
  /**
  Return a string representation of this node for debugging
  purposes.
  */
  toString() {
    if (this.type.spec.toDebugString)
      return this.type.spec.toDebugString(this);
    let name2 = this.type.name;
    if (this.content.size)
      name2 += "(" + this.content.toStringInner() + ")";
    return wrapMarks(this.marks, name2);
  }
  /**
  Get the content match in this node at the given index.
  */
  contentMatchAt(index2) {
    let match2 = this.type.contentMatch.matchFragment(this.content, 0, index2);
    if (!match2)
      throw new Error("Called contentMatchAt on a node with invalid content");
    return match2;
  }
  /**
  Test whether replacing the range between `from` and `to` (by
  child index) with the given replacement fragment (which defaults
  to the empty fragment) would leave the node's content valid. You
  can optionally pass `start` and `end` indices into the
  replacement fragment.
  */
  canReplace(from2, to, replacement = Fragment.empty, start2 = 0, end = replacement.childCount) {
    let one = this.contentMatchAt(from2).matchFragment(replacement, start2, end);
    let two = one && one.matchFragment(this.content, to);
    if (!two || !two.validEnd)
      return false;
    for (let i2 = start2; i2 < end; i2++)
      if (!this.type.allowsMarks(replacement.child(i2).marks))
        return false;
    return true;
  }
  /**
  Test whether replacing the range `from` to `to` (by index) with
  a node of the given type would leave the node's content valid.
  */
  canReplaceWith(from2, to, type, marks) {
    if (marks && !this.type.allowsMarks(marks))
      return false;
    let start2 = this.contentMatchAt(from2).matchType(type);
    let end = start2 && start2.matchFragment(this.content, to);
    return end ? end.validEnd : false;
  }
  /**
  Test whether the given node's content could be appended to this
  node. If that node is empty, this will only return true if there
  is at least one node type that can appear in both nodes (to avoid
  merging completely incompatible nodes).
  */
  canAppend(other) {
    if (other.content.size)
      return this.canReplace(this.childCount, this.childCount, other.content);
    else
      return this.type.compatibleContent(other.type);
  }
  /**
  Check whether this node and its descendants conform to the
  schema, and raise an exception when they do not.
  */
  check() {
    this.type.checkContent(this.content);
    this.type.checkAttrs(this.attrs);
    let copy2 = Mark$1.none;
    for (let i2 = 0; i2 < this.marks.length; i2++) {
      let mark = this.marks[i2];
      mark.type.checkAttrs(mark.attrs);
      copy2 = mark.addToSet(copy2);
    }
    if (!Mark$1.sameSet(copy2, this.marks))
      throw new RangeError(`Invalid collection of marks for node ${this.type.name}: ${this.marks.map((m2) => m2.type.name)}`);
    this.content.forEach((node2) => node2.check());
  }
  /**
  Return a JSON-serializeable representation of this node.
  */
  toJSON() {
    let obj = { type: this.type.name };
    for (let _2 in this.attrs) {
      obj.attrs = this.attrs;
      break;
    }
    if (this.content.size)
      obj.content = this.content.toJSON();
    if (this.marks.length)
      obj.marks = this.marks.map((n2) => n2.toJSON());
    return obj;
  }
  /**
  Deserialize a node from its JSON representation.
  */
  static fromJSON(schema2, json) {
    if (!json)
      throw new RangeError("Invalid input for Node.fromJSON");
    let marks = void 0;
    if (json.marks) {
      if (!Array.isArray(json.marks))
        throw new RangeError("Invalid mark data for Node.fromJSON");
      marks = json.marks.map(schema2.markFromJSON);
    }
    if (json.type == "text") {
      if (typeof json.text != "string")
        throw new RangeError("Invalid text node in JSON");
      return schema2.text(json.text, marks);
    }
    let content = Fragment.fromJSON(schema2, json.content);
    let node2 = schema2.nodeType(json.type).create(json.attrs, content, marks);
    node2.type.checkAttrs(node2.attrs);
    return node2;
  }
};
Node$2.prototype.text = void 0;
class TextNode extends Node$2 {
  static {
    __name(this, "TextNode");
  }
  /**
  @internal
  */
  constructor(type, attrs2, content, marks) {
    super(type, attrs2, null, marks);
    if (!content)
      throw new RangeError("Empty text nodes are not allowed");
    this.text = content;
  }
  toString() {
    if (this.type.spec.toDebugString)
      return this.type.spec.toDebugString(this);
    return wrapMarks(this.marks, JSON.stringify(this.text));
  }
  get textContent() {
    return this.text;
  }
  textBetween(from2, to) {
    return this.text.slice(from2, to);
  }
  get nodeSize() {
    return this.text.length;
  }
  mark(marks) {
    return marks == this.marks ? this : new TextNode(this.type, this.attrs, this.text, marks);
  }
  withText(text2) {
    if (text2 == this.text)
      return this;
    return new TextNode(this.type, this.attrs, text2, this.marks);
  }
  cut(from2 = 0, to = this.text.length) {
    if (from2 == 0 && to == this.text.length)
      return this;
    return this.withText(this.text.slice(from2, to));
  }
  eq(other) {
    return this.sameMarkup(other) && this.text == other.text;
  }
  toJSON() {
    let base2 = super.toJSON();
    base2.text = this.text;
    return base2;
  }
}
function wrapMarks(marks, str) {
  for (let i2 = marks.length - 1; i2 >= 0; i2--)
    str = marks[i2].type.name + "(" + str + ")";
  return str;
}
__name(wrapMarks, "wrapMarks");
class ContentMatch {
  static {
    __name(this, "ContentMatch");
  }
  /**
  @internal
  */
  constructor(validEnd) {
    this.validEnd = validEnd;
    this.next = [];
    this.wrapCache = [];
  }
  /**
  @internal
  */
  static parse(string, nodeTypes) {
    let stream = new TokenStream(string, nodeTypes);
    if (stream.next == null)
      return ContentMatch.empty;
    let expr = parseExpr(stream);
    if (stream.next)
      stream.err("Unexpected trailing text");
    let match2 = dfa(nfa(expr));
    checkForDeadEnds(match2, stream);
    return match2;
  }
  /**
  Match a node type, returning a match after that node if
  successful.
  */
  matchType(type) {
    for (let i2 = 0; i2 < this.next.length; i2++)
      if (this.next[i2].type == type)
        return this.next[i2].next;
    return null;
  }
  /**
  Try to match a fragment. Returns the resulting match when
  successful.
  */
  matchFragment(frag, start2 = 0, end = frag.childCount) {
    let cur = this;
    for (let i2 = start2; cur && i2 < end; i2++)
      cur = cur.matchType(frag.child(i2).type);
    return cur;
  }
  /**
  @internal
  */
  get inlineContent() {
    return this.next.length != 0 && this.next[0].type.isInline;
  }
  /**
  Get the first matching node type at this match position that can
  be generated.
  */
  get defaultType() {
    for (let i2 = 0; i2 < this.next.length; i2++) {
      let { type } = this.next[i2];
      if (!(type.isText || type.hasRequiredAttrs()))
        return type;
    }
    return null;
  }
  /**
  @internal
  */
  compatible(other) {
    for (let i2 = 0; i2 < this.next.length; i2++)
      for (let j2 = 0; j2 < other.next.length; j2++)
        if (this.next[i2].type == other.next[j2].type)
          return true;
    return false;
  }
  /**
  Try to match the given fragment, and if that fails, see if it can
  be made to match by inserting nodes in front of it. When
  successful, return a fragment of inserted nodes (which may be
  empty if nothing had to be inserted). When `toEnd` is true, only
  return a fragment if the resulting match goes to the end of the
  content expression.
  */
  fillBefore(after, toEnd = false, startIndex = 0) {
    let seen2 = [this];
    function search2(match2, types) {
      let finished = match2.matchFragment(after, startIndex);
      if (finished && (!toEnd || finished.validEnd))
        return Fragment.from(types.map((tp) => tp.createAndFill()));
      for (let i2 = 0; i2 < match2.next.length; i2++) {
        let { type, next } = match2.next[i2];
        if (!(type.isText || type.hasRequiredAttrs()) && seen2.indexOf(next) == -1) {
          seen2.push(next);
          let found2 = search2(next, types.concat(type));
          if (found2)
            return found2;
        }
      }
      return null;
    }
    __name(search2, "search");
    return search2(this, []);
  }
  /**
  Find a set of wrapping node types that would allow a node of the
  given type to appear at this position. The result may be empty
  (when it fits directly) and will be null when no such wrapping
  exists.
  */
  findWrapping(target) {
    for (let i2 = 0; i2 < this.wrapCache.length; i2 += 2)
      if (this.wrapCache[i2] == target)
        return this.wrapCache[i2 + 1];
    let computed2 = this.computeWrapping(target);
    this.wrapCache.push(target, computed2);
    return computed2;
  }
  /**
  @internal
  */
  computeWrapping(target) {
    let seen2 = /* @__PURE__ */ Object.create(null), active = [{ match: this, type: null, via: null }];
    while (active.length) {
      let current = active.shift(), match2 = current.match;
      if (match2.matchType(target)) {
        let result = [];
        for (let obj = current; obj.type; obj = obj.via)
          result.push(obj.type);
        return result.reverse();
      }
      for (let i2 = 0; i2 < match2.next.length; i2++) {
        let { type, next } = match2.next[i2];
        if (!type.isLeaf && !type.hasRequiredAttrs() && !(type.name in seen2) && (!current.type || next.validEnd)) {
          active.push({ match: type.contentMatch, type, via: current });
          seen2[type.name] = true;
        }
      }
    }
    return null;
  }
  /**
  The number of outgoing edges this node has in the finite
  automaton that describes the content expression.
  */
  get edgeCount() {
    return this.next.length;
  }
  /**
  Get the _n_​th outgoing edge from this node in the finite
  automaton that describes the content expression.
  */
  edge(n2) {
    if (n2 >= this.next.length)
      throw new RangeError(`There's no ${n2}th edge in this content match`);
    return this.next[n2];
  }
  /**
  @internal
  */
  toString() {
    let seen2 = [];
    function scan(m2) {
      seen2.push(m2);
      for (let i2 = 0; i2 < m2.next.length; i2++)
        if (seen2.indexOf(m2.next[i2].next) == -1)
          scan(m2.next[i2].next);
    }
    __name(scan, "scan");
    scan(this);
    return seen2.map((m2, i2) => {
      let out = i2 + (m2.validEnd ? "*" : " ") + " ";
      for (let i3 = 0; i3 < m2.next.length; i3++)
        out += (i3 ? ", " : "") + m2.next[i3].type.name + "->" + seen2.indexOf(m2.next[i3].next);
      return out;
    }).join("\n");
  }
}
ContentMatch.empty = new ContentMatch(true);
class TokenStream {
  static {
    __name(this, "TokenStream");
  }
  constructor(string, nodeTypes) {
    this.string = string;
    this.nodeTypes = nodeTypes;
    this.inline = null;
    this.pos = 0;
    this.tokens = string.split(/\s*(?=\b|\W|$)/);
    if (this.tokens[this.tokens.length - 1] == "")
      this.tokens.pop();
    if (this.tokens[0] == "")
      this.tokens.shift();
  }
  get next() {
    return this.tokens[this.pos];
  }
  eat(tok) {
    return this.next == tok && (this.pos++ || true);
  }
  err(str) {
    throw new SyntaxError(str + " (in content expression '" + this.string + "')");
  }
}
function parseExpr(stream) {
  let exprs = [];
  do {
    exprs.push(parseExprSeq(stream));
  } while (stream.eat("|"));
  return exprs.length == 1 ? exprs[0] : { type: "choice", exprs };
}
__name(parseExpr, "parseExpr");
function parseExprSeq(stream) {
  let exprs = [];
  do {
    exprs.push(parseExprSubscript(stream));
  } while (stream.next && stream.next != ")" && stream.next != "|");
  return exprs.length == 1 ? exprs[0] : { type: "seq", exprs };
}
__name(parseExprSeq, "parseExprSeq");
function parseExprSubscript(stream) {
  let expr = parseExprAtom(stream);
  for (; ; ) {
    if (stream.eat("+"))
      expr = { type: "plus", expr };
    else if (stream.eat("*"))
      expr = { type: "star", expr };
    else if (stream.eat("?"))
      expr = { type: "opt", expr };
    else if (stream.eat("{"))
      expr = parseExprRange(stream, expr);
    else
      break;
  }
  return expr;
}
__name(parseExprSubscript, "parseExprSubscript");
function parseNum(stream) {
  if (/\D/.test(stream.next))
    stream.err("Expected number, got '" + stream.next + "'");
  let result = Number(stream.next);
  stream.pos++;
  return result;
}
__name(parseNum, "parseNum");
function parseExprRange(stream, expr) {
  let min = parseNum(stream), max = min;
  if (stream.eat(",")) {
    if (stream.next != "}")
      max = parseNum(stream);
    else
      max = -1;
  }
  if (!stream.eat("}"))
    stream.err("Unclosed braced range");
  return { type: "range", min, max, expr };
}
__name(parseExprRange, "parseExprRange");
function resolveName(stream, name2) {
  let types = stream.nodeTypes, type = types[name2];
  if (type)
    return [type];
  let result = [];
  for (let typeName in types) {
    let type2 = types[typeName];
    if (type2.isInGroup(name2))
      result.push(type2);
  }
  if (result.length == 0)
    stream.err("No node type or group '" + name2 + "' found");
  return result;
}
__name(resolveName, "resolveName");
function parseExprAtom(stream) {
  if (stream.eat("(")) {
    let expr = parseExpr(stream);
    if (!stream.eat(")"))
      stream.err("Missing closing paren");
    return expr;
  } else if (!/\W/.test(stream.next)) {
    let exprs = resolveName(stream, stream.next).map((type) => {
      if (stream.inline == null)
        stream.inline = type.isInline;
      else if (stream.inline != type.isInline)
        stream.err("Mixing inline and block content");
      return { type: "name", value: type };
    });
    stream.pos++;
    return exprs.length == 1 ? exprs[0] : { type: "choice", exprs };
  } else {
    stream.err("Unexpected token '" + stream.next + "'");
  }
}
__name(parseExprAtom, "parseExprAtom");
function nfa(expr) {
  let nfa2 = [[]];
  connect(compile2(expr, 0), node2());
  return nfa2;
  function node2() {
    return nfa2.push([]) - 1;
  }
  __name(node2, "node");
  function edge(from2, to, term) {
    let edge2 = { term, to };
    nfa2[from2].push(edge2);
    return edge2;
  }
  __name(edge, "edge");
  function connect(edges, to) {
    edges.forEach((edge2) => edge2.to = to);
  }
  __name(connect, "connect");
  function compile2(expr2, from2) {
    if (expr2.type == "choice") {
      return expr2.exprs.reduce((out, expr3) => out.concat(compile2(expr3, from2)), []);
    } else if (expr2.type == "seq") {
      for (let i2 = 0; ; i2++) {
        let next = compile2(expr2.exprs[i2], from2);
        if (i2 == expr2.exprs.length - 1)
          return next;
        connect(next, from2 = node2());
      }
    } else if (expr2.type == "star") {
      let loop = node2();
      edge(from2, loop);
      connect(compile2(expr2.expr, loop), loop);
      return [edge(loop)];
    } else if (expr2.type == "plus") {
      let loop = node2();
      connect(compile2(expr2.expr, from2), loop);
      connect(compile2(expr2.expr, loop), loop);
      return [edge(loop)];
    } else if (expr2.type == "opt") {
      return [edge(from2)].concat(compile2(expr2.expr, from2));
    } else if (expr2.type == "range") {
      let cur = from2;
      for (let i2 = 0; i2 < expr2.min; i2++) {
        let next = node2();
        connect(compile2(expr2.expr, cur), next);
        cur = next;
      }
      if (expr2.max == -1) {
        connect(compile2(expr2.expr, cur), cur);
      } else {
        for (let i2 = expr2.min; i2 < expr2.max; i2++) {
          let next = node2();
          edge(cur, next);
          connect(compile2(expr2.expr, cur), next);
          cur = next;
        }
      }
      return [edge(cur)];
    } else if (expr2.type == "name") {
      return [edge(from2, void 0, expr2.value)];
    } else {
      throw new Error("Unknown expr type");
    }
  }
  __name(compile2, "compile");
}
__name(nfa, "nfa");
function cmp(a2, b2) {
  return b2 - a2;
}
__name(cmp, "cmp");
function nullFrom(nfa2, node2) {
  let result = [];
  scan(node2);
  return result.sort(cmp);
  function scan(node3) {
    let edges = nfa2[node3];
    if (edges.length == 1 && !edges[0].term)
      return scan(edges[0].to);
    result.push(node3);
    for (let i2 = 0; i2 < edges.length; i2++) {
      let { term, to } = edges[i2];
      if (!term && result.indexOf(to) == -1)
        scan(to);
    }
  }
  __name(scan, "scan");
}
__name(nullFrom, "nullFrom");
function dfa(nfa2) {
  let labeled = /* @__PURE__ */ Object.create(null);
  return explore(nullFrom(nfa2, 0));
  function explore(states) {
    let out = [];
    states.forEach((node2) => {
      nfa2[node2].forEach(({ term, to }) => {
        if (!term)
          return;
        let set3;
        for (let i2 = 0; i2 < out.length; i2++)
          if (out[i2][0] == term)
            set3 = out[i2][1];
        nullFrom(nfa2, to).forEach((node3) => {
          if (!set3)
            out.push([term, set3 = []]);
          if (set3.indexOf(node3) == -1)
            set3.push(node3);
        });
      });
    });
    let state = labeled[states.join(",")] = new ContentMatch(states.indexOf(nfa2.length - 1) > -1);
    for (let i2 = 0; i2 < out.length; i2++) {
      let states2 = out[i2][1].sort(cmp);
      state.next.push({ type: out[i2][0], next: labeled[states2.join(",")] || explore(states2) });
    }
    return state;
  }
  __name(explore, "explore");
}
__name(dfa, "dfa");
function checkForDeadEnds(match2, stream) {
  for (let i2 = 0, work = [match2]; i2 < work.length; i2++) {
    let state = work[i2], dead = !state.validEnd, nodes = [];
    for (let j2 = 0; j2 < state.next.length; j2++) {
      let { type, next } = state.next[j2];
      nodes.push(type.name);
      if (dead && !(type.isText || type.hasRequiredAttrs()))
        dead = false;
      if (work.indexOf(next) == -1)
        work.push(next);
    }
    if (dead)
      stream.err("Only non-generatable nodes (" + nodes.join(", ") + ") in a required position (see https://prosemirror.net/docs/guide/#generatable)");
  }
}
__name(checkForDeadEnds, "checkForDeadEnds");
function defaultAttrs(attrs2) {
  let defaults2 = /* @__PURE__ */ Object.create(null);
  for (let attrName in attrs2) {
    let attr = attrs2[attrName];
    if (!attr.hasDefault)
      return null;
    defaults2[attrName] = attr.default;
  }
  return defaults2;
}
__name(defaultAttrs, "defaultAttrs");
function computeAttrs(attrs2, value) {
  let built = /* @__PURE__ */ Object.create(null);
  for (let name2 in attrs2) {
    let given = value && value[name2];
    if (given === void 0) {
      let attr = attrs2[name2];
      if (attr.hasDefault)
        given = attr.default;
      else
        throw new RangeError("No value supplied for attribute " + name2);
    }
    built[name2] = given;
  }
  return built;
}
__name(computeAttrs, "computeAttrs");
function checkAttrs(attrs2, values, type, name2) {
  for (let name3 in values)
    if (!(name3 in attrs2))
      throw new RangeError(`Unsupported attribute ${name3} for ${type} of type ${name3}`);
  for (let name3 in attrs2) {
    let attr = attrs2[name3];
    if (attr.validate)
      attr.validate(values[name3]);
  }
}
__name(checkAttrs, "checkAttrs");
function initAttrs(typeName, attrs2) {
  let result = /* @__PURE__ */ Object.create(null);
  if (attrs2)
    for (let name2 in attrs2)
      result[name2] = new Attribute(typeName, name2, attrs2[name2]);
  return result;
}
__name(initAttrs, "initAttrs");
let NodeType$1 = class NodeType2 {
  static {
    __name(this, "NodeType");
  }
  /**
  @internal
  */
  constructor(name2, schema2, spec) {
    this.name = name2;
    this.schema = schema2;
    this.spec = spec;
    this.markSet = null;
    this.groups = spec.group ? spec.group.split(" ") : [];
    this.attrs = initAttrs(name2, spec.attrs);
    this.defaultAttrs = defaultAttrs(this.attrs);
    this.contentMatch = null;
    this.inlineContent = null;
    this.isBlock = !(spec.inline || name2 == "text");
    this.isText = name2 == "text";
  }
  /**
  True if this is an inline type.
  */
  get isInline() {
    return !this.isBlock;
  }
  /**
  True if this is a textblock type, a block that contains inline
  content.
  */
  get isTextblock() {
    return this.isBlock && this.inlineContent;
  }
  /**
  True for node types that allow no content.
  */
  get isLeaf() {
    return this.contentMatch == ContentMatch.empty;
  }
  /**
  True when this node is an atom, i.e. when it does not have
  directly editable content.
  */
  get isAtom() {
    return this.isLeaf || !!this.spec.atom;
  }
  /**
  Return true when this node type is part of the given
  [group](https://prosemirror.net/docs/ref/#model.NodeSpec.group).
  */
  isInGroup(group) {
    return this.groups.indexOf(group) > -1;
  }
  /**
  The node type's [whitespace](https://prosemirror.net/docs/ref/#model.NodeSpec.whitespace) option.
  */
  get whitespace() {
    return this.spec.whitespace || (this.spec.code ? "pre" : "normal");
  }
  /**
  Tells you whether this node type has any required attributes.
  */
  hasRequiredAttrs() {
    for (let n2 in this.attrs)
      if (this.attrs[n2].isRequired)
        return true;
    return false;
  }
  /**
  Indicates whether this node allows some of the same content as
  the given node type.
  */
  compatibleContent(other) {
    return this == other || this.contentMatch.compatible(other.contentMatch);
  }
  /**
  @internal
  */
  computeAttrs(attrs2) {
    if (!attrs2 && this.defaultAttrs)
      return this.defaultAttrs;
    else
      return computeAttrs(this.attrs, attrs2);
  }
  /**
  Create a `Node` of this type. The given attributes are
  checked and defaulted (you can pass `null` to use the type's
  defaults entirely, if no required attributes exist). `content`
  may be a `Fragment`, a node, an array of nodes, or
  `null`. Similarly `marks` may be `null` to default to the empty
  set of marks.
  */
  create(attrs2 = null, content, marks) {
    if (this.isText)
      throw new Error("NodeType.create can't construct text nodes");
    return new Node$2(this, this.computeAttrs(attrs2), Fragment.from(content), Mark$1.setFrom(marks));
  }
  /**
  Like [`create`](https://prosemirror.net/docs/ref/#model.NodeType.create), but check the given content
  against the node type's content restrictions, and throw an error
  if it doesn't match.
  */
  createChecked(attrs2 = null, content, marks) {
    content = Fragment.from(content);
    this.checkContent(content);
    return new Node$2(this, this.computeAttrs(attrs2), content, Mark$1.setFrom(marks));
  }
  /**
  Like [`create`](https://prosemirror.net/docs/ref/#model.NodeType.create), but see if it is
  necessary to add nodes to the start or end of the given fragment
  to make it fit the node. If no fitting wrapping can be found,
  return null. Note that, due to the fact that required nodes can
  always be created, this will always succeed if you pass null or
  `Fragment.empty` as content.
  */
  createAndFill(attrs2 = null, content, marks) {
    attrs2 = this.computeAttrs(attrs2);
    content = Fragment.from(content);
    if (content.size) {
      let before = this.contentMatch.fillBefore(content);
      if (!before)
        return null;
      content = before.append(content);
    }
    let matched = this.contentMatch.matchFragment(content);
    let after = matched && matched.fillBefore(Fragment.empty, true);
    if (!after)
      return null;
    return new Node$2(this, attrs2, content.append(after), Mark$1.setFrom(marks));
  }
  /**
  Returns true if the given fragment is valid content for this node
  type.
  */
  validContent(content) {
    let result = this.contentMatch.matchFragment(content);
    if (!result || !result.validEnd)
      return false;
    for (let i2 = 0; i2 < content.childCount; i2++)
      if (!this.allowsMarks(content.child(i2).marks))
        return false;
    return true;
  }
  /**
  Throws a RangeError if the given fragment is not valid content for this
  node type.
  @internal
  */
  checkContent(content) {
    if (!this.validContent(content))
      throw new RangeError(`Invalid content for node ${this.name}: ${content.toString().slice(0, 50)}`);
  }
  /**
  @internal
  */
  checkAttrs(attrs2) {
    checkAttrs(this.attrs, attrs2, "node", this.name);
  }
  /**
  Check whether the given mark type is allowed in this node.
  */
  allowsMarkType(markType) {
    return this.markSet == null || this.markSet.indexOf(markType) > -1;
  }
  /**
  Test whether the given set of marks are allowed in this node.
  */
  allowsMarks(marks) {
    if (this.markSet == null)
      return true;
    for (let i2 = 0; i2 < marks.length; i2++)
      if (!this.allowsMarkType(marks[i2].type))
        return false;
    return true;
  }
  /**
  Removes the marks that are not allowed in this node from the given set.
  */
  allowedMarks(marks) {
    if (this.markSet == null)
      return marks;
    let copy2;
    for (let i2 = 0; i2 < marks.length; i2++) {
      if (!this.allowsMarkType(marks[i2].type)) {
        if (!copy2)
          copy2 = marks.slice(0, i2);
      } else if (copy2) {
        copy2.push(marks[i2]);
      }
    }
    return !copy2 ? marks : copy2.length ? copy2 : Mark$1.none;
  }
  /**
  @internal
  */
  static compile(nodes, schema2) {
    let result = /* @__PURE__ */ Object.create(null);
    nodes.forEach((name2, spec) => result[name2] = new NodeType2(name2, schema2, spec));
    let topType = schema2.spec.topNode || "doc";
    if (!result[topType])
      throw new RangeError("Schema is missing its top node type ('" + topType + "')");
    if (!result.text)
      throw new RangeError("Every schema needs a 'text' type");
    for (let _2 in result.text.attrs)
      throw new RangeError("The text node type should not have attributes");
    return result;
  }
};
function validateType(typeName, attrName, type) {
  let types = type.split("|");
  return (value) => {
    let name2 = value === null ? "null" : typeof value;
    if (types.indexOf(name2) < 0)
      throw new RangeError(`Expected value of type ${types} for attribute ${attrName} on type ${typeName}, got ${name2}`);
  };
}
__name(validateType, "validateType");
class Attribute {
  static {
    __name(this, "Attribute");
  }
  constructor(typeName, attrName, options2) {
    this.hasDefault = Object.prototype.hasOwnProperty.call(options2, "default");
    this.default = options2.default;
    this.validate = typeof options2.validate == "string" ? validateType(typeName, attrName, options2.validate) : options2.validate;
  }
  get isRequired() {
    return !this.hasDefault;
  }
}
class MarkType {
  static {
    __name(this, "MarkType");
  }
  /**
  @internal
  */
  constructor(name2, rank, schema2, spec) {
    this.name = name2;
    this.rank = rank;
    this.schema = schema2;
    this.spec = spec;
    this.attrs = initAttrs(name2, spec.attrs);
    this.excluded = null;
    let defaults2 = defaultAttrs(this.attrs);
    this.instance = defaults2 ? new Mark$1(this, defaults2) : null;
  }
  /**
  Create a mark of this type. `attrs` may be `null` or an object
  containing only some of the mark's attributes. The others, if
  they have defaults, will be added.
  */
  create(attrs2 = null) {
    if (!attrs2 && this.instance)
      return this.instance;
    return new Mark$1(this, computeAttrs(this.attrs, attrs2));
  }
  /**
  @internal
  */
  static compile(marks, schema2) {
    let result = /* @__PURE__ */ Object.create(null), rank = 0;
    marks.forEach((name2, spec) => result[name2] = new MarkType(name2, rank++, schema2, spec));
    return result;
  }
  /**
  When there is a mark of this type in the given set, a new set
  without it is returned. Otherwise, the input set is returned.
  */
  removeFromSet(set3) {
    for (var i2 = 0; i2 < set3.length; i2++)
      if (set3[i2].type == this) {
        set3 = set3.slice(0, i2).concat(set3.slice(i2 + 1));
        i2--;
      }
    return set3;
  }
  /**
  Tests whether there is a mark of this type in the given set.
  */
  isInSet(set3) {
    for (let i2 = 0; i2 < set3.length; i2++)
      if (set3[i2].type == this)
        return set3[i2];
  }
  /**
  @internal
  */
  checkAttrs(attrs2) {
    checkAttrs(this.attrs, attrs2, "mark", this.name);
  }
  /**
  Queries whether a given mark type is
  [excluded](https://prosemirror.net/docs/ref/#model.MarkSpec.excludes) by this one.
  */
  excludes(other) {
    return this.excluded.indexOf(other) > -1;
  }
}
class Schema {
  static {
    __name(this, "Schema");
  }
  /**
  Construct a schema from a schema [specification](https://prosemirror.net/docs/ref/#model.SchemaSpec).
  */
  constructor(spec) {
    this.linebreakReplacement = null;
    this.cached = /* @__PURE__ */ Object.create(null);
    let instanceSpec = this.spec = {};
    for (let prop2 in spec)
      instanceSpec[prop2] = spec[prop2];
    instanceSpec.nodes = OrderedMap.from(spec.nodes), instanceSpec.marks = OrderedMap.from(spec.marks || {}), this.nodes = NodeType$1.compile(this.spec.nodes, this);
    this.marks = MarkType.compile(this.spec.marks, this);
    let contentExprCache = /* @__PURE__ */ Object.create(null);
    for (let prop2 in this.nodes) {
      if (prop2 in this.marks)
        throw new RangeError(prop2 + " can not be both a node and a mark");
      let type = this.nodes[prop2], contentExpr = type.spec.content || "", markExpr = type.spec.marks;
      type.contentMatch = contentExprCache[contentExpr] || (contentExprCache[contentExpr] = ContentMatch.parse(contentExpr, this.nodes));
      type.inlineContent = type.contentMatch.inlineContent;
      if (type.spec.linebreakReplacement) {
        if (this.linebreakReplacement)
          throw new RangeError("Multiple linebreak nodes defined");
        if (!type.isInline || !type.isLeaf)
          throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");
        this.linebreakReplacement = type;
      }
      type.markSet = markExpr == "_" ? null : markExpr ? gatherMarks(this, markExpr.split(" ")) : markExpr == "" || !type.inlineContent ? [] : null;
    }
    for (let prop2 in this.marks) {
      let type = this.marks[prop2], excl = type.spec.excludes;
      type.excluded = excl == null ? [type] : excl == "" ? [] : gatherMarks(this, excl.split(" "));
    }
    this.nodeFromJSON = this.nodeFromJSON.bind(this);
    this.markFromJSON = this.markFromJSON.bind(this);
    this.topNodeType = this.nodes[this.spec.topNode || "doc"];
    this.cached.wrappings = /* @__PURE__ */ Object.create(null);
  }
  /**
  Create a node in this schema. The `type` may be a string or a
  `NodeType` instance. Attributes will be extended with defaults,
  `content` may be a `Fragment`, `null`, a `Node`, or an array of
  nodes.
  */
  node(type, attrs2 = null, content, marks) {
    if (typeof type == "string")
      type = this.nodeType(type);
    else if (!(type instanceof NodeType$1))
      throw new RangeError("Invalid node type: " + type);
    else if (type.schema != this)
      throw new RangeError("Node type from different schema used (" + type.name + ")");
    return type.createChecked(attrs2, content, marks);
  }
  /**
  Create a text node in the schema. Empty text nodes are not
  allowed.
  */
  text(text2, marks) {
    let type = this.nodes.text;
    return new TextNode(type, type.defaultAttrs, text2, Mark$1.setFrom(marks));
  }
  /**
  Create a mark with the given type and attributes.
  */
  mark(type, attrs2) {
    if (typeof type == "string")
      type = this.marks[type];
    return type.create(attrs2);
  }
  /**
  Deserialize a node from its JSON representation. This method is
  bound.
  */
  nodeFromJSON(json) {
    return Node$2.fromJSON(this, json);
  }
  /**
  Deserialize a mark from its JSON representation. This method is
  bound.
  */
  markFromJSON(json) {
    return Mark$1.fromJSON(this, json);
  }
  /**
  @internal
  */
  nodeType(name2) {
    let found2 = this.nodes[name2];
    if (!found2)
      throw new RangeError("Unknown node type: " + name2);
    return found2;
  }
}
function gatherMarks(schema2, marks) {
  let found2 = [];
  for (let i2 = 0; i2 < marks.length; i2++) {
    let name2 = marks[i2], mark = schema2.marks[name2], ok = mark;
    if (mark) {
      found2.push(mark);
    } else {
      for (let prop2 in schema2.marks) {
        let mark2 = schema2.marks[prop2];
        if (name2 == "_" || mark2.spec.group && mark2.spec.group.split(" ").indexOf(name2) > -1)
          found2.push(ok = mark2);
      }
    }
    if (!ok)
      throw new SyntaxError("Unknown mark type: '" + marks[i2] + "'");
  }
  return found2;
}
__name(gatherMarks, "gatherMarks");
function isTagRule(rule) {
  return rule.tag != null;
}
__name(isTagRule, "isTagRule");
function isStyleRule(rule) {
  return rule.style != null;
}
__name(isStyleRule, "isStyleRule");
class DOMParser {
  static {
    __name(this, "DOMParser");
  }
  /**
  Create a parser that targets the given schema, using the given
  parsing rules.
  */
  constructor(schema2, rules) {
    this.schema = schema2;
    this.rules = rules;
    this.tags = [];
    this.styles = [];
    let matchedStyles = this.matchedStyles = [];
    rules.forEach((rule) => {
      if (isTagRule(rule)) {
        this.tags.push(rule);
      } else if (isStyleRule(rule)) {
        let prop2 = /[^=]*/.exec(rule.style)[0];
        if (matchedStyles.indexOf(prop2) < 0)
          matchedStyles.push(prop2);
        this.styles.push(rule);
      }
    });
    this.normalizeLists = !this.tags.some((r2) => {
      if (!/^(ul|ol)\b/.test(r2.tag) || !r2.node)
        return false;
      let node2 = schema2.nodes[r2.node];
      return node2.contentMatch.matchType(node2);
    });
  }
  /**
  Parse a document from the content of a DOM node.
  */
  parse(dom, options2 = {}) {
    let context = new ParseContext(this, options2, false);
    context.addAll(dom, Mark$1.none, options2.from, options2.to);
    return context.finish();
  }
  /**
  Parses the content of the given DOM node, like
  [`parse`](https://prosemirror.net/docs/ref/#model.DOMParser.parse), and takes the same set of
  options. But unlike that method, which produces a whole node,
  this one returns a slice that is open at the sides, meaning that
  the schema constraints aren't applied to the start of nodes to
  the left of the input and the end of nodes at the end.
  */
  parseSlice(dom, options2 = {}) {
    let context = new ParseContext(this, options2, true);
    context.addAll(dom, Mark$1.none, options2.from, options2.to);
    return Slice.maxOpen(context.finish());
  }
  /**
  @internal
  */
  matchTag(dom, context, after) {
    for (let i2 = after ? this.tags.indexOf(after) + 1 : 0; i2 < this.tags.length; i2++) {
      let rule = this.tags[i2];
      if (matches(dom, rule.tag) && (rule.namespace === void 0 || dom.namespaceURI == rule.namespace) && (!rule.context || context.matchesContext(rule.context))) {
        if (rule.getAttrs) {
          let result = rule.getAttrs(dom);
          if (result === false)
            continue;
          rule.attrs = result || void 0;
        }
        return rule;
      }
    }
  }
  /**
  @internal
  */
  matchStyle(prop2, value, context, after) {
    for (let i2 = after ? this.styles.indexOf(after) + 1 : 0; i2 < this.styles.length; i2++) {
      let rule = this.styles[i2], style2 = rule.style;
      if (style2.indexOf(prop2) != 0 || rule.context && !context.matchesContext(rule.context) || // Test that the style string either precisely matches the prop,
      // or has an '=' sign after the prop, followed by the given
      // value.
      style2.length > prop2.length && (style2.charCodeAt(prop2.length) != 61 || style2.slice(prop2.length + 1) != value))
        continue;
      if (rule.getAttrs) {
        let result = rule.getAttrs(value);
        if (result === false)
          continue;
        rule.attrs = result || void 0;
      }
      return rule;
    }
  }
  /**
  @internal
  */
  static schemaRules(schema2) {
    let result = [];
    function insert(rule) {
      let priority = rule.priority == null ? 50 : rule.priority, i2 = 0;
      for (; i2 < result.length; i2++) {
        let next = result[i2], nextPriority = next.priority == null ? 50 : next.priority;
        if (nextPriority < priority)
          break;
      }
      result.splice(i2, 0, rule);
    }
    __name(insert, "insert");
    for (let name2 in schema2.marks) {
      let rules = schema2.marks[name2].spec.parseDOM;
      if (rules)
        rules.forEach((rule) => {
          insert(rule = copy(rule));
          if (!(rule.mark || rule.ignore || rule.clearMark))
            rule.mark = name2;
        });
    }
    for (let name2 in schema2.nodes) {
      let rules = schema2.nodes[name2].spec.parseDOM;
      if (rules)
        rules.forEach((rule) => {
          insert(rule = copy(rule));
          if (!(rule.node || rule.ignore || rule.mark))
            rule.node = name2;
        });
    }
    return result;
  }
  /**
  Construct a DOM parser using the parsing rules listed in a
  schema's [node specs](https://prosemirror.net/docs/ref/#model.NodeSpec.parseDOM), reordered by
  [priority](https://prosemirror.net/docs/ref/#model.ParseRule.priority).
  */
  static fromSchema(schema2) {
    return schema2.cached.domParser || (schema2.cached.domParser = new DOMParser(schema2, DOMParser.schemaRules(schema2)));
  }
}
const blockTags = {
  address: true,
  article: true,
  aside: true,
  blockquote: true,
  canvas: true,
  dd: true,
  div: true,
  dl: true,
  fieldset: true,
  figcaption: true,
  figure: true,
  footer: true,
  form: true,
  h1: true,
  h2: true,
  h3: true,
  h4: true,
  h5: true,
  h6: true,
  header: true,
  hgroup: true,
  hr: true,
  li: true,
  noscript: true,
  ol: true,
  output: true,
  p: true,
  pre: true,
  section: true,
  table: true,
  tfoot: true,
  ul: true
};
const ignoreTags = {
  head: true,
  noscript: true,
  object: true,
  script: true,
  style: true,
  title: true
};
const listTags = { ol: true, ul: true };
const OPT_PRESERVE_WS = 1, OPT_PRESERVE_WS_FULL = 2, OPT_OPEN_LEFT = 4;
function wsOptionsFor(type, preserveWhitespace, base2) {
  if (preserveWhitespace != null)
    return (preserveWhitespace ? OPT_PRESERVE_WS : 0) | (preserveWhitespace === "full" ? OPT_PRESERVE_WS_FULL : 0);
  return type && type.whitespace == "pre" ? OPT_PRESERVE_WS | OPT_PRESERVE_WS_FULL : base2 & ~OPT_OPEN_LEFT;
}
__name(wsOptionsFor, "wsOptionsFor");
class NodeContext {
  static {
    __name(this, "NodeContext");
  }
  constructor(type, attrs2, marks, solid, match2, options2) {
    this.type = type;
    this.attrs = attrs2;
    this.marks = marks;
    this.solid = solid;
    this.options = options2;
    this.content = [];
    this.activeMarks = Mark$1.none;
    this.match = match2 || (options2 & OPT_OPEN_LEFT ? null : type.contentMatch);
  }
  findWrapping(node2) {
    if (!this.match) {
      if (!this.type)
        return [];
      let fill2 = this.type.contentMatch.fillBefore(Fragment.from(node2));
      if (fill2) {
        this.match = this.type.contentMatch.matchFragment(fill2);
      } else {
        let start2 = this.type.contentMatch, wrap2;
        if (wrap2 = start2.findWrapping(node2.type)) {
          this.match = start2;
          return wrap2;
        } else {
          return null;
        }
      }
    }
    return this.match.findWrapping(node2.type);
  }
  finish(openEnd) {
    if (!(this.options & OPT_PRESERVE_WS)) {
      let last = this.content[this.content.length - 1], m2;
      if (last && last.isText && (m2 = /[ \t\r\n\u000c]+$/.exec(last.text))) {
        let text2 = last;
        if (last.text.length == m2[0].length)
          this.content.pop();
        else
          this.content[this.content.length - 1] = text2.withText(text2.text.slice(0, text2.text.length - m2[0].length));
      }
    }
    let content = Fragment.from(this.content);
    if (!openEnd && this.match)
      content = content.append(this.match.fillBefore(Fragment.empty, true));
    return this.type ? this.type.create(this.attrs, content, this.marks) : content;
  }
  inlineContext(node2) {
    if (this.type)
      return this.type.inlineContent;
    if (this.content.length)
      return this.content[0].isInline;
    return node2.parentNode && !blockTags.hasOwnProperty(node2.parentNode.nodeName.toLowerCase());
  }
}
class ParseContext {
  static {
    __name(this, "ParseContext");
  }
  constructor(parser, options2, isOpen) {
    this.parser = parser;
    this.options = options2;
    this.isOpen = isOpen;
    this.open = 0;
    this.localPreserveWS = false;
    let topNode = options2.topNode, topContext;
    let topOptions = wsOptionsFor(null, options2.preserveWhitespace, 0) | (isOpen ? OPT_OPEN_LEFT : 0);
    if (topNode)
      topContext = new NodeContext(topNode.type, topNode.attrs, Mark$1.none, true, options2.topMatch || topNode.type.contentMatch, topOptions);
    else if (isOpen)
      topContext = new NodeContext(null, null, Mark$1.none, true, null, topOptions);
    else
      topContext = new NodeContext(parser.schema.topNodeType, null, Mark$1.none, true, null, topOptions);
    this.nodes = [topContext];
    this.find = options2.findPositions;
    this.needsBlock = false;
  }
  get top() {
    return this.nodes[this.open];
  }
  // Add a DOM node to the content. Text is inserted as text node,
  // otherwise, the node is passed to `addElement` or, if it has a
  // `style` attribute, `addElementWithStyles`.
  addDOM(dom, marks) {
    if (dom.nodeType == 3)
      this.addTextNode(dom, marks);
    else if (dom.nodeType == 1)
      this.addElement(dom, marks);
  }
  addTextNode(dom, marks) {
    let value = dom.nodeValue;
    let top = this.top, preserveWS = top.options & OPT_PRESERVE_WS_FULL ? "full" : this.localPreserveWS || (top.options & OPT_PRESERVE_WS) > 0;
    if (preserveWS === "full" || top.inlineContext(dom) || /[^ \t\r\n\u000c]/.test(value)) {
      if (!preserveWS) {
        value = value.replace(/[ \t\r\n\u000c]+/g, " ");
        if (/^[ \t\r\n\u000c]/.test(value) && this.open == this.nodes.length - 1) {
          let nodeBefore = top.content[top.content.length - 1];
          let domNodeBefore = dom.previousSibling;
          if (!nodeBefore || domNodeBefore && domNodeBefore.nodeName == "BR" || nodeBefore.isText && /[ \t\r\n\u000c]$/.test(nodeBefore.text))
            value = value.slice(1);
        }
      } else if (preserveWS !== "full") {
        value = value.replace(/\r?\n|\r/g, " ");
      } else {
        value = value.replace(/\r\n?/g, "\n");
      }
      if (value)
        this.insertNode(this.parser.schema.text(value), marks);
      this.findInText(dom);
    } else {
      this.findInside(dom);
    }
  }
  // Try to find a handler for the given tag and use that to parse. If
  // none is found, the element's content nodes are added directly.
  addElement(dom, marks, matchAfter) {
    let outerWS = this.localPreserveWS, top = this.top;
    if (dom.tagName == "PRE" || /pre/.test(dom.style && dom.style.whiteSpace))
      this.localPreserveWS = true;
    let name2 = dom.nodeName.toLowerCase(), ruleID;
    if (listTags.hasOwnProperty(name2) && this.parser.normalizeLists)
      normalizeList(dom);
    let rule = this.options.ruleFromNode && this.options.ruleFromNode(dom) || (ruleID = this.parser.matchTag(dom, this, matchAfter));
    out: if (rule ? rule.ignore : ignoreTags.hasOwnProperty(name2)) {
      this.findInside(dom);
      this.ignoreFallback(dom, marks);
    } else if (!rule || rule.skip || rule.closeParent) {
      if (rule && rule.closeParent)
        this.open = Math.max(0, this.open - 1);
      else if (rule && rule.skip.nodeType)
        dom = rule.skip;
      let sync, oldNeedsBlock = this.needsBlock;
      if (blockTags.hasOwnProperty(name2)) {
        if (top.content.length && top.content[0].isInline && this.open) {
          this.open--;
          top = this.top;
        }
        sync = true;
        if (!top.type)
          this.needsBlock = true;
      } else if (!dom.firstChild) {
        this.leafFallback(dom, marks);
        break out;
      }
      let innerMarks = rule && rule.skip ? marks : this.readStyles(dom, marks);
      if (innerMarks)
        this.addAll(dom, innerMarks);
      if (sync)
        this.sync(top);
      this.needsBlock = oldNeedsBlock;
    } else {
      let innerMarks = this.readStyles(dom, marks);
      if (innerMarks)
        this.addElementByRule(dom, rule, innerMarks, rule.consuming === false ? ruleID : void 0);
    }
    this.localPreserveWS = outerWS;
  }
  // Called for leaf DOM nodes that would otherwise be ignored
  leafFallback(dom, marks) {
    if (dom.nodeName == "BR" && this.top.type && this.top.type.inlineContent)
      this.addTextNode(dom.ownerDocument.createTextNode("\n"), marks);
  }
  // Called for ignored nodes
  ignoreFallback(dom, marks) {
    if (dom.nodeName == "BR" && (!this.top.type || !this.top.type.inlineContent))
      this.findPlace(this.parser.schema.text("-"), marks);
  }
  // Run any style parser associated with the node's styles. Either
  // return an updated array of marks, or null to indicate some of the
  // styles had a rule with `ignore` set.
  readStyles(dom, marks) {
    let styles = dom.style;
    if (styles && styles.length)
      for (let i2 = 0; i2 < this.parser.matchedStyles.length; i2++) {
        let name2 = this.parser.matchedStyles[i2], value = styles.getPropertyValue(name2);
        if (value)
          for (let after = void 0; ; ) {
            let rule = this.parser.matchStyle(name2, value, this, after);
            if (!rule)
              break;
            if (rule.ignore)
              return null;
            if (rule.clearMark)
              marks = marks.filter((m2) => !rule.clearMark(m2));
            else
              marks = marks.concat(this.parser.schema.marks[rule.mark].create(rule.attrs));
            if (rule.consuming === false)
              after = rule;
            else
              break;
          }
      }
    return marks;
  }
  // Look up a handler for the given node. If none are found, return
  // false. Otherwise, apply it, use its return value to drive the way
  // the node's content is wrapped, and return true.
  addElementByRule(dom, rule, marks, continueAfter) {
    let sync, nodeType;
    if (rule.node) {
      nodeType = this.parser.schema.nodes[rule.node];
      if (!nodeType.isLeaf) {
        let inner = this.enter(nodeType, rule.attrs || null, marks, rule.preserveWhitespace);
        if (inner) {
          sync = true;
          marks = inner;
        }
      } else if (!this.insertNode(nodeType.create(rule.attrs), marks)) {
        this.leafFallback(dom, marks);
      }
    } else {
      let markType = this.parser.schema.marks[rule.mark];
      marks = marks.concat(markType.create(rule.attrs));
    }
    let startIn = this.top;
    if (nodeType && nodeType.isLeaf) {
      this.findInside(dom);
    } else if (continueAfter) {
      this.addElement(dom, marks, continueAfter);
    } else if (rule.getContent) {
      this.findInside(dom);
      rule.getContent(dom, this.parser.schema).forEach((node2) => this.insertNode(node2, marks));
    } else {
      let contentDOM = dom;
      if (typeof rule.contentElement == "string")
        contentDOM = dom.querySelector(rule.contentElement);
      else if (typeof rule.contentElement == "function")
        contentDOM = rule.contentElement(dom);
      else if (rule.contentElement)
        contentDOM = rule.contentElement;
      this.findAround(dom, contentDOM, true);
      this.addAll(contentDOM, marks);
      this.findAround(dom, contentDOM, false);
    }
    if (sync && this.sync(startIn))
      this.open--;
  }
  // Add all child nodes between `startIndex` and `endIndex` (or the
  // whole node, if not given). If `sync` is passed, use it to
  // synchronize after every block element.
  addAll(parent2, marks, startIndex, endIndex) {
    let index2 = startIndex || 0;
    for (let dom = startIndex ? parent2.childNodes[startIndex] : parent2.firstChild, end = endIndex == null ? null : parent2.childNodes[endIndex]; dom != end; dom = dom.nextSibling, ++index2) {
      this.findAtPoint(parent2, index2);
      this.addDOM(dom, marks);
    }
    this.findAtPoint(parent2, index2);
  }
  // Try to find a way to fit the given node type into the current
  // context. May add intermediate wrappers and/or leave non-solid
  // nodes that we're in.
  findPlace(node2, marks) {
    let route, sync;
    for (let depth = this.open; depth >= 0; depth--) {
      let cx2 = this.nodes[depth];
      let found2 = cx2.findWrapping(node2);
      if (found2 && (!route || route.length > found2.length)) {
        route = found2;
        sync = cx2;
        if (!found2.length)
          break;
      }
      if (cx2.solid)
        break;
    }
    if (!route)
      return null;
    this.sync(sync);
    for (let i2 = 0; i2 < route.length; i2++)
      marks = this.enterInner(route[i2], null, marks, false);
    return marks;
  }
  // Try to insert the given node, adjusting the context when needed.
  insertNode(node2, marks) {
    if (node2.isInline && this.needsBlock && !this.top.type) {
      let block2 = this.textblockFromContext();
      if (block2)
        marks = this.enterInner(block2, null, marks);
    }
    let innerMarks = this.findPlace(node2, marks);
    if (innerMarks) {
      this.closeExtra();
      let top = this.top;
      if (top.match)
        top.match = top.match.matchType(node2.type);
      let nodeMarks = Mark$1.none;
      for (let m2 of innerMarks.concat(node2.marks))
        if (top.type ? top.type.allowsMarkType(m2.type) : markMayApply(m2.type, node2.type))
          nodeMarks = m2.addToSet(nodeMarks);
      top.content.push(node2.mark(nodeMarks));
      return true;
    }
    return false;
  }
  // Try to start a node of the given type, adjusting the context when
  // necessary.
  enter(type, attrs2, marks, preserveWS) {
    let innerMarks = this.findPlace(type.create(attrs2), marks);
    if (innerMarks)
      innerMarks = this.enterInner(type, attrs2, marks, true, preserveWS);
    return innerMarks;
  }
  // Open a node of the given type
  enterInner(type, attrs2, marks, solid = false, preserveWS) {
    this.closeExtra();
    let top = this.top;
    top.match = top.match && top.match.matchType(type);
    let options2 = wsOptionsFor(type, preserveWS, top.options);
    if (top.options & OPT_OPEN_LEFT && top.content.length == 0)
      options2 |= OPT_OPEN_LEFT;
    let applyMarks = Mark$1.none;
    marks = marks.filter((m2) => {
      if (top.type ? top.type.allowsMarkType(m2.type) : markMayApply(m2.type, type)) {
        applyMarks = m2.addToSet(applyMarks);
        return false;
      }
      return true;
    });
    this.nodes.push(new NodeContext(type, attrs2, applyMarks, solid, null, options2));
    this.open++;
    return marks;
  }
  // Make sure all nodes above this.open are finished and added to
  // their parents
  closeExtra(openEnd = false) {
    let i2 = this.nodes.length - 1;
    if (i2 > this.open) {
      for (; i2 > this.open; i2--)
        this.nodes[i2 - 1].content.push(this.nodes[i2].finish(openEnd));
      this.nodes.length = this.open + 1;
    }
  }
  finish() {
    this.open = 0;
    this.closeExtra(this.isOpen);
    return this.nodes[0].finish(!!(this.isOpen || this.options.topOpen));
  }
  sync(to) {
    for (let i2 = this.open; i2 >= 0; i2--) {
      if (this.nodes[i2] == to) {
        this.open = i2;
        return true;
      } else if (this.localPreserveWS) {
        this.nodes[i2].options |= OPT_PRESERVE_WS;
      }
    }
    return false;
  }
  get currentPos() {
    this.closeExtra();
    let pos = 0;
    for (let i2 = this.open; i2 >= 0; i2--) {
      let content = this.nodes[i2].content;
      for (let j2 = content.length - 1; j2 >= 0; j2--)
        pos += content[j2].nodeSize;
      if (i2)
        pos++;
    }
    return pos;
  }
  findAtPoint(parent2, offset) {
    if (this.find)
      for (let i2 = 0; i2 < this.find.length; i2++) {
        if (this.find[i2].node == parent2 && this.find[i2].offset == offset)
          this.find[i2].pos = this.currentPos;
      }
  }
  findInside(parent2) {
    if (this.find)
      for (let i2 = 0; i2 < this.find.length; i2++) {
        if (this.find[i2].pos == null && parent2.nodeType == 1 && parent2.contains(this.find[i2].node))
          this.find[i2].pos = this.currentPos;
      }
  }
  findAround(parent2, content, before) {
    if (parent2 != content && this.find)
      for (let i2 = 0; i2 < this.find.length; i2++) {
        if (this.find[i2].pos == null && parent2.nodeType == 1 && parent2.contains(this.find[i2].node)) {
          let pos = content.compareDocumentPosition(this.find[i2].node);
          if (pos & (before ? 2 : 4))
            this.find[i2].pos = this.currentPos;
        }
      }
  }
  findInText(textNode) {
    if (this.find)
      for (let i2 = 0; i2 < this.find.length; i2++) {
        if (this.find[i2].node == textNode)
          this.find[i2].pos = this.currentPos - (textNode.nodeValue.length - this.find[i2].offset);
      }
  }
  // Determines whether the given context string matches this context.
  matchesContext(context) {
    if (context.indexOf("|") > -1)
      return context.split(/\s*\|\s*/).some(this.matchesContext, this);
    let parts2 = context.split("/");
    let option = this.options.context;
    let useRoot = !this.isOpen && (!option || option.parent.type == this.nodes[0].type);
    let minDepth = -(option ? option.depth + 1 : 0) + (useRoot ? 0 : 1);
    let match2 = /* @__PURE__ */ __name((i2, depth) => {
      for (; i2 >= 0; i2--) {
        let part = parts2[i2];
        if (part == "") {
          if (i2 == parts2.length - 1 || i2 == 0)
            continue;
          for (; depth >= minDepth; depth--)
            if (match2(i2 - 1, depth))
              return true;
          return false;
        } else {
          let next = depth > 0 || depth == 0 && useRoot ? this.nodes[depth].type : option && depth >= minDepth ? option.node(depth - minDepth).type : null;
          if (!next || next.name != part && !next.isInGroup(part))
            return false;
          depth--;
        }
      }
      return true;
    }, "match");
    return match2(parts2.length - 1, this.open);
  }
  textblockFromContext() {
    let $context = this.options.context;
    if ($context)
      for (let d2 = $context.depth; d2 >= 0; d2--) {
        let deflt = $context.node(d2).contentMatchAt($context.indexAfter(d2)).defaultType;
        if (deflt && deflt.isTextblock && deflt.defaultAttrs)
          return deflt;
      }
    for (let name2 in this.parser.schema.nodes) {
      let type = this.parser.schema.nodes[name2];
      if (type.isTextblock && type.defaultAttrs)
        return type;
    }
  }
}
function normalizeList(dom) {
  for (let child2 = dom.firstChild, prevItem = null; child2; child2 = child2.nextSibling) {
    let name2 = child2.nodeType == 1 ? child2.nodeName.toLowerCase() : null;
    if (name2 && listTags.hasOwnProperty(name2) && prevItem) {
      prevItem.appendChild(child2);
      child2 = prevItem;
    } else if (name2 == "li") {
      prevItem = child2;
    } else if (name2) {
      prevItem = null;
    }
  }
}
__name(normalizeList, "normalizeList");
function matches(dom, selector) {
  return (dom.matches || dom.msMatchesSelector || dom.webkitMatchesSelector || dom.mozMatchesSelector).call(dom, selector);
}
__name(matches, "matches");
function copy(obj) {
  let copy2 = {};
  for (let prop2 in obj)
    copy2[prop2] = obj[prop2];
  return copy2;
}
__name(copy, "copy");
function markMayApply(markType, nodeType) {
  let nodes = nodeType.schema.nodes;
  for (let name2 in nodes) {
    let parent2 = nodes[name2];
    if (!parent2.allowsMarkType(markType))
      continue;
    let seen2 = [], scan = /* @__PURE__ */ __name((match2) => {
      seen2.push(match2);
      for (let i2 = 0; i2 < match2.edgeCount; i2++) {
        let { type, next } = match2.edge(i2);
        if (type == nodeType)
          return true;
        if (seen2.indexOf(next) < 0 && scan(next))
          return true;
      }
    }, "scan");
    if (scan(parent2.contentMatch))
      return true;
  }
}
__name(markMayApply, "markMayApply");
class DOMSerializer {
  static {
    __name(this, "DOMSerializer");
  }
  /**
  Create a serializer. `nodes` should map node names to functions
  that take a node and return a description of the corresponding
  DOM. `marks` does the same for mark names, but also gets an
  argument that tells it whether the mark's content is block or
  inline content (for typical use, it'll always be inline). A mark
  serializer may be `null` to indicate that marks of that type
  should not be serialized.
  */
  constructor(nodes, marks) {
    this.nodes = nodes;
    this.marks = marks;
  }
  /**
  Serialize the content of this fragment to a DOM fragment. When
  not in the browser, the `document` option, containing a DOM
  document, should be passed so that the serializer can create
  nodes.
  */
  serializeFragment(fragment, options2 = {}, target) {
    if (!target)
      target = doc$1(options2).createDocumentFragment();
    let top = target, active = [];
    fragment.forEach((node2) => {
      if (active.length || node2.marks.length) {
        let keep = 0, rendered = 0;
        while (keep < active.length && rendered < node2.marks.length) {
          let next = node2.marks[rendered];
          if (!this.marks[next.type.name]) {
            rendered++;
            continue;
          }
          if (!next.eq(active[keep][0]) || next.type.spec.spanning === false)
            break;
          keep++;
          rendered++;
        }
        while (keep < active.length)
          top = active.pop()[1];
        while (rendered < node2.marks.length) {
          let add3 = node2.marks[rendered++];
          let markDOM = this.serializeMark(add3, node2.isInline, options2);
          if (markDOM) {
            active.push([add3, top]);
            top.appendChild(markDOM.dom);
            top = markDOM.contentDOM || markDOM.dom;
          }
        }
      }
      top.appendChild(this.serializeNodeInner(node2, options2));
    });
    return target;
  }
  /**
  @internal
  */
  serializeNodeInner(node2, options2) {
    let { dom, contentDOM } = renderSpec(doc$1(options2), this.nodes[node2.type.name](node2), null, node2.attrs);
    if (contentDOM) {
      if (node2.isLeaf)
        throw new RangeError("Content hole not allowed in a leaf node spec");
      this.serializeFragment(node2.content, options2, contentDOM);
    }
    return dom;
  }
  /**
  Serialize this node to a DOM node. This can be useful when you
  need to serialize a part of a document, as opposed to the whole
  document. To serialize a whole document, use
  [`serializeFragment`](https://prosemirror.net/docs/ref/#model.DOMSerializer.serializeFragment) on
  its [content](https://prosemirror.net/docs/ref/#model.Node.content).
  */
  serializeNode(node2, options2 = {}) {
    let dom = this.serializeNodeInner(node2, options2);
    for (let i2 = node2.marks.length - 1; i2 >= 0; i2--) {
      let wrap2 = this.serializeMark(node2.marks[i2], node2.isInline, options2);
      if (wrap2) {
        (wrap2.contentDOM || wrap2.dom).appendChild(dom);
        dom = wrap2.dom;
      }
    }
    return dom;
  }
  /**
  @internal
  */
  serializeMark(mark, inline2, options2 = {}) {
    let toDOM = this.marks[mark.type.name];
    return toDOM && renderSpec(doc$1(options2), toDOM(mark, inline2), null, mark.attrs);
  }
  static renderSpec(doc2, structure, xmlNS = null, blockArraysIn) {
    return renderSpec(doc2, structure, xmlNS, blockArraysIn);
  }
  /**
  Build a serializer using the [`toDOM`](https://prosemirror.net/docs/ref/#model.NodeSpec.toDOM)
  properties in a schema's node and mark specs.
  */
  static fromSchema(schema2) {
    return schema2.cached.domSerializer || (schema2.cached.domSerializer = new DOMSerializer(this.nodesFromSchema(schema2), this.marksFromSchema(schema2)));
  }
  /**
  Gather the serializers in a schema's node specs into an object.
  This can be useful as a base to build a custom serializer from.
  */
  static nodesFromSchema(schema2) {
    let result = gatherToDOM(schema2.nodes);
    if (!result.text)
      result.text = (node2) => node2.text;
    return result;
  }
  /**
  Gather the serializers in a schema's mark specs into an object.
  */
  static marksFromSchema(schema2) {
    return gatherToDOM(schema2.marks);
  }
}
function gatherToDOM(obj) {
  let result = {};
  for (let name2 in obj) {
    let toDOM = obj[name2].spec.toDOM;
    if (toDOM)
      result[name2] = toDOM;
  }
  return result;
}
__name(gatherToDOM, "gatherToDOM");
function doc$1(options2) {
  return options2.document || window.document;
}
__name(doc$1, "doc$1");
const suspiciousAttributeCache = /* @__PURE__ */ new WeakMap();
function suspiciousAttributes(attrs2) {
  let value = suspiciousAttributeCache.get(attrs2);
  if (value === void 0)
    suspiciousAttributeCache.set(attrs2, value = suspiciousAttributesInner(attrs2));
  return value;
}
__name(suspiciousAttributes, "suspiciousAttributes");
function suspiciousAttributesInner(attrs2) {
  let result = null;
  function scan(value) {
    if (value && typeof value == "object") {
      if (Array.isArray(value)) {
        if (typeof value[0] == "string") {
          if (!result)
            result = [];
          result.push(value);
        } else {
          for (let i2 = 0; i2 < value.length; i2++)
            scan(value[i2]);
        }
      } else {
        for (let prop2 in value)
          scan(value[prop2]);
      }
    }
  }
  __name(scan, "scan");
  scan(attrs2);
  return result;
}
__name(suspiciousAttributesInner, "suspiciousAttributesInner");
function renderSpec(doc2, structure, xmlNS, blockArraysIn) {
  if (typeof structure == "string")
    return { dom: doc2.createTextNode(structure) };
  if (structure.nodeType != null)
    return { dom: structure };
  if (structure.dom && structure.dom.nodeType != null)
    return structure;
  let tagName = structure[0], suspicious;
  if (typeof tagName != "string")
    throw new RangeError("Invalid array passed to renderSpec");
  if (blockArraysIn && (suspicious = suspiciousAttributes(blockArraysIn)) && suspicious.indexOf(structure) > -1)
    throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");
  let space = tagName.indexOf(" ");
  if (space > 0) {
    xmlNS = tagName.slice(0, space);
    tagName = tagName.slice(space + 1);
  }
  let contentDOM;
  let dom = xmlNS ? doc2.createElementNS(xmlNS, tagName) : doc2.createElement(tagName);
  let attrs2 = structure[1], start2 = 1;
  if (attrs2 && typeof attrs2 == "object" && attrs2.nodeType == null && !Array.isArray(attrs2)) {
    start2 = 2;
    for (let name2 in attrs2)
      if (attrs2[name2] != null) {
        let space2 = name2.indexOf(" ");
        if (space2 > 0)
          dom.setAttributeNS(name2.slice(0, space2), name2.slice(space2 + 1), attrs2[name2]);
        else
          dom.setAttribute(name2, attrs2[name2]);
      }
  }
  for (let i2 = start2; i2 < structure.length; i2++) {
    let child2 = structure[i2];
    if (child2 === 0) {
      if (i2 < structure.length - 1 || i2 > start2)
        throw new RangeError("Content hole must be the only child of its parent node");
      return { dom, contentDOM: dom };
    } else {
      let { dom: inner, contentDOM: innerContent } = renderSpec(doc2, child2, xmlNS, blockArraysIn);
      dom.appendChild(inner);
      if (innerContent) {
        if (contentDOM)
          throw new RangeError("Multiple content holes");
        contentDOM = innerContent;
      }
    }
  }
  return { dom, contentDOM };
}
__name(renderSpec, "renderSpec");
const lower16 = 65535;
const factor16 = Math.pow(2, 16);
function makeRecover(index2, offset) {
  return index2 + offset * factor16;
}
__name(makeRecover, "makeRecover");
function recoverIndex(value) {
  return value & lower16;
}
__name(recoverIndex, "recoverIndex");
function recoverOffset(value) {
  return (value - (value & lower16)) / factor16;
}
__name(recoverOffset, "recoverOffset");
const DEL_BEFORE = 1, DEL_AFTER = 2, DEL_ACROSS = 4, DEL_SIDE = 8;
class MapResult {
  static {
    __name(this, "MapResult");
  }
  /**
  @internal
  */
  constructor(pos, delInfo, recover) {
    this.pos = pos;
    this.delInfo = delInfo;
    this.recover = recover;
  }
  /**
  Tells you whether the position was deleted, that is, whether the
  step removed the token on the side queried (via the `assoc`)
  argument from the document.
  */
  get deleted() {
    return (this.delInfo & DEL_SIDE) > 0;
  }
  /**
  Tells you whether the token before the mapped position was deleted.
  */
  get deletedBefore() {
    return (this.delInfo & (DEL_BEFORE | DEL_ACROSS)) > 0;
  }
  /**
  True when the token after the mapped position was deleted.
  */
  get deletedAfter() {
    return (this.delInfo & (DEL_AFTER | DEL_ACROSS)) > 0;
  }
  /**
  Tells whether any of the steps mapped through deletes across the
  position (including both the token before and after the
  position).
  */
  get deletedAcross() {
    return (this.delInfo & DEL_ACROSS) > 0;
  }
}
class StepMap {
  static {
    __name(this, "StepMap");
  }
  /**
  Create a position map. The modifications to the document are
  represented as an array of numbers, in which each group of three
  represents a modified chunk as `[start, oldSize, newSize]`.
  */
  constructor(ranges, inverted = false) {
    this.ranges = ranges;
    this.inverted = inverted;
    if (!ranges.length && StepMap.empty)
      return StepMap.empty;
  }
  /**
  @internal
  */
  recover(value) {
    let diff2 = 0, index2 = recoverIndex(value);
    if (!this.inverted)
      for (let i2 = 0; i2 < index2; i2++)
        diff2 += this.ranges[i2 * 3 + 2] - this.ranges[i2 * 3 + 1];
    return this.ranges[index2 * 3] + diff2 + recoverOffset(value);
  }
  mapResult(pos, assoc = 1) {
    return this._map(pos, assoc, false);
  }
  map(pos, assoc = 1) {
    return this._map(pos, assoc, true);
  }
  /**
  @internal
  */
  _map(pos, assoc, simple) {
    let diff2 = 0, oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;
    for (let i2 = 0; i2 < this.ranges.length; i2 += 3) {
      let start2 = this.ranges[i2] - (this.inverted ? diff2 : 0);
      if (start2 > pos)
        break;
      let oldSize = this.ranges[i2 + oldIndex], newSize = this.ranges[i2 + newIndex], end = start2 + oldSize;
      if (pos <= end) {
        let side = !oldSize ? assoc : pos == start2 ? -1 : pos == end ? 1 : assoc;
        let result = start2 + diff2 + (side < 0 ? 0 : newSize);
        if (simple)
          return result;
        let recover = pos == (assoc < 0 ? start2 : end) ? null : makeRecover(i2 / 3, pos - start2);
        let del2 = pos == start2 ? DEL_AFTER : pos == end ? DEL_BEFORE : DEL_ACROSS;
        if (assoc < 0 ? pos != start2 : pos != end)
          del2 |= DEL_SIDE;
        return new MapResult(result, del2, recover);
      }
      diff2 += newSize - oldSize;
    }
    return simple ? pos + diff2 : new MapResult(pos + diff2, 0, null);
  }
  /**
  @internal
  */
  touches(pos, recover) {
    let diff2 = 0, index2 = recoverIndex(recover);
    let oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;
    for (let i2 = 0; i2 < this.ranges.length; i2 += 3) {
      let start2 = this.ranges[i2] - (this.inverted ? diff2 : 0);
      if (start2 > pos)
        break;
      let oldSize = this.ranges[i2 + oldIndex], end = start2 + oldSize;
      if (pos <= end && i2 == index2 * 3)
        return true;
      diff2 += this.ranges[i2 + newIndex] - oldSize;
    }
    return false;
  }
  /**
  Calls the given function on each of the changed ranges included in
  this map.
  */
  forEach(f2) {
    let oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;
    for (let i2 = 0, diff2 = 0; i2 < this.ranges.length; i2 += 3) {
      let start2 = this.ranges[i2], oldStart = start2 - (this.inverted ? diff2 : 0), newStart = start2 + (this.inverted ? 0 : diff2);
      let oldSize = this.ranges[i2 + oldIndex], newSize = this.ranges[i2 + newIndex];
      f2(oldStart, oldStart + oldSize, newStart, newStart + newSize);
      diff2 += newSize - oldSize;
    }
  }
  /**
  Create an inverted version of this map. The result can be used to
  map positions in the post-step document to the pre-step document.
  */
  invert() {
    return new StepMap(this.ranges, !this.inverted);
  }
  /**
  @internal
  */
  toString() {
    return (this.inverted ? "-" : "") + JSON.stringify(this.ranges);
  }
  /**
  Create a map that moves all positions by offset `n` (which may be
  negative). This can be useful when applying steps meant for a
  sub-document to a larger document, or vice-versa.
  */
  static offset(n2) {
    return n2 == 0 ? StepMap.empty : new StepMap(n2 < 0 ? [0, -n2, 0] : [0, 0, n2]);
  }
}
StepMap.empty = new StepMap([]);
class Mapping {
  static {
    __name(this, "Mapping");
  }
  /**
  Create a new mapping with the given position maps.
  */
  constructor(maps = [], mirror2, from2 = 0, to = maps.length) {
    this.maps = maps;
    this.mirror = mirror2;
    this.from = from2;
    this.to = to;
  }
  /**
  Create a mapping that maps only through a part of this one.
  */
  slice(from2 = 0, to = this.maps.length) {
    return new Mapping(this.maps, this.mirror, from2, to);
  }
  /**
  @internal
  */
  copy() {
    return new Mapping(this.maps.slice(), this.mirror && this.mirror.slice(), this.from, this.to);
  }
  /**
  Add a step map to the end of this mapping. If `mirrors` is
  given, it should be the index of the step map that is the mirror
  image of this one.
  */
  appendMap(map3, mirrors) {
    this.to = this.maps.push(map3);
    if (mirrors != null)
      this.setMirror(this.maps.length - 1, mirrors);
  }
  /**
  Add all the step maps in a given mapping to this one (preserving
  mirroring information).
  */
  appendMapping(mapping) {
    for (let i2 = 0, startSize = this.maps.length; i2 < mapping.maps.length; i2++) {
      let mirr = mapping.getMirror(i2);
      this.appendMap(mapping.maps[i2], mirr != null && mirr < i2 ? startSize + mirr : void 0);
    }
  }
  /**
  Finds the offset of the step map that mirrors the map at the
  given offset, in this mapping (as per the second argument to
  `appendMap`).
  */
  getMirror(n2) {
    if (this.mirror) {
      for (let i2 = 0; i2 < this.mirror.length; i2++)
        if (this.mirror[i2] == n2)
          return this.mirror[i2 + (i2 % 2 ? -1 : 1)];
    }
  }
  /**
  @internal
  */
  setMirror(n2, m2) {
    if (!this.mirror)
      this.mirror = [];
    this.mirror.push(n2, m2);
  }
  /**
  Append the inverse of the given mapping to this one.
  */
  appendMappingInverted(mapping) {
    for (let i2 = mapping.maps.length - 1, totalSize = this.maps.length + mapping.maps.length; i2 >= 0; i2--) {
      let mirr = mapping.getMirror(i2);
      this.appendMap(mapping.maps[i2].invert(), mirr != null && mirr > i2 ? totalSize - mirr - 1 : void 0);
    }
  }
  /**
  Create an inverted version of this mapping.
  */
  invert() {
    let inverse = new Mapping();
    inverse.appendMappingInverted(this);
    return inverse;
  }
  /**
  Map a position through this mapping.
  */
  map(pos, assoc = 1) {
    if (this.mirror)
      return this._map(pos, assoc, true);
    for (let i2 = this.from; i2 < this.to; i2++)
      pos = this.maps[i2].map(pos, assoc);
    return pos;
  }
  /**
  Map a position through this mapping, returning a mapping
  result.
  */
  mapResult(pos, assoc = 1) {
    return this._map(pos, assoc, false);
  }
  /**
  @internal
  */
  _map(pos, assoc, simple) {
    let delInfo = 0;
    for (let i2 = this.from; i2 < this.to; i2++) {
      let map3 = this.maps[i2], result = map3.mapResult(pos, assoc);
      if (result.recover != null) {
        let corr = this.getMirror(i2);
        if (corr != null && corr > i2 && corr < this.to) {
          i2 = corr;
          pos = this.maps[corr].recover(result.recover);
          continue;
        }
      }
      delInfo |= result.delInfo;
      pos = result.pos;
    }
    return simple ? pos : new MapResult(pos, delInfo, null);
  }
}
const stepsByID = /* @__PURE__ */ Object.create(null);
class Step {
  static {
    __name(this, "Step");
  }
  /**
  Get the step map that represents the changes made by this step,
  and which can be used to transform between positions in the old
  and the new document.
  */
  getMap() {
    return StepMap.empty;
  }
  /**
  Try to merge this step with another one, to be applied directly
  after it. Returns the merged step when possible, null if the
  steps can't be merged.
  */
  merge(other) {
    return null;
  }
  /**
  Deserialize a step from its JSON representation. Will call
  through to the step class' own implementation of this method.
  */
  static fromJSON(schema2, json) {
    if (!json || !json.stepType)
      throw new RangeError("Invalid input for Step.fromJSON");
    let type = stepsByID[json.stepType];
    if (!type)
      throw new RangeError(`No step type ${json.stepType} defined`);
    return type.fromJSON(schema2, json);
  }
  /**
  To be able to serialize steps to JSON, each step needs a string
  ID to attach to its JSON representation. Use this method to
  register an ID for your step classes. Try to pick something
  that's unlikely to clash with steps from other modules.
  */
  static jsonID(id2, stepClass) {
    if (id2 in stepsByID)
      throw new RangeError("Duplicate use of step JSON ID " + id2);
    stepsByID[id2] = stepClass;
    stepClass.prototype.jsonID = id2;
    return stepClass;
  }
}
class StepResult {
  static {
    __name(this, "StepResult");
  }
  /**
  @internal
  */
  constructor(doc2, failed) {
    this.doc = doc2;
    this.failed = failed;
  }
  /**
  Create a successful step result.
  */
  static ok(doc2) {
    return new StepResult(doc2, null);
  }
  /**
  Create a failed step result.
  */
  static fail(message) {
    return new StepResult(null, message);
  }
  /**
  Call [`Node.replace`](https://prosemirror.net/docs/ref/#model.Node.replace) with the given
  arguments. Create a successful result if it succeeds, and a
  failed one if it throws a `ReplaceError`.
  */
  static fromReplace(doc2, from2, to, slice2) {
    try {
      return StepResult.ok(doc2.replace(from2, to, slice2));
    } catch (e2) {
      if (e2 instanceof ReplaceError)
        return StepResult.fail(e2.message);
      throw e2;
    }
  }
}
function mapFragment(fragment, f2, parent2) {
  let mapped = [];
  for (let i2 = 0; i2 < fragment.childCount; i2++) {
    let child2 = fragment.child(i2);
    if (child2.content.size)
      child2 = child2.copy(mapFragment(child2.content, f2, child2));
    if (child2.isInline)
      child2 = f2(child2, parent2, i2);
    mapped.push(child2);
  }
  return Fragment.fromArray(mapped);
}
__name(mapFragment, "mapFragment");
class AddMarkStep extends Step {
  static {
    __name(this, "AddMarkStep");
  }
  /**
  Create a mark step.
  */
  constructor(from2, to, mark) {
    super();
    this.from = from2;
    this.to = to;
    this.mark = mark;
  }
  apply(doc2) {
    let oldSlice = doc2.slice(this.from, this.to), $from = doc2.resolve(this.from);
    let parent2 = $from.node($from.sharedDepth(this.to));
    let slice2 = new Slice(mapFragment(oldSlice.content, (node2, parent3) => {
      if (!node2.isAtom || !parent3.type.allowsMarkType(this.mark.type))
        return node2;
      return node2.mark(this.mark.addToSet(node2.marks));
    }, parent2), oldSlice.openStart, oldSlice.openEnd);
    return StepResult.fromReplace(doc2, this.from, this.to, slice2);
  }
  invert() {
    return new RemoveMarkStep(this.from, this.to, this.mark);
  }
  map(mapping) {
    let from2 = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);
    if (from2.deleted && to.deleted || from2.pos >= to.pos)
      return null;
    return new AddMarkStep(from2.pos, to.pos, this.mark);
  }
  merge(other) {
    if (other instanceof AddMarkStep && other.mark.eq(this.mark) && this.from <= other.to && this.to >= other.from)
      return new AddMarkStep(Math.min(this.from, other.from), Math.max(this.to, other.to), this.mark);
    return null;
  }
  toJSON() {
    return {
      stepType: "addMark",
      mark: this.mark.toJSON(),
      from: this.from,
      to: this.to
    };
  }
  /**
  @internal
  */
  static fromJSON(schema2, json) {
    if (typeof json.from != "number" || typeof json.to != "number")
      throw new RangeError("Invalid input for AddMarkStep.fromJSON");
    return new AddMarkStep(json.from, json.to, schema2.markFromJSON(json.mark));
  }
}
Step.jsonID("addMark", AddMarkStep);
class RemoveMarkStep extends Step {
  static {
    __name(this, "RemoveMarkStep");
  }
  /**
  Create a mark-removing step.
  */
  constructor(from2, to, mark) {
    super();
    this.from = from2;
    this.to = to;
    this.mark = mark;
  }
  apply(doc2) {
    let oldSlice = doc2.slice(this.from, this.to);
    let slice2 = new Slice(mapFragment(oldSlice.content, (node2) => {
      return node2.mark(this.mark.removeFromSet(node2.marks));
    }, doc2), oldSlice.openStart, oldSlice.openEnd);
    return StepResult.fromReplace(doc2, this.from, this.to, slice2);
  }
  invert() {
    return new AddMarkStep(this.from, this.to, this.mark);
  }
  map(mapping) {
    let from2 = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);
    if (from2.deleted && to.deleted || from2.pos >= to.pos)
      return null;
    return new RemoveMarkStep(from2.pos, to.pos, this.mark);
  }
  merge(other) {
    if (other instanceof RemoveMarkStep && other.mark.eq(this.mark) && this.from <= other.to && this.to >= other.from)
      return new RemoveMarkStep(Math.min(this.from, other.from), Math.max(this.to, other.to), this.mark);
    return null;
  }
  toJSON() {
    return {
      stepType: "removeMark",
      mark: this.mark.toJSON(),
      from: this.from,
      to: this.to
    };
  }
  /**
  @internal
  */
  static fromJSON(schema2, json) {
    if (typeof json.from != "number" || typeof json.to != "number")
      throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");
    return new RemoveMarkStep(json.from, json.to, schema2.markFromJSON(json.mark));
  }
}
Step.jsonID("removeMark", RemoveMarkStep);
class AddNodeMarkStep extends Step {
  static {
    __name(this, "AddNodeMarkStep");
  }
  /**
  Create a node mark step.
  */
  constructor(pos, mark) {
    super();
    this.pos = pos;
    this.mark = mark;
  }
  apply(doc2) {
    let node2 = doc2.nodeAt(this.pos);
    if (!node2)
      return StepResult.fail("No node at mark step's position");
    let updated2 = node2.type.create(node2.attrs, null, this.mark.addToSet(node2.marks));
    return StepResult.fromReplace(doc2, this.pos, this.pos + 1, new Slice(Fragment.from(updated2), 0, node2.isLeaf ? 0 : 1));
  }
  invert(doc2) {
    let node2 = doc2.nodeAt(this.pos);
    if (node2) {
      let newSet = this.mark.addToSet(node2.marks);
      if (newSet.length == node2.marks.length) {
        for (let i2 = 0; i2 < node2.marks.length; i2++)
          if (!node2.marks[i2].isInSet(newSet))
            return new AddNodeMarkStep(this.pos, node2.marks[i2]);
        return new AddNodeMarkStep(this.pos, this.mark);
      }
    }
    return new RemoveNodeMarkStep(this.pos, this.mark);
  }
  map(mapping) {
    let pos = mapping.mapResult(this.pos, 1);
    return pos.deletedAfter ? null : new AddNodeMarkStep(pos.pos, this.mark);
  }
  toJSON() {
    return { stepType: "addNodeMark", pos: this.pos, mark: this.mark.toJSON() };
  }
  /**
  @internal
  */
  static fromJSON(schema2, json) {
    if (typeof json.pos != "number")
      throw new RangeError("Invalid input for AddNodeMarkStep.fromJSON");
    return new AddNodeMarkStep(json.pos, schema2.markFromJSON(json.mark));
  }
}
Step.jsonID("addNodeMark", AddNodeMarkStep);
class RemoveNodeMarkStep extends Step {
  static {
    __name(this, "RemoveNodeMarkStep");
  }
  /**
  Create a mark-removing step.
  */
  constructor(pos, mark) {
    super();
    this.pos = pos;
    this.mark = mark;
  }
  apply(doc2) {
    let node2 = doc2.nodeAt(this.pos);
    if (!node2)
      return StepResult.fail("No node at mark step's position");
    let updated2 = node2.type.create(node2.attrs, null, this.mark.removeFromSet(node2.marks));
    return StepResult.fromReplace(doc2, this.pos, this.pos + 1, new Slice(Fragment.from(updated2), 0, node2.isLeaf ? 0 : 1));
  }
  invert(doc2) {
    let node2 = doc2.nodeAt(this.pos);
    if (!node2 || !this.mark.isInSet(node2.marks))
      return this;
    return new AddNodeMarkStep(this.pos, this.mark);
  }
  map(mapping) {
    let pos = mapping.mapResult(this.pos, 1);
    return pos.deletedAfter ? null : new RemoveNodeMarkStep(pos.pos, this.mark);
  }
  toJSON() {
    return { stepType: "removeNodeMark", pos: this.pos, mark: this.mark.toJSON() };
  }
  /**
  @internal
  */
  static fromJSON(schema2, json) {
    if (typeof json.pos != "number")
      throw new RangeError("Invalid input for RemoveNodeMarkStep.fromJSON");
    return new RemoveNodeMarkStep(json.pos, schema2.markFromJSON(json.mark));
  }
}
Step.jsonID("removeNodeMark", RemoveNodeMarkStep);
class ReplaceStep extends Step {
  static {
    __name(this, "ReplaceStep");
  }
  /**
  The given `slice` should fit the 'gap' between `from` and
  `to`—the depths must line up, and the surrounding nodes must be
  able to be joined with the open sides of the slice. When
  `structure` is true, the step will fail if the content between
  from and to is not just a sequence of closing and then opening
  tokens (this is to guard against rebased replace steps
  overwriting something they weren't supposed to).
  */
  constructor(from2, to, slice2, structure = false) {
    super();
    this.from = from2;
    this.to = to;
    this.slice = slice2;
    this.structure = structure;
  }
  apply(doc2) {
    if (this.structure && contentBetween(doc2, this.from, this.to))
      return StepResult.fail("Structure replace would overwrite content");
    return StepResult.fromReplace(doc2, this.from, this.to, this.slice);
  }
  getMap() {
    return new StepMap([this.from, this.to - this.from, this.slice.size]);
  }
  invert(doc2) {
    return new ReplaceStep(this.from, this.from + this.slice.size, doc2.slice(this.from, this.to));
  }
  map(mapping) {
    let from2 = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);
    if (from2.deletedAcross && to.deletedAcross)
      return null;
    return new ReplaceStep(from2.pos, Math.max(from2.pos, to.pos), this.slice);
  }
  merge(other) {
    if (!(other instanceof ReplaceStep) || other.structure || this.structure)
      return null;
    if (this.from + this.slice.size == other.from && !this.slice.openEnd && !other.slice.openStart) {
      let slice2 = this.slice.size + other.slice.size == 0 ? Slice.empty : new Slice(this.slice.content.append(other.slice.content), this.slice.openStart, other.slice.openEnd);
      return new ReplaceStep(this.from, this.to + (other.to - other.from), slice2, this.structure);
    } else if (other.to == this.from && !this.slice.openStart && !other.slice.openEnd) {
      let slice2 = this.slice.size + other.slice.size == 0 ? Slice.empty : new Slice(other.slice.content.append(this.slice.content), other.slice.openStart, this.slice.openEnd);
      return new ReplaceStep(other.from, this.to, slice2, this.structure);
    } else {
      return null;
    }
  }
  toJSON() {
    let json = { stepType: "replace", from: this.from, to: this.to };
    if (this.slice.size)
      json.slice = this.slice.toJSON();
    if (this.structure)
      json.structure = true;
    return json;
  }
  /**
  @internal
  */
  static fromJSON(schema2, json) {
    if (typeof json.from != "number" || typeof json.to != "number")
      throw new RangeError("Invalid input for ReplaceStep.fromJSON");
    return new ReplaceStep(json.from, json.to, Slice.fromJSON(schema2, json.slice), !!json.structure);
  }
}
Step.jsonID("replace", ReplaceStep);
class ReplaceAroundStep extends Step {
  static {
    __name(this, "ReplaceAroundStep");
  }
  /**
  Create a replace-around step with the given range and gap.
  `insert` should be the point in the slice into which the content
  of the gap should be moved. `structure` has the same meaning as
  it has in the [`ReplaceStep`](https://prosemirror.net/docs/ref/#transform.ReplaceStep) class.
  */
  constructor(from2, to, gapFrom, gapTo, slice2, insert, structure = false) {
    super();
    this.from = from2;
    this.to = to;
    this.gapFrom = gapFrom;
    this.gapTo = gapTo;
    this.slice = slice2;
    this.insert = insert;
    this.structure = structure;
  }
  apply(doc2) {
    if (this.structure && (contentBetween(doc2, this.from, this.gapFrom) || contentBetween(doc2, this.gapTo, this.to)))
      return StepResult.fail("Structure gap-replace would overwrite content");
    let gap = doc2.slice(this.gapFrom, this.gapTo);
    if (gap.openStart || gap.openEnd)
      return StepResult.fail("Gap is not a flat range");
    let inserted = this.slice.insertAt(this.insert, gap.content);
    if (!inserted)
      return StepResult.fail("Content does not fit in gap");
    return StepResult.fromReplace(doc2, this.from, this.to, inserted);
  }
  getMap() {
    return new StepMap([
      this.from,
      this.gapFrom - this.from,
      this.insert,
      this.gapTo,
      this.to - this.gapTo,
      this.slice.size - this.insert
    ]);
  }
  invert(doc2) {
    let gap = this.gapTo - this.gapFrom;
    return new ReplaceAroundStep(this.from, this.from + this.slice.size + gap, this.from + this.insert, this.from + this.insert + gap, doc2.slice(this.from, this.to).removeBetween(this.gapFrom - this.from, this.gapTo - this.from), this.gapFrom - this.from, this.structure);
  }
  map(mapping) {
    let from2 = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);
    let gapFrom = this.from == this.gapFrom ? from2.pos : mapping.map(this.gapFrom, -1);
    let gapTo = this.to == this.gapTo ? to.pos : mapping.map(this.gapTo, 1);
    if (from2.deletedAcross && to.deletedAcross || gapFrom < from2.pos || gapTo > to.pos)
      return null;
    return new ReplaceAroundStep(from2.pos, to.pos, gapFrom, gapTo, this.slice, this.insert, this.structure);
  }
  toJSON() {
    let json = {
      stepType: "replaceAround",
      from: this.from,
      to: this.to,
      gapFrom: this.gapFrom,
      gapTo: this.gapTo,
      insert: this.insert
    };
    if (this.slice.size)
      json.slice = this.slice.toJSON();
    if (this.structure)
      json.structure = true;
    return json;
  }
  /**
  @internal
  */
  static fromJSON(schema2, json) {
    if (typeof json.from != "number" || typeof json.to != "number" || typeof json.gapFrom != "number" || typeof json.gapTo != "number" || typeof json.insert != "number")
      throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");
    return new ReplaceAroundStep(json.from, json.to, json.gapFrom, json.gapTo, Slice.fromJSON(schema2, json.slice), json.insert, !!json.structure);
  }
}
Step.jsonID("replaceAround", ReplaceAroundStep);
function contentBetween(doc2, from2, to) {
  let $from = doc2.resolve(from2), dist3 = to - from2, depth = $from.depth;
  while (dist3 > 0 && depth > 0 && $from.indexAfter(depth) == $from.node(depth).childCount) {
    depth--;
    dist3--;
  }
  if (dist3 > 0) {
    let next = $from.node(depth).maybeChild($from.indexAfter(depth));
    while (dist3 > 0) {
      if (!next || next.isLeaf)
        return true;
      next = next.firstChild;
      dist3--;
    }
  }
  return false;
}
__name(contentBetween, "contentBetween");
function addMark(tr2, from2, to, mark) {
  let removed = [], added = [];
  let removing, adding;
  tr2.doc.nodesBetween(from2, to, (node2, pos, parent2) => {
    if (!node2.isInline)
      return;
    let marks = node2.marks;
    if (!mark.isInSet(marks) && parent2.type.allowsMarkType(mark.type)) {
      let start2 = Math.max(pos, from2), end = Math.min(pos + node2.nodeSize, to);
      let newSet = mark.addToSet(marks);
      for (let i2 = 0; i2 < marks.length; i2++) {
        if (!marks[i2].isInSet(newSet)) {
          if (removing && removing.to == start2 && removing.mark.eq(marks[i2]))
            removing.to = end;
          else
            removed.push(removing = new RemoveMarkStep(start2, end, marks[i2]));
        }
      }
      if (adding && adding.to == start2)
        adding.to = end;
      else
        added.push(adding = new AddMarkStep(start2, end, mark));
    }
  });
  removed.forEach((s2) => tr2.step(s2));
  added.forEach((s2) => tr2.step(s2));
}
__name(addMark, "addMark");
function removeMark(tr2, from2, to, mark) {
  let matched = [], step = 0;
  tr2.doc.nodesBetween(from2, to, (node2, pos) => {
    if (!node2.isInline)
      return;
    step++;
    let toRemove = null;
    if (mark instanceof MarkType) {
      let set3 = node2.marks, found2;
      while (found2 = mark.isInSet(set3)) {
        (toRemove || (toRemove = [])).push(found2);
        set3 = found2.removeFromSet(set3);
      }
    } else if (mark) {
      if (mark.isInSet(node2.marks))
        toRemove = [mark];
    } else {
      toRemove = node2.marks;
    }
    if (toRemove && toRemove.length) {
      let end = Math.min(pos + node2.nodeSize, to);
      for (let i2 = 0; i2 < toRemove.length; i2++) {
        let style2 = toRemove[i2], found2;
        for (let j2 = 0; j2 < matched.length; j2++) {
          let m2 = matched[j2];
          if (m2.step == step - 1 && style2.eq(matched[j2].style))
            found2 = m2;
        }
        if (found2) {
          found2.to = end;
          found2.step = step;
        } else {
          matched.push({ style: style2, from: Math.max(pos, from2), to: end, step });
        }
      }
    }
  });
  matched.forEach((m2) => tr2.step(new RemoveMarkStep(m2.from, m2.to, m2.style)));
}
__name(removeMark, "removeMark");
function clearIncompatible(tr2, pos, parentType, match2 = parentType.contentMatch, clearNewlines = true) {
  let node2 = tr2.doc.nodeAt(pos);
  let replSteps = [], cur = pos + 1;
  for (let i2 = 0; i2 < node2.childCount; i2++) {
    let child2 = node2.child(i2), end = cur + child2.nodeSize;
    let allowed = match2.matchType(child2.type);
    if (!allowed) {
      replSteps.push(new ReplaceStep(cur, end, Slice.empty));
    } else {
      match2 = allowed;
      for (let j2 = 0; j2 < child2.marks.length; j2++)
        if (!parentType.allowsMarkType(child2.marks[j2].type))
          tr2.step(new RemoveMarkStep(cur, end, child2.marks[j2]));
      if (clearNewlines && child2.isText && parentType.whitespace != "pre") {
        let m2, newline2 = /\r?\n|\r/g, slice2;
        while (m2 = newline2.exec(child2.text)) {
          if (!slice2)
            slice2 = new Slice(Fragment.from(parentType.schema.text(" ", parentType.allowedMarks(child2.marks))), 0, 0);
          replSteps.push(new ReplaceStep(cur + m2.index, cur + m2.index + m2[0].length, slice2));
        }
      }
    }
    cur = end;
  }
  if (!match2.validEnd) {
    let fill2 = match2.fillBefore(Fragment.empty, true);
    tr2.replace(cur, cur, new Slice(fill2, 0, 0));
  }
  for (let i2 = replSteps.length - 1; i2 >= 0; i2--)
    tr2.step(replSteps[i2]);
}
__name(clearIncompatible, "clearIncompatible");
function canCut(node2, start2, end) {
  return (start2 == 0 || node2.canReplace(start2, node2.childCount)) && (end == node2.childCount || node2.canReplace(0, end));
}
__name(canCut, "canCut");
function liftTarget(range) {
  let parent2 = range.parent;
  let content = parent2.content.cutByIndex(range.startIndex, range.endIndex);
  for (let depth = range.depth; ; --depth) {
    let node2 = range.$from.node(depth);
    let index2 = range.$from.index(depth), endIndex = range.$to.indexAfter(depth);
    if (depth < range.depth && node2.canReplace(index2, endIndex, content))
      return depth;
    if (depth == 0 || node2.type.spec.isolating || !canCut(node2, index2, endIndex))
      break;
  }
  return null;
}
__name(liftTarget, "liftTarget");
function lift$2(tr2, range, target) {
  let { $from, $to, depth } = range;
  let gapStart = $from.before(depth + 1), gapEnd = $to.after(depth + 1);
  let start2 = gapStart, end = gapEnd;
  let before = Fragment.empty, openStart = 0;
  for (let d2 = depth, splitting = false; d2 > target; d2--)
    if (splitting || $from.index(d2) > 0) {
      splitting = true;
      before = Fragment.from($from.node(d2).copy(before));
      openStart++;
    } else {
      start2--;
    }
  let after = Fragment.empty, openEnd = 0;
  for (let d2 = depth, splitting = false; d2 > target; d2--)
    if (splitting || $to.after(d2 + 1) < $to.end(d2)) {
      splitting = true;
      after = Fragment.from($to.node(d2).copy(after));
      openEnd++;
    } else {
      end++;
    }
  tr2.step(new ReplaceAroundStep(start2, end, gapStart, gapEnd, new Slice(before.append(after), openStart, openEnd), before.size - openStart, true));
}
__name(lift$2, "lift$2");
function findWrapping(range, nodeType, attrs2 = null, innerRange = range) {
  let around = findWrappingOutside(range, nodeType);
  let inner = around && findWrappingInside(innerRange, nodeType);
  if (!inner)
    return null;
  return around.map(withAttrs).concat({ type: nodeType, attrs: attrs2 }).concat(inner.map(withAttrs));
}
__name(findWrapping, "findWrapping");
function withAttrs(type) {
  return { type, attrs: null };
}
__name(withAttrs, "withAttrs");
function findWrappingOutside(range, type) {
  let { parent: parent2, startIndex, endIndex } = range;
  let around = parent2.contentMatchAt(startIndex).findWrapping(type);
  if (!around)
    return null;
  let outer = around.length ? around[0] : type;
  return parent2.canReplaceWith(startIndex, endIndex, outer) ? around : null;
}
__name(findWrappingOutside, "findWrappingOutside");
function findWrappingInside(range, type) {
  let { parent: parent2, startIndex, endIndex } = range;
  let inner = parent2.child(startIndex);
  let inside = type.contentMatch.findWrapping(inner.type);
  if (!inside)
    return null;
  let lastType = inside.length ? inside[inside.length - 1] : type;
  let innerMatch = lastType.contentMatch;
  for (let i2 = startIndex; innerMatch && i2 < endIndex; i2++)
    innerMatch = innerMatch.matchType(parent2.child(i2).type);
  if (!innerMatch || !innerMatch.validEnd)
    return null;
  return inside;
}
__name(findWrappingInside, "findWrappingInside");
function wrap(tr2, range, wrappers) {
  let content = Fragment.empty;
  for (let i2 = wrappers.length - 1; i2 >= 0; i2--) {
    if (content.size) {
      let match2 = wrappers[i2].type.contentMatch.matchFragment(content);
      if (!match2 || !match2.validEnd)
        throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper");
    }
    content = Fragment.from(wrappers[i2].type.create(wrappers[i2].attrs, content));
  }
  let start2 = range.start, end = range.end;
  tr2.step(new ReplaceAroundStep(start2, end, start2, end, new Slice(content, 0, 0), wrappers.length, true));
}
__name(wrap, "wrap");
function setBlockType$1(tr2, from2, to, type, attrs2) {
  if (!type.isTextblock)
    throw new RangeError("Type given to setBlockType should be a textblock");
  let mapFrom = tr2.steps.length;
  tr2.doc.nodesBetween(from2, to, (node2, pos) => {
    let attrsHere = typeof attrs2 == "function" ? attrs2(node2) : attrs2;
    if (node2.isTextblock && !node2.hasMarkup(type, attrsHere) && canChangeType(tr2.doc, tr2.mapping.slice(mapFrom).map(pos), type)) {
      let convertNewlines = null;
      if (type.schema.linebreakReplacement) {
        let pre = type.whitespace == "pre", supportLinebreak = !!type.contentMatch.matchType(type.schema.linebreakReplacement);
        if (pre && !supportLinebreak)
          convertNewlines = false;
        else if (!pre && supportLinebreak)
          convertNewlines = true;
      }
      if (convertNewlines === false)
        replaceLinebreaks(tr2, node2, pos, mapFrom);
      clearIncompatible(tr2, tr2.mapping.slice(mapFrom).map(pos, 1), type, void 0, convertNewlines === null);
      let mapping = tr2.mapping.slice(mapFrom);
      let startM = mapping.map(pos, 1), endM = mapping.map(pos + node2.nodeSize, 1);
      tr2.step(new ReplaceAroundStep(startM, endM, startM + 1, endM - 1, new Slice(Fragment.from(type.create(attrsHere, null, node2.marks)), 0, 0), 1, true));
      if (convertNewlines === true)
        replaceNewlines(tr2, node2, pos, mapFrom);
      return false;
    }
  });
}
__name(setBlockType$1, "setBlockType$1");
function replaceNewlines(tr2, node2, pos, mapFrom) {
  node2.forEach((child2, offset) => {
    if (child2.isText) {
      let m2, newline2 = /\r?\n|\r/g;
      while (m2 = newline2.exec(child2.text)) {
        let start2 = tr2.mapping.slice(mapFrom).map(pos + 1 + offset + m2.index);
        tr2.replaceWith(start2, start2 + 1, node2.type.schema.linebreakReplacement.create());
      }
    }
  });
}
__name(replaceNewlines, "replaceNewlines");
function replaceLinebreaks(tr2, node2, pos, mapFrom) {
  node2.forEach((child2, offset) => {
    if (child2.type == child2.type.schema.linebreakReplacement) {
      let start2 = tr2.mapping.slice(mapFrom).map(pos + 1 + offset);
      tr2.replaceWith(start2, start2 + 1, node2.type.schema.text("\n"));
    }
  });
}
__name(replaceLinebreaks, "replaceLinebreaks");
function canChangeType(doc2, pos, type) {
  let $pos = doc2.resolve(pos), index2 = $pos.index();
  return $pos.parent.canReplaceWith(index2, index2 + 1, type);
}
__name(canChangeType, "canChangeType");
function setNodeMarkup(tr2, pos, type, attrs2, marks) {
  let node2 = tr2.doc.nodeAt(pos);
  if (!node2)
    throw new RangeError("No node at given position");
  if (!type)
    type = node2.type;
  let newNode = type.create(attrs2, null, marks || node2.marks);
  if (node2.isLeaf)
    return tr2.replaceWith(pos, pos + node2.nodeSize, newNode);
  if (!type.validContent(node2.content))
    throw new RangeError("Invalid content for node type " + type.name);
  tr2.step(new ReplaceAroundStep(pos, pos + node2.nodeSize, pos + 1, pos + node2.nodeSize - 1, new Slice(Fragment.from(newNode), 0, 0), 1, true));
}
__name(setNodeMarkup, "setNodeMarkup");
function canSplit(doc2, pos, depth = 1, typesAfter) {
  let $pos = doc2.resolve(pos), base2 = $pos.depth - depth;
  let innerType = typesAfter && typesAfter[typesAfter.length - 1] || $pos.parent;
  if (base2 < 0 || $pos.parent.type.spec.isolating || !$pos.parent.canReplace($pos.index(), $pos.parent.childCount) || !innerType.type.validContent($pos.parent.content.cutByIndex($pos.index(), $pos.parent.childCount)))
    return false;
  for (let d2 = $pos.depth - 1, i2 = depth - 2; d2 > base2; d2--, i2--) {
    let node2 = $pos.node(d2), index3 = $pos.index(d2);
    if (node2.type.spec.isolating)
      return false;
    let rest = node2.content.cutByIndex(index3, node2.childCount);
    let overrideChild = typesAfter && typesAfter[i2 + 1];
    if (overrideChild)
      rest = rest.replaceChild(0, overrideChild.type.create(overrideChild.attrs));
    let after = typesAfter && typesAfter[i2] || node2;
    if (!node2.canReplace(index3 + 1, node2.childCount) || !after.type.validContent(rest))
      return false;
  }
  let index2 = $pos.indexAfter(base2);
  let baseType = typesAfter && typesAfter[0];
  return $pos.node(base2).canReplaceWith(index2, index2, baseType ? baseType.type : $pos.node(base2 + 1).type);
}
__name(canSplit, "canSplit");
function split(tr2, pos, depth = 1, typesAfter) {
  let $pos = tr2.doc.resolve(pos), before = Fragment.empty, after = Fragment.empty;
  for (let d2 = $pos.depth, e2 = $pos.depth - depth, i2 = depth - 1; d2 > e2; d2--, i2--) {
    before = Fragment.from($pos.node(d2).copy(before));
    let typeAfter = typesAfter && typesAfter[i2];
    after = Fragment.from(typeAfter ? typeAfter.type.create(typeAfter.attrs, after) : $pos.node(d2).copy(after));
  }
  tr2.step(new ReplaceStep(pos, pos, new Slice(before.append(after), depth, depth), true));
}
__name(split, "split");
function canJoin(doc2, pos) {
  let $pos = doc2.resolve(pos), index2 = $pos.index();
  return joinable($pos.nodeBefore, $pos.nodeAfter) && $pos.parent.canReplace(index2, index2 + 1);
}
__name(canJoin, "canJoin");
function canAppendWithSubstitutedLinebreaks(a2, b2) {
  if (!b2.content.size)
    a2.type.compatibleContent(b2.type);
  let match2 = a2.contentMatchAt(a2.childCount);
  let { linebreakReplacement } = a2.type.schema;
  for (let i2 = 0; i2 < b2.childCount; i2++) {
    let child2 = b2.child(i2);
    let type = child2.type == linebreakReplacement ? a2.type.schema.nodes.text : child2.type;
    match2 = match2.matchType(type);
    if (!match2)
      return false;
    if (!a2.type.allowsMarks(child2.marks))
      return false;
  }
  return match2.validEnd;
}
__name(canAppendWithSubstitutedLinebreaks, "canAppendWithSubstitutedLinebreaks");
function joinable(a2, b2) {
  return !!(a2 && b2 && !a2.isLeaf && canAppendWithSubstitutedLinebreaks(a2, b2));
}
__name(joinable, "joinable");
function joinPoint(doc2, pos, dir = -1) {
  let $pos = doc2.resolve(pos);
  for (let d2 = $pos.depth; ; d2--) {
    let before, after, index2 = $pos.index(d2);
    if (d2 == $pos.depth) {
      before = $pos.nodeBefore;
      after = $pos.nodeAfter;
    } else if (dir > 0) {
      before = $pos.node(d2 + 1);
      index2++;
      after = $pos.node(d2).maybeChild(index2);
    } else {
      before = $pos.node(d2).maybeChild(index2 - 1);
      after = $pos.node(d2 + 1);
    }
    if (before && !before.isTextblock && joinable(before, after) && $pos.node(d2).canReplace(index2, index2 + 1))
      return pos;
    if (d2 == 0)
      break;
    pos = dir < 0 ? $pos.before(d2) : $pos.after(d2);
  }
}
__name(joinPoint, "joinPoint");
function join(tr2, pos, depth) {
  let convertNewlines = null;
  let { linebreakReplacement } = tr2.doc.type.schema;
  let $before = tr2.doc.resolve(pos - depth), beforeType = $before.node().type;
  if (linebreakReplacement && beforeType.inlineContent) {
    let pre = beforeType.whitespace == "pre";
    let supportLinebreak = !!beforeType.contentMatch.matchType(linebreakReplacement);
    if (pre && !supportLinebreak)
      convertNewlines = false;
    else if (!pre && supportLinebreak)
      convertNewlines = true;
  }
  let mapFrom = tr2.steps.length;
  if (convertNewlines === false) {
    let $after = tr2.doc.resolve(pos + depth);
    replaceLinebreaks(tr2, $after.node(), $after.before(), mapFrom);
  }
  if (beforeType.inlineContent)
    clearIncompatible(tr2, pos + depth - 1, beforeType, $before.node().contentMatchAt($before.index()), convertNewlines == null);
  let mapping = tr2.mapping.slice(mapFrom), start2 = mapping.map(pos - depth);
  tr2.step(new ReplaceStep(start2, mapping.map(pos + depth, -1), Slice.empty, true));
  if (convertNewlines === true) {
    let $full = tr2.doc.resolve(start2);
    replaceNewlines(tr2, $full.node(), $full.before(), tr2.steps.length);
  }
  return tr2;
}
__name(join, "join");
function insertPoint(doc2, pos, nodeType) {
  let $pos = doc2.resolve(pos);
  if ($pos.parent.canReplaceWith($pos.index(), $pos.index(), nodeType))
    return pos;
  if ($pos.parentOffset == 0)
    for (let d2 = $pos.depth - 1; d2 >= 0; d2--) {
      let index2 = $pos.index(d2);
      if ($pos.node(d2).canReplaceWith(index2, index2, nodeType))
        return $pos.before(d2 + 1);
      if (index2 > 0)
        return null;
    }
  if ($pos.parentOffset == $pos.parent.content.size)
    for (let d2 = $pos.depth - 1; d2 >= 0; d2--) {
      let index2 = $pos.indexAfter(d2);
      if ($pos.node(d2).canReplaceWith(index2, index2, nodeType))
        return $pos.after(d2 + 1);
      if (index2 < $pos.node(d2).childCount)
        return null;
    }
  return null;
}
__name(insertPoint, "insertPoint");
function dropPoint(doc2, pos, slice2) {
  let $pos = doc2.resolve(pos);
  if (!slice2.content.size)
    return pos;
  let content = slice2.content;
  for (let i2 = 0; i2 < slice2.openStart; i2++)
    content = content.firstChild.content;
  for (let pass = 1; pass <= (slice2.openStart == 0 && slice2.size ? 2 : 1); pass++) {
    for (let d2 = $pos.depth; d2 >= 0; d2--) {
      let bias = d2 == $pos.depth ? 0 : $pos.pos <= ($pos.start(d2 + 1) + $pos.end(d2 + 1)) / 2 ? -1 : 1;
      let insertPos = $pos.index(d2) + (bias > 0 ? 1 : 0);
      let parent2 = $pos.node(d2), fits = false;
      if (pass == 1) {
        fits = parent2.canReplace(insertPos, insertPos, content);
      } else {
        let wrapping = parent2.contentMatchAt(insertPos).findWrapping(content.firstChild.type);
        fits = wrapping && parent2.canReplaceWith(insertPos, insertPos, wrapping[0]);
      }
      if (fits)
        return bias == 0 ? $pos.pos : bias < 0 ? $pos.before(d2 + 1) : $pos.after(d2 + 1);
    }
  }
  return null;
}
__name(dropPoint, "dropPoint");
function replaceStep(doc2, from2, to = from2, slice2 = Slice.empty) {
  if (from2 == to && !slice2.size)
    return null;
  let $from = doc2.resolve(from2), $to = doc2.resolve(to);
  if (fitsTrivially($from, $to, slice2))
    return new ReplaceStep(from2, to, slice2);
  return new Fitter($from, $to, slice2).fit();
}
__name(replaceStep, "replaceStep");
function fitsTrivially($from, $to, slice2) {
  return !slice2.openStart && !slice2.openEnd && $from.start() == $to.start() && $from.parent.canReplace($from.index(), $to.index(), slice2.content);
}
__name(fitsTrivially, "fitsTrivially");
class Fitter {
  static {
    __name(this, "Fitter");
  }
  constructor($from, $to, unplaced) {
    this.$from = $from;
    this.$to = $to;
    this.unplaced = unplaced;
    this.frontier = [];
    this.placed = Fragment.empty;
    for (let i2 = 0; i2 <= $from.depth; i2++) {
      let node2 = $from.node(i2);
      this.frontier.push({
        type: node2.type,
        match: node2.contentMatchAt($from.indexAfter(i2))
      });
    }
    for (let i2 = $from.depth; i2 > 0; i2--)
      this.placed = Fragment.from($from.node(i2).copy(this.placed));
  }
  get depth() {
    return this.frontier.length - 1;
  }
  fit() {
    while (this.unplaced.size) {
      let fit = this.findFittable();
      if (fit)
        this.placeNodes(fit);
      else
        this.openMore() || this.dropNode();
    }
    let moveInline = this.mustMoveInline(), placedSize = this.placed.size - this.depth - this.$from.depth;
    let $from = this.$from, $to = this.close(moveInline < 0 ? this.$to : $from.doc.resolve(moveInline));
    if (!$to)
      return null;
    let content = this.placed, openStart = $from.depth, openEnd = $to.depth;
    while (openStart && openEnd && content.childCount == 1) {
      content = content.firstChild.content;
      openStart--;
      openEnd--;
    }
    let slice2 = new Slice(content, openStart, openEnd);
    if (moveInline > -1)
      return new ReplaceAroundStep($from.pos, moveInline, this.$to.pos, this.$to.end(), slice2, placedSize);
    if (slice2.size || $from.pos != this.$to.pos)
      return new ReplaceStep($from.pos, $to.pos, slice2);
    return null;
  }
  // Find a position on the start spine of `this.unplaced` that has
  // content that can be moved somewhere on the frontier. Returns two
  // depths, one for the slice and one for the frontier.
  findFittable() {
    let startDepth = this.unplaced.openStart;
    for (let cur = this.unplaced.content, d2 = 0, openEnd = this.unplaced.openEnd; d2 < startDepth; d2++) {
      let node2 = cur.firstChild;
      if (cur.childCount > 1)
        openEnd = 0;
      if (node2.type.spec.isolating && openEnd <= d2) {
        startDepth = d2;
        break;
      }
      cur = node2.content;
    }
    for (let pass = 1; pass <= 2; pass++) {
      for (let sliceDepth = pass == 1 ? startDepth : this.unplaced.openStart; sliceDepth >= 0; sliceDepth--) {
        let fragment, parent2 = null;
        if (sliceDepth) {
          parent2 = contentAt(this.unplaced.content, sliceDepth - 1).firstChild;
          fragment = parent2.content;
        } else {
          fragment = this.unplaced.content;
        }
        let first2 = fragment.firstChild;
        for (let frontierDepth = this.depth; frontierDepth >= 0; frontierDepth--) {
          let { type, match: match2 } = this.frontier[frontierDepth], wrap2, inject2 = null;
          if (pass == 1 && (first2 ? match2.matchType(first2.type) || (inject2 = match2.fillBefore(Fragment.from(first2), false)) : parent2 && type.compatibleContent(parent2.type)))
            return { sliceDepth, frontierDepth, parent: parent2, inject: inject2 };
          else if (pass == 2 && first2 && (wrap2 = match2.findWrapping(first2.type)))
            return { sliceDepth, frontierDepth, parent: parent2, wrap: wrap2 };
          if (parent2 && match2.matchType(parent2.type))
            break;
        }
      }
    }
  }
  openMore() {
    let { content, openStart, openEnd } = this.unplaced;
    let inner = contentAt(content, openStart);
    if (!inner.childCount || inner.firstChild.isLeaf)
      return false;
    this.unplaced = new Slice(content, openStart + 1, Math.max(openEnd, inner.size + openStart >= content.size - openEnd ? openStart + 1 : 0));
    return true;
  }
  dropNode() {
    let { content, openStart, openEnd } = this.unplaced;
    let inner = contentAt(content, openStart);
    if (inner.childCount <= 1 && openStart > 0) {
      let openAtEnd = content.size - openStart <= openStart + inner.size;
      this.unplaced = new Slice(dropFromFragment(content, openStart - 1, 1), openStart - 1, openAtEnd ? openStart - 1 : openEnd);
    } else {
      this.unplaced = new Slice(dropFromFragment(content, openStart, 1), openStart, openEnd);
    }
  }
  // Move content from the unplaced slice at `sliceDepth` to the
  // frontier node at `frontierDepth`. Close that frontier node when
  // applicable.
  placeNodes({ sliceDepth, frontierDepth, parent: parent2, inject: inject2, wrap: wrap2 }) {
    while (this.depth > frontierDepth)
      this.closeFrontierNode();
    if (wrap2)
      for (let i2 = 0; i2 < wrap2.length; i2++)
        this.openFrontierNode(wrap2[i2]);
    let slice2 = this.unplaced, fragment = parent2 ? parent2.content : slice2.content;
    let openStart = slice2.openStart - sliceDepth;
    let taken = 0, add3 = [];
    let { match: match2, type } = this.frontier[frontierDepth];
    if (inject2) {
      for (let i2 = 0; i2 < inject2.childCount; i2++)
        add3.push(inject2.child(i2));
      match2 = match2.matchFragment(inject2);
    }
    let openEndCount = fragment.size + sliceDepth - (slice2.content.size - slice2.openEnd);
    while (taken < fragment.childCount) {
      let next = fragment.child(taken), matches2 = match2.matchType(next.type);
      if (!matches2)
        break;
      taken++;
      if (taken > 1 || openStart == 0 || next.content.size) {
        match2 = matches2;
        add3.push(closeNodeStart(next.mark(type.allowedMarks(next.marks)), taken == 1 ? openStart : 0, taken == fragment.childCount ? openEndCount : -1));
      }
    }
    let toEnd = taken == fragment.childCount;
    if (!toEnd)
      openEndCount = -1;
    this.placed = addToFragment(this.placed, frontierDepth, Fragment.from(add3));
    this.frontier[frontierDepth].match = match2;
    if (toEnd && openEndCount < 0 && parent2 && parent2.type == this.frontier[this.depth].type && this.frontier.length > 1)
      this.closeFrontierNode();
    for (let i2 = 0, cur = fragment; i2 < openEndCount; i2++) {
      let node2 = cur.lastChild;
      this.frontier.push({ type: node2.type, match: node2.contentMatchAt(node2.childCount) });
      cur = node2.content;
    }
    this.unplaced = !toEnd ? new Slice(dropFromFragment(slice2.content, sliceDepth, taken), slice2.openStart, slice2.openEnd) : sliceDepth == 0 ? Slice.empty : new Slice(dropFromFragment(slice2.content, sliceDepth - 1, 1), sliceDepth - 1, openEndCount < 0 ? slice2.openEnd : sliceDepth - 1);
  }
  mustMoveInline() {
    if (!this.$to.parent.isTextblock)
      return -1;
    let top = this.frontier[this.depth], level;
    if (!top.type.isTextblock || !contentAfterFits(this.$to, this.$to.depth, top.type, top.match, false) || this.$to.depth == this.depth && (level = this.findCloseLevel(this.$to)) && level.depth == this.depth)
      return -1;
    let { depth } = this.$to, after = this.$to.after(depth);
    while (depth > 1 && after == this.$to.end(--depth))
      ++after;
    return after;
  }
  findCloseLevel($to) {
    scan: for (let i2 = Math.min(this.depth, $to.depth); i2 >= 0; i2--) {
      let { match: match2, type } = this.frontier[i2];
      let dropInner = i2 < $to.depth && $to.end(i2 + 1) == $to.pos + ($to.depth - (i2 + 1));
      let fit = contentAfterFits($to, i2, type, match2, dropInner);
      if (!fit)
        continue;
      for (let d2 = i2 - 1; d2 >= 0; d2--) {
        let { match: match3, type: type2 } = this.frontier[d2];
        let matches2 = contentAfterFits($to, d2, type2, match3, true);
        if (!matches2 || matches2.childCount)
          continue scan;
      }
      return { depth: i2, fit, move: dropInner ? $to.doc.resolve($to.after(i2 + 1)) : $to };
    }
  }
  close($to) {
    let close2 = this.findCloseLevel($to);
    if (!close2)
      return null;
    while (this.depth > close2.depth)
      this.closeFrontierNode();
    if (close2.fit.childCount)
      this.placed = addToFragment(this.placed, close2.depth, close2.fit);
    $to = close2.move;
    for (let d2 = close2.depth + 1; d2 <= $to.depth; d2++) {
      let node2 = $to.node(d2), add3 = node2.type.contentMatch.fillBefore(node2.content, true, $to.index(d2));
      this.openFrontierNode(node2.type, node2.attrs, add3);
    }
    return $to;
  }
  openFrontierNode(type, attrs2 = null, content) {
    let top = this.frontier[this.depth];
    top.match = top.match.matchType(type);
    this.placed = addToFragment(this.placed, this.depth, Fragment.from(type.create(attrs2, content)));
    this.frontier.push({ type, match: type.contentMatch });
  }
  closeFrontierNode() {
    let open2 = this.frontier.pop();
    let add3 = open2.match.fillBefore(Fragment.empty, true);
    if (add3.childCount)
      this.placed = addToFragment(this.placed, this.frontier.length, add3);
  }
}
function dropFromFragment(fragment, depth, count2) {
  if (depth == 0)
    return fragment.cutByIndex(count2, fragment.childCount);
  return fragment.replaceChild(0, fragment.firstChild.copy(dropFromFragment(fragment.firstChild.content, depth - 1, count2)));
}
__name(dropFromFragment, "dropFromFragment");
function addToFragment(fragment, depth, content) {
  if (depth == 0)
    return fragment.append(content);
  return fragment.replaceChild(fragment.childCount - 1, fragment.lastChild.copy(addToFragment(fragment.lastChild.content, depth - 1, content)));
}
__name(addToFragment, "addToFragment");
function contentAt(fragment, depth) {
  for (let i2 = 0; i2 < depth; i2++)
    fragment = fragment.firstChild.content;
  return fragment;
}
__name(contentAt, "contentAt");
function closeNodeStart(node2, openStart, openEnd) {
  if (openStart <= 0)
    return node2;
  let frag = node2.content;
  if (openStart > 1)
    frag = frag.replaceChild(0, closeNodeStart(frag.firstChild, openStart - 1, frag.childCount == 1 ? openEnd - 1 : 0));
  if (openStart > 0) {
    frag = node2.type.contentMatch.fillBefore(frag).append(frag);
    if (openEnd <= 0)
      frag = frag.append(node2.type.contentMatch.matchFragment(frag).fillBefore(Fragment.empty, true));
  }
  return node2.copy(frag);
}
__name(closeNodeStart, "closeNodeStart");
function contentAfterFits($to, depth, type, match2, open2) {
  let node2 = $to.node(depth), index2 = open2 ? $to.indexAfter(depth) : $to.index(depth);
  if (index2 == node2.childCount && !type.compatibleContent(node2.type))
    return null;
  let fit = match2.fillBefore(node2.content, true, index2);
  return fit && !invalidMarks(type, node2.content, index2) ? fit : null;
}
__name(contentAfterFits, "contentAfterFits");
function invalidMarks(type, fragment, start2) {
  for (let i2 = start2; i2 < fragment.childCount; i2++)
    if (!type.allowsMarks(fragment.child(i2).marks))
      return true;
  return false;
}
__name(invalidMarks, "invalidMarks");
function definesContent(type) {
  return type.spec.defining || type.spec.definingForContent;
}
__name(definesContent, "definesContent");
function replaceRange(tr2, from2, to, slice2) {
  if (!slice2.size)
    return tr2.deleteRange(from2, to);
  let $from = tr2.doc.resolve(from2), $to = tr2.doc.resolve(to);
  if (fitsTrivially($from, $to, slice2))
    return tr2.step(new ReplaceStep(from2, to, slice2));
  let targetDepths = coveredDepths($from, tr2.doc.resolve(to));
  if (targetDepths[targetDepths.length - 1] == 0)
    targetDepths.pop();
  let preferredTarget = -($from.depth + 1);
  targetDepths.unshift(preferredTarget);
  for (let d2 = $from.depth, pos = $from.pos - 1; d2 > 0; d2--, pos--) {
    let spec = $from.node(d2).type.spec;
    if (spec.defining || spec.definingAsContext || spec.isolating)
      break;
    if (targetDepths.indexOf(d2) > -1)
      preferredTarget = d2;
    else if ($from.before(d2) == pos)
      targetDepths.splice(1, 0, -d2);
  }
  let preferredTargetIndex = targetDepths.indexOf(preferredTarget);
  let leftNodes = [], preferredDepth = slice2.openStart;
  for (let content = slice2.content, i2 = 0; ; i2++) {
    let node2 = content.firstChild;
    leftNodes.push(node2);
    if (i2 == slice2.openStart)
      break;
    content = node2.content;
  }
  for (let d2 = preferredDepth - 1; d2 >= 0; d2--) {
    let leftNode = leftNodes[d2], def = definesContent(leftNode.type);
    if (def && !leftNode.sameMarkup($from.node(Math.abs(preferredTarget) - 1)))
      preferredDepth = d2;
    else if (def || !leftNode.type.isTextblock)
      break;
  }
  for (let j2 = slice2.openStart; j2 >= 0; j2--) {
    let openDepth = (j2 + preferredDepth + 1) % (slice2.openStart + 1);
    let insert = leftNodes[openDepth];
    if (!insert)
      continue;
    for (let i2 = 0; i2 < targetDepths.length; i2++) {
      let targetDepth = targetDepths[(i2 + preferredTargetIndex) % targetDepths.length], expand = true;
      if (targetDepth < 0) {
        expand = false;
        targetDepth = -targetDepth;
      }
      let parent2 = $from.node(targetDepth - 1), index2 = $from.index(targetDepth - 1);
      if (parent2.canReplaceWith(index2, index2, insert.type, insert.marks))
        return tr2.replace($from.before(targetDepth), expand ? $to.after(targetDepth) : to, new Slice(closeFragment(slice2.content, 0, slice2.openStart, openDepth), openDepth, slice2.openEnd));
    }
  }
  let startSteps = tr2.steps.length;
  for (let i2 = targetDepths.length - 1; i2 >= 0; i2--) {
    tr2.replace(from2, to, slice2);
    if (tr2.steps.length > startSteps)
      break;
    let depth = targetDepths[i2];
    if (depth < 0)
      continue;
    from2 = $from.before(depth);
    to = $to.after(depth);
  }
}
__name(replaceRange, "replaceRange");
function closeFragment(fragment, depth, oldOpen, newOpen, parent2) {
  if (depth < oldOpen) {
    let first2 = fragment.firstChild;
    fragment = fragment.replaceChild(0, first2.copy(closeFragment(first2.content, depth + 1, oldOpen, newOpen, first2)));
  }
  if (depth > newOpen) {
    let match2 = parent2.contentMatchAt(0);
    let start2 = match2.fillBefore(fragment).append(fragment);
    fragment = start2.append(match2.matchFragment(start2).fillBefore(Fragment.empty, true));
  }
  return fragment;
}
__name(closeFragment, "closeFragment");
function replaceRangeWith(tr2, from2, to, node2) {
  if (!node2.isInline && from2 == to && tr2.doc.resolve(from2).parent.content.size) {
    let point = insertPoint(tr2.doc, from2, node2.type);
    if (point != null)
      from2 = to = point;
  }
  tr2.replaceRange(from2, to, new Slice(Fragment.from(node2), 0, 0));
}
__name(replaceRangeWith, "replaceRangeWith");
function deleteRange$1(tr2, from2, to) {
  let $from = tr2.doc.resolve(from2), $to = tr2.doc.resolve(to);
  let covered = coveredDepths($from, $to);
  for (let i2 = 0; i2 < covered.length; i2++) {
    let depth = covered[i2], last = i2 == covered.length - 1;
    if (last && depth == 0 || $from.node(depth).type.contentMatch.validEnd)
      return tr2.delete($from.start(depth), $to.end(depth));
    if (depth > 0 && (last || $from.node(depth - 1).canReplace($from.index(depth - 1), $to.indexAfter(depth - 1))))
      return tr2.delete($from.before(depth), $to.after(depth));
  }
  for (let d2 = 1; d2 <= $from.depth && d2 <= $to.depth; d2++) {
    if (from2 - $from.start(d2) == $from.depth - d2 && to > $from.end(d2) && $to.end(d2) - to != $to.depth - d2 && $from.start(d2 - 1) == $to.start(d2 - 1) && $from.node(d2 - 1).canReplace($from.index(d2 - 1), $to.index(d2 - 1)))
      return tr2.delete($from.before(d2), to);
  }
  tr2.delete(from2, to);
}
__name(deleteRange$1, "deleteRange$1");
function coveredDepths($from, $to) {
  let result = [], minDepth = Math.min($from.depth, $to.depth);
  for (let d2 = minDepth; d2 >= 0; d2--) {
    let start2 = $from.start(d2);
    if (start2 < $from.pos - ($from.depth - d2) || $to.end(d2) > $to.pos + ($to.depth - d2) || $from.node(d2).type.spec.isolating || $to.node(d2).type.spec.isolating)
      break;
    if (start2 == $to.start(d2) || d2 == $from.depth && d2 == $to.depth && $from.parent.inlineContent && $to.parent.inlineContent && d2 && $to.start(d2 - 1) == start2 - 1)
      result.push(d2);
  }
  return result;
}
__name(coveredDepths, "coveredDepths");
class AttrStep extends Step {
  static {
    __name(this, "AttrStep");
  }
  /**
  Construct an attribute step.
  */
  constructor(pos, attr, value) {
    super();
    this.pos = pos;
    this.attr = attr;
    this.value = value;
  }
  apply(doc2) {
    let node2 = doc2.nodeAt(this.pos);
    if (!node2)
      return StepResult.fail("No node at attribute step's position");
    let attrs2 = /* @__PURE__ */ Object.create(null);
    for (let name2 in node2.attrs)
      attrs2[name2] = node2.attrs[name2];
    attrs2[this.attr] = this.value;
    let updated2 = node2.type.create(attrs2, null, node2.marks);
    return StepResult.fromReplace(doc2, this.pos, this.pos + 1, new Slice(Fragment.from(updated2), 0, node2.isLeaf ? 0 : 1));
  }
  getMap() {
    return StepMap.empty;
  }
  invert(doc2) {
    return new AttrStep(this.pos, this.attr, doc2.nodeAt(this.pos).attrs[this.attr]);
  }
  map(mapping) {
    let pos = mapping.mapResult(this.pos, 1);
    return pos.deletedAfter ? null : new AttrStep(pos.pos, this.attr, this.value);
  }
  toJSON() {
    return { stepType: "attr", pos: this.pos, attr: this.attr, value: this.value };
  }
  static fromJSON(schema2, json) {
    if (typeof json.pos != "number" || typeof json.attr != "string")
      throw new RangeError("Invalid input for AttrStep.fromJSON");
    return new AttrStep(json.pos, json.attr, json.value);
  }
}
Step.jsonID("attr", AttrStep);
class DocAttrStep extends Step {
  static {
    __name(this, "DocAttrStep");
  }
  /**
  Construct an attribute step.
  */
  constructor(attr, value) {
    super();
    this.attr = attr;
    this.value = value;
  }
  apply(doc2) {
    let attrs2 = /* @__PURE__ */ Object.create(null);
    for (let name2 in doc2.attrs)
      attrs2[name2] = doc2.attrs[name2];
    attrs2[this.attr] = this.value;
    let updated2 = doc2.type.create(attrs2, doc2.content, doc2.marks);
    return StepResult.ok(updated2);
  }
  getMap() {
    return StepMap.empty;
  }
  invert(doc2) {
    return new DocAttrStep(this.attr, doc2.attrs[this.attr]);
  }
  map(mapping) {
    return this;
  }
  toJSON() {
    return { stepType: "docAttr", attr: this.attr, value: this.value };
  }
  static fromJSON(schema2, json) {
    if (typeof json.attr != "string")
      throw new RangeError("Invalid input for DocAttrStep.fromJSON");
    return new DocAttrStep(json.attr, json.value);
  }
}
Step.jsonID("docAttr", DocAttrStep);
let TransformError = class extends Error {
  static {
    __name(this, "TransformError");
  }
};
TransformError = /* @__PURE__ */ __name(function TransformError2(message) {
  let err = Error.call(this, message);
  err.__proto__ = TransformError2.prototype;
  return err;
}, "TransformError");
TransformError.prototype = Object.create(Error.prototype);
TransformError.prototype.constructor = TransformError;
TransformError.prototype.name = "TransformError";
class Transform {
  static {
    __name(this, "Transform");
  }
  /**
  Create a transform that starts with the given document.
  */
  constructor(doc2) {
    this.doc = doc2;
    this.steps = [];
    this.docs = [];
    this.mapping = new Mapping();
  }
  /**
  The starting document.
  */
  get before() {
    return this.docs.length ? this.docs[0] : this.doc;
  }
  /**
  Apply a new step in this transform, saving the result. Throws an
  error when the step fails.
  */
  step(step) {
    let result = this.maybeStep(step);
    if (result.failed)
      throw new TransformError(result.failed);
    return this;
  }
  /**
  Try to apply a step in this transformation, ignoring it if it
  fails. Returns the step result.
  */
  maybeStep(step) {
    let result = step.apply(this.doc);
    if (!result.failed)
      this.addStep(step, result.doc);
    return result;
  }
  /**
  True when the document has been changed (when there are any
  steps).
  */
  get docChanged() {
    return this.steps.length > 0;
  }
  /**
  @internal
  */
  addStep(step, doc2) {
    this.docs.push(this.doc);
    this.steps.push(step);
    this.mapping.appendMap(step.getMap());
    this.doc = doc2;
  }
  /**
  Replace the part of the document between `from` and `to` with the
  given `slice`.
  */
  replace(from2, to = from2, slice2 = Slice.empty) {
    let step = replaceStep(this.doc, from2, to, slice2);
    if (step)
      this.step(step);
    return this;
  }
  /**
  Replace the given range with the given content, which may be a
  fragment, node, or array of nodes.
  */
  replaceWith(from2, to, content) {
    return this.replace(from2, to, new Slice(Fragment.from(content), 0, 0));
  }
  /**
  Delete the content between the given positions.
  */
  delete(from2, to) {
    return this.replace(from2, to, Slice.empty);
  }
  /**
  Insert the given content at the given position.
  */
  insert(pos, content) {
    return this.replaceWith(pos, pos, content);
  }
  /**
  Replace a range of the document with a given slice, using
  `from`, `to`, and the slice's
  [`openStart`](https://prosemirror.net/docs/ref/#model.Slice.openStart) property as hints, rather
  than fixed start and end points. This method may grow the
  replaced area or close open nodes in the slice in order to get a
  fit that is more in line with WYSIWYG expectations, by dropping
  fully covered parent nodes of the replaced region when they are
  marked [non-defining as
  context](https://prosemirror.net/docs/ref/#model.NodeSpec.definingAsContext), or including an
  open parent node from the slice that _is_ marked as [defining
  its content](https://prosemirror.net/docs/ref/#model.NodeSpec.definingForContent).
  
  This is the method, for example, to handle paste. The similar
  [`replace`](https://prosemirror.net/docs/ref/#transform.Transform.replace) method is a more
  primitive tool which will _not_ move the start and end of its given
  range, and is useful in situations where you need more precise
  control over what happens.
  */
  replaceRange(from2, to, slice2) {
    replaceRange(this, from2, to, slice2);
    return this;
  }
  /**
  Replace the given range with a node, but use `from` and `to` as
  hints, rather than precise positions. When from and to are the same
  and are at the start or end of a parent node in which the given
  node doesn't fit, this method may _move_ them out towards a parent
  that does allow the given node to be placed. When the given range
  completely covers a parent node, this method may completely replace
  that parent node.
  */
  replaceRangeWith(from2, to, node2) {
    replaceRangeWith(this, from2, to, node2);
    return this;
  }
  /**
  Delete the given range, expanding it to cover fully covered
  parent nodes until a valid replace is found.
  */
  deleteRange(from2, to) {
    deleteRange$1(this, from2, to);
    return this;
  }
  /**
  Split the content in the given range off from its parent, if there
  is sibling content before or after it, and move it up the tree to
  the depth specified by `target`. You'll probably want to use
  [`liftTarget`](https://prosemirror.net/docs/ref/#transform.liftTarget) to compute `target`, to make
  sure the lift is valid.
  */
  lift(range, target) {
    lift$2(this, range, target);
    return this;
  }
  /**
  Join the blocks around the given position. If depth is 2, their
  last and first siblings are also joined, and so on.
  */
  join(pos, depth = 1) {
    join(this, pos, depth);
    return this;
  }
  /**
  Wrap the given [range](https://prosemirror.net/docs/ref/#model.NodeRange) in the given set of wrappers.
  The wrappers are assumed to be valid in this position, and should
  probably be computed with [`findWrapping`](https://prosemirror.net/docs/ref/#transform.findWrapping).
  */
  wrap(range, wrappers) {
    wrap(this, range, wrappers);
    return this;
  }
  /**
  Set the type of all textblocks (partly) between `from` and `to` to
  the given node type with the given attributes.
  */
  setBlockType(from2, to = from2, type, attrs2 = null) {
    setBlockType$1(this, from2, to, type, attrs2);
    return this;
  }
  /**
  Change the type, attributes, and/or marks of the node at `pos`.
  When `type` isn't given, the existing node type is preserved,
  */
  setNodeMarkup(pos, type, attrs2 = null, marks) {
    setNodeMarkup(this, pos, type, attrs2, marks);
    return this;
  }
  /**
  Set a single attribute on a given node to a new value.
  The `pos` addresses the document content. Use `setDocAttribute`
  to set attributes on the document itself.
  */
  setNodeAttribute(pos, attr, value) {
    this.step(new AttrStep(pos, attr, value));
    return this;
  }
  /**
  Set a single attribute on the document to a new value.
  */
  setDocAttribute(attr, value) {
    this.step(new DocAttrStep(attr, value));
    return this;
  }
  /**
  Add a mark to the node at position `pos`.
  */
  addNodeMark(pos, mark) {
    this.step(new AddNodeMarkStep(pos, mark));
    return this;
  }
  /**
  Remove a mark (or a mark of the given type) from the node at
  position `pos`.
  */
  removeNodeMark(pos, mark) {
    if (!(mark instanceof Mark$1)) {
      let node2 = this.doc.nodeAt(pos);
      if (!node2)
        throw new RangeError("No node at position " + pos);
      mark = mark.isInSet(node2.marks);
      if (!mark)
        return this;
    }
    this.step(new RemoveNodeMarkStep(pos, mark));
    return this;
  }
  /**
  Split the node at the given position, and optionally, if `depth` is
  greater than one, any number of nodes above that. By default, the
  parts split off will inherit the node type of the original node.
  This can be changed by passing an array of types and attributes to
  use after the split.
  */
  split(pos, depth = 1, typesAfter) {
    split(this, pos, depth, typesAfter);
    return this;
  }
  /**
  Add the given mark to the inline content between `from` and `to`.
  */
  addMark(from2, to, mark) {
    addMark(this, from2, to, mark);
    return this;
  }
  /**
  Remove marks from inline nodes between `from` and `to`. When
  `mark` is a single mark, remove precisely that mark. When it is
  a mark type, remove all marks of that type. When it is null,
  remove all marks of any type.
  */
  removeMark(from2, to, mark) {
    removeMark(this, from2, to, mark);
    return this;
  }
  /**
  Removes all marks and nodes from the content of the node at
  `pos` that don't match the given new parent node type. Accepts
  an optional starting [content match](https://prosemirror.net/docs/ref/#model.ContentMatch) as
  third argument.
  */
  clearIncompatible(pos, parentType, match2) {
    clearIncompatible(this, pos, parentType, match2);
    return this;
  }
}
const classesById = /* @__PURE__ */ Object.create(null);
class Selection {
  static {
    __name(this, "Selection");
  }
  /**
  Initialize a selection with the head and anchor and ranges. If no
  ranges are given, constructs a single range across `$anchor` and
  `$head`.
  */
  constructor($anchor, $head, ranges) {
    this.$anchor = $anchor;
    this.$head = $head;
    this.ranges = ranges || [new SelectionRange($anchor.min($head), $anchor.max($head))];
  }
  /**
  The selection's anchor, as an unresolved position.
  */
  get anchor() {
    return this.$anchor.pos;
  }
  /**
  The selection's head.
  */
  get head() {
    return this.$head.pos;
  }
  /**
  The lower bound of the selection's main range.
  */
  get from() {
    return this.$from.pos;
  }
  /**
  The upper bound of the selection's main range.
  */
  get to() {
    return this.$to.pos;
  }
  /**
  The resolved lower  bound of the selection's main range.
  */
  get $from() {
    return this.ranges[0].$from;
  }
  /**
  The resolved upper bound of the selection's main range.
  */
  get $to() {
    return this.ranges[0].$to;
  }
  /**
  Indicates whether the selection contains any content.
  */
  get empty() {
    let ranges = this.ranges;
    for (let i2 = 0; i2 < ranges.length; i2++)
      if (ranges[i2].$from.pos != ranges[i2].$to.pos)
        return false;
    return true;
  }
  /**
  Get the content of this selection as a slice.
  */
  content() {
    return this.$from.doc.slice(this.from, this.to, true);
  }
  /**
  Replace the selection with a slice or, if no slice is given,
  delete the selection. Will append to the given transaction.
  */
  replace(tr2, content = Slice.empty) {
    let lastNode = content.content.lastChild, lastParent = null;
    for (let i2 = 0; i2 < content.openEnd; i2++) {
      lastParent = lastNode;
      lastNode = lastNode.lastChild;
    }
    let mapFrom = tr2.steps.length, ranges = this.ranges;
    for (let i2 = 0; i2 < ranges.length; i2++) {
      let { $from, $to } = ranges[i2], mapping = tr2.mapping.slice(mapFrom);
      tr2.replaceRange(mapping.map($from.pos), mapping.map($to.pos), i2 ? Slice.empty : content);
      if (i2 == 0)
        selectionToInsertionEnd$1(tr2, mapFrom, (lastNode ? lastNode.isInline : lastParent && lastParent.isTextblock) ? -1 : 1);
    }
  }
  /**
  Replace the selection with the given node, appending the changes
  to the given transaction.
  */
  replaceWith(tr2, node2) {
    let mapFrom = tr2.steps.length, ranges = this.ranges;
    for (let i2 = 0; i2 < ranges.length; i2++) {
      let { $from, $to } = ranges[i2], mapping = tr2.mapping.slice(mapFrom);
      let from2 = mapping.map($from.pos), to = mapping.map($to.pos);
      if (i2) {
        tr2.deleteRange(from2, to);
      } else {
        tr2.replaceRangeWith(from2, to, node2);
        selectionToInsertionEnd$1(tr2, mapFrom, node2.isInline ? -1 : 1);
      }
    }
  }
  /**
  Find a valid cursor or leaf node selection starting at the given
  position and searching back if `dir` is negative, and forward if
  positive. When `textOnly` is true, only consider cursor
  selections. Will return null when no valid selection position is
  found.
  */
  static findFrom($pos, dir, textOnly = false) {
    let inner = $pos.parent.inlineContent ? new TextSelection($pos) : findSelectionIn($pos.node(0), $pos.parent, $pos.pos, $pos.index(), dir, textOnly);
    if (inner)
      return inner;
    for (let depth = $pos.depth - 1; depth >= 0; depth--) {
      let found2 = dir < 0 ? findSelectionIn($pos.node(0), $pos.node(depth), $pos.before(depth + 1), $pos.index(depth), dir, textOnly) : findSelectionIn($pos.node(0), $pos.node(depth), $pos.after(depth + 1), $pos.index(depth) + 1, dir, textOnly);
      if (found2)
        return found2;
    }
    return null;
  }
  /**
  Find a valid cursor or leaf node selection near the given
  position. Searches forward first by default, but if `bias` is
  negative, it will search backwards first.
  */
  static near($pos, bias = 1) {
    return this.findFrom($pos, bias) || this.findFrom($pos, -bias) || new AllSelection($pos.node(0));
  }
  /**
  Find the cursor or leaf node selection closest to the start of
  the given document. Will return an
  [`AllSelection`](https://prosemirror.net/docs/ref/#state.AllSelection) if no valid position
  exists.
  */
  static atStart(doc2) {
    return findSelectionIn(doc2, doc2, 0, 0, 1) || new AllSelection(doc2);
  }
  /**
  Find the cursor or leaf node selection closest to the end of the
  given document.
  */
  static atEnd(doc2) {
    return findSelectionIn(doc2, doc2, doc2.content.size, doc2.childCount, -1) || new AllSelection(doc2);
  }
  /**
  Deserialize the JSON representation of a selection. Must be
  implemented for custom classes (as a static class method).
  */
  static fromJSON(doc2, json) {
    if (!json || !json.type)
      throw new RangeError("Invalid input for Selection.fromJSON");
    let cls = classesById[json.type];
    if (!cls)
      throw new RangeError(`No selection type ${json.type} defined`);
    return cls.fromJSON(doc2, json);
  }
  /**
  To be able to deserialize selections from JSON, custom selection
  classes must register themselves with an ID string, so that they
  can be disambiguated. Try to pick something that's unlikely to
  clash with classes from other modules.
  */
  static jsonID(id2, selectionClass) {
    if (id2 in classesById)
      throw new RangeError("Duplicate use of selection JSON ID " + id2);
    classesById[id2] = selectionClass;
    selectionClass.prototype.jsonID = id2;
    return selectionClass;
  }
  /**
  Get a [bookmark](https://prosemirror.net/docs/ref/#state.SelectionBookmark) for this selection,
  which is a value that can be mapped without having access to a
  current document, and later resolved to a real selection for a
  given document again. (This is used mostly by the history to
  track and restore old selections.) The default implementation of
  this method just converts the selection to a text selection and
  returns the bookmark for that.
  */
  getBookmark() {
    return TextSelection.between(this.$anchor, this.$head).getBookmark();
  }
}
Selection.prototype.visible = true;
class SelectionRange {
  static {
    __name(this, "SelectionRange");
  }
  /**
  Create a range.
  */
  constructor($from, $to) {
    this.$from = $from;
    this.$to = $to;
  }
}
let warnedAboutTextSelection = false;
function checkTextSelection($pos) {
  if (!warnedAboutTextSelection && !$pos.parent.inlineContent) {
    warnedAboutTextSelection = true;
    console["warn"]("TextSelection endpoint not pointing into a node with inline content (" + $pos.parent.type.name + ")");
  }
}
__name(checkTextSelection, "checkTextSelection");
class TextSelection extends Selection {
  static {
    __name(this, "TextSelection");
  }
  /**
  Construct a text selection between the given points.
  */
  constructor($anchor, $head = $anchor) {
    checkTextSelection($anchor);
    checkTextSelection($head);
    super($anchor, $head);
  }
  /**
  Returns a resolved position if this is a cursor selection (an
  empty text selection), and null otherwise.
  */
  get $cursor() {
    return this.$anchor.pos == this.$head.pos ? this.$head : null;
  }
  map(doc2, mapping) {
    let $head = doc2.resolve(mapping.map(this.head));
    if (!$head.parent.inlineContent)
      return Selection.near($head);
    let $anchor = doc2.resolve(mapping.map(this.anchor));
    return new TextSelection($anchor.parent.inlineContent ? $anchor : $head, $head);
  }
  replace(tr2, content = Slice.empty) {
    super.replace(tr2, content);
    if (content == Slice.empty) {
      let marks = this.$from.marksAcross(this.$to);
      if (marks)
        tr2.ensureMarks(marks);
    }
  }
  eq(other) {
    return other instanceof TextSelection && other.anchor == this.anchor && other.head == this.head;
  }
  getBookmark() {
    return new TextBookmark(this.anchor, this.head);
  }
  toJSON() {
    return { type: "text", anchor: this.anchor, head: this.head };
  }
  /**
  @internal
  */
  static fromJSON(doc2, json) {
    if (typeof json.anchor != "number" || typeof json.head != "number")
      throw new RangeError("Invalid input for TextSelection.fromJSON");
    return new TextSelection(doc2.resolve(json.anchor), doc2.resolve(json.head));
  }
  /**
  Create a text selection from non-resolved positions.
  */
  static create(doc2, anchor, head = anchor) {
    let $anchor = doc2.resolve(anchor);
    return new this($anchor, head == anchor ? $anchor : doc2.resolve(head));
  }
  /**
  Return a text selection that spans the given positions or, if
  they aren't text positions, find a text selection near them.
  `bias` determines whether the method searches forward (default)
  or backwards (negative number) first. Will fall back to calling
  [`Selection.near`](https://prosemirror.net/docs/ref/#state.Selection^near) when the document
  doesn't contain a valid text position.
  */
  static between($anchor, $head, bias) {
    let dPos = $anchor.pos - $head.pos;
    if (!bias || dPos)
      bias = dPos >= 0 ? 1 : -1;
    if (!$head.parent.inlineContent) {
      let found2 = Selection.findFrom($head, bias, true) || Selection.findFrom($head, -bias, true);
      if (found2)
        $head = found2.$head;
      else
        return Selection.near($head, bias);
    }
    if (!$anchor.parent.inlineContent) {
      if (dPos == 0) {
        $anchor = $head;
      } else {
        $anchor = (Selection.findFrom($anchor, -bias, true) || Selection.findFrom($anchor, bias, true)).$anchor;
        if ($anchor.pos < $head.pos != dPos < 0)
          $anchor = $head;
      }
    }
    return new TextSelection($anchor, $head);
  }
}
Selection.jsonID("text", TextSelection);
class TextBookmark {
  static {
    __name(this, "TextBookmark");
  }
  constructor(anchor, head) {
    this.anchor = anchor;
    this.head = head;
  }
  map(mapping) {
    return new TextBookmark(mapping.map(this.anchor), mapping.map(this.head));
  }
  resolve(doc2) {
    return TextSelection.between(doc2.resolve(this.anchor), doc2.resolve(this.head));
  }
}
class NodeSelection extends Selection {
  static {
    __name(this, "NodeSelection");
  }
  /**
  Create a node selection. Does not verify the validity of its
  argument.
  */
  constructor($pos) {
    let node2 = $pos.nodeAfter;
    let $end = $pos.node(0).resolve($pos.pos + node2.nodeSize);
    super($pos, $end);
    this.node = node2;
  }
  map(doc2, mapping) {
    let { deleted, pos } = mapping.mapResult(this.anchor);
    let $pos = doc2.resolve(pos);
    if (deleted)
      return Selection.near($pos);
    return new NodeSelection($pos);
  }
  content() {
    return new Slice(Fragment.from(this.node), 0, 0);
  }
  eq(other) {
    return other instanceof NodeSelection && other.anchor == this.anchor;
  }
  toJSON() {
    return { type: "node", anchor: this.anchor };
  }
  getBookmark() {
    return new NodeBookmark(this.anchor);
  }
  /**
  @internal
  */
  static fromJSON(doc2, json) {
    if (typeof json.anchor != "number")
      throw new RangeError("Invalid input for NodeSelection.fromJSON");
    return new NodeSelection(doc2.resolve(json.anchor));
  }
  /**
  Create a node selection from non-resolved positions.
  */
  static create(doc2, from2) {
    return new NodeSelection(doc2.resolve(from2));
  }
  /**
  Determines whether the given node may be selected as a node
  selection.
  */
  static isSelectable(node2) {
    return !node2.isText && node2.type.spec.selectable !== false;
  }
}
NodeSelection.prototype.visible = false;
Selection.jsonID("node", NodeSelection);
class NodeBookmark {
  static {
    __name(this, "NodeBookmark");
  }
  constructor(anchor) {
    this.anchor = anchor;
  }
  map(mapping) {
    let { deleted, pos } = mapping.mapResult(this.anchor);
    return deleted ? new TextBookmark(pos, pos) : new NodeBookmark(pos);
  }
  resolve(doc2) {
    let $pos = doc2.resolve(this.anchor), node2 = $pos.nodeAfter;
    if (node2 && NodeSelection.isSelectable(node2))
      return new NodeSelection($pos);
    return Selection.near($pos);
  }
}
class AllSelection extends Selection {
  static {
    __name(this, "AllSelection");
  }
  /**
  Create an all-selection over the given document.
  */
  constructor(doc2) {
    super(doc2.resolve(0), doc2.resolve(doc2.content.size));
  }
  replace(tr2, content = Slice.empty) {
    if (content == Slice.empty) {
      tr2.delete(0, tr2.doc.content.size);
      let sel = Selection.atStart(tr2.doc);
      if (!sel.eq(tr2.selection))
        tr2.setSelection(sel);
    } else {
      super.replace(tr2, content);
    }
  }
  toJSON() {
    return { type: "all" };
  }
  /**
  @internal
  */
  static fromJSON(doc2) {
    return new AllSelection(doc2);
  }
  map(doc2) {
    return new AllSelection(doc2);
  }
  eq(other) {
    return other instanceof AllSelection;
  }
  getBookmark() {
    return AllBookmark;
  }
}
Selection.jsonID("all", AllSelection);
const AllBookmark = {
  map() {
    return this;
  },
  resolve(doc2) {
    return new AllSelection(doc2);
  }
};
function findSelectionIn(doc2, node2, pos, index2, dir, text2 = false) {
  if (node2.inlineContent)
    return TextSelection.create(doc2, pos);
  for (let i2 = index2 - (dir > 0 ? 0 : 1); dir > 0 ? i2 < node2.childCount : i2 >= 0; i2 += dir) {
    let child2 = node2.child(i2);
    if (!child2.isAtom) {
      let inner = findSelectionIn(doc2, child2, pos + dir, dir < 0 ? child2.childCount : 0, dir, text2);
      if (inner)
        return inner;
    } else if (!text2 && NodeSelection.isSelectable(child2)) {
      return NodeSelection.create(doc2, pos - (dir < 0 ? child2.nodeSize : 0));
    }
    pos += child2.nodeSize * dir;
  }
  return null;
}
__name(findSelectionIn, "findSelectionIn");
function selectionToInsertionEnd$1(tr2, startLen, bias) {
  let last = tr2.steps.length - 1;
  if (last < startLen)
    return;
  let step = tr2.steps[last];
  if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep))
    return;
  let map3 = tr2.mapping.maps[last], end;
  map3.forEach((_from, _to, _newFrom, newTo) => {
    if (end == null)
      end = newTo;
  });
  tr2.setSelection(Selection.near(tr2.doc.resolve(end), bias));
}
__name(selectionToInsertionEnd$1, "selectionToInsertionEnd$1");
const UPDATED_SEL = 1, UPDATED_MARKS = 2, UPDATED_SCROLL = 4;
class Transaction extends Transform {
  static {
    __name(this, "Transaction");
  }
  /**
  @internal
  */
  constructor(state) {
    super(state.doc);
    this.curSelectionFor = 0;
    this.updated = 0;
    this.meta = /* @__PURE__ */ Object.create(null);
    this.time = Date.now();
    this.curSelection = state.selection;
    this.storedMarks = state.storedMarks;
  }
  /**
  The transaction's current selection. This defaults to the editor
  selection [mapped](https://prosemirror.net/docs/ref/#state.Selection.map) through the steps in the
  transaction, but can be overwritten with
  [`setSelection`](https://prosemirror.net/docs/ref/#state.Transaction.setSelection).
  */
  get selection() {
    if (this.curSelectionFor < this.steps.length) {
      this.curSelection = this.curSelection.map(this.doc, this.mapping.slice(this.curSelectionFor));
      this.curSelectionFor = this.steps.length;
    }
    return this.curSelection;
  }
  /**
  Update the transaction's current selection. Will determine the
  selection that the editor gets when the transaction is applied.
  */
  setSelection(selection) {
    if (selection.$from.doc != this.doc)
      throw new RangeError("Selection passed to setSelection must point at the current document");
    this.curSelection = selection;
    this.curSelectionFor = this.steps.length;
    this.updated = (this.updated | UPDATED_SEL) & ~UPDATED_MARKS;
    this.storedMarks = null;
    return this;
  }
  /**
  Whether the selection was explicitly updated by this transaction.
  */
  get selectionSet() {
    return (this.updated & UPDATED_SEL) > 0;
  }
  /**
  Set the current stored marks.
  */
  setStoredMarks(marks) {
    this.storedMarks = marks;
    this.updated |= UPDATED_MARKS;
    return this;
  }
  /**
  Make sure the current stored marks or, if that is null, the marks
  at the selection, match the given set of marks. Does nothing if
  this is already the case.
  */
  ensureMarks(marks) {
    if (!Mark$1.sameSet(this.storedMarks || this.selection.$from.marks(), marks))
      this.setStoredMarks(marks);
    return this;
  }
  /**
  Add a mark to the set of stored marks.
  */
  addStoredMark(mark) {
    return this.ensureMarks(mark.addToSet(this.storedMarks || this.selection.$head.marks()));
  }
  /**
  Remove a mark or mark type from the set of stored marks.
  */
  removeStoredMark(mark) {
    return this.ensureMarks(mark.removeFromSet(this.storedMarks || this.selection.$head.marks()));
  }
  /**
  Whether the stored marks were explicitly set for this transaction.
  */
  get storedMarksSet() {
    return (this.updated & UPDATED_MARKS) > 0;
  }
  /**
  @internal
  */
  addStep(step, doc2) {
    super.addStep(step, doc2);
    this.updated = this.updated & ~UPDATED_MARKS;
    this.storedMarks = null;
  }
  /**
  Update the timestamp for the transaction.
  */
  setTime(time) {
    this.time = time;
    return this;
  }
  /**
  Replace the current selection with the given slice.
  */
  replaceSelection(slice2) {
    this.selection.replace(this, slice2);
    return this;
  }
  /**
  Replace the selection with the given node. When `inheritMarks` is
  true and the content is inline, it inherits the marks from the
  place where it is inserted.
  */
  replaceSelectionWith(node2, inheritMarks = true) {
    let selection = this.selection;
    if (inheritMarks)
      node2 = node2.mark(this.storedMarks || (selection.empty ? selection.$from.marks() : selection.$from.marksAcross(selection.$to) || Mark$1.none));
    selection.replaceWith(this, node2);
    return this;
  }
  /**
  Delete the selection.
  */
  deleteSelection() {
    this.selection.replace(this);
    return this;
  }
  /**
  Replace the given range, or the selection if no range is given,
  with a text node containing the given string.
  */
  insertText(text2, from2, to) {
    let schema2 = this.doc.type.schema;
    if (from2 == null) {
      if (!text2)
        return this.deleteSelection();
      return this.replaceSelectionWith(schema2.text(text2), true);
    } else {
      if (to == null)
        to = from2;
      to = to == null ? from2 : to;
      if (!text2)
        return this.deleteRange(from2, to);
      let marks = this.storedMarks;
      if (!marks) {
        let $from = this.doc.resolve(from2);
        marks = to == from2 ? $from.marks() : $from.marksAcross(this.doc.resolve(to));
      }
      this.replaceRangeWith(from2, to, schema2.text(text2, marks));
      if (!this.selection.empty)
        this.setSelection(Selection.near(this.selection.$to));
      return this;
    }
  }
  /**
  Store a metadata property in this transaction, keyed either by
  name or by plugin.
  */
  setMeta(key, value) {
    this.meta[typeof key == "string" ? key : key.key] = value;
    return this;
  }
  /**
  Retrieve a metadata property for a given name or plugin.
  */
  getMeta(key) {
    return this.meta[typeof key == "string" ? key : key.key];
  }
  /**
  Returns true if this transaction doesn't contain any metadata,
  and can thus safely be extended.
  */
  get isGeneric() {
    for (let _2 in this.meta)
      return false;
    return true;
  }
  /**
  Indicate that the editor should scroll the selection into view
  when updated to the state produced by this transaction.
  */
  scrollIntoView() {
    this.updated |= UPDATED_SCROLL;
    return this;
  }
  /**
  True when this transaction has had `scrollIntoView` called on it.
  */
  get scrolledIntoView() {
    return (this.updated & UPDATED_SCROLL) > 0;
  }
}
function bind$2(f2, self2) {
  return !self2 || !f2 ? f2 : f2.bind(self2);
}
__name(bind$2, "bind$2");
class FieldDesc {
  static {
    __name(this, "FieldDesc");
  }
  constructor(name2, desc, self2) {
    this.name = name2;
    this.init = bind$2(desc.init, self2);
    this.apply = bind$2(desc.apply, self2);
  }
}
const baseFields = [
  new FieldDesc("doc", {
    init(config2) {
      return config2.doc || config2.schema.topNodeType.createAndFill();
    },
    apply(tr2) {
      return tr2.doc;
    }
  }),
  new FieldDesc("selection", {
    init(config2, instance) {
      return config2.selection || Selection.atStart(instance.doc);
    },
    apply(tr2) {
      return tr2.selection;
    }
  }),
  new FieldDesc("storedMarks", {
    init(config2) {
      return config2.storedMarks || null;
    },
    apply(tr2, _marks, _old, state) {
      return state.selection.$cursor ? tr2.storedMarks : null;
    }
  }),
  new FieldDesc("scrollToSelection", {
    init() {
      return 0;
    },
    apply(tr2, prev) {
      return tr2.scrolledIntoView ? prev + 1 : prev;
    }
  })
];
class Configuration {
  static {
    __name(this, "Configuration");
  }
  constructor(schema2, plugins) {
    this.schema = schema2;
    this.plugins = [];
    this.pluginsByKey = /* @__PURE__ */ Object.create(null);
    this.fields = baseFields.slice();
    if (plugins)
      plugins.forEach((plugin) => {
        if (this.pluginsByKey[plugin.key])
          throw new RangeError("Adding different instances of a keyed plugin (" + plugin.key + ")");
        this.plugins.push(plugin);
        this.pluginsByKey[plugin.key] = plugin;
        if (plugin.spec.state)
          this.fields.push(new FieldDesc(plugin.key, plugin.spec.state, plugin));
      });
  }
}
class EditorState {
  static {
    __name(this, "EditorState");
  }
  /**
  @internal
  */
  constructor(config2) {
    this.config = config2;
  }
  /**
  The schema of the state's document.
  */
  get schema() {
    return this.config.schema;
  }
  /**
  The plugins that are active in this state.
  */
  get plugins() {
    return this.config.plugins;
  }
  /**
  Apply the given transaction to produce a new state.
  */
  apply(tr2) {
    return this.applyTransaction(tr2).state;
  }
  /**
  @internal
  */
  filterTransaction(tr2, ignore = -1) {
    for (let i2 = 0; i2 < this.config.plugins.length; i2++)
      if (i2 != ignore) {
        let plugin = this.config.plugins[i2];
        if (plugin.spec.filterTransaction && !plugin.spec.filterTransaction.call(plugin, tr2, this))
          return false;
      }
    return true;
  }
  /**
  Verbose variant of [`apply`](https://prosemirror.net/docs/ref/#state.EditorState.apply) that
  returns the precise transactions that were applied (which might
  be influenced by the [transaction
  hooks](https://prosemirror.net/docs/ref/#state.PluginSpec.filterTransaction) of
  plugins) along with the new state.
  */
  applyTransaction(rootTr) {
    if (!this.filterTransaction(rootTr))
      return { state: this, transactions: [] };
    let trs = [rootTr], newState = this.applyInner(rootTr), seen2 = null;
    for (; ; ) {
      let haveNew = false;
      for (let i2 = 0; i2 < this.config.plugins.length; i2++) {
        let plugin = this.config.plugins[i2];
        if (plugin.spec.appendTransaction) {
          let n2 = seen2 ? seen2[i2].n : 0, oldState = seen2 ? seen2[i2].state : this;
          let tr2 = n2 < trs.length && plugin.spec.appendTransaction.call(plugin, n2 ? trs.slice(n2) : trs, oldState, newState);
          if (tr2 && newState.filterTransaction(tr2, i2)) {
            tr2.setMeta("appendedTransaction", rootTr);
            if (!seen2) {
              seen2 = [];
              for (let j2 = 0; j2 < this.config.plugins.length; j2++)
                seen2.push(j2 < i2 ? { state: newState, n: trs.length } : { state: this, n: 0 });
            }
            trs.push(tr2);
            newState = newState.applyInner(tr2);
            haveNew = true;
          }
          if (seen2)
            seen2[i2] = { state: newState, n: trs.length };
        }
      }
      if (!haveNew)
        return { state: newState, transactions: trs };
    }
  }
  /**
  @internal
  */
  applyInner(tr2) {
    if (!tr2.before.eq(this.doc))
      throw new RangeError("Applying a mismatched transaction");
    let newInstance = new EditorState(this.config), fields = this.config.fields;
    for (let i2 = 0; i2 < fields.length; i2++) {
      let field2 = fields[i2];
      newInstance[field2.name] = field2.apply(tr2, this[field2.name], this, newInstance);
    }
    return newInstance;
  }
  /**
  Start a [transaction](https://prosemirror.net/docs/ref/#state.Transaction) from this state.
  */
  get tr() {
    return new Transaction(this);
  }
  /**
  Create a new state.
  */
  static create(config2) {
    let $config = new Configuration(config2.doc ? config2.doc.type.schema : config2.schema, config2.plugins);
    let instance = new EditorState($config);
    for (let i2 = 0; i2 < $config.fields.length; i2++)
      instance[$config.fields[i2].name] = $config.fields[i2].init(config2, instance);
    return instance;
  }
  /**
  Create a new state based on this one, but with an adjusted set
  of active plugins. State fields that exist in both sets of
  plugins are kept unchanged. Those that no longer exist are
  dropped, and those that are new are initialized using their
  [`init`](https://prosemirror.net/docs/ref/#state.StateField.init) method, passing in the new
  configuration object..
  */
  reconfigure(config2) {
    let $config = new Configuration(this.schema, config2.plugins);
    let fields = $config.fields, instance = new EditorState($config);
    for (let i2 = 0; i2 < fields.length; i2++) {
      let name2 = fields[i2].name;
      instance[name2] = this.hasOwnProperty(name2) ? this[name2] : fields[i2].init(config2, instance);
    }
    return instance;
  }
  /**
  Serialize this state to JSON. If you want to serialize the state
  of plugins, pass an object mapping property names to use in the
  resulting JSON object to plugin objects. The argument may also be
  a string or number, in which case it is ignored, to support the
  way `JSON.stringify` calls `toString` methods.
  */
  toJSON(pluginFields) {
    let result = { doc: this.doc.toJSON(), selection: this.selection.toJSON() };
    if (this.storedMarks)
      result.storedMarks = this.storedMarks.map((m2) => m2.toJSON());
    if (pluginFields && typeof pluginFields == "object")
      for (let prop2 in pluginFields) {
        if (prop2 == "doc" || prop2 == "selection")
          throw new RangeError("The JSON fields `doc` and `selection` are reserved");
        let plugin = pluginFields[prop2], state = plugin.spec.state;
        if (state && state.toJSON)
          result[prop2] = state.toJSON.call(plugin, this[plugin.key]);
      }
    return result;
  }
  /**
  Deserialize a JSON representation of a state. `config` should
  have at least a `schema` field, and should contain array of
  plugins to initialize the state with. `pluginFields` can be used
  to deserialize the state of plugins, by associating plugin
  instances with the property names they use in the JSON object.
  */
  static fromJSON(config2, json, pluginFields) {
    if (!json)
      throw new RangeError("Invalid input for EditorState.fromJSON");
    if (!config2.schema)
      throw new RangeError("Required config field 'schema' missing");
    let $config = new Configuration(config2.schema, config2.plugins);
    let instance = new EditorState($config);
    $config.fields.forEach((field2) => {
      if (field2.name == "doc") {
        instance.doc = Node$2.fromJSON(config2.schema, json.doc);
      } else if (field2.name == "selection") {
        instance.selection = Selection.fromJSON(instance.doc, json.selection);
      } else if (field2.name == "storedMarks") {
        if (json.storedMarks)
          instance.storedMarks = json.storedMarks.map(config2.schema.markFromJSON);
      } else {
        if (pluginFields)
          for (let prop2 in pluginFields) {
            let plugin = pluginFields[prop2], state = plugin.spec.state;
            if (plugin.key == field2.name && state && state.fromJSON && Object.prototype.hasOwnProperty.call(json, prop2)) {
              instance[field2.name] = state.fromJSON.call(plugin, config2, json[prop2], instance);
              return;
            }
          }
        instance[field2.name] = field2.init(config2, instance);
      }
    });
    return instance;
  }
}
function bindProps(obj, self2, target) {
  for (let prop2 in obj) {
    let val = obj[prop2];
    if (val instanceof Function)
      val = val.bind(self2);
    else if (prop2 == "handleDOMEvents")
      val = bindProps(val, self2, {});
    target[prop2] = val;
  }
  return target;
}
__name(bindProps, "bindProps");
class Plugin {
  static {
    __name(this, "Plugin");
  }
  /**
  Create a plugin.
  */
  constructor(spec) {
    this.spec = spec;
    this.props = {};
    if (spec.props)
      bindProps(spec.props, this, this.props);
    this.key = spec.key ? spec.key.key : createKey$1("plugin");
  }
  /**
  Extract the plugin's state field from an editor state.
  */
  getState(state) {
    return state[this.key];
  }
}
const keys = /* @__PURE__ */ Object.create(null);
function createKey$1(name2) {
  if (name2 in keys)
    return name2 + "$" + ++keys[name2];
  keys[name2] = 0;
  return name2 + "$";
}
__name(createKey$1, "createKey$1");
class PluginKey {
  static {
    __name(this, "PluginKey");
  }
  /**
  Create a plugin key.
  */
  constructor(name2 = "key") {
    this.key = createKey$1(name2);
  }
  /**
  Get the active plugin with this key, if any, from an editor
  state.
  */
  get(state) {
    return state.config.pluginsByKey[this.key];
  }
  /**
  Get the plugin's state from an editor state.
  */
  getState(state) {
    return state[this.key];
  }
}
const domIndex = /* @__PURE__ */ __name(function(node2) {
  for (var index2 = 0; ; index2++) {
    node2 = node2.previousSibling;
    if (!node2)
      return index2;
  }
}, "domIndex");
const parentNode = /* @__PURE__ */ __name(function(node2) {
  let parent2 = node2.assignedSlot || node2.parentNode;
  return parent2 && parent2.nodeType == 11 ? parent2.host : parent2;
}, "parentNode");
let reusedRange = null;
const textRange = /* @__PURE__ */ __name(function(node2, from2, to) {
  let range = reusedRange || (reusedRange = document.createRange());
  range.setEnd(node2, to == null ? node2.nodeValue.length : to);
  range.setStart(node2, from2 || 0);
  return range;
}, "textRange");
const clearReusedRange = /* @__PURE__ */ __name(function() {
  reusedRange = null;
}, "clearReusedRange");
const isEquivalentPosition = /* @__PURE__ */ __name(function(node2, off2, targetNode, targetOff) {
  return targetNode && (scanFor(node2, off2, targetNode, targetOff, -1) || scanFor(node2, off2, targetNode, targetOff, 1));
}, "isEquivalentPosition");
const atomElements = /^(img|br|input|textarea|hr)$/i;
function scanFor(node2, off2, targetNode, targetOff, dir) {
  for (; ; ) {
    if (node2 == targetNode && off2 == targetOff)
      return true;
    if (off2 == (dir < 0 ? 0 : nodeSize(node2))) {
      let parent2 = node2.parentNode;
      if (!parent2 || parent2.nodeType != 1 || hasBlockDesc(node2) || atomElements.test(node2.nodeName) || node2.contentEditable == "false")
        return false;
      off2 = domIndex(node2) + (dir < 0 ? 0 : 1);
      node2 = parent2;
    } else if (node2.nodeType == 1) {
      node2 = node2.childNodes[off2 + (dir < 0 ? -1 : 0)];
      if (node2.contentEditable == "false")
        return false;
      off2 = dir < 0 ? nodeSize(node2) : 0;
    } else {
      return false;
    }
  }
}
__name(scanFor, "scanFor");
function nodeSize(node2) {
  return node2.nodeType == 3 ? node2.nodeValue.length : node2.childNodes.length;
}
__name(nodeSize, "nodeSize");
function textNodeBefore$1(node2, offset) {
  for (; ; ) {
    if (node2.nodeType == 3 && offset)
      return node2;
    if (node2.nodeType == 1 && offset > 0) {
      if (node2.contentEditable == "false")
        return null;
      node2 = node2.childNodes[offset - 1];
      offset = nodeSize(node2);
    } else if (node2.parentNode && !hasBlockDesc(node2)) {
      offset = domIndex(node2);
      node2 = node2.parentNode;
    } else {
      return null;
    }
  }
}
__name(textNodeBefore$1, "textNodeBefore$1");
function textNodeAfter$1(node2, offset) {
  for (; ; ) {
    if (node2.nodeType == 3 && offset < node2.nodeValue.length)
      return node2;
    if (node2.nodeType == 1 && offset < node2.childNodes.length) {
      if (node2.contentEditable == "false")
        return null;
      node2 = node2.childNodes[offset];
      offset = 0;
    } else if (node2.parentNode && !hasBlockDesc(node2)) {
      offset = domIndex(node2) + 1;
      node2 = node2.parentNode;
    } else {
      return null;
    }
  }
}
__name(textNodeAfter$1, "textNodeAfter$1");
function isOnEdge(node2, offset, parent2) {
  for (let atStart = offset == 0, atEnd = offset == nodeSize(node2); atStart || atEnd; ) {
    if (node2 == parent2)
      return true;
    let index2 = domIndex(node2);
    node2 = node2.parentNode;
    if (!node2)
      return false;
    atStart = atStart && index2 == 0;
    atEnd = atEnd && index2 == nodeSize(node2);
  }
}
__name(isOnEdge, "isOnEdge");
function hasBlockDesc(dom) {
  let desc;
  for (let cur = dom; cur; cur = cur.parentNode)
    if (desc = cur.pmViewDesc)
      break;
  return desc && desc.node && desc.node.isBlock && (desc.dom == dom || desc.contentDOM == dom);
}
__name(hasBlockDesc, "hasBlockDesc");
const selectionCollapsed = /* @__PURE__ */ __name(function(domSel) {
  return domSel.focusNode && isEquivalentPosition(domSel.focusNode, domSel.focusOffset, domSel.anchorNode, domSel.anchorOffset);
}, "selectionCollapsed");
function keyEvent(keyCode, key) {
  let event = document.createEvent("Event");
  event.initEvent("keydown", true, true);
  event.keyCode = keyCode;
  event.key = event.code = key;
  return event;
}
__name(keyEvent, "keyEvent");
function deepActiveElement(doc2) {
  let elt = doc2.activeElement;
  while (elt && elt.shadowRoot)
    elt = elt.shadowRoot.activeElement;
  return elt;
}
__name(deepActiveElement, "deepActiveElement");
function caretFromPoint(doc2, x2, y2) {
  if (doc2.caretPositionFromPoint) {
    try {
      let pos = doc2.caretPositionFromPoint(x2, y2);
      if (pos)
        return { node: pos.offsetNode, offset: Math.min(nodeSize(pos.offsetNode), pos.offset) };
    } catch (_2) {
    }
  }
  if (doc2.caretRangeFromPoint) {
    let range = doc2.caretRangeFromPoint(x2, y2);
    if (range)
      return { node: range.startContainer, offset: Math.min(nodeSize(range.startContainer), range.startOffset) };
  }
}
__name(caretFromPoint, "caretFromPoint");
const nav = typeof navigator != "undefined" ? navigator : null;
const doc = typeof document != "undefined" ? document : null;
const agent = nav && nav.userAgent || "";
const ie_edge = /Edge\/(\d+)/.exec(agent);
const ie_upto10 = /MSIE \d/.exec(agent);
const ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(agent);
const ie$1 = !!(ie_upto10 || ie_11up || ie_edge);
const ie_version = ie_upto10 ? document.documentMode : ie_11up ? +ie_11up[1] : ie_edge ? +ie_edge[1] : 0;
const gecko = !ie$1 && /gecko\/(\d+)/i.test(agent);
gecko && +(/Firefox\/(\d+)/.exec(agent) || [0, 0])[1];
const _chrome = !ie$1 && /Chrome\/(\d+)/.exec(agent);
const chrome$1 = !!_chrome;
const chrome_version = _chrome ? +_chrome[1] : 0;
const safari = !ie$1 && !!nav && /Apple Computer/.test(nav.vendor);
const ios = safari && (/Mobile\/\w+/.test(agent) || !!nav && nav.maxTouchPoints > 2);
const mac$3 = ios || (nav ? /Mac/.test(nav.platform) : false);
const windows = nav ? /Win/.test(nav.platform) : false;
const android = /Android \d/.test(agent);
const webkit = !!doc && "webkitFontSmoothing" in doc.documentElement.style;
const webkit_version = webkit ? +(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent) || [0, 0])[1] : 0;
function windowRect(doc2) {
  let vp = doc2.defaultView && doc2.defaultView.visualViewport;
  if (vp)
    return {
      left: 0,
      right: vp.width,
      top: 0,
      bottom: vp.height
    };
  return {
    left: 0,
    right: doc2.documentElement.clientWidth,
    top: 0,
    bottom: doc2.documentElement.clientHeight
  };
}
__name(windowRect, "windowRect");
function getSide(value, side) {
  return typeof value == "number" ? value : value[side];
}
__name(getSide, "getSide");
function clientRect(node2) {
  let rect = node2.getBoundingClientRect();
  let scaleX = rect.width / node2.offsetWidth || 1;
  let scaleY = rect.height / node2.offsetHeight || 1;
  return {
    left: rect.left,
    right: rect.left + node2.clientWidth * scaleX,
    top: rect.top,
    bottom: rect.top + node2.clientHeight * scaleY
  };
}
__name(clientRect, "clientRect");
function scrollRectIntoView(view, rect, startDOM) {
  let scrollThreshold = view.someProp("scrollThreshold") || 0, scrollMargin = view.someProp("scrollMargin") || 5;
  let doc2 = view.dom.ownerDocument;
  for (let parent2 = startDOM || view.dom; ; parent2 = parentNode(parent2)) {
    if (!parent2)
      break;
    if (parent2.nodeType != 1)
      continue;
    let elt = parent2;
    let atTop = elt == doc2.body;
    let bounding = atTop ? windowRect(doc2) : clientRect(elt);
    let moveX = 0, moveY = 0;
    if (rect.top < bounding.top + getSide(scrollThreshold, "top"))
      moveY = -(bounding.top - rect.top + getSide(scrollMargin, "top"));
    else if (rect.bottom > bounding.bottom - getSide(scrollThreshold, "bottom"))
      moveY = rect.bottom - rect.top > bounding.bottom - bounding.top ? rect.top + getSide(scrollMargin, "top") - bounding.top : rect.bottom - bounding.bottom + getSide(scrollMargin, "bottom");
    if (rect.left < bounding.left + getSide(scrollThreshold, "left"))
      moveX = -(bounding.left - rect.left + getSide(scrollMargin, "left"));
    else if (rect.right > bounding.right - getSide(scrollThreshold, "right"))
      moveX = rect.right - bounding.right + getSide(scrollMargin, "right");
    if (moveX || moveY) {
      if (atTop) {
        doc2.defaultView.scrollBy(moveX, moveY);
      } else {
        let startX = elt.scrollLeft, startY = elt.scrollTop;
        if (moveY)
          elt.scrollTop += moveY;
        if (moveX)
          elt.scrollLeft += moveX;
        let dX = elt.scrollLeft - startX, dY = elt.scrollTop - startY;
        rect = { left: rect.left - dX, top: rect.top - dY, right: rect.right - dX, bottom: rect.bottom - dY };
      }
    }
    if (atTop || /^(fixed|sticky)$/.test(getComputedStyle(parent2).position))
      break;
  }
}
__name(scrollRectIntoView, "scrollRectIntoView");
function storeScrollPos(view) {
  let rect = view.dom.getBoundingClientRect(), startY = Math.max(0, rect.top);
  let refDOM, refTop;
  for (let x2 = (rect.left + rect.right) / 2, y2 = startY + 1; y2 < Math.min(innerHeight, rect.bottom); y2 += 5) {
    let dom = view.root.elementFromPoint(x2, y2);
    if (!dom || dom == view.dom || !view.dom.contains(dom))
      continue;
    let localRect = dom.getBoundingClientRect();
    if (localRect.top >= startY - 20) {
      refDOM = dom;
      refTop = localRect.top;
      break;
    }
  }
  return { refDOM, refTop, stack: scrollStack(view.dom) };
}
__name(storeScrollPos, "storeScrollPos");
function scrollStack(dom) {
  let stack = [], doc2 = dom.ownerDocument;
  for (let cur = dom; cur; cur = parentNode(cur)) {
    stack.push({ dom: cur, top: cur.scrollTop, left: cur.scrollLeft });
    if (dom == doc2)
      break;
  }
  return stack;
}
__name(scrollStack, "scrollStack");
function resetScrollPos({ refDOM, refTop, stack }) {
  let newRefTop = refDOM ? refDOM.getBoundingClientRect().top : 0;
  restoreScrollStack(stack, newRefTop == 0 ? 0 : newRefTop - refTop);
}
__name(resetScrollPos, "resetScrollPos");
function restoreScrollStack(stack, dTop) {
  for (let i2 = 0; i2 < stack.length; i2++) {
    let { dom, top, left } = stack[i2];
    if (dom.scrollTop != top + dTop)
      dom.scrollTop = top + dTop;
    if (dom.scrollLeft != left)
      dom.scrollLeft = left;
  }
}
__name(restoreScrollStack, "restoreScrollStack");
let preventScrollSupported = null;
function focusPreventScroll(dom) {
  if (dom.setActive)
    return dom.setActive();
  if (preventScrollSupported)
    return dom.focus(preventScrollSupported);
  let stored = scrollStack(dom);
  dom.focus(preventScrollSupported == null ? {
    get preventScroll() {
      preventScrollSupported = { preventScroll: true };
      return true;
    }
  } : void 0);
  if (!preventScrollSupported) {
    preventScrollSupported = false;
    restoreScrollStack(stored, 0);
  }
}
__name(focusPreventScroll, "focusPreventScroll");
function findOffsetInNode(node2, coords) {
  let closest, dxClosest = 2e8, coordsClosest, offset = 0;
  let rowBot = coords.top, rowTop = coords.top;
  let firstBelow, coordsBelow;
  for (let child2 = node2.firstChild, childIndex = 0; child2; child2 = child2.nextSibling, childIndex++) {
    let rects;
    if (child2.nodeType == 1)
      rects = child2.getClientRects();
    else if (child2.nodeType == 3)
      rects = textRange(child2).getClientRects();
    else
      continue;
    for (let i2 = 0; i2 < rects.length; i2++) {
      let rect = rects[i2];
      if (rect.top <= rowBot && rect.bottom >= rowTop) {
        rowBot = Math.max(rect.bottom, rowBot);
        rowTop = Math.min(rect.top, rowTop);
        let dx = rect.left > coords.left ? rect.left - coords.left : rect.right < coords.left ? coords.left - rect.right : 0;
        if (dx < dxClosest) {
          closest = child2;
          dxClosest = dx;
          coordsClosest = dx && closest.nodeType == 3 ? {
            left: rect.right < coords.left ? rect.right : rect.left,
            top: coords.top
          } : coords;
          if (child2.nodeType == 1 && dx)
            offset = childIndex + (coords.left >= (rect.left + rect.right) / 2 ? 1 : 0);
          continue;
        }
      } else if (rect.top > coords.top && !firstBelow && rect.left <= coords.left && rect.right >= coords.left) {
        firstBelow = child2;
        coordsBelow = { left: Math.max(rect.left, Math.min(rect.right, coords.left)), top: rect.top };
      }
      if (!closest && (coords.left >= rect.right && coords.top >= rect.top || coords.left >= rect.left && coords.top >= rect.bottom))
        offset = childIndex + 1;
    }
  }
  if (!closest && firstBelow) {
    closest = firstBelow;
    coordsClosest = coordsBelow;
    dxClosest = 0;
  }
  if (closest && closest.nodeType == 3)
    return findOffsetInText(closest, coordsClosest);
  if (!closest || dxClosest && closest.nodeType == 1)
    return { node: node2, offset };
  return findOffsetInNode(closest, coordsClosest);
}
__name(findOffsetInNode, "findOffsetInNode");
function findOffsetInText(node2, coords) {
  let len = node2.nodeValue.length;
  let range = document.createRange();
  for (let i2 = 0; i2 < len; i2++) {
    range.setEnd(node2, i2 + 1);
    range.setStart(node2, i2);
    let rect = singleRect(range, 1);
    if (rect.top == rect.bottom)
      continue;
    if (inRect(coords, rect))
      return { node: node2, offset: i2 + (coords.left >= (rect.left + rect.right) / 2 ? 1 : 0) };
  }
  return { node: node2, offset: 0 };
}
__name(findOffsetInText, "findOffsetInText");
function inRect(coords, rect) {
  return coords.left >= rect.left - 1 && coords.left <= rect.right + 1 && coords.top >= rect.top - 1 && coords.top <= rect.bottom + 1;
}
__name(inRect, "inRect");
function targetKludge(dom, coords) {
  let parent2 = dom.parentNode;
  if (parent2 && /^li$/i.test(parent2.nodeName) && coords.left < dom.getBoundingClientRect().left)
    return parent2;
  return dom;
}
__name(targetKludge, "targetKludge");
function posFromElement(view, elt, coords) {
  let { node: node2, offset } = findOffsetInNode(elt, coords), bias = -1;
  if (node2.nodeType == 1 && !node2.firstChild) {
    let rect = node2.getBoundingClientRect();
    bias = rect.left != rect.right && coords.left > (rect.left + rect.right) / 2 ? 1 : -1;
  }
  return view.docView.posFromDOM(node2, offset, bias);
}
__name(posFromElement, "posFromElement");
function posFromCaret(view, node2, offset, coords) {
  let outsideBlock = -1;
  for (let cur = node2, sawBlock = false; ; ) {
    if (cur == view.dom)
      break;
    let desc = view.docView.nearestDesc(cur, true), rect;
    if (!desc)
      return null;
    if (desc.dom.nodeType == 1 && (desc.node.isBlock && desc.parent || !desc.contentDOM) && // Ignore elements with zero-size bounding rectangles
    ((rect = desc.dom.getBoundingClientRect()).width || rect.height)) {
      if (desc.node.isBlock && desc.parent) {
        if (!sawBlock && rect.left > coords.left || rect.top > coords.top)
          outsideBlock = desc.posBefore;
        else if (!sawBlock && rect.right < coords.left || rect.bottom < coords.top)
          outsideBlock = desc.posAfter;
        sawBlock = true;
      }
      if (!desc.contentDOM && outsideBlock < 0 && !desc.node.isText) {
        let before = desc.node.isBlock ? coords.top < (rect.top + rect.bottom) / 2 : coords.left < (rect.left + rect.right) / 2;
        return before ? desc.posBefore : desc.posAfter;
      }
    }
    cur = desc.dom.parentNode;
  }
  return outsideBlock > -1 ? outsideBlock : view.docView.posFromDOM(node2, offset, -1);
}
__name(posFromCaret, "posFromCaret");
function elementFromPoint(element, coords, box) {
  let len = element.childNodes.length;
  if (len && box.top < box.bottom) {
    for (let startI = Math.max(0, Math.min(len - 1, Math.floor(len * (coords.top - box.top) / (box.bottom - box.top)) - 2)), i2 = startI; ; ) {
      let child2 = element.childNodes[i2];
      if (child2.nodeType == 1) {
        let rects = child2.getClientRects();
        for (let j2 = 0; j2 < rects.length; j2++) {
          let rect = rects[j2];
          if (inRect(coords, rect))
            return elementFromPoint(child2, coords, rect);
        }
      }
      if ((i2 = (i2 + 1) % len) == startI)
        break;
    }
  }
  return element;
}
__name(elementFromPoint, "elementFromPoint");
function posAtCoords(view, coords) {
  let doc2 = view.dom.ownerDocument, node2, offset = 0;
  let caret = caretFromPoint(doc2, coords.left, coords.top);
  if (caret)
    ({ node: node2, offset } = caret);
  let elt = (view.root.elementFromPoint ? view.root : doc2).elementFromPoint(coords.left, coords.top);
  let pos;
  if (!elt || !view.dom.contains(elt.nodeType != 1 ? elt.parentNode : elt)) {
    let box = view.dom.getBoundingClientRect();
    if (!inRect(coords, box))
      return null;
    elt = elementFromPoint(view.dom, coords, box);
    if (!elt)
      return null;
  }
  if (safari) {
    for (let p2 = elt; node2 && p2; p2 = parentNode(p2))
      if (p2.draggable)
        node2 = void 0;
  }
  elt = targetKludge(elt, coords);
  if (node2) {
    if (gecko && node2.nodeType == 1) {
      offset = Math.min(offset, node2.childNodes.length);
      if (offset < node2.childNodes.length) {
        let next = node2.childNodes[offset], box;
        if (next.nodeName == "IMG" && (box = next.getBoundingClientRect()).right <= coords.left && box.bottom > coords.top)
          offset++;
      }
    }
    let prev;
    if (webkit && offset && node2.nodeType == 1 && (prev = node2.childNodes[offset - 1]).nodeType == 1 && prev.contentEditable == "false" && prev.getBoundingClientRect().top >= coords.top)
      offset--;
    if (node2 == view.dom && offset == node2.childNodes.length - 1 && node2.lastChild.nodeType == 1 && coords.top > node2.lastChild.getBoundingClientRect().bottom)
      pos = view.state.doc.content.size;
    else if (offset == 0 || node2.nodeType != 1 || node2.childNodes[offset - 1].nodeName != "BR")
      pos = posFromCaret(view, node2, offset, coords);
  }
  if (pos == null)
    pos = posFromElement(view, elt, coords);
  let desc = view.docView.nearestDesc(elt, true);
  return { pos, inside: desc ? desc.posAtStart - desc.border : -1 };
}
__name(posAtCoords, "posAtCoords");
function nonZero(rect) {
  return rect.top < rect.bottom || rect.left < rect.right;
}
__name(nonZero, "nonZero");
function singleRect(target, bias) {
  let rects = target.getClientRects();
  if (rects.length) {
    let first2 = rects[bias < 0 ? 0 : rects.length - 1];
    if (nonZero(first2))
      return first2;
  }
  return Array.prototype.find.call(rects, nonZero) || target.getBoundingClientRect();
}
__name(singleRect, "singleRect");
const BIDI = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
function coordsAtPos(view, pos, side) {
  let { node: node2, offset, atom } = view.docView.domFromPos(pos, side < 0 ? -1 : 1);
  let supportEmptyRange = webkit || gecko;
  if (node2.nodeType == 3) {
    if (supportEmptyRange && (BIDI.test(node2.nodeValue) || (side < 0 ? !offset : offset == node2.nodeValue.length))) {
      let rect = singleRect(textRange(node2, offset, offset), side);
      if (gecko && offset && /\s/.test(node2.nodeValue[offset - 1]) && offset < node2.nodeValue.length) {
        let rectBefore = singleRect(textRange(node2, offset - 1, offset - 1), -1);
        if (rectBefore.top == rect.top) {
          let rectAfter = singleRect(textRange(node2, offset, offset + 1), -1);
          if (rectAfter.top != rect.top)
            return flattenV(rectAfter, rectAfter.left < rectBefore.left);
        }
      }
      return rect;
    } else {
      let from2 = offset, to = offset, takeSide = side < 0 ? 1 : -1;
      if (side < 0 && !offset) {
        to++;
        takeSide = -1;
      } else if (side >= 0 && offset == node2.nodeValue.length) {
        from2--;
        takeSide = 1;
      } else if (side < 0) {
        from2--;
      } else {
        to++;
      }
      return flattenV(singleRect(textRange(node2, from2, to), takeSide), takeSide < 0);
    }
  }
  let $dom = view.state.doc.resolve(pos - (atom || 0));
  if (!$dom.parent.inlineContent) {
    if (atom == null && offset && (side < 0 || offset == nodeSize(node2))) {
      let before = node2.childNodes[offset - 1];
      if (before.nodeType == 1)
        return flattenH(before.getBoundingClientRect(), false);
    }
    if (atom == null && offset < nodeSize(node2)) {
      let after = node2.childNodes[offset];
      if (after.nodeType == 1)
        return flattenH(after.getBoundingClientRect(), true);
    }
    return flattenH(node2.getBoundingClientRect(), side >= 0);
  }
  if (atom == null && offset && (side < 0 || offset == nodeSize(node2))) {
    let before = node2.childNodes[offset - 1];
    let target = before.nodeType == 3 ? textRange(before, nodeSize(before) - (supportEmptyRange ? 0 : 1)) : before.nodeType == 1 && (before.nodeName != "BR" || !before.nextSibling) ? before : null;
    if (target)
      return flattenV(singleRect(target, 1), false);
  }
  if (atom == null && offset < nodeSize(node2)) {
    let after = node2.childNodes[offset];
    while (after.pmViewDesc && after.pmViewDesc.ignoreForCoords)
      after = after.nextSibling;
    let target = !after ? null : after.nodeType == 3 ? textRange(after, 0, supportEmptyRange ? 0 : 1) : after.nodeType == 1 ? after : null;
    if (target)
      return flattenV(singleRect(target, -1), true);
  }
  return flattenV(singleRect(node2.nodeType == 3 ? textRange(node2) : node2, -side), side >= 0);
}
__name(coordsAtPos, "coordsAtPos");
function flattenV(rect, left) {
  if (rect.width == 0)
    return rect;
  let x2 = left ? rect.left : rect.right;
  return { top: rect.top, bottom: rect.bottom, left: x2, right: x2 };
}
__name(flattenV, "flattenV");
function flattenH(rect, top) {
  if (rect.height == 0)
    return rect;
  let y2 = top ? rect.top : rect.bottom;
  return { top: y2, bottom: y2, left: rect.left, right: rect.right };
}
__name(flattenH, "flattenH");
function withFlushedState(view, state, f2) {
  let viewState = view.state, active = view.root.activeElement;
  if (viewState != state)
    view.updateState(state);
  if (active != view.dom)
    view.focus();
  try {
    return f2();
  } finally {
    if (viewState != state)
      view.updateState(viewState);
    if (active != view.dom && active)
      active.focus();
  }
}
__name(withFlushedState, "withFlushedState");
function endOfTextblockVertical(view, state, dir) {
  let sel = state.selection;
  let $pos = dir == "up" ? sel.$from : sel.$to;
  return withFlushedState(view, state, () => {
    let { node: dom } = view.docView.domFromPos($pos.pos, dir == "up" ? -1 : 1);
    for (; ; ) {
      let nearest = view.docView.nearestDesc(dom, true);
      if (!nearest)
        break;
      if (nearest.node.isBlock) {
        dom = nearest.contentDOM || nearest.dom;
        break;
      }
      dom = nearest.dom.parentNode;
    }
    let coords = coordsAtPos(view, $pos.pos, 1);
    for (let child2 = dom.firstChild; child2; child2 = child2.nextSibling) {
      let boxes;
      if (child2.nodeType == 1)
        boxes = child2.getClientRects();
      else if (child2.nodeType == 3)
        boxes = textRange(child2, 0, child2.nodeValue.length).getClientRects();
      else
        continue;
      for (let i2 = 0; i2 < boxes.length; i2++) {
        let box = boxes[i2];
        if (box.bottom > box.top + 1 && (dir == "up" ? coords.top - box.top > (box.bottom - coords.top) * 2 : box.bottom - coords.bottom > (coords.bottom - box.top) * 2))
          return false;
      }
    }
    return true;
  });
}
__name(endOfTextblockVertical, "endOfTextblockVertical");
const maybeRTL = /[\u0590-\u08ac]/;
function endOfTextblockHorizontal(view, state, dir) {
  let { $head } = state.selection;
  if (!$head.parent.isTextblock)
    return false;
  let offset = $head.parentOffset, atStart = !offset, atEnd = offset == $head.parent.content.size;
  let sel = view.domSelection();
  if (!sel)
    return $head.pos == $head.start() || $head.pos == $head.end();
  if (!maybeRTL.test($head.parent.textContent) || !sel.modify)
    return dir == "left" || dir == "backward" ? atStart : atEnd;
  return withFlushedState(view, state, () => {
    let { focusNode: oldNode, focusOffset: oldOff, anchorNode, anchorOffset } = view.domSelectionRange();
    let oldBidiLevel = sel.caretBidiLevel;
    sel.modify("move", dir, "character");
    let parentDOM = $head.depth ? view.docView.domAfterPos($head.before()) : view.dom;
    let { focusNode: newNode, focusOffset: newOff } = view.domSelectionRange();
    let result = newNode && !parentDOM.contains(newNode.nodeType == 1 ? newNode : newNode.parentNode) || oldNode == newNode && oldOff == newOff;
    try {
      sel.collapse(anchorNode, anchorOffset);
      if (oldNode && (oldNode != anchorNode || oldOff != anchorOffset) && sel.extend)
        sel.extend(oldNode, oldOff);
    } catch (_2) {
    }
    if (oldBidiLevel != null)
      sel.caretBidiLevel = oldBidiLevel;
    return result;
  });
}
__name(endOfTextblockHorizontal, "endOfTextblockHorizontal");
let cachedState = null;
let cachedDir = null;
let cachedResult = false;
function endOfTextblock(view, state, dir) {
  if (cachedState == state && cachedDir == dir)
    return cachedResult;
  cachedState = state;
  cachedDir = dir;
  return cachedResult = dir == "up" || dir == "down" ? endOfTextblockVertical(view, state, dir) : endOfTextblockHorizontal(view, state, dir);
}
__name(endOfTextblock, "endOfTextblock");
const NOT_DIRTY = 0, CHILD_DIRTY = 1, CONTENT_DIRTY = 2, NODE_DIRTY = 3;
class ViewDesc {
  static {
    __name(this, "ViewDesc");
  }
  constructor(parent2, children, dom, contentDOM) {
    this.parent = parent2;
    this.children = children;
    this.dom = dom;
    this.contentDOM = contentDOM;
    this.dirty = NOT_DIRTY;
    dom.pmViewDesc = this;
  }
  // Used to check whether a given description corresponds to a
  // widget/mark/node.
  matchesWidget(widget) {
    return false;
  }
  matchesMark(mark) {
    return false;
  }
  matchesNode(node2, outerDeco, innerDeco) {
    return false;
  }
  matchesHack(nodeName) {
    return false;
  }
  // When parsing in-editor content (in domchange.js), we allow
  // descriptions to determine the parse rules that should be used to
  // parse them.
  parseRule() {
    return null;
  }
  // Used by the editor's event handler to ignore events that come
  // from certain descs.
  stopEvent(event) {
    return false;
  }
  // The size of the content represented by this desc.
  get size() {
    let size = 0;
    for (let i2 = 0; i2 < this.children.length; i2++)
      size += this.children[i2].size;
    return size;
  }
  // For block nodes, this represents the space taken up by their
  // start/end tokens.
  get border() {
    return 0;
  }
  destroy() {
    this.parent = void 0;
    if (this.dom.pmViewDesc == this)
      this.dom.pmViewDesc = void 0;
    for (let i2 = 0; i2 < this.children.length; i2++)
      this.children[i2].destroy();
  }
  posBeforeChild(child2) {
    for (let i2 = 0, pos = this.posAtStart; ; i2++) {
      let cur = this.children[i2];
      if (cur == child2)
        return pos;
      pos += cur.size;
    }
  }
  get posBefore() {
    return this.parent.posBeforeChild(this);
  }
  get posAtStart() {
    return this.parent ? this.parent.posBeforeChild(this) + this.border : 0;
  }
  get posAfter() {
    return this.posBefore + this.size;
  }
  get posAtEnd() {
    return this.posAtStart + this.size - 2 * this.border;
  }
  localPosFromDOM(dom, offset, bias) {
    if (this.contentDOM && this.contentDOM.contains(dom.nodeType == 1 ? dom : dom.parentNode)) {
      if (bias < 0) {
        let domBefore, desc;
        if (dom == this.contentDOM) {
          domBefore = dom.childNodes[offset - 1];
        } else {
          while (dom.parentNode != this.contentDOM)
            dom = dom.parentNode;
          domBefore = dom.previousSibling;
        }
        while (domBefore && !((desc = domBefore.pmViewDesc) && desc.parent == this))
          domBefore = domBefore.previousSibling;
        return domBefore ? this.posBeforeChild(desc) + desc.size : this.posAtStart;
      } else {
        let domAfter, desc;
        if (dom == this.contentDOM) {
          domAfter = dom.childNodes[offset];
        } else {
          while (dom.parentNode != this.contentDOM)
            dom = dom.parentNode;
          domAfter = dom.nextSibling;
        }
        while (domAfter && !((desc = domAfter.pmViewDesc) && desc.parent == this))
          domAfter = domAfter.nextSibling;
        return domAfter ? this.posBeforeChild(desc) : this.posAtEnd;
      }
    }
    let atEnd;
    if (dom == this.dom && this.contentDOM) {
      atEnd = offset > domIndex(this.contentDOM);
    } else if (this.contentDOM && this.contentDOM != this.dom && this.dom.contains(this.contentDOM)) {
      atEnd = dom.compareDocumentPosition(this.contentDOM) & 2;
    } else if (this.dom.firstChild) {
      if (offset == 0)
        for (let search2 = dom; ; search2 = search2.parentNode) {
          if (search2 == this.dom) {
            atEnd = false;
            break;
          }
          if (search2.previousSibling)
            break;
        }
      if (atEnd == null && offset == dom.childNodes.length)
        for (let search2 = dom; ; search2 = search2.parentNode) {
          if (search2 == this.dom) {
            atEnd = true;
            break;
          }
          if (search2.nextSibling)
            break;
        }
    }
    return (atEnd == null ? bias > 0 : atEnd) ? this.posAtEnd : this.posAtStart;
  }
  nearestDesc(dom, onlyNodes = false) {
    for (let first2 = true, cur = dom; cur; cur = cur.parentNode) {
      let desc = this.getDesc(cur), nodeDOM;
      if (desc && (!onlyNodes || desc.node)) {
        if (first2 && (nodeDOM = desc.nodeDOM) && !(nodeDOM.nodeType == 1 ? nodeDOM.contains(dom.nodeType == 1 ? dom : dom.parentNode) : nodeDOM == dom))
          first2 = false;
        else
          return desc;
      }
    }
  }
  getDesc(dom) {
    let desc = dom.pmViewDesc;
    for (let cur = desc; cur; cur = cur.parent)
      if (cur == this)
        return desc;
  }
  posFromDOM(dom, offset, bias) {
    for (let scan = dom; scan; scan = scan.parentNode) {
      let desc = this.getDesc(scan);
      if (desc)
        return desc.localPosFromDOM(dom, offset, bias);
    }
    return -1;
  }
  // Find the desc for the node after the given pos, if any. (When a
  // parent node overrode rendering, there might not be one.)
  descAt(pos) {
    for (let i2 = 0, offset = 0; i2 < this.children.length; i2++) {
      let child2 = this.children[i2], end = offset + child2.size;
      if (offset == pos && end != offset) {
        while (!child2.border && child2.children.length)
          child2 = child2.children[0];
        return child2;
      }
      if (pos < end)
        return child2.descAt(pos - offset - child2.border);
      offset = end;
    }
  }
  domFromPos(pos, side) {
    if (!this.contentDOM)
      return { node: this.dom, offset: 0, atom: pos + 1 };
    let i2 = 0, offset = 0;
    for (let curPos = 0; i2 < this.children.length; i2++) {
      let child2 = this.children[i2], end = curPos + child2.size;
      if (end > pos || child2 instanceof TrailingHackViewDesc) {
        offset = pos - curPos;
        break;
      }
      curPos = end;
    }
    if (offset)
      return this.children[i2].domFromPos(offset - this.children[i2].border, side);
    for (let prev; i2 && !(prev = this.children[i2 - 1]).size && prev instanceof WidgetViewDesc && prev.side >= 0; i2--) {
    }
    if (side <= 0) {
      let prev, enter2 = true;
      for (; ; i2--, enter2 = false) {
        prev = i2 ? this.children[i2 - 1] : null;
        if (!prev || prev.dom.parentNode == this.contentDOM)
          break;
      }
      if (prev && side && enter2 && !prev.border && !prev.domAtom)
        return prev.domFromPos(prev.size, side);
      return { node: this.contentDOM, offset: prev ? domIndex(prev.dom) + 1 : 0 };
    } else {
      let next, enter2 = true;
      for (; ; i2++, enter2 = false) {
        next = i2 < this.children.length ? this.children[i2] : null;
        if (!next || next.dom.parentNode == this.contentDOM)
          break;
      }
      if (next && enter2 && !next.border && !next.domAtom)
        return next.domFromPos(0, side);
      return { node: this.contentDOM, offset: next ? domIndex(next.dom) : this.contentDOM.childNodes.length };
    }
  }
  // Used to find a DOM range in a single parent for a given changed
  // range.
  parseRange(from2, to, base2 = 0) {
    if (this.children.length == 0)
      return { node: this.contentDOM, from: from2, to, fromOffset: 0, toOffset: this.contentDOM.childNodes.length };
    let fromOffset = -1, toOffset = -1;
    for (let offset = base2, i2 = 0; ; i2++) {
      let child2 = this.children[i2], end = offset + child2.size;
      if (fromOffset == -1 && from2 <= end) {
        let childBase = offset + child2.border;
        if (from2 >= childBase && to <= end - child2.border && child2.node && child2.contentDOM && this.contentDOM.contains(child2.contentDOM))
          return child2.parseRange(from2, to, childBase);
        from2 = offset;
        for (let j2 = i2; j2 > 0; j2--) {
          let prev = this.children[j2 - 1];
          if (prev.size && prev.dom.parentNode == this.contentDOM && !prev.emptyChildAt(1)) {
            fromOffset = domIndex(prev.dom) + 1;
            break;
          }
          from2 -= prev.size;
        }
        if (fromOffset == -1)
          fromOffset = 0;
      }
      if (fromOffset > -1 && (end > to || i2 == this.children.length - 1)) {
        to = end;
        for (let j2 = i2 + 1; j2 < this.children.length; j2++) {
          let next = this.children[j2];
          if (next.size && next.dom.parentNode == this.contentDOM && !next.emptyChildAt(-1)) {
            toOffset = domIndex(next.dom);
            break;
          }
          to += next.size;
        }
        if (toOffset == -1)
          toOffset = this.contentDOM.childNodes.length;
        break;
      }
      offset = end;
    }
    return { node: this.contentDOM, from: from2, to, fromOffset, toOffset };
  }
  emptyChildAt(side) {
    if (this.border || !this.contentDOM || !this.children.length)
      return false;
    let child2 = this.children[side < 0 ? 0 : this.children.length - 1];
    return child2.size == 0 || child2.emptyChildAt(side);
  }
  domAfterPos(pos) {
    let { node: node2, offset } = this.domFromPos(pos, 0);
    if (node2.nodeType != 1 || offset == node2.childNodes.length)
      throw new RangeError("No node after pos " + pos);
    return node2.childNodes[offset];
  }
  // View descs are responsible for setting any selection that falls
  // entirely inside of them, so that custom implementations can do
  // custom things with the selection. Note that this falls apart when
  // a selection starts in such a node and ends in another, in which
  // case we just use whatever domFromPos produces as a best effort.
  setSelection(anchor, head, view, force = false) {
    let from2 = Math.min(anchor, head), to = Math.max(anchor, head);
    for (let i2 = 0, offset = 0; i2 < this.children.length; i2++) {
      let child2 = this.children[i2], end = offset + child2.size;
      if (from2 > offset && to < end)
        return child2.setSelection(anchor - offset - child2.border, head - offset - child2.border, view, force);
      offset = end;
    }
    let anchorDOM = this.domFromPos(anchor, anchor ? -1 : 1);
    let headDOM = head == anchor ? anchorDOM : this.domFromPos(head, head ? -1 : 1);
    let domSel = view.root.getSelection();
    let selRange = view.domSelectionRange();
    let brKludge = false;
    if ((gecko || safari) && anchor == head) {
      let { node: node2, offset } = anchorDOM;
      if (node2.nodeType == 3) {
        brKludge = !!(offset && node2.nodeValue[offset - 1] == "\n");
        if (brKludge && offset == node2.nodeValue.length) {
          for (let scan = node2, after; scan; scan = scan.parentNode) {
            if (after = scan.nextSibling) {
              if (after.nodeName == "BR")
                anchorDOM = headDOM = { node: after.parentNode, offset: domIndex(after) + 1 };
              break;
            }
            let desc = scan.pmViewDesc;
            if (desc && desc.node && desc.node.isBlock)
              break;
          }
        }
      } else {
        let prev = node2.childNodes[offset - 1];
        brKludge = prev && (prev.nodeName == "BR" || prev.contentEditable == "false");
      }
    }
    if (gecko && selRange.focusNode && selRange.focusNode != headDOM.node && selRange.focusNode.nodeType == 1) {
      let after = selRange.focusNode.childNodes[selRange.focusOffset];
      if (after && after.contentEditable == "false")
        force = true;
    }
    if (!(force || brKludge && safari) && isEquivalentPosition(anchorDOM.node, anchorDOM.offset, selRange.anchorNode, selRange.anchorOffset) && isEquivalentPosition(headDOM.node, headDOM.offset, selRange.focusNode, selRange.focusOffset))
      return;
    let domSelExtended = false;
    if ((domSel.extend || anchor == head) && !brKludge) {
      domSel.collapse(anchorDOM.node, anchorDOM.offset);
      try {
        if (anchor != head)
          domSel.extend(headDOM.node, headDOM.offset);
        domSelExtended = true;
      } catch (_2) {
      }
    }
    if (!domSelExtended) {
      if (anchor > head) {
        let tmp = anchorDOM;
        anchorDOM = headDOM;
        headDOM = tmp;
      }
      let range = document.createRange();
      range.setEnd(headDOM.node, headDOM.offset);
      range.setStart(anchorDOM.node, anchorDOM.offset);
      domSel.removeAllRanges();
      domSel.addRange(range);
    }
  }
  ignoreMutation(mutation) {
    return !this.contentDOM && mutation.type != "selection";
  }
  get contentLost() {
    return this.contentDOM && this.contentDOM != this.dom && !this.dom.contains(this.contentDOM);
  }
  // Remove a subtree of the element tree that has been touched
  // by a DOM change, so that the next update will redraw it.
  markDirty(from2, to) {
    for (let offset = 0, i2 = 0; i2 < this.children.length; i2++) {
      let child2 = this.children[i2], end = offset + child2.size;
      if (offset == end ? from2 <= end && to >= offset : from2 < end && to > offset) {
        let startInside = offset + child2.border, endInside = end - child2.border;
        if (from2 >= startInside && to <= endInside) {
          this.dirty = from2 == offset || to == end ? CONTENT_DIRTY : CHILD_DIRTY;
          if (from2 == startInside && to == endInside && (child2.contentLost || child2.dom.parentNode != this.contentDOM))
            child2.dirty = NODE_DIRTY;
          else
            child2.markDirty(from2 - startInside, to - startInside);
          return;
        } else {
          child2.dirty = child2.dom == child2.contentDOM && child2.dom.parentNode == this.contentDOM && !child2.children.length ? CONTENT_DIRTY : NODE_DIRTY;
        }
      }
      offset = end;
    }
    this.dirty = CONTENT_DIRTY;
  }
  markParentsDirty() {
    let level = 1;
    for (let node2 = this.parent; node2; node2 = node2.parent, level++) {
      let dirty = level == 1 ? CONTENT_DIRTY : CHILD_DIRTY;
      if (node2.dirty < dirty)
        node2.dirty = dirty;
    }
  }
  get domAtom() {
    return false;
  }
  get ignoreForCoords() {
    return false;
  }
  isText(text2) {
    return false;
  }
}
class WidgetViewDesc extends ViewDesc {
  static {
    __name(this, "WidgetViewDesc");
  }
  constructor(parent2, widget, view, pos) {
    let self2, dom = widget.type.toDOM;
    if (typeof dom == "function")
      dom = dom(view, () => {
        if (!self2)
          return pos;
        if (self2.parent)
          return self2.parent.posBeforeChild(self2);
      });
    if (!widget.type.spec.raw) {
      if (dom.nodeType != 1) {
        let wrap2 = document.createElement("span");
        wrap2.appendChild(dom);
        dom = wrap2;
      }
      dom.contentEditable = "false";
      dom.classList.add("ProseMirror-widget");
    }
    super(parent2, [], dom, null);
    this.widget = widget;
    this.widget = widget;
    self2 = this;
  }
  matchesWidget(widget) {
    return this.dirty == NOT_DIRTY && widget.type.eq(this.widget.type);
  }
  parseRule() {
    return { ignore: true };
  }
  stopEvent(event) {
    let stop2 = this.widget.spec.stopEvent;
    return stop2 ? stop2(event) : false;
  }
  ignoreMutation(mutation) {
    return mutation.type != "selection" || this.widget.spec.ignoreSelection;
  }
  destroy() {
    this.widget.type.destroy(this.dom);
    super.destroy();
  }
  get domAtom() {
    return true;
  }
  get side() {
    return this.widget.type.side;
  }
}
class CompositionViewDesc extends ViewDesc {
  static {
    __name(this, "CompositionViewDesc");
  }
  constructor(parent2, dom, textDOM, text2) {
    super(parent2, [], dom, null);
    this.textDOM = textDOM;
    this.text = text2;
  }
  get size() {
    return this.text.length;
  }
  localPosFromDOM(dom, offset) {
    if (dom != this.textDOM)
      return this.posAtStart + (offset ? this.size : 0);
    return this.posAtStart + offset;
  }
  domFromPos(pos) {
    return { node: this.textDOM, offset: pos };
  }
  ignoreMutation(mut) {
    return mut.type === "characterData" && mut.target.nodeValue == mut.oldValue;
  }
}
class MarkViewDesc extends ViewDesc {
  static {
    __name(this, "MarkViewDesc");
  }
  constructor(parent2, mark, dom, contentDOM, spec) {
    super(parent2, [], dom, contentDOM);
    this.mark = mark;
    this.spec = spec;
  }
  static create(parent2, mark, inline2, view) {
    let custom2 = view.nodeViews[mark.type.name];
    let spec = custom2 && custom2(mark, view, inline2);
    if (!spec || !spec.dom)
      spec = DOMSerializer.renderSpec(document, mark.type.spec.toDOM(mark, inline2), null, mark.attrs);
    return new MarkViewDesc(parent2, mark, spec.dom, spec.contentDOM || spec.dom, spec);
  }
  parseRule() {
    if (this.dirty & NODE_DIRTY || this.mark.type.spec.reparseInView)
      return null;
    return { mark: this.mark.type.name, attrs: this.mark.attrs, contentElement: this.contentDOM };
  }
  matchesMark(mark) {
    return this.dirty != NODE_DIRTY && this.mark.eq(mark);
  }
  markDirty(from2, to) {
    super.markDirty(from2, to);
    if (this.dirty != NOT_DIRTY) {
      let parent2 = this.parent;
      while (!parent2.node)
        parent2 = parent2.parent;
      if (parent2.dirty < this.dirty)
        parent2.dirty = this.dirty;
      this.dirty = NOT_DIRTY;
    }
  }
  slice(from2, to, view) {
    let copy2 = MarkViewDesc.create(this.parent, this.mark, true, view);
    let nodes = this.children, size = this.size;
    if (to < size)
      nodes = replaceNodes(nodes, to, size, view);
    if (from2 > 0)
      nodes = replaceNodes(nodes, 0, from2, view);
    for (let i2 = 0; i2 < nodes.length; i2++)
      nodes[i2].parent = copy2;
    copy2.children = nodes;
    return copy2;
  }
  ignoreMutation(mutation) {
    return this.spec.ignoreMutation ? this.spec.ignoreMutation(mutation) : super.ignoreMutation(mutation);
  }
  destroy() {
    if (this.spec.destroy)
      this.spec.destroy();
    super.destroy();
  }
}
class NodeViewDesc extends ViewDesc {
  static {
    __name(this, "NodeViewDesc");
  }
  constructor(parent2, node2, outerDeco, innerDeco, dom, contentDOM, nodeDOM, view, pos) {
    super(parent2, [], dom, contentDOM);
    this.node = node2;
    this.outerDeco = outerDeco;
    this.innerDeco = innerDeco;
    this.nodeDOM = nodeDOM;
  }
  // By default, a node is rendered using the `toDOM` method from the
  // node type spec. But client code can use the `nodeViews` spec to
  // supply a custom node view, which can influence various aspects of
  // the way the node works.
  //
  // (Using subclassing for this was intentionally decided against,
  // since it'd require exposing a whole slew of finicky
  // implementation details to the user code that they probably will
  // never need.)
  static create(parent2, node2, outerDeco, innerDeco, view, pos) {
    let custom2 = view.nodeViews[node2.type.name], descObj;
    let spec = custom2 && custom2(node2, view, () => {
      if (!descObj)
        return pos;
      if (descObj.parent)
        return descObj.parent.posBeforeChild(descObj);
    }, outerDeco, innerDeco);
    let dom = spec && spec.dom, contentDOM = spec && spec.contentDOM;
    if (node2.isText) {
      if (!dom)
        dom = document.createTextNode(node2.text);
      else if (dom.nodeType != 3)
        throw new RangeError("Text must be rendered as a DOM text node");
    } else if (!dom) {
      let spec2 = DOMSerializer.renderSpec(document, node2.type.spec.toDOM(node2), null, node2.attrs);
      ({ dom, contentDOM } = spec2);
    }
    if (!contentDOM && !node2.isText && dom.nodeName != "BR") {
      if (!dom.hasAttribute("contenteditable"))
        dom.contentEditable = "false";
      if (node2.type.spec.draggable)
        dom.draggable = true;
    }
    let nodeDOM = dom;
    dom = applyOuterDeco(dom, outerDeco, node2);
    if (spec)
      return descObj = new CustomNodeViewDesc(parent2, node2, outerDeco, innerDeco, dom, contentDOM || null, nodeDOM, spec, view, pos + 1);
    else if (node2.isText)
      return new TextViewDesc(parent2, node2, outerDeco, innerDeco, dom, nodeDOM, view);
    else
      return new NodeViewDesc(parent2, node2, outerDeco, innerDeco, dom, contentDOM || null, nodeDOM, view, pos + 1);
  }
  parseRule() {
    if (this.node.type.spec.reparseInView)
      return null;
    let rule = { node: this.node.type.name, attrs: this.node.attrs };
    if (this.node.type.whitespace == "pre")
      rule.preserveWhitespace = "full";
    if (!this.contentDOM) {
      rule.getContent = () => this.node.content;
    } else if (!this.contentLost) {
      rule.contentElement = this.contentDOM;
    } else {
      for (let i2 = this.children.length - 1; i2 >= 0; i2--) {
        let child2 = this.children[i2];
        if (this.dom.contains(child2.dom.parentNode)) {
          rule.contentElement = child2.dom.parentNode;
          break;
        }
      }
      if (!rule.contentElement)
        rule.getContent = () => Fragment.empty;
    }
    return rule;
  }
  matchesNode(node2, outerDeco, innerDeco) {
    return this.dirty == NOT_DIRTY && node2.eq(this.node) && sameOuterDeco(outerDeco, this.outerDeco) && innerDeco.eq(this.innerDeco);
  }
  get size() {
    return this.node.nodeSize;
  }
  get border() {
    return this.node.isLeaf ? 0 : 1;
  }
  // Syncs `this.children` to match `this.node.content` and the local
  // decorations, possibly introducing nesting for marks. Then, in a
  // separate step, syncs the DOM inside `this.contentDOM` to
  // `this.children`.
  updateChildren(view, pos) {
    let inline2 = this.node.inlineContent, off2 = pos;
    let composition = view.composing ? this.localCompositionInfo(view, pos) : null;
    let localComposition = composition && composition.pos > -1 ? composition : null;
    let compositionInChild = composition && composition.pos < 0;
    let updater = new ViewTreeUpdater(this, localComposition && localComposition.node, view);
    iterDeco(this.node, this.innerDeco, (widget, i2, insideNode) => {
      if (widget.spec.marks)
        updater.syncToMarks(widget.spec.marks, inline2, view);
      else if (widget.type.side >= 0 && !insideNode)
        updater.syncToMarks(i2 == this.node.childCount ? Mark$1.none : this.node.child(i2).marks, inline2, view);
      updater.placeWidget(widget, view, off2);
    }, (child2, outerDeco, innerDeco, i2) => {
      updater.syncToMarks(child2.marks, inline2, view);
      let compIndex;
      if (updater.findNodeMatch(child2, outerDeco, innerDeco, i2)) ;
      else if (compositionInChild && view.state.selection.from > off2 && view.state.selection.to < off2 + child2.nodeSize && (compIndex = updater.findIndexWithChild(composition.node)) > -1 && updater.updateNodeAt(child2, outerDeco, innerDeco, compIndex, view)) ;
      else if (updater.updateNextNode(child2, outerDeco, innerDeco, view, i2, off2)) ;
      else {
        updater.addNode(child2, outerDeco, innerDeco, view, off2);
      }
      off2 += child2.nodeSize;
    });
    updater.syncToMarks([], inline2, view);
    if (this.node.isTextblock)
      updater.addTextblockHacks();
    updater.destroyRest();
    if (updater.changed || this.dirty == CONTENT_DIRTY) {
      if (localComposition)
        this.protectLocalComposition(view, localComposition);
      renderDescs(this.contentDOM, this.children, view);
      if (ios)
        iosHacks(this.dom);
    }
  }
  localCompositionInfo(view, pos) {
    let { from: from2, to } = view.state.selection;
    if (!(view.state.selection instanceof TextSelection) || from2 < pos || to > pos + this.node.content.size)
      return null;
    let textNode = view.input.compositionNode;
    if (!textNode || !this.dom.contains(textNode.parentNode))
      return null;
    if (this.node.inlineContent) {
      let text2 = textNode.nodeValue;
      let textPos = findTextInFragment(this.node.content, text2, from2 - pos, to - pos);
      return textPos < 0 ? null : { node: textNode, pos: textPos, text: text2 };
    } else {
      return { node: textNode, pos: -1, text: "" };
    }
  }
  protectLocalComposition(view, { node: node2, pos, text: text2 }) {
    if (this.getDesc(node2))
      return;
    let topNode = node2;
    for (; ; topNode = topNode.parentNode) {
      if (topNode.parentNode == this.contentDOM)
        break;
      while (topNode.previousSibling)
        topNode.parentNode.removeChild(topNode.previousSibling);
      while (topNode.nextSibling)
        topNode.parentNode.removeChild(topNode.nextSibling);
      if (topNode.pmViewDesc)
        topNode.pmViewDesc = void 0;
    }
    let desc = new CompositionViewDesc(this, topNode, node2, text2);
    view.input.compositionNodes.push(desc);
    this.children = replaceNodes(this.children, pos, pos + text2.length, view, desc);
  }
  // If this desc must be updated to match the given node decoration,
  // do so and return true.
  update(node2, outerDeco, innerDeco, view) {
    if (this.dirty == NODE_DIRTY || !node2.sameMarkup(this.node))
      return false;
    this.updateInner(node2, outerDeco, innerDeco, view);
    return true;
  }
  updateInner(node2, outerDeco, innerDeco, view) {
    this.updateOuterDeco(outerDeco);
    this.node = node2;
    this.innerDeco = innerDeco;
    if (this.contentDOM)
      this.updateChildren(view, this.posAtStart);
    this.dirty = NOT_DIRTY;
  }
  updateOuterDeco(outerDeco) {
    if (sameOuterDeco(outerDeco, this.outerDeco))
      return;
    let needsWrap = this.nodeDOM.nodeType != 1;
    let oldDOM = this.dom;
    this.dom = patchOuterDeco(this.dom, this.nodeDOM, computeOuterDeco(this.outerDeco, this.node, needsWrap), computeOuterDeco(outerDeco, this.node, needsWrap));
    if (this.dom != oldDOM) {
      oldDOM.pmViewDesc = void 0;
      this.dom.pmViewDesc = this;
    }
    this.outerDeco = outerDeco;
  }
  // Mark this node as being the selected node.
  selectNode() {
    if (this.nodeDOM.nodeType == 1)
      this.nodeDOM.classList.add("ProseMirror-selectednode");
    if (this.contentDOM || !this.node.type.spec.draggable)
      this.dom.draggable = true;
  }
  // Remove selected node marking from this node.
  deselectNode() {
    if (this.nodeDOM.nodeType == 1) {
      this.nodeDOM.classList.remove("ProseMirror-selectednode");
      if (this.contentDOM || !this.node.type.spec.draggable)
        this.dom.removeAttribute("draggable");
    }
  }
  get domAtom() {
    return this.node.isAtom;
  }
}
function docViewDesc(doc2, outerDeco, innerDeco, dom, view) {
  applyOuterDeco(dom, outerDeco, doc2);
  let docView = new NodeViewDesc(void 0, doc2, outerDeco, innerDeco, dom, dom, dom, view, 0);
  if (docView.contentDOM)
    docView.updateChildren(view, 0);
  return docView;
}
__name(docViewDesc, "docViewDesc");
class TextViewDesc extends NodeViewDesc {
  static {
    __name(this, "TextViewDesc");
  }
  constructor(parent2, node2, outerDeco, innerDeco, dom, nodeDOM, view) {
    super(parent2, node2, outerDeco, innerDeco, dom, null, nodeDOM, view, 0);
  }
  parseRule() {
    let skip = this.nodeDOM.parentNode;
    while (skip && skip != this.dom && !skip.pmIsDeco)
      skip = skip.parentNode;
    return { skip: skip || true };
  }
  update(node2, outerDeco, innerDeco, view) {
    if (this.dirty == NODE_DIRTY || this.dirty != NOT_DIRTY && !this.inParent() || !node2.sameMarkup(this.node))
      return false;
    this.updateOuterDeco(outerDeco);
    if ((this.dirty != NOT_DIRTY || node2.text != this.node.text) && node2.text != this.nodeDOM.nodeValue) {
      this.nodeDOM.nodeValue = node2.text;
      if (view.trackWrites == this.nodeDOM)
        view.trackWrites = null;
    }
    this.node = node2;
    this.dirty = NOT_DIRTY;
    return true;
  }
  inParent() {
    let parentDOM = this.parent.contentDOM;
    for (let n2 = this.nodeDOM; n2; n2 = n2.parentNode)
      if (n2 == parentDOM)
        return true;
    return false;
  }
  domFromPos(pos) {
    return { node: this.nodeDOM, offset: pos };
  }
  localPosFromDOM(dom, offset, bias) {
    if (dom == this.nodeDOM)
      return this.posAtStart + Math.min(offset, this.node.text.length);
    return super.localPosFromDOM(dom, offset, bias);
  }
  ignoreMutation(mutation) {
    return mutation.type != "characterData" && mutation.type != "selection";
  }
  slice(from2, to, view) {
    let node2 = this.node.cut(from2, to), dom = document.createTextNode(node2.text);
    return new TextViewDesc(this.parent, node2, this.outerDeco, this.innerDeco, dom, dom, view);
  }
  markDirty(from2, to) {
    super.markDirty(from2, to);
    if (this.dom != this.nodeDOM && (from2 == 0 || to == this.nodeDOM.nodeValue.length))
      this.dirty = NODE_DIRTY;
  }
  get domAtom() {
    return false;
  }
  isText(text2) {
    return this.node.text == text2;
  }
}
class TrailingHackViewDesc extends ViewDesc {
  static {
    __name(this, "TrailingHackViewDesc");
  }
  parseRule() {
    return { ignore: true };
  }
  matchesHack(nodeName) {
    return this.dirty == NOT_DIRTY && this.dom.nodeName == nodeName;
  }
  get domAtom() {
    return true;
  }
  get ignoreForCoords() {
    return this.dom.nodeName == "IMG";
  }
}
class CustomNodeViewDesc extends NodeViewDesc {
  static {
    __name(this, "CustomNodeViewDesc");
  }
  constructor(parent2, node2, outerDeco, innerDeco, dom, contentDOM, nodeDOM, spec, view, pos) {
    super(parent2, node2, outerDeco, innerDeco, dom, contentDOM, nodeDOM, view, pos);
    this.spec = spec;
  }
  // A custom `update` method gets to decide whether the update goes
  // through. If it does, and there's a `contentDOM` node, our logic
  // updates the children.
  update(node2, outerDeco, innerDeco, view) {
    if (this.dirty == NODE_DIRTY)
      return false;
    if (this.spec.update && (this.node.type == node2.type || this.spec.multiType)) {
      let result = this.spec.update(node2, outerDeco, innerDeco);
      if (result)
        this.updateInner(node2, outerDeco, innerDeco, view);
      return result;
    } else if (!this.contentDOM && !node2.isLeaf) {
      return false;
    } else {
      return super.update(node2, outerDeco, innerDeco, view);
    }
  }
  selectNode() {
    this.spec.selectNode ? this.spec.selectNode() : super.selectNode();
  }
  deselectNode() {
    this.spec.deselectNode ? this.spec.deselectNode() : super.deselectNode();
  }
  setSelection(anchor, head, view, force) {
    this.spec.setSelection ? this.spec.setSelection(anchor, head, view.root) : super.setSelection(anchor, head, view, force);
  }
  destroy() {
    if (this.spec.destroy)
      this.spec.destroy();
    super.destroy();
  }
  stopEvent(event) {
    return this.spec.stopEvent ? this.spec.stopEvent(event) : false;
  }
  ignoreMutation(mutation) {
    return this.spec.ignoreMutation ? this.spec.ignoreMutation(mutation) : super.ignoreMutation(mutation);
  }
}
function renderDescs(parentDOM, descs, view) {
  let dom = parentDOM.firstChild, written = false;
  for (let i2 = 0; i2 < descs.length; i2++) {
    let desc = descs[i2], childDOM = desc.dom;
    if (childDOM.parentNode == parentDOM) {
      while (childDOM != dom) {
        dom = rm(dom);
        written = true;
      }
      dom = dom.nextSibling;
    } else {
      written = true;
      parentDOM.insertBefore(childDOM, dom);
    }
    if (desc instanceof MarkViewDesc) {
      let pos = dom ? dom.previousSibling : parentDOM.lastChild;
      renderDescs(desc.contentDOM, desc.children, view);
      dom = pos ? pos.nextSibling : parentDOM.firstChild;
    }
  }
  while (dom) {
    dom = rm(dom);
    written = true;
  }
  if (written && view.trackWrites == parentDOM)
    view.trackWrites = null;
}
__name(renderDescs, "renderDescs");
const OuterDecoLevel = /* @__PURE__ */ __name(function(nodeName) {
  if (nodeName)
    this.nodeName = nodeName;
}, "OuterDecoLevel");
OuterDecoLevel.prototype = /* @__PURE__ */ Object.create(null);
const noDeco = [new OuterDecoLevel()];
function computeOuterDeco(outerDeco, node2, needsWrap) {
  if (outerDeco.length == 0)
    return noDeco;
  let top = needsWrap ? noDeco[0] : new OuterDecoLevel(), result = [top];
  for (let i2 = 0; i2 < outerDeco.length; i2++) {
    let attrs2 = outerDeco[i2].type.attrs;
    if (!attrs2)
      continue;
    if (attrs2.nodeName)
      result.push(top = new OuterDecoLevel(attrs2.nodeName));
    for (let name2 in attrs2) {
      let val = attrs2[name2];
      if (val == null)
        continue;
      if (needsWrap && result.length == 1)
        result.push(top = new OuterDecoLevel(node2.isInline ? "span" : "div"));
      if (name2 == "class")
        top.class = (top.class ? top.class + " " : "") + val;
      else if (name2 == "style")
        top.style = (top.style ? top.style + ";" : "") + val;
      else if (name2 != "nodeName")
        top[name2] = val;
    }
  }
  return result;
}
__name(computeOuterDeco, "computeOuterDeco");
function patchOuterDeco(outerDOM, nodeDOM, prevComputed, curComputed) {
  if (prevComputed == noDeco && curComputed == noDeco)
    return nodeDOM;
  let curDOM = nodeDOM;
  for (let i2 = 0; i2 < curComputed.length; i2++) {
    let deco = curComputed[i2], prev = prevComputed[i2];
    if (i2) {
      let parent2;
      if (prev && prev.nodeName == deco.nodeName && curDOM != outerDOM && (parent2 = curDOM.parentNode) && parent2.nodeName.toLowerCase() == deco.nodeName) {
        curDOM = parent2;
      } else {
        parent2 = document.createElement(deco.nodeName);
        parent2.pmIsDeco = true;
        parent2.appendChild(curDOM);
        prev = noDeco[0];
        curDOM = parent2;
      }
    }
    patchAttributes(curDOM, prev || noDeco[0], deco);
  }
  return curDOM;
}
__name(patchOuterDeco, "patchOuterDeco");
function patchAttributes(dom, prev, cur) {
  for (let name2 in prev)
    if (name2 != "class" && name2 != "style" && name2 != "nodeName" && !(name2 in cur))
      dom.removeAttribute(name2);
  for (let name2 in cur)
    if (name2 != "class" && name2 != "style" && name2 != "nodeName" && cur[name2] != prev[name2])
      dom.setAttribute(name2, cur[name2]);
  if (prev.class != cur.class) {
    let prevList = prev.class ? prev.class.split(" ").filter(Boolean) : [];
    let curList = cur.class ? cur.class.split(" ").filter(Boolean) : [];
    for (let i2 = 0; i2 < prevList.length; i2++)
      if (curList.indexOf(prevList[i2]) == -1)
        dom.classList.remove(prevList[i2]);
    for (let i2 = 0; i2 < curList.length; i2++)
      if (prevList.indexOf(curList[i2]) == -1)
        dom.classList.add(curList[i2]);
    if (dom.classList.length == 0)
      dom.removeAttribute("class");
  }
  if (prev.style != cur.style) {
    if (prev.style) {
      let prop2 = /\s*([\w\-\xa1-\uffff]+)\s*:(?:"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|\(.*?\)|[^;])*/g, m2;
      while (m2 = prop2.exec(prev.style))
        dom.style.removeProperty(m2[1]);
    }
    if (cur.style)
      dom.style.cssText += cur.style;
  }
}
__name(patchAttributes, "patchAttributes");
function applyOuterDeco(dom, deco, node2) {
  return patchOuterDeco(dom, dom, noDeco, computeOuterDeco(deco, node2, dom.nodeType != 1));
}
__name(applyOuterDeco, "applyOuterDeco");
function sameOuterDeco(a2, b2) {
  if (a2.length != b2.length)
    return false;
  for (let i2 = 0; i2 < a2.length; i2++)
    if (!a2[i2].type.eq(b2[i2].type))
      return false;
  return true;
}
__name(sameOuterDeco, "sameOuterDeco");
function rm(dom) {
  let next = dom.nextSibling;
  dom.parentNode.removeChild(dom);
  return next;
}
__name(rm, "rm");
class ViewTreeUpdater {
  static {
    __name(this, "ViewTreeUpdater");
  }
  constructor(top, lock, view) {
    this.lock = lock;
    this.view = view;
    this.index = 0;
    this.stack = [];
    this.changed = false;
    this.top = top;
    this.preMatch = preMatch(top.node.content, top);
  }
  // Destroy and remove the children between the given indices in
  // `this.top`.
  destroyBetween(start2, end) {
    if (start2 == end)
      return;
    for (let i2 = start2; i2 < end; i2++)
      this.top.children[i2].destroy();
    this.top.children.splice(start2, end - start2);
    this.changed = true;
  }
  // Destroy all remaining children in `this.top`.
  destroyRest() {
    this.destroyBetween(this.index, this.top.children.length);
  }
  // Sync the current stack of mark descs with the given array of
  // marks, reusing existing mark descs when possible.
  syncToMarks(marks, inline2, view) {
    let keep = 0, depth = this.stack.length >> 1;
    let maxKeep = Math.min(depth, marks.length);
    while (keep < maxKeep && (keep == depth - 1 ? this.top : this.stack[keep + 1 << 1]).matchesMark(marks[keep]) && marks[keep].type.spec.spanning !== false)
      keep++;
    while (keep < depth) {
      this.destroyRest();
      this.top.dirty = NOT_DIRTY;
      this.index = this.stack.pop();
      this.top = this.stack.pop();
      depth--;
    }
    while (depth < marks.length) {
      this.stack.push(this.top, this.index + 1);
      let found2 = -1;
      for (let i2 = this.index; i2 < Math.min(this.index + 3, this.top.children.length); i2++) {
        let next = this.top.children[i2];
        if (next.matchesMark(marks[depth]) && !this.isLocked(next.dom)) {
          found2 = i2;
          break;
        }
      }
      if (found2 > -1) {
        if (found2 > this.index) {
          this.changed = true;
          this.destroyBetween(this.index, found2);
        }
        this.top = this.top.children[this.index];
      } else {
        let markDesc = MarkViewDesc.create(this.top, marks[depth], inline2, view);
        this.top.children.splice(this.index, 0, markDesc);
        this.top = markDesc;
        this.changed = true;
      }
      this.index = 0;
      depth++;
    }
  }
  // Try to find a node desc matching the given data. Skip over it and
  // return true when successful.
  findNodeMatch(node2, outerDeco, innerDeco, index2) {
    let found2 = -1, targetDesc;
    if (index2 >= this.preMatch.index && (targetDesc = this.preMatch.matches[index2 - this.preMatch.index]).parent == this.top && targetDesc.matchesNode(node2, outerDeco, innerDeco)) {
      found2 = this.top.children.indexOf(targetDesc, this.index);
    } else {
      for (let i2 = this.index, e2 = Math.min(this.top.children.length, i2 + 5); i2 < e2; i2++) {
        let child2 = this.top.children[i2];
        if (child2.matchesNode(node2, outerDeco, innerDeco) && !this.preMatch.matched.has(child2)) {
          found2 = i2;
          break;
        }
      }
    }
    if (found2 < 0)
      return false;
    this.destroyBetween(this.index, found2);
    this.index++;
    return true;
  }
  updateNodeAt(node2, outerDeco, innerDeco, index2, view) {
    let child2 = this.top.children[index2];
    if (child2.dirty == NODE_DIRTY && child2.dom == child2.contentDOM)
      child2.dirty = CONTENT_DIRTY;
    if (!child2.update(node2, outerDeco, innerDeco, view))
      return false;
    this.destroyBetween(this.index, index2);
    this.index++;
    return true;
  }
  findIndexWithChild(domNode) {
    for (; ; ) {
      let parent2 = domNode.parentNode;
      if (!parent2)
        return -1;
      if (parent2 == this.top.contentDOM) {
        let desc = domNode.pmViewDesc;
        if (desc)
          for (let i2 = this.index; i2 < this.top.children.length; i2++) {
            if (this.top.children[i2] == desc)
              return i2;
          }
        return -1;
      }
      domNode = parent2;
    }
  }
  // Try to update the next node, if any, to the given data. Checks
  // pre-matches to avoid overwriting nodes that could still be used.
  updateNextNode(node2, outerDeco, innerDeco, view, index2, pos) {
    for (let i2 = this.index; i2 < this.top.children.length; i2++) {
      let next = this.top.children[i2];
      if (next instanceof NodeViewDesc) {
        let preMatch2 = this.preMatch.matched.get(next);
        if (preMatch2 != null && preMatch2 != index2)
          return false;
        let nextDOM = next.dom, updated2;
        let locked = this.isLocked(nextDOM) && !(node2.isText && next.node && next.node.isText && next.nodeDOM.nodeValue == node2.text && next.dirty != NODE_DIRTY && sameOuterDeco(outerDeco, next.outerDeco));
        if (!locked && next.update(node2, outerDeco, innerDeco, view)) {
          this.destroyBetween(this.index, i2);
          if (next.dom != nextDOM)
            this.changed = true;
          this.index++;
          return true;
        } else if (!locked && (updated2 = this.recreateWrapper(next, node2, outerDeco, innerDeco, view, pos))) {
          this.destroyBetween(this.index, i2);
          this.top.children[this.index] = updated2;
          if (updated2.contentDOM) {
            updated2.dirty = CONTENT_DIRTY;
            updated2.updateChildren(view, pos + 1);
            updated2.dirty = NOT_DIRTY;
          }
          this.changed = true;
          this.index++;
          return true;
        }
        break;
      }
    }
    return false;
  }
  // When a node with content is replaced by a different node with
  // identical content, move over its children.
  recreateWrapper(next, node2, outerDeco, innerDeco, view, pos) {
    if (next.dirty || node2.isAtom || !next.children.length || !next.node.content.eq(node2.content) || !sameOuterDeco(outerDeco, next.outerDeco) || !innerDeco.eq(next.innerDeco))
      return null;
    let wrapper = NodeViewDesc.create(this.top, node2, outerDeco, innerDeco, view, pos);
    if (wrapper.contentDOM) {
      wrapper.children = next.children;
      next.children = [];
      for (let ch of wrapper.children)
        ch.parent = wrapper;
    }
    next.destroy();
    return wrapper;
  }
  // Insert the node as a newly created node desc.
  addNode(node2, outerDeco, innerDeco, view, pos) {
    let desc = NodeViewDesc.create(this.top, node2, outerDeco, innerDeco, view, pos);
    if (desc.contentDOM)
      desc.updateChildren(view, pos + 1);
    this.top.children.splice(this.index++, 0, desc);
    this.changed = true;
  }
  placeWidget(widget, view, pos) {
    let next = this.index < this.top.children.length ? this.top.children[this.index] : null;
    if (next && next.matchesWidget(widget) && (widget == next.widget || !next.widget.type.toDOM.parentNode)) {
      this.index++;
    } else {
      let desc = new WidgetViewDesc(this.top, widget, view, pos);
      this.top.children.splice(this.index++, 0, desc);
      this.changed = true;
    }
  }
  // Make sure a textblock looks and behaves correctly in
  // contentEditable.
  addTextblockHacks() {
    let lastChild = this.top.children[this.index - 1], parent2 = this.top;
    while (lastChild instanceof MarkViewDesc) {
      parent2 = lastChild;
      lastChild = parent2.children[parent2.children.length - 1];
    }
    if (!lastChild || // Empty textblock
    !(lastChild instanceof TextViewDesc) || /\n$/.test(lastChild.node.text) || this.view.requiresGeckoHackNode && /\s$/.test(lastChild.node.text)) {
      if ((safari || chrome$1) && lastChild && lastChild.dom.contentEditable == "false")
        this.addHackNode("IMG", parent2);
      this.addHackNode("BR", this.top);
    }
  }
  addHackNode(nodeName, parent2) {
    if (parent2 == this.top && this.index < parent2.children.length && parent2.children[this.index].matchesHack(nodeName)) {
      this.index++;
    } else {
      let dom = document.createElement(nodeName);
      if (nodeName == "IMG") {
        dom.className = "ProseMirror-separator";
        dom.alt = "";
      }
      if (nodeName == "BR")
        dom.className = "ProseMirror-trailingBreak";
      let hack = new TrailingHackViewDesc(this.top, [], dom, null);
      if (parent2 != this.top)
        parent2.children.push(hack);
      else
        parent2.children.splice(this.index++, 0, hack);
      this.changed = true;
    }
  }
  isLocked(node2) {
    return this.lock && (node2 == this.lock || node2.nodeType == 1 && node2.contains(this.lock.parentNode));
  }
}
function preMatch(frag, parentDesc) {
  let curDesc = parentDesc, descI = curDesc.children.length;
  let fI = frag.childCount, matched = /* @__PURE__ */ new Map(), matches2 = [];
  outer: while (fI > 0) {
    let desc;
    for (; ; ) {
      if (descI) {
        let next = curDesc.children[descI - 1];
        if (next instanceof MarkViewDesc) {
          curDesc = next;
          descI = next.children.length;
        } else {
          desc = next;
          descI--;
          break;
        }
      } else if (curDesc == parentDesc) {
        break outer;
      } else {
        descI = curDesc.parent.children.indexOf(curDesc);
        curDesc = curDesc.parent;
      }
    }
    let node2 = desc.node;
    if (!node2)
      continue;
    if (node2 != frag.child(fI - 1))
      break;
    --fI;
    matched.set(desc, fI);
    matches2.push(desc);
  }
  return { index: fI, matched, matches: matches2.reverse() };
}
__name(preMatch, "preMatch");
function compareSide(a2, b2) {
  return a2.type.side - b2.type.side;
}
__name(compareSide, "compareSide");
function iterDeco(parent2, deco, onWidget, onNode) {
  let locals = deco.locals(parent2), offset = 0;
  if (locals.length == 0) {
    for (let i2 = 0; i2 < parent2.childCount; i2++) {
      let child2 = parent2.child(i2);
      onNode(child2, locals, deco.forChild(offset, child2), i2);
      offset += child2.nodeSize;
    }
    return;
  }
  let decoIndex = 0, active = [], restNode = null;
  for (let parentIndex = 0; ; ) {
    let widget, widgets;
    while (decoIndex < locals.length && locals[decoIndex].to == offset) {
      let next = locals[decoIndex++];
      if (next.widget) {
        if (!widget)
          widget = next;
        else
          (widgets || (widgets = [widget])).push(next);
      }
    }
    if (widget) {
      if (widgets) {
        widgets.sort(compareSide);
        for (let i2 = 0; i2 < widgets.length; i2++)
          onWidget(widgets[i2], parentIndex, !!restNode);
      } else {
        onWidget(widget, parentIndex, !!restNode);
      }
    }
    let child2, index2;
    if (restNode) {
      index2 = -1;
      child2 = restNode;
      restNode = null;
    } else if (parentIndex < parent2.childCount) {
      index2 = parentIndex;
      child2 = parent2.child(parentIndex++);
    } else {
      break;
    }
    for (let i2 = 0; i2 < active.length; i2++)
      if (active[i2].to <= offset)
        active.splice(i2--, 1);
    while (decoIndex < locals.length && locals[decoIndex].from <= offset && locals[decoIndex].to > offset)
      active.push(locals[decoIndex++]);
    let end = offset + child2.nodeSize;
    if (child2.isText) {
      let cutAt = end;
      if (decoIndex < locals.length && locals[decoIndex].from < cutAt)
        cutAt = locals[decoIndex].from;
      for (let i2 = 0; i2 < active.length; i2++)
        if (active[i2].to < cutAt)
          cutAt = active[i2].to;
      if (cutAt < end) {
        restNode = child2.cut(cutAt - offset);
        child2 = child2.cut(0, cutAt - offset);
        end = cutAt;
        index2 = -1;
      }
    } else {
      while (decoIndex < locals.length && locals[decoIndex].to < end)
        decoIndex++;
    }
    let outerDeco = child2.isInline && !child2.isLeaf ? active.filter((d2) => !d2.inline) : active.slice();
    onNode(child2, outerDeco, deco.forChild(offset, child2), index2);
    offset = end;
  }
}
__name(iterDeco, "iterDeco");
function iosHacks(dom) {
  if (dom.nodeName == "UL" || dom.nodeName == "OL") {
    let oldCSS = dom.style.cssText;
    dom.style.cssText = oldCSS + "; list-style: square !important";
    window.getComputedStyle(dom).listStyle;
    dom.style.cssText = oldCSS;
  }
}
__name(iosHacks, "iosHacks");
function findTextInFragment(frag, text2, from2, to) {
  for (let i2 = 0, pos = 0; i2 < frag.childCount && pos <= to; ) {
    let child2 = frag.child(i2++), childStart = pos;
    pos += child2.nodeSize;
    if (!child2.isText)
      continue;
    let str = child2.text;
    while (i2 < frag.childCount) {
      let next = frag.child(i2++);
      pos += next.nodeSize;
      if (!next.isText)
        break;
      str += next.text;
    }
    if (pos >= from2) {
      if (pos >= to && str.slice(to - text2.length - childStart, to - childStart) == text2)
        return to - text2.length;
      let found2 = childStart < to ? str.lastIndexOf(text2, to - childStart - 1) : -1;
      if (found2 >= 0 && found2 + text2.length + childStart >= from2)
        return childStart + found2;
      if (from2 == to && str.length >= to + text2.length - childStart && str.slice(to - childStart, to - childStart + text2.length) == text2)
        return to;
    }
  }
  return -1;
}
__name(findTextInFragment, "findTextInFragment");
function replaceNodes(nodes, from2, to, view, replacement) {
  let result = [];
  for (let i2 = 0, off2 = 0; i2 < nodes.length; i2++) {
    let child2 = nodes[i2], start2 = off2, end = off2 += child2.size;
    if (start2 >= to || end <= from2) {
      result.push(child2);
    } else {
      if (start2 < from2)
        result.push(child2.slice(0, from2 - start2, view));
      if (replacement) {
        result.push(replacement);
        replacement = void 0;
      }
      if (end > to)
        result.push(child2.slice(to - start2, child2.size, view));
    }
  }
  return result;
}
__name(replaceNodes, "replaceNodes");
function selectionFromDOM(view, origin2 = null) {
  let domSel = view.domSelectionRange(), doc2 = view.state.doc;
  if (!domSel.focusNode)
    return null;
  let nearestDesc = view.docView.nearestDesc(domSel.focusNode), inWidget = nearestDesc && nearestDesc.size == 0;
  let head = view.docView.posFromDOM(domSel.focusNode, domSel.focusOffset, 1);
  if (head < 0)
    return null;
  let $head = doc2.resolve(head), anchor, selection;
  if (selectionCollapsed(domSel)) {
    anchor = head;
    while (nearestDesc && !nearestDesc.node)
      nearestDesc = nearestDesc.parent;
    let nearestDescNode = nearestDesc.node;
    if (nearestDesc && nearestDescNode.isAtom && NodeSelection.isSelectable(nearestDescNode) && nearestDesc.parent && !(nearestDescNode.isInline && isOnEdge(domSel.focusNode, domSel.focusOffset, nearestDesc.dom))) {
      let pos = nearestDesc.posBefore;
      selection = new NodeSelection(head == pos ? $head : doc2.resolve(pos));
    }
  } else {
    if (domSel instanceof view.dom.ownerDocument.defaultView.Selection && domSel.rangeCount > 1) {
      let min = head, max = head;
      for (let i2 = 0; i2 < domSel.rangeCount; i2++) {
        let range = domSel.getRangeAt(i2);
        min = Math.min(min, view.docView.posFromDOM(range.startContainer, range.startOffset, 1));
        max = Math.max(max, view.docView.posFromDOM(range.endContainer, range.endOffset, -1));
      }
      if (min < 0)
        return null;
      [anchor, head] = max == view.state.selection.anchor ? [max, min] : [min, max];
      $head = doc2.resolve(head);
    } else {
      anchor = view.docView.posFromDOM(domSel.anchorNode, domSel.anchorOffset, 1);
    }
    if (anchor < 0)
      return null;
  }
  let $anchor = doc2.resolve(anchor);
  if (!selection) {
    let bias = origin2 == "pointer" || view.state.selection.head < $head.pos && !inWidget ? 1 : -1;
    selection = selectionBetween(view, $anchor, $head, bias);
  }
  return selection;
}
__name(selectionFromDOM, "selectionFromDOM");
function editorOwnsSelection(view) {
  return view.editable ? view.hasFocus() : hasSelection(view) && document.activeElement && document.activeElement.contains(view.dom);
}
__name(editorOwnsSelection, "editorOwnsSelection");
function selectionToDOM(view, force = false) {
  let sel = view.state.selection;
  syncNodeSelection(view, sel);
  if (!editorOwnsSelection(view))
    return;
  if (!force && view.input.mouseDown && view.input.mouseDown.allowDefault && chrome$1) {
    let domSel = view.domSelectionRange(), curSel = view.domObserver.currentSelection;
    if (domSel.anchorNode && curSel.anchorNode && isEquivalentPosition(domSel.anchorNode, domSel.anchorOffset, curSel.anchorNode, curSel.anchorOffset)) {
      view.input.mouseDown.delayedSelectionSync = true;
      view.domObserver.setCurSelection();
      return;
    }
  }
  view.domObserver.disconnectSelection();
  if (view.cursorWrapper) {
    selectCursorWrapper(view);
  } else {
    let { anchor, head } = sel, resetEditableFrom, resetEditableTo;
    if (brokenSelectBetweenUneditable && !(sel instanceof TextSelection)) {
      if (!sel.$from.parent.inlineContent)
        resetEditableFrom = temporarilyEditableNear(view, sel.from);
      if (!sel.empty && !sel.$from.parent.inlineContent)
        resetEditableTo = temporarilyEditableNear(view, sel.to);
    }
    view.docView.setSelection(anchor, head, view, force);
    if (brokenSelectBetweenUneditable) {
      if (resetEditableFrom)
        resetEditable(resetEditableFrom);
      if (resetEditableTo)
        resetEditable(resetEditableTo);
    }
    if (sel.visible) {
      view.dom.classList.remove("ProseMirror-hideselection");
    } else {
      view.dom.classList.add("ProseMirror-hideselection");
      if ("onselectionchange" in document)
        removeClassOnSelectionChange(view);
    }
  }
  view.domObserver.setCurSelection();
  view.domObserver.connectSelection();
}
__name(selectionToDOM, "selectionToDOM");
const brokenSelectBetweenUneditable = safari || chrome$1 && chrome_version < 63;
function temporarilyEditableNear(view, pos) {
  let { node: node2, offset } = view.docView.domFromPos(pos, 0);
  let after = offset < node2.childNodes.length ? node2.childNodes[offset] : null;
  let before = offset ? node2.childNodes[offset - 1] : null;
  if (safari && after && after.contentEditable == "false")
    return setEditable(after);
  if ((!after || after.contentEditable == "false") && (!before || before.contentEditable == "false")) {
    if (after)
      return setEditable(after);
    else if (before)
      return setEditable(before);
  }
}
__name(temporarilyEditableNear, "temporarilyEditableNear");
function setEditable(element) {
  element.contentEditable = "true";
  if (safari && element.draggable) {
    element.draggable = false;
    element.wasDraggable = true;
  }
  return element;
}
__name(setEditable, "setEditable");
function resetEditable(element) {
  element.contentEditable = "false";
  if (element.wasDraggable) {
    element.draggable = true;
    element.wasDraggable = null;
  }
}
__name(resetEditable, "resetEditable");
function removeClassOnSelectionChange(view) {
  let doc2 = view.dom.ownerDocument;
  doc2.removeEventListener("selectionchange", view.input.hideSelectionGuard);
  let domSel = view.domSelectionRange();
  let node2 = domSel.anchorNode, offset = domSel.anchorOffset;
  doc2.addEventListener("selectionchange", view.input.hideSelectionGuard = () => {
    if (domSel.anchorNode != node2 || domSel.anchorOffset != offset) {
      doc2.removeEventListener("selectionchange", view.input.hideSelectionGuard);
      setTimeout(() => {
        if (!editorOwnsSelection(view) || view.state.selection.visible)
          view.dom.classList.remove("ProseMirror-hideselection");
      }, 20);
    }
  });
}
__name(removeClassOnSelectionChange, "removeClassOnSelectionChange");
function selectCursorWrapper(view) {
  let domSel = view.domSelection(), range = document.createRange();
  if (!domSel)
    return;
  let node2 = view.cursorWrapper.dom, img = node2.nodeName == "IMG";
  if (img)
    range.setStart(node2.parentNode, domIndex(node2) + 1);
  else
    range.setStart(node2, 0);
  range.collapse(true);
  domSel.removeAllRanges();
  domSel.addRange(range);
  if (!img && !view.state.selection.visible && ie$1 && ie_version <= 11) {
    node2.disabled = true;
    node2.disabled = false;
  }
}
__name(selectCursorWrapper, "selectCursorWrapper");
function syncNodeSelection(view, sel) {
  if (sel instanceof NodeSelection) {
    let desc = view.docView.descAt(sel.from);
    if (desc != view.lastSelectedViewDesc) {
      clearNodeSelection(view);
      if (desc)
        desc.selectNode();
      view.lastSelectedViewDesc = desc;
    }
  } else {
    clearNodeSelection(view);
  }
}
__name(syncNodeSelection, "syncNodeSelection");
function clearNodeSelection(view) {
  if (view.lastSelectedViewDesc) {
    if (view.lastSelectedViewDesc.parent)
      view.lastSelectedViewDesc.deselectNode();
    view.lastSelectedViewDesc = void 0;
  }
}
__name(clearNodeSelection, "clearNodeSelection");
function selectionBetween(view, $anchor, $head, bias) {
  return view.someProp("createSelectionBetween", (f2) => f2(view, $anchor, $head)) || TextSelection.between($anchor, $head, bias);
}
__name(selectionBetween, "selectionBetween");
function hasFocusAndSelection(view) {
  if (view.editable && !view.hasFocus())
    return false;
  return hasSelection(view);
}
__name(hasFocusAndSelection, "hasFocusAndSelection");
function hasSelection(view) {
  let sel = view.domSelectionRange();
  if (!sel.anchorNode)
    return false;
  try {
    return view.dom.contains(sel.anchorNode.nodeType == 3 ? sel.anchorNode.parentNode : sel.anchorNode) && (view.editable || view.dom.contains(sel.focusNode.nodeType == 3 ? sel.focusNode.parentNode : sel.focusNode));
  } catch (_2) {
    return false;
  }
}
__name(hasSelection, "hasSelection");
function anchorInRightPlace(view) {
  let anchorDOM = view.docView.domFromPos(view.state.selection.anchor, 0);
  let domSel = view.domSelectionRange();
  return isEquivalentPosition(anchorDOM.node, anchorDOM.offset, domSel.anchorNode, domSel.anchorOffset);
}
__name(anchorInRightPlace, "anchorInRightPlace");
function moveSelectionBlock(state, dir) {
  let { $anchor, $head } = state.selection;
  let $side = dir > 0 ? $anchor.max($head) : $anchor.min($head);
  let $start = !$side.parent.inlineContent ? $side : $side.depth ? state.doc.resolve(dir > 0 ? $side.after() : $side.before()) : null;
  return $start && Selection.findFrom($start, dir);
}
__name(moveSelectionBlock, "moveSelectionBlock");
function apply(view, sel) {
  view.dispatch(view.state.tr.setSelection(sel).scrollIntoView());
  return true;
}
__name(apply, "apply");
function selectHorizontally(view, dir, mods) {
  let sel = view.state.selection;
  if (sel instanceof TextSelection) {
    if (mods.indexOf("s") > -1) {
      let { $head } = sel, node2 = $head.textOffset ? null : dir < 0 ? $head.nodeBefore : $head.nodeAfter;
      if (!node2 || node2.isText || !node2.isLeaf)
        return false;
      let $newHead = view.state.doc.resolve($head.pos + node2.nodeSize * (dir < 0 ? -1 : 1));
      return apply(view, new TextSelection(sel.$anchor, $newHead));
    } else if (!sel.empty) {
      return false;
    } else if (view.endOfTextblock(dir > 0 ? "forward" : "backward")) {
      let next = moveSelectionBlock(view.state, dir);
      if (next && next instanceof NodeSelection)
        return apply(view, next);
      return false;
    } else if (!(mac$3 && mods.indexOf("m") > -1)) {
      let $head = sel.$head, node2 = $head.textOffset ? null : dir < 0 ? $head.nodeBefore : $head.nodeAfter, desc;
      if (!node2 || node2.isText)
        return false;
      let nodePos = dir < 0 ? $head.pos - node2.nodeSize : $head.pos;
      if (!(node2.isAtom || (desc = view.docView.descAt(nodePos)) && !desc.contentDOM))
        return false;
      if (NodeSelection.isSelectable(node2)) {
        return apply(view, new NodeSelection(dir < 0 ? view.state.doc.resolve($head.pos - node2.nodeSize) : $head));
      } else if (webkit) {
        return apply(view, new TextSelection(view.state.doc.resolve(dir < 0 ? nodePos : nodePos + node2.nodeSize)));
      } else {
        return false;
      }
    }
  } else if (sel instanceof NodeSelection && sel.node.isInline) {
    return apply(view, new TextSelection(dir > 0 ? sel.$to : sel.$from));
  } else {
    let next = moveSelectionBlock(view.state, dir);
    if (next)
      return apply(view, next);
    return false;
  }
}
__name(selectHorizontally, "selectHorizontally");
function nodeLen(node2) {
  return node2.nodeType == 3 ? node2.nodeValue.length : node2.childNodes.length;
}
__name(nodeLen, "nodeLen");
function isIgnorable(dom, dir) {
  let desc = dom.pmViewDesc;
  return desc && desc.size == 0 && (dir < 0 || dom.nextSibling || dom.nodeName != "BR");
}
__name(isIgnorable, "isIgnorable");
function skipIgnoredNodes(view, dir) {
  return dir < 0 ? skipIgnoredNodesBefore(view) : skipIgnoredNodesAfter(view);
}
__name(skipIgnoredNodes, "skipIgnoredNodes");
function skipIgnoredNodesBefore(view) {
  let sel = view.domSelectionRange();
  let node2 = sel.focusNode, offset = sel.focusOffset;
  if (!node2)
    return;
  let moveNode, moveOffset, force = false;
  if (gecko && node2.nodeType == 1 && offset < nodeLen(node2) && isIgnorable(node2.childNodes[offset], -1))
    force = true;
  for (; ; ) {
    if (offset > 0) {
      if (node2.nodeType != 1) {
        break;
      } else {
        let before = node2.childNodes[offset - 1];
        if (isIgnorable(before, -1)) {
          moveNode = node2;
          moveOffset = --offset;
        } else if (before.nodeType == 3) {
          node2 = before;
          offset = node2.nodeValue.length;
        } else
          break;
      }
    } else if (isBlockNode(node2)) {
      break;
    } else {
      let prev = node2.previousSibling;
      while (prev && isIgnorable(prev, -1)) {
        moveNode = node2.parentNode;
        moveOffset = domIndex(prev);
        prev = prev.previousSibling;
      }
      if (!prev) {
        node2 = node2.parentNode;
        if (node2 == view.dom)
          break;
        offset = 0;
      } else {
        node2 = prev;
        offset = nodeLen(node2);
      }
    }
  }
  if (force)
    setSelFocus(view, node2, offset);
  else if (moveNode)
    setSelFocus(view, moveNode, moveOffset);
}
__name(skipIgnoredNodesBefore, "skipIgnoredNodesBefore");
function skipIgnoredNodesAfter(view) {
  let sel = view.domSelectionRange();
  let node2 = sel.focusNode, offset = sel.focusOffset;
  if (!node2)
    return;
  let len = nodeLen(node2);
  let moveNode, moveOffset;
  for (; ; ) {
    if (offset < len) {
      if (node2.nodeType != 1)
        break;
      let after = node2.childNodes[offset];
      if (isIgnorable(after, 1)) {
        moveNode = node2;
        moveOffset = ++offset;
      } else
        break;
    } else if (isBlockNode(node2)) {
      break;
    } else {
      let next = node2.nextSibling;
      while (next && isIgnorable(next, 1)) {
        moveNode = next.parentNode;
        moveOffset = domIndex(next) + 1;
        next = next.nextSibling;
      }
      if (!next) {
        node2 = node2.parentNode;
        if (node2 == view.dom)
          break;
        offset = len = 0;
      } else {
        node2 = next;
        offset = 0;
        len = nodeLen(node2);
      }
    }
  }
  if (moveNode)
    setSelFocus(view, moveNode, moveOffset);
}
__name(skipIgnoredNodesAfter, "skipIgnoredNodesAfter");
function isBlockNode(dom) {
  let desc = dom.pmViewDesc;
  return desc && desc.node && desc.node.isBlock;
}
__name(isBlockNode, "isBlockNode");
function textNodeAfter(node2, offset) {
  while (node2 && offset == node2.childNodes.length && !hasBlockDesc(node2)) {
    offset = domIndex(node2) + 1;
    node2 = node2.parentNode;
  }
  while (node2 && offset < node2.childNodes.length) {
    let next = node2.childNodes[offset];
    if (next.nodeType == 3)
      return next;
    if (next.nodeType == 1 && next.contentEditable == "false")
      break;
    node2 = next;
    offset = 0;
  }
}
__name(textNodeAfter, "textNodeAfter");
function textNodeBefore(node2, offset) {
  while (node2 && !offset && !hasBlockDesc(node2)) {
    offset = domIndex(node2);
    node2 = node2.parentNode;
  }
  while (node2 && offset) {
    let next = node2.childNodes[offset - 1];
    if (next.nodeType == 3)
      return next;
    if (next.nodeType == 1 && next.contentEditable == "false")
      break;
    node2 = next;
    offset = node2.childNodes.length;
  }
}
__name(textNodeBefore, "textNodeBefore");
function setSelFocus(view, node2, offset) {
  if (node2.nodeType != 3) {
    let before, after;
    if (after = textNodeAfter(node2, offset)) {
      node2 = after;
      offset = 0;
    } else if (before = textNodeBefore(node2, offset)) {
      node2 = before;
      offset = before.nodeValue.length;
    }
  }
  let sel = view.domSelection();
  if (!sel)
    return;
  if (selectionCollapsed(sel)) {
    let range = document.createRange();
    range.setEnd(node2, offset);
    range.setStart(node2, offset);
    sel.removeAllRanges();
    sel.addRange(range);
  } else if (sel.extend) {
    sel.extend(node2, offset);
  }
  view.domObserver.setCurSelection();
  let { state } = view;
  setTimeout(() => {
    if (view.state == state)
      selectionToDOM(view);
  }, 50);
}
__name(setSelFocus, "setSelFocus");
function findDirection(view, pos) {
  let $pos = view.state.doc.resolve(pos);
  if (!(chrome$1 || windows) && $pos.parent.inlineContent) {
    let coords = view.coordsAtPos(pos);
    if (pos > $pos.start()) {
      let before = view.coordsAtPos(pos - 1);
      let mid = (before.top + before.bottom) / 2;
      if (mid > coords.top && mid < coords.bottom && Math.abs(before.left - coords.left) > 1)
        return before.left < coords.left ? "ltr" : "rtl";
    }
    if (pos < $pos.end()) {
      let after = view.coordsAtPos(pos + 1);
      let mid = (after.top + after.bottom) / 2;
      if (mid > coords.top && mid < coords.bottom && Math.abs(after.left - coords.left) > 1)
        return after.left > coords.left ? "ltr" : "rtl";
    }
  }
  let computed2 = getComputedStyle(view.dom).direction;
  return computed2 == "rtl" ? "rtl" : "ltr";
}
__name(findDirection, "findDirection");
function selectVertically(view, dir, mods) {
  let sel = view.state.selection;
  if (sel instanceof TextSelection && !sel.empty || mods.indexOf("s") > -1)
    return false;
  if (mac$3 && mods.indexOf("m") > -1)
    return false;
  let { $from, $to } = sel;
  if (!$from.parent.inlineContent || view.endOfTextblock(dir < 0 ? "up" : "down")) {
    let next = moveSelectionBlock(view.state, dir);
    if (next && next instanceof NodeSelection)
      return apply(view, next);
  }
  if (!$from.parent.inlineContent) {
    let side = dir < 0 ? $from : $to;
    let beyond = sel instanceof AllSelection ? Selection.near(side, dir) : Selection.findFrom(side, dir);
    return beyond ? apply(view, beyond) : false;
  }
  return false;
}
__name(selectVertically, "selectVertically");
function stopNativeHorizontalDelete(view, dir) {
  if (!(view.state.selection instanceof TextSelection))
    return true;
  let { $head, $anchor, empty: empty2 } = view.state.selection;
  if (!$head.sameParent($anchor))
    return true;
  if (!empty2)
    return false;
  if (view.endOfTextblock(dir > 0 ? "forward" : "backward"))
    return true;
  let nextNode = !$head.textOffset && (dir < 0 ? $head.nodeBefore : $head.nodeAfter);
  if (nextNode && !nextNode.isText) {
    let tr2 = view.state.tr;
    if (dir < 0)
      tr2.delete($head.pos - nextNode.nodeSize, $head.pos);
    else
      tr2.delete($head.pos, $head.pos + nextNode.nodeSize);
    view.dispatch(tr2);
    return true;
  }
  return false;
}
__name(stopNativeHorizontalDelete, "stopNativeHorizontalDelete");
function switchEditable(view, node2, state) {
  view.domObserver.stop();
  node2.contentEditable = state;
  view.domObserver.start();
}
__name(switchEditable, "switchEditable");
function safariDownArrowBug(view) {
  if (!safari || view.state.selection.$head.parentOffset > 0)
    return false;
  let { focusNode, focusOffset } = view.domSelectionRange();
  if (focusNode && focusNode.nodeType == 1 && focusOffset == 0 && focusNode.firstChild && focusNode.firstChild.contentEditable == "false") {
    let child2 = focusNode.firstChild;
    switchEditable(view, child2, "true");
    setTimeout(() => switchEditable(view, child2, "false"), 20);
  }
  return false;
}
__name(safariDownArrowBug, "safariDownArrowBug");
function getMods(event) {
  let result = "";
  if (event.ctrlKey)
    result += "c";
  if (event.metaKey)
    result += "m";
  if (event.altKey)
    result += "a";
  if (event.shiftKey)
    result += "s";
  return result;
}
__name(getMods, "getMods");
function captureKeyDown(view, event) {
  let code2 = event.keyCode, mods = getMods(event);
  if (code2 == 8 || mac$3 && code2 == 72 && mods == "c") {
    return stopNativeHorizontalDelete(view, -1) || skipIgnoredNodes(view, -1);
  } else if (code2 == 46 && !event.shiftKey || mac$3 && code2 == 68 && mods == "c") {
    return stopNativeHorizontalDelete(view, 1) || skipIgnoredNodes(view, 1);
  } else if (code2 == 13 || code2 == 27) {
    return true;
  } else if (code2 == 37 || mac$3 && code2 == 66 && mods == "c") {
    let dir = code2 == 37 ? findDirection(view, view.state.selection.from) == "ltr" ? -1 : 1 : -1;
    return selectHorizontally(view, dir, mods) || skipIgnoredNodes(view, dir);
  } else if (code2 == 39 || mac$3 && code2 == 70 && mods == "c") {
    let dir = code2 == 39 ? findDirection(view, view.state.selection.from) == "ltr" ? 1 : -1 : 1;
    return selectHorizontally(view, dir, mods) || skipIgnoredNodes(view, dir);
  } else if (code2 == 38 || mac$3 && code2 == 80 && mods == "c") {
    return selectVertically(view, -1, mods) || skipIgnoredNodes(view, -1);
  } else if (code2 == 40 || mac$3 && code2 == 78 && mods == "c") {
    return safariDownArrowBug(view) || selectVertically(view, 1, mods) || skipIgnoredNodes(view, 1);
  } else if (mods == (mac$3 ? "m" : "c") && (code2 == 66 || code2 == 73 || code2 == 89 || code2 == 90)) {
    return true;
  }
  return false;
}
__name(captureKeyDown, "captureKeyDown");
function serializeForClipboard(view, slice2) {
  view.someProp("transformCopied", (f2) => {
    slice2 = f2(slice2, view);
  });
  let context = [], { content, openStart, openEnd } = slice2;
  while (openStart > 1 && openEnd > 1 && content.childCount == 1 && content.firstChild.childCount == 1) {
    openStart--;
    openEnd--;
    let node2 = content.firstChild;
    context.push(node2.type.name, node2.attrs != node2.type.defaultAttrs ? node2.attrs : null);
    content = node2.content;
  }
  let serializer = view.someProp("clipboardSerializer") || DOMSerializer.fromSchema(view.state.schema);
  let doc2 = detachedDoc(), wrap2 = doc2.createElement("div");
  wrap2.appendChild(serializer.serializeFragment(content, { document: doc2 }));
  let firstChild = wrap2.firstChild, needsWrap, wrappers = 0;
  while (firstChild && firstChild.nodeType == 1 && (needsWrap = wrapMap[firstChild.nodeName.toLowerCase()])) {
    for (let i2 = needsWrap.length - 1; i2 >= 0; i2--) {
      let wrapper = doc2.createElement(needsWrap[i2]);
      while (wrap2.firstChild)
        wrapper.appendChild(wrap2.firstChild);
      wrap2.appendChild(wrapper);
      wrappers++;
    }
    firstChild = wrap2.firstChild;
  }
  if (firstChild && firstChild.nodeType == 1)
    firstChild.setAttribute("data-pm-slice", `${openStart} ${openEnd}${wrappers ? ` -${wrappers}` : ""} ${JSON.stringify(context)}`);
  let text2 = view.someProp("clipboardTextSerializer", (f2) => f2(slice2, view)) || slice2.content.textBetween(0, slice2.content.size, "\n\n");
  return { dom: wrap2, text: text2, slice: slice2 };
}
__name(serializeForClipboard, "serializeForClipboard");
function parseFromClipboard(view, text2, html, plainText, $context) {
  let inCode = $context.parent.type.spec.code;
  let dom, slice2;
  if (!html && !text2)
    return null;
  let asText = text2 && (plainText || inCode || !html);
  if (asText) {
    view.someProp("transformPastedText", (f2) => {
      text2 = f2(text2, inCode || plainText, view);
    });
    if (inCode)
      return text2 ? new Slice(Fragment.from(view.state.schema.text(text2.replace(/\r\n?/g, "\n"))), 0, 0) : Slice.empty;
    let parsed = view.someProp("clipboardTextParser", (f2) => f2(text2, $context, plainText, view));
    if (parsed) {
      slice2 = parsed;
    } else {
      let marks = $context.marks();
      let { schema: schema2 } = view.state, serializer = DOMSerializer.fromSchema(schema2);
      dom = document.createElement("div");
      text2.split(/(?:\r\n?|\n)+/).forEach((block2) => {
        let p2 = dom.appendChild(document.createElement("p"));
        if (block2)
          p2.appendChild(serializer.serializeNode(schema2.text(block2, marks)));
      });
    }
  } else {
    view.someProp("transformPastedHTML", (f2) => {
      html = f2(html, view);
    });
    dom = readHTML(html);
    if (webkit)
      restoreReplacedSpaces(dom);
  }
  let contextNode = dom && dom.querySelector("[data-pm-slice]");
  let sliceData = contextNode && /^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(contextNode.getAttribute("data-pm-slice") || "");
  if (sliceData && sliceData[3])
    for (let i2 = +sliceData[3]; i2 > 0; i2--) {
      let child2 = dom.firstChild;
      while (child2 && child2.nodeType != 1)
        child2 = child2.nextSibling;
      if (!child2)
        break;
      dom = child2;
    }
  if (!slice2) {
    let parser = view.someProp("clipboardParser") || view.someProp("domParser") || DOMParser.fromSchema(view.state.schema);
    slice2 = parser.parseSlice(dom, {
      preserveWhitespace: !!(asText || sliceData),
      context: $context,
      ruleFromNode(dom2) {
        if (dom2.nodeName == "BR" && !dom2.nextSibling && dom2.parentNode && !inlineParents.test(dom2.parentNode.nodeName))
          return { ignore: true };
        return null;
      }
    });
  }
  if (sliceData) {
    slice2 = addContext(closeSlice(slice2, +sliceData[1], +sliceData[2]), sliceData[4]);
  } else {
    slice2 = Slice.maxOpen(normalizeSiblings(slice2.content, $context), true);
    if (slice2.openStart || slice2.openEnd) {
      let openStart = 0, openEnd = 0;
      for (let node2 = slice2.content.firstChild; openStart < slice2.openStart && !node2.type.spec.isolating; openStart++, node2 = node2.firstChild) {
      }
      for (let node2 = slice2.content.lastChild; openEnd < slice2.openEnd && !node2.type.spec.isolating; openEnd++, node2 = node2.lastChild) {
      }
      slice2 = closeSlice(slice2, openStart, openEnd);
    }
  }
  view.someProp("transformPasted", (f2) => {
    slice2 = f2(slice2, view);
  });
  return slice2;
}
__name(parseFromClipboard, "parseFromClipboard");
const inlineParents = /^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i;
function normalizeSiblings(fragment, $context) {
  if (fragment.childCount < 2)
    return fragment;
  for (let d2 = $context.depth; d2 >= 0; d2--) {
    let parent2 = $context.node(d2);
    let match2 = parent2.contentMatchAt($context.index(d2));
    let lastWrap, result = [];
    fragment.forEach((node2) => {
      if (!result)
        return;
      let wrap2 = match2.findWrapping(node2.type), inLast;
      if (!wrap2)
        return result = null;
      if (inLast = result.length && lastWrap.length && addToSibling(wrap2, lastWrap, node2, result[result.length - 1], 0)) {
        result[result.length - 1] = inLast;
      } else {
        if (result.length)
          result[result.length - 1] = closeRight(result[result.length - 1], lastWrap.length);
        let wrapped = withWrappers(node2, wrap2);
        result.push(wrapped);
        match2 = match2.matchType(wrapped.type);
        lastWrap = wrap2;
      }
    });
    if (result)
      return Fragment.from(result);
  }
  return fragment;
}
__name(normalizeSiblings, "normalizeSiblings");
function withWrappers(node2, wrap2, from2 = 0) {
  for (let i2 = wrap2.length - 1; i2 >= from2; i2--)
    node2 = wrap2[i2].create(null, Fragment.from(node2));
  return node2;
}
__name(withWrappers, "withWrappers");
function addToSibling(wrap2, lastWrap, node2, sibling, depth) {
  if (depth < wrap2.length && depth < lastWrap.length && wrap2[depth] == lastWrap[depth]) {
    let inner = addToSibling(wrap2, lastWrap, node2, sibling.lastChild, depth + 1);
    if (inner)
      return sibling.copy(sibling.content.replaceChild(sibling.childCount - 1, inner));
    let match2 = sibling.contentMatchAt(sibling.childCount);
    if (match2.matchType(depth == wrap2.length - 1 ? node2.type : wrap2[depth + 1]))
      return sibling.copy(sibling.content.append(Fragment.from(withWrappers(node2, wrap2, depth + 1))));
  }
}
__name(addToSibling, "addToSibling");
function closeRight(node2, depth) {
  if (depth == 0)
    return node2;
  let fragment = node2.content.replaceChild(node2.childCount - 1, closeRight(node2.lastChild, depth - 1));
  let fill2 = node2.contentMatchAt(node2.childCount).fillBefore(Fragment.empty, true);
  return node2.copy(fragment.append(fill2));
}
__name(closeRight, "closeRight");
function closeRange(fragment, side, from2, to, depth, openEnd) {
  let node2 = side < 0 ? fragment.firstChild : fragment.lastChild, inner = node2.content;
  if (fragment.childCount > 1)
    openEnd = 0;
  if (depth < to - 1)
    inner = closeRange(inner, side, from2, to, depth + 1, openEnd);
  if (depth >= from2)
    inner = side < 0 ? node2.contentMatchAt(0).fillBefore(inner, openEnd <= depth).append(inner) : inner.append(node2.contentMatchAt(node2.childCount).fillBefore(Fragment.empty, true));
  return fragment.replaceChild(side < 0 ? 0 : fragment.childCount - 1, node2.copy(inner));
}
__name(closeRange, "closeRange");
function closeSlice(slice2, openStart, openEnd) {
  if (openStart < slice2.openStart)
    slice2 = new Slice(closeRange(slice2.content, -1, openStart, slice2.openStart, 0, slice2.openEnd), openStart, slice2.openEnd);
  if (openEnd < slice2.openEnd)
    slice2 = new Slice(closeRange(slice2.content, 1, openEnd, slice2.openEnd, 0, 0), slice2.openStart, openEnd);
  return slice2;
}
__name(closeSlice, "closeSlice");
const wrapMap = {
  thead: ["table"],
  tbody: ["table"],
  tfoot: ["table"],
  caption: ["table"],
  colgroup: ["table"],
  col: ["table", "colgroup"],
  tr: ["table", "tbody"],
  td: ["table", "tbody", "tr"],
  th: ["table", "tbody", "tr"]
};
let _detachedDoc = null;
function detachedDoc() {
  return _detachedDoc || (_detachedDoc = document.implementation.createHTMLDocument("title"));
}
__name(detachedDoc, "detachedDoc");
let _policy = null;
function maybeWrapTrusted(html) {
  let trustedTypes = window.trustedTypes;
  if (!trustedTypes)
    return html;
  if (!_policy)
    _policy = trustedTypes.createPolicy("ProseMirrorClipboard", { createHTML: /* @__PURE__ */ __name((s2) => s2, "createHTML") });
  return _policy.createHTML(html);
}
__name(maybeWrapTrusted, "maybeWrapTrusted");
function readHTML(html) {
  let metas = /^(\s*<meta [^>]*>)*/.exec(html);
  if (metas)
    html = html.slice(metas[0].length);
  let elt = detachedDoc().createElement("div");
  let firstTag = /<([a-z][^>\s]+)/i.exec(html), wrap2;
  if (wrap2 = firstTag && wrapMap[firstTag[1].toLowerCase()])
    html = wrap2.map((n2) => "<" + n2 + ">").join("") + html + wrap2.map((n2) => "</" + n2 + ">").reverse().join("");
  elt.innerHTML = maybeWrapTrusted(html);
  if (wrap2)
    for (let i2 = 0; i2 < wrap2.length; i2++)
      elt = elt.querySelector(wrap2[i2]) || elt;
  return elt;
}
__name(readHTML, "readHTML");
function restoreReplacedSpaces(dom) {
  let nodes = dom.querySelectorAll(chrome$1 ? "span:not([class]):not([style])" : "span.Apple-converted-space");
  for (let i2 = 0; i2 < nodes.length; i2++) {
    let node2 = nodes[i2];
    if (node2.childNodes.length == 1 && node2.textContent == " " && node2.parentNode)
      node2.parentNode.replaceChild(dom.ownerDocument.createTextNode(" "), node2);
  }
}
__name(restoreReplacedSpaces, "restoreReplacedSpaces");
function addContext(slice2, context) {
  if (!slice2.size)
    return slice2;
  let schema2 = slice2.content.firstChild.type.schema, array;
  try {
    array = JSON.parse(context);
  } catch (e2) {
    return slice2;
  }
  let { content, openStart, openEnd } = slice2;
  for (let i2 = array.length - 2; i2 >= 0; i2 -= 2) {
    let type = schema2.nodes[array[i2]];
    if (!type || type.hasRequiredAttrs())
      break;
    content = Fragment.from(type.create(array[i2 + 1], content));
    openStart++;
    openEnd++;
  }
  return new Slice(content, openStart, openEnd);
}
__name(addContext, "addContext");
const handlers = {};
const editHandlers = {};
const passiveHandlers = { touchstart: true, touchmove: true };
class InputState {
  static {
    __name(this, "InputState");
  }
  constructor() {
    this.shiftKey = false;
    this.mouseDown = null;
    this.lastKeyCode = null;
    this.lastKeyCodeTime = 0;
    this.lastClick = { time: 0, x: 0, y: 0, type: "" };
    this.lastSelectionOrigin = null;
    this.lastSelectionTime = 0;
    this.lastIOSEnter = 0;
    this.lastIOSEnterFallbackTimeout = -1;
    this.lastFocus = 0;
    this.lastTouch = 0;
    this.lastChromeDelete = 0;
    this.composing = false;
    this.compositionNode = null;
    this.composingTimeout = -1;
    this.compositionNodes = [];
    this.compositionEndedAt = -2e8;
    this.compositionID = 1;
    this.compositionPendingChanges = 0;
    this.domChangeCount = 0;
    this.eventHandlers = /* @__PURE__ */ Object.create(null);
    this.hideSelectionGuard = null;
  }
}
function initInput(view) {
  for (let event in handlers) {
    let handler5 = handlers[event];
    view.dom.addEventListener(event, view.input.eventHandlers[event] = (event2) => {
      if (eventBelongsToView(view, event2) && !runCustomHandler(view, event2) && (view.editable || !(event2.type in editHandlers)))
        handler5(view, event2);
    }, passiveHandlers[event] ? { passive: true } : void 0);
  }
  if (safari)
    view.dom.addEventListener("input", () => null);
  ensureListeners(view);
}
__name(initInput, "initInput");
function setSelectionOrigin(view, origin2) {
  view.input.lastSelectionOrigin = origin2;
  view.input.lastSelectionTime = Date.now();
}
__name(setSelectionOrigin, "setSelectionOrigin");
function destroyInput(view) {
  view.domObserver.stop();
  for (let type in view.input.eventHandlers)
    view.dom.removeEventListener(type, view.input.eventHandlers[type]);
  clearTimeout(view.input.composingTimeout);
  clearTimeout(view.input.lastIOSEnterFallbackTimeout);
}
__name(destroyInput, "destroyInput");
function ensureListeners(view) {
  view.someProp("handleDOMEvents", (currentHandlers) => {
    for (let type in currentHandlers)
      if (!view.input.eventHandlers[type])
        view.dom.addEventListener(type, view.input.eventHandlers[type] = (event) => runCustomHandler(view, event));
  });
}
__name(ensureListeners, "ensureListeners");
function runCustomHandler(view, event) {
  return view.someProp("handleDOMEvents", (handlers2) => {
    let handler5 = handlers2[event.type];
    return handler5 ? handler5(view, event) || event.defaultPrevented : false;
  });
}
__name(runCustomHandler, "runCustomHandler");
function eventBelongsToView(view, event) {
  if (!event.bubbles)
    return true;
  if (event.defaultPrevented)
    return false;
  for (let node2 = event.target; node2 != view.dom; node2 = node2.parentNode)
    if (!node2 || node2.nodeType == 11 || node2.pmViewDesc && node2.pmViewDesc.stopEvent(event))
      return false;
  return true;
}
__name(eventBelongsToView, "eventBelongsToView");
function dispatchEvent(view, event) {
  if (!runCustomHandler(view, event) && handlers[event.type] && (view.editable || !(event.type in editHandlers)))
    handlers[event.type](view, event);
}
__name(dispatchEvent, "dispatchEvent");
editHandlers.keydown = (view, _event) => {
  let event = _event;
  view.input.shiftKey = event.keyCode == 16 || event.shiftKey;
  if (inOrNearComposition(view, event))
    return;
  view.input.lastKeyCode = event.keyCode;
  view.input.lastKeyCodeTime = Date.now();
  if (android && chrome$1 && event.keyCode == 13)
    return;
  if (event.keyCode != 229)
    view.domObserver.forceFlush();
  if (ios && event.keyCode == 13 && !event.ctrlKey && !event.altKey && !event.metaKey) {
    let now2 = Date.now();
    view.input.lastIOSEnter = now2;
    view.input.lastIOSEnterFallbackTimeout = setTimeout(() => {
      if (view.input.lastIOSEnter == now2) {
        view.someProp("handleKeyDown", (f2) => f2(view, keyEvent(13, "Enter")));
        view.input.lastIOSEnter = 0;
      }
    }, 200);
  } else if (view.someProp("handleKeyDown", (f2) => f2(view, event)) || captureKeyDown(view, event)) {
    event.preventDefault();
  } else {
    setSelectionOrigin(view, "key");
  }
};
editHandlers.keyup = (view, event) => {
  if (event.keyCode == 16)
    view.input.shiftKey = false;
};
editHandlers.keypress = (view, _event) => {
  let event = _event;
  if (inOrNearComposition(view, event) || !event.charCode || event.ctrlKey && !event.altKey || mac$3 && event.metaKey)
    return;
  if (view.someProp("handleKeyPress", (f2) => f2(view, event))) {
    event.preventDefault();
    return;
  }
  let sel = view.state.selection;
  if (!(sel instanceof TextSelection) || !sel.$from.sameParent(sel.$to)) {
    let text2 = String.fromCharCode(event.charCode);
    if (!/[\r\n]/.test(text2) && !view.someProp("handleTextInput", (f2) => f2(view, sel.$from.pos, sel.$to.pos, text2)))
      view.dispatch(view.state.tr.insertText(text2).scrollIntoView());
    event.preventDefault();
  }
};
function eventCoords(event) {
  return { left: event.clientX, top: event.clientY };
}
__name(eventCoords, "eventCoords");
function isNear(event, click2) {
  let dx = click2.x - event.clientX, dy = click2.y - event.clientY;
  return dx * dx + dy * dy < 100;
}
__name(isNear, "isNear");
function runHandlerOnContext(view, propName, pos, inside, event) {
  if (inside == -1)
    return false;
  let $pos = view.state.doc.resolve(inside);
  for (let i2 = $pos.depth + 1; i2 > 0; i2--) {
    if (view.someProp(propName, (f2) => i2 > $pos.depth ? f2(view, pos, $pos.nodeAfter, $pos.before(i2), event, true) : f2(view, pos, $pos.node(i2), $pos.before(i2), event, false)))
      return true;
  }
  return false;
}
__name(runHandlerOnContext, "runHandlerOnContext");
function updateSelection(view, selection, origin2) {
  if (!view.focused)
    view.focus();
  if (view.state.selection.eq(selection))
    return;
  let tr2 = view.state.tr.setSelection(selection);
  if (origin2 == "pointer")
    tr2.setMeta("pointer", true);
  view.dispatch(tr2);
}
__name(updateSelection, "updateSelection");
function selectClickedLeaf(view, inside) {
  if (inside == -1)
    return false;
  let $pos = view.state.doc.resolve(inside), node2 = $pos.nodeAfter;
  if (node2 && node2.isAtom && NodeSelection.isSelectable(node2)) {
    updateSelection(view, new NodeSelection($pos), "pointer");
    return true;
  }
  return false;
}
__name(selectClickedLeaf, "selectClickedLeaf");
function selectClickedNode(view, inside) {
  if (inside == -1)
    return false;
  let sel = view.state.selection, selectedNode, selectAt;
  if (sel instanceof NodeSelection)
    selectedNode = sel.node;
  let $pos = view.state.doc.resolve(inside);
  for (let i2 = $pos.depth + 1; i2 > 0; i2--) {
    let node2 = i2 > $pos.depth ? $pos.nodeAfter : $pos.node(i2);
    if (NodeSelection.isSelectable(node2)) {
      if (selectedNode && sel.$from.depth > 0 && i2 >= sel.$from.depth && $pos.before(sel.$from.depth + 1) == sel.$from.pos)
        selectAt = $pos.before(sel.$from.depth);
      else
        selectAt = $pos.before(i2);
      break;
    }
  }
  if (selectAt != null) {
    updateSelection(view, NodeSelection.create(view.state.doc, selectAt), "pointer");
    return true;
  } else {
    return false;
  }
}
__name(selectClickedNode, "selectClickedNode");
function handleSingleClick(view, pos, inside, event, selectNode) {
  return runHandlerOnContext(view, "handleClickOn", pos, inside, event) || view.someProp("handleClick", (f2) => f2(view, pos, event)) || (selectNode ? selectClickedNode(view, inside) : selectClickedLeaf(view, inside));
}
__name(handleSingleClick, "handleSingleClick");
function handleDoubleClick(view, pos, inside, event) {
  return runHandlerOnContext(view, "handleDoubleClickOn", pos, inside, event) || view.someProp("handleDoubleClick", (f2) => f2(view, pos, event));
}
__name(handleDoubleClick, "handleDoubleClick");
function handleTripleClick$1(view, pos, inside, event) {
  return runHandlerOnContext(view, "handleTripleClickOn", pos, inside, event) || view.someProp("handleTripleClick", (f2) => f2(view, pos, event)) || defaultTripleClick(view, inside, event);
}
__name(handleTripleClick$1, "handleTripleClick$1");
function defaultTripleClick(view, inside, event) {
  if (event.button != 0)
    return false;
  let doc2 = view.state.doc;
  if (inside == -1) {
    if (doc2.inlineContent) {
      updateSelection(view, TextSelection.create(doc2, 0, doc2.content.size), "pointer");
      return true;
    }
    return false;
  }
  let $pos = doc2.resolve(inside);
  for (let i2 = $pos.depth + 1; i2 > 0; i2--) {
    let node2 = i2 > $pos.depth ? $pos.nodeAfter : $pos.node(i2);
    let nodePos = $pos.before(i2);
    if (node2.inlineContent)
      updateSelection(view, TextSelection.create(doc2, nodePos + 1, nodePos + 1 + node2.content.size), "pointer");
    else if (NodeSelection.isSelectable(node2))
      updateSelection(view, NodeSelection.create(doc2, nodePos), "pointer");
    else
      continue;
    return true;
  }
}
__name(defaultTripleClick, "defaultTripleClick");
function forceDOMFlush(view) {
  return endComposition(view);
}
__name(forceDOMFlush, "forceDOMFlush");
const selectNodeModifier = mac$3 ? "metaKey" : "ctrlKey";
handlers.mousedown = (view, _event) => {
  let event = _event;
  view.input.shiftKey = event.shiftKey;
  let flushed = forceDOMFlush(view);
  let now2 = Date.now(), type = "singleClick";
  if (now2 - view.input.lastClick.time < 500 && isNear(event, view.input.lastClick) && !event[selectNodeModifier]) {
    if (view.input.lastClick.type == "singleClick")
      type = "doubleClick";
    else if (view.input.lastClick.type == "doubleClick")
      type = "tripleClick";
  }
  view.input.lastClick = { time: now2, x: event.clientX, y: event.clientY, type };
  let pos = view.posAtCoords(eventCoords(event));
  if (!pos)
    return;
  if (type == "singleClick") {
    if (view.input.mouseDown)
      view.input.mouseDown.done();
    view.input.mouseDown = new MouseDown(view, pos, event, !!flushed);
  } else if ((type == "doubleClick" ? handleDoubleClick : handleTripleClick$1)(view, pos.pos, pos.inside, event)) {
    event.preventDefault();
  } else {
    setSelectionOrigin(view, "pointer");
  }
};
class MouseDown {
  static {
    __name(this, "MouseDown");
  }
  constructor(view, pos, event, flushed) {
    this.view = view;
    this.pos = pos;
    this.event = event;
    this.flushed = flushed;
    this.delayedSelectionSync = false;
    this.mightDrag = null;
    this.startDoc = view.state.doc;
    this.selectNode = !!event[selectNodeModifier];
    this.allowDefault = event.shiftKey;
    let targetNode, targetPos;
    if (pos.inside > -1) {
      targetNode = view.state.doc.nodeAt(pos.inside);
      targetPos = pos.inside;
    } else {
      let $pos = view.state.doc.resolve(pos.pos);
      targetNode = $pos.parent;
      targetPos = $pos.depth ? $pos.before() : 0;
    }
    const target = flushed ? null : event.target;
    const targetDesc = target ? view.docView.nearestDesc(target, true) : null;
    this.target = targetDesc && targetDesc.dom.nodeType == 1 ? targetDesc.dom : null;
    let { selection } = view.state;
    if (event.button == 0 && targetNode.type.spec.draggable && targetNode.type.spec.selectable !== false || selection instanceof NodeSelection && selection.from <= targetPos && selection.to > targetPos)
      this.mightDrag = {
        node: targetNode,
        pos: targetPos,
        addAttr: !!(this.target && !this.target.draggable),
        setUneditable: !!(this.target && gecko && !this.target.hasAttribute("contentEditable"))
      };
    if (this.target && this.mightDrag && (this.mightDrag.addAttr || this.mightDrag.setUneditable)) {
      this.view.domObserver.stop();
      if (this.mightDrag.addAttr)
        this.target.draggable = true;
      if (this.mightDrag.setUneditable)
        setTimeout(() => {
          if (this.view.input.mouseDown == this)
            this.target.setAttribute("contentEditable", "false");
        }, 20);
      this.view.domObserver.start();
    }
    view.root.addEventListener("mouseup", this.up = this.up.bind(this));
    view.root.addEventListener("mousemove", this.move = this.move.bind(this));
    setSelectionOrigin(view, "pointer");
  }
  done() {
    this.view.root.removeEventListener("mouseup", this.up);
    this.view.root.removeEventListener("mousemove", this.move);
    if (this.mightDrag && this.target) {
      this.view.domObserver.stop();
      if (this.mightDrag.addAttr)
        this.target.removeAttribute("draggable");
      if (this.mightDrag.setUneditable)
        this.target.removeAttribute("contentEditable");
      this.view.domObserver.start();
    }
    if (this.delayedSelectionSync)
      setTimeout(() => selectionToDOM(this.view));
    this.view.input.mouseDown = null;
  }
  up(event) {
    this.done();
    if (!this.view.dom.contains(event.target))
      return;
    let pos = this.pos;
    if (this.view.state.doc != this.startDoc)
      pos = this.view.posAtCoords(eventCoords(event));
    this.updateAllowDefault(event);
    if (this.allowDefault || !pos) {
      setSelectionOrigin(this.view, "pointer");
    } else if (handleSingleClick(this.view, pos.pos, pos.inside, event, this.selectNode)) {
      event.preventDefault();
    } else if (event.button == 0 && (this.flushed || // Safari ignores clicks on draggable elements
    safari && this.mightDrag && !this.mightDrag.node.isAtom || // Chrome will sometimes treat a node selection as a
    // cursor, but still report that the node is selected
    // when asked through getSelection. You'll then get a
    // situation where clicking at the point where that
    // (hidden) cursor is doesn't change the selection, and
    // thus doesn't get a reaction from ProseMirror. This
    // works around that.
    chrome$1 && !this.view.state.selection.visible && Math.min(Math.abs(pos.pos - this.view.state.selection.from), Math.abs(pos.pos - this.view.state.selection.to)) <= 2)) {
      updateSelection(this.view, Selection.near(this.view.state.doc.resolve(pos.pos)), "pointer");
      event.preventDefault();
    } else {
      setSelectionOrigin(this.view, "pointer");
    }
  }
  move(event) {
    this.updateAllowDefault(event);
    setSelectionOrigin(this.view, "pointer");
    if (event.buttons == 0)
      this.done();
  }
  updateAllowDefault(event) {
    if (!this.allowDefault && (Math.abs(this.event.x - event.clientX) > 4 || Math.abs(this.event.y - event.clientY) > 4))
      this.allowDefault = true;
  }
}
handlers.touchstart = (view) => {
  view.input.lastTouch = Date.now();
  forceDOMFlush(view);
  setSelectionOrigin(view, "pointer");
};
handlers.touchmove = (view) => {
  view.input.lastTouch = Date.now();
  setSelectionOrigin(view, "pointer");
};
handlers.contextmenu = (view) => forceDOMFlush(view);
function inOrNearComposition(view, event) {
  if (view.composing)
    return true;
  if (safari && Math.abs(event.timeStamp - view.input.compositionEndedAt) < 500) {
    view.input.compositionEndedAt = -2e8;
    return true;
  }
  return false;
}
__name(inOrNearComposition, "inOrNearComposition");
const timeoutComposition = android ? 5e3 : -1;
editHandlers.compositionstart = editHandlers.compositionupdate = (view) => {
  if (!view.composing) {
    view.domObserver.flush();
    let { state } = view, $pos = state.selection.$to;
    if (state.selection instanceof TextSelection && (state.storedMarks || !$pos.textOffset && $pos.parentOffset && $pos.nodeBefore.marks.some((m2) => m2.type.spec.inclusive === false))) {
      view.markCursor = view.state.storedMarks || $pos.marks();
      endComposition(view, true);
      view.markCursor = null;
    } else {
      endComposition(view, !state.selection.empty);
      if (gecko && state.selection.empty && $pos.parentOffset && !$pos.textOffset && $pos.nodeBefore.marks.length) {
        let sel = view.domSelectionRange();
        for (let node2 = sel.focusNode, offset = sel.focusOffset; node2 && node2.nodeType == 1 && offset != 0; ) {
          let before = offset < 0 ? node2.lastChild : node2.childNodes[offset - 1];
          if (!before)
            break;
          if (before.nodeType == 3) {
            let sel2 = view.domSelection();
            if (sel2)
              sel2.collapse(before, before.nodeValue.length);
            break;
          } else {
            node2 = before;
            offset = -1;
          }
        }
      }
    }
    view.input.composing = true;
  }
  scheduleComposeEnd(view, timeoutComposition);
};
editHandlers.compositionend = (view, event) => {
  if (view.composing) {
    view.input.composing = false;
    view.input.compositionEndedAt = event.timeStamp;
    view.input.compositionPendingChanges = view.domObserver.pendingRecords().length ? view.input.compositionID : 0;
    view.input.compositionNode = null;
    if (view.input.compositionPendingChanges)
      Promise.resolve().then(() => view.domObserver.flush());
    view.input.compositionID++;
    scheduleComposeEnd(view, 20);
  }
};
function scheduleComposeEnd(view, delay) {
  clearTimeout(view.input.composingTimeout);
  if (delay > -1)
    view.input.composingTimeout = setTimeout(() => endComposition(view), delay);
}
__name(scheduleComposeEnd, "scheduleComposeEnd");
function clearComposition(view) {
  if (view.composing) {
    view.input.composing = false;
    view.input.compositionEndedAt = timestampFromCustomEvent();
  }
  while (view.input.compositionNodes.length > 0)
    view.input.compositionNodes.pop().markParentsDirty();
}
__name(clearComposition, "clearComposition");
function findCompositionNode(view) {
  let sel = view.domSelectionRange();
  if (!sel.focusNode)
    return null;
  let textBefore = textNodeBefore$1(sel.focusNode, sel.focusOffset);
  let textAfter = textNodeAfter$1(sel.focusNode, sel.focusOffset);
  if (textBefore && textAfter && textBefore != textAfter) {
    let descAfter = textAfter.pmViewDesc, lastChanged = view.domObserver.lastChangedTextNode;
    if (textBefore == lastChanged || textAfter == lastChanged)
      return lastChanged;
    if (!descAfter || !descAfter.isText(textAfter.nodeValue)) {
      return textAfter;
    } else if (view.input.compositionNode == textAfter) {
      let descBefore = textBefore.pmViewDesc;
      if (!(!descBefore || !descBefore.isText(textBefore.nodeValue)))
        return textAfter;
    }
  }
  return textBefore || textAfter;
}
__name(findCompositionNode, "findCompositionNode");
function timestampFromCustomEvent() {
  let event = document.createEvent("Event");
  event.initEvent("event", true, true);
  return event.timeStamp;
}
__name(timestampFromCustomEvent, "timestampFromCustomEvent");
function endComposition(view, restarting = false) {
  if (android && view.domObserver.flushingSoon >= 0)
    return;
  view.domObserver.forceFlush();
  clearComposition(view);
  if (restarting || view.docView && view.docView.dirty) {
    let sel = selectionFromDOM(view);
    if (sel && !sel.eq(view.state.selection))
      view.dispatch(view.state.tr.setSelection(sel));
    else if ((view.markCursor || restarting) && !view.state.selection.empty)
      view.dispatch(view.state.tr.deleteSelection());
    else
      view.updateState(view.state);
    return true;
  }
  return false;
}
__name(endComposition, "endComposition");
function captureCopy(view, dom) {
  if (!view.dom.parentNode)
    return;
  let wrap2 = view.dom.parentNode.appendChild(document.createElement("div"));
  wrap2.appendChild(dom);
  wrap2.style.cssText = "position: fixed; left: -10000px; top: 10px";
  let sel = getSelection(), range = document.createRange();
  range.selectNodeContents(dom);
  view.dom.blur();
  sel.removeAllRanges();
  sel.addRange(range);
  setTimeout(() => {
    if (wrap2.parentNode)
      wrap2.parentNode.removeChild(wrap2);
    view.focus();
  }, 50);
}
__name(captureCopy, "captureCopy");
const brokenClipboardAPI = ie$1 && ie_version < 15 || ios && webkit_version < 604;
handlers.copy = editHandlers.cut = (view, _event) => {
  let event = _event;
  let sel = view.state.selection, cut2 = event.type == "cut";
  if (sel.empty)
    return;
  let data = brokenClipboardAPI ? null : event.clipboardData;
  let slice2 = sel.content(), { dom, text: text2 } = serializeForClipboard(view, slice2);
  if (data) {
    event.preventDefault();
    data.clearData();
    data.setData("text/html", dom.innerHTML);
    data.setData("text/plain", text2);
  } else {
    captureCopy(view, dom);
  }
  if (cut2)
    view.dispatch(view.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent", "cut"));
};
function sliceSingleNode(slice2) {
  return slice2.openStart == 0 && slice2.openEnd == 0 && slice2.content.childCount == 1 ? slice2.content.firstChild : null;
}
__name(sliceSingleNode, "sliceSingleNode");
function capturePaste(view, event) {
  if (!view.dom.parentNode)
    return;
  let plainText = view.input.shiftKey || view.state.selection.$from.parent.type.spec.code;
  let target = view.dom.parentNode.appendChild(document.createElement(plainText ? "textarea" : "div"));
  if (!plainText)
    target.contentEditable = "true";
  target.style.cssText = "position: fixed; left: -10000px; top: 10px";
  target.focus();
  let plain = view.input.shiftKey && view.input.lastKeyCode != 45;
  setTimeout(() => {
    view.focus();
    if (target.parentNode)
      target.parentNode.removeChild(target);
    if (plainText)
      doPaste(view, target.value, null, plain, event);
    else
      doPaste(view, target.textContent, target.innerHTML, plain, event);
  }, 50);
}
__name(capturePaste, "capturePaste");
function doPaste(view, text2, html, preferPlain, event) {
  let slice2 = parseFromClipboard(view, text2, html, preferPlain, view.state.selection.$from);
  if (view.someProp("handlePaste", (f2) => f2(view, event, slice2 || Slice.empty)))
    return true;
  if (!slice2)
    return false;
  let singleNode = sliceSingleNode(slice2);
  let tr2 = singleNode ? view.state.tr.replaceSelectionWith(singleNode, preferPlain) : view.state.tr.replaceSelection(slice2);
  view.dispatch(tr2.scrollIntoView().setMeta("paste", true).setMeta("uiEvent", "paste"));
  return true;
}
__name(doPaste, "doPaste");
function getText$1(clipboardData) {
  let text2 = clipboardData.getData("text/plain") || clipboardData.getData("Text");
  if (text2)
    return text2;
  let uris = clipboardData.getData("text/uri-list");
  return uris ? uris.replace(/\r?\n/g, " ") : "";
}
__name(getText$1, "getText$1");
editHandlers.paste = (view, _event) => {
  let event = _event;
  if (view.composing && !android)
    return;
  let data = brokenClipboardAPI ? null : event.clipboardData;
  let plain = view.input.shiftKey && view.input.lastKeyCode != 45;
  if (data && doPaste(view, getText$1(data), data.getData("text/html"), plain, event))
    event.preventDefault();
  else
    capturePaste(view, event);
};
class Dragging {
  static {
    __name(this, "Dragging");
  }
  constructor(slice2, move, node2) {
    this.slice = slice2;
    this.move = move;
    this.node = node2;
  }
}
const dragCopyModifier = mac$3 ? "altKey" : "ctrlKey";
handlers.dragstart = (view, _event) => {
  let event = _event;
  let mouseDown = view.input.mouseDown;
  if (mouseDown)
    mouseDown.done();
  if (!event.dataTransfer)
    return;
  let sel = view.state.selection;
  let pos = sel.empty ? null : view.posAtCoords(eventCoords(event));
  let node2;
  if (pos && pos.pos >= sel.from && pos.pos <= (sel instanceof NodeSelection ? sel.to - 1 : sel.to)) ;
  else if (mouseDown && mouseDown.mightDrag) {
    node2 = NodeSelection.create(view.state.doc, mouseDown.mightDrag.pos);
  } else if (event.target && event.target.nodeType == 1) {
    let desc = view.docView.nearestDesc(event.target, true);
    if (desc && desc.node.type.spec.draggable && desc != view.docView)
      node2 = NodeSelection.create(view.state.doc, desc.posBefore);
  }
  let draggedSlice = (node2 || view.state.selection).content();
  let { dom, text: text2, slice: slice2 } = serializeForClipboard(view, draggedSlice);
  if (!event.dataTransfer.files.length || !chrome$1 || chrome_version > 120)
    event.dataTransfer.clearData();
  event.dataTransfer.setData(brokenClipboardAPI ? "Text" : "text/html", dom.innerHTML);
  event.dataTransfer.effectAllowed = "copyMove";
  if (!brokenClipboardAPI)
    event.dataTransfer.setData("text/plain", text2);
  view.dragging = new Dragging(slice2, !event[dragCopyModifier], node2);
};
handlers.dragend = (view) => {
  let dragging = view.dragging;
  window.setTimeout(() => {
    if (view.dragging == dragging)
      view.dragging = null;
  }, 50);
};
editHandlers.dragover = editHandlers.dragenter = (_2, e2) => e2.preventDefault();
editHandlers.drop = (view, _event) => {
  let event = _event;
  let dragging = view.dragging;
  view.dragging = null;
  if (!event.dataTransfer)
    return;
  let eventPos = view.posAtCoords(eventCoords(event));
  if (!eventPos)
    return;
  let $mouse = view.state.doc.resolve(eventPos.pos);
  let slice2 = dragging && dragging.slice;
  if (slice2) {
    view.someProp("transformPasted", (f2) => {
      slice2 = f2(slice2, view);
    });
  } else {
    slice2 = parseFromClipboard(view, getText$1(event.dataTransfer), brokenClipboardAPI ? null : event.dataTransfer.getData("text/html"), false, $mouse);
  }
  let move = !!(dragging && !event[dragCopyModifier]);
  if (view.someProp("handleDrop", (f2) => f2(view, event, slice2 || Slice.empty, move))) {
    event.preventDefault();
    return;
  }
  if (!slice2)
    return;
  event.preventDefault();
  let insertPos = slice2 ? dropPoint(view.state.doc, $mouse.pos, slice2) : $mouse.pos;
  if (insertPos == null)
    insertPos = $mouse.pos;
  let tr2 = view.state.tr;
  if (move) {
    let { node: node2 } = dragging;
    if (node2)
      node2.replace(tr2);
    else
      tr2.deleteSelection();
  }
  let pos = tr2.mapping.map(insertPos);
  let isNode2 = slice2.openStart == 0 && slice2.openEnd == 0 && slice2.content.childCount == 1;
  let beforeInsert = tr2.doc;
  if (isNode2)
    tr2.replaceRangeWith(pos, pos, slice2.content.firstChild);
  else
    tr2.replaceRange(pos, pos, slice2);
  if (tr2.doc.eq(beforeInsert))
    return;
  let $pos = tr2.doc.resolve(pos);
  if (isNode2 && NodeSelection.isSelectable(slice2.content.firstChild) && $pos.nodeAfter && $pos.nodeAfter.sameMarkup(slice2.content.firstChild)) {
    tr2.setSelection(new NodeSelection($pos));
  } else {
    let end = tr2.mapping.map(insertPos);
    tr2.mapping.maps[tr2.mapping.maps.length - 1].forEach((_from, _to, _newFrom, newTo) => end = newTo);
    tr2.setSelection(selectionBetween(view, $pos, tr2.doc.resolve(end)));
  }
  view.focus();
  view.dispatch(tr2.setMeta("uiEvent", "drop"));
};
handlers.focus = (view) => {
  view.input.lastFocus = Date.now();
  if (!view.focused) {
    view.domObserver.stop();
    view.dom.classList.add("ProseMirror-focused");
    view.domObserver.start();
    view.focused = true;
    setTimeout(() => {
      if (view.docView && view.hasFocus() && !view.domObserver.currentSelection.eq(view.domSelectionRange()))
        selectionToDOM(view);
    }, 20);
  }
};
handlers.blur = (view, _event) => {
  let event = _event;
  if (view.focused) {
    view.domObserver.stop();
    view.dom.classList.remove("ProseMirror-focused");
    view.domObserver.start();
    if (event.relatedTarget && view.dom.contains(event.relatedTarget))
      view.domObserver.currentSelection.clear();
    view.focused = false;
  }
};
handlers.beforeinput = (view, _event) => {
  let event = _event;
  if (chrome$1 && android && event.inputType == "deleteContentBackward") {
    view.domObserver.flushSoon();
    let { domChangeCount } = view.input;
    setTimeout(() => {
      if (view.input.domChangeCount != domChangeCount)
        return;
      view.dom.blur();
      view.focus();
      if (view.someProp("handleKeyDown", (f2) => f2(view, keyEvent(8, "Backspace"))))
        return;
      let { $cursor } = view.state.selection;
      if ($cursor && $cursor.pos > 0)
        view.dispatch(view.state.tr.delete($cursor.pos - 1, $cursor.pos).scrollIntoView());
    }, 50);
  }
};
for (let prop2 in editHandlers)
  handlers[prop2] = editHandlers[prop2];
function compareObjs(a2, b2) {
  if (a2 == b2)
    return true;
  for (let p2 in a2)
    if (a2[p2] !== b2[p2])
      return false;
  for (let p2 in b2)
    if (!(p2 in a2))
      return false;
  return true;
}
__name(compareObjs, "compareObjs");
class WidgetType {
  static {
    __name(this, "WidgetType");
  }
  constructor(toDOM, spec) {
    this.toDOM = toDOM;
    this.spec = spec || noSpec;
    this.side = this.spec.side || 0;
  }
  map(mapping, span, offset, oldOffset) {
    let { pos, deleted } = mapping.mapResult(span.from + oldOffset, this.side < 0 ? -1 : 1);
    return deleted ? null : new Decoration(pos - offset, pos - offset, this);
  }
  valid() {
    return true;
  }
  eq(other) {
    return this == other || other instanceof WidgetType && (this.spec.key && this.spec.key == other.spec.key || this.toDOM == other.toDOM && compareObjs(this.spec, other.spec));
  }
  destroy(node2) {
    if (this.spec.destroy)
      this.spec.destroy(node2);
  }
}
class InlineType {
  static {
    __name(this, "InlineType");
  }
  constructor(attrs2, spec) {
    this.attrs = attrs2;
    this.spec = spec || noSpec;
  }
  map(mapping, span, offset, oldOffset) {
    let from2 = mapping.map(span.from + oldOffset, this.spec.inclusiveStart ? -1 : 1) - offset;
    let to = mapping.map(span.to + oldOffset, this.spec.inclusiveEnd ? 1 : -1) - offset;
    return from2 >= to ? null : new Decoration(from2, to, this);
  }
  valid(_2, span) {
    return span.from < span.to;
  }
  eq(other) {
    return this == other || other instanceof InlineType && compareObjs(this.attrs, other.attrs) && compareObjs(this.spec, other.spec);
  }
  static is(span) {
    return span.type instanceof InlineType;
  }
  destroy() {
  }
}
class NodeType {
  static {
    __name(this, "NodeType");
  }
  constructor(attrs2, spec) {
    this.attrs = attrs2;
    this.spec = spec || noSpec;
  }
  map(mapping, span, offset, oldOffset) {
    let from2 = mapping.mapResult(span.from + oldOffset, 1);
    if (from2.deleted)
      return null;
    let to = mapping.mapResult(span.to + oldOffset, -1);
    if (to.deleted || to.pos <= from2.pos)
      return null;
    return new Decoration(from2.pos - offset, to.pos - offset, this);
  }
  valid(node2, span) {
    let { index: index2, offset } = node2.content.findIndex(span.from), child2;
    return offset == span.from && !(child2 = node2.child(index2)).isText && offset + child2.nodeSize == span.to;
  }
  eq(other) {
    return this == other || other instanceof NodeType && compareObjs(this.attrs, other.attrs) && compareObjs(this.spec, other.spec);
  }
  destroy() {
  }
}
class Decoration {
  static {
    __name(this, "Decoration");
  }
  /**
  @internal
  */
  constructor(from2, to, type) {
    this.from = from2;
    this.to = to;
    this.type = type;
  }
  /**
  @internal
  */
  copy(from2, to) {
    return new Decoration(from2, to, this.type);
  }
  /**
  @internal
  */
  eq(other, offset = 0) {
    return this.type.eq(other.type) && this.from + offset == other.from && this.to + offset == other.to;
  }
  /**
  @internal
  */
  map(mapping, offset, oldOffset) {
    return this.type.map(mapping, this, offset, oldOffset);
  }
  /**
  Creates a widget decoration, which is a DOM node that's shown in
  the document at the given position. It is recommended that you
  delay rendering the widget by passing a function that will be
  called when the widget is actually drawn in a view, but you can
  also directly pass a DOM node. `getPos` can be used to find the
  widget's current document position.
  */
  static widget(pos, toDOM, spec) {
    return new Decoration(pos, pos, new WidgetType(toDOM, spec));
  }
  /**
  Creates an inline decoration, which adds the given attributes to
  each inline node between `from` and `to`.
  */
  static inline(from2, to, attrs2, spec) {
    return new Decoration(from2, to, new InlineType(attrs2, spec));
  }
  /**
  Creates a node decoration. `from` and `to` should point precisely
  before and after a node in the document. That node, and only that
  node, will receive the given attributes.
  */
  static node(from2, to, attrs2, spec) {
    return new Decoration(from2, to, new NodeType(attrs2, spec));
  }
  /**
  The spec provided when creating this decoration. Can be useful
  if you've stored extra information in that object.
  */
  get spec() {
    return this.type.spec;
  }
  /**
  @internal
  */
  get inline() {
    return this.type instanceof InlineType;
  }
  /**
  @internal
  */
  get widget() {
    return this.type instanceof WidgetType;
  }
}
const none = [], noSpec = {};
class DecorationSet {
  static {
    __name(this, "DecorationSet");
  }
  /**
  @internal
  */
  constructor(local, children) {
    this.local = local.length ? local : none;
    this.children = children.length ? children : none;
  }
  /**
  Create a set of decorations, using the structure of the given
  document. This will consume (modify) the `decorations` array, so
  you must make a copy if you want need to preserve that.
  */
  static create(doc2, decorations) {
    return decorations.length ? buildTree(decorations, doc2, 0, noSpec) : empty;
  }
  /**
  Find all decorations in this set which touch the given range
  (including decorations that start or end directly at the
  boundaries) and match the given predicate on their spec. When
  `start` and `end` are omitted, all decorations in the set are
  considered. When `predicate` isn't given, all decorations are
  assumed to match.
  */
  find(start2, end, predicate) {
    let result = [];
    this.findInner(start2 == null ? 0 : start2, end == null ? 1e9 : end, result, 0, predicate);
    return result;
  }
  findInner(start2, end, result, offset, predicate) {
    for (let i2 = 0; i2 < this.local.length; i2++) {
      let span = this.local[i2];
      if (span.from <= end && span.to >= start2 && (!predicate || predicate(span.spec)))
        result.push(span.copy(span.from + offset, span.to + offset));
    }
    for (let i2 = 0; i2 < this.children.length; i2 += 3) {
      if (this.children[i2] < end && this.children[i2 + 1] > start2) {
        let childOff = this.children[i2] + 1;
        this.children[i2 + 2].findInner(start2 - childOff, end - childOff, result, offset + childOff, predicate);
      }
    }
  }
  /**
  Map the set of decorations in response to a change in the
  document.
  */
  map(mapping, doc2, options2) {
    if (this == empty || mapping.maps.length == 0)
      return this;
    return this.mapInner(mapping, doc2, 0, 0, options2 || noSpec);
  }
  /**
  @internal
  */
  mapInner(mapping, node2, offset, oldOffset, options2) {
    let newLocal;
    for (let i2 = 0; i2 < this.local.length; i2++) {
      let mapped = this.local[i2].map(mapping, offset, oldOffset);
      if (mapped && mapped.type.valid(node2, mapped))
        (newLocal || (newLocal = [])).push(mapped);
      else if (options2.onRemove)
        options2.onRemove(this.local[i2].spec);
    }
    if (this.children.length)
      return mapChildren(this.children, newLocal || [], mapping, node2, offset, oldOffset, options2);
    else
      return newLocal ? new DecorationSet(newLocal.sort(byPos), none) : empty;
  }
  /**
  Add the given array of decorations to the ones in the set,
  producing a new set. Consumes the `decorations` array. Needs
  access to the current document to create the appropriate tree
  structure.
  */
  add(doc2, decorations) {
    if (!decorations.length)
      return this;
    if (this == empty)
      return DecorationSet.create(doc2, decorations);
    return this.addInner(doc2, decorations, 0);
  }
  addInner(doc2, decorations, offset) {
    let children, childIndex = 0;
    doc2.forEach((childNode, childOffset) => {
      let baseOffset = childOffset + offset, found2;
      if (!(found2 = takeSpansForNode(decorations, childNode, baseOffset)))
        return;
      if (!children)
        children = this.children.slice();
      while (childIndex < children.length && children[childIndex] < childOffset)
        childIndex += 3;
      if (children[childIndex] == childOffset)
        children[childIndex + 2] = children[childIndex + 2].addInner(childNode, found2, baseOffset + 1);
      else
        children.splice(childIndex, 0, childOffset, childOffset + childNode.nodeSize, buildTree(found2, childNode, baseOffset + 1, noSpec));
      childIndex += 3;
    });
    let local = moveSpans(childIndex ? withoutNulls(decorations) : decorations, -offset);
    for (let i2 = 0; i2 < local.length; i2++)
      if (!local[i2].type.valid(doc2, local[i2]))
        local.splice(i2--, 1);
    return new DecorationSet(local.length ? this.local.concat(local).sort(byPos) : this.local, children || this.children);
  }
  /**
  Create a new set that contains the decorations in this set, minus
  the ones in the given array.
  */
  remove(decorations) {
    if (decorations.length == 0 || this == empty)
      return this;
    return this.removeInner(decorations, 0);
  }
  removeInner(decorations, offset) {
    let children = this.children, local = this.local;
    for (let i2 = 0; i2 < children.length; i2 += 3) {
      let found2;
      let from2 = children[i2] + offset, to = children[i2 + 1] + offset;
      for (let j2 = 0, span; j2 < decorations.length; j2++)
        if (span = decorations[j2]) {
          if (span.from > from2 && span.to < to) {
            decorations[j2] = null;
            (found2 || (found2 = [])).push(span);
          }
        }
      if (!found2)
        continue;
      if (children == this.children)
        children = this.children.slice();
      let removed = children[i2 + 2].removeInner(found2, from2 + 1);
      if (removed != empty) {
        children[i2 + 2] = removed;
      } else {
        children.splice(i2, 3);
        i2 -= 3;
      }
    }
    if (local.length) {
      for (let i2 = 0, span; i2 < decorations.length; i2++)
        if (span = decorations[i2]) {
          for (let j2 = 0; j2 < local.length; j2++)
            if (local[j2].eq(span, offset)) {
              if (local == this.local)
                local = this.local.slice();
              local.splice(j2--, 1);
            }
        }
    }
    if (children == this.children && local == this.local)
      return this;
    return local.length || children.length ? new DecorationSet(local, children) : empty;
  }
  forChild(offset, node2) {
    if (this == empty)
      return this;
    if (node2.isLeaf)
      return DecorationSet.empty;
    let child2, local;
    for (let i2 = 0; i2 < this.children.length; i2 += 3)
      if (this.children[i2] >= offset) {
        if (this.children[i2] == offset)
          child2 = this.children[i2 + 2];
        break;
      }
    let start2 = offset + 1, end = start2 + node2.content.size;
    for (let i2 = 0; i2 < this.local.length; i2++) {
      let dec = this.local[i2];
      if (dec.from < end && dec.to > start2 && dec.type instanceof InlineType) {
        let from2 = Math.max(start2, dec.from) - start2, to = Math.min(end, dec.to) - start2;
        if (from2 < to)
          (local || (local = [])).push(dec.copy(from2, to));
      }
    }
    if (local) {
      let localSet = new DecorationSet(local.sort(byPos), none);
      return child2 ? new DecorationGroup([localSet, child2]) : localSet;
    }
    return child2 || empty;
  }
  /**
  @internal
  */
  eq(other) {
    if (this == other)
      return true;
    if (!(other instanceof DecorationSet) || this.local.length != other.local.length || this.children.length != other.children.length)
      return false;
    for (let i2 = 0; i2 < this.local.length; i2++)
      if (!this.local[i2].eq(other.local[i2]))
        return false;
    for (let i2 = 0; i2 < this.children.length; i2 += 3)
      if (this.children[i2] != other.children[i2] || this.children[i2 + 1] != other.children[i2 + 1] || !this.children[i2 + 2].eq(other.children[i2 + 2]))
        return false;
    return true;
  }
  /**
  @internal
  */
  locals(node2) {
    return removeOverlap(this.localsInner(node2));
  }
  /**
  @internal
  */
  localsInner(node2) {
    if (this == empty)
      return none;
    if (node2.inlineContent || !this.local.some(InlineType.is))
      return this.local;
    let result = [];
    for (let i2 = 0; i2 < this.local.length; i2++) {
      if (!(this.local[i2].type instanceof InlineType))
        result.push(this.local[i2]);
    }
    return result;
  }
  forEachSet(f2) {
    f2(this);
  }
}
DecorationSet.empty = new DecorationSet([], []);
DecorationSet.removeOverlap = removeOverlap;
const empty = DecorationSet.empty;
class DecorationGroup {
  static {
    __name(this, "DecorationGroup");
  }
  constructor(members) {
    this.members = members;
  }
  map(mapping, doc2) {
    const mappedDecos = this.members.map((member) => member.map(mapping, doc2, noSpec));
    return DecorationGroup.from(mappedDecos);
  }
  forChild(offset, child2) {
    if (child2.isLeaf)
      return DecorationSet.empty;
    let found2 = [];
    for (let i2 = 0; i2 < this.members.length; i2++) {
      let result = this.members[i2].forChild(offset, child2);
      if (result == empty)
        continue;
      if (result instanceof DecorationGroup)
        found2 = found2.concat(result.members);
      else
        found2.push(result);
    }
    return DecorationGroup.from(found2);
  }
  eq(other) {
    if (!(other instanceof DecorationGroup) || other.members.length != this.members.length)
      return false;
    for (let i2 = 0; i2 < this.members.length; i2++)
      if (!this.members[i2].eq(other.members[i2]))
        return false;
    return true;
  }
  locals(node2) {
    let result, sorted = true;
    for (let i2 = 0; i2 < this.members.length; i2++) {
      let locals = this.members[i2].localsInner(node2);
      if (!locals.length)
        continue;
      if (!result) {
        result = locals;
      } else {
        if (sorted) {
          result = result.slice();
          sorted = false;
        }
        for (let j2 = 0; j2 < locals.length; j2++)
          result.push(locals[j2]);
      }
    }
    return result ? removeOverlap(sorted ? result : result.sort(byPos)) : none;
  }
  // Create a group for the given array of decoration sets, or return
  // a single set when possible.
  static from(members) {
    switch (members.length) {
      case 0:
        return empty;
      case 1:
        return members[0];
      default:
        return new DecorationGroup(members.every((m2) => m2 instanceof DecorationSet) ? members : members.reduce((r2, m2) => r2.concat(m2 instanceof DecorationSet ? m2 : m2.members), []));
    }
  }
  forEachSet(f2) {
    for (let i2 = 0; i2 < this.members.length; i2++)
      this.members[i2].forEachSet(f2);
  }
}
function mapChildren(oldChildren, newLocal, mapping, node2, offset, oldOffset, options2) {
  let children = oldChildren.slice();
  for (let i2 = 0, baseOffset = oldOffset; i2 < mapping.maps.length; i2++) {
    let moved = 0;
    mapping.maps[i2].forEach((oldStart, oldEnd, newStart, newEnd) => {
      let dSize = newEnd - newStart - (oldEnd - oldStart);
      for (let i3 = 0; i3 < children.length; i3 += 3) {
        let end = children[i3 + 1];
        if (end < 0 || oldStart > end + baseOffset - moved)
          continue;
        let start2 = children[i3] + baseOffset - moved;
        if (oldEnd >= start2) {
          children[i3 + 1] = oldStart <= start2 ? -2 : -1;
        } else if (oldStart >= baseOffset && dSize) {
          children[i3] += dSize;
          children[i3 + 1] += dSize;
        }
      }
      moved += dSize;
    });
    baseOffset = mapping.maps[i2].map(baseOffset, -1);
  }
  let mustRebuild = false;
  for (let i2 = 0; i2 < children.length; i2 += 3)
    if (children[i2 + 1] < 0) {
      if (children[i2 + 1] == -2) {
        mustRebuild = true;
        children[i2 + 1] = -1;
        continue;
      }
      let from2 = mapping.map(oldChildren[i2] + oldOffset), fromLocal = from2 - offset;
      if (fromLocal < 0 || fromLocal >= node2.content.size) {
        mustRebuild = true;
        continue;
      }
      let to = mapping.map(oldChildren[i2 + 1] + oldOffset, -1), toLocal = to - offset;
      let { index: index2, offset: childOffset } = node2.content.findIndex(fromLocal);
      let childNode = node2.maybeChild(index2);
      if (childNode && childOffset == fromLocal && childOffset + childNode.nodeSize == toLocal) {
        let mapped = children[i2 + 2].mapInner(mapping, childNode, from2 + 1, oldChildren[i2] + oldOffset + 1, options2);
        if (mapped != empty) {
          children[i2] = fromLocal;
          children[i2 + 1] = toLocal;
          children[i2 + 2] = mapped;
        } else {
          children[i2 + 1] = -2;
          mustRebuild = true;
        }
      } else {
        mustRebuild = true;
      }
    }
  if (mustRebuild) {
    let decorations = mapAndGatherRemainingDecorations(children, oldChildren, newLocal, mapping, offset, oldOffset, options2);
    let built = buildTree(decorations, node2, 0, options2);
    newLocal = built.local;
    for (let i2 = 0; i2 < children.length; i2 += 3)
      if (children[i2 + 1] < 0) {
        children.splice(i2, 3);
        i2 -= 3;
      }
    for (let i2 = 0, j2 = 0; i2 < built.children.length; i2 += 3) {
      let from2 = built.children[i2];
      while (j2 < children.length && children[j2] < from2)
        j2 += 3;
      children.splice(j2, 0, built.children[i2], built.children[i2 + 1], built.children[i2 + 2]);
    }
  }
  return new DecorationSet(newLocal.sort(byPos), children);
}
__name(mapChildren, "mapChildren");
function moveSpans(spans, offset) {
  if (!offset || !spans.length)
    return spans;
  let result = [];
  for (let i2 = 0; i2 < spans.length; i2++) {
    let span = spans[i2];
    result.push(new Decoration(span.from + offset, span.to + offset, span.type));
  }
  return result;
}
__name(moveSpans, "moveSpans");
function mapAndGatherRemainingDecorations(children, oldChildren, decorations, mapping, offset, oldOffset, options2) {
  function gather(set3, oldOffset2) {
    for (let i2 = 0; i2 < set3.local.length; i2++) {
      let mapped = set3.local[i2].map(mapping, offset, oldOffset2);
      if (mapped)
        decorations.push(mapped);
      else if (options2.onRemove)
        options2.onRemove(set3.local[i2].spec);
    }
    for (let i2 = 0; i2 < set3.children.length; i2 += 3)
      gather(set3.children[i2 + 2], set3.children[i2] + oldOffset2 + 1);
  }
  __name(gather, "gather");
  for (let i2 = 0; i2 < children.length; i2 += 3)
    if (children[i2 + 1] == -1)
      gather(children[i2 + 2], oldChildren[i2] + oldOffset + 1);
  return decorations;
}
__name(mapAndGatherRemainingDecorations, "mapAndGatherRemainingDecorations");
function takeSpansForNode(spans, node2, offset) {
  if (node2.isLeaf)
    return null;
  let end = offset + node2.nodeSize, found2 = null;
  for (let i2 = 0, span; i2 < spans.length; i2++) {
    if ((span = spans[i2]) && span.from > offset && span.to < end) {
      (found2 || (found2 = [])).push(span);
      spans[i2] = null;
    }
  }
  return found2;
}
__name(takeSpansForNode, "takeSpansForNode");
function withoutNulls(array) {
  let result = [];
  for (let i2 = 0; i2 < array.length; i2++)
    if (array[i2] != null)
      result.push(array[i2]);
  return result;
}
__name(withoutNulls, "withoutNulls");
function buildTree(spans, node2, offset, options2) {
  let children = [], hasNulls = false;
  node2.forEach((childNode, localStart) => {
    let found2 = takeSpansForNode(spans, childNode, localStart + offset);
    if (found2) {
      hasNulls = true;
      let subtree = buildTree(found2, childNode, offset + localStart + 1, options2);
      if (subtree != empty)
        children.push(localStart, localStart + childNode.nodeSize, subtree);
    }
  });
  let locals = moveSpans(hasNulls ? withoutNulls(spans) : spans, -offset).sort(byPos);
  for (let i2 = 0; i2 < locals.length; i2++)
    if (!locals[i2].type.valid(node2, locals[i2])) {
      if (options2.onRemove)
        options2.onRemove(locals[i2].spec);
      locals.splice(i2--, 1);
    }
  return locals.length || children.length ? new DecorationSet(locals, children) : empty;
}
__name(buildTree, "buildTree");
function byPos(a2, b2) {
  return a2.from - b2.from || a2.to - b2.to;
}
__name(byPos, "byPos");
function removeOverlap(spans) {
  let working = spans;
  for (let i2 = 0; i2 < working.length - 1; i2++) {
    let span = working[i2];
    if (span.from != span.to)
      for (let j2 = i2 + 1; j2 < working.length; j2++) {
        let next = working[j2];
        if (next.from == span.from) {
          if (next.to != span.to) {
            if (working == spans)
              working = spans.slice();
            working[j2] = next.copy(next.from, span.to);
            insertAhead(working, j2 + 1, next.copy(span.to, next.to));
          }
          continue;
        } else {
          if (next.from < span.to) {
            if (working == spans)
              working = spans.slice();
            working[i2] = span.copy(span.from, next.from);
            insertAhead(working, j2, span.copy(next.from, span.to));
          }
          break;
        }
      }
  }
  return working;
}
__name(removeOverlap, "removeOverlap");
function insertAhead(array, i2, deco) {
  while (i2 < array.length && byPos(deco, array[i2]) > 0)
    i2++;
  array.splice(i2, 0, deco);
}
__name(insertAhead, "insertAhead");
function viewDecorations(view) {
  let found2 = [];
  view.someProp("decorations", (f2) => {
    let result = f2(view.state);
    if (result && result != empty)
      found2.push(result);
  });
  if (view.cursorWrapper)
    found2.push(DecorationSet.create(view.state.doc, [view.cursorWrapper.deco]));
  return DecorationGroup.from(found2);
}
__name(viewDecorations, "viewDecorations");
const observeOptions = {
  childList: true,
  characterData: true,
  characterDataOldValue: true,
  attributes: true,
  attributeOldValue: true,
  subtree: true
};
const useCharData = ie$1 && ie_version <= 11;
class SelectionState {
  static {
    __name(this, "SelectionState");
  }
  constructor() {
    this.anchorNode = null;
    this.anchorOffset = 0;
    this.focusNode = null;
    this.focusOffset = 0;
  }
  set(sel) {
    this.anchorNode = sel.anchorNode;
    this.anchorOffset = sel.anchorOffset;
    this.focusNode = sel.focusNode;
    this.focusOffset = sel.focusOffset;
  }
  clear() {
    this.anchorNode = this.focusNode = null;
  }
  eq(sel) {
    return sel.anchorNode == this.anchorNode && sel.anchorOffset == this.anchorOffset && sel.focusNode == this.focusNode && sel.focusOffset == this.focusOffset;
  }
}
class DOMObserver {
  static {
    __name(this, "DOMObserver");
  }
  constructor(view, handleDOMChange) {
    this.view = view;
    this.handleDOMChange = handleDOMChange;
    this.queue = [];
    this.flushingSoon = -1;
    this.observer = null;
    this.currentSelection = new SelectionState();
    this.onCharData = null;
    this.suppressingSelectionUpdates = false;
    this.lastChangedTextNode = null;
    this.observer = window.MutationObserver && new window.MutationObserver((mutations) => {
      for (let i2 = 0; i2 < mutations.length; i2++)
        this.queue.push(mutations[i2]);
      if (ie$1 && ie_version <= 11 && mutations.some((m2) => m2.type == "childList" && m2.removedNodes.length || m2.type == "characterData" && m2.oldValue.length > m2.target.nodeValue.length))
        this.flushSoon();
      else
        this.flush();
    });
    if (useCharData) {
      this.onCharData = (e2) => {
        this.queue.push({ target: e2.target, type: "characterData", oldValue: e2.prevValue });
        this.flushSoon();
      };
    }
    this.onSelectionChange = this.onSelectionChange.bind(this);
  }
  flushSoon() {
    if (this.flushingSoon < 0)
      this.flushingSoon = window.setTimeout(() => {
        this.flushingSoon = -1;
        this.flush();
      }, 20);
  }
  forceFlush() {
    if (this.flushingSoon > -1) {
      window.clearTimeout(this.flushingSoon);
      this.flushingSoon = -1;
      this.flush();
    }
  }
  start() {
    if (this.observer) {
      this.observer.takeRecords();
      this.observer.observe(this.view.dom, observeOptions);
    }
    if (this.onCharData)
      this.view.dom.addEventListener("DOMCharacterDataModified", this.onCharData);
    this.connectSelection();
  }
  stop() {
    if (this.observer) {
      let take = this.observer.takeRecords();
      if (take.length) {
        for (let i2 = 0; i2 < take.length; i2++)
          this.queue.push(take[i2]);
        window.setTimeout(() => this.flush(), 20);
      }
      this.observer.disconnect();
    }
    if (this.onCharData)
      this.view.dom.removeEventListener("DOMCharacterDataModified", this.onCharData);
    this.disconnectSelection();
  }
  connectSelection() {
    this.view.dom.ownerDocument.addEventListener("selectionchange", this.onSelectionChange);
  }
  disconnectSelection() {
    this.view.dom.ownerDocument.removeEventListener("selectionchange", this.onSelectionChange);
  }
  suppressSelectionUpdates() {
    this.suppressingSelectionUpdates = true;
    setTimeout(() => this.suppressingSelectionUpdates = false, 50);
  }
  onSelectionChange() {
    if (!hasFocusAndSelection(this.view))
      return;
    if (this.suppressingSelectionUpdates)
      return selectionToDOM(this.view);
    if (ie$1 && ie_version <= 11 && !this.view.state.selection.empty) {
      let sel = this.view.domSelectionRange();
      if (sel.focusNode && isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset))
        return this.flushSoon();
    }
    this.flush();
  }
  setCurSelection() {
    this.currentSelection.set(this.view.domSelectionRange());
  }
  ignoreSelectionChange(sel) {
    if (!sel.focusNode)
      return true;
    let ancestors = /* @__PURE__ */ new Set(), container;
    for (let scan = sel.focusNode; scan; scan = parentNode(scan))
      ancestors.add(scan);
    for (let scan = sel.anchorNode; scan; scan = parentNode(scan))
      if (ancestors.has(scan)) {
        container = scan;
        break;
      }
    let desc = container && this.view.docView.nearestDesc(container);
    if (desc && desc.ignoreMutation({
      type: "selection",
      target: container.nodeType == 3 ? container.parentNode : container
    })) {
      this.setCurSelection();
      return true;
    }
  }
  pendingRecords() {
    if (this.observer)
      for (let mut of this.observer.takeRecords())
        this.queue.push(mut);
    return this.queue;
  }
  flush() {
    let { view } = this;
    if (!view.docView || this.flushingSoon > -1)
      return;
    let mutations = this.pendingRecords();
    if (mutations.length)
      this.queue = [];
    let sel = view.domSelectionRange();
    let newSel = !this.suppressingSelectionUpdates && !this.currentSelection.eq(sel) && hasFocusAndSelection(view) && !this.ignoreSelectionChange(sel);
    let from2 = -1, to = -1, typeOver = false, added = [];
    if (view.editable) {
      for (let i2 = 0; i2 < mutations.length; i2++) {
        let result = this.registerMutation(mutations[i2], added);
        if (result) {
          from2 = from2 < 0 ? result.from : Math.min(result.from, from2);
          to = to < 0 ? result.to : Math.max(result.to, to);
          if (result.typeOver)
            typeOver = true;
        }
      }
    }
    if (gecko && added.length) {
      let brs = added.filter((n2) => n2.nodeName == "BR");
      if (brs.length == 2) {
        let [a2, b2] = brs;
        if (a2.parentNode && a2.parentNode.parentNode == b2.parentNode)
          b2.remove();
        else
          a2.remove();
      } else {
        let { focusNode } = this.currentSelection;
        for (let br of brs) {
          let parent2 = br.parentNode;
          if (parent2 && parent2.nodeName == "LI" && (!focusNode || blockParent(view, focusNode) != parent2))
            br.remove();
        }
      }
    }
    let readSel = null;
    if (from2 < 0 && newSel && view.input.lastFocus > Date.now() - 200 && Math.max(view.input.lastTouch, view.input.lastClick.time) < Date.now() - 300 && selectionCollapsed(sel) && (readSel = selectionFromDOM(view)) && readSel.eq(Selection.near(view.state.doc.resolve(0), 1))) {
      view.input.lastFocus = 0;
      selectionToDOM(view);
      this.currentSelection.set(sel);
      view.scrollToSelection();
    } else if (from2 > -1 || newSel) {
      if (from2 > -1) {
        view.docView.markDirty(from2, to);
        checkCSS(view);
      }
      this.handleDOMChange(from2, to, typeOver, added);
      if (view.docView && view.docView.dirty)
        view.updateState(view.state);
      else if (!this.currentSelection.eq(sel))
        selectionToDOM(view);
      this.currentSelection.set(sel);
    }
  }
  registerMutation(mut, added) {
    if (added.indexOf(mut.target) > -1)
      return null;
    let desc = this.view.docView.nearestDesc(mut.target);
    if (mut.type == "attributes" && (desc == this.view.docView || mut.attributeName == "contenteditable" || // Firefox sometimes fires spurious events for null/empty styles
    mut.attributeName == "style" && !mut.oldValue && !mut.target.getAttribute("style")))
      return null;
    if (!desc || desc.ignoreMutation(mut))
      return null;
    if (mut.type == "childList") {
      for (let i2 = 0; i2 < mut.addedNodes.length; i2++) {
        let node2 = mut.addedNodes[i2];
        added.push(node2);
        if (node2.nodeType == 3)
          this.lastChangedTextNode = node2;
      }
      if (desc.contentDOM && desc.contentDOM != desc.dom && !desc.contentDOM.contains(mut.target))
        return { from: desc.posBefore, to: desc.posAfter };
      let prev = mut.previousSibling, next = mut.nextSibling;
      if (ie$1 && ie_version <= 11 && mut.addedNodes.length) {
        for (let i2 = 0; i2 < mut.addedNodes.length; i2++) {
          let { previousSibling, nextSibling } = mut.addedNodes[i2];
          if (!previousSibling || Array.prototype.indexOf.call(mut.addedNodes, previousSibling) < 0)
            prev = previousSibling;
          if (!nextSibling || Array.prototype.indexOf.call(mut.addedNodes, nextSibling) < 0)
            next = nextSibling;
        }
      }
      let fromOffset = prev && prev.parentNode == mut.target ? domIndex(prev) + 1 : 0;
      let from2 = desc.localPosFromDOM(mut.target, fromOffset, -1);
      let toOffset = next && next.parentNode == mut.target ? domIndex(next) : mut.target.childNodes.length;
      let to = desc.localPosFromDOM(mut.target, toOffset, 1);
      return { from: from2, to };
    } else if (mut.type == "attributes") {
      return { from: desc.posAtStart - desc.border, to: desc.posAtEnd + desc.border };
    } else {
      this.lastChangedTextNode = mut.target;
      return {
        from: desc.posAtStart,
        to: desc.posAtEnd,
        // An event was generated for a text change that didn't change
        // any text. Mark the dom change to fall back to assuming the
        // selection was typed over with an identical value if it can't
        // find another change.
        typeOver: mut.target.nodeValue == mut.oldValue
      };
    }
  }
}
let cssChecked = /* @__PURE__ */ new WeakMap();
let cssCheckWarned = false;
function checkCSS(view) {
  if (cssChecked.has(view))
    return;
  cssChecked.set(view, null);
  if (["normal", "nowrap", "pre-line"].indexOf(getComputedStyle(view.dom).whiteSpace) !== -1) {
    view.requiresGeckoHackNode = gecko;
    if (cssCheckWarned)
      return;
    console["warn"]("ProseMirror expects the CSS white-space property to be set, preferably to 'pre-wrap'. It is recommended to load style/prosemirror.css from the prosemirror-view package.");
    cssCheckWarned = true;
  }
}
__name(checkCSS, "checkCSS");
function rangeToSelectionRange(view, range) {
  let anchorNode = range.startContainer, anchorOffset = range.startOffset;
  let focusNode = range.endContainer, focusOffset = range.endOffset;
  let currentAnchor = view.domAtPos(view.state.selection.anchor);
  if (isEquivalentPosition(currentAnchor.node, currentAnchor.offset, focusNode, focusOffset))
    [anchorNode, anchorOffset, focusNode, focusOffset] = [focusNode, focusOffset, anchorNode, anchorOffset];
  return { anchorNode, anchorOffset, focusNode, focusOffset };
}
__name(rangeToSelectionRange, "rangeToSelectionRange");
function safariShadowSelectionRange(view, selection) {
  if (selection.getComposedRanges) {
    let range = selection.getComposedRanges(view.root)[0];
    if (range)
      return rangeToSelectionRange(view, range);
  }
  let found2;
  function read2(event) {
    event.preventDefault();
    event.stopImmediatePropagation();
    found2 = event.getTargetRanges()[0];
  }
  __name(read2, "read");
  view.dom.addEventListener("beforeinput", read2, true);
  document.execCommand("indent");
  view.dom.removeEventListener("beforeinput", read2, true);
  return found2 ? rangeToSelectionRange(view, found2) : null;
}
__name(safariShadowSelectionRange, "safariShadowSelectionRange");
function blockParent(view, node2) {
  for (let p2 = node2.parentNode; p2 && p2 != view.dom; p2 = p2.parentNode) {
    let desc = view.docView.nearestDesc(p2, true);
    if (desc && desc.node.isBlock)
      return p2;
  }
  return null;
}
__name(blockParent, "blockParent");
function parseBetween(view, from_, to_) {
  let { node: parent2, fromOffset, toOffset, from: from2, to } = view.docView.parseRange(from_, to_);
  let domSel = view.domSelectionRange();
  let find2;
  let anchor = domSel.anchorNode;
  if (anchor && view.dom.contains(anchor.nodeType == 1 ? anchor : anchor.parentNode)) {
    find2 = [{ node: anchor, offset: domSel.anchorOffset }];
    if (!selectionCollapsed(domSel))
      find2.push({ node: domSel.focusNode, offset: domSel.focusOffset });
  }
  if (chrome$1 && view.input.lastKeyCode === 8) {
    for (let off2 = toOffset; off2 > fromOffset; off2--) {
      let node2 = parent2.childNodes[off2 - 1], desc = node2.pmViewDesc;
      if (node2.nodeName == "BR" && !desc) {
        toOffset = off2;
        break;
      }
      if (!desc || desc.size)
        break;
    }
  }
  let startDoc = view.state.doc;
  let parser = view.someProp("domParser") || DOMParser.fromSchema(view.state.schema);
  let $from = startDoc.resolve(from2);
  let sel = null, doc2 = parser.parse(parent2, {
    topNode: $from.parent,
    topMatch: $from.parent.contentMatchAt($from.index()),
    topOpen: true,
    from: fromOffset,
    to: toOffset,
    preserveWhitespace: $from.parent.type.whitespace == "pre" ? "full" : true,
    findPositions: find2,
    ruleFromNode,
    context: $from
  });
  if (find2 && find2[0].pos != null) {
    let anchor2 = find2[0].pos, head = find2[1] && find2[1].pos;
    if (head == null)
      head = anchor2;
    sel = { anchor: anchor2 + from2, head: head + from2 };
  }
  return { doc: doc2, sel, from: from2, to };
}
__name(parseBetween, "parseBetween");
function ruleFromNode(dom) {
  let desc = dom.pmViewDesc;
  if (desc) {
    return desc.parseRule();
  } else if (dom.nodeName == "BR" && dom.parentNode) {
    if (safari && /^(ul|ol)$/i.test(dom.parentNode.nodeName)) {
      let skip = document.createElement("div");
      skip.appendChild(document.createElement("li"));
      return { skip };
    } else if (dom.parentNode.lastChild == dom || safari && /^(tr|table)$/i.test(dom.parentNode.nodeName)) {
      return { ignore: true };
    }
  } else if (dom.nodeName == "IMG" && dom.getAttribute("mark-placeholder")) {
    return { ignore: true };
  }
  return null;
}
__name(ruleFromNode, "ruleFromNode");
const isInline$1 = /^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i;
function readDOMChange(view, from2, to, typeOver, addedNodes) {
  let compositionID = view.input.compositionPendingChanges || (view.composing ? view.input.compositionID : 0);
  view.input.compositionPendingChanges = 0;
  if (from2 < 0) {
    let origin2 = view.input.lastSelectionTime > Date.now() - 50 ? view.input.lastSelectionOrigin : null;
    let newSel = selectionFromDOM(view, origin2);
    if (newSel && !view.state.selection.eq(newSel)) {
      if (chrome$1 && android && view.input.lastKeyCode === 13 && Date.now() - 100 < view.input.lastKeyCodeTime && view.someProp("handleKeyDown", (f2) => f2(view, keyEvent(13, "Enter"))))
        return;
      let tr3 = view.state.tr.setSelection(newSel);
      if (origin2 == "pointer")
        tr3.setMeta("pointer", true);
      else if (origin2 == "key")
        tr3.scrollIntoView();
      if (compositionID)
        tr3.setMeta("composition", compositionID);
      view.dispatch(tr3);
    }
    return;
  }
  let $before = view.state.doc.resolve(from2);
  let shared = $before.sharedDepth(to);
  from2 = $before.before(shared + 1);
  to = view.state.doc.resolve(to).after(shared + 1);
  let sel = view.state.selection;
  let parse2 = parseBetween(view, from2, to);
  let doc2 = view.state.doc, compare2 = doc2.slice(parse2.from, parse2.to);
  let preferredPos, preferredSide;
  if (view.input.lastKeyCode === 8 && Date.now() - 100 < view.input.lastKeyCodeTime) {
    preferredPos = view.state.selection.to;
    preferredSide = "end";
  } else {
    preferredPos = view.state.selection.from;
    preferredSide = "start";
  }
  view.input.lastKeyCode = null;
  let change = findDiff(compare2.content, parse2.doc.content, parse2.from, preferredPos, preferredSide);
  if (change)
    view.input.domChangeCount++;
  if ((ios && view.input.lastIOSEnter > Date.now() - 225 || android) && addedNodes.some((n2) => n2.nodeType == 1 && !isInline$1.test(n2.nodeName)) && (!change || change.endA >= change.endB) && view.someProp("handleKeyDown", (f2) => f2(view, keyEvent(13, "Enter")))) {
    view.input.lastIOSEnter = 0;
    return;
  }
  if (!change) {
    if (typeOver && sel instanceof TextSelection && !sel.empty && sel.$head.sameParent(sel.$anchor) && !view.composing && !(parse2.sel && parse2.sel.anchor != parse2.sel.head)) {
      change = { start: sel.from, endA: sel.to, endB: sel.to };
    } else {
      if (parse2.sel) {
        let sel2 = resolveSelection(view, view.state.doc, parse2.sel);
        if (sel2 && !sel2.eq(view.state.selection)) {
          let tr3 = view.state.tr.setSelection(sel2);
          if (compositionID)
            tr3.setMeta("composition", compositionID);
          view.dispatch(tr3);
        }
      }
      return;
    }
  }
  if (view.state.selection.from < view.state.selection.to && change.start == change.endB && view.state.selection instanceof TextSelection) {
    if (change.start > view.state.selection.from && change.start <= view.state.selection.from + 2 && view.state.selection.from >= parse2.from) {
      change.start = view.state.selection.from;
    } else if (change.endA < view.state.selection.to && change.endA >= view.state.selection.to - 2 && view.state.selection.to <= parse2.to) {
      change.endB += view.state.selection.to - change.endA;
      change.endA = view.state.selection.to;
    }
  }
  if (ie$1 && ie_version <= 11 && change.endB == change.start + 1 && change.endA == change.start && change.start > parse2.from && parse2.doc.textBetween(change.start - parse2.from - 1, change.start - parse2.from + 1) == "  ") {
    change.start--;
    change.endA--;
    change.endB--;
  }
  let $from = parse2.doc.resolveNoCache(change.start - parse2.from);
  let $to = parse2.doc.resolveNoCache(change.endB - parse2.from);
  let $fromA = doc2.resolve(change.start);
  let inlineChange = $from.sameParent($to) && $from.parent.inlineContent && $fromA.end() >= change.endA;
  let nextSel;
  if ((ios && view.input.lastIOSEnter > Date.now() - 225 && (!inlineChange || addedNodes.some((n2) => n2.nodeName == "DIV" || n2.nodeName == "P")) || !inlineChange && $from.pos < parse2.doc.content.size && !$from.sameParent($to) && (nextSel = Selection.findFrom(parse2.doc.resolve($from.pos + 1), 1, true)) && nextSel.head == $to.pos) && view.someProp("handleKeyDown", (f2) => f2(view, keyEvent(13, "Enter")))) {
    view.input.lastIOSEnter = 0;
    return;
  }
  if (view.state.selection.anchor > change.start && looksLikeBackspace(doc2, change.start, change.endA, $from, $to) && view.someProp("handleKeyDown", (f2) => f2(view, keyEvent(8, "Backspace")))) {
    if (android && chrome$1)
      view.domObserver.suppressSelectionUpdates();
    return;
  }
  if (chrome$1 && change.endB == change.start)
    view.input.lastChromeDelete = Date.now();
  if (android && !inlineChange && $from.start() != $to.start() && $to.parentOffset == 0 && $from.depth == $to.depth && parse2.sel && parse2.sel.anchor == parse2.sel.head && parse2.sel.head == change.endA) {
    change.endB -= 2;
    $to = parse2.doc.resolveNoCache(change.endB - parse2.from);
    setTimeout(() => {
      view.someProp("handleKeyDown", function(f2) {
        return f2(view, keyEvent(13, "Enter"));
      });
    }, 20);
  }
  let chFrom = change.start, chTo = change.endA;
  let tr2, storedMarks, markChange;
  if (inlineChange) {
    if ($from.pos == $to.pos) {
      if (ie$1 && ie_version <= 11 && $from.parentOffset == 0) {
        view.domObserver.suppressSelectionUpdates();
        setTimeout(() => selectionToDOM(view), 20);
      }
      tr2 = view.state.tr.delete(chFrom, chTo);
      storedMarks = doc2.resolve(change.start).marksAcross(doc2.resolve(change.endA));
    } else if (
      // Adding or removing a mark
      change.endA == change.endB && (markChange = isMarkChange($from.parent.content.cut($from.parentOffset, $to.parentOffset), $fromA.parent.content.cut($fromA.parentOffset, change.endA - $fromA.start())))
    ) {
      tr2 = view.state.tr;
      if (markChange.type == "add")
        tr2.addMark(chFrom, chTo, markChange.mark);
      else
        tr2.removeMark(chFrom, chTo, markChange.mark);
    } else if ($from.parent.child($from.index()).isText && $from.index() == $to.index() - ($to.textOffset ? 0 : 1)) {
      let text2 = $from.parent.textBetween($from.parentOffset, $to.parentOffset);
      if (view.someProp("handleTextInput", (f2) => f2(view, chFrom, chTo, text2)))
        return;
      tr2 = view.state.tr.insertText(text2, chFrom, chTo);
    }
  }
  if (!tr2)
    tr2 = view.state.tr.replace(chFrom, chTo, parse2.doc.slice(change.start - parse2.from, change.endB - parse2.from));
  if (parse2.sel) {
    let sel2 = resolveSelection(view, tr2.doc, parse2.sel);
    if (sel2 && !(chrome$1 && view.composing && sel2.empty && (change.start != change.endB || view.input.lastChromeDelete < Date.now() - 100) && (sel2.head == chFrom || sel2.head == tr2.mapping.map(chTo) - 1) || ie$1 && sel2.empty && sel2.head == chFrom))
      tr2.setSelection(sel2);
  }
  if (storedMarks)
    tr2.ensureMarks(storedMarks);
  if (compositionID)
    tr2.setMeta("composition", compositionID);
  view.dispatch(tr2.scrollIntoView());
}
__name(readDOMChange, "readDOMChange");
function resolveSelection(view, doc2, parsedSel) {
  if (Math.max(parsedSel.anchor, parsedSel.head) > doc2.content.size)
    return null;
  return selectionBetween(view, doc2.resolve(parsedSel.anchor), doc2.resolve(parsedSel.head));
}
__name(resolveSelection, "resolveSelection");
function isMarkChange(cur, prev) {
  let curMarks = cur.firstChild.marks, prevMarks = prev.firstChild.marks;
  let added = curMarks, removed = prevMarks, type, mark, update2;
  for (let i2 = 0; i2 < prevMarks.length; i2++)
    added = prevMarks[i2].removeFromSet(added);
  for (let i2 = 0; i2 < curMarks.length; i2++)
    removed = curMarks[i2].removeFromSet(removed);
  if (added.length == 1 && removed.length == 0) {
    mark = added[0];
    type = "add";
    update2 = /* @__PURE__ */ __name((node2) => node2.mark(mark.addToSet(node2.marks)), "update");
  } else if (added.length == 0 && removed.length == 1) {
    mark = removed[0];
    type = "remove";
    update2 = /* @__PURE__ */ __name((node2) => node2.mark(mark.removeFromSet(node2.marks)), "update");
  } else {
    return null;
  }
  let updated2 = [];
  for (let i2 = 0; i2 < prev.childCount; i2++)
    updated2.push(update2(prev.child(i2)));
  if (Fragment.from(updated2).eq(cur))
    return { mark, type };
}
__name(isMarkChange, "isMarkChange");
function looksLikeBackspace(old, start2, end, $newStart, $newEnd) {
  if (
    // The content must have shrunk
    end - start2 <= $newEnd.pos - $newStart.pos || // newEnd must point directly at or after the end of the block that newStart points into
    skipClosingAndOpening($newStart, true, false) < $newEnd.pos
  )
    return false;
  let $start = old.resolve(start2);
  if (!$newStart.parent.isTextblock) {
    let after = $start.nodeAfter;
    return after != null && end == start2 + after.nodeSize;
  }
  if ($start.parentOffset < $start.parent.content.size || !$start.parent.isTextblock)
    return false;
  let $next = old.resolve(skipClosingAndOpening($start, true, true));
  if (!$next.parent.isTextblock || $next.pos > end || skipClosingAndOpening($next, true, false) < end)
    return false;
  return $newStart.parent.content.cut($newStart.parentOffset).eq($next.parent.content);
}
__name(looksLikeBackspace, "looksLikeBackspace");
function skipClosingAndOpening($pos, fromEnd, mayOpen) {
  let depth = $pos.depth, end = fromEnd ? $pos.end() : $pos.pos;
  while (depth > 0 && (fromEnd || $pos.indexAfter(depth) == $pos.node(depth).childCount)) {
    depth--;
    end++;
    fromEnd = false;
  }
  if (mayOpen) {
    let next = $pos.node(depth).maybeChild($pos.indexAfter(depth));
    while (next && !next.isLeaf) {
      next = next.firstChild;
      end++;
    }
  }
  return end;
}
__name(skipClosingAndOpening, "skipClosingAndOpening");
function findDiff(a2, b2, pos, preferredPos, preferredSide) {
  let start2 = a2.findDiffStart(b2, pos);
  if (start2 == null)
    return null;
  let { a: endA, b: endB } = a2.findDiffEnd(b2, pos + a2.size, pos + b2.size);
  if (preferredSide == "end") {
    let adjust = Math.max(0, start2 - Math.min(endA, endB));
    preferredPos -= endA + adjust - start2;
  }
  if (endA < start2 && a2.size < b2.size) {
    let move = preferredPos <= start2 && preferredPos >= endA ? start2 - preferredPos : 0;
    start2 -= move;
    if (start2 && start2 < b2.size && isSurrogatePair(b2.textBetween(start2 - 1, start2 + 1)))
      start2 += move ? 1 : -1;
    endB = start2 + (endB - endA);
    endA = start2;
  } else if (endB < start2) {
    let move = preferredPos <= start2 && preferredPos >= endB ? start2 - preferredPos : 0;
    start2 -= move;
    if (start2 && start2 < a2.size && isSurrogatePair(a2.textBetween(start2 - 1, start2 + 1)))
      start2 += move ? 1 : -1;
    endA = start2 + (endA - endB);
    endB = start2;
  }
  return { start: start2, endA, endB };
}
__name(findDiff, "findDiff");
function isSurrogatePair(str) {
  if (str.length != 2)
    return false;
  let a2 = str.charCodeAt(0), b2 = str.charCodeAt(1);
  return a2 >= 56320 && a2 <= 57343 && b2 >= 55296 && b2 <= 56319;
}
__name(isSurrogatePair, "isSurrogatePair");
const __serializeForClipboard = serializeForClipboard;
const __parseFromClipboard = parseFromClipboard;
const __endComposition = endComposition;
class EditorView {
  static {
    __name(this, "EditorView");
  }
  /**
  Create a view. `place` may be a DOM node that the editor should
  be appended to, a function that will place it into the document,
  or an object whose `mount` property holds the node to use as the
  document container. If it is `null`, the editor will not be
  added to the document.
  */
  constructor(place, props) {
    this._root = null;
    this.focused = false;
    this.trackWrites = null;
    this.mounted = false;
    this.markCursor = null;
    this.cursorWrapper = null;
    this.lastSelectedViewDesc = void 0;
    this.input = new InputState();
    this.prevDirectPlugins = [];
    this.pluginViews = [];
    this.requiresGeckoHackNode = false;
    this.dragging = null;
    this._props = props;
    this.state = props.state;
    this.directPlugins = props.plugins || [];
    this.directPlugins.forEach(checkStateComponent);
    this.dispatch = this.dispatch.bind(this);
    this.dom = place && place.mount || document.createElement("div");
    if (place) {
      if (place.appendChild)
        place.appendChild(this.dom);
      else if (typeof place == "function")
        place(this.dom);
      else if (place.mount)
        this.mounted = true;
    }
    this.editable = getEditable(this);
    updateCursorWrapper(this);
    this.nodeViews = buildNodeViews(this);
    this.docView = docViewDesc(this.state.doc, computeDocDeco(this), viewDecorations(this), this.dom, this);
    this.domObserver = new DOMObserver(this, (from2, to, typeOver, added) => readDOMChange(this, from2, to, typeOver, added));
    this.domObserver.start();
    initInput(this);
    this.updatePluginViews();
  }
  /**
  Holds `true` when a
  [composition](https://w3c.github.io/uievents/#events-compositionevents)
  is active.
  */
  get composing() {
    return this.input.composing;
  }
  /**
  The view's current [props](https://prosemirror.net/docs/ref/#view.EditorProps).
  */
  get props() {
    if (this._props.state != this.state) {
      let prev = this._props;
      this._props = {};
      for (let name2 in prev)
        this._props[name2] = prev[name2];
      this._props.state = this.state;
    }
    return this._props;
  }
  /**
  Update the view's props. Will immediately cause an update to
  the DOM.
  */
  update(props) {
    if (props.handleDOMEvents != this._props.handleDOMEvents)
      ensureListeners(this);
    let prevProps = this._props;
    this._props = props;
    if (props.plugins) {
      props.plugins.forEach(checkStateComponent);
      this.directPlugins = props.plugins;
    }
    this.updateStateInner(props.state, prevProps);
  }
  /**
  Update the view by updating existing props object with the object
  given as argument. Equivalent to `view.update(Object.assign({},
  view.props, props))`.
  */
  setProps(props) {
    let updated2 = {};
    for (let name2 in this._props)
      updated2[name2] = this._props[name2];
    updated2.state = this.state;
    for (let name2 in props)
      updated2[name2] = props[name2];
    this.update(updated2);
  }
  /**
  Update the editor's `state` prop, without touching any of the
  other props.
  */
  updateState(state) {
    this.updateStateInner(state, this._props);
  }
  updateStateInner(state, prevProps) {
    var _a2;
    let prev = this.state, redraw = false, updateSel = false;
    if (state.storedMarks && this.composing) {
      clearComposition(this);
      updateSel = true;
    }
    this.state = state;
    let pluginsChanged = prev.plugins != state.plugins || this._props.plugins != prevProps.plugins;
    if (pluginsChanged || this._props.plugins != prevProps.plugins || this._props.nodeViews != prevProps.nodeViews) {
      let nodeViews = buildNodeViews(this);
      if (changedNodeViews(nodeViews, this.nodeViews)) {
        this.nodeViews = nodeViews;
        redraw = true;
      }
    }
    if (pluginsChanged || prevProps.handleDOMEvents != this._props.handleDOMEvents) {
      ensureListeners(this);
    }
    this.editable = getEditable(this);
    updateCursorWrapper(this);
    let innerDeco = viewDecorations(this), outerDeco = computeDocDeco(this);
    let scroll = prev.plugins != state.plugins && !prev.doc.eq(state.doc) ? "reset" : state.scrollToSelection > prev.scrollToSelection ? "to selection" : "preserve";
    let updateDoc2 = redraw || !this.docView.matchesNode(state.doc, outerDeco, innerDeco);
    if (updateDoc2 || !state.selection.eq(prev.selection))
      updateSel = true;
    let oldScrollPos = scroll == "preserve" && updateSel && this.dom.style.overflowAnchor == null && storeScrollPos(this);
    if (updateSel) {
      this.domObserver.stop();
      let forceSelUpdate = updateDoc2 && (ie$1 || chrome$1) && !this.composing && !prev.selection.empty && !state.selection.empty && selectionContextChanged(prev.selection, state.selection);
      if (updateDoc2) {
        let chromeKludge = chrome$1 ? this.trackWrites = this.domSelectionRange().focusNode : null;
        if (this.composing)
          this.input.compositionNode = findCompositionNode(this);
        if (redraw || !this.docView.update(state.doc, outerDeco, innerDeco, this)) {
          this.docView.updateOuterDeco(outerDeco);
          this.docView.destroy();
          this.docView = docViewDesc(state.doc, outerDeco, innerDeco, this.dom, this);
        }
        if (chromeKludge && !this.trackWrites)
          forceSelUpdate = true;
      }
      if (forceSelUpdate || !(this.input.mouseDown && this.domObserver.currentSelection.eq(this.domSelectionRange()) && anchorInRightPlace(this))) {
        selectionToDOM(this, forceSelUpdate);
      } else {
        syncNodeSelection(this, state.selection);
        this.domObserver.setCurSelection();
      }
      this.domObserver.start();
    }
    this.updatePluginViews(prev);
    if (((_a2 = this.dragging) === null || _a2 === void 0 ? void 0 : _a2.node) && !prev.doc.eq(state.doc))
      this.updateDraggedNode(this.dragging, prev);
    if (scroll == "reset") {
      this.dom.scrollTop = 0;
    } else if (scroll == "to selection") {
      this.scrollToSelection();
    } else if (oldScrollPos) {
      resetScrollPos(oldScrollPos);
    }
  }
  /**
  @internal
  */
  scrollToSelection() {
    let startDOM = this.domSelectionRange().focusNode;
    if (this.someProp("handleScrollToSelection", (f2) => f2(this))) ;
    else if (this.state.selection instanceof NodeSelection) {
      let target = this.docView.domAfterPos(this.state.selection.from);
      if (target.nodeType == 1)
        scrollRectIntoView(this, target.getBoundingClientRect(), startDOM);
    } else {
      scrollRectIntoView(this, this.coordsAtPos(this.state.selection.head, 1), startDOM);
    }
  }
  destroyPluginViews() {
    let view;
    while (view = this.pluginViews.pop())
      if (view.destroy)
        view.destroy();
  }
  updatePluginViews(prevState) {
    if (!prevState || prevState.plugins != this.state.plugins || this.directPlugins != this.prevDirectPlugins) {
      this.prevDirectPlugins = this.directPlugins;
      this.destroyPluginViews();
      for (let i2 = 0; i2 < this.directPlugins.length; i2++) {
        let plugin = this.directPlugins[i2];
        if (plugin.spec.view)
          this.pluginViews.push(plugin.spec.view(this));
      }
      for (let i2 = 0; i2 < this.state.plugins.length; i2++) {
        let plugin = this.state.plugins[i2];
        if (plugin.spec.view)
          this.pluginViews.push(plugin.spec.view(this));
      }
    } else {
      for (let i2 = 0; i2 < this.pluginViews.length; i2++) {
        let pluginView = this.pluginViews[i2];
        if (pluginView.update)
          pluginView.update(this, prevState);
      }
    }
  }
  updateDraggedNode(dragging, prev) {
    let sel = dragging.node, found2 = -1;
    if (this.state.doc.nodeAt(sel.from) == sel.node) {
      found2 = sel.from;
    } else {
      let movedPos = sel.from + (this.state.doc.content.size - prev.doc.content.size);
      let moved = movedPos > 0 && this.state.doc.nodeAt(movedPos);
      if (moved == sel.node)
        found2 = movedPos;
    }
    this.dragging = new Dragging(dragging.slice, dragging.move, found2 < 0 ? void 0 : NodeSelection.create(this.state.doc, found2));
  }
  someProp(propName, f2) {
    let prop2 = this._props && this._props[propName], value;
    if (prop2 != null && (value = f2 ? f2(prop2) : prop2))
      return value;
    for (let i2 = 0; i2 < this.directPlugins.length; i2++) {
      let prop3 = this.directPlugins[i2].props[propName];
      if (prop3 != null && (value = f2 ? f2(prop3) : prop3))
        return value;
    }
    let plugins = this.state.plugins;
    if (plugins)
      for (let i2 = 0; i2 < plugins.length; i2++) {
        let prop3 = plugins[i2].props[propName];
        if (prop3 != null && (value = f2 ? f2(prop3) : prop3))
          return value;
      }
  }
  /**
  Query whether the view has focus.
  */
  hasFocus() {
    if (ie$1) {
      let node2 = this.root.activeElement;
      if (node2 == this.dom)
        return true;
      if (!node2 || !this.dom.contains(node2))
        return false;
      while (node2 && this.dom != node2 && this.dom.contains(node2)) {
        if (node2.contentEditable == "false")
          return false;
        node2 = node2.parentElement;
      }
      return true;
    }
    return this.root.activeElement == this.dom;
  }
  /**
  Focus the editor.
  */
  focus() {
    this.domObserver.stop();
    if (this.editable)
      focusPreventScroll(this.dom);
    selectionToDOM(this);
    this.domObserver.start();
  }
  /**
  Get the document root in which the editor exists. This will
  usually be the top-level `document`, but might be a [shadow
  DOM](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Shadow_DOM)
  root if the editor is inside one.
  */
  get root() {
    let cached = this._root;
    if (cached == null)
      for (let search2 = this.dom.parentNode; search2; search2 = search2.parentNode) {
        if (search2.nodeType == 9 || search2.nodeType == 11 && search2.host) {
          if (!search2.getSelection)
            Object.getPrototypeOf(search2).getSelection = () => search2.ownerDocument.getSelection();
          return this._root = search2;
        }
      }
    return cached || document;
  }
  /**
  When an existing editor view is moved to a new document or
  shadow tree, call this to make it recompute its root.
  */
  updateRoot() {
    this._root = null;
  }
  /**
  Given a pair of viewport coordinates, return the document
  position that corresponds to them. May return null if the given
  coordinates aren't inside of the editor. When an object is
  returned, its `pos` property is the position nearest to the
  coordinates, and its `inside` property holds the position of the
  inner node that the position falls inside of, or -1 if it is at
  the top level, not in any node.
  */
  posAtCoords(coords) {
    return posAtCoords(this, coords);
  }
  /**
  Returns the viewport rectangle at a given document position.
  `left` and `right` will be the same number, as this returns a
  flat cursor-ish rectangle. If the position is between two things
  that aren't directly adjacent, `side` determines which element
  is used. When < 0, the element before the position is used,
  otherwise the element after.
  */
  coordsAtPos(pos, side = 1) {
    return coordsAtPos(this, pos, side);
  }
  /**
  Find the DOM position that corresponds to the given document
  position. When `side` is negative, find the position as close as
  possible to the content before the position. When positive,
  prefer positions close to the content after the position. When
  zero, prefer as shallow a position as possible.
  
  Note that you should **not** mutate the editor's internal DOM,
  only inspect it (and even that is usually not necessary).
  */
  domAtPos(pos, side = 0) {
    return this.docView.domFromPos(pos, side);
  }
  /**
  Find the DOM node that represents the document node after the
  given position. May return `null` when the position doesn't point
  in front of a node or if the node is inside an opaque node view.
  
  This is intended to be able to call things like
  `getBoundingClientRect` on that DOM node. Do **not** mutate the
  editor DOM directly, or add styling this way, since that will be
  immediately overriden by the editor as it redraws the node.
  */
  nodeDOM(pos) {
    let desc = this.docView.descAt(pos);
    return desc ? desc.nodeDOM : null;
  }
  /**
  Find the document position that corresponds to a given DOM
  position. (Whenever possible, it is preferable to inspect the
  document structure directly, rather than poking around in the
  DOM, but sometimes—for example when interpreting an event
  target—you don't have a choice.)
  
  The `bias` parameter can be used to influence which side of a DOM
  node to use when the position is inside a leaf node.
  */
  posAtDOM(node2, offset, bias = -1) {
    let pos = this.docView.posFromDOM(node2, offset, bias);
    if (pos == null)
      throw new RangeError("DOM position not inside the editor");
    return pos;
  }
  /**
  Find out whether the selection is at the end of a textblock when
  moving in a given direction. When, for example, given `"left"`,
  it will return true if moving left from the current cursor
  position would leave that position's parent textblock. Will apply
  to the view's current state by default, but it is possible to
  pass a different state.
  */
  endOfTextblock(dir, state) {
    return endOfTextblock(this, state || this.state, dir);
  }
  /**
  Run the editor's paste logic with the given HTML string. The
  `event`, if given, will be passed to the
  [`handlePaste`](https://prosemirror.net/docs/ref/#view.EditorProps.handlePaste) hook.
  */
  pasteHTML(html, event) {
    return doPaste(this, "", html, false, event || new ClipboardEvent("paste"));
  }
  /**
  Run the editor's paste logic with the given plain-text input.
  */
  pasteText(text2, event) {
    return doPaste(this, text2, null, true, event || new ClipboardEvent("paste"));
  }
  /**
  Removes the editor from the DOM and destroys all [node
  views](https://prosemirror.net/docs/ref/#view.NodeView).
  */
  destroy() {
    if (!this.docView)
      return;
    destroyInput(this);
    this.destroyPluginViews();
    if (this.mounted) {
      this.docView.update(this.state.doc, [], viewDecorations(this), this);
      this.dom.textContent = "";
    } else if (this.dom.parentNode) {
      this.dom.parentNode.removeChild(this.dom);
    }
    this.docView.destroy();
    this.docView = null;
    clearReusedRange();
  }
  /**
  This is true when the view has been
  [destroyed](https://prosemirror.net/docs/ref/#view.EditorView.destroy) (and thus should not be
  used anymore).
  */
  get isDestroyed() {
    return this.docView == null;
  }
  /**
  Used for testing.
  */
  dispatchEvent(event) {
    return dispatchEvent(this, event);
  }
  /**
  Dispatch a transaction. Will call
  [`dispatchTransaction`](https://prosemirror.net/docs/ref/#view.DirectEditorProps.dispatchTransaction)
  when given, and otherwise defaults to applying the transaction to
  the current state and calling
  [`updateState`](https://prosemirror.net/docs/ref/#view.EditorView.updateState) with the result.
  This method is bound to the view instance, so that it can be
  easily passed around.
  */
  dispatch(tr2) {
    let dispatchTransaction = this._props.dispatchTransaction;
    if (dispatchTransaction)
      dispatchTransaction.call(this, tr2);
    else
      this.updateState(this.state.apply(tr2));
  }
  /**
  @internal
  */
  domSelectionRange() {
    let sel = this.domSelection();
    if (!sel)
      return { focusNode: null, focusOffset: 0, anchorNode: null, anchorOffset: 0 };
    return safari && this.root.nodeType === 11 && deepActiveElement(this.dom.ownerDocument) == this.dom && safariShadowSelectionRange(this, sel) || sel;
  }
  /**
  @internal
  */
  domSelection() {
    return this.root.getSelection();
  }
}
function computeDocDeco(view) {
  let attrs2 = /* @__PURE__ */ Object.create(null);
  attrs2.class = "ProseMirror";
  attrs2.contenteditable = String(view.editable);
  view.someProp("attributes", (value) => {
    if (typeof value == "function")
      value = value(view.state);
    if (value)
      for (let attr in value) {
        if (attr == "class")
          attrs2.class += " " + value[attr];
        else if (attr == "style")
          attrs2.style = (attrs2.style ? attrs2.style + ";" : "") + value[attr];
        else if (!attrs2[attr] && attr != "contenteditable" && attr != "nodeName")
          attrs2[attr] = String(value[attr]);
      }
  });
  if (!attrs2.translate)
    attrs2.translate = "no";
  return [Decoration.node(0, view.state.doc.content.size, attrs2)];
}
__name(computeDocDeco, "computeDocDeco");
function updateCursorWrapper(view) {
  if (view.markCursor) {
    let dom = document.createElement("img");
    dom.className = "ProseMirror-separator";
    dom.setAttribute("mark-placeholder", "true");
    dom.setAttribute("alt", "");
    view.cursorWrapper = { dom, deco: Decoration.widget(view.state.selection.from, dom, { raw: true, marks: view.markCursor }) };
  } else {
    view.cursorWrapper = null;
  }
}
__name(updateCursorWrapper, "updateCursorWrapper");
function getEditable(view) {
  return !view.someProp("editable", (value) => value(view.state) === false);
}
__name(getEditable, "getEditable");
function selectionContextChanged(sel1, sel2) {
  let depth = Math.min(sel1.$anchor.sharedDepth(sel1.head), sel2.$anchor.sharedDepth(sel2.head));
  return sel1.$anchor.start(depth) != sel2.$anchor.start(depth);
}
__name(selectionContextChanged, "selectionContextChanged");
function buildNodeViews(view) {
  let result = /* @__PURE__ */ Object.create(null);
  function add3(obj) {
    for (let prop2 in obj)
      if (!Object.prototype.hasOwnProperty.call(result, prop2))
        result[prop2] = obj[prop2];
  }
  __name(add3, "add");
  view.someProp("nodeViews", add3);
  view.someProp("markViews", add3);
  return result;
}
__name(buildNodeViews, "buildNodeViews");
function changedNodeViews(a2, b2) {
  let nA = 0, nB = 0;
  for (let prop2 in a2) {
    if (a2[prop2] != b2[prop2])
      return true;
    nA++;
  }
  for (let _2 in b2)
    nB++;
  return nA != nB;
}
__name(changedNodeViews, "changedNodeViews");
function checkStateComponent(plugin) {
  if (plugin.spec.state || plugin.spec.filterTransaction || plugin.spec.appendTransaction)
    throw new RangeError("Plugins passed directly to the view must not have a state component");
}
__name(checkStateComponent, "checkStateComponent");
var base$1 = {
  8: "Backspace",
  9: "Tab",
  10: "Enter",
  12: "NumLock",
  13: "Enter",
  16: "Shift",
  17: "Control",
  18: "Alt",
  20: "CapsLock",
  27: "Escape",
  32: " ",
  33: "PageUp",
  34: "PageDown",
  35: "End",
  36: "Home",
  37: "ArrowLeft",
  38: "ArrowUp",
  39: "ArrowRight",
  40: "ArrowDown",
  44: "PrintScreen",
  45: "Insert",
  46: "Delete",
  59: ";",
  61: "=",
  91: "Meta",
  92: "Meta",
  106: "*",
  107: "+",
  108: ",",
  109: "-",
  110: ".",
  111: "/",
  144: "NumLock",
  145: "ScrollLock",
  160: "Shift",
  161: "Shift",
  162: "Control",
  163: "Control",
  164: "Alt",
  165: "Alt",
  173: "-",
  186: ";",
  187: "=",
  188: ",",
  189: "-",
  190: ".",
  191: "/",
  192: "`",
  219: "[",
  220: "\\",
  221: "]",
  222: "'"
};
var shift = {
  48: ")",
  49: "!",
  50: "@",
  51: "#",
  52: "$",
  53: "%",
  54: "^",
  55: "&",
  56: "*",
  57: "(",
  59: ":",
  61: "+",
  173: "_",
  186: ":",
  187: "+",
  188: "<",
  189: "_",
  190: ">",
  191: "?",
  192: "~",
  219: "{",
  220: "|",
  221: "}",
  222: '"'
};
var mac$2 = typeof navigator != "undefined" && /Mac/.test(navigator.platform);
var ie = typeof navigator != "undefined" && /MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);
for (var i = 0; i < 10; i++) base$1[48 + i] = base$1[96 + i] = String(i);
for (var i = 1; i <= 24; i++) base$1[i + 111] = "F" + i;
for (var i = 65; i <= 90; i++) {
  base$1[i] = String.fromCharCode(i + 32);
  shift[i] = String.fromCharCode(i);
}
for (var code$1 in base$1) if (!shift.hasOwnProperty(code$1)) shift[code$1] = base$1[code$1];
function keyName(event) {
  var ignoreKey = mac$2 && event.metaKey && event.shiftKey && !event.ctrlKey && !event.altKey || ie && event.shiftKey && event.key && event.key.length == 1 || event.key == "Unidentified";
  var name2 = !ignoreKey && event.key || (event.shiftKey ? shift : base$1)[event.keyCode] || event.key || "Unidentified";
  if (name2 == "Esc") name2 = "Escape";
  if (name2 == "Del") name2 = "Delete";
  if (name2 == "Left") name2 = "ArrowLeft";
  if (name2 == "Up") name2 = "ArrowUp";
  if (name2 == "Right") name2 = "ArrowRight";
  if (name2 == "Down") name2 = "ArrowDown";
  return name2;
}
__name(keyName, "keyName");
const mac$1 = typeof navigator != "undefined" ? /Mac|iP(hone|[oa]d)/.test(navigator.platform) : false;
function normalizeKeyName$1(name2) {
  let parts2 = name2.split(/-(?!$)/), result = parts2[parts2.length - 1];
  if (result == "Space")
    result = " ";
  let alt, ctrl, shift2, meta;
  for (let i2 = 0; i2 < parts2.length - 1; i2++) {
    let mod = parts2[i2];
    if (/^(cmd|meta|m)$/i.test(mod))
      meta = true;
    else if (/^a(lt)?$/i.test(mod))
      alt = true;
    else if (/^(c|ctrl|control)$/i.test(mod))
      ctrl = true;
    else if (/^s(hift)?$/i.test(mod))
      shift2 = true;
    else if (/^mod$/i.test(mod)) {
      if (mac$1)
        meta = true;
      else
        ctrl = true;
    } else
      throw new Error("Unrecognized modifier name: " + mod);
  }
  if (alt)
    result = "Alt-" + result;
  if (ctrl)
    result = "Ctrl-" + result;
  if (meta)
    result = "Meta-" + result;
  if (shift2)
    result = "Shift-" + result;
  return result;
}
__name(normalizeKeyName$1, "normalizeKeyName$1");
function normalize$1(map3) {
  let copy2 = /* @__PURE__ */ Object.create(null);
  for (let prop2 in map3)
    copy2[normalizeKeyName$1(prop2)] = map3[prop2];
  return copy2;
}
__name(normalize$1, "normalize$1");
function modifiers(name2, event, shift2 = true) {
  if (event.altKey)
    name2 = "Alt-" + name2;
  if (event.ctrlKey)
    name2 = "Ctrl-" + name2;
  if (event.metaKey)
    name2 = "Meta-" + name2;
  if (shift2 && event.shiftKey)
    name2 = "Shift-" + name2;
  return name2;
}
__name(modifiers, "modifiers");
function keymap(bindings) {
  return new Plugin({ props: { handleKeyDown: keydownHandler(bindings) } });
}
__name(keymap, "keymap");
function keydownHandler(bindings) {
  let map3 = normalize$1(bindings);
  return function(view, event) {
    let name2 = keyName(event), baseName, direct = map3[modifiers(name2, event)];
    if (direct && direct(view.state, view.dispatch, view))
      return true;
    if (name2.length == 1 && name2 != " ") {
      if (event.shiftKey) {
        let noShift = map3[modifiers(name2, event, false)];
        if (noShift && noShift(view.state, view.dispatch, view))
          return true;
      }
      if ((event.shiftKey || event.altKey || event.metaKey || name2.charCodeAt(0) > 127) && (baseName = base$1[event.keyCode]) && baseName != name2) {
        let fromCode = map3[modifiers(baseName, event)];
        if (fromCode && fromCode(view.state, view.dispatch, view))
          return true;
      }
    }
    return false;
  };
}
__name(keydownHandler, "keydownHandler");
const deleteSelection$1 = /* @__PURE__ */ __name((state, dispatch) => {
  if (state.selection.empty)
    return false;
  if (dispatch)
    dispatch(state.tr.deleteSelection().scrollIntoView());
  return true;
}, "deleteSelection$1");
function atBlockStart(state, view) {
  let { $cursor } = state.selection;
  if (!$cursor || (view ? !view.endOfTextblock("backward", state) : $cursor.parentOffset > 0))
    return null;
  return $cursor;
}
__name(atBlockStart, "atBlockStart");
const joinBackward$1 = /* @__PURE__ */ __name((state, dispatch, view) => {
  let $cursor = atBlockStart(state, view);
  if (!$cursor)
    return false;
  let $cut = findCutBefore($cursor);
  if (!$cut) {
    let range = $cursor.blockRange(), target = range && liftTarget(range);
    if (target == null)
      return false;
    if (dispatch)
      dispatch(state.tr.lift(range, target).scrollIntoView());
    return true;
  }
  let before = $cut.nodeBefore;
  if (deleteBarrier(state, $cut, dispatch, -1))
    return true;
  if ($cursor.parent.content.size == 0 && (textblockAt(before, "end") || NodeSelection.isSelectable(before))) {
    for (let depth = $cursor.depth; ; depth--) {
      let delStep = replaceStep(state.doc, $cursor.before(depth), $cursor.after(depth), Slice.empty);
      if (delStep && delStep.slice.size < delStep.to - delStep.from) {
        if (dispatch) {
          let tr2 = state.tr.step(delStep);
          tr2.setSelection(textblockAt(before, "end") ? Selection.findFrom(tr2.doc.resolve(tr2.mapping.map($cut.pos, -1)), -1) : NodeSelection.create(tr2.doc, $cut.pos - before.nodeSize));
          dispatch(tr2.scrollIntoView());
        }
        return true;
      }
      if (depth == 1 || $cursor.node(depth - 1).childCount > 1)
        break;
    }
  }
  if (before.isAtom && $cut.depth == $cursor.depth - 1) {
    if (dispatch)
      dispatch(state.tr.delete($cut.pos - before.nodeSize, $cut.pos).scrollIntoView());
    return true;
  }
  return false;
}, "joinBackward$1");
const joinTextblockBackward$1 = /* @__PURE__ */ __name((state, dispatch, view) => {
  let $cursor = atBlockStart(state, view);
  if (!$cursor)
    return false;
  let $cut = findCutBefore($cursor);
  return $cut ? joinTextblocksAround(state, $cut, dispatch) : false;
}, "joinTextblockBackward$1");
const joinTextblockForward$1 = /* @__PURE__ */ __name((state, dispatch, view) => {
  let $cursor = atBlockEnd(state, view);
  if (!$cursor)
    return false;
  let $cut = findCutAfter($cursor);
  return $cut ? joinTextblocksAround(state, $cut, dispatch) : false;
}, "joinTextblockForward$1");
function joinTextblocksAround(state, $cut, dispatch) {
  let before = $cut.nodeBefore, beforeText = before, beforePos = $cut.pos - 1;
  for (; !beforeText.isTextblock; beforePos--) {
    if (beforeText.type.spec.isolating)
      return false;
    let child2 = beforeText.lastChild;
    if (!child2)
      return false;
    beforeText = child2;
  }
  let after = $cut.nodeAfter, afterText = after, afterPos = $cut.pos + 1;
  for (; !afterText.isTextblock; afterPos++) {
    if (afterText.type.spec.isolating)
      return false;
    let child2 = afterText.firstChild;
    if (!child2)
      return false;
    afterText = child2;
  }
  let step = replaceStep(state.doc, beforePos, afterPos, Slice.empty);
  if (!step || step.from != beforePos || step instanceof ReplaceStep && step.slice.size >= afterPos - beforePos)
    return false;
  if (dispatch) {
    let tr2 = state.tr.step(step);
    tr2.setSelection(TextSelection.create(tr2.doc, beforePos));
    dispatch(tr2.scrollIntoView());
  }
  return true;
}
__name(joinTextblocksAround, "joinTextblocksAround");
function textblockAt(node2, side, only = false) {
  for (let scan = node2; scan; scan = side == "start" ? scan.firstChild : scan.lastChild) {
    if (scan.isTextblock)
      return true;
    if (only && scan.childCount != 1)
      return false;
  }
  return false;
}
__name(textblockAt, "textblockAt");
const selectNodeBackward$1 = /* @__PURE__ */ __name((state, dispatch, view) => {
  let { $head, empty: empty2 } = state.selection, $cut = $head;
  if (!empty2)
    return false;
  if ($head.parent.isTextblock) {
    if (view ? !view.endOfTextblock("backward", state) : $head.parentOffset > 0)
      return false;
    $cut = findCutBefore($head);
  }
  let node2 = $cut && $cut.nodeBefore;
  if (!node2 || !NodeSelection.isSelectable(node2))
    return false;
  if (dispatch)
    dispatch(state.tr.setSelection(NodeSelection.create(state.doc, $cut.pos - node2.nodeSize)).scrollIntoView());
  return true;
}, "selectNodeBackward$1");
function findCutBefore($pos) {
  if (!$pos.parent.type.spec.isolating)
    for (let i2 = $pos.depth - 1; i2 >= 0; i2--) {
      if ($pos.index(i2) > 0)
        return $pos.doc.resolve($pos.before(i2 + 1));
      if ($pos.node(i2).type.spec.isolating)
        break;
    }
  return null;
}
__name(findCutBefore, "findCutBefore");
function atBlockEnd(state, view) {
  let { $cursor } = state.selection;
  if (!$cursor || (view ? !view.endOfTextblock("forward", state) : $cursor.parentOffset < $cursor.parent.content.size))
    return null;
  return $cursor;
}
__name(atBlockEnd, "atBlockEnd");
const joinForward$1 = /* @__PURE__ */ __name((state, dispatch, view) => {
  let $cursor = atBlockEnd(state, view);
  if (!$cursor)
    return false;
  let $cut = findCutAfter($cursor);
  if (!$cut)
    return false;
  let after = $cut.nodeAfter;
  if (deleteBarrier(state, $cut, dispatch, 1))
    return true;
  if ($cursor.parent.content.size == 0 && (textblockAt(after, "start") || NodeSelection.isSelectable(after))) {
    let delStep = replaceStep(state.doc, $cursor.before(), $cursor.after(), Slice.empty);
    if (delStep && delStep.slice.size < delStep.to - delStep.from) {
      if (dispatch) {
        let tr2 = state.tr.step(delStep);
        tr2.setSelection(textblockAt(after, "start") ? Selection.findFrom(tr2.doc.resolve(tr2.mapping.map($cut.pos)), 1) : NodeSelection.create(tr2.doc, tr2.mapping.map($cut.pos)));
        dispatch(tr2.scrollIntoView());
      }
      return true;
    }
  }
  if (after.isAtom && $cut.depth == $cursor.depth - 1) {
    if (dispatch)
      dispatch(state.tr.delete($cut.pos, $cut.pos + after.nodeSize).scrollIntoView());
    return true;
  }
  return false;
}, "joinForward$1");
const selectNodeForward$1 = /* @__PURE__ */ __name((state, dispatch, view) => {
  let { $head, empty: empty2 } = state.selection, $cut = $head;
  if (!empty2)
    return false;
  if ($head.parent.isTextblock) {
    if (view ? !view.endOfTextblock("forward", state) : $head.parentOffset < $head.parent.content.size)
      return false;
    $cut = findCutAfter($head);
  }
  let node2 = $cut && $cut.nodeAfter;
  if (!node2 || !NodeSelection.isSelectable(node2))
    return false;
  if (dispatch)
    dispatch(state.tr.setSelection(NodeSelection.create(state.doc, $cut.pos)).scrollIntoView());
  return true;
}, "selectNodeForward$1");
function findCutAfter($pos) {
  if (!$pos.parent.type.spec.isolating)
    for (let i2 = $pos.depth - 1; i2 >= 0; i2--) {
      let parent2 = $pos.node(i2);
      if ($pos.index(i2) + 1 < parent2.childCount)
        return $pos.doc.resolve($pos.after(i2 + 1));
      if (parent2.type.spec.isolating)
        break;
    }
  return null;
}
__name(findCutAfter, "findCutAfter");
const joinUp$1 = /* @__PURE__ */ __name((state, dispatch) => {
  let sel = state.selection, nodeSel = sel instanceof NodeSelection, point;
  if (nodeSel) {
    if (sel.node.isTextblock || !canJoin(state.doc, sel.from))
      return false;
    point = sel.from;
  } else {
    point = joinPoint(state.doc, sel.from, -1);
    if (point == null)
      return false;
  }
  if (dispatch) {
    let tr2 = state.tr.join(point);
    if (nodeSel)
      tr2.setSelection(NodeSelection.create(tr2.doc, point - state.doc.resolve(point).nodeBefore.nodeSize));
    dispatch(tr2.scrollIntoView());
  }
  return true;
}, "joinUp$1");
const joinDown$1 = /* @__PURE__ */ __name((state, dispatch) => {
  let sel = state.selection, point;
  if (sel instanceof NodeSelection) {
    if (sel.node.isTextblock || !canJoin(state.doc, sel.to))
      return false;
    point = sel.to;
  } else {
    point = joinPoint(state.doc, sel.to, 1);
    if (point == null)
      return false;
  }
  if (dispatch)
    dispatch(state.tr.join(point).scrollIntoView());
  return true;
}, "joinDown$1");
const lift$1 = /* @__PURE__ */ __name((state, dispatch) => {
  let { $from, $to } = state.selection;
  let range = $from.blockRange($to), target = range && liftTarget(range);
  if (target == null)
    return false;
  if (dispatch)
    dispatch(state.tr.lift(range, target).scrollIntoView());
  return true;
}, "lift$1");
const newlineInCode$1 = /* @__PURE__ */ __name((state, dispatch) => {
  let { $head, $anchor } = state.selection;
  if (!$head.parent.type.spec.code || !$head.sameParent($anchor))
    return false;
  if (dispatch)
    dispatch(state.tr.insertText("\n").scrollIntoView());
  return true;
}, "newlineInCode$1");
function defaultBlockAt$1(match2) {
  for (let i2 = 0; i2 < match2.edgeCount; i2++) {
    let { type } = match2.edge(i2);
    if (type.isTextblock && !type.hasRequiredAttrs())
      return type;
  }
  return null;
}
__name(defaultBlockAt$1, "defaultBlockAt$1");
const exitCode$1 = /* @__PURE__ */ __name((state, dispatch) => {
  let { $head, $anchor } = state.selection;
  if (!$head.parent.type.spec.code || !$head.sameParent($anchor))
    return false;
  let above = $head.node(-1), after = $head.indexAfter(-1), type = defaultBlockAt$1(above.contentMatchAt(after));
  if (!type || !above.canReplaceWith(after, after, type))
    return false;
  if (dispatch) {
    let pos = $head.after(), tr2 = state.tr.replaceWith(pos, pos, type.createAndFill());
    tr2.setSelection(Selection.near(tr2.doc.resolve(pos), 1));
    dispatch(tr2.scrollIntoView());
  }
  return true;
}, "exitCode$1");
const createParagraphNear$1 = /* @__PURE__ */ __name((state, dispatch) => {
  let sel = state.selection, { $from, $to } = sel;
  if (sel instanceof AllSelection || $from.parent.inlineContent || $to.parent.inlineContent)
    return false;
  let type = defaultBlockAt$1($to.parent.contentMatchAt($to.indexAfter()));
  if (!type || !type.isTextblock)
    return false;
  if (dispatch) {
    let side = (!$from.parentOffset && $to.index() < $to.parent.childCount ? $from : $to).pos;
    let tr2 = state.tr.insert(side, type.createAndFill());
    tr2.setSelection(TextSelection.create(tr2.doc, side + 1));
    dispatch(tr2.scrollIntoView());
  }
  return true;
}, "createParagraphNear$1");
const liftEmptyBlock$1 = /* @__PURE__ */ __name((state, dispatch) => {
  let { $cursor } = state.selection;
  if (!$cursor || $cursor.parent.content.size)
    return false;
  if ($cursor.depth > 1 && $cursor.after() != $cursor.end(-1)) {
    let before = $cursor.before();
    if (canSplit(state.doc, before)) {
      if (dispatch)
        dispatch(state.tr.split(before).scrollIntoView());
      return true;
    }
  }
  let range = $cursor.blockRange(), target = range && liftTarget(range);
  if (target == null)
    return false;
  if (dispatch)
    dispatch(state.tr.lift(range, target).scrollIntoView());
  return true;
}, "liftEmptyBlock$1");
function splitBlockAs(splitNode) {
  return (state, dispatch) => {
    let { $from, $to } = state.selection;
    if (state.selection instanceof NodeSelection && state.selection.node.isBlock) {
      if (!$from.parentOffset || !canSplit(state.doc, $from.pos))
        return false;
      if (dispatch)
        dispatch(state.tr.split($from.pos).scrollIntoView());
      return true;
    }
    if (!$from.depth)
      return false;
    let types = [];
    let splitDepth, deflt, atEnd = false, atStart = false;
    for (let d2 = $from.depth; ; d2--) {
      let node2 = $from.node(d2);
      if (node2.isBlock) {
        atEnd = $from.end(d2) == $from.pos + ($from.depth - d2);
        atStart = $from.start(d2) == $from.pos - ($from.depth - d2);
        deflt = defaultBlockAt$1($from.node(d2 - 1).contentMatchAt($from.indexAfter(d2 - 1)));
        let splitType = splitNode && splitNode($to.parent, atEnd, $from);
        types.unshift(splitType || (atEnd && deflt ? { type: deflt } : null));
        splitDepth = d2;
        break;
      } else {
        if (d2 == 1)
          return false;
        types.unshift(null);
      }
    }
    let tr2 = state.tr;
    if (state.selection instanceof TextSelection || state.selection instanceof AllSelection)
      tr2.deleteSelection();
    let splitPos = tr2.mapping.map($from.pos);
    let can = canSplit(tr2.doc, splitPos, types.length, types);
    if (!can) {
      types[0] = deflt ? { type: deflt } : null;
      can = canSplit(tr2.doc, splitPos, types.length, types);
    }
    tr2.split(splitPos, types.length, types);
    if (!atEnd && atStart && $from.node(splitDepth).type != deflt) {
      let first2 = tr2.mapping.map($from.before(splitDepth)), $first = tr2.doc.resolve(first2);
      if (deflt && $from.node(splitDepth - 1).canReplaceWith($first.index(), $first.index() + 1, deflt))
        tr2.setNodeMarkup(tr2.mapping.map($from.before(splitDepth)), deflt);
    }
    if (dispatch)
      dispatch(tr2.scrollIntoView());
    return true;
  };
}
__name(splitBlockAs, "splitBlockAs");
const splitBlock$1 = splitBlockAs();
const splitBlockKeepMarks = /* @__PURE__ */ __name((state, dispatch) => {
  return splitBlock$1(state, dispatch && ((tr2) => {
    let marks = state.storedMarks || state.selection.$to.parentOffset && state.selection.$from.marks();
    if (marks)
      tr2.ensureMarks(marks);
    dispatch(tr2);
  }));
}, "splitBlockKeepMarks");
const selectParentNode$1 = /* @__PURE__ */ __name((state, dispatch) => {
  let { $from, to } = state.selection, pos;
  let same = $from.sharedDepth(to);
  if (same == 0)
    return false;
  pos = $from.before(same);
  if (dispatch)
    dispatch(state.tr.setSelection(NodeSelection.create(state.doc, pos)));
  return true;
}, "selectParentNode$1");
const selectAll$1 = /* @__PURE__ */ __name((state, dispatch) => {
  if (dispatch)
    dispatch(state.tr.setSelection(new AllSelection(state.doc)));
  return true;
}, "selectAll$1");
function joinMaybeClear(state, $pos, dispatch) {
  let before = $pos.nodeBefore, after = $pos.nodeAfter, index2 = $pos.index();
  if (!before || !after || !before.type.compatibleContent(after.type))
    return false;
  if (!before.content.size && $pos.parent.canReplace(index2 - 1, index2)) {
    if (dispatch)
      dispatch(state.tr.delete($pos.pos - before.nodeSize, $pos.pos).scrollIntoView());
    return true;
  }
  if (!$pos.parent.canReplace(index2, index2 + 1) || !(after.isTextblock || canJoin(state.doc, $pos.pos)))
    return false;
  if (dispatch)
    dispatch(state.tr.join($pos.pos).scrollIntoView());
  return true;
}
__name(joinMaybeClear, "joinMaybeClear");
function deleteBarrier(state, $cut, dispatch, dir) {
  let before = $cut.nodeBefore, after = $cut.nodeAfter, conn, match2;
  let isolated = before.type.spec.isolating || after.type.spec.isolating;
  if (!isolated && joinMaybeClear(state, $cut, dispatch))
    return true;
  let canDelAfter = !isolated && $cut.parent.canReplace($cut.index(), $cut.index() + 1);
  if (canDelAfter && (conn = (match2 = before.contentMatchAt(before.childCount)).findWrapping(after.type)) && match2.matchType(conn[0] || after.type).validEnd) {
    if (dispatch) {
      let end = $cut.pos + after.nodeSize, wrap2 = Fragment.empty;
      for (let i2 = conn.length - 1; i2 >= 0; i2--)
        wrap2 = Fragment.from(conn[i2].create(null, wrap2));
      wrap2 = Fragment.from(before.copy(wrap2));
      let tr2 = state.tr.step(new ReplaceAroundStep($cut.pos - 1, end, $cut.pos, end, new Slice(wrap2, 1, 0), conn.length, true));
      let $joinAt = tr2.doc.resolve(end + 2 * conn.length);
      if ($joinAt.nodeAfter && $joinAt.nodeAfter.type == before.type && canJoin(tr2.doc, $joinAt.pos))
        tr2.join($joinAt.pos);
      dispatch(tr2.scrollIntoView());
    }
    return true;
  }
  let selAfter = after.type.spec.isolating || dir > 0 && isolated ? null : Selection.findFrom($cut, 1);
  let range = selAfter && selAfter.$from.blockRange(selAfter.$to), target = range && liftTarget(range);
  if (target != null && target >= $cut.depth) {
    if (dispatch)
      dispatch(state.tr.lift(range, target).scrollIntoView());
    return true;
  }
  if (canDelAfter && textblockAt(after, "start", true) && textblockAt(before, "end")) {
    let at2 = before, wrap2 = [];
    for (; ; ) {
      wrap2.push(at2);
      if (at2.isTextblock)
        break;
      at2 = at2.lastChild;
    }
    let afterText = after, afterDepth = 1;
    for (; !afterText.isTextblock; afterText = afterText.firstChild)
      afterDepth++;
    if (at2.canReplace(at2.childCount, at2.childCount, afterText.content)) {
      if (dispatch) {
        let end = Fragment.empty;
        for (let i2 = wrap2.length - 1; i2 >= 0; i2--)
          end = Fragment.from(wrap2[i2].copy(end));
        let tr2 = state.tr.step(new ReplaceAroundStep($cut.pos - wrap2.length, $cut.pos + after.nodeSize, $cut.pos + afterDepth, $cut.pos + after.nodeSize - afterDepth, new Slice(end, wrap2.length, 0), 0, true));
        dispatch(tr2.scrollIntoView());
      }
      return true;
    }
  }
  return false;
}
__name(deleteBarrier, "deleteBarrier");
function selectTextblockSide(side) {
  return function(state, dispatch) {
    let sel = state.selection, $pos = side < 0 ? sel.$from : sel.$to;
    let depth = $pos.depth;
    while ($pos.node(depth).isInline) {
      if (!depth)
        return false;
      depth--;
    }
    if (!$pos.node(depth).isTextblock)
      return false;
    if (dispatch)
      dispatch(state.tr.setSelection(TextSelection.create(state.doc, side < 0 ? $pos.start(depth) : $pos.end(depth))));
    return true;
  };
}
__name(selectTextblockSide, "selectTextblockSide");
const selectTextblockStart$1 = selectTextblockSide(-1);
const selectTextblockEnd$1 = selectTextblockSide(1);
function wrapIn$1(nodeType, attrs2 = null) {
  return function(state, dispatch) {
    let { $from, $to } = state.selection;
    let range = $from.blockRange($to), wrapping = range && findWrapping(range, nodeType, attrs2);
    if (!wrapping)
      return false;
    if (dispatch)
      dispatch(state.tr.wrap(range, wrapping).scrollIntoView());
    return true;
  };
}
__name(wrapIn$1, "wrapIn$1");
function setBlockType(nodeType, attrs2 = null) {
  return function(state, dispatch) {
    let applicable = false;
    for (let i2 = 0; i2 < state.selection.ranges.length && !applicable; i2++) {
      let { $from: { pos: from2 }, $to: { pos: to } } = state.selection.ranges[i2];
      state.doc.nodesBetween(from2, to, (node2, pos) => {
        if (applicable)
          return false;
        if (!node2.isTextblock || node2.hasMarkup(nodeType, attrs2))
          return;
        if (node2.type == nodeType) {
          applicable = true;
        } else {
          let $pos = state.doc.resolve(pos), index2 = $pos.index();
          applicable = $pos.parent.canReplaceWith(index2, index2 + 1, nodeType);
        }
      });
    }
    if (!applicable)
      return false;
    if (dispatch) {
      let tr2 = state.tr;
      for (let i2 = 0; i2 < state.selection.ranges.length; i2++) {
        let { $from: { pos: from2 }, $to: { pos: to } } = state.selection.ranges[i2];
        tr2.setBlockType(from2, to, nodeType, attrs2);
      }
      dispatch(tr2.scrollIntoView());
    }
    return true;
  };
}
__name(setBlockType, "setBlockType");
function markApplies(doc2, ranges, type, enterAtoms) {
  for (let i2 = 0; i2 < ranges.length; i2++) {
    let { $from, $to } = ranges[i2];
    let can = $from.depth == 0 ? doc2.inlineContent && doc2.type.allowsMarkType(type) : false;
    doc2.nodesBetween($from.pos, $to.pos, (node2, pos) => {
      if (can || !enterAtoms && node2.isAtom && node2.isInline && pos >= $from.pos && pos + node2.nodeSize <= $to.pos)
        return false;
      can = node2.inlineContent && node2.type.allowsMarkType(type);
    });
    if (can)
      return true;
  }
  return false;
}
__name(markApplies, "markApplies");
function removeInlineAtoms(ranges) {
  let result = [];
  for (let i2 = 0; i2 < ranges.length; i2++) {
    let { $from, $to } = ranges[i2];
    $from.doc.nodesBetween($from.pos, $to.pos, (node2, pos) => {
      if (node2.isAtom && node2.content.size && node2.isInline && pos >= $from.pos && pos + node2.nodeSize <= $to.pos) {
        if (pos + 1 > $from.pos)
          result.push(new SelectionRange($from, $from.doc.resolve(pos + 1)));
        $from = $from.doc.resolve(pos + 1 + node2.content.size);
        return false;
      }
    });
    if ($from.pos < $to.pos)
      result.push(new SelectionRange($from, $to));
  }
  return result;
}
__name(removeInlineAtoms, "removeInlineAtoms");
function toggleMark$1(markType, attrs2 = null, options2) {
  let removeWhenPresent = (options2 && options2.removeWhenPresent) !== false;
  let enterAtoms = (options2 && options2.enterInlineAtoms) !== false;
  return function(state, dispatch) {
    let { empty: empty2, $cursor, ranges } = state.selection;
    if (empty2 && !$cursor || !markApplies(state.doc, ranges, markType, enterAtoms))
      return false;
    if (dispatch) {
      if ($cursor) {
        if (markType.isInSet(state.storedMarks || $cursor.marks()))
          dispatch(state.tr.removeStoredMark(markType));
        else
          dispatch(state.tr.addStoredMark(markType.create(attrs2)));
      } else {
        let add3, tr2 = state.tr;
        if (!enterAtoms)
          ranges = removeInlineAtoms(ranges);
        if (removeWhenPresent) {
          add3 = !ranges.some((r2) => state.doc.rangeHasMark(r2.$from.pos, r2.$to.pos, markType));
        } else {
          add3 = !ranges.every((r2) => {
            let missing = false;
            tr2.doc.nodesBetween(r2.$from.pos, r2.$to.pos, (node2, pos, parent2) => {
              if (missing)
                return false;
              missing = !markType.isInSet(node2.marks) && !!parent2 && parent2.type.allowsMarkType(markType) && !(node2.isText && /^\s*$/.test(node2.textBetween(Math.max(0, r2.$from.pos - pos), Math.min(node2.nodeSize, r2.$to.pos - pos))));
            });
            return !missing;
          });
        }
        for (let i2 = 0; i2 < ranges.length; i2++) {
          let { $from, $to } = ranges[i2];
          if (!add3) {
            tr2.removeMark($from.pos, $to.pos, markType);
          } else {
            let from2 = $from.pos, to = $to.pos, start2 = $from.nodeAfter, end = $to.nodeBefore;
            let spaceStart = start2 && start2.isText ? /^\s*/.exec(start2.text)[0].length : 0;
            let spaceEnd = end && end.isText ? /\s*$/.exec(end.text)[0].length : 0;
            if (from2 + spaceStart < to) {
              from2 += spaceStart;
              to -= spaceEnd;
            }
            tr2.addMark(from2, to, markType.create(attrs2));
          }
        }
        dispatch(tr2.scrollIntoView());
      }
    }
    return true;
  };
}
__name(toggleMark$1, "toggleMark$1");
function wrapDispatchForJoin(dispatch, isJoinable) {
  return (tr2) => {
    if (!tr2.isGeneric)
      return dispatch(tr2);
    let ranges = [];
    for (let i2 = 0; i2 < tr2.mapping.maps.length; i2++) {
      let map3 = tr2.mapping.maps[i2];
      for (let j2 = 0; j2 < ranges.length; j2++)
        ranges[j2] = map3.map(ranges[j2]);
      map3.forEach((_s, _e2, from2, to) => ranges.push(from2, to));
    }
    let joinable2 = [];
    for (let i2 = 0; i2 < ranges.length; i2 += 2) {
      let from2 = ranges[i2], to = ranges[i2 + 1];
      let $from = tr2.doc.resolve(from2), depth = $from.sharedDepth(to), parent2 = $from.node(depth);
      for (let index2 = $from.indexAfter(depth), pos = $from.after(depth + 1); pos <= to; ++index2) {
        let after = parent2.maybeChild(index2);
        if (!after)
          break;
        if (index2 && joinable2.indexOf(pos) == -1) {
          let before = parent2.child(index2 - 1);
          if (before.type == after.type && isJoinable(before, after))
            joinable2.push(pos);
        }
        pos += after.nodeSize;
      }
    }
    joinable2.sort((a2, b2) => a2 - b2);
    for (let i2 = joinable2.length - 1; i2 >= 0; i2--) {
      if (canJoin(tr2.doc, joinable2[i2]))
        tr2.join(joinable2[i2]);
    }
    dispatch(tr2);
  };
}
__name(wrapDispatchForJoin, "wrapDispatchForJoin");
function autoJoin(command2, isJoinable) {
  let canJoin2 = Array.isArray(isJoinable) ? (node2) => isJoinable.indexOf(node2.type.name) > -1 : isJoinable;
  return (state, dispatch, view) => command2(state, dispatch && wrapDispatchForJoin(dispatch, canJoin2), view);
}
__name(autoJoin, "autoJoin");
function chainCommands(...commands2) {
  return function(state, dispatch, view) {
    for (let i2 = 0; i2 < commands2.length; i2++)
      if (commands2[i2](state, dispatch, view))
        return true;
    return false;
  };
}
__name(chainCommands, "chainCommands");
let backspace = chainCommands(deleteSelection$1, joinBackward$1, selectNodeBackward$1);
let del = chainCommands(deleteSelection$1, joinForward$1, selectNodeForward$1);
const pcBaseKeymap = {
  "Enter": chainCommands(newlineInCode$1, createParagraphNear$1, liftEmptyBlock$1, splitBlock$1),
  "Mod-Enter": exitCode$1,
  "Backspace": backspace,
  "Mod-Backspace": backspace,
  "Shift-Backspace": backspace,
  "Delete": del,
  "Mod-Delete": del,
  "Mod-a": selectAll$1
};
const macBaseKeymap = {
  "Ctrl-h": pcBaseKeymap["Backspace"],
  "Alt-Backspace": pcBaseKeymap["Mod-Backspace"],
  "Ctrl-d": pcBaseKeymap["Delete"],
  "Ctrl-Alt-Backspace": pcBaseKeymap["Mod-Delete"],
  "Alt-Delete": pcBaseKeymap["Mod-Delete"],
  "Alt-d": pcBaseKeymap["Mod-Delete"],
  "Ctrl-a": selectTextblockStart$1,
  "Ctrl-e": selectTextblockEnd$1
};
for (let key in pcBaseKeymap)
  macBaseKeymap[key] = pcBaseKeymap[key];
const mac = typeof navigator != "undefined" ? /Mac|iP(hone|[oa]d)/.test(navigator.platform) : typeof os != "undefined" && os.platform ? os.platform() == "darwin" : false;
const baseKeymap = mac ? macBaseKeymap : pcBaseKeymap;
const olDOM = ["ol", 0], ulDOM = ["ul", 0], liDOM = ["li", 0];
const orderedList = {
  attrs: { order: { default: 1, validate: "number" } },
  parseDOM: [{ tag: "ol", getAttrs(dom) {
    return { order: dom.hasAttribute("start") ? +dom.getAttribute("start") : 1 };
  } }],
  toDOM(node2) {
    return node2.attrs.order == 1 ? olDOM : ["ol", { start: node2.attrs.order }, 0];
  }
};
const bulletList = {
  parseDOM: [{ tag: "ul" }],
  toDOM() {
    return ulDOM;
  }
};
const listItem = {
  parseDOM: [{ tag: "li" }],
  toDOM() {
    return liDOM;
  },
  defining: true
};
function add(obj, props) {
  let copy2 = {};
  for (let prop2 in obj)
    copy2[prop2] = obj[prop2];
  for (let prop2 in props)
    copy2[prop2] = props[prop2];
  return copy2;
}
__name(add, "add");
function addListNodes(nodes, itemContent, listGroup) {
  return nodes.append({
    ordered_list: add(orderedList, { content: "list_item+", group: listGroup }),
    bullet_list: add(bulletList, { content: "list_item+", group: listGroup }),
    list_item: add(listItem, { content: itemContent })
  });
}
__name(addListNodes, "addListNodes");
function wrapInList$1(listType, attrs2 = null) {
  return function(state, dispatch) {
    let { $from, $to } = state.selection;
    let range = $from.blockRange($to);
    if (!range)
      return false;
    let tr2 = dispatch ? state.tr : null;
    if (!wrapRangeInList(tr2, range, listType, attrs2))
      return false;
    if (dispatch)
      dispatch(tr2.scrollIntoView());
    return true;
  };
}
__name(wrapInList$1, "wrapInList$1");
function wrapRangeInList(tr2, range, listType, attrs2 = null) {
  let doJoin = false, outerRange = range, doc2 = range.$from.doc;
  if (range.depth >= 2 && range.$from.node(range.depth - 1).type.compatibleContent(listType) && range.startIndex == 0) {
    if (range.$from.index(range.depth - 1) == 0)
      return false;
    let $insert = doc2.resolve(range.start - 2);
    outerRange = new NodeRange($insert, $insert, range.depth);
    if (range.endIndex < range.parent.childCount)
      range = new NodeRange(range.$from, doc2.resolve(range.$to.end(range.depth)), range.depth);
    doJoin = true;
  }
  let wrap2 = findWrapping(outerRange, listType, attrs2, range);
  if (!wrap2)
    return false;
  if (tr2)
    doWrapInList(tr2, range, wrap2, doJoin, listType);
  return true;
}
__name(wrapRangeInList, "wrapRangeInList");
function doWrapInList(tr2, range, wrappers, joinBefore, listType) {
  let content = Fragment.empty;
  for (let i2 = wrappers.length - 1; i2 >= 0; i2--)
    content = Fragment.from(wrappers[i2].type.create(wrappers[i2].attrs, content));
  tr2.step(new ReplaceAroundStep(range.start - (joinBefore ? 2 : 0), range.end, range.start, range.end, new Slice(content, 0, 0), wrappers.length, true));
  let found2 = 0;
  for (let i2 = 0; i2 < wrappers.length; i2++)
    if (wrappers[i2].type == listType)
      found2 = i2 + 1;
  let splitDepth = wrappers.length - found2;
  let splitPos = range.start + wrappers.length - (joinBefore ? 2 : 0), parent2 = range.parent;
  for (let i2 = range.startIndex, e2 = range.endIndex, first2 = true; i2 < e2; i2++, first2 = false) {
    if (!first2 && canSplit(tr2.doc, splitPos, splitDepth)) {
      tr2.split(splitPos, splitDepth);
      splitPos += 2 * splitDepth;
    }
    splitPos += parent2.child(i2).nodeSize;
  }
  return tr2;
}
__name(doWrapInList, "doWrapInList");
function splitListItem$1(itemType, itemAttrs) {
  return function(state, dispatch) {
    let { $from, $to, node: node2 } = state.selection;
    if (node2 && node2.isBlock || $from.depth < 2 || !$from.sameParent($to))
      return false;
    let grandParent = $from.node(-1);
    if (grandParent.type != itemType)
      return false;
    if ($from.parent.content.size == 0 && $from.node(-1).childCount == $from.indexAfter(-1)) {
      if ($from.depth == 3 || $from.node(-3).type != itemType || $from.index(-2) != $from.node(-2).childCount - 1)
        return false;
      if (dispatch) {
        let wrap2 = Fragment.empty;
        let depthBefore = $from.index(-1) ? 1 : $from.index(-2) ? 2 : 3;
        for (let d2 = $from.depth - depthBefore; d2 >= $from.depth - 3; d2--)
          wrap2 = Fragment.from($from.node(d2).copy(wrap2));
        let depthAfter = $from.indexAfter(-1) < $from.node(-2).childCount ? 1 : $from.indexAfter(-2) < $from.node(-3).childCount ? 2 : 3;
        wrap2 = wrap2.append(Fragment.from(itemType.createAndFill()));
        let start2 = $from.before($from.depth - (depthBefore - 1));
        let tr3 = state.tr.replace(start2, $from.after(-depthAfter), new Slice(wrap2, 4 - depthBefore, 0));
        let sel = -1;
        tr3.doc.nodesBetween(start2, tr3.doc.content.size, (node3, pos) => {
          if (sel > -1)
            return false;
          if (node3.isTextblock && node3.content.size == 0)
            sel = pos + 1;
        });
        if (sel > -1)
          tr3.setSelection(Selection.near(tr3.doc.resolve(sel)));
        dispatch(tr3.scrollIntoView());
      }
      return true;
    }
    let nextType = $to.pos == $from.end() ? grandParent.contentMatchAt(0).defaultType : null;
    let tr2 = state.tr.delete($from.pos, $to.pos);
    let types = nextType ? [itemAttrs ? { type: itemType, attrs: itemAttrs } : null, { type: nextType }] : void 0;
    if (!canSplit(tr2.doc, $from.pos, 2, types))
      return false;
    if (dispatch)
      dispatch(tr2.split($from.pos, 2, types).scrollIntoView());
    return true;
  };
}
__name(splitListItem$1, "splitListItem$1");
function splitListItemKeepMarks(itemType, itemAttrs) {
  let split2 = splitListItem$1(itemType, itemAttrs);
  return (state, dispatch) => {
    return split2(state, dispatch && ((tr2) => {
      let marks = state.storedMarks || state.selection.$to.parentOffset && state.selection.$from.marks();
      if (marks)
        tr2.ensureMarks(marks);
      dispatch(tr2);
    }));
  };
}
__name(splitListItemKeepMarks, "splitListItemKeepMarks");
function liftListItem$1(itemType) {
  return function(state, dispatch) {
    let { $from, $to } = state.selection;
    let range = $from.blockRange($to, (node2) => node2.childCount > 0 && node2.firstChild.type == itemType);
    if (!range)
      return false;
    if (!dispatch)
      return true;
    if ($from.node(range.depth - 1).type == itemType)
      return liftToOuterList(state, dispatch, itemType, range);
    else
      return liftOutOfList(state, dispatch, range);
  };
}
__name(liftListItem$1, "liftListItem$1");
function liftToOuterList(state, dispatch, itemType, range) {
  let tr2 = state.tr, end = range.end, endOfList = range.$to.end(range.depth);
  if (end < endOfList) {
    tr2.step(new ReplaceAroundStep(end - 1, endOfList, end, endOfList, new Slice(Fragment.from(itemType.create(null, range.parent.copy())), 1, 0), 1, true));
    range = new NodeRange(tr2.doc.resolve(range.$from.pos), tr2.doc.resolve(endOfList), range.depth);
  }
  const target = liftTarget(range);
  if (target == null)
    return false;
  tr2.lift(range, target);
  let after = tr2.mapping.map(end, -1) - 1;
  if (canJoin(tr2.doc, after))
    tr2.join(after);
  dispatch(tr2.scrollIntoView());
  return true;
}
__name(liftToOuterList, "liftToOuterList");
function liftOutOfList(state, dispatch, range) {
  let tr2 = state.tr, list2 = range.parent;
  for (let pos = range.end, i2 = range.endIndex - 1, e2 = range.startIndex; i2 > e2; i2--) {
    pos -= list2.child(i2).nodeSize;
    tr2.delete(pos - 1, pos + 1);
  }
  let $start = tr2.doc.resolve(range.start), item = $start.nodeAfter;
  if (tr2.mapping.map(range.end) != range.start + $start.nodeAfter.nodeSize)
    return false;
  let atStart = range.startIndex == 0, atEnd = range.endIndex == list2.childCount;
  let parent2 = $start.node(-1), indexBefore = $start.index(-1);
  if (!parent2.canReplace(indexBefore + (atStart ? 0 : 1), indexBefore + 1, item.content.append(atEnd ? Fragment.empty : Fragment.from(list2))))
    return false;
  let start2 = $start.pos, end = start2 + item.nodeSize;
  tr2.step(new ReplaceAroundStep(start2 - (atStart ? 1 : 0), end + (atEnd ? 1 : 0), start2 + 1, end - 1, new Slice((atStart ? Fragment.empty : Fragment.from(list2.copy(Fragment.empty))).append(atEnd ? Fragment.empty : Fragment.from(list2.copy(Fragment.empty))), atStart ? 0 : 1, atEnd ? 0 : 1), atStart ? 0 : 1));
  dispatch(tr2.scrollIntoView());
  return true;
}
__name(liftOutOfList, "liftOutOfList");
function sinkListItem$1(itemType) {
  return function(state, dispatch) {
    let { $from, $to } = state.selection;
    let range = $from.blockRange($to, (node2) => node2.childCount > 0 && node2.firstChild.type == itemType);
    if (!range)
      return false;
    let startIndex = range.startIndex;
    if (startIndex == 0)
      return false;
    let parent2 = range.parent, nodeBefore = parent2.child(startIndex - 1);
    if (nodeBefore.type != itemType)
      return false;
    if (dispatch) {
      let nestedBefore = nodeBefore.lastChild && nodeBefore.lastChild.type == parent2.type;
      let inner = Fragment.from(nestedBefore ? itemType.create() : null);
      let slice2 = new Slice(Fragment.from(itemType.create(null, Fragment.from(parent2.type.create(null, inner)))), nestedBefore ? 3 : 1, 0);
      let before = range.start, after = range.end;
      dispatch(state.tr.step(new ReplaceAroundStep(before - (nestedBefore ? 3 : 1), after, before, after, slice2, 1, true)).scrollIntoView());
    }
    return true;
  };
}
__name(sinkListItem$1, "sinkListItem$1");
function createChainableState(config2) {
  const { state, transaction } = config2;
  let { selection } = transaction;
  let { doc: doc2 } = transaction;
  let { storedMarks } = transaction;
  return {
    ...state,
    apply: state.apply.bind(state),
    applyTransaction: state.applyTransaction.bind(state),
    plugins: state.plugins,
    schema: state.schema,
    reconfigure: state.reconfigure.bind(state),
    toJSON: state.toJSON.bind(state),
    get storedMarks() {
      return storedMarks;
    },
    get selection() {
      return selection;
    },
    get doc() {
      return doc2;
    },
    get tr() {
      selection = transaction.selection;
      doc2 = transaction.doc;
      storedMarks = transaction.storedMarks;
      return transaction;
    }
  };
}
__name(createChainableState, "createChainableState");
class CommandManager {
  static {
    __name(this, "CommandManager");
  }
  constructor(props) {
    this.editor = props.editor;
    this.rawCommands = this.editor.extensionManager.commands;
    this.customState = props.state;
  }
  get hasCustomState() {
    return !!this.customState;
  }
  get state() {
    return this.customState || this.editor.state;
  }
  get commands() {
    const { rawCommands, editor, state } = this;
    const { view } = editor;
    const { tr: tr2 } = state;
    const props = this.buildProps(tr2);
    return Object.fromEntries(Object.entries(rawCommands).map(([name2, command2]) => {
      const method = /* @__PURE__ */ __name((...args) => {
        const callback = command2(...args)(props);
        if (!tr2.getMeta("preventDispatch") && !this.hasCustomState) {
          view.dispatch(tr2);
        }
        return callback;
      }, "method");
      return [name2, method];
    }));
  }
  get chain() {
    return () => this.createChain();
  }
  get can() {
    return () => this.createCan();
  }
  createChain(startTr, shouldDispatch = true) {
    const { rawCommands, editor, state } = this;
    const { view } = editor;
    const callbacks = [];
    const hasStartTransaction = !!startTr;
    const tr2 = startTr || state.tr;
    const run2 = /* @__PURE__ */ __name(() => {
      if (!hasStartTransaction && shouldDispatch && !tr2.getMeta("preventDispatch") && !this.hasCustomState) {
        view.dispatch(tr2);
      }
      return callbacks.every((callback) => callback === true);
    }, "run");
    const chain = {
      ...Object.fromEntries(Object.entries(rawCommands).map(([name2, command2]) => {
        const chainedCommand = /* @__PURE__ */ __name((...args) => {
          const props = this.buildProps(tr2, shouldDispatch);
          const callback = command2(...args)(props);
          callbacks.push(callback);
          return chain;
        }, "chainedCommand");
        return [name2, chainedCommand];
      })),
      run: run2
    };
    return chain;
  }
  createCan(startTr) {
    const { rawCommands, state } = this;
    const dispatch = false;
    const tr2 = startTr || state.tr;
    const props = this.buildProps(tr2, dispatch);
    const formattedCommands = Object.fromEntries(Object.entries(rawCommands).map(([name2, command2]) => {
      return [name2, (...args) => command2(...args)({ ...props, dispatch: void 0 })];
    }));
    return {
      ...formattedCommands,
      chain: /* @__PURE__ */ __name(() => this.createChain(tr2, dispatch), "chain")
    };
  }
  buildProps(tr2, shouldDispatch = true) {
    const { rawCommands, editor, state } = this;
    const { view } = editor;
    const props = {
      tr: tr2,
      editor,
      view,
      state: createChainableState({
        state,
        transaction: tr2
      }),
      dispatch: shouldDispatch ? () => void 0 : void 0,
      chain: /* @__PURE__ */ __name(() => this.createChain(tr2, shouldDispatch), "chain"),
      can: /* @__PURE__ */ __name(() => this.createCan(tr2), "can"),
      get commands() {
        return Object.fromEntries(Object.entries(rawCommands).map(([name2, command2]) => {
          return [name2, (...args) => command2(...args)(props)];
        }));
      }
    };
    return props;
  }
}
class EventEmitter {
  static {
    __name(this, "EventEmitter");
  }
  constructor() {
    this.callbacks = {};
  }
  on(event, fn) {
    if (!this.callbacks[event]) {
      this.callbacks[event] = [];
    }
    this.callbacks[event].push(fn);
    return this;
  }
  emit(event, ...args) {
    const callbacks = this.callbacks[event];
    if (callbacks) {
      callbacks.forEach((callback) => callback.apply(this, args));
    }
    return this;
  }
  off(event, fn) {
    const callbacks = this.callbacks[event];
    if (callbacks) {
      if (fn) {
        this.callbacks[event] = callbacks.filter((callback) => callback !== fn);
      } else {
        delete this.callbacks[event];
      }
    }
    return this;
  }
  once(event, fn) {
    const onceFn = /* @__PURE__ */ __name((...args) => {
      this.off(event, onceFn);
      fn.apply(this, args);
    }, "onceFn");
    return this.on(event, onceFn);
  }
  removeAllListeners() {
    this.callbacks = {};
  }
}
function getExtensionField(extension, field2, context) {
  if (extension.config[field2] === void 0 && extension.parent) {
    return getExtensionField(extension.parent, field2, context);
  }
  if (typeof extension.config[field2] === "function") {
    const value = extension.config[field2].bind({
      ...context,
      parent: extension.parent ? getExtensionField(extension.parent, field2, context) : null
    });
    return value;
  }
  return extension.config[field2];
}
__name(getExtensionField, "getExtensionField");
function splitExtensions(extensions) {
  const baseExtensions = extensions.filter((extension) => extension.type === "extension");
  const nodeExtensions = extensions.filter((extension) => extension.type === "node");
  const markExtensions = extensions.filter((extension) => extension.type === "mark");
  return {
    baseExtensions,
    nodeExtensions,
    markExtensions
  };
}
__name(splitExtensions, "splitExtensions");
function getAttributesFromExtensions(extensions) {
  const extensionAttributes = [];
  const { nodeExtensions, markExtensions } = splitExtensions(extensions);
  const nodeAndMarkExtensions = [...nodeExtensions, ...markExtensions];
  const defaultAttribute = {
    default: null,
    rendered: true,
    renderHTML: null,
    parseHTML: null,
    keepOnSplit: true,
    isRequired: false
  };
  extensions.forEach((extension) => {
    const context = {
      name: extension.name,
      options: extension.options,
      storage: extension.storage,
      extensions: nodeAndMarkExtensions
    };
    const addGlobalAttributes = getExtensionField(extension, "addGlobalAttributes", context);
    if (!addGlobalAttributes) {
      return;
    }
    const globalAttributes = addGlobalAttributes();
    globalAttributes.forEach((globalAttribute) => {
      globalAttribute.types.forEach((type) => {
        Object.entries(globalAttribute.attributes).forEach(([name2, attribute2]) => {
          extensionAttributes.push({
            type,
            name: name2,
            attribute: {
              ...defaultAttribute,
              ...attribute2
            }
          });
        });
      });
    });
  });
  nodeAndMarkExtensions.forEach((extension) => {
    const context = {
      name: extension.name,
      options: extension.options,
      storage: extension.storage
    };
    const addAttributes = getExtensionField(extension, "addAttributes", context);
    if (!addAttributes) {
      return;
    }
    const attributes = addAttributes();
    Object.entries(attributes).forEach(([name2, attribute2]) => {
      const mergedAttr = {
        ...defaultAttribute,
        ...attribute2
      };
      if (typeof (mergedAttr === null || mergedAttr === void 0 ? void 0 : mergedAttr.default) === "function") {
        mergedAttr.default = mergedAttr.default();
      }
      if ((mergedAttr === null || mergedAttr === void 0 ? void 0 : mergedAttr.isRequired) && (mergedAttr === null || mergedAttr === void 0 ? void 0 : mergedAttr.default) === void 0) {
        delete mergedAttr.default;
      }
      extensionAttributes.push({
        type: extension.name,
        name: name2,
        attribute: mergedAttr
      });
    });
  });
  return extensionAttributes;
}
__name(getAttributesFromExtensions, "getAttributesFromExtensions");
function getNodeType(nameOrType, schema2) {
  if (typeof nameOrType === "string") {
    if (!schema2.nodes[nameOrType]) {
      throw Error(`There is no node type named '${nameOrType}'. Maybe you forgot to add the extension?`);
    }
    return schema2.nodes[nameOrType];
  }
  return nameOrType;
}
__name(getNodeType, "getNodeType");
function mergeAttributes(...objects) {
  return objects.filter((item) => !!item).reduce((items, item) => {
    const mergedAttributes = { ...items };
    Object.entries(item).forEach(([key, value]) => {
      const exists = mergedAttributes[key];
      if (!exists) {
        mergedAttributes[key] = value;
        return;
      }
      if (key === "class") {
        const valueClasses = value ? value.split(" ") : [];
        const existingClasses = mergedAttributes[key] ? mergedAttributes[key].split(" ") : [];
        const insertClasses = valueClasses.filter((valueClass) => !existingClasses.includes(valueClass));
        mergedAttributes[key] = [...existingClasses, ...insertClasses].join(" ");
      } else if (key === "style") {
        const newStyles = value ? value.split(";").map((style2) => style2.trim()).filter(Boolean) : [];
        const existingStyles = mergedAttributes[key] ? mergedAttributes[key].split(";").map((style2) => style2.trim()).filter(Boolean) : [];
        const styleMap = /* @__PURE__ */ new Map();
        existingStyles.forEach((style2) => {
          const [property, val] = style2.split(":").map((part) => part.trim());
          styleMap.set(property, val);
        });
        newStyles.forEach((style2) => {
          const [property, val] = style2.split(":").map((part) => part.trim());
          styleMap.set(property, val);
        });
        mergedAttributes[key] = Array.from(styleMap.entries()).map(([property, val]) => `${property}: ${val}`).join("; ");
      } else {
        mergedAttributes[key] = value;
      }
    });
    return mergedAttributes;
  }, {});
}
__name(mergeAttributes, "mergeAttributes");
function getRenderedAttributes(nodeOrMark, extensionAttributes) {
  return extensionAttributes.filter((attribute2) => attribute2.type === nodeOrMark.type.name).filter((item) => item.attribute.rendered).map((item) => {
    if (!item.attribute.renderHTML) {
      return {
        [item.name]: nodeOrMark.attrs[item.name]
      };
    }
    return item.attribute.renderHTML(nodeOrMark.attrs) || {};
  }).reduce((attributes, attribute2) => mergeAttributes(attributes, attribute2), {});
}
__name(getRenderedAttributes, "getRenderedAttributes");
function isFunction$1(value) {
  return typeof value === "function";
}
__name(isFunction$1, "isFunction$1");
function callOrReturn(value, context = void 0, ...props) {
  if (isFunction$1(value)) {
    if (context) {
      return value.bind(context)(...props);
    }
    return value(...props);
  }
  return value;
}
__name(callOrReturn, "callOrReturn");
function isEmptyObject(value = {}) {
  return Object.keys(value).length === 0 && value.constructor === Object;
}
__name(isEmptyObject, "isEmptyObject");
function fromString(value) {
  if (typeof value !== "string") {
    return value;
  }
  if (value.match(/^[+-]?(?:\d*\.)?\d+$/)) {
    return Number(value);
  }
  if (value === "true") {
    return true;
  }
  if (value === "false") {
    return false;
  }
  return value;
}
__name(fromString, "fromString");
function injectExtensionAttributesToParseRule(parseRule, extensionAttributes) {
  if ("style" in parseRule) {
    return parseRule;
  }
  return {
    ...parseRule,
    getAttrs: /* @__PURE__ */ __name((node2) => {
      const oldAttributes = parseRule.getAttrs ? parseRule.getAttrs(node2) : parseRule.attrs;
      if (oldAttributes === false) {
        return false;
      }
      const newAttributes = extensionAttributes.reduce((items, item) => {
        const value = item.attribute.parseHTML ? item.attribute.parseHTML(node2) : fromString(node2.getAttribute(item.name));
        if (value === null || value === void 0) {
          return items;
        }
        return {
          ...items,
          [item.name]: value
        };
      }, {});
      return { ...oldAttributes, ...newAttributes };
    }, "getAttrs")
  };
}
__name(injectExtensionAttributesToParseRule, "injectExtensionAttributesToParseRule");
function cleanUpSchemaItem(data) {
  return Object.fromEntries(
    // @ts-ignore
    Object.entries(data).filter(([key, value]) => {
      if (key === "attrs" && isEmptyObject(value)) {
        return false;
      }
      return value !== null && value !== void 0;
    })
  );
}
__name(cleanUpSchemaItem, "cleanUpSchemaItem");
function getSchemaByResolvedExtensions(extensions, editor) {
  var _a2;
  const allAttributes = getAttributesFromExtensions(extensions);
  const { nodeExtensions, markExtensions } = splitExtensions(extensions);
  const topNode = (_a2 = nodeExtensions.find((extension) => getExtensionField(extension, "topNode"))) === null || _a2 === void 0 ? void 0 : _a2.name;
  const nodes = Object.fromEntries(nodeExtensions.map((extension) => {
    const extensionAttributes = allAttributes.filter((attribute2) => attribute2.type === extension.name);
    const context = {
      name: extension.name,
      options: extension.options,
      storage: extension.storage,
      editor
    };
    const extraNodeFields = extensions.reduce((fields, e2) => {
      const extendNodeSchema = getExtensionField(e2, "extendNodeSchema", context);
      return {
        ...fields,
        ...extendNodeSchema ? extendNodeSchema(extension) : {}
      };
    }, {});
    const schema2 = cleanUpSchemaItem({
      ...extraNodeFields,
      content: callOrReturn(getExtensionField(extension, "content", context)),
      marks: callOrReturn(getExtensionField(extension, "marks", context)),
      group: callOrReturn(getExtensionField(extension, "group", context)),
      inline: callOrReturn(getExtensionField(extension, "inline", context)),
      atom: callOrReturn(getExtensionField(extension, "atom", context)),
      selectable: callOrReturn(getExtensionField(extension, "selectable", context)),
      draggable: callOrReturn(getExtensionField(extension, "draggable", context)),
      code: callOrReturn(getExtensionField(extension, "code", context)),
      whitespace: callOrReturn(getExtensionField(extension, "whitespace", context)),
      linebreakReplacement: callOrReturn(getExtensionField(extension, "linebreakReplacement", context)),
      defining: callOrReturn(getExtensionField(extension, "defining", context)),
      isolating: callOrReturn(getExtensionField(extension, "isolating", context)),
      attrs: Object.fromEntries(extensionAttributes.map((extensionAttribute) => {
        var _a3;
        return [extensionAttribute.name, { default: (_a3 = extensionAttribute === null || extensionAttribute === void 0 ? void 0 : extensionAttribute.attribute) === null || _a3 === void 0 ? void 0 : _a3.default }];
      }))
    });
    const parseHTML = callOrReturn(getExtensionField(extension, "parseHTML", context));
    if (parseHTML) {
      schema2.parseDOM = parseHTML.map((parseRule) => injectExtensionAttributesToParseRule(parseRule, extensionAttributes));
    }
    const renderHTML = getExtensionField(extension, "renderHTML", context);
    if (renderHTML) {
      schema2.toDOM = (node2) => renderHTML({
        node: node2,
        HTMLAttributes: getRenderedAttributes(node2, extensionAttributes)
      });
    }
    const renderText = getExtensionField(extension, "renderText", context);
    if (renderText) {
      schema2.toText = renderText;
    }
    return [extension.name, schema2];
  }));
  const marks = Object.fromEntries(markExtensions.map((extension) => {
    const extensionAttributes = allAttributes.filter((attribute2) => attribute2.type === extension.name);
    const context = {
      name: extension.name,
      options: extension.options,
      storage: extension.storage,
      editor
    };
    const extraMarkFields = extensions.reduce((fields, e2) => {
      const extendMarkSchema = getExtensionField(e2, "extendMarkSchema", context);
      return {
        ...fields,
        ...extendMarkSchema ? extendMarkSchema(extension) : {}
      };
    }, {});
    const schema2 = cleanUpSchemaItem({
      ...extraMarkFields,
      inclusive: callOrReturn(getExtensionField(extension, "inclusive", context)),
      excludes: callOrReturn(getExtensionField(extension, "excludes", context)),
      group: callOrReturn(getExtensionField(extension, "group", context)),
      spanning: callOrReturn(getExtensionField(extension, "spanning", context)),
      code: callOrReturn(getExtensionField(extension, "code", context)),
      attrs: Object.fromEntries(extensionAttributes.map((extensionAttribute) => {
        var _a3;
        return [extensionAttribute.name, { default: (_a3 = extensionAttribute === null || extensionAttribute === void 0 ? void 0 : extensionAttribute.attribute) === null || _a3 === void 0 ? void 0 : _a3.default }];
      }))
    });
    const parseHTML = callOrReturn(getExtensionField(extension, "parseHTML", context));
    if (parseHTML) {
      schema2.parseDOM = parseHTML.map((parseRule) => injectExtensionAttributesToParseRule(parseRule, extensionAttributes));
    }
    const renderHTML = getExtensionField(extension, "renderHTML", context);
    if (renderHTML) {
      schema2.toDOM = (mark) => renderHTML({
        mark,
        HTMLAttributes: getRenderedAttributes(mark, extensionAttributes)
      });
    }
    return [extension.name, schema2];
  }));
  return new Schema({
    topNode,
    nodes,
    marks
  });
}
__name(getSchemaByResolvedExtensions, "getSchemaByResolvedExtensions");
function getSchemaTypeByName(name2, schema2) {
  return schema2.nodes[name2] || schema2.marks[name2] || null;
}
__name(getSchemaTypeByName, "getSchemaTypeByName");
function isExtensionRulesEnabled(extension, enabled) {
  if (Array.isArray(enabled)) {
    return enabled.some((enabledExtension) => {
      const name2 = typeof enabledExtension === "string" ? enabledExtension : enabledExtension.name;
      return name2 === extension.name;
    });
  }
  return enabled;
}
__name(isExtensionRulesEnabled, "isExtensionRulesEnabled");
function getHTMLFromFragment(fragment, schema2) {
  const documentFragment = DOMSerializer.fromSchema(schema2).serializeFragment(fragment);
  const temporaryDocument = document.implementation.createHTMLDocument();
  const container = temporaryDocument.createElement("div");
  container.appendChild(documentFragment);
  return container.innerHTML;
}
__name(getHTMLFromFragment, "getHTMLFromFragment");
const getTextContentFromNodes = /* @__PURE__ */ __name(($from, maxMatch = 500) => {
  let textBefore = "";
  const sliceEndPos = $from.parentOffset;
  $from.parent.nodesBetween(Math.max(0, sliceEndPos - maxMatch), sliceEndPos, (node2, pos, parent2, index2) => {
    var _a2, _b;
    const chunk = ((_b = (_a2 = node2.type.spec).toText) === null || _b === void 0 ? void 0 : _b.call(_a2, {
      node: node2,
      pos,
      parent: parent2,
      index: index2
    })) || node2.textContent || "%leaf%";
    textBefore += node2.isAtom && !node2.isText ? chunk : chunk.slice(0, Math.max(0, sliceEndPos - pos));
  });
  return textBefore;
}, "getTextContentFromNodes");
function isRegExp$1(value) {
  return Object.prototype.toString.call(value) === "[object RegExp]";
}
__name(isRegExp$1, "isRegExp$1");
class InputRule {
  static {
    __name(this, "InputRule");
  }
  constructor(config2) {
    this.find = config2.find;
    this.handler = config2.handler;
  }
}
const inputRuleMatcherHandler = /* @__PURE__ */ __name((text2, find2) => {
  if (isRegExp$1(find2)) {
    return find2.exec(text2);
  }
  const inputRuleMatch = find2(text2);
  if (!inputRuleMatch) {
    return null;
  }
  const result = [inputRuleMatch.text];
  result.index = inputRuleMatch.index;
  result.input = text2;
  result.data = inputRuleMatch.data;
  if (inputRuleMatch.replaceWith) {
    if (!inputRuleMatch.text.includes(inputRuleMatch.replaceWith)) {
      console.warn('[tiptap warn]: "inputRuleMatch.replaceWith" must be part of "inputRuleMatch.text".');
    }
    result.push(inputRuleMatch.replaceWith);
  }
  return result;
}, "inputRuleMatcherHandler");
function run$1$1(config2) {
  var _a2;
  const { editor, from: from2, to, text: text2, rules, plugin } = config2;
  const { view } = editor;
  if (view.composing) {
    return false;
  }
  const $from = view.state.doc.resolve(from2);
  if (
    // check for code node
    $from.parent.type.spec.code || !!((_a2 = $from.nodeBefore || $from.nodeAfter) === null || _a2 === void 0 ? void 0 : _a2.marks.find((mark) => mark.type.spec.code))
  ) {
    return false;
  }
  let matched = false;
  const textBefore = getTextContentFromNodes($from) + text2;
  rules.forEach((rule) => {
    if (matched) {
      return;
    }
    const match2 = inputRuleMatcherHandler(textBefore, rule.find);
    if (!match2) {
      return;
    }
    const tr2 = view.state.tr;
    const state = createChainableState({
      state: view.state,
      transaction: tr2
    });
    const range = {
      from: from2 - (match2[0].length - text2.length),
      to
    };
    const { commands: commands2, chain, can } = new CommandManager({
      editor,
      state
    });
    const handler5 = rule.handler({
      state,
      range,
      match: match2,
      commands: commands2,
      chain,
      can
    });
    if (handler5 === null || !tr2.steps.length) {
      return;
    }
    tr2.setMeta(plugin, {
      transform: tr2,
      from: from2,
      to,
      text: text2
    });
    view.dispatch(tr2);
    matched = true;
  });
  return matched;
}
__name(run$1$1, "run$1$1");
function inputRulesPlugin(props) {
  const { editor, rules } = props;
  const plugin = new Plugin({
    state: {
      init() {
        return null;
      },
      apply(tr2, prev, state) {
        const stored = tr2.getMeta(plugin);
        if (stored) {
          return stored;
        }
        const simulatedInputMeta = tr2.getMeta("applyInputRules");
        const isSimulatedInput = !!simulatedInputMeta;
        if (isSimulatedInput) {
          setTimeout(() => {
            let { text: text2 } = simulatedInputMeta;
            if (typeof text2 === "string") {
              text2 = text2;
            } else {
              text2 = getHTMLFromFragment(Fragment.from(text2), state.schema);
            }
            const { from: from2 } = simulatedInputMeta;
            const to = from2 + text2.length;
            run$1$1({
              editor,
              from: from2,
              to,
              text: text2,
              rules,
              plugin
            });
          });
        }
        return tr2.selectionSet || tr2.docChanged ? null : prev;
      }
    },
    props: {
      handleTextInput(view, from2, to, text2) {
        return run$1$1({
          editor,
          from: from2,
          to,
          text: text2,
          rules,
          plugin
        });
      },
      handleDOMEvents: {
        compositionend: /* @__PURE__ */ __name((view) => {
          setTimeout(() => {
            const { $cursor } = view.state.selection;
            if ($cursor) {
              run$1$1({
                editor,
                from: $cursor.pos,
                to: $cursor.pos,
                text: "",
                rules,
                plugin
              });
            }
          });
          return false;
        }, "compositionend")
      },
      // add support for input rules to trigger on enter
      // this is useful for example for code blocks
      handleKeyDown(view, event) {
        if (event.key !== "Enter") {
          return false;
        }
        const { $cursor } = view.state.selection;
        if ($cursor) {
          return run$1$1({
            editor,
            from: $cursor.pos,
            to: $cursor.pos,
            text: "\n",
            rules,
            plugin
          });
        }
        return false;
      }
    },
    // @ts-ignore
    isInputRules: true
  });
  return plugin;
}
__name(inputRulesPlugin, "inputRulesPlugin");
function getType(value) {
  return Object.prototype.toString.call(value).slice(8, -1);
}
__name(getType, "getType");
function isPlainObject(value) {
  if (getType(value) !== "Object") {
    return false;
  }
  return value.constructor === Object && Object.getPrototypeOf(value) === Object.prototype;
}
__name(isPlainObject, "isPlainObject");
function mergeDeep(target, source) {
  const output = { ...target };
  if (isPlainObject(target) && isPlainObject(source)) {
    Object.keys(source).forEach((key) => {
      if (isPlainObject(source[key]) && isPlainObject(target[key])) {
        output[key] = mergeDeep(target[key], source[key]);
      } else {
        output[key] = source[key];
      }
    });
  }
  return output;
}
__name(mergeDeep, "mergeDeep");
class Mark {
  static {
    __name(this, "Mark");
  }
  constructor(config2 = {}) {
    this.type = "mark";
    this.name = "mark";
    this.parent = null;
    this.child = null;
    this.config = {
      name: this.name,
      defaultOptions: {}
    };
    this.config = {
      ...this.config,
      ...config2
    };
    this.name = this.config.name;
    if (config2.defaultOptions && Object.keys(config2.defaultOptions).length > 0) {
      console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${this.name}".`);
    }
    this.options = this.config.defaultOptions;
    if (this.config.addOptions) {
      this.options = callOrReturn(getExtensionField(this, "addOptions", {
        name: this.name
      }));
    }
    this.storage = callOrReturn(getExtensionField(this, "addStorage", {
      name: this.name,
      options: this.options
    })) || {};
  }
  static create(config2 = {}) {
    return new Mark(config2);
  }
  configure(options2 = {}) {
    const extension = this.extend({
      ...this.config,
      addOptions: /* @__PURE__ */ __name(() => {
        return mergeDeep(this.options, options2);
      }, "addOptions")
    });
    extension.name = this.name;
    extension.parent = this.parent;
    return extension;
  }
  extend(extendedConfig = {}) {
    const extension = new Mark(extendedConfig);
    extension.parent = this;
    this.child = extension;
    extension.name = extendedConfig.name ? extendedConfig.name : extension.parent.name;
    if (extendedConfig.defaultOptions && Object.keys(extendedConfig.defaultOptions).length > 0) {
      console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${extension.name}".`);
    }
    extension.options = callOrReturn(getExtensionField(extension, "addOptions", {
      name: extension.name
    }));
    extension.storage = callOrReturn(getExtensionField(extension, "addStorage", {
      name: extension.name,
      options: extension.options
    }));
    return extension;
  }
  static handleExit({ editor, mark }) {
    const { tr: tr2 } = editor.state;
    const currentPos = editor.state.selection.$from;
    const isAtEnd = currentPos.pos === currentPos.end();
    if (isAtEnd) {
      const currentMarks = currentPos.marks();
      const isInMark = !!currentMarks.find((m2) => (m2 === null || m2 === void 0 ? void 0 : m2.type.name) === mark.name);
      if (!isInMark) {
        return false;
      }
      const removeMark2 = currentMarks.find((m2) => (m2 === null || m2 === void 0 ? void 0 : m2.type.name) === mark.name);
      if (removeMark2) {
        tr2.removeStoredMark(removeMark2);
      }
      tr2.insertText(" ", currentPos.pos);
      editor.view.dispatch(tr2);
      return true;
    }
    return false;
  }
}
function isNumber$2(value) {
  return typeof value === "number";
}
__name(isNumber$2, "isNumber$2");
class PasteRule {
  static {
    __name(this, "PasteRule");
  }
  constructor(config2) {
    this.find = config2.find;
    this.handler = config2.handler;
  }
}
const pasteRuleMatcherHandler = /* @__PURE__ */ __name((text2, find2, event) => {
  if (isRegExp$1(find2)) {
    return [...text2.matchAll(find2)];
  }
  const matches2 = find2(text2, event);
  if (!matches2) {
    return [];
  }
  return matches2.map((pasteRuleMatch) => {
    const result = [pasteRuleMatch.text];
    result.index = pasteRuleMatch.index;
    result.input = text2;
    result.data = pasteRuleMatch.data;
    if (pasteRuleMatch.replaceWith) {
      if (!pasteRuleMatch.text.includes(pasteRuleMatch.replaceWith)) {
        console.warn('[tiptap warn]: "pasteRuleMatch.replaceWith" must be part of "pasteRuleMatch.text".');
      }
      result.push(pasteRuleMatch.replaceWith);
    }
    return result;
  });
}, "pasteRuleMatcherHandler");
function run$2(config2) {
  const { editor, state, from: from2, to, rule, pasteEvent, dropEvent } = config2;
  const { commands: commands2, chain, can } = new CommandManager({
    editor,
    state
  });
  const handlers2 = [];
  state.doc.nodesBetween(from2, to, (node2, pos) => {
    if (!node2.isTextblock || node2.type.spec.code) {
      return;
    }
    const resolvedFrom = Math.max(from2, pos);
    const resolvedTo = Math.min(to, pos + node2.content.size);
    const textToMatch = node2.textBetween(resolvedFrom - pos, resolvedTo - pos, void 0, "￼");
    const matches2 = pasteRuleMatcherHandler(textToMatch, rule.find, pasteEvent);
    matches2.forEach((match2) => {
      if (match2.index === void 0) {
        return;
      }
      const start2 = resolvedFrom + match2.index + 1;
      const end = start2 + match2[0].length;
      const range = {
        from: state.tr.mapping.map(start2),
        to: state.tr.mapping.map(end)
      };
      const handler5 = rule.handler({
        state,
        range,
        match: match2,
        commands: commands2,
        chain,
        can,
        pasteEvent,
        dropEvent
      });
      handlers2.push(handler5);
    });
  });
  const success = handlers2.every((handler5) => handler5 !== null);
  return success;
}
__name(run$2, "run$2");
const createClipboardPasteEvent = /* @__PURE__ */ __name((text2) => {
  var _a2;
  const event = new ClipboardEvent("paste", {
    clipboardData: new DataTransfer()
  });
  (_a2 = event.clipboardData) === null || _a2 === void 0 ? void 0 : _a2.setData("text/html", text2);
  return event;
}, "createClipboardPasteEvent");
function pasteRulesPlugin(props) {
  const { editor, rules } = props;
  let dragSourceElement = null;
  let isPastedFromProseMirror = false;
  let isDroppedFromProseMirror = false;
  let pasteEvent = typeof ClipboardEvent !== "undefined" ? new ClipboardEvent("paste") : null;
  let dropEvent;
  try {
    dropEvent = typeof DragEvent !== "undefined" ? new DragEvent("drop") : null;
  } catch (e2) {
    dropEvent = null;
  }
  const processEvent = /* @__PURE__ */ __name(({ state, from: from2, to, rule, pasteEvt }) => {
    const tr2 = state.tr;
    const chainableState = createChainableState({
      state,
      transaction: tr2
    });
    const handler5 = run$2({
      editor,
      state: chainableState,
      from: Math.max(from2 - 1, 0),
      to: to.b - 1,
      rule,
      pasteEvent: pasteEvt,
      dropEvent
    });
    if (!handler5 || !tr2.steps.length) {
      return;
    }
    try {
      dropEvent = typeof DragEvent !== "undefined" ? new DragEvent("drop") : null;
    } catch (e2) {
      dropEvent = null;
    }
    pasteEvent = typeof ClipboardEvent !== "undefined" ? new ClipboardEvent("paste") : null;
    return tr2;
  }, "processEvent");
  const plugins = rules.map((rule) => {
    return new Plugin({
      // we register a global drag handler to track the current drag source element
      view(view) {
        const handleDragstart = /* @__PURE__ */ __name((event) => {
          var _a2;
          dragSourceElement = ((_a2 = view.dom.parentElement) === null || _a2 === void 0 ? void 0 : _a2.contains(event.target)) ? view.dom.parentElement : null;
        }, "handleDragstart");
        window.addEventListener("dragstart", handleDragstart);
        return {
          destroy() {
            window.removeEventListener("dragstart", handleDragstart);
          }
        };
      },
      props: {
        handleDOMEvents: {
          drop: /* @__PURE__ */ __name((view, event) => {
            isDroppedFromProseMirror = dragSourceElement === view.dom.parentElement;
            dropEvent = event;
            return false;
          }, "drop"),
          paste: /* @__PURE__ */ __name((_view, event) => {
            var _a2;
            const html = (_a2 = event.clipboardData) === null || _a2 === void 0 ? void 0 : _a2.getData("text/html");
            pasteEvent = event;
            isPastedFromProseMirror = !!(html === null || html === void 0 ? void 0 : html.includes("data-pm-slice"));
            return false;
          }, "paste")
        }
      },
      appendTransaction: /* @__PURE__ */ __name((transactions, oldState, state) => {
        const transaction = transactions[0];
        const isPaste = transaction.getMeta("uiEvent") === "paste" && !isPastedFromProseMirror;
        const isDrop = transaction.getMeta("uiEvent") === "drop" && !isDroppedFromProseMirror;
        const simulatedPasteMeta = transaction.getMeta("applyPasteRules");
        const isSimulatedPaste = !!simulatedPasteMeta;
        if (!isPaste && !isDrop && !isSimulatedPaste) {
          return;
        }
        if (isSimulatedPaste) {
          let { text: text2 } = simulatedPasteMeta;
          if (typeof text2 === "string") {
            text2 = text2;
          } else {
            text2 = getHTMLFromFragment(Fragment.from(text2), state.schema);
          }
          const { from: from3 } = simulatedPasteMeta;
          const to2 = from3 + text2.length;
          const pasteEvt = createClipboardPasteEvent(text2);
          return processEvent({
            rule,
            state,
            from: from3,
            to: { b: to2 },
            pasteEvt
          });
        }
        const from2 = oldState.doc.content.findDiffStart(state.doc.content);
        const to = oldState.doc.content.findDiffEnd(state.doc.content);
        if (!isNumber$2(from2) || !to || from2 === to.b) {
          return;
        }
        return processEvent({
          rule,
          state,
          from: from2,
          to,
          pasteEvt: pasteEvent
        });
      }, "appendTransaction")
    });
  });
  return plugins;
}
__name(pasteRulesPlugin, "pasteRulesPlugin");
function findDuplicates(items) {
  const filtered = items.filter((el, index2) => items.indexOf(el) !== index2);
  return Array.from(new Set(filtered));
}
__name(findDuplicates, "findDuplicates");
class ExtensionManager {
  static {
    __name(this, "ExtensionManager");
  }
  constructor(extensions, editor) {
    this.splittableMarks = [];
    this.editor = editor;
    this.extensions = ExtensionManager.resolve(extensions);
    this.schema = getSchemaByResolvedExtensions(this.extensions, editor);
    this.setupExtensions();
  }
  /**
   * Returns a flattened and sorted extension list while
   * also checking for duplicated extensions and warns the user.
   * @param extensions An array of Tiptap extensions
   * @returns An flattened and sorted array of Tiptap extensions
   */
  static resolve(extensions) {
    const resolvedExtensions = ExtensionManager.sort(ExtensionManager.flatten(extensions));
    const duplicatedNames = findDuplicates(resolvedExtensions.map((extension) => extension.name));
    if (duplicatedNames.length) {
      console.warn(`[tiptap warn]: Duplicate extension names found: [${duplicatedNames.map((item) => `'${item}'`).join(", ")}]. This can lead to issues.`);
    }
    return resolvedExtensions;
  }
  /**
   * Create a flattened array of extensions by traversing the `addExtensions` field.
   * @param extensions An array of Tiptap extensions
   * @returns A flattened array of Tiptap extensions
   */
  static flatten(extensions) {
    return extensions.map((extension) => {
      const context = {
        name: extension.name,
        options: extension.options,
        storage: extension.storage
      };
      const addExtensions = getExtensionField(extension, "addExtensions", context);
      if (addExtensions) {
        return [extension, ...this.flatten(addExtensions())];
      }
      return extension;
    }).flat(10);
  }
  /**
   * Sort extensions by priority.
   * @param extensions An array of Tiptap extensions
   * @returns A sorted array of Tiptap extensions by priority
   */
  static sort(extensions) {
    const defaultPriority = 100;
    return extensions.sort((a2, b2) => {
      const priorityA = getExtensionField(a2, "priority") || defaultPriority;
      const priorityB = getExtensionField(b2, "priority") || defaultPriority;
      if (priorityA > priorityB) {
        return -1;
      }
      if (priorityA < priorityB) {
        return 1;
      }
      return 0;
    });
  }
  /**
   * Get all commands from the extensions.
   * @returns An object with all commands where the key is the command name and the value is the command function
   */
  get commands() {
    return this.extensions.reduce((commands2, extension) => {
      const context = {
        name: extension.name,
        options: extension.options,
        storage: extension.storage,
        editor: this.editor,
        type: getSchemaTypeByName(extension.name, this.schema)
      };
      const addCommands = getExtensionField(extension, "addCommands", context);
      if (!addCommands) {
        return commands2;
      }
      return {
        ...commands2,
        ...addCommands()
      };
    }, {});
  }
  /**
   * Get all registered Prosemirror plugins from the extensions.
   * @returns An array of Prosemirror plugins
   */
  get plugins() {
    const { editor } = this;
    const extensions = ExtensionManager.sort([...this.extensions].reverse());
    const inputRules = [];
    const pasteRules = [];
    const allPlugins = extensions.map((extension) => {
      const context = {
        name: extension.name,
        options: extension.options,
        storage: extension.storage,
        editor,
        type: getSchemaTypeByName(extension.name, this.schema)
      };
      const plugins = [];
      const addKeyboardShortcuts = getExtensionField(extension, "addKeyboardShortcuts", context);
      let defaultBindings = {};
      if (extension.type === "mark" && getExtensionField(extension, "exitable", context)) {
        defaultBindings.ArrowRight = () => Mark.handleExit({ editor, mark: extension });
      }
      if (addKeyboardShortcuts) {
        const bindings = Object.fromEntries(Object.entries(addKeyboardShortcuts()).map(([shortcut, method]) => {
          return [shortcut, () => method({ editor })];
        }));
        defaultBindings = { ...defaultBindings, ...bindings };
      }
      const keyMapPlugin = keymap(defaultBindings);
      plugins.push(keyMapPlugin);
      const addInputRules = getExtensionField(extension, "addInputRules", context);
      if (isExtensionRulesEnabled(extension, editor.options.enableInputRules) && addInputRules) {
        inputRules.push(...addInputRules());
      }
      const addPasteRules = getExtensionField(extension, "addPasteRules", context);
      if (isExtensionRulesEnabled(extension, editor.options.enablePasteRules) && addPasteRules) {
        pasteRules.push(...addPasteRules());
      }
      const addProseMirrorPlugins = getExtensionField(extension, "addProseMirrorPlugins", context);
      if (addProseMirrorPlugins) {
        const proseMirrorPlugins = addProseMirrorPlugins();
        plugins.push(...proseMirrorPlugins);
      }
      return plugins;
    }).flat();
    return [
      inputRulesPlugin({
        editor,
        rules: inputRules
      }),
      ...pasteRulesPlugin({
        editor,
        rules: pasteRules
      }),
      ...allPlugins
    ];
  }
  /**
   * Get all attributes from the extensions.
   * @returns An array of attributes
   */
  get attributes() {
    return getAttributesFromExtensions(this.extensions);
  }
  /**
   * Get all node views from the extensions.
   * @returns An object with all node views where the key is the node name and the value is the node view function
   */
  get nodeViews() {
    const { editor } = this;
    const { nodeExtensions } = splitExtensions(this.extensions);
    return Object.fromEntries(nodeExtensions.filter((extension) => !!getExtensionField(extension, "addNodeView")).map((extension) => {
      const extensionAttributes = this.attributes.filter((attribute2) => attribute2.type === extension.name);
      const context = {
        name: extension.name,
        options: extension.options,
        storage: extension.storage,
        editor,
        type: getNodeType(extension.name, this.schema)
      };
      const addNodeView = getExtensionField(extension, "addNodeView", context);
      if (!addNodeView) {
        return [];
      }
      const nodeview = /* @__PURE__ */ __name((node2, view, getPos, decorations, innerDecorations) => {
        const HTMLAttributes = getRenderedAttributes(node2, extensionAttributes);
        return addNodeView()({
          // pass-through
          node: node2,
          view,
          getPos,
          decorations,
          innerDecorations,
          // tiptap-specific
          editor,
          extension,
          HTMLAttributes
        });
      }, "nodeview");
      return [extension.name, nodeview];
    }));
  }
  /**
   * Go through all extensions, create extension storages & setup marks
   * & bind editor event listener.
   */
  setupExtensions() {
    this.extensions.forEach((extension) => {
      var _a2;
      this.editor.extensionStorage[extension.name] = extension.storage;
      const context = {
        name: extension.name,
        options: extension.options,
        storage: extension.storage,
        editor: this.editor,
        type: getSchemaTypeByName(extension.name, this.schema)
      };
      if (extension.type === "mark") {
        const keepOnSplit = (_a2 = callOrReturn(getExtensionField(extension, "keepOnSplit", context))) !== null && _a2 !== void 0 ? _a2 : true;
        if (keepOnSplit) {
          this.splittableMarks.push(extension.name);
        }
      }
      const onBeforeCreate = getExtensionField(extension, "onBeforeCreate", context);
      const onCreate = getExtensionField(extension, "onCreate", context);
      const onUpdate = getExtensionField(extension, "onUpdate", context);
      const onSelectionUpdate = getExtensionField(extension, "onSelectionUpdate", context);
      const onTransaction = getExtensionField(extension, "onTransaction", context);
      const onFocus = getExtensionField(extension, "onFocus", context);
      const onBlur = getExtensionField(extension, "onBlur", context);
      const onDestroy = getExtensionField(extension, "onDestroy", context);
      if (onBeforeCreate) {
        this.editor.on("beforeCreate", onBeforeCreate);
      }
      if (onCreate) {
        this.editor.on("create", onCreate);
      }
      if (onUpdate) {
        this.editor.on("update", onUpdate);
      }
      if (onSelectionUpdate) {
        this.editor.on("selectionUpdate", onSelectionUpdate);
      }
      if (onTransaction) {
        this.editor.on("transaction", onTransaction);
      }
      if (onFocus) {
        this.editor.on("focus", onFocus);
      }
      if (onBlur) {
        this.editor.on("blur", onBlur);
      }
      if (onDestroy) {
        this.editor.on("destroy", onDestroy);
      }
    });
  }
}
class Extension {
  static {
    __name(this, "Extension");
  }
  constructor(config2 = {}) {
    this.type = "extension";
    this.name = "extension";
    this.parent = null;
    this.child = null;
    this.config = {
      name: this.name,
      defaultOptions: {}
    };
    this.config = {
      ...this.config,
      ...config2
    };
    this.name = this.config.name;
    if (config2.defaultOptions && Object.keys(config2.defaultOptions).length > 0) {
      console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${this.name}".`);
    }
    this.options = this.config.defaultOptions;
    if (this.config.addOptions) {
      this.options = callOrReturn(getExtensionField(this, "addOptions", {
        name: this.name
      }));
    }
    this.storage = callOrReturn(getExtensionField(this, "addStorage", {
      name: this.name,
      options: this.options
    })) || {};
  }
  static create(config2 = {}) {
    return new Extension(config2);
  }
  configure(options2 = {}) {
    const extension = this.extend({
      ...this.config,
      addOptions: /* @__PURE__ */ __name(() => {
        return mergeDeep(this.options, options2);
      }, "addOptions")
    });
    extension.name = this.name;
    extension.parent = this.parent;
    return extension;
  }
  extend(extendedConfig = {}) {
    const extension = new Extension({ ...this.config, ...extendedConfig });
    extension.parent = this;
    this.child = extension;
    extension.name = extendedConfig.name ? extendedConfig.name : extension.parent.name;
    if (extendedConfig.defaultOptions && Object.keys(extendedConfig.defaultOptions).length > 0) {
      console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${extension.name}".`);
    }
    extension.options = callOrReturn(getExtensionField(extension, "addOptions", {
      name: extension.name
    }));
    extension.storage = callOrReturn(getExtensionField(extension, "addStorage", {
      name: extension.name,
      options: extension.options
    }));
    return extension;
  }
}
function getTextBetween(startNode, range, options2) {
  const { from: from2, to } = range;
  const { blockSeparator = "\n\n", textSerializers = {} } = options2 || {};
  let text2 = "";
  startNode.nodesBetween(from2, to, (node2, pos, parent2, index2) => {
    var _a2;
    if (node2.isBlock && pos > from2) {
      text2 += blockSeparator;
    }
    const textSerializer = textSerializers === null || textSerializers === void 0 ? void 0 : textSerializers[node2.type.name];
    if (textSerializer) {
      if (parent2) {
        text2 += textSerializer({
          node: node2,
          pos,
          parent: parent2,
          index: index2,
          range
        });
      }
      return false;
    }
    if (node2.isText) {
      text2 += (_a2 = node2 === null || node2 === void 0 ? void 0 : node2.text) === null || _a2 === void 0 ? void 0 : _a2.slice(Math.max(from2, pos) - pos, to - pos);
    }
  });
  return text2;
}
__name(getTextBetween, "getTextBetween");
function getTextSerializersFromSchema(schema2) {
  return Object.fromEntries(Object.entries(schema2.nodes).filter(([, node2]) => node2.spec.toText).map(([name2, node2]) => [name2, node2.spec.toText]));
}
__name(getTextSerializersFromSchema, "getTextSerializersFromSchema");
const ClipboardTextSerializer = Extension.create({
  name: "clipboardTextSerializer",
  addOptions() {
    return {
      blockSeparator: void 0
    };
  },
  addProseMirrorPlugins() {
    return [
      new Plugin({
        key: new PluginKey("clipboardTextSerializer"),
        props: {
          clipboardTextSerializer: /* @__PURE__ */ __name(() => {
            const { editor } = this;
            const { state, schema: schema2 } = editor;
            const { doc: doc2, selection } = state;
            const { ranges } = selection;
            const from2 = Math.min(...ranges.map((range2) => range2.$from.pos));
            const to = Math.max(...ranges.map((range2) => range2.$to.pos));
            const textSerializers = getTextSerializersFromSchema(schema2);
            const range = { from: from2, to };
            return getTextBetween(doc2, range, {
              ...this.options.blockSeparator !== void 0 ? { blockSeparator: this.options.blockSeparator } : {},
              textSerializers
            });
          }, "clipboardTextSerializer")
        }
      })
    ];
  }
});
const blur = /* @__PURE__ */ __name(() => ({ editor, view }) => {
  requestAnimationFrame(() => {
    var _a2;
    if (!editor.isDestroyed) {
      view.dom.blur();
      (_a2 = window === null || window === void 0 ? void 0 : window.getSelection()) === null || _a2 === void 0 ? void 0 : _a2.removeAllRanges();
    }
  });
  return true;
}, "blur");
const clearContent = /* @__PURE__ */ __name((emitUpdate = false) => ({ commands: commands2 }) => {
  return commands2.setContent("", emitUpdate);
}, "clearContent");
const clearNodes = /* @__PURE__ */ __name(() => ({ state, tr: tr2, dispatch }) => {
  const { selection } = tr2;
  const { ranges } = selection;
  if (!dispatch) {
    return true;
  }
  ranges.forEach(({ $from, $to }) => {
    state.doc.nodesBetween($from.pos, $to.pos, (node2, pos) => {
      if (node2.type.isText) {
        return;
      }
      const { doc: doc2, mapping } = tr2;
      const $mappedFrom = doc2.resolve(mapping.map(pos));
      const $mappedTo = doc2.resolve(mapping.map(pos + node2.nodeSize));
      const nodeRange = $mappedFrom.blockRange($mappedTo);
      if (!nodeRange) {
        return;
      }
      const targetLiftDepth = liftTarget(nodeRange);
      if (node2.type.isTextblock) {
        const { defaultType } = $mappedFrom.parent.contentMatchAt($mappedFrom.index());
        tr2.setNodeMarkup(nodeRange.start, defaultType);
      }
      if (targetLiftDepth || targetLiftDepth === 0) {
        tr2.lift(nodeRange, targetLiftDepth);
      }
    });
  });
  return true;
}, "clearNodes");
const command = /* @__PURE__ */ __name((fn) => (props) => {
  return fn(props);
}, "command");
const createParagraphNear = /* @__PURE__ */ __name(() => ({ state, dispatch }) => {
  return createParagraphNear$1(state, dispatch);
}, "createParagraphNear");
const cut = /* @__PURE__ */ __name((originRange, targetPos) => ({ editor, tr: tr2 }) => {
  const { state } = editor;
  const contentSlice = state.doc.slice(originRange.from, originRange.to);
  tr2.deleteRange(originRange.from, originRange.to);
  const newPos = tr2.mapping.map(targetPos);
  tr2.insert(newPos, contentSlice.content);
  tr2.setSelection(new TextSelection(tr2.doc.resolve(newPos - 1)));
  return true;
}, "cut");
const deleteCurrentNode = /* @__PURE__ */ __name(() => ({ tr: tr2, dispatch }) => {
  const { selection } = tr2;
  const currentNode = selection.$anchor.node();
  if (currentNode.content.size > 0) {
    return false;
  }
  const $pos = tr2.selection.$anchor;
  for (let depth = $pos.depth; depth > 0; depth -= 1) {
    const node2 = $pos.node(depth);
    if (node2.type === currentNode.type) {
      if (dispatch) {
        const from2 = $pos.before(depth);
        const to = $pos.after(depth);
        tr2.delete(from2, to).scrollIntoView();
      }
      return true;
    }
  }
  return false;
}, "deleteCurrentNode");
const deleteNode = /* @__PURE__ */ __name((typeOrName) => ({ tr: tr2, state, dispatch }) => {
  const type = getNodeType(typeOrName, state.schema);
  const $pos = tr2.selection.$anchor;
  for (let depth = $pos.depth; depth > 0; depth -= 1) {
    const node2 = $pos.node(depth);
    if (node2.type === type) {
      if (dispatch) {
        const from2 = $pos.before(depth);
        const to = $pos.after(depth);
        tr2.delete(from2, to).scrollIntoView();
      }
      return true;
    }
  }
  return false;
}, "deleteNode");
const deleteRange = /* @__PURE__ */ __name((range) => ({ tr: tr2, dispatch }) => {
  const { from: from2, to } = range;
  if (dispatch) {
    tr2.delete(from2, to);
  }
  return true;
}, "deleteRange");
const deleteSelection = /* @__PURE__ */ __name(() => ({ state, dispatch }) => {
  return deleteSelection$1(state, dispatch);
}, "deleteSelection");
const enter = /* @__PURE__ */ __name(() => ({ commands: commands2 }) => {
  return commands2.keyboardShortcut("Enter");
}, "enter");
const exitCode = /* @__PURE__ */ __name(() => ({ state, dispatch }) => {
  return exitCode$1(state, dispatch);
}, "exitCode");
function objectIncludes(object1, object2, options2 = { strict: true }) {
  const keys2 = Object.keys(object2);
  if (!keys2.length) {
    return true;
  }
  return keys2.every((key) => {
    if (options2.strict) {
      return object2[key] === object1[key];
    }
    if (isRegExp$1(object2[key])) {
      return object2[key].test(object1[key]);
    }
    return object2[key] === object1[key];
  });
}
__name(objectIncludes, "objectIncludes");
function findMarkInSet(marks, type, attributes = {}) {
  return marks.find((item) => {
    return item.type === type && objectIncludes(
      // Only check equality for the attributes that are provided
      Object.fromEntries(Object.keys(attributes).map((k2) => [k2, item.attrs[k2]])),
      attributes
    );
  });
}
__name(findMarkInSet, "findMarkInSet");
function isMarkInSet(marks, type, attributes = {}) {
  return !!findMarkInSet(marks, type, attributes);
}
__name(isMarkInSet, "isMarkInSet");
function getMarkRange($pos, type, attributes) {
  var _a2;
  if (!$pos || !type) {
    return;
  }
  let start2 = $pos.parent.childAfter($pos.parentOffset);
  if (!start2.node || !start2.node.marks.some((mark2) => mark2.type === type)) {
    start2 = $pos.parent.childBefore($pos.parentOffset);
  }
  if (!start2.node || !start2.node.marks.some((mark2) => mark2.type === type)) {
    return;
  }
  attributes = attributes || ((_a2 = start2.node.marks[0]) === null || _a2 === void 0 ? void 0 : _a2.attrs);
  const mark = findMarkInSet([...start2.node.marks], type, attributes);
  if (!mark) {
    return;
  }
  let startIndex = start2.index;
  let startPos = $pos.start() + start2.offset;
  let endIndex = startIndex + 1;
  let endPos = startPos + start2.node.nodeSize;
  while (startIndex > 0 && isMarkInSet([...$pos.parent.child(startIndex - 1).marks], type, attributes)) {
    startIndex -= 1;
    startPos -= $pos.parent.child(startIndex).nodeSize;
  }
  while (endIndex < $pos.parent.childCount && isMarkInSet([...$pos.parent.child(endIndex).marks], type, attributes)) {
    endPos += $pos.parent.child(endIndex).nodeSize;
    endIndex += 1;
  }
  return {
    from: startPos,
    to: endPos
  };
}
__name(getMarkRange, "getMarkRange");
function getMarkType(nameOrType, schema2) {
  if (typeof nameOrType === "string") {
    if (!schema2.marks[nameOrType]) {
      throw Error(`There is no mark type named '${nameOrType}'. Maybe you forgot to add the extension?`);
    }
    return schema2.marks[nameOrType];
  }
  return nameOrType;
}
__name(getMarkType, "getMarkType");
const extendMarkRange = /* @__PURE__ */ __name((typeOrName, attributes = {}) => ({ tr: tr2, state, dispatch }) => {
  const type = getMarkType(typeOrName, state.schema);
  const { doc: doc2, selection } = tr2;
  const { $from, from: from2, to } = selection;
  if (dispatch) {
    const range = getMarkRange($from, type, attributes);
    if (range && range.from <= from2 && range.to >= to) {
      const newSelection = TextSelection.create(doc2, range.from, range.to);
      tr2.setSelection(newSelection);
    }
  }
  return true;
}, "extendMarkRange");
const first = /* @__PURE__ */ __name((commands2) => (props) => {
  const items = typeof commands2 === "function" ? commands2(props) : commands2;
  for (let i2 = 0; i2 < items.length; i2 += 1) {
    if (items[i2](props)) {
      return true;
    }
  }
  return false;
}, "first");
function isTextSelection(value) {
  return value instanceof TextSelection;
}
__name(isTextSelection, "isTextSelection");
function minMax(value = 0, min = 0, max = 0) {
  return Math.min(Math.max(value, min), max);
}
__name(minMax, "minMax");
function resolveFocusPosition(doc2, position = null) {
  if (!position) {
    return null;
  }
  const selectionAtStart = Selection.atStart(doc2);
  const selectionAtEnd = Selection.atEnd(doc2);
  if (position === "start" || position === true) {
    return selectionAtStart;
  }
  if (position === "end") {
    return selectionAtEnd;
  }
  const minPos = selectionAtStart.from;
  const maxPos = selectionAtEnd.to;
  if (position === "all") {
    return TextSelection.create(doc2, minMax(0, minPos, maxPos), minMax(doc2.content.size, minPos, maxPos));
  }
  return TextSelection.create(doc2, minMax(position, minPos, maxPos), minMax(position, minPos, maxPos));
}
__name(resolveFocusPosition, "resolveFocusPosition");
function isiOS() {
  return [
    "iPad Simulator",
    "iPhone Simulator",
    "iPod Simulator",
    "iPad",
    "iPhone",
    "iPod"
  ].includes(navigator.platform) || navigator.userAgent.includes("Mac") && "ontouchend" in document;
}
__name(isiOS, "isiOS");
const focus = /* @__PURE__ */ __name((position = null, options2 = {}) => ({ editor, view, tr: tr2, dispatch }) => {
  options2 = {
    scrollIntoView: true,
    ...options2
  };
  const delayedFocus = /* @__PURE__ */ __name(() => {
    if (isiOS()) {
      view.dom.focus();
    }
    requestAnimationFrame(() => {
      if (!editor.isDestroyed) {
        view.focus();
        if (options2 === null || options2 === void 0 ? void 0 : options2.scrollIntoView) {
          editor.commands.scrollIntoView();
        }
      }
    });
  }, "delayedFocus");
  if (view.hasFocus() && position === null || position === false) {
    return true;
  }
  if (dispatch && position === null && !isTextSelection(editor.state.selection)) {
    delayedFocus();
    return true;
  }
  const selection = resolveFocusPosition(tr2.doc, position) || editor.state.selection;
  const isSameSelection = editor.state.selection.eq(selection);
  if (dispatch) {
    if (!isSameSelection) {
      tr2.setSelection(selection);
    }
    if (isSameSelection && tr2.storedMarks) {
      tr2.setStoredMarks(tr2.storedMarks);
    }
    delayedFocus();
  }
  return true;
}, "focus");
const forEach = /* @__PURE__ */ __name((items, fn) => (props) => {
  return items.every((item, index2) => fn(item, { ...props, index: index2 }));
}, "forEach");
const insertContent = /* @__PURE__ */ __name((value, options2) => ({ tr: tr2, commands: commands2 }) => {
  return commands2.insertContentAt({ from: tr2.selection.from, to: tr2.selection.to }, value, options2);
}, "insertContent");
const removeWhitespaces = /* @__PURE__ */ __name((node2) => {
  const children = node2.childNodes;
  for (let i2 = children.length - 1; i2 >= 0; i2 -= 1) {
    const child2 = children[i2];
    if (child2.nodeType === 3 && child2.nodeValue && /^(\n\s\s|\n)$/.test(child2.nodeValue)) {
      node2.removeChild(child2);
    } else if (child2.nodeType === 1) {
      removeWhitespaces(child2);
    }
  }
  return node2;
}, "removeWhitespaces");
function elementFromString$1(value) {
  const wrappedValue = `<body>${value}</body>`;
  const html = new window.DOMParser().parseFromString(wrappedValue, "text/html").body;
  return removeWhitespaces(html);
}
__name(elementFromString$1, "elementFromString$1");
function createNodeFromContent(content, schema2, options2) {
  if (content instanceof Node$2 || content instanceof Fragment) {
    return content;
  }
  options2 = {
    slice: true,
    parseOptions: {},
    ...options2
  };
  const isJSONContent = typeof content === "object" && content !== null;
  const isTextContent = typeof content === "string";
  if (isJSONContent) {
    try {
      const isArrayContent = Array.isArray(content) && content.length > 0;
      if (isArrayContent) {
        return Fragment.fromArray(content.map((item) => schema2.nodeFromJSON(item)));
      }
      const node2 = schema2.nodeFromJSON(content);
      if (options2.errorOnInvalidContent) {
        node2.check();
      }
      return node2;
    } catch (error2) {
      if (options2.errorOnInvalidContent) {
        throw new Error("[tiptap error]: Invalid JSON content", { cause: error2 });
      }
      console.warn("[tiptap warn]: Invalid content.", "Passed value:", content, "Error:", error2);
      return createNodeFromContent("", schema2, options2);
    }
  }
  if (isTextContent) {
    if (options2.errorOnInvalidContent) {
      let hasInvalidContent = false;
      let invalidContent = "";
      const contentCheckSchema = new Schema({
        topNode: schema2.spec.topNode,
        marks: schema2.spec.marks,
        // Prosemirror's schemas are executed such that: the last to execute, matches last
        // This means that we can add a catch-all node at the end of the schema to catch any content that we don't know how to handle
        nodes: schema2.spec.nodes.append({
          __tiptap__private__unknown__catch__all__node: {
            content: "inline*",
            group: "block",
            parseDOM: [
              {
                tag: "*",
                getAttrs: /* @__PURE__ */ __name((e2) => {
                  hasInvalidContent = true;
                  invalidContent = typeof e2 === "string" ? e2 : e2.outerHTML;
                  return null;
                }, "getAttrs")
              }
            ]
          }
        })
      });
      if (options2.slice) {
        DOMParser.fromSchema(contentCheckSchema).parseSlice(elementFromString$1(content), options2.parseOptions);
      } else {
        DOMParser.fromSchema(contentCheckSchema).parse(elementFromString$1(content), options2.parseOptions);
      }
      if (options2.errorOnInvalidContent && hasInvalidContent) {
        throw new Error("[tiptap error]: Invalid HTML content", { cause: new Error(`Invalid element found: ${invalidContent}`) });
      }
    }
    const parser = DOMParser.fromSchema(schema2);
    if (options2.slice) {
      return parser.parseSlice(elementFromString$1(content), options2.parseOptions).content;
    }
    return parser.parse(elementFromString$1(content), options2.parseOptions);
  }
  return createNodeFromContent("", schema2, options2);
}
__name(createNodeFromContent, "createNodeFromContent");
function selectionToInsertionEnd(tr2, startLen, bias) {
  const last = tr2.steps.length - 1;
  if (last < startLen) {
    return;
  }
  const step = tr2.steps[last];
  if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep)) {
    return;
  }
  const map3 = tr2.mapping.maps[last];
  let end = 0;
  map3.forEach((_from, _to, _newFrom, newTo) => {
    if (end === 0) {
      end = newTo;
    }
  });
  tr2.setSelection(Selection.near(tr2.doc.resolve(end), bias));
}
__name(selectionToInsertionEnd, "selectionToInsertionEnd");
const isFragment = /* @__PURE__ */ __name((nodeOrFragment) => {
  return !("type" in nodeOrFragment);
}, "isFragment");
const insertContentAt = /* @__PURE__ */ __name((position, value, options2) => ({ tr: tr2, dispatch, editor }) => {
  var _a2;
  if (dispatch) {
    options2 = {
      parseOptions: editor.options.parseOptions,
      updateSelection: true,
      applyInputRules: false,
      applyPasteRules: false,
      ...options2
    };
    let content;
    try {
      content = createNodeFromContent(value, editor.schema, {
        parseOptions: {
          preserveWhitespace: "full",
          ...options2.parseOptions
        },
        errorOnInvalidContent: (_a2 = options2.errorOnInvalidContent) !== null && _a2 !== void 0 ? _a2 : editor.options.enableContentCheck
      });
    } catch (e2) {
      editor.emit("contentError", {
        editor,
        error: e2,
        disableCollaboration: /* @__PURE__ */ __name(() => {
          if (editor.storage.collaboration) {
            editor.storage.collaboration.isDisabled = true;
          }
        }, "disableCollaboration")
      });
      return false;
    }
    let { from: from2, to } = typeof position === "number" ? { from: position, to: position } : { from: position.from, to: position.to };
    let isOnlyTextContent = true;
    let isOnlyBlockContent = true;
    const nodes = isFragment(content) ? content : [content];
    nodes.forEach((node2) => {
      node2.check();
      isOnlyTextContent = isOnlyTextContent ? node2.isText && node2.marks.length === 0 : false;
      isOnlyBlockContent = isOnlyBlockContent ? node2.isBlock : false;
    });
    if (from2 === to && isOnlyBlockContent) {
      const { parent: parent2 } = tr2.doc.resolve(from2);
      const isEmptyTextBlock = parent2.isTextblock && !parent2.type.spec.code && !parent2.childCount;
      if (isEmptyTextBlock) {
        from2 -= 1;
        to += 1;
      }
    }
    let newContent;
    if (isOnlyTextContent) {
      if (Array.isArray(value)) {
        newContent = value.map((v2) => v2.text || "").join("");
      } else if (value instanceof Fragment) {
        let text2 = "";
        value.forEach((node2) => {
          if (node2.text) {
            text2 += node2.text;
          }
        });
        newContent = text2;
      } else if (typeof value === "object" && !!value && !!value.text) {
        newContent = value.text;
      } else {
        newContent = value;
      }
      tr2.insertText(newContent, from2, to);
    } else {
      newContent = content;
      tr2.replaceWith(from2, to, newContent);
    }
    if (options2.updateSelection) {
      selectionToInsertionEnd(tr2, tr2.steps.length - 1, -1);
    }
    if (options2.applyInputRules) {
      tr2.setMeta("applyInputRules", { from: from2, text: newContent });
    }
    if (options2.applyPasteRules) {
      tr2.setMeta("applyPasteRules", { from: from2, text: newContent });
    }
  }
  return true;
}, "insertContentAt");
const joinUp = /* @__PURE__ */ __name(() => ({ state, dispatch }) => {
  return joinUp$1(state, dispatch);
}, "joinUp");
const joinDown = /* @__PURE__ */ __name(() => ({ state, dispatch }) => {
  return joinDown$1(state, dispatch);
}, "joinDown");
const joinBackward = /* @__PURE__ */ __name(() => ({ state, dispatch }) => {
  return joinBackward$1(state, dispatch);
}, "joinBackward");
const joinForward = /* @__PURE__ */ __name(() => ({ state, dispatch }) => {
  return joinForward$1(state, dispatch);
}, "joinForward");
const joinItemBackward = /* @__PURE__ */ __name(() => ({ state, dispatch, tr: tr2 }) => {
  try {
    const point = joinPoint(state.doc, state.selection.$from.pos, -1);
    if (point === null || point === void 0) {
      return false;
    }
    tr2.join(point, 2);
    if (dispatch) {
      dispatch(tr2);
    }
    return true;
  } catch (e2) {
    return false;
  }
}, "joinItemBackward");
const joinItemForward = /* @__PURE__ */ __name(() => ({ state, dispatch, tr: tr2 }) => {
  try {
    const point = joinPoint(state.doc, state.selection.$from.pos, 1);
    if (point === null || point === void 0) {
      return false;
    }
    tr2.join(point, 2);
    if (dispatch) {
      dispatch(tr2);
    }
    return true;
  } catch (e2) {
    return false;
  }
}, "joinItemForward");
const joinTextblockBackward = /* @__PURE__ */ __name(() => ({ state, dispatch }) => {
  return joinTextblockBackward$1(state, dispatch);
}, "joinTextblockBackward");
const joinTextblockForward = /* @__PURE__ */ __name(() => ({ state, dispatch }) => {
  return joinTextblockForward$1(state, dispatch);
}, "joinTextblockForward");
function isMacOS() {
  return typeof navigator !== "undefined" ? /Mac/.test(navigator.platform) : false;
}
__name(isMacOS, "isMacOS");
function normalizeKeyName(name2) {
  const parts2 = name2.split(/-(?!$)/);
  let result = parts2[parts2.length - 1];
  if (result === "Space") {
    result = " ";
  }
  let alt;
  let ctrl;
  let shift2;
  let meta;
  for (let i2 = 0; i2 < parts2.length - 1; i2 += 1) {
    const mod = parts2[i2];
    if (/^(cmd|meta|m)$/i.test(mod)) {
      meta = true;
    } else if (/^a(lt)?$/i.test(mod)) {
      alt = true;
    } else if (/^(c|ctrl|control)$/i.test(mod)) {
      ctrl = true;
    } else if (/^s(hift)?$/i.test(mod)) {
      shift2 = true;
    } else if (/^mod$/i.test(mod)) {
      if (isiOS() || isMacOS()) {
        meta = true;
      } else {
        ctrl = true;
      }
    } else {
      throw new Error(`Unrecognized modifier name: ${mod}`);
    }
  }
  if (alt) {
    result = `Alt-${result}`;
  }
  if (ctrl) {
    result = `Ctrl-${result}`;
  }
  if (meta) {
    result = `Meta-${result}`;
  }
  if (shift2) {
    result = `Shift-${result}`;
  }
  return result;
}
__name(normalizeKeyName, "normalizeKeyName");
const keyboardShortcut = /* @__PURE__ */ __name((name2) => ({ editor, view, tr: tr2, dispatch }) => {
  const keys2 = normalizeKeyName(name2).split(/-(?!$)/);
  const key = keys2.find((item) => !["Alt", "Ctrl", "Meta", "Shift"].includes(item));
  const event = new KeyboardEvent("keydown", {
    key: key === "Space" ? " " : key,
    altKey: keys2.includes("Alt"),
    ctrlKey: keys2.includes("Ctrl"),
    metaKey: keys2.includes("Meta"),
    shiftKey: keys2.includes("Shift"),
    bubbles: true,
    cancelable: true
  });
  const capturedTransaction = editor.captureTransaction(() => {
    view.someProp("handleKeyDown", (f2) => f2(view, event));
  });
  capturedTransaction === null || capturedTransaction === void 0 ? void 0 : capturedTransaction.steps.forEach((step) => {
    const newStep = step.map(tr2.mapping);
    if (newStep && dispatch) {
      tr2.maybeStep(newStep);
    }
  });
  return true;
}, "keyboardShortcut");
function isNodeActive(state, typeOrName, attributes = {}) {
  const { from: from2, to, empty: empty2 } = state.selection;
  const type = typeOrName ? getNodeType(typeOrName, state.schema) : null;
  const nodeRanges = [];
  state.doc.nodesBetween(from2, to, (node2, pos) => {
    if (node2.isText) {
      return;
    }
    const relativeFrom = Math.max(from2, pos);
    const relativeTo = Math.min(to, pos + node2.nodeSize);
    nodeRanges.push({
      node: node2,
      from: relativeFrom,
      to: relativeTo
    });
  });
  const selectionRange = to - from2;
  const matchedNodeRanges = nodeRanges.filter((nodeRange) => {
    if (!type) {
      return true;
    }
    return type.name === nodeRange.node.type.name;
  }).filter((nodeRange) => objectIncludes(nodeRange.node.attrs, attributes, { strict: false }));
  if (empty2) {
    return !!matchedNodeRanges.length;
  }
  const range = matchedNodeRanges.reduce((sum2, nodeRange) => sum2 + nodeRange.to - nodeRange.from, 0);
  return range >= selectionRange;
}
__name(isNodeActive, "isNodeActive");
const lift = /* @__PURE__ */ __name((typeOrName, attributes = {}) => ({ state, dispatch }) => {
  const type = getNodeType(typeOrName, state.schema);
  const isActive2 = isNodeActive(state, type, attributes);
  if (!isActive2) {
    return false;
  }
  return lift$1(state, dispatch);
}, "lift");
const liftEmptyBlock = /* @__PURE__ */ __name(() => ({ state, dispatch }) => {
  return liftEmptyBlock$1(state, dispatch);
}, "liftEmptyBlock");
const liftListItem = /* @__PURE__ */ __name((typeOrName) => ({ state, dispatch }) => {
  const type = getNodeType(typeOrName, state.schema);
  return liftListItem$1(type)(state, dispatch);
}, "liftListItem");
const newlineInCode = /* @__PURE__ */ __name(() => ({ state, dispatch }) => {
  return newlineInCode$1(state, dispatch);
}, "newlineInCode");
function getSchemaTypeNameByName(name2, schema2) {
  if (schema2.nodes[name2]) {
    return "node";
  }
  if (schema2.marks[name2]) {
    return "mark";
  }
  return null;
}
__name(getSchemaTypeNameByName, "getSchemaTypeNameByName");
function deleteProps(obj, propOrProps) {
  const props = typeof propOrProps === "string" ? [propOrProps] : propOrProps;
  return Object.keys(obj).reduce((newObj, prop2) => {
    if (!props.includes(prop2)) {
      newObj[prop2] = obj[prop2];
    }
    return newObj;
  }, {});
}
__name(deleteProps, "deleteProps");
const resetAttributes = /* @__PURE__ */ __name((typeOrName, attributes) => ({ tr: tr2, state, dispatch }) => {
  let nodeType = null;
  let markType = null;
  const schemaType = getSchemaTypeNameByName(typeof typeOrName === "string" ? typeOrName : typeOrName.name, state.schema);
  if (!schemaType) {
    return false;
  }
  if (schemaType === "node") {
    nodeType = getNodeType(typeOrName, state.schema);
  }
  if (schemaType === "mark") {
    markType = getMarkType(typeOrName, state.schema);
  }
  if (dispatch) {
    tr2.selection.ranges.forEach((range) => {
      state.doc.nodesBetween(range.$from.pos, range.$to.pos, (node2, pos) => {
        if (nodeType && nodeType === node2.type) {
          tr2.setNodeMarkup(pos, void 0, deleteProps(node2.attrs, attributes));
        }
        if (markType && node2.marks.length) {
          node2.marks.forEach((mark) => {
            if (markType === mark.type) {
              tr2.addMark(pos, pos + node2.nodeSize, markType.create(deleteProps(mark.attrs, attributes)));
            }
          });
        }
      });
    });
  }
  return true;
}, "resetAttributes");
const scrollIntoView = /* @__PURE__ */ __name(() => ({ tr: tr2, dispatch }) => {
  if (dispatch) {
    tr2.scrollIntoView();
  }
  return true;
}, "scrollIntoView");
const selectAll = /* @__PURE__ */ __name(() => ({ tr: tr2, commands: commands2 }) => {
  return commands2.setTextSelection({
    from: 0,
    to: tr2.doc.content.size
  });
}, "selectAll");
const selectNodeBackward = /* @__PURE__ */ __name(() => ({ state, dispatch }) => {
  return selectNodeBackward$1(state, dispatch);
}, "selectNodeBackward");
const selectNodeForward = /* @__PURE__ */ __name(() => ({ state, dispatch }) => {
  return selectNodeForward$1(state, dispatch);
}, "selectNodeForward");
const selectParentNode = /* @__PURE__ */ __name(() => ({ state, dispatch }) => {
  return selectParentNode$1(state, dispatch);
}, "selectParentNode");
const selectTextblockEnd = /* @__PURE__ */ __name(() => ({ state, dispatch }) => {
  return selectTextblockEnd$1(state, dispatch);
}, "selectTextblockEnd");
const selectTextblockStart = /* @__PURE__ */ __name(() => ({ state, dispatch }) => {
  return selectTextblockStart$1(state, dispatch);
}, "selectTextblockStart");
function createDocument(content, schema2, parseOptions = {}, options2 = {}) {
  return createNodeFromContent(content, schema2, {
    slice: false,
    parseOptions,
    errorOnInvalidContent: options2.errorOnInvalidContent
  });
}
__name(createDocument, "createDocument");
const setContent = /* @__PURE__ */ __name((content, emitUpdate = false, parseOptions = {}, options2 = {}) => ({ editor, tr: tr2, dispatch, commands: commands2 }) => {
  var _a2, _b;
  const { doc: doc2 } = tr2;
  if (parseOptions.preserveWhitespace !== "full") {
    const document2 = createDocument(content, editor.schema, parseOptions, {
      errorOnInvalidContent: (_a2 = options2.errorOnInvalidContent) !== null && _a2 !== void 0 ? _a2 : editor.options.enableContentCheck
    });
    if (dispatch) {
      tr2.replaceWith(0, doc2.content.size, document2).setMeta("preventUpdate", !emitUpdate);
    }
    return true;
  }
  if (dispatch) {
    tr2.setMeta("preventUpdate", !emitUpdate);
  }
  return commands2.insertContentAt({ from: 0, to: doc2.content.size }, content, {
    parseOptions,
    errorOnInvalidContent: (_b = options2.errorOnInvalidContent) !== null && _b !== void 0 ? _b : editor.options.enableContentCheck
  });
}, "setContent");
function getMarkAttributes(state, typeOrName) {
  const type = getMarkType(typeOrName, state.schema);
  const { from: from2, to, empty: empty2 } = state.selection;
  const marks = [];
  if (empty2) {
    if (state.storedMarks) {
      marks.push(...state.storedMarks);
    }
    marks.push(...state.selection.$head.marks());
  } else {
    state.doc.nodesBetween(from2, to, (node2) => {
      marks.push(...node2.marks);
    });
  }
  const mark = marks.find((markItem) => markItem.type.name === type.name);
  if (!mark) {
    return {};
  }
  return { ...mark.attrs };
}
__name(getMarkAttributes, "getMarkAttributes");
function combineTransactionSteps(oldDoc, transactions) {
  const transform = new Transform(oldDoc);
  transactions.forEach((transaction) => {
    transaction.steps.forEach((step) => {
      transform.step(step);
    });
  });
  return transform;
}
__name(combineTransactionSteps, "combineTransactionSteps");
function defaultBlockAt(match2) {
  for (let i2 = 0; i2 < match2.edgeCount; i2 += 1) {
    const { type } = match2.edge(i2);
    if (type.isTextblock && !type.hasRequiredAttrs()) {
      return type;
    }
  }
  return null;
}
__name(defaultBlockAt, "defaultBlockAt");
function findChildren(node2, predicate) {
  const nodesWithPos = [];
  node2.descendants((child2, pos) => {
    if (predicate(child2)) {
      nodesWithPos.push({
        node: child2,
        pos
      });
    }
  });
  return nodesWithPos;
}
__name(findChildren, "findChildren");
function findChildrenInRange(node2, range, predicate) {
  const nodesWithPos = [];
  node2.nodesBetween(range.from, range.to, (child2, pos) => {
    if (predicate(child2)) {
      nodesWithPos.push({
        node: child2,
        pos
      });
    }
  });
  return nodesWithPos;
}
__name(findChildrenInRange, "findChildrenInRange");
function findParentNodeClosestToPos($pos, predicate) {
  for (let i2 = $pos.depth; i2 > 0; i2 -= 1) {
    const node2 = $pos.node(i2);
    if (predicate(node2)) {
      return {
        pos: i2 > 0 ? $pos.before(i2) : 0,
        start: $pos.start(i2),
        depth: i2,
        node: node2
      };
    }
  }
}
__name(findParentNodeClosestToPos, "findParentNodeClosestToPos");
function findParentNode(predicate) {
  return (selection) => findParentNodeClosestToPos(selection.$from, predicate);
}
__name(findParentNode, "findParentNode");
function getSchema(extensions, editor) {
  const resolvedExtensions = ExtensionManager.resolve(extensions);
  return getSchemaByResolvedExtensions(resolvedExtensions, editor);
}
__name(getSchema, "getSchema");
function generateHTML(doc2, extensions) {
  const schema2 = getSchema(extensions);
  const contentNode = Node$2.fromJSON(schema2, doc2);
  return getHTMLFromFragment(contentNode.content, schema2);
}
__name(generateHTML, "generateHTML");
function generateJSON(html, extensions) {
  const schema2 = getSchema(extensions);
  const dom = elementFromString$1(html);
  return DOMParser.fromSchema(schema2).parse(dom).toJSON();
}
__name(generateJSON, "generateJSON");
function getText(node2, options2) {
  const range = {
    from: 0,
    to: node2.content.size
  };
  return getTextBetween(node2, range, options2);
}
__name(getText, "getText");
function generateText(doc2, extensions, options2) {
  const { blockSeparator = "\n\n", textSerializers = {} } = options2 || {};
  const schema2 = getSchema(extensions);
  const contentNode = Node$2.fromJSON(schema2, doc2);
  return getText(contentNode, {
    blockSeparator,
    textSerializers: {
      ...getTextSerializersFromSchema(schema2),
      ...textSerializers
    }
  });
}
__name(generateText, "generateText");
function getNodeAttributes(state, typeOrName) {
  const type = getNodeType(typeOrName, state.schema);
  const { from: from2, to } = state.selection;
  const nodes = [];
  state.doc.nodesBetween(from2, to, (node3) => {
    nodes.push(node3);
  });
  const node2 = nodes.reverse().find((nodeItem) => nodeItem.type.name === type.name);
  if (!node2) {
    return {};
  }
  return { ...node2.attrs };
}
__name(getNodeAttributes, "getNodeAttributes");
function getAttributes(state, typeOrName) {
  const schemaType = getSchemaTypeNameByName(typeof typeOrName === "string" ? typeOrName : typeOrName.name, state.schema);
  if (schemaType === "node") {
    return getNodeAttributes(state, typeOrName);
  }
  if (schemaType === "mark") {
    return getMarkAttributes(state, typeOrName);
  }
  return {};
}
__name(getAttributes, "getAttributes");
function removeDuplicates(array, by = JSON.stringify) {
  const seen2 = {};
  return array.filter((item) => {
    const key = by(item);
    return Object.prototype.hasOwnProperty.call(seen2, key) ? false : seen2[key] = true;
  });
}
__name(removeDuplicates, "removeDuplicates");
function simplifyChangedRanges(changes) {
  const uniqueChanges = removeDuplicates(changes);
  return uniqueChanges.length === 1 ? uniqueChanges : uniqueChanges.filter((change, index2) => {
    const rest = uniqueChanges.filter((_2, i2) => i2 !== index2);
    return !rest.some((otherChange) => {
      return change.oldRange.from >= otherChange.oldRange.from && change.oldRange.to <= otherChange.oldRange.to && change.newRange.from >= otherChange.newRange.from && change.newRange.to <= otherChange.newRange.to;
    });
  });
}
__name(simplifyChangedRanges, "simplifyChangedRanges");
function getChangedRanges(transform) {
  const { mapping, steps } = transform;
  const changes = [];
  mapping.maps.forEach((stepMap, index2) => {
    const ranges = [];
    if (!stepMap.ranges.length) {
      const { from: from2, to } = steps[index2];
      if (from2 === void 0 || to === void 0) {
        return;
      }
      ranges.push({ from: from2, to });
    } else {
      stepMap.forEach((from2, to) => {
        ranges.push({ from: from2, to });
      });
    }
    ranges.forEach(({ from: from2, to }) => {
      const newStart = mapping.slice(index2).map(from2, -1);
      const newEnd = mapping.slice(index2).map(to);
      const oldStart = mapping.invert().map(newStart, -1);
      const oldEnd = mapping.invert().map(newEnd);
      changes.push({
        oldRange: {
          from: oldStart,
          to: oldEnd
        },
        newRange: {
          from: newStart,
          to: newEnd
        }
      });
    });
  });
  return simplifyChangedRanges(changes);
}
__name(getChangedRanges, "getChangedRanges");
function getDebugJSON(node2, startOffset = 0) {
  const isTopNode = node2.type === node2.type.schema.topNodeType;
  const increment2 = isTopNode ? 0 : 1;
  const from2 = startOffset;
  const to = from2 + node2.nodeSize;
  const marks = node2.marks.map((mark) => {
    const output2 = {
      type: mark.type.name
    };
    if (Object.keys(mark.attrs).length) {
      output2.attrs = { ...mark.attrs };
    }
    return output2;
  });
  const attrs2 = { ...node2.attrs };
  const output = {
    type: node2.type.name,
    from: from2,
    to
  };
  if (Object.keys(attrs2).length) {
    output.attrs = attrs2;
  }
  if (marks.length) {
    output.marks = marks;
  }
  if (node2.content.childCount) {
    output.content = [];
    node2.forEach((child2, offset) => {
      var _a2;
      (_a2 = output.content) === null || _a2 === void 0 ? void 0 : _a2.push(getDebugJSON(child2, startOffset + offset + increment2));
    });
  }
  if (node2.text) {
    output.text = node2.text;
  }
  return output;
}
__name(getDebugJSON, "getDebugJSON");
function getMarksBetween(from2, to, doc2) {
  const marks = [];
  if (from2 === to) {
    doc2.resolve(from2).marks().forEach((mark) => {
      const $pos = doc2.resolve(from2);
      const range = getMarkRange($pos, mark.type);
      if (!range) {
        return;
      }
      marks.push({
        mark,
        ...range
      });
    });
  } else {
    doc2.nodesBetween(from2, to, (node2, pos) => {
      if (!node2 || (node2 === null || node2 === void 0 ? void 0 : node2.nodeSize) === void 0) {
        return;
      }
      marks.push(...node2.marks.map((mark) => ({
        from: pos,
        to: pos + node2.nodeSize,
        mark
      })));
    });
  }
  return marks;
}
__name(getMarksBetween, "getMarksBetween");
const getNodeAtPosition = /* @__PURE__ */ __name((state, typeOrName, pos, maxDepth = 20) => {
  const $pos = state.doc.resolve(pos);
  let currentDepth = maxDepth;
  let node2 = null;
  while (currentDepth > 0 && node2 === null) {
    const currentNode = $pos.node(currentDepth);
    if ((currentNode === null || currentNode === void 0 ? void 0 : currentNode.type.name) === typeOrName) {
      node2 = currentNode;
    } else {
      currentDepth -= 1;
    }
  }
  return [node2, currentDepth];
}, "getNodeAtPosition");
function getSplittedAttributes(extensionAttributes, typeName, attributes) {
  return Object.fromEntries(Object.entries(attributes).filter(([name2]) => {
    const extensionAttribute = extensionAttributes.find((item) => {
      return item.type === typeName && item.name === name2;
    });
    if (!extensionAttribute) {
      return false;
    }
    return extensionAttribute.attribute.keepOnSplit;
  }));
}
__name(getSplittedAttributes, "getSplittedAttributes");
function isMarkActive(state, typeOrName, attributes = {}) {
  const { empty: empty2, ranges } = state.selection;
  const type = typeOrName ? getMarkType(typeOrName, state.schema) : null;
  if (empty2) {
    return !!(state.storedMarks || state.selection.$from.marks()).filter((mark) => {
      if (!type) {
        return true;
      }
      return type.name === mark.type.name;
    }).find((mark) => objectIncludes(mark.attrs, attributes, { strict: false }));
  }
  let selectionRange = 0;
  const markRanges = [];
  ranges.forEach(({ $from, $to }) => {
    const from2 = $from.pos;
    const to = $to.pos;
    state.doc.nodesBetween(from2, to, (node2, pos) => {
      if (!node2.isText && !node2.marks.length) {
        return;
      }
      const relativeFrom = Math.max(from2, pos);
      const relativeTo = Math.min(to, pos + node2.nodeSize);
      const range2 = relativeTo - relativeFrom;
      selectionRange += range2;
      markRanges.push(...node2.marks.map((mark) => ({
        mark,
        from: relativeFrom,
        to: relativeTo
      })));
    });
  });
  if (selectionRange === 0) {
    return false;
  }
  const matchedRange = markRanges.filter((markRange) => {
    if (!type) {
      return true;
    }
    return type.name === markRange.mark.type.name;
  }).filter((markRange) => objectIncludes(markRange.mark.attrs, attributes, { strict: false })).reduce((sum2, markRange) => sum2 + markRange.to - markRange.from, 0);
  const excludedRange = markRanges.filter((markRange) => {
    if (!type) {
      return true;
    }
    return markRange.mark.type !== type && markRange.mark.type.excludes(type);
  }).reduce((sum2, markRange) => sum2 + markRange.to - markRange.from, 0);
  const range = matchedRange > 0 ? matchedRange + excludedRange : matchedRange;
  return range >= selectionRange;
}
__name(isMarkActive, "isMarkActive");
function isActive(state, name2, attributes = {}) {
  if (!name2) {
    return isNodeActive(state, null, attributes) || isMarkActive(state, null, attributes);
  }
  const schemaType = getSchemaTypeNameByName(name2, state.schema);
  if (schemaType === "node") {
    return isNodeActive(state, name2, attributes);
  }
  if (schemaType === "mark") {
    return isMarkActive(state, name2, attributes);
  }
  return false;
}
__name(isActive, "isActive");
const isAtEndOfNode = /* @__PURE__ */ __name((state, nodeType) => {
  const { $from, $to, $anchor } = state.selection;
  if (nodeType) {
    const parentNode2 = findParentNode((node2) => node2.type.name === nodeType)(state.selection);
    if (!parentNode2) {
      return false;
    }
    const $parentPos = state.doc.resolve(parentNode2.pos + 1);
    if ($anchor.pos + 1 === $parentPos.end()) {
      return true;
    }
    return false;
  }
  if ($to.parentOffset < $to.parent.nodeSize - 2 || $from.pos !== $to.pos) {
    return false;
  }
  return true;
}, "isAtEndOfNode");
const isAtStartOfNode = /* @__PURE__ */ __name((state) => {
  const { $from, $to } = state.selection;
  if ($from.parentOffset > 0 || $from.pos !== $to.pos) {
    return false;
  }
  return true;
}, "isAtStartOfNode");
function isList(name2, extensions) {
  const { nodeExtensions } = splitExtensions(extensions);
  const extension = nodeExtensions.find((item) => item.name === name2);
  if (!extension) {
    return false;
  }
  const context = {
    name: extension.name,
    options: extension.options,
    storage: extension.storage
  };
  const group = callOrReturn(getExtensionField(extension, "group", context));
  if (typeof group !== "string") {
    return false;
  }
  return group.split(" ").includes("list");
}
__name(isList, "isList");
function isNodeEmpty(node2, { checkChildren = true, ignoreWhitespace = false } = {}) {
  var _a2;
  if (ignoreWhitespace) {
    if (node2.type.name === "hardBreak") {
      return true;
    }
    if (node2.isText) {
      return /^\s*$/m.test((_a2 = node2.text) !== null && _a2 !== void 0 ? _a2 : "");
    }
  }
  if (node2.isText) {
    return !node2.text;
  }
  if (node2.isAtom || node2.isLeaf) {
    return false;
  }
  if (node2.content.childCount === 0) {
    return true;
  }
  if (checkChildren) {
    let isContentEmpty = true;
    node2.content.forEach((childNode) => {
      if (isContentEmpty === false) {
        return;
      }
      if (!isNodeEmpty(childNode, { ignoreWhitespace, checkChildren })) {
        isContentEmpty = false;
      }
    });
    return isContentEmpty;
  }
  return false;
}
__name(isNodeEmpty, "isNodeEmpty");
function isNodeSelection(value) {
  return value instanceof NodeSelection;
}
__name(isNodeSelection, "isNodeSelection");
function posToDOMRect(view, from2, to) {
  const minPos = 0;
  const maxPos = view.state.doc.content.size;
  const resolvedFrom = minMax(from2, minPos, maxPos);
  const resolvedEnd = minMax(to, minPos, maxPos);
  const start2 = view.coordsAtPos(resolvedFrom);
  const end = view.coordsAtPos(resolvedEnd, -1);
  const top = Math.min(start2.top, end.top);
  const bottom = Math.max(start2.bottom, end.bottom);
  const left = Math.min(start2.left, end.left);
  const right = Math.max(start2.right, end.right);
  const width2 = right - left;
  const height = bottom - top;
  const x2 = left;
  const y2 = top;
  const data = {
    top,
    bottom,
    left,
    right,
    width: width2,
    height,
    x: x2,
    y: y2
  };
  return {
    ...data,
    toJSON: /* @__PURE__ */ __name(() => data, "toJSON")
  };
}
__name(posToDOMRect, "posToDOMRect");
function canSetMark(state, tr2, newMarkType) {
  var _a2;
  const { selection } = tr2;
  let cursor = null;
  if (isTextSelection(selection)) {
    cursor = selection.$cursor;
  }
  if (cursor) {
    const currentMarks = (_a2 = state.storedMarks) !== null && _a2 !== void 0 ? _a2 : cursor.marks();
    return !!newMarkType.isInSet(currentMarks) || !currentMarks.some((mark) => mark.type.excludes(newMarkType));
  }
  const { ranges } = selection;
  return ranges.some(({ $from, $to }) => {
    let someNodeSupportsMark = $from.depth === 0 ? state.doc.inlineContent && state.doc.type.allowsMarkType(newMarkType) : false;
    state.doc.nodesBetween($from.pos, $to.pos, (node2, _pos, parent2) => {
      if (someNodeSupportsMark) {
        return false;
      }
      if (node2.isInline) {
        const parentAllowsMarkType = !parent2 || parent2.type.allowsMarkType(newMarkType);
        const currentMarksAllowMarkType = !!newMarkType.isInSet(node2.marks) || !node2.marks.some((otherMark) => otherMark.type.excludes(newMarkType));
        someNodeSupportsMark = parentAllowsMarkType && currentMarksAllowMarkType;
      }
      return !someNodeSupportsMark;
    });
    return someNodeSupportsMark;
  });
}
__name(canSetMark, "canSetMark");
const setMark = /* @__PURE__ */ __name((typeOrName, attributes = {}) => ({ tr: tr2, state, dispatch }) => {
  const { selection } = tr2;
  const { empty: empty2, ranges } = selection;
  const type = getMarkType(typeOrName, state.schema);
  if (dispatch) {
    if (empty2) {
      const oldAttributes = getMarkAttributes(state, type);
      tr2.addStoredMark(type.create({
        ...oldAttributes,
        ...attributes
      }));
    } else {
      ranges.forEach((range) => {
        const from2 = range.$from.pos;
        const to = range.$to.pos;
        state.doc.nodesBetween(from2, to, (node2, pos) => {
          const trimmedFrom = Math.max(pos, from2);
          const trimmedTo = Math.min(pos + node2.nodeSize, to);
          const someHasMark = node2.marks.find((mark) => mark.type === type);
          if (someHasMark) {
            node2.marks.forEach((mark) => {
              if (type === mark.type) {
                tr2.addMark(trimmedFrom, trimmedTo, type.create({
                  ...mark.attrs,
                  ...attributes
                }));
              }
            });
          } else {
            tr2.addMark(trimmedFrom, trimmedTo, type.create(attributes));
          }
        });
      });
    }
  }
  return canSetMark(state, tr2, type);
}, "setMark");
const setMeta = /* @__PURE__ */ __name((key, value) => ({ tr: tr2 }) => {
  tr2.setMeta(key, value);
  return true;
}, "setMeta");
const setNode = /* @__PURE__ */ __name((typeOrName, attributes = {}) => ({ state, dispatch, chain }) => {
  const type = getNodeType(typeOrName, state.schema);
  let attributesToCopy;
  if (state.selection.$anchor.sameParent(state.selection.$head)) {
    attributesToCopy = state.selection.$anchor.parent.attrs;
  }
  if (!type.isTextblock) {
    console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.');
    return false;
  }
  return chain().command(({ commands: commands2 }) => {
    const canSetBlock = setBlockType(type, { ...attributesToCopy, ...attributes })(state);
    if (canSetBlock) {
      return true;
    }
    return commands2.clearNodes();
  }).command(({ state: updatedState }) => {
    return setBlockType(type, { ...attributesToCopy, ...attributes })(updatedState, dispatch);
  }).run();
}, "setNode");
const setNodeSelection = /* @__PURE__ */ __name((position) => ({ tr: tr2, dispatch }) => {
  if (dispatch) {
    const { doc: doc2 } = tr2;
    const from2 = minMax(position, 0, doc2.content.size);
    const selection = NodeSelection.create(doc2, from2);
    tr2.setSelection(selection);
  }
  return true;
}, "setNodeSelection");
const setTextSelection = /* @__PURE__ */ __name((position) => ({ tr: tr2, dispatch }) => {
  if (dispatch) {
    const { doc: doc2 } = tr2;
    const { from: from2, to } = typeof position === "number" ? { from: position, to: position } : position;
    const minPos = TextSelection.atStart(doc2).from;
    const maxPos = TextSelection.atEnd(doc2).to;
    const resolvedFrom = minMax(from2, minPos, maxPos);
    const resolvedEnd = minMax(to, minPos, maxPos);
    const selection = TextSelection.create(doc2, resolvedFrom, resolvedEnd);
    tr2.setSelection(selection);
  }
  return true;
}, "setTextSelection");
const sinkListItem = /* @__PURE__ */ __name((typeOrName) => ({ state, dispatch }) => {
  const type = getNodeType(typeOrName, state.schema);
  return sinkListItem$1(type)(state, dispatch);
}, "sinkListItem");
function ensureMarks(state, splittableMarks) {
  const marks = state.storedMarks || state.selection.$to.parentOffset && state.selection.$from.marks();
  if (marks) {
    const filteredMarks = marks.filter((mark) => splittableMarks === null || splittableMarks === void 0 ? void 0 : splittableMarks.includes(mark.type.name));
    state.tr.ensureMarks(filteredMarks);
  }
}
__name(ensureMarks, "ensureMarks");
const splitBlock = /* @__PURE__ */ __name(({ keepMarks = true } = {}) => ({ tr: tr2, state, dispatch, editor }) => {
  const { selection, doc: doc2 } = tr2;
  const { $from, $to } = selection;
  const extensionAttributes = editor.extensionManager.attributes;
  const newAttributes = getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs);
  if (selection instanceof NodeSelection && selection.node.isBlock) {
    if (!$from.parentOffset || !canSplit(doc2, $from.pos)) {
      return false;
    }
    if (dispatch) {
      if (keepMarks) {
        ensureMarks(state, editor.extensionManager.splittableMarks);
      }
      tr2.split($from.pos).scrollIntoView();
    }
    return true;
  }
  if (!$from.parent.isBlock) {
    return false;
  }
  const atEnd = $to.parentOffset === $to.parent.content.size;
  const deflt = $from.depth === 0 ? void 0 : defaultBlockAt($from.node(-1).contentMatchAt($from.indexAfter(-1)));
  let types = atEnd && deflt ? [
    {
      type: deflt,
      attrs: newAttributes
    }
  ] : void 0;
  let can = canSplit(tr2.doc, tr2.mapping.map($from.pos), 1, types);
  if (!types && !can && canSplit(tr2.doc, tr2.mapping.map($from.pos), 1, deflt ? [{ type: deflt }] : void 0)) {
    can = true;
    types = deflt ? [
      {
        type: deflt,
        attrs: newAttributes
      }
    ] : void 0;
  }
  if (dispatch) {
    if (can) {
      if (selection instanceof TextSelection) {
        tr2.deleteSelection();
      }
      tr2.split(tr2.mapping.map($from.pos), 1, types);
      if (deflt && !atEnd && !$from.parentOffset && $from.parent.type !== deflt) {
        const first2 = tr2.mapping.map($from.before());
        const $first = tr2.doc.resolve(first2);
        if ($from.node(-1).canReplaceWith($first.index(), $first.index() + 1, deflt)) {
          tr2.setNodeMarkup(tr2.mapping.map($from.before()), deflt);
        }
      }
    }
    if (keepMarks) {
      ensureMarks(state, editor.extensionManager.splittableMarks);
    }
    tr2.scrollIntoView();
  }
  return can;
}, "splitBlock");
const splitListItem = /* @__PURE__ */ __name((typeOrName, overrideAttrs = {}) => ({ tr: tr2, state, dispatch, editor }) => {
  var _a2;
  const type = getNodeType(typeOrName, state.schema);
  const { $from, $to } = state.selection;
  const node2 = state.selection.node;
  if (node2 && node2.isBlock || $from.depth < 2 || !$from.sameParent($to)) {
    return false;
  }
  const grandParent = $from.node(-1);
  if (grandParent.type !== type) {
    return false;
  }
  const extensionAttributes = editor.extensionManager.attributes;
  if ($from.parent.content.size === 0 && $from.node(-1).childCount === $from.indexAfter(-1)) {
    if ($from.depth === 2 || $from.node(-3).type !== type || $from.index(-2) !== $from.node(-2).childCount - 1) {
      return false;
    }
    if (dispatch) {
      let wrap2 = Fragment.empty;
      const depthBefore = $from.index(-1) ? 1 : $from.index(-2) ? 2 : 3;
      for (let d2 = $from.depth - depthBefore; d2 >= $from.depth - 3; d2 -= 1) {
        wrap2 = Fragment.from($from.node(d2).copy(wrap2));
      }
      const depthAfter = $from.indexAfter(-1) < $from.node(-2).childCount ? 1 : $from.indexAfter(-2) < $from.node(-3).childCount ? 2 : 3;
      const newNextTypeAttributes2 = {
        ...getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs),
        ...overrideAttrs
      };
      const nextType2 = ((_a2 = type.contentMatch.defaultType) === null || _a2 === void 0 ? void 0 : _a2.createAndFill(newNextTypeAttributes2)) || void 0;
      wrap2 = wrap2.append(Fragment.from(type.createAndFill(null, nextType2) || void 0));
      const start2 = $from.before($from.depth - (depthBefore - 1));
      tr2.replace(start2, $from.after(-depthAfter), new Slice(wrap2, 4 - depthBefore, 0));
      let sel = -1;
      tr2.doc.nodesBetween(start2, tr2.doc.content.size, (n2, pos) => {
        if (sel > -1) {
          return false;
        }
        if (n2.isTextblock && n2.content.size === 0) {
          sel = pos + 1;
        }
      });
      if (sel > -1) {
        tr2.setSelection(TextSelection.near(tr2.doc.resolve(sel)));
      }
      tr2.scrollIntoView();
    }
    return true;
  }
  const nextType = $to.pos === $from.end() ? grandParent.contentMatchAt(0).defaultType : null;
  const newTypeAttributes = {
    ...getSplittedAttributes(extensionAttributes, grandParent.type.name, grandParent.attrs),
    ...overrideAttrs
  };
  const newNextTypeAttributes = {
    ...getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs),
    ...overrideAttrs
  };
  tr2.delete($from.pos, $to.pos);
  const types = nextType ? [
    { type, attrs: newTypeAttributes },
    { type: nextType, attrs: newNextTypeAttributes }
  ] : [{ type, attrs: newTypeAttributes }];
  if (!canSplit(tr2.doc, $from.pos, 2)) {
    return false;
  }
  if (dispatch) {
    const { selection, storedMarks } = state;
    const { splittableMarks } = editor.extensionManager;
    const marks = storedMarks || selection.$to.parentOffset && selection.$from.marks();
    tr2.split($from.pos, 2, types).scrollIntoView();
    if (!marks || !dispatch) {
      return true;
    }
    const filteredMarks = marks.filter((mark) => splittableMarks.includes(mark.type.name));
    tr2.ensureMarks(filteredMarks);
  }
  return true;
}, "splitListItem");
const joinListBackwards = /* @__PURE__ */ __name((tr2, listType) => {
  const list2 = findParentNode((node2) => node2.type === listType)(tr2.selection);
  if (!list2) {
    return true;
  }
  const before = tr2.doc.resolve(Math.max(0, list2.pos - 1)).before(list2.depth);
  if (before === void 0) {
    return true;
  }
  const nodeBefore = tr2.doc.nodeAt(before);
  const canJoinBackwards = list2.node.type === (nodeBefore === null || nodeBefore === void 0 ? void 0 : nodeBefore.type) && canJoin(tr2.doc, list2.pos);
  if (!canJoinBackwards) {
    return true;
  }
  tr2.join(list2.pos);
  return true;
}, "joinListBackwards");
const joinListForwards = /* @__PURE__ */ __name((tr2, listType) => {
  const list2 = findParentNode((node2) => node2.type === listType)(tr2.selection);
  if (!list2) {
    return true;
  }
  const after = tr2.doc.resolve(list2.start).after(list2.depth);
  if (after === void 0) {
    return true;
  }
  const nodeAfter = tr2.doc.nodeAt(after);
  const canJoinForwards = list2.node.type === (nodeAfter === null || nodeAfter === void 0 ? void 0 : nodeAfter.type) && canJoin(tr2.doc, after);
  if (!canJoinForwards) {
    return true;
  }
  tr2.join(after);
  return true;
}, "joinListForwards");
const toggleList = /* @__PURE__ */ __name((listTypeOrName, itemTypeOrName, keepMarks, attributes = {}) => ({ editor, tr: tr2, state, dispatch, chain, commands: commands2, can }) => {
  const { extensions, splittableMarks } = editor.extensionManager;
  const listType = getNodeType(listTypeOrName, state.schema);
  const itemType = getNodeType(itemTypeOrName, state.schema);
  const { selection, storedMarks } = state;
  const { $from, $to } = selection;
  const range = $from.blockRange($to);
  const marks = storedMarks || selection.$to.parentOffset && selection.$from.marks();
  if (!range) {
    return false;
  }
  const parentList = findParentNode((node2) => isList(node2.type.name, extensions))(selection);
  if (range.depth >= 1 && parentList && range.depth - parentList.depth <= 1) {
    if (parentList.node.type === listType) {
      return commands2.liftListItem(itemType);
    }
    if (isList(parentList.node.type.name, extensions) && listType.validContent(parentList.node.content) && dispatch) {
      return chain().command(() => {
        tr2.setNodeMarkup(parentList.pos, listType);
        return true;
      }).command(() => joinListBackwards(tr2, listType)).command(() => joinListForwards(tr2, listType)).run();
    }
  }
  if (!keepMarks || !marks || !dispatch) {
    return chain().command(() => {
      const canWrapInList = can().wrapInList(listType, attributes);
      if (canWrapInList) {
        return true;
      }
      return commands2.clearNodes();
    }).wrapInList(listType, attributes).command(() => joinListBackwards(tr2, listType)).command(() => joinListForwards(tr2, listType)).run();
  }
  return chain().command(() => {
    const canWrapInList = can().wrapInList(listType, attributes);
    const filteredMarks = marks.filter((mark) => splittableMarks.includes(mark.type.name));
    tr2.ensureMarks(filteredMarks);
    if (canWrapInList) {
      return true;
    }
    return commands2.clearNodes();
  }).wrapInList(listType, attributes).command(() => joinListBackwards(tr2, listType)).command(() => joinListForwards(tr2, listType)).run();
}, "toggleList");
const toggleMark = /* @__PURE__ */ __name((typeOrName, attributes = {}, options2 = {}) => ({ state, commands: commands2 }) => {
  const { extendEmptyMarkRange = false } = options2;
  const type = getMarkType(typeOrName, state.schema);
  const isActive2 = isMarkActive(state, type, attributes);
  if (isActive2) {
    return commands2.unsetMark(type, { extendEmptyMarkRange });
  }
  return commands2.setMark(type, attributes);
}, "toggleMark");
const toggleNode = /* @__PURE__ */ __name((typeOrName, toggleTypeOrName, attributes = {}) => ({ state, commands: commands2 }) => {
  const type = getNodeType(typeOrName, state.schema);
  const toggleType = getNodeType(toggleTypeOrName, state.schema);
  const isActive2 = isNodeActive(state, type, attributes);
  let attributesToCopy;
  if (state.selection.$anchor.sameParent(state.selection.$head)) {
    attributesToCopy = state.selection.$anchor.parent.attrs;
  }
  if (isActive2) {
    return commands2.setNode(toggleType, attributesToCopy);
  }
  return commands2.setNode(type, { ...attributesToCopy, ...attributes });
}, "toggleNode");
const toggleWrap = /* @__PURE__ */ __name((typeOrName, attributes = {}) => ({ state, commands: commands2 }) => {
  const type = getNodeType(typeOrName, state.schema);
  const isActive2 = isNodeActive(state, type, attributes);
  if (isActive2) {
    return commands2.lift(type);
  }
  return commands2.wrapIn(type, attributes);
}, "toggleWrap");
const undoInputRule = /* @__PURE__ */ __name(() => ({ state, dispatch }) => {
  const plugins = state.plugins;
  for (let i2 = 0; i2 < plugins.length; i2 += 1) {
    const plugin = plugins[i2];
    let undoable;
    if (plugin.spec.isInputRules && (undoable = plugin.getState(state))) {
      if (dispatch) {
        const tr2 = state.tr;
        const toUndo = undoable.transform;
        for (let j2 = toUndo.steps.length - 1; j2 >= 0; j2 -= 1) {
          tr2.step(toUndo.steps[j2].invert(toUndo.docs[j2]));
        }
        if (undoable.text) {
          const marks = tr2.doc.resolve(undoable.from).marks();
          tr2.replaceWith(undoable.from, undoable.to, state.schema.text(undoable.text, marks));
        } else {
          tr2.delete(undoable.from, undoable.to);
        }
      }
      return true;
    }
  }
  return false;
}, "undoInputRule");
const unsetAllMarks = /* @__PURE__ */ __name(() => ({ tr: tr2, dispatch }) => {
  const { selection } = tr2;
  const { empty: empty2, ranges } = selection;
  if (empty2) {
    return true;
  }
  if (dispatch) {
    ranges.forEach((range) => {
      tr2.removeMark(range.$from.pos, range.$to.pos);
    });
  }
  return true;
}, "unsetAllMarks");
const unsetMark = /* @__PURE__ */ __name((typeOrName, options2 = {}) => ({ tr: tr2, state, dispatch }) => {
  var _a2;
  const { extendEmptyMarkRange = false } = options2;
  const { selection } = tr2;
  const type = getMarkType(typeOrName, state.schema);
  const { $from, empty: empty2, ranges } = selection;
  if (!dispatch) {
    return true;
  }
  if (empty2 && extendEmptyMarkRange) {
    let { from: from2, to } = selection;
    const attrs2 = (_a2 = $from.marks().find((mark) => mark.type === type)) === null || _a2 === void 0 ? void 0 : _a2.attrs;
    const range = getMarkRange($from, type, attrs2);
    if (range) {
      from2 = range.from;
      to = range.to;
    }
    tr2.removeMark(from2, to, type);
  } else {
    ranges.forEach((range) => {
      tr2.removeMark(range.$from.pos, range.$to.pos, type);
    });
  }
  tr2.removeStoredMark(type);
  return true;
}, "unsetMark");
const updateAttributes = /* @__PURE__ */ __name((typeOrName, attributes = {}) => ({ tr: tr2, state, dispatch }) => {
  let nodeType = null;
  let markType = null;
  const schemaType = getSchemaTypeNameByName(typeof typeOrName === "string" ? typeOrName : typeOrName.name, state.schema);
  if (!schemaType) {
    return false;
  }
  if (schemaType === "node") {
    nodeType = getNodeType(typeOrName, state.schema);
  }
  if (schemaType === "mark") {
    markType = getMarkType(typeOrName, state.schema);
  }
  if (dispatch) {
    tr2.selection.ranges.forEach((range) => {
      const from2 = range.$from.pos;
      const to = range.$to.pos;
      let lastPos;
      let lastNode;
      let trimmedFrom;
      let trimmedTo;
      if (tr2.selection.empty) {
        state.doc.nodesBetween(from2, to, (node2, pos) => {
          if (nodeType && nodeType === node2.type) {
            trimmedFrom = Math.max(pos, from2);
            trimmedTo = Math.min(pos + node2.nodeSize, to);
            lastPos = pos;
            lastNode = node2;
          }
        });
      } else {
        state.doc.nodesBetween(from2, to, (node2, pos) => {
          if (pos < from2 && nodeType && nodeType === node2.type) {
            trimmedFrom = Math.max(pos, from2);
            trimmedTo = Math.min(pos + node2.nodeSize, to);
            lastPos = pos;
            lastNode = node2;
          }
          if (pos >= from2 && pos <= to) {
            if (nodeType && nodeType === node2.type) {
              tr2.setNodeMarkup(pos, void 0, {
                ...node2.attrs,
                ...attributes
              });
            }
            if (markType && node2.marks.length) {
              node2.marks.forEach((mark) => {
                if (markType === mark.type) {
                  const trimmedFrom2 = Math.max(pos, from2);
                  const trimmedTo2 = Math.min(pos + node2.nodeSize, to);
                  tr2.addMark(trimmedFrom2, trimmedTo2, markType.create({
                    ...mark.attrs,
                    ...attributes
                  }));
                }
              });
            }
          }
        });
      }
      if (lastNode) {
        if (lastPos !== void 0) {
          tr2.setNodeMarkup(lastPos, void 0, {
            ...lastNode.attrs,
            ...attributes
          });
        }
        if (markType && lastNode.marks.length) {
          lastNode.marks.forEach((mark) => {
            if (markType === mark.type) {
              tr2.addMark(trimmedFrom, trimmedTo, markType.create({
                ...mark.attrs,
                ...attributes
              }));
            }
          });
        }
      }
    });
  }
  return true;
}, "updateAttributes");
const wrapIn = /* @__PURE__ */ __name((typeOrName, attributes = {}) => ({ state, dispatch }) => {
  const type = getNodeType(typeOrName, state.schema);
  return wrapIn$1(type, attributes)(state, dispatch);
}, "wrapIn");
const wrapInList = /* @__PURE__ */ __name((typeOrName, attributes = {}) => ({ state, dispatch }) => {
  const type = getNodeType(typeOrName, state.schema);
  return wrapInList$1(type, attributes)(state, dispatch);
}, "wrapInList");
var commands = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  blur,
  clearContent,
  clearNodes,
  command,
  createParagraphNear,
  cut,
  deleteCurrentNode,
  deleteNode,
  deleteRange,
  deleteSelection,
  enter,
  exitCode,
  extendMarkRange,
  first,
  focus,
  forEach,
  insertContent,
  insertContentAt,
  joinBackward,
  joinDown,
  joinForward,
  joinItemBackward,
  joinItemForward,
  joinTextblockBackward,
  joinTextblockForward,
  joinUp,
  keyboardShortcut,
  lift,
  liftEmptyBlock,
  liftListItem,
  newlineInCode,
  resetAttributes,
  scrollIntoView,
  selectAll,
  selectNodeBackward,
  selectNodeForward,
  selectParentNode,
  selectTextblockEnd,
  selectTextblockStart,
  setContent,
  setMark,
  setMeta,
  setNode,
  setNodeSelection,
  setTextSelection,
  sinkListItem,
  splitBlock,
  splitListItem,
  toggleList,
  toggleMark,
  toggleNode,
  toggleWrap,
  undoInputRule,
  unsetAllMarks,
  unsetMark,
  updateAttributes,
  wrapIn,
  wrapInList
});
const Commands = Extension.create({
  name: "commands",
  addCommands() {
    return {
      ...commands
    };
  }
});
const Drop = Extension.create({
  name: "drop",
  addProseMirrorPlugins() {
    return [
      new Plugin({
        key: new PluginKey("tiptapDrop"),
        props: {
          handleDrop: /* @__PURE__ */ __name((_2, e2, slice2, moved) => {
            this.editor.emit("drop", {
              editor: this.editor,
              event: e2,
              slice: slice2,
              moved
            });
          }, "handleDrop")
        }
      })
    ];
  }
});
const Editable = Extension.create({
  name: "editable",
  addProseMirrorPlugins() {
    return [
      new Plugin({
        key: new PluginKey("editable"),
        props: {
          editable: /* @__PURE__ */ __name(() => this.editor.options.editable, "editable")
        }
      })
    ];
  }
});
const FocusEvents = Extension.create({
  name: "focusEvents",
  addProseMirrorPlugins() {
    const { editor } = this;
    return [
      new Plugin({
        key: new PluginKey("focusEvents"),
        props: {
          handleDOMEvents: {
            focus: /* @__PURE__ */ __name((view, event) => {
              editor.isFocused = true;
              const transaction = editor.state.tr.setMeta("focus", { event }).setMeta("addToHistory", false);
              view.dispatch(transaction);
              return false;
            }, "focus"),
            blur: /* @__PURE__ */ __name((view, event) => {
              editor.isFocused = false;
              const transaction = editor.state.tr.setMeta("blur", { event }).setMeta("addToHistory", false);
              view.dispatch(transaction);
              return false;
            }, "blur")
          }
        }
      })
    ];
  }
});
const Keymap = Extension.create({
  name: "keymap",
  addKeyboardShortcuts() {
    const handleBackspace = /* @__PURE__ */ __name(() => this.editor.commands.first(({ commands: commands2 }) => [
      () => commands2.undoInputRule(),
      // maybe convert first text block node to default node
      () => commands2.command(({ tr: tr2 }) => {
        const { selection, doc: doc2 } = tr2;
        const { empty: empty2, $anchor } = selection;
        const { pos, parent: parent2 } = $anchor;
        const $parentPos = $anchor.parent.isTextblock && pos > 0 ? tr2.doc.resolve(pos - 1) : $anchor;
        const parentIsIsolating = $parentPos.parent.type.spec.isolating;
        const parentPos = $anchor.pos - $anchor.parentOffset;
        const isAtStart = parentIsIsolating && $parentPos.parent.childCount === 1 ? parentPos === $anchor.pos : Selection.atStart(doc2).from === pos;
        if (!empty2 || !parent2.type.isTextblock || parent2.textContent.length || !isAtStart || isAtStart && $anchor.parent.type.name === "paragraph") {
          return false;
        }
        return commands2.clearNodes();
      }),
      () => commands2.deleteSelection(),
      () => commands2.joinBackward(),
      () => commands2.selectNodeBackward()
    ]), "handleBackspace");
    const handleDelete = /* @__PURE__ */ __name(() => this.editor.commands.first(({ commands: commands2 }) => [
      () => commands2.deleteSelection(),
      () => commands2.deleteCurrentNode(),
      () => commands2.joinForward(),
      () => commands2.selectNodeForward()
    ]), "handleDelete");
    const handleEnter = /* @__PURE__ */ __name(() => this.editor.commands.first(({ commands: commands2 }) => [
      () => commands2.newlineInCode(),
      () => commands2.createParagraphNear(),
      () => commands2.liftEmptyBlock(),
      () => commands2.splitBlock()
    ]), "handleEnter");
    const baseKeymap2 = {
      Enter: handleEnter,
      "Mod-Enter": /* @__PURE__ */ __name(() => this.editor.commands.exitCode(), "Mod-Enter"),
      Backspace: handleBackspace,
      "Mod-Backspace": handleBackspace,
      "Shift-Backspace": handleBackspace,
      Delete: handleDelete,
      "Mod-Delete": handleDelete,
      "Mod-a": /* @__PURE__ */ __name(() => this.editor.commands.selectAll(), "Mod-a")
    };
    const pcKeymap = {
      ...baseKeymap2
    };
    const macKeymap = {
      ...baseKeymap2,
      "Ctrl-h": handleBackspace,
      "Alt-Backspace": handleBackspace,
      "Ctrl-d": handleDelete,
      "Ctrl-Alt-Backspace": handleDelete,
      "Alt-Delete": handleDelete,
      "Alt-d": handleDelete,
      "Ctrl-a": /* @__PURE__ */ __name(() => this.editor.commands.selectTextblockStart(), "Ctrl-a"),
      "Ctrl-e": /* @__PURE__ */ __name(() => this.editor.commands.selectTextblockEnd(), "Ctrl-e")
    };
    if (isiOS() || isMacOS()) {
      return macKeymap;
    }
    return pcKeymap;
  },
  addProseMirrorPlugins() {
    return [
      // With this plugin we check if the whole document was selected and deleted.
      // In this case we will additionally call `clearNodes()` to convert e.g. a heading
      // to a paragraph if necessary.
      // This is an alternative to ProseMirror's `AllSelection`, which doesn’t work well
      // with many other commands.
      new Plugin({
        key: new PluginKey("clearDocument"),
        appendTransaction: /* @__PURE__ */ __name((transactions, oldState, newState) => {
          const docChanges = transactions.some((transaction) => transaction.docChanged) && !oldState.doc.eq(newState.doc);
          const ignoreTr = transactions.some((transaction) => transaction.getMeta("preventClearDocument"));
          if (!docChanges || ignoreTr) {
            return;
          }
          const { empty: empty2, from: from2, to } = oldState.selection;
          const allFrom = Selection.atStart(oldState.doc).from;
          const allEnd = Selection.atEnd(oldState.doc).to;
          const allWasSelected = from2 === allFrom && to === allEnd;
          if (empty2 || !allWasSelected) {
            return;
          }
          const isEmpty3 = isNodeEmpty(newState.doc);
          if (!isEmpty3) {
            return;
          }
          const tr2 = newState.tr;
          const state = createChainableState({
            state: newState,
            transaction: tr2
          });
          const { commands: commands2 } = new CommandManager({
            editor: this.editor,
            state
          });
          commands2.clearNodes();
          if (!tr2.steps.length) {
            return;
          }
          return tr2;
        }, "appendTransaction")
      })
    ];
  }
});
const Paste = Extension.create({
  name: "paste",
  addProseMirrorPlugins() {
    return [
      new Plugin({
        key: new PluginKey("tiptapPaste"),
        props: {
          handlePaste: /* @__PURE__ */ __name((_view, e2, slice2) => {
            this.editor.emit("paste", {
              editor: this.editor,
              event: e2,
              slice: slice2
            });
          }, "handlePaste")
        }
      })
    ];
  }
});
const Tabindex = Extension.create({
  name: "tabindex",
  addProseMirrorPlugins() {
    return [
      new Plugin({
        key: new PluginKey("tabindex"),
        props: {
          attributes: /* @__PURE__ */ __name(() => this.editor.isEditable ? { tabindex: "0" } : {}, "attributes")
        }
      })
    ];
  }
});
var index$1 = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  ClipboardTextSerializer,
  Commands,
  Drop,
  Editable,
  FocusEvents,
  Keymap,
  Paste,
  Tabindex
});
class NodePos {
  static {
    __name(this, "NodePos");
  }
  get name() {
    return this.node.type.name;
  }
  constructor(pos, editor, isBlock = false, node2 = null) {
    this.currentNode = null;
    this.actualDepth = null;
    this.isBlock = isBlock;
    this.resolvedPos = pos;
    this.editor = editor;
    this.currentNode = node2;
  }
  get node() {
    return this.currentNode || this.resolvedPos.node();
  }
  get element() {
    return this.editor.view.domAtPos(this.pos).node;
  }
  get depth() {
    var _a2;
    return (_a2 = this.actualDepth) !== null && _a2 !== void 0 ? _a2 : this.resolvedPos.depth;
  }
  get pos() {
    return this.resolvedPos.pos;
  }
  get content() {
    return this.node.content;
  }
  set content(content) {
    let from2 = this.from;
    let to = this.to;
    if (this.isBlock) {
      if (this.content.size === 0) {
        console.error(`You can’t set content on a block node. Tried to set content on ${this.name} at ${this.pos}`);
        return;
      }
      from2 = this.from + 1;
      to = this.to - 1;
    }
    this.editor.commands.insertContentAt({ from: from2, to }, content);
  }
  get attributes() {
    return this.node.attrs;
  }
  get textContent() {
    return this.node.textContent;
  }
  get size() {
    return this.node.nodeSize;
  }
  get from() {
    if (this.isBlock) {
      return this.pos;
    }
    return this.resolvedPos.start(this.resolvedPos.depth);
  }
  get range() {
    return {
      from: this.from,
      to: this.to
    };
  }
  get to() {
    if (this.isBlock) {
      return this.pos + this.size;
    }
    return this.resolvedPos.end(this.resolvedPos.depth) + (this.node.isText ? 0 : 1);
  }
  get parent() {
    if (this.depth === 0) {
      return null;
    }
    const parentPos = this.resolvedPos.start(this.resolvedPos.depth - 1);
    const $pos = this.resolvedPos.doc.resolve(parentPos);
    return new NodePos($pos, this.editor);
  }
  get before() {
    let $pos = this.resolvedPos.doc.resolve(this.from - (this.isBlock ? 1 : 2));
    if ($pos.depth !== this.depth) {
      $pos = this.resolvedPos.doc.resolve(this.from - 3);
    }
    return new NodePos($pos, this.editor);
  }
  get after() {
    let $pos = this.resolvedPos.doc.resolve(this.to + (this.isBlock ? 2 : 1));
    if ($pos.depth !== this.depth) {
      $pos = this.resolvedPos.doc.resolve(this.to + 3);
    }
    return new NodePos($pos, this.editor);
  }
  get children() {
    const children = [];
    this.node.content.forEach((node2, offset) => {
      const isBlock = node2.isBlock && !node2.isTextblock;
      const isNonTextAtom = node2.isAtom && !node2.isText;
      const targetPos = this.pos + offset + (isNonTextAtom ? 0 : 1);
      const $pos = this.resolvedPos.doc.resolve(targetPos);
      if (!isBlock && $pos.depth <= this.depth) {
        return;
      }
      const childNodePos = new NodePos($pos, this.editor, isBlock, isBlock ? node2 : null);
      if (isBlock) {
        childNodePos.actualDepth = this.depth + 1;
      }
      children.push(new NodePos($pos, this.editor, isBlock, isBlock ? node2 : null));
    });
    return children;
  }
  get firstChild() {
    return this.children[0] || null;
  }
  get lastChild() {
    const children = this.children;
    return children[children.length - 1] || null;
  }
  closest(selector, attributes = {}) {
    let node2 = null;
    let currentNode = this.parent;
    while (currentNode && !node2) {
      if (currentNode.node.type.name === selector) {
        if (Object.keys(attributes).length > 0) {
          const nodeAttributes = currentNode.node.attrs;
          const attrKeys = Object.keys(attributes);
          for (let index2 = 0; index2 < attrKeys.length; index2 += 1) {
            const key = attrKeys[index2];
            if (nodeAttributes[key] !== attributes[key]) {
              break;
            }
          }
        } else {
          node2 = currentNode;
        }
      }
      currentNode = currentNode.parent;
    }
    return node2;
  }
  querySelector(selector, attributes = {}) {
    return this.querySelectorAll(selector, attributes, true)[0] || null;
  }
  querySelectorAll(selector, attributes = {}, firstItemOnly = false) {
    let nodes = [];
    if (!this.children || this.children.length === 0) {
      return nodes;
    }
    const attrKeys = Object.keys(attributes);
    this.children.forEach((childPos) => {
      if (firstItemOnly && nodes.length > 0) {
        return;
      }
      if (childPos.node.type.name === selector) {
        const doesAllAttributesMatch = attrKeys.every((key) => attributes[key] === childPos.node.attrs[key]);
        if (doesAllAttributesMatch) {
          nodes.push(childPos);
        }
      }
      if (firstItemOnly && nodes.length > 0) {
        return;
      }
      nodes = nodes.concat(childPos.querySelectorAll(selector, attributes, firstItemOnly));
    });
    return nodes;
  }
  setAttribute(attributes) {
    const { tr: tr2 } = this.editor.state;
    tr2.setNodeMarkup(this.from, void 0, {
      ...this.node.attrs,
      ...attributes
    });
    this.editor.view.dispatch(tr2);
  }
}
const style = `.ProseMirror {
  position: relative;
}

.ProseMirror {
  word-wrap: break-word;
  white-space: pre-wrap;
  white-space: break-spaces;
  -webkit-font-variant-ligatures: none;
  font-variant-ligatures: none;
  font-feature-settings: "liga" 0; /* the above doesn't seem to work in Edge */
}

.ProseMirror [contenteditable="false"] {
  white-space: normal;
}

.ProseMirror [contenteditable="false"] [contenteditable="true"] {
  white-space: pre-wrap;
}

.ProseMirror pre {
  white-space: pre-wrap;
}

img.ProseMirror-separator {
  display: inline !important;
  border: none !important;
  margin: 0 !important;
  width: 0 !important;
  height: 0 !important;
}

.ProseMirror-gapcursor {
  display: none;
  pointer-events: none;
  position: absolute;
  margin: 0;
}

.ProseMirror-gapcursor:after {
  content: "";
  display: block;
  position: absolute;
  top: -2px;
  width: 20px;
  border-top: 1px solid black;
  animation: ProseMirror-cursor-blink 1.1s steps(2, start) infinite;
}

@keyframes ProseMirror-cursor-blink {
  to {
    visibility: hidden;
  }
}

.ProseMirror-hideselection *::selection {
  background: transparent;
}

.ProseMirror-hideselection *::-moz-selection {
  background: transparent;
}

.ProseMirror-hideselection * {
  caret-color: transparent;
}

.ProseMirror-focused .ProseMirror-gapcursor {
  display: block;
}

.tippy-box[data-animation=fade][data-state=hidden] {
  opacity: 0
}`;
function createStyleTag(style2, nonce, suffix) {
  const tiptapStyleTag = document.querySelector(`style[data-tiptap-style${suffix ? `-${suffix}` : ""}]`);
  if (tiptapStyleTag !== null) {
    return tiptapStyleTag;
  }
  const styleNode = document.createElement("style");
  if (nonce) {
    styleNode.setAttribute("nonce", nonce);
  }
  styleNode.setAttribute(`data-tiptap-style${suffix ? `-${suffix}` : ""}`, "");
  styleNode.innerHTML = style2;
  document.getElementsByTagName("head")[0].appendChild(styleNode);
  return styleNode;
}
__name(createStyleTag, "createStyleTag");
class Editor extends EventEmitter {
  static {
    __name(this, "Editor");
  }
  constructor(options2 = {}) {
    super();
    this.isFocused = false;
    this.isInitialized = false;
    this.extensionStorage = {};
    this.options = {
      element: document.createElement("div"),
      content: "",
      injectCSS: true,
      injectNonce: void 0,
      extensions: [],
      autofocus: false,
      editable: true,
      editorProps: {},
      parseOptions: {},
      coreExtensionOptions: {},
      enableInputRules: true,
      enablePasteRules: true,
      enableCoreExtensions: true,
      enableContentCheck: false,
      onBeforeCreate: /* @__PURE__ */ __name(() => null, "onBeforeCreate"),
      onCreate: /* @__PURE__ */ __name(() => null, "onCreate"),
      onUpdate: /* @__PURE__ */ __name(() => null, "onUpdate"),
      onSelectionUpdate: /* @__PURE__ */ __name(() => null, "onSelectionUpdate"),
      onTransaction: /* @__PURE__ */ __name(() => null, "onTransaction"),
      onFocus: /* @__PURE__ */ __name(() => null, "onFocus"),
      onBlur: /* @__PURE__ */ __name(() => null, "onBlur"),
      onDestroy: /* @__PURE__ */ __name(() => null, "onDestroy"),
      onContentError: /* @__PURE__ */ __name(({ error: error2 }) => {
        throw error2;
      }, "onContentError"),
      onPaste: /* @__PURE__ */ __name(() => null, "onPaste"),
      onDrop: /* @__PURE__ */ __name(() => null, "onDrop")
    };
    this.isCapturingTransaction = false;
    this.capturedTransaction = null;
    this.setOptions(options2);
    this.createExtensionManager();
    this.createCommandManager();
    this.createSchema();
    this.on("beforeCreate", this.options.onBeforeCreate);
    this.emit("beforeCreate", { editor: this });
    this.on("contentError", this.options.onContentError);
    this.createView();
    this.injectCSS();
    this.on("create", this.options.onCreate);
    this.on("update", this.options.onUpdate);
    this.on("selectionUpdate", this.options.onSelectionUpdate);
    this.on("transaction", this.options.onTransaction);
    this.on("focus", this.options.onFocus);
    this.on("blur", this.options.onBlur);
    this.on("destroy", this.options.onDestroy);
    this.on("drop", ({ event, slice: slice2, moved }) => this.options.onDrop(event, slice2, moved));
    this.on("paste", ({ event, slice: slice2 }) => this.options.onPaste(event, slice2));
    window.setTimeout(() => {
      if (this.isDestroyed) {
        return;
      }
      this.commands.focus(this.options.autofocus);
      this.emit("create", { editor: this });
      this.isInitialized = true;
    }, 0);
  }
  /**
   * Returns the editor storage.
   */
  get storage() {
    return this.extensionStorage;
  }
  /**
   * An object of all registered commands.
   */
  get commands() {
    return this.commandManager.commands;
  }
  /**
   * Create a command chain to call multiple commands at once.
   */
  chain() {
    return this.commandManager.chain();
  }
  /**
   * Check if a command or a command chain can be executed. Without executing it.
   */
  can() {
    return this.commandManager.can();
  }
  /**
   * Inject CSS styles.
   */
  injectCSS() {
    if (this.options.injectCSS && document) {
      this.css = createStyleTag(style, this.options.injectNonce);
    }
  }
  /**
   * Update editor options.
   *
   * @param options A list of options
   */
  setOptions(options2 = {}) {
    this.options = {
      ...this.options,
      ...options2
    };
    if (!this.view || !this.state || this.isDestroyed) {
      return;
    }
    if (this.options.editorProps) {
      this.view.setProps(this.options.editorProps);
    }
    this.view.updateState(this.state);
  }
  /**
   * Update editable state of the editor.
   */
  setEditable(editable, emitUpdate = true) {
    this.setOptions({ editable });
    if (emitUpdate) {
      this.emit("update", { editor: this, transaction: this.state.tr });
    }
  }
  /**
   * Returns whether the editor is editable.
   */
  get isEditable() {
    return this.options.editable && this.view && this.view.editable;
  }
  /**
   * Returns the editor state.
   */
  get state() {
    return this.view.state;
  }
  /**
   * Register a ProseMirror plugin.
   *
   * @param plugin A ProseMirror plugin
   * @param handlePlugins Control how to merge the plugin into the existing plugins.
   * @returns The new editor state
   */
  registerPlugin(plugin, handlePlugins) {
    const plugins = isFunction$1(handlePlugins) ? handlePlugins(plugin, [...this.state.plugins]) : [...this.state.plugins, plugin];
    const state = this.state.reconfigure({ plugins });
    this.view.updateState(state);
    return state;
  }
  /**
   * Unregister a ProseMirror plugin.
   *
   * @param nameOrPluginKeyToRemove The plugins name
   * @returns The new editor state or undefined if the editor is destroyed
   */
  unregisterPlugin(nameOrPluginKeyToRemove) {
    if (this.isDestroyed) {
      return void 0;
    }
    const prevPlugins = this.state.plugins;
    let plugins = prevPlugins;
    [].concat(nameOrPluginKeyToRemove).forEach((nameOrPluginKey) => {
      const name2 = typeof nameOrPluginKey === "string" ? `${nameOrPluginKey}$` : nameOrPluginKey.key;
      plugins = prevPlugins.filter((plugin) => !plugin.key.startsWith(name2));
    });
    if (prevPlugins.length === plugins.length) {
      return void 0;
    }
    const state = this.state.reconfigure({
      plugins
    });
    this.view.updateState(state);
    return state;
  }
  /**
   * Creates an extension manager.
   */
  createExtensionManager() {
    var _a2, _b;
    const coreExtensions = this.options.enableCoreExtensions ? [
      Editable,
      ClipboardTextSerializer.configure({
        blockSeparator: (_b = (_a2 = this.options.coreExtensionOptions) === null || _a2 === void 0 ? void 0 : _a2.clipboardTextSerializer) === null || _b === void 0 ? void 0 : _b.blockSeparator
      }),
      Commands,
      FocusEvents,
      Keymap,
      Tabindex,
      Drop,
      Paste
    ].filter((ext) => {
      if (typeof this.options.enableCoreExtensions === "object") {
        return this.options.enableCoreExtensions[ext.name] !== false;
      }
      return true;
    }) : [];
    const allExtensions = [...coreExtensions, ...this.options.extensions].filter((extension) => {
      return ["extension", "node", "mark"].includes(extension === null || extension === void 0 ? void 0 : extension.type);
    });
    this.extensionManager = new ExtensionManager(allExtensions, this);
  }
  /**
   * Creates an command manager.
   */
  createCommandManager() {
    this.commandManager = new CommandManager({
      editor: this
    });
  }
  /**
   * Creates a ProseMirror schema.
   */
  createSchema() {
    this.schema = this.extensionManager.schema;
  }
  /**
   * Creates a ProseMirror view.
   */
  createView() {
    var _a2;
    let doc2;
    try {
      doc2 = createDocument(this.options.content, this.schema, this.options.parseOptions, { errorOnInvalidContent: this.options.enableContentCheck });
    } catch (e2) {
      if (!(e2 instanceof Error) || !["[tiptap error]: Invalid JSON content", "[tiptap error]: Invalid HTML content"].includes(e2.message)) {
        throw e2;
      }
      this.emit("contentError", {
        editor: this,
        error: e2,
        disableCollaboration: /* @__PURE__ */ __name(() => {
          if (this.storage.collaboration) {
            this.storage.collaboration.isDisabled = true;
          }
          this.options.extensions = this.options.extensions.filter((extension) => extension.name !== "collaboration");
          this.createExtensionManager();
        }, "disableCollaboration")
      });
      doc2 = createDocument(this.options.content, this.schema, this.options.parseOptions, { errorOnInvalidContent: false });
    }
    const selection = resolveFocusPosition(doc2, this.options.autofocus);
    this.view = new EditorView(this.options.element, {
      ...this.options.editorProps,
      attributes: {
        // add `role="textbox"` to the editor element
        role: "textbox",
        ...(_a2 = this.options.editorProps) === null || _a2 === void 0 ? void 0 : _a2.attributes
      },
      dispatchTransaction: this.dispatchTransaction.bind(this),
      state: EditorState.create({
        doc: doc2,
        selection: selection || void 0
      })
    });
    const newState = this.state.reconfigure({
      plugins: this.extensionManager.plugins
    });
    this.view.updateState(newState);
    this.createNodeViews();
    this.prependClass();
    const dom = this.view.dom;
    dom.editor = this;
  }
  /**
   * Creates all node views.
   */
  createNodeViews() {
    if (this.view.isDestroyed) {
      return;
    }
    this.view.setProps({
      nodeViews: this.extensionManager.nodeViews
    });
  }
  /**
   * Prepend class name to element.
   */
  prependClass() {
    this.view.dom.className = `tiptap ${this.view.dom.className}`;
  }
  captureTransaction(fn) {
    this.isCapturingTransaction = true;
    fn();
    this.isCapturingTransaction = false;
    const tr2 = this.capturedTransaction;
    this.capturedTransaction = null;
    return tr2;
  }
  /**
   * The callback over which to send transactions (state updates) produced by the view.
   *
   * @param transaction An editor state transaction
   */
  dispatchTransaction(transaction) {
    if (this.view.isDestroyed) {
      return;
    }
    if (this.isCapturingTransaction) {
      if (!this.capturedTransaction) {
        this.capturedTransaction = transaction;
        return;
      }
      transaction.steps.forEach((step) => {
        var _a2;
        return (_a2 = this.capturedTransaction) === null || _a2 === void 0 ? void 0 : _a2.step(step);
      });
      return;
    }
    const state = this.state.apply(transaction);
    const selectionHasChanged = !this.state.selection.eq(state.selection);
    this.emit("beforeTransaction", {
      editor: this,
      transaction,
      nextState: state
    });
    this.view.updateState(state);
    this.emit("transaction", {
      editor: this,
      transaction
    });
    if (selectionHasChanged) {
      this.emit("selectionUpdate", {
        editor: this,
        transaction
      });
    }
    const focus2 = transaction.getMeta("focus");
    const blur2 = transaction.getMeta("blur");
    if (focus2) {
      this.emit("focus", {
        editor: this,
        event: focus2.event,
        transaction
      });
    }
    if (blur2) {
      this.emit("blur", {
        editor: this,
        event: blur2.event,
        transaction
      });
    }
    if (!transaction.docChanged || transaction.getMeta("preventUpdate")) {
      return;
    }
    this.emit("update", {
      editor: this,
      transaction
    });
  }
  /**
   * Get attributes of the currently selected node or mark.
   */
  getAttributes(nameOrType) {
    return getAttributes(this.state, nameOrType);
  }
  isActive(nameOrAttributes, attributesOrUndefined) {
    const name2 = typeof nameOrAttributes === "string" ? nameOrAttributes : null;
    const attributes = typeof nameOrAttributes === "string" ? attributesOrUndefined : nameOrAttributes;
    return isActive(this.state, name2, attributes);
  }
  /**
   * Get the document as JSON.
   */
  getJSON() {
    return this.state.doc.toJSON();
  }
  /**
   * Get the document as HTML.
   */
  getHTML() {
    return getHTMLFromFragment(this.state.doc.content, this.schema);
  }
  /**
   * Get the document as text.
   */
  getText(options2) {
    const { blockSeparator = "\n\n", textSerializers = {} } = options2 || {};
    return getText(this.state.doc, {
      blockSeparator,
      textSerializers: {
        ...getTextSerializersFromSchema(this.schema),
        ...textSerializers
      }
    });
  }
  /**
   * Check if there is no content.
   */
  get isEmpty() {
    return isNodeEmpty(this.state.doc);
  }
  /**
   * Get the number of characters for the current document.
   *
   * @deprecated
   */
  getCharacterCount() {
    console.warn('[tiptap warn]: "editor.getCharacterCount()" is deprecated. Please use "editor.storage.characterCount.characters()" instead.');
    return this.state.doc.content.size - 2;
  }
  /**
   * Destroy the editor.
   */
  destroy() {
    this.emit("destroy");
    if (this.view) {
      const dom = this.view.dom;
      if (dom && dom.editor) {
        delete dom.editor;
      }
      this.view.destroy();
    }
    this.removeAllListeners();
  }
  /**
   * Check if the editor is already destroyed.
   */
  get isDestroyed() {
    var _a2;
    return !((_a2 = this.view) === null || _a2 === void 0 ? void 0 : _a2.docView);
  }
  $node(selector, attributes) {
    var _a2;
    return ((_a2 = this.$doc) === null || _a2 === void 0 ? void 0 : _a2.querySelector(selector, attributes)) || null;
  }
  $nodes(selector, attributes) {
    var _a2;
    return ((_a2 = this.$doc) === null || _a2 === void 0 ? void 0 : _a2.querySelectorAll(selector, attributes)) || null;
  }
  $pos(pos) {
    const $pos = this.state.doc.resolve(pos);
    return new NodePos($pos, this);
  }
  get $doc() {
    return this.$pos(0);
  }
}
function markInputRule(config2) {
  return new InputRule({
    find: config2.find,
    handler: /* @__PURE__ */ __name(({ state, range, match: match2 }) => {
      const attributes = callOrReturn(config2.getAttributes, void 0, match2);
      if (attributes === false || attributes === null) {
        return null;
      }
      const { tr: tr2 } = state;
      const captureGroup = match2[match2.length - 1];
      const fullMatch = match2[0];
      if (captureGroup) {
        const startSpaces = fullMatch.search(/\S/);
        const textStart = range.from + fullMatch.indexOf(captureGroup);
        const textEnd = textStart + captureGroup.length;
        const excludedMarks = getMarksBetween(range.from, range.to, state.doc).filter((item) => {
          const excluded = item.mark.type.excluded;
          return excluded.find((type) => type === config2.type && type !== item.mark.type);
        }).filter((item) => item.to > textStart);
        if (excludedMarks.length) {
          return null;
        }
        if (textEnd < range.to) {
          tr2.delete(textEnd, range.to);
        }
        if (textStart > range.from) {
          tr2.delete(range.from + startSpaces, textStart);
        }
        const markEnd = range.from + startSpaces + captureGroup.length;
        tr2.addMark(range.from + startSpaces, markEnd, config2.type.create(attributes || {}));
        tr2.removeStoredMark(config2.type);
      }
    }, "handler")
  });
}
__name(markInputRule, "markInputRule");
function nodeInputRule(config2) {
  return new InputRule({
    find: config2.find,
    handler: /* @__PURE__ */ __name(({ state, range, match: match2 }) => {
      const attributes = callOrReturn(config2.getAttributes, void 0, match2) || {};
      const { tr: tr2 } = state;
      const start2 = range.from;
      let end = range.to;
      const newNode = config2.type.create(attributes);
      if (match2[1]) {
        const offset = match2[0].lastIndexOf(match2[1]);
        let matchStart = start2 + offset;
        if (matchStart > end) {
          matchStart = end;
        } else {
          end = matchStart + match2[1].length;
        }
        const lastChar = match2[0][match2[0].length - 1];
        tr2.insertText(lastChar, start2 + match2[0].length - 1);
        tr2.replaceWith(matchStart, end, newNode);
      } else if (match2[0]) {
        const insertionStart = config2.type.isInline ? start2 : start2 - 1;
        tr2.insert(insertionStart, config2.type.create(attributes)).delete(tr2.mapping.map(start2), tr2.mapping.map(end));
      }
      tr2.scrollIntoView();
    }, "handler")
  });
}
__name(nodeInputRule, "nodeInputRule");
function textblockTypeInputRule(config2) {
  return new InputRule({
    find: config2.find,
    handler: /* @__PURE__ */ __name(({ state, range, match: match2 }) => {
      const $start = state.doc.resolve(range.from);
      const attributes = callOrReturn(config2.getAttributes, void 0, match2) || {};
      if (!$start.node(-1).canReplaceWith($start.index(-1), $start.indexAfter(-1), config2.type)) {
        return null;
      }
      state.tr.delete(range.from, range.to).setBlockType(range.from, range.from, config2.type, attributes);
    }, "handler")
  });
}
__name(textblockTypeInputRule, "textblockTypeInputRule");
function textInputRule(config2) {
  return new InputRule({
    find: config2.find,
    handler: /* @__PURE__ */ __name(({ state, range, match: match2 }) => {
      let insert = config2.replace;
      let start2 = range.from;
      const end = range.to;
      if (match2[1]) {
        const offset = match2[0].lastIndexOf(match2[1]);
        insert += match2[0].slice(offset + match2[1].length);
        start2 += offset;
        const cutOff = start2 - end;
        if (cutOff > 0) {
          insert = match2[0].slice(offset - cutOff, offset) + insert;
          start2 = end;
        }
      }
      state.tr.insertText(insert, start2, end);
    }, "handler")
  });
}
__name(textInputRule, "textInputRule");
function wrappingInputRule(config2) {
  return new InputRule({
    find: config2.find,
    handler: /* @__PURE__ */ __name(({ state, range, match: match2, chain }) => {
      const attributes = callOrReturn(config2.getAttributes, void 0, match2) || {};
      const tr2 = state.tr.delete(range.from, range.to);
      const $start = tr2.doc.resolve(range.from);
      const blockRange = $start.blockRange();
      const wrapping = blockRange && findWrapping(blockRange, config2.type, attributes);
      if (!wrapping) {
        return null;
      }
      tr2.wrap(blockRange, wrapping);
      if (config2.keepMarks && config2.editor) {
        const { selection, storedMarks } = state;
        const { splittableMarks } = config2.editor.extensionManager;
        const marks = storedMarks || selection.$to.parentOffset && selection.$from.marks();
        if (marks) {
          const filteredMarks = marks.filter((mark) => splittableMarks.includes(mark.type.name));
          tr2.ensureMarks(filteredMarks);
        }
      }
      if (config2.keepAttributes) {
        const nodeType = config2.type.name === "bulletList" || config2.type.name === "orderedList" ? "listItem" : "taskList";
        chain().updateAttributes(nodeType, attributes).run();
      }
      const before = tr2.doc.resolve(range.from - 1).nodeBefore;
      if (before && before.type === config2.type && canJoin(tr2.doc, range.from - 1) && (!config2.joinPredicate || config2.joinPredicate(match2, before))) {
        tr2.join(range.from - 1);
      }
    }, "handler")
  });
}
__name(wrappingInputRule, "wrappingInputRule");
let Node$1 = class Node3 {
  static {
    __name(this, "Node");
  }
  constructor(config2 = {}) {
    this.type = "node";
    this.name = "node";
    this.parent = null;
    this.child = null;
    this.config = {
      name: this.name,
      defaultOptions: {}
    };
    this.config = {
      ...this.config,
      ...config2
    };
    this.name = this.config.name;
    if (config2.defaultOptions && Object.keys(config2.defaultOptions).length > 0) {
      console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${this.name}".`);
    }
    this.options = this.config.defaultOptions;
    if (this.config.addOptions) {
      this.options = callOrReturn(getExtensionField(this, "addOptions", {
        name: this.name
      }));
    }
    this.storage = callOrReturn(getExtensionField(this, "addStorage", {
      name: this.name,
      options: this.options
    })) || {};
  }
  static create(config2 = {}) {
    return new Node3(config2);
  }
  configure(options2 = {}) {
    const extension = this.extend({
      ...this.config,
      addOptions: /* @__PURE__ */ __name(() => {
        return mergeDeep(this.options, options2);
      }, "addOptions")
    });
    extension.name = this.name;
    extension.parent = this.parent;
    return extension;
  }
  extend(extendedConfig = {}) {
    const extension = new Node3(extendedConfig);
    extension.parent = this;
    this.child = extension;
    extension.name = extendedConfig.name ? extendedConfig.name : extension.parent.name;
    if (extendedConfig.defaultOptions && Object.keys(extendedConfig.defaultOptions).length > 0) {
      console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${extension.name}".`);
    }
    extension.options = callOrReturn(getExtensionField(extension, "addOptions", {
      name: extension.name
    }));
    extension.storage = callOrReturn(getExtensionField(extension, "addStorage", {
      name: extension.name,
      options: extension.options
    }));
    return extension;
  }
};
function isAndroid$1() {
  return navigator.platform === "Android" || /android/i.test(navigator.userAgent);
}
__name(isAndroid$1, "isAndroid$1");
class NodeView {
  static {
    __name(this, "NodeView");
  }
  constructor(component, props, options2) {
    this.isDragging = false;
    this.component = component;
    this.editor = props.editor;
    this.options = {
      stopEvent: null,
      ignoreMutation: null,
      ...options2
    };
    this.extension = props.extension;
    this.node = props.node;
    this.decorations = props.decorations;
    this.innerDecorations = props.innerDecorations;
    this.view = props.view;
    this.HTMLAttributes = props.HTMLAttributes;
    this.getPos = props.getPos;
    this.mount();
  }
  mount() {
    return;
  }
  get dom() {
    return this.editor.view.dom;
  }
  get contentDOM() {
    return null;
  }
  onDragStart(event) {
    var _a2, _b, _c, _d, _e2, _f, _g;
    const { view } = this.editor;
    const target = event.target;
    const dragHandle = target.nodeType === 3 ? (_a2 = target.parentElement) === null || _a2 === void 0 ? void 0 : _a2.closest("[data-drag-handle]") : target.closest("[data-drag-handle]");
    if (!this.dom || ((_b = this.contentDOM) === null || _b === void 0 ? void 0 : _b.contains(target)) || !dragHandle) {
      return;
    }
    let x2 = 0;
    let y2 = 0;
    if (this.dom !== dragHandle) {
      const domBox = this.dom.getBoundingClientRect();
      const handleBox = dragHandle.getBoundingClientRect();
      const offsetX = (_c = event.offsetX) !== null && _c !== void 0 ? _c : (_d = event.nativeEvent) === null || _d === void 0 ? void 0 : _d.offsetX;
      const offsetY = (_e2 = event.offsetY) !== null && _e2 !== void 0 ? _e2 : (_f = event.nativeEvent) === null || _f === void 0 ? void 0 : _f.offsetY;
      x2 = handleBox.x - domBox.x + offsetX;
      y2 = handleBox.y - domBox.y + offsetY;
    }
    (_g = event.dataTransfer) === null || _g === void 0 ? void 0 : _g.setDragImage(this.dom, x2, y2);
    const pos = this.getPos();
    if (typeof pos !== "number") {
      return;
    }
    const selection = NodeSelection.create(view.state.doc, pos);
    const transaction = view.state.tr.setSelection(selection);
    view.dispatch(transaction);
  }
  stopEvent(event) {
    var _a2;
    if (!this.dom) {
      return false;
    }
    if (typeof this.options.stopEvent === "function") {
      return this.options.stopEvent({ event });
    }
    const target = event.target;
    const isInElement = this.dom.contains(target) && !((_a2 = this.contentDOM) === null || _a2 === void 0 ? void 0 : _a2.contains(target));
    if (!isInElement) {
      return false;
    }
    const isDragEvent = event.type.startsWith("drag");
    const isDropEvent = event.type === "drop";
    const isInput = ["INPUT", "BUTTON", "SELECT", "TEXTAREA"].includes(target.tagName) || target.isContentEditable;
    if (isInput && !isDropEvent && !isDragEvent) {
      return true;
    }
    const { isEditable } = this.editor;
    const { isDragging } = this;
    const isDraggable = !!this.node.type.spec.draggable;
    const isSelectable = NodeSelection.isSelectable(this.node);
    const isCopyEvent = event.type === "copy";
    const isPasteEvent = event.type === "paste";
    const isCutEvent = event.type === "cut";
    const isClickEvent = event.type === "mousedown";
    if (!isDraggable && isSelectable && isDragEvent) {
      event.preventDefault();
    }
    if (isDraggable && isDragEvent && !isDragging) {
      event.preventDefault();
      return false;
    }
    if (isDraggable && isEditable && !isDragging && isClickEvent) {
      const dragHandle = target.closest("[data-drag-handle]");
      const isValidDragHandle = dragHandle && (this.dom === dragHandle || this.dom.contains(dragHandle));
      if (isValidDragHandle) {
        this.isDragging = true;
        document.addEventListener("dragend", () => {
          this.isDragging = false;
        }, { once: true });
        document.addEventListener("drop", () => {
          this.isDragging = false;
        }, { once: true });
        document.addEventListener("mouseup", () => {
          this.isDragging = false;
        }, { once: true });
      }
    }
    if (isDragging || isDropEvent || isCopyEvent || isPasteEvent || isCutEvent || isClickEvent && isSelectable) {
      return false;
    }
    return true;
  }
  /**
   * Called when a DOM [mutation](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) or a selection change happens within the view.
   * @return `false` if the editor should re-read the selection or re-parse the range around the mutation
   * @return `true` if it can safely be ignored.
   */
  ignoreMutation(mutation) {
    if (!this.dom || !this.contentDOM) {
      return true;
    }
    if (typeof this.options.ignoreMutation === "function") {
      return this.options.ignoreMutation({ mutation });
    }
    if (this.node.isLeaf || this.node.isAtom) {
      return true;
    }
    if (mutation.type === "selection") {
      return false;
    }
    if (this.dom.contains(mutation.target) && mutation.type === "childList" && (isiOS() || isAndroid$1()) && this.editor.isFocused) {
      const changedNodes = [
        ...Array.from(mutation.addedNodes),
        ...Array.from(mutation.removedNodes)
      ];
      if (changedNodes.every((node2) => node2.isContentEditable)) {
        return false;
      }
    }
    if (this.contentDOM === mutation.target && mutation.type === "attributes") {
      return true;
    }
    if (this.contentDOM.contains(mutation.target)) {
      return false;
    }
    return true;
  }
  /**
   * Update the attributes of the prosemirror node.
   */
  updateAttributes(attributes) {
    this.editor.commands.command(({ tr: tr2 }) => {
      const pos = this.getPos();
      if (typeof pos !== "number") {
        return false;
      }
      tr2.setNodeMarkup(pos, void 0, {
        ...this.node.attrs,
        ...attributes
      });
      return true;
    });
  }
  /**
   * Delete the node.
   */
  deleteNode() {
    const from2 = this.getPos();
    if (typeof from2 !== "number") {
      return;
    }
    const to = from2 + this.node.nodeSize;
    this.editor.commands.deleteRange({ from: from2, to });
  }
}
function markPasteRule(config2) {
  return new PasteRule({
    find: config2.find,
    handler: /* @__PURE__ */ __name(({ state, range, match: match2, pasteEvent }) => {
      const attributes = callOrReturn(config2.getAttributes, void 0, match2, pasteEvent);
      if (attributes === false || attributes === null) {
        return null;
      }
      const { tr: tr2 } = state;
      const captureGroup = match2[match2.length - 1];
      const fullMatch = match2[0];
      let markEnd = range.to;
      if (captureGroup) {
        const startSpaces = fullMatch.search(/\S/);
        const textStart = range.from + fullMatch.indexOf(captureGroup);
        const textEnd = textStart + captureGroup.length;
        const excludedMarks = getMarksBetween(range.from, range.to, state.doc).filter((item) => {
          const excluded = item.mark.type.excluded;
          return excluded.find((type) => type === config2.type && type !== item.mark.type);
        }).filter((item) => item.to > textStart);
        if (excludedMarks.length) {
          return null;
        }
        if (textEnd < range.to) {
          tr2.delete(textEnd, range.to);
        }
        if (textStart > range.from) {
          tr2.delete(range.from + startSpaces, textStart);
        }
        markEnd = range.from + startSpaces + captureGroup.length;
        tr2.addMark(range.from + startSpaces, markEnd, config2.type.create(attributes || {}));
        tr2.removeStoredMark(config2.type);
      }
    }, "handler")
  });
}
__name(markPasteRule, "markPasteRule");
function escapeForRegEx(string) {
  return string.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&");
}
__name(escapeForRegEx, "escapeForRegEx");
function isString$3(value) {
  return typeof value === "string";
}
__name(isString$3, "isString$3");
function nodePasteRule(config2) {
  return new PasteRule({
    find: config2.find,
    handler({ match: match2, chain, range, pasteEvent }) {
      const attributes = callOrReturn(config2.getAttributes, void 0, match2, pasteEvent);
      const content = callOrReturn(config2.getContent, void 0, attributes);
      if (attributes === false || attributes === null) {
        return null;
      }
      const node2 = { type: config2.type.name, attrs: attributes };
      if (content) {
        node2.content = content;
      }
      if (match2.input) {
        chain().deleteRange(range).insertContentAt(range.from, node2);
      }
    }
  });
}
__name(nodePasteRule, "nodePasteRule");
function textPasteRule(config2) {
  return new PasteRule({
    find: config2.find,
    handler: /* @__PURE__ */ __name(({ state, range, match: match2 }) => {
      let insert = config2.replace;
      let start2 = range.from;
      const end = range.to;
      if (match2[1]) {
        const offset = match2[0].lastIndexOf(match2[1]);
        insert += match2[0].slice(offset + match2[1].length);
        start2 += offset;
        const cutOff = start2 - end;
        if (cutOff > 0) {
          insert = match2[0].slice(offset - cutOff, offset) + insert;
          start2 = end;
        }
      }
      state.tr.insertText(insert, start2, end);
    }, "handler")
  });
}
__name(textPasteRule, "textPasteRule");
class Tracker {
  static {
    __name(this, "Tracker");
  }
  constructor(transaction) {
    this.transaction = transaction;
    this.currentStep = this.transaction.steps.length;
  }
  map(position) {
    let deleted = false;
    const mappedPosition = this.transaction.steps.slice(this.currentStep).reduce((newPosition, step) => {
      const mapResult = step.getMap().mapResult(newPosition);
      if (mapResult.deleted) {
        deleted = true;
      }
      return mapResult.pos;
    }, position);
    return {
      position: mappedPosition,
      deleted
    };
  }
}
const encodedTlds = " ögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2olterskluwer11odside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2";
const encodedUtlds = "ελ1υ2бг1ел3дети4ею2католик6ом3мкд2он1сква6онлайн5рг3рус2ф2сайт3рб3укр3қаз3հայ3ישראל5קום3ابوظبي5رامكو5لاردن4بحرين5جزائر5سعودية6عليان5مغرب5مارات5یران5بارت2زار4يتك3ھارت5تونس4سودان3رية5شبكة4عراق2ب2مان4فلسطين6قطر3كاثوليك6وم3مصر2ليسيا5وريتانيا7قع4همراه5پاکستان7ڀارت4कॉम3नेट3भारत0म्3ोत5संगठन5বাংলা5ভারত2ৰত4ਭਾਰਤ4ભારત4ଭାରତ4இந்தியா6லங்கை6சிங்கப்பூர்11భారత్5ಭಾರತ4ഭാരതം5ලංකා4คอม3ไทย3ລາວ3გე2みんな3アマゾン4クラウド4グーグル4コム2ストア3セール3ファッション6ポイント4世界2中信1国1國1文网3亚马逊3企业2佛山2信息2健康2八卦2公司1益2台湾1灣2商城1店1标2嘉里0大酒店5在线2大拿2天主教3娱乐2家電2广东2微博2慈善2我爱你3手机2招聘2政务1府2新加坡2闻2时尚2書籍2机构2淡马锡3游戏2澳門2点看2移动2组织机构4网址1店1站1络2联通2谷歌2购物2通販2集团2電訊盈科4飞利浦3食品2餐厅2香格里拉3港2닷넷1컴2삼성2한국2";
const assign$2 = /* @__PURE__ */ __name((target, properties) => {
  for (const key in properties) {
    target[key] = properties[key];
  }
  return target;
}, "assign$2");
const numeric = "numeric";
const ascii = "ascii";
const alpha = "alpha";
const asciinumeric = "asciinumeric";
const alphanumeric = "alphanumeric";
const domain = "domain";
const emoji = "emoji";
const scheme = "scheme";
const slashscheme = "slashscheme";
const whitespace = "whitespace";
function registerGroup(name2, groups) {
  if (!(name2 in groups)) {
    groups[name2] = [];
  }
  return groups[name2];
}
__name(registerGroup, "registerGroup");
function addToGroups(t2, flags, groups) {
  if (flags[numeric]) {
    flags[asciinumeric] = true;
    flags[alphanumeric] = true;
  }
  if (flags[ascii]) {
    flags[asciinumeric] = true;
    flags[alpha] = true;
  }
  if (flags[asciinumeric]) {
    flags[alphanumeric] = true;
  }
  if (flags[alpha]) {
    flags[alphanumeric] = true;
  }
  if (flags[alphanumeric]) {
    flags[domain] = true;
  }
  if (flags[emoji]) {
    flags[domain] = true;
  }
  for (const k2 in flags) {
    const group = registerGroup(k2, groups);
    if (group.indexOf(t2) < 0) {
      group.push(t2);
    }
  }
}
__name(addToGroups, "addToGroups");
function flagsForToken(t2, groups) {
  const result = {};
  for (const c2 in groups) {
    if (groups[c2].indexOf(t2) >= 0) {
      result[c2] = true;
    }
  }
  return result;
}
__name(flagsForToken, "flagsForToken");
function State(token = null) {
  this.j = {};
  this.jr = [];
  this.jd = null;
  this.t = token;
}
__name(State, "State");
State.groups = {};
State.prototype = {
  accepts() {
    return !!this.t;
  },
  /**
   * Follow an existing transition from the given input to the next state.
   * Does not mutate.
   * @param {string} input character or token type to transition on
   * @returns {?State<T>} the next state, if any
   */
  go(input) {
    const state = this;
    const nextState = state.j[input];
    if (nextState) {
      return nextState;
    }
    for (let i2 = 0; i2 < state.jr.length; i2++) {
      const regex2 = state.jr[i2][0];
      const nextState2 = state.jr[i2][1];
      if (nextState2 && regex2.test(input)) {
        return nextState2;
      }
    }
    return state.jd;
  },
  /**
   * Whether the state has a transition for the given input. Set the second
   * argument to true to only look for an exact match (and not a default or
   * regular-expression-based transition)
   * @param {string} input
   * @param {boolean} exactOnly
   */
  has(input, exactOnly = false) {
    return exactOnly ? input in this.j : !!this.go(input);
  },
  /**
   * Short for "transition all"; create a transition from the array of items
   * in the given list to the same final resulting state.
   * @param {string | string[]} inputs Group of inputs to transition on
   * @param {Transition<T> | State<T>} [next] Transition options
   * @param {Flags} [flags] Collections flags to add token to
   * @param {Collections<T>} [groups] Master list of token groups
   */
  ta(inputs, next, flags, groups) {
    for (let i2 = 0; i2 < inputs.length; i2++) {
      this.tt(inputs[i2], next, flags, groups);
    }
  },
  /**
   * Short for "take regexp transition"; defines a transition for this state
   * when it encounters a token which matches the given regular expression
   * @param {RegExp} regexp Regular expression transition (populate first)
   * @param {T | State<T>} [next] Transition options
   * @param {Flags} [flags] Collections flags to add token to
   * @param {Collections<T>} [groups] Master list of token groups
   * @returns {State<T>} taken after the given input
   */
  tr(regexp2, next, flags, groups) {
    groups = groups || State.groups;
    let nextState;
    if (next && next.j) {
      nextState = next;
    } else {
      nextState = new State(next);
      if (flags && groups) {
        addToGroups(next, flags, groups);
      }
    }
    this.jr.push([regexp2, nextState]);
    return nextState;
  },
  /**
   * Short for "take transitions", will take as many sequential transitions as
   * the length of the given input and returns the
   * resulting final state.
   * @param {string | string[]} input
   * @param {T | State<T>} [next] Transition options
   * @param {Flags} [flags] Collections flags to add token to
   * @param {Collections<T>} [groups] Master list of token groups
   * @returns {State<T>} taken after the given input
   */
  ts(input, next, flags, groups) {
    let state = this;
    const len = input.length;
    if (!len) {
      return state;
    }
    for (let i2 = 0; i2 < len - 1; i2++) {
      state = state.tt(input[i2]);
    }
    return state.tt(input[len - 1], next, flags, groups);
  },
  /**
   * Short for "take transition", this is a method for building/working with
   * state machines.
   *
   * If a state already exists for the given input, returns it.
   *
   * If a token is specified, that state will emit that token when reached by
   * the linkify engine.
   *
   * If no state exists, it will be initialized with some default transitions
   * that resemble existing default transitions.
   *
   * If a state is given for the second argument, that state will be
   * transitioned to on the given input regardless of what that input
   * previously did.
   *
   * Specify a token group flags to define groups that this token belongs to.
   * The token will be added to corresponding entires in the given groups
   * object.
   *
   * @param {string} input character, token type to transition on
   * @param {T | State<T>} [next] Transition options
   * @param {Flags} [flags] Collections flags to add token to
   * @param {Collections<T>} [groups] Master list of groups
   * @returns {State<T>} taken after the given input
   */
  tt(input, next, flags, groups) {
    groups = groups || State.groups;
    const state = this;
    if (next && next.j) {
      state.j[input] = next;
      return next;
    }
    const t2 = next;
    let nextState, templateState = state.go(input);
    if (templateState) {
      nextState = new State();
      assign$2(nextState.j, templateState.j);
      nextState.jr.push.apply(nextState.jr, templateState.jr);
      nextState.jd = templateState.jd;
      nextState.t = templateState.t;
    } else {
      nextState = new State();
    }
    if (t2) {
      if (groups) {
        if (nextState.t && typeof nextState.t === "string") {
          const allFlags = assign$2(flagsForToken(nextState.t, groups), flags);
          addToGroups(t2, allFlags, groups);
        } else if (flags) {
          addToGroups(t2, flags, groups);
        }
      }
      nextState.t = t2;
    }
    state.j[input] = nextState;
    return nextState;
  }
};
const ta = /* @__PURE__ */ __name((state, input, next, flags, groups) => state.ta(input, next, flags, groups), "ta");
const tr = /* @__PURE__ */ __name((state, regexp2, next, flags, groups) => state.tr(regexp2, next, flags, groups), "tr");
const ts = /* @__PURE__ */ __name((state, input, next, flags, groups) => state.ts(input, next, flags, groups), "ts");
const tt = /* @__PURE__ */ __name((state, input, next, flags, groups) => state.tt(input, next, flags, groups), "tt");
const WORD = "WORD";
const UWORD = "UWORD";
const ASCIINUMERICAL = "ASCIINUMERICAL";
const ALPHANUMERICAL = "ALPHANUMERICAL";
const LOCALHOST = "LOCALHOST";
const TLD = "TLD";
const UTLD = "UTLD";
const SCHEME = "SCHEME";
const SLASH_SCHEME = "SLASH_SCHEME";
const NUM = "NUM";
const WS = "WS";
const NL = "NL";
const OPENBRACE = "OPENBRACE";
const CLOSEBRACE = "CLOSEBRACE";
const OPENBRACKET = "OPENBRACKET";
const CLOSEBRACKET = "CLOSEBRACKET";
const OPENPAREN = "OPENPAREN";
const CLOSEPAREN = "CLOSEPAREN";
const OPENANGLEBRACKET = "OPENANGLEBRACKET";
const CLOSEANGLEBRACKET = "CLOSEANGLEBRACKET";
const FULLWIDTHLEFTPAREN = "FULLWIDTHLEFTPAREN";
const FULLWIDTHRIGHTPAREN = "FULLWIDTHRIGHTPAREN";
const LEFTCORNERBRACKET = "LEFTCORNERBRACKET";
const RIGHTCORNERBRACKET = "RIGHTCORNERBRACKET";
const LEFTWHITECORNERBRACKET = "LEFTWHITECORNERBRACKET";
const RIGHTWHITECORNERBRACKET = "RIGHTWHITECORNERBRACKET";
const FULLWIDTHLESSTHAN = "FULLWIDTHLESSTHAN";
const FULLWIDTHGREATERTHAN = "FULLWIDTHGREATERTHAN";
const AMPERSAND = "AMPERSAND";
const APOSTROPHE$1 = "APOSTROPHE";
const ASTERISK = "ASTERISK";
const AT = "AT";
const BACKSLASH = "BACKSLASH";
const BACKTICK = "BACKTICK";
const CARET = "CARET";
const COLON = "COLON";
const COMMA = "COMMA";
const DOLLAR = "DOLLAR";
const DOT = "DOT";
const EQUALS = "EQUALS";
const EXCLAMATION = "EXCLAMATION";
const HYPHEN = "HYPHEN";
const PERCENT = "PERCENT";
const PIPE = "PIPE";
const PLUS = "PLUS";
const POUND = "POUND";
const QUERY = "QUERY";
const QUOTE = "QUOTE";
const FULLWIDTHMIDDLEDOT = "FULLWIDTHMIDDLEDOT";
const SEMI = "SEMI";
const SLASH = "SLASH";
const TILDE = "TILDE";
const UNDERSCORE = "UNDERSCORE";
const EMOJI$1 = "EMOJI";
const SYM = "SYM";
var tk = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  WORD,
  UWORD,
  ASCIINUMERICAL,
  ALPHANUMERICAL,
  LOCALHOST,
  TLD,
  UTLD,
  SCHEME,
  SLASH_SCHEME,
  NUM,
  WS,
  NL,
  OPENBRACE,
  CLOSEBRACE,
  OPENBRACKET,
  CLOSEBRACKET,
  OPENPAREN,
  CLOSEPAREN,
  OPENANGLEBRACKET,
  CLOSEANGLEBRACKET,
  FULLWIDTHLEFTPAREN,
  FULLWIDTHRIGHTPAREN,
  LEFTCORNERBRACKET,
  RIGHTCORNERBRACKET,
  LEFTWHITECORNERBRACKET,
  RIGHTWHITECORNERBRACKET,
  FULLWIDTHLESSTHAN,
  FULLWIDTHGREATERTHAN,
  AMPERSAND,
  APOSTROPHE: APOSTROPHE$1,
  ASTERISK,
  AT,
  BACKSLASH,
  BACKTICK,
  CARET,
  COLON,
  COMMA,
  DOLLAR,
  DOT,
  EQUALS,
  EXCLAMATION,
  HYPHEN,
  PERCENT,
  PIPE,
  PLUS,
  POUND,
  QUERY,
  QUOTE,
  FULLWIDTHMIDDLEDOT,
  SEMI,
  SLASH,
  TILDE,
  UNDERSCORE,
  EMOJI: EMOJI$1,
  SYM
});
const ASCII_LETTER = /[a-z]/;
const LETTER = /\p{L}/u;
const EMOJI = /\p{Emoji}/u;
const EMOJI_VARIATION$1 = /\ufe0f/;
const DIGIT = /\d/;
const SPACE$1 = /\s/;
var regexp = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  ASCII_LETTER,
  LETTER,
  EMOJI,
  EMOJI_VARIATION: EMOJI_VARIATION$1,
  DIGIT,
  SPACE: SPACE$1
});
const CR = "\r";
const LF = "\n";
const EMOJI_VARIATION = "️";
const EMOJI_JOINER = "‍";
const OBJECT_REPLACEMENT = "￼";
let tlds = null, utlds = null;
function init$2(customSchemes = []) {
  const groups = {};
  State.groups = groups;
  const Start = new State();
  if (tlds == null) {
    tlds = decodeTlds(encodedTlds);
  }
  if (utlds == null) {
    utlds = decodeTlds(encodedUtlds);
  }
  tt(Start, "'", APOSTROPHE$1);
  tt(Start, "{", OPENBRACE);
  tt(Start, "}", CLOSEBRACE);
  tt(Start, "[", OPENBRACKET);
  tt(Start, "]", CLOSEBRACKET);
  tt(Start, "(", OPENPAREN);
  tt(Start, ")", CLOSEPAREN);
  tt(Start, "<", OPENANGLEBRACKET);
  tt(Start, ">", CLOSEANGLEBRACKET);
  tt(Start, "（", FULLWIDTHLEFTPAREN);
  tt(Start, "）", FULLWIDTHRIGHTPAREN);
  tt(Start, "「", LEFTCORNERBRACKET);
  tt(Start, "」", RIGHTCORNERBRACKET);
  tt(Start, "『", LEFTWHITECORNERBRACKET);
  tt(Start, "』", RIGHTWHITECORNERBRACKET);
  tt(Start, "＜", FULLWIDTHLESSTHAN);
  tt(Start, "＞", FULLWIDTHGREATERTHAN);
  tt(Start, "&", AMPERSAND);
  tt(Start, "*", ASTERISK);
  tt(Start, "@", AT);
  tt(Start, "`", BACKTICK);
  tt(Start, "^", CARET);
  tt(Start, ":", COLON);
  tt(Start, ",", COMMA);
  tt(Start, "$", DOLLAR);
  tt(Start, ".", DOT);
  tt(Start, "=", EQUALS);
  tt(Start, "!", EXCLAMATION);
  tt(Start, "-", HYPHEN);
  tt(Start, "%", PERCENT);
  tt(Start, "|", PIPE);
  tt(Start, "+", PLUS);
  tt(Start, "#", POUND);
  tt(Start, "?", QUERY);
  tt(Start, '"', QUOTE);
  tt(Start, "/", SLASH);
  tt(Start, ";", SEMI);
  tt(Start, "~", TILDE);
  tt(Start, "_", UNDERSCORE);
  tt(Start, "\\", BACKSLASH);
  tt(Start, "・", FULLWIDTHMIDDLEDOT);
  const Num = tr(Start, DIGIT, NUM, {
    [numeric]: true
  });
  tr(Num, DIGIT, Num);
  const Asciinumeric = tr(Num, ASCII_LETTER, ASCIINUMERICAL, {
    [asciinumeric]: true
  });
  const Alphanumeric = tr(Num, LETTER, ALPHANUMERICAL, {
    [alphanumeric]: true
  });
  const Word = tr(Start, ASCII_LETTER, WORD, {
    [ascii]: true
  });
  tr(Word, DIGIT, Asciinumeric);
  tr(Word, ASCII_LETTER, Word);
  tr(Asciinumeric, DIGIT, Asciinumeric);
  tr(Asciinumeric, ASCII_LETTER, Asciinumeric);
  const UWord = tr(Start, LETTER, UWORD, {
    [alpha]: true
  });
  tr(UWord, ASCII_LETTER);
  tr(UWord, DIGIT, Alphanumeric);
  tr(UWord, LETTER, UWord);
  tr(Alphanumeric, DIGIT, Alphanumeric);
  tr(Alphanumeric, ASCII_LETTER);
  tr(Alphanumeric, LETTER, Alphanumeric);
  const Nl2 = tt(Start, LF, NL, {
    [whitespace]: true
  });
  const Cr = tt(Start, CR, WS, {
    [whitespace]: true
  });
  const Ws = tr(Start, SPACE$1, WS, {
    [whitespace]: true
  });
  tt(Start, OBJECT_REPLACEMENT, Ws);
  tt(Cr, LF, Nl2);
  tt(Cr, OBJECT_REPLACEMENT, Ws);
  tr(Cr, SPACE$1, Ws);
  tt(Ws, CR);
  tt(Ws, LF);
  tr(Ws, SPACE$1, Ws);
  tt(Ws, OBJECT_REPLACEMENT, Ws);
  const Emoji = tr(Start, EMOJI, EMOJI$1, {
    [emoji]: true
  });
  tt(Emoji, "#");
  tr(Emoji, EMOJI, Emoji);
  tt(Emoji, EMOJI_VARIATION, Emoji);
  const EmojiJoiner = tt(Emoji, EMOJI_JOINER);
  tt(EmojiJoiner, "#");
  tr(EmojiJoiner, EMOJI, Emoji);
  const wordjr = [[ASCII_LETTER, Word], [DIGIT, Asciinumeric]];
  const uwordjr = [[ASCII_LETTER, null], [LETTER, UWord], [DIGIT, Alphanumeric]];
  for (let i2 = 0; i2 < tlds.length; i2++) {
    fastts(Start, tlds[i2], TLD, WORD, wordjr);
  }
  for (let i2 = 0; i2 < utlds.length; i2++) {
    fastts(Start, utlds[i2], UTLD, UWORD, uwordjr);
  }
  addToGroups(TLD, {
    tld: true,
    ascii: true
  }, groups);
  addToGroups(UTLD, {
    utld: true,
    alpha: true
  }, groups);
  fastts(Start, "file", SCHEME, WORD, wordjr);
  fastts(Start, "mailto", SCHEME, WORD, wordjr);
  fastts(Start, "http", SLASH_SCHEME, WORD, wordjr);
  fastts(Start, "https", SLASH_SCHEME, WORD, wordjr);
  fastts(Start, "ftp", SLASH_SCHEME, WORD, wordjr);
  fastts(Start, "ftps", SLASH_SCHEME, WORD, wordjr);
  addToGroups(SCHEME, {
    scheme: true,
    ascii: true
  }, groups);
  addToGroups(SLASH_SCHEME, {
    slashscheme: true,
    ascii: true
  }, groups);
  customSchemes = customSchemes.sort((a2, b2) => a2[0] > b2[0] ? 1 : -1);
  for (let i2 = 0; i2 < customSchemes.length; i2++) {
    const sch = customSchemes[i2][0];
    const optionalSlashSlash = customSchemes[i2][1];
    const flags = optionalSlashSlash ? {
      [scheme]: true
    } : {
      [slashscheme]: true
    };
    if (sch.indexOf("-") >= 0) {
      flags[domain] = true;
    } else if (!ASCII_LETTER.test(sch)) {
      flags[numeric] = true;
    } else if (DIGIT.test(sch)) {
      flags[asciinumeric] = true;
    } else {
      flags[ascii] = true;
    }
    ts(Start, sch, sch, flags);
  }
  ts(Start, "localhost", LOCALHOST, {
    ascii: true
  });
  Start.jd = new State(SYM);
  return {
    start: Start,
    tokens: assign$2({
      groups
    }, tk)
  };
}
__name(init$2, "init$2");
function run$1(start2, str) {
  const iterable = stringToArray(str.replace(/[A-Z]/g, (c2) => c2.toLowerCase()));
  const charCount = iterable.length;
  const tokens = [];
  let cursor = 0;
  let charCursor = 0;
  while (charCursor < charCount) {
    let state = start2;
    let nextState = null;
    let tokenLength = 0;
    let latestAccepting = null;
    let sinceAccepts = -1;
    let charsSinceAccepts = -1;
    while (charCursor < charCount && (nextState = state.go(iterable[charCursor]))) {
      state = nextState;
      if (state.accepts()) {
        sinceAccepts = 0;
        charsSinceAccepts = 0;
        latestAccepting = state;
      } else if (sinceAccepts >= 0) {
        sinceAccepts += iterable[charCursor].length;
        charsSinceAccepts++;
      }
      tokenLength += iterable[charCursor].length;
      cursor += iterable[charCursor].length;
      charCursor++;
    }
    cursor -= sinceAccepts;
    charCursor -= charsSinceAccepts;
    tokenLength -= sinceAccepts;
    tokens.push({
      t: latestAccepting.t,
      // token type/name
      v: str.slice(cursor - tokenLength, cursor),
      // string value
      s: cursor - tokenLength,
      // start index
      e: cursor
      // end index (excluding)
    });
  }
  return tokens;
}
__name(run$1, "run$1");
function stringToArray(str) {
  const result = [];
  const len = str.length;
  let index2 = 0;
  while (index2 < len) {
    let first2 = str.charCodeAt(index2);
    let second;
    let char = first2 < 55296 || first2 > 56319 || index2 + 1 === len || (second = str.charCodeAt(index2 + 1)) < 56320 || second > 57343 ? str[index2] : str.slice(index2, index2 + 2);
    result.push(char);
    index2 += char.length;
  }
  return result;
}
__name(stringToArray, "stringToArray");
function fastts(state, input, t2, defaultt, jr) {
  let next;
  const len = input.length;
  for (let i2 = 0; i2 < len - 1; i2++) {
    const char = input[i2];
    if (state.j[char]) {
      next = state.j[char];
    } else {
      next = new State(defaultt);
      next.jr = jr.slice();
      state.j[char] = next;
    }
    state = next;
  }
  next = new State(t2);
  next.jr = jr.slice();
  state.j[input[len - 1]] = next;
  return next;
}
__name(fastts, "fastts");
function decodeTlds(encoded) {
  const words = [];
  const stack = [];
  let i2 = 0;
  let digits = "0123456789";
  while (i2 < encoded.length) {
    let popDigitCount = 0;
    while (digits.indexOf(encoded[i2 + popDigitCount]) >= 0) {
      popDigitCount++;
    }
    if (popDigitCount > 0) {
      words.push(stack.join(""));
      for (let popCount = parseInt(encoded.substring(i2, i2 + popDigitCount), 10); popCount > 0; popCount--) {
        stack.pop();
      }
      i2 += popDigitCount;
    } else {
      stack.push(encoded[i2]);
      i2++;
    }
  }
  return words;
}
__name(decodeTlds, "decodeTlds");
const defaults = {
  defaultProtocol: "http",
  events: null,
  format: noop,
  formatHref: noop,
  nl2br: false,
  tagName: "a",
  target: null,
  rel: null,
  validate: true,
  truncate: Infinity,
  className: null,
  attributes: null,
  ignoreTags: [],
  render: null
};
function Options(opts, defaultRender = null) {
  let o2 = assign$2({}, defaults);
  if (opts) {
    o2 = assign$2(o2, opts instanceof Options ? opts.o : opts);
  }
  const ignoredTags = o2.ignoreTags;
  const uppercaseIgnoredTags = [];
  for (let i2 = 0; i2 < ignoredTags.length; i2++) {
    uppercaseIgnoredTags.push(ignoredTags[i2].toUpperCase());
  }
  this.o = o2;
  if (defaultRender) {
    this.defaultRender = defaultRender;
  }
  this.ignoreTags = uppercaseIgnoredTags;
}
__name(Options, "Options");
Options.prototype = {
  o: defaults,
  /**
   * @type string[]
   */
  ignoreTags: [],
  /**
   * @param {IntermediateRepresentation} ir
   * @returns {any}
   */
  defaultRender(ir) {
    return ir;
  },
  /**
   * Returns true or false based on whether a token should be displayed as a
   * link based on the user options.
   * @param {MultiToken} token
   * @returns {boolean}
   */
  check(token) {
    return this.get("validate", token.toString(), token);
  },
  // Private methods
  /**
   * Resolve an option's value based on the value of the option and the given
   * params. If operator and token are specified and the target option is
   * callable, automatically calls the function with the given argument.
   * @template {keyof Opts} K
   * @param {K} key Name of option to use
   * @param {string} [operator] will be passed to the target option if it's a
   * function. If not specified, RAW function value gets returned
   * @param {MultiToken} [token] The token from linkify.tokenize
   * @returns {Opts[K] | any}
   */
  get(key, operator, token) {
    const isCallable = operator != null;
    let option = this.o[key];
    if (!option) {
      return option;
    }
    if (typeof option === "object") {
      option = token.t in option ? option[token.t] : defaults[key];
      if (typeof option === "function" && isCallable) {
        option = option(operator, token);
      }
    } else if (typeof option === "function" && isCallable) {
      option = option(operator, token.t, token);
    }
    return option;
  },
  /**
   * @template {keyof Opts} L
   * @param {L} key Name of options object to use
   * @param {string} [operator]
   * @param {MultiToken} [token]
   * @returns {Opts[L] | any}
   */
  getObj(key, operator, token) {
    let obj = this.o[key];
    if (typeof obj === "function" && operator != null) {
      obj = obj(operator, token.t, token);
    }
    return obj;
  },
  /**
   * Convert the given token to a rendered element that may be added to the
   * calling-interface's DOM
   * @param {MultiToken} token Token to render to an HTML element
   * @returns {any} Render result; e.g., HTML string, DOM element, React
   *   Component, etc.
   */
  render(token) {
    const ir = token.render(this);
    const renderFn = this.get("render", null, token) || this.defaultRender;
    return renderFn(ir, token.t, token);
  }
};
function noop(val) {
  return val;
}
__name(noop, "noop");
var options = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  defaults,
  Options,
  assign: assign$2
});
function MultiToken(value, tokens) {
  this.t = "token";
  this.v = value;
  this.tk = tokens;
}
__name(MultiToken, "MultiToken");
MultiToken.prototype = {
  isLink: false,
  /**
   * Return the string this token represents.
   * @return {string}
   */
  toString() {
    return this.v;
  },
  /**
   * What should the value for this token be in the `href` HTML attribute?
   * Returns the `.toString` value by default.
   * @param {string} [scheme]
   * @return {string}
   */
  toHref(scheme2) {
    return this.toString();
  },
  /**
   * @param {Options} options Formatting options
   * @returns {string}
   */
  toFormattedString(options2) {
    const val = this.toString();
    const truncate2 = options2.get("truncate", val, this);
    const formatted = options2.get("format", val, this);
    return truncate2 && formatted.length > truncate2 ? formatted.substring(0, truncate2) + "…" : formatted;
  },
  /**
   *
   * @param {Options} options
   * @returns {string}
   */
  toFormattedHref(options2) {
    return options2.get("formatHref", this.toHref(options2.get("defaultProtocol")), this);
  },
  /**
   * The start index of this token in the original input string
   * @returns {number}
   */
  startIndex() {
    return this.tk[0].s;
  },
  /**
   * The end index of this token in the original input string (up to this
   * index but not including it)
   * @returns {number}
   */
  endIndex() {
    return this.tk[this.tk.length - 1].e;
  },
  /**
  	Returns an object  of relevant values for this token, which includes keys
  	* type - Kind of token ('url', 'email', etc.)
  	* value - Original text
  	* href - The value that should be added to the anchor tag's href
  		attribute
  		@method toObject
  	@param {string} [protocol] `'http'` by default
  */
  toObject(protocol = defaults.defaultProtocol) {
    return {
      type: this.t,
      value: this.toString(),
      isLink: this.isLink,
      href: this.toHref(protocol),
      start: this.startIndex(),
      end: this.endIndex()
    };
  },
  /**
   *
   * @param {Options} options Formatting option
   */
  toFormattedObject(options2) {
    return {
      type: this.t,
      value: this.toFormattedString(options2),
      isLink: this.isLink,
      href: this.toFormattedHref(options2),
      start: this.startIndex(),
      end: this.endIndex()
    };
  },
  /**
   * Whether this token should be rendered as a link according to the given options
   * @param {Options} options
   * @returns {boolean}
   */
  validate(options2) {
    return options2.get("validate", this.toString(), this);
  },
  /**
   * Return an object that represents how this link should be rendered.
   * @param {Options} options Formattinng options
   */
  render(options2) {
    const token = this;
    const href = this.toHref(options2.get("defaultProtocol"));
    const formattedHref = options2.get("formatHref", href, this);
    const tagName = options2.get("tagName", href, token);
    const content = this.toFormattedString(options2);
    const attributes = {};
    const className = options2.get("className", href, token);
    const target = options2.get("target", href, token);
    const rel = options2.get("rel", href, token);
    const attrs2 = options2.getObj("attributes", href, token);
    const eventListeners = options2.getObj("events", href, token);
    attributes.href = formattedHref;
    if (className) {
      attributes.class = className;
    }
    if (target) {
      attributes.target = target;
    }
    if (rel) {
      attributes.rel = rel;
    }
    if (attrs2) {
      assign$2(attributes, attrs2);
    }
    return {
      tagName,
      attributes,
      content,
      eventListeners
    };
  }
};
function createTokenClass(type, props) {
  class Token2 extends MultiToken {
    static {
      __name(this, "Token");
    }
    constructor(value, tokens) {
      super(value, tokens);
      this.t = type;
    }
  }
  for (const p2 in props) {
    Token2.prototype[p2] = props[p2];
  }
  Token2.t = type;
  return Token2;
}
__name(createTokenClass, "createTokenClass");
const Email = createTokenClass("email", {
  isLink: true,
  toHref() {
    return "mailto:" + this.toString();
  }
});
const Text$3 = createTokenClass("text");
const Nl = createTokenClass("nl");
const Url$1 = createTokenClass("url", {
  isLink: true,
  /**
  	Lowercases relevant parts of the domain and adds the protocol if
  	required. Note that this will not escape unsafe HTML characters in the
  	URL.
  		@param {string} [scheme] default scheme (e.g., 'https')
  	@return {string} the full href
  */
  toHref(scheme2 = defaults.defaultProtocol) {
    return this.hasProtocol() ? this.v : `${scheme2}://${this.v}`;
  },
  /**
   * Check whether this URL token has a protocol
   * @return {boolean}
   */
  hasProtocol() {
    const tokens = this.tk;
    return tokens.length >= 2 && tokens[0].t !== LOCALHOST && tokens[1].t === COLON;
  }
});
var multi = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  MultiToken,
  Base: MultiToken,
  createTokenClass,
  Email,
  Text: Text$3,
  Nl,
  Url: Url$1
});
const makeState = /* @__PURE__ */ __name((arg) => new State(arg), "makeState");
function init$1({
  groups
}) {
  const qsAccepting = groups.domain.concat([AMPERSAND, ASTERISK, AT, BACKSLASH, BACKTICK, CARET, DOLLAR, EQUALS, HYPHEN, NUM, PERCENT, PIPE, PLUS, POUND, SLASH, SYM, TILDE, UNDERSCORE]);
  const qsNonAccepting = [COLON, COMMA, DOT, EXCLAMATION, PERCENT, QUERY, QUOTE, SEMI, OPENANGLEBRACKET, CLOSEANGLEBRACKET, OPENBRACE, CLOSEBRACE, CLOSEBRACKET, OPENBRACKET, OPENPAREN, CLOSEPAREN, FULLWIDTHLEFTPAREN, FULLWIDTHRIGHTPAREN, LEFTCORNERBRACKET, RIGHTCORNERBRACKET, LEFTWHITECORNERBRACKET, RIGHTWHITECORNERBRACKET, FULLWIDTHLESSTHAN, FULLWIDTHGREATERTHAN];
  const localpartAccepting = [AMPERSAND, APOSTROPHE$1, ASTERISK, BACKSLASH, BACKTICK, CARET, DOLLAR, EQUALS, HYPHEN, OPENBRACE, CLOSEBRACE, PERCENT, PIPE, PLUS, POUND, QUERY, SLASH, SYM, TILDE, UNDERSCORE];
  const Start = makeState();
  const Localpart = tt(Start, TILDE);
  ta(Localpart, localpartAccepting, Localpart);
  ta(Localpart, groups.domain, Localpart);
  const Domain = makeState(), Scheme = makeState(), SlashScheme = makeState();
  ta(Start, groups.domain, Domain);
  ta(Start, groups.scheme, Scheme);
  ta(Start, groups.slashscheme, SlashScheme);
  ta(Domain, localpartAccepting, Localpart);
  ta(Domain, groups.domain, Domain);
  const LocalpartAt = tt(Domain, AT);
  tt(Localpart, AT, LocalpartAt);
  tt(Scheme, AT, LocalpartAt);
  tt(SlashScheme, AT, LocalpartAt);
  const LocalpartDot = tt(Localpart, DOT);
  ta(LocalpartDot, localpartAccepting, Localpart);
  ta(LocalpartDot, groups.domain, Localpart);
  const EmailDomain = makeState();
  ta(LocalpartAt, groups.domain, EmailDomain);
  ta(EmailDomain, groups.domain, EmailDomain);
  const EmailDomainDot = tt(EmailDomain, DOT);
  ta(EmailDomainDot, groups.domain, EmailDomain);
  const Email$1 = makeState(Email);
  ta(EmailDomainDot, groups.tld, Email$1);
  ta(EmailDomainDot, groups.utld, Email$1);
  tt(LocalpartAt, LOCALHOST, Email$1);
  const EmailDomainHyphen = tt(EmailDomain, HYPHEN);
  tt(EmailDomainHyphen, HYPHEN, EmailDomainHyphen);
  ta(EmailDomainHyphen, groups.domain, EmailDomain);
  ta(Email$1, groups.domain, EmailDomain);
  tt(Email$1, DOT, EmailDomainDot);
  tt(Email$1, HYPHEN, EmailDomainHyphen);
  const EmailColon = tt(Email$1, COLON);
  ta(EmailColon, groups.numeric, Email);
  const DomainHyphen = tt(Domain, HYPHEN);
  const DomainDot = tt(Domain, DOT);
  tt(DomainHyphen, HYPHEN, DomainHyphen);
  ta(DomainHyphen, groups.domain, Domain);
  ta(DomainDot, localpartAccepting, Localpart);
  ta(DomainDot, groups.domain, Domain);
  const DomainDotTld = makeState(Url$1);
  ta(DomainDot, groups.tld, DomainDotTld);
  ta(DomainDot, groups.utld, DomainDotTld);
  ta(DomainDotTld, groups.domain, Domain);
  ta(DomainDotTld, localpartAccepting, Localpart);
  tt(DomainDotTld, DOT, DomainDot);
  tt(DomainDotTld, HYPHEN, DomainHyphen);
  tt(DomainDotTld, AT, LocalpartAt);
  const DomainDotTldColon = tt(DomainDotTld, COLON);
  const DomainDotTldColonPort = makeState(Url$1);
  ta(DomainDotTldColon, groups.numeric, DomainDotTldColonPort);
  const Url$1$1 = makeState(Url$1);
  const UrlNonaccept = makeState();
  ta(Url$1$1, qsAccepting, Url$1$1);
  ta(Url$1$1, qsNonAccepting, UrlNonaccept);
  ta(UrlNonaccept, qsAccepting, Url$1$1);
  ta(UrlNonaccept, qsNonAccepting, UrlNonaccept);
  tt(DomainDotTld, SLASH, Url$1$1);
  tt(DomainDotTldColonPort, SLASH, Url$1$1);
  const SchemeColon = tt(Scheme, COLON);
  const SlashSchemeColon = tt(SlashScheme, COLON);
  const SlashSchemeColonSlash = tt(SlashSchemeColon, SLASH);
  const UriPrefix = tt(SlashSchemeColonSlash, SLASH);
  ta(Scheme, groups.domain, Domain);
  tt(Scheme, DOT, DomainDot);
  tt(Scheme, HYPHEN, DomainHyphen);
  ta(SlashScheme, groups.domain, Domain);
  tt(SlashScheme, DOT, DomainDot);
  tt(SlashScheme, HYPHEN, DomainHyphen);
  ta(SchemeColon, groups.domain, Url$1$1);
  tt(SchemeColon, SLASH, Url$1$1);
  tt(SchemeColon, QUERY, Url$1$1);
  ta(UriPrefix, groups.domain, Url$1$1);
  ta(UriPrefix, qsAccepting, Url$1$1);
  tt(UriPrefix, SLASH, Url$1$1);
  const bracketPairs = [
    [OPENBRACE, CLOSEBRACE],
    // {}
    [OPENBRACKET, CLOSEBRACKET],
    // []
    [OPENPAREN, CLOSEPAREN],
    // ()
    [OPENANGLEBRACKET, CLOSEANGLEBRACKET],
    // <>
    [FULLWIDTHLEFTPAREN, FULLWIDTHRIGHTPAREN],
    // （）
    [LEFTCORNERBRACKET, RIGHTCORNERBRACKET],
    // 「」
    [LEFTWHITECORNERBRACKET, RIGHTWHITECORNERBRACKET],
    // 『』
    [FULLWIDTHLESSTHAN, FULLWIDTHGREATERTHAN]
    // ＜＞
  ];
  for (let i2 = 0; i2 < bracketPairs.length; i2++) {
    const [OPEN, CLOSE] = bracketPairs[i2];
    const UrlOpen = tt(Url$1$1, OPEN);
    tt(UrlNonaccept, OPEN, UrlOpen);
    tt(UrlOpen, CLOSE, Url$1$1);
    const UrlOpenQ = makeState(Url$1);
    ta(UrlOpen, qsAccepting, UrlOpenQ);
    const UrlOpenSyms = makeState();
    ta(UrlOpen, qsNonAccepting);
    ta(UrlOpenQ, qsAccepting, UrlOpenQ);
    ta(UrlOpenQ, qsNonAccepting, UrlOpenSyms);
    ta(UrlOpenSyms, qsAccepting, UrlOpenQ);
    ta(UrlOpenSyms, qsNonAccepting, UrlOpenSyms);
    tt(UrlOpenQ, CLOSE, Url$1$1);
    tt(UrlOpenSyms, CLOSE, Url$1$1);
  }
  tt(Start, LOCALHOST, DomainDotTld);
  tt(Start, NL, Nl);
  return {
    start: Start,
    tokens: tk
  };
}
__name(init$1, "init$1");
function run(start2, input, tokens) {
  let len = tokens.length;
  let cursor = 0;
  let multis = [];
  let textTokens = [];
  while (cursor < len) {
    let state = start2;
    let secondState = null;
    let nextState = null;
    let multiLength = 0;
    let latestAccepting = null;
    let sinceAccepts = -1;
    while (cursor < len && !(secondState = state.go(tokens[cursor].t))) {
      textTokens.push(tokens[cursor++]);
    }
    while (cursor < len && (nextState = secondState || state.go(tokens[cursor].t))) {
      secondState = null;
      state = nextState;
      if (state.accepts()) {
        sinceAccepts = 0;
        latestAccepting = state;
      } else if (sinceAccepts >= 0) {
        sinceAccepts++;
      }
      cursor++;
      multiLength++;
    }
    if (sinceAccepts < 0) {
      cursor -= multiLength;
      if (cursor < len) {
        textTokens.push(tokens[cursor]);
        cursor++;
      }
    } else {
      if (textTokens.length > 0) {
        multis.push(initMultiToken(Text$3, input, textTokens));
        textTokens = [];
      }
      cursor -= sinceAccepts;
      multiLength -= sinceAccepts;
      const Multi = latestAccepting.t;
      const subtokens = tokens.slice(cursor - multiLength, cursor);
      multis.push(initMultiToken(Multi, input, subtokens));
    }
  }
  if (textTokens.length > 0) {
    multis.push(initMultiToken(Text$3, input, textTokens));
  }
  return multis;
}
__name(run, "run");
function initMultiToken(Multi, input, tokens) {
  const startIdx = tokens[0].s;
  const endIdx = tokens[tokens.length - 1].e;
  const value = input.slice(startIdx, endIdx);
  return new Multi(value, tokens);
}
__name(initMultiToken, "initMultiToken");
const warn = typeof console !== "undefined" && console && console.warn || (() => {
});
const warnAdvice = "until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time.";
const INIT = {
  scanner: null,
  parser: null,
  tokenQueue: [],
  pluginQueue: [],
  customSchemes: [],
  initialized: false
};
function reset() {
  State.groups = {};
  INIT.scanner = null;
  INIT.parser = null;
  INIT.tokenQueue = [];
  INIT.pluginQueue = [];
  INIT.customSchemes = [];
  INIT.initialized = false;
  return INIT;
}
__name(reset, "reset");
function registerTokenPlugin(name2, plugin) {
  if (typeof plugin !== "function") {
    throw new Error(`linkifyjs: Invalid token plugin ${plugin} (expects function)`);
  }
  for (let i2 = 0; i2 < INIT.tokenQueue.length; i2++) {
    if (name2 === INIT.tokenQueue[i2][0]) {
      warn(`linkifyjs: token plugin "${name2}" already registered - will be overwritten`);
      INIT.tokenQueue[i2] = [name2, plugin];
      return;
    }
  }
  INIT.tokenQueue.push([name2, plugin]);
  if (INIT.initialized) {
    warn(`linkifyjs: already initialized - will not register token plugin "${name2}" ${warnAdvice}`);
  }
}
__name(registerTokenPlugin, "registerTokenPlugin");
function registerPlugin(name2, plugin) {
  if (typeof plugin !== "function") {
    throw new Error(`linkifyjs: Invalid plugin ${plugin} (expects function)`);
  }
  for (let i2 = 0; i2 < INIT.pluginQueue.length; i2++) {
    if (name2 === INIT.pluginQueue[i2][0]) {
      warn(`linkifyjs: plugin "${name2}" already registered - will be overwritten`);
      INIT.pluginQueue[i2] = [name2, plugin];
      return;
    }
  }
  INIT.pluginQueue.push([name2, plugin]);
  if (INIT.initialized) {
    warn(`linkifyjs: already initialized - will not register plugin "${name2}" ${warnAdvice}`);
  }
}
__name(registerPlugin, "registerPlugin");
function registerCustomProtocol(scheme2, optionalSlashSlash = false) {
  if (INIT.initialized) {
    warn(`linkifyjs: already initialized - will not register custom scheme "${scheme2}" ${warnAdvice}`);
  }
  if (!/^[0-9a-z]+(-[0-9a-z]+)*$/.test(scheme2)) {
    throw new Error(`linkifyjs: incorrect scheme format.
1. Must only contain digits, lowercase ASCII letters or "-"
2. Cannot start or end with "-"
3. "-" cannot repeat`);
  }
  INIT.customSchemes.push([scheme2, optionalSlashSlash]);
}
__name(registerCustomProtocol, "registerCustomProtocol");
function init() {
  INIT.scanner = init$2(INIT.customSchemes);
  for (let i2 = 0; i2 < INIT.tokenQueue.length; i2++) {
    INIT.tokenQueue[i2][1]({
      scanner: INIT.scanner
    });
  }
  INIT.parser = init$1(INIT.scanner.tokens);
  for (let i2 = 0; i2 < INIT.pluginQueue.length; i2++) {
    INIT.pluginQueue[i2][1]({
      scanner: INIT.scanner,
      parser: INIT.parser
    });
  }
  INIT.initialized = true;
  return INIT;
}
__name(init, "init");
function tokenize(str) {
  if (!INIT.initialized) {
    init();
  }
  return run(INIT.parser.start, str, run$1(INIT.scanner.start, str));
}
__name(tokenize, "tokenize");
tokenize.scan = run$1;
function find(str, type = null, opts = null) {
  if (type && typeof type === "object") {
    if (opts) {
      throw Error(`linkifyjs: Invalid link type ${type}; must be a string`);
    }
    opts = type;
    type = null;
  }
  const options2 = new Options(opts);
  const tokens = tokenize(str);
  const filtered = [];
  for (let i2 = 0; i2 < tokens.length; i2++) {
    const token = tokens[i2];
    if (token.isLink && (!type || token.t === type) && options2.check(token)) {
      filtered.push(token.toFormattedObject(options2));
    }
  }
  return filtered;
}
__name(find, "find");
function test(str, type = null) {
  const tokens = tokenize(str);
  return tokens.length === 1 && tokens[0].isLink && (!type || tokens[0].t === type);
}
__name(test, "test");
function isValidLinkStructure(tokens) {
  if (tokens.length === 1) {
    return tokens[0].isLink;
  }
  if (tokens.length === 3 && tokens[1].isLink) {
    return ["()", "[]"].includes(tokens[0].value + tokens[2].value);
  }
  return false;
}
__name(isValidLinkStructure, "isValidLinkStructure");
function autolink$1(options2) {
  return new Plugin({
    key: new PluginKey("autolink"),
    appendTransaction: /* @__PURE__ */ __name((transactions, oldState, newState) => {
      const docChanges = transactions.some((transaction) => transaction.docChanged) && !oldState.doc.eq(newState.doc);
      const preventAutolink = transactions.some((transaction) => transaction.getMeta("preventAutolink"));
      if (!docChanges || preventAutolink) {
        return;
      }
      const { tr: tr2 } = newState;
      const transform = combineTransactionSteps(oldState.doc, [...transactions]);
      const changes = getChangedRanges(transform);
      changes.forEach(({ newRange }) => {
        const nodesInChangedRanges = findChildrenInRange(newState.doc, newRange, (node2) => node2.isTextblock);
        let textBlock;
        let textBeforeWhitespace;
        if (nodesInChangedRanges.length > 1) {
          textBlock = nodesInChangedRanges[0];
          textBeforeWhitespace = newState.doc.textBetween(textBlock.pos, textBlock.pos + textBlock.node.nodeSize, void 0, " ");
        } else if (nodesInChangedRanges.length && newState.doc.textBetween(newRange.from, newRange.to, " ", " ").endsWith(" ")) {
          textBlock = nodesInChangedRanges[0];
          textBeforeWhitespace = newState.doc.textBetween(textBlock.pos, newRange.to, void 0, " ");
        }
        if (textBlock && textBeforeWhitespace) {
          const wordsBeforeWhitespace = textBeforeWhitespace.split(" ").filter((s2) => s2 !== "");
          if (wordsBeforeWhitespace.length <= 0) {
            return false;
          }
          const lastWordBeforeSpace = wordsBeforeWhitespace[wordsBeforeWhitespace.length - 1];
          const lastWordAndBlockOffset = textBlock.pos + textBeforeWhitespace.lastIndexOf(lastWordBeforeSpace);
          if (!lastWordBeforeSpace) {
            return false;
          }
          const linksBeforeSpace = tokenize(lastWordBeforeSpace).map((t2) => t2.toObject(options2.defaultProtocol));
          if (!isValidLinkStructure(linksBeforeSpace)) {
            return false;
          }
          linksBeforeSpace.filter((link2) => link2.isLink).map((link2) => ({
            ...link2,
            from: lastWordAndBlockOffset + link2.start + 1,
            to: lastWordAndBlockOffset + link2.end + 1
          })).filter((link2) => {
            if (!newState.schema.marks.code) {
              return true;
            }
            return !newState.doc.rangeHasMark(link2.from, link2.to, newState.schema.marks.code);
          }).filter((link2) => options2.validate(link2.value)).filter((link2) => options2.shouldAutoLink(link2.value)).forEach((link2) => {
            if (getMarksBetween(link2.from, link2.to, newState.doc).some((item) => item.mark.type === options2.type)) {
              return;
            }
            tr2.addMark(link2.from, link2.to, options2.type.create({
              href: link2.href
            }));
          });
        }
      });
      if (!tr2.steps.length) {
        return;
      }
      return tr2;
    }, "appendTransaction")
  });
}
__name(autolink$1, "autolink$1");
function clickHandler(options2) {
  return new Plugin({
    key: new PluginKey("handleClickLink"),
    props: {
      handleClick: /* @__PURE__ */ __name((view, pos, event) => {
        var _a2, _b;
        if (event.button !== 0) {
          return false;
        }
        if (!view.editable) {
          return false;
        }
        let a2 = event.target;
        const els = [];
        while (a2.nodeName !== "DIV") {
          els.push(a2);
          a2 = a2.parentNode;
        }
        if (!els.find((value) => value.nodeName === "A")) {
          return false;
        }
        const attrs2 = getAttributes(view.state, options2.type.name);
        const link2 = event.target;
        const href = (_a2 = link2 === null || link2 === void 0 ? void 0 : link2.href) !== null && _a2 !== void 0 ? _a2 : attrs2.href;
        const target = (_b = link2 === null || link2 === void 0 ? void 0 : link2.target) !== null && _b !== void 0 ? _b : attrs2.target;
        if (link2 && href) {
          window.open(href, target);
          return true;
        }
        return false;
      }, "handleClick")
    }
  });
}
__name(clickHandler, "clickHandler");
function pasteHandler(options2) {
  return new Plugin({
    key: new PluginKey("handlePasteLink"),
    props: {
      handlePaste: /* @__PURE__ */ __name((view, event, slice2) => {
        const { state } = view;
        const { selection } = state;
        const { empty: empty2 } = selection;
        if (empty2) {
          return false;
        }
        let textContent = "";
        slice2.content.forEach((node2) => {
          textContent += node2.textContent;
        });
        const link2 = find(textContent, { defaultProtocol: options2.defaultProtocol }).find((item) => item.isLink && item.value === textContent);
        if (!textContent || !link2) {
          return false;
        }
        options2.editor.commands.setMark(options2.type, {
          href: link2.href
        });
        return true;
      }, "handlePaste")
    }
  });
}
__name(pasteHandler, "pasteHandler");
const pasteRegex$2 = /https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z]{2,}\b(?:[-a-zA-Z0-9@:%._+~#=?!&/]*)(?:[-a-zA-Z0-9@:%._+~#=?!&/]*)/gi;
const ATTR_WHITESPACE = /[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g;
function isAllowedUri(uri, protocols) {
  const allowedProtocols = [
    "http",
    "https",
    "ftp",
    "ftps",
    "mailto",
    "tel",
    "callto",
    "sms",
    "cid",
    "xmpp"
  ];
  if (protocols) {
    protocols.forEach((protocol) => {
      const nextProtocol = typeof protocol === "string" ? protocol : protocol.scheme;
      if (nextProtocol) {
        allowedProtocols.push(nextProtocol);
      }
    });
  }
  return !uri || uri.replace(ATTR_WHITESPACE, "").match(new RegExp(
    // eslint-disable-next-line no-useless-escape
    `^(?:(?:${allowedProtocols.join("|")}):|[^a-z]|[a-z+.-]+(?:[^a-z+.-:]|$))`,
    "i"
  ));
}
__name(isAllowedUri, "isAllowedUri");
const Link$2 = Mark.create({
  name: "link",
  priority: 1e3,
  keepOnSplit: false,
  exitable: true,
  onCreate() {
    if (this.options.validate && !this.options.shouldAutoLink) {
      this.options.shouldAutoLink = this.options.validate;
      console.warn("The `validate` option is deprecated. Rename to the `shouldAutoLink` option instead.");
    }
    this.options.protocols.forEach((protocol) => {
      if (typeof protocol === "string") {
        registerCustomProtocol(protocol);
        return;
      }
      registerCustomProtocol(protocol.scheme, protocol.optionalSlashes);
    });
  },
  onDestroy() {
    reset();
  },
  inclusive() {
    return this.options.autolink;
  },
  addOptions() {
    return {
      openOnClick: true,
      linkOnPaste: true,
      autolink: true,
      protocols: [],
      defaultProtocol: "http",
      HTMLAttributes: {
        target: "_blank",
        rel: "noopener noreferrer nofollow",
        class: null
      },
      isAllowedUri: /* @__PURE__ */ __name((url, ctx) => !!isAllowedUri(url, ctx.protocols), "isAllowedUri"),
      validate: /* @__PURE__ */ __name((url) => !!url, "validate"),
      shouldAutoLink: /* @__PURE__ */ __name((url) => !!url, "shouldAutoLink")
    };
  },
  addAttributes() {
    return {
      href: {
        default: null,
        parseHTML(element) {
          return element.getAttribute("href");
        }
      },
      target: {
        default: this.options.HTMLAttributes.target
      },
      rel: {
        default: this.options.HTMLAttributes.rel
      },
      class: {
        default: this.options.HTMLAttributes.class
      }
    };
  },
  parseHTML() {
    return [
      {
        tag: "a[href]",
        getAttrs: /* @__PURE__ */ __name((dom) => {
          const href = dom.getAttribute("href");
          if (!href || !this.options.isAllowedUri(href, {
            defaultValidate: /* @__PURE__ */ __name((url) => !!isAllowedUri(url, this.options.protocols), "defaultValidate"),
            protocols: this.options.protocols,
            defaultProtocol: this.options.defaultProtocol
          })) {
            return false;
          }
          return null;
        }, "getAttrs")
      }
    ];
  },
  renderHTML({ HTMLAttributes }) {
    if (!this.options.isAllowedUri(HTMLAttributes.href, {
      defaultValidate: /* @__PURE__ */ __name((href) => !!isAllowedUri(href, this.options.protocols), "defaultValidate"),
      protocols: this.options.protocols,
      defaultProtocol: this.options.defaultProtocol
    })) {
      return [
        "a",
        mergeAttributes(this.options.HTMLAttributes, { ...HTMLAttributes, href: "" }),
        0
      ];
    }
    return ["a", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0];
  },
  addCommands() {
    return {
      setLink: /* @__PURE__ */ __name((attributes) => ({ chain }) => {
        const { href } = attributes;
        if (!this.options.isAllowedUri(href, {
          defaultValidate: /* @__PURE__ */ __name((url) => !!isAllowedUri(url, this.options.protocols), "defaultValidate"),
          protocols: this.options.protocols,
          defaultProtocol: this.options.defaultProtocol
        })) {
          return false;
        }
        return chain().setMark(this.name, attributes).setMeta("preventAutolink", true).run();
      }, "setLink"),
      toggleLink: /* @__PURE__ */ __name((attributes) => ({ chain }) => {
        const { href } = attributes;
        if (!this.options.isAllowedUri(href, {
          defaultValidate: /* @__PURE__ */ __name((url) => !!isAllowedUri(url, this.options.protocols), "defaultValidate"),
          protocols: this.options.protocols,
          defaultProtocol: this.options.defaultProtocol
        })) {
          return false;
        }
        return chain().toggleMark(this.name, attributes, { extendEmptyMarkRange: true }).setMeta("preventAutolink", true).run();
      }, "toggleLink"),
      unsetLink: /* @__PURE__ */ __name(() => ({ chain }) => {
        return chain().unsetMark(this.name, { extendEmptyMarkRange: true }).setMeta("preventAutolink", true).run();
      }, "unsetLink")
    };
  },
  addPasteRules() {
    return [
      markPasteRule({
        find: /* @__PURE__ */ __name((text2) => {
          const foundLinks = [];
          if (text2) {
            const { protocols, defaultProtocol } = this.options;
            const links = find(text2).filter((item) => item.isLink && this.options.isAllowedUri(item.value, {
              defaultValidate: /* @__PURE__ */ __name((href) => !!isAllowedUri(href, protocols), "defaultValidate"),
              protocols,
              defaultProtocol
            }));
            if (links.length) {
              links.forEach((link2) => foundLinks.push({
                text: link2.value,
                data: {
                  href: link2.href
                },
                index: link2.start
              }));
            }
          }
          return foundLinks;
        }, "find"),
        type: this.type,
        getAttributes: /* @__PURE__ */ __name((match2) => {
          var _a2;
          return {
            href: (_a2 = match2.data) === null || _a2 === void 0 ? void 0 : _a2.href
          };
        }, "getAttributes")
      })
    ];
  },
  addProseMirrorPlugins() {
    const plugins = [];
    const { protocols, defaultProtocol } = this.options;
    if (this.options.autolink) {
      plugins.push(autolink$1({
        type: this.type,
        defaultProtocol: this.options.defaultProtocol,
        validate: /* @__PURE__ */ __name((url) => this.options.isAllowedUri(url, {
          defaultValidate: /* @__PURE__ */ __name((href) => !!isAllowedUri(href, protocols), "defaultValidate"),
          protocols,
          defaultProtocol
        }), "validate"),
        shouldAutoLink: this.options.shouldAutoLink
      }));
    }
    if (this.options.openOnClick === true) {
      plugins.push(clickHandler({
        type: this.type
      }));
    }
    if (this.options.linkOnPaste) {
      plugins.push(pasteHandler({
        editor: this.editor,
        defaultProtocol: this.options.defaultProtocol,
        type: this.type
      }));
    }
    return plugins;
  }
});
var readFromCache;
var addToCache;
if (typeof WeakMap != "undefined") {
  let cache = /* @__PURE__ */ new WeakMap();
  readFromCache = /* @__PURE__ */ __name((key) => cache.get(key), "readFromCache");
  addToCache = /* @__PURE__ */ __name((key, value) => {
    cache.set(key, value);
    return value;
  }, "addToCache");
} else {
  const cache = [];
  const cacheSize = 10;
  let cachePos = 0;
  readFromCache = /* @__PURE__ */ __name((key) => {
    for (let i2 = 0; i2 < cache.length; i2 += 2)
      if (cache[i2] == key)
        return cache[i2 + 1];
  }, "readFromCache");
  addToCache = /* @__PURE__ */ __name((key, value) => {
    if (cachePos == cacheSize)
      cachePos = 0;
    cache[cachePos++] = key;
    return cache[cachePos++] = value;
  }, "addToCache");
}
var TableMap = class {
  static {
    __name(this, "TableMap");
  }
  constructor(width2, height, map3, problems) {
    this.width = width2;
    this.height = height;
    this.map = map3;
    this.problems = problems;
  }
  // Find the dimensions of the cell at the given position.
  findCell(pos) {
    for (let i2 = 0; i2 < this.map.length; i2++) {
      const curPos = this.map[i2];
      if (curPos != pos)
        continue;
      const left = i2 % this.width;
      const top = i2 / this.width | 0;
      let right = left + 1;
      let bottom = top + 1;
      for (let j2 = 1; right < this.width && this.map[i2 + j2] == curPos; j2++) {
        right++;
      }
      for (let j2 = 1; bottom < this.height && this.map[i2 + this.width * j2] == curPos; j2++) {
        bottom++;
      }
      return { left, top, right, bottom };
    }
    throw new RangeError(`No cell with offset ${pos} found`);
  }
  // Find the left side of the cell at the given position.
  colCount(pos) {
    for (let i2 = 0; i2 < this.map.length; i2++) {
      if (this.map[i2] == pos) {
        return i2 % this.width;
      }
    }
    throw new RangeError(`No cell with offset ${pos} found`);
  }
  // Find the next cell in the given direction, starting from the cell
  // at `pos`, if any.
  nextCell(pos, axis, dir) {
    const { left, right, top, bottom } = this.findCell(pos);
    if (axis == "horiz") {
      if (dir < 0 ? left == 0 : right == this.width)
        return null;
      return this.map[top * this.width + (dir < 0 ? left - 1 : right)];
    } else {
      if (dir < 0 ? top == 0 : bottom == this.height)
        return null;
      return this.map[left + this.width * (dir < 0 ? top - 1 : bottom)];
    }
  }
  // Get the rectangle spanning the two given cells.
  rectBetween(a2, b2) {
    const {
      left: leftA,
      right: rightA,
      top: topA,
      bottom: bottomA
    } = this.findCell(a2);
    const {
      left: leftB,
      right: rightB,
      top: topB,
      bottom: bottomB
    } = this.findCell(b2);
    return {
      left: Math.min(leftA, leftB),
      top: Math.min(topA, topB),
      right: Math.max(rightA, rightB),
      bottom: Math.max(bottomA, bottomB)
    };
  }
  // Return the position of all cells that have the top left corner in
  // the given rectangle.
  cellsInRect(rect) {
    const result = [];
    const seen2 = {};
    for (let row = rect.top; row < rect.bottom; row++) {
      for (let col = rect.left; col < rect.right; col++) {
        const index2 = row * this.width + col;
        const pos = this.map[index2];
        if (seen2[pos])
          continue;
        seen2[pos] = true;
        if (col == rect.left && col && this.map[index2 - 1] == pos || row == rect.top && row && this.map[index2 - this.width] == pos) {
          continue;
        }
        result.push(pos);
      }
    }
    return result;
  }
  // Return the position at which the cell at the given row and column
  // starts, or would start, if a cell started there.
  positionAt(row, col, table2) {
    for (let i2 = 0, rowStart = 0; ; i2++) {
      const rowEnd = rowStart + table2.child(i2).nodeSize;
      if (i2 == row) {
        let index2 = col + row * this.width;
        const rowEndIndex = (row + 1) * this.width;
        while (index2 < rowEndIndex && this.map[index2] < rowStart)
          index2++;
        return index2 == rowEndIndex ? rowEnd - 1 : this.map[index2];
      }
      rowStart = rowEnd;
    }
  }
  // Find the table map for the given table node.
  static get(table2) {
    return readFromCache(table2) || addToCache(table2, computeMap(table2));
  }
};
function computeMap(table2) {
  if (table2.type.spec.tableRole != "table")
    throw new RangeError("Not a table node: " + table2.type.name);
  const width2 = findWidth(table2), height = table2.childCount;
  const map3 = [];
  let mapPos = 0;
  let problems = null;
  const colWidths = [];
  for (let i2 = 0, e2 = width2 * height; i2 < e2; i2++)
    map3[i2] = 0;
  for (let row = 0, pos = 0; row < height; row++) {
    const rowNode = table2.child(row);
    pos++;
    for (let i2 = 0; ; i2++) {
      while (mapPos < map3.length && map3[mapPos] != 0)
        mapPos++;
      if (i2 == rowNode.childCount)
        break;
      const cellNode = rowNode.child(i2);
      const { colspan, rowspan, colwidth } = cellNode.attrs;
      for (let h2 = 0; h2 < rowspan; h2++) {
        if (h2 + row >= height) {
          (problems || (problems = [])).push({
            type: "overlong_rowspan",
            pos,
            n: rowspan - h2
          });
          break;
        }
        const start2 = mapPos + h2 * width2;
        for (let w2 = 0; w2 < colspan; w2++) {
          if (map3[start2 + w2] == 0)
            map3[start2 + w2] = pos;
          else
            (problems || (problems = [])).push({
              type: "collision",
              row,
              pos,
              n: colspan - w2
            });
          const colW = colwidth && colwidth[w2];
          if (colW) {
            const widthIndex = (start2 + w2) % width2 * 2, prev = colWidths[widthIndex];
            if (prev == null || prev != colW && colWidths[widthIndex + 1] == 1) {
              colWidths[widthIndex] = colW;
              colWidths[widthIndex + 1] = 1;
            } else if (prev == colW) {
              colWidths[widthIndex + 1]++;
            }
          }
        }
      }
      mapPos += colspan;
      pos += cellNode.nodeSize;
    }
    const expectedPos = (row + 1) * width2;
    let missing = 0;
    while (mapPos < expectedPos)
      if (map3[mapPos++] == 0)
        missing++;
    if (missing)
      (problems || (problems = [])).push({ type: "missing", row, n: missing });
    pos++;
  }
  const tableMap = new TableMap(width2, height, map3, problems);
  let badWidths = false;
  for (let i2 = 0; !badWidths && i2 < colWidths.length; i2 += 2)
    if (colWidths[i2] != null && colWidths[i2 + 1] < height)
      badWidths = true;
  if (badWidths)
    findBadColWidths(tableMap, colWidths, table2);
  return tableMap;
}
__name(computeMap, "computeMap");
function findWidth(table2) {
  let width2 = -1;
  let hasRowSpan = false;
  for (let row = 0; row < table2.childCount; row++) {
    const rowNode = table2.child(row);
    let rowWidth = 0;
    if (hasRowSpan)
      for (let j2 = 0; j2 < row; j2++) {
        const prevRow = table2.child(j2);
        for (let i2 = 0; i2 < prevRow.childCount; i2++) {
          const cell = prevRow.child(i2);
          if (j2 + cell.attrs.rowspan > row)
            rowWidth += cell.attrs.colspan;
        }
      }
    for (let i2 = 0; i2 < rowNode.childCount; i2++) {
      const cell = rowNode.child(i2);
      rowWidth += cell.attrs.colspan;
      if (cell.attrs.rowspan > 1)
        hasRowSpan = true;
    }
    if (width2 == -1)
      width2 = rowWidth;
    else if (width2 != rowWidth)
      width2 = Math.max(width2, rowWidth);
  }
  return width2;
}
__name(findWidth, "findWidth");
function findBadColWidths(map3, colWidths, table2) {
  if (!map3.problems)
    map3.problems = [];
  const seen2 = {};
  for (let i2 = 0; i2 < map3.map.length; i2++) {
    const pos = map3.map[i2];
    if (seen2[pos])
      continue;
    seen2[pos] = true;
    const node2 = table2.nodeAt(pos);
    if (!node2) {
      throw new RangeError(`No cell with offset ${pos} found`);
    }
    let updated2 = null;
    const attrs2 = node2.attrs;
    for (let j2 = 0; j2 < attrs2.colspan; j2++) {
      const col = (i2 + j2) % map3.width;
      const colWidth = colWidths[col * 2];
      if (colWidth != null && (!attrs2.colwidth || attrs2.colwidth[j2] != colWidth))
        (updated2 || (updated2 = freshColWidth(attrs2)))[j2] = colWidth;
    }
    if (updated2)
      map3.problems.unshift({
        type: "colwidth mismatch",
        pos,
        colwidth: updated2
      });
  }
}
__name(findBadColWidths, "findBadColWidths");
function freshColWidth(attrs2) {
  if (attrs2.colwidth)
    return attrs2.colwidth.slice();
  const result = [];
  for (let i2 = 0; i2 < attrs2.colspan; i2++)
    result.push(0);
  return result;
}
__name(freshColWidth, "freshColWidth");
function getCellAttrs(dom, extraAttrs) {
  if (typeof dom === "string") {
    return {};
  }
  const widthAttr = dom.getAttribute("data-colwidth");
  const widths = widthAttr && /^\d+(,\d+)*$/.test(widthAttr) ? widthAttr.split(",").map((s2) => Number(s2)) : null;
  const colspan = Number(dom.getAttribute("colspan") || 1);
  const result = {
    colspan,
    rowspan: Number(dom.getAttribute("rowspan") || 1),
    colwidth: widths && widths.length == colspan ? widths : null
  };
  for (const prop2 in extraAttrs) {
    const getter = extraAttrs[prop2].getFromDOM;
    const value = getter && getter(dom);
    if (value != null) {
      result[prop2] = value;
    }
  }
  return result;
}
__name(getCellAttrs, "getCellAttrs");
function setCellAttrs(node2, extraAttrs) {
  const attrs2 = {};
  if (node2.attrs.colspan != 1)
    attrs2.colspan = node2.attrs.colspan;
  if (node2.attrs.rowspan != 1)
    attrs2.rowspan = node2.attrs.rowspan;
  if (node2.attrs.colwidth)
    attrs2["data-colwidth"] = node2.attrs.colwidth.join(",");
  for (const prop2 in extraAttrs) {
    const setter = extraAttrs[prop2].setDOMAttr;
    if (setter)
      setter(node2.attrs[prop2], attrs2);
  }
  return attrs2;
}
__name(setCellAttrs, "setCellAttrs");
function tableNodes(options2) {
  const extraAttrs = options2.cellAttributes || {};
  const cellAttrs = {
    colspan: { default: 1 },
    rowspan: { default: 1 },
    colwidth: { default: null }
  };
  for (const prop2 in extraAttrs)
    cellAttrs[prop2] = { default: extraAttrs[prop2].default };
  return {
    table: {
      content: "table_row+",
      tableRole: "table",
      isolating: true,
      group: options2.tableGroup,
      parseDOM: [{ tag: "table" }],
      toDOM() {
        return ["table", ["tbody", 0]];
      }
    },
    table_row: {
      content: "(table_cell | table_header)*",
      tableRole: "row",
      parseDOM: [{ tag: "tr" }],
      toDOM() {
        return ["tr", 0];
      }
    },
    table_cell: {
      content: options2.cellContent,
      attrs: cellAttrs,
      tableRole: "cell",
      isolating: true,
      parseDOM: [
        { tag: "td", getAttrs: /* @__PURE__ */ __name((dom) => getCellAttrs(dom, extraAttrs), "getAttrs") }
      ],
      toDOM(node2) {
        return ["td", setCellAttrs(node2, extraAttrs), 0];
      }
    },
    table_header: {
      content: options2.cellContent,
      attrs: cellAttrs,
      tableRole: "header_cell",
      isolating: true,
      parseDOM: [
        { tag: "th", getAttrs: /* @__PURE__ */ __name((dom) => getCellAttrs(dom, extraAttrs), "getAttrs") }
      ],
      toDOM(node2) {
        return ["th", setCellAttrs(node2, extraAttrs), 0];
      }
    }
  };
}
__name(tableNodes, "tableNodes");
function tableNodeTypes(schema2) {
  let result = schema2.cached.tableNodeTypes;
  if (!result) {
    result = schema2.cached.tableNodeTypes = {};
    for (const name2 in schema2.nodes) {
      const type = schema2.nodes[name2], role = type.spec.tableRole;
      if (role)
        result[role] = type;
    }
  }
  return result;
}
__name(tableNodeTypes, "tableNodeTypes");
var tableEditingKey = new PluginKey("selectingCells");
function cellAround($pos) {
  for (let d2 = $pos.depth - 1; d2 > 0; d2--)
    if ($pos.node(d2).type.spec.tableRole == "row")
      return $pos.node(0).resolve($pos.before(d2 + 1));
  return null;
}
__name(cellAround, "cellAround");
function cellWrapping($pos) {
  for (let d2 = $pos.depth; d2 > 0; d2--) {
    const role = $pos.node(d2).type.spec.tableRole;
    if (role === "cell" || role === "header_cell")
      return $pos.node(d2);
  }
  return null;
}
__name(cellWrapping, "cellWrapping");
function isInTable(state) {
  const $head = state.selection.$head;
  for (let d2 = $head.depth; d2 > 0; d2--)
    if ($head.node(d2).type.spec.tableRole == "row")
      return true;
  return false;
}
__name(isInTable, "isInTable");
function selectionCell(state) {
  const sel = state.selection;
  if ("$anchorCell" in sel && sel.$anchorCell) {
    return sel.$anchorCell.pos > sel.$headCell.pos ? sel.$anchorCell : sel.$headCell;
  } else if ("node" in sel && sel.node && sel.node.type.spec.tableRole == "cell") {
    return sel.$anchor;
  }
  const $cell = cellAround(sel.$head) || cellNear(sel.$head);
  if ($cell) {
    return $cell;
  }
  throw new RangeError(`No cell found around position ${sel.head}`);
}
__name(selectionCell, "selectionCell");
function cellNear($pos) {
  for (let after = $pos.nodeAfter, pos = $pos.pos; after; after = after.firstChild, pos++) {
    const role = after.type.spec.tableRole;
    if (role == "cell" || role == "header_cell")
      return $pos.doc.resolve(pos);
  }
  for (let before = $pos.nodeBefore, pos = $pos.pos; before; before = before.lastChild, pos--) {
    const role = before.type.spec.tableRole;
    if (role == "cell" || role == "header_cell")
      return $pos.doc.resolve(pos - before.nodeSize);
  }
}
__name(cellNear, "cellNear");
function pointsAtCell($pos) {
  return $pos.parent.type.spec.tableRole == "row" && !!$pos.nodeAfter;
}
__name(pointsAtCell, "pointsAtCell");
function moveCellForward($pos) {
  return $pos.node(0).resolve($pos.pos + $pos.nodeAfter.nodeSize);
}
__name(moveCellForward, "moveCellForward");
function inSameTable($cellA, $cellB) {
  return $cellA.depth == $cellB.depth && $cellA.pos >= $cellB.start(-1) && $cellA.pos <= $cellB.end(-1);
}
__name(inSameTable, "inSameTable");
function findCell($pos) {
  return TableMap.get($pos.node(-1)).findCell($pos.pos - $pos.start(-1));
}
__name(findCell, "findCell");
function colCount($pos) {
  return TableMap.get($pos.node(-1)).colCount($pos.pos - $pos.start(-1));
}
__name(colCount, "colCount");
function nextCell($pos, axis, dir) {
  const table2 = $pos.node(-1);
  const map3 = TableMap.get(table2);
  const tableStart = $pos.start(-1);
  const moved = map3.nextCell($pos.pos - tableStart, axis, dir);
  return moved == null ? null : $pos.node(0).resolve(tableStart + moved);
}
__name(nextCell, "nextCell");
function removeColSpan(attrs2, pos, n2 = 1) {
  const result = { ...attrs2, colspan: attrs2.colspan - n2 };
  if (result.colwidth) {
    result.colwidth = result.colwidth.slice();
    result.colwidth.splice(pos, n2);
    if (!result.colwidth.some((w2) => w2 > 0))
      result.colwidth = null;
  }
  return result;
}
__name(removeColSpan, "removeColSpan");
function addColSpan(attrs2, pos, n2 = 1) {
  const result = { ...attrs2, colspan: attrs2.colspan + n2 };
  if (result.colwidth) {
    result.colwidth = result.colwidth.slice();
    for (let i2 = 0; i2 < n2; i2++)
      result.colwidth.splice(pos, 0, 0);
  }
  return result;
}
__name(addColSpan, "addColSpan");
function columnIsHeader(map3, table2, col) {
  const headerCell = tableNodeTypes(table2.type.schema).header_cell;
  for (let row = 0; row < map3.height; row++)
    if (table2.nodeAt(map3.map[col + row * map3.width]).type != headerCell)
      return false;
  return true;
}
__name(columnIsHeader, "columnIsHeader");
var CellSelection = class _CellSelection extends Selection {
  static {
    __name(this, "_CellSelection");
  }
  // A table selection is identified by its anchor and head cells. The
  // positions given to this constructor should point _before_ two
  // cells in the same table. They may be the same, to select a single
  // cell.
  constructor($anchorCell, $headCell = $anchorCell) {
    const table2 = $anchorCell.node(-1);
    const map3 = TableMap.get(table2);
    const tableStart = $anchorCell.start(-1);
    const rect = map3.rectBetween(
      $anchorCell.pos - tableStart,
      $headCell.pos - tableStart
    );
    const doc2 = $anchorCell.node(0);
    const cells = map3.cellsInRect(rect).filter((p2) => p2 != $headCell.pos - tableStart);
    cells.unshift($headCell.pos - tableStart);
    const ranges = cells.map((pos) => {
      const cell = table2.nodeAt(pos);
      if (!cell) {
        throw RangeError(`No cell with offset ${pos} found`);
      }
      const from2 = tableStart + pos + 1;
      return new SelectionRange(
        doc2.resolve(from2),
        doc2.resolve(from2 + cell.content.size)
      );
    });
    super(ranges[0].$from, ranges[0].$to, ranges);
    this.$anchorCell = $anchorCell;
    this.$headCell = $headCell;
  }
  map(doc2, mapping) {
    const $anchorCell = doc2.resolve(mapping.map(this.$anchorCell.pos));
    const $headCell = doc2.resolve(mapping.map(this.$headCell.pos));
    if (pointsAtCell($anchorCell) && pointsAtCell($headCell) && inSameTable($anchorCell, $headCell)) {
      const tableChanged = this.$anchorCell.node(-1) != $anchorCell.node(-1);
      if (tableChanged && this.isRowSelection())
        return _CellSelection.rowSelection($anchorCell, $headCell);
      else if (tableChanged && this.isColSelection())
        return _CellSelection.colSelection($anchorCell, $headCell);
      else
        return new _CellSelection($anchorCell, $headCell);
    }
    return TextSelection.between($anchorCell, $headCell);
  }
  // Returns a rectangular slice of table rows containing the selected
  // cells.
  content() {
    const table2 = this.$anchorCell.node(-1);
    const map3 = TableMap.get(table2);
    const tableStart = this.$anchorCell.start(-1);
    const rect = map3.rectBetween(
      this.$anchorCell.pos - tableStart,
      this.$headCell.pos - tableStart
    );
    const seen2 = {};
    const rows = [];
    for (let row = rect.top; row < rect.bottom; row++) {
      const rowContent = [];
      for (let index2 = row * map3.width + rect.left, col = rect.left; col < rect.right; col++, index2++) {
        const pos = map3.map[index2];
        if (seen2[pos])
          continue;
        seen2[pos] = true;
        const cellRect = map3.findCell(pos);
        let cell = table2.nodeAt(pos);
        if (!cell) {
          throw RangeError(`No cell with offset ${pos} found`);
        }
        const extraLeft = rect.left - cellRect.left;
        const extraRight = cellRect.right - rect.right;
        if (extraLeft > 0 || extraRight > 0) {
          let attrs2 = cell.attrs;
          if (extraLeft > 0) {
            attrs2 = removeColSpan(attrs2, 0, extraLeft);
          }
          if (extraRight > 0) {
            attrs2 = removeColSpan(
              attrs2,
              attrs2.colspan - extraRight,
              extraRight
            );
          }
          if (cellRect.left < rect.left) {
            cell = cell.type.createAndFill(attrs2);
            if (!cell) {
              throw RangeError(
                `Could not create cell with attrs ${JSON.stringify(attrs2)}`
              );
            }
          } else {
            cell = cell.type.create(attrs2, cell.content);
          }
        }
        if (cellRect.top < rect.top || cellRect.bottom > rect.bottom) {
          const attrs2 = {
            ...cell.attrs,
            rowspan: Math.min(cellRect.bottom, rect.bottom) - Math.max(cellRect.top, rect.top)
          };
          if (cellRect.top < rect.top) {
            cell = cell.type.createAndFill(attrs2);
          } else {
            cell = cell.type.create(attrs2, cell.content);
          }
        }
        rowContent.push(cell);
      }
      rows.push(table2.child(row).copy(Fragment.from(rowContent)));
    }
    const fragment = this.isColSelection() && this.isRowSelection() ? table2 : rows;
    return new Slice(Fragment.from(fragment), 1, 1);
  }
  replace(tr2, content = Slice.empty) {
    const mapFrom = tr2.steps.length, ranges = this.ranges;
    for (let i2 = 0; i2 < ranges.length; i2++) {
      const { $from, $to } = ranges[i2], mapping = tr2.mapping.slice(mapFrom);
      tr2.replace(
        mapping.map($from.pos),
        mapping.map($to.pos),
        i2 ? Slice.empty : content
      );
    }
    const sel = Selection.findFrom(
      tr2.doc.resolve(tr2.mapping.slice(mapFrom).map(this.to)),
      -1
    );
    if (sel)
      tr2.setSelection(sel);
  }
  replaceWith(tr2, node2) {
    this.replace(tr2, new Slice(Fragment.from(node2), 0, 0));
  }
  forEachCell(f2) {
    const table2 = this.$anchorCell.node(-1);
    const map3 = TableMap.get(table2);
    const tableStart = this.$anchorCell.start(-1);
    const cells = map3.cellsInRect(
      map3.rectBetween(
        this.$anchorCell.pos - tableStart,
        this.$headCell.pos - tableStart
      )
    );
    for (let i2 = 0; i2 < cells.length; i2++) {
      f2(table2.nodeAt(cells[i2]), tableStart + cells[i2]);
    }
  }
  // True if this selection goes all the way from the top to the
  // bottom of the table.
  isColSelection() {
    const anchorTop = this.$anchorCell.index(-1);
    const headTop = this.$headCell.index(-1);
    if (Math.min(anchorTop, headTop) > 0)
      return false;
    const anchorBottom = anchorTop + this.$anchorCell.nodeAfter.attrs.rowspan;
    const headBottom = headTop + this.$headCell.nodeAfter.attrs.rowspan;
    return Math.max(anchorBottom, headBottom) == this.$headCell.node(-1).childCount;
  }
  // Returns the smallest column selection that covers the given anchor
  // and head cell.
  static colSelection($anchorCell, $headCell = $anchorCell) {
    const table2 = $anchorCell.node(-1);
    const map3 = TableMap.get(table2);
    const tableStart = $anchorCell.start(-1);
    const anchorRect = map3.findCell($anchorCell.pos - tableStart);
    const headRect = map3.findCell($headCell.pos - tableStart);
    const doc2 = $anchorCell.node(0);
    if (anchorRect.top <= headRect.top) {
      if (anchorRect.top > 0)
        $anchorCell = doc2.resolve(tableStart + map3.map[anchorRect.left]);
      if (headRect.bottom < map3.height)
        $headCell = doc2.resolve(
          tableStart + map3.map[map3.width * (map3.height - 1) + headRect.right - 1]
        );
    } else {
      if (headRect.top > 0)
        $headCell = doc2.resolve(tableStart + map3.map[headRect.left]);
      if (anchorRect.bottom < map3.height)
        $anchorCell = doc2.resolve(
          tableStart + map3.map[map3.width * (map3.height - 1) + anchorRect.right - 1]
        );
    }
    return new _CellSelection($anchorCell, $headCell);
  }
  // True if this selection goes all the way from the left to the
  // right of the table.
  isRowSelection() {
    const table2 = this.$anchorCell.node(-1);
    const map3 = TableMap.get(table2);
    const tableStart = this.$anchorCell.start(-1);
    const anchorLeft = map3.colCount(this.$anchorCell.pos - tableStart);
    const headLeft = map3.colCount(this.$headCell.pos - tableStart);
    if (Math.min(anchorLeft, headLeft) > 0)
      return false;
    const anchorRight = anchorLeft + this.$anchorCell.nodeAfter.attrs.colspan;
    const headRight = headLeft + this.$headCell.nodeAfter.attrs.colspan;
    return Math.max(anchorRight, headRight) == map3.width;
  }
  eq(other) {
    return other instanceof _CellSelection && other.$anchorCell.pos == this.$anchorCell.pos && other.$headCell.pos == this.$headCell.pos;
  }
  // Returns the smallest row selection that covers the given anchor
  // and head cell.
  static rowSelection($anchorCell, $headCell = $anchorCell) {
    const table2 = $anchorCell.node(-1);
    const map3 = TableMap.get(table2);
    const tableStart = $anchorCell.start(-1);
    const anchorRect = map3.findCell($anchorCell.pos - tableStart);
    const headRect = map3.findCell($headCell.pos - tableStart);
    const doc2 = $anchorCell.node(0);
    if (anchorRect.left <= headRect.left) {
      if (anchorRect.left > 0)
        $anchorCell = doc2.resolve(
          tableStart + map3.map[anchorRect.top * map3.width]
        );
      if (headRect.right < map3.width)
        $headCell = doc2.resolve(
          tableStart + map3.map[map3.width * (headRect.top + 1) - 1]
        );
    } else {
      if (headRect.left > 0)
        $headCell = doc2.resolve(tableStart + map3.map[headRect.top * map3.width]);
      if (anchorRect.right < map3.width)
        $anchorCell = doc2.resolve(
          tableStart + map3.map[map3.width * (anchorRect.top + 1) - 1]
        );
    }
    return new _CellSelection($anchorCell, $headCell);
  }
  toJSON() {
    return {
      type: "cell",
      anchor: this.$anchorCell.pos,
      head: this.$headCell.pos
    };
  }
  static fromJSON(doc2, json) {
    return new _CellSelection(doc2.resolve(json.anchor), doc2.resolve(json.head));
  }
  static create(doc2, anchorCell, headCell = anchorCell) {
    return new _CellSelection(doc2.resolve(anchorCell), doc2.resolve(headCell));
  }
  getBookmark() {
    return new CellBookmark(this.$anchorCell.pos, this.$headCell.pos);
  }
};
CellSelection.prototype.visible = false;
Selection.jsonID("cell", CellSelection);
var CellBookmark = class _CellBookmark {
  static {
    __name(this, "_CellBookmark");
  }
  constructor(anchor, head) {
    this.anchor = anchor;
    this.head = head;
  }
  map(mapping) {
    return new _CellBookmark(mapping.map(this.anchor), mapping.map(this.head));
  }
  resolve(doc2) {
    const $anchorCell = doc2.resolve(this.anchor), $headCell = doc2.resolve(this.head);
    if ($anchorCell.parent.type.spec.tableRole == "row" && $headCell.parent.type.spec.tableRole == "row" && $anchorCell.index() < $anchorCell.parent.childCount && $headCell.index() < $headCell.parent.childCount && inSameTable($anchorCell, $headCell))
      return new CellSelection($anchorCell, $headCell);
    else
      return Selection.near($headCell, 1);
  }
};
function drawCellSelection(state) {
  if (!(state.selection instanceof CellSelection))
    return null;
  const cells = [];
  state.selection.forEachCell((node2, pos) => {
    cells.push(
      Decoration.node(pos, pos + node2.nodeSize, { class: "selectedCell" })
    );
  });
  return DecorationSet.create(state.doc, cells);
}
__name(drawCellSelection, "drawCellSelection");
function isCellBoundarySelection({ $from, $to }) {
  if ($from.pos == $to.pos || $from.pos < $to.pos - 6)
    return false;
  let afterFrom = $from.pos;
  let beforeTo = $to.pos;
  let depth = $from.depth;
  for (; depth >= 0; depth--, afterFrom++)
    if ($from.after(depth + 1) < $from.end(depth))
      break;
  for (let d2 = $to.depth; d2 >= 0; d2--, beforeTo--)
    if ($to.before(d2 + 1) > $to.start(d2))
      break;
  return afterFrom == beforeTo && /row|table/.test($from.node(depth).type.spec.tableRole);
}
__name(isCellBoundarySelection, "isCellBoundarySelection");
function isTextSelectionAcrossCells({ $from, $to }) {
  let fromCellBoundaryNode;
  let toCellBoundaryNode;
  for (let i2 = $from.depth; i2 > 0; i2--) {
    const node2 = $from.node(i2);
    if (node2.type.spec.tableRole === "cell" || node2.type.spec.tableRole === "header_cell") {
      fromCellBoundaryNode = node2;
      break;
    }
  }
  for (let i2 = $to.depth; i2 > 0; i2--) {
    const node2 = $to.node(i2);
    if (node2.type.spec.tableRole === "cell" || node2.type.spec.tableRole === "header_cell") {
      toCellBoundaryNode = node2;
      break;
    }
  }
  return fromCellBoundaryNode !== toCellBoundaryNode && $to.parentOffset === 0;
}
__name(isTextSelectionAcrossCells, "isTextSelectionAcrossCells");
function normalizeSelection(state, tr2, allowTableNodeSelection) {
  const sel = (tr2 || state).selection;
  const doc2 = (tr2 || state).doc;
  let normalize3;
  let role;
  if (sel instanceof NodeSelection && (role = sel.node.type.spec.tableRole)) {
    if (role == "cell" || role == "header_cell") {
      normalize3 = CellSelection.create(doc2, sel.from);
    } else if (role == "row") {
      const $cell = doc2.resolve(sel.from + 1);
      normalize3 = CellSelection.rowSelection($cell, $cell);
    } else if (!allowTableNodeSelection) {
      const map3 = TableMap.get(sel.node);
      const start2 = sel.from + 1;
      const lastCell = start2 + map3.map[map3.width * map3.height - 1];
      normalize3 = CellSelection.create(doc2, start2 + 1, lastCell);
    }
  } else if (sel instanceof TextSelection && isCellBoundarySelection(sel)) {
    normalize3 = TextSelection.create(doc2, sel.from);
  } else if (sel instanceof TextSelection && isTextSelectionAcrossCells(sel)) {
    normalize3 = TextSelection.create(doc2, sel.$from.start(), sel.$from.end());
  }
  if (normalize3)
    (tr2 || (tr2 = state.tr)).setSelection(normalize3);
  return tr2;
}
__name(normalizeSelection, "normalizeSelection");
var fixTablesKey = new PluginKey("fix-tables");
function changedDescendants(old, cur, offset, f2) {
  const oldSize = old.childCount, curSize = cur.childCount;
  outer:
    for (let i2 = 0, j2 = 0; i2 < curSize; i2++) {
      const child2 = cur.child(i2);
      for (let scan = j2, e2 = Math.min(oldSize, i2 + 3); scan < e2; scan++) {
        if (old.child(scan) == child2) {
          j2 = scan + 1;
          offset += child2.nodeSize;
          continue outer;
        }
      }
      f2(child2, offset);
      if (j2 < oldSize && old.child(j2).sameMarkup(child2))
        changedDescendants(old.child(j2), child2, offset + 1, f2);
      else
        child2.nodesBetween(0, child2.content.size, f2, offset + 1);
      offset += child2.nodeSize;
    }
}
__name(changedDescendants, "changedDescendants");
function fixTables(state, oldState) {
  let tr2;
  const check = /* @__PURE__ */ __name((node2, pos) => {
    if (node2.type.spec.tableRole == "table")
      tr2 = fixTable(state, node2, pos, tr2);
  }, "check");
  if (!oldState)
    state.doc.descendants(check);
  else if (oldState.doc != state.doc)
    changedDescendants(oldState.doc, state.doc, 0, check);
  return tr2;
}
__name(fixTables, "fixTables");
function fixTable(state, table2, tablePos, tr2) {
  const map3 = TableMap.get(table2);
  if (!map3.problems)
    return tr2;
  if (!tr2)
    tr2 = state.tr;
  const mustAdd = [];
  for (let i2 = 0; i2 < map3.height; i2++)
    mustAdd.push(0);
  for (let i2 = 0; i2 < map3.problems.length; i2++) {
    const prob = map3.problems[i2];
    if (prob.type == "collision") {
      const cell = table2.nodeAt(prob.pos);
      if (!cell)
        continue;
      const attrs2 = cell.attrs;
      for (let j2 = 0; j2 < attrs2.rowspan; j2++)
        mustAdd[prob.row + j2] += prob.n;
      tr2.setNodeMarkup(
        tr2.mapping.map(tablePos + 1 + prob.pos),
        null,
        removeColSpan(attrs2, attrs2.colspan - prob.n, prob.n)
      );
    } else if (prob.type == "missing") {
      mustAdd[prob.row] += prob.n;
    } else if (prob.type == "overlong_rowspan") {
      const cell = table2.nodeAt(prob.pos);
      if (!cell)
        continue;
      tr2.setNodeMarkup(tr2.mapping.map(tablePos + 1 + prob.pos), null, {
        ...cell.attrs,
        rowspan: cell.attrs.rowspan - prob.n
      });
    } else if (prob.type == "colwidth mismatch") {
      const cell = table2.nodeAt(prob.pos);
      if (!cell)
        continue;
      tr2.setNodeMarkup(tr2.mapping.map(tablePos + 1 + prob.pos), null, {
        ...cell.attrs,
        colwidth: prob.colwidth
      });
    }
  }
  let first2, last;
  for (let i2 = 0; i2 < mustAdd.length; i2++)
    if (mustAdd[i2]) {
      if (first2 == null)
        first2 = i2;
      last = i2;
    }
  for (let i2 = 0, pos = tablePos + 1; i2 < map3.height; i2++) {
    const row = table2.child(i2);
    const end = pos + row.nodeSize;
    const add3 = mustAdd[i2];
    if (add3 > 0) {
      let role = "cell";
      if (row.firstChild) {
        role = row.firstChild.type.spec.tableRole;
      }
      const nodes = [];
      for (let j2 = 0; j2 < add3; j2++) {
        const node2 = tableNodeTypes(state.schema)[role].createAndFill();
        if (node2)
          nodes.push(node2);
      }
      const side = (i2 == 0 || first2 == i2 - 1) && last == i2 ? pos + 1 : end - 1;
      tr2.insert(tr2.mapping.map(side), nodes);
    }
    pos = end;
  }
  return tr2.setMeta(fixTablesKey, { fixTables: true });
}
__name(fixTable, "fixTable");
function selectedRect(state) {
  const sel = state.selection;
  const $pos = selectionCell(state);
  const table2 = $pos.node(-1);
  const tableStart = $pos.start(-1);
  const map3 = TableMap.get(table2);
  const rect = sel instanceof CellSelection ? map3.rectBetween(
    sel.$anchorCell.pos - tableStart,
    sel.$headCell.pos - tableStart
  ) : map3.findCell($pos.pos - tableStart);
  return { ...rect, tableStart, map: map3, table: table2 };
}
__name(selectedRect, "selectedRect");
function addColumn(tr2, { map: map3, tableStart, table: table2 }, col) {
  let refColumn = col > 0 ? -1 : 0;
  if (columnIsHeader(map3, table2, col + refColumn)) {
    refColumn = col == 0 || col == map3.width ? null : 0;
  }
  for (let row = 0; row < map3.height; row++) {
    const index2 = row * map3.width + col;
    if (col > 0 && col < map3.width && map3.map[index2 - 1] == map3.map[index2]) {
      const pos = map3.map[index2];
      const cell = table2.nodeAt(pos);
      tr2.setNodeMarkup(
        tr2.mapping.map(tableStart + pos),
        null,
        addColSpan(cell.attrs, col - map3.colCount(pos))
      );
      row += cell.attrs.rowspan - 1;
    } else {
      const type = refColumn == null ? tableNodeTypes(table2.type.schema).cell : table2.nodeAt(map3.map[index2 + refColumn]).type;
      const pos = map3.positionAt(row, col, table2);
      tr2.insert(tr2.mapping.map(tableStart + pos), type.createAndFill());
    }
  }
  return tr2;
}
__name(addColumn, "addColumn");
function addColumnBefore(state, dispatch) {
  if (!isInTable(state))
    return false;
  if (dispatch) {
    const rect = selectedRect(state);
    dispatch(addColumn(state.tr, rect, rect.left));
  }
  return true;
}
__name(addColumnBefore, "addColumnBefore");
function addColumnAfter(state, dispatch) {
  if (!isInTable(state))
    return false;
  if (dispatch) {
    const rect = selectedRect(state);
    dispatch(addColumn(state.tr, rect, rect.right));
  }
  return true;
}
__name(addColumnAfter, "addColumnAfter");
function removeColumn(tr2, { map: map3, table: table2, tableStart }, col) {
  const mapStart = tr2.mapping.maps.length;
  for (let row = 0; row < map3.height; ) {
    const index2 = row * map3.width + col;
    const pos = map3.map[index2];
    const cell = table2.nodeAt(pos);
    const attrs2 = cell.attrs;
    if (col > 0 && map3.map[index2 - 1] == pos || col < map3.width - 1 && map3.map[index2 + 1] == pos) {
      tr2.setNodeMarkup(
        tr2.mapping.slice(mapStart).map(tableStart + pos),
        null,
        removeColSpan(attrs2, col - map3.colCount(pos))
      );
    } else {
      const start2 = tr2.mapping.slice(mapStart).map(tableStart + pos);
      tr2.delete(start2, start2 + cell.nodeSize);
    }
    row += attrs2.rowspan;
  }
}
__name(removeColumn, "removeColumn");
function deleteColumn(state, dispatch) {
  if (!isInTable(state))
    return false;
  if (dispatch) {
    const rect = selectedRect(state);
    const tr2 = state.tr;
    if (rect.left == 0 && rect.right == rect.map.width)
      return false;
    for (let i2 = rect.right - 1; ; i2--) {
      removeColumn(tr2, rect, i2);
      if (i2 == rect.left)
        break;
      const table2 = rect.tableStart ? tr2.doc.nodeAt(rect.tableStart - 1) : tr2.doc;
      if (!table2) {
        throw RangeError("No table found");
      }
      rect.table = table2;
      rect.map = TableMap.get(table2);
    }
    dispatch(tr2);
  }
  return true;
}
__name(deleteColumn, "deleteColumn");
function rowIsHeader(map3, table2, row) {
  var _a2;
  const headerCell = tableNodeTypes(table2.type.schema).header_cell;
  for (let col = 0; col < map3.width; col++)
    if (((_a2 = table2.nodeAt(map3.map[col + row * map3.width])) == null ? void 0 : _a2.type) != headerCell)
      return false;
  return true;
}
__name(rowIsHeader, "rowIsHeader");
function addRow(tr2, { map: map3, tableStart, table: table2 }, row) {
  var _a2;
  let rowPos = tableStart;
  for (let i2 = 0; i2 < row; i2++)
    rowPos += table2.child(i2).nodeSize;
  const cells = [];
  let refRow = row > 0 ? -1 : 0;
  if (rowIsHeader(map3, table2, row + refRow))
    refRow = row == 0 || row == map3.height ? null : 0;
  for (let col = 0, index2 = map3.width * row; col < map3.width; col++, index2++) {
    if (row > 0 && row < map3.height && map3.map[index2] == map3.map[index2 - map3.width]) {
      const pos = map3.map[index2];
      const attrs2 = table2.nodeAt(pos).attrs;
      tr2.setNodeMarkup(tableStart + pos, null, {
        ...attrs2,
        rowspan: attrs2.rowspan + 1
      });
      col += attrs2.colspan - 1;
    } else {
      const type = refRow == null ? tableNodeTypes(table2.type.schema).cell : (_a2 = table2.nodeAt(map3.map[index2 + refRow * map3.width])) == null ? void 0 : _a2.type;
      const node2 = type == null ? void 0 : type.createAndFill();
      if (node2)
        cells.push(node2);
    }
  }
  tr2.insert(rowPos, tableNodeTypes(table2.type.schema).row.create(null, cells));
  return tr2;
}
__name(addRow, "addRow");
function addRowBefore(state, dispatch) {
  if (!isInTable(state))
    return false;
  if (dispatch) {
    const rect = selectedRect(state);
    dispatch(addRow(state.tr, rect, rect.top));
  }
  return true;
}
__name(addRowBefore, "addRowBefore");
function addRowAfter(state, dispatch) {
  if (!isInTable(state))
    return false;
  if (dispatch) {
    const rect = selectedRect(state);
    dispatch(addRow(state.tr, rect, rect.bottom));
  }
  return true;
}
__name(addRowAfter, "addRowAfter");
function removeRow(tr2, { map: map3, table: table2, tableStart }, row) {
  let rowPos = 0;
  for (let i2 = 0; i2 < row; i2++)
    rowPos += table2.child(i2).nodeSize;
  const nextRow = rowPos + table2.child(row).nodeSize;
  const mapFrom = tr2.mapping.maps.length;
  tr2.delete(rowPos + tableStart, nextRow + tableStart);
  const seen2 = /* @__PURE__ */ new Set();
  for (let col = 0, index2 = row * map3.width; col < map3.width; col++, index2++) {
    const pos = map3.map[index2];
    if (seen2.has(pos))
      continue;
    seen2.add(pos);
    if (row > 0 && pos == map3.map[index2 - map3.width]) {
      const attrs2 = table2.nodeAt(pos).attrs;
      tr2.setNodeMarkup(tr2.mapping.slice(mapFrom).map(pos + tableStart), null, {
        ...attrs2,
        rowspan: attrs2.rowspan - 1
      });
      col += attrs2.colspan - 1;
    } else if (row < map3.height && pos == map3.map[index2 + map3.width]) {
      const cell = table2.nodeAt(pos);
      const attrs2 = cell.attrs;
      const copy2 = cell.type.create(
        { ...attrs2, rowspan: cell.attrs.rowspan - 1 },
        cell.content
      );
      const newPos = map3.positionAt(row + 1, col, table2);
      tr2.insert(tr2.mapping.slice(mapFrom).map(tableStart + newPos), copy2);
      col += attrs2.colspan - 1;
    }
  }
}
__name(removeRow, "removeRow");
function deleteRow(state, dispatch) {
  if (!isInTable(state))
    return false;
  if (dispatch) {
    const rect = selectedRect(state), tr2 = state.tr;
    if (rect.top == 0 && rect.bottom == rect.map.height)
      return false;
    for (let i2 = rect.bottom - 1; ; i2--) {
      removeRow(tr2, rect, i2);
      if (i2 == rect.top)
        break;
      const table2 = rect.tableStart ? tr2.doc.nodeAt(rect.tableStart - 1) : tr2.doc;
      if (!table2) {
        throw RangeError("No table found");
      }
      rect.table = table2;
      rect.map = TableMap.get(rect.table);
    }
    dispatch(tr2);
  }
  return true;
}
__name(deleteRow, "deleteRow");
function isEmpty(cell) {
  const c2 = cell.content;
  return c2.childCount == 1 && c2.child(0).isTextblock && c2.child(0).childCount == 0;
}
__name(isEmpty, "isEmpty");
function cellsOverlapRectangle({ width: width2, height, map: map3 }, rect) {
  let indexTop = rect.top * width2 + rect.left, indexLeft = indexTop;
  let indexBottom = (rect.bottom - 1) * width2 + rect.left, indexRight = indexTop + (rect.right - rect.left - 1);
  for (let i2 = rect.top; i2 < rect.bottom; i2++) {
    if (rect.left > 0 && map3[indexLeft] == map3[indexLeft - 1] || rect.right < width2 && map3[indexRight] == map3[indexRight + 1])
      return true;
    indexLeft += width2;
    indexRight += width2;
  }
  for (let i2 = rect.left; i2 < rect.right; i2++) {
    if (rect.top > 0 && map3[indexTop] == map3[indexTop - width2] || rect.bottom < height && map3[indexBottom] == map3[indexBottom + width2])
      return true;
    indexTop++;
    indexBottom++;
  }
  return false;
}
__name(cellsOverlapRectangle, "cellsOverlapRectangle");
function mergeCells(state, dispatch) {
  const sel = state.selection;
  if (!(sel instanceof CellSelection) || sel.$anchorCell.pos == sel.$headCell.pos)
    return false;
  const rect = selectedRect(state), { map: map3 } = rect;
  if (cellsOverlapRectangle(map3, rect))
    return false;
  if (dispatch) {
    const tr2 = state.tr;
    const seen2 = {};
    let content = Fragment.empty;
    let mergedPos;
    let mergedCell;
    for (let row = rect.top; row < rect.bottom; row++) {
      for (let col = rect.left; col < rect.right; col++) {
        const cellPos = map3.map[row * map3.width + col];
        const cell = rect.table.nodeAt(cellPos);
        if (seen2[cellPos] || !cell)
          continue;
        seen2[cellPos] = true;
        if (mergedPos == null) {
          mergedPos = cellPos;
          mergedCell = cell;
        } else {
          if (!isEmpty(cell))
            content = content.append(cell.content);
          const mapped = tr2.mapping.map(cellPos + rect.tableStart);
          tr2.delete(mapped, mapped + cell.nodeSize);
        }
      }
    }
    if (mergedPos == null || mergedCell == null) {
      return true;
    }
    tr2.setNodeMarkup(mergedPos + rect.tableStart, null, {
      ...addColSpan(
        mergedCell.attrs,
        mergedCell.attrs.colspan,
        rect.right - rect.left - mergedCell.attrs.colspan
      ),
      rowspan: rect.bottom - rect.top
    });
    if (content.size) {
      const end = mergedPos + 1 + mergedCell.content.size;
      const start2 = isEmpty(mergedCell) ? mergedPos + 1 : end;
      tr2.replaceWith(start2 + rect.tableStart, end + rect.tableStart, content);
    }
    tr2.setSelection(
      new CellSelection(tr2.doc.resolve(mergedPos + rect.tableStart))
    );
    dispatch(tr2);
  }
  return true;
}
__name(mergeCells, "mergeCells");
function splitCell(state, dispatch) {
  const nodeTypes = tableNodeTypes(state.schema);
  return splitCellWithType(({ node: node2 }) => {
    return nodeTypes[node2.type.spec.tableRole];
  })(state, dispatch);
}
__name(splitCell, "splitCell");
function splitCellWithType(getCellType) {
  return (state, dispatch) => {
    var _a2;
    const sel = state.selection;
    let cellNode;
    let cellPos;
    if (!(sel instanceof CellSelection)) {
      cellNode = cellWrapping(sel.$from);
      if (!cellNode)
        return false;
      cellPos = (_a2 = cellAround(sel.$from)) == null ? void 0 : _a2.pos;
    } else {
      if (sel.$anchorCell.pos != sel.$headCell.pos)
        return false;
      cellNode = sel.$anchorCell.nodeAfter;
      cellPos = sel.$anchorCell.pos;
    }
    if (cellNode == null || cellPos == null) {
      return false;
    }
    if (cellNode.attrs.colspan == 1 && cellNode.attrs.rowspan == 1) {
      return false;
    }
    if (dispatch) {
      let baseAttrs = cellNode.attrs;
      const attrs2 = [];
      const colwidth = baseAttrs.colwidth;
      if (baseAttrs.rowspan > 1)
        baseAttrs = { ...baseAttrs, rowspan: 1 };
      if (baseAttrs.colspan > 1)
        baseAttrs = { ...baseAttrs, colspan: 1 };
      const rect = selectedRect(state), tr2 = state.tr;
      for (let i2 = 0; i2 < rect.right - rect.left; i2++)
        attrs2.push(
          colwidth ? {
            ...baseAttrs,
            colwidth: colwidth && colwidth[i2] ? [colwidth[i2]] : null
          } : baseAttrs
        );
      let lastCell;
      for (let row = rect.top; row < rect.bottom; row++) {
        let pos = rect.map.positionAt(row, rect.left, rect.table);
        if (row == rect.top)
          pos += cellNode.nodeSize;
        for (let col = rect.left, i2 = 0; col < rect.right; col++, i2++) {
          if (col == rect.left && row == rect.top)
            continue;
          tr2.insert(
            lastCell = tr2.mapping.map(pos + rect.tableStart, 1),
            getCellType({ node: cellNode, row, col }).createAndFill(attrs2[i2])
          );
        }
      }
      tr2.setNodeMarkup(
        cellPos,
        getCellType({ node: cellNode, row: rect.top, col: rect.left }),
        attrs2[0]
      );
      if (sel instanceof CellSelection)
        tr2.setSelection(
          new CellSelection(
            tr2.doc.resolve(sel.$anchorCell.pos),
            lastCell ? tr2.doc.resolve(lastCell) : void 0
          )
        );
      dispatch(tr2);
    }
    return true;
  };
}
__name(splitCellWithType, "splitCellWithType");
function setCellAttr(name2, value) {
  return function(state, dispatch) {
    if (!isInTable(state))
      return false;
    const $cell = selectionCell(state);
    if ($cell.nodeAfter.attrs[name2] === value)
      return false;
    if (dispatch) {
      const tr2 = state.tr;
      if (state.selection instanceof CellSelection)
        state.selection.forEachCell((node2, pos) => {
          if (node2.attrs[name2] !== value)
            tr2.setNodeMarkup(pos, null, {
              ...node2.attrs,
              [name2]: value
            });
        });
      else
        tr2.setNodeMarkup($cell.pos, null, {
          ...$cell.nodeAfter.attrs,
          [name2]: value
        });
      dispatch(tr2);
    }
    return true;
  };
}
__name(setCellAttr, "setCellAttr");
function deprecated_toggleHeader(type) {
  return function(state, dispatch) {
    if (!isInTable(state))
      return false;
    if (dispatch) {
      const types = tableNodeTypes(state.schema);
      const rect = selectedRect(state), tr2 = state.tr;
      const cells = rect.map.cellsInRect(
        type == "column" ? {
          left: rect.left,
          top: 0,
          right: rect.right,
          bottom: rect.map.height
        } : type == "row" ? {
          left: 0,
          top: rect.top,
          right: rect.map.width,
          bottom: rect.bottom
        } : rect
      );
      const nodes = cells.map((pos) => rect.table.nodeAt(pos));
      for (let i2 = 0; i2 < cells.length; i2++)
        if (nodes[i2].type == types.header_cell)
          tr2.setNodeMarkup(
            rect.tableStart + cells[i2],
            types.cell,
            nodes[i2].attrs
          );
      if (tr2.steps.length == 0)
        for (let i2 = 0; i2 < cells.length; i2++)
          tr2.setNodeMarkup(
            rect.tableStart + cells[i2],
            types.header_cell,
            nodes[i2].attrs
          );
      dispatch(tr2);
    }
    return true;
  };
}
__name(deprecated_toggleHeader, "deprecated_toggleHeader");
function isHeaderEnabledByType(type, rect, types) {
  const cellPositions = rect.map.cellsInRect({
    left: 0,
    top: 0,
    right: type == "row" ? rect.map.width : 1,
    bottom: type == "column" ? rect.map.height : 1
  });
  for (let i2 = 0; i2 < cellPositions.length; i2++) {
    const cell = rect.table.nodeAt(cellPositions[i2]);
    if (cell && cell.type !== types.header_cell) {
      return false;
    }
  }
  return true;
}
__name(isHeaderEnabledByType, "isHeaderEnabledByType");
function toggleHeader(type, options2) {
  options2 = options2 || { useDeprecatedLogic: false };
  if (options2.useDeprecatedLogic)
    return deprecated_toggleHeader(type);
  return function(state, dispatch) {
    if (!isInTable(state))
      return false;
    if (dispatch) {
      const types = tableNodeTypes(state.schema);
      const rect = selectedRect(state), tr2 = state.tr;
      const isHeaderRowEnabled = isHeaderEnabledByType("row", rect, types);
      const isHeaderColumnEnabled = isHeaderEnabledByType(
        "column",
        rect,
        types
      );
      const isHeaderEnabled = type === "column" ? isHeaderRowEnabled : type === "row" ? isHeaderColumnEnabled : false;
      const selectionStartsAt = isHeaderEnabled ? 1 : 0;
      const cellsRect = type == "column" ? {
        left: 0,
        top: selectionStartsAt,
        right: 1,
        bottom: rect.map.height
      } : type == "row" ? {
        left: selectionStartsAt,
        top: 0,
        right: rect.map.width,
        bottom: 1
      } : rect;
      const newType = type == "column" ? isHeaderColumnEnabled ? types.cell : types.header_cell : type == "row" ? isHeaderRowEnabled ? types.cell : types.header_cell : types.cell;
      rect.map.cellsInRect(cellsRect).forEach((relativeCellPos) => {
        const cellPos = relativeCellPos + rect.tableStart;
        const cell = tr2.doc.nodeAt(cellPos);
        if (cell) {
          tr2.setNodeMarkup(cellPos, newType, cell.attrs);
        }
      });
      dispatch(tr2);
    }
    return true;
  };
}
__name(toggleHeader, "toggleHeader");
var toggleHeaderRow = toggleHeader("row", {
  useDeprecatedLogic: true
});
var toggleHeaderColumn = toggleHeader("column", {
  useDeprecatedLogic: true
});
var toggleHeaderCell = toggleHeader("cell", {
  useDeprecatedLogic: true
});
function findNextCell($cell, dir) {
  if (dir < 0) {
    const before = $cell.nodeBefore;
    if (before)
      return $cell.pos - before.nodeSize;
    for (let row = $cell.index(-1) - 1, rowEnd = $cell.before(); row >= 0; row--) {
      const rowNode = $cell.node(-1).child(row);
      const lastChild = rowNode.lastChild;
      if (lastChild) {
        return rowEnd - 1 - lastChild.nodeSize;
      }
      rowEnd -= rowNode.nodeSize;
    }
  } else {
    if ($cell.index() < $cell.parent.childCount - 1) {
      return $cell.pos + $cell.nodeAfter.nodeSize;
    }
    const table2 = $cell.node(-1);
    for (let row = $cell.indexAfter(-1), rowStart = $cell.after(); row < table2.childCount; row++) {
      const rowNode = table2.child(row);
      if (rowNode.childCount)
        return rowStart + 1;
      rowStart += rowNode.nodeSize;
    }
  }
  return null;
}
__name(findNextCell, "findNextCell");
function goToNextCell(direction) {
  return function(state, dispatch) {
    if (!isInTable(state))
      return false;
    const cell = findNextCell(selectionCell(state), direction);
    if (cell == null)
      return false;
    if (dispatch) {
      const $cell = state.doc.resolve(cell);
      dispatch(
        state.tr.setSelection(TextSelection.between($cell, moveCellForward($cell))).scrollIntoView()
      );
    }
    return true;
  };
}
__name(goToNextCell, "goToNextCell");
function deleteTable(state, dispatch) {
  const $pos = state.selection.$anchor;
  for (let d2 = $pos.depth; d2 > 0; d2--) {
    const node2 = $pos.node(d2);
    if (node2.type.spec.tableRole == "table") {
      if (dispatch)
        dispatch(
          state.tr.delete($pos.before(d2), $pos.after(d2)).scrollIntoView()
        );
      return true;
    }
  }
  return false;
}
__name(deleteTable, "deleteTable");
function deleteCellSelection(state, dispatch) {
  const sel = state.selection;
  if (!(sel instanceof CellSelection))
    return false;
  if (dispatch) {
    const tr2 = state.tr;
    const baseContent = tableNodeTypes(state.schema).cell.createAndFill().content;
    sel.forEachCell((cell, pos) => {
      if (!cell.content.eq(baseContent))
        tr2.replace(
          tr2.mapping.map(pos + 1),
          tr2.mapping.map(pos + cell.nodeSize - 1),
          new Slice(baseContent, 0, 0)
        );
    });
    if (tr2.docChanged)
      dispatch(tr2);
  }
  return true;
}
__name(deleteCellSelection, "deleteCellSelection");
function pastedCells(slice2) {
  if (!slice2.size)
    return null;
  let { content, openStart, openEnd } = slice2;
  while (content.childCount == 1 && (openStart > 0 && openEnd > 0 || content.child(0).type.spec.tableRole == "table")) {
    openStart--;
    openEnd--;
    content = content.child(0).content;
  }
  const first2 = content.child(0);
  const role = first2.type.spec.tableRole;
  const schema2 = first2.type.schema, rows = [];
  if (role == "row") {
    for (let i2 = 0; i2 < content.childCount; i2++) {
      let cells = content.child(i2).content;
      const left = i2 ? 0 : Math.max(0, openStart - 1);
      const right = i2 < content.childCount - 1 ? 0 : Math.max(0, openEnd - 1);
      if (left || right)
        cells = fitSlice(
          tableNodeTypes(schema2).row,
          new Slice(cells, left, right)
        ).content;
      rows.push(cells);
    }
  } else if (role == "cell" || role == "header_cell") {
    rows.push(
      openStart || openEnd ? fitSlice(
        tableNodeTypes(schema2).row,
        new Slice(content, openStart, openEnd)
      ).content : content
    );
  } else {
    return null;
  }
  return ensureRectangular(schema2, rows);
}
__name(pastedCells, "pastedCells");
function ensureRectangular(schema2, rows) {
  const widths = [];
  for (let i2 = 0; i2 < rows.length; i2++) {
    const row = rows[i2];
    for (let j2 = row.childCount - 1; j2 >= 0; j2--) {
      const { rowspan, colspan } = row.child(j2).attrs;
      for (let r2 = i2; r2 < i2 + rowspan; r2++)
        widths[r2] = (widths[r2] || 0) + colspan;
    }
  }
  let width2 = 0;
  for (let r2 = 0; r2 < widths.length; r2++)
    width2 = Math.max(width2, widths[r2]);
  for (let r2 = 0; r2 < widths.length; r2++) {
    if (r2 >= rows.length)
      rows.push(Fragment.empty);
    if (widths[r2] < width2) {
      const empty2 = tableNodeTypes(schema2).cell.createAndFill();
      const cells = [];
      for (let i2 = widths[r2]; i2 < width2; i2++) {
        cells.push(empty2);
      }
      rows[r2] = rows[r2].append(Fragment.from(cells));
    }
  }
  return { height: rows.length, width: width2, rows };
}
__name(ensureRectangular, "ensureRectangular");
function fitSlice(nodeType, slice2) {
  const node2 = nodeType.createAndFill();
  const tr2 = new Transform(node2).replace(0, node2.content.size, slice2);
  return tr2.doc;
}
__name(fitSlice, "fitSlice");
function clipCells({ width: width2, height, rows }, newWidth, newHeight) {
  if (width2 != newWidth) {
    const added = [];
    const newRows = [];
    for (let row = 0; row < rows.length; row++) {
      const frag = rows[row], cells = [];
      for (let col = added[row] || 0, i2 = 0; col < newWidth; i2++) {
        let cell = frag.child(i2 % frag.childCount);
        if (col + cell.attrs.colspan > newWidth)
          cell = cell.type.createChecked(
            removeColSpan(
              cell.attrs,
              cell.attrs.colspan,
              col + cell.attrs.colspan - newWidth
            ),
            cell.content
          );
        cells.push(cell);
        col += cell.attrs.colspan;
        for (let j2 = 1; j2 < cell.attrs.rowspan; j2++)
          added[row + j2] = (added[row + j2] || 0) + cell.attrs.colspan;
      }
      newRows.push(Fragment.from(cells));
    }
    rows = newRows;
    width2 = newWidth;
  }
  if (height != newHeight) {
    const newRows = [];
    for (let row = 0, i2 = 0; row < newHeight; row++, i2++) {
      const cells = [], source = rows[i2 % height];
      for (let j2 = 0; j2 < source.childCount; j2++) {
        let cell = source.child(j2);
        if (row + cell.attrs.rowspan > newHeight)
          cell = cell.type.create(
            {
              ...cell.attrs,
              rowspan: Math.max(1, newHeight - cell.attrs.rowspan)
            },
            cell.content
          );
        cells.push(cell);
      }
      newRows.push(Fragment.from(cells));
    }
    rows = newRows;
    height = newHeight;
  }
  return { width: width2, height, rows };
}
__name(clipCells, "clipCells");
function growTable(tr2, map3, table2, start2, width2, height, mapFrom) {
  const schema2 = tr2.doc.type.schema;
  const types = tableNodeTypes(schema2);
  let empty2;
  let emptyHead;
  if (width2 > map3.width) {
    for (let row = 0, rowEnd = 0; row < map3.height; row++) {
      const rowNode = table2.child(row);
      rowEnd += rowNode.nodeSize;
      const cells = [];
      let add3;
      if (rowNode.lastChild == null || rowNode.lastChild.type == types.cell)
        add3 = empty2 || (empty2 = types.cell.createAndFill());
      else
        add3 = emptyHead || (emptyHead = types.header_cell.createAndFill());
      for (let i2 = map3.width; i2 < width2; i2++)
        cells.push(add3);
      tr2.insert(tr2.mapping.slice(mapFrom).map(rowEnd - 1 + start2), cells);
    }
  }
  if (height > map3.height) {
    const cells = [];
    for (let i2 = 0, start22 = (map3.height - 1) * map3.width; i2 < Math.max(map3.width, width2); i2++) {
      const header = i2 >= map3.width ? false : table2.nodeAt(map3.map[start22 + i2]).type == types.header_cell;
      cells.push(
        header ? emptyHead || (emptyHead = types.header_cell.createAndFill()) : empty2 || (empty2 = types.cell.createAndFill())
      );
    }
    const emptyRow = types.row.create(null, Fragment.from(cells)), rows = [];
    for (let i2 = map3.height; i2 < height; i2++)
      rows.push(emptyRow);
    tr2.insert(tr2.mapping.slice(mapFrom).map(start2 + table2.nodeSize - 2), rows);
  }
  return !!(empty2 || emptyHead);
}
__name(growTable, "growTable");
function isolateHorizontal(tr2, map3, table2, start2, left, right, top, mapFrom) {
  if (top == 0 || top == map3.height)
    return false;
  let found2 = false;
  for (let col = left; col < right; col++) {
    const index2 = top * map3.width + col, pos = map3.map[index2];
    if (map3.map[index2 - map3.width] == pos) {
      found2 = true;
      const cell = table2.nodeAt(pos);
      const { top: cellTop, left: cellLeft } = map3.findCell(pos);
      tr2.setNodeMarkup(tr2.mapping.slice(mapFrom).map(pos + start2), null, {
        ...cell.attrs,
        rowspan: top - cellTop
      });
      tr2.insert(
        tr2.mapping.slice(mapFrom).map(map3.positionAt(top, cellLeft, table2)),
        cell.type.createAndFill({
          ...cell.attrs,
          rowspan: cellTop + cell.attrs.rowspan - top
        })
      );
      col += cell.attrs.colspan - 1;
    }
  }
  return found2;
}
__name(isolateHorizontal, "isolateHorizontal");
function isolateVertical(tr2, map3, table2, start2, top, bottom, left, mapFrom) {
  if (left == 0 || left == map3.width)
    return false;
  let found2 = false;
  for (let row = top; row < bottom; row++) {
    const index2 = row * map3.width + left, pos = map3.map[index2];
    if (map3.map[index2 - 1] == pos) {
      found2 = true;
      const cell = table2.nodeAt(pos);
      const cellLeft = map3.colCount(pos);
      const updatePos = tr2.mapping.slice(mapFrom).map(pos + start2);
      tr2.setNodeMarkup(
        updatePos,
        null,
        removeColSpan(
          cell.attrs,
          left - cellLeft,
          cell.attrs.colspan - (left - cellLeft)
        )
      );
      tr2.insert(
        updatePos + cell.nodeSize,
        cell.type.createAndFill(
          removeColSpan(cell.attrs, 0, left - cellLeft)
        )
      );
      row += cell.attrs.rowspan - 1;
    }
  }
  return found2;
}
__name(isolateVertical, "isolateVertical");
function insertCells(state, dispatch, tableStart, rect, cells) {
  let table2 = tableStart ? state.doc.nodeAt(tableStart - 1) : state.doc;
  if (!table2) {
    throw new Error("No table found");
  }
  let map3 = TableMap.get(table2);
  const { top, left } = rect;
  const right = left + cells.width, bottom = top + cells.height;
  const tr2 = state.tr;
  let mapFrom = 0;
  function recomp() {
    table2 = tableStart ? tr2.doc.nodeAt(tableStart - 1) : tr2.doc;
    if (!table2) {
      throw new Error("No table found");
    }
    map3 = TableMap.get(table2);
    mapFrom = tr2.mapping.maps.length;
  }
  __name(recomp, "recomp");
  if (growTable(tr2, map3, table2, tableStart, right, bottom, mapFrom))
    recomp();
  if (isolateHorizontal(tr2, map3, table2, tableStart, left, right, top, mapFrom))
    recomp();
  if (isolateHorizontal(tr2, map3, table2, tableStart, left, right, bottom, mapFrom))
    recomp();
  if (isolateVertical(tr2, map3, table2, tableStart, top, bottom, left, mapFrom))
    recomp();
  if (isolateVertical(tr2, map3, table2, tableStart, top, bottom, right, mapFrom))
    recomp();
  for (let row = top; row < bottom; row++) {
    const from2 = map3.positionAt(row, left, table2), to = map3.positionAt(row, right, table2);
    tr2.replace(
      tr2.mapping.slice(mapFrom).map(from2 + tableStart),
      tr2.mapping.slice(mapFrom).map(to + tableStart),
      new Slice(cells.rows[row - top], 0, 0)
    );
  }
  recomp();
  tr2.setSelection(
    new CellSelection(
      tr2.doc.resolve(tableStart + map3.positionAt(top, left, table2)),
      tr2.doc.resolve(tableStart + map3.positionAt(bottom - 1, right - 1, table2))
    )
  );
  dispatch(tr2);
}
__name(insertCells, "insertCells");
var handleKeyDown$1 = keydownHandler({
  ArrowLeft: arrow$1("horiz", -1),
  ArrowRight: arrow$1("horiz", 1),
  ArrowUp: arrow$1("vert", -1),
  ArrowDown: arrow$1("vert", 1),
  "Shift-ArrowLeft": shiftArrow("horiz", -1),
  "Shift-ArrowRight": shiftArrow("horiz", 1),
  "Shift-ArrowUp": shiftArrow("vert", -1),
  "Shift-ArrowDown": shiftArrow("vert", 1),
  Backspace: deleteCellSelection,
  "Mod-Backspace": deleteCellSelection,
  Delete: deleteCellSelection,
  "Mod-Delete": deleteCellSelection
});
function maybeSetSelection(state, dispatch, selection) {
  if (selection.eq(state.selection))
    return false;
  if (dispatch)
    dispatch(state.tr.setSelection(selection).scrollIntoView());
  return true;
}
__name(maybeSetSelection, "maybeSetSelection");
function arrow$1(axis, dir) {
  return (state, dispatch, view) => {
    if (!view)
      return false;
    const sel = state.selection;
    if (sel instanceof CellSelection) {
      return maybeSetSelection(
        state,
        dispatch,
        Selection.near(sel.$headCell, dir)
      );
    }
    if (axis != "horiz" && !sel.empty)
      return false;
    const end = atEndOfCell(view, axis, dir);
    if (end == null)
      return false;
    if (axis == "horiz") {
      return maybeSetSelection(
        state,
        dispatch,
        Selection.near(state.doc.resolve(sel.head + dir), dir)
      );
    } else {
      const $cell = state.doc.resolve(end);
      const $next = nextCell($cell, axis, dir);
      let newSel;
      if ($next)
        newSel = Selection.near($next, 1);
      else if (dir < 0)
        newSel = Selection.near(state.doc.resolve($cell.before(-1)), -1);
      else
        newSel = Selection.near(state.doc.resolve($cell.after(-1)), 1);
      return maybeSetSelection(state, dispatch, newSel);
    }
  };
}
__name(arrow$1, "arrow$1");
function shiftArrow(axis, dir) {
  return (state, dispatch, view) => {
    if (!view)
      return false;
    const sel = state.selection;
    let cellSel;
    if (sel instanceof CellSelection) {
      cellSel = sel;
    } else {
      const end = atEndOfCell(view, axis, dir);
      if (end == null)
        return false;
      cellSel = new CellSelection(state.doc.resolve(end));
    }
    const $head = nextCell(cellSel.$headCell, axis, dir);
    if (!$head)
      return false;
    return maybeSetSelection(
      state,
      dispatch,
      new CellSelection(cellSel.$anchorCell, $head)
    );
  };
}
__name(shiftArrow, "shiftArrow");
function handleTripleClick(view, pos) {
  const doc2 = view.state.doc, $cell = cellAround(doc2.resolve(pos));
  if (!$cell)
    return false;
  view.dispatch(view.state.tr.setSelection(new CellSelection($cell)));
  return true;
}
__name(handleTripleClick, "handleTripleClick");
function handlePaste(view, _2, slice2) {
  if (!isInTable(view.state))
    return false;
  let cells = pastedCells(slice2);
  const sel = view.state.selection;
  if (sel instanceof CellSelection) {
    if (!cells)
      cells = {
        width: 1,
        height: 1,
        rows: [
          Fragment.from(
            fitSlice(tableNodeTypes(view.state.schema).cell, slice2)
          )
        ]
      };
    const table2 = sel.$anchorCell.node(-1);
    const start2 = sel.$anchorCell.start(-1);
    const rect = TableMap.get(table2).rectBetween(
      sel.$anchorCell.pos - start2,
      sel.$headCell.pos - start2
    );
    cells = clipCells(cells, rect.right - rect.left, rect.bottom - rect.top);
    insertCells(view.state, view.dispatch, start2, rect, cells);
    return true;
  } else if (cells) {
    const $cell = selectionCell(view.state);
    const start2 = $cell.start(-1);
    insertCells(
      view.state,
      view.dispatch,
      start2,
      TableMap.get($cell.node(-1)).findCell($cell.pos - start2),
      cells
    );
    return true;
  } else {
    return false;
  }
}
__name(handlePaste, "handlePaste");
function handleMouseDown(view, startEvent) {
  var _a2;
  if (startEvent.ctrlKey || startEvent.metaKey)
    return;
  const startDOMCell = domInCell(view, startEvent.target);
  let $anchor;
  if (startEvent.shiftKey && view.state.selection instanceof CellSelection) {
    setCellSelection(view.state.selection.$anchorCell, startEvent);
    startEvent.preventDefault();
  } else if (startEvent.shiftKey && startDOMCell && ($anchor = cellAround(view.state.selection.$anchor)) != null && ((_a2 = cellUnderMouse(view, startEvent)) == null ? void 0 : _a2.pos) != $anchor.pos) {
    setCellSelection($anchor, startEvent);
    startEvent.preventDefault();
  } else if (!startDOMCell) {
    return;
  }
  function setCellSelection($anchor2, event) {
    let $head = cellUnderMouse(view, event);
    const starting = tableEditingKey.getState(view.state) == null;
    if (!$head || !inSameTable($anchor2, $head)) {
      if (starting)
        $head = $anchor2;
      else
        return;
    }
    const selection = new CellSelection($anchor2, $head);
    if (starting || !view.state.selection.eq(selection)) {
      const tr2 = view.state.tr.setSelection(selection);
      if (starting)
        tr2.setMeta(tableEditingKey, $anchor2.pos);
      view.dispatch(tr2);
    }
  }
  __name(setCellSelection, "setCellSelection");
  function stop2() {
    view.root.removeEventListener("mouseup", stop2);
    view.root.removeEventListener("dragstart", stop2);
    view.root.removeEventListener("mousemove", move);
    if (tableEditingKey.getState(view.state) != null)
      view.dispatch(view.state.tr.setMeta(tableEditingKey, -1));
  }
  __name(stop2, "stop");
  function move(_event) {
    const event = _event;
    const anchor = tableEditingKey.getState(view.state);
    let $anchor2;
    if (anchor != null) {
      $anchor2 = view.state.doc.resolve(anchor);
    } else if (domInCell(view, event.target) != startDOMCell) {
      $anchor2 = cellUnderMouse(view, startEvent);
      if (!$anchor2)
        return stop2();
    }
    if ($anchor2)
      setCellSelection($anchor2, event);
  }
  __name(move, "move");
  view.root.addEventListener("mouseup", stop2);
  view.root.addEventListener("dragstart", stop2);
  view.root.addEventListener("mousemove", move);
}
__name(handleMouseDown, "handleMouseDown");
function atEndOfCell(view, axis, dir) {
  if (!(view.state.selection instanceof TextSelection))
    return null;
  const { $head } = view.state.selection;
  for (let d2 = $head.depth - 1; d2 >= 0; d2--) {
    const parent2 = $head.node(d2), index2 = dir < 0 ? $head.index(d2) : $head.indexAfter(d2);
    if (index2 != (dir < 0 ? 0 : parent2.childCount))
      return null;
    if (parent2.type.spec.tableRole == "cell" || parent2.type.spec.tableRole == "header_cell") {
      const cellPos = $head.before(d2);
      const dirStr = axis == "vert" ? dir > 0 ? "down" : "up" : dir > 0 ? "right" : "left";
      return view.endOfTextblock(dirStr) ? cellPos : null;
    }
  }
  return null;
}
__name(atEndOfCell, "atEndOfCell");
function domInCell(view, dom) {
  for (; dom && dom != view.dom; dom = dom.parentNode) {
    if (dom.nodeName == "TD" || dom.nodeName == "TH") {
      return dom;
    }
  }
  return null;
}
__name(domInCell, "domInCell");
function cellUnderMouse(view, event) {
  const mousePos = view.posAtCoords({
    left: event.clientX,
    top: event.clientY
  });
  if (!mousePos)
    return null;
  return mousePos ? cellAround(view.state.doc.resolve(mousePos.pos)) : null;
}
__name(cellUnderMouse, "cellUnderMouse");
var TableView$1 = class TableView2 {
  static {
    __name(this, "TableView");
  }
  constructor(node2, defaultCellMinWidth) {
    this.node = node2;
    this.defaultCellMinWidth = defaultCellMinWidth;
    this.dom = document.createElement("div");
    this.dom.className = "tableWrapper";
    this.table = this.dom.appendChild(document.createElement("table"));
    this.table.style.setProperty(
      "--default-cell-min-width",
      `${defaultCellMinWidth}px`
    );
    this.colgroup = this.table.appendChild(document.createElement("colgroup"));
    updateColumnsOnResize(node2, this.colgroup, this.table, defaultCellMinWidth);
    this.contentDOM = this.table.appendChild(document.createElement("tbody"));
  }
  update(node2) {
    if (node2.type != this.node.type)
      return false;
    this.node = node2;
    updateColumnsOnResize(
      node2,
      this.colgroup,
      this.table,
      this.defaultCellMinWidth
    );
    return true;
  }
  ignoreMutation(record2) {
    return record2.type == "attributes" && (record2.target == this.table || this.colgroup.contains(record2.target));
  }
};
function updateColumnsOnResize(node2, colgroup, table2, defaultCellMinWidth, overrideCol, overrideValue) {
  var _a2;
  let totalWidth = 0;
  let fixedWidth = true;
  let nextDOM = colgroup.firstChild;
  const row = node2.firstChild;
  if (!row)
    return;
  for (let i2 = 0, col = 0; i2 < row.childCount; i2++) {
    const { colspan, colwidth } = row.child(i2).attrs;
    for (let j2 = 0; j2 < colspan; j2++, col++) {
      const hasWidth = overrideCol == col ? overrideValue : colwidth && colwidth[j2];
      const cssWidth = hasWidth ? hasWidth + "px" : "";
      totalWidth += hasWidth || defaultCellMinWidth;
      if (!hasWidth)
        fixedWidth = false;
      if (!nextDOM) {
        const col2 = document.createElement("col");
        col2.style.width = cssWidth;
        colgroup.appendChild(col2);
      } else {
        if (nextDOM.style.width != cssWidth) {
          nextDOM.style.width = cssWidth;
        }
        nextDOM = nextDOM.nextSibling;
      }
    }
  }
  while (nextDOM) {
    const after = nextDOM.nextSibling;
    (_a2 = nextDOM.parentNode) == null ? void 0 : _a2.removeChild(nextDOM);
    nextDOM = after;
  }
  if (fixedWidth) {
    table2.style.width = totalWidth + "px";
    table2.style.minWidth = "";
  } else {
    table2.style.width = "";
    table2.style.minWidth = totalWidth + "px";
  }
}
__name(updateColumnsOnResize, "updateColumnsOnResize");
var columnResizingPluginKey = new PluginKey(
  "tableColumnResizing"
);
function columnResizing({
  handleWidth = 5,
  cellMinWidth = 25,
  defaultCellMinWidth = 100,
  View: View2 = TableView$1,
  lastColumnResizable = true
} = {}) {
  const plugin = new Plugin({
    key: columnResizingPluginKey,
    state: {
      init(_2, state) {
        var _a2, _b;
        const nodeViews = (_b = (_a2 = plugin.spec) == null ? void 0 : _a2.props) == null ? void 0 : _b.nodeViews;
        const tableName = tableNodeTypes(state.schema).table.name;
        if (View2 && nodeViews) {
          nodeViews[tableName] = (node2, view) => {
            return new View2(node2, defaultCellMinWidth, view);
          };
        }
        return new ResizeState(-1, false);
      },
      apply(tr2, prev) {
        return prev.apply(tr2);
      }
    },
    props: {
      attributes: /* @__PURE__ */ __name((state) => {
        const pluginState = columnResizingPluginKey.getState(state);
        return pluginState && pluginState.activeHandle > -1 ? { class: "resize-cursor" } : {};
      }, "attributes"),
      handleDOMEvents: {
        mousemove: /* @__PURE__ */ __name((view, event) => {
          handleMouseMove(view, event, handleWidth, lastColumnResizable);
        }, "mousemove"),
        mouseleave: /* @__PURE__ */ __name((view) => {
          handleMouseLeave(view);
        }, "mouseleave"),
        mousedown: /* @__PURE__ */ __name((view, event) => {
          handleMouseDown2(view, event, cellMinWidth, defaultCellMinWidth);
        }, "mousedown")
      },
      decorations: /* @__PURE__ */ __name((state) => {
        const pluginState = columnResizingPluginKey.getState(state);
        if (pluginState && pluginState.activeHandle > -1) {
          return handleDecorations(state, pluginState.activeHandle);
        }
      }, "decorations"),
      nodeViews: {}
    }
  });
  return plugin;
}
__name(columnResizing, "columnResizing");
var ResizeState = class _ResizeState {
  static {
    __name(this, "_ResizeState");
  }
  constructor(activeHandle, dragging) {
    this.activeHandle = activeHandle;
    this.dragging = dragging;
  }
  apply(tr2) {
    const state = this;
    const action = tr2.getMeta(columnResizingPluginKey);
    if (action && action.setHandle != null)
      return new _ResizeState(action.setHandle, false);
    if (action && action.setDragging !== void 0)
      return new _ResizeState(state.activeHandle, action.setDragging);
    if (state.activeHandle > -1 && tr2.docChanged) {
      let handle = tr2.mapping.map(state.activeHandle, -1);
      if (!pointsAtCell(tr2.doc.resolve(handle))) {
        handle = -1;
      }
      return new _ResizeState(handle, state.dragging);
    }
    return state;
  }
};
function handleMouseMove(view, event, handleWidth, lastColumnResizable) {
  const pluginState = columnResizingPluginKey.getState(view.state);
  if (!pluginState)
    return;
  if (!pluginState.dragging) {
    const target = domCellAround(event.target);
    let cell = -1;
    if (target) {
      const { left, right } = target.getBoundingClientRect();
      if (event.clientX - left <= handleWidth)
        cell = edgeCell(view, event, "left", handleWidth);
      else if (right - event.clientX <= handleWidth)
        cell = edgeCell(view, event, "right", handleWidth);
    }
    if (cell != pluginState.activeHandle) {
      if (!lastColumnResizable && cell !== -1) {
        const $cell = view.state.doc.resolve(cell);
        const table2 = $cell.node(-1);
        const map3 = TableMap.get(table2);
        const tableStart = $cell.start(-1);
        const col = map3.colCount($cell.pos - tableStart) + $cell.nodeAfter.attrs.colspan - 1;
        if (col == map3.width - 1) {
          return;
        }
      }
      updateHandle(view, cell);
    }
  }
}
__name(handleMouseMove, "handleMouseMove");
function handleMouseLeave(view) {
  const pluginState = columnResizingPluginKey.getState(view.state);
  if (pluginState && pluginState.activeHandle > -1 && !pluginState.dragging)
    updateHandle(view, -1);
}
__name(handleMouseLeave, "handleMouseLeave");
function handleMouseDown2(view, event, cellMinWidth, defaultCellMinWidth) {
  var _a2;
  const win = (_a2 = view.dom.ownerDocument.defaultView) != null ? _a2 : window;
  const pluginState = columnResizingPluginKey.getState(view.state);
  if (!pluginState || pluginState.activeHandle == -1 || pluginState.dragging)
    return false;
  const cell = view.state.doc.nodeAt(pluginState.activeHandle);
  const width2 = currentColWidth(view, pluginState.activeHandle, cell.attrs);
  view.dispatch(
    view.state.tr.setMeta(columnResizingPluginKey, {
      setDragging: { startX: event.clientX, startWidth: width2 }
    })
  );
  function finish(event2) {
    win.removeEventListener("mouseup", finish);
    win.removeEventListener("mousemove", move);
    const pluginState2 = columnResizingPluginKey.getState(view.state);
    if (pluginState2 == null ? void 0 : pluginState2.dragging) {
      updateColumnWidth(
        view,
        pluginState2.activeHandle,
        draggedWidth(pluginState2.dragging, event2, cellMinWidth)
      );
      view.dispatch(
        view.state.tr.setMeta(columnResizingPluginKey, { setDragging: null })
      );
    }
  }
  __name(finish, "finish");
  function move(event2) {
    if (!event2.which)
      return finish(event2);
    const pluginState2 = columnResizingPluginKey.getState(view.state);
    if (!pluginState2)
      return;
    if (pluginState2.dragging) {
      const dragged = draggedWidth(pluginState2.dragging, event2, cellMinWidth);
      displayColumnWidth(
        view,
        pluginState2.activeHandle,
        dragged,
        defaultCellMinWidth
      );
    }
  }
  __name(move, "move");
  displayColumnWidth(
    view,
    pluginState.activeHandle,
    width2,
    defaultCellMinWidth
  );
  win.addEventListener("mouseup", finish);
  win.addEventListener("mousemove", move);
  event.preventDefault();
  return true;
}
__name(handleMouseDown2, "handleMouseDown2");
function currentColWidth(view, cellPos, { colspan, colwidth }) {
  const width2 = colwidth && colwidth[colwidth.length - 1];
  if (width2)
    return width2;
  const dom = view.domAtPos(cellPos);
  const node2 = dom.node.childNodes[dom.offset];
  let domWidth = node2.offsetWidth, parts2 = colspan;
  if (colwidth) {
    for (let i2 = 0; i2 < colspan; i2++)
      if (colwidth[i2]) {
        domWidth -= colwidth[i2];
        parts2--;
      }
  }
  return domWidth / parts2;
}
__name(currentColWidth, "currentColWidth");
function domCellAround(target) {
  while (target && target.nodeName != "TD" && target.nodeName != "TH")
    target = target.classList && target.classList.contains("ProseMirror") ? null : target.parentNode;
  return target;
}
__name(domCellAround, "domCellAround");
function edgeCell(view, event, side, handleWidth) {
  const offset = side == "right" ? -handleWidth : handleWidth;
  const found2 = view.posAtCoords({
    left: event.clientX + offset,
    top: event.clientY
  });
  if (!found2)
    return -1;
  const { pos } = found2;
  const $cell = cellAround(view.state.doc.resolve(pos));
  if (!$cell)
    return -1;
  if (side == "right")
    return $cell.pos;
  const map3 = TableMap.get($cell.node(-1)), start2 = $cell.start(-1);
  const index2 = map3.map.indexOf($cell.pos - start2);
  return index2 % map3.width == 0 ? -1 : start2 + map3.map[index2 - 1];
}
__name(edgeCell, "edgeCell");
function draggedWidth(dragging, event, resizeMinWidth) {
  const offset = event.clientX - dragging.startX;
  return Math.max(resizeMinWidth, dragging.startWidth + offset);
}
__name(draggedWidth, "draggedWidth");
function updateHandle(view, value) {
  view.dispatch(
    view.state.tr.setMeta(columnResizingPluginKey, { setHandle: value })
  );
}
__name(updateHandle, "updateHandle");
function updateColumnWidth(view, cell, width2) {
  const $cell = view.state.doc.resolve(cell);
  const table2 = $cell.node(-1), map3 = TableMap.get(table2), start2 = $cell.start(-1);
  const col = map3.colCount($cell.pos - start2) + $cell.nodeAfter.attrs.colspan - 1;
  const tr2 = view.state.tr;
  for (let row = 0; row < map3.height; row++) {
    const mapIndex = row * map3.width + col;
    if (row && map3.map[mapIndex] == map3.map[mapIndex - map3.width])
      continue;
    const pos = map3.map[mapIndex];
    const attrs2 = table2.nodeAt(pos).attrs;
    const index2 = attrs2.colspan == 1 ? 0 : col - map3.colCount(pos);
    if (attrs2.colwidth && attrs2.colwidth[index2] == width2)
      continue;
    const colwidth = attrs2.colwidth ? attrs2.colwidth.slice() : zeroes(attrs2.colspan);
    colwidth[index2] = width2;
    tr2.setNodeMarkup(start2 + pos, null, { ...attrs2, colwidth });
  }
  if (tr2.docChanged)
    view.dispatch(tr2);
}
__name(updateColumnWidth, "updateColumnWidth");
function displayColumnWidth(view, cell, width2, defaultCellMinWidth) {
  const $cell = view.state.doc.resolve(cell);
  const table2 = $cell.node(-1), start2 = $cell.start(-1);
  const col = TableMap.get(table2).colCount($cell.pos - start2) + $cell.nodeAfter.attrs.colspan - 1;
  let dom = view.domAtPos($cell.start(-1)).node;
  while (dom && dom.nodeName != "TABLE") {
    dom = dom.parentNode;
  }
  if (!dom)
    return;
  updateColumnsOnResize(
    table2,
    dom.firstChild,
    dom,
    defaultCellMinWidth,
    col,
    width2
  );
}
__name(displayColumnWidth, "displayColumnWidth");
function zeroes(n2) {
  return Array(n2).fill(0);
}
__name(zeroes, "zeroes");
function handleDecorations(state, cell) {
  var _a2;
  const decorations = [];
  const $cell = state.doc.resolve(cell);
  const table2 = $cell.node(-1);
  if (!table2) {
    return DecorationSet.empty;
  }
  const map3 = TableMap.get(table2);
  const start2 = $cell.start(-1);
  const col = map3.colCount($cell.pos - start2) + $cell.nodeAfter.attrs.colspan - 1;
  for (let row = 0; row < map3.height; row++) {
    const index2 = col + row * map3.width;
    if ((col == map3.width - 1 || map3.map[index2] != map3.map[index2 + 1]) && (row == 0 || map3.map[index2] != map3.map[index2 - map3.width])) {
      const cellPos = map3.map[index2];
      const pos = start2 + cellPos + table2.nodeAt(cellPos).nodeSize - 1;
      const dom = document.createElement("div");
      dom.className = "column-resize-handle";
      if ((_a2 = columnResizingPluginKey.getState(state)) == null ? void 0 : _a2.dragging) {
        decorations.push(
          Decoration.node(
            start2 + cellPos,
            start2 + cellPos + table2.nodeAt(cellPos).nodeSize,
            {
              class: "column-resize-dragging"
            }
          )
        );
      }
      decorations.push(Decoration.widget(pos, dom));
    }
  }
  return DecorationSet.create(state.doc, decorations);
}
__name(handleDecorations, "handleDecorations");
function tableEditing({
  allowTableNodeSelection = false
} = {}) {
  return new Plugin({
    key: tableEditingKey,
    // This piece of state is used to remember when a mouse-drag
    // cell-selection is happening, so that it can continue even as
    // transactions (which might move its anchor cell) come in.
    state: {
      init() {
        return null;
      },
      apply(tr2, cur) {
        const set3 = tr2.getMeta(tableEditingKey);
        if (set3 != null)
          return set3 == -1 ? null : set3;
        if (cur == null || !tr2.docChanged)
          return cur;
        const { deleted, pos } = tr2.mapping.mapResult(cur);
        return deleted ? null : pos;
      }
    },
    props: {
      decorations: drawCellSelection,
      handleDOMEvents: {
        mousedown: handleMouseDown
      },
      createSelectionBetween(view) {
        return tableEditingKey.getState(view.state) != null ? view.state.selection : null;
      },
      handleTripleClick,
      handleKeyDown: handleKeyDown$1,
      handlePaste
    },
    appendTransaction(_2, oldState, state) {
      return normalizeSelection(
        state,
        fixTables(state, oldState),
        allowTableNodeSelection
      );
    }
  });
}
__name(tableEditing, "tableEditing");
function getColStyleDeclaration(minWidth, width2) {
  if (width2) {
    return ["width", `${Math.max(width2, minWidth)}px`];
  }
  return ["min-width", `${minWidth}px`];
}
__name(getColStyleDeclaration, "getColStyleDeclaration");
function updateColumns(node2, colgroup, table2, cellMinWidth, overrideCol, overrideValue) {
  var _a2;
  let totalWidth = 0;
  let fixedWidth = true;
  let nextDOM = colgroup.firstChild;
  const row = node2.firstChild;
  if (row !== null) {
    for (let i2 = 0, col = 0; i2 < row.childCount; i2 += 1) {
      const { colspan, colwidth } = row.child(i2).attrs;
      for (let j2 = 0; j2 < colspan; j2 += 1, col += 1) {
        const hasWidth = overrideCol === col ? overrideValue : colwidth && colwidth[j2];
        const cssWidth = hasWidth ? `${hasWidth}px` : "";
        totalWidth += hasWidth || cellMinWidth;
        if (!hasWidth) {
          fixedWidth = false;
        }
        if (!nextDOM) {
          const colElement = document.createElement("col");
          const [propertyKey, propertyValue] = getColStyleDeclaration(cellMinWidth, hasWidth);
          colElement.style.setProperty(propertyKey, propertyValue);
          colgroup.appendChild(colElement);
        } else {
          if (nextDOM.style.width !== cssWidth) {
            const [propertyKey, propertyValue] = getColStyleDeclaration(cellMinWidth, hasWidth);
            nextDOM.style.setProperty(propertyKey, propertyValue);
          }
          nextDOM = nextDOM.nextSibling;
        }
      }
    }
  }
  while (nextDOM) {
    const after = nextDOM.nextSibling;
    (_a2 = nextDOM.parentNode) === null || _a2 === void 0 ? void 0 : _a2.removeChild(nextDOM);
    nextDOM = after;
  }
  if (fixedWidth) {
    table2.style.width = `${totalWidth}px`;
    table2.style.minWidth = "";
  } else {
    table2.style.width = "";
    table2.style.minWidth = `${totalWidth}px`;
  }
}
__name(updateColumns, "updateColumns");
class TableView {
  static {
    __name(this, "TableView");
  }
  constructor(node2, cellMinWidth) {
    this.node = node2;
    this.cellMinWidth = cellMinWidth;
    this.dom = document.createElement("div");
    this.dom.className = "tableWrapper";
    this.table = this.dom.appendChild(document.createElement("table"));
    this.colgroup = this.table.appendChild(document.createElement("colgroup"));
    updateColumns(node2, this.colgroup, this.table, cellMinWidth);
    this.contentDOM = this.table.appendChild(document.createElement("tbody"));
  }
  update(node2) {
    if (node2.type !== this.node.type) {
      return false;
    }
    this.node = node2;
    updateColumns(node2, this.colgroup, this.table, this.cellMinWidth);
    return true;
  }
  ignoreMutation(mutation) {
    return mutation.type === "attributes" && (mutation.target === this.table || this.colgroup.contains(mutation.target));
  }
}
function createColGroup(node2, cellMinWidth, overrideCol, overrideValue) {
  let totalWidth = 0;
  let fixedWidth = true;
  const cols = [];
  const row = node2.firstChild;
  if (!row) {
    return {};
  }
  for (let i2 = 0, col = 0; i2 < row.childCount; i2 += 1) {
    const { colspan, colwidth } = row.child(i2).attrs;
    for (let j2 = 0; j2 < colspan; j2 += 1, col += 1) {
      const hasWidth = overrideCol === col ? overrideValue : colwidth && colwidth[j2];
      totalWidth += hasWidth || cellMinWidth;
      if (!hasWidth) {
        fixedWidth = false;
      }
      const [property, value] = getColStyleDeclaration(cellMinWidth, hasWidth);
      cols.push([
        "col",
        { style: `${property}: ${value}` }
      ]);
    }
  }
  const tableWidth = fixedWidth ? `${totalWidth}px` : "";
  const tableMinWidth = fixedWidth ? "" : `${totalWidth}px`;
  const colgroup = ["colgroup", {}, ...cols];
  return { colgroup, tableWidth, tableMinWidth };
}
__name(createColGroup, "createColGroup");
function createCell(cellType, cellContent) {
  if (cellContent) {
    return cellType.createChecked(null, cellContent);
  }
  return cellType.createAndFill();
}
__name(createCell, "createCell");
function getTableNodeTypes(schema2) {
  if (schema2.cached.tableNodeTypes) {
    return schema2.cached.tableNodeTypes;
  }
  const roles = {};
  Object.keys(schema2.nodes).forEach((type) => {
    const nodeType = schema2.nodes[type];
    if (nodeType.spec.tableRole) {
      roles[nodeType.spec.tableRole] = nodeType;
    }
  });
  schema2.cached.tableNodeTypes = roles;
  return roles;
}
__name(getTableNodeTypes, "getTableNodeTypes");
function createTable(schema2, rowsCount, colsCount, withHeaderRow, cellContent) {
  const types = getTableNodeTypes(schema2);
  const headerCells = [];
  const cells = [];
  for (let index2 = 0; index2 < colsCount; index2 += 1) {
    const cell = createCell(types.cell, cellContent);
    if (cell) {
      cells.push(cell);
    }
    if (withHeaderRow) {
      const headerCell = createCell(types.header_cell, cellContent);
      if (headerCell) {
        headerCells.push(headerCell);
      }
    }
  }
  const rows = [];
  for (let index2 = 0; index2 < rowsCount; index2 += 1) {
    rows.push(types.row.createChecked(null, withHeaderRow && index2 === 0 ? headerCells : cells));
  }
  return types.table.createChecked(null, rows);
}
__name(createTable, "createTable");
function isCellSelection(value) {
  return value instanceof CellSelection;
}
__name(isCellSelection, "isCellSelection");
const deleteTableWhenAllCellsSelected = /* @__PURE__ */ __name(({ editor }) => {
  const { selection } = editor.state;
  if (!isCellSelection(selection)) {
    return false;
  }
  let cellCount = 0;
  const table2 = findParentNodeClosestToPos(selection.ranges[0].$from, (node2) => {
    return node2.type.name === "table";
  });
  table2 === null || table2 === void 0 ? void 0 : table2.node.descendants((node2) => {
    if (node2.type.name === "table") {
      return false;
    }
    if (["tableCell", "tableHeader"].includes(node2.type.name)) {
      cellCount += 1;
    }
  });
  const allCellsSelected = cellCount === selection.ranges.length;
  if (!allCellsSelected) {
    return false;
  }
  editor.commands.deleteTable();
  return true;
}, "deleteTableWhenAllCellsSelected");
const Table$2 = Node$1.create({
  name: "table",
  // @ts-ignore
  addOptions() {
    return {
      HTMLAttributes: {},
      resizable: false,
      handleWidth: 5,
      cellMinWidth: 25,
      // TODO: fix
      View: TableView,
      lastColumnResizable: true,
      allowTableNodeSelection: false
    };
  },
  content: "tableRow+",
  tableRole: "table",
  isolating: true,
  group: "block",
  parseHTML() {
    return [{ tag: "table" }];
  },
  renderHTML({ node: node2, HTMLAttributes }) {
    const { colgroup, tableWidth, tableMinWidth } = createColGroup(node2, this.options.cellMinWidth);
    const table2 = [
      "table",
      mergeAttributes(this.options.HTMLAttributes, HTMLAttributes, {
        style: tableWidth ? `width: ${tableWidth}` : `min-width: ${tableMinWidth}`
      }),
      colgroup,
      ["tbody", 0]
    ];
    return table2;
  },
  addCommands() {
    return {
      insertTable: /* @__PURE__ */ __name(({ rows = 3, cols = 3, withHeaderRow = true } = {}) => ({ tr: tr2, dispatch, editor }) => {
        const node2 = createTable(editor.schema, rows, cols, withHeaderRow);
        if (dispatch) {
          const offset = tr2.selection.from + 1;
          tr2.replaceSelectionWith(node2).scrollIntoView().setSelection(TextSelection.near(tr2.doc.resolve(offset)));
        }
        return true;
      }, "insertTable"),
      addColumnBefore: /* @__PURE__ */ __name(() => ({ state, dispatch }) => {
        return addColumnBefore(state, dispatch);
      }, "addColumnBefore"),
      addColumnAfter: /* @__PURE__ */ __name(() => ({ state, dispatch }) => {
        return addColumnAfter(state, dispatch);
      }, "addColumnAfter"),
      deleteColumn: /* @__PURE__ */ __name(() => ({ state, dispatch }) => {
        return deleteColumn(state, dispatch);
      }, "deleteColumn"),
      addRowBefore: /* @__PURE__ */ __name(() => ({ state, dispatch }) => {
        return addRowBefore(state, dispatch);
      }, "addRowBefore"),
      addRowAfter: /* @__PURE__ */ __name(() => ({ state, dispatch }) => {
        return addRowAfter(state, dispatch);
      }, "addRowAfter"),
      deleteRow: /* @__PURE__ */ __name(() => ({ state, dispatch }) => {
        return deleteRow(state, dispatch);
      }, "deleteRow"),
      deleteTable: /* @__PURE__ */ __name(() => ({ state, dispatch }) => {
        return deleteTable(state, dispatch);
      }, "deleteTable"),
      mergeCells: /* @__PURE__ */ __name(() => ({ state, dispatch }) => {
        return mergeCells(state, dispatch);
      }, "mergeCells"),
      splitCell: /* @__PURE__ */ __name(() => ({ state, dispatch }) => {
        return splitCell(state, dispatch);
      }, "splitCell"),
      toggleHeaderColumn: /* @__PURE__ */ __name(() => ({ state, dispatch }) => {
        return toggleHeader("column")(state, dispatch);
      }, "toggleHeaderColumn"),
      toggleHeaderRow: /* @__PURE__ */ __name(() => ({ state, dispatch }) => {
        return toggleHeader("row")(state, dispatch);
      }, "toggleHeaderRow"),
      toggleHeaderCell: /* @__PURE__ */ __name(() => ({ state, dispatch }) => {
        return toggleHeaderCell(state, dispatch);
      }, "toggleHeaderCell"),
      mergeOrSplit: /* @__PURE__ */ __name(() => ({ state, dispatch }) => {
        if (mergeCells(state, dispatch)) {
          return true;
        }
        return splitCell(state, dispatch);
      }, "mergeOrSplit"),
      setCellAttribute: /* @__PURE__ */ __name((name2, value) => ({ state, dispatch }) => {
        return setCellAttr(name2, value)(state, dispatch);
      }, "setCellAttribute"),
      goToNextCell: /* @__PURE__ */ __name(() => ({ state, dispatch }) => {
        return goToNextCell(1)(state, dispatch);
      }, "goToNextCell"),
      goToPreviousCell: /* @__PURE__ */ __name(() => ({ state, dispatch }) => {
        return goToNextCell(-1)(state, dispatch);
      }, "goToPreviousCell"),
      fixTables: /* @__PURE__ */ __name(() => ({ state, dispatch }) => {
        if (dispatch) {
          fixTables(state);
        }
        return true;
      }, "fixTables"),
      setCellSelection: /* @__PURE__ */ __name((position) => ({ tr: tr2, dispatch }) => {
        if (dispatch) {
          const selection = CellSelection.create(tr2.doc, position.anchorCell, position.headCell);
          tr2.setSelection(selection);
        }
        return true;
      }, "setCellSelection")
    };
  },
  addKeyboardShortcuts() {
    return {
      Tab: /* @__PURE__ */ __name(() => {
        if (this.editor.commands.goToNextCell()) {
          return true;
        }
        if (!this.editor.can().addRowAfter()) {
          return false;
        }
        return this.editor.chain().addRowAfter().goToNextCell().run();
      }, "Tab"),
      "Shift-Tab": /* @__PURE__ */ __name(() => this.editor.commands.goToPreviousCell(), "Shift-Tab"),
      Backspace: deleteTableWhenAllCellsSelected,
      "Mod-Backspace": deleteTableWhenAllCellsSelected,
      Delete: deleteTableWhenAllCellsSelected,
      "Mod-Delete": deleteTableWhenAllCellsSelected
    };
  },
  addProseMirrorPlugins() {
    const isResizable = this.options.resizable && this.editor.isEditable;
    return [
      ...isResizable ? [
        columnResizing({
          handleWidth: this.options.handleWidth,
          cellMinWidth: this.options.cellMinWidth,
          defaultCellMinWidth: this.options.cellMinWidth,
          View: this.options.View,
          lastColumnResizable: this.options.lastColumnResizable
        })
      ] : [],
      tableEditing({
        allowTableNodeSelection: this.options.allowTableNodeSelection
      })
    ];
  },
  extendNodeSchema(extension) {
    const context = {
      name: extension.name,
      options: extension.options,
      storage: extension.storage
    };
    return {
      tableRole: callOrReturn(getExtensionField(extension, "tableRole", context))
    };
  }
});
const TableCell = Node$1.create({
  name: "tableCell",
  addOptions() {
    return {
      HTMLAttributes: {}
    };
  },
  content: "block+",
  addAttributes() {
    return {
      colspan: {
        default: 1
      },
      rowspan: {
        default: 1
      },
      colwidth: {
        default: null,
        parseHTML: /* @__PURE__ */ __name((element) => {
          const colwidth = element.getAttribute("colwidth");
          const value = colwidth ? colwidth.split(",").map((width2) => parseInt(width2, 10)) : null;
          return value;
        }, "parseHTML")
      }
    };
  },
  tableRole: "cell",
  isolating: true,
  parseHTML() {
    return [
      { tag: "td" }
    ];
  },
  renderHTML({ HTMLAttributes }) {
    return ["td", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0];
  }
});
const TableHeader = Node$1.create({
  name: "tableHeader",
  addOptions() {
    return {
      HTMLAttributes: {}
    };
  },
  content: "block+",
  addAttributes() {
    return {
      colspan: {
        default: 1
      },
      rowspan: {
        default: 1
      },
      colwidth: {
        default: null,
        parseHTML: /* @__PURE__ */ __name((element) => {
          const colwidth = element.getAttribute("colwidth");
          const value = colwidth ? colwidth.split(",").map((width2) => parseInt(width2, 10)) : null;
          return value;
        }, "parseHTML")
      }
    };
  },
  tableRole: "header_cell",
  isolating: true,
  parseHTML() {
    return [
      { tag: "th" }
    ];
  },
  renderHTML({ HTMLAttributes }) {
    return ["th", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0];
  }
});
const TableRow = Node$1.create({
  name: "tableRow",
  addOptions() {
    return {
      HTMLAttributes: {}
    };
  },
  content: "(tableCell | tableHeader)*",
  tableRole: "row",
  parseHTML() {
    return [
      { tag: "tr" }
    ];
  },
  renderHTML({ HTMLAttributes }) {
    return ["tr", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0];
  }
});
const inputRegex$4 = /^\s*>\s$/;
const Blockquote$2 = Node$1.create({
  name: "blockquote",
  addOptions() {
    return {
      HTMLAttributes: {}
    };
  },
  content: "block+",
  group: "block",
  defining: true,
  parseHTML() {
    return [
      { tag: "blockquote" }
    ];
  },
  renderHTML({ HTMLAttributes }) {
    return ["blockquote", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0];
  },
  addCommands() {
    return {
      setBlockquote: /* @__PURE__ */ __name(() => ({ commands: commands2 }) => {
        return commands2.wrapIn(this.name);
      }, "setBlockquote"),
      toggleBlockquote: /* @__PURE__ */ __name(() => ({ commands: commands2 }) => {
        return commands2.toggleWrap(this.name);
      }, "toggleBlockquote"),
      unsetBlockquote: /* @__PURE__ */ __name(() => ({ commands: commands2 }) => {
        return commands2.lift(this.name);
      }, "unsetBlockquote")
    };
  },
  addKeyboardShortcuts() {
    return {
      "Mod-Shift-b": /* @__PURE__ */ __name(() => this.editor.commands.toggleBlockquote(), "Mod-Shift-b")
    };
  },
  addInputRules() {
    return [
      wrappingInputRule({
        find: inputRegex$4,
        type: this.type
      })
    ];
  }
});
const starInputRegex$1 = /(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/;
const starPasteRegex$1 = /(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g;
const underscoreInputRegex$1 = /(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/;
const underscorePasteRegex$1 = /(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g;
const Bold$2 = Mark.create({
  name: "bold",
  addOptions() {
    return {
      HTMLAttributes: {}
    };
  },
  parseHTML() {
    return [
      {
        tag: "strong"
      },
      {
        tag: "b",
        getAttrs: /* @__PURE__ */ __name((node2) => node2.style.fontWeight !== "normal" && null, "getAttrs")
      },
      {
        style: "font-weight=400",
        clearMark: /* @__PURE__ */ __name((mark) => mark.type.name === this.name, "clearMark")
      },
      {
        style: "font-weight",
        getAttrs: /* @__PURE__ */ __name((value) => /^(bold(er)?|[5-9]\d{2,})$/.test(value) && null, "getAttrs")
      }
    ];
  },
  renderHTML({ HTMLAttributes }) {
    return ["strong", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0];
  },
  addCommands() {
    return {
      setBold: /* @__PURE__ */ __name(() => ({ commands: commands2 }) => {
        return commands2.setMark(this.name);
      }, "setBold"),
      toggleBold: /* @__PURE__ */ __name(() => ({ commands: commands2 }) => {
        return commands2.toggleMark(this.name);
      }, "toggleBold"),
      unsetBold: /* @__PURE__ */ __name(() => ({ commands: commands2 }) => {
        return commands2.unsetMark(this.name);
      }, "unsetBold")
    };
  },
  addKeyboardShortcuts() {
    return {
      "Mod-b": /* @__PURE__ */ __name(() => this.editor.commands.toggleBold(), "Mod-b"),
      "Mod-B": /* @__PURE__ */ __name(() => this.editor.commands.toggleBold(), "Mod-B")
    };
  },
  addInputRules() {
    return [
      markInputRule({
        find: starInputRegex$1,
        type: this.type
      }),
      markInputRule({
        find: underscoreInputRegex$1,
        type: this.type
      })
    ];
  },
  addPasteRules() {
    return [
      markPasteRule({
        find: starPasteRegex$1,
        type: this.type
      }),
      markPasteRule({
        find: underscorePasteRegex$1,
        type: this.type
      })
    ];
  }
});
const ListItemName$1 = "listItem";
const TextStyleName$1 = "textStyle";
const inputRegex$3 = /^\s*([-+*])\s$/;
const BulletList$2 = Node$1.create({
  name: "bulletList",
  addOptions() {
    return {
      itemTypeName: "listItem",
      HTMLAttributes: {},
      keepMarks: false,
      keepAttributes: false
    };
  },
  group: "block list",
  content() {
    return `${this.options.itemTypeName}+`;
  },
  parseHTML() {
    return [
      { tag: "ul" }
    ];
  },
  renderHTML({ HTMLAttributes }) {
    return ["ul", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0];
  },
  addCommands() {
    return {
      toggleBulletList: /* @__PURE__ */ __name(() => ({ commands: commands2, chain }) => {
        if (this.options.keepAttributes) {
          return chain().toggleList(this.name, this.options.itemTypeName, this.options.keepMarks).updateAttributes(ListItemName$1, this.editor.getAttributes(TextStyleName$1)).run();
        }
        return commands2.toggleList(this.name, this.options.itemTypeName, this.options.keepMarks);
      }, "toggleBulletList")
    };
  },
  addKeyboardShortcuts() {
    return {
      "Mod-Shift-8": /* @__PURE__ */ __name(() => this.editor.commands.toggleBulletList(), "Mod-Shift-8")
    };
  },
  addInputRules() {
    let inputRule = wrappingInputRule({
      find: inputRegex$3,
      type: this.type
    });
    if (this.options.keepMarks || this.options.keepAttributes) {
      inputRule = wrappingInputRule({
        find: inputRegex$3,
        type: this.type,
        keepMarks: this.options.keepMarks,
        keepAttributes: this.options.keepAttributes,
        getAttributes: /* @__PURE__ */ __name(() => {
          return this.editor.getAttributes(TextStyleName$1);
        }, "getAttributes"),
        editor: this.editor
      });
    }
    return [
      inputRule
    ];
  }
});
const inputRegex$2 = /(?<!`)`([^`]+)`(?!`)/;
const pasteRegex$1 = /(?<!`)`([^`]+)`(?!`)/g;
const Code$2 = Mark.create({
  name: "code",
  addOptions() {
    return {
      HTMLAttributes: {}
    };
  },
  excludes: "_",
  code: true,
  exitable: true,
  parseHTML() {
    return [
      { tag: "code" }
    ];
  },
  renderHTML({ HTMLAttributes }) {
    return ["code", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0];
  },
  addCommands() {
    return {
      setCode: /* @__PURE__ */ __name(() => ({ commands: commands2 }) => {
        return commands2.setMark(this.name);
      }, "setCode"),
      toggleCode: /* @__PURE__ */ __name(() => ({ commands: commands2 }) => {
        return commands2.toggleMark(this.name);
      }, "toggleCode"),
      unsetCode: /* @__PURE__ */ __name(() => ({ commands: commands2 }) => {
        return commands2.unsetMark(this.name);
      }, "unsetCode")
    };
  },
  addKeyboardShortcuts() {
    return {
      "Mod-e": /* @__PURE__ */ __name(() => this.editor.commands.toggleCode(), "Mod-e")
    };
  },
  addInputRules() {
    return [
      markInputRule({
        find: inputRegex$2,
        type: this.type
      })
    ];
  },
  addPasteRules() {
    return [
      markPasteRule({
        find: pasteRegex$1,
        type: this.type
      })
    ];
  }
});
const backtickInputRegex = /^```([a-z]+)?[\s\n]$/;
const tildeInputRegex = /^~~~([a-z]+)?[\s\n]$/;
const CodeBlock$2 = Node$1.create({
  name: "codeBlock",
  addOptions() {
    return {
      languageClassPrefix: "language-",
      exitOnTripleEnter: true,
      exitOnArrowDown: true,
      defaultLanguage: null,
      HTMLAttributes: {}
    };
  },
  content: "text*",
  marks: "",
  group: "block",
  code: true,
  defining: true,
  addAttributes() {
    return {
      language: {
        default: this.options.defaultLanguage,
        parseHTML: /* @__PURE__ */ __name((element) => {
          var _a2;
          const { languageClassPrefix } = this.options;
          const classNames2 = [...((_a2 = element.firstElementChild) === null || _a2 === void 0 ? void 0 : _a2.classList) || []];
          const languages = classNames2.filter((className) => className.startsWith(languageClassPrefix)).map((className) => className.replace(languageClassPrefix, ""));
          const language = languages[0];
          if (!language) {
            return null;
          }
          return language;
        }, "parseHTML"),
        rendered: false
      }
    };
  },
  parseHTML() {
    return [
      {
        tag: "pre",
        preserveWhitespace: "full"
      }
    ];
  },
  renderHTML({ node: node2, HTMLAttributes }) {
    return [
      "pre",
      mergeAttributes(this.options.HTMLAttributes, HTMLAttributes),
      [
        "code",
        {
          class: node2.attrs.language ? this.options.languageClassPrefix + node2.attrs.language : null
        },
        0
      ]
    ];
  },
  addCommands() {
    return {
      setCodeBlock: /* @__PURE__ */ __name((attributes) => ({ commands: commands2 }) => {
        return commands2.setNode(this.name, attributes);
      }, "setCodeBlock"),
      toggleCodeBlock: /* @__PURE__ */ __name((attributes) => ({ commands: commands2 }) => {
        return commands2.toggleNode(this.name, "paragraph", attributes);
      }, "toggleCodeBlock")
    };
  },
  addKeyboardShortcuts() {
    return {
      "Mod-Alt-c": /* @__PURE__ */ __name(() => this.editor.commands.toggleCodeBlock(), "Mod-Alt-c"),
      // remove code block when at start of document or code block is empty
      Backspace: /* @__PURE__ */ __name(() => {
        const { empty: empty2, $anchor } = this.editor.state.selection;
        const isAtStart = $anchor.pos === 1;
        if (!empty2 || $anchor.parent.type.name !== this.name) {
          return false;
        }
        if (isAtStart || !$anchor.parent.textContent.length) {
          return this.editor.commands.clearNodes();
        }
        return false;
      }, "Backspace"),
      // exit node on triple enter
      Enter: /* @__PURE__ */ __name(({ editor }) => {
        if (!this.options.exitOnTripleEnter) {
          return false;
        }
        const { state } = editor;
        const { selection } = state;
        const { $from, empty: empty2 } = selection;
        if (!empty2 || $from.parent.type !== this.type) {
          return false;
        }
        const isAtEnd = $from.parentOffset === $from.parent.nodeSize - 2;
        const endsWithDoubleNewline = $from.parent.textContent.endsWith("\n\n");
        if (!isAtEnd || !endsWithDoubleNewline) {
          return false;
        }
        return editor.chain().command(({ tr: tr2 }) => {
          tr2.delete($from.pos - 2, $from.pos);
          return true;
        }).exitCode().run();
      }, "Enter"),
      // exit node on arrow down
      ArrowDown: /* @__PURE__ */ __name(({ editor }) => {
        if (!this.options.exitOnArrowDown) {
          return false;
        }
        const { state } = editor;
        const { selection, doc: doc2 } = state;
        const { $from, empty: empty2 } = selection;
        if (!empty2 || $from.parent.type !== this.type) {
          return false;
        }
        const isAtEnd = $from.parentOffset === $from.parent.nodeSize - 2;
        if (!isAtEnd) {
          return false;
        }
        const after = $from.after();
        if (after === void 0) {
          return false;
        }
        const nodeAfter = doc2.nodeAt(after);
        if (nodeAfter) {
          return editor.commands.command(({ tr: tr2 }) => {
            tr2.setSelection(Selection.near(doc2.resolve(after)));
            return true;
          });
        }
        return editor.commands.exitCode();
      }, "ArrowDown")
    };
  },
  addInputRules() {
    return [
      textblockTypeInputRule({
        find: backtickInputRegex,
        type: this.type,
        getAttributes: /* @__PURE__ */ __name((match2) => ({
          language: match2[1]
        }), "getAttributes")
      }),
      textblockTypeInputRule({
        find: tildeInputRegex,
        type: this.type,
        getAttributes: /* @__PURE__ */ __name((match2) => ({
          language: match2[1]
        }), "getAttributes")
      })
    ];
  },
  addProseMirrorPlugins() {
    return [
      // this plugin creates a code block for pasted content from VS Code
      // we can also detect the copied code language
      new Plugin({
        key: new PluginKey("codeBlockVSCodeHandler"),
        props: {
          handlePaste: /* @__PURE__ */ __name((view, event) => {
            if (!event.clipboardData) {
              return false;
            }
            if (this.editor.isActive(this.type.name)) {
              return false;
            }
            const text2 = event.clipboardData.getData("text/plain");
            const vscode = event.clipboardData.getData("vscode-editor-data");
            const vscodeData = vscode ? JSON.parse(vscode) : void 0;
            const language = vscodeData === null || vscodeData === void 0 ? void 0 : vscodeData.mode;
            if (!text2 || !language) {
              return false;
            }
            const { tr: tr2, schema: schema2 } = view.state;
            const textNode = schema2.text(text2.replace(/\r\n?/g, "\n"));
            tr2.replaceSelectionWith(this.type.create({ language }, textNode));
            if (tr2.selection.$from.parent.type !== this.type) {
              tr2.setSelection(TextSelection.near(tr2.doc.resolve(Math.max(0, tr2.selection.from - 2))));
            }
            tr2.setMeta("paste", true);
            view.dispatch(tr2);
            return true;
          }, "handlePaste")
        }
      })
    ];
  }
});
const Document$1 = Node$1.create({
  name: "doc",
  topNode: true,
  content: "block+"
});
function dropCursor(options2 = {}) {
  return new Plugin({
    view(editorView) {
      return new DropCursorView(editorView, options2);
    }
  });
}
__name(dropCursor, "dropCursor");
class DropCursorView {
  static {
    __name(this, "DropCursorView");
  }
  constructor(editorView, options2) {
    var _a2;
    this.editorView = editorView;
    this.cursorPos = null;
    this.element = null;
    this.timeout = -1;
    this.width = (_a2 = options2.width) !== null && _a2 !== void 0 ? _a2 : 1;
    this.color = options2.color === false ? void 0 : options2.color || "black";
    this.class = options2.class;
    this.handlers = ["dragover", "dragend", "drop", "dragleave"].map((name2) => {
      let handler5 = /* @__PURE__ */ __name((e2) => {
        this[name2](e2);
      }, "handler");
      editorView.dom.addEventListener(name2, handler5);
      return { name: name2, handler: handler5 };
    });
  }
  destroy() {
    this.handlers.forEach(({ name: name2, handler: handler5 }) => this.editorView.dom.removeEventListener(name2, handler5));
  }
  update(editorView, prevState) {
    if (this.cursorPos != null && prevState.doc != editorView.state.doc) {
      if (this.cursorPos > editorView.state.doc.content.size)
        this.setCursor(null);
      else
        this.updateOverlay();
    }
  }
  setCursor(pos) {
    if (pos == this.cursorPos)
      return;
    this.cursorPos = pos;
    if (pos == null) {
      this.element.parentNode.removeChild(this.element);
      this.element = null;
    } else {
      this.updateOverlay();
    }
  }
  updateOverlay() {
    let $pos = this.editorView.state.doc.resolve(this.cursorPos);
    let isBlock = !$pos.parent.inlineContent, rect;
    if (isBlock) {
      let before = $pos.nodeBefore, after = $pos.nodeAfter;
      if (before || after) {
        let node2 = this.editorView.nodeDOM(this.cursorPos - (before ? before.nodeSize : 0));
        if (node2) {
          let nodeRect = node2.getBoundingClientRect();
          let top = before ? nodeRect.bottom : nodeRect.top;
          if (before && after)
            top = (top + this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top) / 2;
          rect = { left: nodeRect.left, right: nodeRect.right, top: top - this.width / 2, bottom: top + this.width / 2 };
        }
      }
    }
    if (!rect) {
      let coords = this.editorView.coordsAtPos(this.cursorPos);
      rect = { left: coords.left - this.width / 2, right: coords.left + this.width / 2, top: coords.top, bottom: coords.bottom };
    }
    let parent2 = this.editorView.dom.offsetParent;
    if (!this.element) {
      this.element = parent2.appendChild(document.createElement("div"));
      if (this.class)
        this.element.className = this.class;
      this.element.style.cssText = "position: absolute; z-index: 50; pointer-events: none;";
      if (this.color) {
        this.element.style.backgroundColor = this.color;
      }
    }
    this.element.classList.toggle("prosemirror-dropcursor-block", isBlock);
    this.element.classList.toggle("prosemirror-dropcursor-inline", !isBlock);
    let parentLeft, parentTop;
    if (!parent2 || parent2 == document.body && getComputedStyle(parent2).position == "static") {
      parentLeft = -pageXOffset;
      parentTop = -pageYOffset;
    } else {
      let rect2 = parent2.getBoundingClientRect();
      parentLeft = rect2.left - parent2.scrollLeft;
      parentTop = rect2.top - parent2.scrollTop;
    }
    this.element.style.left = rect.left - parentLeft + "px";
    this.element.style.top = rect.top - parentTop + "px";
    this.element.style.width = rect.right - rect.left + "px";
    this.element.style.height = rect.bottom - rect.top + "px";
  }
  scheduleRemoval(timeout) {
    clearTimeout(this.timeout);
    this.timeout = setTimeout(() => this.setCursor(null), timeout);
  }
  dragover(event) {
    if (!this.editorView.editable)
      return;
    let pos = this.editorView.posAtCoords({ left: event.clientX, top: event.clientY });
    let node2 = pos && pos.inside >= 0 && this.editorView.state.doc.nodeAt(pos.inside);
    let disableDropCursor = node2 && node2.type.spec.disableDropCursor;
    let disabled = typeof disableDropCursor == "function" ? disableDropCursor(this.editorView, pos, event) : disableDropCursor;
    if (pos && !disabled) {
      let target = pos.pos;
      if (this.editorView.dragging && this.editorView.dragging.slice) {
        let point = dropPoint(this.editorView.state.doc, target, this.editorView.dragging.slice);
        if (point != null)
          target = point;
      }
      this.setCursor(target);
      this.scheduleRemoval(5e3);
    }
  }
  dragend() {
    this.scheduleRemoval(20);
  }
  drop() {
    this.scheduleRemoval(20);
  }
  dragleave(event) {
    if (event.target == this.editorView.dom || !this.editorView.dom.contains(event.relatedTarget))
      this.setCursor(null);
  }
}
const Dropcursor = Extension.create({
  name: "dropCursor",
  addOptions() {
    return {
      color: "currentColor",
      width: 1,
      class: void 0
    };
  },
  addProseMirrorPlugins() {
    return [
      dropCursor(this.options)
    ];
  }
});
class GapCursor extends Selection {
  static {
    __name(this, "GapCursor");
  }
  /**
  Create a gap cursor.
  */
  constructor($pos) {
    super($pos, $pos);
  }
  map(doc2, mapping) {
    let $pos = doc2.resolve(mapping.map(this.head));
    return GapCursor.valid($pos) ? new GapCursor($pos) : Selection.near($pos);
  }
  content() {
    return Slice.empty;
  }
  eq(other) {
    return other instanceof GapCursor && other.head == this.head;
  }
  toJSON() {
    return { type: "gapcursor", pos: this.head };
  }
  /**
  @internal
  */
  static fromJSON(doc2, json) {
    if (typeof json.pos != "number")
      throw new RangeError("Invalid input for GapCursor.fromJSON");
    return new GapCursor(doc2.resolve(json.pos));
  }
  /**
  @internal
  */
  getBookmark() {
    return new GapBookmark(this.anchor);
  }
  /**
  @internal
  */
  static valid($pos) {
    let parent2 = $pos.parent;
    if (parent2.isTextblock || !closedBefore($pos) || !closedAfter($pos))
      return false;
    let override = parent2.type.spec.allowGapCursor;
    if (override != null)
      return override;
    let deflt = parent2.contentMatchAt($pos.index()).defaultType;
    return deflt && deflt.isTextblock;
  }
  /**
  @internal
  */
  static findGapCursorFrom($pos, dir, mustMove = false) {
    search: for (; ; ) {
      if (!mustMove && GapCursor.valid($pos))
        return $pos;
      let pos = $pos.pos, next = null;
      for (let d2 = $pos.depth; ; d2--) {
        let parent2 = $pos.node(d2);
        if (dir > 0 ? $pos.indexAfter(d2) < parent2.childCount : $pos.index(d2) > 0) {
          next = parent2.child(dir > 0 ? $pos.indexAfter(d2) : $pos.index(d2) - 1);
          break;
        } else if (d2 == 0) {
          return null;
        }
        pos += dir;
        let $cur = $pos.doc.resolve(pos);
        if (GapCursor.valid($cur))
          return $cur;
      }
      for (; ; ) {
        let inside = dir > 0 ? next.firstChild : next.lastChild;
        if (!inside) {
          if (next.isAtom && !next.isText && !NodeSelection.isSelectable(next)) {
            $pos = $pos.doc.resolve(pos + next.nodeSize * dir);
            mustMove = false;
            continue search;
          }
          break;
        }
        next = inside;
        pos += dir;
        let $cur = $pos.doc.resolve(pos);
        if (GapCursor.valid($cur))
          return $cur;
      }
      return null;
    }
  }
}
GapCursor.prototype.visible = false;
GapCursor.findFrom = GapCursor.findGapCursorFrom;
Selection.jsonID("gapcursor", GapCursor);
class GapBookmark {
  static {
    __name(this, "GapBookmark");
  }
  constructor(pos) {
    this.pos = pos;
  }
  map(mapping) {
    return new GapBookmark(mapping.map(this.pos));
  }
  resolve(doc2) {
    let $pos = doc2.resolve(this.pos);
    return GapCursor.valid($pos) ? new GapCursor($pos) : Selection.near($pos);
  }
}
function closedBefore($pos) {
  for (let d2 = $pos.depth; d2 >= 0; d2--) {
    let index2 = $pos.index(d2), parent2 = $pos.node(d2);
    if (index2 == 0) {
      if (parent2.type.spec.isolating)
        return true;
      continue;
    }
    for (let before = parent2.child(index2 - 1); ; before = before.lastChild) {
      if (before.childCount == 0 && !before.inlineContent || before.isAtom || before.type.spec.isolating)
        return true;
      if (before.inlineContent)
        return false;
    }
  }
  return true;
}
__name(closedBefore, "closedBefore");
function closedAfter($pos) {
  for (let d2 = $pos.depth; d2 >= 0; d2--) {
    let index2 = $pos.indexAfter(d2), parent2 = $pos.node(d2);
    if (index2 == parent2.childCount) {
      if (parent2.type.spec.isolating)
        return true;
      continue;
    }
    for (let after = parent2.child(index2); ; after = after.firstChild) {
      if (after.childCount == 0 && !after.inlineContent || after.isAtom || after.type.spec.isolating)
        return true;
      if (after.inlineContent)
        return false;
    }
  }
  return true;
}
__name(closedAfter, "closedAfter");
function gapCursor() {
  return new Plugin({
    props: {
      decorations: drawGapCursor,
      createSelectionBetween(_view, $anchor, $head) {
        return $anchor.pos == $head.pos && GapCursor.valid($head) ? new GapCursor($head) : null;
      },
      handleClick,
      handleKeyDown,
      handleDOMEvents: { beforeinput }
    }
  });
}
__name(gapCursor, "gapCursor");
const handleKeyDown = keydownHandler({
  "ArrowLeft": arrow("horiz", -1),
  "ArrowRight": arrow("horiz", 1),
  "ArrowUp": arrow("vert", -1),
  "ArrowDown": arrow("vert", 1)
});
function arrow(axis, dir) {
  const dirStr = axis == "vert" ? dir > 0 ? "down" : "up" : dir > 0 ? "right" : "left";
  return function(state, dispatch, view) {
    let sel = state.selection;
    let $start = dir > 0 ? sel.$to : sel.$from, mustMove = sel.empty;
    if (sel instanceof TextSelection) {
      if (!view.endOfTextblock(dirStr) || $start.depth == 0)
        return false;
      mustMove = false;
      $start = state.doc.resolve(dir > 0 ? $start.after() : $start.before());
    }
    let $found = GapCursor.findGapCursorFrom($start, dir, mustMove);
    if (!$found)
      return false;
    if (dispatch)
      dispatch(state.tr.setSelection(new GapCursor($found)));
    return true;
  };
}
__name(arrow, "arrow");
function handleClick(view, pos, event) {
  if (!view || !view.editable)
    return false;
  let $pos = view.state.doc.resolve(pos);
  if (!GapCursor.valid($pos))
    return false;
  let clickPos = view.posAtCoords({ left: event.clientX, top: event.clientY });
  if (clickPos && clickPos.inside > -1 && NodeSelection.isSelectable(view.state.doc.nodeAt(clickPos.inside)))
    return false;
  view.dispatch(view.state.tr.setSelection(new GapCursor($pos)));
  return true;
}
__name(handleClick, "handleClick");
function beforeinput(view, event) {
  if (event.inputType != "insertCompositionText" || !(view.state.selection instanceof GapCursor))
    return false;
  let { $from } = view.state.selection;
  let insert = $from.parent.contentMatchAt($from.index()).findWrapping(view.state.schema.nodes.text);
  if (!insert)
    return false;
  let frag = Fragment.empty;
  for (let i2 = insert.length - 1; i2 >= 0; i2--)
    frag = Fragment.from(insert[i2].createAndFill(null, frag));
  let tr2 = view.state.tr.replace($from.pos, $from.pos, new Slice(frag, 0, 0));
  tr2.setSelection(TextSelection.near(tr2.doc.resolve($from.pos + 1)));
  view.dispatch(tr2);
  return false;
}
__name(beforeinput, "beforeinput");
function drawGapCursor(state) {
  if (!(state.selection instanceof GapCursor))
    return null;
  let node2 = document.createElement("div");
  node2.className = "ProseMirror-gapcursor";
  return DecorationSet.create(state.doc, [Decoration.widget(state.selection.head, node2, { key: "gapcursor" })]);
}
__name(drawGapCursor, "drawGapCursor");
const Gapcursor = Extension.create({
  name: "gapCursor",
  addProseMirrorPlugins() {
    return [
      gapCursor()
    ];
  },
  extendNodeSchema(extension) {
    var _a2;
    const context = {
      name: extension.name,
      options: extension.options,
      storage: extension.storage
    };
    return {
      allowGapCursor: (_a2 = callOrReturn(getExtensionField(extension, "allowGapCursor", context))) !== null && _a2 !== void 0 ? _a2 : null
    };
  }
});
const HardBreak$2 = Node$1.create({
  name: "hardBreak",
  addOptions() {
    return {
      keepMarks: true,
      HTMLAttributes: {}
    };
  },
  inline: true,
  group: "inline",
  selectable: false,
  linebreakReplacement: true,
  parseHTML() {
    return [
      { tag: "br" }
    ];
  },
  renderHTML({ HTMLAttributes }) {
    return ["br", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes)];
  },
  renderText() {
    return "\n";
  },
  addCommands() {
    return {
      setHardBreak: /* @__PURE__ */ __name(() => ({ commands: commands2, chain, state, editor }) => {
        return commands2.first([
          () => commands2.exitCode(),
          () => commands2.command(() => {
            const { selection, storedMarks } = state;
            if (selection.$from.parent.type.spec.isolating) {
              return false;
            }
            const { keepMarks } = this.options;
            const { splittableMarks } = editor.extensionManager;
            const marks = storedMarks || selection.$to.parentOffset && selection.$from.marks();
            return chain().insertContent({ type: this.name }).command(({ tr: tr2, dispatch }) => {
              if (dispatch && marks && keepMarks) {
                const filteredMarks = marks.filter((mark) => splittableMarks.includes(mark.type.name));
                tr2.ensureMarks(filteredMarks);
              }
              return true;
            }).run();
          })
        ]);
      }, "setHardBreak")
    };
  },
  addKeyboardShortcuts() {
    return {
      "Mod-Enter": /* @__PURE__ */ __name(() => this.editor.commands.setHardBreak(), "Mod-Enter"),
      "Shift-Enter": /* @__PURE__ */ __name(() => this.editor.commands.setHardBreak(), "Shift-Enter")
    };
  }
});
const Heading$2 = Node$1.create({
  name: "heading",
  addOptions() {
    return {
      levels: [1, 2, 3, 4, 5, 6],
      HTMLAttributes: {}
    };
  },
  content: "inline*",
  group: "block",
  defining: true,
  addAttributes() {
    return {
      level: {
        default: 1,
        rendered: false
      }
    };
  },
  parseHTML() {
    return this.options.levels.map((level) => ({
      tag: `h${level}`,
      attrs: { level }
    }));
  },
  renderHTML({ node: node2, HTMLAttributes }) {
    const hasLevel = this.options.levels.includes(node2.attrs.level);
    const level = hasLevel ? node2.attrs.level : this.options.levels[0];
    return [`h${level}`, mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0];
  },
  addCommands() {
    return {
      setHeading: /* @__PURE__ */ __name((attributes) => ({ commands: commands2 }) => {
        if (!this.options.levels.includes(attributes.level)) {
          return false;
        }
        return commands2.setNode(this.name, attributes);
      }, "setHeading"),
      toggleHeading: /* @__PURE__ */ __name((attributes) => ({ commands: commands2 }) => {
        if (!this.options.levels.includes(attributes.level)) {
          return false;
        }
        return commands2.toggleNode(this.name, "paragraph", attributes);
      }, "toggleHeading")
    };
  },
  addKeyboardShortcuts() {
    return this.options.levels.reduce((items, level) => ({
      ...items,
      ...{
        [`Mod-Alt-${level}`]: () => this.editor.commands.toggleHeading({ level })
      }
    }), {});
  },
  addInputRules() {
    return this.options.levels.map((level) => {
      return textblockTypeInputRule({
        find: new RegExp(`^(#{1,${level}})\\s$`),
        type: this.type,
        getAttributes: {
          level
        }
      });
    });
  }
});
var GOOD_LEAF_SIZE = 200;
var RopeSequence = /* @__PURE__ */ __name(function RopeSequence2() {
}, "RopeSequence");
RopeSequence.prototype.append = /* @__PURE__ */ __name(function append2(other) {
  if (!other.length) {
    return this;
  }
  other = RopeSequence.from(other);
  return !this.length && other || other.length < GOOD_LEAF_SIZE && this.leafAppend(other) || this.length < GOOD_LEAF_SIZE && other.leafPrepend(this) || this.appendInner(other);
}, "append");
RopeSequence.prototype.prepend = /* @__PURE__ */ __name(function prepend(other) {
  if (!other.length) {
    return this;
  }
  return RopeSequence.from(other).append(this);
}, "prepend");
RopeSequence.prototype.appendInner = /* @__PURE__ */ __name(function appendInner(other) {
  return new Append(this, other);
}, "appendInner");
RopeSequence.prototype.slice = /* @__PURE__ */ __name(function slice(from2, to) {
  if (from2 === void 0) from2 = 0;
  if (to === void 0) to = this.length;
  if (from2 >= to) {
    return RopeSequence.empty;
  }
  return this.sliceInner(Math.max(0, from2), Math.min(this.length, to));
}, "slice");
RopeSequence.prototype.get = /* @__PURE__ */ __name(function get2(i2) {
  if (i2 < 0 || i2 >= this.length) {
    return void 0;
  }
  return this.getInner(i2);
}, "get");
RopeSequence.prototype.forEach = /* @__PURE__ */ __name(function forEach2(f2, from2, to) {
  if (from2 === void 0) from2 = 0;
  if (to === void 0) to = this.length;
  if (from2 <= to) {
    this.forEachInner(f2, from2, to, 0);
  } else {
    this.forEachInvertedInner(f2, from2, to, 0);
  }
}, "forEach");
RopeSequence.prototype.map = /* @__PURE__ */ __name(function map2(f2, from2, to) {
  if (from2 === void 0) from2 = 0;
  if (to === void 0) to = this.length;
  var result = [];
  this.forEach(function(elt, i2) {
    return result.push(f2(elt, i2));
  }, from2, to);
  return result;
}, "map");
RopeSequence.from = /* @__PURE__ */ __name(function from(values) {
  if (values instanceof RopeSequence) {
    return values;
  }
  return values && values.length ? new Leaf(values) : RopeSequence.empty;
}, "from");
var Leaf = /* @__PURE__ */ function(RopeSequence3) {
  function Leaf2(values) {
    RopeSequence3.call(this);
    this.values = values;
  }
  __name(Leaf2, "Leaf");
  if (RopeSequence3) Leaf2.__proto__ = RopeSequence3;
  Leaf2.prototype = Object.create(RopeSequence3 && RopeSequence3.prototype);
  Leaf2.prototype.constructor = Leaf2;
  var prototypeAccessors = { length: { configurable: true }, depth: { configurable: true } };
  Leaf2.prototype.flatten = /* @__PURE__ */ __name(function flatten2() {
    return this.values;
  }, "flatten");
  Leaf2.prototype.sliceInner = /* @__PURE__ */ __name(function sliceInner(from2, to) {
    if (from2 == 0 && to == this.length) {
      return this;
    }
    return new Leaf2(this.values.slice(from2, to));
  }, "sliceInner");
  Leaf2.prototype.getInner = /* @__PURE__ */ __name(function getInner(i2) {
    return this.values[i2];
  }, "getInner");
  Leaf2.prototype.forEachInner = /* @__PURE__ */ __name(function forEachInner(f2, from2, to, start2) {
    for (var i2 = from2; i2 < to; i2++) {
      if (f2(this.values[i2], start2 + i2) === false) {
        return false;
      }
    }
  }, "forEachInner");
  Leaf2.prototype.forEachInvertedInner = /* @__PURE__ */ __name(function forEachInvertedInner(f2, from2, to, start2) {
    for (var i2 = from2 - 1; i2 >= to; i2--) {
      if (f2(this.values[i2], start2 + i2) === false) {
        return false;
      }
    }
  }, "forEachInvertedInner");
  Leaf2.prototype.leafAppend = /* @__PURE__ */ __name(function leafAppend(other) {
    if (this.length + other.length <= GOOD_LEAF_SIZE) {
      return new Leaf2(this.values.concat(other.flatten()));
    }
  }, "leafAppend");
  Leaf2.prototype.leafPrepend = /* @__PURE__ */ __name(function leafPrepend(other) {
    if (this.length + other.length <= GOOD_LEAF_SIZE) {
      return new Leaf2(other.flatten().concat(this.values));
    }
  }, "leafPrepend");
  prototypeAccessors.length.get = function() {
    return this.values.length;
  };
  prototypeAccessors.depth.get = function() {
    return 0;
  };
  Object.defineProperties(Leaf2.prototype, prototypeAccessors);
  return Leaf2;
}(RopeSequence);
RopeSequence.empty = new Leaf([]);
var Append = /* @__PURE__ */ function(RopeSequence3) {
  function Append2(left, right) {
    RopeSequence3.call(this);
    this.left = left;
    this.right = right;
    this.length = left.length + right.length;
    this.depth = Math.max(left.depth, right.depth) + 1;
  }
  __name(Append2, "Append");
  if (RopeSequence3) Append2.__proto__ = RopeSequence3;
  Append2.prototype = Object.create(RopeSequence3 && RopeSequence3.prototype);
  Append2.prototype.constructor = Append2;
  Append2.prototype.flatten = /* @__PURE__ */ __name(function flatten2() {
    return this.left.flatten().concat(this.right.flatten());
  }, "flatten");
  Append2.prototype.getInner = /* @__PURE__ */ __name(function getInner(i2) {
    return i2 < this.left.length ? this.left.get(i2) : this.right.get(i2 - this.left.length);
  }, "getInner");
  Append2.prototype.forEachInner = /* @__PURE__ */ __name(function forEachInner(f2, from2, to, start2) {
    var leftLen = this.left.length;
    if (from2 < leftLen && this.left.forEachInner(f2, from2, Math.min(to, leftLen), start2) === false) {
      return false;
    }
    if (to > leftLen && this.right.forEachInner(f2, Math.max(from2 - leftLen, 0), Math.min(this.length, to) - leftLen, start2 + leftLen) === false) {
      return false;
    }
  }, "forEachInner");
  Append2.prototype.forEachInvertedInner = /* @__PURE__ */ __name(function forEachInvertedInner(f2, from2, to, start2) {
    var leftLen = this.left.length;
    if (from2 > leftLen && this.right.forEachInvertedInner(f2, from2 - leftLen, Math.max(to, leftLen) - leftLen, start2 + leftLen) === false) {
      return false;
    }
    if (to < leftLen && this.left.forEachInvertedInner(f2, Math.min(from2, leftLen), to, start2) === false) {
      return false;
    }
  }, "forEachInvertedInner");
  Append2.prototype.sliceInner = /* @__PURE__ */ __name(function sliceInner(from2, to) {
    if (from2 == 0 && to == this.length) {
      return this;
    }
    var leftLen = this.left.length;
    if (to <= leftLen) {
      return this.left.slice(from2, to);
    }
    if (from2 >= leftLen) {
      return this.right.slice(from2 - leftLen, to - leftLen);
    }
    return this.left.slice(from2, leftLen).append(this.right.slice(0, to - leftLen));
  }, "sliceInner");
  Append2.prototype.leafAppend = /* @__PURE__ */ __name(function leafAppend(other) {
    var inner = this.right.leafAppend(other);
    if (inner) {
      return new Append2(this.left, inner);
    }
  }, "leafAppend");
  Append2.prototype.leafPrepend = /* @__PURE__ */ __name(function leafPrepend(other) {
    var inner = this.left.leafPrepend(other);
    if (inner) {
      return new Append2(inner, this.right);
    }
  }, "leafPrepend");
  Append2.prototype.appendInner = /* @__PURE__ */ __name(function appendInner2(other) {
    if (this.left.depth >= Math.max(this.right.depth, other.depth) + 1) {
      return new Append2(this.left, new Append2(this.right, other));
    }
    return new Append2(this, other);
  }, "appendInner");
  return Append2;
}(RopeSequence);
const max_empty_items = 500;
class Branch {
  static {
    __name(this, "Branch");
  }
  constructor(items, eventCount) {
    this.items = items;
    this.eventCount = eventCount;
  }
  // Pop the latest event off the branch's history and apply it
  // to a document transform.
  popEvent(state, preserveItems) {
    if (this.eventCount == 0)
      return null;
    let end = this.items.length;
    for (; ; end--) {
      let next = this.items.get(end - 1);
      if (next.selection) {
        --end;
        break;
      }
    }
    let remap, mapFrom;
    if (preserveItems) {
      remap = this.remapping(end, this.items.length);
      mapFrom = remap.maps.length;
    }
    let transform = state.tr;
    let selection, remaining;
    let addAfter = [], addBefore = [];
    this.items.forEach((item, i2) => {
      if (!item.step) {
        if (!remap) {
          remap = this.remapping(end, i2 + 1);
          mapFrom = remap.maps.length;
        }
        mapFrom--;
        addBefore.push(item);
        return;
      }
      if (remap) {
        addBefore.push(new Item(item.map));
        let step = item.step.map(remap.slice(mapFrom)), map3;
        if (step && transform.maybeStep(step).doc) {
          map3 = transform.mapping.maps[transform.mapping.maps.length - 1];
          addAfter.push(new Item(map3, void 0, void 0, addAfter.length + addBefore.length));
        }
        mapFrom--;
        if (map3)
          remap.appendMap(map3, mapFrom);
      } else {
        transform.maybeStep(item.step);
      }
      if (item.selection) {
        selection = remap ? item.selection.map(remap.slice(mapFrom)) : item.selection;
        remaining = new Branch(this.items.slice(0, end).append(addBefore.reverse().concat(addAfter)), this.eventCount - 1);
        return false;
      }
    }, this.items.length, 0);
    return { remaining, transform, selection };
  }
  // Create a new branch with the given transform added.
  addTransform(transform, selection, histOptions, preserveItems) {
    let newItems = [], eventCount = this.eventCount;
    let oldItems = this.items, lastItem = !preserveItems && oldItems.length ? oldItems.get(oldItems.length - 1) : null;
    for (let i2 = 0; i2 < transform.steps.length; i2++) {
      let step = transform.steps[i2].invert(transform.docs[i2]);
      let item = new Item(transform.mapping.maps[i2], step, selection), merged;
      if (merged = lastItem && lastItem.merge(item)) {
        item = merged;
        if (i2)
          newItems.pop();
        else
          oldItems = oldItems.slice(0, oldItems.length - 1);
      }
      newItems.push(item);
      if (selection) {
        eventCount++;
        selection = void 0;
      }
      if (!preserveItems)
        lastItem = item;
    }
    let overflow = eventCount - histOptions.depth;
    if (overflow > DEPTH_OVERFLOW) {
      oldItems = cutOffEvents(oldItems, overflow);
      eventCount -= overflow;
    }
    return new Branch(oldItems.append(newItems), eventCount);
  }
  remapping(from2, to) {
    let maps = new Mapping();
    this.items.forEach((item, i2) => {
      let mirrorPos = item.mirrorOffset != null && i2 - item.mirrorOffset >= from2 ? maps.maps.length - item.mirrorOffset : void 0;
      maps.appendMap(item.map, mirrorPos);
    }, from2, to);
    return maps;
  }
  addMaps(array) {
    if (this.eventCount == 0)
      return this;
    return new Branch(this.items.append(array.map((map3) => new Item(map3))), this.eventCount);
  }
  // When the collab module receives remote changes, the history has
  // to know about those, so that it can adjust the steps that were
  // rebased on top of the remote changes, and include the position
  // maps for the remote changes in its array of items.
  rebased(rebasedTransform, rebasedCount) {
    if (!this.eventCount)
      return this;
    let rebasedItems = [], start2 = Math.max(0, this.items.length - rebasedCount);
    let mapping = rebasedTransform.mapping;
    let newUntil = rebasedTransform.steps.length;
    let eventCount = this.eventCount;
    this.items.forEach((item) => {
      if (item.selection)
        eventCount--;
    }, start2);
    let iRebased = rebasedCount;
    this.items.forEach((item) => {
      let pos = mapping.getMirror(--iRebased);
      if (pos == null)
        return;
      newUntil = Math.min(newUntil, pos);
      let map3 = mapping.maps[pos];
      if (item.step) {
        let step = rebasedTransform.steps[pos].invert(rebasedTransform.docs[pos]);
        let selection = item.selection && item.selection.map(mapping.slice(iRebased + 1, pos));
        if (selection)
          eventCount++;
        rebasedItems.push(new Item(map3, step, selection));
      } else {
        rebasedItems.push(new Item(map3));
      }
    }, start2);
    let newMaps = [];
    for (let i2 = rebasedCount; i2 < newUntil; i2++)
      newMaps.push(new Item(mapping.maps[i2]));
    let items = this.items.slice(0, start2).append(newMaps).append(rebasedItems);
    let branch = new Branch(items, eventCount);
    if (branch.emptyItemCount() > max_empty_items)
      branch = branch.compress(this.items.length - rebasedItems.length);
    return branch;
  }
  emptyItemCount() {
    let count2 = 0;
    this.items.forEach((item) => {
      if (!item.step)
        count2++;
    });
    return count2;
  }
  // Compressing a branch means rewriting it to push the air (map-only
  // items) out. During collaboration, these naturally accumulate
  // because each remote change adds one. The `upto` argument is used
  // to ensure that only the items below a given level are compressed,
  // because `rebased` relies on a clean, untouched set of items in
  // order to associate old items with rebased steps.
  compress(upto = this.items.length) {
    let remap = this.remapping(0, upto), mapFrom = remap.maps.length;
    let items = [], events2 = 0;
    this.items.forEach((item, i2) => {
      if (i2 >= upto) {
        items.push(item);
        if (item.selection)
          events2++;
      } else if (item.step) {
        let step = item.step.map(remap.slice(mapFrom)), map3 = step && step.getMap();
        mapFrom--;
        if (map3)
          remap.appendMap(map3, mapFrom);
        if (step) {
          let selection = item.selection && item.selection.map(remap.slice(mapFrom));
          if (selection)
            events2++;
          let newItem = new Item(map3.invert(), step, selection), merged, last = items.length - 1;
          if (merged = items.length && items[last].merge(newItem))
            items[last] = merged;
          else
            items.push(newItem);
        }
      } else if (item.map) {
        mapFrom--;
      }
    }, this.items.length, 0);
    return new Branch(RopeSequence.from(items.reverse()), events2);
  }
}
Branch.empty = new Branch(RopeSequence.empty, 0);
function cutOffEvents(items, n2) {
  let cutPoint;
  items.forEach((item, i2) => {
    if (item.selection && n2-- == 0) {
      cutPoint = i2;
      return false;
    }
  });
  return items.slice(cutPoint);
}
__name(cutOffEvents, "cutOffEvents");
class Item {
  static {
    __name(this, "Item");
  }
  constructor(map3, step, selection, mirrorOffset) {
    this.map = map3;
    this.step = step;
    this.selection = selection;
    this.mirrorOffset = mirrorOffset;
  }
  merge(other) {
    if (this.step && other.step && !other.selection) {
      let step = other.step.merge(this.step);
      if (step)
        return new Item(step.getMap().invert(), step, this.selection);
    }
  }
}
class HistoryState {
  static {
    __name(this, "HistoryState");
  }
  constructor(done, undone, prevRanges, prevTime, prevComposition) {
    this.done = done;
    this.undone = undone;
    this.prevRanges = prevRanges;
    this.prevTime = prevTime;
    this.prevComposition = prevComposition;
  }
}
const DEPTH_OVERFLOW = 20;
function applyTransaction(history2, state, tr2, options2) {
  let historyTr = tr2.getMeta(historyKey), rebased;
  if (historyTr)
    return historyTr.historyState;
  if (tr2.getMeta(closeHistoryKey))
    history2 = new HistoryState(history2.done, history2.undone, null, 0, -1);
  let appended = tr2.getMeta("appendedTransaction");
  if (tr2.steps.length == 0) {
    return history2;
  } else if (appended && appended.getMeta(historyKey)) {
    if (appended.getMeta(historyKey).redo)
      return new HistoryState(history2.done.addTransform(tr2, void 0, options2, mustPreserveItems(state)), history2.undone, rangesFor(tr2.mapping.maps), history2.prevTime, history2.prevComposition);
    else
      return new HistoryState(history2.done, history2.undone.addTransform(tr2, void 0, options2, mustPreserveItems(state)), null, history2.prevTime, history2.prevComposition);
  } else if (tr2.getMeta("addToHistory") !== false && !(appended && appended.getMeta("addToHistory") === false)) {
    let composition = tr2.getMeta("composition");
    let newGroup = history2.prevTime == 0 || !appended && history2.prevComposition != composition && (history2.prevTime < (tr2.time || 0) - options2.newGroupDelay || !isAdjacentTo(tr2, history2.prevRanges));
    let prevRanges = appended ? mapRanges(history2.prevRanges, tr2.mapping) : rangesFor(tr2.mapping.maps);
    return new HistoryState(history2.done.addTransform(tr2, newGroup ? state.selection.getBookmark() : void 0, options2, mustPreserveItems(state)), Branch.empty, prevRanges, tr2.time, composition == null ? history2.prevComposition : composition);
  } else if (rebased = tr2.getMeta("rebased")) {
    return new HistoryState(history2.done.rebased(tr2, rebased), history2.undone.rebased(tr2, rebased), mapRanges(history2.prevRanges, tr2.mapping), history2.prevTime, history2.prevComposition);
  } else {
    return new HistoryState(history2.done.addMaps(tr2.mapping.maps), history2.undone.addMaps(tr2.mapping.maps), mapRanges(history2.prevRanges, tr2.mapping), history2.prevTime, history2.prevComposition);
  }
}
__name(applyTransaction, "applyTransaction");
function isAdjacentTo(transform, prevRanges) {
  if (!prevRanges)
    return false;
  if (!transform.docChanged)
    return true;
  let adjacent = false;
  transform.mapping.maps[0].forEach((start2, end) => {
    for (let i2 = 0; i2 < prevRanges.length; i2 += 2)
      if (start2 <= prevRanges[i2 + 1] && end >= prevRanges[i2])
        adjacent = true;
  });
  return adjacent;
}
__name(isAdjacentTo, "isAdjacentTo");
function rangesFor(maps) {
  let result = [];
  for (let i2 = maps.length - 1; i2 >= 0 && result.length == 0; i2--)
    maps[i2].forEach((_from, _to, from2, to) => result.push(from2, to));
  return result;
}
__name(rangesFor, "rangesFor");
function mapRanges(ranges, mapping) {
  if (!ranges)
    return null;
  let result = [];
  for (let i2 = 0; i2 < ranges.length; i2 += 2) {
    let from2 = mapping.map(ranges[i2], 1), to = mapping.map(ranges[i2 + 1], -1);
    if (from2 <= to)
      result.push(from2, to);
  }
  return result;
}
__name(mapRanges, "mapRanges");
function histTransaction(history2, state, redo2) {
  let preserveItems = mustPreserveItems(state);
  let histOptions = historyKey.get(state).spec.config;
  let pop = (redo2 ? history2.undone : history2.done).popEvent(state, preserveItems);
  if (!pop)
    return null;
  let selection = pop.selection.resolve(pop.transform.doc);
  let added = (redo2 ? history2.done : history2.undone).addTransform(pop.transform, state.selection.getBookmark(), histOptions, preserveItems);
  let newHist = new HistoryState(redo2 ? added : pop.remaining, redo2 ? pop.remaining : added, null, 0, -1);
  return pop.transform.setSelection(selection).setMeta(historyKey, { redo: redo2, historyState: newHist });
}
__name(histTransaction, "histTransaction");
let cachedPreserveItems = false, cachedPreserveItemsPlugins = null;
function mustPreserveItems(state) {
  let plugins = state.plugins;
  if (cachedPreserveItemsPlugins != plugins) {
    cachedPreserveItems = false;
    cachedPreserveItemsPlugins = plugins;
    for (let i2 = 0; i2 < plugins.length; i2++)
      if (plugins[i2].spec.historyPreserveItems) {
        cachedPreserveItems = true;
        break;
      }
  }
  return cachedPreserveItems;
}
__name(mustPreserveItems, "mustPreserveItems");
function closeHistory(tr2) {
  return tr2.setMeta(closeHistoryKey, true);
}
__name(closeHistory, "closeHistory");
const historyKey = new PluginKey("history");
const closeHistoryKey = new PluginKey("closeHistory");
function history$1(config2 = {}) {
  config2 = {
    depth: config2.depth || 100,
    newGroupDelay: config2.newGroupDelay || 500
  };
  return new Plugin({
    key: historyKey,
    state: {
      init() {
        return new HistoryState(Branch.empty, Branch.empty, null, 0, -1);
      },
      apply(tr2, hist, state) {
        return applyTransaction(hist, state, tr2, config2);
      }
    },
    config: config2,
    props: {
      handleDOMEvents: {
        beforeinput(view, e2) {
          let inputType = e2.inputType;
          let command2 = inputType == "historyUndo" ? undo : inputType == "historyRedo" ? redo : null;
          if (!command2)
            return false;
          e2.preventDefault();
          return command2(view.state, view.dispatch);
        }
      }
    }
  });
}
__name(history$1, "history$1");
function buildCommand(redo2, scroll) {
  return (state, dispatch) => {
    let hist = historyKey.getState(state);
    if (!hist || (redo2 ? hist.undone : hist.done).eventCount == 0)
      return false;
    if (dispatch) {
      let tr2 = histTransaction(hist, state, redo2);
      if (tr2)
        dispatch(scroll ? tr2.scrollIntoView() : tr2);
    }
    return true;
  };
}
__name(buildCommand, "buildCommand");
const undo = buildCommand(false, true);
const redo = buildCommand(true, true);
const undoNoScroll = buildCommand(false, false);
const redoNoScroll = buildCommand(true, false);
function undoDepth(state) {
  let hist = historyKey.getState(state);
  return hist ? hist.done.eventCount : 0;
}
__name(undoDepth, "undoDepth");
function redoDepth(state) {
  let hist = historyKey.getState(state);
  return hist ? hist.undone.eventCount : 0;
}
__name(redoDepth, "redoDepth");
const History = Extension.create({
  name: "history",
  addOptions() {
    return {
      depth: 100,
      newGroupDelay: 500
    };
  },
  addCommands() {
    return {
      undo: /* @__PURE__ */ __name(() => ({ state, dispatch }) => {
        return undo(state, dispatch);
      }, "undo"),
      redo: /* @__PURE__ */ __name(() => ({ state, dispatch }) => {
        return redo(state, dispatch);
      }, "redo")
    };
  },
  addProseMirrorPlugins() {
    return [
      history$1(this.options)
    ];
  },
  addKeyboardShortcuts() {
    return {
      "Mod-z": /* @__PURE__ */ __name(() => this.editor.commands.undo(), "Mod-z"),
      "Shift-Mod-z": /* @__PURE__ */ __name(() => this.editor.commands.redo(), "Shift-Mod-z"),
      "Mod-y": /* @__PURE__ */ __name(() => this.editor.commands.redo(), "Mod-y"),
      // Russian keyboard layouts
      "Mod-я": /* @__PURE__ */ __name(() => this.editor.commands.undo(), "Mod-я"),
      "Shift-Mod-я": /* @__PURE__ */ __name(() => this.editor.commands.redo(), "Shift-Mod-я")
    };
  }
});
const HorizontalRule$2 = Node$1.create({
  name: "horizontalRule",
  addOptions() {
    return {
      HTMLAttributes: {}
    };
  },
  group: "block",
  parseHTML() {
    return [{ tag: "hr" }];
  },
  renderHTML({ HTMLAttributes }) {
    return ["hr", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes)];
  },
  addCommands() {
    return {
      setHorizontalRule: /* @__PURE__ */ __name(() => ({ chain, state }) => {
        const { selection } = state;
        const { $from: $originFrom, $to: $originTo } = selection;
        const currentChain = chain();
        if ($originFrom.parentOffset === 0) {
          currentChain.insertContentAt({
            from: Math.max($originFrom.pos - 1, 0),
            to: $originTo.pos
          }, {
            type: this.name
          });
        } else if (isNodeSelection(selection)) {
          currentChain.insertContentAt($originTo.pos, {
            type: this.name
          });
        } else {
          currentChain.insertContent({ type: this.name });
        }
        return currentChain.command(({ tr: tr2, dispatch }) => {
          var _a2;
          if (dispatch) {
            const { $to } = tr2.selection;
            const posAfter = $to.end();
            if ($to.nodeAfter) {
              if ($to.nodeAfter.isTextblock) {
                tr2.setSelection(TextSelection.create(tr2.doc, $to.pos + 1));
              } else if ($to.nodeAfter.isBlock) {
                tr2.setSelection(NodeSelection.create(tr2.doc, $to.pos));
              } else {
                tr2.setSelection(TextSelection.create(tr2.doc, $to.pos));
              }
            } else {
              const node2 = (_a2 = $to.parent.type.contentMatch.defaultType) === null || _a2 === void 0 ? void 0 : _a2.create();
              if (node2) {
                tr2.insert(posAfter, node2);
                tr2.setSelection(TextSelection.create(tr2.doc, posAfter + 1));
              }
            }
            tr2.scrollIntoView();
          }
          return true;
        }).run();
      }, "setHorizontalRule")
    };
  },
  addInputRules() {
    return [
      nodeInputRule({
        find: /^(?:---|—-|___\s|\*\*\*\s)$/,
        type: this.type
      })
    ];
  }
});
const starInputRegex = /(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/;
const starPasteRegex = /(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g;
const underscoreInputRegex = /(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/;
const underscorePasteRegex = /(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g;
const Italic$2 = Mark.create({
  name: "italic",
  addOptions() {
    return {
      HTMLAttributes: {}
    };
  },
  parseHTML() {
    return [
      {
        tag: "em"
      },
      {
        tag: "i",
        getAttrs: /* @__PURE__ */ __name((node2) => node2.style.fontStyle !== "normal" && null, "getAttrs")
      },
      {
        style: "font-style=normal",
        clearMark: /* @__PURE__ */ __name((mark) => mark.type.name === this.name, "clearMark")
      },
      {
        style: "font-style=italic"
      }
    ];
  },
  renderHTML({ HTMLAttributes }) {
    return ["em", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0];
  },
  addCommands() {
    return {
      setItalic: /* @__PURE__ */ __name(() => ({ commands: commands2 }) => {
        return commands2.setMark(this.name);
      }, "setItalic"),
      toggleItalic: /* @__PURE__ */ __name(() => ({ commands: commands2 }) => {
        return commands2.toggleMark(this.name);
      }, "toggleItalic"),
      unsetItalic: /* @__PURE__ */ __name(() => ({ commands: commands2 }) => {
        return commands2.unsetMark(this.name);
      }, "unsetItalic")
    };
  },
  addKeyboardShortcuts() {
    return {
      "Mod-i": /* @__PURE__ */ __name(() => this.editor.commands.toggleItalic(), "Mod-i"),
      "Mod-I": /* @__PURE__ */ __name(() => this.editor.commands.toggleItalic(), "Mod-I")
    };
  },
  addInputRules() {
    return [
      markInputRule({
        find: starInputRegex,
        type: this.type
      }),
      markInputRule({
        find: underscoreInputRegex,
        type: this.type
      })
    ];
  },
  addPasteRules() {
    return [
      markPasteRule({
        find: starPasteRegex,
        type: this.type
      }),
      markPasteRule({
        find: underscorePasteRegex,
        type: this.type
      })
    ];
  }
});
const ListItem$2 = Node$1.create({
  name: "listItem",
  addOptions() {
    return {
      HTMLAttributes: {},
      bulletListTypeName: "bulletList",
      orderedListTypeName: "orderedList"
    };
  },
  content: "paragraph block*",
  defining: true,
  parseHTML() {
    return [
      {
        tag: "li"
      }
    ];
  },
  renderHTML({ HTMLAttributes }) {
    return ["li", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0];
  },
  addKeyboardShortcuts() {
    return {
      Enter: /* @__PURE__ */ __name(() => this.editor.commands.splitListItem(this.name), "Enter"),
      Tab: /* @__PURE__ */ __name(() => this.editor.commands.sinkListItem(this.name), "Tab"),
      "Shift-Tab": /* @__PURE__ */ __name(() => this.editor.commands.liftListItem(this.name), "Shift-Tab")
    };
  }
});
const ListItemName = "listItem";
const TextStyleName = "textStyle";
const inputRegex$1 = /^(\d+)\.\s$/;
const OrderedList$2 = Node$1.create({
  name: "orderedList",
  addOptions() {
    return {
      itemTypeName: "listItem",
      HTMLAttributes: {},
      keepMarks: false,
      keepAttributes: false
    };
  },
  group: "block list",
  content() {
    return `${this.options.itemTypeName}+`;
  },
  addAttributes() {
    return {
      start: {
        default: 1,
        parseHTML: /* @__PURE__ */ __name((element) => {
          return element.hasAttribute("start") ? parseInt(element.getAttribute("start") || "", 10) : 1;
        }, "parseHTML")
      },
      type: {
        default: void 0,
        parseHTML: /* @__PURE__ */ __name((element) => element.getAttribute("type"), "parseHTML")
      }
    };
  },
  parseHTML() {
    return [
      {
        tag: "ol"
      }
    ];
  },
  renderHTML({ HTMLAttributes }) {
    const { start: start2, ...attributesWithoutStart } = HTMLAttributes;
    return start2 === 1 ? ["ol", mergeAttributes(this.options.HTMLAttributes, attributesWithoutStart), 0] : ["ol", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0];
  },
  addCommands() {
    return {
      toggleOrderedList: /* @__PURE__ */ __name(() => ({ commands: commands2, chain }) => {
        if (this.options.keepAttributes) {
          return chain().toggleList(this.name, this.options.itemTypeName, this.options.keepMarks).updateAttributes(ListItemName, this.editor.getAttributes(TextStyleName)).run();
        }
        return commands2.toggleList(this.name, this.options.itemTypeName, this.options.keepMarks);
      }, "toggleOrderedList")
    };
  },
  addKeyboardShortcuts() {
    return {
      "Mod-Shift-7": /* @__PURE__ */ __name(() => this.editor.commands.toggleOrderedList(), "Mod-Shift-7")
    };
  },
  addInputRules() {
    let inputRule = wrappingInputRule({
      find: inputRegex$1,
      type: this.type,
      getAttributes: /* @__PURE__ */ __name((match2) => ({ start: +match2[1] }), "getAttributes"),
      joinPredicate: /* @__PURE__ */ __name((match2, node2) => node2.childCount + node2.attrs.start === +match2[1], "joinPredicate")
    });
    if (this.options.keepMarks || this.options.keepAttributes) {
      inputRule = wrappingInputRule({
        find: inputRegex$1,
        type: this.type,
        keepMarks: this.options.keepMarks,
        keepAttributes: this.options.keepAttributes,
        getAttributes: /* @__PURE__ */ __name((match2) => ({ start: +match2[1], ...this.editor.getAttributes(TextStyleName) }), "getAttributes"),
        joinPredicate: /* @__PURE__ */ __name((match2, node2) => node2.childCount + node2.attrs.start === +match2[1], "joinPredicate"),
        editor: this.editor
      });
    }
    return [
      inputRule
    ];
  }
});
const Paragraph$2 = Node$1.create({
  name: "paragraph",
  priority: 1e3,
  addOptions() {
    return {
      HTMLAttributes: {}
    };
  },
  group: "block",
  content: "inline*",
  parseHTML() {
    return [
      { tag: "p" }
    ];
  },
  renderHTML({ HTMLAttributes }) {
    return ["p", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0];
  },
  addCommands() {
    return {
      setParagraph: /* @__PURE__ */ __name(() => ({ commands: commands2 }) => {
        return commands2.setNode(this.name);
      }, "setParagraph")
    };
  },
  addKeyboardShortcuts() {
    return {
      "Mod-Alt-0": /* @__PURE__ */ __name(() => this.editor.commands.setParagraph(), "Mod-Alt-0")
    };
  }
});
const inputRegex = /(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/;
const pasteRegex = /(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g;
const Strike$2 = Mark.create({
  name: "strike",
  addOptions() {
    return {
      HTMLAttributes: {}
    };
  },
  parseHTML() {
    return [
      {
        tag: "s"
      },
      {
        tag: "del"
      },
      {
        tag: "strike"
      },
      {
        style: "text-decoration",
        consuming: false,
        getAttrs: /* @__PURE__ */ __name((style2) => style2.includes("line-through") ? {} : false, "getAttrs")
      }
    ];
  },
  renderHTML({ HTMLAttributes }) {
    return ["s", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0];
  },
  addCommands() {
    return {
      setStrike: /* @__PURE__ */ __name(() => ({ commands: commands2 }) => {
        return commands2.setMark(this.name);
      }, "setStrike"),
      toggleStrike: /* @__PURE__ */ __name(() => ({ commands: commands2 }) => {
        return commands2.toggleMark(this.name);
      }, "toggleStrike"),
      unsetStrike: /* @__PURE__ */ __name(() => ({ commands: commands2 }) => {
        return commands2.unsetMark(this.name);
      }, "unsetStrike")
    };
  },
  addKeyboardShortcuts() {
    return {
      "Mod-Shift-s": /* @__PURE__ */ __name(() => this.editor.commands.toggleStrike(), "Mod-Shift-s")
    };
  },
  addInputRules() {
    return [
      markInputRule({
        find: inputRegex,
        type: this.type
      })
    ];
  },
  addPasteRules() {
    return [
      markPasteRule({
        find: pasteRegex,
        type: this.type
      })
    ];
  }
});
const Text$2 = Node$1.create({
  name: "text",
  group: "inline"
});
const StarterKit = Extension.create({
  name: "starterKit",
  addExtensions() {
    var _a2, _b, _c, _d, _e2, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t2;
    const extensions = [];
    if (this.options.bold !== false) {
      extensions.push(Bold$2.configure((_a2 = this.options) === null || _a2 === void 0 ? void 0 : _a2.bold));
    }
    if (this.options.blockquote !== false) {
      extensions.push(Blockquote$2.configure((_b = this.options) === null || _b === void 0 ? void 0 : _b.blockquote));
    }
    if (this.options.bulletList !== false) {
      extensions.push(BulletList$2.configure((_c = this.options) === null || _c === void 0 ? void 0 : _c.bulletList));
    }
    if (this.options.code !== false) {
      extensions.push(Code$2.configure((_d = this.options) === null || _d === void 0 ? void 0 : _d.code));
    }
    if (this.options.codeBlock !== false) {
      extensions.push(CodeBlock$2.configure((_e2 = this.options) === null || _e2 === void 0 ? void 0 : _e2.codeBlock));
    }
    if (this.options.document !== false) {
      extensions.push(Document$1.configure((_f = this.options) === null || _f === void 0 ? void 0 : _f.document));
    }
    if (this.options.dropcursor !== false) {
      extensions.push(Dropcursor.configure((_g = this.options) === null || _g === void 0 ? void 0 : _g.dropcursor));
    }
    if (this.options.gapcursor !== false) {
      extensions.push(Gapcursor.configure((_h = this.options) === null || _h === void 0 ? void 0 : _h.gapcursor));
    }
    if (this.options.hardBreak !== false) {
      extensions.push(HardBreak$2.configure((_j = this.options) === null || _j === void 0 ? void 0 : _j.hardBreak));
    }
    if (this.options.heading !== false) {
      extensions.push(Heading$2.configure((_k = this.options) === null || _k === void 0 ? void 0 : _k.heading));
    }
    if (this.options.history !== false) {
      extensions.push(History.configure((_l = this.options) === null || _l === void 0 ? void 0 : _l.history));
    }
    if (this.options.horizontalRule !== false) {
      extensions.push(HorizontalRule$2.configure((_m = this.options) === null || _m === void 0 ? void 0 : _m.horizontalRule));
    }
    if (this.options.italic !== false) {
      extensions.push(Italic$2.configure((_o = this.options) === null || _o === void 0 ? void 0 : _o.italic));
    }
    if (this.options.listItem !== false) {
      extensions.push(ListItem$2.configure((_p = this.options) === null || _p === void 0 ? void 0 : _p.listItem));
    }
    if (this.options.orderedList !== false) {
      extensions.push(OrderedList$2.configure((_q = this.options) === null || _q === void 0 ? void 0 : _q.orderedList));
    }
    if (this.options.paragraph !== false) {
      extensions.push(Paragraph$2.configure((_r = this.options) === null || _r === void 0 ? void 0 : _r.paragraph));
    }
    if (this.options.strike !== false) {
      extensions.push(Strike$2.configure((_s = this.options) === null || _s === void 0 ? void 0 : _s.strike));
    }
    if (this.options.text !== false) {
      extensions.push(Text$2.configure((_t2 = this.options) === null || _t2 === void 0 ? void 0 : _t2.text));
    }
    return extensions;
  }
});
const decodeCache = {};
function getDecodeCache(exclude) {
  let cache = decodeCache[exclude];
  if (cache) {
    return cache;
  }
  cache = decodeCache[exclude] = [];
  for (let i2 = 0; i2 < 128; i2++) {
    const ch = String.fromCharCode(i2);
    cache.push(ch);
  }
  for (let i2 = 0; i2 < exclude.length; i2++) {
    const ch = exclude.charCodeAt(i2);
    cache[ch] = "%" + ("0" + ch.toString(16).toUpperCase()).slice(-2);
  }
  return cache;
}
__name(getDecodeCache, "getDecodeCache");
function decode$2(string, exclude) {
  if (typeof exclude !== "string") {
    exclude = decode$2.defaultChars;
  }
  const cache = getDecodeCache(exclude);
  return string.replace(/(%[a-f0-9]{2})+/gi, function(seq) {
    let result = "";
    for (let i2 = 0, l2 = seq.length; i2 < l2; i2 += 3) {
      const b1 = parseInt(seq.slice(i2 + 1, i2 + 3), 16);
      if (b1 < 128) {
        result += cache[b1];
        continue;
      }
      if ((b1 & 224) === 192 && i2 + 3 < l2) {
        const b2 = parseInt(seq.slice(i2 + 4, i2 + 6), 16);
        if ((b2 & 192) === 128) {
          const chr = b1 << 6 & 1984 | b2 & 63;
          if (chr < 128) {
            result += "��";
          } else {
            result += String.fromCharCode(chr);
          }
          i2 += 3;
          continue;
        }
      }
      if ((b1 & 240) === 224 && i2 + 6 < l2) {
        const b2 = parseInt(seq.slice(i2 + 4, i2 + 6), 16);
        const b3 = parseInt(seq.slice(i2 + 7, i2 + 9), 16);
        if ((b2 & 192) === 128 && (b3 & 192) === 128) {
          const chr = b1 << 12 & 61440 | b2 << 6 & 4032 | b3 & 63;
          if (chr < 2048 || chr >= 55296 && chr <= 57343) {
            result += "���";
          } else {
            result += String.fromCharCode(chr);
          }
          i2 += 6;
          continue;
        }
      }
      if ((b1 & 248) === 240 && i2 + 9 < l2) {
        const b2 = parseInt(seq.slice(i2 + 4, i2 + 6), 16);
        const b3 = parseInt(seq.slice(i2 + 7, i2 + 9), 16);
        const b4 = parseInt(seq.slice(i2 + 10, i2 + 12), 16);
        if ((b2 & 192) === 128 && (b3 & 192) === 128 && (b4 & 192) === 128) {
          let chr = b1 << 18 & 1835008 | b2 << 12 & 258048 | b3 << 6 & 4032 | b4 & 63;
          if (chr < 65536 || chr > 1114111) {
            result += "����";
          } else {
            chr -= 65536;
            result += String.fromCharCode(55296 + (chr >> 10), 56320 + (chr & 1023));
          }
          i2 += 9;
          continue;
        }
      }
      result += "�";
    }
    return result;
  });
}
__name(decode$2, "decode$2");
decode$2.defaultChars = ";/?:@&=+$,#";
decode$2.componentChars = "";
const encodeCache = {};
function getEncodeCache(exclude) {
  let cache = encodeCache[exclude];
  if (cache) {
    return cache;
  }
  cache = encodeCache[exclude] = [];
  for (let i2 = 0; i2 < 128; i2++) {
    const ch = String.fromCharCode(i2);
    if (/^[0-9a-z]$/i.test(ch)) {
      cache.push(ch);
    } else {
      cache.push("%" + ("0" + i2.toString(16).toUpperCase()).slice(-2));
    }
  }
  for (let i2 = 0; i2 < exclude.length; i2++) {
    cache[exclude.charCodeAt(i2)] = exclude[i2];
  }
  return cache;
}
__name(getEncodeCache, "getEncodeCache");
function encode$2(string, exclude, keepEscaped) {
  if (typeof exclude !== "string") {
    keepEscaped = exclude;
    exclude = encode$2.defaultChars;
  }
  if (typeof keepEscaped === "undefined") {
    keepEscaped = true;
  }
  const cache = getEncodeCache(exclude);
  let result = "";
  for (let i2 = 0, l2 = string.length; i2 < l2; i2++) {
    const code2 = string.charCodeAt(i2);
    if (keepEscaped && code2 === 37 && i2 + 2 < l2) {
      if (/^[0-9a-f]{2}$/i.test(string.slice(i2 + 1, i2 + 3))) {
        result += string.slice(i2, i2 + 3);
        i2 += 2;
        continue;
      }
    }
    if (code2 < 128) {
      result += cache[code2];
      continue;
    }
    if (code2 >= 55296 && code2 <= 57343) {
      if (code2 >= 55296 && code2 <= 56319 && i2 + 1 < l2) {
        const nextCode = string.charCodeAt(i2 + 1);
        if (nextCode >= 56320 && nextCode <= 57343) {
          result += encodeURIComponent(string[i2] + string[i2 + 1]);
          i2++;
          continue;
        }
      }
      result += "%EF%BF%BD";
      continue;
    }
    result += encodeURIComponent(string[i2]);
  }
  return result;
}
__name(encode$2, "encode$2");
encode$2.defaultChars = ";/?:@&=+$,-_.!~*'()#";
encode$2.componentChars = "-_.!~*'()";
function format$1(url) {
  let result = "";
  result += url.protocol || "";
  result += url.slashes ? "//" : "";
  result += url.auth ? url.auth + "@" : "";
  if (url.hostname && url.hostname.indexOf(":") !== -1) {
    result += "[" + url.hostname + "]";
  } else {
    result += url.hostname || "";
  }
  result += url.port ? ":" + url.port : "";
  result += url.pathname || "";
  result += url.search || "";
  result += url.hash || "";
  return result;
}
__name(format$1, "format$1");
;
function Url() {
  this.protocol = null;
  this.slashes = null;
  this.auth = null;
  this.port = null;
  this.hostname = null;
  this.hash = null;
  this.search = null;
  this.pathname = null;
}
__name(Url, "Url");
const protocolPattern = /^([a-z0-9.+-]+:)/i;
const portPattern = /:[0-9]*$/;
const simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/;
const delims = ["<", ">", '"', "`", " ", "\r", "\n", "	"];
const unwise = ["{", "}", "|", "\\", "^", "`"].concat(delims);
const autoEscape = ["'"].concat(unwise);
const nonHostChars = ["%", "/", "?", ";", "#"].concat(autoEscape);
const hostEndingChars = ["/", "?", "#"];
const hostnameMaxLen = 255;
const hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/;
const hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/;
const hostlessProtocol = {
  javascript: true,
  "javascript:": true
};
const slashedProtocol = {
  http: true,
  https: true,
  ftp: true,
  gopher: true,
  file: true,
  "http:": true,
  "https:": true,
  "ftp:": true,
  "gopher:": true,
  "file:": true
};
function urlParse(url, slashesDenoteHost) {
  if (url && url instanceof Url) return url;
  const u2 = new Url();
  u2.parse(url, slashesDenoteHost);
  return u2;
}
__name(urlParse, "urlParse");
Url.prototype.parse = function(url, slashesDenoteHost) {
  let lowerProto, hec, slashes;
  let rest = url;
  rest = rest.trim();
  if (!slashesDenoteHost && url.split("#").length === 1) {
    const simplePath = simplePathPattern.exec(rest);
    if (simplePath) {
      this.pathname = simplePath[1];
      if (simplePath[2]) {
        this.search = simplePath[2];
      }
      return this;
    }
  }
  let proto = protocolPattern.exec(rest);
  if (proto) {
    proto = proto[0];
    lowerProto = proto.toLowerCase();
    this.protocol = proto;
    rest = rest.substr(proto.length);
  }
  if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
    slashes = rest.substr(0, 2) === "//";
    if (slashes && !(proto && hostlessProtocol[proto])) {
      rest = rest.substr(2);
      this.slashes = true;
    }
  }
  if (!hostlessProtocol[proto] && (slashes || proto && !slashedProtocol[proto])) {
    let hostEnd = -1;
    for (let i2 = 0; i2 < hostEndingChars.length; i2++) {
      hec = rest.indexOf(hostEndingChars[i2]);
      if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) {
        hostEnd = hec;
      }
    }
    let auth2, atSign;
    if (hostEnd === -1) {
      atSign = rest.lastIndexOf("@");
    } else {
      atSign = rest.lastIndexOf("@", hostEnd);
    }
    if (atSign !== -1) {
      auth2 = rest.slice(0, atSign);
      rest = rest.slice(atSign + 1);
      this.auth = auth2;
    }
    hostEnd = -1;
    for (let i2 = 0; i2 < nonHostChars.length; i2++) {
      hec = rest.indexOf(nonHostChars[i2]);
      if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) {
        hostEnd = hec;
      }
    }
    if (hostEnd === -1) {
      hostEnd = rest.length;
    }
    if (rest[hostEnd - 1] === ":") {
      hostEnd--;
    }
    const host = rest.slice(0, hostEnd);
    rest = rest.slice(hostEnd);
    this.parseHost(host);
    this.hostname = this.hostname || "";
    const ipv6Hostname = this.hostname[0] === "[" && this.hostname[this.hostname.length - 1] === "]";
    if (!ipv6Hostname) {
      const hostparts = this.hostname.split(/\./);
      for (let i2 = 0, l2 = hostparts.length; i2 < l2; i2++) {
        const part = hostparts[i2];
        if (!part) {
          continue;
        }
        if (!part.match(hostnamePartPattern)) {
          let newpart = "";
          for (let j2 = 0, k2 = part.length; j2 < k2; j2++) {
            if (part.charCodeAt(j2) > 127) {
              newpart += "x";
            } else {
              newpart += part[j2];
            }
          }
          if (!newpart.match(hostnamePartPattern)) {
            const validParts = hostparts.slice(0, i2);
            const notHost = hostparts.slice(i2 + 1);
            const bit = part.match(hostnamePartStart);
            if (bit) {
              validParts.push(bit[1]);
              notHost.unshift(bit[2]);
            }
            if (notHost.length) {
              rest = notHost.join(".") + rest;
            }
            this.hostname = validParts.join(".");
            break;
          }
        }
      }
    }
    if (this.hostname.length > hostnameMaxLen) {
      this.hostname = "";
    }
    if (ipv6Hostname) {
      this.hostname = this.hostname.substr(1, this.hostname.length - 2);
    }
  }
  const hash = rest.indexOf("#");
  if (hash !== -1) {
    this.hash = rest.substr(hash);
    rest = rest.slice(0, hash);
  }
  const qm = rest.indexOf("?");
  if (qm !== -1) {
    this.search = rest.substr(qm);
    rest = rest.slice(0, qm);
  }
  if (rest) {
    this.pathname = rest;
  }
  if (slashedProtocol[lowerProto] && this.hostname && !this.pathname) {
    this.pathname = "";
  }
  return this;
};
Url.prototype.parseHost = function(host) {
  let port = portPattern.exec(host);
  if (port) {
    port = port[0];
    if (port !== ":") {
      this.port = port.substr(1);
    }
    host = host.substr(0, host.length - port.length);
  }
  if (host) {
    this.hostname = host;
  }
};
const mdurl = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  decode: decode$2,
  encode: encode$2,
  format: format$1,
  parse: urlParse
}, Symbol.toStringTag, { value: "Module" }));
const Any = /[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
const Cc = /[\0-\x1F\x7F-\x9F]/;
const regex$1 = /[\xAD\u0600-\u0605\u061C\u06DD\u070F\u0890\u0891\u08E2\u180E\u200B-\u200F\u202A-\u202E\u2060-\u2064\u2066-\u206F\uFEFF\uFFF9-\uFFFB]|\uD804[\uDCBD\uDCCD]|\uD80D[\uDC30-\uDC3F]|\uD82F[\uDCA0-\uDCA3]|\uD834[\uDD73-\uDD7A]|\uDB40[\uDC01\uDC20-\uDC7F]/;
const P = /[!-#%-\*,-\/:;\?@\[-\]_\{\}\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061D-\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u09FD\u0A76\u0AF0\u0C77\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1B7D\u1B7E\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4F\u2E52-\u2E5D\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]|\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD803[\uDEAD\uDF55-\uDF59\uDF86-\uDF89]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC8\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDC4B-\uDC4F\uDC5A\uDC5B\uDC5D\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDE60-\uDE6C\uDEB9\uDF3C-\uDF3E]|\uD806[\uDC3B\uDD44-\uDD46\uDDE2\uDE3F-\uDE46\uDE9A-\uDE9C\uDE9E-\uDEA2\uDF00-\uDF09]|\uD807[\uDC41-\uDC45\uDC70\uDC71\uDEF7\uDEF8\uDF43-\uDF4F\uDFFF]|\uD809[\uDC70-\uDC74]|\uD80B[\uDFF1\uDFF2]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD81B[\uDE97-\uDE9A\uDFE2]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]|\uD83A[\uDD5E\uDD5F]/;
const regex = /[\$\+<->\^`\|~\xA2-\xA6\xA8\xA9\xAC\xAE-\xB1\xB4\xB8\xD7\xF7\u02C2-\u02C5\u02D2-\u02DF\u02E5-\u02EB\u02ED\u02EF-\u02FF\u0375\u0384\u0385\u03F6\u0482\u058D-\u058F\u0606-\u0608\u060B\u060E\u060F\u06DE\u06E9\u06FD\u06FE\u07F6\u07FE\u07FF\u0888\u09F2\u09F3\u09FA\u09FB\u0AF1\u0B70\u0BF3-\u0BFA\u0C7F\u0D4F\u0D79\u0E3F\u0F01-\u0F03\u0F13\u0F15-\u0F17\u0F1A-\u0F1F\u0F34\u0F36\u0F38\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE\u0FCF\u0FD5-\u0FD8\u109E\u109F\u1390-\u1399\u166D\u17DB\u1940\u19DE-\u19FF\u1B61-\u1B6A\u1B74-\u1B7C\u1FBD\u1FBF-\u1FC1\u1FCD-\u1FCF\u1FDD-\u1FDF\u1FED-\u1FEF\u1FFD\u1FFE\u2044\u2052\u207A-\u207C\u208A-\u208C\u20A0-\u20C0\u2100\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u214F\u218A\u218B\u2190-\u2307\u230C-\u2328\u232B-\u2426\u2440-\u244A\u249C-\u24E9\u2500-\u2767\u2794-\u27C4\u27C7-\u27E5\u27F0-\u2982\u2999-\u29D7\u29DC-\u29FB\u29FE-\u2B73\u2B76-\u2B95\u2B97-\u2BFF\u2CE5-\u2CEA\u2E50\u2E51\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFF\u3004\u3012\u3013\u3020\u3036\u3037\u303E\u303F\u309B\u309C\u3190\u3191\u3196-\u319F\u31C0-\u31E3\u31EF\u3200-\u321E\u322A-\u3247\u3250\u3260-\u327F\u328A-\u32B0\u32C0-\u33FF\u4DC0-\u4DFF\uA490-\uA4C6\uA700-\uA716\uA720\uA721\uA789\uA78A\uA828-\uA82B\uA836-\uA839\uAA77-\uAA79\uAB5B\uAB6A\uAB6B\uFB29\uFBB2-\uFBC2\uFD40-\uFD4F\uFDCF\uFDFC-\uFDFF\uFE62\uFE64-\uFE66\uFE69\uFF04\uFF0B\uFF1C-\uFF1E\uFF3E\uFF40\uFF5C\uFF5E\uFFE0-\uFFE6\uFFE8-\uFFEE\uFFFC\uFFFD]|\uD800[\uDD37-\uDD3F\uDD79-\uDD89\uDD8C-\uDD8E\uDD90-\uDD9C\uDDA0\uDDD0-\uDDFC]|\uD802[\uDC77\uDC78\uDEC8]|\uD805\uDF3F|\uD807[\uDFD5-\uDFF1]|\uD81A[\uDF3C-\uDF3F\uDF45]|\uD82F\uDC9C|\uD833[\uDF50-\uDFC3]|\uD834[\uDC00-\uDCF5\uDD00-\uDD26\uDD29-\uDD64\uDD6A-\uDD6C\uDD83\uDD84\uDD8C-\uDDA9\uDDAE-\uDDEA\uDE00-\uDE41\uDE45\uDF00-\uDF56]|\uD835[\uDEC1\uDEDB\uDEFB\uDF15\uDF35\uDF4F\uDF6F\uDF89\uDFA9\uDFC3]|\uD836[\uDC00-\uDDFF\uDE37-\uDE3A\uDE6D-\uDE74\uDE76-\uDE83\uDE85\uDE86]|\uD838[\uDD4F\uDEFF]|\uD83B[\uDCAC\uDCB0\uDD2E\uDEF0\uDEF1]|\uD83C[\uDC00-\uDC2B\uDC30-\uDC93\uDCA0-\uDCAE\uDCB1-\uDCBF\uDCC1-\uDCCF\uDCD1-\uDCF5\uDD0D-\uDDAD\uDDE6-\uDE02\uDE10-\uDE3B\uDE40-\uDE48\uDE50\uDE51\uDE60-\uDE65\uDF00-\uDFFF]|\uD83D[\uDC00-\uDED7\uDEDC-\uDEEC\uDEF0-\uDEFC\uDF00-\uDF76\uDF7B-\uDFD9\uDFE0-\uDFEB\uDFF0]|\uD83E[\uDC00-\uDC0B\uDC10-\uDC47\uDC50-\uDC59\uDC60-\uDC87\uDC90-\uDCAD\uDCB0\uDCB1\uDD00-\uDE53\uDE60-\uDE6D\uDE70-\uDE7C\uDE80-\uDE88\uDE90-\uDEBD\uDEBF-\uDEC5\uDECE-\uDEDB\uDEE0-\uDEE8\uDEF0-\uDEF8\uDF00-\uDF92\uDF94-\uDFCA]/;
const Z = /[ \xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]/;
const ucmicro = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  Any,
  Cc,
  Cf: regex$1,
  P,
  S: regex,
  Z
}, Symbol.toStringTag, { value: "Module" }));
const htmlDecodeTree = new Uint16Array(
  // prettier-ignore
  'ᵁ<Õıʊҝջאٵ۞ޢߖࠏ੊ઑඡ๭༉༦჊ረዡᐕᒝᓃᓟᔥ\0\0\0\0\0\0ᕫᛍᦍᰒᷝ὾⁠↰⊍⏀⏻⑂⠤⤒ⴈ⹈⿎〖㊺㘹㞬㣾㨨㩱㫠㬮ࠀEMabcfglmnoprstu\\bfms¦³¹ÈÏlig耻Æ䃆P耻&䀦cute耻Á䃁reve;䄂Āiyx}rc耻Â䃂;䐐r;쀀𝔄rave耻À䃀pha;䎑acr;䄀d;橓Āgp¡on;䄄f;쀀𝔸plyFunction;恡ing耻Å䃅Ācs¾Ãr;쀀𝒜ign;扔ilde耻Ã䃃ml耻Ä䃄ЀaceforsuåûþėĜĢħĪĀcrêòkslash;或Ŷöø;櫧ed;挆y;䐑ƀcrtąċĔause;戵noullis;愬a;䎒r;쀀𝔅pf;쀀𝔹eve;䋘còēmpeq;扎܀HOacdefhilorsuōőŖƀƞƢƵƷƺǜȕɳɸɾcy;䐧PY耻©䂩ƀcpyŝŢźute;䄆Ā;iŧŨ拒talDifferentialD;慅leys;愭ȀaeioƉƎƔƘron;䄌dil耻Ç䃇rc;䄈nint;戰ot;䄊ĀdnƧƭilla;䂸terDot;䂷òſi;䎧rcleȀDMPTǇǋǑǖot;抙inus;抖lus;投imes;抗oĀcsǢǸkwiseContourIntegral;戲eCurlyĀDQȃȏoubleQuote;思uote;怙ȀlnpuȞȨɇɕonĀ;eȥȦ户;橴ƀgitȯȶȺruent;扡nt;戯ourIntegral;戮ĀfrɌɎ;愂oduct;成nterClockwiseContourIntegral;戳oss;樯cr;쀀𝒞pĀ;Cʄʅ拓ap;才րDJSZacefiosʠʬʰʴʸˋ˗ˡ˦̳ҍĀ;oŹʥtrahd;椑cy;䐂cy;䐅cy;䐏ƀgrsʿ˄ˇger;怡r;憡hv;櫤Āayː˕ron;䄎;䐔lĀ;t˝˞戇a;䎔r;쀀𝔇Āaf˫̧Ācm˰̢riticalȀADGT̖̜̀̆cute;䂴oŴ̋̍;䋙bleAcute;䋝rave;䁠ilde;䋜ond;拄ferentialD;慆Ѱ̽\0\0\0͔͂\0Ѕf;쀀𝔻ƀ;DE͈͉͍䂨ot;惜qual;扐blèCDLRUVͣͲ΂ϏϢϸontourIntegraìȹoɴ͹\0\0ͻ»͉nArrow;懓Āeo·ΤftƀARTΐΖΡrrow;懐ightArrow;懔eåˊngĀLRΫτeftĀARγιrrow;柸ightArrow;柺ightArrow;柹ightĀATϘϞrrow;懒ee;抨pɁϩ\0\0ϯrrow;懑ownArrow;懕erticalBar;戥ǹABLRTaВЪаўѿͼrrowƀ;BUНОТ憓ar;椓pArrow;懵reve;䌑eft˒к\0ц\0ѐightVector;楐eeVector;楞ectorĀ;Bљњ憽ar;楖ightǔѧ\0ѱeeVector;楟ectorĀ;BѺѻ懁ar;楗eeĀ;A҆҇护rrow;憧ĀctҒҗr;쀀𝒟rok;䄐ࠀNTacdfglmopqstuxҽӀӄӋӞӢӧӮӵԡԯԶՒ՝ՠեG;䅊H耻Ð䃐cute耻É䃉ƀaiyӒӗӜron;䄚rc耻Ê䃊;䐭ot;䄖r;쀀𝔈rave耻È䃈ement;戈ĀapӺӾcr;䄒tyɓԆ\0\0ԒmallSquare;旻erySmallSquare;斫ĀgpԦԪon;䄘f;쀀𝔼silon;䎕uĀaiԼՉlĀ;TՂՃ橵ilde;扂librium;懌Āci՗՚r;愰m;橳a;䎗ml耻Ë䃋Āipժկsts;戃onentialE;慇ʀcfiosօֈ֍ֲ׌y;䐤r;쀀𝔉lledɓ֗\0\0֣mallSquare;旼erySmallSquare;斪Ͱֺ\0ֿ\0\0ׄf;쀀𝔽All;戀riertrf;愱cò׋؀JTabcdfgorstר׬ׯ׺؀ؒؖ؛؝أ٬ٲcy;䐃耻>䀾mmaĀ;d׷׸䎓;䏜reve;䄞ƀeiy؇،ؐdil;䄢rc;䄜;䐓ot;䄠r;쀀𝔊;拙pf;쀀𝔾eater̀EFGLSTصلَٖٛ٦qualĀ;Lؾؿ扥ess;招ullEqual;执reater;檢ess;扷lantEqual;橾ilde;扳cr;쀀𝒢;扫ЀAacfiosuڅڋږڛڞڪھۊRDcy;䐪Āctڐڔek;䋇;䁞irc;䄤r;愌lbertSpace;愋ǰگ\0ڲf;愍izontalLine;攀Āctۃۅòکrok;䄦mpńېۘownHumðįqual;扏܀EJOacdfgmnostuۺ۾܃܇܎ܚܞܡܨ݄ݸދޏޕcy;䐕lig;䄲cy;䐁cute耻Í䃍Āiyܓܘrc耻Î䃎;䐘ot;䄰r;愑rave耻Ì䃌ƀ;apܠܯܿĀcgܴܷr;䄪inaryI;慈lieóϝǴ݉\0ݢĀ;eݍݎ戬Āgrݓݘral;戫section;拂isibleĀCTݬݲomma;恣imes;恢ƀgptݿރވon;䄮f;쀀𝕀a;䎙cr;愐ilde;䄨ǫޚ\0ޞcy;䐆l耻Ï䃏ʀcfosuެ޷޼߂ߐĀiyޱ޵rc;䄴;䐙r;쀀𝔍pf;쀀𝕁ǣ߇\0ߌr;쀀𝒥rcy;䐈kcy;䐄΀HJacfosߤߨ߽߬߱ࠂࠈcy;䐥cy;䐌ppa;䎚Āey߶߻dil;䄶;䐚r;쀀𝔎pf;쀀𝕂cr;쀀𝒦րJTaceflmostࠥࠩࠬࡐࡣ঳সে্਷ੇcy;䐉耻<䀼ʀcmnpr࠷࠼ࡁࡄࡍute;䄹bda;䎛g;柪lacetrf;愒r;憞ƀaeyࡗ࡜ࡡron;䄽dil;䄻;䐛Āfsࡨ॰tԀACDFRTUVarࡾࢩࢱࣦ࣠ࣼयज़ΐ४Ānrࢃ࢏gleBracket;柨rowƀ;BR࢙࢚࢞憐ar;懤ightArrow;懆eiling;挈oǵࢷ\0ࣃbleBracket;柦nǔࣈ\0࣒eeVector;楡ectorĀ;Bࣛࣜ懃ar;楙loor;挊ightĀAV࣯ࣵrrow;憔ector;楎Āerँगeƀ;AVउऊऐ抣rrow;憤ector;楚iangleƀ;BEतथऩ抲ar;槏qual;抴pƀDTVषूौownVector;楑eeVector;楠ectorĀ;Bॖॗ憿ar;楘ectorĀ;B॥०憼ar;楒ightáΜs̀EFGLSTॾঋকঝঢভqualGreater;拚ullEqual;扦reater;扶ess;檡lantEqual;橽ilde;扲r;쀀𝔏Ā;eঽা拘ftarrow;懚idot;䄿ƀnpw৔ਖਛgȀLRlr৞৷ਂਐeftĀAR০৬rrow;柵ightArrow;柷ightArrow;柶eftĀarγਊightáοightáϊf;쀀𝕃erĀLRਢਬeftArrow;憙ightArrow;憘ƀchtਾੀੂòࡌ;憰rok;䅁;扪Ѐacefiosuਗ਼੝੠੷੼અઋ઎p;椅y;䐜Ādl੥੯iumSpace;恟lintrf;愳r;쀀𝔐nusPlus;戓pf;쀀𝕄cò੶;䎜ҀJacefostuણધભીଔଙඑ඗ඞcy;䐊cute;䅃ƀaey઴હાron;䅇dil;䅅;䐝ƀgswે૰଎ativeƀMTV૓૟૨ediumSpace;怋hiĀcn૦૘ë૙eryThiî૙tedĀGL૸ଆreaterGreateòٳessLesóੈLine;䀊r;쀀𝔑ȀBnptଢନଷ଺reak;恠BreakingSpace;䂠f;愕ڀ;CDEGHLNPRSTV୕ୖ୪୼஡௫ఄ౞಄ದ೘ൡඅ櫬Āou୛୤ngruent;扢pCap;扭oubleVerticalBar;戦ƀlqxஃஊ஛ement;戉ualĀ;Tஒஓ扠ilde;쀀≂̸ists;戄reater΀;EFGLSTஶஷ஽௉௓௘௥扯qual;扱ullEqual;쀀≧̸reater;쀀≫̸ess;批lantEqual;쀀⩾̸ilde;扵umpń௲௽ownHump;쀀≎̸qual;쀀≏̸eĀfsఊధtTriangleƀ;BEచఛడ拪ar;쀀⧏̸qual;括s̀;EGLSTవశ఼ౄోౘ扮qual;扰reater;扸ess;쀀≪̸lantEqual;쀀⩽̸ilde;扴estedĀGL౨౹reaterGreater;쀀⪢̸essLess;쀀⪡̸recedesƀ;ESಒಓಛ技qual;쀀⪯̸lantEqual;拠ĀeiಫಹverseElement;戌ghtTriangleƀ;BEೋೌ೒拫ar;쀀⧐̸qual;拭ĀquೝഌuareSuĀbp೨೹setĀ;E೰ೳ쀀⊏̸qual;拢ersetĀ;Eഃആ쀀⊐̸qual;拣ƀbcpഓതൎsetĀ;Eഛഞ쀀⊂⃒qual;抈ceedsȀ;ESTലള഻െ抁qual;쀀⪰̸lantEqual;拡ilde;쀀≿̸ersetĀ;E൘൛쀀⊃⃒qual;抉ildeȀ;EFT൮൯൵ൿ扁qual;扄ullEqual;扇ilde;扉erticalBar;戤cr;쀀𝒩ilde耻Ñ䃑;䎝܀Eacdfgmoprstuvලෂ෉෕ෛ෠෧෼ขภยา฿ไlig;䅒cute耻Ó䃓Āiy෎ීrc耻Ô䃔;䐞blac;䅐r;쀀𝔒rave耻Ò䃒ƀaei෮ෲ෶cr;䅌ga;䎩cron;䎟pf;쀀𝕆enCurlyĀDQฎบoubleQuote;怜uote;怘;橔Āclวฬr;쀀𝒪ash耻Ø䃘iŬื฼de耻Õ䃕es;樷ml耻Ö䃖erĀBP๋๠Āar๐๓r;怾acĀek๚๜;揞et;掴arenthesis;揜Ҁacfhilors๿ງຊຏຒດຝະ໼rtialD;戂y;䐟r;쀀𝔓i;䎦;䎠usMinus;䂱Āipຢອncareplanåڝf;愙Ȁ;eio຺ູ໠໤檻cedesȀ;EST່້໏໚扺qual;檯lantEqual;扼ilde;找me;怳Ādp໩໮uct;戏ortionĀ;aȥ໹l;戝Āci༁༆r;쀀𝒫;䎨ȀUfos༑༖༛༟OT耻"䀢r;쀀𝔔pf;愚cr;쀀𝒬؀BEacefhiorsu༾གྷཇའཱིྦྷྪྭ႖ႩႴႾarr;椐G耻®䂮ƀcnrཎནབute;䅔g;柫rĀ;tཛྷཝ憠l;椖ƀaeyཧཬཱron;䅘dil;䅖;䐠Ā;vླྀཹ愜erseĀEUྂྙĀlq྇ྎement;戋uilibrium;懋pEquilibrium;楯r»ཹo;䎡ghtЀACDFTUVa࿁࿫࿳ဢဨၛႇϘĀnr࿆࿒gleBracket;柩rowƀ;BL࿜࿝࿡憒ar;懥eftArrow;懄eiling;按oǵ࿹\0စbleBracket;柧nǔည\0နeeVector;楝ectorĀ;Bဝသ懂ar;楕loor;挋Āerိ၃eƀ;AVဵံြ抢rrow;憦ector;楛iangleƀ;BEၐၑၕ抳ar;槐qual;抵pƀDTVၣၮၸownVector;楏eeVector;楜ectorĀ;Bႂႃ憾ar;楔ectorĀ;B႑႒懀ar;楓Āpuႛ႞f;愝ndImplies;楰ightarrow;懛ĀchႹႼr;愛;憱leDelayed;槴ڀHOacfhimoqstuფჱჷჽᄙᄞᅑᅖᅡᅧᆵᆻᆿĀCcჩხHcy;䐩y;䐨FTcy;䐬cute;䅚ʀ;aeiyᄈᄉᄎᄓᄗ檼ron;䅠dil;䅞rc;䅜;䐡r;쀀𝔖ortȀDLRUᄪᄴᄾᅉownArrow»ОeftArrow»࢚ightArrow»࿝pArrow;憑gma;䎣allCircle;战pf;쀀𝕊ɲᅭ\0\0ᅰt;戚areȀ;ISUᅻᅼᆉᆯ斡ntersection;抓uĀbpᆏᆞsetĀ;Eᆗᆘ抏qual;抑ersetĀ;Eᆨᆩ抐qual;抒nion;抔cr;쀀𝒮ar;拆ȀbcmpᇈᇛሉላĀ;sᇍᇎ拐etĀ;Eᇍᇕqual;抆ĀchᇠህeedsȀ;ESTᇭᇮᇴᇿ扻qual;檰lantEqual;扽ilde;承Tháྌ;我ƀ;esሒሓሣ拑rsetĀ;Eሜም抃qual;抇et»ሓրHRSacfhiorsሾቄ቉ቕ቞ቱቶኟዂወዑORN耻Þ䃞ADE;愢ĀHc቎ቒcy;䐋y;䐦Ābuቚቜ;䀉;䎤ƀaeyብቪቯron;䅤dil;䅢;䐢r;쀀𝔗Āeiቻ኉ǲኀ\0ኇefore;戴a;䎘Ācn኎ኘkSpace;쀀  Space;怉ldeȀ;EFTካኬኲኼ戼qual;扃ullEqual;扅ilde;扈pf;쀀𝕋ipleDot;惛Āctዖዛr;쀀𝒯rok;䅦ૡዷጎጚጦ\0ጬጱ\0\0\0\0\0ጸጽ፷ᎅ\0᏿ᐄᐊᐐĀcrዻጁute耻Ú䃚rĀ;oጇገ憟cir;楉rǣጓ\0጖y;䐎ve;䅬Āiyጞጣrc耻Û䃛;䐣blac;䅰r;쀀𝔘rave耻Ù䃙acr;䅪Ādiፁ፩erĀBPፈ፝Āarፍፐr;䁟acĀekፗፙ;揟et;掵arenthesis;揝onĀ;P፰፱拃lus;抎Āgp፻፿on;䅲f;쀀𝕌ЀADETadps᎕ᎮᎸᏄϨᏒᏗᏳrrowƀ;BDᅐᎠᎤar;椒ownArrow;懅ownArrow;憕quilibrium;楮eeĀ;AᏋᏌ报rrow;憥ownáϳerĀLRᏞᏨeftArrow;憖ightArrow;憗iĀ;lᏹᏺ䏒on;䎥ing;䅮cr;쀀𝒰ilde;䅨ml耻Ü䃜ҀDbcdefosvᐧᐬᐰᐳᐾᒅᒊᒐᒖash;披ar;櫫y;䐒ashĀ;lᐻᐼ抩;櫦Āerᑃᑅ;拁ƀbtyᑌᑐᑺar;怖Ā;iᑏᑕcalȀBLSTᑡᑥᑪᑴar;戣ine;䁼eparator;杘ilde;所ThinSpace;怊r;쀀𝔙pf;쀀𝕍cr;쀀𝒱dash;抪ʀcefosᒧᒬᒱᒶᒼirc;䅴dge;拀r;쀀𝔚pf;쀀𝕎cr;쀀𝒲Ȁfiosᓋᓐᓒᓘr;쀀𝔛;䎞pf;쀀𝕏cr;쀀𝒳ҀAIUacfosuᓱᓵᓹᓽᔄᔏᔔᔚᔠcy;䐯cy;䐇cy;䐮cute耻Ý䃝Āiyᔉᔍrc;䅶;䐫r;쀀𝔜pf;쀀𝕐cr;쀀𝒴ml;䅸ЀHacdefosᔵᔹᔿᕋᕏᕝᕠᕤcy;䐖cute;䅹Āayᕄᕉron;䅽;䐗ot;䅻ǲᕔ\0ᕛoWidtè૙a;䎖r;愨pf;愤cr;쀀𝒵௡ᖃᖊᖐ\0ᖰᖶᖿ\0\0\0\0ᗆᗛᗫᙟ᙭\0ᚕ᚛ᚲᚹ\0ᚾcute耻á䃡reve;䄃̀;Ediuyᖜᖝᖡᖣᖨᖭ戾;쀀∾̳;房rc耻â䃢te肻´̆;䐰lig耻æ䃦Ā;r²ᖺ;쀀𝔞rave耻à䃠ĀepᗊᗖĀfpᗏᗔsym;愵èᗓha;䎱ĀapᗟcĀclᗤᗧr;䄁g;樿ɤᗰ\0\0ᘊʀ;adsvᗺᗻᗿᘁᘇ戧nd;橕;橜lope;橘;橚΀;elmrszᘘᘙᘛᘞᘿᙏᙙ戠;榤e»ᘙsdĀ;aᘥᘦ戡ѡᘰᘲᘴᘶᘸᘺᘼᘾ;榨;榩;榪;榫;榬;榭;榮;榯tĀ;vᙅᙆ戟bĀ;dᙌᙍ抾;榝Āptᙔᙗh;戢»¹arr;捼Āgpᙣᙧon;䄅f;쀀𝕒΀;Eaeiop዁ᙻᙽᚂᚄᚇᚊ;橰cir;橯;扊d;手s;䀧roxĀ;e዁ᚒñᚃing耻å䃥ƀctyᚡᚦᚨr;쀀𝒶;䀪mpĀ;e዁ᚯñʈilde耻ã䃣ml耻ä䃤Āciᛂᛈoninôɲnt;樑ࠀNabcdefiklnoprsu᛭ᛱᜰ᜼ᝃᝈ᝸᝽០៦ᠹᡐᜍ᤽᥈ᥰot;櫭Ācrᛶ᜞kȀcepsᜀᜅᜍᜓong;扌psilon;䏶rime;怵imĀ;e᜚᜛戽q;拍Ŷᜢᜦee;抽edĀ;gᜬᜭ挅e»ᜭrkĀ;t፜᜷brk;掶Āoyᜁᝁ;䐱quo;怞ʀcmprtᝓ᝛ᝡᝤᝨausĀ;eĊĉptyv;榰séᜌnoõēƀahwᝯ᝱ᝳ;䎲;愶een;扬r;쀀𝔟g΀costuvwឍឝឳេ៕៛៞ƀaiuបពរðݠrc;旯p»፱ƀdptឤឨឭot;樀lus;樁imes;樂ɱឹ\0\0ើcup;樆ar;昅riangleĀdu៍្own;施p;斳plus;樄eåᑄåᒭarow;植ƀako៭ᠦᠵĀcn៲ᠣkƀlst៺֫᠂ozenge;槫riangleȀ;dlr᠒᠓᠘᠝斴own;斾eft;旂ight;斸k;搣Ʊᠫ\0ᠳƲᠯ\0ᠱ;斒;斑4;斓ck;斈ĀeoᠾᡍĀ;qᡃᡆ쀀=⃥uiv;쀀≡⃥t;挐Ȁptwxᡙᡞᡧᡬf;쀀𝕓Ā;tᏋᡣom»Ꮜtie;拈؀DHUVbdhmptuvᢅᢖᢪᢻᣗᣛᣬ᣿ᤅᤊᤐᤡȀLRlrᢎᢐᢒᢔ;敗;敔;敖;敓ʀ;DUduᢡᢢᢤᢦᢨ敐;敦;敩;敤;敧ȀLRlrᢳᢵᢷᢹ;敝;敚;敜;教΀;HLRhlrᣊᣋᣍᣏᣑᣓᣕ救;敬;散;敠;敫;敢;敟ox;槉ȀLRlrᣤᣦᣨᣪ;敕;敒;攐;攌ʀ;DUduڽ᣷᣹᣻᣽;敥;敨;攬;攴inus;抟lus;択imes;抠ȀLRlrᤙᤛᤝ᤟;敛;敘;攘;攔΀;HLRhlrᤰᤱᤳᤵᤷ᤻᤹攂;敪;敡;敞;攼;攤;攜Āevģ᥂bar耻¦䂦Ȁceioᥑᥖᥚᥠr;쀀𝒷mi;恏mĀ;e᜚᜜lƀ;bhᥨᥩᥫ䁜;槅sub;柈Ŭᥴ᥾lĀ;e᥹᥺怢t»᥺pƀ;Eeįᦅᦇ;檮Ā;qۜۛೡᦧ\0᧨ᨑᨕᨲ\0ᨷᩐ\0\0᪴\0\0᫁\0\0ᬡᬮ᭍᭒\0᯽\0ᰌƀcpr᦭ᦲ᧝ute;䄇̀;abcdsᦿᧀᧄ᧊᧕᧙戩nd;橄rcup;橉Āau᧏᧒p;橋p;橇ot;橀;쀀∩︀Āeo᧢᧥t;恁îړȀaeiu᧰᧻ᨁᨅǰ᧵\0᧸s;橍on;䄍dil耻ç䃧rc;䄉psĀ;sᨌᨍ橌m;橐ot;䄋ƀdmnᨛᨠᨦil肻¸ƭptyv;榲t脀¢;eᨭᨮ䂢räƲr;쀀𝔠ƀceiᨽᩀᩍy;䑇ckĀ;mᩇᩈ朓ark»ᩈ;䏇r΀;Ecefms᩟᩠ᩢᩫ᪤᪪᪮旋;槃ƀ;elᩩᩪᩭ䋆q;扗eɡᩴ\0\0᪈rrowĀlr᩼᪁eft;憺ight;憻ʀRSacd᪒᪔᪖᪚᪟»ཇ;擈st;抛irc;抚ash;抝nint;樐id;櫯cir;槂ubsĀ;u᪻᪼晣it»᪼ˬ᫇᫔᫺\0ᬊonĀ;eᫍᫎ䀺Ā;qÇÆɭ᫙\0\0᫢aĀ;t᫞᫟䀬;䁀ƀ;fl᫨᫩᫫戁îᅠeĀmx᫱᫶ent»᫩eóɍǧ᫾\0ᬇĀ;dኻᬂot;橭nôɆƀfryᬐᬔᬗ;쀀𝕔oäɔ脀©;sŕᬝr;愗Āaoᬥᬩrr;憵ss;朗Ācuᬲᬷr;쀀𝒸Ābpᬼ᭄Ā;eᭁᭂ櫏;櫑Ā;eᭉᭊ櫐;櫒dot;拯΀delprvw᭠᭬᭷ᮂᮬᯔ᯹arrĀlr᭨᭪;椸;椵ɰ᭲\0\0᭵r;拞c;拟arrĀ;p᭿ᮀ憶;椽̀;bcdosᮏᮐᮖᮡᮥᮨ截rcap;橈Āauᮛᮞp;橆p;橊ot;抍r;橅;쀀∪︀Ȁalrv᮵ᮿᯞᯣrrĀ;mᮼᮽ憷;椼yƀevwᯇᯔᯘqɰᯎ\0\0ᯒreã᭳uã᭵ee;拎edge;拏en耻¤䂤earrowĀlrᯮ᯳eft»ᮀight»ᮽeäᯝĀciᰁᰇoninôǷnt;戱lcty;挭ঀAHabcdefhijlorstuwz᰸᰻᰿ᱝᱩᱵᲊᲞᲬᲷ᳻᳿ᴍᵻᶑᶫᶻ᷆᷍rò΁ar;楥Ȁglrs᱈ᱍ᱒᱔ger;怠eth;愸òᄳhĀ;vᱚᱛ怐»ऊūᱡᱧarow;椏aã̕Āayᱮᱳron;䄏;䐴ƀ;ao̲ᱼᲄĀgrʿᲁr;懊tseq;橷ƀglmᲑᲔᲘ耻°䂰ta;䎴ptyv;榱ĀirᲣᲨsht;楿;쀀𝔡arĀlrᲳᲵ»ࣜ»သʀaegsv᳂͸᳖᳜᳠mƀ;oș᳊᳔ndĀ;ș᳑uit;晦amma;䏝in;拲ƀ;io᳧᳨᳸䃷de脀÷;o᳧ᳰntimes;拇nø᳷cy;䑒cɯᴆ\0\0ᴊrn;挞op;挍ʀlptuwᴘᴝᴢᵉᵕlar;䀤f;쀀𝕕ʀ;emps̋ᴭᴷᴽᵂqĀ;d͒ᴳot;扑inus;戸lus;戔quare;抡blebarwedgåúnƀadhᄮᵝᵧownarrowóᲃarpoonĀlrᵲᵶefôᲴighôᲶŢᵿᶅkaro÷གɯᶊ\0\0ᶎrn;挟op;挌ƀcotᶘᶣᶦĀryᶝᶡ;쀀𝒹;䑕l;槶rok;䄑Ādrᶰᶴot;拱iĀ;fᶺ᠖斿Āah᷀᷃ròЩaòྦangle;榦Āci᷒ᷕy;䑟grarr;柿ऀDacdefglmnopqrstuxḁḉḙḸոḼṉṡṾấắẽỡἪἷὄ὎὚ĀDoḆᴴoôᲉĀcsḎḔute耻é䃩ter;橮ȀaioyḢḧḱḶron;䄛rĀ;cḭḮ扖耻ê䃪lon;払;䑍ot;䄗ĀDrṁṅot;扒;쀀𝔢ƀ;rsṐṑṗ檚ave耻è䃨Ā;dṜṝ檖ot;檘Ȁ;ilsṪṫṲṴ檙nters;揧;愓Ā;dṹṺ檕ot;檗ƀapsẅẉẗcr;䄓tyƀ;svẒẓẕ戅et»ẓpĀ1;ẝẤĳạả;怄;怅怃ĀgsẪẬ;䅋p;怂ĀgpẴẸon;䄙f;쀀𝕖ƀalsỄỎỒrĀ;sỊị拕l;槣us;橱iƀ;lvỚớở䎵on»ớ;䏵ȀcsuvỪỳἋἣĀioữḱrc»Ḯɩỹ\0\0ỻíՈantĀglἂἆtr»ṝess»Ṻƀaeiἒ἖Ἒls;䀽st;扟vĀ;DȵἠD;橸parsl;槥ĀDaἯἳot;打rr;楱ƀcdiἾὁỸr;愯oô͒ĀahὉὋ;䎷耻ð䃰Āmrὓὗl耻ë䃫o;悬ƀcipὡὤὧl;䀡sôծĀeoὬὴctatioîՙnentialåչৡᾒ\0ᾞ\0ᾡᾧ\0\0ῆῌ\0ΐ\0ῦῪ \0 ⁚llingdotseñṄy;䑄male;晀ƀilrᾭᾳ῁lig;耀ﬃɩᾹ\0\0᾽g;耀ﬀig;耀ﬄ;쀀𝔣lig;耀ﬁlig;쀀fjƀaltῙ῜ῡt;晭ig;耀ﬂns;斱of;䆒ǰ΅\0ῳf;쀀𝕗ĀakֿῷĀ;vῼ´拔;櫙artint;樍Āao‌⁕Ācs‑⁒α‚‰‸⁅⁈\0⁐β•‥‧‪‬\0‮耻½䂽;慓耻¼䂼;慕;慙;慛Ƴ‴\0‶;慔;慖ʴ‾⁁\0\0⁃耻¾䂾;慗;慜5;慘ƶ⁌\0⁎;慚;慝8;慞l;恄wn;挢cr;쀀𝒻ࢀEabcdefgijlnorstv₂₉₟₥₰₴⃰⃵⃺⃿℃ℒℸ̗ℾ⅒↞Ā;lٍ₇;檌ƀcmpₐₕ₝ute;䇵maĀ;dₜ᳚䎳;檆reve;䄟Āiy₪₮rc;䄝;䐳ot;䄡Ȁ;lqsؾق₽⃉ƀ;qsؾٌ⃄lanô٥Ȁ;cdl٥⃒⃥⃕c;檩otĀ;o⃜⃝檀Ā;l⃢⃣檂;檄Ā;e⃪⃭쀀⋛︀s;檔r;쀀𝔤Ā;gٳ؛mel;愷cy;䑓Ȁ;Eajٚℌℎℐ;檒;檥;檤ȀEaesℛℝ℩ℴ;扩pĀ;p℣ℤ檊rox»ℤĀ;q℮ℯ檈Ā;q℮ℛim;拧pf;쀀𝕘Āci⅃ⅆr;愊mƀ;el٫ⅎ⅐;檎;檐茀>;cdlqr׮ⅠⅪⅮⅳⅹĀciⅥⅧ;檧r;橺ot;拗Par;榕uest;橼ʀadelsↄⅪ←ٖ↛ǰ↉\0↎proø₞r;楸qĀlqؿ↖lesó₈ií٫Āen↣↭rtneqq;쀀≩︀Å↪ԀAabcefkosy⇄⇇⇱⇵⇺∘∝∯≨≽ròΠȀilmr⇐⇔⇗⇛rsðᒄf»․ilôکĀdr⇠⇤cy;䑊ƀ;cwࣴ⇫⇯ir;楈;憭ar;意irc;䄥ƀalr∁∎∓rtsĀ;u∉∊晥it»∊lip;怦con;抹r;쀀𝔥sĀew∣∩arow;椥arow;椦ʀamopr∺∾≃≞≣rr;懿tht;戻kĀlr≉≓eftarrow;憩ightarrow;憪f;쀀𝕙bar;怕ƀclt≯≴≸r;쀀𝒽asè⇴rok;䄧Ābp⊂⊇ull;恃hen»ᱛૡ⊣\0⊪\0⊸⋅⋎\0⋕⋳\0\0⋸⌢⍧⍢⍿\0⎆⎪⎴cute耻í䃭ƀ;iyݱ⊰⊵rc耻î䃮;䐸Ācx⊼⊿y;䐵cl耻¡䂡ĀfrΟ⋉;쀀𝔦rave耻ì䃬Ȁ;inoܾ⋝⋩⋮Āin⋢⋦nt;樌t;戭fin;槜ta;愩lig;䄳ƀaop⋾⌚⌝ƀcgt⌅⌈⌗r;䄫ƀelpܟ⌏⌓inåގarôܠh;䄱f;抷ed;䆵ʀ;cfotӴ⌬⌱⌽⍁are;愅inĀ;t⌸⌹戞ie;槝doô⌙ʀ;celpݗ⍌⍐⍛⍡al;抺Āgr⍕⍙eróᕣã⍍arhk;樗rod;樼Ȁcgpt⍯⍲⍶⍻y;䑑on;䄯f;쀀𝕚a;䎹uest耻¿䂿Āci⎊⎏r;쀀𝒾nʀ;EdsvӴ⎛⎝⎡ӳ;拹ot;拵Ā;v⎦⎧拴;拳Ā;iݷ⎮lde;䄩ǫ⎸\0⎼cy;䑖l耻ï䃯̀cfmosu⏌⏗⏜⏡⏧⏵Āiy⏑⏕rc;䄵;䐹r;쀀𝔧ath;䈷pf;쀀𝕛ǣ⏬\0⏱r;쀀𝒿rcy;䑘kcy;䑔Ѐacfghjos␋␖␢␧␭␱␵␻ppaĀ;v␓␔䎺;䏰Āey␛␠dil;䄷;䐺r;쀀𝔨reen;䄸cy;䑅cy;䑜pf;쀀𝕜cr;쀀𝓀஀ABEHabcdefghjlmnoprstuv⑰⒁⒆⒍⒑┎┽╚▀♎♞♥♹♽⚚⚲⛘❝❨➋⟀⠁⠒ƀart⑷⑺⑼rò৆òΕail;椛arr;椎Ā;gঔ⒋;檋ar;楢ॣ⒥\0⒪\0⒱\0\0\0\0\0⒵Ⓔ\0ⓆⓈⓍ\0⓹ute;䄺mptyv;榴raîࡌbda;䎻gƀ;dlࢎⓁⓃ;榑åࢎ;檅uo耻«䂫rЀ;bfhlpst࢙ⓞⓦⓩ⓫⓮⓱⓵Ā;f࢝ⓣs;椟s;椝ë≒p;憫l;椹im;楳l;憢ƀ;ae⓿─┄檫il;椙Ā;s┉┊檭;쀀⪭︀ƀabr┕┙┝rr;椌rk;杲Āak┢┬cĀek┨┪;䁻;䁛Āes┱┳;榋lĀdu┹┻;榏;榍Ȁaeuy╆╋╖╘ron;䄾Ādi═╔il;䄼ìࢰâ┩;䐻Ȁcqrs╣╦╭╽a;椶uoĀ;rนᝆĀdu╲╷har;楧shar;楋h;憲ʀ;fgqs▋▌উ◳◿扤tʀahlrt▘▤▷◂◨rrowĀ;t࢙□aé⓶arpoonĀdu▯▴own»њp»०eftarrows;懇ightƀahs◍◖◞rrowĀ;sࣴࢧarpoonó྘quigarro÷⇰hreetimes;拋ƀ;qs▋ও◺lanôবʀ;cdgsব☊☍☝☨c;檨otĀ;o☔☕橿Ā;r☚☛檁;檃Ā;e☢☥쀀⋚︀s;檓ʀadegs☳☹☽♉♋pproøⓆot;拖qĀgq♃♅ôউgtò⒌ôছiíলƀilr♕࣡♚sht;楼;쀀𝔩Ā;Eজ♣;檑š♩♶rĀdu▲♮Ā;l॥♳;楪lk;斄cy;䑙ʀ;achtੈ⚈⚋⚑⚖rò◁orneòᴈard;楫ri;旺Āio⚟⚤dot;䅀ustĀ;a⚬⚭掰che»⚭ȀEaes⚻⚽⛉⛔;扨pĀ;p⛃⛄檉rox»⛄Ā;q⛎⛏檇Ā;q⛎⚻im;拦Ѐabnoptwz⛩⛴⛷✚✯❁❇❐Ānr⛮⛱g;柬r;懽rëࣁgƀlmr⛿✍✔eftĀar০✇ightá৲apsto;柼ightá৽parrowĀlr✥✩efô⓭ight;憬ƀafl✶✹✽r;榅;쀀𝕝us;樭imes;樴š❋❏st;戗áፎƀ;ef❗❘᠀旊nge»❘arĀ;l❤❥䀨t;榓ʀachmt❳❶❼➅➇ròࢨorneòᶌarĀ;d྘➃;業;怎ri;抿̀achiqt➘➝ੀ➢➮➻quo;怹r;쀀𝓁mƀ;egল➪➬;檍;檏Ābu┪➳oĀ;rฟ➹;怚rok;䅂萀<;cdhilqrࠫ⟒☹⟜⟠⟥⟪⟰Āci⟗⟙;檦r;橹reå◲mes;拉arr;楶uest;橻ĀPi⟵⟹ar;榖ƀ;ef⠀भ᠛旃rĀdu⠇⠍shar;楊har;楦Āen⠗⠡rtneqq;쀀≨︀Å⠞܀Dacdefhilnopsu⡀⡅⢂⢎⢓⢠⢥⢨⣚⣢⣤ઃ⣳⤂Dot;戺Ȁclpr⡎⡒⡣⡽r耻¯䂯Āet⡗⡙;時Ā;e⡞⡟朠se»⡟Ā;sျ⡨toȀ;dluျ⡳⡷⡻owîҌefôएðᏑker;斮Āoy⢇⢌mma;権;䐼ash;怔asuredangle»ᘦr;쀀𝔪o;愧ƀcdn⢯⢴⣉ro耻µ䂵Ȁ;acdᑤ⢽⣀⣄sôᚧir;櫰ot肻·Ƶusƀ;bd⣒ᤃ⣓戒Ā;uᴼ⣘;横ţ⣞⣡p;櫛ò−ðઁĀdp⣩⣮els;抧f;쀀𝕞Āct⣸⣽r;쀀𝓂pos»ᖝƀ;lm⤉⤊⤍䎼timap;抸ఀGLRVabcdefghijlmoprstuvw⥂⥓⥾⦉⦘⧚⧩⨕⨚⩘⩝⪃⪕⪤⪨⬄⬇⭄⭿⮮ⰴⱧⱼ⳩Āgt⥇⥋;쀀⋙̸Ā;v⥐௏쀀≫⃒ƀelt⥚⥲⥶ftĀar⥡⥧rrow;懍ightarrow;懎;쀀⋘̸Ā;v⥻ే쀀≪⃒ightarrow;懏ĀDd⦎⦓ash;抯ash;抮ʀbcnpt⦣⦧⦬⦱⧌la»˞ute;䅄g;쀀∠⃒ʀ;Eiop඄⦼⧀⧅⧈;쀀⩰̸d;쀀≋̸s;䅉roø඄urĀ;a⧓⧔普lĀ;s⧓ସǳ⧟\0⧣p肻 ଷmpĀ;e௹ఀʀaeouy⧴⧾⨃⨐⨓ǰ⧹\0⧻;橃on;䅈dil;䅆ngĀ;dൾ⨊ot;쀀⩭̸p;橂;䐽ash;怓΀;Aadqsxஒ⨩⨭⨻⩁⩅⩐rr;懗rĀhr⨳⨶k;椤Ā;oᏲᏰot;쀀≐̸uiöୣĀei⩊⩎ar;椨í஘istĀ;s஠டr;쀀𝔫ȀEest௅⩦⩹⩼ƀ;qs஼⩭௡ƀ;qs஼௅⩴lanô௢ií௪Ā;rஶ⪁»ஷƀAap⪊⪍⪑rò⥱rr;憮ar;櫲ƀ;svྍ⪜ྌĀ;d⪡⪢拼;拺cy;䑚΀AEadest⪷⪺⪾⫂⫅⫶⫹rò⥦;쀀≦̸rr;憚r;急Ȁ;fqs఻⫎⫣⫯tĀar⫔⫙rro÷⫁ightarro÷⪐ƀ;qs఻⪺⫪lanôౕĀ;sౕ⫴»శiíౝĀ;rవ⫾iĀ;eచథiäඐĀpt⬌⬑f;쀀𝕟膀¬;in⬙⬚⬶䂬nȀ;Edvஉ⬤⬨⬮;쀀⋹̸ot;쀀⋵̸ǡஉ⬳⬵;拷;拶iĀ;vಸ⬼ǡಸ⭁⭃;拾;拽ƀaor⭋⭣⭩rȀ;ast୻⭕⭚⭟lleì୻l;쀀⫽⃥;쀀∂̸lint;樔ƀ;ceಒ⭰⭳uåಥĀ;cಘ⭸Ā;eಒ⭽ñಘȀAait⮈⮋⮝⮧rò⦈rrƀ;cw⮔⮕⮙憛;쀀⤳̸;쀀↝̸ghtarrow»⮕riĀ;eೋೖ΀chimpqu⮽⯍⯙⬄୸⯤⯯Ȁ;cerല⯆ഷ⯉uå൅;쀀𝓃ortɭ⬅\0\0⯖ará⭖mĀ;e൮⯟Ā;q൴൳suĀbp⯫⯭å೸åഋƀbcp⯶ⰑⰙȀ;Ees⯿ⰀഢⰄ抄;쀀⫅̸etĀ;eഛⰋqĀ;qണⰀcĀ;eലⰗñസȀ;EesⰢⰣൟⰧ抅;쀀⫆̸etĀ;e൘ⰮqĀ;qൠⰣȀgilrⰽⰿⱅⱇìௗlde耻ñ䃱çృiangleĀlrⱒⱜeftĀ;eచⱚñదightĀ;eೋⱥñ೗Ā;mⱬⱭ䎽ƀ;esⱴⱵⱹ䀣ro;愖p;怇ҀDHadgilrsⲏⲔⲙⲞⲣⲰⲶⳓⳣash;抭arr;椄p;쀀≍⃒ash;抬ĀetⲨⲬ;쀀≥⃒;쀀>⃒nfin;槞ƀAetⲽⳁⳅrr;椂;쀀≤⃒Ā;rⳊⳍ쀀<⃒ie;쀀⊴⃒ĀAtⳘⳜrr;椃rie;쀀⊵⃒im;쀀∼⃒ƀAan⳰⳴ⴂrr;懖rĀhr⳺⳽k;椣Ā;oᏧᏥear;椧ቓ᪕\0\0\0\0\0\0\0\0\0\0\0\0\0ⴭ\0ⴸⵈⵠⵥ⵲ⶄᬇ\0\0ⶍⶫ\0ⷈⷎ\0ⷜ⸙⸫⸾⹃Ācsⴱ᪗ute耻ó䃳ĀiyⴼⵅrĀ;c᪞ⵂ耻ô䃴;䐾ʀabios᪠ⵒⵗǈⵚlac;䅑v;樸old;榼lig;䅓Ācr⵩⵭ir;榿;쀀𝔬ͯ⵹\0\0⵼\0ⶂn;䋛ave耻ò䃲;槁Ābmⶈ෴ar;榵Ȁacitⶕ⶘ⶥⶨrò᪀Āir⶝ⶠr;榾oss;榻nå๒;槀ƀaeiⶱⶵⶹcr;䅍ga;䏉ƀcdnⷀⷅǍron;䎿;榶pf;쀀𝕠ƀaelⷔ⷗ǒr;榷rp;榹΀;adiosvⷪⷫⷮ⸈⸍⸐⸖戨rò᪆Ȁ;efmⷷⷸ⸂⸅橝rĀ;oⷾⷿ愴f»ⷿ耻ª䂪耻º䂺gof;抶r;橖lope;橗;橛ƀclo⸟⸡⸧ò⸁ash耻ø䃸l;折iŬⸯ⸴de耻õ䃵esĀ;aǛ⸺s;樶ml耻ö䃶bar;挽ૡ⹞\0⹽\0⺀⺝\0⺢⺹\0\0⻋ຜ\0⼓\0\0⼫⾼\0⿈rȀ;astЃ⹧⹲຅脀¶;l⹭⹮䂶leìЃɩ⹸\0\0⹻m;櫳;櫽y;䐿rʀcimpt⺋⺏⺓ᡥ⺗nt;䀥od;䀮il;怰enk;怱r;쀀𝔭ƀimo⺨⺰⺴Ā;v⺭⺮䏆;䏕maô੶ne;明ƀ;tv⺿⻀⻈䏀chfork»´;䏖Āau⻏⻟nĀck⻕⻝kĀ;h⇴⻛;愎ö⇴sҀ;abcdemst⻳⻴ᤈ⻹⻽⼄⼆⼊⼎䀫cir;樣ir;樢Āouᵀ⼂;樥;橲n肻±ຝim;樦wo;樧ƀipu⼙⼠⼥ntint;樕f;쀀𝕡nd耻£䂣Ԁ;Eaceinosu່⼿⽁⽄⽇⾁⾉⾒⽾⾶;檳p;檷uå໙Ā;c໎⽌̀;acens່⽙⽟⽦⽨⽾pproø⽃urlyeñ໙ñ໎ƀaes⽯⽶⽺pprox;檹qq;檵im;拨iíໟmeĀ;s⾈ຮ怲ƀEas⽸⾐⽺ð⽵ƀdfp໬⾙⾯ƀals⾠⾥⾪lar;挮ine;挒urf;挓Ā;t໻⾴ï໻rel;抰Āci⿀⿅r;쀀𝓅;䏈ncsp;怈̀fiopsu⿚⋢⿟⿥⿫⿱r;쀀𝔮pf;쀀𝕢rime;恗cr;쀀𝓆ƀaeo⿸〉〓tĀei⿾々rnionóڰnt;樖stĀ;e【】䀿ñἙô༔઀ABHabcdefhilmnoprstux぀けさすムㄎㄫㅇㅢㅲㆎ㈆㈕㈤㈩㉘㉮㉲㊐㊰㊷ƀartぇおがròႳòϝail;検aròᱥar;楤΀cdenqrtとふへみわゔヌĀeuねぱ;쀀∽̱te;䅕iãᅮmptyv;榳gȀ;del࿑らるろ;榒;榥å࿑uo耻»䂻rր;abcfhlpstw࿜ガクシスゼゾダッデナp;極Ā;f࿠ゴs;椠;椳s;椞ë≝ð✮l;楅im;楴l;憣;憝Āaiパフil;椚oĀ;nホボ戶aló༞ƀabrョリヮrò៥rk;杳ĀakンヽcĀekヹ・;䁽;䁝Āes㄂㄄;榌lĀduㄊㄌ;榎;榐Ȁaeuyㄗㄜㄧㄩron;䅙Ādiㄡㄥil;䅗ì࿲âヺ;䑀Ȁclqsㄴㄷㄽㅄa;椷dhar;楩uoĀ;rȎȍh;憳ƀacgㅎㅟངlȀ;ipsླྀㅘㅛႜnåႻarôྩt;断ƀilrㅩဣㅮsht;楽;쀀𝔯ĀaoㅷㆆrĀduㅽㅿ»ѻĀ;l႑ㆄ;楬Ā;vㆋㆌ䏁;䏱ƀgns㆕ㇹㇼht̀ahlrstㆤㆰ㇂㇘㇤㇮rrowĀ;t࿜ㆭaéトarpoonĀduㆻㆿowîㅾp»႒eftĀah㇊㇐rrowó࿪arpoonóՑightarrows;應quigarro÷ニhreetimes;拌g;䋚ingdotseñἲƀahm㈍㈐㈓rò࿪aòՑ;怏oustĀ;a㈞㈟掱che»㈟mid;櫮Ȁabpt㈲㈽㉀㉒Ānr㈷㈺g;柭r;懾rëဃƀafl㉇㉊㉎r;榆;쀀𝕣us;樮imes;樵Āap㉝㉧rĀ;g㉣㉤䀩t;榔olint;樒arò㇣Ȁachq㉻㊀Ⴜ㊅quo;怺r;쀀𝓇Ābu・㊊oĀ;rȔȓƀhir㊗㊛㊠reåㇸmes;拊iȀ;efl㊪ၙᠡ㊫方tri;槎luhar;楨;愞ൡ㋕㋛㋟㌬㌸㍱\0㍺㎤\0\0㏬㏰\0㐨㑈㑚㒭㒱㓊㓱\0㘖\0\0㘳cute;䅛quï➺Ԁ;Eaceinpsyᇭ㋳㋵㋿㌂㌋㌏㌟㌦㌩;檴ǰ㋺\0㋼;檸on;䅡uåᇾĀ;dᇳ㌇il;䅟rc;䅝ƀEas㌖㌘㌛;檶p;檺im;择olint;樓iíሄ;䑁otƀ;be㌴ᵇ㌵担;橦΀Aacmstx㍆㍊㍗㍛㍞㍣㍭rr;懘rĀhr㍐㍒ë∨Ā;oਸ਼਴t耻§䂧i;䀻war;椩mĀin㍩ðnuóñt;朶rĀ;o㍶⁕쀀𝔰Ȁacoy㎂㎆㎑㎠rp;景Āhy㎋㎏cy;䑉;䑈rtɭ㎙\0\0㎜iäᑤaraì⹯耻­䂭Āgm㎨㎴maƀ;fv㎱㎲㎲䏃;䏂Ѐ;deglnprካ㏅㏉㏎㏖㏞㏡㏦ot;橪Ā;q኱ኰĀ;E㏓㏔檞;檠Ā;E㏛㏜檝;檟e;扆lus;樤arr;楲aròᄽȀaeit㏸㐈㐏㐗Āls㏽㐄lsetmé㍪hp;樳parsl;槤Ādlᑣ㐔e;挣Ā;e㐜㐝檪Ā;s㐢㐣檬;쀀⪬︀ƀflp㐮㐳㑂tcy;䑌Ā;b㐸㐹䀯Ā;a㐾㐿槄r;挿f;쀀𝕤aĀdr㑍ЂesĀ;u㑔㑕晠it»㑕ƀcsu㑠㑹㒟Āau㑥㑯pĀ;sᆈ㑫;쀀⊓︀pĀ;sᆴ㑵;쀀⊔︀uĀbp㑿㒏ƀ;esᆗᆜ㒆etĀ;eᆗ㒍ñᆝƀ;esᆨᆭ㒖etĀ;eᆨ㒝ñᆮƀ;afᅻ㒦ְrť㒫ֱ»ᅼaròᅈȀcemt㒹㒾㓂㓅r;쀀𝓈tmîñiì㐕aræᆾĀar㓎㓕rĀ;f㓔ឿ昆Āan㓚㓭ightĀep㓣㓪psiloîỠhé⺯s»⡒ʀbcmnp㓻㕞ሉ㖋㖎Ҁ;Edemnprs㔎㔏㔑㔕㔞㔣㔬㔱㔶抂;櫅ot;檽Ā;dᇚ㔚ot;櫃ult;櫁ĀEe㔨㔪;櫋;把lus;檿arr;楹ƀeiu㔽㕒㕕tƀ;en㔎㕅㕋qĀ;qᇚ㔏eqĀ;q㔫㔨m;櫇Ābp㕚㕜;櫕;櫓c̀;acensᇭ㕬㕲㕹㕻㌦pproø㋺urlyeñᇾñᇳƀaes㖂㖈㌛pproø㌚qñ㌗g;晪ڀ123;Edehlmnps㖩㖬㖯ሜ㖲㖴㗀㗉㗕㗚㗟㗨㗭耻¹䂹耻²䂲耻³䂳;櫆Āos㖹㖼t;檾ub;櫘Ā;dሢ㗅ot;櫄sĀou㗏㗒l;柉b;櫗arr;楻ult;櫂ĀEe㗤㗦;櫌;抋lus;櫀ƀeiu㗴㘉㘌tƀ;enሜ㗼㘂qĀ;qሢ㖲eqĀ;q㗧㗤m;櫈Ābp㘑㘓;櫔;櫖ƀAan㘜㘠㘭rr;懙rĀhr㘦㘨ë∮Ā;oਫ਩war;椪lig耻ß䃟௡㙑㙝㙠ዎ㙳㙹\0㙾㛂\0\0\0\0\0㛛㜃\0㜉㝬\0\0\0㞇ɲ㙖\0\0㙛get;挖;䏄rë๟ƀaey㙦㙫㙰ron;䅥dil;䅣;䑂lrec;挕r;쀀𝔱Ȁeiko㚆㚝㚵㚼ǲ㚋\0㚑eĀ4fኄኁaƀ;sv㚘㚙㚛䎸ym;䏑Ācn㚢㚲kĀas㚨㚮pproø዁im»ኬsðኞĀas㚺㚮ð዁rn耻þ䃾Ǭ̟㛆⋧es膀×;bd㛏㛐㛘䃗Ā;aᤏ㛕r;樱;樰ƀeps㛡㛣㜀á⩍Ȁ;bcf҆㛬㛰㛴ot;挶ir;櫱Ā;o㛹㛼쀀𝕥rk;櫚á㍢rime;怴ƀaip㜏㜒㝤dåቈ΀adempst㜡㝍㝀㝑㝗㝜㝟ngleʀ;dlqr㜰㜱㜶㝀㝂斵own»ᶻeftĀ;e⠀㜾ñम;扜ightĀ;e㊪㝋ñၚot;旬inus;樺lus;樹b;槍ime;樻ezium;揢ƀcht㝲㝽㞁Āry㝷㝻;쀀𝓉;䑆cy;䑛rok;䅧Āio㞋㞎xô᝷headĀlr㞗㞠eftarro÷ࡏightarrow»ཝऀAHabcdfghlmoprstuw㟐㟓㟗㟤㟰㟼㠎㠜㠣㠴㡑㡝㡫㢩㣌㣒㣪㣶ròϭar;楣Ācr㟜㟢ute耻ú䃺òᅐrǣ㟪\0㟭y;䑞ve;䅭Āiy㟵㟺rc耻û䃻;䑃ƀabh㠃㠆㠋ròᎭlac;䅱aòᏃĀir㠓㠘sht;楾;쀀𝔲rave耻ù䃹š㠧㠱rĀlr㠬㠮»ॗ»ႃlk;斀Āct㠹㡍ɯ㠿\0\0㡊rnĀ;e㡅㡆挜r»㡆op;挏ri;旸Āal㡖㡚cr;䅫肻¨͉Āgp㡢㡦on;䅳f;쀀𝕦̀adhlsuᅋ㡸㡽፲㢑㢠ownáᎳarpoonĀlr㢈㢌efô㠭ighô㠯iƀ;hl㢙㢚㢜䏅»ᏺon»㢚parrows;懈ƀcit㢰㣄㣈ɯ㢶\0\0㣁rnĀ;e㢼㢽挝r»㢽op;挎ng;䅯ri;旹cr;쀀𝓊ƀdir㣙㣝㣢ot;拰lde;䅩iĀ;f㜰㣨»᠓Āam㣯㣲rò㢨l耻ü䃼angle;榧ހABDacdeflnoprsz㤜㤟㤩㤭㦵㦸㦽㧟㧤㧨㧳㧹㧽㨁㨠ròϷarĀ;v㤦㤧櫨;櫩asèϡĀnr㤲㤷grt;榜΀eknprst㓣㥆㥋㥒㥝㥤㦖appá␕othinçẖƀhir㓫⻈㥙opô⾵Ā;hᎷ㥢ïㆍĀiu㥩㥭gmá㎳Ābp㥲㦄setneqĀ;q㥽㦀쀀⊊︀;쀀⫋︀setneqĀ;q㦏㦒쀀⊋︀;쀀⫌︀Āhr㦛㦟etá㚜iangleĀlr㦪㦯eft»थight»ၑy;䐲ash»ံƀelr㧄㧒㧗ƀ;beⷪ㧋㧏ar;抻q;扚lip;拮Ābt㧜ᑨaòᑩr;쀀𝔳tré㦮suĀbp㧯㧱»ജ»൙pf;쀀𝕧roð໻tré㦴Ācu㨆㨋r;쀀𝓋Ābp㨐㨘nĀEe㦀㨖»㥾nĀEe㦒㨞»㦐igzag;榚΀cefoprs㨶㨻㩖㩛㩔㩡㩪irc;䅵Ādi㩀㩑Ābg㩅㩉ar;機eĀ;qᗺ㩏;扙erp;愘r;쀀𝔴pf;쀀𝕨Ā;eᑹ㩦atèᑹcr;쀀𝓌ૣណ㪇\0㪋\0㪐㪛\0\0㪝㪨㪫㪯\0\0㫃㫎\0㫘ៜ៟tré៑r;쀀𝔵ĀAa㪔㪗ròσrò৶;䎾ĀAa㪡㪤ròθrò৫að✓is;拻ƀdptឤ㪵㪾Āfl㪺ឩ;쀀𝕩imåឲĀAa㫇㫊ròώròਁĀcq㫒ីr;쀀𝓍Āpt៖㫜ré។Ѐacefiosu㫰㫽㬈㬌㬑㬕㬛㬡cĀuy㫶㫻te耻ý䃽;䑏Āiy㬂㬆rc;䅷;䑋n耻¥䂥r;쀀𝔶cy;䑗pf;쀀𝕪cr;쀀𝓎Ācm㬦㬩y;䑎l耻ÿ䃿Ԁacdefhiosw㭂㭈㭔㭘㭤㭩㭭㭴㭺㮀cute;䅺Āay㭍㭒ron;䅾;䐷ot;䅼Āet㭝㭡træᕟa;䎶r;쀀𝔷cy;䐶grarr;懝pf;쀀𝕫cr;쀀𝓏Ājn㮅㮇;怍j;怌'.split("").map((c2) => c2.charCodeAt(0))
);
const xmlDecodeTree = new Uint16Array(
  // prettier-ignore
  "Ȁaglq	\x1Bɭ\0\0p;䀦os;䀧t;䀾t;䀼uot;䀢".split("").map((c2) => c2.charCodeAt(0))
);
var _a;
const decodeMap = /* @__PURE__ */ new Map([
  [0, 65533],
  // C1 Unicode control character reference replacements
  [128, 8364],
  [130, 8218],
  [131, 402],
  [132, 8222],
  [133, 8230],
  [134, 8224],
  [135, 8225],
  [136, 710],
  [137, 8240],
  [138, 352],
  [139, 8249],
  [140, 338],
  [142, 381],
  [145, 8216],
  [146, 8217],
  [147, 8220],
  [148, 8221],
  [149, 8226],
  [150, 8211],
  [151, 8212],
  [152, 732],
  [153, 8482],
  [154, 353],
  [155, 8250],
  [156, 339],
  [158, 382],
  [159, 376]
]);
const fromCodePoint$1 = (
  // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, node/no-unsupported-features/es-builtins
  (_a = String.fromCodePoint) !== null && _a !== void 0 ? _a : function(codePoint) {
    let output = "";
    if (codePoint > 65535) {
      codePoint -= 65536;
      output += String.fromCharCode(codePoint >>> 10 & 1023 | 55296);
      codePoint = 56320 | codePoint & 1023;
    }
    output += String.fromCharCode(codePoint);
    return output;
  }
);
function replaceCodePoint(codePoint) {
  var _a2;
  if (codePoint >= 55296 && codePoint <= 57343 || codePoint > 1114111) {
    return 65533;
  }
  return (_a2 = decodeMap.get(codePoint)) !== null && _a2 !== void 0 ? _a2 : codePoint;
}
__name(replaceCodePoint, "replaceCodePoint");
function decodeCodePoint(codePoint) {
  return fromCodePoint$1(replaceCodePoint(codePoint));
}
__name(decodeCodePoint, "decodeCodePoint");
var CharCodes;
(function(CharCodes2) {
  CharCodes2[CharCodes2["NUM"] = 35] = "NUM";
  CharCodes2[CharCodes2["SEMI"] = 59] = "SEMI";
  CharCodes2[CharCodes2["EQUALS"] = 61] = "EQUALS";
  CharCodes2[CharCodes2["ZERO"] = 48] = "ZERO";
  CharCodes2[CharCodes2["NINE"] = 57] = "NINE";
  CharCodes2[CharCodes2["LOWER_A"] = 97] = "LOWER_A";
  CharCodes2[CharCodes2["LOWER_F"] = 102] = "LOWER_F";
  CharCodes2[CharCodes2["LOWER_X"] = 120] = "LOWER_X";
  CharCodes2[CharCodes2["LOWER_Z"] = 122] = "LOWER_Z";
  CharCodes2[CharCodes2["UPPER_A"] = 65] = "UPPER_A";
  CharCodes2[CharCodes2["UPPER_F"] = 70] = "UPPER_F";
  CharCodes2[CharCodes2["UPPER_Z"] = 90] = "UPPER_Z";
})(CharCodes || (CharCodes = {}));
const TO_LOWER_BIT = 32;
var BinTrieFlags;
(function(BinTrieFlags2) {
  BinTrieFlags2[BinTrieFlags2["VALUE_LENGTH"] = 49152] = "VALUE_LENGTH";
  BinTrieFlags2[BinTrieFlags2["BRANCH_LENGTH"] = 16256] = "BRANCH_LENGTH";
  BinTrieFlags2[BinTrieFlags2["JUMP_TABLE"] = 127] = "JUMP_TABLE";
})(BinTrieFlags || (BinTrieFlags = {}));
function isNumber$1(code2) {
  return code2 >= CharCodes.ZERO && code2 <= CharCodes.NINE;
}
__name(isNumber$1, "isNumber$1");
function isHexadecimalCharacter(code2) {
  return code2 >= CharCodes.UPPER_A && code2 <= CharCodes.UPPER_F || code2 >= CharCodes.LOWER_A && code2 <= CharCodes.LOWER_F;
}
__name(isHexadecimalCharacter, "isHexadecimalCharacter");
function isAsciiAlphaNumeric(code2) {
  return code2 >= CharCodes.UPPER_A && code2 <= CharCodes.UPPER_Z || code2 >= CharCodes.LOWER_A && code2 <= CharCodes.LOWER_Z || isNumber$1(code2);
}
__name(isAsciiAlphaNumeric, "isAsciiAlphaNumeric");
function isEntityInAttributeInvalidEnd(code2) {
  return code2 === CharCodes.EQUALS || isAsciiAlphaNumeric(code2);
}
__name(isEntityInAttributeInvalidEnd, "isEntityInAttributeInvalidEnd");
var EntityDecoderState;
(function(EntityDecoderState2) {
  EntityDecoderState2[EntityDecoderState2["EntityStart"] = 0] = "EntityStart";
  EntityDecoderState2[EntityDecoderState2["NumericStart"] = 1] = "NumericStart";
  EntityDecoderState2[EntityDecoderState2["NumericDecimal"] = 2] = "NumericDecimal";
  EntityDecoderState2[EntityDecoderState2["NumericHex"] = 3] = "NumericHex";
  EntityDecoderState2[EntityDecoderState2["NamedEntity"] = 4] = "NamedEntity";
})(EntityDecoderState || (EntityDecoderState = {}));
var DecodingMode;
(function(DecodingMode2) {
  DecodingMode2[DecodingMode2["Legacy"] = 0] = "Legacy";
  DecodingMode2[DecodingMode2["Strict"] = 1] = "Strict";
  DecodingMode2[DecodingMode2["Attribute"] = 2] = "Attribute";
})(DecodingMode || (DecodingMode = {}));
class EntityDecoder {
  static {
    __name(this, "EntityDecoder");
  }
  constructor(decodeTree, emitCodePoint, errors2) {
    this.decodeTree = decodeTree;
    this.emitCodePoint = emitCodePoint;
    this.errors = errors2;
    this.state = EntityDecoderState.EntityStart;
    this.consumed = 1;
    this.result = 0;
    this.treeIndex = 0;
    this.excess = 1;
    this.decodeMode = DecodingMode.Strict;
  }
  /** Resets the instance to make it reusable. */
  startEntity(decodeMode) {
    this.decodeMode = decodeMode;
    this.state = EntityDecoderState.EntityStart;
    this.result = 0;
    this.treeIndex = 0;
    this.excess = 1;
    this.consumed = 1;
  }
  /**
   * Write an entity to the decoder. This can be called multiple times with partial entities.
   * If the entity is incomplete, the decoder will return -1.
   *
   * Mirrors the implementation of `getDecoder`, but with the ability to stop decoding if the
   * entity is incomplete, and resume when the next string is written.
   *
   * @param string The string containing the entity (or a continuation of the entity).
   * @param offset The offset at which the entity begins. Should be 0 if this is not the first call.
   * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
   */
  write(str, offset) {
    switch (this.state) {
      case EntityDecoderState.EntityStart: {
        if (str.charCodeAt(offset) === CharCodes.NUM) {
          this.state = EntityDecoderState.NumericStart;
          this.consumed += 1;
          return this.stateNumericStart(str, offset + 1);
        }
        this.state = EntityDecoderState.NamedEntity;
        return this.stateNamedEntity(str, offset);
      }
      case EntityDecoderState.NumericStart: {
        return this.stateNumericStart(str, offset);
      }
      case EntityDecoderState.NumericDecimal: {
        return this.stateNumericDecimal(str, offset);
      }
      case EntityDecoderState.NumericHex: {
        return this.stateNumericHex(str, offset);
      }
      case EntityDecoderState.NamedEntity: {
        return this.stateNamedEntity(str, offset);
      }
    }
  }
  /**
   * Switches between the numeric decimal and hexadecimal states.
   *
   * Equivalent to the `Numeric character reference state` in the HTML spec.
   *
   * @param str The string containing the entity (or a continuation of the entity).
   * @param offset The current offset.
   * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
   */
  stateNumericStart(str, offset) {
    if (offset >= str.length) {
      return -1;
    }
    if ((str.charCodeAt(offset) | TO_LOWER_BIT) === CharCodes.LOWER_X) {
      this.state = EntityDecoderState.NumericHex;
      this.consumed += 1;
      return this.stateNumericHex(str, offset + 1);
    }
    this.state = EntityDecoderState.NumericDecimal;
    return this.stateNumericDecimal(str, offset);
  }
  addToNumericResult(str, start2, end, base2) {
    if (start2 !== end) {
      const digitCount = end - start2;
      this.result = this.result * Math.pow(base2, digitCount) + parseInt(str.substr(start2, digitCount), base2);
      this.consumed += digitCount;
    }
  }
  /**
   * Parses a hexadecimal numeric entity.
   *
   * Equivalent to the `Hexademical character reference state` in the HTML spec.
   *
   * @param str The string containing the entity (or a continuation of the entity).
   * @param offset The current offset.
   * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
   */
  stateNumericHex(str, offset) {
    const startIdx = offset;
    while (offset < str.length) {
      const char = str.charCodeAt(offset);
      if (isNumber$1(char) || isHexadecimalCharacter(char)) {
        offset += 1;
      } else {
        this.addToNumericResult(str, startIdx, offset, 16);
        return this.emitNumericEntity(char, 3);
      }
    }
    this.addToNumericResult(str, startIdx, offset, 16);
    return -1;
  }
  /**
   * Parses a decimal numeric entity.
   *
   * Equivalent to the `Decimal character reference state` in the HTML spec.
   *
   * @param str The string containing the entity (or a continuation of the entity).
   * @param offset The current offset.
   * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
   */
  stateNumericDecimal(str, offset) {
    const startIdx = offset;
    while (offset < str.length) {
      const char = str.charCodeAt(offset);
      if (isNumber$1(char)) {
        offset += 1;
      } else {
        this.addToNumericResult(str, startIdx, offset, 10);
        return this.emitNumericEntity(char, 2);
      }
    }
    this.addToNumericResult(str, startIdx, offset, 10);
    return -1;
  }
  /**
   * Validate and emit a numeric entity.
   *
   * Implements the logic from the `Hexademical character reference start
   * state` and `Numeric character reference end state` in the HTML spec.
   *
   * @param lastCp The last code point of the entity. Used to see if the
   *               entity was terminated with a semicolon.
   * @param expectedLength The minimum number of characters that should be
   *                       consumed. Used to validate that at least one digit
   *                       was consumed.
   * @returns The number of characters that were consumed.
   */
  emitNumericEntity(lastCp, expectedLength) {
    var _a2;
    if (this.consumed <= expectedLength) {
      (_a2 = this.errors) === null || _a2 === void 0 ? void 0 : _a2.absenceOfDigitsInNumericCharacterReference(this.consumed);
      return 0;
    }
    if (lastCp === CharCodes.SEMI) {
      this.consumed += 1;
    } else if (this.decodeMode === DecodingMode.Strict) {
      return 0;
    }
    this.emitCodePoint(replaceCodePoint(this.result), this.consumed);
    if (this.errors) {
      if (lastCp !== CharCodes.SEMI) {
        this.errors.missingSemicolonAfterCharacterReference();
      }
      this.errors.validateNumericCharacterReference(this.result);
    }
    return this.consumed;
  }
  /**
   * Parses a named entity.
   *
   * Equivalent to the `Named character reference state` in the HTML spec.
   *
   * @param str The string containing the entity (or a continuation of the entity).
   * @param offset The current offset.
   * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
   */
  stateNamedEntity(str, offset) {
    const { decodeTree } = this;
    let current = decodeTree[this.treeIndex];
    let valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14;
    for (; offset < str.length; offset++, this.excess++) {
      const char = str.charCodeAt(offset);
      this.treeIndex = determineBranch(decodeTree, current, this.treeIndex + Math.max(1, valueLength), char);
      if (this.treeIndex < 0) {
        return this.result === 0 || // If we are parsing an attribute
        this.decodeMode === DecodingMode.Attribute && // We shouldn't have consumed any characters after the entity,
        (valueLength === 0 || // And there should be no invalid characters.
        isEntityInAttributeInvalidEnd(char)) ? 0 : this.emitNotTerminatedNamedEntity();
      }
      current = decodeTree[this.treeIndex];
      valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14;
      if (valueLength !== 0) {
        if (char === CharCodes.SEMI) {
          return this.emitNamedEntityData(this.treeIndex, valueLength, this.consumed + this.excess);
        }
        if (this.decodeMode !== DecodingMode.Strict) {
          this.result = this.treeIndex;
          this.consumed += this.excess;
          this.excess = 0;
        }
      }
    }
    return -1;
  }
  /**
   * Emit a named entity that was not terminated with a semicolon.
   *
   * @returns The number of characters consumed.
   */
  emitNotTerminatedNamedEntity() {
    var _a2;
    const { result, decodeTree } = this;
    const valueLength = (decodeTree[result] & BinTrieFlags.VALUE_LENGTH) >> 14;
    this.emitNamedEntityData(result, valueLength, this.consumed);
    (_a2 = this.errors) === null || _a2 === void 0 ? void 0 : _a2.missingSemicolonAfterCharacterReference();
    return this.consumed;
  }
  /**
   * Emit a named entity.
   *
   * @param result The index of the entity in the decode tree.
   * @param valueLength The number of bytes in the entity.
   * @param consumed The number of characters consumed.
   *
   * @returns The number of characters consumed.
   */
  emitNamedEntityData(result, valueLength, consumed) {
    const { decodeTree } = this;
    this.emitCodePoint(valueLength === 1 ? decodeTree[result] & ~BinTrieFlags.VALUE_LENGTH : decodeTree[result + 1], consumed);
    if (valueLength === 3) {
      this.emitCodePoint(decodeTree[result + 2], consumed);
    }
    return consumed;
  }
  /**
   * Signal to the parser that the end of the input was reached.
   *
   * Remaining data will be emitted and relevant errors will be produced.
   *
   * @returns The number of characters consumed.
   */
  end() {
    var _a2;
    switch (this.state) {
      case EntityDecoderState.NamedEntity: {
        return this.result !== 0 && (this.decodeMode !== DecodingMode.Attribute || this.result === this.treeIndex) ? this.emitNotTerminatedNamedEntity() : 0;
      }
      case EntityDecoderState.NumericDecimal: {
        return this.emitNumericEntity(0, 2);
      }
      case EntityDecoderState.NumericHex: {
        return this.emitNumericEntity(0, 3);
      }
      case EntityDecoderState.NumericStart: {
        (_a2 = this.errors) === null || _a2 === void 0 ? void 0 : _a2.absenceOfDigitsInNumericCharacterReference(this.consumed);
        return 0;
      }
      case EntityDecoderState.EntityStart: {
        return 0;
      }
    }
  }
}
function getDecoder(decodeTree) {
  let ret = "";
  const decoder = new EntityDecoder(decodeTree, (str) => ret += fromCodePoint$1(str));
  return /* @__PURE__ */ __name(function decodeWithTrie(str, decodeMode) {
    let lastIndex = 0;
    let offset = 0;
    while ((offset = str.indexOf("&", offset)) >= 0) {
      ret += str.slice(lastIndex, offset);
      decoder.startEntity(decodeMode);
      const len = decoder.write(
        str,
        // Skip the "&"
        offset + 1
      );
      if (len < 0) {
        lastIndex = offset + decoder.end();
        break;
      }
      lastIndex = offset + len;
      offset = len === 0 ? lastIndex + 1 : lastIndex;
    }
    const result = ret + str.slice(lastIndex);
    ret = "";
    return result;
  }, "decodeWithTrie");
}
__name(getDecoder, "getDecoder");
function determineBranch(decodeTree, current, nodeIdx, char) {
  const branchCount = (current & BinTrieFlags.BRANCH_LENGTH) >> 7;
  const jumpOffset = current & BinTrieFlags.JUMP_TABLE;
  if (branchCount === 0) {
    return jumpOffset !== 0 && char === jumpOffset ? nodeIdx : -1;
  }
  if (jumpOffset) {
    const value = char - jumpOffset;
    return value < 0 || value >= branchCount ? -1 : decodeTree[nodeIdx + value] - 1;
  }
  let lo = nodeIdx;
  let hi = lo + branchCount - 1;
  while (lo <= hi) {
    const mid = lo + hi >>> 1;
    const midVal = decodeTree[mid];
    if (midVal < char) {
      lo = mid + 1;
    } else if (midVal > char) {
      hi = mid - 1;
    } else {
      return decodeTree[mid + branchCount];
    }
  }
  return -1;
}
__name(determineBranch, "determineBranch");
const htmlDecoder = getDecoder(htmlDecodeTree);
const xmlDecoder = getDecoder(xmlDecodeTree);
function decodeHTML(str, mode = DecodingMode.Legacy) {
  return htmlDecoder(str, mode);
}
__name(decodeHTML, "decodeHTML");
function decodeHTMLAttribute(str) {
  return htmlDecoder(str, DecodingMode.Attribute);
}
__name(decodeHTMLAttribute, "decodeHTMLAttribute");
function decodeHTMLStrict(str) {
  return htmlDecoder(str, DecodingMode.Strict);
}
__name(decodeHTMLStrict, "decodeHTMLStrict");
function decodeXML(str) {
  return xmlDecoder(str, DecodingMode.Strict);
}
__name(decodeXML, "decodeXML");
function restoreDiff(arr) {
  for (let i2 = 1; i2 < arr.length; i2++) {
    arr[i2][0] += arr[i2 - 1][0] + 1;
  }
  return arr;
}
__name(restoreDiff, "restoreDiff");
const htmlTrie = new Map(/* @__PURE__ */ restoreDiff([[9, "&Tab;"], [0, "&NewLine;"], [22, "&excl;"], [0, "&quot;"], [0, "&num;"], [0, "&dollar;"], [0, "&percnt;"], [0, "&amp;"], [0, "&apos;"], [0, "&lpar;"], [0, "&rpar;"], [0, "&ast;"], [0, "&plus;"], [0, "&comma;"], [1, "&period;"], [0, "&sol;"], [10, "&colon;"], [0, "&semi;"], [0, { v: "&lt;", n: 8402, o: "&nvlt;" }], [0, { v: "&equals;", n: 8421, o: "&bne;" }], [0, { v: "&gt;", n: 8402, o: "&nvgt;" }], [0, "&quest;"], [0, "&commat;"], [26, "&lbrack;"], [0, "&bsol;"], [0, "&rbrack;"], [0, "&Hat;"], [0, "&lowbar;"], [0, "&DiacriticalGrave;"], [5, { n: 106, o: "&fjlig;" }], [20, "&lbrace;"], [0, "&verbar;"], [0, "&rbrace;"], [34, "&nbsp;"], [0, "&iexcl;"], [0, "&cent;"], [0, "&pound;"], [0, "&curren;"], [0, "&yen;"], [0, "&brvbar;"], [0, "&sect;"], [0, "&die;"], [0, "&copy;"], [0, "&ordf;"], [0, "&laquo;"], [0, "&not;"], [0, "&shy;"], [0, "&circledR;"], [0, "&macr;"], [0, "&deg;"], [0, "&PlusMinus;"], [0, "&sup2;"], [0, "&sup3;"], [0, "&acute;"], [0, "&micro;"], [0, "&para;"], [0, "&centerdot;"], [0, "&cedil;"], [0, "&sup1;"], [0, "&ordm;"], [0, "&raquo;"], [0, "&frac14;"], [0, "&frac12;"], [0, "&frac34;"], [0, "&iquest;"], [0, "&Agrave;"], [0, "&Aacute;"], [0, "&Acirc;"], [0, "&Atilde;"], [0, "&Auml;"], [0, "&angst;"], [0, "&AElig;"], [0, "&Ccedil;"], [0, "&Egrave;"], [0, "&Eacute;"], [0, "&Ecirc;"], [0, "&Euml;"], [0, "&Igrave;"], [0, "&Iacute;"], [0, "&Icirc;"], [0, "&Iuml;"], [0, "&ETH;"], [0, "&Ntilde;"], [0, "&Ograve;"], [0, "&Oacute;"], [0, "&Ocirc;"], [0, "&Otilde;"], [0, "&Ouml;"], [0, "&times;"], [0, "&Oslash;"], [0, "&Ugrave;"], [0, "&Uacute;"], [0, "&Ucirc;"], [0, "&Uuml;"], [0, "&Yacute;"], [0, "&THORN;"], [0, "&szlig;"], [0, "&agrave;"], [0, "&aacute;"], [0, "&acirc;"], [0, "&atilde;"], [0, "&auml;"], [0, "&aring;"], [0, "&aelig;"], [0, "&ccedil;"], [0, "&egrave;"], [0, "&eacute;"], [0, "&ecirc;"], [0, "&euml;"], [0, "&igrave;"], [0, "&iacute;"], [0, "&icirc;"], [0, "&iuml;"], [0, "&eth;"], [0, "&ntilde;"], [0, "&ograve;"], [0, "&oacute;"], [0, "&ocirc;"], [0, "&otilde;"], [0, "&ouml;"], [0, "&div;"], [0, "&oslash;"], [0, "&ugrave;"], [0, "&uacute;"], [0, "&ucirc;"], [0, "&uuml;"], [0, "&yacute;"], [0, "&thorn;"], [0, "&yuml;"], [0, "&Amacr;"], [0, "&amacr;"], [0, "&Abreve;"], [0, "&abreve;"], [0, "&Aogon;"], [0, "&aogon;"], [0, "&Cacute;"], [0, "&cacute;"], [0, "&Ccirc;"], [0, "&ccirc;"], [0, "&Cdot;"], [0, "&cdot;"], [0, "&Ccaron;"], [0, "&ccaron;"], [0, "&Dcaron;"], [0, "&dcaron;"], [0, "&Dstrok;"], [0, "&dstrok;"], [0, "&Emacr;"], [0, "&emacr;"], [2, "&Edot;"], [0, "&edot;"], [0, "&Eogon;"], [0, "&eogon;"], [0, "&Ecaron;"], [0, "&ecaron;"], [0, "&Gcirc;"], [0, "&gcirc;"], [0, "&Gbreve;"], [0, "&gbreve;"], [0, "&Gdot;"], [0, "&gdot;"], [0, "&Gcedil;"], [1, "&Hcirc;"], [0, "&hcirc;"], [0, "&Hstrok;"], [0, "&hstrok;"], [0, "&Itilde;"], [0, "&itilde;"], [0, "&Imacr;"], [0, "&imacr;"], [2, "&Iogon;"], [0, "&iogon;"], [0, "&Idot;"], [0, "&imath;"], [0, "&IJlig;"], [0, "&ijlig;"], [0, "&Jcirc;"], [0, "&jcirc;"], [0, "&Kcedil;"], [0, "&kcedil;"], [0, "&kgreen;"], [0, "&Lacute;"], [0, "&lacute;"], [0, "&Lcedil;"], [0, "&lcedil;"], [0, "&Lcaron;"], [0, "&lcaron;"], [0, "&Lmidot;"], [0, "&lmidot;"], [0, "&Lstrok;"], [0, "&lstrok;"], [0, "&Nacute;"], [0, "&nacute;"], [0, "&Ncedil;"], [0, "&ncedil;"], [0, "&Ncaron;"], [0, "&ncaron;"], [0, "&napos;"], [0, "&ENG;"], [0, "&eng;"], [0, "&Omacr;"], [0, "&omacr;"], [2, "&Odblac;"], [0, "&odblac;"], [0, "&OElig;"], [0, "&oelig;"], [0, "&Racute;"], [0, "&racute;"], [0, "&Rcedil;"], [0, "&rcedil;"], [0, "&Rcaron;"], [0, "&rcaron;"], [0, "&Sacute;"], [0, "&sacute;"], [0, "&Scirc;"], [0, "&scirc;"], [0, "&Scedil;"], [0, "&scedil;"], [0, "&Scaron;"], [0, "&scaron;"], [0, "&Tcedil;"], [0, "&tcedil;"], [0, "&Tcaron;"], [0, "&tcaron;"], [0, "&Tstrok;"], [0, "&tstrok;"], [0, "&Utilde;"], [0, "&utilde;"], [0, "&Umacr;"], [0, "&umacr;"], [0, "&Ubreve;"], [0, "&ubreve;"], [0, "&Uring;"], [0, "&uring;"], [0, "&Udblac;"], [0, "&udblac;"], [0, "&Uogon;"], [0, "&uogon;"], [0, "&Wcirc;"], [0, "&wcirc;"], [0, "&Ycirc;"], [0, "&ycirc;"], [0, "&Yuml;"], [0, "&Zacute;"], [0, "&zacute;"], [0, "&Zdot;"], [0, "&zdot;"], [0, "&Zcaron;"], [0, "&zcaron;"], [19, "&fnof;"], [34, "&imped;"], [63, "&gacute;"], [65, "&jmath;"], [142, "&circ;"], [0, "&caron;"], [16, "&breve;"], [0, "&DiacriticalDot;"], [0, "&ring;"], [0, "&ogon;"], [0, "&DiacriticalTilde;"], [0, "&dblac;"], [51, "&DownBreve;"], [127, "&Alpha;"], [0, "&Beta;"], [0, "&Gamma;"], [0, "&Delta;"], [0, "&Epsilon;"], [0, "&Zeta;"], [0, "&Eta;"], [0, "&Theta;"], [0, "&Iota;"], [0, "&Kappa;"], [0, "&Lambda;"], [0, "&Mu;"], [0, "&Nu;"], [0, "&Xi;"], [0, "&Omicron;"], [0, "&Pi;"], [0, "&Rho;"], [1, "&Sigma;"], [0, "&Tau;"], [0, "&Upsilon;"], [0, "&Phi;"], [0, "&Chi;"], [0, "&Psi;"], [0, "&ohm;"], [7, "&alpha;"], [0, "&beta;"], [0, "&gamma;"], [0, "&delta;"], [0, "&epsi;"], [0, "&zeta;"], [0, "&eta;"], [0, "&theta;"], [0, "&iota;"], [0, "&kappa;"], [0, "&lambda;"], [0, "&mu;"], [0, "&nu;"], [0, "&xi;"], [0, "&omicron;"], [0, "&pi;"], [0, "&rho;"], [0, "&sigmaf;"], [0, "&sigma;"], [0, "&tau;"], [0, "&upsi;"], [0, "&phi;"], [0, "&chi;"], [0, "&psi;"], [0, "&omega;"], [7, "&thetasym;"], [0, "&Upsi;"], [2, "&phiv;"], [0, "&piv;"], [5, "&Gammad;"], [0, "&digamma;"], [18, "&kappav;"], [0, "&rhov;"], [3, "&epsiv;"], [0, "&backepsilon;"], [10, "&IOcy;"], [0, "&DJcy;"], [0, "&GJcy;"], [0, "&Jukcy;"], [0, "&DScy;"], [0, "&Iukcy;"], [0, "&YIcy;"], [0, "&Jsercy;"], [0, "&LJcy;"], [0, "&NJcy;"], [0, "&TSHcy;"], [0, "&KJcy;"], [1, "&Ubrcy;"], [0, "&DZcy;"], [0, "&Acy;"], [0, "&Bcy;"], [0, "&Vcy;"], [0, "&Gcy;"], [0, "&Dcy;"], [0, "&IEcy;"], [0, "&ZHcy;"], [0, "&Zcy;"], [0, "&Icy;"], [0, "&Jcy;"], [0, "&Kcy;"], [0, "&Lcy;"], [0, "&Mcy;"], [0, "&Ncy;"], [0, "&Ocy;"], [0, "&Pcy;"], [0, "&Rcy;"], [0, "&Scy;"], [0, "&Tcy;"], [0, "&Ucy;"], [0, "&Fcy;"], [0, "&KHcy;"], [0, "&TScy;"], [0, "&CHcy;"], [0, "&SHcy;"], [0, "&SHCHcy;"], [0, "&HARDcy;"], [0, "&Ycy;"], [0, "&SOFTcy;"], [0, "&Ecy;"], [0, "&YUcy;"], [0, "&YAcy;"], [0, "&acy;"], [0, "&bcy;"], [0, "&vcy;"], [0, "&gcy;"], [0, "&dcy;"], [0, "&iecy;"], [0, "&zhcy;"], [0, "&zcy;"], [0, "&icy;"], [0, "&jcy;"], [0, "&kcy;"], [0, "&lcy;"], [0, "&mcy;"], [0, "&ncy;"], [0, "&ocy;"], [0, "&pcy;"], [0, "&rcy;"], [0, "&scy;"], [0, "&tcy;"], [0, "&ucy;"], [0, "&fcy;"], [0, "&khcy;"], [0, "&tscy;"], [0, "&chcy;"], [0, "&shcy;"], [0, "&shchcy;"], [0, "&hardcy;"], [0, "&ycy;"], [0, "&softcy;"], [0, "&ecy;"], [0, "&yucy;"], [0, "&yacy;"], [1, "&iocy;"], [0, "&djcy;"], [0, "&gjcy;"], [0, "&jukcy;"], [0, "&dscy;"], [0, "&iukcy;"], [0, "&yicy;"], [0, "&jsercy;"], [0, "&ljcy;"], [0, "&njcy;"], [0, "&tshcy;"], [0, "&kjcy;"], [1, "&ubrcy;"], [0, "&dzcy;"], [7074, "&ensp;"], [0, "&emsp;"], [0, "&emsp13;"], [0, "&emsp14;"], [1, "&numsp;"], [0, "&puncsp;"], [0, "&ThinSpace;"], [0, "&hairsp;"], [0, "&NegativeMediumSpace;"], [0, "&zwnj;"], [0, "&zwj;"], [0, "&lrm;"], [0, "&rlm;"], [0, "&dash;"], [2, "&ndash;"], [0, "&mdash;"], [0, "&horbar;"], [0, "&Verbar;"], [1, "&lsquo;"], [0, "&CloseCurlyQuote;"], [0, "&lsquor;"], [1, "&ldquo;"], [0, "&CloseCurlyDoubleQuote;"], [0, "&bdquo;"], [1, "&dagger;"], [0, "&Dagger;"], [0, "&bull;"], [2, "&nldr;"], [0, "&hellip;"], [9, "&permil;"], [0, "&pertenk;"], [0, "&prime;"], [0, "&Prime;"], [0, "&tprime;"], [0, "&backprime;"], [3, "&lsaquo;"], [0, "&rsaquo;"], [3, "&oline;"], [2, "&caret;"], [1, "&hybull;"], [0, "&frasl;"], [10, "&bsemi;"], [7, "&qprime;"], [7, { v: "&MediumSpace;", n: 8202, o: "&ThickSpace;" }], [0, "&NoBreak;"], [0, "&af;"], [0, "&InvisibleTimes;"], [0, "&ic;"], [72, "&euro;"], [46, "&tdot;"], [0, "&DotDot;"], [37, "&complexes;"], [2, "&incare;"], [4, "&gscr;"], [0, "&hamilt;"], [0, "&Hfr;"], [0, "&Hopf;"], [0, "&planckh;"], [0, "&hbar;"], [0, "&imagline;"], [0, "&Ifr;"], [0, "&lagran;"], [0, "&ell;"], [1, "&naturals;"], [0, "&numero;"], [0, "&copysr;"], [0, "&weierp;"], [0, "&Popf;"], [0, "&Qopf;"], [0, "&realine;"], [0, "&real;"], [0, "&reals;"], [0, "&rx;"], [3, "&trade;"], [1, "&integers;"], [2, "&mho;"], [0, "&zeetrf;"], [0, "&iiota;"], [2, "&bernou;"], [0, "&Cayleys;"], [1, "&escr;"], [0, "&Escr;"], [0, "&Fouriertrf;"], [1, "&Mellintrf;"], [0, "&order;"], [0, "&alefsym;"], [0, "&beth;"], [0, "&gimel;"], [0, "&daleth;"], [12, "&CapitalDifferentialD;"], [0, "&dd;"], [0, "&ee;"], [0, "&ii;"], [10, "&frac13;"], [0, "&frac23;"], [0, "&frac15;"], [0, "&frac25;"], [0, "&frac35;"], [0, "&frac45;"], [0, "&frac16;"], [0, "&frac56;"], [0, "&frac18;"], [0, "&frac38;"], [0, "&frac58;"], [0, "&frac78;"], [49, "&larr;"], [0, "&ShortUpArrow;"], [0, "&rarr;"], [0, "&darr;"], [0, "&harr;"], [0, "&updownarrow;"], [0, "&nwarr;"], [0, "&nearr;"], [0, "&LowerRightArrow;"], [0, "&LowerLeftArrow;"], [0, "&nlarr;"], [0, "&nrarr;"], [1, { v: "&rarrw;", n: 824, o: "&nrarrw;" }], [0, "&Larr;"], [0, "&Uarr;"], [0, "&Rarr;"], [0, "&Darr;"], [0, "&larrtl;"], [0, "&rarrtl;"], [0, "&LeftTeeArrow;"], [0, "&mapstoup;"], [0, "&map;"], [0, "&DownTeeArrow;"], [1, "&hookleftarrow;"], [0, "&hookrightarrow;"], [0, "&larrlp;"], [0, "&looparrowright;"], [0, "&harrw;"], [0, "&nharr;"], [1, "&lsh;"], [0, "&rsh;"], [0, "&ldsh;"], [0, "&rdsh;"], [1, "&crarr;"], [0, "&cularr;"], [0, "&curarr;"], [2, "&circlearrowleft;"], [0, "&circlearrowright;"], [0, "&leftharpoonup;"], [0, "&DownLeftVector;"], [0, "&RightUpVector;"], [0, "&LeftUpVector;"], [0, "&rharu;"], [0, "&DownRightVector;"], [0, "&dharr;"], [0, "&dharl;"], [0, "&RightArrowLeftArrow;"], [0, "&udarr;"], [0, "&LeftArrowRightArrow;"], [0, "&leftleftarrows;"], [0, "&upuparrows;"], [0, "&rightrightarrows;"], [0, "&ddarr;"], [0, "&leftrightharpoons;"], [0, "&Equilibrium;"], [0, "&nlArr;"], [0, "&nhArr;"], [0, "&nrArr;"], [0, "&DoubleLeftArrow;"], [0, "&DoubleUpArrow;"], [0, "&DoubleRightArrow;"], [0, "&dArr;"], [0, "&DoubleLeftRightArrow;"], [0, "&DoubleUpDownArrow;"], [0, "&nwArr;"], [0, "&neArr;"], [0, "&seArr;"], [0, "&swArr;"], [0, "&lAarr;"], [0, "&rAarr;"], [1, "&zigrarr;"], [6, "&larrb;"], [0, "&rarrb;"], [15, "&DownArrowUpArrow;"], [7, "&loarr;"], [0, "&roarr;"], [0, "&hoarr;"], [0, "&forall;"], [0, "&comp;"], [0, { v: "&part;", n: 824, o: "&npart;" }], [0, "&exist;"], [0, "&nexist;"], [0, "&empty;"], [1, "&Del;"], [0, "&Element;"], [0, "&NotElement;"], [1, "&ni;"], [0, "&notni;"], [2, "&prod;"], [0, "&coprod;"], [0, "&sum;"], [0, "&minus;"], [0, "&MinusPlus;"], [0, "&dotplus;"], [1, "&Backslash;"], [0, "&lowast;"], [0, "&compfn;"], [1, "&radic;"], [2, "&prop;"], [0, "&infin;"], [0, "&angrt;"], [0, { v: "&ang;", n: 8402, o: "&nang;" }], [0, "&angmsd;"], [0, "&angsph;"], [0, "&mid;"], [0, "&nmid;"], [0, "&DoubleVerticalBar;"], [0, "&NotDoubleVerticalBar;"], [0, "&and;"], [0, "&or;"], [0, { v: "&cap;", n: 65024, o: "&caps;" }], [0, { v: "&cup;", n: 65024, o: "&cups;" }], [0, "&int;"], [0, "&Int;"], [0, "&iiint;"], [0, "&conint;"], [0, "&Conint;"], [0, "&Cconint;"], [0, "&cwint;"], [0, "&ClockwiseContourIntegral;"], [0, "&awconint;"], [0, "&there4;"], [0, "&becaus;"], [0, "&ratio;"], [0, "&Colon;"], [0, "&dotminus;"], [1, "&mDDot;"], [0, "&homtht;"], [0, { v: "&sim;", n: 8402, o: "&nvsim;" }], [0, { v: "&backsim;", n: 817, o: "&race;" }], [0, { v: "&ac;", n: 819, o: "&acE;" }], [0, "&acd;"], [0, "&VerticalTilde;"], [0, "&NotTilde;"], [0, { v: "&eqsim;", n: 824, o: "&nesim;" }], [0, "&sime;"], [0, "&NotTildeEqual;"], [0, "&cong;"], [0, "&simne;"], [0, "&ncong;"], [0, "&ap;"], [0, "&nap;"], [0, "&ape;"], [0, { v: "&apid;", n: 824, o: "&napid;" }], [0, "&backcong;"], [0, { v: "&asympeq;", n: 8402, o: "&nvap;" }], [0, { v: "&bump;", n: 824, o: "&nbump;" }], [0, { v: "&bumpe;", n: 824, o: "&nbumpe;" }], [0, { v: "&doteq;", n: 824, o: "&nedot;" }], [0, "&doteqdot;"], [0, "&efDot;"], [0, "&erDot;"], [0, "&Assign;"], [0, "&ecolon;"], [0, "&ecir;"], [0, "&circeq;"], [1, "&wedgeq;"], [0, "&veeeq;"], [1, "&triangleq;"], [2, "&equest;"], [0, "&ne;"], [0, { v: "&Congruent;", n: 8421, o: "&bnequiv;" }], [0, "&nequiv;"], [1, { v: "&le;", n: 8402, o: "&nvle;" }], [0, { v: "&ge;", n: 8402, o: "&nvge;" }], [0, { v: "&lE;", n: 824, o: "&nlE;" }], [0, { v: "&gE;", n: 824, o: "&ngE;" }], [0, { v: "&lnE;", n: 65024, o: "&lvertneqq;" }], [0, { v: "&gnE;", n: 65024, o: "&gvertneqq;" }], [0, { v: "&ll;", n: new Map(/* @__PURE__ */ restoreDiff([[824, "&nLtv;"], [7577, "&nLt;"]])) }], [0, { v: "&gg;", n: new Map(/* @__PURE__ */ restoreDiff([[824, "&nGtv;"], [7577, "&nGt;"]])) }], [0, "&between;"], [0, "&NotCupCap;"], [0, "&nless;"], [0, "&ngt;"], [0, "&nle;"], [0, "&nge;"], [0, "&lesssim;"], [0, "&GreaterTilde;"], [0, "&nlsim;"], [0, "&ngsim;"], [0, "&LessGreater;"], [0, "&gl;"], [0, "&NotLessGreater;"], [0, "&NotGreaterLess;"], [0, "&pr;"], [0, "&sc;"], [0, "&prcue;"], [0, "&sccue;"], [0, "&PrecedesTilde;"], [0, { v: "&scsim;", n: 824, o: "&NotSucceedsTilde;" }], [0, "&NotPrecedes;"], [0, "&NotSucceeds;"], [0, { v: "&sub;", n: 8402, o: "&NotSubset;" }], [0, { v: "&sup;", n: 8402, o: "&NotSuperset;" }], [0, "&nsub;"], [0, "&nsup;"], [0, "&sube;"], [0, "&supe;"], [0, "&NotSubsetEqual;"], [0, "&NotSupersetEqual;"], [0, { v: "&subne;", n: 65024, o: "&varsubsetneq;" }], [0, { v: "&supne;", n: 65024, o: "&varsupsetneq;" }], [1, "&cupdot;"], [0, "&UnionPlus;"], [0, { v: "&sqsub;", n: 824, o: "&NotSquareSubset;" }], [0, { v: "&sqsup;", n: 824, o: "&NotSquareSuperset;" }], [0, "&sqsube;"], [0, "&sqsupe;"], [0, { v: "&sqcap;", n: 65024, o: "&sqcaps;" }], [0, { v: "&sqcup;", n: 65024, o: "&sqcups;" }], [0, "&CirclePlus;"], [0, "&CircleMinus;"], [0, "&CircleTimes;"], [0, "&osol;"], [0, "&CircleDot;"], [0, "&circledcirc;"], [0, "&circledast;"], [1, "&circleddash;"], [0, "&boxplus;"], [0, "&boxminus;"], [0, "&boxtimes;"], [0, "&dotsquare;"], [0, "&RightTee;"], [0, "&dashv;"], [0, "&DownTee;"], [0, "&bot;"], [1, "&models;"], [0, "&DoubleRightTee;"], [0, "&Vdash;"], [0, "&Vvdash;"], [0, "&VDash;"], [0, "&nvdash;"], [0, "&nvDash;"], [0, "&nVdash;"], [0, "&nVDash;"], [0, "&prurel;"], [1, "&LeftTriangle;"], [0, "&RightTriangle;"], [0, { v: "&LeftTriangleEqual;", n: 8402, o: "&nvltrie;" }], [0, { v: "&RightTriangleEqual;", n: 8402, o: "&nvrtrie;" }], [0, "&origof;"], [0, "&imof;"], [0, "&multimap;"], [0, "&hercon;"], [0, "&intcal;"], [0, "&veebar;"], [1, "&barvee;"], [0, "&angrtvb;"], [0, "&lrtri;"], [0, "&bigwedge;"], [0, "&bigvee;"], [0, "&bigcap;"], [0, "&bigcup;"], [0, "&diam;"], [0, "&sdot;"], [0, "&sstarf;"], [0, "&divideontimes;"], [0, "&bowtie;"], [0, "&ltimes;"], [0, "&rtimes;"], [0, "&leftthreetimes;"], [0, "&rightthreetimes;"], [0, "&backsimeq;"], [0, "&curlyvee;"], [0, "&curlywedge;"], [0, "&Sub;"], [0, "&Sup;"], [0, "&Cap;"], [0, "&Cup;"], [0, "&fork;"], [0, "&epar;"], [0, "&lessdot;"], [0, "&gtdot;"], [0, { v: "&Ll;", n: 824, o: "&nLl;" }], [0, { v: "&Gg;", n: 824, o: "&nGg;" }], [0, { v: "&leg;", n: 65024, o: "&lesg;" }], [0, { v: "&gel;", n: 65024, o: "&gesl;" }], [2, "&cuepr;"], [0, "&cuesc;"], [0, "&NotPrecedesSlantEqual;"], [0, "&NotSucceedsSlantEqual;"], [0, "&NotSquareSubsetEqual;"], [0, "&NotSquareSupersetEqual;"], [2, "&lnsim;"], [0, "&gnsim;"], [0, "&precnsim;"], [0, "&scnsim;"], [0, "&nltri;"], [0, "&NotRightTriangle;"], [0, "&nltrie;"], [0, "&NotRightTriangleEqual;"], [0, "&vellip;"], [0, "&ctdot;"], [0, "&utdot;"], [0, "&dtdot;"], [0, "&disin;"], [0, "&isinsv;"], [0, "&isins;"], [0, { v: "&isindot;", n: 824, o: "&notindot;" }], [0, "&notinvc;"], [0, "&notinvb;"], [1, { v: "&isinE;", n: 824, o: "&notinE;" }], [0, "&nisd;"], [0, "&xnis;"], [0, "&nis;"], [0, "&notnivc;"], [0, "&notnivb;"], [6, "&barwed;"], [0, "&Barwed;"], [1, "&lceil;"], [0, "&rceil;"], [0, "&LeftFloor;"], [0, "&rfloor;"], [0, "&drcrop;"], [0, "&dlcrop;"], [0, "&urcrop;"], [0, "&ulcrop;"], [0, "&bnot;"], [1, "&profline;"], [0, "&profsurf;"], [1, "&telrec;"], [0, "&target;"], [5, "&ulcorn;"], [0, "&urcorn;"], [0, "&dlcorn;"], [0, "&drcorn;"], [2, "&frown;"], [0, "&smile;"], [9, "&cylcty;"], [0, "&profalar;"], [7, "&topbot;"], [6, "&ovbar;"], [1, "&solbar;"], [60, "&angzarr;"], [51, "&lmoustache;"], [0, "&rmoustache;"], [2, "&OverBracket;"], [0, "&bbrk;"], [0, "&bbrktbrk;"], [37, "&OverParenthesis;"], [0, "&UnderParenthesis;"], [0, "&OverBrace;"], [0, "&UnderBrace;"], [2, "&trpezium;"], [4, "&elinters;"], [59, "&blank;"], [164, "&circledS;"], [55, "&boxh;"], [1, "&boxv;"], [9, "&boxdr;"], [3, "&boxdl;"], [3, "&boxur;"], [3, "&boxul;"], [3, "&boxvr;"], [7, "&boxvl;"], [7, "&boxhd;"], [7, "&boxhu;"], [7, "&boxvh;"], [19, "&boxH;"], [0, "&boxV;"], [0, "&boxdR;"], [0, "&boxDr;"], [0, "&boxDR;"], [0, "&boxdL;"], [0, "&boxDl;"], [0, "&boxDL;"], [0, "&boxuR;"], [0, "&boxUr;"], [0, "&boxUR;"], [0, "&boxuL;"], [0, "&boxUl;"], [0, "&boxUL;"], [0, "&boxvR;"], [0, "&boxVr;"], [0, "&boxVR;"], [0, "&boxvL;"], [0, "&boxVl;"], [0, "&boxVL;"], [0, "&boxHd;"], [0, "&boxhD;"], [0, "&boxHD;"], [0, "&boxHu;"], [0, "&boxhU;"], [0, "&boxHU;"], [0, "&boxvH;"], [0, "&boxVh;"], [0, "&boxVH;"], [19, "&uhblk;"], [3, "&lhblk;"], [3, "&block;"], [8, "&blk14;"], [0, "&blk12;"], [0, "&blk34;"], [13, "&square;"], [8, "&blacksquare;"], [0, "&EmptyVerySmallSquare;"], [1, "&rect;"], [0, "&marker;"], [2, "&fltns;"], [1, "&bigtriangleup;"], [0, "&blacktriangle;"], [0, "&triangle;"], [2, "&blacktriangleright;"], [0, "&rtri;"], [3, "&bigtriangledown;"], [0, "&blacktriangledown;"], [0, "&dtri;"], [2, "&blacktriangleleft;"], [0, "&ltri;"], [6, "&loz;"], [0, "&cir;"], [32, "&tridot;"], [2, "&bigcirc;"], [8, "&ultri;"], [0, "&urtri;"], [0, "&lltri;"], [0, "&EmptySmallSquare;"], [0, "&FilledSmallSquare;"], [8, "&bigstar;"], [0, "&star;"], [7, "&phone;"], [49, "&female;"], [1, "&male;"], [29, "&spades;"], [2, "&clubs;"], [1, "&hearts;"], [0, "&diamondsuit;"], [3, "&sung;"], [2, "&flat;"], [0, "&natural;"], [0, "&sharp;"], [163, "&check;"], [3, "&cross;"], [8, "&malt;"], [21, "&sext;"], [33, "&VerticalSeparator;"], [25, "&lbbrk;"], [0, "&rbbrk;"], [84, "&bsolhsub;"], [0, "&suphsol;"], [28, "&LeftDoubleBracket;"], [0, "&RightDoubleBracket;"], [0, "&lang;"], [0, "&rang;"], [0, "&Lang;"], [0, "&Rang;"], [0, "&loang;"], [0, "&roang;"], [7, "&longleftarrow;"], [0, "&longrightarrow;"], [0, "&longleftrightarrow;"], [0, "&DoubleLongLeftArrow;"], [0, "&DoubleLongRightArrow;"], [0, "&DoubleLongLeftRightArrow;"], [1, "&longmapsto;"], [2, "&dzigrarr;"], [258, "&nvlArr;"], [0, "&nvrArr;"], [0, "&nvHarr;"], [0, "&Map;"], [6, "&lbarr;"], [0, "&bkarow;"], [0, "&lBarr;"], [0, "&dbkarow;"], [0, "&drbkarow;"], [0, "&DDotrahd;"], [0, "&UpArrowBar;"], [0, "&DownArrowBar;"], [2, "&Rarrtl;"], [2, "&latail;"], [0, "&ratail;"], [0, "&lAtail;"], [0, "&rAtail;"], [0, "&larrfs;"], [0, "&rarrfs;"], [0, "&larrbfs;"], [0, "&rarrbfs;"], [2, "&nwarhk;"], [0, "&nearhk;"], [0, "&hksearow;"], [0, "&hkswarow;"], [0, "&nwnear;"], [0, "&nesear;"], [0, "&seswar;"], [0, "&swnwar;"], [8, { v: "&rarrc;", n: 824, o: "&nrarrc;" }], [1, "&cudarrr;"], [0, "&ldca;"], [0, "&rdca;"], [0, "&cudarrl;"], [0, "&larrpl;"], [2, "&curarrm;"], [0, "&cularrp;"], [7, "&rarrpl;"], [2, "&harrcir;"], [0, "&Uarrocir;"], [0, "&lurdshar;"], [0, "&ldrushar;"], [2, "&LeftRightVector;"], [0, "&RightUpDownVector;"], [0, "&DownLeftRightVector;"], [0, "&LeftUpDownVector;"], [0, "&LeftVectorBar;"], [0, "&RightVectorBar;"], [0, "&RightUpVectorBar;"], [0, "&RightDownVectorBar;"], [0, "&DownLeftVectorBar;"], [0, "&DownRightVectorBar;"], [0, "&LeftUpVectorBar;"], [0, "&LeftDownVectorBar;"], [0, "&LeftTeeVector;"], [0, "&RightTeeVector;"], [0, "&RightUpTeeVector;"], [0, "&RightDownTeeVector;"], [0, "&DownLeftTeeVector;"], [0, "&DownRightTeeVector;"], [0, "&LeftUpTeeVector;"], [0, "&LeftDownTeeVector;"], [0, "&lHar;"], [0, "&uHar;"], [0, "&rHar;"], [0, "&dHar;"], [0, "&luruhar;"], [0, "&ldrdhar;"], [0, "&ruluhar;"], [0, "&rdldhar;"], [0, "&lharul;"], [0, "&llhard;"], [0, "&rharul;"], [0, "&lrhard;"], [0, "&udhar;"], [0, "&duhar;"], [0, "&RoundImplies;"], [0, "&erarr;"], [0, "&simrarr;"], [0, "&larrsim;"], [0, "&rarrsim;"], [0, "&rarrap;"], [0, "&ltlarr;"], [1, "&gtrarr;"], [0, "&subrarr;"], [1, "&suplarr;"], [0, "&lfisht;"], [0, "&rfisht;"], [0, "&ufisht;"], [0, "&dfisht;"], [5, "&lopar;"], [0, "&ropar;"], [4, "&lbrke;"], [0, "&rbrke;"], [0, "&lbrkslu;"], [0, "&rbrksld;"], [0, "&lbrksld;"], [0, "&rbrkslu;"], [0, "&langd;"], [0, "&rangd;"], [0, "&lparlt;"], [0, "&rpargt;"], [0, "&gtlPar;"], [0, "&ltrPar;"], [3, "&vzigzag;"], [1, "&vangrt;"], [0, "&angrtvbd;"], [6, "&ange;"], [0, "&range;"], [0, "&dwangle;"], [0, "&uwangle;"], [0, "&angmsdaa;"], [0, "&angmsdab;"], [0, "&angmsdac;"], [0, "&angmsdad;"], [0, "&angmsdae;"], [0, "&angmsdaf;"], [0, "&angmsdag;"], [0, "&angmsdah;"], [0, "&bemptyv;"], [0, "&demptyv;"], [0, "&cemptyv;"], [0, "&raemptyv;"], [0, "&laemptyv;"], [0, "&ohbar;"], [0, "&omid;"], [0, "&opar;"], [1, "&operp;"], [1, "&olcross;"], [0, "&odsold;"], [1, "&olcir;"], [0, "&ofcir;"], [0, "&olt;"], [0, "&ogt;"], [0, "&cirscir;"], [0, "&cirE;"], [0, "&solb;"], [0, "&bsolb;"], [3, "&boxbox;"], [3, "&trisb;"], [0, "&rtriltri;"], [0, { v: "&LeftTriangleBar;", n: 824, o: "&NotLeftTriangleBar;" }], [0, { v: "&RightTriangleBar;", n: 824, o: "&NotRightTriangleBar;" }], [11, "&iinfin;"], [0, "&infintie;"], [0, "&nvinfin;"], [4, "&eparsl;"], [0, "&smeparsl;"], [0, "&eqvparsl;"], [5, "&blacklozenge;"], [8, "&RuleDelayed;"], [1, "&dsol;"], [9, "&bigodot;"], [0, "&bigoplus;"], [0, "&bigotimes;"], [1, "&biguplus;"], [1, "&bigsqcup;"], [5, "&iiiint;"], [0, "&fpartint;"], [2, "&cirfnint;"], [0, "&awint;"], [0, "&rppolint;"], [0, "&scpolint;"], [0, "&npolint;"], [0, "&pointint;"], [0, "&quatint;"], [0, "&intlarhk;"], [10, "&pluscir;"], [0, "&plusacir;"], [0, "&simplus;"], [0, "&plusdu;"], [0, "&plussim;"], [0, "&plustwo;"], [1, "&mcomma;"], [0, "&minusdu;"], [2, "&loplus;"], [0, "&roplus;"], [0, "&Cross;"], [0, "&timesd;"], [0, "&timesbar;"], [1, "&smashp;"], [0, "&lotimes;"], [0, "&rotimes;"], [0, "&otimesas;"], [0, "&Otimes;"], [0, "&odiv;"], [0, "&triplus;"], [0, "&triminus;"], [0, "&tritime;"], [0, "&intprod;"], [2, "&amalg;"], [0, "&capdot;"], [1, "&ncup;"], [0, "&ncap;"], [0, "&capand;"], [0, "&cupor;"], [0, "&cupcap;"], [0, "&capcup;"], [0, "&cupbrcap;"], [0, "&capbrcup;"], [0, "&cupcup;"], [0, "&capcap;"], [0, "&ccups;"], [0, "&ccaps;"], [2, "&ccupssm;"], [2, "&And;"], [0, "&Or;"], [0, "&andand;"], [0, "&oror;"], [0, "&orslope;"], [0, "&andslope;"], [1, "&andv;"], [0, "&orv;"], [0, "&andd;"], [0, "&ord;"], [1, "&wedbar;"], [6, "&sdote;"], [3, "&simdot;"], [2, { v: "&congdot;", n: 824, o: "&ncongdot;" }], [0, "&easter;"], [0, "&apacir;"], [0, { v: "&apE;", n: 824, o: "&napE;" }], [0, "&eplus;"], [0, "&pluse;"], [0, "&Esim;"], [0, "&Colone;"], [0, "&Equal;"], [1, "&ddotseq;"], [0, "&equivDD;"], [0, "&ltcir;"], [0, "&gtcir;"], [0, "&ltquest;"], [0, "&gtquest;"], [0, { v: "&leqslant;", n: 824, o: "&nleqslant;" }], [0, { v: "&geqslant;", n: 824, o: "&ngeqslant;" }], [0, "&lesdot;"], [0, "&gesdot;"], [0, "&lesdoto;"], [0, "&gesdoto;"], [0, "&lesdotor;"], [0, "&gesdotol;"], [0, "&lap;"], [0, "&gap;"], [0, "&lne;"], [0, "&gne;"], [0, "&lnap;"], [0, "&gnap;"], [0, "&lEg;"], [0, "&gEl;"], [0, "&lsime;"], [0, "&gsime;"], [0, "&lsimg;"], [0, "&gsiml;"], [0, "&lgE;"], [0, "&glE;"], [0, "&lesges;"], [0, "&gesles;"], [0, "&els;"], [0, "&egs;"], [0, "&elsdot;"], [0, "&egsdot;"], [0, "&el;"], [0, "&eg;"], [2, "&siml;"], [0, "&simg;"], [0, "&simlE;"], [0, "&simgE;"], [0, { v: "&LessLess;", n: 824, o: "&NotNestedLessLess;" }], [0, { v: "&GreaterGreater;", n: 824, o: "&NotNestedGreaterGreater;" }], [1, "&glj;"], [0, "&gla;"], [0, "&ltcc;"], [0, "&gtcc;"], [0, "&lescc;"], [0, "&gescc;"], [0, "&smt;"], [0, "&lat;"], [0, { v: "&smte;", n: 65024, o: "&smtes;" }], [0, { v: "&late;", n: 65024, o: "&lates;" }], [0, "&bumpE;"], [0, { v: "&PrecedesEqual;", n: 824, o: "&NotPrecedesEqual;" }], [0, { v: "&sce;", n: 824, o: "&NotSucceedsEqual;" }], [2, "&prE;"], [0, "&scE;"], [0, "&precneqq;"], [0, "&scnE;"], [0, "&prap;"], [0, "&scap;"], [0, "&precnapprox;"], [0, "&scnap;"], [0, "&Pr;"], [0, "&Sc;"], [0, "&subdot;"], [0, "&supdot;"], [0, "&subplus;"], [0, "&supplus;"], [0, "&submult;"], [0, "&supmult;"], [0, "&subedot;"], [0, "&supedot;"], [0, { v: "&subE;", n: 824, o: "&nsubE;" }], [0, { v: "&supE;", n: 824, o: "&nsupE;" }], [0, "&subsim;"], [0, "&supsim;"], [2, { v: "&subnE;", n: 65024, o: "&varsubsetneqq;" }], [0, { v: "&supnE;", n: 65024, o: "&varsupsetneqq;" }], [2, "&csub;"], [0, "&csup;"], [0, "&csube;"], [0, "&csupe;"], [0, "&subsup;"], [0, "&supsub;"], [0, "&subsub;"], [0, "&supsup;"], [0, "&suphsub;"], [0, "&supdsub;"], [0, "&forkv;"], [0, "&topfork;"], [0, "&mlcp;"], [8, "&Dashv;"], [1, "&Vdashl;"], [0, "&Barv;"], [0, "&vBar;"], [0, "&vBarv;"], [1, "&Vbar;"], [0, "&Not;"], [0, "&bNot;"], [0, "&rnmid;"], [0, "&cirmid;"], [0, "&midcir;"], [0, "&topcir;"], [0, "&nhpar;"], [0, "&parsim;"], [9, { v: "&parsl;", n: 8421, o: "&nparsl;" }], [44343, { n: new Map(/* @__PURE__ */ restoreDiff([[56476, "&Ascr;"], [1, "&Cscr;"], [0, "&Dscr;"], [2, "&Gscr;"], [2, "&Jscr;"], [0, "&Kscr;"], [2, "&Nscr;"], [0, "&Oscr;"], [0, "&Pscr;"], [0, "&Qscr;"], [1, "&Sscr;"], [0, "&Tscr;"], [0, "&Uscr;"], [0, "&Vscr;"], [0, "&Wscr;"], [0, "&Xscr;"], [0, "&Yscr;"], [0, "&Zscr;"], [0, "&ascr;"], [0, "&bscr;"], [0, "&cscr;"], [0, "&dscr;"], [1, "&fscr;"], [1, "&hscr;"], [0, "&iscr;"], [0, "&jscr;"], [0, "&kscr;"], [0, "&lscr;"], [0, "&mscr;"], [0, "&nscr;"], [1, "&pscr;"], [0, "&qscr;"], [0, "&rscr;"], [0, "&sscr;"], [0, "&tscr;"], [0, "&uscr;"], [0, "&vscr;"], [0, "&wscr;"], [0, "&xscr;"], [0, "&yscr;"], [0, "&zscr;"], [52, "&Afr;"], [0, "&Bfr;"], [1, "&Dfr;"], [0, "&Efr;"], [0, "&Ffr;"], [0, "&Gfr;"], [2, "&Jfr;"], [0, "&Kfr;"], [0, "&Lfr;"], [0, "&Mfr;"], [0, "&Nfr;"], [0, "&Ofr;"], [0, "&Pfr;"], [0, "&Qfr;"], [1, "&Sfr;"], [0, "&Tfr;"], [0, "&Ufr;"], [0, "&Vfr;"], [0, "&Wfr;"], [0, "&Xfr;"], [0, "&Yfr;"], [1, "&afr;"], [0, "&bfr;"], [0, "&cfr;"], [0, "&dfr;"], [0, "&efr;"], [0, "&ffr;"], [0, "&gfr;"], [0, "&hfr;"], [0, "&ifr;"], [0, "&jfr;"], [0, "&kfr;"], [0, "&lfr;"], [0, "&mfr;"], [0, "&nfr;"], [0, "&ofr;"], [0, "&pfr;"], [0, "&qfr;"], [0, "&rfr;"], [0, "&sfr;"], [0, "&tfr;"], [0, "&ufr;"], [0, "&vfr;"], [0, "&wfr;"], [0, "&xfr;"], [0, "&yfr;"], [0, "&zfr;"], [0, "&Aopf;"], [0, "&Bopf;"], [1, "&Dopf;"], [0, "&Eopf;"], [0, "&Fopf;"], [0, "&Gopf;"], [1, "&Iopf;"], [0, "&Jopf;"], [0, "&Kopf;"], [0, "&Lopf;"], [0, "&Mopf;"], [1, "&Oopf;"], [3, "&Sopf;"], [0, "&Topf;"], [0, "&Uopf;"], [0, "&Vopf;"], [0, "&Wopf;"], [0, "&Xopf;"], [0, "&Yopf;"], [1, "&aopf;"], [0, "&bopf;"], [0, "&copf;"], [0, "&dopf;"], [0, "&eopf;"], [0, "&fopf;"], [0, "&gopf;"], [0, "&hopf;"], [0, "&iopf;"], [0, "&jopf;"], [0, "&kopf;"], [0, "&lopf;"], [0, "&mopf;"], [0, "&nopf;"], [0, "&oopf;"], [0, "&popf;"], [0, "&qopf;"], [0, "&ropf;"], [0, "&sopf;"], [0, "&topf;"], [0, "&uopf;"], [0, "&vopf;"], [0, "&wopf;"], [0, "&xopf;"], [0, "&yopf;"], [0, "&zopf;"]])) }], [8906, "&fflig;"], [0, "&filig;"], [0, "&fllig;"], [0, "&ffilig;"], [0, "&ffllig;"]]));
const xmlReplacer = /["&'<>$\x80-\uFFFF]/g;
const xmlCodeMap = /* @__PURE__ */ new Map([
  [34, "&quot;"],
  [38, "&amp;"],
  [39, "&apos;"],
  [60, "&lt;"],
  [62, "&gt;"]
]);
const getCodePoint = (
  // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
  String.prototype.codePointAt != null ? (str, index2) => str.codePointAt(index2) : (
    // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
    (c2, index2) => (c2.charCodeAt(index2) & 64512) === 55296 ? (c2.charCodeAt(index2) - 55296) * 1024 + c2.charCodeAt(index2 + 1) - 56320 + 65536 : c2.charCodeAt(index2)
  )
);
function encodeXML(str) {
  let ret = "";
  let lastIdx = 0;
  let match2;
  while ((match2 = xmlReplacer.exec(str)) !== null) {
    const i2 = match2.index;
    const char = str.charCodeAt(i2);
    const next = xmlCodeMap.get(char);
    if (next !== void 0) {
      ret += str.substring(lastIdx, i2) + next;
      lastIdx = i2 + 1;
    } else {
      ret += `${str.substring(lastIdx, i2)}&#x${getCodePoint(str, i2).toString(16)};`;
      lastIdx = xmlReplacer.lastIndex += Number((char & 64512) === 55296);
    }
  }
  return ret + str.substr(lastIdx);
}
__name(encodeXML, "encodeXML");
const escape$2 = encodeXML;
function getEscaper(regex2, map3) {
  return /* @__PURE__ */ __name(function escape2(data) {
    let match2;
    let lastIdx = 0;
    let result = "";
    while (match2 = regex2.exec(data)) {
      if (lastIdx !== match2.index) {
        result += data.substring(lastIdx, match2.index);
      }
      result += map3.get(match2[0].charCodeAt(0));
      lastIdx = match2.index + 1;
    }
    return result + data.substring(lastIdx);
  }, "escape");
}
__name(getEscaper, "getEscaper");
const escapeUTF8 = getEscaper(/[&<>'"]/g, xmlCodeMap);
const escapeAttribute = getEscaper(/["&\u00A0]/g, /* @__PURE__ */ new Map([
  [34, "&quot;"],
  [38, "&amp;"],
  [160, "&nbsp;"]
]));
const escapeText = getEscaper(/[&<>\u00A0]/g, /* @__PURE__ */ new Map([
  [38, "&amp;"],
  [60, "&lt;"],
  [62, "&gt;"],
  [160, "&nbsp;"]
]));
const htmlReplacer = /[\t\n!-,./:-@[-`\f{-}$\x80-\uFFFF]/g;
function encodeHTML(data) {
  return encodeHTMLTrieRe(htmlReplacer, data);
}
__name(encodeHTML, "encodeHTML");
function encodeNonAsciiHTML(data) {
  return encodeHTMLTrieRe(xmlReplacer, data);
}
__name(encodeNonAsciiHTML, "encodeNonAsciiHTML");
function encodeHTMLTrieRe(regExp, str) {
  let ret = "";
  let lastIdx = 0;
  let match2;
  while ((match2 = regExp.exec(str)) !== null) {
    const i2 = match2.index;
    ret += str.substring(lastIdx, i2);
    const char = str.charCodeAt(i2);
    let next = htmlTrie.get(char);
    if (typeof next === "object") {
      if (i2 + 1 < str.length) {
        const nextChar = str.charCodeAt(i2 + 1);
        const value = typeof next.n === "number" ? next.n === nextChar ? next.o : void 0 : next.n.get(nextChar);
        if (value !== void 0) {
          ret += value;
          lastIdx = regExp.lastIndex += 1;
          continue;
        }
      }
      next = next.v;
    }
    if (next !== void 0) {
      ret += next;
      lastIdx = i2 + 1;
    } else {
      const cp = getCodePoint(str, i2);
      ret += `&#x${cp.toString(16)};`;
      lastIdx = regExp.lastIndex += Number(cp !== char);
    }
  }
  return ret + str.substr(lastIdx);
}
__name(encodeHTMLTrieRe, "encodeHTMLTrieRe");
var EntityLevel;
(function(EntityLevel2) {
  EntityLevel2[EntityLevel2["XML"] = 0] = "XML";
  EntityLevel2[EntityLevel2["HTML"] = 1] = "HTML";
})(EntityLevel || (EntityLevel = {}));
var EncodingMode;
(function(EncodingMode2) {
  EncodingMode2[EncodingMode2["UTF8"] = 0] = "UTF8";
  EncodingMode2[EncodingMode2["ASCII"] = 1] = "ASCII";
  EncodingMode2[EncodingMode2["Extensive"] = 2] = "Extensive";
  EncodingMode2[EncodingMode2["Attribute"] = 3] = "Attribute";
  EncodingMode2[EncodingMode2["Text"] = 4] = "Text";
})(EncodingMode || (EncodingMode = {}));
function decode$1(data, options2 = EntityLevel.XML) {
  const level = typeof options2 === "number" ? options2 : options2.level;
  if (level === EntityLevel.HTML) {
    const mode = typeof options2 === "object" ? options2.mode : void 0;
    return decodeHTML(data, mode);
  }
  return decodeXML(data);
}
__name(decode$1, "decode$1");
function decodeStrict(data, options2 = EntityLevel.XML) {
  var _a2;
  const opts = typeof options2 === "number" ? { level: options2 } : options2;
  (_a2 = opts.mode) !== null && _a2 !== void 0 ? _a2 : opts.mode = DecodingMode.Strict;
  return decode$1(data, opts);
}
__name(decodeStrict, "decodeStrict");
function encode$1(data, options2 = EntityLevel.XML) {
  const opts = typeof options2 === "number" ? { level: options2 } : options2;
  if (opts.mode === EncodingMode.UTF8)
    return escapeUTF8(data);
  if (opts.mode === EncodingMode.Attribute)
    return escapeAttribute(data);
  if (opts.mode === EncodingMode.Text)
    return escapeText(data);
  if (opts.level === EntityLevel.HTML) {
    if (opts.mode === EncodingMode.ASCII) {
      return encodeNonAsciiHTML(data);
    }
    return encodeHTML(data);
  }
  return encodeXML(data);
}
__name(encode$1, "encode$1");
function _class$1(obj) {
  return Object.prototype.toString.call(obj);
}
__name(_class$1, "_class$1");
function isString$2(obj) {
  return _class$1(obj) === "[object String]";
}
__name(isString$2, "isString$2");
const _hasOwnProperty = Object.prototype.hasOwnProperty;
function has(object, key) {
  return _hasOwnProperty.call(object, key);
}
__name(has, "has");
function assign$1(obj) {
  const sources = Array.prototype.slice.call(arguments, 1);
  sources.forEach(function(source) {
    if (!source) {
      return;
    }
    if (typeof source !== "object") {
      throw new TypeError(source + "must be object");
    }
    Object.keys(source).forEach(function(key) {
      obj[key] = source[key];
    });
  });
  return obj;
}
__name(assign$1, "assign$1");
function arrayReplaceAt(src, pos, newElements) {
  return [].concat(src.slice(0, pos), newElements, src.slice(pos + 1));
}
__name(arrayReplaceAt, "arrayReplaceAt");
function isValidEntityCode(c2) {
  if (c2 >= 55296 && c2 <= 57343) {
    return false;
  }
  if (c2 >= 64976 && c2 <= 65007) {
    return false;
  }
  if ((c2 & 65535) === 65535 || (c2 & 65535) === 65534) {
    return false;
  }
  if (c2 >= 0 && c2 <= 8) {
    return false;
  }
  if (c2 === 11) {
    return false;
  }
  if (c2 >= 14 && c2 <= 31) {
    return false;
  }
  if (c2 >= 127 && c2 <= 159) {
    return false;
  }
  if (c2 > 1114111) {
    return false;
  }
  return true;
}
__name(isValidEntityCode, "isValidEntityCode");
function fromCodePoint(c2) {
  if (c2 > 65535) {
    c2 -= 65536;
    const surrogate1 = 55296 + (c2 >> 10);
    const surrogate2 = 56320 + (c2 & 1023);
    return String.fromCharCode(surrogate1, surrogate2);
  }
  return String.fromCharCode(c2);
}
__name(fromCodePoint, "fromCodePoint");
const UNESCAPE_MD_RE = /\\([!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~])/g;
const ENTITY_RE = /&([a-z#][a-z0-9]{1,31});/gi;
const UNESCAPE_ALL_RE = new RegExp(UNESCAPE_MD_RE.source + "|" + ENTITY_RE.source, "gi");
const DIGITAL_ENTITY_TEST_RE = /^#((?:x[a-f0-9]{1,8}|[0-9]{1,8}))$/i;
function replaceEntityPattern(match2, name2) {
  if (name2.charCodeAt(0) === 35 && DIGITAL_ENTITY_TEST_RE.test(name2)) {
    const code2 = name2[1].toLowerCase() === "x" ? parseInt(name2.slice(2), 16) : parseInt(name2.slice(1), 10);
    if (isValidEntityCode(code2)) {
      return fromCodePoint(code2);
    }
    return match2;
  }
  const decoded = decodeHTML(match2);
  if (decoded !== match2) {
    return decoded;
  }
  return match2;
}
__name(replaceEntityPattern, "replaceEntityPattern");
function unescapeMd(str) {
  if (str.indexOf("\\") < 0) {
    return str;
  }
  return str.replace(UNESCAPE_MD_RE, "$1");
}
__name(unescapeMd, "unescapeMd");
function unescapeAll(str) {
  if (str.indexOf("\\") < 0 && str.indexOf("&") < 0) {
    return str;
  }
  return str.replace(UNESCAPE_ALL_RE, function(match2, escaped, entity2) {
    if (escaped) {
      return escaped;
    }
    return replaceEntityPattern(match2, entity2);
  });
}
__name(unescapeAll, "unescapeAll");
const HTML_ESCAPE_TEST_RE = /[&<>"]/;
const HTML_ESCAPE_REPLACE_RE = /[&<>"]/g;
const HTML_REPLACEMENTS = {
  "&": "&amp;",
  "<": "&lt;",
  ">": "&gt;",
  '"': "&quot;"
};
function replaceUnsafeChar(ch) {
  return HTML_REPLACEMENTS[ch];
}
__name(replaceUnsafeChar, "replaceUnsafeChar");
function escapeHtml(str) {
  if (HTML_ESCAPE_TEST_RE.test(str)) {
    return str.replace(HTML_ESCAPE_REPLACE_RE, replaceUnsafeChar);
  }
  return str;
}
__name(escapeHtml, "escapeHtml");
const REGEXP_ESCAPE_RE = /[.?*+^$[\]\\(){}|-]/g;
function escapeRE$1(str) {
  return str.replace(REGEXP_ESCAPE_RE, "\\$&");
}
__name(escapeRE$1, "escapeRE$1");
function isSpace(code2) {
  switch (code2) {
    case 9:
    case 32:
      return true;
  }
  return false;
}
__name(isSpace, "isSpace");
function isWhiteSpace(code2) {
  if (code2 >= 8192 && code2 <= 8202) {
    return true;
  }
  switch (code2) {
    case 9:
    case 10:
    case 11:
    case 12:
    case 13:
    case 32:
    case 160:
    case 5760:
    case 8239:
    case 8287:
    case 12288:
      return true;
  }
  return false;
}
__name(isWhiteSpace, "isWhiteSpace");
function isPunctChar(ch) {
  return P.test(ch) || regex.test(ch);
}
__name(isPunctChar, "isPunctChar");
function isMdAsciiPunct(ch) {
  switch (ch) {
    case 33:
    case 34:
    case 35:
    case 36:
    case 37:
    case 38:
    case 39:
    case 40:
    case 41:
    case 42:
    case 43:
    case 44:
    case 45:
    case 46:
    case 47:
    case 58:
    case 59:
    case 60:
    case 61:
    case 62:
    case 63:
    case 64:
    case 91:
    case 92:
    case 93:
    case 94:
    case 95:
    case 96:
    case 123:
    case 124:
    case 125:
    case 126:
      return true;
    default:
      return false;
  }
}
__name(isMdAsciiPunct, "isMdAsciiPunct");
function normalizeReference(str) {
  str = str.trim().replace(/\s+/g, " ");
  if ("ẞ".toLowerCase() === "Ṿ") {
    str = str.replace(/ẞ/g, "ß");
  }
  return str.toLowerCase().toUpperCase();
}
__name(normalizeReference, "normalizeReference");
const lib = { mdurl, ucmicro };
const utils = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  arrayReplaceAt,
  assign: assign$1,
  escapeHtml,
  escapeRE: escapeRE$1,
  fromCodePoint,
  has,
  isMdAsciiPunct,
  isPunctChar,
  isSpace,
  isString: isString$2,
  isValidEntityCode,
  isWhiteSpace,
  lib,
  normalizeReference,
  unescapeAll,
  unescapeMd
}, Symbol.toStringTag, { value: "Module" }));
function parseLinkLabel(state, start2, disableNested) {
  let level, found2, marker, prevPos;
  const max = state.posMax;
  const oldPos = state.pos;
  state.pos = start2 + 1;
  level = 1;
  while (state.pos < max) {
    marker = state.src.charCodeAt(state.pos);
    if (marker === 93) {
      level--;
      if (level === 0) {
        found2 = true;
        break;
      }
    }
    prevPos = state.pos;
    state.md.inline.skipToken(state);
    if (marker === 91) {
      if (prevPos === state.pos - 1) {
        level++;
      } else if (disableNested) {
        state.pos = oldPos;
        return -1;
      }
    }
  }
  let labelEnd = -1;
  if (found2) {
    labelEnd = state.pos;
  }
  state.pos = oldPos;
  return labelEnd;
}
__name(parseLinkLabel, "parseLinkLabel");
function parseLinkDestination(str, start2, max) {
  let code2;
  let pos = start2;
  const result = {
    ok: false,
    pos: 0,
    str: ""
  };
  if (str.charCodeAt(pos) === 60) {
    pos++;
    while (pos < max) {
      code2 = str.charCodeAt(pos);
      if (code2 === 10) {
        return result;
      }
      if (code2 === 60) {
        return result;
      }
      if (code2 === 62) {
        result.pos = pos + 1;
        result.str = unescapeAll(str.slice(start2 + 1, pos));
        result.ok = true;
        return result;
      }
      if (code2 === 92 && pos + 1 < max) {
        pos += 2;
        continue;
      }
      pos++;
    }
    return result;
  }
  let level = 0;
  while (pos < max) {
    code2 = str.charCodeAt(pos);
    if (code2 === 32) {
      break;
    }
    if (code2 < 32 || code2 === 127) {
      break;
    }
    if (code2 === 92 && pos + 1 < max) {
      if (str.charCodeAt(pos + 1) === 32) {
        break;
      }
      pos += 2;
      continue;
    }
    if (code2 === 40) {
      level++;
      if (level > 32) {
        return result;
      }
    }
    if (code2 === 41) {
      if (level === 0) {
        break;
      }
      level--;
    }
    pos++;
  }
  if (start2 === pos) {
    return result;
  }
  if (level !== 0) {
    return result;
  }
  result.str = unescapeAll(str.slice(start2, pos));
  result.pos = pos;
  result.ok = true;
  return result;
}
__name(parseLinkDestination, "parseLinkDestination");
function parseLinkTitle(str, start2, max, prev_state) {
  let code2;
  let pos = start2;
  const state = {
    // if `true`, this is a valid link title
    ok: false,
    // if `true`, this link can be continued on the next line
    can_continue: false,
    // if `ok`, it's the position of the first character after the closing marker
    pos: 0,
    // if `ok`, it's the unescaped title
    str: "",
    // expected closing marker character code
    marker: 0
  };
  if (prev_state) {
    state.str = prev_state.str;
    state.marker = prev_state.marker;
  } else {
    if (pos >= max) {
      return state;
    }
    let marker = str.charCodeAt(pos);
    if (marker !== 34 && marker !== 39 && marker !== 40) {
      return state;
    }
    start2++;
    pos++;
    if (marker === 40) {
      marker = 41;
    }
    state.marker = marker;
  }
  while (pos < max) {
    code2 = str.charCodeAt(pos);
    if (code2 === state.marker) {
      state.pos = pos + 1;
      state.str += unescapeAll(str.slice(start2, pos));
      state.ok = true;
      return state;
    } else if (code2 === 40 && state.marker === 41) {
      return state;
    } else if (code2 === 92 && pos + 1 < max) {
      pos++;
    }
    pos++;
  }
  state.can_continue = true;
  state.str += unescapeAll(str.slice(start2, pos));
  return state;
}
__name(parseLinkTitle, "parseLinkTitle");
const helpers = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  parseLinkDestination,
  parseLinkLabel,
  parseLinkTitle
}, Symbol.toStringTag, { value: "Module" }));
const default_rules = {};
default_rules.code_inline = function(tokens, idx, options2, env, slf) {
  const token = tokens[idx];
  return "<code" + slf.renderAttrs(token) + ">" + escapeHtml(token.content) + "</code>";
};
default_rules.code_block = function(tokens, idx, options2, env, slf) {
  const token = tokens[idx];
  return "<pre" + slf.renderAttrs(token) + "><code>" + escapeHtml(tokens[idx].content) + "</code></pre>\n";
};
default_rules.fence = function(tokens, idx, options2, env, slf) {
  const token = tokens[idx];
  const info = token.info ? unescapeAll(token.info).trim() : "";
  let langName = "";
  let langAttrs = "";
  if (info) {
    const arr = info.split(/(\s+)/g);
    langName = arr[0];
    langAttrs = arr.slice(2).join("");
  }
  let highlighted;
  if (options2.highlight) {
    highlighted = options2.highlight(token.content, langName, langAttrs) || escapeHtml(token.content);
  } else {
    highlighted = escapeHtml(token.content);
  }
  if (highlighted.indexOf("<pre") === 0) {
    return highlighted + "\n";
  }
  if (info) {
    const i2 = token.attrIndex("class");
    const tmpAttrs = token.attrs ? token.attrs.slice() : [];
    if (i2 < 0) {
      tmpAttrs.push(["class", options2.langPrefix + langName]);
    } else {
      tmpAttrs[i2] = tmpAttrs[i2].slice();
      tmpAttrs[i2][1] += " " + options2.langPrefix + langName;
    }
    const tmpToken = {
      attrs: tmpAttrs
    };
    return `<pre><code${slf.renderAttrs(tmpToken)}>${highlighted}</code></pre>
`;
  }
  return `<pre><code${slf.renderAttrs(token)}>${highlighted}</code></pre>
`;
};
default_rules.image = function(tokens, idx, options2, env, slf) {
  const token = tokens[idx];
  token.attrs[token.attrIndex("alt")][1] = slf.renderInlineAsText(token.children, options2, env);
  return slf.renderToken(tokens, idx, options2);
};
default_rules.hardbreak = function(tokens, idx, options2) {
  return options2.xhtmlOut ? "<br />\n" : "<br>\n";
};
default_rules.softbreak = function(tokens, idx, options2) {
  return options2.breaks ? options2.xhtmlOut ? "<br />\n" : "<br>\n" : "\n";
};
default_rules.text = function(tokens, idx) {
  return escapeHtml(tokens[idx].content);
};
default_rules.html_block = function(tokens, idx) {
  return tokens[idx].content;
};
default_rules.html_inline = function(tokens, idx) {
  return tokens[idx].content;
};
function Renderer() {
  this.rules = assign$1({}, default_rules);
}
__name(Renderer, "Renderer");
Renderer.prototype.renderAttrs = /* @__PURE__ */ __name(function renderAttrs(token) {
  let i2, l2, result;
  if (!token.attrs) {
    return "";
  }
  result = "";
  for (i2 = 0, l2 = token.attrs.length; i2 < l2; i2++) {
    result += " " + escapeHtml(token.attrs[i2][0]) + '="' + escapeHtml(token.attrs[i2][1]) + '"';
  }
  return result;
}, "renderAttrs");
Renderer.prototype.renderToken = /* @__PURE__ */ __name(function renderToken(tokens, idx, options2) {
  const token = tokens[idx];
  let result = "";
  if (token.hidden) {
    return "";
  }
  if (token.block && token.nesting !== -1 && idx && tokens[idx - 1].hidden) {
    result += "\n";
  }
  result += (token.nesting === -1 ? "</" : "<") + token.tag;
  result += this.renderAttrs(token);
  if (token.nesting === 0 && options2.xhtmlOut) {
    result += " /";
  }
  let needLf = false;
  if (token.block) {
    needLf = true;
    if (token.nesting === 1) {
      if (idx + 1 < tokens.length) {
        const nextToken = tokens[idx + 1];
        if (nextToken.type === "inline" || nextToken.hidden) {
          needLf = false;
        } else if (nextToken.nesting === -1 && nextToken.tag === token.tag) {
          needLf = false;
        }
      }
    }
  }
  result += needLf ? ">\n" : ">";
  return result;
}, "renderToken");
Renderer.prototype.renderInline = function(tokens, options2, env) {
  let result = "";
  const rules = this.rules;
  for (let i2 = 0, len = tokens.length; i2 < len; i2++) {
    const type = tokens[i2].type;
    if (typeof rules[type] !== "undefined") {
      result += rules[type](tokens, i2, options2, env, this);
    } else {
      result += this.renderToken(tokens, i2, options2);
    }
  }
  return result;
};
Renderer.prototype.renderInlineAsText = function(tokens, options2, env) {
  let result = "";
  for (let i2 = 0, len = tokens.length; i2 < len; i2++) {
    switch (tokens[i2].type) {
      case "text":
        result += tokens[i2].content;
        break;
      case "image":
        result += this.renderInlineAsText(tokens[i2].children, options2, env);
        break;
      case "html_inline":
      case "html_block":
        result += tokens[i2].content;
        break;
      case "softbreak":
      case "hardbreak":
        result += "\n";
        break;
      default:
    }
  }
  return result;
};
Renderer.prototype.render = function(tokens, options2, env) {
  let result = "";
  const rules = this.rules;
  for (let i2 = 0, len = tokens.length; i2 < len; i2++) {
    const type = tokens[i2].type;
    if (type === "inline") {
      result += this.renderInline(tokens[i2].children, options2, env);
    } else if (typeof rules[type] !== "undefined") {
      result += rules[type](tokens, i2, options2, env, this);
    } else {
      result += this.renderToken(tokens, i2, options2, env);
    }
  }
  return result;
};
function Ruler() {
  this.__rules__ = [];
  this.__cache__ = null;
}
__name(Ruler, "Ruler");
Ruler.prototype.__find__ = function(name2) {
  for (let i2 = 0; i2 < this.__rules__.length; i2++) {
    if (this.__rules__[i2].name === name2) {
      return i2;
    }
  }
  return -1;
};
Ruler.prototype.__compile__ = function() {
  const self2 = this;
  const chains = [""];
  self2.__rules__.forEach(function(rule) {
    if (!rule.enabled) {
      return;
    }
    rule.alt.forEach(function(altName) {
      if (chains.indexOf(altName) < 0) {
        chains.push(altName);
      }
    });
  });
  self2.__cache__ = {};
  chains.forEach(function(chain) {
    self2.__cache__[chain] = [];
    self2.__rules__.forEach(function(rule) {
      if (!rule.enabled) {
        return;
      }
      if (chain && rule.alt.indexOf(chain) < 0) {
        return;
      }
      self2.__cache__[chain].push(rule.fn);
    });
  });
};
Ruler.prototype.at = function(name2, fn, options2) {
  const index2 = this.__find__(name2);
  const opt = options2 || {};
  if (index2 === -1) {
    throw new Error("Parser rule not found: " + name2);
  }
  this.__rules__[index2].fn = fn;
  this.__rules__[index2].alt = opt.alt || [];
  this.__cache__ = null;
};
Ruler.prototype.before = function(beforeName, ruleName, fn, options2) {
  const index2 = this.__find__(beforeName);
  const opt = options2 || {};
  if (index2 === -1) {
    throw new Error("Parser rule not found: " + beforeName);
  }
  this.__rules__.splice(index2, 0, {
    name: ruleName,
    enabled: true,
    fn,
    alt: opt.alt || []
  });
  this.__cache__ = null;
};
Ruler.prototype.after = function(afterName, ruleName, fn, options2) {
  const index2 = this.__find__(afterName);
  const opt = options2 || {};
  if (index2 === -1) {
    throw new Error("Parser rule not found: " + afterName);
  }
  this.__rules__.splice(index2 + 1, 0, {
    name: ruleName,
    enabled: true,
    fn,
    alt: opt.alt || []
  });
  this.__cache__ = null;
};
Ruler.prototype.push = function(ruleName, fn, options2) {
  const opt = options2 || {};
  this.__rules__.push({
    name: ruleName,
    enabled: true,
    fn,
    alt: opt.alt || []
  });
  this.__cache__ = null;
};
Ruler.prototype.enable = function(list2, ignoreInvalid) {
  if (!Array.isArray(list2)) {
    list2 = [list2];
  }
  const result = [];
  list2.forEach(function(name2) {
    const idx = this.__find__(name2);
    if (idx < 0) {
      if (ignoreInvalid) {
        return;
      }
      throw new Error("Rules manager: invalid rule name " + name2);
    }
    this.__rules__[idx].enabled = true;
    result.push(name2);
  }, this);
  this.__cache__ = null;
  return result;
};
Ruler.prototype.enableOnly = function(list2, ignoreInvalid) {
  if (!Array.isArray(list2)) {
    list2 = [list2];
  }
  this.__rules__.forEach(function(rule) {
    rule.enabled = false;
  });
  this.enable(list2, ignoreInvalid);
};
Ruler.prototype.disable = function(list2, ignoreInvalid) {
  if (!Array.isArray(list2)) {
    list2 = [list2];
  }
  const result = [];
  list2.forEach(function(name2) {
    const idx = this.__find__(name2);
    if (idx < 0) {
      if (ignoreInvalid) {
        return;
      }
      throw new Error("Rules manager: invalid rule name " + name2);
    }
    this.__rules__[idx].enabled = false;
    result.push(name2);
  }, this);
  this.__cache__ = null;
  return result;
};
Ruler.prototype.getRules = function(chainName) {
  if (this.__cache__ === null) {
    this.__compile__();
  }
  return this.__cache__[chainName] || [];
};
function Token(type, tag, nesting) {
  this.type = type;
  this.tag = tag;
  this.attrs = null;
  this.map = null;
  this.nesting = nesting;
  this.level = 0;
  this.children = null;
  this.content = "";
  this.markup = "";
  this.info = "";
  this.meta = null;
  this.block = false;
  this.hidden = false;
}
__name(Token, "Token");
Token.prototype.attrIndex = /* @__PURE__ */ __name(function attrIndex(name2) {
  if (!this.attrs) {
    return -1;
  }
  const attrs2 = this.attrs;
  for (let i2 = 0, len = attrs2.length; i2 < len; i2++) {
    if (attrs2[i2][0] === name2) {
      return i2;
    }
  }
  return -1;
}, "attrIndex");
Token.prototype.attrPush = /* @__PURE__ */ __name(function attrPush(attrData) {
  if (this.attrs) {
    this.attrs.push(attrData);
  } else {
    this.attrs = [attrData];
  }
}, "attrPush");
Token.prototype.attrSet = /* @__PURE__ */ __name(function attrSet2(name2, value) {
  const idx = this.attrIndex(name2);
  const attrData = [name2, value];
  if (idx < 0) {
    this.attrPush(attrData);
  } else {
    this.attrs[idx] = attrData;
  }
}, "attrSet");
Token.prototype.attrGet = /* @__PURE__ */ __name(function attrGet(name2) {
  const idx = this.attrIndex(name2);
  let value = null;
  if (idx >= 0) {
    value = this.attrs[idx][1];
  }
  return value;
}, "attrGet");
Token.prototype.attrJoin = /* @__PURE__ */ __name(function attrJoin(name2, value) {
  const idx = this.attrIndex(name2);
  if (idx < 0) {
    this.attrPush([name2, value]);
  } else {
    this.attrs[idx][1] = this.attrs[idx][1] + " " + value;
  }
}, "attrJoin");
function StateCore(src, md2, env) {
  this.src = src;
  this.env = env;
  this.tokens = [];
  this.inlineMode = false;
  this.md = md2;
}
__name(StateCore, "StateCore");
StateCore.prototype.Token = Token;
const NEWLINES_RE = /\r\n?|\n/g;
const NULL_RE = /\0/g;
function normalize(state) {
  let str;
  str = state.src.replace(NEWLINES_RE, "\n");
  str = str.replace(NULL_RE, "�");
  state.src = str;
}
__name(normalize, "normalize");
function block(state) {
  let token;
  if (state.inlineMode) {
    token = new state.Token("inline", "", 0);
    token.content = state.src;
    token.map = [0, 1];
    token.children = [];
    state.tokens.push(token);
  } else {
    state.md.block.parse(state.src, state.md, state.env, state.tokens);
  }
}
__name(block, "block");
function inline(state) {
  const tokens = state.tokens;
  for (let i2 = 0, l2 = tokens.length; i2 < l2; i2++) {
    const tok = tokens[i2];
    if (tok.type === "inline") {
      state.md.inline.parse(tok.content, state.md, state.env, tok.children);
    }
  }
}
__name(inline, "inline");
function isLinkOpen$1(str) {
  return /^<a[>\s]/i.test(str);
}
__name(isLinkOpen$1, "isLinkOpen$1");
function isLinkClose$1(str) {
  return /^<\/a\s*>/i.test(str);
}
__name(isLinkClose$1, "isLinkClose$1");
function linkify$1(state) {
  const blockTokens = state.tokens;
  if (!state.md.options.linkify) {
    return;
  }
  for (let j2 = 0, l2 = blockTokens.length; j2 < l2; j2++) {
    if (blockTokens[j2].type !== "inline" || !state.md.linkify.pretest(blockTokens[j2].content)) {
      continue;
    }
    let tokens = blockTokens[j2].children;
    let htmlLinkLevel = 0;
    for (let i2 = tokens.length - 1; i2 >= 0; i2--) {
      const currentToken = tokens[i2];
      if (currentToken.type === "link_close") {
        i2--;
        while (tokens[i2].level !== currentToken.level && tokens[i2].type !== "link_open") {
          i2--;
        }
        continue;
      }
      if (currentToken.type === "html_inline") {
        if (isLinkOpen$1(currentToken.content) && htmlLinkLevel > 0) {
          htmlLinkLevel--;
        }
        if (isLinkClose$1(currentToken.content)) {
          htmlLinkLevel++;
        }
      }
      if (htmlLinkLevel > 0) {
        continue;
      }
      if (currentToken.type === "text" && state.md.linkify.test(currentToken.content)) {
        const text2 = currentToken.content;
        let links = state.md.linkify.match(text2);
        const nodes = [];
        let level = currentToken.level;
        let lastPos = 0;
        if (links.length > 0 && links[0].index === 0 && i2 > 0 && tokens[i2 - 1].type === "text_special") {
          links = links.slice(1);
        }
        for (let ln = 0; ln < links.length; ln++) {
          const url = links[ln].url;
          const fullUrl = state.md.normalizeLink(url);
          if (!state.md.validateLink(fullUrl)) {
            continue;
          }
          let urlText = links[ln].text;
          if (!links[ln].schema) {
            urlText = state.md.normalizeLinkText("http://" + urlText).replace(/^http:\/\//, "");
          } else if (links[ln].schema === "mailto:" && !/^mailto:/i.test(urlText)) {
            urlText = state.md.normalizeLinkText("mailto:" + urlText).replace(/^mailto:/, "");
          } else {
            urlText = state.md.normalizeLinkText(urlText);
          }
          const pos = links[ln].index;
          if (pos > lastPos) {
            const token = new state.Token("text", "", 0);
            token.content = text2.slice(lastPos, pos);
            token.level = level;
            nodes.push(token);
          }
          const token_o = new state.Token("link_open", "a", 1);
          token_o.attrs = [["href", fullUrl]];
          token_o.level = level++;
          token_o.markup = "linkify";
          token_o.info = "auto";
          nodes.push(token_o);
          const token_t = new state.Token("text", "", 0);
          token_t.content = urlText;
          token_t.level = level;
          nodes.push(token_t);
          const token_c = new state.Token("link_close", "a", -1);
          token_c.level = --level;
          token_c.markup = "linkify";
          token_c.info = "auto";
          nodes.push(token_c);
          lastPos = links[ln].lastIndex;
        }
        if (lastPos < text2.length) {
          const token = new state.Token("text", "", 0);
          token.content = text2.slice(lastPos);
          token.level = level;
          nodes.push(token);
        }
        blockTokens[j2].children = tokens = arrayReplaceAt(tokens, i2, nodes);
      }
    }
  }
}
__name(linkify$1, "linkify$1");
const RARE_RE = /\+-|\.\.|\?\?\?\?|!!!!|,,|--/;
const SCOPED_ABBR_TEST_RE = /\((c|tm|r)\)/i;
const SCOPED_ABBR_RE = /\((c|tm|r)\)/ig;
const SCOPED_ABBR = {
  c: "©",
  r: "®",
  tm: "™"
};
function replaceFn(match2, name2) {
  return SCOPED_ABBR[name2.toLowerCase()];
}
__name(replaceFn, "replaceFn");
function replace_scoped(inlineTokens) {
  let inside_autolink = 0;
  for (let i2 = inlineTokens.length - 1; i2 >= 0; i2--) {
    const token = inlineTokens[i2];
    if (token.type === "text" && !inside_autolink) {
      token.content = token.content.replace(SCOPED_ABBR_RE, replaceFn);
    }
    if (token.type === "link_open" && token.info === "auto") {
      inside_autolink--;
    }
    if (token.type === "link_close" && token.info === "auto") {
      inside_autolink++;
    }
  }
}
__name(replace_scoped, "replace_scoped");
function replace_rare(inlineTokens) {
  let inside_autolink = 0;
  for (let i2 = inlineTokens.length - 1; i2 >= 0; i2--) {
    const token = inlineTokens[i2];
    if (token.type === "text" && !inside_autolink) {
      if (RARE_RE.test(token.content)) {
        token.content = token.content.replace(/\+-/g, "±").replace(/\.{2,}/g, "…").replace(/([?!])…/g, "$1..").replace(/([?!]){4,}/g, "$1$1$1").replace(/,{2,}/g, ",").replace(/(^|[^-])---(?=[^-]|$)/mg, "$1—").replace(/(^|\s)--(?=\s|$)/mg, "$1–").replace(/(^|[^-\s])--(?=[^-\s]|$)/mg, "$1–");
      }
    }
    if (token.type === "link_open" && token.info === "auto") {
      inside_autolink--;
    }
    if (token.type === "link_close" && token.info === "auto") {
      inside_autolink++;
    }
  }
}
__name(replace_rare, "replace_rare");
function replace(state) {
  let blkIdx;
  if (!state.md.options.typographer) {
    return;
  }
  for (blkIdx = state.tokens.length - 1; blkIdx >= 0; blkIdx--) {
    if (state.tokens[blkIdx].type !== "inline") {
      continue;
    }
    if (SCOPED_ABBR_TEST_RE.test(state.tokens[blkIdx].content)) {
      replace_scoped(state.tokens[blkIdx].children);
    }
    if (RARE_RE.test(state.tokens[blkIdx].content)) {
      replace_rare(state.tokens[blkIdx].children);
    }
  }
}
__name(replace, "replace");
const QUOTE_TEST_RE = /['"]/;
const QUOTE_RE = /['"]/g;
const APOSTROPHE = "’";
function replaceAt(str, index2, ch) {
  return str.slice(0, index2) + ch + str.slice(index2 + 1);
}
__name(replaceAt, "replaceAt");
function process_inlines(tokens, state) {
  let j2;
  const stack = [];
  for (let i2 = 0; i2 < tokens.length; i2++) {
    const token = tokens[i2];
    const thisLevel = tokens[i2].level;
    for (j2 = stack.length - 1; j2 >= 0; j2--) {
      if (stack[j2].level <= thisLevel) {
        break;
      }
    }
    stack.length = j2 + 1;
    if (token.type !== "text") {
      continue;
    }
    let text2 = token.content;
    let pos = 0;
    let max = text2.length;
    OUTER:
      while (pos < max) {
        QUOTE_RE.lastIndex = pos;
        const t2 = QUOTE_RE.exec(text2);
        if (!t2) {
          break;
        }
        let canOpen = true;
        let canClose = true;
        pos = t2.index + 1;
        const isSingle = t2[0] === "'";
        let lastChar = 32;
        if (t2.index - 1 >= 0) {
          lastChar = text2.charCodeAt(t2.index - 1);
        } else {
          for (j2 = i2 - 1; j2 >= 0; j2--) {
            if (tokens[j2].type === "softbreak" || tokens[j2].type === "hardbreak") break;
            if (!tokens[j2].content) continue;
            lastChar = tokens[j2].content.charCodeAt(tokens[j2].content.length - 1);
            break;
          }
        }
        let nextChar = 32;
        if (pos < max) {
          nextChar = text2.charCodeAt(pos);
        } else {
          for (j2 = i2 + 1; j2 < tokens.length; j2++) {
            if (tokens[j2].type === "softbreak" || tokens[j2].type === "hardbreak") break;
            if (!tokens[j2].content) continue;
            nextChar = tokens[j2].content.charCodeAt(0);
            break;
          }
        }
        const isLastPunctChar = isMdAsciiPunct(lastChar) || isPunctChar(String.fromCharCode(lastChar));
        const isNextPunctChar = isMdAsciiPunct(nextChar) || isPunctChar(String.fromCharCode(nextChar));
        const isLastWhiteSpace = isWhiteSpace(lastChar);
        const isNextWhiteSpace = isWhiteSpace(nextChar);
        if (isNextWhiteSpace) {
          canOpen = false;
        } else if (isNextPunctChar) {
          if (!(isLastWhiteSpace || isLastPunctChar)) {
            canOpen = false;
          }
        }
        if (isLastWhiteSpace) {
          canClose = false;
        } else if (isLastPunctChar) {
          if (!(isNextWhiteSpace || isNextPunctChar)) {
            canClose = false;
          }
        }
        if (nextChar === 34 && t2[0] === '"') {
          if (lastChar >= 48 && lastChar <= 57) {
            canClose = canOpen = false;
          }
        }
        if (canOpen && canClose) {
          canOpen = isLastPunctChar;
          canClose = isNextPunctChar;
        }
        if (!canOpen && !canClose) {
          if (isSingle) {
            token.content = replaceAt(token.content, t2.index, APOSTROPHE);
          }
          continue;
        }
        if (canClose) {
          for (j2 = stack.length - 1; j2 >= 0; j2--) {
            let item = stack[j2];
            if (stack[j2].level < thisLevel) {
              break;
            }
            if (item.single === isSingle && stack[j2].level === thisLevel) {
              item = stack[j2];
              let openQuote;
              let closeQuote;
              if (isSingle) {
                openQuote = state.md.options.quotes[2];
                closeQuote = state.md.options.quotes[3];
              } else {
                openQuote = state.md.options.quotes[0];
                closeQuote = state.md.options.quotes[1];
              }
              token.content = replaceAt(token.content, t2.index, closeQuote);
              tokens[item.token].content = replaceAt(
                tokens[item.token].content,
                item.pos,
                openQuote
              );
              pos += closeQuote.length - 1;
              if (item.token === i2) {
                pos += openQuote.length - 1;
              }
              text2 = token.content;
              max = text2.length;
              stack.length = j2;
              continue OUTER;
            }
          }
        }
        if (canOpen) {
          stack.push({
            token: i2,
            pos: t2.index,
            single: isSingle,
            level: thisLevel
          });
        } else if (canClose && isSingle) {
          token.content = replaceAt(token.content, t2.index, APOSTROPHE);
        }
      }
  }
}
__name(process_inlines, "process_inlines");
function smartquotes(state) {
  if (!state.md.options.typographer) {
    return;
  }
  for (let blkIdx = state.tokens.length - 1; blkIdx >= 0; blkIdx--) {
    if (state.tokens[blkIdx].type !== "inline" || !QUOTE_TEST_RE.test(state.tokens[blkIdx].content)) {
      continue;
    }
    process_inlines(state.tokens[blkIdx].children, state);
  }
}
__name(smartquotes, "smartquotes");
function text_join(state) {
  let curr, last;
  const blockTokens = state.tokens;
  const l2 = blockTokens.length;
  for (let j2 = 0; j2 < l2; j2++) {
    if (blockTokens[j2].type !== "inline") continue;
    const tokens = blockTokens[j2].children;
    const max = tokens.length;
    for (curr = 0; curr < max; curr++) {
      if (tokens[curr].type === "text_special") {
        tokens[curr].type = "text";
      }
    }
    for (curr = last = 0; curr < max; curr++) {
      if (tokens[curr].type === "text" && curr + 1 < max && tokens[curr + 1].type === "text") {
        tokens[curr + 1].content = tokens[curr].content + tokens[curr + 1].content;
      } else {
        if (curr !== last) {
          tokens[last] = tokens[curr];
        }
        last++;
      }
    }
    if (curr !== last) {
      tokens.length = last;
    }
  }
}
__name(text_join, "text_join");
const _rules$2 = [
  ["normalize", normalize],
  ["block", block],
  ["inline", inline],
  ["linkify", linkify$1],
  ["replacements", replace],
  ["smartquotes", smartquotes],
  // `text_join` finds `text_special` tokens (for escape sequences)
  // and joins them with the rest of the text
  ["text_join", text_join]
];
function Core() {
  this.ruler = new Ruler();
  for (let i2 = 0; i2 < _rules$2.length; i2++) {
    this.ruler.push(_rules$2[i2][0], _rules$2[i2][1]);
  }
}
__name(Core, "Core");
Core.prototype.process = function(state) {
  const rules = this.ruler.getRules("");
  for (let i2 = 0, l2 = rules.length; i2 < l2; i2++) {
    rules[i2](state);
  }
};
Core.prototype.State = StateCore;
function StateBlock(src, md2, env, tokens) {
  this.src = src;
  this.md = md2;
  this.env = env;
  this.tokens = tokens;
  this.bMarks = [];
  this.eMarks = [];
  this.tShift = [];
  this.sCount = [];
  this.bsCount = [];
  this.blkIndent = 0;
  this.line = 0;
  this.lineMax = 0;
  this.tight = false;
  this.ddIndent = -1;
  this.listIndent = -1;
  this.parentType = "root";
  this.level = 0;
  const s2 = this.src;
  for (let start2 = 0, pos = 0, indent = 0, offset = 0, len = s2.length, indent_found = false; pos < len; pos++) {
    const ch = s2.charCodeAt(pos);
    if (!indent_found) {
      if (isSpace(ch)) {
        indent++;
        if (ch === 9) {
          offset += 4 - offset % 4;
        } else {
          offset++;
        }
        continue;
      } else {
        indent_found = true;
      }
    }
    if (ch === 10 || pos === len - 1) {
      if (ch !== 10) {
        pos++;
      }
      this.bMarks.push(start2);
      this.eMarks.push(pos);
      this.tShift.push(indent);
      this.sCount.push(offset);
      this.bsCount.push(0);
      indent_found = false;
      indent = 0;
      offset = 0;
      start2 = pos + 1;
    }
  }
  this.bMarks.push(s2.length);
  this.eMarks.push(s2.length);
  this.tShift.push(0);
  this.sCount.push(0);
  this.bsCount.push(0);
  this.lineMax = this.bMarks.length - 1;
}
__name(StateBlock, "StateBlock");
StateBlock.prototype.push = function(type, tag, nesting) {
  const token = new Token(type, tag, nesting);
  token.block = true;
  if (nesting < 0) this.level--;
  token.level = this.level;
  if (nesting > 0) this.level++;
  this.tokens.push(token);
  return token;
};
StateBlock.prototype.isEmpty = /* @__PURE__ */ __name(function isEmpty2(line) {
  return this.bMarks[line] + this.tShift[line] >= this.eMarks[line];
}, "isEmpty");
StateBlock.prototype.skipEmptyLines = /* @__PURE__ */ __name(function skipEmptyLines(from2) {
  for (let max = this.lineMax; from2 < max; from2++) {
    if (this.bMarks[from2] + this.tShift[from2] < this.eMarks[from2]) {
      break;
    }
  }
  return from2;
}, "skipEmptyLines");
StateBlock.prototype.skipSpaces = /* @__PURE__ */ __name(function skipSpaces(pos) {
  for (let max = this.src.length; pos < max; pos++) {
    const ch = this.src.charCodeAt(pos);
    if (!isSpace(ch)) {
      break;
    }
  }
  return pos;
}, "skipSpaces");
StateBlock.prototype.skipSpacesBack = /* @__PURE__ */ __name(function skipSpacesBack(pos, min) {
  if (pos <= min) {
    return pos;
  }
  while (pos > min) {
    if (!isSpace(this.src.charCodeAt(--pos))) {
      return pos + 1;
    }
  }
  return pos;
}, "skipSpacesBack");
StateBlock.prototype.skipChars = /* @__PURE__ */ __name(function skipChars(pos, code2) {
  for (let max = this.src.length; pos < max; pos++) {
    if (this.src.charCodeAt(pos) !== code2) {
      break;
    }
  }
  return pos;
}, "skipChars");
StateBlock.prototype.skipCharsBack = /* @__PURE__ */ __name(function skipCharsBack(pos, code2, min) {
  if (pos <= min) {
    return pos;
  }
  while (pos > min) {
    if (code2 !== this.src.charCodeAt(--pos)) {
      return pos + 1;
    }
  }
  return pos;
}, "skipCharsBack");
StateBlock.prototype.getLines = /* @__PURE__ */ __name(function getLines(begin, end, indent, keepLastLF) {
  if (begin >= end) {
    return "";
  }
  const queue = new Array(end - begin);
  for (let i2 = 0, line = begin; line < end; line++, i2++) {
    let lineIndent = 0;
    const lineStart = this.bMarks[line];
    let first2 = lineStart;
    let last;
    if (line + 1 < end || keepLastLF) {
      last = this.eMarks[line] + 1;
    } else {
      last = this.eMarks[line];
    }
    while (first2 < last && lineIndent < indent) {
      const ch = this.src.charCodeAt(first2);
      if (isSpace(ch)) {
        if (ch === 9) {
          lineIndent += 4 - (lineIndent + this.bsCount[line]) % 4;
        } else {
          lineIndent++;
        }
      } else if (first2 - lineStart < this.tShift[line]) {
        lineIndent++;
      } else {
        break;
      }
      first2++;
    }
    if (lineIndent > indent) {
      queue[i2] = new Array(lineIndent - indent + 1).join(" ") + this.src.slice(first2, last);
    } else {
      queue[i2] = this.src.slice(first2, last);
    }
  }
  return queue.join("");
}, "getLines");
StateBlock.prototype.Token = Token;
const MAX_AUTOCOMPLETED_CELLS = 65536;
function getLine(state, line) {
  const pos = state.bMarks[line] + state.tShift[line];
  const max = state.eMarks[line];
  return state.src.slice(pos, max);
}
__name(getLine, "getLine");
function escapedSplit(str) {
  const result = [];
  const max = str.length;
  let pos = 0;
  let ch = str.charCodeAt(pos);
  let isEscaped = false;
  let lastPos = 0;
  let current = "";
  while (pos < max) {
    if (ch === 124) {
      if (!isEscaped) {
        result.push(current + str.substring(lastPos, pos));
        current = "";
        lastPos = pos + 1;
      } else {
        current += str.substring(lastPos, pos - 1);
        lastPos = pos;
      }
    }
    isEscaped = ch === 92;
    pos++;
    ch = str.charCodeAt(pos);
  }
  result.push(current + str.substring(lastPos));
  return result;
}
__name(escapedSplit, "escapedSplit");
function table(state, startLine, endLine, silent) {
  if (startLine + 2 > endLine) {
    return false;
  }
  let nextLine = startLine + 1;
  if (state.sCount[nextLine] < state.blkIndent) {
    return false;
  }
  if (state.sCount[nextLine] - state.blkIndent >= 4) {
    return false;
  }
  let pos = state.bMarks[nextLine] + state.tShift[nextLine];
  if (pos >= state.eMarks[nextLine]) {
    return false;
  }
  const firstCh = state.src.charCodeAt(pos++);
  if (firstCh !== 124 && firstCh !== 45 && firstCh !== 58) {
    return false;
  }
  if (pos >= state.eMarks[nextLine]) {
    return false;
  }
  const secondCh = state.src.charCodeAt(pos++);
  if (secondCh !== 124 && secondCh !== 45 && secondCh !== 58 && !isSpace(secondCh)) {
    return false;
  }
  if (firstCh === 45 && isSpace(secondCh)) {
    return false;
  }
  while (pos < state.eMarks[nextLine]) {
    const ch = state.src.charCodeAt(pos);
    if (ch !== 124 && ch !== 45 && ch !== 58 && !isSpace(ch)) {
      return false;
    }
    pos++;
  }
  let lineText = getLine(state, startLine + 1);
  let columns = lineText.split("|");
  const aligns = [];
  for (let i2 = 0; i2 < columns.length; i2++) {
    const t2 = columns[i2].trim();
    if (!t2) {
      if (i2 === 0 || i2 === columns.length - 1) {
        continue;
      } else {
        return false;
      }
    }
    if (!/^:?-+:?$/.test(t2)) {
      return false;
    }
    if (t2.charCodeAt(t2.length - 1) === 58) {
      aligns.push(t2.charCodeAt(0) === 58 ? "center" : "right");
    } else if (t2.charCodeAt(0) === 58) {
      aligns.push("left");
    } else {
      aligns.push("");
    }
  }
  lineText = getLine(state, startLine).trim();
  if (lineText.indexOf("|") === -1) {
    return false;
  }
  if (state.sCount[startLine] - state.blkIndent >= 4) {
    return false;
  }
  columns = escapedSplit(lineText);
  if (columns.length && columns[0] === "") columns.shift();
  if (columns.length && columns[columns.length - 1] === "") columns.pop();
  const columnCount = columns.length;
  if (columnCount === 0 || columnCount !== aligns.length) {
    return false;
  }
  if (silent) {
    return true;
  }
  const oldParentType = state.parentType;
  state.parentType = "table";
  const terminatorRules = state.md.block.ruler.getRules("blockquote");
  const token_to = state.push("table_open", "table", 1);
  const tableLines = [startLine, 0];
  token_to.map = tableLines;
  const token_tho = state.push("thead_open", "thead", 1);
  token_tho.map = [startLine, startLine + 1];
  const token_htro = state.push("tr_open", "tr", 1);
  token_htro.map = [startLine, startLine + 1];
  for (let i2 = 0; i2 < columns.length; i2++) {
    const token_ho = state.push("th_open", "th", 1);
    if (aligns[i2]) {
      token_ho.attrs = [["style", "text-align:" + aligns[i2]]];
    }
    const token_il = state.push("inline", "", 0);
    token_il.content = columns[i2].trim();
    token_il.children = [];
    state.push("th_close", "th", -1);
  }
  state.push("tr_close", "tr", -1);
  state.push("thead_close", "thead", -1);
  let tbodyLines;
  let autocompletedCells = 0;
  for (nextLine = startLine + 2; nextLine < endLine; nextLine++) {
    if (state.sCount[nextLine] < state.blkIndent) {
      break;
    }
    let terminate2 = false;
    for (let i2 = 0, l2 = terminatorRules.length; i2 < l2; i2++) {
      if (terminatorRules[i2](state, nextLine, endLine, true)) {
        terminate2 = true;
        break;
      }
    }
    if (terminate2) {
      break;
    }
    lineText = getLine(state, nextLine).trim();
    if (!lineText) {
      break;
    }
    if (state.sCount[nextLine] - state.blkIndent >= 4) {
      break;
    }
    columns = escapedSplit(lineText);
    if (columns.length && columns[0] === "") columns.shift();
    if (columns.length && columns[columns.length - 1] === "") columns.pop();
    autocompletedCells += columnCount - columns.length;
    if (autocompletedCells > MAX_AUTOCOMPLETED_CELLS) {
      break;
    }
    if (nextLine === startLine + 2) {
      const token_tbo = state.push("tbody_open", "tbody", 1);
      token_tbo.map = tbodyLines = [startLine + 2, 0];
    }
    const token_tro = state.push("tr_open", "tr", 1);
    token_tro.map = [nextLine, nextLine + 1];
    for (let i2 = 0; i2 < columnCount; i2++) {
      const token_tdo = state.push("td_open", "td", 1);
      if (aligns[i2]) {
        token_tdo.attrs = [["style", "text-align:" + aligns[i2]]];
      }
      const token_il = state.push("inline", "", 0);
      token_il.content = columns[i2] ? columns[i2].trim() : "";
      token_il.children = [];
      state.push("td_close", "td", -1);
    }
    state.push("tr_close", "tr", -1);
  }
  if (tbodyLines) {
    state.push("tbody_close", "tbody", -1);
    tbodyLines[1] = nextLine;
  }
  state.push("table_close", "table", -1);
  tableLines[1] = nextLine;
  state.parentType = oldParentType;
  state.line = nextLine;
  return true;
}
__name(table, "table");
function code(state, startLine, endLine) {
  if (state.sCount[startLine] - state.blkIndent < 4) {
    return false;
  }
  let nextLine = startLine + 1;
  let last = nextLine;
  while (nextLine < endLine) {
    if (state.isEmpty(nextLine)) {
      nextLine++;
      continue;
    }
    if (state.sCount[nextLine] - state.blkIndent >= 4) {
      nextLine++;
      last = nextLine;
      continue;
    }
    break;
  }
  state.line = last;
  const token = state.push("code_block", "code", 0);
  token.content = state.getLines(startLine, last, 4 + state.blkIndent, false) + "\n";
  token.map = [startLine, state.line];
  return true;
}
__name(code, "code");
function fence(state, startLine, endLine, silent) {
  let pos = state.bMarks[startLine] + state.tShift[startLine];
  let max = state.eMarks[startLine];
  if (state.sCount[startLine] - state.blkIndent >= 4) {
    return false;
  }
  if (pos + 3 > max) {
    return false;
  }
  const marker = state.src.charCodeAt(pos);
  if (marker !== 126 && marker !== 96) {
    return false;
  }
  let mem = pos;
  pos = state.skipChars(pos, marker);
  let len = pos - mem;
  if (len < 3) {
    return false;
  }
  const markup = state.src.slice(mem, pos);
  const params = state.src.slice(pos, max);
  if (marker === 96) {
    if (params.indexOf(String.fromCharCode(marker)) >= 0) {
      return false;
    }
  }
  if (silent) {
    return true;
  }
  let nextLine = startLine;
  let haveEndMarker = false;
  for (; ; ) {
    nextLine++;
    if (nextLine >= endLine) {
      break;
    }
    pos = mem = state.bMarks[nextLine] + state.tShift[nextLine];
    max = state.eMarks[nextLine];
    if (pos < max && state.sCount[nextLine] < state.blkIndent) {
      break;
    }
    if (state.src.charCodeAt(pos) !== marker) {
      continue;
    }
    if (state.sCount[nextLine] - state.blkIndent >= 4) {
      continue;
    }
    pos = state.skipChars(pos, marker);
    if (pos - mem < len) {
      continue;
    }
    pos = state.skipSpaces(pos);
    if (pos < max) {
      continue;
    }
    haveEndMarker = true;
    break;
  }
  len = state.sCount[startLine];
  state.line = nextLine + (haveEndMarker ? 1 : 0);
  const token = state.push("fence", "code", 0);
  token.info = params;
  token.content = state.getLines(startLine + 1, nextLine, len, true);
  token.markup = markup;
  token.map = [startLine, state.line];
  return true;
}
__name(fence, "fence");
function blockquote(state, startLine, endLine, silent) {
  let pos = state.bMarks[startLine] + state.tShift[startLine];
  let max = state.eMarks[startLine];
  const oldLineMax = state.lineMax;
  if (state.sCount[startLine] - state.blkIndent >= 4) {
    return false;
  }
  if (state.src.charCodeAt(pos) !== 62) {
    return false;
  }
  if (silent) {
    return true;
  }
  const oldBMarks = [];
  const oldBSCount = [];
  const oldSCount = [];
  const oldTShift = [];
  const terminatorRules = state.md.block.ruler.getRules("blockquote");
  const oldParentType = state.parentType;
  state.parentType = "blockquote";
  let lastLineEmpty = false;
  let nextLine;
  for (nextLine = startLine; nextLine < endLine; nextLine++) {
    const isOutdented = state.sCount[nextLine] < state.blkIndent;
    pos = state.bMarks[nextLine] + state.tShift[nextLine];
    max = state.eMarks[nextLine];
    if (pos >= max) {
      break;
    }
    if (state.src.charCodeAt(pos++) === 62 && !isOutdented) {
      let initial = state.sCount[nextLine] + 1;
      let spaceAfterMarker;
      let adjustTab;
      if (state.src.charCodeAt(pos) === 32) {
        pos++;
        initial++;
        adjustTab = false;
        spaceAfterMarker = true;
      } else if (state.src.charCodeAt(pos) === 9) {
        spaceAfterMarker = true;
        if ((state.bsCount[nextLine] + initial) % 4 === 3) {
          pos++;
          initial++;
          adjustTab = false;
        } else {
          adjustTab = true;
        }
      } else {
        spaceAfterMarker = false;
      }
      let offset = initial;
      oldBMarks.push(state.bMarks[nextLine]);
      state.bMarks[nextLine] = pos;
      while (pos < max) {
        const ch = state.src.charCodeAt(pos);
        if (isSpace(ch)) {
          if (ch === 9) {
            offset += 4 - (offset + state.bsCount[nextLine] + (adjustTab ? 1 : 0)) % 4;
          } else {
            offset++;
          }
        } else {
          break;
        }
        pos++;
      }
      lastLineEmpty = pos >= max;
      oldBSCount.push(state.bsCount[nextLine]);
      state.bsCount[nextLine] = state.sCount[nextLine] + 1 + (spaceAfterMarker ? 1 : 0);
      oldSCount.push(state.sCount[nextLine]);
      state.sCount[nextLine] = offset - initial;
      oldTShift.push(state.tShift[nextLine]);
      state.tShift[nextLine] = pos - state.bMarks[nextLine];
      continue;
    }
    if (lastLineEmpty) {
      break;
    }
    let terminate2 = false;
    for (let i2 = 0, l2 = terminatorRules.length; i2 < l2; i2++) {
      if (terminatorRules[i2](state, nextLine, endLine, true)) {
        terminate2 = true;
        break;
      }
    }
    if (terminate2) {
      state.lineMax = nextLine;
      if (state.blkIndent !== 0) {
        oldBMarks.push(state.bMarks[nextLine]);
        oldBSCount.push(state.bsCount[nextLine]);
        oldTShift.push(state.tShift[nextLine]);
        oldSCount.push(state.sCount[nextLine]);
        state.sCount[nextLine] -= state.blkIndent;
      }
      break;
    }
    oldBMarks.push(state.bMarks[nextLine]);
    oldBSCount.push(state.bsCount[nextLine]);
    oldTShift.push(state.tShift[nextLine]);
    oldSCount.push(state.sCount[nextLine]);
    state.sCount[nextLine] = -1;
  }
  const oldIndent = state.blkIndent;
  state.blkIndent = 0;
  const token_o = state.push("blockquote_open", "blockquote", 1);
  token_o.markup = ">";
  const lines = [startLine, 0];
  token_o.map = lines;
  state.md.block.tokenize(state, startLine, nextLine);
  const token_c = state.push("blockquote_close", "blockquote", -1);
  token_c.markup = ">";
  state.lineMax = oldLineMax;
  state.parentType = oldParentType;
  lines[1] = state.line;
  for (let i2 = 0; i2 < oldTShift.length; i2++) {
    state.bMarks[i2 + startLine] = oldBMarks[i2];
    state.tShift[i2 + startLine] = oldTShift[i2];
    state.sCount[i2 + startLine] = oldSCount[i2];
    state.bsCount[i2 + startLine] = oldBSCount[i2];
  }
  state.blkIndent = oldIndent;
  return true;
}
__name(blockquote, "blockquote");
function hr(state, startLine, endLine, silent) {
  const max = state.eMarks[startLine];
  if (state.sCount[startLine] - state.blkIndent >= 4) {
    return false;
  }
  let pos = state.bMarks[startLine] + state.tShift[startLine];
  const marker = state.src.charCodeAt(pos++);
  if (marker !== 42 && marker !== 45 && marker !== 95) {
    return false;
  }
  let cnt = 1;
  while (pos < max) {
    const ch = state.src.charCodeAt(pos++);
    if (ch !== marker && !isSpace(ch)) {
      return false;
    }
    if (ch === marker) {
      cnt++;
    }
  }
  if (cnt < 3) {
    return false;
  }
  if (silent) {
    return true;
  }
  state.line = startLine + 1;
  const token = state.push("hr", "hr", 0);
  token.map = [startLine, state.line];
  token.markup = Array(cnt + 1).join(String.fromCharCode(marker));
  return true;
}
__name(hr, "hr");
function skipBulletListMarker(state, startLine) {
  const max = state.eMarks[startLine];
  let pos = state.bMarks[startLine] + state.tShift[startLine];
  const marker = state.src.charCodeAt(pos++);
  if (marker !== 42 && marker !== 45 && marker !== 43) {
    return -1;
  }
  if (pos < max) {
    const ch = state.src.charCodeAt(pos);
    if (!isSpace(ch)) {
      return -1;
    }
  }
  return pos;
}
__name(skipBulletListMarker, "skipBulletListMarker");
function skipOrderedListMarker(state, startLine) {
  const start2 = state.bMarks[startLine] + state.tShift[startLine];
  const max = state.eMarks[startLine];
  let pos = start2;
  if (pos + 1 >= max) {
    return -1;
  }
  let ch = state.src.charCodeAt(pos++);
  if (ch < 48 || ch > 57) {
    return -1;
  }
  for (; ; ) {
    if (pos >= max) {
      return -1;
    }
    ch = state.src.charCodeAt(pos++);
    if (ch >= 48 && ch <= 57) {
      if (pos - start2 >= 10) {
        return -1;
      }
      continue;
    }
    if (ch === 41 || ch === 46) {
      break;
    }
    return -1;
  }
  if (pos < max) {
    ch = state.src.charCodeAt(pos);
    if (!isSpace(ch)) {
      return -1;
    }
  }
  return pos;
}
__name(skipOrderedListMarker, "skipOrderedListMarker");
function markTightParagraphs(state, idx) {
  const level = state.level + 2;
  for (let i2 = idx + 2, l2 = state.tokens.length - 2; i2 < l2; i2++) {
    if (state.tokens[i2].level === level && state.tokens[i2].type === "paragraph_open") {
      state.tokens[i2 + 2].hidden = true;
      state.tokens[i2].hidden = true;
      i2 += 2;
    }
  }
}
__name(markTightParagraphs, "markTightParagraphs");
function list(state, startLine, endLine, silent) {
  let max, pos, start2, token;
  let nextLine = startLine;
  let tight = true;
  if (state.sCount[nextLine] - state.blkIndent >= 4) {
    return false;
  }
  if (state.listIndent >= 0 && state.sCount[nextLine] - state.listIndent >= 4 && state.sCount[nextLine] < state.blkIndent) {
    return false;
  }
  let isTerminatingParagraph = false;
  if (silent && state.parentType === "paragraph") {
    if (state.sCount[nextLine] >= state.blkIndent) {
      isTerminatingParagraph = true;
    }
  }
  let isOrdered;
  let markerValue;
  let posAfterMarker;
  if ((posAfterMarker = skipOrderedListMarker(state, nextLine)) >= 0) {
    isOrdered = true;
    start2 = state.bMarks[nextLine] + state.tShift[nextLine];
    markerValue = Number(state.src.slice(start2, posAfterMarker - 1));
    if (isTerminatingParagraph && markerValue !== 1) return false;
  } else if ((posAfterMarker = skipBulletListMarker(state, nextLine)) >= 0) {
    isOrdered = false;
  } else {
    return false;
  }
  if (isTerminatingParagraph) {
    if (state.skipSpaces(posAfterMarker) >= state.eMarks[nextLine]) return false;
  }
  if (silent) {
    return true;
  }
  const markerCharCode = state.src.charCodeAt(posAfterMarker - 1);
  const listTokIdx = state.tokens.length;
  if (isOrdered) {
    token = state.push("ordered_list_open", "ol", 1);
    if (markerValue !== 1) {
      token.attrs = [["start", markerValue]];
    }
  } else {
    token = state.push("bullet_list_open", "ul", 1);
  }
  const listLines = [nextLine, 0];
  token.map = listLines;
  token.markup = String.fromCharCode(markerCharCode);
  let prevEmptyEnd = false;
  const terminatorRules = state.md.block.ruler.getRules("list");
  const oldParentType = state.parentType;
  state.parentType = "list";
  while (nextLine < endLine) {
    pos = posAfterMarker;
    max = state.eMarks[nextLine];
    const initial = state.sCount[nextLine] + posAfterMarker - (state.bMarks[nextLine] + state.tShift[nextLine]);
    let offset = initial;
    while (pos < max) {
      const ch = state.src.charCodeAt(pos);
      if (ch === 9) {
        offset += 4 - (offset + state.bsCount[nextLine]) % 4;
      } else if (ch === 32) {
        offset++;
      } else {
        break;
      }
      pos++;
    }
    const contentStart = pos;
    let indentAfterMarker;
    if (contentStart >= max) {
      indentAfterMarker = 1;
    } else {
      indentAfterMarker = offset - initial;
    }
    if (indentAfterMarker > 4) {
      indentAfterMarker = 1;
    }
    const indent = initial + indentAfterMarker;
    token = state.push("list_item_open", "li", 1);
    token.markup = String.fromCharCode(markerCharCode);
    const itemLines = [nextLine, 0];
    token.map = itemLines;
    if (isOrdered) {
      token.info = state.src.slice(start2, posAfterMarker - 1);
    }
    const oldTight = state.tight;
    const oldTShift = state.tShift[nextLine];
    const oldSCount = state.sCount[nextLine];
    const oldListIndent = state.listIndent;
    state.listIndent = state.blkIndent;
    state.blkIndent = indent;
    state.tight = true;
    state.tShift[nextLine] = contentStart - state.bMarks[nextLine];
    state.sCount[nextLine] = offset;
    if (contentStart >= max && state.isEmpty(nextLine + 1)) {
      state.line = Math.min(state.line + 2, endLine);
    } else {
      state.md.block.tokenize(state, nextLine, endLine, true);
    }
    if (!state.tight || prevEmptyEnd) {
      tight = false;
    }
    prevEmptyEnd = state.line - nextLine > 1 && state.isEmpty(state.line - 1);
    state.blkIndent = state.listIndent;
    state.listIndent = oldListIndent;
    state.tShift[nextLine] = oldTShift;
    state.sCount[nextLine] = oldSCount;
    state.tight = oldTight;
    token = state.push("list_item_close", "li", -1);
    token.markup = String.fromCharCode(markerCharCode);
    nextLine = state.line;
    itemLines[1] = nextLine;
    if (nextLine >= endLine) {
      break;
    }
    if (state.sCount[nextLine] < state.blkIndent) {
      break;
    }
    if (state.sCount[nextLine] - state.blkIndent >= 4) {
      break;
    }
    let terminate2 = false;
    for (let i2 = 0, l2 = terminatorRules.length; i2 < l2; i2++) {
      if (terminatorRules[i2](state, nextLine, endLine, true)) {
        terminate2 = true;
        break;
      }
    }
    if (terminate2) {
      break;
    }
    if (isOrdered) {
      posAfterMarker = skipOrderedListMarker(state, nextLine);
      if (posAfterMarker < 0) {
        break;
      }
      start2 = state.bMarks[nextLine] + state.tShift[nextLine];
    } else {
      posAfterMarker = skipBulletListMarker(state, nextLine);
      if (posAfterMarker < 0) {
        break;
      }
    }
    if (markerCharCode !== state.src.charCodeAt(posAfterMarker - 1)) {
      break;
    }
  }
  if (isOrdered) {
    token = state.push("ordered_list_close", "ol", -1);
  } else {
    token = state.push("bullet_list_close", "ul", -1);
  }
  token.markup = String.fromCharCode(markerCharCode);
  listLines[1] = nextLine;
  state.line = nextLine;
  state.parentType = oldParentType;
  if (tight) {
    markTightParagraphs(state, listTokIdx);
  }
  return true;
}
__name(list, "list");
function reference(state, startLine, _endLine, silent) {
  let pos = state.bMarks[startLine] + state.tShift[startLine];
  let max = state.eMarks[startLine];
  let nextLine = startLine + 1;
  if (state.sCount[startLine] - state.blkIndent >= 4) {
    return false;
  }
  if (state.src.charCodeAt(pos) !== 91) {
    return false;
  }
  function getNextLine(nextLine2) {
    const endLine = state.lineMax;
    if (nextLine2 >= endLine || state.isEmpty(nextLine2)) {
      return null;
    }
    let isContinuation = false;
    if (state.sCount[nextLine2] - state.blkIndent > 3) {
      isContinuation = true;
    }
    if (state.sCount[nextLine2] < 0) {
      isContinuation = true;
    }
    if (!isContinuation) {
      const terminatorRules = state.md.block.ruler.getRules("reference");
      const oldParentType = state.parentType;
      state.parentType = "reference";
      let terminate2 = false;
      for (let i2 = 0, l2 = terminatorRules.length; i2 < l2; i2++) {
        if (terminatorRules[i2](state, nextLine2, endLine, true)) {
          terminate2 = true;
          break;
        }
      }
      state.parentType = oldParentType;
      if (terminate2) {
        return null;
      }
    }
    const pos2 = state.bMarks[nextLine2] + state.tShift[nextLine2];
    const max2 = state.eMarks[nextLine2];
    return state.src.slice(pos2, max2 + 1);
  }
  __name(getNextLine, "getNextLine");
  let str = state.src.slice(pos, max + 1);
  max = str.length;
  let labelEnd = -1;
  for (pos = 1; pos < max; pos++) {
    const ch = str.charCodeAt(pos);
    if (ch === 91) {
      return false;
    } else if (ch === 93) {
      labelEnd = pos;
      break;
    } else if (ch === 10) {
      const lineContent = getNextLine(nextLine);
      if (lineContent !== null) {
        str += lineContent;
        max = str.length;
        nextLine++;
      }
    } else if (ch === 92) {
      pos++;
      if (pos < max && str.charCodeAt(pos) === 10) {
        const lineContent = getNextLine(nextLine);
        if (lineContent !== null) {
          str += lineContent;
          max = str.length;
          nextLine++;
        }
      }
    }
  }
  if (labelEnd < 0 || str.charCodeAt(labelEnd + 1) !== 58) {
    return false;
  }
  for (pos = labelEnd + 2; pos < max; pos++) {
    const ch = str.charCodeAt(pos);
    if (ch === 10) {
      const lineContent = getNextLine(nextLine);
      if (lineContent !== null) {
        str += lineContent;
        max = str.length;
        nextLine++;
      }
    } else if (isSpace(ch)) {
    } else {
      break;
    }
  }
  const destRes = state.md.helpers.parseLinkDestination(str, pos, max);
  if (!destRes.ok) {
    return false;
  }
  const href = state.md.normalizeLink(destRes.str);
  if (!state.md.validateLink(href)) {
    return false;
  }
  pos = destRes.pos;
  const destEndPos = pos;
  const destEndLineNo = nextLine;
  const start2 = pos;
  for (; pos < max; pos++) {
    const ch = str.charCodeAt(pos);
    if (ch === 10) {
      const lineContent = getNextLine(nextLine);
      if (lineContent !== null) {
        str += lineContent;
        max = str.length;
        nextLine++;
      }
    } else if (isSpace(ch)) {
    } else {
      break;
    }
  }
  let titleRes = state.md.helpers.parseLinkTitle(str, pos, max);
  while (titleRes.can_continue) {
    const lineContent = getNextLine(nextLine);
    if (lineContent === null) break;
    str += lineContent;
    pos = max;
    max = str.length;
    nextLine++;
    titleRes = state.md.helpers.parseLinkTitle(str, pos, max, titleRes);
  }
  let title;
  if (pos < max && start2 !== pos && titleRes.ok) {
    title = titleRes.str;
    pos = titleRes.pos;
  } else {
    title = "";
    pos = destEndPos;
    nextLine = destEndLineNo;
  }
  while (pos < max) {
    const ch = str.charCodeAt(pos);
    if (!isSpace(ch)) {
      break;
    }
    pos++;
  }
  if (pos < max && str.charCodeAt(pos) !== 10) {
    if (title) {
      title = "";
      pos = destEndPos;
      nextLine = destEndLineNo;
      while (pos < max) {
        const ch = str.charCodeAt(pos);
        if (!isSpace(ch)) {
          break;
        }
        pos++;
      }
    }
  }
  if (pos < max && str.charCodeAt(pos) !== 10) {
    return false;
  }
  const label = normalizeReference(str.slice(1, labelEnd));
  if (!label) {
    return false;
  }
  if (silent) {
    return true;
  }
  if (typeof state.env.references === "undefined") {
    state.env.references = {};
  }
  if (typeof state.env.references[label] === "undefined") {
    state.env.references[label] = { title, href };
  }
  state.line = nextLine;
  return true;
}
__name(reference, "reference");
const block_names = [
  "address",
  "article",
  "aside",
  "base",
  "basefont",
  "blockquote",
  "body",
  "caption",
  "center",
  "col",
  "colgroup",
  "dd",
  "details",
  "dialog",
  "dir",
  "div",
  "dl",
  "dt",
  "fieldset",
  "figcaption",
  "figure",
  "footer",
  "form",
  "frame",
  "frameset",
  "h1",
  "h2",
  "h3",
  "h4",
  "h5",
  "h6",
  "head",
  "header",
  "hr",
  "html",
  "iframe",
  "legend",
  "li",
  "link",
  "main",
  "menu",
  "menuitem",
  "nav",
  "noframes",
  "ol",
  "optgroup",
  "option",
  "p",
  "param",
  "search",
  "section",
  "summary",
  "table",
  "tbody",
  "td",
  "tfoot",
  "th",
  "thead",
  "title",
  "tr",
  "track",
  "ul"
];
const attr_name = "[a-zA-Z_:][a-zA-Z0-9:._-]*";
const unquoted = "[^\"'=<>`\\x00-\\x20]+";
const single_quoted = "'[^']*'";
const double_quoted = '"[^"]*"';
const attr_value = "(?:" + unquoted + "|" + single_quoted + "|" + double_quoted + ")";
const attribute = "(?:\\s+" + attr_name + "(?:\\s*=\\s*" + attr_value + ")?)";
const open_tag = "<[A-Za-z][A-Za-z0-9\\-]*" + attribute + "*\\s*\\/?>";
const close_tag = "<\\/[A-Za-z][A-Za-z0-9\\-]*\\s*>";
const comment = "<!---?>|<!--(?:[^-]|-[^-]|--[^>])*-->";
const processing = "<[?][\\s\\S]*?[?]>";
const declaration = "<![A-Za-z][^>]*>";
const cdata = "<!\\[CDATA\\[[\\s\\S]*?\\]\\]>";
const HTML_TAG_RE = new RegExp("^(?:" + open_tag + "|" + close_tag + "|" + comment + "|" + processing + "|" + declaration + "|" + cdata + ")");
const HTML_OPEN_CLOSE_TAG_RE = new RegExp("^(?:" + open_tag + "|" + close_tag + ")");
const HTML_SEQUENCES = [
  [/^<(script|pre|style|textarea)(?=(\s|>|$))/i, /<\/(script|pre|style|textarea)>/i, true],
  [/^<!--/, /-->/, true],
  [/^<\?/, /\?>/, true],
  [/^<![A-Z]/, />/, true],
  [/^<!\[CDATA\[/, /\]\]>/, true],
  [new RegExp("^</?(" + block_names.join("|") + ")(?=(\\s|/?>|$))", "i"), /^$/, true],
  [new RegExp(HTML_OPEN_CLOSE_TAG_RE.source + "\\s*$"), /^$/, false]
];
function html_block(state, startLine, endLine, silent) {
  let pos = state.bMarks[startLine] + state.tShift[startLine];
  let max = state.eMarks[startLine];
  if (state.sCount[startLine] - state.blkIndent >= 4) {
    return false;
  }
  if (!state.md.options.html) {
    return false;
  }
  if (state.src.charCodeAt(pos) !== 60) {
    return false;
  }
  let lineText = state.src.slice(pos, max);
  let i2 = 0;
  for (; i2 < HTML_SEQUENCES.length; i2++) {
    if (HTML_SEQUENCES[i2][0].test(lineText)) {
      break;
    }
  }
  if (i2 === HTML_SEQUENCES.length) {
    return false;
  }
  if (silent) {
    return HTML_SEQUENCES[i2][2];
  }
  let nextLine = startLine + 1;
  if (!HTML_SEQUENCES[i2][1].test(lineText)) {
    for (; nextLine < endLine; nextLine++) {
      if (state.sCount[nextLine] < state.blkIndent) {
        break;
      }
      pos = state.bMarks[nextLine] + state.tShift[nextLine];
      max = state.eMarks[nextLine];
      lineText = state.src.slice(pos, max);
      if (HTML_SEQUENCES[i2][1].test(lineText)) {
        if (lineText.length !== 0) {
          nextLine++;
        }
        break;
      }
    }
  }
  state.line = nextLine;
  const token = state.push("html_block", "", 0);
  token.map = [startLine, nextLine];
  token.content = state.getLines(startLine, nextLine, state.blkIndent, true);
  return true;
}
__name(html_block, "html_block");
function heading(state, startLine, endLine, silent) {
  let pos = state.bMarks[startLine] + state.tShift[startLine];
  let max = state.eMarks[startLine];
  if (state.sCount[startLine] - state.blkIndent >= 4) {
    return false;
  }
  let ch = state.src.charCodeAt(pos);
  if (ch !== 35 || pos >= max) {
    return false;
  }
  let level = 1;
  ch = state.src.charCodeAt(++pos);
  while (ch === 35 && pos < max && level <= 6) {
    level++;
    ch = state.src.charCodeAt(++pos);
  }
  if (level > 6 || pos < max && !isSpace(ch)) {
    return false;
  }
  if (silent) {
    return true;
  }
  max = state.skipSpacesBack(max, pos);
  const tmp = state.skipCharsBack(max, 35, pos);
  if (tmp > pos && isSpace(state.src.charCodeAt(tmp - 1))) {
    max = tmp;
  }
  state.line = startLine + 1;
  const token_o = state.push("heading_open", "h" + String(level), 1);
  token_o.markup = "########".slice(0, level);
  token_o.map = [startLine, state.line];
  const token_i = state.push("inline", "", 0);
  token_i.content = state.src.slice(pos, max).trim();
  token_i.map = [startLine, state.line];
  token_i.children = [];
  const token_c = state.push("heading_close", "h" + String(level), -1);
  token_c.markup = "########".slice(0, level);
  return true;
}
__name(heading, "heading");
function lheading(state, startLine, endLine) {
  const terminatorRules = state.md.block.ruler.getRules("paragraph");
  if (state.sCount[startLine] - state.blkIndent >= 4) {
    return false;
  }
  const oldParentType = state.parentType;
  state.parentType = "paragraph";
  let level = 0;
  let marker;
  let nextLine = startLine + 1;
  for (; nextLine < endLine && !state.isEmpty(nextLine); nextLine++) {
    if (state.sCount[nextLine] - state.blkIndent > 3) {
      continue;
    }
    if (state.sCount[nextLine] >= state.blkIndent) {
      let pos = state.bMarks[nextLine] + state.tShift[nextLine];
      const max = state.eMarks[nextLine];
      if (pos < max) {
        marker = state.src.charCodeAt(pos);
        if (marker === 45 || marker === 61) {
          pos = state.skipChars(pos, marker);
          pos = state.skipSpaces(pos);
          if (pos >= max) {
            level = marker === 61 ? 1 : 2;
            break;
          }
        }
      }
    }
    if (state.sCount[nextLine] < 0) {
      continue;
    }
    let terminate2 = false;
    for (let i2 = 0, l2 = terminatorRules.length; i2 < l2; i2++) {
      if (terminatorRules[i2](state, nextLine, endLine, true)) {
        terminate2 = true;
        break;
      }
    }
    if (terminate2) {
      break;
    }
  }
  if (!level) {
    return false;
  }
  const content = state.getLines(startLine, nextLine, state.blkIndent, false).trim();
  state.line = nextLine + 1;
  const token_o = state.push("heading_open", "h" + String(level), 1);
  token_o.markup = String.fromCharCode(marker);
  token_o.map = [startLine, state.line];
  const token_i = state.push("inline", "", 0);
  token_i.content = content;
  token_i.map = [startLine, state.line - 1];
  token_i.children = [];
  const token_c = state.push("heading_close", "h" + String(level), -1);
  token_c.markup = String.fromCharCode(marker);
  state.parentType = oldParentType;
  return true;
}
__name(lheading, "lheading");
function paragraph(state, startLine, endLine) {
  const terminatorRules = state.md.block.ruler.getRules("paragraph");
  const oldParentType = state.parentType;
  let nextLine = startLine + 1;
  state.parentType = "paragraph";
  for (; nextLine < endLine && !state.isEmpty(nextLine); nextLine++) {
    if (state.sCount[nextLine] - state.blkIndent > 3) {
      continue;
    }
    if (state.sCount[nextLine] < 0) {
      continue;
    }
    let terminate2 = false;
    for (let i2 = 0, l2 = terminatorRules.length; i2 < l2; i2++) {
      if (terminatorRules[i2](state, nextLine, endLine, true)) {
        terminate2 = true;
        break;
      }
    }
    if (terminate2) {
      break;
    }
  }
  const content = state.getLines(startLine, nextLine, state.blkIndent, false).trim();
  state.line = nextLine;
  const token_o = state.push("paragraph_open", "p", 1);
  token_o.map = [startLine, state.line];
  const token_i = state.push("inline", "", 0);
  token_i.content = content;
  token_i.map = [startLine, state.line];
  token_i.children = [];
  state.push("paragraph_close", "p", -1);
  state.parentType = oldParentType;
  return true;
}
__name(paragraph, "paragraph");
const _rules$1 = [
  // First 2 params - rule name & source. Secondary array - list of rules,
  // which can be terminated by this one.
  ["table", table, ["paragraph", "reference"]],
  ["code", code],
  ["fence", fence, ["paragraph", "reference", "blockquote", "list"]],
  ["blockquote", blockquote, ["paragraph", "reference", "blockquote", "list"]],
  ["hr", hr, ["paragraph", "reference", "blockquote", "list"]],
  ["list", list, ["paragraph", "reference", "blockquote"]],
  ["reference", reference],
  ["html_block", html_block, ["paragraph", "reference", "blockquote"]],
  ["heading", heading, ["paragraph", "reference", "blockquote"]],
  ["lheading", lheading],
  ["paragraph", paragraph]
];
function ParserBlock() {
  this.ruler = new Ruler();
  for (let i2 = 0; i2 < _rules$1.length; i2++) {
    this.ruler.push(_rules$1[i2][0], _rules$1[i2][1], { alt: (_rules$1[i2][2] || []).slice() });
  }
}
__name(ParserBlock, "ParserBlock");
ParserBlock.prototype.tokenize = function(state, startLine, endLine) {
  const rules = this.ruler.getRules("");
  const len = rules.length;
  const maxNesting = state.md.options.maxNesting;
  let line = startLine;
  let hasEmptyLines = false;
  while (line < endLine) {
    state.line = line = state.skipEmptyLines(line);
    if (line >= endLine) {
      break;
    }
    if (state.sCount[line] < state.blkIndent) {
      break;
    }
    if (state.level >= maxNesting) {
      state.line = endLine;
      break;
    }
    const prevLine = state.line;
    let ok = false;
    for (let i2 = 0; i2 < len; i2++) {
      ok = rules[i2](state, line, endLine, false);
      if (ok) {
        if (prevLine >= state.line) {
          throw new Error("block rule didn't increment state.line");
        }
        break;
      }
    }
    if (!ok) throw new Error("none of the block rules matched");
    state.tight = !hasEmptyLines;
    if (state.isEmpty(state.line - 1)) {
      hasEmptyLines = true;
    }
    line = state.line;
    if (line < endLine && state.isEmpty(line)) {
      hasEmptyLines = true;
      line++;
      state.line = line;
    }
  }
};
ParserBlock.prototype.parse = function(src, md2, env, outTokens) {
  if (!src) {
    return;
  }
  const state = new this.State(src, md2, env, outTokens);
  this.tokenize(state, state.line, state.lineMax);
};
ParserBlock.prototype.State = StateBlock;
function StateInline(src, md2, env, outTokens) {
  this.src = src;
  this.env = env;
  this.md = md2;
  this.tokens = outTokens;
  this.tokens_meta = Array(outTokens.length);
  this.pos = 0;
  this.posMax = this.src.length;
  this.level = 0;
  this.pending = "";
  this.pendingLevel = 0;
  this.cache = {};
  this.delimiters = [];
  this._prev_delimiters = [];
  this.backticks = {};
  this.backticksScanned = false;
  this.linkLevel = 0;
}
__name(StateInline, "StateInline");
StateInline.prototype.pushPending = function() {
  const token = new Token("text", "", 0);
  token.content = this.pending;
  token.level = this.pendingLevel;
  this.tokens.push(token);
  this.pending = "";
  return token;
};
StateInline.prototype.push = function(type, tag, nesting) {
  if (this.pending) {
    this.pushPending();
  }
  const token = new Token(type, tag, nesting);
  let token_meta = null;
  if (nesting < 0) {
    this.level--;
    this.delimiters = this._prev_delimiters.pop();
  }
  token.level = this.level;
  if (nesting > 0) {
    this.level++;
    this._prev_delimiters.push(this.delimiters);
    this.delimiters = [];
    token_meta = { delimiters: this.delimiters };
  }
  this.pendingLevel = this.level;
  this.tokens.push(token);
  this.tokens_meta.push(token_meta);
  return token;
};
StateInline.prototype.scanDelims = function(start2, canSplitWord) {
  const max = this.posMax;
  const marker = this.src.charCodeAt(start2);
  const lastChar = start2 > 0 ? this.src.charCodeAt(start2 - 1) : 32;
  let pos = start2;
  while (pos < max && this.src.charCodeAt(pos) === marker) {
    pos++;
  }
  const count2 = pos - start2;
  const nextChar = pos < max ? this.src.charCodeAt(pos) : 32;
  const isLastPunctChar = isMdAsciiPunct(lastChar) || isPunctChar(String.fromCharCode(lastChar));
  const isNextPunctChar = isMdAsciiPunct(nextChar) || isPunctChar(String.fromCharCode(nextChar));
  const isLastWhiteSpace = isWhiteSpace(lastChar);
  const isNextWhiteSpace = isWhiteSpace(nextChar);
  const left_flanking = !isNextWhiteSpace && (!isNextPunctChar || isLastWhiteSpace || isLastPunctChar);
  const right_flanking = !isLastWhiteSpace && (!isLastPunctChar || isNextWhiteSpace || isNextPunctChar);
  const can_open = left_flanking && (canSplitWord || !right_flanking || isLastPunctChar);
  const can_close = right_flanking && (canSplitWord || !left_flanking || isNextPunctChar);
  return { can_open, can_close, length: count2 };
};
StateInline.prototype.Token = Token;
function isTerminatorChar(ch) {
  switch (ch) {
    case 10:
    case 33:
    case 35:
    case 36:
    case 37:
    case 38:
    case 42:
    case 43:
    case 45:
    case 58:
    case 60:
    case 61:
    case 62:
    case 64:
    case 91:
    case 92:
    case 93:
    case 94:
    case 95:
    case 96:
    case 123:
    case 125:
    case 126:
      return true;
    default:
      return false;
  }
}
__name(isTerminatorChar, "isTerminatorChar");
function text(state, silent) {
  let pos = state.pos;
  while (pos < state.posMax && !isTerminatorChar(state.src.charCodeAt(pos))) {
    pos++;
  }
  if (pos === state.pos) {
    return false;
  }
  if (!silent) {
    state.pending += state.src.slice(state.pos, pos);
  }
  state.pos = pos;
  return true;
}
__name(text, "text");
const SCHEME_RE = /(?:^|[^a-z0-9.+-])([a-z][a-z0-9.+-]*)$/i;
function linkify(state, silent) {
  if (!state.md.options.linkify) return false;
  if (state.linkLevel > 0) return false;
  const pos = state.pos;
  const max = state.posMax;
  if (pos + 3 > max) return false;
  if (state.src.charCodeAt(pos) !== 58) return false;
  if (state.src.charCodeAt(pos + 1) !== 47) return false;
  if (state.src.charCodeAt(pos + 2) !== 47) return false;
  const match2 = state.pending.match(SCHEME_RE);
  if (!match2) return false;
  const proto = match2[1];
  const link2 = state.md.linkify.matchAtStart(state.src.slice(pos - proto.length));
  if (!link2) return false;
  let url = link2.url;
  if (url.length <= proto.length) return false;
  url = url.replace(/\*+$/, "");
  const fullUrl = state.md.normalizeLink(url);
  if (!state.md.validateLink(fullUrl)) return false;
  if (!silent) {
    state.pending = state.pending.slice(0, -proto.length);
    const token_o = state.push("link_open", "a", 1);
    token_o.attrs = [["href", fullUrl]];
    token_o.markup = "linkify";
    token_o.info = "auto";
    const token_t = state.push("text", "", 0);
    token_t.content = state.md.normalizeLinkText(url);
    const token_c = state.push("link_close", "a", -1);
    token_c.markup = "linkify";
    token_c.info = "auto";
  }
  state.pos += url.length - proto.length;
  return true;
}
__name(linkify, "linkify");
function newline(state, silent) {
  let pos = state.pos;
  if (state.src.charCodeAt(pos) !== 10) {
    return false;
  }
  const pmax = state.pending.length - 1;
  const max = state.posMax;
  if (!silent) {
    if (pmax >= 0 && state.pending.charCodeAt(pmax) === 32) {
      if (pmax >= 1 && state.pending.charCodeAt(pmax - 1) === 32) {
        let ws = pmax - 1;
        while (ws >= 1 && state.pending.charCodeAt(ws - 1) === 32) ws--;
        state.pending = state.pending.slice(0, ws);
        state.push("hardbreak", "br", 0);
      } else {
        state.pending = state.pending.slice(0, -1);
        state.push("softbreak", "br", 0);
      }
    } else {
      state.push("softbreak", "br", 0);
    }
  }
  pos++;
  while (pos < max && isSpace(state.src.charCodeAt(pos))) {
    pos++;
  }
  state.pos = pos;
  return true;
}
__name(newline, "newline");
const ESCAPED = [];
for (let i2 = 0; i2 < 256; i2++) {
  ESCAPED.push(0);
}
"\\!\"#$%&'()*+,./:;<=>?@[]^_`{|}~-".split("").forEach(function(ch) {
  ESCAPED[ch.charCodeAt(0)] = 1;
});
function escape$1(state, silent) {
  let pos = state.pos;
  const max = state.posMax;
  if (state.src.charCodeAt(pos) !== 92) return false;
  pos++;
  if (pos >= max) return false;
  let ch1 = state.src.charCodeAt(pos);
  if (ch1 === 10) {
    if (!silent) {
      state.push("hardbreak", "br", 0);
    }
    pos++;
    while (pos < max) {
      ch1 = state.src.charCodeAt(pos);
      if (!isSpace(ch1)) break;
      pos++;
    }
    state.pos = pos;
    return true;
  }
  let escapedStr = state.src[pos];
  if (ch1 >= 55296 && ch1 <= 56319 && pos + 1 < max) {
    const ch2 = state.src.charCodeAt(pos + 1);
    if (ch2 >= 56320 && ch2 <= 57343) {
      escapedStr += state.src[pos + 1];
      pos++;
    }
  }
  const origStr = "\\" + escapedStr;
  if (!silent) {
    const token = state.push("text_special", "", 0);
    if (ch1 < 256 && ESCAPED[ch1] !== 0) {
      token.content = escapedStr;
    } else {
      token.content = origStr;
    }
    token.markup = origStr;
    token.info = "escape";
  }
  state.pos = pos + 1;
  return true;
}
__name(escape$1, "escape$1");
function backtick(state, silent) {
  let pos = state.pos;
  const ch = state.src.charCodeAt(pos);
  if (ch !== 96) {
    return false;
  }
  const start2 = pos;
  pos++;
  const max = state.posMax;
  while (pos < max && state.src.charCodeAt(pos) === 96) {
    pos++;
  }
  const marker = state.src.slice(start2, pos);
  const openerLength = marker.length;
  if (state.backticksScanned && (state.backticks[openerLength] || 0) <= start2) {
    if (!silent) state.pending += marker;
    state.pos += openerLength;
    return true;
  }
  let matchEnd = pos;
  let matchStart;
  while ((matchStart = state.src.indexOf("`", matchEnd)) !== -1) {
    matchEnd = matchStart + 1;
    while (matchEnd < max && state.src.charCodeAt(matchEnd) === 96) {
      matchEnd++;
    }
    const closerLength = matchEnd - matchStart;
    if (closerLength === openerLength) {
      if (!silent) {
        const token = state.push("code_inline", "code", 0);
        token.markup = marker;
        token.content = state.src.slice(pos, matchStart).replace(/\n/g, " ").replace(/^ (.+) $/, "$1");
      }
      state.pos = matchEnd;
      return true;
    }
    state.backticks[closerLength] = matchStart;
  }
  state.backticksScanned = true;
  if (!silent) state.pending += marker;
  state.pos += openerLength;
  return true;
}
__name(backtick, "backtick");
function strikethrough_tokenize(state, silent) {
  const start2 = state.pos;
  const marker = state.src.charCodeAt(start2);
  if (silent) {
    return false;
  }
  if (marker !== 126) {
    return false;
  }
  const scanned = state.scanDelims(state.pos, true);
  let len = scanned.length;
  const ch = String.fromCharCode(marker);
  if (len < 2) {
    return false;
  }
  let token;
  if (len % 2) {
    token = state.push("text", "", 0);
    token.content = ch;
    len--;
  }
  for (let i2 = 0; i2 < len; i2 += 2) {
    token = state.push("text", "", 0);
    token.content = ch + ch;
    state.delimiters.push({
      marker,
      length: 0,
      // disable "rule of 3" length checks meant for emphasis
      token: state.tokens.length - 1,
      end: -1,
      open: scanned.can_open,
      close: scanned.can_close
    });
  }
  state.pos += scanned.length;
  return true;
}
__name(strikethrough_tokenize, "strikethrough_tokenize");
function postProcess$1(state, delimiters) {
  let token;
  const loneMarkers = [];
  const max = delimiters.length;
  for (let i2 = 0; i2 < max; i2++) {
    const startDelim = delimiters[i2];
    if (startDelim.marker !== 126) {
      continue;
    }
    if (startDelim.end === -1) {
      continue;
    }
    const endDelim = delimiters[startDelim.end];
    token = state.tokens[startDelim.token];
    token.type = "s_open";
    token.tag = "s";
    token.nesting = 1;
    token.markup = "~~";
    token.content = "";
    token = state.tokens[endDelim.token];
    token.type = "s_close";
    token.tag = "s";
    token.nesting = -1;
    token.markup = "~~";
    token.content = "";
    if (state.tokens[endDelim.token - 1].type === "text" && state.tokens[endDelim.token - 1].content === "~") {
      loneMarkers.push(endDelim.token - 1);
    }
  }
  while (loneMarkers.length) {
    const i2 = loneMarkers.pop();
    let j2 = i2 + 1;
    while (j2 < state.tokens.length && state.tokens[j2].type === "s_close") {
      j2++;
    }
    j2--;
    if (i2 !== j2) {
      token = state.tokens[j2];
      state.tokens[j2] = state.tokens[i2];
      state.tokens[i2] = token;
    }
  }
}
__name(postProcess$1, "postProcess$1");
function strikethrough_postProcess(state) {
  const tokens_meta = state.tokens_meta;
  const max = state.tokens_meta.length;
  postProcess$1(state, state.delimiters);
  for (let curr = 0; curr < max; curr++) {
    if (tokens_meta[curr] && tokens_meta[curr].delimiters) {
      postProcess$1(state, tokens_meta[curr].delimiters);
    }
  }
}
__name(strikethrough_postProcess, "strikethrough_postProcess");
const r_strikethrough = {
  tokenize: strikethrough_tokenize,
  postProcess: strikethrough_postProcess
};
function emphasis_tokenize(state, silent) {
  const start2 = state.pos;
  const marker = state.src.charCodeAt(start2);
  if (silent) {
    return false;
  }
  if (marker !== 95 && marker !== 42) {
    return false;
  }
  const scanned = state.scanDelims(state.pos, marker === 42);
  for (let i2 = 0; i2 < scanned.length; i2++) {
    const token = state.push("text", "", 0);
    token.content = String.fromCharCode(marker);
    state.delimiters.push({
      // Char code of the starting marker (number).
      //
      marker,
      // Total length of these series of delimiters.
      //
      length: scanned.length,
      // A position of the token this delimiter corresponds to.
      //
      token: state.tokens.length - 1,
      // If this delimiter is matched as a valid opener, `end` will be
      // equal to its position, otherwise it's `-1`.
      //
      end: -1,
      // Boolean flags that determine if this delimiter could open or close
      // an emphasis.
      //
      open: scanned.can_open,
      close: scanned.can_close
    });
  }
  state.pos += scanned.length;
  return true;
}
__name(emphasis_tokenize, "emphasis_tokenize");
function postProcess(state, delimiters) {
  const max = delimiters.length;
  for (let i2 = max - 1; i2 >= 0; i2--) {
    const startDelim = delimiters[i2];
    if (startDelim.marker !== 95 && startDelim.marker !== 42) {
      continue;
    }
    if (startDelim.end === -1) {
      continue;
    }
    const endDelim = delimiters[startDelim.end];
    const isStrong = i2 > 0 && delimiters[i2 - 1].end === startDelim.end + 1 && // check that first two markers match and adjacent
    delimiters[i2 - 1].marker === startDelim.marker && delimiters[i2 - 1].token === startDelim.token - 1 && // check that last two markers are adjacent (we can safely assume they match)
    delimiters[startDelim.end + 1].token === endDelim.token + 1;
    const ch = String.fromCharCode(startDelim.marker);
    const token_o = state.tokens[startDelim.token];
    token_o.type = isStrong ? "strong_open" : "em_open";
    token_o.tag = isStrong ? "strong" : "em";
    token_o.nesting = 1;
    token_o.markup = isStrong ? ch + ch : ch;
    token_o.content = "";
    const token_c = state.tokens[endDelim.token];
    token_c.type = isStrong ? "strong_close" : "em_close";
    token_c.tag = isStrong ? "strong" : "em";
    token_c.nesting = -1;
    token_c.markup = isStrong ? ch + ch : ch;
    token_c.content = "";
    if (isStrong) {
      state.tokens[delimiters[i2 - 1].token].content = "";
      state.tokens[delimiters[startDelim.end + 1].token].content = "";
      i2--;
    }
  }
}
__name(postProcess, "postProcess");
function emphasis_post_process(state) {
  const tokens_meta = state.tokens_meta;
  const max = state.tokens_meta.length;
  postProcess(state, state.delimiters);
  for (let curr = 0; curr < max; curr++) {
    if (tokens_meta[curr] && tokens_meta[curr].delimiters) {
      postProcess(state, tokens_meta[curr].delimiters);
    }
  }
}
__name(emphasis_post_process, "emphasis_post_process");
const r_emphasis = {
  tokenize: emphasis_tokenize,
  postProcess: emphasis_post_process
};
function link(state, silent) {
  let code2, label, res, ref2;
  let href = "";
  let title = "";
  let start2 = state.pos;
  let parseReference = true;
  if (state.src.charCodeAt(state.pos) !== 91) {
    return false;
  }
  const oldPos = state.pos;
  const max = state.posMax;
  const labelStart = state.pos + 1;
  const labelEnd = state.md.helpers.parseLinkLabel(state, state.pos, true);
  if (labelEnd < 0) {
    return false;
  }
  let pos = labelEnd + 1;
  if (pos < max && state.src.charCodeAt(pos) === 40) {
    parseReference = false;
    pos++;
    for (; pos < max; pos++) {
      code2 = state.src.charCodeAt(pos);
      if (!isSpace(code2) && code2 !== 10) {
        break;
      }
    }
    if (pos >= max) {
      return false;
    }
    start2 = pos;
    res = state.md.helpers.parseLinkDestination(state.src, pos, state.posMax);
    if (res.ok) {
      href = state.md.normalizeLink(res.str);
      if (state.md.validateLink(href)) {
        pos = res.pos;
      } else {
        href = "";
      }
      start2 = pos;
      for (; pos < max; pos++) {
        code2 = state.src.charCodeAt(pos);
        if (!isSpace(code2) && code2 !== 10) {
          break;
        }
      }
      res = state.md.helpers.parseLinkTitle(state.src, pos, state.posMax);
      if (pos < max && start2 !== pos && res.ok) {
        title = res.str;
        pos = res.pos;
        for (; pos < max; pos++) {
          code2 = state.src.charCodeAt(pos);
          if (!isSpace(code2) && code2 !== 10) {
            break;
          }
        }
      }
    }
    if (pos >= max || state.src.charCodeAt(pos) !== 41) {
      parseReference = true;
    }
    pos++;
  }
  if (parseReference) {
    if (typeof state.env.references === "undefined") {
      return false;
    }
    if (pos < max && state.src.charCodeAt(pos) === 91) {
      start2 = pos + 1;
      pos = state.md.helpers.parseLinkLabel(state, pos);
      if (pos >= 0) {
        label = state.src.slice(start2, pos++);
      } else {
        pos = labelEnd + 1;
      }
    } else {
      pos = labelEnd + 1;
    }
    if (!label) {
      label = state.src.slice(labelStart, labelEnd);
    }
    ref2 = state.env.references[normalizeReference(label)];
    if (!ref2) {
      state.pos = oldPos;
      return false;
    }
    href = ref2.href;
    title = ref2.title;
  }
  if (!silent) {
    state.pos = labelStart;
    state.posMax = labelEnd;
    const token_o = state.push("link_open", "a", 1);
    const attrs2 = [["href", href]];
    token_o.attrs = attrs2;
    if (title) {
      attrs2.push(["title", title]);
    }
    state.linkLevel++;
    state.md.inline.tokenize(state);
    state.linkLevel--;
    state.push("link_close", "a", -1);
  }
  state.pos = pos;
  state.posMax = max;
  return true;
}
__name(link, "link");
function image(state, silent) {
  let code2, content, label, pos, ref2, res, title, start2;
  let href = "";
  const oldPos = state.pos;
  const max = state.posMax;
  if (state.src.charCodeAt(state.pos) !== 33) {
    return false;
  }
  if (state.src.charCodeAt(state.pos + 1) !== 91) {
    return false;
  }
  const labelStart = state.pos + 2;
  const labelEnd = state.md.helpers.parseLinkLabel(state, state.pos + 1, false);
  if (labelEnd < 0) {
    return false;
  }
  pos = labelEnd + 1;
  if (pos < max && state.src.charCodeAt(pos) === 40) {
    pos++;
    for (; pos < max; pos++) {
      code2 = state.src.charCodeAt(pos);
      if (!isSpace(code2) && code2 !== 10) {
        break;
      }
    }
    if (pos >= max) {
      return false;
    }
    start2 = pos;
    res = state.md.helpers.parseLinkDestination(state.src, pos, state.posMax);
    if (res.ok) {
      href = state.md.normalizeLink(res.str);
      if (state.md.validateLink(href)) {
        pos = res.pos;
      } else {
        href = "";
      }
    }
    start2 = pos;
    for (; pos < max; pos++) {
      code2 = state.src.charCodeAt(pos);
      if (!isSpace(code2) && code2 !== 10) {
        break;
      }
    }
    res = state.md.helpers.parseLinkTitle(state.src, pos, state.posMax);
    if (pos < max && start2 !== pos && res.ok) {
      title = res.str;
      pos = res.pos;
      for (; pos < max; pos++) {
        code2 = state.src.charCodeAt(pos);
        if (!isSpace(code2) && code2 !== 10) {
          break;
        }
      }
    } else {
      title = "";
    }
    if (pos >= max || state.src.charCodeAt(pos) !== 41) {
      state.pos = oldPos;
      return false;
    }
    pos++;
  } else {
    if (typeof state.env.references === "undefined") {
      return false;
    }
    if (pos < max && state.src.charCodeAt(pos) === 91) {
      start2 = pos + 1;
      pos = state.md.helpers.parseLinkLabel(state, pos);
      if (pos >= 0) {
        label = state.src.slice(start2, pos++);
      } else {
        pos = labelEnd + 1;
      }
    } else {
      pos = labelEnd + 1;
    }
    if (!label) {
      label = state.src.slice(labelStart, labelEnd);
    }
    ref2 = state.env.references[normalizeReference(label)];
    if (!ref2) {
      state.pos = oldPos;
      return false;
    }
    href = ref2.href;
    title = ref2.title;
  }
  if (!silent) {
    content = state.src.slice(labelStart, labelEnd);
    const tokens = [];
    state.md.inline.parse(
      content,
      state.md,
      state.env,
      tokens
    );
    const token = state.push("image", "img", 0);
    const attrs2 = [["src", href], ["alt", ""]];
    token.attrs = attrs2;
    token.children = tokens;
    token.content = content;
    if (title) {
      attrs2.push(["title", title]);
    }
  }
  state.pos = pos;
  state.posMax = max;
  return true;
}
__name(image, "image");
const EMAIL_RE = /^([a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)$/;
const AUTOLINK_RE = /^([a-zA-Z][a-zA-Z0-9+.-]{1,31}):([^<>\x00-\x20]*)$/;
function autolink(state, silent) {
  let pos = state.pos;
  if (state.src.charCodeAt(pos) !== 60) {
    return false;
  }
  const start2 = state.pos;
  const max = state.posMax;
  for (; ; ) {
    if (++pos >= max) return false;
    const ch = state.src.charCodeAt(pos);
    if (ch === 60) return false;
    if (ch === 62) break;
  }
  const url = state.src.slice(start2 + 1, pos);
  if (AUTOLINK_RE.test(url)) {
    const fullUrl = state.md.normalizeLink(url);
    if (!state.md.validateLink(fullUrl)) {
      return false;
    }
    if (!silent) {
      const token_o = state.push("link_open", "a", 1);
      token_o.attrs = [["href", fullUrl]];
      token_o.markup = "autolink";
      token_o.info = "auto";
      const token_t = state.push("text", "", 0);
      token_t.content = state.md.normalizeLinkText(url);
      const token_c = state.push("link_close", "a", -1);
      token_c.markup = "autolink";
      token_c.info = "auto";
    }
    state.pos += url.length + 2;
    return true;
  }
  if (EMAIL_RE.test(url)) {
    const fullUrl = state.md.normalizeLink("mailto:" + url);
    if (!state.md.validateLink(fullUrl)) {
      return false;
    }
    if (!silent) {
      const token_o = state.push("link_open", "a", 1);
      token_o.attrs = [["href", fullUrl]];
      token_o.markup = "autolink";
      token_o.info = "auto";
      const token_t = state.push("text", "", 0);
      token_t.content = state.md.normalizeLinkText(url);
      const token_c = state.push("link_close", "a", -1);
      token_c.markup = "autolink";
      token_c.info = "auto";
    }
    state.pos += url.length + 2;
    return true;
  }
  return false;
}
__name(autolink, "autolink");
function isLinkOpen(str) {
  return /^<a[>\s]/i.test(str);
}
__name(isLinkOpen, "isLinkOpen");
function isLinkClose(str) {
  return /^<\/a\s*>/i.test(str);
}
__name(isLinkClose, "isLinkClose");
function isLetter(ch) {
  const lc = ch | 32;
  return lc >= 97 && lc <= 122;
}
__name(isLetter, "isLetter");
function html_inline(state, silent) {
  if (!state.md.options.html) {
    return false;
  }
  const max = state.posMax;
  const pos = state.pos;
  if (state.src.charCodeAt(pos) !== 60 || pos + 2 >= max) {
    return false;
  }
  const ch = state.src.charCodeAt(pos + 1);
  if (ch !== 33 && ch !== 63 && ch !== 47 && !isLetter(ch)) {
    return false;
  }
  const match2 = state.src.slice(pos).match(HTML_TAG_RE);
  if (!match2) {
    return false;
  }
  if (!silent) {
    const token = state.push("html_inline", "", 0);
    token.content = match2[0];
    if (isLinkOpen(token.content)) state.linkLevel++;
    if (isLinkClose(token.content)) state.linkLevel--;
  }
  state.pos += match2[0].length;
  return true;
}
__name(html_inline, "html_inline");
const DIGITAL_RE = /^&#((?:x[a-f0-9]{1,6}|[0-9]{1,7}));/i;
const NAMED_RE = /^&([a-z][a-z0-9]{1,31});/i;
function entity(state, silent) {
  const pos = state.pos;
  const max = state.posMax;
  if (state.src.charCodeAt(pos) !== 38) return false;
  if (pos + 1 >= max) return false;
  const ch = state.src.charCodeAt(pos + 1);
  if (ch === 35) {
    const match2 = state.src.slice(pos).match(DIGITAL_RE);
    if (match2) {
      if (!silent) {
        const code2 = match2[1][0].toLowerCase() === "x" ? parseInt(match2[1].slice(1), 16) : parseInt(match2[1], 10);
        const token = state.push("text_special", "", 0);
        token.content = isValidEntityCode(code2) ? fromCodePoint(code2) : fromCodePoint(65533);
        token.markup = match2[0];
        token.info = "entity";
      }
      state.pos += match2[0].length;
      return true;
    }
  } else {
    const match2 = state.src.slice(pos).match(NAMED_RE);
    if (match2) {
      const decoded = decodeHTML(match2[0]);
      if (decoded !== match2[0]) {
        if (!silent) {
          const token = state.push("text_special", "", 0);
          token.content = decoded;
          token.markup = match2[0];
          token.info = "entity";
        }
        state.pos += match2[0].length;
        return true;
      }
    }
  }
  return false;
}
__name(entity, "entity");
function processDelimiters(delimiters) {
  const openersBottom = {};
  const max = delimiters.length;
  if (!max) return;
  let headerIdx = 0;
  let lastTokenIdx = -2;
  const jumps = [];
  for (let closerIdx = 0; closerIdx < max; closerIdx++) {
    const closer = delimiters[closerIdx];
    jumps.push(0);
    if (delimiters[headerIdx].marker !== closer.marker || lastTokenIdx !== closer.token - 1) {
      headerIdx = closerIdx;
    }
    lastTokenIdx = closer.token;
    closer.length = closer.length || 0;
    if (!closer.close) continue;
    if (!openersBottom.hasOwnProperty(closer.marker)) {
      openersBottom[closer.marker] = [-1, -1, -1, -1, -1, -1];
    }
    const minOpenerIdx = openersBottom[closer.marker][(closer.open ? 3 : 0) + closer.length % 3];
    let openerIdx = headerIdx - jumps[headerIdx] - 1;
    let newMinOpenerIdx = openerIdx;
    for (; openerIdx > minOpenerIdx; openerIdx -= jumps[openerIdx] + 1) {
      const opener = delimiters[openerIdx];
      if (opener.marker !== closer.marker) continue;
      if (opener.open && opener.end < 0) {
        let isOddMatch = false;
        if (opener.close || closer.open) {
          if ((opener.length + closer.length) % 3 === 0) {
            if (opener.length % 3 !== 0 || closer.length % 3 !== 0) {
              isOddMatch = true;
            }
          }
        }
        if (!isOddMatch) {
          const lastJump = openerIdx > 0 && !delimiters[openerIdx - 1].open ? jumps[openerIdx - 1] + 1 : 0;
          jumps[closerIdx] = closerIdx - openerIdx + lastJump;
          jumps[openerIdx] = lastJump;
          closer.open = false;
          opener.end = closerIdx;
          opener.close = false;
          newMinOpenerIdx = -1;
          lastTokenIdx = -2;
          break;
        }
      }
    }
    if (newMinOpenerIdx !== -1) {
      openersBottom[closer.marker][(closer.open ? 3 : 0) + (closer.length || 0) % 3] = newMinOpenerIdx;
    }
  }
}
__name(processDelimiters, "processDelimiters");
function link_pairs(state) {
  const tokens_meta = state.tokens_meta;
  const max = state.tokens_meta.length;
  processDelimiters(state.delimiters);
  for (let curr = 0; curr < max; curr++) {
    if (tokens_meta[curr] && tokens_meta[curr].delimiters) {
      processDelimiters(tokens_meta[curr].delimiters);
    }
  }
}
__name(link_pairs, "link_pairs");
function fragments_join(state) {
  let curr, last;
  let level = 0;
  const tokens = state.tokens;
  const max = state.tokens.length;
  for (curr = last = 0; curr < max; curr++) {
    if (tokens[curr].nesting < 0) level--;
    tokens[curr].level = level;
    if (tokens[curr].nesting > 0) level++;
    if (tokens[curr].type === "text" && curr + 1 < max && tokens[curr + 1].type === "text") {
      tokens[curr + 1].content = tokens[curr].content + tokens[curr + 1].content;
    } else {
      if (curr !== last) {
        tokens[last] = tokens[curr];
      }
      last++;
    }
  }
  if (curr !== last) {
    tokens.length = last;
  }
}
__name(fragments_join, "fragments_join");
const _rules = [
  ["text", text],
  ["linkify", linkify],
  ["newline", newline],
  ["escape", escape$1],
  ["backticks", backtick],
  ["strikethrough", r_strikethrough.tokenize],
  ["emphasis", r_emphasis.tokenize],
  ["link", link],
  ["image", image],
  ["autolink", autolink],
  ["html_inline", html_inline],
  ["entity", entity]
];
const _rules2 = [
  ["balance_pairs", link_pairs],
  ["strikethrough", r_strikethrough.postProcess],
  ["emphasis", r_emphasis.postProcess],
  // rules for pairs separate '**' into its own text tokens, which may be left unused,
  // rule below merges unused segments back with the rest of the text
  ["fragments_join", fragments_join]
];
function ParserInline() {
  this.ruler = new Ruler();
  for (let i2 = 0; i2 < _rules.length; i2++) {
    this.ruler.push(_rules[i2][0], _rules[i2][1]);
  }
  this.ruler2 = new Ruler();
  for (let i2 = 0; i2 < _rules2.length; i2++) {
    this.ruler2.push(_rules2[i2][0], _rules2[i2][1]);
  }
}
__name(ParserInline, "ParserInline");
ParserInline.prototype.skipToken = function(state) {
  const pos = state.pos;
  const rules = this.ruler.getRules("");
  const len = rules.length;
  const maxNesting = state.md.options.maxNesting;
  const cache = state.cache;
  if (typeof cache[pos] !== "undefined") {
    state.pos = cache[pos];
    return;
  }
  let ok = false;
  if (state.level < maxNesting) {
    for (let i2 = 0; i2 < len; i2++) {
      state.level++;
      ok = rules[i2](state, true);
      state.level--;
      if (ok) {
        if (pos >= state.pos) {
          throw new Error("inline rule didn't increment state.pos");
        }
        break;
      }
    }
  } else {
    state.pos = state.posMax;
  }
  if (!ok) {
    state.pos++;
  }
  cache[pos] = state.pos;
};
ParserInline.prototype.tokenize = function(state) {
  const rules = this.ruler.getRules("");
  const len = rules.length;
  const end = state.posMax;
  const maxNesting = state.md.options.maxNesting;
  while (state.pos < end) {
    const prevPos = state.pos;
    let ok = false;
    if (state.level < maxNesting) {
      for (let i2 = 0; i2 < len; i2++) {
        ok = rules[i2](state, false);
        if (ok) {
          if (prevPos >= state.pos) {
            throw new Error("inline rule didn't increment state.pos");
          }
          break;
        }
      }
    }
    if (ok) {
      if (state.pos >= end) {
        break;
      }
      continue;
    }
    state.pending += state.src[state.pos++];
  }
  if (state.pending) {
    state.pushPending();
  }
};
ParserInline.prototype.parse = function(str, md2, env, outTokens) {
  const state = new this.State(str, md2, env, outTokens);
  this.tokenize(state);
  const rules = this.ruler2.getRules("");
  const len = rules.length;
  for (let i2 = 0; i2 < len; i2++) {
    rules[i2](state);
  }
};
ParserInline.prototype.State = StateInline;
function reFactory(opts) {
  const re2 = {};
  opts = opts || {};
  re2.src_Any = Any.source;
  re2.src_Cc = Cc.source;
  re2.src_Z = Z.source;
  re2.src_P = P.source;
  re2.src_ZPCc = [re2.src_Z, re2.src_P, re2.src_Cc].join("|");
  re2.src_ZCc = [re2.src_Z, re2.src_Cc].join("|");
  const text_separators = "[><｜]";
  re2.src_pseudo_letter = "(?:(?!" + text_separators + "|" + re2.src_ZPCc + ")" + re2.src_Any + ")";
  re2.src_ip4 = "(?:(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)";
  re2.src_auth = "(?:(?:(?!" + re2.src_ZCc + "|[@/\\[\\]()]).)+@)?";
  re2.src_port = "(?::(?:6(?:[0-4]\\d{3}|5(?:[0-4]\\d{2}|5(?:[0-2]\\d|3[0-5])))|[1-5]?\\d{1,4}))?";
  re2.src_host_terminator = "(?=$|" + text_separators + "|" + re2.src_ZPCc + ")(?!" + (opts["---"] ? "-(?!--)|" : "-|") + "_|:\\d|\\.-|\\.(?!$|" + re2.src_ZPCc + "))";
  re2.src_path = "(?:[/?#](?:(?!" + re2.src_ZCc + "|" + text_separators + `|[()[\\]{}.,"'?!\\-;]).|\\[(?:(?!` + re2.src_ZCc + "|\\]).)*\\]|\\((?:(?!" + re2.src_ZCc + "|[)]).)*\\)|\\{(?:(?!" + re2.src_ZCc + '|[}]).)*\\}|\\"(?:(?!' + re2.src_ZCc + `|["]).)+\\"|\\'(?:(?!` + re2.src_ZCc + "|[']).)+\\'|\\'(?=" + re2.src_pseudo_letter + "|[-])|\\.{2,}[a-zA-Z0-9%/&]|\\.(?!" + re2.src_ZCc + "|[.]|$)|" + (opts["---"] ? "\\-(?!--(?:[^-]|$))(?:-*)|" : "\\-+|") + // allow `,,,` in paths
  ",(?!" + re2.src_ZCc + "|$)|;(?!" + re2.src_ZCc + "|$)|\\!+(?!" + re2.src_ZCc + "|[!]|$)|\\?(?!" + re2.src_ZCc + "|[?]|$))+|\\/)?";
  re2.src_email_name = '[\\-;:&=\\+\\$,\\.a-zA-Z0-9_][\\-;:&=\\+\\$,\\"\\.a-zA-Z0-9_]*';
  re2.src_xn = "xn--[a-z0-9\\-]{1,59}";
  re2.src_domain_root = // Allow letters & digits (http://test1)
  "(?:" + re2.src_xn + "|" + re2.src_pseudo_letter + "{1,63})";
  re2.src_domain = "(?:" + re2.src_xn + "|(?:" + re2.src_pseudo_letter + ")|(?:" + re2.src_pseudo_letter + "(?:-|" + re2.src_pseudo_letter + "){0,61}" + re2.src_pseudo_letter + "))";
  re2.src_host = "(?:(?:(?:(?:" + re2.src_domain + ")\\.)*" + re2.src_domain + "))";
  re2.tpl_host_fuzzy = "(?:" + re2.src_ip4 + "|(?:(?:(?:" + re2.src_domain + ")\\.)+(?:%TLDS%)))";
  re2.tpl_host_no_ip_fuzzy = "(?:(?:(?:" + re2.src_domain + ")\\.)+(?:%TLDS%))";
  re2.src_host_strict = re2.src_host + re2.src_host_terminator;
  re2.tpl_host_fuzzy_strict = re2.tpl_host_fuzzy + re2.src_host_terminator;
  re2.src_host_port_strict = re2.src_host + re2.src_port + re2.src_host_terminator;
  re2.tpl_host_port_fuzzy_strict = re2.tpl_host_fuzzy + re2.src_port + re2.src_host_terminator;
  re2.tpl_host_port_no_ip_fuzzy_strict = re2.tpl_host_no_ip_fuzzy + re2.src_port + re2.src_host_terminator;
  re2.tpl_host_fuzzy_test = "localhost|www\\.|\\.\\d{1,3}\\.|(?:\\.(?:%TLDS%)(?:" + re2.src_ZPCc + "|>|$))";
  re2.tpl_email_fuzzy = "(^|" + text_separators + '|"|\\(|' + re2.src_ZCc + ")(" + re2.src_email_name + "@" + re2.tpl_host_fuzzy_strict + ")";
  re2.tpl_link_fuzzy = // Fuzzy link can't be prepended with .:/\- and non punctuation.
  // but can start with > (markdown blockquote)
  "(^|(?![.:/\\-_@])(?:[$+<=>^`|｜]|" + re2.src_ZPCc + "))((?![$+<=>^`|｜])" + re2.tpl_host_port_fuzzy_strict + re2.src_path + ")";
  re2.tpl_link_no_ip_fuzzy = // Fuzzy link can't be prepended with .:/\- and non punctuation.
  // but can start with > (markdown blockquote)
  "(^|(?![.:/\\-_@])(?:[$+<=>^`|｜]|" + re2.src_ZPCc + "))((?![$+<=>^`|｜])" + re2.tpl_host_port_no_ip_fuzzy_strict + re2.src_path + ")";
  return re2;
}
__name(reFactory, "reFactory");
function assign(obj) {
  const sources = Array.prototype.slice.call(arguments, 1);
  sources.forEach(function(source) {
    if (!source) {
      return;
    }
    Object.keys(source).forEach(function(key) {
      obj[key] = source[key];
    });
  });
  return obj;
}
__name(assign, "assign");
function _class(obj) {
  return Object.prototype.toString.call(obj);
}
__name(_class, "_class");
function isString$1(obj) {
  return _class(obj) === "[object String]";
}
__name(isString$1, "isString$1");
function isObject$1(obj) {
  return _class(obj) === "[object Object]";
}
__name(isObject$1, "isObject$1");
function isRegExp(obj) {
  return _class(obj) === "[object RegExp]";
}
__name(isRegExp, "isRegExp");
function isFunction(obj) {
  return _class(obj) === "[object Function]";
}
__name(isFunction, "isFunction");
function escapeRE(str) {
  return str.replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&");
}
__name(escapeRE, "escapeRE");
const defaultOptions = {
  fuzzyLink: true,
  fuzzyEmail: true,
  fuzzyIP: false
};
function isOptionsObj(obj) {
  return Object.keys(obj || {}).reduce(function(acc, k2) {
    return acc || defaultOptions.hasOwnProperty(k2);
  }, false);
}
__name(isOptionsObj, "isOptionsObj");
const defaultSchemas = {
  "http:": {
    validate: /* @__PURE__ */ __name(function(text2, pos, self2) {
      const tail = text2.slice(pos);
      if (!self2.re.http) {
        self2.re.http = new RegExp(
          "^\\/\\/" + self2.re.src_auth + self2.re.src_host_port_strict + self2.re.src_path,
          "i"
        );
      }
      if (self2.re.http.test(tail)) {
        return tail.match(self2.re.http)[0].length;
      }
      return 0;
    }, "validate")
  },
  "https:": "http:",
  "ftp:": "http:",
  "//": {
    validate: /* @__PURE__ */ __name(function(text2, pos, self2) {
      const tail = text2.slice(pos);
      if (!self2.re.no_http) {
        self2.re.no_http = new RegExp(
          "^" + self2.re.src_auth + // Don't allow single-level domains, because of false positives like '//test'
          // with code comments
          "(?:localhost|(?:(?:" + self2.re.src_domain + ")\\.)+" + self2.re.src_domain_root + ")" + self2.re.src_port + self2.re.src_host_terminator + self2.re.src_path,
          "i"
        );
      }
      if (self2.re.no_http.test(tail)) {
        if (pos >= 3 && text2[pos - 3] === ":") {
          return 0;
        }
        if (pos >= 3 && text2[pos - 3] === "/") {
          return 0;
        }
        return tail.match(self2.re.no_http)[0].length;
      }
      return 0;
    }, "validate")
  },
  "mailto:": {
    validate: /* @__PURE__ */ __name(function(text2, pos, self2) {
      const tail = text2.slice(pos);
      if (!self2.re.mailto) {
        self2.re.mailto = new RegExp(
          "^" + self2.re.src_email_name + "@" + self2.re.src_host_strict,
          "i"
        );
      }
      if (self2.re.mailto.test(tail)) {
        return tail.match(self2.re.mailto)[0].length;
      }
      return 0;
    }, "validate")
  }
};
const tlds_2ch_src_re = "a[cdefgilmnoqrstuwxz]|b[abdefghijmnorstvwyz]|c[acdfghiklmnoruvwxyz]|d[ejkmoz]|e[cegrstu]|f[ijkmor]|g[abdefghilmnpqrstuwy]|h[kmnrtu]|i[delmnoqrst]|j[emop]|k[eghimnprwyz]|l[abcikrstuvy]|m[acdeghklmnopqrstuvwxyz]|n[acefgilopruz]|om|p[aefghklmnrstwy]|qa|r[eosuw]|s[abcdeghijklmnortuvxyz]|t[cdfghjklmnortvwz]|u[agksyz]|v[aceginu]|w[fs]|y[et]|z[amw]";
const tlds_default = "biz|com|edu|gov|net|org|pro|web|xxx|aero|asia|coop|info|museum|name|shop|рф".split("|");
function resetScanCache(self2) {
  self2.__index__ = -1;
  self2.__text_cache__ = "";
}
__name(resetScanCache, "resetScanCache");
function createValidator(re2) {
  return function(text2, pos) {
    const tail = text2.slice(pos);
    if (re2.test(tail)) {
      return tail.match(re2)[0].length;
    }
    return 0;
  };
}
__name(createValidator, "createValidator");
function createNormalizer() {
  return function(match2, self2) {
    self2.normalize(match2);
  };
}
__name(createNormalizer, "createNormalizer");
function compile(self2) {
  const re2 = self2.re = reFactory(self2.__opts__);
  const tlds3 = self2.__tlds__.slice();
  self2.onCompile();
  if (!self2.__tlds_replaced__) {
    tlds3.push(tlds_2ch_src_re);
  }
  tlds3.push(re2.src_xn);
  re2.src_tlds = tlds3.join("|");
  function untpl(tpl) {
    return tpl.replace("%TLDS%", re2.src_tlds);
  }
  __name(untpl, "untpl");
  re2.email_fuzzy = RegExp(untpl(re2.tpl_email_fuzzy), "i");
  re2.link_fuzzy = RegExp(untpl(re2.tpl_link_fuzzy), "i");
  re2.link_no_ip_fuzzy = RegExp(untpl(re2.tpl_link_no_ip_fuzzy), "i");
  re2.host_fuzzy_test = RegExp(untpl(re2.tpl_host_fuzzy_test), "i");
  const aliases = [];
  self2.__compiled__ = {};
  function schemaError(name2, val) {
    throw new Error('(LinkifyIt) Invalid schema "' + name2 + '": ' + val);
  }
  __name(schemaError, "schemaError");
  Object.keys(self2.__schemas__).forEach(function(name2) {
    const val = self2.__schemas__[name2];
    if (val === null) {
      return;
    }
    const compiled = { validate: null, link: null };
    self2.__compiled__[name2] = compiled;
    if (isObject$1(val)) {
      if (isRegExp(val.validate)) {
        compiled.validate = createValidator(val.validate);
      } else if (isFunction(val.validate)) {
        compiled.validate = val.validate;
      } else {
        schemaError(name2, val);
      }
      if (isFunction(val.normalize)) {
        compiled.normalize = val.normalize;
      } else if (!val.normalize) {
        compiled.normalize = createNormalizer();
      } else {
        schemaError(name2, val);
      }
      return;
    }
    if (isString$1(val)) {
      aliases.push(name2);
      return;
    }
    schemaError(name2, val);
  });
  aliases.forEach(function(alias) {
    if (!self2.__compiled__[self2.__schemas__[alias]]) {
      return;
    }
    self2.__compiled__[alias].validate = self2.__compiled__[self2.__schemas__[alias]].validate;
    self2.__compiled__[alias].normalize = self2.__compiled__[self2.__schemas__[alias]].normalize;
  });
  self2.__compiled__[""] = { validate: null, normalize: createNormalizer() };
  const slist = Object.keys(self2.__compiled__).filter(function(name2) {
    return name2.length > 0 && self2.__compiled__[name2];
  }).map(escapeRE).join("|");
  self2.re.schema_test = RegExp("(^|(?!_)(?:[><｜]|" + re2.src_ZPCc + "))(" + slist + ")", "i");
  self2.re.schema_search = RegExp("(^|(?!_)(?:[><｜]|" + re2.src_ZPCc + "))(" + slist + ")", "ig");
  self2.re.schema_at_start = RegExp("^" + self2.re.schema_search.source, "i");
  self2.re.pretest = RegExp(
    "(" + self2.re.schema_test.source + ")|(" + self2.re.host_fuzzy_test.source + ")|@",
    "i"
  );
  resetScanCache(self2);
}
__name(compile, "compile");
function Match(self2, shift2) {
  const start2 = self2.__index__;
  const end = self2.__last_index__;
  const text2 = self2.__text_cache__.slice(start2, end);
  this.schema = self2.__schema__.toLowerCase();
  this.index = start2 + shift2;
  this.lastIndex = end + shift2;
  this.raw = text2;
  this.text = text2;
  this.url = text2;
}
__name(Match, "Match");
function createMatch(self2, shift2) {
  const match2 = new Match(self2, shift2);
  self2.__compiled__[match2.schema].normalize(match2, self2);
  return match2;
}
__name(createMatch, "createMatch");
function LinkifyIt(schemas, options2) {
  if (!(this instanceof LinkifyIt)) {
    return new LinkifyIt(schemas, options2);
  }
  if (!options2) {
    if (isOptionsObj(schemas)) {
      options2 = schemas;
      schemas = {};
    }
  }
  this.__opts__ = assign({}, defaultOptions, options2);
  this.__index__ = -1;
  this.__last_index__ = -1;
  this.__schema__ = "";
  this.__text_cache__ = "";
  this.__schemas__ = assign({}, defaultSchemas, schemas);
  this.__compiled__ = {};
  this.__tlds__ = tlds_default;
  this.__tlds_replaced__ = false;
  this.re = {};
  compile(this);
}
__name(LinkifyIt, "LinkifyIt");
LinkifyIt.prototype.add = /* @__PURE__ */ __name(function add2(schema2, definition) {
  this.__schemas__[schema2] = definition;
  compile(this);
  return this;
}, "add");
LinkifyIt.prototype.set = /* @__PURE__ */ __name(function set2(options2) {
  this.__opts__ = assign(this.__opts__, options2);
  return this;
}, "set");
LinkifyIt.prototype.test = /* @__PURE__ */ __name(function test2(text2) {
  this.__text_cache__ = text2;
  this.__index__ = -1;
  if (!text2.length) {
    return false;
  }
  let m2, ml, me2, len, shift2, next, re2, tld_pos, at_pos;
  if (this.re.schema_test.test(text2)) {
    re2 = this.re.schema_search;
    re2.lastIndex = 0;
    while ((m2 = re2.exec(text2)) !== null) {
      len = this.testSchemaAt(text2, m2[2], re2.lastIndex);
      if (len) {
        this.__schema__ = m2[2];
        this.__index__ = m2.index + m2[1].length;
        this.__last_index__ = m2.index + m2[0].length + len;
        break;
      }
    }
  }
  if (this.__opts__.fuzzyLink && this.__compiled__["http:"]) {
    tld_pos = text2.search(this.re.host_fuzzy_test);
    if (tld_pos >= 0) {
      if (this.__index__ < 0 || tld_pos < this.__index__) {
        if ((ml = text2.match(this.__opts__.fuzzyIP ? this.re.link_fuzzy : this.re.link_no_ip_fuzzy)) !== null) {
          shift2 = ml.index + ml[1].length;
          if (this.__index__ < 0 || shift2 < this.__index__) {
            this.__schema__ = "";
            this.__index__ = shift2;
            this.__last_index__ = ml.index + ml[0].length;
          }
        }
      }
    }
  }
  if (this.__opts__.fuzzyEmail && this.__compiled__["mailto:"]) {
    at_pos = text2.indexOf("@");
    if (at_pos >= 0) {
      if ((me2 = text2.match(this.re.email_fuzzy)) !== null) {
        shift2 = me2.index + me2[1].length;
        next = me2.index + me2[0].length;
        if (this.__index__ < 0 || shift2 < this.__index__ || shift2 === this.__index__ && next > this.__last_index__) {
          this.__schema__ = "mailto:";
          this.__index__ = shift2;
          this.__last_index__ = next;
        }
      }
    }
  }
  return this.__index__ >= 0;
}, "test");
LinkifyIt.prototype.pretest = /* @__PURE__ */ __name(function pretest(text2) {
  return this.re.pretest.test(text2);
}, "pretest");
LinkifyIt.prototype.testSchemaAt = /* @__PURE__ */ __name(function testSchemaAt(text2, schema2, pos) {
  if (!this.__compiled__[schema2.toLowerCase()]) {
    return 0;
  }
  return this.__compiled__[schema2.toLowerCase()].validate(text2, pos, this);
}, "testSchemaAt");
LinkifyIt.prototype.match = /* @__PURE__ */ __name(function match(text2) {
  const result = [];
  let shift2 = 0;
  if (this.__index__ >= 0 && this.__text_cache__ === text2) {
    result.push(createMatch(this, shift2));
    shift2 = this.__last_index__;
  }
  let tail = shift2 ? text2.slice(shift2) : text2;
  while (this.test(tail)) {
    result.push(createMatch(this, shift2));
    tail = tail.slice(this.__last_index__);
    shift2 += this.__last_index__;
  }
  if (result.length) {
    return result;
  }
  return null;
}, "match");
LinkifyIt.prototype.matchAtStart = /* @__PURE__ */ __name(function matchAtStart(text2) {
  this.__text_cache__ = text2;
  this.__index__ = -1;
  if (!text2.length) return null;
  const m2 = this.re.schema_at_start.exec(text2);
  if (!m2) return null;
  const len = this.testSchemaAt(text2, m2[2], m2[0].length);
  if (!len) return null;
  this.__schema__ = m2[2];
  this.__index__ = m2.index + m2[1].length;
  this.__last_index__ = m2.index + m2[0].length + len;
  return createMatch(this, 0);
}, "matchAtStart");
LinkifyIt.prototype.tlds = /* @__PURE__ */ __name(function tlds2(list2, keepOld) {
  list2 = Array.isArray(list2) ? list2 : [list2];
  if (!keepOld) {
    this.__tlds__ = list2.slice();
    this.__tlds_replaced__ = true;
    compile(this);
    return this;
  }
  this.__tlds__ = this.__tlds__.concat(list2).sort().filter(function(el, idx, arr) {
    return el !== arr[idx - 1];
  }).reverse();
  compile(this);
  return this;
}, "tlds");
LinkifyIt.prototype.normalize = /* @__PURE__ */ __name(function normalize2(match2) {
  if (!match2.schema) {
    match2.url = "http://" + match2.url;
  }
  if (match2.schema === "mailto:" && !/^mailto:/i.test(match2.url)) {
    match2.url = "mailto:" + match2.url;
  }
}, "normalize");
LinkifyIt.prototype.onCompile = /* @__PURE__ */ __name(function onCompile() {
}, "onCompile");
"use strict";
const maxInt = 2147483647;
const base = 36;
const tMin = 1;
const tMax = 26;
const skew = 38;
const damp = 700;
const initialBias = 72;
const initialN = 128;
const delimiter = "-";
const regexPunycode = /^xn--/;
const regexNonASCII = /[^\0-\x7F]/;
const regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g;
const errors = {
  "overflow": "Overflow: input needs wider integers to process",
  "not-basic": "Illegal input >= 0x80 (not a basic code point)",
  "invalid-input": "Invalid input"
};
const baseMinusTMin = base - tMin;
const floor = Math.floor;
const stringFromCharCode = String.fromCharCode;
function error(type) {
  throw new RangeError(errors[type]);
}
__name(error, "error");
function map(array, callback) {
  const result = [];
  let length = array.length;
  while (length--) {
    result[length] = callback(array[length]);
  }
  return result;
}
__name(map, "map");
function mapDomain(domain2, callback) {
  const parts2 = domain2.split("@");
  let result = "";
  if (parts2.length > 1) {
    result = parts2[0] + "@";
    domain2 = parts2[1];
  }
  domain2 = domain2.replace(regexSeparators, ".");
  const labels = domain2.split(".");
  const encoded = map(labels, callback).join(".");
  return result + encoded;
}
__name(mapDomain, "mapDomain");
function ucs2decode(string) {
  const output = [];
  let counter = 0;
  const length = string.length;
  while (counter < length) {
    const value = string.charCodeAt(counter++);
    if (value >= 55296 && value <= 56319 && counter < length) {
      const extra = string.charCodeAt(counter++);
      if ((extra & 64512) == 56320) {
        output.push(((value & 1023) << 10) + (extra & 1023) + 65536);
      } else {
        output.push(value);
        counter--;
      }
    } else {
      output.push(value);
    }
  }
  return output;
}
__name(ucs2decode, "ucs2decode");
const ucs2encode = /* @__PURE__ */ __name((codePoints) => String.fromCodePoint(...codePoints), "ucs2encode");
const basicToDigit = /* @__PURE__ */ __name(function(codePoint) {
  if (codePoint >= 48 && codePoint < 58) {
    return 26 + (codePoint - 48);
  }
  if (codePoint >= 65 && codePoint < 91) {
    return codePoint - 65;
  }
  if (codePoint >= 97 && codePoint < 123) {
    return codePoint - 97;
  }
  return base;
}, "basicToDigit");
const digitToBasic = /* @__PURE__ */ __name(function(digit, flag) {
  return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
}, "digitToBasic");
const adapt = /* @__PURE__ */ __name(function(delta2, numPoints, firstTime) {
  let k2 = 0;
  delta2 = firstTime ? floor(delta2 / damp) : delta2 >> 1;
  delta2 += floor(delta2 / numPoints);
  for (; delta2 > baseMinusTMin * tMax >> 1; k2 += base) {
    delta2 = floor(delta2 / baseMinusTMin);
  }
  return floor(k2 + (baseMinusTMin + 1) * delta2 / (delta2 + skew));
}, "adapt");
const decode = /* @__PURE__ */ __name(function(input) {
  const output = [];
  const inputLength = input.length;
  let i2 = 0;
  let n2 = initialN;
  let bias = initialBias;
  let basic = input.lastIndexOf(delimiter);
  if (basic < 0) {
    basic = 0;
  }
  for (let j2 = 0; j2 < basic; ++j2) {
    if (input.charCodeAt(j2) >= 128) {
      error("not-basic");
    }
    output.push(input.charCodeAt(j2));
  }
  for (let index2 = basic > 0 ? basic + 1 : 0; index2 < inputLength; ) {
    const oldi = i2;
    for (let w2 = 1, k2 = base; ; k2 += base) {
      if (index2 >= inputLength) {
        error("invalid-input");
      }
      const digit = basicToDigit(input.charCodeAt(index2++));
      if (digit >= base) {
        error("invalid-input");
      }
      if (digit > floor((maxInt - i2) / w2)) {
        error("overflow");
      }
      i2 += digit * w2;
      const t2 = k2 <= bias ? tMin : k2 >= bias + tMax ? tMax : k2 - bias;
      if (digit < t2) {
        break;
      }
      const baseMinusT = base - t2;
      if (w2 > floor(maxInt / baseMinusT)) {
        error("overflow");
      }
      w2 *= baseMinusT;
    }
    const out = output.length + 1;
    bias = adapt(i2 - oldi, out, oldi == 0);
    if (floor(i2 / out) > maxInt - n2) {
      error("overflow");
    }
    n2 += floor(i2 / out);
    i2 %= out;
    output.splice(i2++, 0, n2);
  }
  return String.fromCodePoint(...output);
}, "decode");
const encode = /* @__PURE__ */ __name(function(input) {
  const output = [];
  input = ucs2decode(input);
  const inputLength = input.length;
  let n2 = initialN;
  let delta2 = 0;
  let bias = initialBias;
  for (const currentValue of input) {
    if (currentValue < 128) {
      output.push(stringFromCharCode(currentValue));
    }
  }
  const basicLength = output.length;
  let handledCPCount = basicLength;
  if (basicLength) {
    output.push(delimiter);
  }
  while (handledCPCount < inputLength) {
    let m2 = maxInt;
    for (const currentValue of input) {
      if (currentValue >= n2 && currentValue < m2) {
        m2 = currentValue;
      }
    }
    const handledCPCountPlusOne = handledCPCount + 1;
    if (m2 - n2 > floor((maxInt - delta2) / handledCPCountPlusOne)) {
      error("overflow");
    }
    delta2 += (m2 - n2) * handledCPCountPlusOne;
    n2 = m2;
    for (const currentValue of input) {
      if (currentValue < n2 && ++delta2 > maxInt) {
        error("overflow");
      }
      if (currentValue === n2) {
        let q2 = delta2;
        for (let k2 = base; ; k2 += base) {
          const t2 = k2 <= bias ? tMin : k2 >= bias + tMax ? tMax : k2 - bias;
          if (q2 < t2) {
            break;
          }
          const qMinusT = q2 - t2;
          const baseMinusT = base - t2;
          output.push(
            stringFromCharCode(digitToBasic(t2 + qMinusT % baseMinusT, 0))
          );
          q2 = floor(qMinusT / baseMinusT);
        }
        output.push(stringFromCharCode(digitToBasic(q2, 0)));
        bias = adapt(delta2, handledCPCountPlusOne, handledCPCount === basicLength);
        delta2 = 0;
        ++handledCPCount;
      }
    }
    ++delta2;
    ++n2;
  }
  return output.join("");
}, "encode");
const toUnicode = /* @__PURE__ */ __name(function(input) {
  return mapDomain(input, function(string) {
    return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string;
  });
}, "toUnicode");
const toASCII = /* @__PURE__ */ __name(function(input) {
  return mapDomain(input, function(string) {
    return regexNonASCII.test(string) ? "xn--" + encode(string) : string;
  });
}, "toASCII");
const punycode = {
  /**
   * A string representing the current Punycode.js version number.
   * @memberOf punycode
   * @type String
   */
  "version": "2.3.1",
  /**
   * An object of methods to convert from JavaScript's internal character
   * representation (UCS-2) to Unicode code points, and back.
   * @see <https://mathiasbynens.be/notes/javascript-encoding>
   * @memberOf punycode
   * @type Object
   */
  "ucs2": {
    "decode": ucs2decode,
    "encode": ucs2encode
  },
  "decode": decode,
  "encode": encode,
  "toASCII": toASCII,
  "toUnicode": toUnicode
};
const cfg_default = {
  options: {
    // Enable HTML tags in source
    html: false,
    // Use '/' to close single tags (<br />)
    xhtmlOut: false,
    // Convert '\n' in paragraphs into <br>
    breaks: false,
    // CSS language prefix for fenced blocks
    langPrefix: "language-",
    // autoconvert URL-like texts to links
    linkify: false,
    // Enable some language-neutral replacements + quotes beautification
    typographer: false,
    // Double + single quotes replacement pairs, when typographer enabled,
    // and smartquotes on. Could be either a String or an Array.
    //
    // For example, you can use '«»„“' for Russian, '„“‚‘' for German,
    // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp).
    quotes: "“”‘’",
    /* “”‘’ */
    // Highlighter function. Should return escaped HTML,
    // or '' if the source string is not changed and should be escaped externaly.
    // If result starts with <pre... internal wrapper is skipped.
    //
    // function (/*str, lang*/) { return ''; }
    //
    highlight: null,
    // Internal protection, recursion limit
    maxNesting: 100
  },
  components: {
    core: {},
    block: {},
    inline: {}
  }
};
const cfg_zero = {
  options: {
    // Enable HTML tags in source
    html: false,
    // Use '/' to close single tags (<br />)
    xhtmlOut: false,
    // Convert '\n' in paragraphs into <br>
    breaks: false,
    // CSS language prefix for fenced blocks
    langPrefix: "language-",
    // autoconvert URL-like texts to links
    linkify: false,
    // Enable some language-neutral replacements + quotes beautification
    typographer: false,
    // Double + single quotes replacement pairs, when typographer enabled,
    // and smartquotes on. Could be either a String or an Array.
    //
    // For example, you can use '«»„“' for Russian, '„“‚‘' for German,
    // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp).
    quotes: "“”‘’",
    /* “”‘’ */
    // Highlighter function. Should return escaped HTML,
    // or '' if the source string is not changed and should be escaped externaly.
    // If result starts with <pre... internal wrapper is skipped.
    //
    // function (/*str, lang*/) { return ''; }
    //
    highlight: null,
    // Internal protection, recursion limit
    maxNesting: 20
  },
  components: {
    core: {
      rules: [
        "normalize",
        "block",
        "inline",
        "text_join"
      ]
    },
    block: {
      rules: [
        "paragraph"
      ]
    },
    inline: {
      rules: [
        "text"
      ],
      rules2: [
        "balance_pairs",
        "fragments_join"
      ]
    }
  }
};
const cfg_commonmark = {
  options: {
    // Enable HTML tags in source
    html: true,
    // Use '/' to close single tags (<br />)
    xhtmlOut: true,
    // Convert '\n' in paragraphs into <br>
    breaks: false,
    // CSS language prefix for fenced blocks
    langPrefix: "language-",
    // autoconvert URL-like texts to links
    linkify: false,
    // Enable some language-neutral replacements + quotes beautification
    typographer: false,
    // Double + single quotes replacement pairs, when typographer enabled,
    // and smartquotes on. Could be either a String or an Array.
    //
    // For example, you can use '«»„“' for Russian, '„“‚‘' for German,
    // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp).
    quotes: "“”‘’",
    /* “”‘’ */
    // Highlighter function. Should return escaped HTML,
    // or '' if the source string is not changed and should be escaped externaly.
    // If result starts with <pre... internal wrapper is skipped.
    //
    // function (/*str, lang*/) { return ''; }
    //
    highlight: null,
    // Internal protection, recursion limit
    maxNesting: 20
  },
  components: {
    core: {
      rules: [
        "normalize",
        "block",
        "inline",
        "text_join"
      ]
    },
    block: {
      rules: [
        "blockquote",
        "code",
        "fence",
        "heading",
        "hr",
        "html_block",
        "lheading",
        "list",
        "reference",
        "paragraph"
      ]
    },
    inline: {
      rules: [
        "autolink",
        "backticks",
        "emphasis",
        "entity",
        "escape",
        "html_inline",
        "image",
        "link",
        "newline",
        "text"
      ],
      rules2: [
        "balance_pairs",
        "emphasis",
        "fragments_join"
      ]
    }
  }
};
const config = {
  default: cfg_default,
  zero: cfg_zero,
  commonmark: cfg_commonmark
};
const BAD_PROTO_RE = /^(vbscript|javascript|file|data):/;
const GOOD_DATA_RE = /^data:image\/(gif|png|jpeg|webp);/;
function validateLink(url) {
  const str = url.trim().toLowerCase();
  return BAD_PROTO_RE.test(str) ? GOOD_DATA_RE.test(str) : true;
}
__name(validateLink, "validateLink");
const RECODE_HOSTNAME_FOR = ["http:", "https:", "mailto:"];
function normalizeLink(url) {
  const parsed = urlParse(url, true);
  if (parsed.hostname) {
    if (!parsed.protocol || RECODE_HOSTNAME_FOR.indexOf(parsed.protocol) >= 0) {
      try {
        parsed.hostname = punycode.toASCII(parsed.hostname);
      } catch (er) {
      }
    }
  }
  return encode$2(format$1(parsed));
}
__name(normalizeLink, "normalizeLink");
function normalizeLinkText(url) {
  const parsed = urlParse(url, true);
  if (parsed.hostname) {
    if (!parsed.protocol || RECODE_HOSTNAME_FOR.indexOf(parsed.protocol) >= 0) {
      try {
        parsed.hostname = punycode.toUnicode(parsed.hostname);
      } catch (er) {
      }
    }
  }
  return decode$2(format$1(parsed), decode$2.defaultChars + "%");
}
__name(normalizeLinkText, "normalizeLinkText");
function MarkdownIt(presetName, options2) {
  if (!(this instanceof MarkdownIt)) {
    return new MarkdownIt(presetName, options2);
  }
  if (!options2) {
    if (!isString$2(presetName)) {
      options2 = presetName || {};
      presetName = "default";
    }
  }
  this.inline = new ParserInline();
  this.block = new ParserBlock();
  this.core = new Core();
  this.renderer = new Renderer();
  this.linkify = new LinkifyIt();
  this.validateLink = validateLink;
  this.normalizeLink = normalizeLink;
  this.normalizeLinkText = normalizeLinkText;
  this.utils = utils;
  this.helpers = assign$1({}, helpers);
  this.options = {};
  this.configure(presetName);
  if (options2) {
    this.set(options2);
  }
}
__name(MarkdownIt, "MarkdownIt");
MarkdownIt.prototype.set = function(options2) {
  assign$1(this.options, options2);
  return this;
};
MarkdownIt.prototype.configure = function(presets) {
  const self2 = this;
  if (isString$2(presets)) {
    const presetName = presets;
    presets = config[presetName];
    if (!presets) {
      throw new Error('Wrong `markdown-it` preset "' + presetName + '", check name');
    }
  }
  if (!presets) {
    throw new Error("Wrong `markdown-it` preset, can't be empty");
  }
  if (presets.options) {
    self2.set(presets.options);
  }
  if (presets.components) {
    Object.keys(presets.components).forEach(function(name2) {
      if (presets.components[name2].rules) {
        self2[name2].ruler.enableOnly(presets.components[name2].rules);
      }
      if (presets.components[name2].rules2) {
        self2[name2].ruler2.enableOnly(presets.components[name2].rules2);
      }
    });
  }
  return this;
};
MarkdownIt.prototype.enable = function(list2, ignoreInvalid) {
  let result = [];
  if (!Array.isArray(list2)) {
    list2 = [list2];
  }
  ["core", "block", "inline"].forEach(function(chain) {
    result = result.concat(this[chain].ruler.enable(list2, true));
  }, this);
  result = result.concat(this.inline.ruler2.enable(list2, true));
  const missed = list2.filter(function(name2) {
    return result.indexOf(name2) < 0;
  });
  if (missed.length && !ignoreInvalid) {
    throw new Error("MarkdownIt. Failed to enable unknown rule(s): " + missed);
  }
  return this;
};
MarkdownIt.prototype.disable = function(list2, ignoreInvalid) {
  let result = [];
  if (!Array.isArray(list2)) {
    list2 = [list2];
  }
  ["core", "block", "inline"].forEach(function(chain) {
    result = result.concat(this[chain].ruler.disable(list2, true));
  }, this);
  result = result.concat(this.inline.ruler2.disable(list2, true));
  const missed = list2.filter(function(name2) {
    return result.indexOf(name2) < 0;
  });
  if (missed.length && !ignoreInvalid) {
    throw new Error("MarkdownIt. Failed to disable unknown rule(s): " + missed);
  }
  return this;
};
MarkdownIt.prototype.use = function(plugin) {
  const args = [this].concat(Array.prototype.slice.call(arguments, 1));
  plugin.apply(plugin, args);
  return this;
};
MarkdownIt.prototype.parse = function(src, env) {
  if (typeof src !== "string") {
    throw new Error("Input data should be a String");
  }
  const state = new this.core.State(src, this, env);
  this.core.process(state);
  return state.tokens;
};
MarkdownIt.prototype.render = function(src, env) {
  env = env || {};
  return this.renderer.render(this.parse(src, env), this.options, env);
};
MarkdownIt.prototype.parseInline = function(src, env) {
  const state = new this.core.State(src, this, env);
  state.inlineMode = true;
  this.core.process(state);
  return state.tokens;
};
MarkdownIt.prototype.renderInline = function(src, env) {
  env = env || {};
  return this.renderer.render(this.parseInline(src, env), this.options, env);
};
const schema = new Schema({
  nodes: {
    doc: {
      content: "block+"
    },
    paragraph: {
      content: "inline*",
      group: "block",
      parseDOM: [{ tag: "p" }],
      toDOM() {
        return ["p", 0];
      }
    },
    blockquote: {
      content: "block+",
      group: "block",
      parseDOM: [{ tag: "blockquote" }],
      toDOM() {
        return ["blockquote", 0];
      }
    },
    horizontal_rule: {
      group: "block",
      parseDOM: [{ tag: "hr" }],
      toDOM() {
        return ["div", ["hr"]];
      }
    },
    heading: {
      attrs: { level: { default: 1 } },
      content: "(text | image)*",
      group: "block",
      defining: true,
      parseDOM: [
        { tag: "h1", attrs: { level: 1 } },
        { tag: "h2", attrs: { level: 2 } },
        { tag: "h3", attrs: { level: 3 } },
        { tag: "h4", attrs: { level: 4 } },
        { tag: "h5", attrs: { level: 5 } },
        { tag: "h6", attrs: { level: 6 } }
      ],
      toDOM(node2) {
        return ["h" + node2.attrs.level, 0];
      }
    },
    code_block: {
      content: "text*",
      group: "block",
      code: true,
      defining: true,
      marks: "",
      attrs: { params: { default: "" } },
      parseDOM: [{ tag: "pre", preserveWhitespace: "full", getAttrs: /* @__PURE__ */ __name((node2) => ({ params: node2.getAttribute("data-params") || "" }), "getAttrs") }],
      toDOM(node2) {
        return ["pre", node2.attrs.params ? { "data-params": node2.attrs.params } : {}, ["code", 0]];
      }
    },
    ordered_list: {
      content: "list_item+",
      group: "block",
      attrs: { order: { default: 1 }, tight: { default: false } },
      parseDOM: [{ tag: "ol", getAttrs(dom) {
        return {
          order: dom.hasAttribute("start") ? +dom.getAttribute("start") : 1,
          tight: dom.hasAttribute("data-tight")
        };
      } }],
      toDOM(node2) {
        return ["ol", {
          start: node2.attrs.order == 1 ? null : node2.attrs.order,
          "data-tight": node2.attrs.tight ? "true" : null
        }, 0];
      }
    },
    bullet_list: {
      content: "list_item+",
      group: "block",
      attrs: { tight: { default: false } },
      parseDOM: [{ tag: "ul", getAttrs: /* @__PURE__ */ __name((dom) => ({ tight: dom.hasAttribute("data-tight") }), "getAttrs") }],
      toDOM(node2) {
        return ["ul", { "data-tight": node2.attrs.tight ? "true" : null }, 0];
      }
    },
    list_item: {
      content: "block+",
      defining: true,
      parseDOM: [{ tag: "li" }],
      toDOM() {
        return ["li", 0];
      }
    },
    text: {
      group: "inline"
    },
    image: {
      inline: true,
      attrs: {
        src: {},
        alt: { default: null },
        title: { default: null }
      },
      group: "inline",
      draggable: true,
      parseDOM: [{ tag: "img[src]", getAttrs(dom) {
        return {
          src: dom.getAttribute("src"),
          title: dom.getAttribute("title"),
          alt: dom.getAttribute("alt")
        };
      } }],
      toDOM(node2) {
        return ["img", node2.attrs];
      }
    },
    hard_break: {
      inline: true,
      group: "inline",
      selectable: false,
      parseDOM: [{ tag: "br" }],
      toDOM() {
        return ["br"];
      }
    }
  },
  marks: {
    em: {
      parseDOM: [
        { tag: "i" },
        { tag: "em" },
        { style: "font-style=italic" },
        { style: "font-style=normal", clearMark: /* @__PURE__ */ __name((m2) => m2.type.name == "em", "clearMark") }
      ],
      toDOM() {
        return ["em"];
      }
    },
    strong: {
      parseDOM: [
        { tag: "strong" },
        { tag: "b", getAttrs: /* @__PURE__ */ __name((node2) => node2.style.fontWeight != "normal" && null, "getAttrs") },
        { style: "font-weight=400", clearMark: /* @__PURE__ */ __name((m2) => m2.type.name == "strong", "clearMark") },
        { style: "font-weight", getAttrs: /* @__PURE__ */ __name((value) => /^(bold(er)?|[5-9]\d{2,})$/.test(value) && null, "getAttrs") }
      ],
      toDOM() {
        return ["strong"];
      }
    },
    link: {
      attrs: {
        href: {},
        title: { default: null }
      },
      inclusive: false,
      parseDOM: [{ tag: "a[href]", getAttrs(dom) {
        return { href: dom.getAttribute("href"), title: dom.getAttribute("title") };
      } }],
      toDOM(node2) {
        return ["a", node2.attrs];
      }
    },
    code: {
      parseDOM: [{ tag: "code" }],
      toDOM() {
        return ["code"];
      }
    }
  }
});
function maybeMerge(a2, b2) {
  if (a2.isText && b2.isText && Mark$1.sameSet(a2.marks, b2.marks))
    return a2.withText(a2.text + b2.text);
}
__name(maybeMerge, "maybeMerge");
class MarkdownParseState {
  static {
    __name(this, "MarkdownParseState");
  }
  constructor(schema2, tokenHandlers2) {
    this.schema = schema2;
    this.tokenHandlers = tokenHandlers2;
    this.stack = [{ type: schema2.topNodeType, attrs: null, content: [], marks: Mark$1.none }];
  }
  top() {
    return this.stack[this.stack.length - 1];
  }
  push(elt) {
    if (this.stack.length)
      this.top().content.push(elt);
  }
  // Adds the given text to the current position in the document,
  // using the current marks as styling.
  addText(text2) {
    if (!text2)
      return;
    let top = this.top(), nodes = top.content, last = nodes[nodes.length - 1];
    let node2 = this.schema.text(text2, top.marks), merged;
    if (last && (merged = maybeMerge(last, node2)))
      nodes[nodes.length - 1] = merged;
    else
      nodes.push(node2);
  }
  // Adds the given mark to the set of active marks.
  openMark(mark) {
    let top = this.top();
    top.marks = mark.addToSet(top.marks);
  }
  // Removes the given mark from the set of active marks.
  closeMark(mark) {
    let top = this.top();
    top.marks = mark.removeFromSet(top.marks);
  }
  parseTokens(toks) {
    for (let i2 = 0; i2 < toks.length; i2++) {
      let tok = toks[i2];
      let handler5 = this.tokenHandlers[tok.type];
      if (!handler5)
        throw new Error("Token type `" + tok.type + "` not supported by Markdown parser");
      handler5(this, tok, toks, i2);
    }
  }
  // Add a node at the current position.
  addNode(type, attrs2, content) {
    let top = this.top();
    let node2 = type.createAndFill(attrs2, content, top ? top.marks : []);
    if (!node2)
      return null;
    this.push(node2);
    return node2;
  }
  // Wrap subsequent content in a node of the given type.
  openNode(type, attrs2) {
    this.stack.push({ type, attrs: attrs2, content: [], marks: Mark$1.none });
  }
  // Close and return the node that is currently on top of the stack.
  closeNode() {
    let info = this.stack.pop();
    return this.addNode(info.type, info.attrs, info.content);
  }
}
function attrs(spec, token, tokens, i2) {
  if (spec.getAttrs)
    return spec.getAttrs(token, tokens, i2);
  else if (spec.attrs instanceof Function)
    return spec.attrs(token);
  else
    return spec.attrs;
}
__name(attrs, "attrs");
function noCloseToken(spec, type) {
  return spec.noCloseToken || type == "code_inline" || type == "code_block" || type == "fence";
}
__name(noCloseToken, "noCloseToken");
function withoutTrailingNewline(str) {
  return str[str.length - 1] == "\n" ? str.slice(0, str.length - 1) : str;
}
__name(withoutTrailingNewline, "withoutTrailingNewline");
function noOp() {
}
__name(noOp, "noOp");
function tokenHandlers(schema2, tokens) {
  let handlers2 = /* @__PURE__ */ Object.create(null);
  for (let type in tokens) {
    let spec = tokens[type];
    if (spec.block) {
      let nodeType = schema2.nodeType(spec.block);
      if (noCloseToken(spec, type)) {
        handlers2[type] = (state, tok, tokens2, i2) => {
          state.openNode(nodeType, attrs(spec, tok, tokens2, i2));
          state.addText(withoutTrailingNewline(tok.content));
          state.closeNode();
        };
      } else {
        handlers2[type + "_open"] = (state, tok, tokens2, i2) => state.openNode(nodeType, attrs(spec, tok, tokens2, i2));
        handlers2[type + "_close"] = (state) => state.closeNode();
      }
    } else if (spec.node) {
      let nodeType = schema2.nodeType(spec.node);
      handlers2[type] = (state, tok, tokens2, i2) => state.addNode(nodeType, attrs(spec, tok, tokens2, i2));
    } else if (spec.mark) {
      let markType = schema2.marks[spec.mark];
      if (noCloseToken(spec, type)) {
        handlers2[type] = (state, tok, tokens2, i2) => {
          state.openMark(markType.create(attrs(spec, tok, tokens2, i2)));
          state.addText(withoutTrailingNewline(tok.content));
          state.closeMark(markType);
        };
      } else {
        handlers2[type + "_open"] = (state, tok, tokens2, i2) => state.openMark(markType.create(attrs(spec, tok, tokens2, i2)));
        handlers2[type + "_close"] = (state) => state.closeMark(markType);
      }
    } else if (spec.ignore) {
      if (noCloseToken(spec, type)) {
        handlers2[type] = noOp;
      } else {
        handlers2[type + "_open"] = noOp;
        handlers2[type + "_close"] = noOp;
      }
    } else {
      throw new RangeError("Unrecognized parsing spec " + JSON.stringify(spec));
    }
  }
  handlers2.text = (state, tok) => state.addText(tok.content);
  handlers2.inline = (state, tok) => state.parseTokens(tok.children);
  handlers2.softbreak = handlers2.softbreak || ((state) => state.addText(" "));
  return handlers2;
}
__name(tokenHandlers, "tokenHandlers");
let MarkdownParser$1 = class MarkdownParser2 {
  static {
    __name(this, "MarkdownParser");
  }
  /**
  Create a parser with the given configuration. You can configure
  the markdown-it parser to parse the dialect you want, and provide
  a description of the ProseMirror entities those tokens map to in
  the `tokens` object, which maps token names to descriptions of
  what to do with them. Such a description is an object, and may
  have the following properties:
  */
  constructor(schema2, tokenizer, tokens) {
    this.schema = schema2;
    this.tokenizer = tokenizer;
    this.tokens = tokens;
    this.tokenHandlers = tokenHandlers(schema2, tokens);
  }
  /**
  Parse a string as [CommonMark](http://commonmark.org/) markup,
  and create a ProseMirror document as prescribed by this parser's
  rules.
  
  The second argument, when given, is passed through to the
  [Markdown
  parser](https://markdown-it.github.io/markdown-it/#MarkdownIt.parse).
  */
  parse(text2, markdownEnv = {}) {
    let state = new MarkdownParseState(this.schema, this.tokenHandlers), doc2;
    state.parseTokens(this.tokenizer.parse(text2, markdownEnv));
    do {
      doc2 = state.closeNode();
    } while (state.stack.length);
    return doc2 || this.schema.topNodeType.createAndFill();
  }
};
function listIsTight(tokens, i2) {
  while (++i2 < tokens.length)
    if (tokens[i2].type != "list_item_open")
      return tokens[i2].hidden;
  return false;
}
__name(listIsTight, "listIsTight");
const defaultMarkdownParser = new MarkdownParser$1(schema, MarkdownIt("commonmark", { html: false }), {
  blockquote: { block: "blockquote" },
  paragraph: { block: "paragraph" },
  list_item: { block: "list_item" },
  bullet_list: { block: "bullet_list", getAttrs: /* @__PURE__ */ __name((_2, tokens, i2) => ({ tight: listIsTight(tokens, i2) }), "getAttrs") },
  ordered_list: { block: "ordered_list", getAttrs: /* @__PURE__ */ __name((tok, tokens, i2) => ({
    order: +tok.attrGet("start") || 1,
    tight: listIsTight(tokens, i2)
  }), "getAttrs") },
  heading: { block: "heading", getAttrs: /* @__PURE__ */ __name((tok) => ({ level: +tok.tag.slice(1) }), "getAttrs") },
  code_block: { block: "code_block", noCloseToken: true },
  fence: { block: "code_block", getAttrs: /* @__PURE__ */ __name((tok) => ({ params: tok.info || "" }), "getAttrs"), noCloseToken: true },
  hr: { node: "horizontal_rule" },
  image: { node: "image", getAttrs: /* @__PURE__ */ __name((tok) => ({
    src: tok.attrGet("src"),
    title: tok.attrGet("title") || null,
    alt: tok.children[0] && tok.children[0].content || null
  }), "getAttrs") },
  hardbreak: { node: "hard_break" },
  em: { mark: "em" },
  strong: { mark: "strong" },
  link: { mark: "link", getAttrs: /* @__PURE__ */ __name((tok) => ({
    href: tok.attrGet("href"),
    title: tok.attrGet("title") || null
  }), "getAttrs") },
  code_inline: { mark: "code", noCloseToken: true }
});
const blankMark = { open: "", close: "", mixable: true };
let MarkdownSerializer$1 = class MarkdownSerializer2 {
  static {
    __name(this, "MarkdownSerializer");
  }
  /**
  Construct a serializer with the given configuration. The `nodes`
  object should map node names in a given schema to function that
  take a serializer state and such a node, and serialize the node.
  */
  constructor(nodes, marks, options2 = {}) {
    this.nodes = nodes;
    this.marks = marks;
    this.options = options2;
  }
  /**
  Serialize the content of the given node to
  [CommonMark](http://commonmark.org/).
  */
  serialize(content, options2 = {}) {
    options2 = Object.assign({}, this.options, options2);
    let state = new MarkdownSerializerState$1(this.nodes, this.marks, options2);
    state.renderContent(content);
    return state.out;
  }
};
const defaultMarkdownSerializer = new MarkdownSerializer$1({
  blockquote(state, node2) {
    state.wrapBlock("> ", null, node2, () => state.renderContent(node2));
  },
  code_block(state, node2) {
    const backticks = node2.textContent.match(/`{3,}/gm);
    const fence2 = backticks ? backticks.sort().slice(-1)[0] + "`" : "```";
    state.write(fence2 + (node2.attrs.params || "") + "\n");
    state.text(node2.textContent, false);
    state.write("\n");
    state.write(fence2);
    state.closeBlock(node2);
  },
  heading(state, node2) {
    state.write(state.repeat("#", node2.attrs.level) + " ");
    state.renderInline(node2, false);
    state.closeBlock(node2);
  },
  horizontal_rule(state, node2) {
    state.write(node2.attrs.markup || "---");
    state.closeBlock(node2);
  },
  bullet_list(state, node2) {
    state.renderList(node2, "  ", () => (node2.attrs.bullet || "*") + " ");
  },
  ordered_list(state, node2) {
    let start2 = node2.attrs.order || 1;
    let maxW = String(start2 + node2.childCount - 1).length;
    let space = state.repeat(" ", maxW + 2);
    state.renderList(node2, space, (i2) => {
      let nStr = String(start2 + i2);
      return state.repeat(" ", maxW - nStr.length) + nStr + ". ";
    });
  },
  list_item(state, node2) {
    state.renderContent(node2);
  },
  paragraph(state, node2) {
    state.renderInline(node2);
    state.closeBlock(node2);
  },
  image(state, node2) {
    state.write("![" + state.esc(node2.attrs.alt || "") + "](" + node2.attrs.src.replace(/[\(\)]/g, "\\$&") + (node2.attrs.title ? ' "' + node2.attrs.title.replace(/"/g, '\\"') + '"' : "") + ")");
  },
  hard_break(state, node2, parent2, index2) {
    for (let i2 = index2 + 1; i2 < parent2.childCount; i2++)
      if (parent2.child(i2).type != node2.type) {
        state.write("\\\n");
        return;
      }
  },
  text(state, node2) {
    state.text(node2.text, !state.inAutolink);
  }
}, {
  em: { open: "*", close: "*", mixable: true, expelEnclosingWhitespace: true },
  strong: { open: "**", close: "**", mixable: true, expelEnclosingWhitespace: true },
  link: {
    open(state, mark, parent2, index2) {
      state.inAutolink = isPlainURL(mark, parent2, index2);
      return state.inAutolink ? "<" : "[";
    },
    close(state, mark, parent2, index2) {
      let { inAutolink } = state;
      state.inAutolink = void 0;
      return inAutolink ? ">" : "](" + mark.attrs.href.replace(/[\(\)"]/g, "\\$&") + (mark.attrs.title ? ` "${mark.attrs.title.replace(/"/g, '\\"')}"` : "") + ")";
    },
    mixable: true
  },
  code: {
    open(_state, _mark, parent2, index2) {
      return backticksFor(parent2.child(index2), -1);
    },
    close(_state, _mark, parent2, index2) {
      return backticksFor(parent2.child(index2 - 1), 1);
    },
    escape: false
  }
});
function backticksFor(node2, side) {
  let ticks = /`+/g, m2, len = 0;
  if (node2.isText)
    while (m2 = ticks.exec(node2.text))
      len = Math.max(len, m2[0].length);
  let result = len > 0 && side > 0 ? " `" : "`";
  for (let i2 = 0; i2 < len; i2++)
    result += "`";
  if (len > 0 && side < 0)
    result += " ";
  return result;
}
__name(backticksFor, "backticksFor");
function isPlainURL(link2, parent2, index2) {
  if (link2.attrs.title || !/^\w+:/.test(link2.attrs.href))
    return false;
  let content = parent2.child(index2);
  if (!content.isText || content.text != link2.attrs.href || content.marks[content.marks.length - 1] != link2)
    return false;
  return index2 == parent2.childCount - 1 || !link2.isInSet(parent2.child(index2 + 1).marks);
}
__name(isPlainURL, "isPlainURL");
let MarkdownSerializerState$1 = class MarkdownSerializerState2 {
  static {
    __name(this, "MarkdownSerializerState");
  }
  /**
  @internal
  */
  constructor(nodes, marks, options2) {
    this.nodes = nodes;
    this.marks = marks;
    this.options = options2;
    this.delim = "";
    this.out = "";
    this.closed = null;
    this.inAutolink = void 0;
    this.atBlockStart = false;
    this.inTightList = false;
    if (typeof this.options.tightLists == "undefined")
      this.options.tightLists = false;
    if (typeof this.options.hardBreakNodeName == "undefined")
      this.options.hardBreakNodeName = "hard_break";
  }
  /**
  @internal
  */
  flushClose(size = 2) {
    if (this.closed) {
      if (!this.atBlank())
        this.out += "\n";
      if (size > 1) {
        let delimMin = this.delim;
        let trim2 = /\s+$/.exec(delimMin);
        if (trim2)
          delimMin = delimMin.slice(0, delimMin.length - trim2[0].length);
        for (let i2 = 1; i2 < size; i2++)
          this.out += delimMin + "\n";
      }
      this.closed = null;
    }
  }
  /**
  @internal
  */
  getMark(name2) {
    let info = this.marks[name2];
    if (!info) {
      if (this.options.strict !== false)
        throw new Error(`Mark type \`${name2}\` not supported by Markdown renderer`);
      info = blankMark;
    }
    return info;
  }
  /**
  Render a block, prefixing each line with `delim`, and the first
  line in `firstDelim`. `node` should be the node that is closed at
  the end of the block, and `f` is a function that renders the
  content of the block.
  */
  wrapBlock(delim, firstDelim, node2, f2) {
    let old = this.delim;
    this.write(firstDelim != null ? firstDelim : delim);
    this.delim += delim;
    f2();
    this.delim = old;
    this.closeBlock(node2);
  }
  /**
  @internal
  */
  atBlank() {
    return /(^|\n)$/.test(this.out);
  }
  /**
  Ensure the current content ends with a newline.
  */
  ensureNewLine() {
    if (!this.atBlank())
      this.out += "\n";
  }
  /**
  Prepare the state for writing output (closing closed paragraphs,
  adding delimiters, and so on), and then optionally add content
  (unescaped) to the output.
  */
  write(content) {
    this.flushClose();
    if (this.delim && this.atBlank())
      this.out += this.delim;
    if (content)
      this.out += content;
  }
  /**
  Close the block for the given node.
  */
  closeBlock(node2) {
    this.closed = node2;
  }
  /**
  Add the given text to the document. When escape is not `false`,
  it will be escaped.
  */
  text(text2, escape2 = true) {
    let lines = text2.split("\n");
    for (let i2 = 0; i2 < lines.length; i2++) {
      this.write();
      if (!escape2 && lines[i2][0] == "[" && /(^|[^\\])\!$/.test(this.out))
        this.out = this.out.slice(0, this.out.length - 1) + "\\!";
      this.out += escape2 ? this.esc(lines[i2], this.atBlockStart) : lines[i2];
      if (i2 != lines.length - 1)
        this.out += "\n";
    }
  }
  /**
  Render the given node as a block.
  */
  render(node2, parent2, index2) {
    if (this.nodes[node2.type.name]) {
      this.nodes[node2.type.name](this, node2, parent2, index2);
    } else {
      if (this.options.strict !== false) {
        throw new Error("Token type `" + node2.type.name + "` not supported by Markdown renderer");
      } else if (!node2.type.isLeaf) {
        if (node2.type.inlineContent)
          this.renderInline(node2);
        else
          this.renderContent(node2);
        if (node2.isBlock)
          this.closeBlock(node2);
      }
    }
  }
  /**
  Render the contents of `parent` as block nodes.
  */
  renderContent(parent2) {
    parent2.forEach((node2, _2, i2) => this.render(node2, parent2, i2));
  }
  /**
  Render the contents of `parent` as inline content.
  */
  renderInline(parent2, fromBlockStart = true) {
    this.atBlockStart = fromBlockStart;
    let active = [], trailing = "";
    let progress = /* @__PURE__ */ __name((node2, offset, index2) => {
      let marks = node2 ? node2.marks : [];
      if (node2 && node2.type.name === this.options.hardBreakNodeName)
        marks = marks.filter((m2) => {
          if (index2 + 1 == parent2.childCount)
            return false;
          let next = parent2.child(index2 + 1);
          return m2.isInSet(next.marks) && (!next.isText || /\S/.test(next.text));
        });
      let leading = trailing;
      trailing = "";
      if (node2 && node2.isText && marks.some((mark) => {
        let info = this.getMark(mark.type.name);
        return info && info.expelEnclosingWhitespace && !mark.isInSet(active);
      })) {
        let [_2, lead, rest] = /^(\s*)(.*)$/m.exec(node2.text);
        if (lead) {
          leading += lead;
          node2 = rest ? node2.withText(rest) : null;
          if (!node2)
            marks = active;
        }
      }
      if (node2 && node2.isText && marks.some((mark) => {
        let info = this.getMark(mark.type.name);
        return info && info.expelEnclosingWhitespace && (index2 == parent2.childCount - 1 || !mark.isInSet(parent2.child(index2 + 1).marks));
      })) {
        let [_2, rest, trail] = /^(.*?)(\s*)$/m.exec(node2.text);
        if (trail) {
          trailing = trail;
          node2 = rest ? node2.withText(rest) : null;
          if (!node2)
            marks = active;
        }
      }
      let inner = marks.length ? marks[marks.length - 1] : null;
      let noEsc = inner && this.getMark(inner.type.name).escape === false;
      let len = marks.length - (noEsc ? 1 : 0);
      outer: for (let i2 = 0; i2 < len; i2++) {
        let mark = marks[i2];
        if (!this.getMark(mark.type.name).mixable)
          break;
        for (let j2 = 0; j2 < active.length; j2++) {
          let other = active[j2];
          if (!this.getMark(other.type.name).mixable)
            break;
          if (mark.eq(other)) {
            if (i2 > j2)
              marks = marks.slice(0, j2).concat(mark).concat(marks.slice(j2, i2)).concat(marks.slice(i2 + 1, len));
            else if (j2 > i2)
              marks = marks.slice(0, i2).concat(marks.slice(i2 + 1, j2)).concat(mark).concat(marks.slice(j2, len));
            continue outer;
          }
        }
      }
      let keep = 0;
      while (keep < Math.min(active.length, len) && marks[keep].eq(active[keep]))
        ++keep;
      while (keep < active.length)
        this.text(this.markString(active.pop(), false, parent2, index2), false);
      if (leading)
        this.text(leading);
      if (node2) {
        while (active.length < len) {
          let add3 = marks[active.length];
          active.push(add3);
          this.text(this.markString(add3, true, parent2, index2), false);
          this.atBlockStart = false;
        }
        if (noEsc && node2.isText)
          this.text(this.markString(inner, true, parent2, index2) + node2.text + this.markString(inner, false, parent2, index2 + 1), false);
        else
          this.render(node2, parent2, index2);
        this.atBlockStart = false;
      }
      if ((node2 === null || node2 === void 0 ? void 0 : node2.isText) && node2.nodeSize > 0) {
        this.atBlockStart = false;
      }
    }, "progress");
    parent2.forEach(progress);
    progress(null, 0, parent2.childCount);
    this.atBlockStart = false;
  }
  /**
  Render a node's content as a list. `delim` should be the extra
  indentation added to all lines except the first in an item,
  `firstDelim` is a function going from an item index to a
  delimiter for the first line of the item.
  */
  renderList(node2, delim, firstDelim) {
    if (this.closed && this.closed.type == node2.type)
      this.flushClose(3);
    else if (this.inTightList)
      this.flushClose(1);
    let isTight = typeof node2.attrs.tight != "undefined" ? node2.attrs.tight : this.options.tightLists;
    let prevTight = this.inTightList;
    this.inTightList = isTight;
    node2.forEach((child2, _2, i2) => {
      if (i2 && isTight)
        this.flushClose(1);
      this.wrapBlock(delim, firstDelim(i2), node2, () => this.render(child2, node2, i2));
    });
    this.inTightList = prevTight;
  }
  /**
  Escape the given string so that it can safely appear in Markdown
  content. If `startOfLine` is true, also escape characters that
  have special meaning only at the start of the line.
  */
  esc(str, startOfLine = false) {
    str = str.replace(/[`*\\~\[\]_]/g, (m2, i2) => m2 == "_" && i2 > 0 && i2 + 1 < str.length && str[i2 - 1].match(/\w/) && str[i2 + 1].match(/\w/) ? m2 : "\\" + m2);
    if (startOfLine)
      str = str.replace(/^(\+[ ]|[\-*>])/, "\\$&").replace(/^(\s*)(#{1,6})(\s|$)/, "$1\\$2$3").replace(/^(\s*\d+)\.\s/, "$1\\. ");
    if (this.options.escapeExtraCharacters)
      str = str.replace(this.options.escapeExtraCharacters, "\\$&");
    return str;
  }
  /**
  @internal
  */
  quote(str) {
    let wrap2 = str.indexOf('"') == -1 ? '""' : str.indexOf("'") == -1 ? "''" : "()";
    return wrap2[0] + str + wrap2[1];
  }
  /**
  Repeat the given string `n` times.
  */
  repeat(str, n2) {
    let out = "";
    for (let i2 = 0; i2 < n2; i2++)
      out += str;
    return out;
  }
  /**
  Get the markdown string for a given opening or closing mark.
  */
  markString(mark, open2, parent2, index2) {
    let info = this.getMark(mark.type.name);
    let value = open2 ? info.open : info.close;
    return typeof value == "string" ? value : value(this, mark, parent2, index2);
  }
  /**
  Get leading and trailing whitespace from a string. Values of
  leading or trailing property of the return object will be undefined
  if there is no match.
  */
  getEnclosingWhitespace(text2) {
    return {
      leading: (text2.match(/^(\s+)/) || [void 0])[0],
      trailing: (text2.match(/(\s+)$/) || [void 0])[0]
    };
  }
};
var disableCheckboxes = true;
var useLabelWrapper = false;
var useLabelAfter = false;
var markdownItTaskLists = /* @__PURE__ */ __name(function(md2, options2) {
  if (options2) {
    disableCheckboxes = !options2.enabled;
    useLabelWrapper = !!options2.label;
    useLabelAfter = !!options2.labelAfter;
  }
  md2.core.ruler.after("inline", "github-task-lists", function(state) {
    var tokens = state.tokens;
    for (var i2 = 2; i2 < tokens.length; i2++) {
      if (isTodoItem(tokens, i2)) {
        todoify(tokens[i2], state.Token);
        attrSet(tokens[i2 - 2], "class", "task-list-item" + (!disableCheckboxes ? " enabled" : ""));
        attrSet(tokens[parentToken(tokens, i2 - 2)], "class", "contains-task-list");
      }
    }
  });
}, "markdownItTaskLists");
function attrSet(token, name2, value) {
  var index2 = token.attrIndex(name2);
  var attr = [name2, value];
  if (index2 < 0) {
    token.attrPush(attr);
  } else {
    token.attrs[index2] = attr;
  }
}
__name(attrSet, "attrSet");
function parentToken(tokens, index2) {
  var targetLevel = tokens[index2].level - 1;
  for (var i2 = index2 - 1; i2 >= 0; i2--) {
    if (tokens[i2].level === targetLevel) {
      return i2;
    }
  }
  return -1;
}
__name(parentToken, "parentToken");
function isTodoItem(tokens, index2) {
  return isInline(tokens[index2]) && isParagraph(tokens[index2 - 1]) && isListItem(tokens[index2 - 2]) && startsWithTodoMarkdown(tokens[index2]);
}
__name(isTodoItem, "isTodoItem");
function todoify(token, TokenConstructor) {
  token.children.unshift(makeCheckbox(token, TokenConstructor));
  token.children[1].content = token.children[1].content.slice(3);
  token.content = token.content.slice(3);
  if (useLabelWrapper) {
    if (useLabelAfter) {
      token.children.pop();
      var id2 = "task-item-" + Math.ceil(Math.random() * (1e4 * 1e3) - 1e3);
      token.children[0].content = token.children[0].content.slice(0, -1) + ' id="' + id2 + '">';
      token.children.push(afterLabel(token.content, id2, TokenConstructor));
    } else {
      token.children.unshift(beginLabel(TokenConstructor));
      token.children.push(endLabel(TokenConstructor));
    }
  }
}
__name(todoify, "todoify");
function makeCheckbox(token, TokenConstructor) {
  var checkbox = new TokenConstructor("html_inline", "", 0);
  var disabledAttr = disableCheckboxes ? ' disabled="" ' : "";
  if (token.content.indexOf("[ ] ") === 0) {
    checkbox.content = '<input class="task-list-item-checkbox"' + disabledAttr + 'type="checkbox">';
  } else if (token.content.indexOf("[x] ") === 0 || token.content.indexOf("[X] ") === 0) {
    checkbox.content = '<input class="task-list-item-checkbox" checked=""' + disabledAttr + 'type="checkbox">';
  }
  return checkbox;
}
__name(makeCheckbox, "makeCheckbox");
function beginLabel(TokenConstructor) {
  var token = new TokenConstructor("html_inline", "", 0);
  token.content = "<label>";
  return token;
}
__name(beginLabel, "beginLabel");
function endLabel(TokenConstructor) {
  var token = new TokenConstructor("html_inline", "", 0);
  token.content = "</label>";
  return token;
}
__name(endLabel, "endLabel");
function afterLabel(content, id2, TokenConstructor) {
  var token = new TokenConstructor("html_inline", "", 0);
  token.content = '<label class="task-list-item-label" for="' + id2 + '">' + content + "</label>";
  token.attrs = [{ for: id2 }];
  return token;
}
__name(afterLabel, "afterLabel");
function isInline(token) {
  return token.type === "inline";
}
__name(isInline, "isInline");
function isParagraph(token) {
  return token.type === "paragraph_open";
}
__name(isParagraph, "isParagraph");
function isListItem(token) {
  return token.type === "list_item_open";
}
__name(isListItem, "isListItem");
function startsWithTodoMarkdown(token) {
  return token.content.indexOf("[ ] ") === 0 || token.content.indexOf("[x] ") === 0 || token.content.indexOf("[X] ") === 0;
}
__name(startsWithTodoMarkdown, "startsWithTodoMarkdown");
const taskListPlugin = /* @__PURE__ */ getDefaultExportFromCjs(markdownItTaskLists);
var __defProp = Object.defineProperty;
var __defNormalProp = /* @__PURE__ */ __name((obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value, "__defNormalProp");
var __publicField = /* @__PURE__ */ __name((obj, key, value) => {
  __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
  return value;
}, "__publicField");
const MarkdownTightLists = Extension.create({
  name: "markdownTightLists",
  addOptions: /* @__PURE__ */ __name(() => ({
    tight: true,
    tightClass: "tight",
    listTypes: ["bulletList", "orderedList"]
  }), "addOptions"),
  addGlobalAttributes() {
    return [{
      types: this.options.listTypes,
      attributes: {
        tight: {
          default: this.options.tight,
          parseHTML: /* @__PURE__ */ __name((element) => element.getAttribute("data-tight") === "true" || !element.querySelector("p"), "parseHTML"),
          renderHTML: /* @__PURE__ */ __name((attributes) => ({
            class: attributes.tight ? this.options.tightClass : null,
            "data-tight": attributes.tight ? "true" : null
          }), "renderHTML")
        }
      }
    }];
  },
  addCommands() {
    var _this = this;
    return {
      toggleTight: /* @__PURE__ */ __name(function() {
        let tight = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : null;
        return (_ref) => {
          let {
            editor,
            commands: commands2
          } = _ref;
          function toggleTight(name2) {
            if (!editor.isActive(name2)) {
              return false;
            }
            const attrs2 = editor.getAttributes(name2);
            return commands2.updateAttributes(name2, {
              tight: tight !== null && tight !== void 0 ? tight : !(attrs2 !== null && attrs2 !== void 0 && attrs2.tight)
            });
          }
          __name(toggleTight, "toggleTight");
          return _this.options.listTypes.some((name2) => toggleTight(name2));
        };
      }, "toggleTight")
    };
  }
});
const md = MarkdownIt();
function scanDelims(text2, pos) {
  md.inline.State.prototype.scanDelims.call({
    src: text2,
    posMax: text2.length
  });
  const state = new md.inline.State(text2, null, null, []);
  return state.scanDelims(pos, true);
}
__name(scanDelims, "scanDelims");
function shiftDelim(text2, delim, start2, offset) {
  let res = text2.substring(0, start2) + text2.substring(start2 + delim.length);
  res = res.substring(0, start2 + offset) + delim + res.substring(start2 + offset);
  return res;
}
__name(shiftDelim, "shiftDelim");
function trimStart(text2, delim, from2, to) {
  let pos = from2, res = text2;
  while (pos < to) {
    if (scanDelims(res, pos).can_open) {
      break;
    }
    res = shiftDelim(res, delim, pos, 1);
    pos++;
  }
  return {
    text: res,
    from: pos,
    to
  };
}
__name(trimStart, "trimStart");
function trimEnd(text2, delim, from2, to) {
  let pos = to, res = text2;
  while (pos > from2) {
    if (scanDelims(res, pos).can_close) {
      break;
    }
    res = shiftDelim(res, delim, pos, -1);
    pos--;
  }
  return {
    text: res,
    from: from2,
    to: pos
  };
}
__name(trimEnd, "trimEnd");
function trimInline(text2, delim, from2, to) {
  let state = {
    text: text2,
    from: from2,
    to
  };
  state = trimStart(state.text, delim, state.from, state.to);
  state = trimEnd(state.text, delim, state.from, state.to);
  if (state.to - state.from < delim.length + 1) {
    state.text = state.text.substring(0, state.from) + state.text.substring(state.to + delim.length);
  }
  return state.text;
}
__name(trimInline, "trimInline");
class MarkdownSerializerState extends MarkdownSerializerState$1 {
  static {
    __name(this, "MarkdownSerializerState");
  }
  constructor(nodes, marks, options2) {
    super(nodes, marks, options2 !== null && options2 !== void 0 ? options2 : {});
    __publicField(this, "inTable", false);
    this.inlines = [];
  }
  render(node2, parent2, index2) {
    super.render(node2, parent2, index2);
    const top = this.inlines[this.inlines.length - 1];
    if (top !== null && top !== void 0 && top.start && top !== null && top !== void 0 && top.end) {
      const {
        delimiter: delimiter2,
        start: start2,
        end
      } = this.normalizeInline(top);
      this.out = trimInline(this.out, delimiter2, start2, end);
      this.inlines.pop();
    }
  }
  markString(mark, open2, parent2, index2) {
    const info = this.marks[mark.type.name];
    if (info.expelEnclosingWhitespace) {
      if (open2) {
        this.inlines.push({
          start: this.out.length,
          delimiter: info.open
        });
      } else {
        const top = this.inlines.pop();
        this.inlines.push({
          ...top,
          end: this.out.length
        });
      }
    }
    return super.markString(mark, open2, parent2, index2);
  }
  normalizeInline(inline2) {
    let {
      start: start2,
      end
    } = inline2;
    while (this.out.charAt(start2).match(/\s/)) {
      start2++;
    }
    return {
      ...inline2,
      start: start2
    };
  }
}
const HTMLMark = Mark.create({
  name: "markdownHTMLMark",
  /**
   * @return {{markdown: MarkdownMarkSpec}}
   */
  addStorage() {
    return {
      markdown: {
        serialize: {
          open(state, mark) {
            var _getMarkTags$, _getMarkTags;
            if (!this.editor.storage.markdown.options.html) {
              console.warn(`Tiptap Markdown: "${mark.type.name}" mark is only available in html mode`);
              return "";
            }
            return (_getMarkTags$ = (_getMarkTags = getMarkTags(mark)) === null || _getMarkTags === void 0 ? void 0 : _getMarkTags[0]) !== null && _getMarkTags$ !== void 0 ? _getMarkTags$ : "";
          },
          close(state, mark) {
            var _getMarkTags$2, _getMarkTags2;
            if (!this.editor.storage.markdown.options.html) {
              return "";
            }
            return (_getMarkTags$2 = (_getMarkTags2 = getMarkTags(mark)) === null || _getMarkTags2 === void 0 ? void 0 : _getMarkTags2[1]) !== null && _getMarkTags$2 !== void 0 ? _getMarkTags$2 : "";
          }
        },
        parse: {
          // handled by markdown-it
        }
      }
    };
  }
});
function getMarkTags(mark) {
  const schema2 = mark.type.schema;
  const node2 = schema2.text(" ", [mark]);
  const html = getHTMLFromFragment(Fragment.from(node2), schema2);
  const match2 = html.match(/^(<.*?>) (<\/.*?>)$/);
  return match2 ? [match2[1], match2[2]] : null;
}
__name(getMarkTags, "getMarkTags");
function elementFromString(value) {
  const wrappedValue = `<body>${value}</body>`;
  return new window.DOMParser().parseFromString(wrappedValue, "text/html").body;
}
__name(elementFromString, "elementFromString");
function escapeHTML(value) {
  return value === null || value === void 0 ? void 0 : value.replace(/</g, "&lt;").replace(/>/g, "&gt;");
}
__name(escapeHTML, "escapeHTML");
function extractElement(node2) {
  const parent2 = node2.parentElement;
  const prepend2 = parent2.cloneNode();
  while (parent2.firstChild && parent2.firstChild !== node2) {
    prepend2.appendChild(parent2.firstChild);
  }
  if (prepend2.childNodes.length > 0) {
    parent2.parentElement.insertBefore(prepend2, parent2);
  }
  parent2.parentElement.insertBefore(node2, parent2);
  if (parent2.childNodes.length === 0) {
    parent2.remove();
  }
}
__name(extractElement, "extractElement");
function unwrapElement(node2) {
  const parent2 = node2.parentNode;
  while (node2.firstChild)
    parent2.insertBefore(node2.firstChild, node2);
  parent2.removeChild(node2);
}
__name(unwrapElement, "unwrapElement");
const HTMLNode = Node$1.create({
  name: "markdownHTMLNode",
  addStorage() {
    return {
      markdown: {
        serialize(state, node2, parent2) {
          if (this.editor.storage.markdown.options.html) {
            state.write(serializeHTML(node2, parent2));
          } else {
            console.warn(`Tiptap Markdown: "${node2.type.name}" node is only available in html mode`);
            state.write(`[${node2.type.name}]`);
          }
          if (node2.isBlock) {
            state.closeBlock(node2);
          }
        },
        parse: {
          // handled by markdown-it
        }
      }
    };
  }
});
function serializeHTML(node2, parent2) {
  const schema2 = node2.type.schema;
  const html = getHTMLFromFragment(Fragment.from(node2), schema2);
  if (node2.isBlock && (parent2 instanceof Fragment || parent2.type.name === schema2.topNodeType.name)) {
    return formatBlock(html);
  }
  return html;
}
__name(serializeHTML, "serializeHTML");
function formatBlock(html) {
  const dom = elementFromString(html);
  const element = dom.firstElementChild;
  element.innerHTML = element.innerHTML.trim() ? `
${element.innerHTML}
` : `
`;
  return element.outerHTML;
}
__name(formatBlock, "formatBlock");
const Blockquote = Node$1.create({
  name: "blockquote"
});
const Blockquote$1 = Blockquote.extend({
  /**
   * @return {{markdown: MarkdownNodeSpec}}
   */
  addStorage() {
    return {
      markdown: {
        serialize: defaultMarkdownSerializer.nodes.blockquote,
        parse: {
          // handled by markdown-it
        }
      }
    };
  }
});
const BulletList = Node$1.create({
  name: "bulletList"
});
const BulletList$1 = BulletList.extend({
  /**
   * @return {{markdown: MarkdownNodeSpec}}
   */
  addStorage() {
    return {
      markdown: {
        serialize(state, node2) {
          return state.renderList(node2, "  ", () => (this.editor.storage.markdown.options.bulletListMarker || "-") + " ");
        },
        parse: {
          // handled by markdown-it
        }
      }
    };
  }
});
const CodeBlock = Node$1.create({
  name: "codeBlock"
});
const CodeBlock$1 = CodeBlock.extend({
  /**
   * @return {{markdown: MarkdownNodeSpec}}
   */
  addStorage() {
    return {
      markdown: {
        serialize(state, node2) {
          state.write("```" + (node2.attrs.language || "") + "\n");
          state.text(node2.textContent, false);
          state.ensureNewLine();
          state.write("```");
          state.closeBlock(node2);
        },
        parse: {
          setup(markdownit2) {
            var _this$options$languag;
            markdownit2.set({
              langPrefix: (_this$options$languag = this.options.languageClassPrefix) !== null && _this$options$languag !== void 0 ? _this$options$languag : "language-"
            });
          },
          updateDOM(element) {
            element.innerHTML = element.innerHTML.replace(/\n<\/code><\/pre>/g, "</code></pre>");
          }
        }
      }
    };
  }
});
const HardBreak = Node$1.create({
  name: "hardBreak"
});
const HardBreak$1 = HardBreak.extend({
  /**
   * @return {{markdown: MarkdownNodeSpec}}
   */
  addStorage() {
    return {
      markdown: {
        serialize(state, node2, parent2, index2) {
          for (let i2 = index2 + 1; i2 < parent2.childCount; i2++)
            if (parent2.child(i2).type != node2.type) {
              state.write(state.inTable ? HTMLNode.storage.markdown.serialize.call(this, state, node2, parent2) : "\\\n");
              return;
            }
        },
        parse: {
          // handled by markdown-it
        }
      }
    };
  }
});
const Heading = Node$1.create({
  name: "heading"
});
const Heading$1 = Heading.extend({
  /**
   * @return {{markdown: MarkdownNodeSpec}}
   */
  addStorage() {
    return {
      markdown: {
        serialize: defaultMarkdownSerializer.nodes.heading,
        parse: {
          // handled by markdown-it
        }
      }
    };
  }
});
const HorizontalRule = Node$1.create({
  name: "horizontalRule"
});
const HorizontalRule$1 = HorizontalRule.extend({
  /**
   * @return {{markdown: MarkdownNodeSpec}}
   */
  addStorage() {
    return {
      markdown: {
        serialize: defaultMarkdownSerializer.nodes.horizontal_rule,
        parse: {
          // handled by markdown-it
        }
      }
    };
  }
});
const Image$1 = Node$1.create({
  name: "image"
});
const Image$1$1 = Image$1.extend({
  /**
   * @return {{markdown: MarkdownNodeSpec}}
   */
  addStorage() {
    return {
      markdown: {
        serialize: defaultMarkdownSerializer.nodes.image,
        parse: {
          // handled by markdown-it
        }
      }
    };
  }
});
const ListItem = Node$1.create({
  name: "listItem"
});
const ListItem$1 = ListItem.extend({
  /**
   * @return {{markdown: MarkdownNodeSpec}}
   */
  addStorage() {
    return {
      markdown: {
        serialize: defaultMarkdownSerializer.nodes.list_item,
        parse: {
          // handled by markdown-it
        }
      }
    };
  }
});
const OrderedList = Node$1.create({
  name: "orderedList"
});
function findIndexOfAdjacentNode(node2, parent2, index2) {
  let i2 = 0;
  for (; index2 - i2 > 0; i2++) {
    if (parent2.child(index2 - i2 - 1).type.name !== node2.type.name) {
      break;
    }
  }
  return i2;
}
__name(findIndexOfAdjacentNode, "findIndexOfAdjacentNode");
const OrderedList$1 = OrderedList.extend({
  /**
   * @return {{markdown: MarkdownNodeSpec}}
   */
  addStorage() {
    return {
      markdown: {
        serialize(state, node2, parent2, index2) {
          const start2 = node2.attrs.start || 1;
          const maxW = String(start2 + node2.childCount - 1).length;
          const space = state.repeat(" ", maxW + 2);
          const adjacentIndex = findIndexOfAdjacentNode(node2, parent2, index2);
          const separator = adjacentIndex % 2 ? ") " : ". ";
          state.renderList(node2, space, (i2) => {
            const nStr = String(start2 + i2);
            return state.repeat(" ", maxW - nStr.length) + nStr + separator;
          });
        },
        parse: {
          // handled by markdown-it
        }
      }
    };
  }
});
const Paragraph = Node$1.create({
  name: "paragraph"
});
const Paragraph$1 = Paragraph.extend({
  /**
   * @return {{markdown: MarkdownNodeSpec}}
   */
  addStorage() {
    return {
      markdown: {
        serialize: defaultMarkdownSerializer.nodes.paragraph,
        parse: {
          // handled by markdown-it
        }
      }
    };
  }
});
function childNodes(node2) {
  var _node$content$content, _node$content;
  return (_node$content$content = node2 === null || node2 === void 0 || (_node$content = node2.content) === null || _node$content === void 0 ? void 0 : _node$content.content) !== null && _node$content$content !== void 0 ? _node$content$content : [];
}
__name(childNodes, "childNodes");
const Table = Node$1.create({
  name: "table"
});
const Table$1 = Table.extend({
  /**
   * @return {{markdown: MarkdownNodeSpec}}
   */
  addStorage() {
    return {
      markdown: {
        serialize(state, node2, parent2) {
          if (!isMarkdownSerializable(node2)) {
            HTMLNode.storage.markdown.serialize.call(this, state, node2, parent2);
            return;
          }
          state.inTable = true;
          node2.forEach((row, p2, i2) => {
            state.write("| ");
            row.forEach((col, p22, j2) => {
              if (j2) {
                state.write(" | ");
              }
              const cellContent = col.firstChild;
              if (cellContent.textContent.trim()) {
                state.renderInline(cellContent);
              }
            });
            state.write(" |");
            state.ensureNewLine();
            if (!i2) {
              const delimiterRow = Array.from({
                length: row.childCount
              }).map(() => "---").join(" | ");
              state.write(`| ${delimiterRow} |`);
              state.ensureNewLine();
            }
          });
          state.closeBlock(node2);
          state.inTable = false;
        },
        parse: {
          // handled by markdown-it
        }
      }
    };
  }
});
function hasSpan(node2) {
  return node2.attrs.colspan > 1 || node2.attrs.rowspan > 1;
}
__name(hasSpan, "hasSpan");
function isMarkdownSerializable(node2) {
  const rows = childNodes(node2);
  const firstRow = rows[0];
  const bodyRows = rows.slice(1);
  if (childNodes(firstRow).some((cell) => cell.type.name !== "tableHeader" || hasSpan(cell) || cell.childCount > 1)) {
    return false;
  }
  if (bodyRows.some((row) => childNodes(row).some((cell) => cell.type.name === "tableHeader" || hasSpan(cell) || cell.childCount > 1))) {
    return false;
  }
  return true;
}
__name(isMarkdownSerializable, "isMarkdownSerializable");
const TaskItem$1 = Node$1.create({
  name: "taskItem"
});
const TaskItem$1$1 = TaskItem$1.extend({
  /**
   * @return {{markdown: MarkdownNodeSpec}}
   */
  addStorage() {
    return {
      markdown: {
        serialize(state, node2) {
          const check = node2.attrs.checked ? "[x]" : "[ ]";
          state.write(`${check} `);
          state.renderContent(node2);
        },
        parse: {
          updateDOM(element) {
            [...element.querySelectorAll(".task-list-item")].forEach((item) => {
              const input = item.querySelector("input");
              item.setAttribute("data-type", "taskItem");
              if (input) {
                item.setAttribute("data-checked", input.checked);
                input.remove();
              }
            });
          }
        }
      }
    };
  }
});
const TaskList = Node$1.create({
  name: "taskList"
});
const TaskList$1 = TaskList.extend({
  /**
   * @return {{markdown: MarkdownNodeSpec}}
   */
  addStorage() {
    return {
      markdown: {
        serialize: BulletList$1.storage.markdown.serialize,
        parse: {
          setup(markdownit2) {
            markdownit2.use(taskListPlugin);
          },
          updateDOM(element) {
            [...element.querySelectorAll(".contains-task-list")].forEach((list2) => {
              list2.setAttribute("data-type", "taskList");
            });
          }
        }
      }
    };
  }
});
const Text$1 = Node$1.create({
  name: "text"
});
const Text$1$1 = Text$1.extend({
  /**
   * @return {{markdown: MarkdownNodeSpec}}
   */
  addStorage() {
    return {
      markdown: {
        serialize(state, node2) {
          state.text(escapeHTML(node2.text));
        },
        parse: {
          // handled by markdown-it
        }
      }
    };
  }
});
const Bold = Mark.create({
  name: "bold"
});
const Bold$1 = Bold.extend({
  /**
   * @return {{markdown: MarkdownMarkSpec}}
   */
  addStorage() {
    return {
      markdown: {
        serialize: defaultMarkdownSerializer.marks.strong,
        parse: {
          // handled by markdown-it
        }
      }
    };
  }
});
const Code = Mark.create({
  name: "code"
});
const Code$1 = Code.extend({
  /**
   * @return {{markdown: MarkdownMarkSpec}}
   */
  addStorage() {
    return {
      markdown: {
        serialize: defaultMarkdownSerializer.marks.code,
        parse: {
          // handled by markdown-it
        }
      }
    };
  }
});
const Italic = Mark.create({
  name: "italic"
});
const Italic$1 = Italic.extend({
  /**
   * @return {{markdown: MarkdownMarkSpec}}
   */
  addStorage() {
    return {
      markdown: {
        serialize: defaultMarkdownSerializer.marks.em,
        parse: {
          // handled by markdown-it
        }
      }
    };
  }
});
const Link = Mark.create({
  name: "link"
});
const Link$1 = Link.extend({
  /**
   * @return {{markdown: MarkdownMarkSpec}}
   */
  addStorage() {
    return {
      markdown: {
        serialize: defaultMarkdownSerializer.marks.link,
        parse: {
          // handled by markdown-it
        }
      }
    };
  }
});
const Strike = Mark.create({
  name: "strike"
});
const Strike$1 = Strike.extend({
  /**
   * @return {{markdown: MarkdownMarkSpec}}
   */
  addStorage() {
    return {
      markdown: {
        serialize: {
          open: "~~",
          close: "~~",
          expelEnclosingWhitespace: true
        },
        parse: {
          // handled by markdown-it
        }
      }
    };
  }
});
const markdownExtensions = [Blockquote$1, BulletList$1, CodeBlock$1, HardBreak$1, Heading$1, HorizontalRule$1, HTMLNode, Image$1$1, ListItem$1, OrderedList$1, Paragraph$1, Table$1, TaskItem$1$1, TaskList$1, Text$1$1, Bold$1, Code$1, HTMLMark, Italic$1, Link$1, Strike$1];
function getMarkdownSpec(extension) {
  var _extension$storage, _markdownExtensions$f;
  const markdownSpec = (_extension$storage = extension.storage) === null || _extension$storage === void 0 ? void 0 : _extension$storage.markdown;
  const defaultMarkdownSpec = (_markdownExtensions$f = markdownExtensions.find((e2) => e2.name === extension.name)) === null || _markdownExtensions$f === void 0 ? void 0 : _markdownExtensions$f.storage.markdown;
  if (markdownSpec || defaultMarkdownSpec) {
    return {
      ...defaultMarkdownSpec,
      ...markdownSpec
    };
  }
  return null;
}
__name(getMarkdownSpec, "getMarkdownSpec");
class MarkdownSerializer {
  static {
    __name(this, "MarkdownSerializer");
  }
  constructor(editor) {
    __publicField(this, "editor", null);
    this.editor = editor;
  }
  serialize(content) {
    const state = new MarkdownSerializerState(this.nodes, this.marks, {
      hardBreakNodeName: HardBreak$1.name
    });
    state.renderContent(content);
    return state.out;
  }
  get nodes() {
    var _this$editor$extensio;
    return {
      ...Object.fromEntries(Object.keys(this.editor.schema.nodes).map((name2) => [name2, this.serializeNode(HTMLNode)])),
      ...Object.fromEntries((_this$editor$extensio = this.editor.extensionManager.extensions.filter((extension) => extension.type === "node" && this.serializeNode(extension)).map((extension) => [extension.name, this.serializeNode(extension)])) !== null && _this$editor$extensio !== void 0 ? _this$editor$extensio : [])
    };
  }
  get marks() {
    var _this$editor$extensio2;
    return {
      ...Object.fromEntries(Object.keys(this.editor.schema.marks).map((name2) => [name2, this.serializeMark(HTMLMark)])),
      ...Object.fromEntries((_this$editor$extensio2 = this.editor.extensionManager.extensions.filter((extension) => extension.type === "mark" && this.serializeMark(extension)).map((extension) => [extension.name, this.serializeMark(extension)])) !== null && _this$editor$extensio2 !== void 0 ? _this$editor$extensio2 : [])
    };
  }
  serializeNode(node2) {
    var _getMarkdownSpec;
    return (_getMarkdownSpec = getMarkdownSpec(node2)) === null || _getMarkdownSpec === void 0 || (_getMarkdownSpec = _getMarkdownSpec.serialize) === null || _getMarkdownSpec === void 0 ? void 0 : _getMarkdownSpec.bind({
      editor: this.editor,
      options: node2.options
    });
  }
  serializeMark(mark) {
    var _getMarkdownSpec2;
    const serialize = (_getMarkdownSpec2 = getMarkdownSpec(mark)) === null || _getMarkdownSpec2 === void 0 ? void 0 : _getMarkdownSpec2.serialize;
    return serialize ? {
      ...serialize,
      open: typeof serialize.open === "function" ? serialize.open.bind({
        editor: this.editor,
        options: mark.options
      }) : serialize.open,
      close: typeof serialize.close === "function" ? serialize.close.bind({
        editor: this.editor,
        options: mark.options
      }) : serialize.close
    } : null;
  }
}
class MarkdownParser {
  static {
    __name(this, "MarkdownParser");
  }
  constructor(editor, _ref) {
    __publicField(this, "editor", null);
    __publicField(this, "md", null);
    let {
      html,
      linkify: linkify2,
      breaks
    } = _ref;
    this.editor = editor;
    this.md = this.withPatchedRenderer(MarkdownIt({
      html,
      linkify: linkify2,
      breaks
    }));
  }
  parse(content) {
    let {
      inline: inline2
    } = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
    if (typeof content === "string") {
      this.editor.extensionManager.extensions.forEach((extension) => {
        var _getMarkdownSpec;
        return (_getMarkdownSpec = getMarkdownSpec(extension)) === null || _getMarkdownSpec === void 0 || (_getMarkdownSpec = _getMarkdownSpec.parse) === null || _getMarkdownSpec === void 0 || (_getMarkdownSpec = _getMarkdownSpec.setup) === null || _getMarkdownSpec === void 0 ? void 0 : _getMarkdownSpec.call({
          editor: this.editor,
          options: extension.options
        }, this.md);
      });
      const renderedHTML = this.md.render(content);
      const element = elementFromString(renderedHTML);
      this.editor.extensionManager.extensions.forEach((extension) => {
        var _getMarkdownSpec2;
        return (_getMarkdownSpec2 = getMarkdownSpec(extension)) === null || _getMarkdownSpec2 === void 0 || (_getMarkdownSpec2 = _getMarkdownSpec2.parse) === null || _getMarkdownSpec2 === void 0 || (_getMarkdownSpec2 = _getMarkdownSpec2.updateDOM) === null || _getMarkdownSpec2 === void 0 ? void 0 : _getMarkdownSpec2.call({
          editor: this.editor,
          options: extension.options
        }, element);
      });
      this.normalizeDOM(element, {
        inline: inline2,
        content
      });
      return element.innerHTML;
    }
    return content;
  }
  normalizeDOM(node2, _ref2) {
    let {
      inline: inline2,
      content
    } = _ref2;
    this.normalizeBlocks(node2);
    node2.querySelectorAll("*").forEach((el) => {
      var _el$nextSibling;
      if (((_el$nextSibling = el.nextSibling) === null || _el$nextSibling === void 0 ? void 0 : _el$nextSibling.nodeType) === Node.TEXT_NODE && !el.closest("pre")) {
        el.nextSibling.textContent = el.nextSibling.textContent.replace(/^\n/, "");
      }
    });
    if (inline2) {
      this.normalizeInline(node2, content);
    }
    return node2;
  }
  normalizeBlocks(node2) {
    const blocks = Object.values(this.editor.schema.nodes).filter((node22) => node22.isBlock);
    const selector = blocks.map((block2) => {
      var _block$spec$parseDOM;
      return (_block$spec$parseDOM = block2.spec.parseDOM) === null || _block$spec$parseDOM === void 0 ? void 0 : _block$spec$parseDOM.map((spec) => spec.tag);
    }).flat().filter(Boolean).join(",");
    if (!selector) {
      return;
    }
    [...node2.querySelectorAll(selector)].forEach((el) => {
      if (el.parentElement.matches("p")) {
        extractElement(el);
      }
    });
  }
  normalizeInline(node2, content) {
    var _node$firstElementChi;
    if ((_node$firstElementChi = node2.firstElementChild) !== null && _node$firstElementChi !== void 0 && _node$firstElementChi.matches("p")) {
      var _content$match$, _content$match, _content$match$2, _content$match2;
      const firstParagraph = node2.firstElementChild;
      const {
        nextElementSibling
      } = firstParagraph;
      const startSpaces = (_content$match$ = (_content$match = content.match(/^\s+/)) === null || _content$match === void 0 ? void 0 : _content$match[0]) !== null && _content$match$ !== void 0 ? _content$match$ : "";
      const endSpaces = !nextElementSibling ? (_content$match$2 = (_content$match2 = content.match(/\s+$/)) === null || _content$match2 === void 0 ? void 0 : _content$match2[0]) !== null && _content$match$2 !== void 0 ? _content$match$2 : "" : "";
      if (content.match(/^\n\n/)) {
        firstParagraph.innerHTML = `${firstParagraph.innerHTML}${endSpaces}`;
        return;
      }
      unwrapElement(firstParagraph);
      node2.innerHTML = `${startSpaces}${node2.innerHTML}${endSpaces}`;
    }
  }
  /**
   * @param {markdownit} md
   */
  withPatchedRenderer(md2) {
    const withoutNewLine = /* @__PURE__ */ __name((renderer) => function() {
      const rendered = renderer(...arguments);
      if (rendered === "\n") {
        return rendered;
      }
      if (rendered[rendered.length - 1] === "\n") {
        return rendered.slice(0, -1);
      }
      return rendered;
    }, "withoutNewLine");
    md2.renderer.rules.hardbreak = withoutNewLine(md2.renderer.rules.hardbreak);
    md2.renderer.rules.softbreak = withoutNewLine(md2.renderer.rules.softbreak);
    md2.renderer.rules.fence = withoutNewLine(md2.renderer.rules.fence);
    md2.renderer.rules.code_block = withoutNewLine(md2.renderer.rules.code_block);
    md2.renderer.renderToken = withoutNewLine(md2.renderer.renderToken.bind(md2.renderer));
    return md2;
  }
}
const MarkdownClipboard = Extension.create({
  name: "markdownClipboard",
  addOptions() {
    return {
      transformPastedText: false,
      transformCopiedText: false
    };
  },
  addProseMirrorPlugins() {
    return [new Plugin({
      key: new PluginKey("markdownClipboard"),
      props: {
        clipboardTextParser: /* @__PURE__ */ __name((text2, context, plainText) => {
          if (plainText || !this.options.transformPastedText) {
            return null;
          }
          const parsed = this.editor.storage.markdown.parser.parse(text2, {
            inline: true
          });
          return DOMParser.fromSchema(this.editor.schema).parseSlice(elementFromString(parsed), {
            preserveWhitespace: true,
            context
          });
        }, "clipboardTextParser"),
        /**
         * @param {import('prosemirror-model').Slice} slice
         */
        clipboardTextSerializer: /* @__PURE__ */ __name((slice2) => {
          if (!this.options.transformCopiedText) {
            return null;
          }
          return this.editor.storage.markdown.serializer.serialize(slice2.content);
        }, "clipboardTextSerializer")
      }
    })];
  }
});
const Markdown = Extension.create({
  name: "markdown",
  priority: 50,
  addOptions() {
    return {
      html: true,
      tightLists: true,
      tightListClass: "tight",
      bulletListMarker: "-",
      linkify: false,
      breaks: false,
      transformPastedText: false,
      transformCopiedText: false
    };
  },
  addCommands() {
    const commands2 = index$1.Commands.config.addCommands();
    return {
      setContent: /* @__PURE__ */ __name((content, emitUpdate, parseOptions) => (props) => {
        return commands2.setContent(props.editor.storage.markdown.parser.parse(content), emitUpdate, parseOptions)(props);
      }, "setContent"),
      insertContentAt: /* @__PURE__ */ __name((range, content, options2) => (props) => {
        return commands2.insertContentAt(range, props.editor.storage.markdown.parser.parse(content, {
          inline: true
        }), options2)(props);
      }, "insertContentAt")
    };
  },
  onBeforeCreate() {
    this.editor.storage.markdown = {
      options: {
        ...this.options
      },
      parser: new MarkdownParser(this.editor, this.options),
      serializer: new MarkdownSerializer(this.editor),
      getMarkdown: /* @__PURE__ */ __name(() => {
        return this.editor.storage.markdown.serializer.serialize(this.editor.state.doc);
      }, "getMarkdown")
    };
    this.editor.options.initialContent = this.editor.options.content;
    this.editor.options.content = this.editor.storage.markdown.parser.parse(this.editor.options.content);
  },
  onCreate() {
    this.editor.options.content = this.editor.options.initialContent;
    delete this.editor.options.initialContent;
  },
  addStorage() {
    return {
      /// storage will be defined in onBeforeCreate() to prevent initial object overriding
    };
  },
  addExtensions() {
    return [MarkdownTightLists.configure({
      tight: this.options.tightLists,
      tightClass: this.options.tightListClass
    }), MarkdownClipboard.configure({
      transformPastedText: this.options.transformPastedText,
      transformCopiedText: this.options.transformCopiedText
    })];
  }
});
function addMarkdownWidget(node2, name2, opts) {
  Markdown.configure({
    html: false,
    breaks: true,
    transformPastedText: true
  });
  const editor = new Editor({
    extensions: [
      StarterKit,
      Markdown,
      Link$2,
      Table$2,
      TableCell,
      TableHeader,
      TableRow
    ],
    content: opts.defaultVal,
    editable: false
  });
  const inputEl = editor.options.element;
  inputEl.classList.add("comfy-markdown");
  const textarea = document.createElement("textarea");
  inputEl.append(textarea);
  const widget = node2.addDOMWidget(name2, "MARKDOWN", inputEl, {
    getValue() {
      return textarea.value;
    },
    setValue(v2) {
      textarea.value = v2;
      editor.commands.setContent(v2);
    }
  });
  widget.inputEl = inputEl;
  widget.options.minNodeSize = [400, 200];
  inputEl.addEventListener("pointerdown", (event) => {
    if (event.button !== 0) {
      app$1.canvas.processMouseDown(event);
      return;
    }
    if (event.target instanceof HTMLAnchorElement) {
      return;
    }
    inputEl.classList.add("editing");
    setTimeout(() => {
      textarea.focus();
    }, 0);
  });
  textarea.addEventListener("blur", () => {
    inputEl.classList.remove("editing");
  });
  textarea.addEventListener("change", () => {
    editor.commands.setContent(textarea.value);
    widget.callback?.(widget.value);
  });
  inputEl.addEventListener("keydown", (event) => {
    event.stopPropagation();
  });
  inputEl.addEventListener("pointerdown", (event) => {
    if (event.button === 1) {
      app$1.canvas.processMouseDown(event);
    }
  });
  inputEl.addEventListener("pointermove", (event) => {
    if ((event.buttons & 4) === 4) {
      app$1.canvas.processMouseMove(event);
    }
  });
  inputEl.addEventListener("pointerup", (event) => {
    if (event.button === 1) {
      app$1.canvas.processMouseUp(event);
    }
  });
  return widget;
}
__name(addMarkdownWidget, "addMarkdownWidget");
const useMarkdownWidget = /* @__PURE__ */ __name(() => {
  const widgetConstructor = /* @__PURE__ */ __name((node2, inputSpec) => {
    return addMarkdownWidget(node2, inputSpec.name, {
      defaultVal: inputSpec.default ?? ""
    });
  }, "widgetConstructor");
  return widgetConstructor;
}, "useMarkdownWidget");
function addMultilineWidget(node2, name2, opts) {
  const inputEl = document.createElement("textarea");
  inputEl.className = "comfy-multiline-input";
  inputEl.value = opts.defaultVal;
  inputEl.placeholder = opts.placeholder || name2;
  inputEl.spellcheck = useSettingStore().get("Comfy.TextareaWidget.Spellcheck");
  const widget = node2.addDOMWidget(name2, "customtext", inputEl, {
    getValue() {
      return inputEl.value;
    },
    setValue(v2) {
      inputEl.value = v2;
    }
  });
  widget.inputEl = inputEl;
  widget.options.minNodeSize = [400, 200];
  inputEl.addEventListener("input", () => {
    widget.callback?.(widget.value);
  });
  inputEl.addEventListener("pointerdown", (event) => {
    if (event.button === 1) {
      app$1.canvas.processMouseDown(event);
    }
  });
  inputEl.addEventListener("pointermove", (event) => {
    if ((event.buttons & 4) === 4) {
      app$1.canvas.processMouseMove(event);
    }
  });
  inputEl.addEventListener("pointerup", (event) => {
    if (event.button === 1) {
      app$1.canvas.processMouseUp(event);
    }
  });
  let ignoreEventsTimer = null;
  let ignoredEvents = 0;
  inputEl.addEventListener("wheel", (event) => {
    if (!Object.is(event.deltaX, -0)) return;
    const multiplier = document.activeElement === inputEl ? 2 : 1;
    const maxScrollHeight = inputEl.scrollHeight - inputEl.clientHeight;
    if (event.deltaY < 0 && inputEl.scrollTop === 0 || event.deltaY > 0 && inputEl.scrollTop === maxScrollHeight) {
      if (!ignoreEventsTimer || ignoredEvents > 25 * multiplier) {
        app$1.canvas.processMouseWheel(event);
      } else {
        ignoredEvents++;
      }
    } else if (event.deltaY !== 0) {
      ignoredEvents = 0;
      if (ignoreEventsTimer) clearTimeout(ignoreEventsTimer);
      ignoreEventsTimer = setTimeout(() => {
        ignoreEventsTimer = null;
      }, 800 * multiplier);
    }
  });
  return widget;
}
__name(addMultilineWidget, "addMultilineWidget");
const useStringWidget = /* @__PURE__ */ __name(() => {
  const widgetConstructor = /* @__PURE__ */ __name((node2, inputSpec) => {
    if (!isStringInputSpec(inputSpec)) {
      throw new Error(`Invalid input data: ${inputSpec}`);
    }
    const defaultVal = inputSpec.default ?? "";
    const multiline = inputSpec.multiline;
    const widget = multiline ? addMultilineWidget(node2, inputSpec.name, {
      defaultVal,
      placeholder: inputSpec.placeholder
    }) : node2.addWidget("text", inputSpec.name, defaultVal, () => {
    }, {});
    if (typeof inputSpec.dynamicPrompts === "boolean") {
      widget.dynamicPrompts = inputSpec.dynamicPrompts;
    }
    return widget;
  }, "widgetConstructor");
  return widgetConstructor;
}, "useStringWidget");
const StringWidget = useStringWidget();
const FloatWidget = useFloatWidget();
const BooleanWidget = useBooleanWidget();
function addWidgetFromValue(node2, value) {
  let widget;
  if (typeof value === "string") {
    widget = StringWidget(node2, {
      type: "STRING",
      name: "UNKNOWN",
      multiline: value.length > 20
    });
  } else if (typeof value === "number") {
    widget = FloatWidget(node2, {
      type: "FLOAT",
      name: "UNKNOWN"
    });
  } else if (typeof value === "boolean") {
    widget = BooleanWidget(node2, {
      type: "BOOLEAN",
      name: "UNKNOWN"
    });
  } else {
    widget = StringWidget(node2, {
      type: "STRING",
      name: "UNKNOWN",
      multiline: true
    });
    widget.value = JSON.stringify(value);
    return;
  }
  widget.value = value;
}
__name(addWidgetFromValue, "addWidgetFromValue");
LGraphNode.prototype.onConfigure = useChainCallback(
  LGraphNode.prototype.onConfigure,
  function(info) {
    if (!this.has_errors || !info.widgets_values) return;
    for (let i2 = 0; i2 < info.widgets_values.length; i2++) {
      const widgetValue = info.widgets_values[i2];
      addWidgetFromValue(this, widgetValue);
    }
    this.serialize_widgets = true;
  }
);
const transformWidgetConstructorV2ToV1 = /* @__PURE__ */ __name((widgetConstructorV2) => {
  return (node2, inputName, inputData) => {
    const inputSpec = transformInputSpecV1ToV2(inputData, {
      name: inputName
    });
    const widget = widgetConstructorV2(node2, inputSpec);
    return {
      widget,
      minWidth: widget.options.minNodeSize?.[0],
      minHeight: widget.options.minNodeSize?.[1]
    };
  };
}, "transformWidgetConstructorV2ToV1");
function controlValueRunBefore() {
  return useSettingStore().get("Comfy.WidgetControlMode") === "before";
}
__name(controlValueRunBefore, "controlValueRunBefore");
function updateControlWidgetLabel(widget) {
  if (controlValueRunBefore()) {
    widget.label = t("g.control_before_generate");
  } else {
    widget.label = t("g.control_after_generate");
  }
}
__name(updateControlWidgetLabel, "updateControlWidgetLabel");
const IS_CONTROL_WIDGET = Symbol();
const HAS_EXECUTED = Symbol();
function addValueControlWidget(node2, targetWidget, defaultValue, _values, widgetName, inputData) {
  let name2 = inputData?.[1]?.control_after_generate;
  if (typeof name2 !== "string") {
    name2 = widgetName;
  }
  const widgets = addValueControlWidgets(
    node2,
    targetWidget,
    defaultValue ?? "randomize",
    {
      addFilterList: false,
      controlAfterGenerateName: name2
    },
    inputData
  );
  return widgets[0];
}
__name(addValueControlWidget, "addValueControlWidget");
function addValueControlWidgets(node2, targetWidget, defaultValue, options2, inputData) {
  if (!defaultValue) defaultValue = "randomize";
  if (!options2) options2 = {};
  const getName = /* @__PURE__ */ __name((defaultName, optionName) => {
    let name2 = defaultName;
    if (options2[optionName]) {
      name2 = options2[optionName];
    } else if (typeof inputData?.[1]?.[defaultName] === "string") {
      name2 = inputData?.[1]?.[defaultName];
    } else if (inputData?.[1]?.control_prefix) {
      name2 = inputData?.[1]?.control_prefix + " " + name2;
    }
    return name2;
  }, "getName");
  const valueControl = node2.addWidget(
    "combo",
    getName("control_after_generate", "controlAfterGenerateName"),
    defaultValue,
    function() {
    },
    {
      values: ["fixed", "increment", "decrement", "randomize"],
      serialize: false
      // Don't include this in prompt.
    }
  );
  valueControl.tooltip = "Allows the linked widget to be changed automatically, for example randomizing the noise seed.";
  valueControl[IS_CONTROL_WIDGET] = true;
  updateControlWidgetLabel(valueControl);
  const widgets = [valueControl];
  const isCombo = isComboWidget(targetWidget);
  let comboFilter;
  if (isCombo && valueControl.options.values) {
    valueControl.options.values.push("increment-wrap");
  }
  if (isCombo && options2.addFilterList !== false) {
    comboFilter = node2.addWidget(
      "string",
      getName("control_filter_list", "controlFilterListName"),
      "",
      function() {
      },
      {
        serialize: false
        // Don't include this in prompt.
      }
    );
    updateControlWidgetLabel(comboFilter);
    comboFilter.tooltip = "Allows for filtering the list of values when changing the value via the control generate mode. Allows for RegEx matches in the format /abc/ to only filter to values containing 'abc'.";
    widgets.push(comboFilter);
  }
  const applyWidgetControl = /* @__PURE__ */ __name(() => {
    var v2 = valueControl.value;
    if (isCombo && v2 !== "fixed") {
      let values = targetWidget.options.values ?? [];
      const filter3 = comboFilter?.value;
      if (filter3) {
        let check;
        if (filter3.startsWith("/") && filter3.endsWith("/")) {
          try {
            const regex2 = new RegExp(filter3.substring(1, filter3.length - 1));
            check = /* @__PURE__ */ __name((item) => regex2.test(item), "check");
          } catch (error2) {
            console.error(
              "Error constructing RegExp filter for node " + node2.id,
              filter3,
              error2
            );
          }
        }
        if (!check) {
          const lower = filter3.toLocaleLowerCase();
          check = /* @__PURE__ */ __name((item) => item.toLocaleLowerCase().includes(lower), "check");
        }
        values = values.filter((item) => check(item));
        if (!values.length && targetWidget.options.values?.length) {
          console.warn(
            "Filter for node " + node2.id + " has filtered out all items",
            filter3
          );
        }
      }
      let current_index = values.indexOf(targetWidget.value);
      let current_length = values.length;
      switch (v2) {
        case "increment":
          current_index += 1;
          break;
        case "increment-wrap":
          current_index += 1;
          if (current_index >= current_length) {
            current_index = 0;
          }
          break;
        case "decrement":
          current_index -= 1;
          break;
        case "randomize":
          current_index = Math.floor(Math.random() * current_length);
          break;
        default:
          break;
      }
      current_index = Math.max(0, current_index);
      current_index = Math.min(current_length - 1, current_index);
      if (current_index >= 0) {
        let value = values[current_index];
        targetWidget.value = value;
        targetWidget.callback?.(value);
      }
    } else {
      let { min = 0, max = 1, step2 = 1 } = targetWidget.options;
      max = Math.min(1125899906842624, max);
      min = Math.max(-1125899906842624, min);
      let range = (max - min) / step2;
      switch (v2) {
        case "fixed":
          break;
        case "increment":
          targetWidget.value += step2;
          break;
        case "decrement":
          targetWidget.value -= step2;
          break;
        case "randomize":
          targetWidget.value = Math.floor(Math.random() * range) * step2 + min;
          break;
        default:
          break;
      }
      if (targetWidget.value < min) targetWidget.value = min;
      if (targetWidget.value > max) targetWidget.value = max;
      targetWidget.callback?.(targetWidget.value);
    }
  }, "applyWidgetControl");
  valueControl.beforeQueued = () => {
    if (controlValueRunBefore()) {
      if (valueControl[HAS_EXECUTED]) {
        applyWidgetControl();
      }
    }
    valueControl[HAS_EXECUTED] = true;
  };
  valueControl.afterQueued = () => {
    if (!controlValueRunBefore()) {
      applyWidgetControl();
    }
  };
  return widgets;
}
__name(addValueControlWidgets, "addValueControlWidgets");
const ComfyWidgets = {
  INT: transformWidgetConstructorV2ToV1(useIntWidget()),
  FLOAT: transformWidgetConstructorV2ToV1(useFloatWidget()),
  BOOLEAN: transformWidgetConstructorV2ToV1(useBooleanWidget()),
  STRING: transformWidgetConstructorV2ToV1(useStringWidget()),
  MARKDOWN: transformWidgetConstructorV2ToV1(useMarkdownWidget()),
  COMBO: transformWidgetConstructorV2ToV1(useComboWidget()),
  IMAGEUPLOAD: useImageUploadWidget()
};
window.comfyAPI = window.comfyAPI || {};
window.comfyAPI.widgets = window.comfyAPI.widgets || {};
window.comfyAPI.widgets.updateControlWidgetLabel = updateControlWidgetLabel;
window.comfyAPI.widgets.IS_CONTROL_WIDGET = IS_CONTROL_WIDGET;
window.comfyAPI.widgets.addValueControlWidget = addValueControlWidget;
window.comfyAPI.widgets.addValueControlWidgets = addValueControlWidgets;
window.comfyAPI.widgets.ComfyWidgets = ComfyWidgets;
const useWidgetStore = /* @__PURE__ */ defineStore("widget", () => {
  const coreWidgets = ComfyWidgets;
  const customWidgets = ref$3(/* @__PURE__ */ new Map());
  const widgets = computed(
    () => new Map([...customWidgets.value, ...Object.entries(coreWidgets)])
  );
  function inputIsWidget(spec) {
    const type = Array.isArray(spec) ? getInputSpecType(spec) : spec.type;
    return widgets.value.has(type);
  }
  __name(inputIsWidget, "inputIsWidget");
  function registerCustomWidgets(newWidgets) {
    for (const [type, widget] of Object.entries(newWidgets)) {
      customWidgets.value.set(type, widget);
    }
  }
  __name(registerCustomWidgets, "registerCustomWidgets");
  return {
    widgets,
    inputIsWidget,
    registerCustomWidgets
  };
});
const _hoisted_1$N = { class: "_sb_node_preview" };
const _hoisted_2$E = { class: "_sb_table" };
const _hoisted_3$q = { class: "_sb_col" };
const _hoisted_4$f = { class: "_sb_col" };
const _hoisted_5$c = { class: "_sb_col" };
const _sfc_main$Y = /* @__PURE__ */ defineComponent({
  __name: "NodePreview",
  props: {
    nodeDef: {}
  },
  setup(__props) {
    const props = __props;
    const colorPaletteStore = useColorPaletteStore();
    const litegraphColors = computed(
      () => colorPaletteStore.completedActivePalette.colors.litegraph_base
    );
    const widgetStore = useWidgetStore();
    const nodeDef = props.nodeDef;
    const allInputDefs = Object.values(nodeDef.inputs);
    const allOutputDefs = nodeDef.outputs;
    const slotInputDefs = allInputDefs.filter(
      (input) => !widgetStore.inputIsWidget(input)
    );
    const widgetInputDefs = allInputDefs.filter(
      (input) => widgetStore.inputIsWidget(input)
    );
    const truncateDefaultValue = /* @__PURE__ */ __name((value, charLimit = 32) => {
      let stringValue;
      if (typeof value === "object" && value !== null) {
        stringValue = JSON.stringify(value);
      } else if (Array.isArray(value)) {
        stringValue = JSON.stringify(value);
      } else if (typeof value === "string") {
        stringValue = value;
      } else {
        stringValue = String(value);
      }
      return _.truncate(stringValue, { length: charLimit });
    }, "truncateDefaultValue");
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", _hoisted_1$N, [
        createBaseVNode("div", _hoisted_2$E, [
          createBaseVNode("div", {
            class: "node_header",
            style: normalizeStyle({
              backgroundColor: litegraphColors.value.NODE_DEFAULT_COLOR,
              color: litegraphColors.value.NODE_TITLE_COLOR
            })
          }, [
            _cache[0] || (_cache[0] = createBaseVNode("div", { class: "_sb_dot headdot" }, null, -1)),
            createTextVNode(" " + toDisplayString(unref(nodeDef).display_name), 1)
          ], 4),
          _cache[5] || (_cache[5] = createBaseVNode("div", { class: "_sb_preview_badge" }, "PREVIEW", -1)),
          (openBlock(true), createElementBlock(Fragment$1, null, renderList(unref(_).zip(unref(slotInputDefs), unref(allOutputDefs)), ([slotInput, slotOutput]) => {
            return openBlock(), createElementBlock("div", {
              key: (slotInput?.name || "") + (slotOutput?.index.toString() || ""),
              class: "_sb_row slot_row"
            }, [
              createBaseVNode("div", _hoisted_3$q, [
                slotInput ? (openBlock(), createElementBlock("div", {
                  key: 0,
                  class: normalizeClass(["_sb_dot", slotInput.type])
                }, null, 2)) : createCommentVNode("", true)
              ]),
              createBaseVNode("div", _hoisted_4$f, toDisplayString(slotInput ? slotInput.name : ""), 1),
              _cache[1] || (_cache[1] = createBaseVNode("div", { class: "_sb_col middle-column" }, null, -1)),
              createBaseVNode("div", {
                class: "_sb_col _sb_inherit",
                style: normalizeStyle({
                  color: litegraphColors.value.NODE_TEXT_COLOR
                })
              }, toDisplayString(slotOutput ? slotOutput.name : ""), 5),
              createBaseVNode("div", _hoisted_5$c, [
                slotOutput ? (openBlock(), createElementBlock("div", {
                  key: 0,
                  class: normalizeClass(["_sb_dot", slotOutput.type])
                }, null, 2)) : createCommentVNode("", true)
              ])
            ]);
          }), 128)),
          (openBlock(true), createElementBlock(Fragment$1, null, renderList(unref(widgetInputDefs), (widgetInput) => {
            return openBlock(), createElementBlock("div", {
              key: widgetInput.name,
              class: "_sb_row _long_field"
            }, [
              _cache[2] || (_cache[2] = createBaseVNode("div", { class: "_sb_col _sb_arrow" }, "◀", -1)),
              createBaseVNode("div", {
                class: "_sb_col",
                style: normalizeStyle({
                  color: litegraphColors.value.WIDGET_SECONDARY_TEXT_COLOR
                })
              }, toDisplayString(widgetInput.name), 5),
              _cache[3] || (_cache[3] = createBaseVNode("div", { class: "_sb_col middle-column" }, null, -1)),
              createBaseVNode("div", {
                class: "_sb_col _sb_inherit",
                style: normalizeStyle({ color: litegraphColors.value.WIDGET_TEXT_COLOR })
              }, toDisplayString(truncateDefaultValue(widgetInput.default)), 5),
              _cache[4] || (_cache[4] = createBaseVNode("div", { class: "_sb_col _sb_arrow" }, "▶", -1))
            ]);
          }), 128))
        ]),
        unref(nodeDef).description ? (openBlock(), createElementBlock("div", {
          key: 0,
          class: "_sb_description",
          style: normalizeStyle({
            color: litegraphColors.value.WIDGET_SECONDARY_TEXT_COLOR,
            backgroundColor: litegraphColors.value.WIDGET_BGCOLOR
          })
        }, toDisplayString(unref(nodeDef).description), 5)) : createCommentVNode("", true)
      ]);
    };
  }
});
const NodePreview = /* @__PURE__ */ _export_sfc(_sfc_main$Y, [["__scopeId", "data-v-f0ad355d"]]);
const PACK_LIST_CACHE_SIZE = 20;
const PACK_BY_ID_CACHE_SIZE = 64;
const isNodePack = /* @__PURE__ */ __name((pack) => {
  return pack !== void 0 && "id" in pack;
}, "isNodePack");
const useComfyRegistryStore = /* @__PURE__ */ defineStore("comfyRegistry", () => {
  const registryService = useComfyRegistryService();
  let getPacksByIdController = null;
  const getPacksByIdCache = new QuickLRU$1({
    maxSize: PACK_BY_ID_CACHE_SIZE
  });
  const listAllPacks = useCachedRequest(
    registryService.listAllPacks,
    { maxSize: PACK_LIST_CACHE_SIZE }
  );
  const getPackById = useCachedRequest(
    async (params) => {
      if (!params) return null;
      return registryService.getPackById(params);
    },
    { maxSize: PACK_BY_ID_CACHE_SIZE }
  );
  const getPacksByIds = /* @__PURE__ */ __name(async (ids) => {
    const [cachedPacksIds, uncachedPacksIds] = lodashExports.partition(
      ids,
      (id2) => getPacksByIdCache.has(id2)
    );
    const resolvedPacks = cachedPacksIds.map((id2) => getPacksByIdCache.get(id2)).filter(isNodePack);
    if (uncachedPacksIds.length) {
      getPacksByIdController = new AbortController();
      const uncachedPacks = await registryService.listAllPacks(
        {
          node_id: uncachedPacksIds.filter(
            (id2) => id2 !== void 0
          )
        },
        getPacksByIdController.signal
      );
      const { nodes = [] } = uncachedPacks ?? {};
      nodes.forEach((pack) => {
        if (pack?.id) {
          getPacksByIdCache.set(pack.id, pack);
          resolvedPacks.push(pack);
        }
      });
    }
    return resolvedPacks;
  }, "getPacksByIds");
  const getNodeDefs = useCachedRequest(registryService.getNodeDefs, { maxSize: PACK_BY_ID_CACHE_SIZE });
  const search2 = useCachedRequest(registryService.search, { maxSize: PACK_LIST_CACHE_SIZE });
  const clearCache = /* @__PURE__ */ __name(() => {
    getNodeDefs.clear();
    listAllPacks.clear();
    getPackById.clear();
  }, "clearCache");
  const cancelRequests = /* @__PURE__ */ __name(() => {
    getNodeDefs.cancel();
    listAllPacks.cancel();
    getPackById.cancel();
    getPacksByIdController?.abort();
  }, "cancelRequests");
  return {
    listAllPacks,
    getPackById,
    getPacksByIds: {
      call: getPacksByIds,
      cancel: /* @__PURE__ */ __name(() => getPacksByIdController?.abort(), "cancel")
    },
    getNodeDefs,
    search: search2,
    clearCache,
    cancelRequests,
    isLoading: registryService.isLoading,
    error: registryService.error
  };
});
const registryToFrontendV2NodeOutputs = /* @__PURE__ */ __name((registryDef) => {
  const returnTypes = JSON.parse(registryDef.return_types ?? "{}");
  if (!returnTypes.length) return [];
  const returnNames = JSON.parse(registryDef.return_names ?? "{}");
  const outputsIsList = registryDef.output_is_list ?? [];
  const outputs = [];
  for (let i2 = 0; i2 < returnTypes.length; i2++) {
    outputs.push({
      type: returnTypes[i2],
      name: returnNames[i2] || returnTypes[i2],
      is_list: outputsIsList[i2] ?? false,
      index: i2
    });
  }
  return outputs;
}, "registryToFrontendV2NodeOutputs");
const registryToFrontendV2NodeInputs = /* @__PURE__ */ __name((registryDef) => {
  const inputTypes = JSON.parse(
    registryDef.input_types ?? "{}"
  );
  if (!inputTypes || !Object.keys(inputTypes).length) return {};
  const inputsV2 = {};
  if (inputTypes.required) {
    Object.entries(inputTypes.required).forEach(([name2, inputSpecV1]) => {
      inputsV2[name2] = transformInputSpecV1ToV2(inputSpecV1, {
        name: name2,
        isOptional: false
      });
    });
  }
  if (inputTypes.optional) {
    Object.entries(inputTypes.optional).forEach(([name2, inputSpecV1]) => {
      inputsV2[name2] = transformInputSpecV1ToV2(inputSpecV1, {
        name: name2,
        isOptional: true
      });
    });
  }
  return inputsV2;
}, "registryToFrontendV2NodeInputs");
const registryToFrontendV2NodeDef = /* @__PURE__ */ __name((nodeDef, nodePack) => {
  const name2 = nodeDef.comfy_node_name ?? "Node Name";
  return {
    category: nodeDef.category ?? "unknown",
    description: nodeDef.description ?? "",
    display_name: name2,
    name: name2,
    inputs: registryToFrontendV2NodeInputs(nodeDef),
    outputs: registryToFrontendV2NodeOutputs(nodeDef),
    output_node: false,
    python_module: nodePack.name ?? nodePack.id ?? "unknown"
  };
}, "registryToFrontendV2NodeDef");
const _hoisted_1$M = { class: "flex flex-col gap-4 mt-4 text-sm" };
const _sfc_main$X = /* @__PURE__ */ defineComponent({
  __name: "NodesTabPanel",
  props: {
    nodePack: {},
    nodeNames: {}
  },
  setup(__props) {
    const { getNodeDefs } = useComfyRegistryStore();
    const isLoading = ref$3(false);
    const registryNodeDefs = shallowRef(null);
    const fetchNodeDefs = /* @__PURE__ */ __name(async () => {
      isLoading.value = true;
      const { id: packId } = __props.nodePack;
      const version2 = __props.nodePack.latest_version?.version;
      if (!packId || !version2) {
        registryNodeDefs.value = null;
      } else {
        const response = await getNodeDefs.call({
          packId,
          version: version2,
          page: 1,
          limit: 256
        });
        registryNodeDefs.value = response?.comfy_nodes ?? null;
      }
      isLoading.value = false;
    }, "fetchNodeDefs");
    whenever(() => __props.nodePack, fetchNodeDefs, { immediate: true, deep: true });
    const toFrontendNodeDef = /* @__PURE__ */ __name((nodeDef) => {
      try {
        return registryToFrontendV2NodeDef(nodeDef, __props.nodePack);
      } catch (error2) {
        return null;
      }
    }, "toFrontendNodeDef");
    const mappedNodeDefs = computed(() => {
      if (!registryNodeDefs.value) return null;
      return registryNodeDefs.value.map(toFrontendNodeDef).filter((nodeDef) => nodeDef !== null);
    });
    const createNodeDefKey = /* @__PURE__ */ __name((nodeDef) => `${nodeDef.category}${nodeDef.comfy_node_name ?? useId()}`, "createNodeDefKey");
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", _hoisted_1$M, [
        mappedNodeDefs.value?.length ? (openBlock(true), createElementBlock(Fragment$1, { key: 0 }, renderList(mappedNodeDefs.value, (nodeDef) => {
          return openBlock(), createElementBlock("div", {
            key: createNodeDefKey(nodeDef),
            class: "border rounded-lg p-4"
          }, [
            createVNode(NodePreview, {
              "node-def": nodeDef,
              class: "!text-[.625rem] !min-w-full"
            }, null, 8, ["node-def"])
          ]);
        }), 128)) : isLoading.value ? (openBlock(), createBlock(unref(script$x), { key: 1 })) : _ctx.nodeNames.length ? (openBlock(true), createElementBlock(Fragment$1, { key: 2 }, renderList(_ctx.nodeNames, (node2) => {
          return openBlock(), createElementBlock("div", {
            key: node2,
            class: "text-muted truncate"
          }, toDisplayString(node2), 1);
        }), 128)) : (openBlock(), createBlock(NoResultsPlaceholder, {
          key: 3,
          title: _ctx.$t("manager.noNodesFound"),
          message: _ctx.$t("manager.noNodesFoundDescription")
        }, null, 8, ["title", "message"]))
      ]);
    };
  }
});
const _hoisted_1$L = { class: "overflow-hidden" };
const _sfc_main$W = /* @__PURE__ */ defineComponent({
  __name: "InfoTabs",
  props: {
    nodePack: {}
  },
  setup(__props) {
    const nodeNames = computed(() => {
      const { comfy_nodes } = __props.nodePack;
      return comfy_nodes ?? [];
    });
    const activeTab = ref$3("description");
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", _hoisted_1$L, [
        createVNode(unref(script$u), { value: activeTab.value }, {
          default: withCtx(() => [
            createVNode(unref(script$B), null, {
              default: withCtx(() => [
                createVNode(unref(script$C), { value: "description" }, {
                  default: withCtx(() => [
                    createTextVNode(toDisplayString(_ctx.$t("g.description")), 1)
                  ]),
                  _: 1
                }),
                createVNode(unref(script$C), { value: "nodes" }, {
                  default: withCtx(() => [
                    createTextVNode(toDisplayString(_ctx.$t("g.nodes")), 1)
                  ]),
                  _: 1
                })
              ]),
              _: 1
            }),
            createVNode(unref(script$v), { class: "overflow-auto" }, {
              default: withCtx(() => [
                createVNode(unref(script$o), { value: "description" }, {
                  default: withCtx(() => [
                    createVNode(_sfc_main$_, { "node-pack": _ctx.nodePack }, null, 8, ["node-pack"])
                  ]),
                  _: 1
                }),
                createVNode(unref(script$o), { value: "nodes" }, {
                  default: withCtx(() => [
                    createVNode(_sfc_main$X, {
                      "node-pack": _ctx.nodePack,
                      "node-names": nodeNames.value
                    }, null, 8, ["node-pack", "node-names"])
                  ]),
                  _: 1
                })
              ]),
              _: 1
            })
          ]),
          _: 1
        }, 8, ["value"])
      ]);
    };
  }
});
const _hoisted_1$K = { class: "flex py-1.5 text-xs" };
const _hoisted_2$D = { class: "w-1/3 truncate pr-2 text-muted" };
const _hoisted_3$p = { class: "w-2/3" };
const _sfc_main$V = /* @__PURE__ */ defineComponent({
  __name: "MetadataRow",
  props: {
    label: { default: "N/A" },
    value: { default: "N/A" }
  },
  setup(__props) {
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", _hoisted_1$K, [
        createBaseVNode("div", _hoisted_2$D, toDisplayString(_ctx.label) + ":", 1),
        createBaseVNode("div", _hoisted_3$p, [
          renderSlot(_ctx.$slots, "default", {}, () => [
            createTextVNode(toDisplayString(_ctx.value), 1)
          ])
        ])
      ]);
    };
  }
});
const _hoisted_1$J = {
  key: 0,
  class: "flex flex-col h-full z-40 w-80 overflow-hidden relative"
};
const _hoisted_2$C = { class: "top-0 z-10 px-6 pt-6 w-full" };
const _hoisted_3$o = { class: "mb-6" };
const _hoisted_4$e = { class: "mb-6 overflow-hidden" };
const _hoisted_5$b = {
  key: 1,
  class: "mt-4 mx-8 flex-1 overflow-hidden text-sm"
};
const _sfc_main$U = /* @__PURE__ */ defineComponent({
  __name: "InfoPanel",
  props: {
    nodePack: {}
  },
  setup(__props) {
    const scrollContainer = ref$3(null);
    const managerStore = useComfyManagerStore();
    const isInstalled = computed(() => managerStore.isPackInstalled(__props.nodePack.id));
    const isInstalling = ref$3(false);
    provide(IsInstallingKey, isInstalling);
    whenever(isInstalled, () => {
      isInstalling.value = false;
    });
    const { isPackInstalled } = useComfyManagerStore();
    const { t: t2, d: d2, n: n2 } = useI18n();
    const infoItems = computed(() => [
      {
        key: "publisher",
        label: t2("manager.createdBy"),
        value: __props.nodePack.publisher?.name ?? __props.nodePack.publisher?.id
      },
      {
        key: "downloads",
        label: t2("manager.downloads"),
        value: __props.nodePack.downloads ? n2(__props.nodePack.downloads) : void 0
      },
      {
        key: "lastUpdated",
        label: t2("manager.lastUpdated"),
        value: __props.nodePack.latest_version?.createdAt ? d2(__props.nodePack.latest_version.createdAt, {
          dateStyle: "medium"
        }) : void 0
      }
    ]);
    const { y: y2 } = useScroll(scrollContainer, {
      eventListenerOptions: {
        passive: true
      }
    });
    const onNodePackChange = /* @__PURE__ */ __name(() => {
      y2.value = 0;
    }, "onNodePackChange");
    whenever(() => __props.nodePack, onNodePackChange, { immediate: true, deep: true });
    return (_ctx, _cache) => {
      return _ctx.nodePack ? (openBlock(), createElementBlock("div", _hoisted_1$J, [
        createBaseVNode("div", _hoisted_2$C, [
          createVNode(_sfc_main$11, {
            "node-packs": [_ctx.nodePack]
          }, null, 8, ["node-packs"])
        ]),
        createBaseVNode("div", {
          ref_key: "scrollContainer",
          ref: scrollContainer,
          class: "p-6 pt-2 overflow-y-auto flex-1 text-sm hidden-scrollbar"
        }, [
          createBaseVNode("div", _hoisted_3$o, [
            unref(isPackInstalled)(_ctx.nodePack.id) ? (openBlock(), createBlock(_sfc_main$V, {
              key: 0,
              label: unref(t2)("manager.filter.enabled"),
              class: "flex",
              style: { "align-items": "center" }
            }, {
              default: withCtx(() => [
                createVNode(_sfc_main$16, { "node-pack": _ctx.nodePack }, null, 8, ["node-pack"])
              ]),
              _: 1
            }, 8, ["label"])) : createCommentVNode("", true),
            (openBlock(true), createElementBlock(Fragment$1, null, renderList(infoItems.value, (item) => {
              return withDirectives((openBlock(), createBlock(_sfc_main$V, {
                key: item.key,
                label: item.label,
                value: item.value
              }, null, 8, ["label", "value"])), [
                [vShow, item.value !== void 0 && item.value !== null]
              ]);
            }), 128)),
            createVNode(_sfc_main$V, {
              label: unref(t2)("g.status")
            }, {
              default: withCtx(() => [
                createVNode(_sfc_main$19, {
                  "status-type": _ctx.nodePack.status
                }, null, 8, ["status-type"])
              ]),
              _: 1
            }, 8, ["label"]),
            createVNode(_sfc_main$V, {
              label: unref(t2)("manager.version")
            }, {
              default: withCtx(() => [
                createVNode(_sfc_main$17, { "node-pack": _ctx.nodePack }, null, 8, ["node-pack"])
              ]),
              _: 1
            }, 8, ["label"])
          ]),
          createBaseVNode("div", _hoisted_4$e, [
            createVNode(_sfc_main$W, { "node-pack": _ctx.nodePack }, null, 8, ["node-pack"])
          ])
        ], 512)
      ])) : (openBlock(), createElementBlock("div", _hoisted_5$b, toDisplayString(_ctx.$t("manager.infoPanelEmpty")), 1));
    };
  }
});
const InfoPanel = /* @__PURE__ */ _export_sfc(_sfc_main$U, [["__scopeId", "data-v-59439551"]]);
const _hoisted_1$I = { class: "relative w-24 h-24" };
const _hoisted_2$B = { class: "border rounded-lg p-0.5" };
const _hoisted_3$n = {
  key: 0,
  class: "absolute -top-2 -right-2 bg-primary rounded-full w-7 h-7 flex items-center justify-center text-xs font-bold shadow-md z-10"
};
const _sfc_main$T = /* @__PURE__ */ defineComponent({
  __name: "PackIconStacked",
  props: {
    nodePacks: {},
    maxVisible: { default: 3 },
    offset: { default: 8 }
  },
  setup(__props) {
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", _hoisted_1$I, [
        (openBlock(true), createElementBlock(Fragment$1, null, renderList(_ctx.nodePacks.slice(0, _ctx.maxVisible), (pack, index2) => {
          return openBlock(), createElementBlock("div", {
            key: pack.id,
            class: "absolute",
            style: normalizeStyle({
              bottom: `${index2 * _ctx.offset}px`,
              right: `${index2 * _ctx.offset}px`,
              zIndex: _ctx.maxVisible - index2
            })
          }, [
            createBaseVNode("div", _hoisted_2$B, [
              createVNode(_sfc_main$12, {
                "node-pack": pack,
                width: "4.5rem",
                height: "4.5rem"
              }, null, 8, ["node-pack"])
            ])
          ], 4);
        }), 128)),
        _ctx.nodePacks.length > _ctx.maxVisible ? (openBlock(), createElementBlock("div", _hoisted_3$n, " +" + toDisplayString(_ctx.nodePacks.length - _ctx.maxVisible), 1)) : createCommentVNode("", true)
      ]);
    };
  }
});
const _hoisted_1$H = {
  key: 0,
  class: "flex flex-col h-full"
};
const _hoisted_2$A = { class: "p-6 flex-1 overflow-auto" };
const _hoisted_3$m = { class: "mb-6" };
const _hoisted_4$d = {
  key: 1,
  class: "mt-4 mx-8 flex-1 overflow-hidden text-sm"
};
const _sfc_main$S = /* @__PURE__ */ defineComponent({
  __name: "InfoPanelMultiItem",
  props: {
    nodePacks: {}
  },
  setup(__props) {
    const { getNodeDefs } = useComfyRegistryStore();
    const getPackNodes = /* @__PURE__ */ __name(async (pack) => {
      if (!pack.latest_version?.version) return [];
      const nodeDefs = await getNodeDefs.call({
        packId: pack.id,
        version: pack.latest_version?.version
      });
      return nodeDefs?.comfy_nodes ?? [];
    }, "getPackNodes");
    const { state: allNodeDefs } = useAsyncState(
      () => Promise.all(__props.nodePacks.map(getPackNodes)),
      [],
      {
        immediate: true
      }
    );
    const totalNodesCount = computed(
      () => allNodeDefs.value.reduce(
        (total, nodeDefs) => total + (nodeDefs?.length || 0),
        0
      )
    );
    onUnmounted(() => {
      getNodeDefs.cancel();
    });
    return (_ctx, _cache) => {
      return _ctx.nodePacks?.length ? (openBlock(), createElementBlock("div", _hoisted_1$H, [
        createBaseVNode("div", _hoisted_2$A, [
          createVNode(_sfc_main$11, { "node-packs": _ctx.nodePacks }, {
            thumbnail: withCtx(() => [
              createVNode(_sfc_main$T, { "node-packs": _ctx.nodePacks }, null, 8, ["node-packs"])
            ]),
            title: withCtx(() => [
              createTextVNode(toDisplayString(_ctx.nodePacks.length) + " " + toDisplayString(_ctx.$t("manager.packsSelected")), 1)
            ]),
            "install-button": withCtx(() => [
              createVNode(_sfc_main$14, {
                "full-width": true,
                "node-packs": _ctx.nodePacks
              }, null, 8, ["node-packs"])
            ]),
            _: 1
          }, 8, ["node-packs"]),
          createBaseVNode("div", _hoisted_3$m, [
            createVNode(_sfc_main$V, {
              label: _ctx.$t("g.status")
            }, {
              default: withCtx(() => [
                createVNode(_sfc_main$19, { "status-type": "NodeVersionStatusActive" })
              ]),
              _: 1
            }, 8, ["label"]),
            createVNode(_sfc_main$V, {
              label: _ctx.$t("manager.totalNodes"),
              value: totalNodesCount.value
            }, null, 8, ["label", "value"])
          ])
        ])
      ])) : (openBlock(), createElementBlock("div", _hoisted_4$d, toDisplayString(_ctx.$t("manager.infoPanelEmpty")), 1));
    };
  }
});
const _hoisted_1$G = { class: "w-[100%] flex justify-between items-center" };
const _hoisted_2$z = { class: "flex justify-start items-center" };
const _hoisted_3$l = { class: "px-3 py-2 rounded-md flex justify-start items-start gap-2.5" };
const _hoisted_4$c = { class: "text-right justify-start text-sm font-bold leading-none" };
const _hoisted_5$a = { class: "inline-flex justify-start items-center gap-3" };
const _hoisted_6$9 = {
  key: 0,
  class: "flex items-center text-sm text-muted tracking-tighter"
};
const _sfc_main$R = /* @__PURE__ */ defineComponent({
  __name: "PackCardHeader",
  props: {
    nodePack: {}
  },
  setup(__props) {
    const { isPackInstalled } = useComfyManagerStore();
    const isInstalled = computed(() => isPackInstalled(__props.nodePack?.id));
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", _hoisted_1$G, [
        createBaseVNode("div", _hoisted_2$z, [
          _cache[0] || (_cache[0] = createBaseVNode("div", { class: "w-1 h-6 rounded-md" }, null, -1)),
          _cache[1] || (_cache[1] = createBaseVNode("div", { class: "w-6 h-6 relative overflow-hidden" }, [
            createBaseVNode("i", {
              class: "pi pi-box text-xl text-muted",
              style: { "opacity": "0.6" }
            })
          ], -1)),
          createBaseVNode("div", _hoisted_3$l, [
            createBaseVNode("div", _hoisted_4$c, toDisplayString(_ctx.$t("manager.nodePack")), 1)
          ])
        ]),
        createBaseVNode("div", _hoisted_5$a, [
          _ctx.nodePack.downloads ? (openBlock(), createElementBlock("div", _hoisted_6$9, [
            _cache[2] || (_cache[2] = createBaseVNode("i", { class: "pi pi-download mr-2" }, null, -1)),
            createTextVNode(" " + toDisplayString(_ctx.$n(_ctx.nodePack.downloads)), 1)
          ])) : createCommentVNode("", true),
          isInstalled.value ? (openBlock(), createBlock(_sfc_main$16, {
            key: 1,
            "node-pack": _ctx.nodePack
          }, null, 8, ["node-pack"])) : (openBlock(), createBlock(_sfc_main$14, {
            key: 2,
            "node-packs": [_ctx.nodePack]
          }, null, 8, ["node-packs"]))
        ])
      ]);
    };
  }
});
const _hoisted_1$F = { class: "flex justify-between px-5 py-4 text-xs text-muted font-medium leading-3" };
const _hoisted_2$y = { class: "flex items-center gap-2 cursor-pointer" };
const _hoisted_3$k = {
  key: 0,
  class: "max-w-40 truncate"
};
const _hoisted_4$b = {
  key: 0,
  class: "flex items-center gap-2 truncate"
};
const _sfc_main$Q = /* @__PURE__ */ defineComponent({
  __name: "PackCardFooter",
  props: {
    nodePack: {}
  },
  setup(__props) {
    const publisherName = computed(() => {
      if (!__props.nodePack) return null;
      const { publisher, author } = __props.nodePack;
      return publisher?.name ?? publisher?.id ?? author;
    });
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", _hoisted_1$F, [
        createBaseVNode("div", _hoisted_2$y, [
          publisherName.value ? (openBlock(), createElementBlock("span", _hoisted_3$k, toDisplayString(publisherName.value), 1)) : createCommentVNode("", true)
        ]),
        _ctx.nodePack.latest_version?.createdAt ? (openBlock(), createElementBlock("div", _hoisted_4$b, toDisplayString(_ctx.$t("g.updated")) + " " + toDisplayString(_ctx.$d(new Date(_ctx.nodePack.latest_version.createdAt), {
          dateStyle: "medium"
        })), 1)) : createCommentVNode("", true)
      ]);
    };
  }
});
const usePackUpdateStatus = /* @__PURE__ */ __name((nodePack) => {
  const { isPackInstalled, getInstalledPackVersion } = useComfyManagerStore();
  const isInstalled = computed(() => isPackInstalled(nodePack?.id));
  const installedVersion = computed(
    () => getInstalledPackVersion(nodePack.id ?? "")
  );
  const latestVersion = computed(() => nodePack.latest_version?.version);
  const isNightlyPack = computed(
    () => !!installedVersion.value && !isSemVer(installedVersion.value)
  );
  const isUpdateAvailable = computed(() => {
    if (!isInstalled.value || isNightlyPack.value || !latestVersion.value) {
      return false;
    }
    return compareVersions(latestVersion.value, installedVersion.value) > 0;
  });
  return {
    isUpdateAvailable,
    isNightlyPack,
    installedVersion,
    latestVersion
  };
}, "usePackUpdateStatus");
const _hoisted_1$E = {
  key: 0,
  class: "self-stretch inline-flex flex-col justify-center items-center gap-2 h-full"
};
const _hoisted_2$x = { class: "self-stretch text-center justify-start text-sm font-medium leading-none" };
const _hoisted_3$j = {
  key: 1,
  class: "self-stretch px-4 py-3 inline-flex justify-start items-start cursor-pointer"
};
const _hoisted_4$a = { class: "px-4 inline-flex flex-col justify-start items-start overflow-hidden" };
const _hoisted_5$9 = { class: "text-sm font-bold truncate overflow-hidden text-ellipsis" };
const _hoisted_6$8 = { class: "self-stretch inline-flex justify-center items-center gap-2.5" };
const _hoisted_7$4 = {
  key: 0,
  class: "flex-1 justify-start text-muted text-sm font-medium leading-3 break-words overflow-hidden min-h-12 line-clamp-3"
};
const _hoisted_8$3 = { class: "self-stretch inline-flex justify-start items-center gap-2" };
const _hoisted_9$3 = {
  key: 0,
  class: "px-2 py-1 flex justify-center text-sm items-center gap-1"
};
const _hoisted_10$3 = { class: "text-center justify-center font-medium leading-3" };
const _hoisted_11$2 = { class: "px-2 py-1 flex justify-center items-center gap-1" };
const _hoisted_12$1 = {
  key: 0,
  class: "w-4 h-4 relative overflow-hidden"
};
const _sfc_main$P = /* @__PURE__ */ defineComponent({
  __name: "PackCard",
  props: {
    nodePack: {},
    isSelected: { type: Boolean, default: false }
  },
  setup(__props) {
    const isInstalling = ref$3(false);
    provide(IsInstallingKey, isInstalling);
    const { isPackInstalled, isPackEnabled } = useComfyManagerStore();
    const { isUpdateAvailable } = usePackUpdateStatus(__props.nodePack);
    const isInstalled = computed(() => isPackInstalled(__props.nodePack?.id));
    const isDisabled = computed(
      () => isInstalled.value && !isPackEnabled(__props.nodePack?.id)
    );
    whenever(isInstalled, () => isInstalling.value = false);
    const nodesCount = computed(() => __props.nodePack.comfy_nodes?.length);
    return (_ctx, _cache) => {
      const _component_PackCardHeader = _sfc_main$R;
      return openBlock(), createBlock(unref(script$9), {
        class: normalizeClass(["w-full h-full inline-flex flex-col justify-between items-start overflow-hidden rounded-2xl shadow-elevation-3 dark-theme:bg-dark-elevation-2 transition-all duration-200", {
          "outline outline-[6px] outline-[var(--p-primary-color)]": _ctx.isSelected,
          "opacity-60": isDisabled.value
        }]),
        pt: {
          body: { class: "p-0 flex flex-col w-full h-full rounded-2xl gap-0" },
          content: { class: "flex-1 flex flex-col rounded-2xl" },
          title: {
            class: "self-stretch w-full px-4 py-3 inline-flex justify-start items-center gap-6"
          },
          footer: { class: "p-0 m-0" }
        }
      }, {
        title: withCtx(() => [
          createVNode(_component_PackCardHeader, { "node-pack": _ctx.nodePack }, null, 8, ["node-pack"])
        ]),
        content: withCtx(() => [
          createVNode(_sfc_main$1c),
          isInstalling.value ? (openBlock(), createElementBlock("div", _hoisted_1$E, [
            createVNode(unref(script$x)),
            createBaseVNode("div", _hoisted_2$x, toDisplayString(_ctx.$t("g.installing")) + "... ", 1)
          ])) : (openBlock(), createElementBlock("div", _hoisted_3$j, [
            createVNode(_sfc_main$12, { "node-pack": _ctx.nodePack }, null, 8, ["node-pack"]),
            createBaseVNode("div", _hoisted_4$a, [
              createBaseVNode("span", _hoisted_5$9, toDisplayString(_ctx.nodePack.name), 1),
              createBaseVNode("div", _hoisted_6$8, [
                _ctx.nodePack.description ? (openBlock(), createElementBlock("p", _hoisted_7$4, toDisplayString(_ctx.nodePack.description), 1)) : createCommentVNode("", true)
              ]),
              createBaseVNode("div", _hoisted_8$3, [
                nodesCount.value ? (openBlock(), createElementBlock("div", _hoisted_9$3, [
                  createBaseVNode("div", _hoisted_10$3, toDisplayString(nodesCount.value) + " " + toDisplayString(_ctx.$t("g.nodes")), 1)
                ])) : createCommentVNode("", true),
                createBaseVNode("div", _hoisted_11$2, [
                  unref(isUpdateAvailable) ? (openBlock(), createElementBlock("div", _hoisted_12$1, _cache[0] || (_cache[0] = [
                    createBaseVNode("i", { class: "pi pi-arrow-circle-up text-blue-600" }, null, -1)
                  ]))) : createCommentVNode("", true),
                  createVNode(_sfc_main$17, { "node-pack": _ctx.nodePack }, null, 8, ["node-pack"])
                ])
              ])
            ])
          ]))
        ]),
        footer: withCtx(() => [
          createVNode(_sfc_main$1c, { width: 0.1 }),
          createVNode(_sfc_main$Q, { "node-pack": _ctx.nodePack }, null, 8, ["node-pack"])
        ]),
        _: 1
      }, 8, ["class"]);
    };
  }
});
const _hoisted_1$D = { class: "flex items-center gap-1" };
const _hoisted_2$w = { class: "text-muted" };
const _sfc_main$O = /* @__PURE__ */ defineComponent({
  __name: "SearchFilterDropdown",
  props: {
    options: {},
    label: {},
    modelValue: {}
  },
  emits: ["update:modelValue"],
  setup(__props) {
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", _hoisted_1$D, [
        createBaseVNode("span", _hoisted_2$w, toDisplayString(_ctx.label) + ":", 1),
        createVNode(unref(script$c), {
          "model-value": _ctx.modelValue,
          options: _ctx.options,
          "option-label": "label",
          "option-value": "id",
          class: "min-w-[6rem] border-none bg-transparent shadow-none",
          pt: {
            input: { class: "py-0 px-1 border-none" },
            trigger: { class: "hidden" },
            panel: { class: "shadow-md" },
            item: { class: "py-2 px-3 text-sm" }
          },
          "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => _ctx.$emit("update:modelValue", $event))
        }, null, 8, ["model-value", "options"])
      ]);
    };
  }
});
const _hoisted_1$C = { class: "relative w-full p-6" };
const _hoisted_2$v = { class: "flex items-center w-full" };
const _hoisted_3$i = { class: "flex mt-3 text-sm" };
const _hoisted_4$9 = { class: "flex gap-6 ml-1" };
const _hoisted_5$8 = { class: "flex items-center gap-4 ml-6" };
const _hoisted_6$7 = {
  key: 0,
  class: "text-color-secondary"
};
const _sfc_main$N = /* @__PURE__ */ defineComponent({
  __name: "RegistrySearchBar",
  props: /* @__PURE__ */ mergeModels({
    searchResults: {},
    suggestions: {}
  }, {
    "searchQuery": {},
    "searchQueryModifiers": {},
    "searchMode": { default: "packs" },
    "searchModeModifiers": {},
    "sortField": {
      default: SortableAlgoliaField.Downloads
    },
    "sortFieldModifiers": {}
  }),
  emits: ["update:searchQuery", "update:searchMode", "update:sortField"],
  setup(__props) {
    const searchQuery = useModel(__props, "searchQuery");
    const searchMode = useModel(__props, "searchMode");
    const sortField = useModel(__props, "sortField");
    const { t: t2 } = useI18n();
    const hasResults = computed(
      () => searchQuery.value?.trim() && __props.searchResults?.length
    );
    const sortOptions = [
      { id: SortableAlgoliaField.Downloads, label: t2("manager.sort.downloads") },
      { id: SortableAlgoliaField.Created, label: t2("manager.sort.created") },
      { id: SortableAlgoliaField.Updated, label: t2("manager.sort.updated") },
      { id: SortableAlgoliaField.Publisher, label: t2("manager.sort.publisher") },
      { id: SortableAlgoliaField.Name, label: t2("g.name") }
    ];
    const filterOptions = [
      { id: "packs", label: t2("manager.filter.nodePack") },
      { id: "nodes", label: t2("g.nodes") }
    ];
    const onOptionSelect = /* @__PURE__ */ __name((event) => {
      searchQuery.value = event.value.query;
    }, "onOptionSelect");
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", _hoisted_1$C, [
        createBaseVNode("div", _hoisted_2$v, [
          createVNode(unref(script$D), {
            modelValue: searchQuery.value,
            "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => searchQuery.value = $event),
            modelModifiers: { lazy: true },
            suggestions: _ctx.suggestions || [],
            placeholder: _ctx.$t("manager.searchPlaceholder"),
            "complete-on-focus": false,
            delay: 8,
            "option-label": "query",
            class: "w-full",
            pt: {
              pcInputText: {
                root: {
                  autofocus: true,
                  class: "w-5/12 rounded-2xl"
                }
              },
              loader: {
                style: "display: none"
              }
            },
            "show-empty-message": false,
            onComplete: unref(lodashExports.stubTrue),
            onOptionSelect
          }, null, 8, ["modelValue", "suggestions", "placeholder", "onComplete"])
        ]),
        createBaseVNode("div", _hoisted_3$i, [
          createBaseVNode("div", _hoisted_4$9, [
            createVNode(_sfc_main$O, {
              modelValue: searchMode.value,
              "onUpdate:modelValue": _cache[1] || (_cache[1] = ($event) => searchMode.value = $event),
              options: filterOptions,
              label: _ctx.$t("g.filter")
            }, null, 8, ["modelValue", "label"]),
            createVNode(_sfc_main$O, {
              modelValue: sortField.value,
              "onUpdate:modelValue": _cache[2] || (_cache[2] = ($event) => sortField.value = $event),
              options: sortOptions,
              label: _ctx.$t("g.sort")
            }, null, 8, ["modelValue", "label"])
          ]),
          createBaseVNode("div", _hoisted_5$8, [
            hasResults.value ? (openBlock(), createElementBlock("small", _hoisted_6$7, toDisplayString(_ctx.$t("g.resultsCount", { count: _ctx.searchResults?.length || 0 })), 1)) : createCommentVNode("", true)
          ])
        ])
      ]);
    };
  }
});
const _hoisted_1$B = {
  class: "rounded-lg border shadow-sm h-full overflow-hidden flex flex-col",
  "data-virtual-grid-item": ""
};
const _hoisted_2$u = { class: "w-full px-4 py-3 flex justify-between items-center border-b" };
const _hoisted_3$h = { class: "flex items-center" };
const _hoisted_4$8 = { class: "w-6 h-6 flex items-center justify-center" };
const _hoisted_5$7 = { class: "flex-1 p-4 flex" };
const _hoisted_6$6 = { class: "flex-shrink-0 mr-4" };
const _hoisted_7$3 = { class: "flex-1 flex flex-col overflow-hidden" };
const _hoisted_8$2 = { class: "mb-3" };
const _hoisted_9$2 = { class: "flex gap-2" };
const _hoisted_10$2 = { class: "w-full px-5 py-4 flex justify-between items-center border-t" };
const _sfc_main$M = /* @__PURE__ */ defineComponent({
  __name: "PackCardSkeleton",
  setup(__props) {
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", _hoisted_1$B, [
        createBaseVNode("div", _hoisted_2$u, [
          createBaseVNode("div", _hoisted_3$h, [
            createBaseVNode("div", _hoisted_4$8, [
              createVNode(unref(script$y), {
                shape: "circle",
                width: "1.5rem",
                height: "1.5rem"
              })
            ]),
            createVNode(unref(script$y), {
              width: "5rem",
              height: "1rem",
              class: "ml-2"
            })
          ]),
          createVNode(unref(script$y), {
            width: "4rem",
            height: "1.75rem",
            "border-radius": "0.75rem"
          })
        ]),
        createBaseVNode("div", _hoisted_5$7, [
          createBaseVNode("div", _hoisted_6$6, [
            createVNode(unref(script$y), {
              width: "4rem",
              height: "4rem",
              "border-radius": "0.5rem"
            })
          ]),
          createBaseVNode("div", _hoisted_7$3, [
            createVNode(unref(script$y), {
              width: "80%",
              height: "1rem",
              class: "mb-2"
            }),
            createBaseVNode("div", _hoisted_8$2, [
              createVNode(unref(script$y), {
                width: "100%",
                height: "0.75rem",
                class: "mb-1"
              }),
              createVNode(unref(script$y), {
                width: "95%",
                height: "0.75rem",
                class: "mb-1"
              }),
              createVNode(unref(script$y), {
                width: "90%",
                height: "0.75rem"
              })
            ]),
            createBaseVNode("div", _hoisted_9$2, [
              createVNode(unref(script$y), {
                width: "4rem",
                height: "1.5rem",
                "border-radius": "0.75rem"
              }),
              createVNode(unref(script$y), {
                width: "5rem",
                height: "1.5rem",
                "border-radius": "0.75rem"
              })
            ])
          ])
        ]),
        createBaseVNode("div", _hoisted_10$2, [
          createVNode(unref(script$y), {
            width: "4rem",
            height: "0.8rem"
          }),
          createVNode(unref(script$y), {
            width: "6rem",
            height: "0.8rem"
          })
        ])
      ]);
    };
  }
});
const _sfc_main$L = /* @__PURE__ */ defineComponent({
  __name: "GridSkeleton",
  props: {
    skeletonCardCount: { default: 12 },
    gridStyle: {}
  },
  setup(__props) {
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", {
        style: normalizeStyle(_ctx.gridStyle)
      }, [
        (openBlock(true), createElementBlock(Fragment$1, null, renderList(_ctx.skeletonCardCount, (n2) => {
          return openBlock(), createBlock(_sfc_main$M, { key: n2 });
        }), 128))
      ], 4);
    };
  }
});
const useResponsiveCollapse = /* @__PURE__ */ __name((breakpointThreshold = "lg") => {
  const breakpoints = useBreakpoints(breakpointsTailwind);
  const isSmallScreen = breakpoints.smallerOrEqual(breakpointThreshold);
  const isOpen = ref$3(!isSmallScreen.value);
  const onIsSmallScreenChange = /* @__PURE__ */ __name(() => {
    if (isSmallScreen.value && isOpen.value) {
      isOpen.value = false;
    } else if (!isSmallScreen.value && !isOpen.value) {
      isOpen.value = true;
    }
  }, "onIsSmallScreenChange");
  watch(isSmallScreen, onIsSmallScreenChange);
  return {
    breakpoints,
    isOpen,
    isSmallScreen,
    open: /* @__PURE__ */ __name(() => isOpen.value = true, "open"),
    close: /* @__PURE__ */ __name(() => isOpen.value = false, "close"),
    toggle: /* @__PURE__ */ __name(() => isOpen.value = !isOpen.value, "toggle")
  };
}, "useResponsiveCollapse");
const useNodePacks = /* @__PURE__ */ __name((packsIds, options2 = {}) => {
  const { immediate = false } = options2;
  const { getPacksByIds } = useComfyRegistryStore();
  const fetchPacks = /* @__PURE__ */ __name(() => getPacksByIds.call(get$2(packsIds).filter(Boolean)), "fetchPacks");
  const {
    isReady,
    isLoading,
    error: error2,
    execute,
    state: nodePacks
  } = useAsyncState(fetchPacks, [], {
    immediate
  });
  const cleanup = /* @__PURE__ */ __name(() => {
    getPacksByIds.cancel();
    isReady.value = false;
    isLoading.value = false;
  }, "cleanup");
  return {
    error: error2,
    isLoading,
    isReady,
    nodePacks,
    startFetch: execute,
    cleanup
  };
}, "useNodePacks");
const useInstalledPacks = /* @__PURE__ */ __name((options2 = {}) => {
  const comfyManagerStore = useComfyManagerStore();
  const installedPackIds = computed(
    () => Array.from(comfyManagerStore.installedPacksIds)
  );
  const { startFetch, cleanup, error: error2, isLoading, nodePacks, isReady } = useNodePacks(installedPackIds, options2);
  const filterInstalledPack = /* @__PURE__ */ __name((packs) => packs.filter((pack) => comfyManagerStore.isPackInstalled(pack.id)), "filterInstalledPack");
  onUnmounted(() => {
    cleanup();
  });
  return {
    error: error2,
    isLoading,
    isReady,
    installedPacks: nodePacks,
    startFetchInstalled: startFetch,
    filterInstalledPack
  };
}, "useInstalledPacks");
function isArray(value) {
  return !Array.isArray ? getTag(value) === "[object Array]" : Array.isArray(value);
}
__name(isArray, "isArray");
const INFINITY = 1 / 0;
function baseToString(value) {
  if (typeof value == "string") {
    return value;
  }
  let result = value + "";
  return result == "0" && 1 / value == -INFINITY ? "-0" : result;
}
__name(baseToString, "baseToString");
function toString(value) {
  return value == null ? "" : baseToString(value);
}
__name(toString, "toString");
function isString(value) {
  return typeof value === "string";
}
__name(isString, "isString");
function isNumber(value) {
  return typeof value === "number";
}
__name(isNumber, "isNumber");
function isBoolean(value) {
  return value === true || value === false || isObjectLike(value) && getTag(value) == "[object Boolean]";
}
__name(isBoolean, "isBoolean");
function isObject(value) {
  return typeof value === "object";
}
__name(isObject, "isObject");
function isObjectLike(value) {
  return isObject(value) && value !== null;
}
__name(isObjectLike, "isObjectLike");
function isDefined(value) {
  return value !== void 0 && value !== null;
}
__name(isDefined, "isDefined");
function isBlank(value) {
  return !value.trim().length;
}
__name(isBlank, "isBlank");
function getTag(value) {
  return value == null ? value === void 0 ? "[object Undefined]" : "[object Null]" : Object.prototype.toString.call(value);
}
__name(getTag, "getTag");
const EXTENDED_SEARCH_UNAVAILABLE = "Extended search is not available";
const INCORRECT_INDEX_TYPE = "Incorrect 'index' type";
const LOGICAL_SEARCH_INVALID_QUERY_FOR_KEY = /* @__PURE__ */ __name((key) => `Invalid value for key ${key}`, "LOGICAL_SEARCH_INVALID_QUERY_FOR_KEY");
const PATTERN_LENGTH_TOO_LARGE = /* @__PURE__ */ __name((max) => `Pattern length exceeds max of ${max}.`, "PATTERN_LENGTH_TOO_LARGE");
const MISSING_KEY_PROPERTY = /* @__PURE__ */ __name((name2) => `Missing ${name2} property in key`, "MISSING_KEY_PROPERTY");
const INVALID_KEY_WEIGHT_VALUE = /* @__PURE__ */ __name((key) => `Property 'weight' in key '${key}' must be a positive integer`, "INVALID_KEY_WEIGHT_VALUE");
const hasOwn = Object.prototype.hasOwnProperty;
class KeyStore {
  static {
    __name(this, "KeyStore");
  }
  constructor(keys2) {
    this._keys = [];
    this._keyMap = {};
    let totalWeight = 0;
    keys2.forEach((key) => {
      let obj = createKey(key);
      this._keys.push(obj);
      this._keyMap[obj.id] = obj;
      totalWeight += obj.weight;
    });
    this._keys.forEach((key) => {
      key.weight /= totalWeight;
    });
  }
  get(keyId) {
    return this._keyMap[keyId];
  }
  keys() {
    return this._keys;
  }
  toJSON() {
    return JSON.stringify(this._keys);
  }
}
function createKey(key) {
  let path = null;
  let id2 = null;
  let src = null;
  let weight = 1;
  let getFn = null;
  if (isString(key) || isArray(key)) {
    src = key;
    path = createKeyPath(key);
    id2 = createKeyId(key);
  } else {
    if (!hasOwn.call(key, "name")) {
      throw new Error(MISSING_KEY_PROPERTY("name"));
    }
    const name2 = key.name;
    src = name2;
    if (hasOwn.call(key, "weight")) {
      weight = key.weight;
      if (weight <= 0) {
        throw new Error(INVALID_KEY_WEIGHT_VALUE(name2));
      }
    }
    path = createKeyPath(name2);
    id2 = createKeyId(name2);
    getFn = key.getFn;
  }
  return { path, id: id2, weight, src, getFn };
}
__name(createKey, "createKey");
function createKeyPath(key) {
  return isArray(key) ? key : key.split(".");
}
__name(createKeyPath, "createKeyPath");
function createKeyId(key) {
  return isArray(key) ? key.join(".") : key;
}
__name(createKeyId, "createKeyId");
function get$1(obj, path) {
  let list2 = [];
  let arr = false;
  const deepGet = /* @__PURE__ */ __name((obj2, path2, index2) => {
    if (!isDefined(obj2)) {
      return;
    }
    if (!path2[index2]) {
      list2.push(obj2);
    } else {
      let key = path2[index2];
      const value = obj2[key];
      if (!isDefined(value)) {
        return;
      }
      if (index2 === path2.length - 1 && (isString(value) || isNumber(value) || isBoolean(value))) {
        list2.push(toString(value));
      } else if (isArray(value)) {
        arr = true;
        for (let i2 = 0, len = value.length; i2 < len; i2 += 1) {
          deepGet(value[i2], path2, index2 + 1);
        }
      } else if (path2.length) {
        deepGet(value, path2, index2 + 1);
      }
    }
  }, "deepGet");
  deepGet(obj, isString(path) ? path.split(".") : path, 0);
  return arr ? list2 : list2[0];
}
__name(get$1, "get$1");
const MatchOptions = {
  // Whether the matches should be included in the result set. When `true`, each record in the result
  // set will include the indices of the matched characters.
  // These can consequently be used for highlighting purposes.
  includeMatches: false,
  // When `true`, the matching function will continue to the end of a search pattern even if
  // a perfect match has already been located in the string.
  findAllMatches: false,
  // Minimum number of characters that must be matched before a result is considered a match
  minMatchCharLength: 1
};
const BasicOptions = {
  // When `true`, the algorithm continues searching to the end of the input even if a perfect
  // match is found before the end of the same input.
  isCaseSensitive: false,
  // When true, the matching function will continue to the end of a search pattern even if
  includeScore: false,
  // List of properties that will be searched. This also supports nested properties.
  keys: [],
  // Whether to sort the result list, by score
  shouldSort: true,
  // Default sort function: sort by ascending score, ascending index
  sortFn: /* @__PURE__ */ __name((a2, b2) => a2.score === b2.score ? a2.idx < b2.idx ? -1 : 1 : a2.score < b2.score ? -1 : 1, "sortFn")
};
const FuzzyOptions = {
  // Approximately where in the text is the pattern expected to be found?
  location: 0,
  // At what point does the match algorithm give up. A threshold of '0.0' requires a perfect match
  // (of both letters and location), a threshold of '1.0' would match anything.
  threshold: 0.6,
  // Determines how close the match must be to the fuzzy location (specified above).
  // An exact letter match which is 'distance' characters away from the fuzzy location
  // would score as a complete mismatch. A distance of '0' requires the match be at
  // the exact location specified, a threshold of '1000' would require a perfect match
  // to be within 800 characters of the fuzzy location to be found using a 0.8 threshold.
  distance: 100
};
const AdvancedOptions = {
  // When `true`, it enables the use of unix-like search commands
  useExtendedSearch: false,
  // The get function to use when fetching an object's properties.
  // The default will search nested paths *ie foo.bar.baz*
  getFn: get$1,
  // When `true`, search will ignore `location` and `distance`, so it won't matter
  // where in the string the pattern appears.
  // More info: https://fusejs.io/concepts/scoring-theory.html#fuzziness-score
  ignoreLocation: false,
  // When `true`, the calculation for the relevance score (used for sorting) will
  // ignore the field-length norm.
  // More info: https://fusejs.io/concepts/scoring-theory.html#field-length-norm
  ignoreFieldNorm: false,
  // The weight to determine how much field length norm effects scoring.
  fieldNormWeight: 1
};
var Config = {
  ...BasicOptions,
  ...MatchOptions,
  ...FuzzyOptions,
  ...AdvancedOptions
};
const SPACE = /[^ ]+/g;
function norm(weight = 1, mantissa = 3) {
  const cache = /* @__PURE__ */ new Map();
  const m2 = Math.pow(10, mantissa);
  return {
    get(value) {
      const numTokens = value.match(SPACE).length;
      if (cache.has(numTokens)) {
        return cache.get(numTokens);
      }
      const norm2 = 1 / Math.pow(numTokens, 0.5 * weight);
      const n2 = parseFloat(Math.round(norm2 * m2) / m2);
      cache.set(numTokens, n2);
      return n2;
    },
    clear() {
      cache.clear();
    }
  };
}
__name(norm, "norm");
class FuseIndex {
  static {
    __name(this, "FuseIndex");
  }
  constructor({
    getFn = Config.getFn,
    fieldNormWeight = Config.fieldNormWeight
  } = {}) {
    this.norm = norm(fieldNormWeight, 3);
    this.getFn = getFn;
    this.isCreated = false;
    this.setIndexRecords();
  }
  setSources(docs = []) {
    this.docs = docs;
  }
  setIndexRecords(records = []) {
    this.records = records;
  }
  setKeys(keys2 = []) {
    this.keys = keys2;
    this._keysMap = {};
    keys2.forEach((key, idx) => {
      this._keysMap[key.id] = idx;
    });
  }
  create() {
    if (this.isCreated || !this.docs.length) {
      return;
    }
    this.isCreated = true;
    if (isString(this.docs[0])) {
      this.docs.forEach((doc2, docIndex) => {
        this._addString(doc2, docIndex);
      });
    } else {
      this.docs.forEach((doc2, docIndex) => {
        this._addObject(doc2, docIndex);
      });
    }
    this.norm.clear();
  }
  // Adds a doc to the end of the index
  add(doc2) {
    const idx = this.size();
    if (isString(doc2)) {
      this._addString(doc2, idx);
    } else {
      this._addObject(doc2, idx);
    }
  }
  // Removes the doc at the specified index of the index
  removeAt(idx) {
    this.records.splice(idx, 1);
    for (let i2 = idx, len = this.size(); i2 < len; i2 += 1) {
      this.records[i2].i -= 1;
    }
  }
  getValueForItemAtKeyId(item, keyId) {
    return item[this._keysMap[keyId]];
  }
  size() {
    return this.records.length;
  }
  _addString(doc2, docIndex) {
    if (!isDefined(doc2) || isBlank(doc2)) {
      return;
    }
    let record2 = {
      v: doc2,
      i: docIndex,
      n: this.norm.get(doc2)
    };
    this.records.push(record2);
  }
  _addObject(doc2, docIndex) {
    let record2 = { i: docIndex, $: {} };
    this.keys.forEach((key, keyIndex) => {
      let value = key.getFn ? key.getFn(doc2) : this.getFn(doc2, key.path);
      if (!isDefined(value)) {
        return;
      }
      if (isArray(value)) {
        let subRecords = [];
        const stack = [{ nestedArrIndex: -1, value }];
        while (stack.length) {
          const { nestedArrIndex, value: value2 } = stack.pop();
          if (!isDefined(value2)) {
            continue;
          }
          if (isString(value2) && !isBlank(value2)) {
            let subRecord = {
              v: value2,
              i: nestedArrIndex,
              n: this.norm.get(value2)
            };
            subRecords.push(subRecord);
          } else if (isArray(value2)) {
            value2.forEach((item, k2) => {
              stack.push({
                nestedArrIndex: k2,
                value: item
              });
            });
          } else ;
        }
        record2.$[keyIndex] = subRecords;
      } else if (isString(value) && !isBlank(value)) {
        let subRecord = {
          v: value,
          n: this.norm.get(value)
        };
        record2.$[keyIndex] = subRecord;
      }
    });
    this.records.push(record2);
  }
  toJSON() {
    return {
      keys: this.keys,
      records: this.records
    };
  }
}
function createIndex(keys2, docs, { getFn = Config.getFn, fieldNormWeight = Config.fieldNormWeight } = {}) {
  const myIndex = new FuseIndex({ getFn, fieldNormWeight });
  myIndex.setKeys(keys2.map(createKey));
  myIndex.setSources(docs);
  myIndex.create();
  return myIndex;
}
__name(createIndex, "createIndex");
function parseIndex(data, { getFn = Config.getFn, fieldNormWeight = Config.fieldNormWeight } = {}) {
  const { keys: keys2, records } = data;
  const myIndex = new FuseIndex({ getFn, fieldNormWeight });
  myIndex.setKeys(keys2);
  myIndex.setIndexRecords(records);
  return myIndex;
}
__name(parseIndex, "parseIndex");
function computeScore$1(pattern, {
  errors: errors2 = 0,
  currentLocation = 0,
  expectedLocation = 0,
  distance: distance2 = Config.distance,
  ignoreLocation = Config.ignoreLocation
} = {}) {
  const accuracy = errors2 / pattern.length;
  if (ignoreLocation) {
    return accuracy;
  }
  const proximity = Math.abs(expectedLocation - currentLocation);
  if (!distance2) {
    return proximity ? 1 : accuracy;
  }
  return accuracy + proximity / distance2;
}
__name(computeScore$1, "computeScore$1");
function convertMaskToIndices(matchmask = [], minMatchCharLength = Config.minMatchCharLength) {
  let indices = [];
  let start2 = -1;
  let end = -1;
  let i2 = 0;
  for (let len = matchmask.length; i2 < len; i2 += 1) {
    let match2 = matchmask[i2];
    if (match2 && start2 === -1) {
      start2 = i2;
    } else if (!match2 && start2 !== -1) {
      end = i2 - 1;
      if (end - start2 + 1 >= minMatchCharLength) {
        indices.push([start2, end]);
      }
      start2 = -1;
    }
  }
  if (matchmask[i2 - 1] && i2 - start2 >= minMatchCharLength) {
    indices.push([start2, i2 - 1]);
  }
  return indices;
}
__name(convertMaskToIndices, "convertMaskToIndices");
const MAX_BITS = 32;
function search(text2, pattern, patternAlphabet, {
  location: location2 = Config.location,
  distance: distance2 = Config.distance,
  threshold = Config.threshold,
  findAllMatches = Config.findAllMatches,
  minMatchCharLength = Config.minMatchCharLength,
  includeMatches = Config.includeMatches,
  ignoreLocation = Config.ignoreLocation
} = {}) {
  if (pattern.length > MAX_BITS) {
    throw new Error(PATTERN_LENGTH_TOO_LARGE(MAX_BITS));
  }
  const patternLen = pattern.length;
  const textLen = text2.length;
  const expectedLocation = Math.max(0, Math.min(location2, textLen));
  let currentThreshold = threshold;
  let bestLocation = expectedLocation;
  const computeMatches = minMatchCharLength > 1 || includeMatches;
  const matchMask = computeMatches ? Array(textLen) : [];
  let index2;
  while ((index2 = text2.indexOf(pattern, bestLocation)) > -1) {
    let score = computeScore$1(pattern, {
      currentLocation: index2,
      expectedLocation,
      distance: distance2,
      ignoreLocation
    });
    currentThreshold = Math.min(score, currentThreshold);
    bestLocation = index2 + patternLen;
    if (computeMatches) {
      let i2 = 0;
      while (i2 < patternLen) {
        matchMask[index2 + i2] = 1;
        i2 += 1;
      }
    }
  }
  bestLocation = -1;
  let lastBitArr = [];
  let finalScore = 1;
  let binMax = patternLen + textLen;
  const mask = 1 << patternLen - 1;
  for (let i2 = 0; i2 < patternLen; i2 += 1) {
    let binMin = 0;
    let binMid = binMax;
    while (binMin < binMid) {
      const score2 = computeScore$1(pattern, {
        errors: i2,
        currentLocation: expectedLocation + binMid,
        expectedLocation,
        distance: distance2,
        ignoreLocation
      });
      if (score2 <= currentThreshold) {
        binMin = binMid;
      } else {
        binMax = binMid;
      }
      binMid = Math.floor((binMax - binMin) / 2 + binMin);
    }
    binMax = binMid;
    let start2 = Math.max(1, expectedLocation - binMid + 1);
    let finish = findAllMatches ? textLen : Math.min(expectedLocation + binMid, textLen) + patternLen;
    let bitArr = Array(finish + 2);
    bitArr[finish + 1] = (1 << i2) - 1;
    for (let j2 = finish; j2 >= start2; j2 -= 1) {
      let currentLocation = j2 - 1;
      let charMatch = patternAlphabet[text2.charAt(currentLocation)];
      if (computeMatches) {
        matchMask[currentLocation] = +!!charMatch;
      }
      bitArr[j2] = (bitArr[j2 + 1] << 1 | 1) & charMatch;
      if (i2) {
        bitArr[j2] |= (lastBitArr[j2 + 1] | lastBitArr[j2]) << 1 | 1 | lastBitArr[j2 + 1];
      }
      if (bitArr[j2] & mask) {
        finalScore = computeScore$1(pattern, {
          errors: i2,
          currentLocation,
          expectedLocation,
          distance: distance2,
          ignoreLocation
        });
        if (finalScore <= currentThreshold) {
          currentThreshold = finalScore;
          bestLocation = currentLocation;
          if (bestLocation <= expectedLocation) {
            break;
          }
          start2 = Math.max(1, 2 * expectedLocation - bestLocation);
        }
      }
    }
    const score = computeScore$1(pattern, {
      errors: i2 + 1,
      currentLocation: expectedLocation,
      expectedLocation,
      distance: distance2,
      ignoreLocation
    });
    if (score > currentThreshold) {
      break;
    }
    lastBitArr = bitArr;
  }
  const result = {
    isMatch: bestLocation >= 0,
    // Count exact matches (those with a score of 0) to be "almost" exact
    score: Math.max(1e-3, finalScore)
  };
  if (computeMatches) {
    const indices = convertMaskToIndices(matchMask, minMatchCharLength);
    if (!indices.length) {
      result.isMatch = false;
    } else if (includeMatches) {
      result.indices = indices;
    }
  }
  return result;
}
__name(search, "search");
function createPatternAlphabet(pattern) {
  let mask = {};
  for (let i2 = 0, len = pattern.length; i2 < len; i2 += 1) {
    const char = pattern.charAt(i2);
    mask[char] = (mask[char] || 0) | 1 << len - i2 - 1;
  }
  return mask;
}
__name(createPatternAlphabet, "createPatternAlphabet");
class BitapSearch {
  static {
    __name(this, "BitapSearch");
  }
  constructor(pattern, {
    location: location2 = Config.location,
    threshold = Config.threshold,
    distance: distance2 = Config.distance,
    includeMatches = Config.includeMatches,
    findAllMatches = Config.findAllMatches,
    minMatchCharLength = Config.minMatchCharLength,
    isCaseSensitive = Config.isCaseSensitive,
    ignoreLocation = Config.ignoreLocation
  } = {}) {
    this.options = {
      location: location2,
      threshold,
      distance: distance2,
      includeMatches,
      findAllMatches,
      minMatchCharLength,
      isCaseSensitive,
      ignoreLocation
    };
    this.pattern = isCaseSensitive ? pattern : pattern.toLowerCase();
    this.chunks = [];
    if (!this.pattern.length) {
      return;
    }
    const addChunk = /* @__PURE__ */ __name((pattern2, startIndex) => {
      this.chunks.push({
        pattern: pattern2,
        alphabet: createPatternAlphabet(pattern2),
        startIndex
      });
    }, "addChunk");
    const len = this.pattern.length;
    if (len > MAX_BITS) {
      let i2 = 0;
      const remainder = len % MAX_BITS;
      const end = len - remainder;
      while (i2 < end) {
        addChunk(this.pattern.substr(i2, MAX_BITS), i2);
        i2 += MAX_BITS;
      }
      if (remainder) {
        const startIndex = len - MAX_BITS;
        addChunk(this.pattern.substr(startIndex), startIndex);
      }
    } else {
      addChunk(this.pattern, 0);
    }
  }
  searchIn(text2) {
    const { isCaseSensitive, includeMatches } = this.options;
    if (!isCaseSensitive) {
      text2 = text2.toLowerCase();
    }
    if (this.pattern === text2) {
      let result2 = {
        isMatch: true,
        score: 0
      };
      if (includeMatches) {
        result2.indices = [[0, text2.length - 1]];
      }
      return result2;
    }
    const {
      location: location2,
      distance: distance2,
      threshold,
      findAllMatches,
      minMatchCharLength,
      ignoreLocation
    } = this.options;
    let allIndices = [];
    let totalScore = 0;
    let hasMatches = false;
    this.chunks.forEach(({ pattern, alphabet, startIndex }) => {
      const { isMatch, score, indices } = search(text2, pattern, alphabet, {
        location: location2 + startIndex,
        distance: distance2,
        threshold,
        findAllMatches,
        minMatchCharLength,
        includeMatches,
        ignoreLocation
      });
      if (isMatch) {
        hasMatches = true;
      }
      totalScore += score;
      if (isMatch && indices) {
        allIndices = [...allIndices, ...indices];
      }
    });
    let result = {
      isMatch: hasMatches,
      score: hasMatches ? totalScore / this.chunks.length : 1
    };
    if (hasMatches && includeMatches) {
      result.indices = allIndices;
    }
    return result;
  }
}
class BaseMatch {
  static {
    __name(this, "BaseMatch");
  }
  constructor(pattern) {
    this.pattern = pattern;
  }
  static isMultiMatch(pattern) {
    return getMatch(pattern, this.multiRegex);
  }
  static isSingleMatch(pattern) {
    return getMatch(pattern, this.singleRegex);
  }
  search() {
  }
}
function getMatch(pattern, exp) {
  const matches2 = pattern.match(exp);
  return matches2 ? matches2[1] : null;
}
__name(getMatch, "getMatch");
class ExactMatch extends BaseMatch {
  static {
    __name(this, "ExactMatch");
  }
  constructor(pattern) {
    super(pattern);
  }
  static get type() {
    return "exact";
  }
  static get multiRegex() {
    return /^="(.*)"$/;
  }
  static get singleRegex() {
    return /^=(.*)$/;
  }
  search(text2) {
    const isMatch = text2 === this.pattern;
    return {
      isMatch,
      score: isMatch ? 0 : 1,
      indices: [0, this.pattern.length - 1]
    };
  }
}
class InverseExactMatch extends BaseMatch {
  static {
    __name(this, "InverseExactMatch");
  }
  constructor(pattern) {
    super(pattern);
  }
  static get type() {
    return "inverse-exact";
  }
  static get multiRegex() {
    return /^!"(.*)"$/;
  }
  static get singleRegex() {
    return /^!(.*)$/;
  }
  search(text2) {
    const index2 = text2.indexOf(this.pattern);
    const isMatch = index2 === -1;
    return {
      isMatch,
      score: isMatch ? 0 : 1,
      indices: [0, text2.length - 1]
    };
  }
}
class PrefixExactMatch extends BaseMatch {
  static {
    __name(this, "PrefixExactMatch");
  }
  constructor(pattern) {
    super(pattern);
  }
  static get type() {
    return "prefix-exact";
  }
  static get multiRegex() {
    return /^\^"(.*)"$/;
  }
  static get singleRegex() {
    return /^\^(.*)$/;
  }
  search(text2) {
    const isMatch = text2.startsWith(this.pattern);
    return {
      isMatch,
      score: isMatch ? 0 : 1,
      indices: [0, this.pattern.length - 1]
    };
  }
}
class InversePrefixExactMatch extends BaseMatch {
  static {
    __name(this, "InversePrefixExactMatch");
  }
  constructor(pattern) {
    super(pattern);
  }
  static get type() {
    return "inverse-prefix-exact";
  }
  static get multiRegex() {
    return /^!\^"(.*)"$/;
  }
  static get singleRegex() {
    return /^!\^(.*)$/;
  }
  search(text2) {
    const isMatch = !text2.startsWith(this.pattern);
    return {
      isMatch,
      score: isMatch ? 0 : 1,
      indices: [0, text2.length - 1]
    };
  }
}
class SuffixExactMatch extends BaseMatch {
  static {
    __name(this, "SuffixExactMatch");
  }
  constructor(pattern) {
    super(pattern);
  }
  static get type() {
    return "suffix-exact";
  }
  static get multiRegex() {
    return /^"(.*)"\$$/;
  }
  static get singleRegex() {
    return /^(.*)\$$/;
  }
  search(text2) {
    const isMatch = text2.endsWith(this.pattern);
    return {
      isMatch,
      score: isMatch ? 0 : 1,
      indices: [text2.length - this.pattern.length, text2.length - 1]
    };
  }
}
class InverseSuffixExactMatch extends BaseMatch {
  static {
    __name(this, "InverseSuffixExactMatch");
  }
  constructor(pattern) {
    super(pattern);
  }
  static get type() {
    return "inverse-suffix-exact";
  }
  static get multiRegex() {
    return /^!"(.*)"\$$/;
  }
  static get singleRegex() {
    return /^!(.*)\$$/;
  }
  search(text2) {
    const isMatch = !text2.endsWith(this.pattern);
    return {
      isMatch,
      score: isMatch ? 0 : 1,
      indices: [0, text2.length - 1]
    };
  }
}
class FuzzyMatch extends BaseMatch {
  static {
    __name(this, "FuzzyMatch");
  }
  constructor(pattern, {
    location: location2 = Config.location,
    threshold = Config.threshold,
    distance: distance2 = Config.distance,
    includeMatches = Config.includeMatches,
    findAllMatches = Config.findAllMatches,
    minMatchCharLength = Config.minMatchCharLength,
    isCaseSensitive = Config.isCaseSensitive,
    ignoreLocation = Config.ignoreLocation
  } = {}) {
    super(pattern);
    this._bitapSearch = new BitapSearch(pattern, {
      location: location2,
      threshold,
      distance: distance2,
      includeMatches,
      findAllMatches,
      minMatchCharLength,
      isCaseSensitive,
      ignoreLocation
    });
  }
  static get type() {
    return "fuzzy";
  }
  static get multiRegex() {
    return /^"(.*)"$/;
  }
  static get singleRegex() {
    return /^(.*)$/;
  }
  search(text2) {
    return this._bitapSearch.searchIn(text2);
  }
}
class IncludeMatch extends BaseMatch {
  static {
    __name(this, "IncludeMatch");
  }
  constructor(pattern) {
    super(pattern);
  }
  static get type() {
    return "include";
  }
  static get multiRegex() {
    return /^'"(.*)"$/;
  }
  static get singleRegex() {
    return /^'(.*)$/;
  }
  search(text2) {
    let location2 = 0;
    let index2;
    const indices = [];
    const patternLen = this.pattern.length;
    while ((index2 = text2.indexOf(this.pattern, location2)) > -1) {
      location2 = index2 + patternLen;
      indices.push([index2, location2 - 1]);
    }
    const isMatch = !!indices.length;
    return {
      isMatch,
      score: isMatch ? 0 : 1,
      indices
    };
  }
}
const searchers = [
  ExactMatch,
  IncludeMatch,
  PrefixExactMatch,
  InversePrefixExactMatch,
  InverseSuffixExactMatch,
  SuffixExactMatch,
  InverseExactMatch,
  FuzzyMatch
];
const searchersLen = searchers.length;
const SPACE_RE = / +(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/;
const OR_TOKEN = "|";
function parseQuery(pattern, options2 = {}) {
  return pattern.split(OR_TOKEN).map((item) => {
    let query2 = item.trim().split(SPACE_RE).filter((item2) => item2 && !!item2.trim());
    let results = [];
    for (let i2 = 0, len = query2.length; i2 < len; i2 += 1) {
      const queryItem = query2[i2];
      let found2 = false;
      let idx = -1;
      while (!found2 && ++idx < searchersLen) {
        const searcher = searchers[idx];
        let token = searcher.isMultiMatch(queryItem);
        if (token) {
          results.push(new searcher(token, options2));
          found2 = true;
        }
      }
      if (found2) {
        continue;
      }
      idx = -1;
      while (++idx < searchersLen) {
        const searcher = searchers[idx];
        let token = searcher.isSingleMatch(queryItem);
        if (token) {
          results.push(new searcher(token, options2));
          break;
        }
      }
    }
    return results;
  });
}
__name(parseQuery, "parseQuery");
const MultiMatchSet = /* @__PURE__ */ new Set([FuzzyMatch.type, IncludeMatch.type]);
class ExtendedSearch {
  static {
    __name(this, "ExtendedSearch");
  }
  constructor(pattern, {
    isCaseSensitive = Config.isCaseSensitive,
    includeMatches = Config.includeMatches,
    minMatchCharLength = Config.minMatchCharLength,
    ignoreLocation = Config.ignoreLocation,
    findAllMatches = Config.findAllMatches,
    location: location2 = Config.location,
    threshold = Config.threshold,
    distance: distance2 = Config.distance
  } = {}) {
    this.query = null;
    this.options = {
      isCaseSensitive,
      includeMatches,
      minMatchCharLength,
      findAllMatches,
      ignoreLocation,
      location: location2,
      threshold,
      distance: distance2
    };
    this.pattern = isCaseSensitive ? pattern : pattern.toLowerCase();
    this.query = parseQuery(this.pattern, this.options);
  }
  static condition(_2, options2) {
    return options2.useExtendedSearch;
  }
  searchIn(text2) {
    const query2 = this.query;
    if (!query2) {
      return {
        isMatch: false,
        score: 1
      };
    }
    const { includeMatches, isCaseSensitive } = this.options;
    text2 = isCaseSensitive ? text2 : text2.toLowerCase();
    let numMatches = 0;
    let allIndices = [];
    let totalScore = 0;
    for (let i2 = 0, qLen = query2.length; i2 < qLen; i2 += 1) {
      const searchers2 = query2[i2];
      allIndices.length = 0;
      numMatches = 0;
      for (let j2 = 0, pLen = searchers2.length; j2 < pLen; j2 += 1) {
        const searcher = searchers2[j2];
        const { isMatch, indices, score } = searcher.search(text2);
        if (isMatch) {
          numMatches += 1;
          totalScore += score;
          if (includeMatches) {
            const type = searcher.constructor.type;
            if (MultiMatchSet.has(type)) {
              allIndices = [...allIndices, ...indices];
            } else {
              allIndices.push(indices);
            }
          }
        } else {
          totalScore = 0;
          numMatches = 0;
          allIndices.length = 0;
          break;
        }
      }
      if (numMatches) {
        let result = {
          isMatch: true,
          score: totalScore / numMatches
        };
        if (includeMatches) {
          result.indices = allIndices;
        }
        return result;
      }
    }
    return {
      isMatch: false,
      score: 1
    };
  }
}
const registeredSearchers = [];
function register$1(...args) {
  registeredSearchers.push(...args);
}
__name(register$1, "register$1");
function createSearcher(pattern, options2) {
  for (let i2 = 0, len = registeredSearchers.length; i2 < len; i2 += 1) {
    let searcherClass = registeredSearchers[i2];
    if (searcherClass.condition(pattern, options2)) {
      return new searcherClass(pattern, options2);
    }
  }
  return new BitapSearch(pattern, options2);
}
__name(createSearcher, "createSearcher");
const LogicalOperator = {
  AND: "$and",
  OR: "$or"
};
const KeyType = {
  PATH: "$path",
  PATTERN: "$val"
};
const isExpression = /* @__PURE__ */ __name((query2) => !!(query2[LogicalOperator.AND] || query2[LogicalOperator.OR]), "isExpression");
const isPath = /* @__PURE__ */ __name((query2) => !!query2[KeyType.PATH], "isPath");
const isLeaf = /* @__PURE__ */ __name((query2) => !isArray(query2) && isObject(query2) && !isExpression(query2), "isLeaf");
const convertToExplicit = /* @__PURE__ */ __name((query2) => ({
  [LogicalOperator.AND]: Object.keys(query2).map((key) => ({
    [key]: query2[key]
  }))
}), "convertToExplicit");
function parse(query2, options2, { auto = true } = {}) {
  const next = /* @__PURE__ */ __name((query3) => {
    let keys2 = Object.keys(query3);
    const isQueryPath = isPath(query3);
    if (!isQueryPath && keys2.length > 1 && !isExpression(query3)) {
      return next(convertToExplicit(query3));
    }
    if (isLeaf(query3)) {
      const key = isQueryPath ? query3[KeyType.PATH] : keys2[0];
      const pattern = isQueryPath ? query3[KeyType.PATTERN] : query3[key];
      if (!isString(pattern)) {
        throw new Error(LOGICAL_SEARCH_INVALID_QUERY_FOR_KEY(key));
      }
      const obj = {
        keyId: createKeyId(key),
        pattern
      };
      if (auto) {
        obj.searcher = createSearcher(pattern, options2);
      }
      return obj;
    }
    let node2 = {
      children: [],
      operator: keys2[0]
    };
    keys2.forEach((key) => {
      const value = query3[key];
      if (isArray(value)) {
        value.forEach((item) => {
          node2.children.push(next(item));
        });
      }
    });
    return node2;
  }, "next");
  if (!isExpression(query2)) {
    query2 = convertToExplicit(query2);
  }
  return next(query2);
}
__name(parse, "parse");
function computeScore(results, { ignoreFieldNorm = Config.ignoreFieldNorm }) {
  results.forEach((result) => {
    let totalScore = 1;
    result.matches.forEach(({ key, norm: norm2, score }) => {
      const weight = key ? key.weight : null;
      totalScore *= Math.pow(
        score === 0 && weight ? Number.EPSILON : score,
        (weight || 1) * (ignoreFieldNorm ? 1 : norm2)
      );
    });
    result.score = totalScore;
  });
}
__name(computeScore, "computeScore");
function transformMatches(result, data) {
  const matches2 = result.matches;
  data.matches = [];
  if (!isDefined(matches2)) {
    return;
  }
  matches2.forEach((match2) => {
    if (!isDefined(match2.indices) || !match2.indices.length) {
      return;
    }
    const { indices, value } = match2;
    let obj = {
      indices,
      value
    };
    if (match2.key) {
      obj.key = match2.key.src;
    }
    if (match2.idx > -1) {
      obj.refIndex = match2.idx;
    }
    data.matches.push(obj);
  });
}
__name(transformMatches, "transformMatches");
function transformScore(result, data) {
  data.score = result.score;
}
__name(transformScore, "transformScore");
function format(results, docs, {
  includeMatches = Config.includeMatches,
  includeScore = Config.includeScore
} = {}) {
  const transformers = [];
  if (includeMatches) transformers.push(transformMatches);
  if (includeScore) transformers.push(transformScore);
  return results.map((result) => {
    const { idx } = result;
    const data = {
      item: docs[idx],
      refIndex: idx
    };
    if (transformers.length) {
      transformers.forEach((transformer) => {
        transformer(result, data);
      });
    }
    return data;
  });
}
__name(format, "format");
class Fuse {
  static {
    __name(this, "Fuse");
  }
  constructor(docs, options2 = {}, index2) {
    this.options = { ...Config, ...options2 };
    if (this.options.useExtendedSearch && false) {
      throw new Error(EXTENDED_SEARCH_UNAVAILABLE);
    }
    this._keyStore = new KeyStore(this.options.keys);
    this.setCollection(docs, index2);
  }
  setCollection(docs, index2) {
    this._docs = docs;
    if (index2 && !(index2 instanceof FuseIndex)) {
      throw new Error(INCORRECT_INDEX_TYPE);
    }
    this._myIndex = index2 || createIndex(this.options.keys, this._docs, {
      getFn: this.options.getFn,
      fieldNormWeight: this.options.fieldNormWeight
    });
  }
  add(doc2) {
    if (!isDefined(doc2)) {
      return;
    }
    this._docs.push(doc2);
    this._myIndex.add(doc2);
  }
  remove(predicate = () => false) {
    const results = [];
    for (let i2 = 0, len = this._docs.length; i2 < len; i2 += 1) {
      const doc2 = this._docs[i2];
      if (predicate(doc2, i2)) {
        this.removeAt(i2);
        i2 -= 1;
        len -= 1;
        results.push(doc2);
      }
    }
    return results;
  }
  removeAt(idx) {
    this._docs.splice(idx, 1);
    this._myIndex.removeAt(idx);
  }
  getIndex() {
    return this._myIndex;
  }
  search(query2, { limit: limit2 = -1 } = {}) {
    const {
      includeMatches,
      includeScore,
      shouldSort,
      sortFn,
      ignoreFieldNorm
    } = this.options;
    let results = isString(query2) ? isString(this._docs[0]) ? this._searchStringList(query2) : this._searchObjectList(query2) : this._searchLogical(query2);
    computeScore(results, { ignoreFieldNorm });
    if (shouldSort) {
      results.sort(sortFn);
    }
    if (isNumber(limit2) && limit2 > -1) {
      results = results.slice(0, limit2);
    }
    return format(results, this._docs, {
      includeMatches,
      includeScore
    });
  }
  _searchStringList(query2) {
    const searcher = createSearcher(query2, this.options);
    const { records } = this._myIndex;
    const results = [];
    records.forEach(({ v: text2, i: idx, n: norm2 }) => {
      if (!isDefined(text2)) {
        return;
      }
      const { isMatch, score, indices } = searcher.searchIn(text2);
      if (isMatch) {
        results.push({
          item: text2,
          idx,
          matches: [{ score, value: text2, norm: norm2, indices }]
        });
      }
    });
    return results;
  }
  _searchLogical(query2) {
    const expression = parse(query2, this.options);
    const evaluate = /* @__PURE__ */ __name((node2, item, idx) => {
      if (!node2.children) {
        const { keyId, searcher } = node2;
        const matches2 = this._findMatches({
          key: this._keyStore.get(keyId),
          value: this._myIndex.getValueForItemAtKeyId(item, keyId),
          searcher
        });
        if (matches2 && matches2.length) {
          return [
            {
              idx,
              item,
              matches: matches2
            }
          ];
        }
        return [];
      }
      const res = [];
      for (let i2 = 0, len = node2.children.length; i2 < len; i2 += 1) {
        const child2 = node2.children[i2];
        const result = evaluate(child2, item, idx);
        if (result.length) {
          res.push(...result);
        } else if (node2.operator === LogicalOperator.AND) {
          return [];
        }
      }
      return res;
    }, "evaluate");
    const records = this._myIndex.records;
    const resultMap = {};
    const results = [];
    records.forEach(({ $: item, i: idx }) => {
      if (isDefined(item)) {
        let expResults = evaluate(expression, item, idx);
        if (expResults.length) {
          if (!resultMap[idx]) {
            resultMap[idx] = { idx, item, matches: [] };
            results.push(resultMap[idx]);
          }
          expResults.forEach(({ matches: matches2 }) => {
            resultMap[idx].matches.push(...matches2);
          });
        }
      }
    });
    return results;
  }
  _searchObjectList(query2) {
    const searcher = createSearcher(query2, this.options);
    const { keys: keys2, records } = this._myIndex;
    const results = [];
    records.forEach(({ $: item, i: idx }) => {
      if (!isDefined(item)) {
        return;
      }
      let matches2 = [];
      keys2.forEach((key, keyIndex) => {
        matches2.push(
          ...this._findMatches({
            key,
            value: item[keyIndex],
            searcher
          })
        );
      });
      if (matches2.length) {
        results.push({
          idx,
          item,
          matches: matches2
        });
      }
    });
    return results;
  }
  _findMatches({ key, value, searcher }) {
    if (!isDefined(value)) {
      return [];
    }
    let matches2 = [];
    if (isArray(value)) {
      value.forEach(({ v: text2, i: idx, n: norm2 }) => {
        if (!isDefined(text2)) {
          return;
        }
        const { isMatch, score, indices } = searcher.searchIn(text2);
        if (isMatch) {
          matches2.push({
            score,
            key,
            value: text2,
            idx,
            norm: norm2,
            indices
          });
        }
      });
    } else {
      const { v: text2, n: norm2 } = value;
      const { isMatch, score, indices } = searcher.searchIn(text2);
      if (isMatch) {
        matches2.push({ score, key, value: text2, norm: norm2, indices });
      }
    }
    return matches2;
  }
}
Fuse.version = "7.0.0";
Fuse.createIndex = createIndex;
Fuse.parseIndex = parseIndex;
Fuse.config = Config;
{
  Fuse.parseQuery = parse;
}
{
  register$1(ExtendedSearch);
}
class FuseFilter {
  static {
    __name(this, "FuseFilter");
  }
  fuseSearch;
  /** The unique identifier for the filter. */
  id;
  /** The name of the filter for display purposes. */
  name;
  /** The sequence of characters to invoke the filter. */
  invokeSequence;
  /** A function that returns the options for the filter. */
  getItemOptions;
  constructor(data, options2) {
    this.id = options2.id;
    this.name = options2.name;
    this.invokeSequence = options2.invokeSequence;
    this.getItemOptions = options2.getItemOptions;
    this.fuseSearch = new FuseSearch(this.getAllNodeOptions(data), {
      fuseOptions: options2.fuseOptions
    });
  }
  getAllNodeOptions(data) {
    const options2 = /* @__PURE__ */ new Set();
    for (const item of data) {
      for (const option of this.getItemOptions(item)) {
        options2.add(option);
      }
    }
    return Array.from(options2);
  }
  matches(item, value, extraOptions = {}) {
    const { wildcard } = extraOptions;
    if (wildcard && value === wildcard) {
      return true;
    }
    const options2 = this.getItemOptions(item);
    return options2.includes(value) || !!wildcard && options2.some((option) => option === wildcard);
  }
}
function isFuseSearchable(item) {
  return "postProcessSearchScores" in item;
}
__name(isFuseSearchable, "isFuseSearchable");
class FuseSearch {
  static {
    __name(this, "FuseSearch");
  }
  fuse;
  keys;
  data;
  advancedScoring;
  constructor(data, options2) {
    const { fuseOptions, createIndex: createIndex2 = true, advancedScoring = false } = options2;
    this.data = data;
    this.keys = fuseOptions?.keys ?? [];
    this.advancedScoring = advancedScoring;
    const index2 = createIndex2 && this.keys.length ? Fuse.createIndex(this.keys, data) : void 0;
    this.fuse = new Fuse(data, fuseOptions, index2);
  }
  search(query2, options2) {
    const fuseResult = !query2 ? this.data.map((x2) => ({ item: x2, score: 0 })) : this.fuse.search(query2, options2);
    if (!this.advancedScoring) {
      return fuseResult.map((x2) => x2.item);
    }
    const aux = fuseResult.map((x2) => ({
      item: x2.item,
      scores: this.calcAuxScores(
        query2.toLocaleLowerCase(),
        x2.item,
        x2.score ?? 0
      )
    })).sort((a2, b2) => this.compareAux(a2.scores, b2.scores));
    return aux.map((x2) => x2.item);
  }
  calcAuxScores(query2, entry, score) {
    let values = [];
    if (typeof entry === "string") {
      values = [entry];
    } else if (typeof entry === "object" && entry !== null) {
      values = this.keys.map((x2) => entry[x2]).filter((x2) => typeof x2 === "string");
    }
    const scores = values.map((x2) => this.calcAuxSingle(query2, x2, score));
    let result = scores.sort(this.compareAux)[0];
    const deprecated = values.some(
      (x2) => x2.toLocaleLowerCase().includes("deprecated")
    );
    result[0] += deprecated && result[0] !== 0 ? 5 : 0;
    if (isFuseSearchable(entry)) {
      result = entry.postProcessSearchScores(result);
    }
    return result;
  }
  calcAuxSingle(query2, item, score) {
    const itemWords = item.split(/ |\b|(?<=[a-z])(?=[A-Z])|(?=[A-Z][a-z])/).map((x2) => x2.toLocaleLowerCase());
    const queryParts = query2.split(" ");
    item = item.toLocaleLowerCase();
    let main = 9;
    let aux1 = 0;
    let aux2 = 0;
    if (item == query2) {
      main = 0;
    } else if (item.startsWith(query2)) {
      main = 1;
      aux2 = item.length;
    } else if (itemWords.includes(query2)) {
      main = 2;
      aux1 = item.indexOf(query2) + item.length * 0.5;
      aux2 = item.length;
    } else if (item.includes(query2)) {
      main = 3;
      aux1 = item.indexOf(query2) + item.length * 0.5;
      aux2 = item.length;
    } else if (queryParts.every((x2) => itemWords.includes(x2))) {
      const indexes = queryParts.map((x2) => itemWords.indexOf(x2));
      const min = Math.min(...indexes);
      const max = Math.max(...indexes);
      main = 4;
      aux1 = max - min + max * 0.5 + item.length * 0.5;
      aux2 = item.length;
    } else if (queryParts.every((x2) => item.includes(x2))) {
      const min = Math.min(...queryParts.map((x2) => item.indexOf(x2)));
      const max = Math.max(...queryParts.map((x2) => item.indexOf(x2) + x2.length));
      main = 5;
      aux1 = max - min + max * 0.5 + item.length * 0.5;
      aux2 = item.length;
    }
    const lengthPenalty = 0.2 * (1 - Math.min(item.length, query2.length) / Math.max(item.length, query2.length));
    return [main, aux1, aux2, score + lengthPenalty];
  }
  compareAux(a2, b2) {
    for (let i2 = 0; i2 < Math.min(a2.length, b2.length); i2++) {
      if (a2[i2] !== b2[i2]) {
        return a2[i2] - b2[i2];
      }
    }
    return a2.length - b2.length;
  }
}
class NodeSearchService {
  static {
    __name(this, "NodeSearchService");
  }
  nodeFuseSearch;
  inputTypeFilter;
  outputTypeFilter;
  nodeCategoryFilter;
  nodeSourceFilter;
  constructor(data) {
    this.nodeFuseSearch = new FuseSearch(data, {
      fuseOptions: {
        keys: ["name", "display_name"],
        includeScore: true,
        threshold: 0.3,
        shouldSort: false,
        useExtendedSearch: true
      },
      createIndex: true,
      advancedScoring: true
    });
    const fuseOptions = {
      includeScore: true,
      threshold: 0.3,
      shouldSort: true
    };
    this.inputTypeFilter = new FuseFilter(data, {
      id: "input",
      name: "Input Type",
      invokeSequence: "i",
      getItemOptions: /* @__PURE__ */ __name((node2) => Object.values(node2.inputs).map((input) => input.type), "getItemOptions"),
      fuseOptions
    });
    this.outputTypeFilter = new FuseFilter(data, {
      id: "output",
      name: "Output Type",
      invokeSequence: "o",
      getItemOptions: /* @__PURE__ */ __name((node2) => node2.outputs.map((output) => output.type), "getItemOptions"),
      fuseOptions
    });
    this.nodeCategoryFilter = new FuseFilter(data, {
      id: "category",
      name: "Category",
      invokeSequence: "c",
      getItemOptions: /* @__PURE__ */ __name((node2) => [node2.category], "getItemOptions"),
      fuseOptions
    });
    this.nodeSourceFilter = new FuseFilter(data, {
      id: "source",
      name: "Source",
      invokeSequence: "s",
      getItemOptions: /* @__PURE__ */ __name((node2) => [node2.nodeSource.displayText], "getItemOptions"),
      fuseOptions
    });
  }
  searchNode(query2, filters = [], options2, extraOptions = {}) {
    const { matchWildcards = true } = extraOptions;
    const wildcard = matchWildcards ? "*" : void 0;
    const matchedNodes = this.nodeFuseSearch.search(query2);
    const results = matchedNodes.filter((node2) => {
      return filters.every((filterAndValue) => {
        const { filterDef, value } = filterAndValue;
        return filterDef.matches(node2, value, { wildcard });
      });
    });
    return options2?.limit ? results.slice(0, options2.limit) : results;
  }
  get nodeFilters() {
    return [
      this.inputTypeFilter,
      this.outputTypeFilter,
      this.nodeCategoryFilter,
      this.nodeSourceFilter
    ];
  }
}
var NodeSourceType = /* @__PURE__ */ ((NodeSourceType2) => {
  NodeSourceType2["Core"] = "core";
  NodeSourceType2["CustomNodes"] = "custom_nodes";
  NodeSourceType2["Unknown"] = "unknown";
  return NodeSourceType2;
})(NodeSourceType || {});
const UNKNOWN_NODE_SOURCE = {
  type: "unknown",
  className: "comfy-unknown",
  displayText: "Unknown",
  badgeText: "?"
};
const shortenNodeName = /* @__PURE__ */ __name((name2) => {
  return name2.replace(/^(ComfyUI-|ComfyUI_|Comfy-|Comfy_)/, "").replace(/(-ComfyUI|_ComfyUI|-Comfy|_Comfy)$/, "");
}, "shortenNodeName");
const getNodeSource = /* @__PURE__ */ __name((python_module) => {
  if (!python_module) {
    return UNKNOWN_NODE_SOURCE;
  }
  const modules = python_module.split(".");
  if (["nodes", "comfy_extras", "comfy_api_nodes"].includes(modules[0])) {
    return {
      type: "core",
      className: "comfy-core",
      displayText: "Comfy Core",
      badgeText: "🦊"
    };
  } else if (modules[0] === "custom_nodes") {
    const moduleName = modules[1];
    const customNodeName = moduleName.split("@")[0];
    const displayName = shortenNodeName(customNodeName);
    return {
      type: "custom_nodes",
      className: "comfy-custom-nodes",
      displayText: displayName,
      badgeText: displayName
    };
  } else {
    return UNKNOWN_NODE_SOURCE;
  }
}, "getNodeSource");
var NodeBadgeMode = /* @__PURE__ */ ((NodeBadgeMode2) => {
  NodeBadgeMode2["None"] = "None";
  NodeBadgeMode2["ShowAll"] = "Show all";
  NodeBadgeMode2["HideBuiltIn"] = "Hide built-in";
  return NodeBadgeMode2;
})(NodeBadgeMode || {});
class ComfyNodeDefImpl {
  static {
    __name(this, "ComfyNodeDefImpl");
  }
  // ComfyNodeDef fields (V1)
  name;
  display_name;
  /**
   * Category is not marked as readonly as the bookmark system
   * needs to write to it to assign a node to a custom folder.
   */
  category;
  python_module;
  description;
  deprecated;
  experimental;
  output_node;
  api_node;
  /**
   * @deprecated Use `inputs` instead
   */
  input;
  /**
   * @deprecated Use `outputs` instead
   */
  output;
  /**
   * @deprecated Use `outputs[n].is_list` instead
   */
  output_is_list;
  /**
   * @deprecated Use `outputs[n].name` instead
   */
  output_name;
  /**
   * @deprecated Use `outputs[n].tooltip` instead
   */
  output_tooltips;
  // V2 fields
  inputs;
  outputs;
  hidden;
  // ComfyNodeDefImpl fields
  nodeSource;
  /**
   * @internal
   * Migrate default input options to forceInput.
   */
  static #migrateDefaultInput(nodeDef) {
    const def = _.cloneDeep(nodeDef);
    def.input ??= {};
    for (const [name2, spec] of Object.entries(def.input.required ?? {})) {
      const inputOptions = spec[1];
      if (inputOptions && inputOptions.defaultInput) {
        console.warn(
          `Use of defaultInput on required input ${nodeDef.python_module}:${nodeDef.name}:${name2} is deprecated. Please drop the defaultInput option.`
        );
      }
    }
    for (const [name2, spec] of Object.entries(def.input.optional ?? {})) {
      const inputOptions = spec[1];
      if (inputOptions && inputOptions.defaultInput) {
        console.warn(
          `Use of defaultInput on optional input ${nodeDef.python_module}:${nodeDef.name}:${name2} is deprecated. Please use forceInput instead.`
        );
        inputOptions.forceInput = true;
      }
    }
    return def;
  }
  constructor(def) {
    const obj = ComfyNodeDefImpl.#migrateDefaultInput(def);
    Object.assign(this, obj);
    this.name = obj.name;
    this.display_name = obj.display_name;
    this.category = obj.category;
    this.python_module = obj.python_module;
    this.description = obj.description;
    this.deprecated = obj.deprecated ?? obj.category === "";
    this.experimental = obj.experimental ?? obj.category.startsWith("_for_testing");
    this.output_node = obj.output_node;
    this.api_node = !!obj.api_node;
    this.input = obj.input ?? {};
    this.output = obj.output ?? [];
    this.output_is_list = obj.output_is_list;
    this.output_name = obj.output_name;
    this.output_tooltips = obj.output_tooltips;
    const defV2 = transformNodeDefV1ToV2(obj);
    this.inputs = defV2.inputs;
    this.outputs = defV2.outputs;
    this.hidden = defV2.hidden;
    this.nodeSource = getNodeSource(obj.python_module);
  }
  get nodePath() {
    return (this.category ? this.category + "/" : "") + this.name;
  }
  get isDummyFolder() {
    return this.name === "";
  }
  postProcessSearchScores(scores) {
    const nodeFrequencyStore = useNodeFrequencyStore();
    const nodeFrequency = nodeFrequencyStore.getNodeFrequencyByName(this.name);
    return [scores[0], -nodeFrequency, ...scores.slice(1)];
  }
  get isCoreNode() {
    return this.nodeSource.type === NodeSourceType.Core;
  }
  get nodeLifeCycleBadgeText() {
    if (this.deprecated) return "[DEPR]";
    if (this.experimental) return "[BETA]";
    return "";
  }
}
const SYSTEM_NODE_DEFS = {
  PrimitiveNode: {
    name: "PrimitiveNode",
    display_name: "Primitive",
    category: "utils",
    input: { required: {}, optional: {} },
    output: ["*"],
    output_name: ["connect to widget input"],
    output_is_list: [false],
    output_node: false,
    python_module: "nodes",
    description: "Primitive values like numbers, strings, and booleans."
  },
  Reroute: {
    name: "Reroute",
    display_name: "Reroute",
    category: "utils",
    input: { required: { "": ["*", {}] }, optional: {} },
    output: ["*"],
    output_name: [""],
    output_is_list: [false],
    output_node: false,
    python_module: "nodes",
    description: "Reroute the connection to another node."
  },
  Note: {
    name: "Note",
    display_name: "Note",
    category: "utils",
    input: { required: {}, optional: {} },
    output: [],
    output_name: [],
    output_is_list: [],
    output_node: false,
    python_module: "nodes",
    description: "Node that add notes to your project"
  },
  MarkdownNote: {
    name: "MarkdownNote",
    display_name: "Markdown Note",
    category: "utils",
    input: { required: {}, optional: {} },
    output: [],
    output_name: [],
    output_is_list: [],
    output_node: false,
    python_module: "nodes",
    description: "Node that add notes to your project. Reformats text as markdown."
  }
};
function buildNodeDefTree(nodeDefs) {
  return buildTree$1(
    nodeDefs,
    (nodeDef) => nodeDef.nodePath.split("/")
  );
}
__name(buildNodeDefTree, "buildNodeDefTree");
function createDummyFolderNodeDef(folderPath) {
  return new ComfyNodeDefImpl({
    name: "",
    display_name: "",
    category: folderPath.endsWith("/") ? folderPath.slice(0, -1) : folderPath,
    python_module: "nodes",
    description: "Dummy Folder Node (User should never see this string)",
    input: {},
    output: [],
    output_name: [],
    output_is_list: [],
    output_node: false
  });
}
__name(createDummyFolderNodeDef, "createDummyFolderNodeDef");
const useNodeDefStore = /* @__PURE__ */ defineStore("nodeDef", () => {
  const nodeDefsByName = ref$3({});
  const nodeDefsByDisplayName = ref$3({});
  const showDeprecated = ref$3(false);
  const showExperimental = ref$3(false);
  const nodeDefs = computed(() => Object.values(nodeDefsByName.value));
  const nodeDataTypes = computed(() => {
    const types = /* @__PURE__ */ new Set();
    for (const nodeDef of nodeDefs.value) {
      for (const input of Object.values(nodeDef.inputs)) {
        types.add(input.type);
      }
      for (const output of nodeDef.outputs) {
        types.add(output.type);
      }
    }
    return types;
  });
  const visibleNodeDefs = computed(
    () => nodeDefs.value.filter(
      (nodeDef) => (showDeprecated.value || !nodeDef.deprecated) && (showExperimental.value || !nodeDef.experimental)
    )
  );
  const nodeSearchService = computed(
    () => new NodeSearchService(visibleNodeDefs.value)
  );
  const nodeTree = computed(() => buildNodeDefTree(visibleNodeDefs.value));
  function updateNodeDefs(nodeDefs2) {
    const newNodeDefsByName = {};
    const newNodeDefsByDisplayName = {};
    for (const nodeDef of nodeDefs2) {
      const nodeDefImpl = nodeDef instanceof ComfyNodeDefImpl ? nodeDef : new ComfyNodeDefImpl(nodeDef);
      newNodeDefsByName[nodeDef.name] = nodeDefImpl;
      newNodeDefsByDisplayName[nodeDef.display_name] = nodeDefImpl;
    }
    nodeDefsByName.value = newNodeDefsByName;
    nodeDefsByDisplayName.value = newNodeDefsByDisplayName;
  }
  __name(updateNodeDefs, "updateNodeDefs");
  function addNodeDef(nodeDef) {
    const nodeDefImpl = new ComfyNodeDefImpl(nodeDef);
    nodeDefsByName.value[nodeDef.name] = nodeDefImpl;
    nodeDefsByDisplayName.value[nodeDef.display_name] = nodeDefImpl;
  }
  __name(addNodeDef, "addNodeDef");
  function fromLGraphNode(node2) {
    return nodeDefsByName.value[node2.constructor?.nodeData?.name] ?? null;
  }
  __name(fromLGraphNode, "fromLGraphNode");
  return {
    nodeDefsByName,
    nodeDefsByDisplayName,
    showDeprecated,
    showExperimental,
    nodeDefs,
    nodeDataTypes,
    visibleNodeDefs,
    nodeSearchService,
    nodeTree,
    updateNodeDefs,
    addNodeDef,
    fromLGraphNode
  };
});
const useNodeFrequencyStore = /* @__PURE__ */ defineStore("nodeFrequency", () => {
  const topNodeDefLimit = ref$3(64);
  const nodeFrequencyLookup = ref$3({});
  const nodeNamesByFrequency = computed(
    () => Object.keys(nodeFrequencyLookup.value)
  );
  const isLoaded = ref$3(false);
  const loadNodeFrequencies = /* @__PURE__ */ __name(async () => {
    if (!isLoaded.value) {
      try {
        const response = await axios.get("assets/sorted-custom-node-map.json");
        nodeFrequencyLookup.value = response.data;
        isLoaded.value = true;
      } catch (error2) {
        console.error("Error loading node frequencies:", error2);
      }
    }
  }, "loadNodeFrequencies");
  const getNodeFrequency = /* @__PURE__ */ __name((nodeDef) => {
    return getNodeFrequencyByName(nodeDef.name);
  }, "getNodeFrequency");
  const getNodeFrequencyByName = /* @__PURE__ */ __name((nodeName) => {
    return nodeFrequencyLookup.value[nodeName] ?? 0;
  }, "getNodeFrequencyByName");
  const nodeDefStore = useNodeDefStore();
  const topNodeDefs = computed(() => {
    return nodeNamesByFrequency.value.map((nodeName) => nodeDefStore.nodeDefsByName[nodeName]).filter((nodeDef) => nodeDef !== void 0).slice(0, topNodeDefLimit.value);
  });
  return {
    nodeNamesByFrequency,
    topNodeDefs,
    isLoaded,
    loadNodeFrequencies,
    getNodeFrequency,
    getNodeFrequencyByName
  };
});
const CORE_NODES_PACK_NAME = "comfy-core";
const useWorkflowPacks = /* @__PURE__ */ __name((options2 = {}) => {
  const nodeDefStore = useNodeDefStore();
  const systemStatsStore = useSystemStatsStore();
  const { search: search2 } = useComfyRegistryStore();
  const workflowPacks = ref$3([]);
  const getWorkflowNodePackId = /* @__PURE__ */ __name((node2) => {
    if (typeof node2.properties?.cnr_id === "string") {
      return node2.properties.cnr_id;
    }
    if (typeof node2.properties?.aux_id === "string") {
      return node2.properties.aux_id;
    }
    return void 0;
  }, "getWorkflowNodePackId");
  const cleanVersionString = /* @__PURE__ */ __name((version2) => version2.replace(/^v/, "").trim(), "cleanVersionString");
  const inferPack = /* @__PURE__ */ __name(async (node2) => {
    const nodeName = node2.type;
    const nodeDef = nodeDefStore.nodeDefsByName[nodeName];
    if (nodeDef?.nodeSource.type === "core") {
      if (!systemStatsStore.systemStats) {
        await systemStatsStore.fetchSystemStats();
      }
      return {
        id: CORE_NODES_PACK_NAME,
        version: systemStatsStore.systemStats?.system?.comfyui_version ?? SelectedVersion.NIGHTLY
      };
    }
    const searchResult = await search2.call({
      comfy_node_search: nodeName,
      limit: 1
    });
    if (searchResult?.nodes?.length) {
      const pack = searchResult.nodes[0];
      return {
        id: pack.id,
        version: pack.latest_version?.version ?? SelectedVersion.NIGHTLY
      };
    }
  }, "inferPack");
  const workflowNodeToPack = /* @__PURE__ */ __name(async (node2) => {
    const packId = getWorkflowNodePackId(node2);
    if (!packId) return inferPack(node2);
    if (packId === CORE_NODES_PACK_NAME) return void 0;
    const version2 = typeof node2.properties.ver === "string" ? cleanVersionString(node2.properties.ver) : void 0;
    return {
      id: packId,
      version: version2
    };
  }, "workflowNodeToPack");
  const getWorkflowPacks = /* @__PURE__ */ __name(async () => {
    if (!app$1.graph?.nodes?.length) return [];
    const packs = await Promise.all(app$1.graph.nodes.map(workflowNodeToPack));
    workflowPacks.value = packs.filter((pack) => pack !== void 0);
  }, "getWorkflowPacks");
  const packsToUniqueIds = /* @__PURE__ */ __name((packs) => packs.reduce((acc, pack) => {
    if (pack?.id) acc.add(pack.id);
    return acc;
  }, /* @__PURE__ */ new Set()), "packsToUniqueIds");
  const workflowPacksIds = computed(
    () => Array.from(packsToUniqueIds(workflowPacks.value))
  );
  const { startFetch, cleanup, error: error2, isLoading, nodePacks, isReady } = useNodePacks(workflowPacksIds, options2);
  const isIdInWorkflow = /* @__PURE__ */ __name((packId) => workflowPacksIds.value.includes(packId), "isIdInWorkflow");
  const filterWorkflowPack = /* @__PURE__ */ __name((packs) => packs.filter((pack) => !!pack.id && isIdInWorkflow(pack.id)), "filterWorkflowPack");
  onUnmounted(() => {
    cleanup();
  });
  return {
    error: error2,
    isLoading,
    isReady,
    workflowPacks: nodePacks,
    startFetchWorkflowPacks: /* @__PURE__ */ __name(async () => {
      await getWorkflowPacks();
      await startFetch();
    }, "startFetchWorkflowPacks"),
    filterWorkflowPack
  };
}, "useWorkflowPacks");
function m() {
  function r2(t2) {
    return new Promise((s2) => {
      let e2 = new XMLHttpRequest();
      e2.open(t2.method, t2.url, true), Object.keys(t2.headers).forEach((n2) => e2.setRequestHeader(n2, t2.headers[n2]));
      let i2 = /* @__PURE__ */ __name((n2, a2) => setTimeout(() => {
        e2.abort(), s2({ status: 0, content: a2, isTimedOut: true });
      }, n2), "i"), u2 = i2(t2.connectTimeout, "Connection timeout"), o2;
      e2.onreadystatechange = () => {
        e2.readyState > e2.OPENED && o2 === void 0 && (clearTimeout(u2), o2 = i2(t2.responseTimeout, "Socket timeout"));
      }, e2.onerror = () => {
        e2.status === 0 && (clearTimeout(u2), clearTimeout(o2), s2({ content: e2.responseText || "Network request failed", status: e2.status, isTimedOut: false }));
      }, e2.onload = () => {
        clearTimeout(u2), clearTimeout(o2), s2({ content: e2.responseText, status: e2.status, isTimedOut: false });
      }, e2.send(t2.data);
    });
  }
  __name(r2, "r");
  return { send: r2 };
}
__name(m, "m");
function createBrowserLocalStorageCache(options2) {
  let storage;
  const namespaceKey = `algolia-client-js-${options2.key}`;
  function getStorage2() {
    if (storage === void 0) {
      storage = options2.localStorage || window.localStorage;
    }
    return storage;
  }
  __name(getStorage2, "getStorage");
  function getNamespace() {
    return JSON.parse(getStorage2().getItem(namespaceKey) || "{}");
  }
  __name(getNamespace, "getNamespace");
  function setNamespace(namespace) {
    getStorage2().setItem(namespaceKey, JSON.stringify(namespace));
  }
  __name(setNamespace, "setNamespace");
  function removeOutdatedCacheItems() {
    const timeToLive = options2.timeToLive ? options2.timeToLive * 1e3 : null;
    const namespace = getNamespace();
    const filteredNamespaceWithoutOldFormattedCacheItems = Object.fromEntries(
      Object.entries(namespace).filter(([, cacheItem]) => {
        return cacheItem.timestamp !== void 0;
      })
    );
    setNamespace(filteredNamespaceWithoutOldFormattedCacheItems);
    if (!timeToLive) {
      return;
    }
    const filteredNamespaceWithoutExpiredItems = Object.fromEntries(
      Object.entries(filteredNamespaceWithoutOldFormattedCacheItems).filter(([, cacheItem]) => {
        const currentTimestamp = (/* @__PURE__ */ new Date()).getTime();
        const isExpired2 = cacheItem.timestamp + timeToLive < currentTimestamp;
        return !isExpired2;
      })
    );
    setNamespace(filteredNamespaceWithoutExpiredItems);
  }
  __name(removeOutdatedCacheItems, "removeOutdatedCacheItems");
  return {
    get(key, defaultValue, events2 = {
      miss: /* @__PURE__ */ __name(() => Promise.resolve(), "miss")
    }) {
      return Promise.resolve().then(() => {
        removeOutdatedCacheItems();
        return getNamespace()[JSON.stringify(key)];
      }).then((value) => {
        return Promise.all([value ? value.value : defaultValue(), value !== void 0]);
      }).then(([value, exists]) => {
        return Promise.all([value, exists || events2.miss(value)]);
      }).then(([value]) => value);
    },
    set(key, value) {
      return Promise.resolve().then(() => {
        const namespace = getNamespace();
        namespace[JSON.stringify(key)] = {
          timestamp: (/* @__PURE__ */ new Date()).getTime(),
          value
        };
        getStorage2().setItem(namespaceKey, JSON.stringify(namespace));
        return value;
      });
    },
    delete(key) {
      return Promise.resolve().then(() => {
        const namespace = getNamespace();
        delete namespace[JSON.stringify(key)];
        getStorage2().setItem(namespaceKey, JSON.stringify(namespace));
      });
    },
    clear() {
      return Promise.resolve().then(() => {
        getStorage2().removeItem(namespaceKey);
      });
    }
  };
}
__name(createBrowserLocalStorageCache, "createBrowserLocalStorageCache");
function createNullCache() {
  return {
    get(_key, defaultValue, events2 = {
      miss: /* @__PURE__ */ __name(() => Promise.resolve(), "miss")
    }) {
      const value = defaultValue();
      return value.then((result) => Promise.all([result, events2.miss(result)])).then(([result]) => result);
    },
    set(_key, value) {
      return Promise.resolve(value);
    },
    delete(_key) {
      return Promise.resolve();
    },
    clear() {
      return Promise.resolve();
    }
  };
}
__name(createNullCache, "createNullCache");
function createFallbackableCache(options2) {
  const caches = [...options2.caches];
  const current = caches.shift();
  if (current === void 0) {
    return createNullCache();
  }
  return {
    get(key, defaultValue, events2 = {
      miss: /* @__PURE__ */ __name(() => Promise.resolve(), "miss")
    }) {
      return current.get(key, defaultValue, events2).catch(() => {
        return createFallbackableCache({ caches }).get(key, defaultValue, events2);
      });
    },
    set(key, value) {
      return current.set(key, value).catch(() => {
        return createFallbackableCache({ caches }).set(key, value);
      });
    },
    delete(key) {
      return current.delete(key).catch(() => {
        return createFallbackableCache({ caches }).delete(key);
      });
    },
    clear() {
      return current.clear().catch(() => {
        return createFallbackableCache({ caches }).clear();
      });
    }
  };
}
__name(createFallbackableCache, "createFallbackableCache");
function createMemoryCache(options2 = { serializable: true }) {
  let cache = {};
  return {
    get(key, defaultValue, events2 = {
      miss: /* @__PURE__ */ __name(() => Promise.resolve(), "miss")
    }) {
      const keyAsString = JSON.stringify(key);
      if (keyAsString in cache) {
        return Promise.resolve(options2.serializable ? JSON.parse(cache[keyAsString]) : cache[keyAsString]);
      }
      const promise = defaultValue();
      return promise.then((value) => events2.miss(value)).then(() => promise);
    },
    set(key, value) {
      cache[JSON.stringify(key)] = options2.serializable ? JSON.stringify(value) : value;
      return Promise.resolve(value);
    },
    delete(key) {
      delete cache[JSON.stringify(key)];
      return Promise.resolve();
    },
    clear() {
      cache = {};
      return Promise.resolve();
    }
  };
}
__name(createMemoryCache, "createMemoryCache");
var DEFAULT_CONNECT_TIMEOUT_BROWSER = 1e3;
var DEFAULT_READ_TIMEOUT_BROWSER = 2e3;
var DEFAULT_WRITE_TIMEOUT_BROWSER = 3e4;
var DEFAULT_CONNECT_TIMEOUT_NODE = 2e3;
var DEFAULT_READ_TIMEOUT_NODE = 5e3;
var DEFAULT_WRITE_TIMEOUT_NODE = 3e4;
function createAlgoliaAgent(version2) {
  const algoliaAgent = {
    value: `Algolia for JavaScript (${version2})`,
    add(options2) {
      const addedAlgoliaAgent = `; ${options2.segment}${options2.version !== void 0 ? ` (${options2.version})` : ""}`;
      if (algoliaAgent.value.indexOf(addedAlgoliaAgent) === -1) {
        algoliaAgent.value = `${algoliaAgent.value}${addedAlgoliaAgent}`;
      }
      return algoliaAgent;
    }
  };
  return algoliaAgent;
}
__name(createAlgoliaAgent, "createAlgoliaAgent");
function createAuth(appId, apiKey, authMode = "WithinHeaders") {
  const credentials = {
    "x-algolia-api-key": apiKey,
    "x-algolia-application-id": appId
  };
  return {
    headers() {
      return authMode === "WithinHeaders" ? credentials : {};
    },
    queryParameters() {
      return authMode === "WithinQueryParameters" ? credentials : {};
    }
  };
}
__name(createAuth, "createAuth");
function createIterablePromise({
  func,
  validate,
  aggregator,
  error: error2,
  timeout = /* @__PURE__ */ __name(() => 0, "timeout")
}) {
  const retry = /* @__PURE__ */ __name((previousResponse) => {
    return new Promise((resolve2, reject) => {
      func(previousResponse).then(async (response) => {
        if (aggregator) {
          await aggregator(response);
        }
        if (await validate(response)) {
          return resolve2(response);
        }
        if (error2 && await error2.validate(response)) {
          return reject(new Error(await error2.message(response)));
        }
        return setTimeout(
          () => {
            retry(response).then(resolve2).catch(reject);
          },
          await timeout()
        );
      }).catch((err) => {
        reject(err);
      });
    });
  }, "retry");
  return retry();
}
__name(createIterablePromise, "createIterablePromise");
function getAlgoliaAgent({ algoliaAgents, client, version: version2 }) {
  const defaultAlgoliaAgent = createAlgoliaAgent(version2).add({
    segment: client,
    version: version2
  });
  algoliaAgents.forEach((algoliaAgent) => defaultAlgoliaAgent.add(algoliaAgent));
  return defaultAlgoliaAgent;
}
__name(getAlgoliaAgent, "getAlgoliaAgent");
function createNullLogger() {
  return {
    debug(_message, _args) {
      return Promise.resolve();
    },
    info(_message, _args) {
      return Promise.resolve();
    },
    error(_message, _args) {
      return Promise.resolve();
    }
  };
}
__name(createNullLogger, "createNullLogger");
var EXPIRATION_DELAY = 2 * 60 * 1e3;
function createStatefulHost(host, status = "up") {
  const lastUpdate = Date.now();
  function isUp() {
    return status === "up" || Date.now() - lastUpdate > EXPIRATION_DELAY;
  }
  __name(isUp, "isUp");
  function isTimedOut() {
    return status === "timed out" && Date.now() - lastUpdate <= EXPIRATION_DELAY;
  }
  __name(isTimedOut, "isTimedOut");
  return { ...host, status, lastUpdate, isUp, isTimedOut };
}
__name(createStatefulHost, "createStatefulHost");
var AlgoliaError = class extends Error {
  static {
    __name(this, "AlgoliaError");
  }
  name = "AlgoliaError";
  constructor(message, name2) {
    super(message);
    if (name2) {
      this.name = name2;
    }
  }
};
var ErrorWithStackTrace = class extends AlgoliaError {
  static {
    __name(this, "ErrorWithStackTrace");
  }
  stackTrace;
  constructor(message, stackTrace, name2) {
    super(message, name2);
    this.stackTrace = stackTrace;
  }
};
var RetryError = class extends ErrorWithStackTrace {
  static {
    __name(this, "RetryError");
  }
  constructor(stackTrace) {
    super(
      "Unreachable hosts - your application id may be incorrect. If the error persists, please reach out to the Algolia Support team: https://alg.li/support.",
      stackTrace,
      "RetryError"
    );
  }
};
var ApiError = class extends ErrorWithStackTrace {
  static {
    __name(this, "ApiError");
  }
  status;
  constructor(message, status, stackTrace, name2 = "ApiError") {
    super(message, stackTrace, name2);
    this.status = status;
  }
};
var DeserializationError = class extends AlgoliaError {
  static {
    __name(this, "DeserializationError");
  }
  response;
  constructor(message, response) {
    super(message, "DeserializationError");
    this.response = response;
  }
};
var DetailedApiError = class extends ApiError {
  static {
    __name(this, "DetailedApiError");
  }
  error;
  constructor(message, status, error2, stackTrace) {
    super(message, status, stackTrace, "DetailedApiError");
    this.error = error2;
  }
};
function shuffle(array) {
  const shuffledArray = array;
  for (let c2 = array.length - 1; c2 > 0; c2--) {
    const b2 = Math.floor(Math.random() * (c2 + 1));
    const a2 = array[c2];
    shuffledArray[c2] = array[b2];
    shuffledArray[b2] = a2;
  }
  return shuffledArray;
}
__name(shuffle, "shuffle");
function serializeUrl(host, path, queryParameters) {
  const queryParametersAsString = serializeQueryParameters(queryParameters);
  let url = `${host.protocol}://${host.url}${host.port ? `:${host.port}` : ""}/${path.charAt(0) === "/" ? path.substring(1) : path}`;
  if (queryParametersAsString.length) {
    url += `?${queryParametersAsString}`;
  }
  return url;
}
__name(serializeUrl, "serializeUrl");
function serializeQueryParameters(parameters) {
  return Object.keys(parameters).filter((key) => parameters[key] !== void 0).sort().map(
    (key) => `${key}=${encodeURIComponent(
      Object.prototype.toString.call(parameters[key]) === "[object Array]" ? parameters[key].join(",") : parameters[key]
    ).replace(/\+/g, "%20")}`
  ).join("&");
}
__name(serializeQueryParameters, "serializeQueryParameters");
function serializeData(request, requestOptions) {
  if (request.method === "GET" || request.data === void 0 && requestOptions.data === void 0) {
    return void 0;
  }
  const data = Array.isArray(request.data) ? request.data : { ...request.data, ...requestOptions.data };
  return JSON.stringify(data);
}
__name(serializeData, "serializeData");
function serializeHeaders(baseHeaders, requestHeaders, requestOptionsHeaders) {
  const headers = {
    Accept: "application/json",
    ...baseHeaders,
    ...requestHeaders,
    ...requestOptionsHeaders
  };
  const serializedHeaders = {};
  Object.keys(headers).forEach((header) => {
    const value = headers[header];
    serializedHeaders[header.toLowerCase()] = value;
  });
  return serializedHeaders;
}
__name(serializeHeaders, "serializeHeaders");
function deserializeSuccess(response) {
  try {
    return JSON.parse(response.content);
  } catch (e2) {
    throw new DeserializationError(e2.message, response);
  }
}
__name(deserializeSuccess, "deserializeSuccess");
function deserializeFailure({ content, status }, stackFrame) {
  try {
    const parsed = JSON.parse(content);
    if ("error" in parsed) {
      return new DetailedApiError(parsed.message, status, parsed.error, stackFrame);
    }
    return new ApiError(parsed.message, status, stackFrame);
  } catch {
  }
  return new ApiError(content, status, stackFrame);
}
__name(deserializeFailure, "deserializeFailure");
function isNetworkError({ isTimedOut, status }) {
  return !isTimedOut && ~~status === 0;
}
__name(isNetworkError, "isNetworkError");
function isRetryable({ isTimedOut, status }) {
  return isTimedOut || isNetworkError({ isTimedOut, status }) || ~~(status / 100) !== 2 && ~~(status / 100) !== 4;
}
__name(isRetryable, "isRetryable");
function isSuccess({ status }) {
  return ~~(status / 100) === 2;
}
__name(isSuccess, "isSuccess");
function stackTraceWithoutCredentials(stackTrace) {
  return stackTrace.map((stackFrame) => stackFrameWithoutCredentials(stackFrame));
}
__name(stackTraceWithoutCredentials, "stackTraceWithoutCredentials");
function stackFrameWithoutCredentials(stackFrame) {
  const modifiedHeaders = stackFrame.request.headers["x-algolia-api-key"] ? { "x-algolia-api-key": "*****" } : {};
  return {
    ...stackFrame,
    request: {
      ...stackFrame.request,
      headers: {
        ...stackFrame.request.headers,
        ...modifiedHeaders
      }
    }
  };
}
__name(stackFrameWithoutCredentials, "stackFrameWithoutCredentials");
function createTransporter({
  hosts,
  hostsCache,
  baseHeaders,
  logger: logger2,
  baseQueryParameters,
  algoliaAgent,
  timeouts,
  requester,
  requestsCache,
  responsesCache
}) {
  async function createRetryableOptions(compatibleHosts) {
    const statefulHosts = await Promise.all(
      compatibleHosts.map((compatibleHost) => {
        return hostsCache.get(compatibleHost, () => {
          return Promise.resolve(createStatefulHost(compatibleHost));
        });
      })
    );
    const hostsUp = statefulHosts.filter((host) => host.isUp());
    const hostsTimedOut = statefulHosts.filter((host) => host.isTimedOut());
    const hostsAvailable = [...hostsUp, ...hostsTimedOut];
    const compatibleHostsAvailable = hostsAvailable.length > 0 ? hostsAvailable : compatibleHosts;
    return {
      hosts: compatibleHostsAvailable,
      getTimeout(timeoutsCount, baseTimeout) {
        const timeoutMultiplier = hostsTimedOut.length === 0 && timeoutsCount === 0 ? 1 : hostsTimedOut.length + 3 + timeoutsCount;
        return timeoutMultiplier * baseTimeout;
      }
    };
  }
  __name(createRetryableOptions, "createRetryableOptions");
  async function retryableRequest(request, requestOptions, isRead = true) {
    const stackTrace = [];
    const data = serializeData(request, requestOptions);
    const headers = serializeHeaders(baseHeaders, request.headers, requestOptions.headers);
    const dataQueryParameters = request.method === "GET" ? {
      ...request.data,
      ...requestOptions.data
    } : {};
    const queryParameters = {
      ...baseQueryParameters,
      ...request.queryParameters,
      ...dataQueryParameters
    };
    if (algoliaAgent.value) {
      queryParameters["x-algolia-agent"] = algoliaAgent.value;
    }
    if (requestOptions && requestOptions.queryParameters) {
      for (const key of Object.keys(requestOptions.queryParameters)) {
        if (!requestOptions.queryParameters[key] || Object.prototype.toString.call(requestOptions.queryParameters[key]) === "[object Object]") {
          queryParameters[key] = requestOptions.queryParameters[key];
        } else {
          queryParameters[key] = requestOptions.queryParameters[key].toString();
        }
      }
    }
    let timeoutsCount = 0;
    const retry = /* @__PURE__ */ __name(async (retryableHosts, getTimeout) => {
      const host = retryableHosts.pop();
      if (host === void 0) {
        throw new RetryError(stackTraceWithoutCredentials(stackTrace));
      }
      const timeout = { ...timeouts, ...requestOptions.timeouts };
      const payload = {
        data,
        headers,
        method: request.method,
        url: serializeUrl(host, request.path, queryParameters),
        connectTimeout: getTimeout(timeoutsCount, timeout.connect),
        responseTimeout: getTimeout(timeoutsCount, isRead ? timeout.read : timeout.write)
      };
      const pushToStackTrace = /* @__PURE__ */ __name((response2) => {
        const stackFrame = {
          request: payload,
          response: response2,
          host,
          triesLeft: retryableHosts.length
        };
        stackTrace.push(stackFrame);
        return stackFrame;
      }, "pushToStackTrace");
      const response = await requester.send(payload);
      if (isRetryable(response)) {
        const stackFrame = pushToStackTrace(response);
        if (response.isTimedOut) {
          timeoutsCount++;
        }
        logger2.info("Retryable failure", stackFrameWithoutCredentials(stackFrame));
        await hostsCache.set(host, createStatefulHost(host, response.isTimedOut ? "timed out" : "down"));
        return retry(retryableHosts, getTimeout);
      }
      if (isSuccess(response)) {
        return deserializeSuccess(response);
      }
      pushToStackTrace(response);
      throw deserializeFailure(response, stackTrace);
    }, "retry");
    const compatibleHosts = hosts.filter(
      (host) => host.accept === "readWrite" || (isRead ? host.accept === "read" : host.accept === "write")
    );
    const options2 = await createRetryableOptions(compatibleHosts);
    return retry([...options2.hosts].reverse(), options2.getTimeout);
  }
  __name(retryableRequest, "retryableRequest");
  function createRequest(request, requestOptions = {}) {
    const isRead = request.useReadTransporter || request.method === "GET";
    if (!isRead) {
      return retryableRequest(request, requestOptions, isRead);
    }
    const createRetryableRequest = /* @__PURE__ */ __name(() => {
      return retryableRequest(request, requestOptions);
    }, "createRetryableRequest");
    const cacheable = requestOptions.cacheable || request.cacheable;
    if (cacheable !== true) {
      return createRetryableRequest();
    }
    const key = {
      request,
      requestOptions,
      transporter: {
        queryParameters: baseQueryParameters,
        headers: baseHeaders
      }
    };
    return responsesCache.get(
      key,
      () => {
        return requestsCache.get(
          key,
          () => (
            /**
             * Finally, if there is no request in progress with the same key,
             * this `createRetryableRequest()` will actually trigger the
             * retryable request.
             */
            requestsCache.set(key, createRetryableRequest()).then(
              (response) => Promise.all([requestsCache.delete(key), response]),
              (err) => Promise.all([requestsCache.delete(key), Promise.reject(err)])
            ).then(([_2, response]) => response)
          )
        );
      },
      {
        /**
         * Of course, once we get this response back from the server, we
         * tell response cache to actually store the received response
         * to be used later.
         */
        miss: /* @__PURE__ */ __name((response) => responsesCache.set(key, response), "miss")
      }
    );
  }
  __name(createRequest, "createRequest");
  return {
    hostsCache,
    requester,
    timeouts,
    logger: logger2,
    algoliaAgent,
    baseHeaders,
    baseQueryParameters,
    hosts,
    request: createRequest,
    requestsCache,
    responsesCache
  };
}
__name(createTransporter, "createTransporter");
var LogLevelEnum = {
  Debug: 1,
  Info: 2,
  Error: 3
};
var apiClientVersion = "5.21.0";
function getDefaultHosts(appId) {
  return [
    {
      url: `${appId}-dsn.algolia.net`,
      accept: "read",
      protocol: "https"
    },
    {
      url: `${appId}.algolia.net`,
      accept: "write",
      protocol: "https"
    }
  ].concat(
    shuffle([
      {
        url: `${appId}-1.algolianet.com`,
        accept: "readWrite",
        protocol: "https"
      },
      {
        url: `${appId}-2.algolianet.com`,
        accept: "readWrite",
        protocol: "https"
      },
      {
        url: `${appId}-3.algolianet.com`,
        accept: "readWrite",
        protocol: "https"
      }
    ])
  );
}
__name(getDefaultHosts, "getDefaultHosts");
function createLiteClient({
  appId: appIdOption,
  apiKey: apiKeyOption,
  authMode,
  algoliaAgents,
  ...options2
}) {
  const auth2 = createAuth(appIdOption, apiKeyOption, authMode);
  const transporter = createTransporter({
    hosts: getDefaultHosts(appIdOption),
    ...options2,
    algoliaAgent: getAlgoliaAgent({
      algoliaAgents,
      client: "Lite",
      version: apiClientVersion
    }),
    baseHeaders: {
      "content-type": "text/plain",
      ...auth2.headers(),
      ...options2.baseHeaders
    },
    baseQueryParameters: {
      ...auth2.queryParameters(),
      ...options2.baseQueryParameters
    }
  });
  return {
    transporter,
    /**
     * The `appId` currently in use.
     */
    appId: appIdOption,
    /**
     * The `apiKey` currently in use.
     */
    apiKey: apiKeyOption,
    /**
     * Clears the cache of the transporter for the `requestsCache` and `responsesCache` properties.
     */
    clearCache() {
      return Promise.all([transporter.requestsCache.clear(), transporter.responsesCache.clear()]).then(() => void 0);
    },
    /**
     * Get the value of the `algoliaAgent`, used by our libraries internally and telemetry system.
     */
    get _ua() {
      return transporter.algoliaAgent.value;
    },
    /**
     * Adds a `segment` to the `x-algolia-agent` sent with every requests.
     *
     * @param segment - The algolia agent (user-agent) segment to add.
     * @param version - The version of the agent.
     */
    addAlgoliaAgent(segment, version2) {
      transporter.algoliaAgent.add({ segment, version: version2 });
    },
    /**
     * Helper method to switch the API key used to authenticate the requests.
     *
     * @param params - Method params.
     * @param params.apiKey - The new API Key to use.
     */
    setClientApiKey({ apiKey }) {
      if (!authMode || authMode === "WithinHeaders") {
        transporter.baseHeaders["x-algolia-api-key"] = apiKey;
      } else {
        transporter.baseQueryParameters["x-algolia-api-key"] = apiKey;
      }
    },
    /**
     * Helper: calls the `search` method but with certainty that we will only request Algolia records (hits) and not facets.
     * Disclaimer: We don't assert that the parameters you pass to this method only contains `hits` requests to prevent impacting search performances, this helper is purely for typing purposes.
     *
     * @summary Search multiple indices for `hits`.
     * @param searchMethodParams - Query requests and strategies. Results will be received in the same order as the queries.
     * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
     */
    searchForHits(searchMethodParams, requestOptions) {
      return this.search(searchMethodParams, requestOptions);
    },
    /**
     * Helper: calls the `search` method but with certainty that we will only request Algolia facets and not records (hits).
     * Disclaimer: We don't assert that the parameters you pass to this method only contains `facets` requests to prevent impacting search performances, this helper is purely for typing purposes.
     *
     * @summary Search multiple indices for `facets`.
     * @param searchMethodParams - Query requests and strategies. Results will be received in the same order as the queries.
     * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
     */
    searchForFacets(searchMethodParams, requestOptions) {
      return this.search(searchMethodParams, requestOptions);
    },
    /**
     * This method lets you send requests to the Algolia REST API.
     * @param customPost - The customPost object.
     * @param customPost.path - Path of the endpoint, anything after \"/1\" must be specified.
     * @param customPost.parameters - Query parameters to apply to the current query.
     * @param customPost.body - Parameters to send with the custom request.
     * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
     */
    customPost({ path, parameters, body }, requestOptions) {
      if (!path) {
        throw new Error("Parameter `path` is required when calling `customPost`.");
      }
      const requestPath = "/{path}".replace("{path}", path);
      const headers = {};
      const queryParameters = parameters ? parameters : {};
      const request = {
        method: "POST",
        path: requestPath,
        queryParameters,
        headers,
        data: body ? body : {}
      };
      return transporter.request(request, requestOptions);
    },
    /**
     * Retrieves recommendations from selected AI models.
     *
     * Required API Key ACLs:
     *  - search
     * @param getRecommendationsParams - The getRecommendationsParams object.
     * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
     */
    getRecommendations(getRecommendationsParams, requestOptions) {
      if (getRecommendationsParams && Array.isArray(getRecommendationsParams)) {
        const newSignatureRequest = {
          requests: getRecommendationsParams
        };
        getRecommendationsParams = newSignatureRequest;
      }
      if (!getRecommendationsParams) {
        throw new Error("Parameter `getRecommendationsParams` is required when calling `getRecommendations`.");
      }
      if (!getRecommendationsParams.requests) {
        throw new Error("Parameter `getRecommendationsParams.requests` is required when calling `getRecommendations`.");
      }
      const requestPath = "/1/indexes/*/recommendations";
      const headers = {};
      const queryParameters = {};
      const request = {
        method: "POST",
        path: requestPath,
        queryParameters,
        headers,
        data: getRecommendationsParams,
        useReadTransporter: true,
        cacheable: true
      };
      return transporter.request(request, requestOptions);
    },
    /**
     * Sends multiple search requests to one or more indices.  This can be useful in these cases:  - Different indices for different purposes, such as, one index for products, another one for marketing content. - Multiple searches to the same index—for example, with different filters.
     *
     * Required API Key ACLs:
     *  - search
     * @param searchMethodParams - Muli-search request body. Results are returned in the same order as the requests.
     * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
     */
    search(searchMethodParams, requestOptions) {
      if (searchMethodParams && Array.isArray(searchMethodParams)) {
        const newSignatureRequest = {
          requests: searchMethodParams.map(({ params, ...legacyRequest }) => {
            if (legacyRequest.type === "facet") {
              return {
                ...legacyRequest,
                ...params,
                type: "facet"
              };
            }
            return {
              ...legacyRequest,
              ...params,
              facet: void 0,
              maxFacetHits: void 0,
              facetQuery: void 0
            };
          })
        };
        searchMethodParams = newSignatureRequest;
      }
      if (!searchMethodParams) {
        throw new Error("Parameter `searchMethodParams` is required when calling `search`.");
      }
      if (!searchMethodParams.requests) {
        throw new Error("Parameter `searchMethodParams.requests` is required when calling `search`.");
      }
      const requestPath = "/1/indexes/*/queries";
      const headers = {};
      const queryParameters = {};
      const request = {
        method: "POST",
        path: requestPath,
        queryParameters,
        headers,
        data: searchMethodParams,
        useReadTransporter: true,
        cacheable: true
      };
      return transporter.request(request, requestOptions);
    }
  };
}
__name(createLiteClient, "createLiteClient");
function liteClient(appId, apiKey, options2) {
  if (!appId || typeof appId !== "string") {
    throw new Error("`appId` is missing.");
  }
  if (!apiKey || typeof apiKey !== "string") {
    throw new Error("`apiKey` is missing.");
  }
  return createLiteClient({
    appId,
    apiKey,
    timeouts: {
      connect: 1e3,
      read: 2e3,
      write: 3e4
    },
    logger: createNullLogger(),
    requester: m(),
    algoliaAgents: [{ segment: "Browser" }],
    authMode: "WithinQueryParameters",
    responsesCache: createMemoryCache(),
    requestsCache: createMemoryCache({ serializable: false }),
    hostsCache: createFallbackableCache({
      caches: [createBrowserLocalStorageCache({ key: `${apiClientVersion}-${appId}` }), createMemoryCache()]
    }),
    ...options2
  });
}
__name(liteClient, "liteClient");
const DEFAULT_MAX_CACHE_SIZE$1 = 64;
const DEFAULT_MIN_CHARS_FOR_SUGGESTIONS = 2;
const RETRIEVE_ATTRIBUTES = [
  "comfy_nodes",
  "name",
  "description",
  "latest_version",
  "status",
  "publisher_id",
  "total_install",
  "create_time",
  "update_time",
  "license",
  "repository_url",
  "latest_version_status",
  "comfy_node_extract_status",
  "id",
  "icon_url"
];
const useAlgoliaSearchService = /* @__PURE__ */ __name((options2 = {}) => {
  const {
    maxCacheSize = DEFAULT_MAX_CACHE_SIZE$1,
    minCharsForSuggestions = DEFAULT_MIN_CHARS_FOR_SUGGESTIONS
  } = options2;
  const searchClient = liteClient("4E0RO38HS8", "684d998c36b67a9a9fce8fc2d8860579");
  const searchPacksCache = new QuickLRU$1({
    maxSize: maxCacheSize
  });
  const toRegistryLatestVersion = /* @__PURE__ */ __name((algoliaNode) => {
    return {
      version: algoliaNode.latest_version,
      createdAt: algoliaNode.update_time,
      status: algoliaNode.latest_version_status,
      comfy_node_extract_status: algoliaNode.comfy_node_extract_status ?? void 0
    };
  }, "toRegistryLatestVersion");
  const toRegistryPublisher = /* @__PURE__ */ __name((algoliaNode) => {
    return {
      id: algoliaNode.publisher_id,
      name: algoliaNode.publisher_id
    };
  }, "toRegistryPublisher");
  function toRegistryPack(algoliaNode) {
    return {
      id: algoliaNode.id ?? algoliaNode.objectID,
      name: algoliaNode.name,
      description: algoliaNode.description,
      repository: algoliaNode.repository_url,
      license: algoliaNode.license,
      downloads: algoliaNode.total_install,
      status: algoliaNode.status,
      icon: algoliaNode.icon_url,
      latest_version: toRegistryLatestVersion(algoliaNode),
      publisher: toRegistryPublisher(algoliaNode),
      // @ts-expect-error remove when comfy_nodes is added to node (pack) info
      comfy_nodes: algoliaNode.comfy_nodes
    };
  }
  __name(toRegistryPack, "toRegistryPack");
  const searchPacks = /* @__PURE__ */ __name(async (query2, params) => {
    const { pageSize, pageNumber } = params;
    const rest = lodashExports.omit(params, ["pageSize", "pageNumber"]);
    const requests = [
      {
        query: query2,
        indexName: "nodes_index",
        attributesToRetrieve: RETRIEVE_ATTRIBUTES,
        ...rest,
        hitsPerPage: pageSize,
        page: pageNumber
      }
    ];
    const shouldQuerySuggestions = query2.length >= minCharsForSuggestions;
    if (shouldQuerySuggestions) {
      requests.push({
        indexName: "nodes_index_query_suggestions",
        query: query2
      });
    }
    const { results } = await searchClient.search({
      requests,
      strategy: "none"
    });
    const [nodePacks, querySuggestions = { hits: [] }] = results;
    return {
      nodePacks: nodePacks.hits,
      querySuggestions: querySuggestions.hits
    };
  }, "searchPacks");
  const searchPacksCached = /* @__PURE__ */ __name(async (query2, params) => {
    const cacheKey = paramsToCacheKey({ query: query2, ...params });
    const cachedResult2 = searchPacksCache.get(cacheKey);
    if (cachedResult2 !== void 0) return cachedResult2;
    const result = await searchPacks(query2, params);
    searchPacksCache.set(cacheKey, result);
    return result;
  }, "searchPacksCached");
  const clearSearchPacksCache = /* @__PURE__ */ __name(() => {
    searchPacksCache.clear();
  }, "clearSearchPacksCache");
  return {
    searchPacks,
    searchPacksCached,
    toRegistryPack,
    clearSearchPacksCache
  };
}, "useAlgoliaSearchService");
const SEARCH_DEBOUNCE_TIME = 320;
const DEFAULT_PAGE_SIZE = 64;
const DEFAULT_SORT_FIELD = SortableAlgoliaField.Downloads;
const DEFAULT_MAX_CACHE_SIZE = 64;
const SORT_DIRECTIONS = {
  [SortableAlgoliaField.Downloads]: "desc",
  [SortableAlgoliaField.Created]: "desc",
  [SortableAlgoliaField.Updated]: "desc",
  [SortableAlgoliaField.Publisher]: "asc",
  [SortableAlgoliaField.Name]: "asc"
};
const isDateField = /* @__PURE__ */ __name((field2) => field2 === SortableAlgoliaField.Created || field2 === SortableAlgoliaField.Updated, "isDateField");
function useRegistrySearch(options2 = {}) {
  const { maxCacheSize = DEFAULT_MAX_CACHE_SIZE } = options2;
  const isLoading = ref$3(false);
  const sortField = ref$3(SortableAlgoliaField.Downloads);
  const searchMode = ref$3("packs");
  const pageSize = ref$3(DEFAULT_PAGE_SIZE);
  const pageNumber = ref$3(0);
  const searchQuery = ref$3("");
  const results = ref$3([]);
  const suggestions = ref$3([]);
  const searchAttributes = computed(
    () => searchMode.value === "nodes" ? ["comfy_nodes"] : ["name", "description"]
  );
  const resultsAsRegistryPacks = computed(
    () => results.value ? results.value.map(algoliaToRegistry) : []
  );
  const resultsAsNodes = computed(
    () => results.value ? results.value.reduce(
      (acc, hit) => acc.concat(hit.comfy_nodes),
      []
    ) : []
  );
  const { searchPacksCached, toRegistryPack, clearSearchPacksCache } = useAlgoliaSearchService({
    maxCacheSize
  });
  const algoliaToRegistry = lodashExports.memoize(
    toRegistryPack,
    (algoliaNode) => algoliaNode.id
  );
  const getSortValue = /* @__PURE__ */ __name((pack) => {
    if (isDateField(sortField.value)) {
      const value = pack[sortField.value];
      return value ? new Date(value).getTime() : 0;
    } else {
      const value = pack[sortField.value];
      return value ?? 0;
    }
  }, "getSortValue");
  const updateSearchResults = /* @__PURE__ */ __name(async (options22) => {
    isLoading.value = true;
    if (!options22.append) {
      pageNumber.value = 0;
    }
    const { nodePacks, querySuggestions } = await searchPacksCached(
      searchQuery.value,
      {
        pageSize: pageSize.value,
        pageNumber: pageNumber.value,
        restrictSearchableAttributes: searchAttributes.value
      }
    );
    let sortedPacks = nodePacks;
    if (sortField.value && sortField.value !== DEFAULT_SORT_FIELD) {
      sortedPacks = lodashExports.orderBy(
        nodePacks,
        [getSortValue],
        [SORT_DIRECTIONS[sortField.value]]
      );
    }
    if (options22.append && results.value?.length) {
      results.value = results.value.concat(sortedPacks);
    } else {
      results.value = sortedPacks;
    }
    suggestions.value = querySuggestions;
    isLoading.value = false;
  }, "updateSearchResults");
  const onQueryChange = /* @__PURE__ */ __name(() => updateSearchResults({ append: false }), "onQueryChange");
  const onPageChange = /* @__PURE__ */ __name(() => updateSearchResults({ append: true }), "onPageChange");
  watch([sortField, searchMode], onQueryChange);
  watch(pageNumber, onPageChange);
  watchDebounced(searchQuery, onQueryChange, {
    debounce: SEARCH_DEBOUNCE_TIME,
    immediate: true
  });
  onUnmounted(clearSearchPacksCache);
  return {
    isLoading,
    pageNumber,
    pageSize,
    sortField,
    searchMode,
    searchQuery,
    suggestions,
    searchResults: resultsAsRegistryPacks,
    nodeSearchResults: resultsAsNodes
  };
}
__name(useRegistrySearch, "useRegistrySearch");
const _hoisted_1$A = ["aria-label"];
const _hoisted_2$t = { class: "flex flex-1 relative overflow-hidden" };
const _hoisted_3$g = { class: "px-6 pt-6 flex flex-col h-full" };
const _hoisted_4$7 = { class: "flex-1 overflow-auto" };
const _hoisted_5$6 = {
  key: 0,
  class: "w-full h-full overflow-auto scrollbar-hide"
};
const _hoisted_6$5 = { class: "w-80 border-l-0 absolute right-0 top-0 bottom-0 flex z-20" };
const _hoisted_7$2 = { class: "flex-1 flex flex-col isolate" };
const _sfc_main$K = /* @__PURE__ */ defineComponent({
  __name: "ManagerDialogContent",
  props: {
    initialTab: { default: /* @__PURE__ */ __name(() => ManagerTab.All, "default") }
  },
  setup(__props) {
    const { t: t2 } = useI18n();
    const comfyManagerStore = useComfyManagerStore();
    const { getPackById } = useComfyRegistryStore();
    const GRID_STYLE = {
      display: "grid",
      gridTemplateColumns: "repeat(auto-fill, minmax(19rem, 1fr))",
      padding: "0.5rem",
      gap: "1.5rem"
    };
    const {
      isSmallScreen,
      isOpen: isSideNavOpen,
      toggle: toggleSideNav
    } = useResponsiveCollapse();
    const tabs = ref$3([
      { id: ManagerTab.All, label: t2("g.all"), icon: "pi-list" },
      { id: ManagerTab.Installed, label: t2("g.installed"), icon: "pi-box" },
      {
        id: ManagerTab.Workflow,
        label: t2("manager.inWorkflow"),
        icon: "pi-folder"
      },
      {
        id: ManagerTab.Missing,
        label: t2("g.missing"),
        icon: "pi-exclamation-circle"
      },
      {
        id: ManagerTab.UpdateAvailable,
        label: t2("g.updateAvailable"),
        icon: "pi-sync"
      }
    ]);
    const selectedTab = ref$3(
      tabs.value.find((tab) => tab.id === __props.initialTab) || tabs.value[0]
    );
    const {
      searchQuery,
      pageNumber,
      isLoading: isSearchLoading,
      searchResults,
      searchMode,
      sortField,
      suggestions
    } = useRegistrySearch();
    pageNumber.value = 0;
    const onApproachEnd = /* @__PURE__ */ __name(() => {
      pageNumber.value++;
    }, "onApproachEnd");
    const isInitialLoad = computed(
      () => searchResults.value.length === 0 && searchQuery.value === ""
    );
    const isEmptySearch = computed(() => searchQuery.value === "");
    const displayPacks = ref$3([]);
    const {
      startFetchInstalled,
      filterInstalledPack,
      installedPacks,
      isLoading: isLoadingInstalled,
      isReady: installedPacksReady
    } = useInstalledPacks();
    const {
      startFetchWorkflowPacks,
      filterWorkflowPack,
      workflowPacks,
      isLoading: isLoadingWorkflow,
      isReady: workflowPacksReady
    } = useWorkflowPacks();
    const filterMissingPacks = /* @__PURE__ */ __name((packs) => packs.filter((pack) => !comfyManagerStore.isPackInstalled(pack.id)), "filterMissingPacks");
    whenever(selectedTab, () => {
      pageNumber.value = 0;
    });
    const isUpdateAvailableTab = computed(
      () => selectedTab.value?.id === ManagerTab.UpdateAvailable
    );
    const isInstalledTab = computed(
      () => selectedTab.value?.id === ManagerTab.Installed
    );
    const isMissingTab = computed(
      () => selectedTab.value?.id === ManagerTab.Missing
    );
    const isWorkflowTab = computed(
      () => selectedTab.value?.id === ManagerTab.Workflow
    );
    const isAllTab = computed(() => selectedTab.value?.id === ManagerTab.All);
    const isOutdatedPack = /* @__PURE__ */ __name((pack) => {
      const { isUpdateAvailable } = usePackUpdateStatus(pack);
      return isUpdateAvailable.value === true;
    }, "isOutdatedPack");
    const filterOutdatedPacks = /* @__PURE__ */ __name((packs) => packs.filter(isOutdatedPack), "filterOutdatedPacks");
    watch(
      [isUpdateAvailableTab, installedPacks],
      async () => {
        if (!isUpdateAvailableTab.value) return;
        if (!isEmptySearch.value) {
          displayPacks.value = filterOutdatedPacks(installedPacks.value);
        } else if (!installedPacks.value.length) {
          await startFetchInstalled();
        } else {
          displayPacks.value = filterOutdatedPacks(installedPacks.value);
        }
      },
      { immediate: true }
    );
    watch(
      [isInstalledTab, installedPacks],
      async () => {
        if (!isInstalledTab.value) return;
        if (!isEmptySearch.value) {
          displayPacks.value = filterInstalledPack(searchResults.value);
        } else if (!installedPacks.value.length && !installedPacksReady.value && !isLoadingInstalled.value) {
          await startFetchInstalled();
        } else {
          displayPacks.value = installedPacks.value;
        }
      },
      { immediate: true }
    );
    watch(
      [isMissingTab, isWorkflowTab, workflowPacks, installedPacks],
      async () => {
        if (!isWorkflowTab.value && !isMissingTab.value) return;
        if (!isEmptySearch.value) {
          displayPacks.value = isMissingTab.value ? filterMissingPacks(filterWorkflowPack(searchResults.value)) : filterWorkflowPack(searchResults.value);
        } else if (!workflowPacks.value.length && !isLoadingWorkflow.value && !workflowPacksReady.value) {
          await startFetchWorkflowPacks();
          if (isMissingTab.value) {
            await startFetchInstalled();
          }
        } else {
          displayPacks.value = isMissingTab.value ? filterMissingPacks(workflowPacks.value) : workflowPacks.value;
        }
      },
      { immediate: true }
    );
    watch([isAllTab, searchResults], () => {
      if (!isAllTab.value) return;
      displayPacks.value = searchResults.value;
    });
    const onResultsChange = /* @__PURE__ */ __name(() => {
      switch (selectedTab.value?.id) {
        case ManagerTab.Installed:
          displayPacks.value = isEmptySearch.value ? installedPacks.value : filterInstalledPack(searchResults.value);
          break;
        case ManagerTab.Workflow:
          displayPacks.value = isEmptySearch.value ? workflowPacks.value : filterWorkflowPack(searchResults.value);
          break;
        case ManagerTab.Missing:
          if (!isEmptySearch.value) {
            displayPacks.value = filterMissingPacks(
              filterWorkflowPack(searchResults.value)
            );
          }
          break;
        case ManagerTab.UpdateAvailable:
          displayPacks.value = isEmptySearch.value ? filterOutdatedPacks(installedPacks.value) : filterOutdatedPacks(searchResults.value);
          break;
        default:
          displayPacks.value = searchResults.value;
      }
    }, "onResultsChange");
    watch(searchResults, onResultsChange, { flush: "post" });
    watch(() => comfyManagerStore.installedPacksIds, onResultsChange);
    const isLoading = computed(() => {
      if (isSearchLoading.value) return searchResults.value.length === 0;
      if (selectedTab.value?.id === ManagerTab.Installed) {
        return isLoadingInstalled.value;
      }
      if (selectedTab.value?.id === ManagerTab.Workflow || selectedTab.value?.id === ManagerTab.Missing) {
        return isLoadingWorkflow.value;
      }
      return isInitialLoad.value;
    });
    const resultsWithKeys = computed(
      () => displayPacks.value.map((item) => ({
        ...item,
        key: item.id || item.name
      }))
    );
    const selectedNodePacks = ref$3([]);
    const selectedNodePack = computed(
      () => selectedNodePacks.value.length === 1 ? selectedNodePacks.value[0] : null
    );
    const getLoadingCount = /* @__PURE__ */ __name(() => {
      switch (selectedTab.value?.id) {
        case ManagerTab.Installed:
          return comfyManagerStore.installedPacksIds?.size;
        case ManagerTab.Workflow:
          return workflowPacks.value?.length;
        case ManagerTab.Missing:
          return workflowPacks.value?.filter?.(
            (pack) => !comfyManagerStore.isPackInstalled(pack.id)
          )?.length;
        default:
          return searchResults.value.length;
      }
    }, "getLoadingCount");
    const skeletonCardCount = computed(() => {
      const loadingCount = getLoadingCount();
      if (loadingCount) return loadingCount;
      return isSmallScreen.value ? 12 : 16;
    });
    const selectNodePack = /* @__PURE__ */ __name((nodePack, event) => {
      if (event.shiftKey || event.ctrlKey || event.metaKey) {
        const index2 = selectedNodePacks.value.findIndex(
          (pack) => pack.id === nodePack.id
        );
        if (index2 === -1) {
          selectedNodePacks.value.push(nodePack);
        } else {
          selectedNodePacks.value.splice(index2, 1);
        }
      } else {
        selectedNodePacks.value = [nodePack];
      }
    }, "selectNodePack");
    const unSelectItems = /* @__PURE__ */ __name(() => {
      selectedNodePacks.value = [];
    }, "unSelectItems");
    const handleGridContainerClick = /* @__PURE__ */ __name((event) => {
      const targetElement = event.target;
      if (targetElement && !targetElement.closest("[data-virtual-grid-item]")) {
        unSelectItems();
      }
    }, "handleGridContainerClick");
    const hasMultipleSelections = computed(() => selectedNodePacks.value.length > 1);
    whenever(selectedNodePack, async () => {
      getPackById.cancel();
      if (!selectedNodePack.value?.id) return;
      if (hasMultipleSelections.value) return;
      const data = await getPackById.call(selectedNodePack.value.id);
      if (data?.id === selectedNodePack.value?.id) {
        selectedNodePacks.value = [lodashExports.merge(selectedNodePack.value, data)];
      }
    });
    let gridContainer = null;
    onMounted(() => {
      gridContainer = document.getElementById("results-grid");
    });
    watch(searchQuery, () => {
      gridContainer ??= document.getElementById("results-grid");
      if (gridContainer) {
        gridContainer.scrollTop = 0;
      }
    });
    onUnmounted(() => {
      getPackById.cancel();
    });
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", {
        class: "flex flex-col mx-auto overflow-hidden h-[83vh] relative",
        "aria-label": _ctx.$t("manager.title")
      }, [
        unref(isSmallScreen) ? (openBlock(), createBlock(unref(script$6), {
          key: 0,
          icon: unref(isSideNavOpen) ? "pi pi-chevron-left" : "pi pi-chevron-right",
          text: "",
          class: normalizeClass(["absolute top-1/2 -translate-y-1/2 z-10", unref(isSideNavOpen) ? "left-[19rem]" : "left-2"]),
          onClick: unref(toggleSideNav)
        }, null, 8, ["icon", "class", "onClick"])) : createCommentVNode("", true),
        createBaseVNode("div", _hoisted_2$t, [
          unref(isSideNavOpen) ? (openBlock(), createBlock(_sfc_main$1a, {
            key: 0,
            selectedTab: selectedTab.value,
            "onUpdate:selectedTab": _cache[0] || (_cache[0] = ($event) => selectedTab.value = $event),
            tabs: tabs.value
          }, null, 8, ["selectedTab", "tabs"])) : createCommentVNode("", true),
          createBaseVNode("div", {
            class: normalizeClass(["flex-1 overflow-auto pr-80", {
              "transition-all duration-300": unref(isSmallScreen),
              "pl-80": unref(isSideNavOpen) || !unref(isSmallScreen),
              "pl-8": !unref(isSideNavOpen) && unref(isSmallScreen)
            }])
          }, [
            createBaseVNode("div", _hoisted_3$g, [
              createVNode(_sfc_main$N, {
                searchQuery: unref(searchQuery),
                "onUpdate:searchQuery": _cache[1] || (_cache[1] = ($event) => isRef(searchQuery) ? searchQuery.value = $event : null),
                searchMode: unref(searchMode),
                "onUpdate:searchMode": _cache[2] || (_cache[2] = ($event) => isRef(searchMode) ? searchMode.value = $event : null),
                sortField: unref(sortField),
                "onUpdate:sortField": _cache[3] || (_cache[3] = ($event) => isRef(sortField) ? sortField.value = $event : null),
                "search-results": unref(searchResults),
                suggestions: unref(suggestions)
              }, null, 8, ["searchQuery", "searchMode", "sortField", "search-results", "suggestions"]),
              createBaseVNode("div", _hoisted_4$7, [
                isLoading.value ? (openBlock(), createElementBlock("div", _hoisted_5$6, [
                  createVNode(_sfc_main$L, {
                    "grid-style": GRID_STYLE,
                    "skeleton-card-count": skeletonCardCount.value
                  }, null, 8, ["skeleton-card-count"])
                ])) : unref(searchResults).length === 0 ? (openBlock(), createBlock(NoResultsPlaceholder, {
                  key: 1,
                  title: unref(comfyManagerStore).error ? _ctx.$t("manager.errorConnecting") : _ctx.$t("manager.noResultsFound"),
                  message: unref(comfyManagerStore).error ? _ctx.$t("manager.tryAgainLater") : _ctx.$t("manager.tryDifferentSearch")
                }, null, 8, ["title", "message"])) : (openBlock(), createElementBlock("div", {
                  key: 2,
                  class: "h-full",
                  onClick: handleGridContainerClick
                }, [
                  createVNode(VirtualGrid, {
                    id: "results-grid",
                    items: resultsWithKeys.value,
                    "buffer-rows": 3,
                    "grid-style": GRID_STYLE,
                    onApproachEnd
                  }, {
                    item: withCtx(({ item }) => [
                      createVNode(_sfc_main$P, {
                        "node-pack": item,
                        "is-selected": selectedNodePacks.value.some((pack) => pack.id === item.id),
                        onClick: withModifiers((event) => selectNodePack(item, event), ["stop"])
                      }, null, 8, ["node-pack", "is-selected", "onClick"])
                    ]),
                    _: 1
                  }, 8, ["items"])
                ]))
              ])
            ])
          ], 2),
          createBaseVNode("div", _hoisted_6$5, [
            createVNode(_sfc_main$1c, {
              orientation: "vertical",
              width: 0.2
            }),
            createBaseVNode("div", _hoisted_7$2, [
              !hasMultipleSelections.value && selectedNodePack.value ? (openBlock(), createBlock(InfoPanel, {
                key: 0,
                "node-pack": selectedNodePack.value
              }, null, 8, ["node-pack"])) : (openBlock(), createBlock(_sfc_main$S, {
                key: 1,
                "node-packs": selectedNodePacks.value
              }, null, 8, ["node-packs"]))
            ])
          ])
        ])
      ], 8, _hoisted_1$A);
    };
  }
});
const _hoisted_1$z = { class: "w-full" };
const _hoisted_2$s = { class: "px-6 py-4" };
const _hoisted_3$f = { class: "text-lg font-normal text-left" };
const _sfc_main$J = /* @__PURE__ */ defineComponent({
  __name: "ManagerHeader",
  setup(__props) {
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", _hoisted_1$z, [
        createBaseVNode("div", _hoisted_2$s, [
          createBaseVNode("h2", _hoisted_3$f, toDisplayString(_ctx.$t("manager.discoverCommunityContent")), 1)
        ]),
        createVNode(_sfc_main$1c, { width: 0.3 })
      ]);
    };
  }
});
const defaultGraph = {
  last_node_id: 9,
  last_link_id: 9,
  nodes: [
    {
      id: 7,
      type: "CLIPTextEncode",
      pos: [413, 389],
      size: [425.27801513671875, 180.6060791015625],
      flags: {},
      order: 3,
      mode: 0,
      inputs: [{ name: "clip", type: "CLIP", link: 5 }],
      outputs: [
        {
          name: "CONDITIONING",
          type: "CONDITIONING",
          links: [6],
          slot_index: 0
        }
      ],
      properties: {},
      widgets_values: ["text, watermark"]
    },
    {
      id: 6,
      type: "CLIPTextEncode",
      pos: [415, 186],
      size: [422.84503173828125, 164.31304931640625],
      flags: {},
      order: 2,
      mode: 0,
      inputs: [{ name: "clip", type: "CLIP", link: 3 }],
      outputs: [
        {
          name: "CONDITIONING",
          type: "CONDITIONING",
          links: [4],
          slot_index: 0
        }
      ],
      properties: {},
      widgets_values: [
        "beautiful scenery nature glass bottle landscape, , purple galaxy bottle,"
      ]
    },
    {
      id: 5,
      type: "EmptyLatentImage",
      pos: [473, 609],
      size: [315, 106],
      flags: {},
      order: 1,
      mode: 0,
      outputs: [{ name: "LATENT", type: "LATENT", links: [2], slot_index: 0 }],
      properties: {},
      widgets_values: [512, 512, 1]
    },
    {
      id: 3,
      type: "KSampler",
      pos: [863, 186],
      size: [315, 262],
      flags: {},
      order: 4,
      mode: 0,
      inputs: [
        { name: "model", type: "MODEL", link: 1 },
        { name: "positive", type: "CONDITIONING", link: 4 },
        { name: "negative", type: "CONDITIONING", link: 6 },
        { name: "latent_image", type: "LATENT", link: 2 }
      ],
      outputs: [{ name: "LATENT", type: "LATENT", links: [7], slot_index: 0 }],
      properties: {},
      widgets_values: [156680208700286, true, 20, 8, "euler", "normal", 1]
    },
    {
      id: 8,
      type: "VAEDecode",
      pos: [1209, 188],
      size: [210, 46],
      flags: {},
      order: 5,
      mode: 0,
      inputs: [
        { name: "samples", type: "LATENT", link: 7 },
        { name: "vae", type: "VAE", link: 8 }
      ],
      outputs: [{ name: "IMAGE", type: "IMAGE", links: [9], slot_index: 0 }],
      properties: {}
    },
    {
      id: 9,
      type: "SaveImage",
      pos: [1451, 189],
      size: [210, 26],
      flags: {},
      order: 6,
      mode: 0,
      inputs: [{ name: "images", type: "IMAGE", link: 9 }],
      properties: {}
    },
    {
      id: 4,
      type: "CheckpointLoaderSimple",
      pos: [26, 474],
      size: [315, 98],
      flags: {},
      order: 0,
      mode: 0,
      outputs: [
        { name: "MODEL", type: "MODEL", links: [1], slot_index: 0 },
        { name: "CLIP", type: "CLIP", links: [3, 5], slot_index: 1 },
        { name: "VAE", type: "VAE", links: [8], slot_index: 2 }
      ],
      properties: {},
      widgets_values: ["v1-5-pruned-emaonly-fp16.safetensors"]
    }
  ],
  links: [
    [1, 4, 0, 3, 0, "MODEL"],
    [2, 5, 0, 3, 3, "LATENT"],
    [3, 4, 1, 6, 0, "CLIP"],
    [4, 6, 0, 3, 1, "CONDITIONING"],
    [5, 4, 1, 7, 0, "CLIP"],
    [6, 7, 0, 3, 2, "CONDITIONING"],
    [7, 3, 0, 8, 0, "LATENT"],
    [8, 4, 2, 8, 1, "VAE"],
    [9, 8, 0, 9, 0, "IMAGE"]
  ],
  groups: [],
  config: {},
  extra: {
    ds: {
      offset: [0, 0],
      scale: 1
    }
  },
  version: 0.4
};
const defaultGraphJSON = JSON.stringify(defaultGraph);
const blankGraph = {
  last_node_id: 0,
  last_link_id: 0,
  nodes: [],
  links: [],
  groups: [],
  config: {},
  extra: {},
  version: 0.4
};
window.comfyAPI = window.comfyAPI || {};
window.comfyAPI.defaultGraph = window.comfyAPI.defaultGraph || {};
window.comfyAPI.defaultGraph.defaultGraph = defaultGraph;
window.comfyAPI.defaultGraph.defaultGraphJSON = defaultGraphJSON;
window.comfyAPI.defaultGraph.blankGraph = blankGraph;
function applyTextReplacements$1(allNodes, value) {
  return value.replace(/%([^%]+)%/g, function(match2, text2) {
    const split2 = text2.split(".");
    if (split2.length !== 2) {
      if (split2[0].startsWith("date:")) {
        return formatDate(split2[0].substring(5), /* @__PURE__ */ new Date());
      }
      if (text2 !== "width" && text2 !== "height") {
        console.warn("Invalid replacement pattern", text2);
      }
      return match2;
    }
    let nodes = allNodes.filter(
      (n2) => n2.properties?.["Node name for S&R"] === split2[0]
    );
    if (!nodes.length) {
      nodes = allNodes.filter((n2) => n2.title === split2[0]);
    }
    if (!nodes.length) {
      console.warn("Unable to find node", split2[0]);
      return match2;
    }
    if (nodes.length > 1) {
      console.warn("Multiple nodes matched", split2[0], "using first match");
    }
    const node2 = nodes[0];
    const widget = node2.widgets?.find((w2) => w2.name === split2[1]);
    if (!widget) {
      console.warn("Unable to find widget", split2[1], "on node", split2[0], node2);
      return match2;
    }
    return ((widget.value ?? "") + "").replaceAll(
      // eslint-disable-next-line no-control-regex
      /[/?<>\\:*|"\x00-\x1F\x7F]/g,
      "_"
    );
  });
}
__name(applyTextReplacements$1, "applyTextReplacements$1");
function calculateImageGrid(imgs, dw, dh) {
  let best = 0;
  let w2 = imgs[0].naturalWidth;
  let h2 = imgs[0].naturalHeight;
  const numImages = imgs.length;
  let cellWidth, cellHeight, cols, rows, shiftX;
  for (let c2 = 1; c2 <= numImages; c2++) {
    const r2 = Math.ceil(numImages / c2);
    const cW = dw / c2;
    const cH = dh / r2;
    const scaleX = cW / w2;
    const scaleY = cH / h2;
    const scale = Math.min(scaleX, scaleY, 1);
    const imageW = w2 * scale;
    const imageH = h2 * scale;
    const area = imageW * imageH * numImages;
    if (area > best) {
      best = area;
      cellWidth = imageW;
      cellHeight = imageH;
      cols = c2;
      rows = r2;
      shiftX = c2 * ((cW - imageW) / 2);
    }
  }
  return { cellWidth, cellHeight, cols, rows, shiftX };
}
__name(calculateImageGrid, "calculateImageGrid");
function createImageHost(node2) {
  const el = $el("div.comfy-img-preview");
  let currentImgs;
  let first2 = true;
  function updateSize() {
    let w2 = null;
    let h2 = null;
    if (currentImgs) {
      let elH = el.clientHeight;
      if (first2) {
        first2 = false;
        if (elH < 190) {
          elH = 190;
        }
        el.style.setProperty("--comfy-widget-min-height", elH.toString());
      } else {
        el.style.setProperty("--comfy-widget-min-height", null);
      }
      const nw = node2.size[0];
      ({ cellWidth: w2, cellHeight: h2 } = calculateImageGrid(
        currentImgs,
        nw - 20,
        elH
      ));
      w2 += "px";
      h2 += "px";
      el.style.setProperty("--comfy-img-preview-width", w2);
      el.style.setProperty("--comfy-img-preview-height", h2);
    }
  }
  __name(updateSize, "updateSize");
  return {
    el,
    getCurrentImage() {
      return currentImgs?.[0];
    },
    // @ts-expect-error fixme ts strict error
    updateImages(imgs) {
      if (imgs !== currentImgs) {
        if (currentImgs == null) {
          requestAnimationFrame(() => {
            updateSize();
          });
        }
        el.replaceChildren(...imgs);
        currentImgs = imgs;
        node2.onResize(node2.size);
        node2.graph.setDirtyCanvas(true, true);
      }
    },
    getHeight() {
      updateSize();
    },
    onDraw() {
      el.style.pointerEvents = "all";
      const over = document.elementFromPoint(
        app$1.canvas.mouse[0],
        app$1.canvas.mouse[1]
      );
      el.style.pointerEvents = "none";
      if (!over) return;
      const idx = currentImgs.indexOf(over);
      node2.overIndex = idx;
    }
  };
}
__name(createImageHost, "createImageHost");
window.comfyAPI = window.comfyAPI || {};
window.comfyAPI.imagePreview = window.comfyAPI.imagePreview || {};
window.comfyAPI.imagePreview.calculateImageGrid = calculateImageGrid;
window.comfyAPI.imagePreview.createImageHost = createImageHost;
function useNodeAnimatedImage() {
  function showAnimatedPreview(node2) {
    if (!node2.imgs?.length) return;
    if (!node2.widgets) return;
    const widgetIdx = node2.widgets.findIndex(
      (w2) => w2.name === ANIM_PREVIEW_WIDGET
    );
    if (widgetIdx > -1) {
      const widget = node2.widgets[widgetIdx];
      widget.options.host.updateImages(node2.imgs);
    } else {
      const host = createImageHost(node2);
      const widget = node2.addDOMWidget(ANIM_PREVIEW_WIDGET, "img", host.el, {
        host,
        // @ts-expect-error `getHeight` of image host returns void instead of number.
        getHeight: host.getHeight,
        onDraw: host.onDraw,
        hideOnZoom: false
      });
      widget.serialize = false;
      widget.serializeValue = () => void 0;
      widget.options.host.updateImages(node2.imgs);
      widget.computeLayoutSize = () => {
        const img = widget.options.host.getCurrentImage();
        if (!img) return { minHeight: 0, minWidth: 0 };
        return fitDimensionsToNodeWidth(
          img.naturalWidth,
          img.naturalHeight,
          node2.size?.[0] || 0
        );
      };
    }
  }
  __name(showAnimatedPreview, "showAnimatedPreview");
  function removeAnimatedPreview(node2) {
    if (!node2.widgets) return;
    const widgetIdx = node2.widgets.findIndex(
      (w2) => w2.name === ANIM_PREVIEW_WIDGET
    );
    if (widgetIdx > -1) {
      node2.widgets[widgetIdx].onRemove?.();
      node2.widgets.splice(widgetIdx, 1);
    }
  }
  __name(removeAnimatedPreview, "removeAnimatedPreview");
  return {
    showAnimatedPreview,
    removeAnimatedPreview
  };
}
__name(useNodeAnimatedImage, "useNodeAnimatedImage");
const useTitleEditorStore = /* @__PURE__ */ defineStore("titleEditor", () => {
  const titleEditorTarget = shallowRef(null);
  return {
    titleEditorTarget
  };
});
const useCanvasStore = /* @__PURE__ */ defineStore("canvas", () => {
  const canvas2 = shallowRef(null);
  const selectedItems = ref$3([]);
  const updateSelectedItems = /* @__PURE__ */ __name(() => {
    const items = Array.from(canvas2.value?.selectedItems ?? []);
    selectedItems.value = items.map((item) => markRaw(item));
  }, "updateSelectedItems");
  const getCanvas = /* @__PURE__ */ __name(() => {
    if (!canvas2.value) throw new Error("getCanvas: canvas is null");
    return canvas2.value;
  }, "getCanvas");
  return {
    canvas: canvas2,
    selectedItems,
    updateSelectedItems,
    getCanvas
  };
});
const renderPreview = /* @__PURE__ */ __name((ctx, node2, shiftY) => {
  const canvas2 = useCanvasStore().getCanvas();
  const mouse = canvas2.graph_mouse;
  if (!canvas2.pointer_is_down && node2.pointerDown) {
    if (mouse[0] === node2.pointerDown.pos[0] && mouse[1] === node2.pointerDown.pos[1]) {
      node2.imageIndex = node2.pointerDown.index;
    }
    node2.pointerDown = null;
  }
  const imgs = node2.imgs ?? [];
  let { imageIndex } = node2;
  const numImages = imgs.length;
  if (numImages === 1 && !imageIndex) {
    node2.imageIndex = imageIndex = 0;
  }
  const settingStore = useSettingStore();
  const allowImageSizeDraw = settingStore.get("Comfy.Node.AllowImageSizeDraw");
  const IMAGE_TEXT_SIZE_TEXT_HEIGHT = allowImageSizeDraw ? 15 : 0;
  const dw = node2.size[0];
  const dh = node2.size[1] - shiftY - IMAGE_TEXT_SIZE_TEXT_HEIGHT;
  if (imageIndex == null) {
    let cellWidth;
    let cellHeight;
    let shiftX;
    let cell_padding;
    let cols;
    const compact_mode = is_all_same_aspect_ratio(imgs);
    if (!compact_mode) {
      cell_padding = 2;
      const largestDimension = imgs.reduce(
        (acc, current) => Math.max(acc, current.naturalWidth, current.naturalHeight),
        0
      );
      const fakeImgs = [];
      fakeImgs.length = imgs.length;
      fakeImgs[0] = {
        naturalWidth: largestDimension,
        naturalHeight: largestDimension
      };
      ({ cellWidth, cellHeight, cols, shiftX } = calculateImageGrid(
        fakeImgs,
        dw,
        dh
      ));
    } else {
      cell_padding = 0;
      ({ cellWidth, cellHeight, cols, shiftX } = calculateImageGrid(
        imgs,
        dw,
        dh
      ));
    }
    let anyHovered = false;
    node2.imageRects = [];
    for (let i2 = 0; i2 < numImages; i2++) {
      const img2 = imgs[i2];
      const row = Math.floor(i2 / cols);
      const col = i2 % cols;
      const x22 = col * cellWidth + shiftX;
      const y22 = row * cellHeight + shiftY;
      if (!anyHovered) {
        anyHovered = LiteGraph.isInsideRectangle(
          mouse[0],
          mouse[1],
          x22 + node2.pos[0],
          y22 + node2.pos[1],
          cellWidth,
          cellHeight
        );
        if (anyHovered) {
          node2.overIndex = i2;
          let value = 110;
          if (canvas2.pointer_is_down) {
            if (!node2.pointerDown || node2.pointerDown.index !== i2) {
              node2.pointerDown = { index: i2, pos: [...mouse] };
            }
            value = 125;
          }
          ctx.filter = `contrast(${value}%) brightness(${value}%)`;
          canvas2.canvas.style.cursor = "pointer";
        }
      }
      node2.imageRects.push([x22, y22, cellWidth, cellHeight]);
      const wratio = cellWidth / img2.width;
      const hratio = cellHeight / img2.height;
      const ratio = Math.min(wratio, hratio);
      const imgHeight = ratio * img2.height;
      const imgY = row * cellHeight + shiftY + (cellHeight - imgHeight) / 2;
      const imgWidth = ratio * img2.width;
      const imgX = col * cellWidth + shiftX + (cellWidth - imgWidth) / 2;
      ctx.drawImage(
        img2,
        imgX + cell_padding,
        imgY + cell_padding,
        imgWidth - cell_padding * 2,
        imgHeight - cell_padding * 2
      );
      if (!compact_mode) {
        ctx.strokeStyle = "#8F8F8F";
        ctx.lineWidth = 1;
        ctx.strokeRect(
          x22 + cell_padding,
          y22 + cell_padding,
          cellWidth - cell_padding * 2,
          cellHeight - cell_padding * 2
        );
      }
      ctx.filter = "none";
    }
    if (!anyHovered) {
      node2.pointerDown = null;
      node2.overIndex = null;
    }
    return;
  }
  const img = imgs[imageIndex];
  let w2 = img.naturalWidth;
  let h2 = img.naturalHeight;
  const scaleX = dw / w2;
  const scaleY = dh / h2;
  const scale = Math.min(scaleX, scaleY, 1);
  w2 *= scale;
  h2 *= scale;
  const x2 = (dw - w2) / 2;
  const y2 = (dh - h2) / 2 + shiftY;
  ctx.drawImage(img, x2, y2, w2, h2);
  if (allowImageSizeDraw) {
    ctx.fillStyle = LiteGraph.NODE_TEXT_COLOR;
    ctx.textAlign = "center";
    ctx.font = "10px sans-serif";
    const sizeText = `${Math.round(img.naturalWidth)} × ${Math.round(img.naturalHeight)}`;
    const textY = y2 + h2 + 10;
    ctx.fillText(sizeText, x2 + w2 / 2, textY);
  }
  const drawButton = /* @__PURE__ */ __name((x22, y22, sz, text2) => {
    const hovered = LiteGraph.isInsideRectangle(
      mouse[0],
      mouse[1],
      x22 + node2.pos[0],
      y22 + node2.pos[1],
      sz,
      sz
    );
    let fill2 = "#333";
    let textFill = "#fff";
    let isClicking = false;
    if (hovered) {
      canvas2.canvas.style.cursor = "pointer";
      if (canvas2.pointer_is_down) {
        fill2 = "#1e90ff";
        isClicking = true;
      } else {
        fill2 = "#eee";
        textFill = "#000";
      }
    }
    ctx.fillStyle = fill2;
    ctx.beginPath();
    ctx.roundRect(x22, y22, sz, sz, [4]);
    ctx.fill();
    ctx.fillStyle = textFill;
    ctx.font = "12px Arial";
    ctx.textAlign = "center";
    ctx.fillText(text2, x22 + 15, y22 + 20);
    return isClicking;
  }, "drawButton");
  if (!(numImages > 1)) return;
  const imageNum = (node2.imageIndex ?? 0) + 1;
  if (drawButton(dw - 40, dh + shiftY - 40, 30, `${imageNum}/${numImages}`)) {
    const i2 = imageNum >= numImages ? 0 : imageNum;
    if (!node2.pointerDown || node2.pointerDown.index !== i2) {
      node2.pointerDown = { index: i2, pos: [...mouse] };
    }
  }
  if (drawButton(dw - 40, shiftY + 10, 30, `x`)) {
    if (!node2.pointerDown || node2.pointerDown.index !== null) {
      node2.pointerDown = { index: null, pos: [...mouse] };
    }
  }
}, "renderPreview");
class ImagePreviewWidget {
  static {
    __name(this, "ImagePreviewWidget");
  }
  type;
  name;
  options;
  /** Dummy value to satisfy type requirements. */
  value;
  y = 0;
  /** Don't serialize the widget value. */
  serialize = false;
  constructor(name2, options2) {
    this.type = "custom";
    this.name = name2;
    this.options = options2;
    this.value = "";
  }
  draw(ctx, node2, _width, y2, _height) {
    renderPreview(ctx, node2, y2);
  }
  computeLayoutSize() {
    return {
      minHeight: 220,
      minWidth: 1
    };
  }
}
const useImagePreviewWidget = /* @__PURE__ */ __name(() => {
  const widgetConstructor = /* @__PURE__ */ __name((node2, inputSpec) => {
    return node2.addCustomWidget(
      new ImagePreviewWidget(inputSpec.name, {
        serialize: false
      })
    );
  }, "widgetConstructor");
  return widgetConstructor;
}, "useImagePreviewWidget");
const CANVAS_IMAGE_PREVIEW_WIDGET = "$$canvas-image-preview";
function useNodeCanvasImagePreview() {
  const imagePreviewWidget = useImagePreviewWidget();
  function showCanvasImagePreview(node2) {
    if (!node2.imgs?.length) return;
    if (!node2.widgets?.find((w2) => w2.name === CANVAS_IMAGE_PREVIEW_WIDGET)) {
      imagePreviewWidget(node2, {
        type: "IMAGE_PREVIEW",
        name: CANVAS_IMAGE_PREVIEW_WIDGET
      });
    }
  }
  __name(showCanvasImagePreview, "showCanvasImagePreview");
  function removeCanvasImagePreview(node2) {
    if (!node2.widgets) return;
    const widgetIdx = node2.widgets.findIndex(
      (w2) => w2.name === CANVAS_IMAGE_PREVIEW_WIDGET
    );
    if (widgetIdx > -1) {
      node2.widgets[widgetIdx].onRemove?.();
      node2.widgets.splice(widgetIdx, 1);
    }
  }
  __name(removeCanvasImagePreview, "removeCanvasImagePreview");
  return {
    showCanvasImagePreview,
    removeCanvasImagePreview
  };
}
__name(useNodeCanvasImagePreview, "useNodeCanvasImagePreview");
const ALWAYS_ENABLED_EXTENSIONS = [];
const ALWAYS_DISABLED_EXTENSIONS = [
  // pysssss.Locking is replaced by pin/unpin in ComfyUI core.
  // https://github.com/Comfy-Org/litegraph.js/pull/117
  "pysssss.Locking",
  // pysssss.SnapToGrid is replaced by Comfy.Graph.AlwaysSnapToGrid in ComfyUI core.
  // pysssss.SnapToGrid tries to write global app.shiftDown state, which is no longer
  // allowed since v1.3.12.
  // https://github.com/Comfy-Org/ComfyUI_frontend/issues/1176
  "pysssss.SnapToGrid",
  // Favicon status is implemented in ComfyUI core in v1.20.
  // https://github.com/Comfy-Org/ComfyUI_frontend/pull/3880
  "pysssss.FaviconStatus",
  "KJNodes.browserstatus"
];
const useExtensionStore = /* @__PURE__ */ defineStore("extension", () => {
  const extensionByName = ref$3({});
  const extensions = computed(() => Object.values(extensionByName.value));
  const disabledExtensionNames = ref$3(/* @__PURE__ */ new Set());
  const inactiveDisabledExtensionNames = computed(() => {
    return Array.from(disabledExtensionNames.value).filter(
      (name2) => !(name2 in extensionByName.value)
    );
  });
  const isExtensionInstalled = /* @__PURE__ */ __name((name2) => name2 in extensionByName.value, "isExtensionInstalled");
  const isExtensionEnabled = /* @__PURE__ */ __name((name2) => !disabledExtensionNames.value.has(name2), "isExtensionEnabled");
  const enabledExtensions = computed(() => {
    return extensions.value.filter((ext) => isExtensionEnabled(ext.name));
  });
  function isExtensionReadOnly(name2) {
    return ALWAYS_DISABLED_EXTENSIONS.includes(name2) || ALWAYS_ENABLED_EXTENSIONS.includes(name2);
  }
  __name(isExtensionReadOnly, "isExtensionReadOnly");
  function registerExtension(extension) {
    if (!extension.name) {
      throw new Error("Extensions must have a 'name' property.");
    }
    if (extensionByName.value[extension.name]) {
      throw new Error(`Extension named '${extension.name}' already registered.`);
    }
    if (disabledExtensionNames.value.has(extension.name)) {
      console.log(`Extension ${extension.name} is disabled.`);
    }
    extensionByName.value[extension.name] = markRaw(extension);
  }
  __name(registerExtension, "registerExtension");
  function loadDisabledExtensionNames(names) {
    disabledExtensionNames.value = new Set(names);
    for (const name2 of ALWAYS_DISABLED_EXTENSIONS) {
      disabledExtensionNames.value.add(name2);
    }
    for (const name2 of ALWAYS_ENABLED_EXTENSIONS) {
      disabledExtensionNames.value.delete(name2);
    }
  }
  __name(loadDisabledExtensionNames, "loadDisabledExtensionNames");
  const coreExtensionNames = ref$3([]);
  function captureCoreExtensions() {
    coreExtensionNames.value = extensions.value.map((ext) => ext.name);
  }
  __name(captureCoreExtensions, "captureCoreExtensions");
  function isCoreExtension(name2) {
    return coreExtensionNames.value.includes(name2);
  }
  __name(isCoreExtension, "isCoreExtension");
  const hasThirdPartyExtensions = computed(() => {
    return extensions.value.some((ext) => !isCoreExtension(ext.name));
  });
  return {
    extensions,
    enabledExtensions,
    inactiveDisabledExtensionNames,
    isExtensionInstalled,
    isExtensionEnabled,
    isExtensionReadOnly,
    registerExtension,
    loadDisabledExtensionNames,
    captureCoreExtensions,
    isCoreExtension,
    hasThirdPartyExtensions
  };
});
const CORE_MENU_COMMANDS = [
  [["Workflow"], ["Comfy.NewBlankWorkflow"]],
  [["Workflow"], ["Comfy.OpenWorkflow", "Comfy.BrowseTemplates"]],
  [
    ["Workflow"],
    [
      "Comfy.SaveWorkflow",
      "Comfy.SaveWorkflowAs",
      "Comfy.ExportWorkflow",
      "Comfy.ExportWorkflowAPI"
    ]
  ],
  [["Edit"], ["Comfy.Undo", "Comfy.Redo"]],
  [["Edit"], ["Comfy.RefreshNodeDefinitions"]],
  [["Edit"], ["Comfy.ClearWorkflow"]],
  [["Edit"], ["Comfy.OpenClipspace"]],
  [
    ["Help"],
    [
      "Comfy.Help.OpenComfyUIIssues",
      "Comfy.Help.OpenComfyUIDocs",
      "Comfy.Help.OpenComfyOrgDiscord",
      "Comfy.Help.OpenComfyUIForum"
    ]
  ],
  [
    ["Help"],
    ["Comfy.Help.AboutComfyUI", "Comfy.Feedback", "Comfy.ContactSupport"]
  ]
];
const useMenuItemStore = /* @__PURE__ */ defineStore("menuItem", () => {
  const commandStore = useCommandStore();
  const menuItems = ref$3([]);
  const registerMenuGroup = /* @__PURE__ */ __name((path, items) => {
    let currentLevel = menuItems.value;
    for (let i2 = 0; i2 < path.length; i2++) {
      const segment = path[i2];
      let found2 = currentLevel.find((item) => item.label === segment);
      if (!found2) {
        found2 = {
          label: segment,
          items: []
        };
        currentLevel.push(found2);
      }
      if (!found2.items) {
        found2.items = [];
      }
      currentLevel = found2.items;
    }
    if (currentLevel.length > 0) {
      currentLevel.push({
        separator: true
      });
    }
    currentLevel.push(...items);
  }, "registerMenuGroup");
  const registerCommands = /* @__PURE__ */ __name((path, commandIds) => {
    const items = commandIds.map((commandId) => commandStore.getCommand(commandId)).map(
      (command2) => ({
        command: /* @__PURE__ */ __name(() => commandStore.execute(command2.id), "command"),
        label: command2.menubarLabel,
        icon: command2.icon,
        tooltip: command2.tooltip,
        comfyCommand: command2
      })
    );
    registerMenuGroup(path, items);
  }, "registerCommands");
  const loadExtensionMenuCommands = /* @__PURE__ */ __name((extension) => {
    if (!extension.menuCommands) {
      return;
    }
    const extensionCommandIds = new Set(
      extension.commands?.map((command2) => command2.id) ?? []
    );
    extension.menuCommands.forEach((menuCommand) => {
      const commands2 = menuCommand.commands.filter(
        (command2) => extensionCommandIds.has(command2)
      );
      if (commands2.length) {
        registerCommands(menuCommand.path, commands2);
      }
    });
  }, "loadExtensionMenuCommands");
  const registerCoreMenuCommands = /* @__PURE__ */ __name(() => {
    for (const [path, commands2] of CORE_MENU_COMMANDS) {
      registerCommands(path, commands2);
    }
  }, "registerCoreMenuCommands");
  return {
    menuItems,
    registerMenuGroup,
    registerCommands,
    loadExtensionMenuCommands,
    registerCoreMenuCommands
  };
});
var addonFit$2 = { exports: {} };
var addonFit = addonFit$2.exports;
(function(module2, exports) {
  !function(e2, t2) {
    true ? module2.exports = t2() : false ? (void 0)([], t2) : true ? exports.FitAddon = t2() : e2.FitAddon = t2();
  }(self, () => (() => {
    "use strict";
    var e2 = {};
    return (() => {
      var t2 = e2;
      Object.defineProperty(t2, "__esModule", { value: true }), t2.FitAddon = void 0, t2.FitAddon = class {
        activate(e3) {
          this._terminal = e3;
        }
        dispose() {
        }
        fit() {
          const e3 = this.proposeDimensions();
          if (!e3 || !this._terminal || isNaN(e3.cols) || isNaN(e3.rows)) return;
          const t3 = this._terminal._core;
          this._terminal.rows === e3.rows && this._terminal.cols === e3.cols || (t3._renderService.clear(), this._terminal.resize(e3.cols, e3.rows));
        }
        proposeDimensions() {
          if (!this._terminal) return;
          if (!this._terminal.element || !this._terminal.element.parentElement) return;
          const e3 = this._terminal._core, t3 = e3._renderService.dimensions;
          if (0 === t3.css.cell.width || 0 === t3.css.cell.height) return;
          const r2 = 0 === this._terminal.options.scrollback ? 0 : e3.viewport.scrollBarWidth, i2 = window.getComputedStyle(this._terminal.element.parentElement), o2 = parseInt(i2.getPropertyValue("height")), s2 = Math.max(0, parseInt(i2.getPropertyValue("width"))), n2 = window.getComputedStyle(this._terminal.element), l2 = o2 - (parseInt(n2.getPropertyValue("padding-top")) + parseInt(n2.getPropertyValue("padding-bottom"))), a2 = s2 - (parseInt(n2.getPropertyValue("padding-right")) + parseInt(n2.getPropertyValue("padding-left"))) - r2;
          return { cols: Math.max(2, Math.floor(a2 / t3.css.cell.width)), rows: Math.max(1, Math.floor(l2 / t3.css.cell.height)) };
        }
      };
    })(), e2;
  })());
})(addonFit$2, addonFit$2.exports);
var addonFitExports = addonFit$2.exports;
const addonFit$1 = /* @__PURE__ */ getDefaultExportFromCjs(addonFitExports);
var xterm$2 = { exports: {} };
var xterm = xterm$2.exports;
(function(module2, exports) {
  !function(e2, t2) {
    if (true) module2.exports = t2();
    else if (false) (void 0)([], t2);
    else {
      var i2 = t2();
      for (var s2 in i2) (true ? exports : e2)[s2] = i2[s2];
    }
  }(globalThis, () => (() => {
    "use strict";
    var e2 = { 4567: function(e3, t3, i3) {
      var s3 = this && this.__decorate || function(e4, t4, i4, s4) {
        var r3, n3 = arguments.length, o3 = n3 < 3 ? t4 : null === s4 ? s4 = Object.getOwnPropertyDescriptor(t4, i4) : s4;
        if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) o3 = Reflect.decorate(e4, t4, i4, s4);
        else for (var a3 = e4.length - 1; a3 >= 0; a3--) (r3 = e4[a3]) && (o3 = (n3 < 3 ? r3(o3) : n3 > 3 ? r3(t4, i4, o3) : r3(t4, i4)) || o3);
        return n3 > 3 && o3 && Object.defineProperty(t4, i4, o3), o3;
      }, r2 = this && this.__param || function(e4, t4) {
        return function(i4, s4) {
          t4(i4, s4, e4);
        };
      };
      Object.defineProperty(t3, "__esModule", { value: true }), t3.AccessibilityManager = void 0;
      const n2 = i3(9042), o2 = i3(9924), a2 = i3(844), h2 = i3(4725), c2 = i3(2585), l2 = i3(3656);
      let d2 = t3.AccessibilityManager = class extends a2.Disposable {
        constructor(e4, t4, i4, s4) {
          super(), this._terminal = e4, this._coreBrowserService = i4, this._renderService = s4, this._rowColumns = /* @__PURE__ */ new WeakMap(), this._liveRegionLineCount = 0, this._charsToConsume = [], this._charsToAnnounce = "", this._accessibilityContainer = this._coreBrowserService.mainDocument.createElement("div"), this._accessibilityContainer.classList.add("xterm-accessibility"), this._rowContainer = this._coreBrowserService.mainDocument.createElement("div"), this._rowContainer.setAttribute("role", "list"), this._rowContainer.classList.add("xterm-accessibility-tree"), this._rowElements = [];
          for (let e5 = 0; e5 < this._terminal.rows; e5++) this._rowElements[e5] = this._createAccessibilityTreeNode(), this._rowContainer.appendChild(this._rowElements[e5]);
          if (this._topBoundaryFocusListener = (e5) => this._handleBoundaryFocus(e5, 0), this._bottomBoundaryFocusListener = (e5) => this._handleBoundaryFocus(e5, 1), this._rowElements[0].addEventListener("focus", this._topBoundaryFocusListener), this._rowElements[this._rowElements.length - 1].addEventListener("focus", this._bottomBoundaryFocusListener), this._refreshRowsDimensions(), this._accessibilityContainer.appendChild(this._rowContainer), this._liveRegion = this._coreBrowserService.mainDocument.createElement("div"), this._liveRegion.classList.add("live-region"), this._liveRegion.setAttribute("aria-live", "assertive"), this._accessibilityContainer.appendChild(this._liveRegion), this._liveRegionDebouncer = this.register(new o2.TimeBasedDebouncer(this._renderRows.bind(this))), !this._terminal.element) throw new Error("Cannot enable accessibility before Terminal.open");
          this._terminal.element.insertAdjacentElement("afterbegin", this._accessibilityContainer), this.register(this._terminal.onResize((e5) => this._handleResize(e5.rows))), this.register(this._terminal.onRender((e5) => this._refreshRows(e5.start, e5.end))), this.register(this._terminal.onScroll(() => this._refreshRows())), this.register(this._terminal.onA11yChar((e5) => this._handleChar(e5))), this.register(this._terminal.onLineFeed(() => this._handleChar("\n"))), this.register(this._terminal.onA11yTab((e5) => this._handleTab(e5))), this.register(this._terminal.onKey((e5) => this._handleKey(e5.key))), this.register(this._terminal.onBlur(() => this._clearLiveRegion())), this.register(this._renderService.onDimensionsChange(() => this._refreshRowsDimensions())), this.register((0, l2.addDisposableDomListener)(document, "selectionchange", () => this._handleSelectionChange())), this.register(this._coreBrowserService.onDprChange(() => this._refreshRowsDimensions())), this._refreshRows(), this.register((0, a2.toDisposable)(() => {
            this._accessibilityContainer.remove(), this._rowElements.length = 0;
          }));
        }
        _handleTab(e4) {
          for (let t4 = 0; t4 < e4; t4++) this._handleChar(" ");
        }
        _handleChar(e4) {
          this._liveRegionLineCount < 21 && (this._charsToConsume.length > 0 ? this._charsToConsume.shift() !== e4 && (this._charsToAnnounce += e4) : this._charsToAnnounce += e4, "\n" === e4 && (this._liveRegionLineCount++, 21 === this._liveRegionLineCount && (this._liveRegion.textContent += n2.tooMuchOutput)));
        }
        _clearLiveRegion() {
          this._liveRegion.textContent = "", this._liveRegionLineCount = 0;
        }
        _handleKey(e4) {
          this._clearLiveRegion(), /\p{Control}/u.test(e4) || this._charsToConsume.push(e4);
        }
        _refreshRows(e4, t4) {
          this._liveRegionDebouncer.refresh(e4, t4, this._terminal.rows);
        }
        _renderRows(e4, t4) {
          const i4 = this._terminal.buffer, s4 = i4.lines.length.toString();
          for (let r3 = e4; r3 <= t4; r3++) {
            const e5 = i4.lines.get(i4.ydisp + r3), t5 = [], n3 = e5?.translateToString(true, void 0, void 0, t5) || "", o3 = (i4.ydisp + r3 + 1).toString(), a3 = this._rowElements[r3];
            a3 && (0 === n3.length ? (a3.innerText = " ", this._rowColumns.set(a3, [0, 1])) : (a3.textContent = n3, this._rowColumns.set(a3, t5)), a3.setAttribute("aria-posinset", o3), a3.setAttribute("aria-setsize", s4));
          }
          this._announceCharacters();
        }
        _announceCharacters() {
          0 !== this._charsToAnnounce.length && (this._liveRegion.textContent += this._charsToAnnounce, this._charsToAnnounce = "");
        }
        _handleBoundaryFocus(e4, t4) {
          const i4 = e4.target, s4 = this._rowElements[0 === t4 ? 1 : this._rowElements.length - 2];
          if (i4.getAttribute("aria-posinset") === (0 === t4 ? "1" : `${this._terminal.buffer.lines.length}`)) return;
          if (e4.relatedTarget !== s4) return;
          let r3, n3;
          if (0 === t4 ? (r3 = i4, n3 = this._rowElements.pop(), this._rowContainer.removeChild(n3)) : (r3 = this._rowElements.shift(), n3 = i4, this._rowContainer.removeChild(r3)), r3.removeEventListener("focus", this._topBoundaryFocusListener), n3.removeEventListener("focus", this._bottomBoundaryFocusListener), 0 === t4) {
            const e5 = this._createAccessibilityTreeNode();
            this._rowElements.unshift(e5), this._rowContainer.insertAdjacentElement("afterbegin", e5);
          } else {
            const e5 = this._createAccessibilityTreeNode();
            this._rowElements.push(e5), this._rowContainer.appendChild(e5);
          }
          this._rowElements[0].addEventListener("focus", this._topBoundaryFocusListener), this._rowElements[this._rowElements.length - 1].addEventListener("focus", this._bottomBoundaryFocusListener), this._terminal.scrollLines(0 === t4 ? -1 : 1), this._rowElements[0 === t4 ? 1 : this._rowElements.length - 2].focus(), e4.preventDefault(), e4.stopImmediatePropagation();
        }
        _handleSelectionChange() {
          if (0 === this._rowElements.length) return;
          const e4 = document.getSelection();
          if (!e4) return;
          if (e4.isCollapsed) return void (this._rowContainer.contains(e4.anchorNode) && this._terminal.clearSelection());
          if (!e4.anchorNode || !e4.focusNode) return void console.error("anchorNode and/or focusNode are null");
          let t4 = { node: e4.anchorNode, offset: e4.anchorOffset }, i4 = { node: e4.focusNode, offset: e4.focusOffset };
          if ((t4.node.compareDocumentPosition(i4.node) & Node.DOCUMENT_POSITION_PRECEDING || t4.node === i4.node && t4.offset > i4.offset) && ([t4, i4] = [i4, t4]), t4.node.compareDocumentPosition(this._rowElements[0]) & (Node.DOCUMENT_POSITION_CONTAINED_BY | Node.DOCUMENT_POSITION_FOLLOWING) && (t4 = { node: this._rowElements[0].childNodes[0], offset: 0 }), !this._rowContainer.contains(t4.node)) return;
          const s4 = this._rowElements.slice(-1)[0];
          if (i4.node.compareDocumentPosition(s4) & (Node.DOCUMENT_POSITION_CONTAINED_BY | Node.DOCUMENT_POSITION_PRECEDING) && (i4 = { node: s4, offset: s4.textContent?.length ?? 0 }), !this._rowContainer.contains(i4.node)) return;
          const r3 = /* @__PURE__ */ __name(({ node: e5, offset: t5 }) => {
            const i5 = e5 instanceof Text ? e5.parentNode : e5;
            let s5 = parseInt(i5?.getAttribute("aria-posinset"), 10) - 1;
            if (isNaN(s5)) return console.warn("row is invalid. Race condition?"), null;
            const r4 = this._rowColumns.get(i5);
            if (!r4) return console.warn("columns is null. Race condition?"), null;
            let n4 = t5 < r4.length ? r4[t5] : r4.slice(-1)[0] + 1;
            return n4 >= this._terminal.cols && (++s5, n4 = 0), { row: s5, column: n4 };
          }, "r"), n3 = r3(t4), o3 = r3(i4);
          if (n3 && o3) {
            if (n3.row > o3.row || n3.row === o3.row && n3.column >= o3.column) throw new Error("invalid range");
            this._terminal.select(n3.column, n3.row, (o3.row - n3.row) * this._terminal.cols - n3.column + o3.column);
          }
        }
        _handleResize(e4) {
          this._rowElements[this._rowElements.length - 1].removeEventListener("focus", this._bottomBoundaryFocusListener);
          for (let e5 = this._rowContainer.children.length; e5 < this._terminal.rows; e5++) this._rowElements[e5] = this._createAccessibilityTreeNode(), this._rowContainer.appendChild(this._rowElements[e5]);
          for (; this._rowElements.length > e4; ) this._rowContainer.removeChild(this._rowElements.pop());
          this._rowElements[this._rowElements.length - 1].addEventListener("focus", this._bottomBoundaryFocusListener), this._refreshRowsDimensions();
        }
        _createAccessibilityTreeNode() {
          const e4 = this._coreBrowserService.mainDocument.createElement("div");
          return e4.setAttribute("role", "listitem"), e4.tabIndex = -1, this._refreshRowDimensions(e4), e4;
        }
        _refreshRowsDimensions() {
          if (this._renderService.dimensions.css.cell.height) {
            this._accessibilityContainer.style.width = `${this._renderService.dimensions.css.canvas.width}px`, this._rowElements.length !== this._terminal.rows && this._handleResize(this._terminal.rows);
            for (let e4 = 0; e4 < this._terminal.rows; e4++) this._refreshRowDimensions(this._rowElements[e4]);
          }
        }
        _refreshRowDimensions(e4) {
          e4.style.height = `${this._renderService.dimensions.css.cell.height}px`;
        }
      };
      t3.AccessibilityManager = d2 = s3([r2(1, c2.IInstantiationService), r2(2, h2.ICoreBrowserService), r2(3, h2.IRenderService)], d2);
    }, 3614: (e3, t3) => {
      function i3(e4) {
        return e4.replace(/\r?\n/g, "\r");
      }
      __name(i3, "i");
      function s3(e4, t4) {
        return t4 ? "\x1B[200~" + e4 + "\x1B[201~" : e4;
      }
      __name(s3, "s");
      function r2(e4, t4, r3, n3) {
        e4 = s3(e4 = i3(e4), r3.decPrivateModes.bracketedPasteMode && true !== n3.rawOptions.ignoreBracketedPasteMode), r3.triggerDataEvent(e4, true), t4.value = "";
      }
      __name(r2, "r");
      function n2(e4, t4, i4) {
        const s4 = i4.getBoundingClientRect(), r3 = e4.clientX - s4.left - 10, n3 = e4.clientY - s4.top - 10;
        t4.style.width = "20px", t4.style.height = "20px", t4.style.left = `${r3}px`, t4.style.top = `${n3}px`, t4.style.zIndex = "1000", t4.focus();
      }
      __name(n2, "n");
      Object.defineProperty(t3, "__esModule", { value: true }), t3.rightClickHandler = t3.moveTextAreaUnderMouseCursor = t3.paste = t3.handlePasteEvent = t3.copyHandler = t3.bracketTextForPaste = t3.prepareTextForTerminal = void 0, t3.prepareTextForTerminal = i3, t3.bracketTextForPaste = s3, t3.copyHandler = function(e4, t4) {
        e4.clipboardData && e4.clipboardData.setData("text/plain", t4.selectionText), e4.preventDefault();
      }, t3.handlePasteEvent = function(e4, t4, i4, s4) {
        e4.stopPropagation(), e4.clipboardData && r2(e4.clipboardData.getData("text/plain"), t4, i4, s4);
      }, t3.paste = r2, t3.moveTextAreaUnderMouseCursor = n2, t3.rightClickHandler = function(e4, t4, i4, s4, r3) {
        n2(e4, t4, i4), r3 && s4.rightClickSelect(e4), t4.value = s4.selectionText, t4.select();
      };
    }, 7239: (e3, t3, i3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.ColorContrastCache = void 0;
      const s3 = i3(1505);
      t3.ColorContrastCache = class {
        constructor() {
          this._color = new s3.TwoKeyMap(), this._css = new s3.TwoKeyMap();
        }
        setCss(e4, t4, i4) {
          this._css.set(e4, t4, i4);
        }
        getCss(e4, t4) {
          return this._css.get(e4, t4);
        }
        setColor(e4, t4, i4) {
          this._color.set(e4, t4, i4);
        }
        getColor(e4, t4) {
          return this._color.get(e4, t4);
        }
        clear() {
          this._color.clear(), this._css.clear();
        }
      };
    }, 3656: (e3, t3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.addDisposableDomListener = void 0, t3.addDisposableDomListener = function(e4, t4, i3, s3) {
        e4.addEventListener(t4, i3, s3);
        let r2 = false;
        return { dispose: /* @__PURE__ */ __name(() => {
          r2 || (r2 = true, e4.removeEventListener(t4, i3, s3));
        }, "dispose") };
      };
    }, 3551: function(e3, t3, i3) {
      var s3 = this && this.__decorate || function(e4, t4, i4, s4) {
        var r3, n3 = arguments.length, o3 = n3 < 3 ? t4 : null === s4 ? s4 = Object.getOwnPropertyDescriptor(t4, i4) : s4;
        if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) o3 = Reflect.decorate(e4, t4, i4, s4);
        else for (var a3 = e4.length - 1; a3 >= 0; a3--) (r3 = e4[a3]) && (o3 = (n3 < 3 ? r3(o3) : n3 > 3 ? r3(t4, i4, o3) : r3(t4, i4)) || o3);
        return n3 > 3 && o3 && Object.defineProperty(t4, i4, o3), o3;
      }, r2 = this && this.__param || function(e4, t4) {
        return function(i4, s4) {
          t4(i4, s4, e4);
        };
      };
      Object.defineProperty(t3, "__esModule", { value: true }), t3.Linkifier = void 0;
      const n2 = i3(3656), o2 = i3(8460), a2 = i3(844), h2 = i3(2585), c2 = i3(4725);
      let l2 = t3.Linkifier = class extends a2.Disposable {
        get currentLink() {
          return this._currentLink;
        }
        constructor(e4, t4, i4, s4, r3) {
          super(), this._element = e4, this._mouseService = t4, this._renderService = i4, this._bufferService = s4, this._linkProviderService = r3, this._linkCacheDisposables = [], this._isMouseOut = true, this._wasResized = false, this._activeLine = -1, this._onShowLinkUnderline = this.register(new o2.EventEmitter()), this.onShowLinkUnderline = this._onShowLinkUnderline.event, this._onHideLinkUnderline = this.register(new o2.EventEmitter()), this.onHideLinkUnderline = this._onHideLinkUnderline.event, this.register((0, a2.getDisposeArrayDisposable)(this._linkCacheDisposables)), this.register((0, a2.toDisposable)(() => {
            this._lastMouseEvent = void 0, this._activeProviderReplies?.clear();
          })), this.register(this._bufferService.onResize(() => {
            this._clearCurrentLink(), this._wasResized = true;
          })), this.register((0, n2.addDisposableDomListener)(this._element, "mouseleave", () => {
            this._isMouseOut = true, this._clearCurrentLink();
          })), this.register((0, n2.addDisposableDomListener)(this._element, "mousemove", this._handleMouseMove.bind(this))), this.register((0, n2.addDisposableDomListener)(this._element, "mousedown", this._handleMouseDown.bind(this))), this.register((0, n2.addDisposableDomListener)(this._element, "mouseup", this._handleMouseUp.bind(this)));
        }
        _handleMouseMove(e4) {
          this._lastMouseEvent = e4;
          const t4 = this._positionFromMouseEvent(e4, this._element, this._mouseService);
          if (!t4) return;
          this._isMouseOut = false;
          const i4 = e4.composedPath();
          for (let e5 = 0; e5 < i4.length; e5++) {
            const t5 = i4[e5];
            if (t5.classList.contains("xterm")) break;
            if (t5.classList.contains("xterm-hover")) return;
          }
          this._lastBufferCell && t4.x === this._lastBufferCell.x && t4.y === this._lastBufferCell.y || (this._handleHover(t4), this._lastBufferCell = t4);
        }
        _handleHover(e4) {
          if (this._activeLine !== e4.y || this._wasResized) return this._clearCurrentLink(), this._askForLink(e4, false), void (this._wasResized = false);
          this._currentLink && this._linkAtPosition(this._currentLink.link, e4) || (this._clearCurrentLink(), this._askForLink(e4, true));
        }
        _askForLink(e4, t4) {
          this._activeProviderReplies && t4 || (this._activeProviderReplies?.forEach((e5) => {
            e5?.forEach((e6) => {
              e6.link.dispose && e6.link.dispose();
            });
          }), this._activeProviderReplies = /* @__PURE__ */ new Map(), this._activeLine = e4.y);
          let i4 = false;
          for (const [s4, r3] of this._linkProviderService.linkProviders.entries()) if (t4) {
            const t5 = this._activeProviderReplies?.get(s4);
            t5 && (i4 = this._checkLinkProviderResult(s4, e4, i4));
          } else r3.provideLinks(e4.y, (t5) => {
            if (this._isMouseOut) return;
            const r4 = t5?.map((e5) => ({ link: e5 }));
            this._activeProviderReplies?.set(s4, r4), i4 = this._checkLinkProviderResult(s4, e4, i4), this._activeProviderReplies?.size === this._linkProviderService.linkProviders.length && this._removeIntersectingLinks(e4.y, this._activeProviderReplies);
          });
        }
        _removeIntersectingLinks(e4, t4) {
          const i4 = /* @__PURE__ */ new Set();
          for (let s4 = 0; s4 < t4.size; s4++) {
            const r3 = t4.get(s4);
            if (r3) for (let t5 = 0; t5 < r3.length; t5++) {
              const s5 = r3[t5], n3 = s5.link.range.start.y < e4 ? 0 : s5.link.range.start.x, o3 = s5.link.range.end.y > e4 ? this._bufferService.cols : s5.link.range.end.x;
              for (let e5 = n3; e5 <= o3; e5++) {
                if (i4.has(e5)) {
                  r3.splice(t5--, 1);
                  break;
                }
                i4.add(e5);
              }
            }
          }
        }
        _checkLinkProviderResult(e4, t4, i4) {
          if (!this._activeProviderReplies) return i4;
          const s4 = this._activeProviderReplies.get(e4);
          let r3 = false;
          for (let t5 = 0; t5 < e4; t5++) this._activeProviderReplies.has(t5) && !this._activeProviderReplies.get(t5) || (r3 = true);
          if (!r3 && s4) {
            const e5 = s4.find((e6) => this._linkAtPosition(e6.link, t4));
            e5 && (i4 = true, this._handleNewLink(e5));
          }
          if (this._activeProviderReplies.size === this._linkProviderService.linkProviders.length && !i4) for (let e5 = 0; e5 < this._activeProviderReplies.size; e5++) {
            const s5 = this._activeProviderReplies.get(e5)?.find((e6) => this._linkAtPosition(e6.link, t4));
            if (s5) {
              i4 = true, this._handleNewLink(s5);
              break;
            }
          }
          return i4;
        }
        _handleMouseDown() {
          this._mouseDownLink = this._currentLink;
        }
        _handleMouseUp(e4) {
          if (!this._currentLink) return;
          const t4 = this._positionFromMouseEvent(e4, this._element, this._mouseService);
          t4 && this._mouseDownLink === this._currentLink && this._linkAtPosition(this._currentLink.link, t4) && this._currentLink.link.activate(e4, this._currentLink.link.text);
        }
        _clearCurrentLink(e4, t4) {
          this._currentLink && this._lastMouseEvent && (!e4 || !t4 || this._currentLink.link.range.start.y >= e4 && this._currentLink.link.range.end.y <= t4) && (this._linkLeave(this._element, this._currentLink.link, this._lastMouseEvent), this._currentLink = void 0, (0, a2.disposeArray)(this._linkCacheDisposables));
        }
        _handleNewLink(e4) {
          if (!this._lastMouseEvent) return;
          const t4 = this._positionFromMouseEvent(this._lastMouseEvent, this._element, this._mouseService);
          t4 && this._linkAtPosition(e4.link, t4) && (this._currentLink = e4, this._currentLink.state = { decorations: { underline: void 0 === e4.link.decorations || e4.link.decorations.underline, pointerCursor: void 0 === e4.link.decorations || e4.link.decorations.pointerCursor }, isHovered: true }, this._linkHover(this._element, e4.link, this._lastMouseEvent), e4.link.decorations = {}, Object.defineProperties(e4.link.decorations, { pointerCursor: { get: /* @__PURE__ */ __name(() => this._currentLink?.state?.decorations.pointerCursor, "get"), set: /* @__PURE__ */ __name((e5) => {
            this._currentLink?.state && this._currentLink.state.decorations.pointerCursor !== e5 && (this._currentLink.state.decorations.pointerCursor = e5, this._currentLink.state.isHovered && this._element.classList.toggle("xterm-cursor-pointer", e5));
          }, "set") }, underline: { get: /* @__PURE__ */ __name(() => this._currentLink?.state?.decorations.underline, "get"), set: /* @__PURE__ */ __name((t5) => {
            this._currentLink?.state && this._currentLink?.state?.decorations.underline !== t5 && (this._currentLink.state.decorations.underline = t5, this._currentLink.state.isHovered && this._fireUnderlineEvent(e4.link, t5));
          }, "set") } }), this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange((e5) => {
            if (!this._currentLink) return;
            const t5 = 0 === e5.start ? 0 : e5.start + 1 + this._bufferService.buffer.ydisp, i4 = this._bufferService.buffer.ydisp + 1 + e5.end;
            if (this._currentLink.link.range.start.y >= t5 && this._currentLink.link.range.end.y <= i4 && (this._clearCurrentLink(t5, i4), this._lastMouseEvent)) {
              const e6 = this._positionFromMouseEvent(this._lastMouseEvent, this._element, this._mouseService);
              e6 && this._askForLink(e6, false);
            }
          })));
        }
        _linkHover(e4, t4, i4) {
          this._currentLink?.state && (this._currentLink.state.isHovered = true, this._currentLink.state.decorations.underline && this._fireUnderlineEvent(t4, true), this._currentLink.state.decorations.pointerCursor && e4.classList.add("xterm-cursor-pointer")), t4.hover && t4.hover(i4, t4.text);
        }
        _fireUnderlineEvent(e4, t4) {
          const i4 = e4.range, s4 = this._bufferService.buffer.ydisp, r3 = this._createLinkUnderlineEvent(i4.start.x - 1, i4.start.y - s4 - 1, i4.end.x, i4.end.y - s4 - 1, void 0);
          (t4 ? this._onShowLinkUnderline : this._onHideLinkUnderline).fire(r3);
        }
        _linkLeave(e4, t4, i4) {
          this._currentLink?.state && (this._currentLink.state.isHovered = false, this._currentLink.state.decorations.underline && this._fireUnderlineEvent(t4, false), this._currentLink.state.decorations.pointerCursor && e4.classList.remove("xterm-cursor-pointer")), t4.leave && t4.leave(i4, t4.text);
        }
        _linkAtPosition(e4, t4) {
          const i4 = e4.range.start.y * this._bufferService.cols + e4.range.start.x, s4 = e4.range.end.y * this._bufferService.cols + e4.range.end.x, r3 = t4.y * this._bufferService.cols + t4.x;
          return i4 <= r3 && r3 <= s4;
        }
        _positionFromMouseEvent(e4, t4, i4) {
          const s4 = i4.getCoords(e4, t4, this._bufferService.cols, this._bufferService.rows);
          if (s4) return { x: s4[0], y: s4[1] + this._bufferService.buffer.ydisp };
        }
        _createLinkUnderlineEvent(e4, t4, i4, s4, r3) {
          return { x1: e4, y1: t4, x2: i4, y2: s4, cols: this._bufferService.cols, fg: r3 };
        }
      };
      t3.Linkifier = l2 = s3([r2(1, c2.IMouseService), r2(2, c2.IRenderService), r2(3, h2.IBufferService), r2(4, c2.ILinkProviderService)], l2);
    }, 9042: (e3, t3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.tooMuchOutput = t3.promptLabel = void 0, t3.promptLabel = "Terminal input", t3.tooMuchOutput = "Too much output to announce, navigate to rows manually to read";
    }, 3730: function(e3, t3, i3) {
      var s3 = this && this.__decorate || function(e4, t4, i4, s4) {
        var r3, n3 = arguments.length, o3 = n3 < 3 ? t4 : null === s4 ? s4 = Object.getOwnPropertyDescriptor(t4, i4) : s4;
        if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) o3 = Reflect.decorate(e4, t4, i4, s4);
        else for (var a3 = e4.length - 1; a3 >= 0; a3--) (r3 = e4[a3]) && (o3 = (n3 < 3 ? r3(o3) : n3 > 3 ? r3(t4, i4, o3) : r3(t4, i4)) || o3);
        return n3 > 3 && o3 && Object.defineProperty(t4, i4, o3), o3;
      }, r2 = this && this.__param || function(e4, t4) {
        return function(i4, s4) {
          t4(i4, s4, e4);
        };
      };
      Object.defineProperty(t3, "__esModule", { value: true }), t3.OscLinkProvider = void 0;
      const n2 = i3(511), o2 = i3(2585);
      let a2 = t3.OscLinkProvider = class {
        constructor(e4, t4, i4) {
          this._bufferService = e4, this._optionsService = t4, this._oscLinkService = i4;
        }
        provideLinks(e4, t4) {
          const i4 = this._bufferService.buffer.lines.get(e4 - 1);
          if (!i4) return void t4(void 0);
          const s4 = [], r3 = this._optionsService.rawOptions.linkHandler, o3 = new n2.CellData(), a3 = i4.getTrimmedLength();
          let c2 = -1, l2 = -1, d2 = false;
          for (let t5 = 0; t5 < a3; t5++) if (-1 !== l2 || i4.hasContent(t5)) {
            if (i4.loadCell(t5, o3), o3.hasExtendedAttrs() && o3.extended.urlId) {
              if (-1 === l2) {
                l2 = t5, c2 = o3.extended.urlId;
                continue;
              }
              d2 = o3.extended.urlId !== c2;
            } else -1 !== l2 && (d2 = true);
            if (d2 || -1 !== l2 && t5 === a3 - 1) {
              const i5 = this._oscLinkService.getLinkData(c2)?.uri;
              if (i5) {
                const n3 = { start: { x: l2 + 1, y: e4 }, end: { x: t5 + (d2 || t5 !== a3 - 1 ? 0 : 1), y: e4 } };
                let o4 = false;
                if (!r3?.allowNonHttpProtocols) try {
                  const e5 = new URL(i5);
                  ["http:", "https:"].includes(e5.protocol) || (o4 = true);
                } catch (e5) {
                  o4 = true;
                }
                o4 || s4.push({ text: i5, range: n3, activate: /* @__PURE__ */ __name((e5, t6) => r3 ? r3.activate(e5, t6, n3) : h2(0, t6), "activate"), hover: /* @__PURE__ */ __name((e5, t6) => r3?.hover?.(e5, t6, n3), "hover"), leave: /* @__PURE__ */ __name((e5, t6) => r3?.leave?.(e5, t6, n3), "leave") });
              }
              d2 = false, o3.hasExtendedAttrs() && o3.extended.urlId ? (l2 = t5, c2 = o3.extended.urlId) : (l2 = -1, c2 = -1);
            }
          }
          t4(s4);
        }
      };
      function h2(e4, t4) {
        if (confirm(`Do you want to navigate to ${t4}?

WARNING: This link could potentially be dangerous`)) {
          const e5 = window.open();
          if (e5) {
            try {
              e5.opener = null;
            } catch {
            }
            e5.location.href = t4;
          } else console.warn("Opening link blocked as opener could not be cleared");
        }
      }
      __name(h2, "h");
      t3.OscLinkProvider = a2 = s3([r2(0, o2.IBufferService), r2(1, o2.IOptionsService), r2(2, o2.IOscLinkService)], a2);
    }, 6193: (e3, t3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.RenderDebouncer = void 0, t3.RenderDebouncer = class {
        constructor(e4, t4) {
          this._renderCallback = e4, this._coreBrowserService = t4, this._refreshCallbacks = [];
        }
        dispose() {
          this._animationFrame && (this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame), this._animationFrame = void 0);
        }
        addRefreshCallback(e4) {
          return this._refreshCallbacks.push(e4), this._animationFrame || (this._animationFrame = this._coreBrowserService.window.requestAnimationFrame(() => this._innerRefresh())), this._animationFrame;
        }
        refresh(e4, t4, i3) {
          this._rowCount = i3, e4 = void 0 !== e4 ? e4 : 0, t4 = void 0 !== t4 ? t4 : this._rowCount - 1, this._rowStart = void 0 !== this._rowStart ? Math.min(this._rowStart, e4) : e4, this._rowEnd = void 0 !== this._rowEnd ? Math.max(this._rowEnd, t4) : t4, this._animationFrame || (this._animationFrame = this._coreBrowserService.window.requestAnimationFrame(() => this._innerRefresh()));
        }
        _innerRefresh() {
          if (this._animationFrame = void 0, void 0 === this._rowStart || void 0 === this._rowEnd || void 0 === this._rowCount) return void this._runRefreshCallbacks();
          const e4 = Math.max(this._rowStart, 0), t4 = Math.min(this._rowEnd, this._rowCount - 1);
          this._rowStart = void 0, this._rowEnd = void 0, this._renderCallback(e4, t4), this._runRefreshCallbacks();
        }
        _runRefreshCallbacks() {
          for (const e4 of this._refreshCallbacks) e4(0);
          this._refreshCallbacks = [];
        }
      };
    }, 3236: (e3, t3, i3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.Terminal = void 0;
      const s3 = i3(3614), r2 = i3(3656), n2 = i3(3551), o2 = i3(9042), a2 = i3(3730), h2 = i3(1680), c2 = i3(3107), l2 = i3(5744), d2 = i3(2950), _2 = i3(1296), u2 = i3(428), f2 = i3(4269), v2 = i3(5114), p2 = i3(8934), g2 = i3(3230), m2 = i3(9312), S2 = i3(4725), C2 = i3(6731), b2 = i3(8055), w2 = i3(8969), y2 = i3(8460), E = i3(844), k2 = i3(6114), L2 = i3(8437), D2 = i3(2584), R = i3(7399), x2 = i3(5941), A2 = i3(9074), B2 = i3(2585), T2 = i3(5435), M2 = i3(4567), O2 = i3(779);
      class P2 extends w2.CoreTerminal {
        static {
          __name(this, "P");
        }
        get onFocus() {
          return this._onFocus.event;
        }
        get onBlur() {
          return this._onBlur.event;
        }
        get onA11yChar() {
          return this._onA11yCharEmitter.event;
        }
        get onA11yTab() {
          return this._onA11yTabEmitter.event;
        }
        get onWillOpen() {
          return this._onWillOpen.event;
        }
        constructor(e4 = {}) {
          super(e4), this.browser = k2, this._keyDownHandled = false, this._keyDownSeen = false, this._keyPressHandled = false, this._unprocessedDeadKey = false, this._accessibilityManager = this.register(new E.MutableDisposable()), this._onCursorMove = this.register(new y2.EventEmitter()), this.onCursorMove = this._onCursorMove.event, this._onKey = this.register(new y2.EventEmitter()), this.onKey = this._onKey.event, this._onRender = this.register(new y2.EventEmitter()), this.onRender = this._onRender.event, this._onSelectionChange = this.register(new y2.EventEmitter()), this.onSelectionChange = this._onSelectionChange.event, this._onTitleChange = this.register(new y2.EventEmitter()), this.onTitleChange = this._onTitleChange.event, this._onBell = this.register(new y2.EventEmitter()), this.onBell = this._onBell.event, this._onFocus = this.register(new y2.EventEmitter()), this._onBlur = this.register(new y2.EventEmitter()), this._onA11yCharEmitter = this.register(new y2.EventEmitter()), this._onA11yTabEmitter = this.register(new y2.EventEmitter()), this._onWillOpen = this.register(new y2.EventEmitter()), this._setup(), this._decorationService = this._instantiationService.createInstance(A2.DecorationService), this._instantiationService.setService(B2.IDecorationService, this._decorationService), this._linkProviderService = this._instantiationService.createInstance(O2.LinkProviderService), this._instantiationService.setService(S2.ILinkProviderService, this._linkProviderService), this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(a2.OscLinkProvider)), this.register(this._inputHandler.onRequestBell(() => this._onBell.fire())), this.register(this._inputHandler.onRequestRefreshRows((e5, t4) => this.refresh(e5, t4))), this.register(this._inputHandler.onRequestSendFocus(() => this._reportFocus())), this.register(this._inputHandler.onRequestReset(() => this.reset())), this.register(this._inputHandler.onRequestWindowsOptionsReport((e5) => this._reportWindowsOptions(e5))), this.register(this._inputHandler.onColor((e5) => this._handleColorEvent(e5))), this.register((0, y2.forwardEvent)(this._inputHandler.onCursorMove, this._onCursorMove)), this.register((0, y2.forwardEvent)(this._inputHandler.onTitleChange, this._onTitleChange)), this.register((0, y2.forwardEvent)(this._inputHandler.onA11yChar, this._onA11yCharEmitter)), this.register((0, y2.forwardEvent)(this._inputHandler.onA11yTab, this._onA11yTabEmitter)), this.register(this._bufferService.onResize((e5) => this._afterResize(e5.cols, e5.rows))), this.register((0, E.toDisposable)(() => {
            this._customKeyEventHandler = void 0, this.element?.parentNode?.removeChild(this.element);
          }));
        }
        _handleColorEvent(e4) {
          if (this._themeService) for (const t4 of e4) {
            let e5, i4 = "";
            switch (t4.index) {
              case 256:
                e5 = "foreground", i4 = "10";
                break;
              case 257:
                e5 = "background", i4 = "11";
                break;
              case 258:
                e5 = "cursor", i4 = "12";
                break;
              default:
                e5 = "ansi", i4 = "4;" + t4.index;
            }
            switch (t4.type) {
              case 0:
                const s4 = b2.color.toColorRGB("ansi" === e5 ? this._themeService.colors.ansi[t4.index] : this._themeService.colors[e5]);
                this.coreService.triggerDataEvent(`${D2.C0.ESC}]${i4};${(0, x2.toRgbString)(s4)}${D2.C1_ESCAPED.ST}`);
                break;
              case 1:
                if ("ansi" === e5) this._themeService.modifyColors((e6) => e6.ansi[t4.index] = b2.channels.toColor(...t4.color));
                else {
                  const i5 = e5;
                  this._themeService.modifyColors((e6) => e6[i5] = b2.channels.toColor(...t4.color));
                }
                break;
              case 2:
                this._themeService.restoreColor(t4.index);
            }
          }
        }
        _setup() {
          super._setup(), this._customKeyEventHandler = void 0;
        }
        get buffer() {
          return this.buffers.active;
        }
        focus() {
          this.textarea && this.textarea.focus({ preventScroll: true });
        }
        _handleScreenReaderModeOptionChange(e4) {
          e4 ? !this._accessibilityManager.value && this._renderService && (this._accessibilityManager.value = this._instantiationService.createInstance(M2.AccessibilityManager, this)) : this._accessibilityManager.clear();
        }
        _handleTextAreaFocus(e4) {
          this.coreService.decPrivateModes.sendFocus && this.coreService.triggerDataEvent(D2.C0.ESC + "[I"), this.element.classList.add("focus"), this._showCursor(), this._onFocus.fire();
        }
        blur() {
          return this.textarea?.blur();
        }
        _handleTextAreaBlur() {
          this.textarea.value = "", this.refresh(this.buffer.y, this.buffer.y), this.coreService.decPrivateModes.sendFocus && this.coreService.triggerDataEvent(D2.C0.ESC + "[O"), this.element.classList.remove("focus"), this._onBlur.fire();
        }
        _syncTextArea() {
          if (!this.textarea || !this.buffer.isCursorInViewport || this._compositionHelper.isComposing || !this._renderService) return;
          const e4 = this.buffer.ybase + this.buffer.y, t4 = this.buffer.lines.get(e4);
          if (!t4) return;
          const i4 = Math.min(this.buffer.x, this.cols - 1), s4 = this._renderService.dimensions.css.cell.height, r3 = t4.getWidth(i4), n3 = this._renderService.dimensions.css.cell.width * r3, o3 = this.buffer.y * this._renderService.dimensions.css.cell.height, a3 = i4 * this._renderService.dimensions.css.cell.width;
          this.textarea.style.left = a3 + "px", this.textarea.style.top = o3 + "px", this.textarea.style.width = n3 + "px", this.textarea.style.height = s4 + "px", this.textarea.style.lineHeight = s4 + "px", this.textarea.style.zIndex = "-5";
        }
        _initGlobal() {
          this._bindKeys(), this.register((0, r2.addDisposableDomListener)(this.element, "copy", (e5) => {
            this.hasSelection() && (0, s3.copyHandler)(e5, this._selectionService);
          }));
          const e4 = /* @__PURE__ */ __name((e5) => (0, s3.handlePasteEvent)(e5, this.textarea, this.coreService, this.optionsService), "e");
          this.register((0, r2.addDisposableDomListener)(this.textarea, "paste", e4)), this.register((0, r2.addDisposableDomListener)(this.element, "paste", e4)), k2.isFirefox ? this.register((0, r2.addDisposableDomListener)(this.element, "mousedown", (e5) => {
            2 === e5.button && (0, s3.rightClickHandler)(e5, this.textarea, this.screenElement, this._selectionService, this.options.rightClickSelectsWord);
          })) : this.register((0, r2.addDisposableDomListener)(this.element, "contextmenu", (e5) => {
            (0, s3.rightClickHandler)(e5, this.textarea, this.screenElement, this._selectionService, this.options.rightClickSelectsWord);
          })), k2.isLinux && this.register((0, r2.addDisposableDomListener)(this.element, "auxclick", (e5) => {
            1 === e5.button && (0, s3.moveTextAreaUnderMouseCursor)(e5, this.textarea, this.screenElement);
          }));
        }
        _bindKeys() {
          this.register((0, r2.addDisposableDomListener)(this.textarea, "keyup", (e4) => this._keyUp(e4), true)), this.register((0, r2.addDisposableDomListener)(this.textarea, "keydown", (e4) => this._keyDown(e4), true)), this.register((0, r2.addDisposableDomListener)(this.textarea, "keypress", (e4) => this._keyPress(e4), true)), this.register((0, r2.addDisposableDomListener)(this.textarea, "compositionstart", () => this._compositionHelper.compositionstart())), this.register((0, r2.addDisposableDomListener)(this.textarea, "compositionupdate", (e4) => this._compositionHelper.compositionupdate(e4))), this.register((0, r2.addDisposableDomListener)(this.textarea, "compositionend", () => this._compositionHelper.compositionend())), this.register((0, r2.addDisposableDomListener)(this.textarea, "input", (e4) => this._inputEvent(e4), true)), this.register(this.onRender(() => this._compositionHelper.updateCompositionElements()));
        }
        open(e4) {
          if (!e4) throw new Error("Terminal requires a parent element.");
          if (e4.isConnected || this._logService.debug("Terminal.open was called on an element that was not attached to the DOM"), this.element?.ownerDocument.defaultView && this._coreBrowserService) return void (this.element.ownerDocument.defaultView !== this._coreBrowserService.window && (this._coreBrowserService.window = this.element.ownerDocument.defaultView));
          this._document = e4.ownerDocument, this.options.documentOverride && this.options.documentOverride instanceof Document && (this._document = this.optionsService.rawOptions.documentOverride), this.element = this._document.createElement("div"), this.element.dir = "ltr", this.element.classList.add("terminal"), this.element.classList.add("xterm"), e4.appendChild(this.element);
          const t4 = this._document.createDocumentFragment();
          this._viewportElement = this._document.createElement("div"), this._viewportElement.classList.add("xterm-viewport"), t4.appendChild(this._viewportElement), this._viewportScrollArea = this._document.createElement("div"), this._viewportScrollArea.classList.add("xterm-scroll-area"), this._viewportElement.appendChild(this._viewportScrollArea), this.screenElement = this._document.createElement("div"), this.screenElement.classList.add("xterm-screen"), this.register((0, r2.addDisposableDomListener)(this.screenElement, "mousemove", (e5) => this.updateCursorStyle(e5))), this._helperContainer = this._document.createElement("div"), this._helperContainer.classList.add("xterm-helpers"), this.screenElement.appendChild(this._helperContainer), t4.appendChild(this.screenElement), this.textarea = this._document.createElement("textarea"), this.textarea.classList.add("xterm-helper-textarea"), this.textarea.setAttribute("aria-label", o2.promptLabel), k2.isChromeOS || this.textarea.setAttribute("aria-multiline", "false"), this.textarea.setAttribute("autocorrect", "off"), this.textarea.setAttribute("autocapitalize", "off"), this.textarea.setAttribute("spellcheck", "false"), this.textarea.tabIndex = 0, this._coreBrowserService = this.register(this._instantiationService.createInstance(v2.CoreBrowserService, this.textarea, e4.ownerDocument.defaultView ?? window, this._document ?? "undefined" != typeof window ? window.document : null)), this._instantiationService.setService(S2.ICoreBrowserService, this._coreBrowserService), this.register((0, r2.addDisposableDomListener)(this.textarea, "focus", (e5) => this._handleTextAreaFocus(e5))), this.register((0, r2.addDisposableDomListener)(this.textarea, "blur", () => this._handleTextAreaBlur())), this._helperContainer.appendChild(this.textarea), this._charSizeService = this._instantiationService.createInstance(u2.CharSizeService, this._document, this._helperContainer), this._instantiationService.setService(S2.ICharSizeService, this._charSizeService), this._themeService = this._instantiationService.createInstance(C2.ThemeService), this._instantiationService.setService(S2.IThemeService, this._themeService), this._characterJoinerService = this._instantiationService.createInstance(f2.CharacterJoinerService), this._instantiationService.setService(S2.ICharacterJoinerService, this._characterJoinerService), this._renderService = this.register(this._instantiationService.createInstance(g2.RenderService, this.rows, this.screenElement)), this._instantiationService.setService(S2.IRenderService, this._renderService), this.register(this._renderService.onRenderedViewportChange((e5) => this._onRender.fire(e5))), this.onResize((e5) => this._renderService.resize(e5.cols, e5.rows)), this._compositionView = this._document.createElement("div"), this._compositionView.classList.add("composition-view"), this._compositionHelper = this._instantiationService.createInstance(d2.CompositionHelper, this.textarea, this._compositionView), this._helperContainer.appendChild(this._compositionView), this._mouseService = this._instantiationService.createInstance(p2.MouseService), this._instantiationService.setService(S2.IMouseService, this._mouseService), this.linkifier = this.register(this._instantiationService.createInstance(n2.Linkifier, this.screenElement)), this.element.appendChild(t4);
          try {
            this._onWillOpen.fire(this.element);
          } catch {
          }
          this._renderService.hasRenderer() || this._renderService.setRenderer(this._createRenderer()), this.viewport = this._instantiationService.createInstance(h2.Viewport, this._viewportElement, this._viewportScrollArea), this.viewport.onRequestScrollLines((e5) => this.scrollLines(e5.amount, e5.suppressScrollEvent, 1)), this.register(this._inputHandler.onRequestSyncScrollBar(() => this.viewport.syncScrollArea())), this.register(this.viewport), this.register(this.onCursorMove(() => {
            this._renderService.handleCursorMove(), this._syncTextArea();
          })), this.register(this.onResize(() => this._renderService.handleResize(this.cols, this.rows))), this.register(this.onBlur(() => this._renderService.handleBlur())), this.register(this.onFocus(() => this._renderService.handleFocus())), this.register(this._renderService.onDimensionsChange(() => this.viewport.syncScrollArea())), this._selectionService = this.register(this._instantiationService.createInstance(m2.SelectionService, this.element, this.screenElement, this.linkifier)), this._instantiationService.setService(S2.ISelectionService, this._selectionService), this.register(this._selectionService.onRequestScrollLines((e5) => this.scrollLines(e5.amount, e5.suppressScrollEvent))), this.register(this._selectionService.onSelectionChange(() => this._onSelectionChange.fire())), this.register(this._selectionService.onRequestRedraw((e5) => this._renderService.handleSelectionChanged(e5.start, e5.end, e5.columnSelectMode))), this.register(this._selectionService.onLinuxMouseSelection((e5) => {
            this.textarea.value = e5, this.textarea.focus(), this.textarea.select();
          })), this.register(this._onScroll.event((e5) => {
            this.viewport.syncScrollArea(), this._selectionService.refresh();
          })), this.register((0, r2.addDisposableDomListener)(this._viewportElement, "scroll", () => this._selectionService.refresh())), this.register(this._instantiationService.createInstance(c2.BufferDecorationRenderer, this.screenElement)), this.register((0, r2.addDisposableDomListener)(this.element, "mousedown", (e5) => this._selectionService.handleMouseDown(e5))), this.coreMouseService.areMouseEventsActive ? (this._selectionService.disable(), this.element.classList.add("enable-mouse-events")) : this._selectionService.enable(), this.options.screenReaderMode && (this._accessibilityManager.value = this._instantiationService.createInstance(M2.AccessibilityManager, this)), this.register(this.optionsService.onSpecificOptionChange("screenReaderMode", (e5) => this._handleScreenReaderModeOptionChange(e5))), this.options.overviewRulerWidth && (this._overviewRulerRenderer = this.register(this._instantiationService.createInstance(l2.OverviewRulerRenderer, this._viewportElement, this.screenElement))), this.optionsService.onSpecificOptionChange("overviewRulerWidth", (e5) => {
            !this._overviewRulerRenderer && e5 && this._viewportElement && this.screenElement && (this._overviewRulerRenderer = this.register(this._instantiationService.createInstance(l2.OverviewRulerRenderer, this._viewportElement, this.screenElement)));
          }), this._charSizeService.measure(), this.refresh(0, this.rows - 1), this._initGlobal(), this.bindMouse();
        }
        _createRenderer() {
          return this._instantiationService.createInstance(_2.DomRenderer, this, this._document, this.element, this.screenElement, this._viewportElement, this._helperContainer, this.linkifier);
        }
        bindMouse() {
          const e4 = this, t4 = this.element;
          function i4(t5) {
            const i5 = e4._mouseService.getMouseReportCoords(t5, e4.screenElement);
            if (!i5) return false;
            let s5, r3;
            switch (t5.overrideType || t5.type) {
              case "mousemove":
                r3 = 32, void 0 === t5.buttons ? (s5 = 3, void 0 !== t5.button && (s5 = t5.button < 3 ? t5.button : 3)) : s5 = 1 & t5.buttons ? 0 : 4 & t5.buttons ? 1 : 2 & t5.buttons ? 2 : 3;
                break;
              case "mouseup":
                r3 = 0, s5 = t5.button < 3 ? t5.button : 3;
                break;
              case "mousedown":
                r3 = 1, s5 = t5.button < 3 ? t5.button : 3;
                break;
              case "wheel":
                if (e4._customWheelEventHandler && false === e4._customWheelEventHandler(t5)) return false;
                if (0 === e4.viewport.getLinesScrolled(t5)) return false;
                r3 = t5.deltaY < 0 ? 0 : 1, s5 = 4;
                break;
              default:
                return false;
            }
            return !(void 0 === r3 || void 0 === s5 || s5 > 4) && e4.coreMouseService.triggerMouseEvent({ col: i5.col, row: i5.row, x: i5.x, y: i5.y, button: s5, action: r3, ctrl: t5.ctrlKey, alt: t5.altKey, shift: t5.shiftKey });
          }
          __name(i4, "i");
          const s4 = { mouseup: null, wheel: null, mousedrag: null, mousemove: null }, n3 = { mouseup: /* @__PURE__ */ __name((e5) => (i4(e5), e5.buttons || (this._document.removeEventListener("mouseup", s4.mouseup), s4.mousedrag && this._document.removeEventListener("mousemove", s4.mousedrag)), this.cancel(e5)), "mouseup"), wheel: /* @__PURE__ */ __name((e5) => (i4(e5), this.cancel(e5, true)), "wheel"), mousedrag: /* @__PURE__ */ __name((e5) => {
            e5.buttons && i4(e5);
          }, "mousedrag"), mousemove: /* @__PURE__ */ __name((e5) => {
            e5.buttons || i4(e5);
          }, "mousemove") };
          this.register(this.coreMouseService.onProtocolChange((e5) => {
            e5 ? ("debug" === this.optionsService.rawOptions.logLevel && this._logService.debug("Binding to mouse events:", this.coreMouseService.explainEvents(e5)), this.element.classList.add("enable-mouse-events"), this._selectionService.disable()) : (this._logService.debug("Unbinding from mouse events."), this.element.classList.remove("enable-mouse-events"), this._selectionService.enable()), 8 & e5 ? s4.mousemove || (t4.addEventListener("mousemove", n3.mousemove), s4.mousemove = n3.mousemove) : (t4.removeEventListener("mousemove", s4.mousemove), s4.mousemove = null), 16 & e5 ? s4.wheel || (t4.addEventListener("wheel", n3.wheel, { passive: false }), s4.wheel = n3.wheel) : (t4.removeEventListener("wheel", s4.wheel), s4.wheel = null), 2 & e5 ? s4.mouseup || (s4.mouseup = n3.mouseup) : (this._document.removeEventListener("mouseup", s4.mouseup), s4.mouseup = null), 4 & e5 ? s4.mousedrag || (s4.mousedrag = n3.mousedrag) : (this._document.removeEventListener("mousemove", s4.mousedrag), s4.mousedrag = null);
          })), this.coreMouseService.activeProtocol = this.coreMouseService.activeProtocol, this.register((0, r2.addDisposableDomListener)(t4, "mousedown", (e5) => {
            if (e5.preventDefault(), this.focus(), this.coreMouseService.areMouseEventsActive && !this._selectionService.shouldForceSelection(e5)) return i4(e5), s4.mouseup && this._document.addEventListener("mouseup", s4.mouseup), s4.mousedrag && this._document.addEventListener("mousemove", s4.mousedrag), this.cancel(e5);
          })), this.register((0, r2.addDisposableDomListener)(t4, "wheel", (e5) => {
            if (!s4.wheel) {
              if (this._customWheelEventHandler && false === this._customWheelEventHandler(e5)) return false;
              if (!this.buffer.hasScrollback) {
                const t5 = this.viewport.getLinesScrolled(e5);
                if (0 === t5) return;
                const i5 = D2.C0.ESC + (this.coreService.decPrivateModes.applicationCursorKeys ? "O" : "[") + (e5.deltaY < 0 ? "A" : "B");
                let s5 = "";
                for (let e6 = 0; e6 < Math.abs(t5); e6++) s5 += i5;
                return this.coreService.triggerDataEvent(s5, true), this.cancel(e5, true);
              }
              return this.viewport.handleWheel(e5) ? this.cancel(e5) : void 0;
            }
          }, { passive: false })), this.register((0, r2.addDisposableDomListener)(t4, "touchstart", (e5) => {
            if (!this.coreMouseService.areMouseEventsActive) return this.viewport.handleTouchStart(e5), this.cancel(e5);
          }, { passive: true })), this.register((0, r2.addDisposableDomListener)(t4, "touchmove", (e5) => {
            if (!this.coreMouseService.areMouseEventsActive) return this.viewport.handleTouchMove(e5) ? void 0 : this.cancel(e5);
          }, { passive: false }));
        }
        refresh(e4, t4) {
          this._renderService?.refreshRows(e4, t4);
        }
        updateCursorStyle(e4) {
          this._selectionService?.shouldColumnSelect(e4) ? this.element.classList.add("column-select") : this.element.classList.remove("column-select");
        }
        _showCursor() {
          this.coreService.isCursorInitialized || (this.coreService.isCursorInitialized = true, this.refresh(this.buffer.y, this.buffer.y));
        }
        scrollLines(e4, t4, i4 = 0) {
          1 === i4 ? (super.scrollLines(e4, t4, i4), this.refresh(0, this.rows - 1)) : this.viewport?.scrollLines(e4);
        }
        paste(e4) {
          (0, s3.paste)(e4, this.textarea, this.coreService, this.optionsService);
        }
        attachCustomKeyEventHandler(e4) {
          this._customKeyEventHandler = e4;
        }
        attachCustomWheelEventHandler(e4) {
          this._customWheelEventHandler = e4;
        }
        registerLinkProvider(e4) {
          return this._linkProviderService.registerLinkProvider(e4);
        }
        registerCharacterJoiner(e4) {
          if (!this._characterJoinerService) throw new Error("Terminal must be opened first");
          const t4 = this._characterJoinerService.register(e4);
          return this.refresh(0, this.rows - 1), t4;
        }
        deregisterCharacterJoiner(e4) {
          if (!this._characterJoinerService) throw new Error("Terminal must be opened first");
          this._characterJoinerService.deregister(e4) && this.refresh(0, this.rows - 1);
        }
        get markers() {
          return this.buffer.markers;
        }
        registerMarker(e4) {
          return this.buffer.addMarker(this.buffer.ybase + this.buffer.y + e4);
        }
        registerDecoration(e4) {
          return this._decorationService.registerDecoration(e4);
        }
        hasSelection() {
          return !!this._selectionService && this._selectionService.hasSelection;
        }
        select(e4, t4, i4) {
          this._selectionService.setSelection(e4, t4, i4);
        }
        getSelection() {
          return this._selectionService ? this._selectionService.selectionText : "";
        }
        getSelectionPosition() {
          if (this._selectionService && this._selectionService.hasSelection) return { start: { x: this._selectionService.selectionStart[0], y: this._selectionService.selectionStart[1] }, end: { x: this._selectionService.selectionEnd[0], y: this._selectionService.selectionEnd[1] } };
        }
        clearSelection() {
          this._selectionService?.clearSelection();
        }
        selectAll() {
          this._selectionService?.selectAll();
        }
        selectLines(e4, t4) {
          this._selectionService?.selectLines(e4, t4);
        }
        _keyDown(e4) {
          if (this._keyDownHandled = false, this._keyDownSeen = true, this._customKeyEventHandler && false === this._customKeyEventHandler(e4)) return false;
          const t4 = this.browser.isMac && this.options.macOptionIsMeta && e4.altKey;
          if (!t4 && !this._compositionHelper.keydown(e4)) return this.options.scrollOnUserInput && this.buffer.ybase !== this.buffer.ydisp && this.scrollToBottom(), false;
          t4 || "Dead" !== e4.key && "AltGraph" !== e4.key || (this._unprocessedDeadKey = true);
          const i4 = (0, R.evaluateKeyboardEvent)(e4, this.coreService.decPrivateModes.applicationCursorKeys, this.browser.isMac, this.options.macOptionIsMeta);
          if (this.updateCursorStyle(e4), 3 === i4.type || 2 === i4.type) {
            const t5 = this.rows - 1;
            return this.scrollLines(2 === i4.type ? -t5 : t5), this.cancel(e4, true);
          }
          return 1 === i4.type && this.selectAll(), !!this._isThirdLevelShift(this.browser, e4) || (i4.cancel && this.cancel(e4, true), !i4.key || !!(e4.key && !e4.ctrlKey && !e4.altKey && !e4.metaKey && 1 === e4.key.length && e4.key.charCodeAt(0) >= 65 && e4.key.charCodeAt(0) <= 90) || (this._unprocessedDeadKey ? (this._unprocessedDeadKey = false, true) : (i4.key !== D2.C0.ETX && i4.key !== D2.C0.CR || (this.textarea.value = ""), this._onKey.fire({ key: i4.key, domEvent: e4 }), this._showCursor(), this.coreService.triggerDataEvent(i4.key, true), !this.optionsService.rawOptions.screenReaderMode || e4.altKey || e4.ctrlKey ? this.cancel(e4, true) : void (this._keyDownHandled = true))));
        }
        _isThirdLevelShift(e4, t4) {
          const i4 = e4.isMac && !this.options.macOptionIsMeta && t4.altKey && !t4.ctrlKey && !t4.metaKey || e4.isWindows && t4.altKey && t4.ctrlKey && !t4.metaKey || e4.isWindows && t4.getModifierState("AltGraph");
          return "keypress" === t4.type ? i4 : i4 && (!t4.keyCode || t4.keyCode > 47);
        }
        _keyUp(e4) {
          this._keyDownSeen = false, this._customKeyEventHandler && false === this._customKeyEventHandler(e4) || (function(e5) {
            return 16 === e5.keyCode || 17 === e5.keyCode || 18 === e5.keyCode;
          }(e4) || this.focus(), this.updateCursorStyle(e4), this._keyPressHandled = false);
        }
        _keyPress(e4) {
          let t4;
          if (this._keyPressHandled = false, this._keyDownHandled) return false;
          if (this._customKeyEventHandler && false === this._customKeyEventHandler(e4)) return false;
          if (this.cancel(e4), e4.charCode) t4 = e4.charCode;
          else if (null === e4.which || void 0 === e4.which) t4 = e4.keyCode;
          else {
            if (0 === e4.which || 0 === e4.charCode) return false;
            t4 = e4.which;
          }
          return !(!t4 || (e4.altKey || e4.ctrlKey || e4.metaKey) && !this._isThirdLevelShift(this.browser, e4) || (t4 = String.fromCharCode(t4), this._onKey.fire({ key: t4, domEvent: e4 }), this._showCursor(), this.coreService.triggerDataEvent(t4, true), this._keyPressHandled = true, this._unprocessedDeadKey = false, 0));
        }
        _inputEvent(e4) {
          if (e4.data && "insertText" === e4.inputType && (!e4.composed || !this._keyDownSeen) && !this.optionsService.rawOptions.screenReaderMode) {
            if (this._keyPressHandled) return false;
            this._unprocessedDeadKey = false;
            const t4 = e4.data;
            return this.coreService.triggerDataEvent(t4, true), this.cancel(e4), true;
          }
          return false;
        }
        resize(e4, t4) {
          e4 !== this.cols || t4 !== this.rows ? super.resize(e4, t4) : this._charSizeService && !this._charSizeService.hasValidSize && this._charSizeService.measure();
        }
        _afterResize(e4, t4) {
          this._charSizeService?.measure(), this.viewport?.syncScrollArea(true);
        }
        clear() {
          if (0 !== this.buffer.ybase || 0 !== this.buffer.y) {
            this.buffer.clearAllMarkers(), this.buffer.lines.set(0, this.buffer.lines.get(this.buffer.ybase + this.buffer.y)), this.buffer.lines.length = 1, this.buffer.ydisp = 0, this.buffer.ybase = 0, this.buffer.y = 0;
            for (let e4 = 1; e4 < this.rows; e4++) this.buffer.lines.push(this.buffer.getBlankLine(L2.DEFAULT_ATTR_DATA));
            this._onScroll.fire({ position: this.buffer.ydisp, source: 0 }), this.viewport?.reset(), this.refresh(0, this.rows - 1);
          }
        }
        reset() {
          this.options.rows = this.rows, this.options.cols = this.cols;
          const e4 = this._customKeyEventHandler;
          this._setup(), super.reset(), this._selectionService?.reset(), this._decorationService.reset(), this.viewport?.reset(), this._customKeyEventHandler = e4, this.refresh(0, this.rows - 1);
        }
        clearTextureAtlas() {
          this._renderService?.clearTextureAtlas();
        }
        _reportFocus() {
          this.element?.classList.contains("focus") ? this.coreService.triggerDataEvent(D2.C0.ESC + "[I") : this.coreService.triggerDataEvent(D2.C0.ESC + "[O");
        }
        _reportWindowsOptions(e4) {
          if (this._renderService) switch (e4) {
            case T2.WindowsOptionsReportType.GET_WIN_SIZE_PIXELS:
              const e5 = this._renderService.dimensions.css.canvas.width.toFixed(0), t4 = this._renderService.dimensions.css.canvas.height.toFixed(0);
              this.coreService.triggerDataEvent(`${D2.C0.ESC}[4;${t4};${e5}t`);
              break;
            case T2.WindowsOptionsReportType.GET_CELL_SIZE_PIXELS:
              const i4 = this._renderService.dimensions.css.cell.width.toFixed(0), s4 = this._renderService.dimensions.css.cell.height.toFixed(0);
              this.coreService.triggerDataEvent(`${D2.C0.ESC}[6;${s4};${i4}t`);
          }
        }
        cancel(e4, t4) {
          if (this.options.cancelEvents || t4) return e4.preventDefault(), e4.stopPropagation(), false;
        }
      }
      t3.Terminal = P2;
    }, 9924: (e3, t3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.TimeBasedDebouncer = void 0, t3.TimeBasedDebouncer = class {
        constructor(e4, t4 = 1e3) {
          this._renderCallback = e4, this._debounceThresholdMS = t4, this._lastRefreshMs = 0, this._additionalRefreshRequested = false;
        }
        dispose() {
          this._refreshTimeoutID && clearTimeout(this._refreshTimeoutID);
        }
        refresh(e4, t4, i3) {
          this._rowCount = i3, e4 = void 0 !== e4 ? e4 : 0, t4 = void 0 !== t4 ? t4 : this._rowCount - 1, this._rowStart = void 0 !== this._rowStart ? Math.min(this._rowStart, e4) : e4, this._rowEnd = void 0 !== this._rowEnd ? Math.max(this._rowEnd, t4) : t4;
          const s3 = Date.now();
          if (s3 - this._lastRefreshMs >= this._debounceThresholdMS) this._lastRefreshMs = s3, this._innerRefresh();
          else if (!this._additionalRefreshRequested) {
            const e5 = s3 - this._lastRefreshMs, t5 = this._debounceThresholdMS - e5;
            this._additionalRefreshRequested = true, this._refreshTimeoutID = window.setTimeout(() => {
              this._lastRefreshMs = Date.now(), this._innerRefresh(), this._additionalRefreshRequested = false, this._refreshTimeoutID = void 0;
            }, t5);
          }
        }
        _innerRefresh() {
          if (void 0 === this._rowStart || void 0 === this._rowEnd || void 0 === this._rowCount) return;
          const e4 = Math.max(this._rowStart, 0), t4 = Math.min(this._rowEnd, this._rowCount - 1);
          this._rowStart = void 0, this._rowEnd = void 0, this._renderCallback(e4, t4);
        }
      };
    }, 1680: function(e3, t3, i3) {
      var s3 = this && this.__decorate || function(e4, t4, i4, s4) {
        var r3, n3 = arguments.length, o3 = n3 < 3 ? t4 : null === s4 ? s4 = Object.getOwnPropertyDescriptor(t4, i4) : s4;
        if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) o3 = Reflect.decorate(e4, t4, i4, s4);
        else for (var a3 = e4.length - 1; a3 >= 0; a3--) (r3 = e4[a3]) && (o3 = (n3 < 3 ? r3(o3) : n3 > 3 ? r3(t4, i4, o3) : r3(t4, i4)) || o3);
        return n3 > 3 && o3 && Object.defineProperty(t4, i4, o3), o3;
      }, r2 = this && this.__param || function(e4, t4) {
        return function(i4, s4) {
          t4(i4, s4, e4);
        };
      };
      Object.defineProperty(t3, "__esModule", { value: true }), t3.Viewport = void 0;
      const n2 = i3(3656), o2 = i3(4725), a2 = i3(8460), h2 = i3(844), c2 = i3(2585);
      let l2 = t3.Viewport = class extends h2.Disposable {
        constructor(e4, t4, i4, s4, r3, o3, h3, c3) {
          super(), this._viewportElement = e4, this._scrollArea = t4, this._bufferService = i4, this._optionsService = s4, this._charSizeService = r3, this._renderService = o3, this._coreBrowserService = h3, this.scrollBarWidth = 0, this._currentRowHeight = 0, this._currentDeviceCellHeight = 0, this._lastRecordedBufferLength = 0, this._lastRecordedViewportHeight = 0, this._lastRecordedBufferHeight = 0, this._lastTouchY = 0, this._lastScrollTop = 0, this._wheelPartialScroll = 0, this._refreshAnimationFrame = null, this._ignoreNextScrollEvent = false, this._smoothScrollState = { startTime: 0, origin: -1, target: -1 }, this._onRequestScrollLines = this.register(new a2.EventEmitter()), this.onRequestScrollLines = this._onRequestScrollLines.event, this.scrollBarWidth = this._viewportElement.offsetWidth - this._scrollArea.offsetWidth || 15, this.register((0, n2.addDisposableDomListener)(this._viewportElement, "scroll", this._handleScroll.bind(this))), this._activeBuffer = this._bufferService.buffer, this.register(this._bufferService.buffers.onBufferActivate((e5) => this._activeBuffer = e5.activeBuffer)), this._renderDimensions = this._renderService.dimensions, this.register(this._renderService.onDimensionsChange((e5) => this._renderDimensions = e5)), this._handleThemeChange(c3.colors), this.register(c3.onChangeColors((e5) => this._handleThemeChange(e5))), this.register(this._optionsService.onSpecificOptionChange("scrollback", () => this.syncScrollArea())), setTimeout(() => this.syncScrollArea());
        }
        _handleThemeChange(e4) {
          this._viewportElement.style.backgroundColor = e4.background.css;
        }
        reset() {
          this._currentRowHeight = 0, this._currentDeviceCellHeight = 0, this._lastRecordedBufferLength = 0, this._lastRecordedViewportHeight = 0, this._lastRecordedBufferHeight = 0, this._lastTouchY = 0, this._lastScrollTop = 0, this._coreBrowserService.window.requestAnimationFrame(() => this.syncScrollArea());
        }
        _refresh(e4) {
          if (e4) return this._innerRefresh(), void (null !== this._refreshAnimationFrame && this._coreBrowserService.window.cancelAnimationFrame(this._refreshAnimationFrame));
          null === this._refreshAnimationFrame && (this._refreshAnimationFrame = this._coreBrowserService.window.requestAnimationFrame(() => this._innerRefresh()));
        }
        _innerRefresh() {
          if (this._charSizeService.height > 0) {
            this._currentRowHeight = this._renderDimensions.device.cell.height / this._coreBrowserService.dpr, this._currentDeviceCellHeight = this._renderDimensions.device.cell.height, this._lastRecordedViewportHeight = this._viewportElement.offsetHeight;
            const e5 = Math.round(this._currentRowHeight * this._lastRecordedBufferLength) + (this._lastRecordedViewportHeight - this._renderDimensions.css.canvas.height);
            this._lastRecordedBufferHeight !== e5 && (this._lastRecordedBufferHeight = e5, this._scrollArea.style.height = this._lastRecordedBufferHeight + "px");
          }
          const e4 = this._bufferService.buffer.ydisp * this._currentRowHeight;
          this._viewportElement.scrollTop !== e4 && (this._ignoreNextScrollEvent = true, this._viewportElement.scrollTop = e4), this._refreshAnimationFrame = null;
        }
        syncScrollArea(e4 = false) {
          if (this._lastRecordedBufferLength !== this._bufferService.buffer.lines.length) return this._lastRecordedBufferLength = this._bufferService.buffer.lines.length, void this._refresh(e4);
          this._lastRecordedViewportHeight === this._renderService.dimensions.css.canvas.height && this._lastScrollTop === this._activeBuffer.ydisp * this._currentRowHeight && this._renderDimensions.device.cell.height === this._currentDeviceCellHeight || this._refresh(e4);
        }
        _handleScroll(e4) {
          if (this._lastScrollTop = this._viewportElement.scrollTop, !this._viewportElement.offsetParent) return;
          if (this._ignoreNextScrollEvent) return this._ignoreNextScrollEvent = false, void this._onRequestScrollLines.fire({ amount: 0, suppressScrollEvent: true });
          const t4 = Math.round(this._lastScrollTop / this._currentRowHeight) - this._bufferService.buffer.ydisp;
          this._onRequestScrollLines.fire({ amount: t4, suppressScrollEvent: true });
        }
        _smoothScroll() {
          if (this._isDisposed || -1 === this._smoothScrollState.origin || -1 === this._smoothScrollState.target) return;
          const e4 = this._smoothScrollPercent();
          this._viewportElement.scrollTop = this._smoothScrollState.origin + Math.round(e4 * (this._smoothScrollState.target - this._smoothScrollState.origin)), e4 < 1 ? this._coreBrowserService.window.requestAnimationFrame(() => this._smoothScroll()) : this._clearSmoothScrollState();
        }
        _smoothScrollPercent() {
          return this._optionsService.rawOptions.smoothScrollDuration && this._smoothScrollState.startTime ? Math.max(Math.min((Date.now() - this._smoothScrollState.startTime) / this._optionsService.rawOptions.smoothScrollDuration, 1), 0) : 1;
        }
        _clearSmoothScrollState() {
          this._smoothScrollState.startTime = 0, this._smoothScrollState.origin = -1, this._smoothScrollState.target = -1;
        }
        _bubbleScroll(e4, t4) {
          const i4 = this._viewportElement.scrollTop + this._lastRecordedViewportHeight;
          return !(t4 < 0 && 0 !== this._viewportElement.scrollTop || t4 > 0 && i4 < this._lastRecordedBufferHeight) || (e4.cancelable && e4.preventDefault(), false);
        }
        handleWheel(e4) {
          const t4 = this._getPixelsScrolled(e4);
          return 0 !== t4 && (this._optionsService.rawOptions.smoothScrollDuration ? (this._smoothScrollState.startTime = Date.now(), this._smoothScrollPercent() < 1 ? (this._smoothScrollState.origin = this._viewportElement.scrollTop, -1 === this._smoothScrollState.target ? this._smoothScrollState.target = this._viewportElement.scrollTop + t4 : this._smoothScrollState.target += t4, this._smoothScrollState.target = Math.max(Math.min(this._smoothScrollState.target, this._viewportElement.scrollHeight), 0), this._smoothScroll()) : this._clearSmoothScrollState()) : this._viewportElement.scrollTop += t4, this._bubbleScroll(e4, t4));
        }
        scrollLines(e4) {
          if (0 !== e4) if (this._optionsService.rawOptions.smoothScrollDuration) {
            const t4 = e4 * this._currentRowHeight;
            this._smoothScrollState.startTime = Date.now(), this._smoothScrollPercent() < 1 ? (this._smoothScrollState.origin = this._viewportElement.scrollTop, this._smoothScrollState.target = this._smoothScrollState.origin + t4, this._smoothScrollState.target = Math.max(Math.min(this._smoothScrollState.target, this._viewportElement.scrollHeight), 0), this._smoothScroll()) : this._clearSmoothScrollState();
          } else this._onRequestScrollLines.fire({ amount: e4, suppressScrollEvent: false });
        }
        _getPixelsScrolled(e4) {
          if (0 === e4.deltaY || e4.shiftKey) return 0;
          let t4 = this._applyScrollModifier(e4.deltaY, e4);
          return e4.deltaMode === WheelEvent.DOM_DELTA_LINE ? t4 *= this._currentRowHeight : e4.deltaMode === WheelEvent.DOM_DELTA_PAGE && (t4 *= this._currentRowHeight * this._bufferService.rows), t4;
        }
        getBufferElements(e4, t4) {
          let i4, s4 = "";
          const r3 = [], n3 = t4 ?? this._bufferService.buffer.lines.length, o3 = this._bufferService.buffer.lines;
          for (let t5 = e4; t5 < n3; t5++) {
            const e5 = o3.get(t5);
            if (!e5) continue;
            const n4 = o3.get(t5 + 1)?.isWrapped;
            if (s4 += e5.translateToString(!n4), !n4 || t5 === o3.length - 1) {
              const e6 = document.createElement("div");
              e6.textContent = s4, r3.push(e6), s4.length > 0 && (i4 = e6), s4 = "";
            }
          }
          return { bufferElements: r3, cursorElement: i4 };
        }
        getLinesScrolled(e4) {
          if (0 === e4.deltaY || e4.shiftKey) return 0;
          let t4 = this._applyScrollModifier(e4.deltaY, e4);
          return e4.deltaMode === WheelEvent.DOM_DELTA_PIXEL ? (t4 /= this._currentRowHeight + 0, this._wheelPartialScroll += t4, t4 = Math.floor(Math.abs(this._wheelPartialScroll)) * (this._wheelPartialScroll > 0 ? 1 : -1), this._wheelPartialScroll %= 1) : e4.deltaMode === WheelEvent.DOM_DELTA_PAGE && (t4 *= this._bufferService.rows), t4;
        }
        _applyScrollModifier(e4, t4) {
          const i4 = this._optionsService.rawOptions.fastScrollModifier;
          return "alt" === i4 && t4.altKey || "ctrl" === i4 && t4.ctrlKey || "shift" === i4 && t4.shiftKey ? e4 * this._optionsService.rawOptions.fastScrollSensitivity * this._optionsService.rawOptions.scrollSensitivity : e4 * this._optionsService.rawOptions.scrollSensitivity;
        }
        handleTouchStart(e4) {
          this._lastTouchY = e4.touches[0].pageY;
        }
        handleTouchMove(e4) {
          const t4 = this._lastTouchY - e4.touches[0].pageY;
          return this._lastTouchY = e4.touches[0].pageY, 0 !== t4 && (this._viewportElement.scrollTop += t4, this._bubbleScroll(e4, t4));
        }
      };
      t3.Viewport = l2 = s3([r2(2, c2.IBufferService), r2(3, c2.IOptionsService), r2(4, o2.ICharSizeService), r2(5, o2.IRenderService), r2(6, o2.ICoreBrowserService), r2(7, o2.IThemeService)], l2);
    }, 3107: function(e3, t3, i3) {
      var s3 = this && this.__decorate || function(e4, t4, i4, s4) {
        var r3, n3 = arguments.length, o3 = n3 < 3 ? t4 : null === s4 ? s4 = Object.getOwnPropertyDescriptor(t4, i4) : s4;
        if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) o3 = Reflect.decorate(e4, t4, i4, s4);
        else for (var a3 = e4.length - 1; a3 >= 0; a3--) (r3 = e4[a3]) && (o3 = (n3 < 3 ? r3(o3) : n3 > 3 ? r3(t4, i4, o3) : r3(t4, i4)) || o3);
        return n3 > 3 && o3 && Object.defineProperty(t4, i4, o3), o3;
      }, r2 = this && this.__param || function(e4, t4) {
        return function(i4, s4) {
          t4(i4, s4, e4);
        };
      };
      Object.defineProperty(t3, "__esModule", { value: true }), t3.BufferDecorationRenderer = void 0;
      const n2 = i3(4725), o2 = i3(844), a2 = i3(2585);
      let h2 = t3.BufferDecorationRenderer = class extends o2.Disposable {
        constructor(e4, t4, i4, s4, r3) {
          super(), this._screenElement = e4, this._bufferService = t4, this._coreBrowserService = i4, this._decorationService = s4, this._renderService = r3, this._decorationElements = /* @__PURE__ */ new Map(), this._altBufferIsActive = false, this._dimensionsChanged = false, this._container = document.createElement("div"), this._container.classList.add("xterm-decoration-container"), this._screenElement.appendChild(this._container), this.register(this._renderService.onRenderedViewportChange(() => this._doRefreshDecorations())), this.register(this._renderService.onDimensionsChange(() => {
            this._dimensionsChanged = true, this._queueRefresh();
          })), this.register(this._coreBrowserService.onDprChange(() => this._queueRefresh())), this.register(this._bufferService.buffers.onBufferActivate(() => {
            this._altBufferIsActive = this._bufferService.buffer === this._bufferService.buffers.alt;
          })), this.register(this._decorationService.onDecorationRegistered(() => this._queueRefresh())), this.register(this._decorationService.onDecorationRemoved((e5) => this._removeDecoration(e5))), this.register((0, o2.toDisposable)(() => {
            this._container.remove(), this._decorationElements.clear();
          }));
        }
        _queueRefresh() {
          void 0 === this._animationFrame && (this._animationFrame = this._renderService.addRefreshCallback(() => {
            this._doRefreshDecorations(), this._animationFrame = void 0;
          }));
        }
        _doRefreshDecorations() {
          for (const e4 of this._decorationService.decorations) this._renderDecoration(e4);
          this._dimensionsChanged = false;
        }
        _renderDecoration(e4) {
          this._refreshStyle(e4), this._dimensionsChanged && this._refreshXPosition(e4);
        }
        _createElement(e4) {
          const t4 = this._coreBrowserService.mainDocument.createElement("div");
          t4.classList.add("xterm-decoration"), t4.classList.toggle("xterm-decoration-top-layer", "top" === e4?.options?.layer), t4.style.width = `${Math.round((e4.options.width || 1) * this._renderService.dimensions.css.cell.width)}px`, t4.style.height = (e4.options.height || 1) * this._renderService.dimensions.css.cell.height + "px", t4.style.top = (e4.marker.line - this._bufferService.buffers.active.ydisp) * this._renderService.dimensions.css.cell.height + "px", t4.style.lineHeight = `${this._renderService.dimensions.css.cell.height}px`;
          const i4 = e4.options.x ?? 0;
          return i4 && i4 > this._bufferService.cols && (t4.style.display = "none"), this._refreshXPosition(e4, t4), t4;
        }
        _refreshStyle(e4) {
          const t4 = e4.marker.line - this._bufferService.buffers.active.ydisp;
          if (t4 < 0 || t4 >= this._bufferService.rows) e4.element && (e4.element.style.display = "none", e4.onRenderEmitter.fire(e4.element));
          else {
            let i4 = this._decorationElements.get(e4);
            i4 || (i4 = this._createElement(e4), e4.element = i4, this._decorationElements.set(e4, i4), this._container.appendChild(i4), e4.onDispose(() => {
              this._decorationElements.delete(e4), i4.remove();
            })), i4.style.top = t4 * this._renderService.dimensions.css.cell.height + "px", i4.style.display = this._altBufferIsActive ? "none" : "block", e4.onRenderEmitter.fire(i4);
          }
        }
        _refreshXPosition(e4, t4 = e4.element) {
          if (!t4) return;
          const i4 = e4.options.x ?? 0;
          "right" === (e4.options.anchor || "left") ? t4.style.right = i4 ? i4 * this._renderService.dimensions.css.cell.width + "px" : "" : t4.style.left = i4 ? i4 * this._renderService.dimensions.css.cell.width + "px" : "";
        }
        _removeDecoration(e4) {
          this._decorationElements.get(e4)?.remove(), this._decorationElements.delete(e4), e4.dispose();
        }
      };
      t3.BufferDecorationRenderer = h2 = s3([r2(1, a2.IBufferService), r2(2, n2.ICoreBrowserService), r2(3, a2.IDecorationService), r2(4, n2.IRenderService)], h2);
    }, 5871: (e3, t3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.ColorZoneStore = void 0, t3.ColorZoneStore = class {
        constructor() {
          this._zones = [], this._zonePool = [], this._zonePoolIndex = 0, this._linePadding = { full: 0, left: 0, center: 0, right: 0 };
        }
        get zones() {
          return this._zonePool.length = Math.min(this._zonePool.length, this._zones.length), this._zones;
        }
        clear() {
          this._zones.length = 0, this._zonePoolIndex = 0;
        }
        addDecoration(e4) {
          if (e4.options.overviewRulerOptions) {
            for (const t4 of this._zones) if (t4.color === e4.options.overviewRulerOptions.color && t4.position === e4.options.overviewRulerOptions.position) {
              if (this._lineIntersectsZone(t4, e4.marker.line)) return;
              if (this._lineAdjacentToZone(t4, e4.marker.line, e4.options.overviewRulerOptions.position)) return void this._addLineToZone(t4, e4.marker.line);
            }
            if (this._zonePoolIndex < this._zonePool.length) return this._zonePool[this._zonePoolIndex].color = e4.options.overviewRulerOptions.color, this._zonePool[this._zonePoolIndex].position = e4.options.overviewRulerOptions.position, this._zonePool[this._zonePoolIndex].startBufferLine = e4.marker.line, this._zonePool[this._zonePoolIndex].endBufferLine = e4.marker.line, void this._zones.push(this._zonePool[this._zonePoolIndex++]);
            this._zones.push({ color: e4.options.overviewRulerOptions.color, position: e4.options.overviewRulerOptions.position, startBufferLine: e4.marker.line, endBufferLine: e4.marker.line }), this._zonePool.push(this._zones[this._zones.length - 1]), this._zonePoolIndex++;
          }
        }
        setPadding(e4) {
          this._linePadding = e4;
        }
        _lineIntersectsZone(e4, t4) {
          return t4 >= e4.startBufferLine && t4 <= e4.endBufferLine;
        }
        _lineAdjacentToZone(e4, t4, i3) {
          return t4 >= e4.startBufferLine - this._linePadding[i3 || "full"] && t4 <= e4.endBufferLine + this._linePadding[i3 || "full"];
        }
        _addLineToZone(e4, t4) {
          e4.startBufferLine = Math.min(e4.startBufferLine, t4), e4.endBufferLine = Math.max(e4.endBufferLine, t4);
        }
      };
    }, 5744: function(e3, t3, i3) {
      var s3 = this && this.__decorate || function(e4, t4, i4, s4) {
        var r3, n3 = arguments.length, o3 = n3 < 3 ? t4 : null === s4 ? s4 = Object.getOwnPropertyDescriptor(t4, i4) : s4;
        if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) o3 = Reflect.decorate(e4, t4, i4, s4);
        else for (var a3 = e4.length - 1; a3 >= 0; a3--) (r3 = e4[a3]) && (o3 = (n3 < 3 ? r3(o3) : n3 > 3 ? r3(t4, i4, o3) : r3(t4, i4)) || o3);
        return n3 > 3 && o3 && Object.defineProperty(t4, i4, o3), o3;
      }, r2 = this && this.__param || function(e4, t4) {
        return function(i4, s4) {
          t4(i4, s4, e4);
        };
      };
      Object.defineProperty(t3, "__esModule", { value: true }), t3.OverviewRulerRenderer = void 0;
      const n2 = i3(5871), o2 = i3(4725), a2 = i3(844), h2 = i3(2585), c2 = { full: 0, left: 0, center: 0, right: 0 }, l2 = { full: 0, left: 0, center: 0, right: 0 }, d2 = { full: 0, left: 0, center: 0, right: 0 };
      let _2 = t3.OverviewRulerRenderer = class extends a2.Disposable {
        get _width() {
          return this._optionsService.options.overviewRulerWidth || 0;
        }
        constructor(e4, t4, i4, s4, r3, o3, h3) {
          super(), this._viewportElement = e4, this._screenElement = t4, this._bufferService = i4, this._decorationService = s4, this._renderService = r3, this._optionsService = o3, this._coreBrowserService = h3, this._colorZoneStore = new n2.ColorZoneStore(), this._shouldUpdateDimensions = true, this._shouldUpdateAnchor = true, this._lastKnownBufferLength = 0, this._canvas = this._coreBrowserService.mainDocument.createElement("canvas"), this._canvas.classList.add("xterm-decoration-overview-ruler"), this._refreshCanvasDimensions(), this._viewportElement.parentElement?.insertBefore(this._canvas, this._viewportElement);
          const c3 = this._canvas.getContext("2d");
          if (!c3) throw new Error("Ctx cannot be null");
          this._ctx = c3, this._registerDecorationListeners(), this._registerBufferChangeListeners(), this._registerDimensionChangeListeners(), this.register((0, a2.toDisposable)(() => {
            this._canvas?.remove();
          }));
        }
        _registerDecorationListeners() {
          this.register(this._decorationService.onDecorationRegistered(() => this._queueRefresh(void 0, true))), this.register(this._decorationService.onDecorationRemoved(() => this._queueRefresh(void 0, true)));
        }
        _registerBufferChangeListeners() {
          this.register(this._renderService.onRenderedViewportChange(() => this._queueRefresh())), this.register(this._bufferService.buffers.onBufferActivate(() => {
            this._canvas.style.display = this._bufferService.buffer === this._bufferService.buffers.alt ? "none" : "block";
          })), this.register(this._bufferService.onScroll(() => {
            this._lastKnownBufferLength !== this._bufferService.buffers.normal.lines.length && (this._refreshDrawHeightConstants(), this._refreshColorZonePadding());
          }));
        }
        _registerDimensionChangeListeners() {
          this.register(this._renderService.onRender(() => {
            this._containerHeight && this._containerHeight === this._screenElement.clientHeight || (this._queueRefresh(true), this._containerHeight = this._screenElement.clientHeight);
          })), this.register(this._optionsService.onSpecificOptionChange("overviewRulerWidth", () => this._queueRefresh(true))), this.register(this._coreBrowserService.onDprChange(() => this._queueRefresh(true))), this._queueRefresh(true);
        }
        _refreshDrawConstants() {
          const e4 = Math.floor(this._canvas.width / 3), t4 = Math.ceil(this._canvas.width / 3);
          l2.full = this._canvas.width, l2.left = e4, l2.center = t4, l2.right = e4, this._refreshDrawHeightConstants(), d2.full = 0, d2.left = 0, d2.center = l2.left, d2.right = l2.left + l2.center;
        }
        _refreshDrawHeightConstants() {
          c2.full = Math.round(2 * this._coreBrowserService.dpr);
          const e4 = this._canvas.height / this._bufferService.buffer.lines.length, t4 = Math.round(Math.max(Math.min(e4, 12), 6) * this._coreBrowserService.dpr);
          c2.left = t4, c2.center = t4, c2.right = t4;
        }
        _refreshColorZonePadding() {
          this._colorZoneStore.setPadding({ full: Math.floor(this._bufferService.buffers.active.lines.length / (this._canvas.height - 1) * c2.full), left: Math.floor(this._bufferService.buffers.active.lines.length / (this._canvas.height - 1) * c2.left), center: Math.floor(this._bufferService.buffers.active.lines.length / (this._canvas.height - 1) * c2.center), right: Math.floor(this._bufferService.buffers.active.lines.length / (this._canvas.height - 1) * c2.right) }), this._lastKnownBufferLength = this._bufferService.buffers.normal.lines.length;
        }
        _refreshCanvasDimensions() {
          this._canvas.style.width = `${this._width}px`, this._canvas.width = Math.round(this._width * this._coreBrowserService.dpr), this._canvas.style.height = `${this._screenElement.clientHeight}px`, this._canvas.height = Math.round(this._screenElement.clientHeight * this._coreBrowserService.dpr), this._refreshDrawConstants(), this._refreshColorZonePadding();
        }
        _refreshDecorations() {
          this._shouldUpdateDimensions && this._refreshCanvasDimensions(), this._ctx.clearRect(0, 0, this._canvas.width, this._canvas.height), this._colorZoneStore.clear();
          for (const e5 of this._decorationService.decorations) this._colorZoneStore.addDecoration(e5);
          this._ctx.lineWidth = 1;
          const e4 = this._colorZoneStore.zones;
          for (const t4 of e4) "full" !== t4.position && this._renderColorZone(t4);
          for (const t4 of e4) "full" === t4.position && this._renderColorZone(t4);
          this._shouldUpdateDimensions = false, this._shouldUpdateAnchor = false;
        }
        _renderColorZone(e4) {
          this._ctx.fillStyle = e4.color, this._ctx.fillRect(d2[e4.position || "full"], Math.round((this._canvas.height - 1) * (e4.startBufferLine / this._bufferService.buffers.active.lines.length) - c2[e4.position || "full"] / 2), l2[e4.position || "full"], Math.round((this._canvas.height - 1) * ((e4.endBufferLine - e4.startBufferLine) / this._bufferService.buffers.active.lines.length) + c2[e4.position || "full"]));
        }
        _queueRefresh(e4, t4) {
          this._shouldUpdateDimensions = e4 || this._shouldUpdateDimensions, this._shouldUpdateAnchor = t4 || this._shouldUpdateAnchor, void 0 === this._animationFrame && (this._animationFrame = this._coreBrowserService.window.requestAnimationFrame(() => {
            this._refreshDecorations(), this._animationFrame = void 0;
          }));
        }
      };
      t3.OverviewRulerRenderer = _2 = s3([r2(2, h2.IBufferService), r2(3, h2.IDecorationService), r2(4, o2.IRenderService), r2(5, h2.IOptionsService), r2(6, o2.ICoreBrowserService)], _2);
    }, 2950: function(e3, t3, i3) {
      var s3 = this && this.__decorate || function(e4, t4, i4, s4) {
        var r3, n3 = arguments.length, o3 = n3 < 3 ? t4 : null === s4 ? s4 = Object.getOwnPropertyDescriptor(t4, i4) : s4;
        if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) o3 = Reflect.decorate(e4, t4, i4, s4);
        else for (var a3 = e4.length - 1; a3 >= 0; a3--) (r3 = e4[a3]) && (o3 = (n3 < 3 ? r3(o3) : n3 > 3 ? r3(t4, i4, o3) : r3(t4, i4)) || o3);
        return n3 > 3 && o3 && Object.defineProperty(t4, i4, o3), o3;
      }, r2 = this && this.__param || function(e4, t4) {
        return function(i4, s4) {
          t4(i4, s4, e4);
        };
      };
      Object.defineProperty(t3, "__esModule", { value: true }), t3.CompositionHelper = void 0;
      const n2 = i3(4725), o2 = i3(2585), a2 = i3(2584);
      let h2 = t3.CompositionHelper = class {
        get isComposing() {
          return this._isComposing;
        }
        constructor(e4, t4, i4, s4, r3, n3) {
          this._textarea = e4, this._compositionView = t4, this._bufferService = i4, this._optionsService = s4, this._coreService = r3, this._renderService = n3, this._isComposing = false, this._isSendingComposition = false, this._compositionPosition = { start: 0, end: 0 }, this._dataAlreadySent = "";
        }
        compositionstart() {
          this._isComposing = true, this._compositionPosition.start = this._textarea.value.length, this._compositionView.textContent = "", this._dataAlreadySent = "", this._compositionView.classList.add("active");
        }
        compositionupdate(e4) {
          this._compositionView.textContent = e4.data, this.updateCompositionElements(), setTimeout(() => {
            this._compositionPosition.end = this._textarea.value.length;
          }, 0);
        }
        compositionend() {
          this._finalizeComposition(true);
        }
        keydown(e4) {
          if (this._isComposing || this._isSendingComposition) {
            if (229 === e4.keyCode) return false;
            if (16 === e4.keyCode || 17 === e4.keyCode || 18 === e4.keyCode) return false;
            this._finalizeComposition(false);
          }
          return 229 !== e4.keyCode || (this._handleAnyTextareaChanges(), false);
        }
        _finalizeComposition(e4) {
          if (this._compositionView.classList.remove("active"), this._isComposing = false, e4) {
            const e5 = { start: this._compositionPosition.start, end: this._compositionPosition.end };
            this._isSendingComposition = true, setTimeout(() => {
              if (this._isSendingComposition) {
                let t4;
                this._isSendingComposition = false, e5.start += this._dataAlreadySent.length, t4 = this._isComposing ? this._textarea.value.substring(e5.start, e5.end) : this._textarea.value.substring(e5.start), t4.length > 0 && this._coreService.triggerDataEvent(t4, true);
              }
            }, 0);
          } else {
            this._isSendingComposition = false;
            const e5 = this._textarea.value.substring(this._compositionPosition.start, this._compositionPosition.end);
            this._coreService.triggerDataEvent(e5, true);
          }
        }
        _handleAnyTextareaChanges() {
          const e4 = this._textarea.value;
          setTimeout(() => {
            if (!this._isComposing) {
              const t4 = this._textarea.value, i4 = t4.replace(e4, "");
              this._dataAlreadySent = i4, t4.length > e4.length ? this._coreService.triggerDataEvent(i4, true) : t4.length < e4.length ? this._coreService.triggerDataEvent(`${a2.C0.DEL}`, true) : t4.length === e4.length && t4 !== e4 && this._coreService.triggerDataEvent(t4, true);
            }
          }, 0);
        }
        updateCompositionElements(e4) {
          if (this._isComposing) {
            if (this._bufferService.buffer.isCursorInViewport) {
              const e5 = Math.min(this._bufferService.buffer.x, this._bufferService.cols - 1), t4 = this._renderService.dimensions.css.cell.height, i4 = this._bufferService.buffer.y * this._renderService.dimensions.css.cell.height, s4 = e5 * this._renderService.dimensions.css.cell.width;
              this._compositionView.style.left = s4 + "px", this._compositionView.style.top = i4 + "px", this._compositionView.style.height = t4 + "px", this._compositionView.style.lineHeight = t4 + "px", this._compositionView.style.fontFamily = this._optionsService.rawOptions.fontFamily, this._compositionView.style.fontSize = this._optionsService.rawOptions.fontSize + "px";
              const r3 = this._compositionView.getBoundingClientRect();
              this._textarea.style.left = s4 + "px", this._textarea.style.top = i4 + "px", this._textarea.style.width = Math.max(r3.width, 1) + "px", this._textarea.style.height = Math.max(r3.height, 1) + "px", this._textarea.style.lineHeight = r3.height + "px";
            }
            e4 || setTimeout(() => this.updateCompositionElements(true), 0);
          }
        }
      };
      t3.CompositionHelper = h2 = s3([r2(2, o2.IBufferService), r2(3, o2.IOptionsService), r2(4, o2.ICoreService), r2(5, n2.IRenderService)], h2);
    }, 9806: (e3, t3) => {
      function i3(e4, t4, i4) {
        const s3 = i4.getBoundingClientRect(), r2 = e4.getComputedStyle(i4), n2 = parseInt(r2.getPropertyValue("padding-left")), o2 = parseInt(r2.getPropertyValue("padding-top"));
        return [t4.clientX - s3.left - n2, t4.clientY - s3.top - o2];
      }
      __name(i3, "i");
      Object.defineProperty(t3, "__esModule", { value: true }), t3.getCoords = t3.getCoordsRelativeToElement = void 0, t3.getCoordsRelativeToElement = i3, t3.getCoords = function(e4, t4, s3, r2, n2, o2, a2, h2, c2) {
        if (!o2) return;
        const l2 = i3(e4, t4, s3);
        return l2 ? (l2[0] = Math.ceil((l2[0] + (c2 ? a2 / 2 : 0)) / a2), l2[1] = Math.ceil(l2[1] / h2), l2[0] = Math.min(Math.max(l2[0], 1), r2 + (c2 ? 1 : 0)), l2[1] = Math.min(Math.max(l2[1], 1), n2), l2) : void 0;
      };
    }, 9504: (e3, t3, i3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.moveToCellSequence = void 0;
      const s3 = i3(2584);
      function r2(e4, t4, i4, s4) {
        const r3 = e4 - n2(e4, i4), a3 = t4 - n2(t4, i4), l2 = Math.abs(r3 - a3) - function(e5, t5, i5) {
          let s5 = 0;
          const r4 = e5 - n2(e5, i5), a4 = t5 - n2(t5, i5);
          for (let n3 = 0; n3 < Math.abs(r4 - a4); n3++) {
            const a5 = "A" === o2(e5, t5) ? -1 : 1, h3 = i5.buffer.lines.get(r4 + a5 * n3);
            h3?.isWrapped && s5++;
          }
          return s5;
        }(e4, t4, i4);
        return c2(l2, h2(o2(e4, t4), s4));
      }
      __name(r2, "r");
      function n2(e4, t4) {
        let i4 = 0, s4 = t4.buffer.lines.get(e4), r3 = s4?.isWrapped;
        for (; r3 && e4 >= 0 && e4 < t4.rows; ) i4++, s4 = t4.buffer.lines.get(--e4), r3 = s4?.isWrapped;
        return i4;
      }
      __name(n2, "n");
      function o2(e4, t4) {
        return e4 > t4 ? "A" : "B";
      }
      __name(o2, "o");
      function a2(e4, t4, i4, s4, r3, n3) {
        let o3 = e4, a3 = t4, h3 = "";
        for (; o3 !== i4 || a3 !== s4; ) o3 += r3 ? 1 : -1, r3 && o3 > n3.cols - 1 ? (h3 += n3.buffer.translateBufferLineToString(a3, false, e4, o3), o3 = 0, e4 = 0, a3++) : !r3 && o3 < 0 && (h3 += n3.buffer.translateBufferLineToString(a3, false, 0, e4 + 1), o3 = n3.cols - 1, e4 = o3, a3--);
        return h3 + n3.buffer.translateBufferLineToString(a3, false, e4, o3);
      }
      __name(a2, "a");
      function h2(e4, t4) {
        const i4 = t4 ? "O" : "[";
        return s3.C0.ESC + i4 + e4;
      }
      __name(h2, "h");
      function c2(e4, t4) {
        e4 = Math.floor(e4);
        let i4 = "";
        for (let s4 = 0; s4 < e4; s4++) i4 += t4;
        return i4;
      }
      __name(c2, "c");
      t3.moveToCellSequence = function(e4, t4, i4, s4) {
        const o3 = i4.buffer.x, l2 = i4.buffer.y;
        if (!i4.buffer.hasScrollback) return function(e5, t5, i5, s5, o4, l3) {
          return 0 === r2(t5, s5, o4, l3).length ? "" : c2(a2(e5, t5, e5, t5 - n2(t5, o4), false, o4).length, h2("D", l3));
        }(o3, l2, 0, t4, i4, s4) + r2(l2, t4, i4, s4) + function(e5, t5, i5, s5, o4, l3) {
          let d3;
          d3 = r2(t5, s5, o4, l3).length > 0 ? s5 - n2(s5, o4) : t5;
          const _3 = s5, u2 = function(e6, t6, i6, s6, o5, a3) {
            let h3;
            return h3 = r2(i6, s6, o5, a3).length > 0 ? s6 - n2(s6, o5) : t6, e6 < i6 && h3 <= s6 || e6 >= i6 && h3 < s6 ? "C" : "D";
          }(e5, t5, i5, s5, o4, l3);
          return c2(a2(e5, d3, i5, _3, "C" === u2, o4).length, h2(u2, l3));
        }(o3, l2, e4, t4, i4, s4);
        let d2;
        if (l2 === t4) return d2 = o3 > e4 ? "D" : "C", c2(Math.abs(o3 - e4), h2(d2, s4));
        d2 = l2 > t4 ? "D" : "C";
        const _2 = Math.abs(l2 - t4);
        return c2(function(e5, t5) {
          return t5.cols - e5;
        }(l2 > t4 ? e4 : o3, i4) + (_2 - 1) * i4.cols + 1 + ((l2 > t4 ? o3 : e4) - 1), h2(d2, s4));
      };
    }, 1296: function(e3, t3, i3) {
      var s3 = this && this.__decorate || function(e4, t4, i4, s4) {
        var r3, n3 = arguments.length, o3 = n3 < 3 ? t4 : null === s4 ? s4 = Object.getOwnPropertyDescriptor(t4, i4) : s4;
        if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) o3 = Reflect.decorate(e4, t4, i4, s4);
        else for (var a3 = e4.length - 1; a3 >= 0; a3--) (r3 = e4[a3]) && (o3 = (n3 < 3 ? r3(o3) : n3 > 3 ? r3(t4, i4, o3) : r3(t4, i4)) || o3);
        return n3 > 3 && o3 && Object.defineProperty(t4, i4, o3), o3;
      }, r2 = this && this.__param || function(e4, t4) {
        return function(i4, s4) {
          t4(i4, s4, e4);
        };
      };
      Object.defineProperty(t3, "__esModule", { value: true }), t3.DomRenderer = void 0;
      const n2 = i3(3787), o2 = i3(2550), a2 = i3(2223), h2 = i3(6171), c2 = i3(6052), l2 = i3(4725), d2 = i3(8055), _2 = i3(8460), u2 = i3(844), f2 = i3(2585), v2 = "xterm-dom-renderer-owner-", p2 = "xterm-rows", g2 = "xterm-fg-", m2 = "xterm-bg-", S2 = "xterm-focus", C2 = "xterm-selection";
      let b2 = 1, w2 = t3.DomRenderer = class extends u2.Disposable {
        constructor(e4, t4, i4, s4, r3, a3, l3, d3, f3, g3, m3, S3, w3) {
          super(), this._terminal = e4, this._document = t4, this._element = i4, this._screenElement = s4, this._viewportElement = r3, this._helperContainer = a3, this._linkifier2 = l3, this._charSizeService = f3, this._optionsService = g3, this._bufferService = m3, this._coreBrowserService = S3, this._themeService = w3, this._terminalClass = b2++, this._rowElements = [], this._selectionRenderModel = (0, c2.createSelectionRenderModel)(), this.onRequestRedraw = this.register(new _2.EventEmitter()).event, this._rowContainer = this._document.createElement("div"), this._rowContainer.classList.add(p2), this._rowContainer.style.lineHeight = "normal", this._rowContainer.setAttribute("aria-hidden", "true"), this._refreshRowElements(this._bufferService.cols, this._bufferService.rows), this._selectionContainer = this._document.createElement("div"), this._selectionContainer.classList.add(C2), this._selectionContainer.setAttribute("aria-hidden", "true"), this.dimensions = (0, h2.createRenderDimensions)(), this._updateDimensions(), this.register(this._optionsService.onOptionChange(() => this._handleOptionsChanged())), this.register(this._themeService.onChangeColors((e5) => this._injectCss(e5))), this._injectCss(this._themeService.colors), this._rowFactory = d3.createInstance(n2.DomRendererRowFactory, document), this._element.classList.add(v2 + this._terminalClass), this._screenElement.appendChild(this._rowContainer), this._screenElement.appendChild(this._selectionContainer), this.register(this._linkifier2.onShowLinkUnderline((e5) => this._handleLinkHover(e5))), this.register(this._linkifier2.onHideLinkUnderline((e5) => this._handleLinkLeave(e5))), this.register((0, u2.toDisposable)(() => {
            this._element.classList.remove(v2 + this._terminalClass), this._rowContainer.remove(), this._selectionContainer.remove(), this._widthCache.dispose(), this._themeStyleElement.remove(), this._dimensionsStyleElement.remove();
          })), this._widthCache = new o2.WidthCache(this._document, this._helperContainer), this._widthCache.setFont(this._optionsService.rawOptions.fontFamily, this._optionsService.rawOptions.fontSize, this._optionsService.rawOptions.fontWeight, this._optionsService.rawOptions.fontWeightBold), this._setDefaultSpacing();
        }
        _updateDimensions() {
          const e4 = this._coreBrowserService.dpr;
          this.dimensions.device.char.width = this._charSizeService.width * e4, this.dimensions.device.char.height = Math.ceil(this._charSizeService.height * e4), this.dimensions.device.cell.width = this.dimensions.device.char.width + Math.round(this._optionsService.rawOptions.letterSpacing), this.dimensions.device.cell.height = Math.floor(this.dimensions.device.char.height * this._optionsService.rawOptions.lineHeight), this.dimensions.device.char.left = 0, this.dimensions.device.char.top = 0, this.dimensions.device.canvas.width = this.dimensions.device.cell.width * this._bufferService.cols, this.dimensions.device.canvas.height = this.dimensions.device.cell.height * this._bufferService.rows, this.dimensions.css.canvas.width = Math.round(this.dimensions.device.canvas.width / e4), this.dimensions.css.canvas.height = Math.round(this.dimensions.device.canvas.height / e4), this.dimensions.css.cell.width = this.dimensions.css.canvas.width / this._bufferService.cols, this.dimensions.css.cell.height = this.dimensions.css.canvas.height / this._bufferService.rows;
          for (const e5 of this._rowElements) e5.style.width = `${this.dimensions.css.canvas.width}px`, e5.style.height = `${this.dimensions.css.cell.height}px`, e5.style.lineHeight = `${this.dimensions.css.cell.height}px`, e5.style.overflow = "hidden";
          this._dimensionsStyleElement || (this._dimensionsStyleElement = this._document.createElement("style"), this._screenElement.appendChild(this._dimensionsStyleElement));
          const t4 = `${this._terminalSelector} .${p2} span { display: inline-block; height: 100%; vertical-align: top;}`;
          this._dimensionsStyleElement.textContent = t4, this._selectionContainer.style.height = this._viewportElement.style.height, this._screenElement.style.width = `${this.dimensions.css.canvas.width}px`, this._screenElement.style.height = `${this.dimensions.css.canvas.height}px`;
        }
        _injectCss(e4) {
          this._themeStyleElement || (this._themeStyleElement = this._document.createElement("style"), this._screenElement.appendChild(this._themeStyleElement));
          let t4 = `${this._terminalSelector} .${p2} { color: ${e4.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;
          t4 += `${this._terminalSelector} .${p2} .xterm-dim { color: ${d2.color.multiplyOpacity(e4.foreground, 0.5).css};}`, t4 += `${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;
          const i4 = `blink_underline_${this._terminalClass}`, s4 = `blink_bar_${this._terminalClass}`, r3 = `blink_block_${this._terminalClass}`;
          t4 += `@keyframes ${i4} { 50% {  border-bottom-style: hidden; }}`, t4 += `@keyframes ${s4} { 50% {  box-shadow: none; }}`, t4 += `@keyframes ${r3} { 0% {  background-color: ${e4.cursor.css};  color: ${e4.cursorAccent.css}; } 50% {  background-color: inherit;  color: ${e4.cursor.css}; }}`, t4 += `${this._terminalSelector} .${p2}.${S2} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${i4} 1s step-end infinite;}${this._terminalSelector} .${p2}.${S2} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${s4} 1s step-end infinite;}${this._terminalSelector} .${p2}.${S2} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${r3} 1s step-end infinite;}${this._terminalSelector} .${p2} .xterm-cursor.xterm-cursor-block { background-color: ${e4.cursor.css}; color: ${e4.cursorAccent.css};}${this._terminalSelector} .${p2} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e4.cursor.css} !important; color: ${e4.cursorAccent.css} !important;}${this._terminalSelector} .${p2} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e4.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${p2} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e4.cursor.css} inset;}${this._terminalSelector} .${p2} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e4.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`, t4 += `${this._terminalSelector} .${C2} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${C2} div { position: absolute; background-color: ${e4.selectionBackgroundOpaque.css};}${this._terminalSelector} .${C2} div { position: absolute; background-color: ${e4.selectionInactiveBackgroundOpaque.css};}`;
          for (const [i5, s5] of e4.ansi.entries()) t4 += `${this._terminalSelector} .${g2}${i5} { color: ${s5.css}; }${this._terminalSelector} .${g2}${i5}.xterm-dim { color: ${d2.color.multiplyOpacity(s5, 0.5).css}; }${this._terminalSelector} .${m2}${i5} { background-color: ${s5.css}; }`;
          t4 += `${this._terminalSelector} .${g2}${a2.INVERTED_DEFAULT_COLOR} { color: ${d2.color.opaque(e4.background).css}; }${this._terminalSelector} .${g2}${a2.INVERTED_DEFAULT_COLOR}.xterm-dim { color: ${d2.color.multiplyOpacity(d2.color.opaque(e4.background), 0.5).css}; }${this._terminalSelector} .${m2}${a2.INVERTED_DEFAULT_COLOR} { background-color: ${e4.foreground.css}; }`, this._themeStyleElement.textContent = t4;
        }
        _setDefaultSpacing() {
          const e4 = this.dimensions.css.cell.width - this._widthCache.get("W", false, false);
          this._rowContainer.style.letterSpacing = `${e4}px`, this._rowFactory.defaultSpacing = e4;
        }
        handleDevicePixelRatioChange() {
          this._updateDimensions(), this._widthCache.clear(), this._setDefaultSpacing();
        }
        _refreshRowElements(e4, t4) {
          for (let e5 = this._rowElements.length; e5 <= t4; e5++) {
            const e6 = this._document.createElement("div");
            this._rowContainer.appendChild(e6), this._rowElements.push(e6);
          }
          for (; this._rowElements.length > t4; ) this._rowContainer.removeChild(this._rowElements.pop());
        }
        handleResize(e4, t4) {
          this._refreshRowElements(e4, t4), this._updateDimensions(), this.handleSelectionChanged(this._selectionRenderModel.selectionStart, this._selectionRenderModel.selectionEnd, this._selectionRenderModel.columnSelectMode);
        }
        handleCharSizeChanged() {
          this._updateDimensions(), this._widthCache.clear(), this._setDefaultSpacing();
        }
        handleBlur() {
          this._rowContainer.classList.remove(S2), this.renderRows(0, this._bufferService.rows - 1);
        }
        handleFocus() {
          this._rowContainer.classList.add(S2), this.renderRows(this._bufferService.buffer.y, this._bufferService.buffer.y);
        }
        handleSelectionChanged(e4, t4, i4) {
          if (this._selectionContainer.replaceChildren(), this._rowFactory.handleSelectionChanged(e4, t4, i4), this.renderRows(0, this._bufferService.rows - 1), !e4 || !t4) return;
          this._selectionRenderModel.update(this._terminal, e4, t4, i4);
          const s4 = this._selectionRenderModel.viewportStartRow, r3 = this._selectionRenderModel.viewportEndRow, n3 = this._selectionRenderModel.viewportCappedStartRow, o3 = this._selectionRenderModel.viewportCappedEndRow;
          if (n3 >= this._bufferService.rows || o3 < 0) return;
          const a3 = this._document.createDocumentFragment();
          if (i4) {
            const i5 = e4[0] > t4[0];
            a3.appendChild(this._createSelectionElement(n3, i5 ? t4[0] : e4[0], i5 ? e4[0] : t4[0], o3 - n3 + 1));
          } else {
            const i5 = s4 === n3 ? e4[0] : 0, h3 = n3 === r3 ? t4[0] : this._bufferService.cols;
            a3.appendChild(this._createSelectionElement(n3, i5, h3));
            const c3 = o3 - n3 - 1;
            if (a3.appendChild(this._createSelectionElement(n3 + 1, 0, this._bufferService.cols, c3)), n3 !== o3) {
              const e5 = r3 === o3 ? t4[0] : this._bufferService.cols;
              a3.appendChild(this._createSelectionElement(o3, 0, e5));
            }
          }
          this._selectionContainer.appendChild(a3);
        }
        _createSelectionElement(e4, t4, i4, s4 = 1) {
          const r3 = this._document.createElement("div"), n3 = t4 * this.dimensions.css.cell.width;
          let o3 = this.dimensions.css.cell.width * (i4 - t4);
          return n3 + o3 > this.dimensions.css.canvas.width && (o3 = this.dimensions.css.canvas.width - n3), r3.style.height = s4 * this.dimensions.css.cell.height + "px", r3.style.top = e4 * this.dimensions.css.cell.height + "px", r3.style.left = `${n3}px`, r3.style.width = `${o3}px`, r3;
        }
        handleCursorMove() {
        }
        _handleOptionsChanged() {
          this._updateDimensions(), this._injectCss(this._themeService.colors), this._widthCache.setFont(this._optionsService.rawOptions.fontFamily, this._optionsService.rawOptions.fontSize, this._optionsService.rawOptions.fontWeight, this._optionsService.rawOptions.fontWeightBold), this._setDefaultSpacing();
        }
        clear() {
          for (const e4 of this._rowElements) e4.replaceChildren();
        }
        renderRows(e4, t4) {
          const i4 = this._bufferService.buffer, s4 = i4.ybase + i4.y, r3 = Math.min(i4.x, this._bufferService.cols - 1), n3 = this._optionsService.rawOptions.cursorBlink, o3 = this._optionsService.rawOptions.cursorStyle, a3 = this._optionsService.rawOptions.cursorInactiveStyle;
          for (let h3 = e4; h3 <= t4; h3++) {
            const e5 = h3 + i4.ydisp, t5 = this._rowElements[h3], c3 = i4.lines.get(e5);
            if (!t5 || !c3) break;
            t5.replaceChildren(...this._rowFactory.createRow(c3, e5, e5 === s4, o3, a3, r3, n3, this.dimensions.css.cell.width, this._widthCache, -1, -1));
          }
        }
        get _terminalSelector() {
          return `.${v2}${this._terminalClass}`;
        }
        _handleLinkHover(e4) {
          this._setCellUnderline(e4.x1, e4.x2, e4.y1, e4.y2, e4.cols, true);
        }
        _handleLinkLeave(e4) {
          this._setCellUnderline(e4.x1, e4.x2, e4.y1, e4.y2, e4.cols, false);
        }
        _setCellUnderline(e4, t4, i4, s4, r3, n3) {
          i4 < 0 && (e4 = 0), s4 < 0 && (t4 = 0);
          const o3 = this._bufferService.rows - 1;
          i4 = Math.max(Math.min(i4, o3), 0), s4 = Math.max(Math.min(s4, o3), 0), r3 = Math.min(r3, this._bufferService.cols);
          const a3 = this._bufferService.buffer, h3 = a3.ybase + a3.y, c3 = Math.min(a3.x, r3 - 1), l3 = this._optionsService.rawOptions.cursorBlink, d3 = this._optionsService.rawOptions.cursorStyle, _3 = this._optionsService.rawOptions.cursorInactiveStyle;
          for (let o4 = i4; o4 <= s4; ++o4) {
            const u3 = o4 + a3.ydisp, f3 = this._rowElements[o4], v3 = a3.lines.get(u3);
            if (!f3 || !v3) break;
            f3.replaceChildren(...this._rowFactory.createRow(v3, u3, u3 === h3, d3, _3, c3, l3, this.dimensions.css.cell.width, this._widthCache, n3 ? o4 === i4 ? e4 : 0 : -1, n3 ? (o4 === s4 ? t4 : r3) - 1 : -1));
          }
        }
      };
      t3.DomRenderer = w2 = s3([r2(7, f2.IInstantiationService), r2(8, l2.ICharSizeService), r2(9, f2.IOptionsService), r2(10, f2.IBufferService), r2(11, l2.ICoreBrowserService), r2(12, l2.IThemeService)], w2);
    }, 3787: function(e3, t3, i3) {
      var s3 = this && this.__decorate || function(e4, t4, i4, s4) {
        var r3, n3 = arguments.length, o3 = n3 < 3 ? t4 : null === s4 ? s4 = Object.getOwnPropertyDescriptor(t4, i4) : s4;
        if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) o3 = Reflect.decorate(e4, t4, i4, s4);
        else for (var a3 = e4.length - 1; a3 >= 0; a3--) (r3 = e4[a3]) && (o3 = (n3 < 3 ? r3(o3) : n3 > 3 ? r3(t4, i4, o3) : r3(t4, i4)) || o3);
        return n3 > 3 && o3 && Object.defineProperty(t4, i4, o3), o3;
      }, r2 = this && this.__param || function(e4, t4) {
        return function(i4, s4) {
          t4(i4, s4, e4);
        };
      };
      Object.defineProperty(t3, "__esModule", { value: true }), t3.DomRendererRowFactory = void 0;
      const n2 = i3(2223), o2 = i3(643), a2 = i3(511), h2 = i3(2585), c2 = i3(8055), l2 = i3(4725), d2 = i3(4269), _2 = i3(6171), u2 = i3(3734);
      let f2 = t3.DomRendererRowFactory = class {
        constructor(e4, t4, i4, s4, r3, n3, o3) {
          this._document = e4, this._characterJoinerService = t4, this._optionsService = i4, this._coreBrowserService = s4, this._coreService = r3, this._decorationService = n3, this._themeService = o3, this._workCell = new a2.CellData(), this._columnSelectMode = false, this.defaultSpacing = 0;
        }
        handleSelectionChanged(e4, t4, i4) {
          this._selectionStart = e4, this._selectionEnd = t4, this._columnSelectMode = i4;
        }
        createRow(e4, t4, i4, s4, r3, a3, h3, l3, _3, f3, p2) {
          const g2 = [], m2 = this._characterJoinerService.getJoinedCharacters(t4), S2 = this._themeService.colors;
          let C2, b2 = e4.getNoBgTrimmedLength();
          i4 && b2 < a3 + 1 && (b2 = a3 + 1);
          let w2 = 0, y2 = "", E = 0, k2 = 0, L2 = 0, D2 = false, R = 0, x2 = false, A2 = 0;
          const B2 = [], T2 = -1 !== f3 && -1 !== p2;
          for (let M2 = 0; M2 < b2; M2++) {
            e4.loadCell(M2, this._workCell);
            let b3 = this._workCell.getWidth();
            if (0 === b3) continue;
            let O2 = false, P2 = M2, I2 = this._workCell;
            if (m2.length > 0 && M2 === m2[0][0]) {
              O2 = true;
              const t5 = m2.shift();
              I2 = new d2.JoinedCellData(this._workCell, e4.translateToString(true, t5[0], t5[1]), t5[1] - t5[0]), P2 = t5[1] - 1, b3 = I2.getWidth();
            }
            const H2 = this._isCellInSelection(M2, t4), F2 = i4 && M2 === a3, W2 = T2 && M2 >= f3 && M2 <= p2;
            let U2 = false;
            this._decorationService.forEachDecorationAtCell(M2, t4, void 0, (e5) => {
              U2 = true;
            });
            let N2 = I2.getChars() || o2.WHITESPACE_CELL_CHAR;
            if (" " === N2 && (I2.isUnderline() || I2.isOverline()) && (N2 = " "), A2 = b3 * l3 - _3.get(N2, I2.isBold(), I2.isItalic()), C2) {
              if (w2 && (H2 && x2 || !H2 && !x2 && I2.bg === E) && (H2 && x2 && S2.selectionForeground || I2.fg === k2) && I2.extended.ext === L2 && W2 === D2 && A2 === R && !F2 && !O2 && !U2) {
                I2.isInvisible() ? y2 += o2.WHITESPACE_CELL_CHAR : y2 += N2, w2++;
                continue;
              }
              w2 && (C2.textContent = y2), C2 = this._document.createElement("span"), w2 = 0, y2 = "";
            } else C2 = this._document.createElement("span");
            if (E = I2.bg, k2 = I2.fg, L2 = I2.extended.ext, D2 = W2, R = A2, x2 = H2, O2 && a3 >= M2 && a3 <= P2 && (a3 = M2), !this._coreService.isCursorHidden && F2 && this._coreService.isCursorInitialized) {
              if (B2.push("xterm-cursor"), this._coreBrowserService.isFocused) h3 && B2.push("xterm-cursor-blink"), B2.push("bar" === s4 ? "xterm-cursor-bar" : "underline" === s4 ? "xterm-cursor-underline" : "xterm-cursor-block");
              else if (r3) switch (r3) {
                case "outline":
                  B2.push("xterm-cursor-outline");
                  break;
                case "block":
                  B2.push("xterm-cursor-block");
                  break;
                case "bar":
                  B2.push("xterm-cursor-bar");
                  break;
                case "underline":
                  B2.push("xterm-cursor-underline");
              }
            }
            if (I2.isBold() && B2.push("xterm-bold"), I2.isItalic() && B2.push("xterm-italic"), I2.isDim() && B2.push("xterm-dim"), y2 = I2.isInvisible() ? o2.WHITESPACE_CELL_CHAR : I2.getChars() || o2.WHITESPACE_CELL_CHAR, I2.isUnderline() && (B2.push(`xterm-underline-${I2.extended.underlineStyle}`), " " === y2 && (y2 = " "), !I2.isUnderlineColorDefault())) if (I2.isUnderlineColorRGB()) C2.style.textDecorationColor = `rgb(${u2.AttributeData.toColorRGB(I2.getUnderlineColor()).join(",")})`;
            else {
              let e5 = I2.getUnderlineColor();
              this._optionsService.rawOptions.drawBoldTextInBrightColors && I2.isBold() && e5 < 8 && (e5 += 8), C2.style.textDecorationColor = S2.ansi[e5].css;
            }
            I2.isOverline() && (B2.push("xterm-overline"), " " === y2 && (y2 = " ")), I2.isStrikethrough() && B2.push("xterm-strikethrough"), W2 && (C2.style.textDecoration = "underline");
            let $2 = I2.getFgColor(), j2 = I2.getFgColorMode(), z2 = I2.getBgColor(), K2 = I2.getBgColorMode();
            const q2 = !!I2.isInverse();
            if (q2) {
              const e5 = $2;
              $2 = z2, z2 = e5;
              const t5 = j2;
              j2 = K2, K2 = t5;
            }
            let V2, G2, X2, J2 = false;
            switch (this._decorationService.forEachDecorationAtCell(M2, t4, void 0, (e5) => {
              "top" !== e5.options.layer && J2 || (e5.backgroundColorRGB && (K2 = 50331648, z2 = e5.backgroundColorRGB.rgba >> 8 & 16777215, V2 = e5.backgroundColorRGB), e5.foregroundColorRGB && (j2 = 50331648, $2 = e5.foregroundColorRGB.rgba >> 8 & 16777215, G2 = e5.foregroundColorRGB), J2 = "top" === e5.options.layer);
            }), !J2 && H2 && (V2 = this._coreBrowserService.isFocused ? S2.selectionBackgroundOpaque : S2.selectionInactiveBackgroundOpaque, z2 = V2.rgba >> 8 & 16777215, K2 = 50331648, J2 = true, S2.selectionForeground && (j2 = 50331648, $2 = S2.selectionForeground.rgba >> 8 & 16777215, G2 = S2.selectionForeground)), J2 && B2.push("xterm-decoration-top"), K2) {
              case 16777216:
              case 33554432:
                X2 = S2.ansi[z2], B2.push(`xterm-bg-${z2}`);
                break;
              case 50331648:
                X2 = c2.channels.toColor(z2 >> 16, z2 >> 8 & 255, 255 & z2), this._addStyle(C2, `background-color:#${v2((z2 >>> 0).toString(16), "0", 6)}`);
                break;
              default:
                q2 ? (X2 = S2.foreground, B2.push(`xterm-bg-${n2.INVERTED_DEFAULT_COLOR}`)) : X2 = S2.background;
            }
            switch (V2 || I2.isDim() && (V2 = c2.color.multiplyOpacity(X2, 0.5)), j2) {
              case 16777216:
              case 33554432:
                I2.isBold() && $2 < 8 && this._optionsService.rawOptions.drawBoldTextInBrightColors && ($2 += 8), this._applyMinimumContrast(C2, X2, S2.ansi[$2], I2, V2, void 0) || B2.push(`xterm-fg-${$2}`);
                break;
              case 50331648:
                const e5 = c2.channels.toColor($2 >> 16 & 255, $2 >> 8 & 255, 255 & $2);
                this._applyMinimumContrast(C2, X2, e5, I2, V2, G2) || this._addStyle(C2, `color:#${v2($2.toString(16), "0", 6)}`);
                break;
              default:
                this._applyMinimumContrast(C2, X2, S2.foreground, I2, V2, G2) || q2 && B2.push(`xterm-fg-${n2.INVERTED_DEFAULT_COLOR}`);
            }
            B2.length && (C2.className = B2.join(" "), B2.length = 0), F2 || O2 || U2 ? C2.textContent = y2 : w2++, A2 !== this.defaultSpacing && (C2.style.letterSpacing = `${A2}px`), g2.push(C2), M2 = P2;
          }
          return C2 && w2 && (C2.textContent = y2), g2;
        }
        _applyMinimumContrast(e4, t4, i4, s4, r3, n3) {
          if (1 === this._optionsService.rawOptions.minimumContrastRatio || (0, _2.treatGlyphAsBackgroundColor)(s4.getCode())) return false;
          const o3 = this._getContrastCache(s4);
          let a3;
          if (r3 || n3 || (a3 = o3.getColor(t4.rgba, i4.rgba)), void 0 === a3) {
            const e5 = this._optionsService.rawOptions.minimumContrastRatio / (s4.isDim() ? 2 : 1);
            a3 = c2.color.ensureContrastRatio(r3 || t4, n3 || i4, e5), o3.setColor((r3 || t4).rgba, (n3 || i4).rgba, a3 ?? null);
          }
          return !!a3 && (this._addStyle(e4, `color:${a3.css}`), true);
        }
        _getContrastCache(e4) {
          return e4.isDim() ? this._themeService.colors.halfContrastCache : this._themeService.colors.contrastCache;
        }
        _addStyle(e4, t4) {
          e4.setAttribute("style", `${e4.getAttribute("style") || ""}${t4};`);
        }
        _isCellInSelection(e4, t4) {
          const i4 = this._selectionStart, s4 = this._selectionEnd;
          return !(!i4 || !s4) && (this._columnSelectMode ? i4[0] <= s4[0] ? e4 >= i4[0] && t4 >= i4[1] && e4 < s4[0] && t4 <= s4[1] : e4 < i4[0] && t4 >= i4[1] && e4 >= s4[0] && t4 <= s4[1] : t4 > i4[1] && t4 < s4[1] || i4[1] === s4[1] && t4 === i4[1] && e4 >= i4[0] && e4 < s4[0] || i4[1] < s4[1] && t4 === s4[1] && e4 < s4[0] || i4[1] < s4[1] && t4 === i4[1] && e4 >= i4[0]);
        }
      };
      function v2(e4, t4, i4) {
        for (; e4.length < i4; ) e4 = t4 + e4;
        return e4;
      }
      __name(v2, "v");
      t3.DomRendererRowFactory = f2 = s3([r2(1, l2.ICharacterJoinerService), r2(2, h2.IOptionsService), r2(3, l2.ICoreBrowserService), r2(4, h2.ICoreService), r2(5, h2.IDecorationService), r2(6, l2.IThemeService)], f2);
    }, 2550: (e3, t3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.WidthCache = void 0, t3.WidthCache = class {
        constructor(e4, t4) {
          this._flat = new Float32Array(256), this._font = "", this._fontSize = 0, this._weight = "normal", this._weightBold = "bold", this._measureElements = [], this._container = e4.createElement("div"), this._container.classList.add("xterm-width-cache-measure-container"), this._container.setAttribute("aria-hidden", "true"), this._container.style.whiteSpace = "pre", this._container.style.fontKerning = "none";
          const i3 = e4.createElement("span");
          i3.classList.add("xterm-char-measure-element");
          const s3 = e4.createElement("span");
          s3.classList.add("xterm-char-measure-element"), s3.style.fontWeight = "bold";
          const r2 = e4.createElement("span");
          r2.classList.add("xterm-char-measure-element"), r2.style.fontStyle = "italic";
          const n2 = e4.createElement("span");
          n2.classList.add("xterm-char-measure-element"), n2.style.fontWeight = "bold", n2.style.fontStyle = "italic", this._measureElements = [i3, s3, r2, n2], this._container.appendChild(i3), this._container.appendChild(s3), this._container.appendChild(r2), this._container.appendChild(n2), t4.appendChild(this._container), this.clear();
        }
        dispose() {
          this._container.remove(), this._measureElements.length = 0, this._holey = void 0;
        }
        clear() {
          this._flat.fill(-9999), this._holey = /* @__PURE__ */ new Map();
        }
        setFont(e4, t4, i3, s3) {
          e4 === this._font && t4 === this._fontSize && i3 === this._weight && s3 === this._weightBold || (this._font = e4, this._fontSize = t4, this._weight = i3, this._weightBold = s3, this._container.style.fontFamily = this._font, this._container.style.fontSize = `${this._fontSize}px`, this._measureElements[0].style.fontWeight = `${i3}`, this._measureElements[1].style.fontWeight = `${s3}`, this._measureElements[2].style.fontWeight = `${i3}`, this._measureElements[3].style.fontWeight = `${s3}`, this.clear());
        }
        get(e4, t4, i3) {
          let s3 = 0;
          if (!t4 && !i3 && 1 === e4.length && (s3 = e4.charCodeAt(0)) < 256) {
            if (-9999 !== this._flat[s3]) return this._flat[s3];
            const t5 = this._measure(e4, 0);
            return t5 > 0 && (this._flat[s3] = t5), t5;
          }
          let r2 = e4;
          t4 && (r2 += "B"), i3 && (r2 += "I");
          let n2 = this._holey.get(r2);
          if (void 0 === n2) {
            let s4 = 0;
            t4 && (s4 |= 1), i3 && (s4 |= 2), n2 = this._measure(e4, s4), n2 > 0 && this._holey.set(r2, n2);
          }
          return n2;
        }
        _measure(e4, t4) {
          const i3 = this._measureElements[t4];
          return i3.textContent = e4.repeat(32), i3.offsetWidth / 32;
        }
      };
    }, 2223: (e3, t3, i3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.TEXT_BASELINE = t3.DIM_OPACITY = t3.INVERTED_DEFAULT_COLOR = void 0;
      const s3 = i3(6114);
      t3.INVERTED_DEFAULT_COLOR = 257, t3.DIM_OPACITY = 0.5, t3.TEXT_BASELINE = s3.isFirefox || s3.isLegacyEdge ? "bottom" : "ideographic";
    }, 6171: (e3, t3) => {
      function i3(e4) {
        return 57508 <= e4 && e4 <= 57558;
      }
      __name(i3, "i");
      function s3(e4) {
        return e4 >= 128512 && e4 <= 128591 || e4 >= 127744 && e4 <= 128511 || e4 >= 128640 && e4 <= 128767 || e4 >= 9728 && e4 <= 9983 || e4 >= 9984 && e4 <= 10175 || e4 >= 65024 && e4 <= 65039 || e4 >= 129280 && e4 <= 129535 || e4 >= 127462 && e4 <= 127487;
      }
      __name(s3, "s");
      Object.defineProperty(t3, "__esModule", { value: true }), t3.computeNextVariantOffset = t3.createRenderDimensions = t3.treatGlyphAsBackgroundColor = t3.allowRescaling = t3.isEmoji = t3.isRestrictedPowerlineGlyph = t3.isPowerlineGlyph = t3.throwIfFalsy = void 0, t3.throwIfFalsy = function(e4) {
        if (!e4) throw new Error("value must not be falsy");
        return e4;
      }, t3.isPowerlineGlyph = i3, t3.isRestrictedPowerlineGlyph = function(e4) {
        return 57520 <= e4 && e4 <= 57527;
      }, t3.isEmoji = s3, t3.allowRescaling = function(e4, t4, r2, n2) {
        return 1 === t4 && r2 > Math.ceil(1.5 * n2) && void 0 !== e4 && e4 > 255 && !s3(e4) && !i3(e4) && !function(e5) {
          return 57344 <= e5 && e5 <= 63743;
        }(e4);
      }, t3.treatGlyphAsBackgroundColor = function(e4) {
        return i3(e4) || function(e5) {
          return 9472 <= e5 && e5 <= 9631;
        }(e4);
      }, t3.createRenderDimensions = function() {
        return { css: { canvas: { width: 0, height: 0 }, cell: { width: 0, height: 0 } }, device: { canvas: { width: 0, height: 0 }, cell: { width: 0, height: 0 }, char: { width: 0, height: 0, left: 0, top: 0 } } };
      }, t3.computeNextVariantOffset = function(e4, t4, i4 = 0) {
        return (e4 - (2 * Math.round(t4) - i4)) % (2 * Math.round(t4));
      };
    }, 6052: (e3, t3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.createSelectionRenderModel = void 0;
      class i3 {
        static {
          __name(this, "i");
        }
        constructor() {
          this.clear();
        }
        clear() {
          this.hasSelection = false, this.columnSelectMode = false, this.viewportStartRow = 0, this.viewportEndRow = 0, this.viewportCappedStartRow = 0, this.viewportCappedEndRow = 0, this.startCol = 0, this.endCol = 0, this.selectionStart = void 0, this.selectionEnd = void 0;
        }
        update(e4, t4, i4, s3 = false) {
          if (this.selectionStart = t4, this.selectionEnd = i4, !t4 || !i4 || t4[0] === i4[0] && t4[1] === i4[1]) return void this.clear();
          const r2 = e4.buffers.active.ydisp, n2 = t4[1] - r2, o2 = i4[1] - r2, a2 = Math.max(n2, 0), h2 = Math.min(o2, e4.rows - 1);
          a2 >= e4.rows || h2 < 0 ? this.clear() : (this.hasSelection = true, this.columnSelectMode = s3, this.viewportStartRow = n2, this.viewportEndRow = o2, this.viewportCappedStartRow = a2, this.viewportCappedEndRow = h2, this.startCol = t4[0], this.endCol = i4[0]);
        }
        isCellSelected(e4, t4, i4) {
          return !!this.hasSelection && (i4 -= e4.buffer.active.viewportY, this.columnSelectMode ? this.startCol <= this.endCol ? t4 >= this.startCol && i4 >= this.viewportCappedStartRow && t4 < this.endCol && i4 <= this.viewportCappedEndRow : t4 < this.startCol && i4 >= this.viewportCappedStartRow && t4 >= this.endCol && i4 <= this.viewportCappedEndRow : i4 > this.viewportStartRow && i4 < this.viewportEndRow || this.viewportStartRow === this.viewportEndRow && i4 === this.viewportStartRow && t4 >= this.startCol && t4 < this.endCol || this.viewportStartRow < this.viewportEndRow && i4 === this.viewportEndRow && t4 < this.endCol || this.viewportStartRow < this.viewportEndRow && i4 === this.viewportStartRow && t4 >= this.startCol);
        }
      }
      t3.createSelectionRenderModel = function() {
        return new i3();
      };
    }, 456: (e3, t3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.SelectionModel = void 0, t3.SelectionModel = class {
        constructor(e4) {
          this._bufferService = e4, this.isSelectAllActive = false, this.selectionStartLength = 0;
        }
        clearSelection() {
          this.selectionStart = void 0, this.selectionEnd = void 0, this.isSelectAllActive = false, this.selectionStartLength = 0;
        }
        get finalSelectionStart() {
          return this.isSelectAllActive ? [0, 0] : this.selectionEnd && this.selectionStart && this.areSelectionValuesReversed() ? this.selectionEnd : this.selectionStart;
        }
        get finalSelectionEnd() {
          if (this.isSelectAllActive) return [this._bufferService.cols, this._bufferService.buffer.ybase + this._bufferService.rows - 1];
          if (this.selectionStart) {
            if (!this.selectionEnd || this.areSelectionValuesReversed()) {
              const e4 = this.selectionStart[0] + this.selectionStartLength;
              return e4 > this._bufferService.cols ? e4 % this._bufferService.cols == 0 ? [this._bufferService.cols, this.selectionStart[1] + Math.floor(e4 / this._bufferService.cols) - 1] : [e4 % this._bufferService.cols, this.selectionStart[1] + Math.floor(e4 / this._bufferService.cols)] : [e4, this.selectionStart[1]];
            }
            if (this.selectionStartLength && this.selectionEnd[1] === this.selectionStart[1]) {
              const e4 = this.selectionStart[0] + this.selectionStartLength;
              return e4 > this._bufferService.cols ? [e4 % this._bufferService.cols, this.selectionStart[1] + Math.floor(e4 / this._bufferService.cols)] : [Math.max(e4, this.selectionEnd[0]), this.selectionEnd[1]];
            }
            return this.selectionEnd;
          }
        }
        areSelectionValuesReversed() {
          const e4 = this.selectionStart, t4 = this.selectionEnd;
          return !(!e4 || !t4) && (e4[1] > t4[1] || e4[1] === t4[1] && e4[0] > t4[0]);
        }
        handleTrim(e4) {
          return this.selectionStart && (this.selectionStart[1] -= e4), this.selectionEnd && (this.selectionEnd[1] -= e4), this.selectionEnd && this.selectionEnd[1] < 0 ? (this.clearSelection(), true) : (this.selectionStart && this.selectionStart[1] < 0 && (this.selectionStart[1] = 0), false);
        }
      };
    }, 428: function(e3, t3, i3) {
      var s3 = this && this.__decorate || function(e4, t4, i4, s4) {
        var r3, n3 = arguments.length, o3 = n3 < 3 ? t4 : null === s4 ? s4 = Object.getOwnPropertyDescriptor(t4, i4) : s4;
        if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) o3 = Reflect.decorate(e4, t4, i4, s4);
        else for (var a3 = e4.length - 1; a3 >= 0; a3--) (r3 = e4[a3]) && (o3 = (n3 < 3 ? r3(o3) : n3 > 3 ? r3(t4, i4, o3) : r3(t4, i4)) || o3);
        return n3 > 3 && o3 && Object.defineProperty(t4, i4, o3), o3;
      }, r2 = this && this.__param || function(e4, t4) {
        return function(i4, s4) {
          t4(i4, s4, e4);
        };
      };
      Object.defineProperty(t3, "__esModule", { value: true }), t3.CharSizeService = void 0;
      const n2 = i3(2585), o2 = i3(8460), a2 = i3(844);
      let h2 = t3.CharSizeService = class extends a2.Disposable {
        get hasValidSize() {
          return this.width > 0 && this.height > 0;
        }
        constructor(e4, t4, i4) {
          super(), this._optionsService = i4, this.width = 0, this.height = 0, this._onCharSizeChange = this.register(new o2.EventEmitter()), this.onCharSizeChange = this._onCharSizeChange.event;
          try {
            this._measureStrategy = this.register(new d2(this._optionsService));
          } catch {
            this._measureStrategy = this.register(new l2(e4, t4, this._optionsService));
          }
          this.register(this._optionsService.onMultipleOptionChange(["fontFamily", "fontSize"], () => this.measure()));
        }
        measure() {
          const e4 = this._measureStrategy.measure();
          e4.width === this.width && e4.height === this.height || (this.width = e4.width, this.height = e4.height, this._onCharSizeChange.fire());
        }
      };
      t3.CharSizeService = h2 = s3([r2(2, n2.IOptionsService)], h2);
      class c2 extends a2.Disposable {
        static {
          __name(this, "c");
        }
        constructor() {
          super(...arguments), this._result = { width: 0, height: 0 };
        }
        _validateAndSet(e4, t4) {
          void 0 !== e4 && e4 > 0 && void 0 !== t4 && t4 > 0 && (this._result.width = e4, this._result.height = t4);
        }
      }
      class l2 extends c2 {
        static {
          __name(this, "l");
        }
        constructor(e4, t4, i4) {
          super(), this._document = e4, this._parentElement = t4, this._optionsService = i4, this._measureElement = this._document.createElement("span"), this._measureElement.classList.add("xterm-char-measure-element"), this._measureElement.textContent = "W".repeat(32), this._measureElement.setAttribute("aria-hidden", "true"), this._measureElement.style.whiteSpace = "pre", this._measureElement.style.fontKerning = "none", this._parentElement.appendChild(this._measureElement);
        }
        measure() {
          return this._measureElement.style.fontFamily = this._optionsService.rawOptions.fontFamily, this._measureElement.style.fontSize = `${this._optionsService.rawOptions.fontSize}px`, this._validateAndSet(Number(this._measureElement.offsetWidth) / 32, Number(this._measureElement.offsetHeight)), this._result;
        }
      }
      class d2 extends c2 {
        static {
          __name(this, "d");
        }
        constructor(e4) {
          super(), this._optionsService = e4, this._canvas = new OffscreenCanvas(100, 100), this._ctx = this._canvas.getContext("2d");
          const t4 = this._ctx.measureText("W");
          if (!("width" in t4 && "fontBoundingBoxAscent" in t4 && "fontBoundingBoxDescent" in t4)) throw new Error("Required font metrics not supported");
        }
        measure() {
          this._ctx.font = `${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;
          const e4 = this._ctx.measureText("W");
          return this._validateAndSet(e4.width, e4.fontBoundingBoxAscent + e4.fontBoundingBoxDescent), this._result;
        }
      }
    }, 4269: function(e3, t3, i3) {
      var s3 = this && this.__decorate || function(e4, t4, i4, s4) {
        var r3, n3 = arguments.length, o3 = n3 < 3 ? t4 : null === s4 ? s4 = Object.getOwnPropertyDescriptor(t4, i4) : s4;
        if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) o3 = Reflect.decorate(e4, t4, i4, s4);
        else for (var a3 = e4.length - 1; a3 >= 0; a3--) (r3 = e4[a3]) && (o3 = (n3 < 3 ? r3(o3) : n3 > 3 ? r3(t4, i4, o3) : r3(t4, i4)) || o3);
        return n3 > 3 && o3 && Object.defineProperty(t4, i4, o3), o3;
      }, r2 = this && this.__param || function(e4, t4) {
        return function(i4, s4) {
          t4(i4, s4, e4);
        };
      };
      Object.defineProperty(t3, "__esModule", { value: true }), t3.CharacterJoinerService = t3.JoinedCellData = void 0;
      const n2 = i3(3734), o2 = i3(643), a2 = i3(511), h2 = i3(2585);
      class c2 extends n2.AttributeData {
        static {
          __name(this, "c");
        }
        constructor(e4, t4, i4) {
          super(), this.content = 0, this.combinedData = "", this.fg = e4.fg, this.bg = e4.bg, this.combinedData = t4, this._width = i4;
        }
        isCombined() {
          return 2097152;
        }
        getWidth() {
          return this._width;
        }
        getChars() {
          return this.combinedData;
        }
        getCode() {
          return 2097151;
        }
        setFromCharData(e4) {
          throw new Error("not implemented");
        }
        getAsCharData() {
          return [this.fg, this.getChars(), this.getWidth(), this.getCode()];
        }
      }
      t3.JoinedCellData = c2;
      let l2 = t3.CharacterJoinerService = class e4 {
        static {
          __name(this, "e");
        }
        constructor(e5) {
          this._bufferService = e5, this._characterJoiners = [], this._nextCharacterJoinerId = 0, this._workCell = new a2.CellData();
        }
        register(e5) {
          const t4 = { id: this._nextCharacterJoinerId++, handler: e5 };
          return this._characterJoiners.push(t4), t4.id;
        }
        deregister(e5) {
          for (let t4 = 0; t4 < this._characterJoiners.length; t4++) if (this._characterJoiners[t4].id === e5) return this._characterJoiners.splice(t4, 1), true;
          return false;
        }
        getJoinedCharacters(e5) {
          if (0 === this._characterJoiners.length) return [];
          const t4 = this._bufferService.buffer.lines.get(e5);
          if (!t4 || 0 === t4.length) return [];
          const i4 = [], s4 = t4.translateToString(true);
          let r3 = 0, n3 = 0, a3 = 0, h3 = t4.getFg(0), c3 = t4.getBg(0);
          for (let e6 = 0; e6 < t4.getTrimmedLength(); e6++) if (t4.loadCell(e6, this._workCell), 0 !== this._workCell.getWidth()) {
            if (this._workCell.fg !== h3 || this._workCell.bg !== c3) {
              if (e6 - r3 > 1) {
                const e7 = this._getJoinedRanges(s4, a3, n3, t4, r3);
                for (let t5 = 0; t5 < e7.length; t5++) i4.push(e7[t5]);
              }
              r3 = e6, a3 = n3, h3 = this._workCell.fg, c3 = this._workCell.bg;
            }
            n3 += this._workCell.getChars().length || o2.WHITESPACE_CELL_CHAR.length;
          }
          if (this._bufferService.cols - r3 > 1) {
            const e6 = this._getJoinedRanges(s4, a3, n3, t4, r3);
            for (let t5 = 0; t5 < e6.length; t5++) i4.push(e6[t5]);
          }
          return i4;
        }
        _getJoinedRanges(t4, i4, s4, r3, n3) {
          const o3 = t4.substring(i4, s4);
          let a3 = [];
          try {
            a3 = this._characterJoiners[0].handler(o3);
          } catch (e5) {
            console.error(e5);
          }
          for (let t5 = 1; t5 < this._characterJoiners.length; t5++) try {
            const i5 = this._characterJoiners[t5].handler(o3);
            for (let t6 = 0; t6 < i5.length; t6++) e4._mergeRanges(a3, i5[t6]);
          } catch (e5) {
            console.error(e5);
          }
          return this._stringRangesToCellRanges(a3, r3, n3), a3;
        }
        _stringRangesToCellRanges(e5, t4, i4) {
          let s4 = 0, r3 = false, n3 = 0, a3 = e5[s4];
          if (a3) {
            for (let h3 = i4; h3 < this._bufferService.cols; h3++) {
              const i5 = t4.getWidth(h3), c3 = t4.getString(h3).length || o2.WHITESPACE_CELL_CHAR.length;
              if (0 !== i5) {
                if (!r3 && a3[0] <= n3 && (a3[0] = h3, r3 = true), a3[1] <= n3) {
                  if (a3[1] = h3, a3 = e5[++s4], !a3) break;
                  a3[0] <= n3 ? (a3[0] = h3, r3 = true) : r3 = false;
                }
                n3 += c3;
              }
            }
            a3 && (a3[1] = this._bufferService.cols);
          }
        }
        static _mergeRanges(e5, t4) {
          let i4 = false;
          for (let s4 = 0; s4 < e5.length; s4++) {
            const r3 = e5[s4];
            if (i4) {
              if (t4[1] <= r3[0]) return e5[s4 - 1][1] = t4[1], e5;
              if (t4[1] <= r3[1]) return e5[s4 - 1][1] = Math.max(t4[1], r3[1]), e5.splice(s4, 1), e5;
              e5.splice(s4, 1), s4--;
            } else {
              if (t4[1] <= r3[0]) return e5.splice(s4, 0, t4), e5;
              if (t4[1] <= r3[1]) return r3[0] = Math.min(t4[0], r3[0]), e5;
              t4[0] < r3[1] && (r3[0] = Math.min(t4[0], r3[0]), i4 = true);
            }
          }
          return i4 ? e5[e5.length - 1][1] = t4[1] : e5.push(t4), e5;
        }
      };
      t3.CharacterJoinerService = l2 = s3([r2(0, h2.IBufferService)], l2);
    }, 5114: (e3, t3, i3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.CoreBrowserService = void 0;
      const s3 = i3(844), r2 = i3(8460), n2 = i3(3656);
      class o2 extends s3.Disposable {
        static {
          __name(this, "o");
        }
        constructor(e4, t4, i4) {
          super(), this._textarea = e4, this._window = t4, this.mainDocument = i4, this._isFocused = false, this._cachedIsFocused = void 0, this._screenDprMonitor = new a2(this._window), this._onDprChange = this.register(new r2.EventEmitter()), this.onDprChange = this._onDprChange.event, this._onWindowChange = this.register(new r2.EventEmitter()), this.onWindowChange = this._onWindowChange.event, this.register(this.onWindowChange((e5) => this._screenDprMonitor.setWindow(e5))), this.register((0, r2.forwardEvent)(this._screenDprMonitor.onDprChange, this._onDprChange)), this._textarea.addEventListener("focus", () => this._isFocused = true), this._textarea.addEventListener("blur", () => this._isFocused = false);
        }
        get window() {
          return this._window;
        }
        set window(e4) {
          this._window !== e4 && (this._window = e4, this._onWindowChange.fire(this._window));
        }
        get dpr() {
          return this.window.devicePixelRatio;
        }
        get isFocused() {
          return void 0 === this._cachedIsFocused && (this._cachedIsFocused = this._isFocused && this._textarea.ownerDocument.hasFocus(), queueMicrotask(() => this._cachedIsFocused = void 0)), this._cachedIsFocused;
        }
      }
      t3.CoreBrowserService = o2;
      class a2 extends s3.Disposable {
        static {
          __name(this, "a");
        }
        constructor(e4) {
          super(), this._parentWindow = e4, this._windowResizeListener = this.register(new s3.MutableDisposable()), this._onDprChange = this.register(new r2.EventEmitter()), this.onDprChange = this._onDprChange.event, this._outerListener = () => this._setDprAndFireIfDiffers(), this._currentDevicePixelRatio = this._parentWindow.devicePixelRatio, this._updateDpr(), this._setWindowResizeListener(), this.register((0, s3.toDisposable)(() => this.clearListener()));
        }
        setWindow(e4) {
          this._parentWindow = e4, this._setWindowResizeListener(), this._setDprAndFireIfDiffers();
        }
        _setWindowResizeListener() {
          this._windowResizeListener.value = (0, n2.addDisposableDomListener)(this._parentWindow, "resize", () => this._setDprAndFireIfDiffers());
        }
        _setDprAndFireIfDiffers() {
          this._parentWindow.devicePixelRatio !== this._currentDevicePixelRatio && this._onDprChange.fire(this._parentWindow.devicePixelRatio), this._updateDpr();
        }
        _updateDpr() {
          this._outerListener && (this._resolutionMediaMatchList?.removeListener(this._outerListener), this._currentDevicePixelRatio = this._parentWindow.devicePixelRatio, this._resolutionMediaMatchList = this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`), this._resolutionMediaMatchList.addListener(this._outerListener));
        }
        clearListener() {
          this._resolutionMediaMatchList && this._outerListener && (this._resolutionMediaMatchList.removeListener(this._outerListener), this._resolutionMediaMatchList = void 0, this._outerListener = void 0);
        }
      }
    }, 779: (e3, t3, i3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.LinkProviderService = void 0;
      const s3 = i3(844);
      class r2 extends s3.Disposable {
        static {
          __name(this, "r");
        }
        constructor() {
          super(), this.linkProviders = [], this.register((0, s3.toDisposable)(() => this.linkProviders.length = 0));
        }
        registerLinkProvider(e4) {
          return this.linkProviders.push(e4), { dispose: /* @__PURE__ */ __name(() => {
            const t4 = this.linkProviders.indexOf(e4);
            -1 !== t4 && this.linkProviders.splice(t4, 1);
          }, "dispose") };
        }
      }
      t3.LinkProviderService = r2;
    }, 8934: function(e3, t3, i3) {
      var s3 = this && this.__decorate || function(e4, t4, i4, s4) {
        var r3, n3 = arguments.length, o3 = n3 < 3 ? t4 : null === s4 ? s4 = Object.getOwnPropertyDescriptor(t4, i4) : s4;
        if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) o3 = Reflect.decorate(e4, t4, i4, s4);
        else for (var a3 = e4.length - 1; a3 >= 0; a3--) (r3 = e4[a3]) && (o3 = (n3 < 3 ? r3(o3) : n3 > 3 ? r3(t4, i4, o3) : r3(t4, i4)) || o3);
        return n3 > 3 && o3 && Object.defineProperty(t4, i4, o3), o3;
      }, r2 = this && this.__param || function(e4, t4) {
        return function(i4, s4) {
          t4(i4, s4, e4);
        };
      };
      Object.defineProperty(t3, "__esModule", { value: true }), t3.MouseService = void 0;
      const n2 = i3(4725), o2 = i3(9806);
      let a2 = t3.MouseService = class {
        constructor(e4, t4) {
          this._renderService = e4, this._charSizeService = t4;
        }
        getCoords(e4, t4, i4, s4, r3) {
          return (0, o2.getCoords)(window, e4, t4, i4, s4, this._charSizeService.hasValidSize, this._renderService.dimensions.css.cell.width, this._renderService.dimensions.css.cell.height, r3);
        }
        getMouseReportCoords(e4, t4) {
          const i4 = (0, o2.getCoordsRelativeToElement)(window, e4, t4);
          if (this._charSizeService.hasValidSize) return i4[0] = Math.min(Math.max(i4[0], 0), this._renderService.dimensions.css.canvas.width - 1), i4[1] = Math.min(Math.max(i4[1], 0), this._renderService.dimensions.css.canvas.height - 1), { col: Math.floor(i4[0] / this._renderService.dimensions.css.cell.width), row: Math.floor(i4[1] / this._renderService.dimensions.css.cell.height), x: Math.floor(i4[0]), y: Math.floor(i4[1]) };
        }
      };
      t3.MouseService = a2 = s3([r2(0, n2.IRenderService), r2(1, n2.ICharSizeService)], a2);
    }, 3230: function(e3, t3, i3) {
      var s3 = this && this.__decorate || function(e4, t4, i4, s4) {
        var r3, n3 = arguments.length, o3 = n3 < 3 ? t4 : null === s4 ? s4 = Object.getOwnPropertyDescriptor(t4, i4) : s4;
        if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) o3 = Reflect.decorate(e4, t4, i4, s4);
        else for (var a3 = e4.length - 1; a3 >= 0; a3--) (r3 = e4[a3]) && (o3 = (n3 < 3 ? r3(o3) : n3 > 3 ? r3(t4, i4, o3) : r3(t4, i4)) || o3);
        return n3 > 3 && o3 && Object.defineProperty(t4, i4, o3), o3;
      }, r2 = this && this.__param || function(e4, t4) {
        return function(i4, s4) {
          t4(i4, s4, e4);
        };
      };
      Object.defineProperty(t3, "__esModule", { value: true }), t3.RenderService = void 0;
      const n2 = i3(6193), o2 = i3(4725), a2 = i3(8460), h2 = i3(844), c2 = i3(7226), l2 = i3(2585);
      let d2 = t3.RenderService = class extends h2.Disposable {
        get dimensions() {
          return this._renderer.value.dimensions;
        }
        constructor(e4, t4, i4, s4, r3, o3, l3, d3) {
          super(), this._rowCount = e4, this._charSizeService = s4, this._renderer = this.register(new h2.MutableDisposable()), this._pausedResizeTask = new c2.DebouncedIdleTask(), this._observerDisposable = this.register(new h2.MutableDisposable()), this._isPaused = false, this._needsFullRefresh = false, this._isNextRenderRedrawOnly = true, this._needsSelectionRefresh = false, this._canvasWidth = 0, this._canvasHeight = 0, this._selectionState = { start: void 0, end: void 0, columnSelectMode: false }, this._onDimensionsChange = this.register(new a2.EventEmitter()), this.onDimensionsChange = this._onDimensionsChange.event, this._onRenderedViewportChange = this.register(new a2.EventEmitter()), this.onRenderedViewportChange = this._onRenderedViewportChange.event, this._onRender = this.register(new a2.EventEmitter()), this.onRender = this._onRender.event, this._onRefreshRequest = this.register(new a2.EventEmitter()), this.onRefreshRequest = this._onRefreshRequest.event, this._renderDebouncer = new n2.RenderDebouncer((e5, t5) => this._renderRows(e5, t5), l3), this.register(this._renderDebouncer), this.register(l3.onDprChange(() => this.handleDevicePixelRatioChange())), this.register(o3.onResize(() => this._fullRefresh())), this.register(o3.buffers.onBufferActivate(() => this._renderer.value?.clear())), this.register(i4.onOptionChange(() => this._handleOptionsChanged())), this.register(this._charSizeService.onCharSizeChange(() => this.handleCharSizeChanged())), this.register(r3.onDecorationRegistered(() => this._fullRefresh())), this.register(r3.onDecorationRemoved(() => this._fullRefresh())), this.register(i4.onMultipleOptionChange(["customGlyphs", "drawBoldTextInBrightColors", "letterSpacing", "lineHeight", "fontFamily", "fontSize", "fontWeight", "fontWeightBold", "minimumContrastRatio", "rescaleOverlappingGlyphs"], () => {
            this.clear(), this.handleResize(o3.cols, o3.rows), this._fullRefresh();
          })), this.register(i4.onMultipleOptionChange(["cursorBlink", "cursorStyle"], () => this.refreshRows(o3.buffer.y, o3.buffer.y, true))), this.register(d3.onChangeColors(() => this._fullRefresh())), this._registerIntersectionObserver(l3.window, t4), this.register(l3.onWindowChange((e5) => this._registerIntersectionObserver(e5, t4)));
        }
        _registerIntersectionObserver(e4, t4) {
          if ("IntersectionObserver" in e4) {
            const i4 = new e4.IntersectionObserver((e5) => this._handleIntersectionChange(e5[e5.length - 1]), { threshold: 0 });
            i4.observe(t4), this._observerDisposable.value = (0, h2.toDisposable)(() => i4.disconnect());
          }
        }
        _handleIntersectionChange(e4) {
          this._isPaused = void 0 === e4.isIntersecting ? 0 === e4.intersectionRatio : !e4.isIntersecting, this._isPaused || this._charSizeService.hasValidSize || this._charSizeService.measure(), !this._isPaused && this._needsFullRefresh && (this._pausedResizeTask.flush(), this.refreshRows(0, this._rowCount - 1), this._needsFullRefresh = false);
        }
        refreshRows(e4, t4, i4 = false) {
          this._isPaused ? this._needsFullRefresh = true : (i4 || (this._isNextRenderRedrawOnly = false), this._renderDebouncer.refresh(e4, t4, this._rowCount));
        }
        _renderRows(e4, t4) {
          this._renderer.value && (e4 = Math.min(e4, this._rowCount - 1), t4 = Math.min(t4, this._rowCount - 1), this._renderer.value.renderRows(e4, t4), this._needsSelectionRefresh && (this._renderer.value.handleSelectionChanged(this._selectionState.start, this._selectionState.end, this._selectionState.columnSelectMode), this._needsSelectionRefresh = false), this._isNextRenderRedrawOnly || this._onRenderedViewportChange.fire({ start: e4, end: t4 }), this._onRender.fire({ start: e4, end: t4 }), this._isNextRenderRedrawOnly = true);
        }
        resize(e4, t4) {
          this._rowCount = t4, this._fireOnCanvasResize();
        }
        _handleOptionsChanged() {
          this._renderer.value && (this.refreshRows(0, this._rowCount - 1), this._fireOnCanvasResize());
        }
        _fireOnCanvasResize() {
          this._renderer.value && (this._renderer.value.dimensions.css.canvas.width === this._canvasWidth && this._renderer.value.dimensions.css.canvas.height === this._canvasHeight || this._onDimensionsChange.fire(this._renderer.value.dimensions));
        }
        hasRenderer() {
          return !!this._renderer.value;
        }
        setRenderer(e4) {
          this._renderer.value = e4, this._renderer.value && (this._renderer.value.onRequestRedraw((e5) => this.refreshRows(e5.start, e5.end, true)), this._needsSelectionRefresh = true, this._fullRefresh());
        }
        addRefreshCallback(e4) {
          return this._renderDebouncer.addRefreshCallback(e4);
        }
        _fullRefresh() {
          this._isPaused ? this._needsFullRefresh = true : this.refreshRows(0, this._rowCount - 1);
        }
        clearTextureAtlas() {
          this._renderer.value && (this._renderer.value.clearTextureAtlas?.(), this._fullRefresh());
        }
        handleDevicePixelRatioChange() {
          this._charSizeService.measure(), this._renderer.value && (this._renderer.value.handleDevicePixelRatioChange(), this.refreshRows(0, this._rowCount - 1));
        }
        handleResize(e4, t4) {
          this._renderer.value && (this._isPaused ? this._pausedResizeTask.set(() => this._renderer.value?.handleResize(e4, t4)) : this._renderer.value.handleResize(e4, t4), this._fullRefresh());
        }
        handleCharSizeChanged() {
          this._renderer.value?.handleCharSizeChanged();
        }
        handleBlur() {
          this._renderer.value?.handleBlur();
        }
        handleFocus() {
          this._renderer.value?.handleFocus();
        }
        handleSelectionChanged(e4, t4, i4) {
          this._selectionState.start = e4, this._selectionState.end = t4, this._selectionState.columnSelectMode = i4, this._renderer.value?.handleSelectionChanged(e4, t4, i4);
        }
        handleCursorMove() {
          this._renderer.value?.handleCursorMove();
        }
        clear() {
          this._renderer.value?.clear();
        }
      };
      t3.RenderService = d2 = s3([r2(2, l2.IOptionsService), r2(3, o2.ICharSizeService), r2(4, l2.IDecorationService), r2(5, l2.IBufferService), r2(6, o2.ICoreBrowserService), r2(7, o2.IThemeService)], d2);
    }, 9312: function(e3, t3, i3) {
      var s3 = this && this.__decorate || function(e4, t4, i4, s4) {
        var r3, n3 = arguments.length, o3 = n3 < 3 ? t4 : null === s4 ? s4 = Object.getOwnPropertyDescriptor(t4, i4) : s4;
        if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) o3 = Reflect.decorate(e4, t4, i4, s4);
        else for (var a3 = e4.length - 1; a3 >= 0; a3--) (r3 = e4[a3]) && (o3 = (n3 < 3 ? r3(o3) : n3 > 3 ? r3(t4, i4, o3) : r3(t4, i4)) || o3);
        return n3 > 3 && o3 && Object.defineProperty(t4, i4, o3), o3;
      }, r2 = this && this.__param || function(e4, t4) {
        return function(i4, s4) {
          t4(i4, s4, e4);
        };
      };
      Object.defineProperty(t3, "__esModule", { value: true }), t3.SelectionService = void 0;
      const n2 = i3(9806), o2 = i3(9504), a2 = i3(456), h2 = i3(4725), c2 = i3(8460), l2 = i3(844), d2 = i3(6114), _2 = i3(4841), u2 = i3(511), f2 = i3(2585), v2 = String.fromCharCode(160), p2 = new RegExp(v2, "g");
      let g2 = t3.SelectionService = class extends l2.Disposable {
        constructor(e4, t4, i4, s4, r3, n3, o3, h3, d3) {
          super(), this._element = e4, this._screenElement = t4, this._linkifier = i4, this._bufferService = s4, this._coreService = r3, this._mouseService = n3, this._optionsService = o3, this._renderService = h3, this._coreBrowserService = d3, this._dragScrollAmount = 0, this._enabled = true, this._workCell = new u2.CellData(), this._mouseDownTimeStamp = 0, this._oldHasSelection = false, this._oldSelectionStart = void 0, this._oldSelectionEnd = void 0, this._onLinuxMouseSelection = this.register(new c2.EventEmitter()), this.onLinuxMouseSelection = this._onLinuxMouseSelection.event, this._onRedrawRequest = this.register(new c2.EventEmitter()), this.onRequestRedraw = this._onRedrawRequest.event, this._onSelectionChange = this.register(new c2.EventEmitter()), this.onSelectionChange = this._onSelectionChange.event, this._onRequestScrollLines = this.register(new c2.EventEmitter()), this.onRequestScrollLines = this._onRequestScrollLines.event, this._mouseMoveListener = (e5) => this._handleMouseMove(e5), this._mouseUpListener = (e5) => this._handleMouseUp(e5), this._coreService.onUserInput(() => {
            this.hasSelection && this.clearSelection();
          }), this._trimListener = this._bufferService.buffer.lines.onTrim((e5) => this._handleTrim(e5)), this.register(this._bufferService.buffers.onBufferActivate((e5) => this._handleBufferActivate(e5))), this.enable(), this._model = new a2.SelectionModel(this._bufferService), this._activeSelectionMode = 0, this.register((0, l2.toDisposable)(() => {
            this._removeMouseDownListeners();
          }));
        }
        reset() {
          this.clearSelection();
        }
        disable() {
          this.clearSelection(), this._enabled = false;
        }
        enable() {
          this._enabled = true;
        }
        get selectionStart() {
          return this._model.finalSelectionStart;
        }
        get selectionEnd() {
          return this._model.finalSelectionEnd;
        }
        get hasSelection() {
          const e4 = this._model.finalSelectionStart, t4 = this._model.finalSelectionEnd;
          return !(!e4 || !t4 || e4[0] === t4[0] && e4[1] === t4[1]);
        }
        get selectionText() {
          const e4 = this._model.finalSelectionStart, t4 = this._model.finalSelectionEnd;
          if (!e4 || !t4) return "";
          const i4 = this._bufferService.buffer, s4 = [];
          if (3 === this._activeSelectionMode) {
            if (e4[0] === t4[0]) return "";
            const r3 = e4[0] < t4[0] ? e4[0] : t4[0], n3 = e4[0] < t4[0] ? t4[0] : e4[0];
            for (let o3 = e4[1]; o3 <= t4[1]; o3++) {
              const e5 = i4.translateBufferLineToString(o3, true, r3, n3);
              s4.push(e5);
            }
          } else {
            const r3 = e4[1] === t4[1] ? t4[0] : void 0;
            s4.push(i4.translateBufferLineToString(e4[1], true, e4[0], r3));
            for (let r4 = e4[1] + 1; r4 <= t4[1] - 1; r4++) {
              const e5 = i4.lines.get(r4), t5 = i4.translateBufferLineToString(r4, true);
              e5?.isWrapped ? s4[s4.length - 1] += t5 : s4.push(t5);
            }
            if (e4[1] !== t4[1]) {
              const e5 = i4.lines.get(t4[1]), r4 = i4.translateBufferLineToString(t4[1], true, 0, t4[0]);
              e5 && e5.isWrapped ? s4[s4.length - 1] += r4 : s4.push(r4);
            }
          }
          return s4.map((e5) => e5.replace(p2, " ")).join(d2.isWindows ? "\r\n" : "\n");
        }
        clearSelection() {
          this._model.clearSelection(), this._removeMouseDownListeners(), this.refresh(), this._onSelectionChange.fire();
        }
        refresh(e4) {
          this._refreshAnimationFrame || (this._refreshAnimationFrame = this._coreBrowserService.window.requestAnimationFrame(() => this._refresh())), d2.isLinux && e4 && this.selectionText.length && this._onLinuxMouseSelection.fire(this.selectionText);
        }
        _refresh() {
          this._refreshAnimationFrame = void 0, this._onRedrawRequest.fire({ start: this._model.finalSelectionStart, end: this._model.finalSelectionEnd, columnSelectMode: 3 === this._activeSelectionMode });
        }
        _isClickInSelection(e4) {
          const t4 = this._getMouseBufferCoords(e4), i4 = this._model.finalSelectionStart, s4 = this._model.finalSelectionEnd;
          return !!(i4 && s4 && t4) && this._areCoordsInSelection(t4, i4, s4);
        }
        isCellInSelection(e4, t4) {
          const i4 = this._model.finalSelectionStart, s4 = this._model.finalSelectionEnd;
          return !(!i4 || !s4) && this._areCoordsInSelection([e4, t4], i4, s4);
        }
        _areCoordsInSelection(e4, t4, i4) {
          return e4[1] > t4[1] && e4[1] < i4[1] || t4[1] === i4[1] && e4[1] === t4[1] && e4[0] >= t4[0] && e4[0] < i4[0] || t4[1] < i4[1] && e4[1] === i4[1] && e4[0] < i4[0] || t4[1] < i4[1] && e4[1] === t4[1] && e4[0] >= t4[0];
        }
        _selectWordAtCursor(e4, t4) {
          const i4 = this._linkifier.currentLink?.link?.range;
          if (i4) return this._model.selectionStart = [i4.start.x - 1, i4.start.y - 1], this._model.selectionStartLength = (0, _2.getRangeLength)(i4, this._bufferService.cols), this._model.selectionEnd = void 0, true;
          const s4 = this._getMouseBufferCoords(e4);
          return !!s4 && (this._selectWordAt(s4, t4), this._model.selectionEnd = void 0, true);
        }
        selectAll() {
          this._model.isSelectAllActive = true, this.refresh(), this._onSelectionChange.fire();
        }
        selectLines(e4, t4) {
          this._model.clearSelection(), e4 = Math.max(e4, 0), t4 = Math.min(t4, this._bufferService.buffer.lines.length - 1), this._model.selectionStart = [0, e4], this._model.selectionEnd = [this._bufferService.cols, t4], this.refresh(), this._onSelectionChange.fire();
        }
        _handleTrim(e4) {
          this._model.handleTrim(e4) && this.refresh();
        }
        _getMouseBufferCoords(e4) {
          const t4 = this._mouseService.getCoords(e4, this._screenElement, this._bufferService.cols, this._bufferService.rows, true);
          if (t4) return t4[0]--, t4[1]--, t4[1] += this._bufferService.buffer.ydisp, t4;
        }
        _getMouseEventScrollAmount(e4) {
          let t4 = (0, n2.getCoordsRelativeToElement)(this._coreBrowserService.window, e4, this._screenElement)[1];
          const i4 = this._renderService.dimensions.css.canvas.height;
          return t4 >= 0 && t4 <= i4 ? 0 : (t4 > i4 && (t4 -= i4), t4 = Math.min(Math.max(t4, -50), 50), t4 /= 50, t4 / Math.abs(t4) + Math.round(14 * t4));
        }
        shouldForceSelection(e4) {
          return d2.isMac ? e4.altKey && this._optionsService.rawOptions.macOptionClickForcesSelection : e4.shiftKey;
        }
        handleMouseDown(e4) {
          if (this._mouseDownTimeStamp = e4.timeStamp, (2 !== e4.button || !this.hasSelection) && 0 === e4.button) {
            if (!this._enabled) {
              if (!this.shouldForceSelection(e4)) return;
              e4.stopPropagation();
            }
            e4.preventDefault(), this._dragScrollAmount = 0, this._enabled && e4.shiftKey ? this._handleIncrementalClick(e4) : 1 === e4.detail ? this._handleSingleClick(e4) : 2 === e4.detail ? this._handleDoubleClick(e4) : 3 === e4.detail && this._handleTripleClick(e4), this._addMouseDownListeners(), this.refresh(true);
          }
        }
        _addMouseDownListeners() {
          this._screenElement.ownerDocument && (this._screenElement.ownerDocument.addEventListener("mousemove", this._mouseMoveListener), this._screenElement.ownerDocument.addEventListener("mouseup", this._mouseUpListener)), this._dragScrollIntervalTimer = this._coreBrowserService.window.setInterval(() => this._dragScroll(), 50);
        }
        _removeMouseDownListeners() {
          this._screenElement.ownerDocument && (this._screenElement.ownerDocument.removeEventListener("mousemove", this._mouseMoveListener), this._screenElement.ownerDocument.removeEventListener("mouseup", this._mouseUpListener)), this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer), this._dragScrollIntervalTimer = void 0;
        }
        _handleIncrementalClick(e4) {
          this._model.selectionStart && (this._model.selectionEnd = this._getMouseBufferCoords(e4));
        }
        _handleSingleClick(e4) {
          if (this._model.selectionStartLength = 0, this._model.isSelectAllActive = false, this._activeSelectionMode = this.shouldColumnSelect(e4) ? 3 : 0, this._model.selectionStart = this._getMouseBufferCoords(e4), !this._model.selectionStart) return;
          this._model.selectionEnd = void 0;
          const t4 = this._bufferService.buffer.lines.get(this._model.selectionStart[1]);
          t4 && t4.length !== this._model.selectionStart[0] && 0 === t4.hasWidth(this._model.selectionStart[0]) && this._model.selectionStart[0]++;
        }
        _handleDoubleClick(e4) {
          this._selectWordAtCursor(e4, true) && (this._activeSelectionMode = 1);
        }
        _handleTripleClick(e4) {
          const t4 = this._getMouseBufferCoords(e4);
          t4 && (this._activeSelectionMode = 2, this._selectLineAt(t4[1]));
        }
        shouldColumnSelect(e4) {
          return e4.altKey && !(d2.isMac && this._optionsService.rawOptions.macOptionClickForcesSelection);
        }
        _handleMouseMove(e4) {
          if (e4.stopImmediatePropagation(), !this._model.selectionStart) return;
          const t4 = this._model.selectionEnd ? [this._model.selectionEnd[0], this._model.selectionEnd[1]] : null;
          if (this._model.selectionEnd = this._getMouseBufferCoords(e4), !this._model.selectionEnd) return void this.refresh(true);
          2 === this._activeSelectionMode ? this._model.selectionEnd[1] < this._model.selectionStart[1] ? this._model.selectionEnd[0] = 0 : this._model.selectionEnd[0] = this._bufferService.cols : 1 === this._activeSelectionMode && this._selectToWordAt(this._model.selectionEnd), this._dragScrollAmount = this._getMouseEventScrollAmount(e4), 3 !== this._activeSelectionMode && (this._dragScrollAmount > 0 ? this._model.selectionEnd[0] = this._bufferService.cols : this._dragScrollAmount < 0 && (this._model.selectionEnd[0] = 0));
          const i4 = this._bufferService.buffer;
          if (this._model.selectionEnd[1] < i4.lines.length) {
            const e5 = i4.lines.get(this._model.selectionEnd[1]);
            e5 && 0 === e5.hasWidth(this._model.selectionEnd[0]) && this._model.selectionEnd[0] < this._bufferService.cols && this._model.selectionEnd[0]++;
          }
          t4 && t4[0] === this._model.selectionEnd[0] && t4[1] === this._model.selectionEnd[1] || this.refresh(true);
        }
        _dragScroll() {
          if (this._model.selectionEnd && this._model.selectionStart && this._dragScrollAmount) {
            this._onRequestScrollLines.fire({ amount: this._dragScrollAmount, suppressScrollEvent: false });
            const e4 = this._bufferService.buffer;
            this._dragScrollAmount > 0 ? (3 !== this._activeSelectionMode && (this._model.selectionEnd[0] = this._bufferService.cols), this._model.selectionEnd[1] = Math.min(e4.ydisp + this._bufferService.rows, e4.lines.length - 1)) : (3 !== this._activeSelectionMode && (this._model.selectionEnd[0] = 0), this._model.selectionEnd[1] = e4.ydisp), this.refresh();
          }
        }
        _handleMouseUp(e4) {
          const t4 = e4.timeStamp - this._mouseDownTimeStamp;
          if (this._removeMouseDownListeners(), this.selectionText.length <= 1 && t4 < 500 && e4.altKey && this._optionsService.rawOptions.altClickMovesCursor) {
            if (this._bufferService.buffer.ybase === this._bufferService.buffer.ydisp) {
              const t5 = this._mouseService.getCoords(e4, this._element, this._bufferService.cols, this._bufferService.rows, false);
              if (t5 && void 0 !== t5[0] && void 0 !== t5[1]) {
                const e5 = (0, o2.moveToCellSequence)(t5[0] - 1, t5[1] - 1, this._bufferService, this._coreService.decPrivateModes.applicationCursorKeys);
                this._coreService.triggerDataEvent(e5, true);
              }
            }
          } else this._fireEventIfSelectionChanged();
        }
        _fireEventIfSelectionChanged() {
          const e4 = this._model.finalSelectionStart, t4 = this._model.finalSelectionEnd, i4 = !(!e4 || !t4 || e4[0] === t4[0] && e4[1] === t4[1]);
          i4 ? e4 && t4 && (this._oldSelectionStart && this._oldSelectionEnd && e4[0] === this._oldSelectionStart[0] && e4[1] === this._oldSelectionStart[1] && t4[0] === this._oldSelectionEnd[0] && t4[1] === this._oldSelectionEnd[1] || this._fireOnSelectionChange(e4, t4, i4)) : this._oldHasSelection && this._fireOnSelectionChange(e4, t4, i4);
        }
        _fireOnSelectionChange(e4, t4, i4) {
          this._oldSelectionStart = e4, this._oldSelectionEnd = t4, this._oldHasSelection = i4, this._onSelectionChange.fire();
        }
        _handleBufferActivate(e4) {
          this.clearSelection(), this._trimListener.dispose(), this._trimListener = e4.activeBuffer.lines.onTrim((e5) => this._handleTrim(e5));
        }
        _convertViewportColToCharacterIndex(e4, t4) {
          let i4 = t4;
          for (let s4 = 0; t4 >= s4; s4++) {
            const r3 = e4.loadCell(s4, this._workCell).getChars().length;
            0 === this._workCell.getWidth() ? i4-- : r3 > 1 && t4 !== s4 && (i4 += r3 - 1);
          }
          return i4;
        }
        setSelection(e4, t4, i4) {
          this._model.clearSelection(), this._removeMouseDownListeners(), this._model.selectionStart = [e4, t4], this._model.selectionStartLength = i4, this.refresh(), this._fireEventIfSelectionChanged();
        }
        rightClickSelect(e4) {
          this._isClickInSelection(e4) || (this._selectWordAtCursor(e4, false) && this.refresh(true), this._fireEventIfSelectionChanged());
        }
        _getWordAt(e4, t4, i4 = true, s4 = true) {
          if (e4[0] >= this._bufferService.cols) return;
          const r3 = this._bufferService.buffer, n3 = r3.lines.get(e4[1]);
          if (!n3) return;
          const o3 = r3.translateBufferLineToString(e4[1], false);
          let a3 = this._convertViewportColToCharacterIndex(n3, e4[0]), h3 = a3;
          const c3 = e4[0] - a3;
          let l3 = 0, d3 = 0, _3 = 0, u3 = 0;
          if (" " === o3.charAt(a3)) {
            for (; a3 > 0 && " " === o3.charAt(a3 - 1); ) a3--;
            for (; h3 < o3.length && " " === o3.charAt(h3 + 1); ) h3++;
          } else {
            let t5 = e4[0], i5 = e4[0];
            0 === n3.getWidth(t5) && (l3++, t5--), 2 === n3.getWidth(i5) && (d3++, i5++);
            const s5 = n3.getString(i5).length;
            for (s5 > 1 && (u3 += s5 - 1, h3 += s5 - 1); t5 > 0 && a3 > 0 && !this._isCharWordSeparator(n3.loadCell(t5 - 1, this._workCell)); ) {
              n3.loadCell(t5 - 1, this._workCell);
              const e5 = this._workCell.getChars().length;
              0 === this._workCell.getWidth() ? (l3++, t5--) : e5 > 1 && (_3 += e5 - 1, a3 -= e5 - 1), a3--, t5--;
            }
            for (; i5 < n3.length && h3 + 1 < o3.length && !this._isCharWordSeparator(n3.loadCell(i5 + 1, this._workCell)); ) {
              n3.loadCell(i5 + 1, this._workCell);
              const e5 = this._workCell.getChars().length;
              2 === this._workCell.getWidth() ? (d3++, i5++) : e5 > 1 && (u3 += e5 - 1, h3 += e5 - 1), h3++, i5++;
            }
          }
          h3++;
          let f3 = a3 + c3 - l3 + _3, v3 = Math.min(this._bufferService.cols, h3 - a3 + l3 + d3 - _3 - u3);
          if (t4 || "" !== o3.slice(a3, h3).trim()) {
            if (i4 && 0 === f3 && 32 !== n3.getCodePoint(0)) {
              const t5 = r3.lines.get(e4[1] - 1);
              if (t5 && n3.isWrapped && 32 !== t5.getCodePoint(this._bufferService.cols - 1)) {
                const t6 = this._getWordAt([this._bufferService.cols - 1, e4[1] - 1], false, true, false);
                if (t6) {
                  const e5 = this._bufferService.cols - t6.start;
                  f3 -= e5, v3 += e5;
                }
              }
            }
            if (s4 && f3 + v3 === this._bufferService.cols && 32 !== n3.getCodePoint(this._bufferService.cols - 1)) {
              const t5 = r3.lines.get(e4[1] + 1);
              if (t5?.isWrapped && 32 !== t5.getCodePoint(0)) {
                const t6 = this._getWordAt([0, e4[1] + 1], false, false, true);
                t6 && (v3 += t6.length);
              }
            }
            return { start: f3, length: v3 };
          }
        }
        _selectWordAt(e4, t4) {
          const i4 = this._getWordAt(e4, t4);
          if (i4) {
            for (; i4.start < 0; ) i4.start += this._bufferService.cols, e4[1]--;
            this._model.selectionStart = [i4.start, e4[1]], this._model.selectionStartLength = i4.length;
          }
        }
        _selectToWordAt(e4) {
          const t4 = this._getWordAt(e4, true);
          if (t4) {
            let i4 = e4[1];
            for (; t4.start < 0; ) t4.start += this._bufferService.cols, i4--;
            if (!this._model.areSelectionValuesReversed()) for (; t4.start + t4.length > this._bufferService.cols; ) t4.length -= this._bufferService.cols, i4++;
            this._model.selectionEnd = [this._model.areSelectionValuesReversed() ? t4.start : t4.start + t4.length, i4];
          }
        }
        _isCharWordSeparator(e4) {
          return 0 !== e4.getWidth() && this._optionsService.rawOptions.wordSeparator.indexOf(e4.getChars()) >= 0;
        }
        _selectLineAt(e4) {
          const t4 = this._bufferService.buffer.getWrappedRangeForLine(e4), i4 = { start: { x: 0, y: t4.first }, end: { x: this._bufferService.cols - 1, y: t4.last } };
          this._model.selectionStart = [0, t4.first], this._model.selectionEnd = void 0, this._model.selectionStartLength = (0, _2.getRangeLength)(i4, this._bufferService.cols);
        }
      };
      t3.SelectionService = g2 = s3([r2(3, f2.IBufferService), r2(4, f2.ICoreService), r2(5, h2.IMouseService), r2(6, f2.IOptionsService), r2(7, h2.IRenderService), r2(8, h2.ICoreBrowserService)], g2);
    }, 4725: (e3, t3, i3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.ILinkProviderService = t3.IThemeService = t3.ICharacterJoinerService = t3.ISelectionService = t3.IRenderService = t3.IMouseService = t3.ICoreBrowserService = t3.ICharSizeService = void 0;
      const s3 = i3(8343);
      t3.ICharSizeService = (0, s3.createDecorator)("CharSizeService"), t3.ICoreBrowserService = (0, s3.createDecorator)("CoreBrowserService"), t3.IMouseService = (0, s3.createDecorator)("MouseService"), t3.IRenderService = (0, s3.createDecorator)("RenderService"), t3.ISelectionService = (0, s3.createDecorator)("SelectionService"), t3.ICharacterJoinerService = (0, s3.createDecorator)("CharacterJoinerService"), t3.IThemeService = (0, s3.createDecorator)("ThemeService"), t3.ILinkProviderService = (0, s3.createDecorator)("LinkProviderService");
    }, 6731: function(e3, t3, i3) {
      var s3 = this && this.__decorate || function(e4, t4, i4, s4) {
        var r3, n3 = arguments.length, o3 = n3 < 3 ? t4 : null === s4 ? s4 = Object.getOwnPropertyDescriptor(t4, i4) : s4;
        if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) o3 = Reflect.decorate(e4, t4, i4, s4);
        else for (var a3 = e4.length - 1; a3 >= 0; a3--) (r3 = e4[a3]) && (o3 = (n3 < 3 ? r3(o3) : n3 > 3 ? r3(t4, i4, o3) : r3(t4, i4)) || o3);
        return n3 > 3 && o3 && Object.defineProperty(t4, i4, o3), o3;
      }, r2 = this && this.__param || function(e4, t4) {
        return function(i4, s4) {
          t4(i4, s4, e4);
        };
      };
      Object.defineProperty(t3, "__esModule", { value: true }), t3.ThemeService = t3.DEFAULT_ANSI_COLORS = void 0;
      const n2 = i3(7239), o2 = i3(8055), a2 = i3(8460), h2 = i3(844), c2 = i3(2585), l2 = o2.css.toColor("#ffffff"), d2 = o2.css.toColor("#000000"), _2 = o2.css.toColor("#ffffff"), u2 = o2.css.toColor("#000000"), f2 = { css: "rgba(255, 255, 255, 0.3)", rgba: 4294967117 };
      t3.DEFAULT_ANSI_COLORS = Object.freeze((() => {
        const e4 = [o2.css.toColor("#2e3436"), o2.css.toColor("#cc0000"), o2.css.toColor("#4e9a06"), o2.css.toColor("#c4a000"), o2.css.toColor("#3465a4"), o2.css.toColor("#75507b"), o2.css.toColor("#06989a"), o2.css.toColor("#d3d7cf"), o2.css.toColor("#555753"), o2.css.toColor("#ef2929"), o2.css.toColor("#8ae234"), o2.css.toColor("#fce94f"), o2.css.toColor("#729fcf"), o2.css.toColor("#ad7fa8"), o2.css.toColor("#34e2e2"), o2.css.toColor("#eeeeec")], t4 = [0, 95, 135, 175, 215, 255];
        for (let i4 = 0; i4 < 216; i4++) {
          const s4 = t4[i4 / 36 % 6 | 0], r3 = t4[i4 / 6 % 6 | 0], n3 = t4[i4 % 6];
          e4.push({ css: o2.channels.toCss(s4, r3, n3), rgba: o2.channels.toRgba(s4, r3, n3) });
        }
        for (let t5 = 0; t5 < 24; t5++) {
          const i4 = 8 + 10 * t5;
          e4.push({ css: o2.channels.toCss(i4, i4, i4), rgba: o2.channels.toRgba(i4, i4, i4) });
        }
        return e4;
      })());
      let v2 = t3.ThemeService = class extends h2.Disposable {
        get colors() {
          return this._colors;
        }
        constructor(e4) {
          super(), this._optionsService = e4, this._contrastCache = new n2.ColorContrastCache(), this._halfContrastCache = new n2.ColorContrastCache(), this._onChangeColors = this.register(new a2.EventEmitter()), this.onChangeColors = this._onChangeColors.event, this._colors = { foreground: l2, background: d2, cursor: _2, cursorAccent: u2, selectionForeground: void 0, selectionBackgroundTransparent: f2, selectionBackgroundOpaque: o2.color.blend(d2, f2), selectionInactiveBackgroundTransparent: f2, selectionInactiveBackgroundOpaque: o2.color.blend(d2, f2), ansi: t3.DEFAULT_ANSI_COLORS.slice(), contrastCache: this._contrastCache, halfContrastCache: this._halfContrastCache }, this._updateRestoreColors(), this._setTheme(this._optionsService.rawOptions.theme), this.register(this._optionsService.onSpecificOptionChange("minimumContrastRatio", () => this._contrastCache.clear())), this.register(this._optionsService.onSpecificOptionChange("theme", () => this._setTheme(this._optionsService.rawOptions.theme)));
        }
        _setTheme(e4 = {}) {
          const i4 = this._colors;
          if (i4.foreground = p2(e4.foreground, l2), i4.background = p2(e4.background, d2), i4.cursor = p2(e4.cursor, _2), i4.cursorAccent = p2(e4.cursorAccent, u2), i4.selectionBackgroundTransparent = p2(e4.selectionBackground, f2), i4.selectionBackgroundOpaque = o2.color.blend(i4.background, i4.selectionBackgroundTransparent), i4.selectionInactiveBackgroundTransparent = p2(e4.selectionInactiveBackground, i4.selectionBackgroundTransparent), i4.selectionInactiveBackgroundOpaque = o2.color.blend(i4.background, i4.selectionInactiveBackgroundTransparent), i4.selectionForeground = e4.selectionForeground ? p2(e4.selectionForeground, o2.NULL_COLOR) : void 0, i4.selectionForeground === o2.NULL_COLOR && (i4.selectionForeground = void 0), o2.color.isOpaque(i4.selectionBackgroundTransparent)) {
            const e5 = 0.3;
            i4.selectionBackgroundTransparent = o2.color.opacity(i4.selectionBackgroundTransparent, e5);
          }
          if (o2.color.isOpaque(i4.selectionInactiveBackgroundTransparent)) {
            const e5 = 0.3;
            i4.selectionInactiveBackgroundTransparent = o2.color.opacity(i4.selectionInactiveBackgroundTransparent, e5);
          }
          if (i4.ansi = t3.DEFAULT_ANSI_COLORS.slice(), i4.ansi[0] = p2(e4.black, t3.DEFAULT_ANSI_COLORS[0]), i4.ansi[1] = p2(e4.red, t3.DEFAULT_ANSI_COLORS[1]), i4.ansi[2] = p2(e4.green, t3.DEFAULT_ANSI_COLORS[2]), i4.ansi[3] = p2(e4.yellow, t3.DEFAULT_ANSI_COLORS[3]), i4.ansi[4] = p2(e4.blue, t3.DEFAULT_ANSI_COLORS[4]), i4.ansi[5] = p2(e4.magenta, t3.DEFAULT_ANSI_COLORS[5]), i4.ansi[6] = p2(e4.cyan, t3.DEFAULT_ANSI_COLORS[6]), i4.ansi[7] = p2(e4.white, t3.DEFAULT_ANSI_COLORS[7]), i4.ansi[8] = p2(e4.brightBlack, t3.DEFAULT_ANSI_COLORS[8]), i4.ansi[9] = p2(e4.brightRed, t3.DEFAULT_ANSI_COLORS[9]), i4.ansi[10] = p2(e4.brightGreen, t3.DEFAULT_ANSI_COLORS[10]), i4.ansi[11] = p2(e4.brightYellow, t3.DEFAULT_ANSI_COLORS[11]), i4.ansi[12] = p2(e4.brightBlue, t3.DEFAULT_ANSI_COLORS[12]), i4.ansi[13] = p2(e4.brightMagenta, t3.DEFAULT_ANSI_COLORS[13]), i4.ansi[14] = p2(e4.brightCyan, t3.DEFAULT_ANSI_COLORS[14]), i4.ansi[15] = p2(e4.brightWhite, t3.DEFAULT_ANSI_COLORS[15]), e4.extendedAnsi) {
            const s4 = Math.min(i4.ansi.length - 16, e4.extendedAnsi.length);
            for (let r3 = 0; r3 < s4; r3++) i4.ansi[r3 + 16] = p2(e4.extendedAnsi[r3], t3.DEFAULT_ANSI_COLORS[r3 + 16]);
          }
          this._contrastCache.clear(), this._halfContrastCache.clear(), this._updateRestoreColors(), this._onChangeColors.fire(this.colors);
        }
        restoreColor(e4) {
          this._restoreColor(e4), this._onChangeColors.fire(this.colors);
        }
        _restoreColor(e4) {
          if (void 0 !== e4) switch (e4) {
            case 256:
              this._colors.foreground = this._restoreColors.foreground;
              break;
            case 257:
              this._colors.background = this._restoreColors.background;
              break;
            case 258:
              this._colors.cursor = this._restoreColors.cursor;
              break;
            default:
              this._colors.ansi[e4] = this._restoreColors.ansi[e4];
          }
          else for (let e5 = 0; e5 < this._restoreColors.ansi.length; ++e5) this._colors.ansi[e5] = this._restoreColors.ansi[e5];
        }
        modifyColors(e4) {
          e4(this._colors), this._onChangeColors.fire(this.colors);
        }
        _updateRestoreColors() {
          this._restoreColors = { foreground: this._colors.foreground, background: this._colors.background, cursor: this._colors.cursor, ansi: this._colors.ansi.slice() };
        }
      };
      function p2(e4, t4) {
        if (void 0 !== e4) try {
          return o2.css.toColor(e4);
        } catch {
        }
        return t4;
      }
      __name(p2, "p");
      t3.ThemeService = v2 = s3([r2(0, c2.IOptionsService)], v2);
    }, 6349: (e3, t3, i3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.CircularList = void 0;
      const s3 = i3(8460), r2 = i3(844);
      class n2 extends r2.Disposable {
        static {
          __name(this, "n");
        }
        constructor(e4) {
          super(), this._maxLength = e4, this.onDeleteEmitter = this.register(new s3.EventEmitter()), this.onDelete = this.onDeleteEmitter.event, this.onInsertEmitter = this.register(new s3.EventEmitter()), this.onInsert = this.onInsertEmitter.event, this.onTrimEmitter = this.register(new s3.EventEmitter()), this.onTrim = this.onTrimEmitter.event, this._array = new Array(this._maxLength), this._startIndex = 0, this._length = 0;
        }
        get maxLength() {
          return this._maxLength;
        }
        set maxLength(e4) {
          if (this._maxLength === e4) return;
          const t4 = new Array(e4);
          for (let i4 = 0; i4 < Math.min(e4, this.length); i4++) t4[i4] = this._array[this._getCyclicIndex(i4)];
          this._array = t4, this._maxLength = e4, this._startIndex = 0;
        }
        get length() {
          return this._length;
        }
        set length(e4) {
          if (e4 > this._length) for (let t4 = this._length; t4 < e4; t4++) this._array[t4] = void 0;
          this._length = e4;
        }
        get(e4) {
          return this._array[this._getCyclicIndex(e4)];
        }
        set(e4, t4) {
          this._array[this._getCyclicIndex(e4)] = t4;
        }
        push(e4) {
          this._array[this._getCyclicIndex(this._length)] = e4, this._length === this._maxLength ? (this._startIndex = ++this._startIndex % this._maxLength, this.onTrimEmitter.fire(1)) : this._length++;
        }
        recycle() {
          if (this._length !== this._maxLength) throw new Error("Can only recycle when the buffer is full");
          return this._startIndex = ++this._startIndex % this._maxLength, this.onTrimEmitter.fire(1), this._array[this._getCyclicIndex(this._length - 1)];
        }
        get isFull() {
          return this._length === this._maxLength;
        }
        pop() {
          return this._array[this._getCyclicIndex(this._length-- - 1)];
        }
        splice(e4, t4, ...i4) {
          if (t4) {
            for (let i5 = e4; i5 < this._length - t4; i5++) this._array[this._getCyclicIndex(i5)] = this._array[this._getCyclicIndex(i5 + t4)];
            this._length -= t4, this.onDeleteEmitter.fire({ index: e4, amount: t4 });
          }
          for (let t5 = this._length - 1; t5 >= e4; t5--) this._array[this._getCyclicIndex(t5 + i4.length)] = this._array[this._getCyclicIndex(t5)];
          for (let t5 = 0; t5 < i4.length; t5++) this._array[this._getCyclicIndex(e4 + t5)] = i4[t5];
          if (i4.length && this.onInsertEmitter.fire({ index: e4, amount: i4.length }), this._length + i4.length > this._maxLength) {
            const e5 = this._length + i4.length - this._maxLength;
            this._startIndex += e5, this._length = this._maxLength, this.onTrimEmitter.fire(e5);
          } else this._length += i4.length;
        }
        trimStart(e4) {
          e4 > this._length && (e4 = this._length), this._startIndex += e4, this._length -= e4, this.onTrimEmitter.fire(e4);
        }
        shiftElements(e4, t4, i4) {
          if (!(t4 <= 0)) {
            if (e4 < 0 || e4 >= this._length) throw new Error("start argument out of range");
            if (e4 + i4 < 0) throw new Error("Cannot shift elements in list beyond index 0");
            if (i4 > 0) {
              for (let s5 = t4 - 1; s5 >= 0; s5--) this.set(e4 + s5 + i4, this.get(e4 + s5));
              const s4 = e4 + t4 + i4 - this._length;
              if (s4 > 0) for (this._length += s4; this._length > this._maxLength; ) this._length--, this._startIndex++, this.onTrimEmitter.fire(1);
            } else for (let s4 = 0; s4 < t4; s4++) this.set(e4 + s4 + i4, this.get(e4 + s4));
          }
        }
        _getCyclicIndex(e4) {
          return (this._startIndex + e4) % this._maxLength;
        }
      }
      t3.CircularList = n2;
    }, 1439: (e3, t3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.clone = void 0, t3.clone = /* @__PURE__ */ __name(function e4(t4, i3 = 5) {
        if ("object" != typeof t4) return t4;
        const s3 = Array.isArray(t4) ? [] : {};
        for (const r2 in t4) s3[r2] = i3 <= 1 ? t4[r2] : t4[r2] && e4(t4[r2], i3 - 1);
        return s3;
      }, "e");
    }, 8055: (e3, t3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.contrastRatio = t3.toPaddedHex = t3.rgba = t3.rgb = t3.css = t3.color = t3.channels = t3.NULL_COLOR = void 0;
      let i3 = 0, s3 = 0, r2 = 0, n2 = 0;
      var o2, a2, h2, c2, l2;
      function d2(e4) {
        const t4 = e4.toString(16);
        return t4.length < 2 ? "0" + t4 : t4;
      }
      __name(d2, "d");
      function _2(e4, t4) {
        return e4 < t4 ? (t4 + 0.05) / (e4 + 0.05) : (e4 + 0.05) / (t4 + 0.05);
      }
      __name(_2, "_");
      t3.NULL_COLOR = { css: "#00000000", rgba: 0 }, function(e4) {
        e4.toCss = function(e5, t4, i4, s4) {
          return void 0 !== s4 ? `#${d2(e5)}${d2(t4)}${d2(i4)}${d2(s4)}` : `#${d2(e5)}${d2(t4)}${d2(i4)}`;
        }, e4.toRgba = function(e5, t4, i4, s4 = 255) {
          return (e5 << 24 | t4 << 16 | i4 << 8 | s4) >>> 0;
        }, e4.toColor = function(t4, i4, s4, r3) {
          return { css: e4.toCss(t4, i4, s4, r3), rgba: e4.toRgba(t4, i4, s4, r3) };
        };
      }(o2 || (t3.channels = o2 = {})), function(e4) {
        function t4(e5, t5) {
          return n2 = Math.round(255 * t5), [i3, s3, r2] = l2.toChannels(e5.rgba), { css: o2.toCss(i3, s3, r2, n2), rgba: o2.toRgba(i3, s3, r2, n2) };
        }
        __name(t4, "t");
        e4.blend = function(e5, t5) {
          if (n2 = (255 & t5.rgba) / 255, 1 === n2) return { css: t5.css, rgba: t5.rgba };
          const a3 = t5.rgba >> 24 & 255, h3 = t5.rgba >> 16 & 255, c3 = t5.rgba >> 8 & 255, l3 = e5.rgba >> 24 & 255, d3 = e5.rgba >> 16 & 255, _3 = e5.rgba >> 8 & 255;
          return i3 = l3 + Math.round((a3 - l3) * n2), s3 = d3 + Math.round((h3 - d3) * n2), r2 = _3 + Math.round((c3 - _3) * n2), { css: o2.toCss(i3, s3, r2), rgba: o2.toRgba(i3, s3, r2) };
        }, e4.isOpaque = function(e5) {
          return 255 == (255 & e5.rgba);
        }, e4.ensureContrastRatio = function(e5, t5, i4) {
          const s4 = l2.ensureContrastRatio(e5.rgba, t5.rgba, i4);
          if (s4) return o2.toColor(s4 >> 24 & 255, s4 >> 16 & 255, s4 >> 8 & 255);
        }, e4.opaque = function(e5) {
          const t5 = (255 | e5.rgba) >>> 0;
          return [i3, s3, r2] = l2.toChannels(t5), { css: o2.toCss(i3, s3, r2), rgba: t5 };
        }, e4.opacity = t4, e4.multiplyOpacity = function(e5, i4) {
          return n2 = 255 & e5.rgba, t4(e5, n2 * i4 / 255);
        }, e4.toColorRGB = function(e5) {
          return [e5.rgba >> 24 & 255, e5.rgba >> 16 & 255, e5.rgba >> 8 & 255];
        };
      }(a2 || (t3.color = a2 = {})), function(e4) {
        let t4, a3;
        try {
          const e5 = document.createElement("canvas");
          e5.width = 1, e5.height = 1;
          const i4 = e5.getContext("2d", { willReadFrequently: true });
          i4 && (t4 = i4, t4.globalCompositeOperation = "copy", a3 = t4.createLinearGradient(0, 0, 1, 1));
        } catch {
        }
        e4.toColor = function(e5) {
          if (e5.match(/#[\da-f]{3,8}/i)) switch (e5.length) {
            case 4:
              return i3 = parseInt(e5.slice(1, 2).repeat(2), 16), s3 = parseInt(e5.slice(2, 3).repeat(2), 16), r2 = parseInt(e5.slice(3, 4).repeat(2), 16), o2.toColor(i3, s3, r2);
            case 5:
              return i3 = parseInt(e5.slice(1, 2).repeat(2), 16), s3 = parseInt(e5.slice(2, 3).repeat(2), 16), r2 = parseInt(e5.slice(3, 4).repeat(2), 16), n2 = parseInt(e5.slice(4, 5).repeat(2), 16), o2.toColor(i3, s3, r2, n2);
            case 7:
              return { css: e5, rgba: (parseInt(e5.slice(1), 16) << 8 | 255) >>> 0 };
            case 9:
              return { css: e5, rgba: parseInt(e5.slice(1), 16) >>> 0 };
          }
          const h3 = e5.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);
          if (h3) return i3 = parseInt(h3[1]), s3 = parseInt(h3[2]), r2 = parseInt(h3[3]), n2 = Math.round(255 * (void 0 === h3[5] ? 1 : parseFloat(h3[5]))), o2.toColor(i3, s3, r2, n2);
          if (!t4 || !a3) throw new Error("css.toColor: Unsupported css format");
          if (t4.fillStyle = a3, t4.fillStyle = e5, "string" != typeof t4.fillStyle) throw new Error("css.toColor: Unsupported css format");
          if (t4.fillRect(0, 0, 1, 1), [i3, s3, r2, n2] = t4.getImageData(0, 0, 1, 1).data, 255 !== n2) throw new Error("css.toColor: Unsupported css format");
          return { rgba: o2.toRgba(i3, s3, r2, n2), css: e5 };
        };
      }(h2 || (t3.css = h2 = {})), function(e4) {
        function t4(e5, t5, i4) {
          const s4 = e5 / 255, r3 = t5 / 255, n3 = i4 / 255;
          return 0.2126 * (s4 <= 0.03928 ? s4 / 12.92 : Math.pow((s4 + 0.055) / 1.055, 2.4)) + 0.7152 * (r3 <= 0.03928 ? r3 / 12.92 : Math.pow((r3 + 0.055) / 1.055, 2.4)) + 0.0722 * (n3 <= 0.03928 ? n3 / 12.92 : Math.pow((n3 + 0.055) / 1.055, 2.4));
        }
        __name(t4, "t");
        e4.relativeLuminance = function(e5) {
          return t4(e5 >> 16 & 255, e5 >> 8 & 255, 255 & e5);
        }, e4.relativeLuminance2 = t4;
      }(c2 || (t3.rgb = c2 = {})), function(e4) {
        function t4(e5, t5, i4) {
          const s4 = e5 >> 24 & 255, r3 = e5 >> 16 & 255, n3 = e5 >> 8 & 255;
          let o3 = t5 >> 24 & 255, a4 = t5 >> 16 & 255, h3 = t5 >> 8 & 255, l3 = _2(c2.relativeLuminance2(o3, a4, h3), c2.relativeLuminance2(s4, r3, n3));
          for (; l3 < i4 && (o3 > 0 || a4 > 0 || h3 > 0); ) o3 -= Math.max(0, Math.ceil(0.1 * o3)), a4 -= Math.max(0, Math.ceil(0.1 * a4)), h3 -= Math.max(0, Math.ceil(0.1 * h3)), l3 = _2(c2.relativeLuminance2(o3, a4, h3), c2.relativeLuminance2(s4, r3, n3));
          return (o3 << 24 | a4 << 16 | h3 << 8 | 255) >>> 0;
        }
        __name(t4, "t");
        function a3(e5, t5, i4) {
          const s4 = e5 >> 24 & 255, r3 = e5 >> 16 & 255, n3 = e5 >> 8 & 255;
          let o3 = t5 >> 24 & 255, a4 = t5 >> 16 & 255, h3 = t5 >> 8 & 255, l3 = _2(c2.relativeLuminance2(o3, a4, h3), c2.relativeLuminance2(s4, r3, n3));
          for (; l3 < i4 && (o3 < 255 || a4 < 255 || h3 < 255); ) o3 = Math.min(255, o3 + Math.ceil(0.1 * (255 - o3))), a4 = Math.min(255, a4 + Math.ceil(0.1 * (255 - a4))), h3 = Math.min(255, h3 + Math.ceil(0.1 * (255 - h3))), l3 = _2(c2.relativeLuminance2(o3, a4, h3), c2.relativeLuminance2(s4, r3, n3));
          return (o3 << 24 | a4 << 16 | h3 << 8 | 255) >>> 0;
        }
        __name(a3, "a");
        e4.blend = function(e5, t5) {
          if (n2 = (255 & t5) / 255, 1 === n2) return t5;
          const a4 = t5 >> 24 & 255, h3 = t5 >> 16 & 255, c3 = t5 >> 8 & 255, l3 = e5 >> 24 & 255, d3 = e5 >> 16 & 255, _3 = e5 >> 8 & 255;
          return i3 = l3 + Math.round((a4 - l3) * n2), s3 = d3 + Math.round((h3 - d3) * n2), r2 = _3 + Math.round((c3 - _3) * n2), o2.toRgba(i3, s3, r2);
        }, e4.ensureContrastRatio = function(e5, i4, s4) {
          const r3 = c2.relativeLuminance(e5 >> 8), n3 = c2.relativeLuminance(i4 >> 8);
          if (_2(r3, n3) < s4) {
            if (n3 < r3) {
              const n4 = t4(e5, i4, s4), o4 = _2(r3, c2.relativeLuminance(n4 >> 8));
              if (o4 < s4) {
                const t5 = a3(e5, i4, s4);
                return o4 > _2(r3, c2.relativeLuminance(t5 >> 8)) ? n4 : t5;
              }
              return n4;
            }
            const o3 = a3(e5, i4, s4), h3 = _2(r3, c2.relativeLuminance(o3 >> 8));
            if (h3 < s4) {
              const n4 = t4(e5, i4, s4);
              return h3 > _2(r3, c2.relativeLuminance(n4 >> 8)) ? o3 : n4;
            }
            return o3;
          }
        }, e4.reduceLuminance = t4, e4.increaseLuminance = a3, e4.toChannels = function(e5) {
          return [e5 >> 24 & 255, e5 >> 16 & 255, e5 >> 8 & 255, 255 & e5];
        };
      }(l2 || (t3.rgba = l2 = {})), t3.toPaddedHex = d2, t3.contrastRatio = _2;
    }, 8969: (e3, t3, i3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.CoreTerminal = void 0;
      const s3 = i3(844), r2 = i3(2585), n2 = i3(4348), o2 = i3(7866), a2 = i3(744), h2 = i3(7302), c2 = i3(6975), l2 = i3(8460), d2 = i3(1753), _2 = i3(1480), u2 = i3(7994), f2 = i3(9282), v2 = i3(5435), p2 = i3(5981), g2 = i3(2660);
      let m2 = false;
      class S2 extends s3.Disposable {
        static {
          __name(this, "S");
        }
        get onScroll() {
          return this._onScrollApi || (this._onScrollApi = this.register(new l2.EventEmitter()), this._onScroll.event((e4) => {
            this._onScrollApi?.fire(e4.position);
          })), this._onScrollApi.event;
        }
        get cols() {
          return this._bufferService.cols;
        }
        get rows() {
          return this._bufferService.rows;
        }
        get buffers() {
          return this._bufferService.buffers;
        }
        get options() {
          return this.optionsService.options;
        }
        set options(e4) {
          for (const t4 in e4) this.optionsService.options[t4] = e4[t4];
        }
        constructor(e4) {
          super(), this._windowsWrappingHeuristics = this.register(new s3.MutableDisposable()), this._onBinary = this.register(new l2.EventEmitter()), this.onBinary = this._onBinary.event, this._onData = this.register(new l2.EventEmitter()), this.onData = this._onData.event, this._onLineFeed = this.register(new l2.EventEmitter()), this.onLineFeed = this._onLineFeed.event, this._onResize = this.register(new l2.EventEmitter()), this.onResize = this._onResize.event, this._onWriteParsed = this.register(new l2.EventEmitter()), this.onWriteParsed = this._onWriteParsed.event, this._onScroll = this.register(new l2.EventEmitter()), this._instantiationService = new n2.InstantiationService(), this.optionsService = this.register(new h2.OptionsService(e4)), this._instantiationService.setService(r2.IOptionsService, this.optionsService), this._bufferService = this.register(this._instantiationService.createInstance(a2.BufferService)), this._instantiationService.setService(r2.IBufferService, this._bufferService), this._logService = this.register(this._instantiationService.createInstance(o2.LogService)), this._instantiationService.setService(r2.ILogService, this._logService), this.coreService = this.register(this._instantiationService.createInstance(c2.CoreService)), this._instantiationService.setService(r2.ICoreService, this.coreService), this.coreMouseService = this.register(this._instantiationService.createInstance(d2.CoreMouseService)), this._instantiationService.setService(r2.ICoreMouseService, this.coreMouseService), this.unicodeService = this.register(this._instantiationService.createInstance(_2.UnicodeService)), this._instantiationService.setService(r2.IUnicodeService, this.unicodeService), this._charsetService = this._instantiationService.createInstance(u2.CharsetService), this._instantiationService.setService(r2.ICharsetService, this._charsetService), this._oscLinkService = this._instantiationService.createInstance(g2.OscLinkService), this._instantiationService.setService(r2.IOscLinkService, this._oscLinkService), this._inputHandler = this.register(new v2.InputHandler(this._bufferService, this._charsetService, this.coreService, this._logService, this.optionsService, this._oscLinkService, this.coreMouseService, this.unicodeService)), this.register((0, l2.forwardEvent)(this._inputHandler.onLineFeed, this._onLineFeed)), this.register(this._inputHandler), this.register((0, l2.forwardEvent)(this._bufferService.onResize, this._onResize)), this.register((0, l2.forwardEvent)(this.coreService.onData, this._onData)), this.register((0, l2.forwardEvent)(this.coreService.onBinary, this._onBinary)), this.register(this.coreService.onRequestScrollToBottom(() => this.scrollToBottom())), this.register(this.coreService.onUserInput(() => this._writeBuffer.handleUserInput())), this.register(this.optionsService.onMultipleOptionChange(["windowsMode", "windowsPty"], () => this._handleWindowsPtyOptionChange())), this.register(this._bufferService.onScroll((e5) => {
            this._onScroll.fire({ position: this._bufferService.buffer.ydisp, source: 0 }), this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop, this._bufferService.buffer.scrollBottom);
          })), this.register(this._inputHandler.onScroll((e5) => {
            this._onScroll.fire({ position: this._bufferService.buffer.ydisp, source: 0 }), this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop, this._bufferService.buffer.scrollBottom);
          })), this._writeBuffer = this.register(new p2.WriteBuffer((e5, t4) => this._inputHandler.parse(e5, t4))), this.register((0, l2.forwardEvent)(this._writeBuffer.onWriteParsed, this._onWriteParsed));
        }
        write(e4, t4) {
          this._writeBuffer.write(e4, t4);
        }
        writeSync(e4, t4) {
          this._logService.logLevel <= r2.LogLevelEnum.WARN && !m2 && (this._logService.warn("writeSync is unreliable and will be removed soon."), m2 = true), this._writeBuffer.writeSync(e4, t4);
        }
        input(e4, t4 = true) {
          this.coreService.triggerDataEvent(e4, t4);
        }
        resize(e4, t4) {
          isNaN(e4) || isNaN(t4) || (e4 = Math.max(e4, a2.MINIMUM_COLS), t4 = Math.max(t4, a2.MINIMUM_ROWS), this._bufferService.resize(e4, t4));
        }
        scroll(e4, t4 = false) {
          this._bufferService.scroll(e4, t4);
        }
        scrollLines(e4, t4, i4) {
          this._bufferService.scrollLines(e4, t4, i4);
        }
        scrollPages(e4) {
          this.scrollLines(e4 * (this.rows - 1));
        }
        scrollToTop() {
          this.scrollLines(-this._bufferService.buffer.ydisp);
        }
        scrollToBottom() {
          this.scrollLines(this._bufferService.buffer.ybase - this._bufferService.buffer.ydisp);
        }
        scrollToLine(e4) {
          const t4 = e4 - this._bufferService.buffer.ydisp;
          0 !== t4 && this.scrollLines(t4);
        }
        registerEscHandler(e4, t4) {
          return this._inputHandler.registerEscHandler(e4, t4);
        }
        registerDcsHandler(e4, t4) {
          return this._inputHandler.registerDcsHandler(e4, t4);
        }
        registerCsiHandler(e4, t4) {
          return this._inputHandler.registerCsiHandler(e4, t4);
        }
        registerOscHandler(e4, t4) {
          return this._inputHandler.registerOscHandler(e4, t4);
        }
        _setup() {
          this._handleWindowsPtyOptionChange();
        }
        reset() {
          this._inputHandler.reset(), this._bufferService.reset(), this._charsetService.reset(), this.coreService.reset(), this.coreMouseService.reset();
        }
        _handleWindowsPtyOptionChange() {
          let e4 = false;
          const t4 = this.optionsService.rawOptions.windowsPty;
          t4 && void 0 !== t4.buildNumber && void 0 !== t4.buildNumber ? e4 = !!("conpty" === t4.backend && t4.buildNumber < 21376) : this.optionsService.rawOptions.windowsMode && (e4 = true), e4 ? this._enableWindowsWrappingHeuristics() : this._windowsWrappingHeuristics.clear();
        }
        _enableWindowsWrappingHeuristics() {
          if (!this._windowsWrappingHeuristics.value) {
            const e4 = [];
            e4.push(this.onLineFeed(f2.updateWindowsModeWrappedState.bind(null, this._bufferService))), e4.push(this.registerCsiHandler({ final: "H" }, () => ((0, f2.updateWindowsModeWrappedState)(this._bufferService), false))), this._windowsWrappingHeuristics.value = (0, s3.toDisposable)(() => {
              for (const t4 of e4) t4.dispose();
            });
          }
        }
      }
      t3.CoreTerminal = S2;
    }, 8460: (e3, t3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.runAndSubscribe = t3.forwardEvent = t3.EventEmitter = void 0, t3.EventEmitter = class {
        constructor() {
          this._listeners = [], this._disposed = false;
        }
        get event() {
          return this._event || (this._event = (e4) => (this._listeners.push(e4), { dispose: /* @__PURE__ */ __name(() => {
            if (!this._disposed) {
              for (let t4 = 0; t4 < this._listeners.length; t4++) if (this._listeners[t4] === e4) return void this._listeners.splice(t4, 1);
            }
          }, "dispose") })), this._event;
        }
        fire(e4, t4) {
          const i3 = [];
          for (let e5 = 0; e5 < this._listeners.length; e5++) i3.push(this._listeners[e5]);
          for (let s3 = 0; s3 < i3.length; s3++) i3[s3].call(void 0, e4, t4);
        }
        dispose() {
          this.clearListeners(), this._disposed = true;
        }
        clearListeners() {
          this._listeners && (this._listeners.length = 0);
        }
      }, t3.forwardEvent = function(e4, t4) {
        return e4((e5) => t4.fire(e5));
      }, t3.runAndSubscribe = function(e4, t4) {
        return t4(void 0), e4((e5) => t4(e5));
      };
    }, 5435: function(e3, t3, i3) {
      var s3 = this && this.__decorate || function(e4, t4, i4, s4) {
        var r3, n3 = arguments.length, o3 = n3 < 3 ? t4 : null === s4 ? s4 = Object.getOwnPropertyDescriptor(t4, i4) : s4;
        if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) o3 = Reflect.decorate(e4, t4, i4, s4);
        else for (var a3 = e4.length - 1; a3 >= 0; a3--) (r3 = e4[a3]) && (o3 = (n3 < 3 ? r3(o3) : n3 > 3 ? r3(t4, i4, o3) : r3(t4, i4)) || o3);
        return n3 > 3 && o3 && Object.defineProperty(t4, i4, o3), o3;
      }, r2 = this && this.__param || function(e4, t4) {
        return function(i4, s4) {
          t4(i4, s4, e4);
        };
      };
      Object.defineProperty(t3, "__esModule", { value: true }), t3.InputHandler = t3.WindowsOptionsReportType = void 0;
      const n2 = i3(2584), o2 = i3(7116), a2 = i3(2015), h2 = i3(844), c2 = i3(482), l2 = i3(8437), d2 = i3(8460), _2 = i3(643), u2 = i3(511), f2 = i3(3734), v2 = i3(2585), p2 = i3(1480), g2 = i3(6242), m2 = i3(6351), S2 = i3(5941), C2 = { "(": 0, ")": 1, "*": 2, "+": 3, "-": 1, ".": 2 }, b2 = 131072;
      function w2(e4, t4) {
        if (e4 > 24) return t4.setWinLines || false;
        switch (e4) {
          case 1:
            return !!t4.restoreWin;
          case 2:
            return !!t4.minimizeWin;
          case 3:
            return !!t4.setWinPosition;
          case 4:
            return !!t4.setWinSizePixels;
          case 5:
            return !!t4.raiseWin;
          case 6:
            return !!t4.lowerWin;
          case 7:
            return !!t4.refreshWin;
          case 8:
            return !!t4.setWinSizeChars;
          case 9:
            return !!t4.maximizeWin;
          case 10:
            return !!t4.fullscreenWin;
          case 11:
            return !!t4.getWinState;
          case 13:
            return !!t4.getWinPosition;
          case 14:
            return !!t4.getWinSizePixels;
          case 15:
            return !!t4.getScreenSizePixels;
          case 16:
            return !!t4.getCellSizePixels;
          case 18:
            return !!t4.getWinSizeChars;
          case 19:
            return !!t4.getScreenSizeChars;
          case 20:
            return !!t4.getIconTitle;
          case 21:
            return !!t4.getWinTitle;
          case 22:
            return !!t4.pushTitle;
          case 23:
            return !!t4.popTitle;
          case 24:
            return !!t4.setWinLines;
        }
        return false;
      }
      __name(w2, "w");
      var y2;
      !function(e4) {
        e4[e4.GET_WIN_SIZE_PIXELS = 0] = "GET_WIN_SIZE_PIXELS", e4[e4.GET_CELL_SIZE_PIXELS = 1] = "GET_CELL_SIZE_PIXELS";
      }(y2 || (t3.WindowsOptionsReportType = y2 = {}));
      let E = 0;
      class k2 extends h2.Disposable {
        static {
          __name(this, "k");
        }
        getAttrData() {
          return this._curAttrData;
        }
        constructor(e4, t4, i4, s4, r3, h3, _3, f3, v3 = new a2.EscapeSequenceParser()) {
          super(), this._bufferService = e4, this._charsetService = t4, this._coreService = i4, this._logService = s4, this._optionsService = r3, this._oscLinkService = h3, this._coreMouseService = _3, this._unicodeService = f3, this._parser = v3, this._parseBuffer = new Uint32Array(4096), this._stringDecoder = new c2.StringToUtf32(), this._utf8Decoder = new c2.Utf8ToUtf32(), this._workCell = new u2.CellData(), this._windowTitle = "", this._iconName = "", this._windowTitleStack = [], this._iconNameStack = [], this._curAttrData = l2.DEFAULT_ATTR_DATA.clone(), this._eraseAttrDataInternal = l2.DEFAULT_ATTR_DATA.clone(), this._onRequestBell = this.register(new d2.EventEmitter()), this.onRequestBell = this._onRequestBell.event, this._onRequestRefreshRows = this.register(new d2.EventEmitter()), this.onRequestRefreshRows = this._onRequestRefreshRows.event, this._onRequestReset = this.register(new d2.EventEmitter()), this.onRequestReset = this._onRequestReset.event, this._onRequestSendFocus = this.register(new d2.EventEmitter()), this.onRequestSendFocus = this._onRequestSendFocus.event, this._onRequestSyncScrollBar = this.register(new d2.EventEmitter()), this.onRequestSyncScrollBar = this._onRequestSyncScrollBar.event, this._onRequestWindowsOptionsReport = this.register(new d2.EventEmitter()), this.onRequestWindowsOptionsReport = this._onRequestWindowsOptionsReport.event, this._onA11yChar = this.register(new d2.EventEmitter()), this.onA11yChar = this._onA11yChar.event, this._onA11yTab = this.register(new d2.EventEmitter()), this.onA11yTab = this._onA11yTab.event, this._onCursorMove = this.register(new d2.EventEmitter()), this.onCursorMove = this._onCursorMove.event, this._onLineFeed = this.register(new d2.EventEmitter()), this.onLineFeed = this._onLineFeed.event, this._onScroll = this.register(new d2.EventEmitter()), this.onScroll = this._onScroll.event, this._onTitleChange = this.register(new d2.EventEmitter()), this.onTitleChange = this._onTitleChange.event, this._onColor = this.register(new d2.EventEmitter()), this.onColor = this._onColor.event, this._parseStack = { paused: false, cursorStartX: 0, cursorStartY: 0, decodedLength: 0, position: 0 }, this._specialColors = [256, 257, 258], this.register(this._parser), this._dirtyRowTracker = new L2(this._bufferService), this._activeBuffer = this._bufferService.buffer, this.register(this._bufferService.buffers.onBufferActivate((e5) => this._activeBuffer = e5.activeBuffer)), this._parser.setCsiHandlerFallback((e5, t5) => {
            this._logService.debug("Unknown CSI code: ", { identifier: this._parser.identToString(e5), params: t5.toArray() });
          }), this._parser.setEscHandlerFallback((e5) => {
            this._logService.debug("Unknown ESC code: ", { identifier: this._parser.identToString(e5) });
          }), this._parser.setExecuteHandlerFallback((e5) => {
            this._logService.debug("Unknown EXECUTE code: ", { code: e5 });
          }), this._parser.setOscHandlerFallback((e5, t5, i5) => {
            this._logService.debug("Unknown OSC code: ", { identifier: e5, action: t5, data: i5 });
          }), this._parser.setDcsHandlerFallback((e5, t5, i5) => {
            "HOOK" === t5 && (i5 = i5.toArray()), this._logService.debug("Unknown DCS code: ", { identifier: this._parser.identToString(e5), action: t5, payload: i5 });
          }), this._parser.setPrintHandler((e5, t5, i5) => this.print(e5, t5, i5)), this._parser.registerCsiHandler({ final: "@" }, (e5) => this.insertChars(e5)), this._parser.registerCsiHandler({ intermediates: " ", final: "@" }, (e5) => this.scrollLeft(e5)), this._parser.registerCsiHandler({ final: "A" }, (e5) => this.cursorUp(e5)), this._parser.registerCsiHandler({ intermediates: " ", final: "A" }, (e5) => this.scrollRight(e5)), this._parser.registerCsiHandler({ final: "B" }, (e5) => this.cursorDown(e5)), this._parser.registerCsiHandler({ final: "C" }, (e5) => this.cursorForward(e5)), this._parser.registerCsiHandler({ final: "D" }, (e5) => this.cursorBackward(e5)), this._parser.registerCsiHandler({ final: "E" }, (e5) => this.cursorNextLine(e5)), this._parser.registerCsiHandler({ final: "F" }, (e5) => this.cursorPrecedingLine(e5)), this._parser.registerCsiHandler({ final: "G" }, (e5) => this.cursorCharAbsolute(e5)), this._parser.registerCsiHandler({ final: "H" }, (e5) => this.cursorPosition(e5)), this._parser.registerCsiHandler({ final: "I" }, (e5) => this.cursorForwardTab(e5)), this._parser.registerCsiHandler({ final: "J" }, (e5) => this.eraseInDisplay(e5, false)), this._parser.registerCsiHandler({ prefix: "?", final: "J" }, (e5) => this.eraseInDisplay(e5, true)), this._parser.registerCsiHandler({ final: "K" }, (e5) => this.eraseInLine(e5, false)), this._parser.registerCsiHandler({ prefix: "?", final: "K" }, (e5) => this.eraseInLine(e5, true)), this._parser.registerCsiHandler({ final: "L" }, (e5) => this.insertLines(e5)), this._parser.registerCsiHandler({ final: "M" }, (e5) => this.deleteLines(e5)), this._parser.registerCsiHandler({ final: "P" }, (e5) => this.deleteChars(e5)), this._parser.registerCsiHandler({ final: "S" }, (e5) => this.scrollUp(e5)), this._parser.registerCsiHandler({ final: "T" }, (e5) => this.scrollDown(e5)), this._parser.registerCsiHandler({ final: "X" }, (e5) => this.eraseChars(e5)), this._parser.registerCsiHandler({ final: "Z" }, (e5) => this.cursorBackwardTab(e5)), this._parser.registerCsiHandler({ final: "`" }, (e5) => this.charPosAbsolute(e5)), this._parser.registerCsiHandler({ final: "a" }, (e5) => this.hPositionRelative(e5)), this._parser.registerCsiHandler({ final: "b" }, (e5) => this.repeatPrecedingCharacter(e5)), this._parser.registerCsiHandler({ final: "c" }, (e5) => this.sendDeviceAttributesPrimary(e5)), this._parser.registerCsiHandler({ prefix: ">", final: "c" }, (e5) => this.sendDeviceAttributesSecondary(e5)), this._parser.registerCsiHandler({ final: "d" }, (e5) => this.linePosAbsolute(e5)), this._parser.registerCsiHandler({ final: "e" }, (e5) => this.vPositionRelative(e5)), this._parser.registerCsiHandler({ final: "f" }, (e5) => this.hVPosition(e5)), this._parser.registerCsiHandler({ final: "g" }, (e5) => this.tabClear(e5)), this._parser.registerCsiHandler({ final: "h" }, (e5) => this.setMode(e5)), this._parser.registerCsiHandler({ prefix: "?", final: "h" }, (e5) => this.setModePrivate(e5)), this._parser.registerCsiHandler({ final: "l" }, (e5) => this.resetMode(e5)), this._parser.registerCsiHandler({ prefix: "?", final: "l" }, (e5) => this.resetModePrivate(e5)), this._parser.registerCsiHandler({ final: "m" }, (e5) => this.charAttributes(e5)), this._parser.registerCsiHandler({ final: "n" }, (e5) => this.deviceStatus(e5)), this._parser.registerCsiHandler({ prefix: "?", final: "n" }, (e5) => this.deviceStatusPrivate(e5)), this._parser.registerCsiHandler({ intermediates: "!", final: "p" }, (e5) => this.softReset(e5)), this._parser.registerCsiHandler({ intermediates: " ", final: "q" }, (e5) => this.setCursorStyle(e5)), this._parser.registerCsiHandler({ final: "r" }, (e5) => this.setScrollRegion(e5)), this._parser.registerCsiHandler({ final: "s" }, (e5) => this.saveCursor(e5)), this._parser.registerCsiHandler({ final: "t" }, (e5) => this.windowOptions(e5)), this._parser.registerCsiHandler({ final: "u" }, (e5) => this.restoreCursor(e5)), this._parser.registerCsiHandler({ intermediates: "'", final: "}" }, (e5) => this.insertColumns(e5)), this._parser.registerCsiHandler({ intermediates: "'", final: "~" }, (e5) => this.deleteColumns(e5)), this._parser.registerCsiHandler({ intermediates: '"', final: "q" }, (e5) => this.selectProtected(e5)), this._parser.registerCsiHandler({ intermediates: "$", final: "p" }, (e5) => this.requestMode(e5, true)), this._parser.registerCsiHandler({ prefix: "?", intermediates: "$", final: "p" }, (e5) => this.requestMode(e5, false)), this._parser.setExecuteHandler(n2.C0.BEL, () => this.bell()), this._parser.setExecuteHandler(n2.C0.LF, () => this.lineFeed()), this._parser.setExecuteHandler(n2.C0.VT, () => this.lineFeed()), this._parser.setExecuteHandler(n2.C0.FF, () => this.lineFeed()), this._parser.setExecuteHandler(n2.C0.CR, () => this.carriageReturn()), this._parser.setExecuteHandler(n2.C0.BS, () => this.backspace()), this._parser.setExecuteHandler(n2.C0.HT, () => this.tab()), this._parser.setExecuteHandler(n2.C0.SO, () => this.shiftOut()), this._parser.setExecuteHandler(n2.C0.SI, () => this.shiftIn()), this._parser.setExecuteHandler(n2.C1.IND, () => this.index()), this._parser.setExecuteHandler(n2.C1.NEL, () => this.nextLine()), this._parser.setExecuteHandler(n2.C1.HTS, () => this.tabSet()), this._parser.registerOscHandler(0, new g2.OscHandler((e5) => (this.setTitle(e5), this.setIconName(e5), true))), this._parser.registerOscHandler(1, new g2.OscHandler((e5) => this.setIconName(e5))), this._parser.registerOscHandler(2, new g2.OscHandler((e5) => this.setTitle(e5))), this._parser.registerOscHandler(4, new g2.OscHandler((e5) => this.setOrReportIndexedColor(e5))), this._parser.registerOscHandler(8, new g2.OscHandler((e5) => this.setHyperlink(e5))), this._parser.registerOscHandler(10, new g2.OscHandler((e5) => this.setOrReportFgColor(e5))), this._parser.registerOscHandler(11, new g2.OscHandler((e5) => this.setOrReportBgColor(e5))), this._parser.registerOscHandler(12, new g2.OscHandler((e5) => this.setOrReportCursorColor(e5))), this._parser.registerOscHandler(104, new g2.OscHandler((e5) => this.restoreIndexedColor(e5))), this._parser.registerOscHandler(110, new g2.OscHandler((e5) => this.restoreFgColor(e5))), this._parser.registerOscHandler(111, new g2.OscHandler((e5) => this.restoreBgColor(e5))), this._parser.registerOscHandler(112, new g2.OscHandler((e5) => this.restoreCursorColor(e5))), this._parser.registerEscHandler({ final: "7" }, () => this.saveCursor()), this._parser.registerEscHandler({ final: "8" }, () => this.restoreCursor()), this._parser.registerEscHandler({ final: "D" }, () => this.index()), this._parser.registerEscHandler({ final: "E" }, () => this.nextLine()), this._parser.registerEscHandler({ final: "H" }, () => this.tabSet()), this._parser.registerEscHandler({ final: "M" }, () => this.reverseIndex()), this._parser.registerEscHandler({ final: "=" }, () => this.keypadApplicationMode()), this._parser.registerEscHandler({ final: ">" }, () => this.keypadNumericMode()), this._parser.registerEscHandler({ final: "c" }, () => this.fullReset()), this._parser.registerEscHandler({ final: "n" }, () => this.setgLevel(2)), this._parser.registerEscHandler({ final: "o" }, () => this.setgLevel(3)), this._parser.registerEscHandler({ final: "|" }, () => this.setgLevel(3)), this._parser.registerEscHandler({ final: "}" }, () => this.setgLevel(2)), this._parser.registerEscHandler({ final: "~" }, () => this.setgLevel(1)), this._parser.registerEscHandler({ intermediates: "%", final: "@" }, () => this.selectDefaultCharset()), this._parser.registerEscHandler({ intermediates: "%", final: "G" }, () => this.selectDefaultCharset());
          for (const e5 in o2.CHARSETS) this._parser.registerEscHandler({ intermediates: "(", final: e5 }, () => this.selectCharset("(" + e5)), this._parser.registerEscHandler({ intermediates: ")", final: e5 }, () => this.selectCharset(")" + e5)), this._parser.registerEscHandler({ intermediates: "*", final: e5 }, () => this.selectCharset("*" + e5)), this._parser.registerEscHandler({ intermediates: "+", final: e5 }, () => this.selectCharset("+" + e5)), this._parser.registerEscHandler({ intermediates: "-", final: e5 }, () => this.selectCharset("-" + e5)), this._parser.registerEscHandler({ intermediates: ".", final: e5 }, () => this.selectCharset("." + e5)), this._parser.registerEscHandler({ intermediates: "/", final: e5 }, () => this.selectCharset("/" + e5));
          this._parser.registerEscHandler({ intermediates: "#", final: "8" }, () => this.screenAlignmentPattern()), this._parser.setErrorHandler((e5) => (this._logService.error("Parsing error: ", e5), e5)), this._parser.registerDcsHandler({ intermediates: "$", final: "q" }, new m2.DcsHandler((e5, t5) => this.requestStatusString(e5, t5)));
        }
        _preserveStack(e4, t4, i4, s4) {
          this._parseStack.paused = true, this._parseStack.cursorStartX = e4, this._parseStack.cursorStartY = t4, this._parseStack.decodedLength = i4, this._parseStack.position = s4;
        }
        _logSlowResolvingAsync(e4) {
          this._logService.logLevel <= v2.LogLevelEnum.WARN && Promise.race([e4, new Promise((e5, t4) => setTimeout(() => t4("#SLOW_TIMEOUT"), 5e3))]).catch((e5) => {
            if ("#SLOW_TIMEOUT" !== e5) throw e5;
            console.warn("async parser handler taking longer than 5000 ms");
          });
        }
        _getCurrentLinkId() {
          return this._curAttrData.extended.urlId;
        }
        parse(e4, t4) {
          let i4, s4 = this._activeBuffer.x, r3 = this._activeBuffer.y, n3 = 0;
          const o3 = this._parseStack.paused;
          if (o3) {
            if (i4 = this._parser.parse(this._parseBuffer, this._parseStack.decodedLength, t4)) return this._logSlowResolvingAsync(i4), i4;
            s4 = this._parseStack.cursorStartX, r3 = this._parseStack.cursorStartY, this._parseStack.paused = false, e4.length > b2 && (n3 = this._parseStack.position + b2);
          }
          if (this._logService.logLevel <= v2.LogLevelEnum.DEBUG && this._logService.debug("parsing data" + ("string" == typeof e4 ? ` "${e4}"` : ` "${Array.prototype.map.call(e4, (e5) => String.fromCharCode(e5)).join("")}"`), "string" == typeof e4 ? e4.split("").map((e5) => e5.charCodeAt(0)) : e4), this._parseBuffer.length < e4.length && this._parseBuffer.length < b2 && (this._parseBuffer = new Uint32Array(Math.min(e4.length, b2))), o3 || this._dirtyRowTracker.clearRange(), e4.length > b2) for (let t5 = n3; t5 < e4.length; t5 += b2) {
            const n4 = t5 + b2 < e4.length ? t5 + b2 : e4.length, o4 = "string" == typeof e4 ? this._stringDecoder.decode(e4.substring(t5, n4), this._parseBuffer) : this._utf8Decoder.decode(e4.subarray(t5, n4), this._parseBuffer);
            if (i4 = this._parser.parse(this._parseBuffer, o4)) return this._preserveStack(s4, r3, o4, t5), this._logSlowResolvingAsync(i4), i4;
          }
          else if (!o3) {
            const t5 = "string" == typeof e4 ? this._stringDecoder.decode(e4, this._parseBuffer) : this._utf8Decoder.decode(e4, this._parseBuffer);
            if (i4 = this._parser.parse(this._parseBuffer, t5)) return this._preserveStack(s4, r3, t5, 0), this._logSlowResolvingAsync(i4), i4;
          }
          this._activeBuffer.x === s4 && this._activeBuffer.y === r3 || this._onCursorMove.fire();
          const a3 = this._dirtyRowTracker.end + (this._bufferService.buffer.ybase - this._bufferService.buffer.ydisp), h3 = this._dirtyRowTracker.start + (this._bufferService.buffer.ybase - this._bufferService.buffer.ydisp);
          h3 < this._bufferService.rows && this._onRequestRefreshRows.fire(Math.min(h3, this._bufferService.rows - 1), Math.min(a3, this._bufferService.rows - 1));
        }
        print(e4, t4, i4) {
          let s4, r3;
          const n3 = this._charsetService.charset, o3 = this._optionsService.rawOptions.screenReaderMode, a3 = this._bufferService.cols, h3 = this._coreService.decPrivateModes.wraparound, d3 = this._coreService.modes.insertMode, u3 = this._curAttrData;
          let f3 = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y);
          this._dirtyRowTracker.markDirty(this._activeBuffer.y), this._activeBuffer.x && i4 - t4 > 0 && 2 === f3.getWidth(this._activeBuffer.x - 1) && f3.setCellFromCodepoint(this._activeBuffer.x - 1, 0, 1, u3);
          let v3 = this._parser.precedingJoinState;
          for (let g3 = t4; g3 < i4; ++g3) {
            if (s4 = e4[g3], s4 < 127 && n3) {
              const e5 = n3[String.fromCharCode(s4)];
              e5 && (s4 = e5.charCodeAt(0));
            }
            const t5 = this._unicodeService.charProperties(s4, v3);
            r3 = p2.UnicodeService.extractWidth(t5);
            const i5 = p2.UnicodeService.extractShouldJoin(t5), m3 = i5 ? p2.UnicodeService.extractWidth(v3) : 0;
            if (v3 = t5, o3 && this._onA11yChar.fire((0, c2.stringFromCodePoint)(s4)), this._getCurrentLinkId() && this._oscLinkService.addLineToLink(this._getCurrentLinkId(), this._activeBuffer.ybase + this._activeBuffer.y), this._activeBuffer.x + r3 - m3 > a3) {
              if (h3) {
                const e5 = f3;
                let t6 = this._activeBuffer.x - m3;
                for (this._activeBuffer.x = m3, this._activeBuffer.y++, this._activeBuffer.y === this._activeBuffer.scrollBottom + 1 ? (this._activeBuffer.y--, this._bufferService.scroll(this._eraseAttrData(), true)) : (this._activeBuffer.y >= this._bufferService.rows && (this._activeBuffer.y = this._bufferService.rows - 1), this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y).isWrapped = true), f3 = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y), m3 > 0 && f3 instanceof l2.BufferLine && f3.copyCellsFrom(e5, t6, 0, m3, false); t6 < a3; ) e5.setCellFromCodepoint(t6++, 0, 1, u3);
              } else if (this._activeBuffer.x = a3 - 1, 2 === r3) continue;
            }
            if (i5 && this._activeBuffer.x) {
              const e5 = f3.getWidth(this._activeBuffer.x - 1) ? 1 : 2;
              f3.addCodepointToCell(this._activeBuffer.x - e5, s4, r3);
              for (let e6 = r3 - m3; --e6 >= 0; ) f3.setCellFromCodepoint(this._activeBuffer.x++, 0, 0, u3);
            } else if (d3 && (f3.insertCells(this._activeBuffer.x, r3 - m3, this._activeBuffer.getNullCell(u3)), 2 === f3.getWidth(a3 - 1) && f3.setCellFromCodepoint(a3 - 1, _2.NULL_CELL_CODE, _2.NULL_CELL_WIDTH, u3)), f3.setCellFromCodepoint(this._activeBuffer.x++, s4, r3, u3), r3 > 0) for (; --r3; ) f3.setCellFromCodepoint(this._activeBuffer.x++, 0, 0, u3);
          }
          this._parser.precedingJoinState = v3, this._activeBuffer.x < a3 && i4 - t4 > 0 && 0 === f3.getWidth(this._activeBuffer.x) && !f3.hasContent(this._activeBuffer.x) && f3.setCellFromCodepoint(this._activeBuffer.x, 0, 1, u3), this._dirtyRowTracker.markDirty(this._activeBuffer.y);
        }
        registerCsiHandler(e4, t4) {
          return "t" !== e4.final || e4.prefix || e4.intermediates ? this._parser.registerCsiHandler(e4, t4) : this._parser.registerCsiHandler(e4, (e5) => !w2(e5.params[0], this._optionsService.rawOptions.windowOptions) || t4(e5));
        }
        registerDcsHandler(e4, t4) {
          return this._parser.registerDcsHandler(e4, new m2.DcsHandler(t4));
        }
        registerEscHandler(e4, t4) {
          return this._parser.registerEscHandler(e4, t4);
        }
        registerOscHandler(e4, t4) {
          return this._parser.registerOscHandler(e4, new g2.OscHandler(t4));
        }
        bell() {
          return this._onRequestBell.fire(), true;
        }
        lineFeed() {
          return this._dirtyRowTracker.markDirty(this._activeBuffer.y), this._optionsService.rawOptions.convertEol && (this._activeBuffer.x = 0), this._activeBuffer.y++, this._activeBuffer.y === this._activeBuffer.scrollBottom + 1 ? (this._activeBuffer.y--, this._bufferService.scroll(this._eraseAttrData())) : this._activeBuffer.y >= this._bufferService.rows ? this._activeBuffer.y = this._bufferService.rows - 1 : this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y).isWrapped = false, this._activeBuffer.x >= this._bufferService.cols && this._activeBuffer.x--, this._dirtyRowTracker.markDirty(this._activeBuffer.y), this._onLineFeed.fire(), true;
        }
        carriageReturn() {
          return this._activeBuffer.x = 0, true;
        }
        backspace() {
          if (!this._coreService.decPrivateModes.reverseWraparound) return this._restrictCursor(), this._activeBuffer.x > 0 && this._activeBuffer.x--, true;
          if (this._restrictCursor(this._bufferService.cols), this._activeBuffer.x > 0) this._activeBuffer.x--;
          else if (0 === this._activeBuffer.x && this._activeBuffer.y > this._activeBuffer.scrollTop && this._activeBuffer.y <= this._activeBuffer.scrollBottom && this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y)?.isWrapped) {
            this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y).isWrapped = false, this._activeBuffer.y--, this._activeBuffer.x = this._bufferService.cols - 1;
            const e4 = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y);
            e4.hasWidth(this._activeBuffer.x) && !e4.hasContent(this._activeBuffer.x) && this._activeBuffer.x--;
          }
          return this._restrictCursor(), true;
        }
        tab() {
          if (this._activeBuffer.x >= this._bufferService.cols) return true;
          const e4 = this._activeBuffer.x;
          return this._activeBuffer.x = this._activeBuffer.nextStop(), this._optionsService.rawOptions.screenReaderMode && this._onA11yTab.fire(this._activeBuffer.x - e4), true;
        }
        shiftOut() {
          return this._charsetService.setgLevel(1), true;
        }
        shiftIn() {
          return this._charsetService.setgLevel(0), true;
        }
        _restrictCursor(e4 = this._bufferService.cols - 1) {
          this._activeBuffer.x = Math.min(e4, Math.max(0, this._activeBuffer.x)), this._activeBuffer.y = this._coreService.decPrivateModes.origin ? Math.min(this._activeBuffer.scrollBottom, Math.max(this._activeBuffer.scrollTop, this._activeBuffer.y)) : Math.min(this._bufferService.rows - 1, Math.max(0, this._activeBuffer.y)), this._dirtyRowTracker.markDirty(this._activeBuffer.y);
        }
        _setCursor(e4, t4) {
          this._dirtyRowTracker.markDirty(this._activeBuffer.y), this._coreService.decPrivateModes.origin ? (this._activeBuffer.x = e4, this._activeBuffer.y = this._activeBuffer.scrollTop + t4) : (this._activeBuffer.x = e4, this._activeBuffer.y = t4), this._restrictCursor(), this._dirtyRowTracker.markDirty(this._activeBuffer.y);
        }
        _moveCursor(e4, t4) {
          this._restrictCursor(), this._setCursor(this._activeBuffer.x + e4, this._activeBuffer.y + t4);
        }
        cursorUp(e4) {
          const t4 = this._activeBuffer.y - this._activeBuffer.scrollTop;
          return t4 >= 0 ? this._moveCursor(0, -Math.min(t4, e4.params[0] || 1)) : this._moveCursor(0, -(e4.params[0] || 1)), true;
        }
        cursorDown(e4) {
          const t4 = this._activeBuffer.scrollBottom - this._activeBuffer.y;
          return t4 >= 0 ? this._moveCursor(0, Math.min(t4, e4.params[0] || 1)) : this._moveCursor(0, e4.params[0] || 1), true;
        }
        cursorForward(e4) {
          return this._moveCursor(e4.params[0] || 1, 0), true;
        }
        cursorBackward(e4) {
          return this._moveCursor(-(e4.params[0] || 1), 0), true;
        }
        cursorNextLine(e4) {
          return this.cursorDown(e4), this._activeBuffer.x = 0, true;
        }
        cursorPrecedingLine(e4) {
          return this.cursorUp(e4), this._activeBuffer.x = 0, true;
        }
        cursorCharAbsolute(e4) {
          return this._setCursor((e4.params[0] || 1) - 1, this._activeBuffer.y), true;
        }
        cursorPosition(e4) {
          return this._setCursor(e4.length >= 2 ? (e4.params[1] || 1) - 1 : 0, (e4.params[0] || 1) - 1), true;
        }
        charPosAbsolute(e4) {
          return this._setCursor((e4.params[0] || 1) - 1, this._activeBuffer.y), true;
        }
        hPositionRelative(e4) {
          return this._moveCursor(e4.params[0] || 1, 0), true;
        }
        linePosAbsolute(e4) {
          return this._setCursor(this._activeBuffer.x, (e4.params[0] || 1) - 1), true;
        }
        vPositionRelative(e4) {
          return this._moveCursor(0, e4.params[0] || 1), true;
        }
        hVPosition(e4) {
          return this.cursorPosition(e4), true;
        }
        tabClear(e4) {
          const t4 = e4.params[0];
          return 0 === t4 ? delete this._activeBuffer.tabs[this._activeBuffer.x] : 3 === t4 && (this._activeBuffer.tabs = {}), true;
        }
        cursorForwardTab(e4) {
          if (this._activeBuffer.x >= this._bufferService.cols) return true;
          let t4 = e4.params[0] || 1;
          for (; t4--; ) this._activeBuffer.x = this._activeBuffer.nextStop();
          return true;
        }
        cursorBackwardTab(e4) {
          if (this._activeBuffer.x >= this._bufferService.cols) return true;
          let t4 = e4.params[0] || 1;
          for (; t4--; ) this._activeBuffer.x = this._activeBuffer.prevStop();
          return true;
        }
        selectProtected(e4) {
          const t4 = e4.params[0];
          return 1 === t4 && (this._curAttrData.bg |= 536870912), 2 !== t4 && 0 !== t4 || (this._curAttrData.bg &= -536870913), true;
        }
        _eraseInBufferLine(e4, t4, i4, s4 = false, r3 = false) {
          const n3 = this._activeBuffer.lines.get(this._activeBuffer.ybase + e4);
          n3.replaceCells(t4, i4, this._activeBuffer.getNullCell(this._eraseAttrData()), r3), s4 && (n3.isWrapped = false);
        }
        _resetBufferLine(e4, t4 = false) {
          const i4 = this._activeBuffer.lines.get(this._activeBuffer.ybase + e4);
          i4 && (i4.fill(this._activeBuffer.getNullCell(this._eraseAttrData()), t4), this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase + e4), i4.isWrapped = false);
        }
        eraseInDisplay(e4, t4 = false) {
          let i4;
          switch (this._restrictCursor(this._bufferService.cols), e4.params[0]) {
            case 0:
              for (i4 = this._activeBuffer.y, this._dirtyRowTracker.markDirty(i4), this._eraseInBufferLine(i4++, this._activeBuffer.x, this._bufferService.cols, 0 === this._activeBuffer.x, t4); i4 < this._bufferService.rows; i4++) this._resetBufferLine(i4, t4);
              this._dirtyRowTracker.markDirty(i4);
              break;
            case 1:
              for (i4 = this._activeBuffer.y, this._dirtyRowTracker.markDirty(i4), this._eraseInBufferLine(i4, 0, this._activeBuffer.x + 1, true, t4), this._activeBuffer.x + 1 >= this._bufferService.cols && (this._activeBuffer.lines.get(i4 + 1).isWrapped = false); i4--; ) this._resetBufferLine(i4, t4);
              this._dirtyRowTracker.markDirty(0);
              break;
            case 2:
              for (i4 = this._bufferService.rows, this._dirtyRowTracker.markDirty(i4 - 1); i4--; ) this._resetBufferLine(i4, t4);
              this._dirtyRowTracker.markDirty(0);
              break;
            case 3:
              const e5 = this._activeBuffer.lines.length - this._bufferService.rows;
              e5 > 0 && (this._activeBuffer.lines.trimStart(e5), this._activeBuffer.ybase = Math.max(this._activeBuffer.ybase - e5, 0), this._activeBuffer.ydisp = Math.max(this._activeBuffer.ydisp - e5, 0), this._onScroll.fire(0));
          }
          return true;
        }
        eraseInLine(e4, t4 = false) {
          switch (this._restrictCursor(this._bufferService.cols), e4.params[0]) {
            case 0:
              this._eraseInBufferLine(this._activeBuffer.y, this._activeBuffer.x, this._bufferService.cols, 0 === this._activeBuffer.x, t4);
              break;
            case 1:
              this._eraseInBufferLine(this._activeBuffer.y, 0, this._activeBuffer.x + 1, false, t4);
              break;
            case 2:
              this._eraseInBufferLine(this._activeBuffer.y, 0, this._bufferService.cols, true, t4);
          }
          return this._dirtyRowTracker.markDirty(this._activeBuffer.y), true;
        }
        insertLines(e4) {
          this._restrictCursor();
          let t4 = e4.params[0] || 1;
          if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) return true;
          const i4 = this._activeBuffer.ybase + this._activeBuffer.y, s4 = this._bufferService.rows - 1 - this._activeBuffer.scrollBottom, r3 = this._bufferService.rows - 1 + this._activeBuffer.ybase - s4 + 1;
          for (; t4--; ) this._activeBuffer.lines.splice(r3 - 1, 1), this._activeBuffer.lines.splice(i4, 0, this._activeBuffer.getBlankLine(this._eraseAttrData()));
          return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y, this._activeBuffer.scrollBottom), this._activeBuffer.x = 0, true;
        }
        deleteLines(e4) {
          this._restrictCursor();
          let t4 = e4.params[0] || 1;
          if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) return true;
          const i4 = this._activeBuffer.ybase + this._activeBuffer.y;
          let s4;
          for (s4 = this._bufferService.rows - 1 - this._activeBuffer.scrollBottom, s4 = this._bufferService.rows - 1 + this._activeBuffer.ybase - s4; t4--; ) this._activeBuffer.lines.splice(i4, 1), this._activeBuffer.lines.splice(s4, 0, this._activeBuffer.getBlankLine(this._eraseAttrData()));
          return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y, this._activeBuffer.scrollBottom), this._activeBuffer.x = 0, true;
        }
        insertChars(e4) {
          this._restrictCursor();
          const t4 = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y);
          return t4 && (t4.insertCells(this._activeBuffer.x, e4.params[0] || 1, this._activeBuffer.getNullCell(this._eraseAttrData())), this._dirtyRowTracker.markDirty(this._activeBuffer.y)), true;
        }
        deleteChars(e4) {
          this._restrictCursor();
          const t4 = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y);
          return t4 && (t4.deleteCells(this._activeBuffer.x, e4.params[0] || 1, this._activeBuffer.getNullCell(this._eraseAttrData())), this._dirtyRowTracker.markDirty(this._activeBuffer.y)), true;
        }
        scrollUp(e4) {
          let t4 = e4.params[0] || 1;
          for (; t4--; ) this._activeBuffer.lines.splice(this._activeBuffer.ybase + this._activeBuffer.scrollTop, 1), this._activeBuffer.lines.splice(this._activeBuffer.ybase + this._activeBuffer.scrollBottom, 0, this._activeBuffer.getBlankLine(this._eraseAttrData()));
          return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom), true;
        }
        scrollDown(e4) {
          let t4 = e4.params[0] || 1;
          for (; t4--; ) this._activeBuffer.lines.splice(this._activeBuffer.ybase + this._activeBuffer.scrollBottom, 1), this._activeBuffer.lines.splice(this._activeBuffer.ybase + this._activeBuffer.scrollTop, 0, this._activeBuffer.getBlankLine(l2.DEFAULT_ATTR_DATA));
          return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom), true;
        }
        scrollLeft(e4) {
          if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) return true;
          const t4 = e4.params[0] || 1;
          for (let e5 = this._activeBuffer.scrollTop; e5 <= this._activeBuffer.scrollBottom; ++e5) {
            const i4 = this._activeBuffer.lines.get(this._activeBuffer.ybase + e5);
            i4.deleteCells(0, t4, this._activeBuffer.getNullCell(this._eraseAttrData())), i4.isWrapped = false;
          }
          return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom), true;
        }
        scrollRight(e4) {
          if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) return true;
          const t4 = e4.params[0] || 1;
          for (let e5 = this._activeBuffer.scrollTop; e5 <= this._activeBuffer.scrollBottom; ++e5) {
            const i4 = this._activeBuffer.lines.get(this._activeBuffer.ybase + e5);
            i4.insertCells(0, t4, this._activeBuffer.getNullCell(this._eraseAttrData())), i4.isWrapped = false;
          }
          return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom), true;
        }
        insertColumns(e4) {
          if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) return true;
          const t4 = e4.params[0] || 1;
          for (let e5 = this._activeBuffer.scrollTop; e5 <= this._activeBuffer.scrollBottom; ++e5) {
            const i4 = this._activeBuffer.lines.get(this._activeBuffer.ybase + e5);
            i4.insertCells(this._activeBuffer.x, t4, this._activeBuffer.getNullCell(this._eraseAttrData())), i4.isWrapped = false;
          }
          return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom), true;
        }
        deleteColumns(e4) {
          if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) return true;
          const t4 = e4.params[0] || 1;
          for (let e5 = this._activeBuffer.scrollTop; e5 <= this._activeBuffer.scrollBottom; ++e5) {
            const i4 = this._activeBuffer.lines.get(this._activeBuffer.ybase + e5);
            i4.deleteCells(this._activeBuffer.x, t4, this._activeBuffer.getNullCell(this._eraseAttrData())), i4.isWrapped = false;
          }
          return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom), true;
        }
        eraseChars(e4) {
          this._restrictCursor();
          const t4 = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y);
          return t4 && (t4.replaceCells(this._activeBuffer.x, this._activeBuffer.x + (e4.params[0] || 1), this._activeBuffer.getNullCell(this._eraseAttrData())), this._dirtyRowTracker.markDirty(this._activeBuffer.y)), true;
        }
        repeatPrecedingCharacter(e4) {
          const t4 = this._parser.precedingJoinState;
          if (!t4) return true;
          const i4 = e4.params[0] || 1, s4 = p2.UnicodeService.extractWidth(t4), r3 = this._activeBuffer.x - s4, n3 = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y).getString(r3), o3 = new Uint32Array(n3.length * i4);
          let a3 = 0;
          for (let e5 = 0; e5 < n3.length; ) {
            const t5 = n3.codePointAt(e5) || 0;
            o3[a3++] = t5, e5 += t5 > 65535 ? 2 : 1;
          }
          let h3 = a3;
          for (let e5 = 1; e5 < i4; ++e5) o3.copyWithin(h3, 0, a3), h3 += a3;
          return this.print(o3, 0, h3), true;
        }
        sendDeviceAttributesPrimary(e4) {
          return e4.params[0] > 0 || (this._is("xterm") || this._is("rxvt-unicode") || this._is("screen") ? this._coreService.triggerDataEvent(n2.C0.ESC + "[?1;2c") : this._is("linux") && this._coreService.triggerDataEvent(n2.C0.ESC + "[?6c")), true;
        }
        sendDeviceAttributesSecondary(e4) {
          return e4.params[0] > 0 || (this._is("xterm") ? this._coreService.triggerDataEvent(n2.C0.ESC + "[>0;276;0c") : this._is("rxvt-unicode") ? this._coreService.triggerDataEvent(n2.C0.ESC + "[>85;95;0c") : this._is("linux") ? this._coreService.triggerDataEvent(e4.params[0] + "c") : this._is("screen") && this._coreService.triggerDataEvent(n2.C0.ESC + "[>83;40003;0c")), true;
        }
        _is(e4) {
          return 0 === (this._optionsService.rawOptions.termName + "").indexOf(e4);
        }
        setMode(e4) {
          for (let t4 = 0; t4 < e4.length; t4++) switch (e4.params[t4]) {
            case 4:
              this._coreService.modes.insertMode = true;
              break;
            case 20:
              this._optionsService.options.convertEol = true;
          }
          return true;
        }
        setModePrivate(e4) {
          for (let t4 = 0; t4 < e4.length; t4++) switch (e4.params[t4]) {
            case 1:
              this._coreService.decPrivateModes.applicationCursorKeys = true;
              break;
            case 2:
              this._charsetService.setgCharset(0, o2.DEFAULT_CHARSET), this._charsetService.setgCharset(1, o2.DEFAULT_CHARSET), this._charsetService.setgCharset(2, o2.DEFAULT_CHARSET), this._charsetService.setgCharset(3, o2.DEFAULT_CHARSET);
              break;
            case 3:
              this._optionsService.rawOptions.windowOptions.setWinLines && (this._bufferService.resize(132, this._bufferService.rows), this._onRequestReset.fire());
              break;
            case 6:
              this._coreService.decPrivateModes.origin = true, this._setCursor(0, 0);
              break;
            case 7:
              this._coreService.decPrivateModes.wraparound = true;
              break;
            case 12:
              this._optionsService.options.cursorBlink = true;
              break;
            case 45:
              this._coreService.decPrivateModes.reverseWraparound = true;
              break;
            case 66:
              this._logService.debug("Serial port requested application keypad."), this._coreService.decPrivateModes.applicationKeypad = true, this._onRequestSyncScrollBar.fire();
              break;
            case 9:
              this._coreMouseService.activeProtocol = "X10";
              break;
            case 1e3:
              this._coreMouseService.activeProtocol = "VT200";
              break;
            case 1002:
              this._coreMouseService.activeProtocol = "DRAG";
              break;
            case 1003:
              this._coreMouseService.activeProtocol = "ANY";
              break;
            case 1004:
              this._coreService.decPrivateModes.sendFocus = true, this._onRequestSendFocus.fire();
              break;
            case 1005:
              this._logService.debug("DECSET 1005 not supported (see #2507)");
              break;
            case 1006:
              this._coreMouseService.activeEncoding = "SGR";
              break;
            case 1015:
              this._logService.debug("DECSET 1015 not supported (see #2507)");
              break;
            case 1016:
              this._coreMouseService.activeEncoding = "SGR_PIXELS";
              break;
            case 25:
              this._coreService.isCursorHidden = false;
              break;
            case 1048:
              this.saveCursor();
              break;
            case 1049:
              this.saveCursor();
            case 47:
            case 1047:
              this._bufferService.buffers.activateAltBuffer(this._eraseAttrData()), this._coreService.isCursorInitialized = true, this._onRequestRefreshRows.fire(0, this._bufferService.rows - 1), this._onRequestSyncScrollBar.fire();
              break;
            case 2004:
              this._coreService.decPrivateModes.bracketedPasteMode = true;
          }
          return true;
        }
        resetMode(e4) {
          for (let t4 = 0; t4 < e4.length; t4++) switch (e4.params[t4]) {
            case 4:
              this._coreService.modes.insertMode = false;
              break;
            case 20:
              this._optionsService.options.convertEol = false;
          }
          return true;
        }
        resetModePrivate(e4) {
          for (let t4 = 0; t4 < e4.length; t4++) switch (e4.params[t4]) {
            case 1:
              this._coreService.decPrivateModes.applicationCursorKeys = false;
              break;
            case 3:
              this._optionsService.rawOptions.windowOptions.setWinLines && (this._bufferService.resize(80, this._bufferService.rows), this._onRequestReset.fire());
              break;
            case 6:
              this._coreService.decPrivateModes.origin = false, this._setCursor(0, 0);
              break;
            case 7:
              this._coreService.decPrivateModes.wraparound = false;
              break;
            case 12:
              this._optionsService.options.cursorBlink = false;
              break;
            case 45:
              this._coreService.decPrivateModes.reverseWraparound = false;
              break;
            case 66:
              this._logService.debug("Switching back to normal keypad."), this._coreService.decPrivateModes.applicationKeypad = false, this._onRequestSyncScrollBar.fire();
              break;
            case 9:
            case 1e3:
            case 1002:
            case 1003:
              this._coreMouseService.activeProtocol = "NONE";
              break;
            case 1004:
              this._coreService.decPrivateModes.sendFocus = false;
              break;
            case 1005:
              this._logService.debug("DECRST 1005 not supported (see #2507)");
              break;
            case 1006:
            case 1016:
              this._coreMouseService.activeEncoding = "DEFAULT";
              break;
            case 1015:
              this._logService.debug("DECRST 1015 not supported (see #2507)");
              break;
            case 25:
              this._coreService.isCursorHidden = true;
              break;
            case 1048:
              this.restoreCursor();
              break;
            case 1049:
            case 47:
            case 1047:
              this._bufferService.buffers.activateNormalBuffer(), 1049 === e4.params[t4] && this.restoreCursor(), this._coreService.isCursorInitialized = true, this._onRequestRefreshRows.fire(0, this._bufferService.rows - 1), this._onRequestSyncScrollBar.fire();
              break;
            case 2004:
              this._coreService.decPrivateModes.bracketedPasteMode = false;
          }
          return true;
        }
        requestMode(e4, t4) {
          const i4 = this._coreService.decPrivateModes, { activeProtocol: s4, activeEncoding: r3 } = this._coreMouseService, o3 = this._coreService, { buffers: a3, cols: h3 } = this._bufferService, { active: c3, alt: l3 } = a3, d3 = this._optionsService.rawOptions, _3 = /* @__PURE__ */ __name((e5) => e5 ? 1 : 2, "_"), u3 = e4.params[0];
          return f3 = u3, v3 = t4 ? 2 === u3 ? 4 : 4 === u3 ? _3(o3.modes.insertMode) : 12 === u3 ? 3 : 20 === u3 ? _3(d3.convertEol) : 0 : 1 === u3 ? _3(i4.applicationCursorKeys) : 3 === u3 ? d3.windowOptions.setWinLines ? 80 === h3 ? 2 : 132 === h3 ? 1 : 0 : 0 : 6 === u3 ? _3(i4.origin) : 7 === u3 ? _3(i4.wraparound) : 8 === u3 ? 3 : 9 === u3 ? _3("X10" === s4) : 12 === u3 ? _3(d3.cursorBlink) : 25 === u3 ? _3(!o3.isCursorHidden) : 45 === u3 ? _3(i4.reverseWraparound) : 66 === u3 ? _3(i4.applicationKeypad) : 67 === u3 ? 4 : 1e3 === u3 ? _3("VT200" === s4) : 1002 === u3 ? _3("DRAG" === s4) : 1003 === u3 ? _3("ANY" === s4) : 1004 === u3 ? _3(i4.sendFocus) : 1005 === u3 ? 4 : 1006 === u3 ? _3("SGR" === r3) : 1015 === u3 ? 4 : 1016 === u3 ? _3("SGR_PIXELS" === r3) : 1048 === u3 ? 1 : 47 === u3 || 1047 === u3 || 1049 === u3 ? _3(c3 === l3) : 2004 === u3 ? _3(i4.bracketedPasteMode) : 0, o3.triggerDataEvent(`${n2.C0.ESC}[${t4 ? "" : "?"}${f3};${v3}$y`), true;
          var f3, v3;
        }
        _updateAttrColor(e4, t4, i4, s4, r3) {
          return 2 === t4 ? (e4 |= 50331648, e4 &= -16777216, e4 |= f2.AttributeData.fromColorRGB([i4, s4, r3])) : 5 === t4 && (e4 &= -50331904, e4 |= 33554432 | 255 & i4), e4;
        }
        _extractColor(e4, t4, i4) {
          const s4 = [0, 0, -1, 0, 0, 0];
          let r3 = 0, n3 = 0;
          do {
            if (s4[n3 + r3] = e4.params[t4 + n3], e4.hasSubParams(t4 + n3)) {
              const i5 = e4.getSubParams(t4 + n3);
              let o3 = 0;
              do {
                5 === s4[1] && (r3 = 1), s4[n3 + o3 + 1 + r3] = i5[o3];
              } while (++o3 < i5.length && o3 + n3 + 1 + r3 < s4.length);
              break;
            }
            if (5 === s4[1] && n3 + r3 >= 2 || 2 === s4[1] && n3 + r3 >= 5) break;
            s4[1] && (r3 = 1);
          } while (++n3 + t4 < e4.length && n3 + r3 < s4.length);
          for (let e5 = 2; e5 < s4.length; ++e5) -1 === s4[e5] && (s4[e5] = 0);
          switch (s4[0]) {
            case 38:
              i4.fg = this._updateAttrColor(i4.fg, s4[1], s4[3], s4[4], s4[5]);
              break;
            case 48:
              i4.bg = this._updateAttrColor(i4.bg, s4[1], s4[3], s4[4], s4[5]);
              break;
            case 58:
              i4.extended = i4.extended.clone(), i4.extended.underlineColor = this._updateAttrColor(i4.extended.underlineColor, s4[1], s4[3], s4[4], s4[5]);
          }
          return n3;
        }
        _processUnderline(e4, t4) {
          t4.extended = t4.extended.clone(), (!~e4 || e4 > 5) && (e4 = 1), t4.extended.underlineStyle = e4, t4.fg |= 268435456, 0 === e4 && (t4.fg &= -268435457), t4.updateExtended();
        }
        _processSGR0(e4) {
          e4.fg = l2.DEFAULT_ATTR_DATA.fg, e4.bg = l2.DEFAULT_ATTR_DATA.bg, e4.extended = e4.extended.clone(), e4.extended.underlineStyle = 0, e4.extended.underlineColor &= -67108864, e4.updateExtended();
        }
        charAttributes(e4) {
          if (1 === e4.length && 0 === e4.params[0]) return this._processSGR0(this._curAttrData), true;
          const t4 = e4.length;
          let i4;
          const s4 = this._curAttrData;
          for (let r3 = 0; r3 < t4; r3++) i4 = e4.params[r3], i4 >= 30 && i4 <= 37 ? (s4.fg &= -50331904, s4.fg |= 16777216 | i4 - 30) : i4 >= 40 && i4 <= 47 ? (s4.bg &= -50331904, s4.bg |= 16777216 | i4 - 40) : i4 >= 90 && i4 <= 97 ? (s4.fg &= -50331904, s4.fg |= 16777224 | i4 - 90) : i4 >= 100 && i4 <= 107 ? (s4.bg &= -50331904, s4.bg |= 16777224 | i4 - 100) : 0 === i4 ? this._processSGR0(s4) : 1 === i4 ? s4.fg |= 134217728 : 3 === i4 ? s4.bg |= 67108864 : 4 === i4 ? (s4.fg |= 268435456, this._processUnderline(e4.hasSubParams(r3) ? e4.getSubParams(r3)[0] : 1, s4)) : 5 === i4 ? s4.fg |= 536870912 : 7 === i4 ? s4.fg |= 67108864 : 8 === i4 ? s4.fg |= 1073741824 : 9 === i4 ? s4.fg |= 2147483648 : 2 === i4 ? s4.bg |= 134217728 : 21 === i4 ? this._processUnderline(2, s4) : 22 === i4 ? (s4.fg &= -134217729, s4.bg &= -134217729) : 23 === i4 ? s4.bg &= -67108865 : 24 === i4 ? (s4.fg &= -268435457, this._processUnderline(0, s4)) : 25 === i4 ? s4.fg &= -536870913 : 27 === i4 ? s4.fg &= -67108865 : 28 === i4 ? s4.fg &= -1073741825 : 29 === i4 ? s4.fg &= 2147483647 : 39 === i4 ? (s4.fg &= -67108864, s4.fg |= 16777215 & l2.DEFAULT_ATTR_DATA.fg) : 49 === i4 ? (s4.bg &= -67108864, s4.bg |= 16777215 & l2.DEFAULT_ATTR_DATA.bg) : 38 === i4 || 48 === i4 || 58 === i4 ? r3 += this._extractColor(e4, r3, s4) : 53 === i4 ? s4.bg |= 1073741824 : 55 === i4 ? s4.bg &= -1073741825 : 59 === i4 ? (s4.extended = s4.extended.clone(), s4.extended.underlineColor = -1, s4.updateExtended()) : 100 === i4 ? (s4.fg &= -67108864, s4.fg |= 16777215 & l2.DEFAULT_ATTR_DATA.fg, s4.bg &= -67108864, s4.bg |= 16777215 & l2.DEFAULT_ATTR_DATA.bg) : this._logService.debug("Unknown SGR attribute: %d.", i4);
          return true;
        }
        deviceStatus(e4) {
          switch (e4.params[0]) {
            case 5:
              this._coreService.triggerDataEvent(`${n2.C0.ESC}[0n`);
              break;
            case 6:
              const e5 = this._activeBuffer.y + 1, t4 = this._activeBuffer.x + 1;
              this._coreService.triggerDataEvent(`${n2.C0.ESC}[${e5};${t4}R`);
          }
          return true;
        }
        deviceStatusPrivate(e4) {
          if (6 === e4.params[0]) {
            const e5 = this._activeBuffer.y + 1, t4 = this._activeBuffer.x + 1;
            this._coreService.triggerDataEvent(`${n2.C0.ESC}[?${e5};${t4}R`);
          }
          return true;
        }
        softReset(e4) {
          return this._coreService.isCursorHidden = false, this._onRequestSyncScrollBar.fire(), this._activeBuffer.scrollTop = 0, this._activeBuffer.scrollBottom = this._bufferService.rows - 1, this._curAttrData = l2.DEFAULT_ATTR_DATA.clone(), this._coreService.reset(), this._charsetService.reset(), this._activeBuffer.savedX = 0, this._activeBuffer.savedY = this._activeBuffer.ybase, this._activeBuffer.savedCurAttrData.fg = this._curAttrData.fg, this._activeBuffer.savedCurAttrData.bg = this._curAttrData.bg, this._activeBuffer.savedCharset = this._charsetService.charset, this._coreService.decPrivateModes.origin = false, true;
        }
        setCursorStyle(e4) {
          const t4 = e4.params[0] || 1;
          switch (t4) {
            case 1:
            case 2:
              this._optionsService.options.cursorStyle = "block";
              break;
            case 3:
            case 4:
              this._optionsService.options.cursorStyle = "underline";
              break;
            case 5:
            case 6:
              this._optionsService.options.cursorStyle = "bar";
          }
          const i4 = t4 % 2 == 1;
          return this._optionsService.options.cursorBlink = i4, true;
        }
        setScrollRegion(e4) {
          const t4 = e4.params[0] || 1;
          let i4;
          return (e4.length < 2 || (i4 = e4.params[1]) > this._bufferService.rows || 0 === i4) && (i4 = this._bufferService.rows), i4 > t4 && (this._activeBuffer.scrollTop = t4 - 1, this._activeBuffer.scrollBottom = i4 - 1, this._setCursor(0, 0)), true;
        }
        windowOptions(e4) {
          if (!w2(e4.params[0], this._optionsService.rawOptions.windowOptions)) return true;
          const t4 = e4.length > 1 ? e4.params[1] : 0;
          switch (e4.params[0]) {
            case 14:
              2 !== t4 && this._onRequestWindowsOptionsReport.fire(y2.GET_WIN_SIZE_PIXELS);
              break;
            case 16:
              this._onRequestWindowsOptionsReport.fire(y2.GET_CELL_SIZE_PIXELS);
              break;
            case 18:
              this._bufferService && this._coreService.triggerDataEvent(`${n2.C0.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);
              break;
            case 22:
              0 !== t4 && 2 !== t4 || (this._windowTitleStack.push(this._windowTitle), this._windowTitleStack.length > 10 && this._windowTitleStack.shift()), 0 !== t4 && 1 !== t4 || (this._iconNameStack.push(this._iconName), this._iconNameStack.length > 10 && this._iconNameStack.shift());
              break;
            case 23:
              0 !== t4 && 2 !== t4 || this._windowTitleStack.length && this.setTitle(this._windowTitleStack.pop()), 0 !== t4 && 1 !== t4 || this._iconNameStack.length && this.setIconName(this._iconNameStack.pop());
          }
          return true;
        }
        saveCursor(e4) {
          return this._activeBuffer.savedX = this._activeBuffer.x, this._activeBuffer.savedY = this._activeBuffer.ybase + this._activeBuffer.y, this._activeBuffer.savedCurAttrData.fg = this._curAttrData.fg, this._activeBuffer.savedCurAttrData.bg = this._curAttrData.bg, this._activeBuffer.savedCharset = this._charsetService.charset, true;
        }
        restoreCursor(e4) {
          return this._activeBuffer.x = this._activeBuffer.savedX || 0, this._activeBuffer.y = Math.max(this._activeBuffer.savedY - this._activeBuffer.ybase, 0), this._curAttrData.fg = this._activeBuffer.savedCurAttrData.fg, this._curAttrData.bg = this._activeBuffer.savedCurAttrData.bg, this._charsetService.charset = this._savedCharset, this._activeBuffer.savedCharset && (this._charsetService.charset = this._activeBuffer.savedCharset), this._restrictCursor(), true;
        }
        setTitle(e4) {
          return this._windowTitle = e4, this._onTitleChange.fire(e4), true;
        }
        setIconName(e4) {
          return this._iconName = e4, true;
        }
        setOrReportIndexedColor(e4) {
          const t4 = [], i4 = e4.split(";");
          for (; i4.length > 1; ) {
            const e5 = i4.shift(), s4 = i4.shift();
            if (/^\d+$/.exec(e5)) {
              const i5 = parseInt(e5);
              if (D2(i5)) if ("?" === s4) t4.push({ type: 0, index: i5 });
              else {
                const e6 = (0, S2.parseColor)(s4);
                e6 && t4.push({ type: 1, index: i5, color: e6 });
              }
            }
          }
          return t4.length && this._onColor.fire(t4), true;
        }
        setHyperlink(e4) {
          const t4 = e4.split(";");
          return !(t4.length < 2) && (t4[1] ? this._createHyperlink(t4[0], t4[1]) : !t4[0] && this._finishHyperlink());
        }
        _createHyperlink(e4, t4) {
          this._getCurrentLinkId() && this._finishHyperlink();
          const i4 = e4.split(":");
          let s4;
          const r3 = i4.findIndex((e5) => e5.startsWith("id="));
          return -1 !== r3 && (s4 = i4[r3].slice(3) || void 0), this._curAttrData.extended = this._curAttrData.extended.clone(), this._curAttrData.extended.urlId = this._oscLinkService.registerLink({ id: s4, uri: t4 }), this._curAttrData.updateExtended(), true;
        }
        _finishHyperlink() {
          return this._curAttrData.extended = this._curAttrData.extended.clone(), this._curAttrData.extended.urlId = 0, this._curAttrData.updateExtended(), true;
        }
        _setOrReportSpecialColor(e4, t4) {
          const i4 = e4.split(";");
          for (let e5 = 0; e5 < i4.length && !(t4 >= this._specialColors.length); ++e5, ++t4) if ("?" === i4[e5]) this._onColor.fire([{ type: 0, index: this._specialColors[t4] }]);
          else {
            const s4 = (0, S2.parseColor)(i4[e5]);
            s4 && this._onColor.fire([{ type: 1, index: this._specialColors[t4], color: s4 }]);
          }
          return true;
        }
        setOrReportFgColor(e4) {
          return this._setOrReportSpecialColor(e4, 0);
        }
        setOrReportBgColor(e4) {
          return this._setOrReportSpecialColor(e4, 1);
        }
        setOrReportCursorColor(e4) {
          return this._setOrReportSpecialColor(e4, 2);
        }
        restoreIndexedColor(e4) {
          if (!e4) return this._onColor.fire([{ type: 2 }]), true;
          const t4 = [], i4 = e4.split(";");
          for (let e5 = 0; e5 < i4.length; ++e5) if (/^\d+$/.exec(i4[e5])) {
            const s4 = parseInt(i4[e5]);
            D2(s4) && t4.push({ type: 2, index: s4 });
          }
          return t4.length && this._onColor.fire(t4), true;
        }
        restoreFgColor(e4) {
          return this._onColor.fire([{ type: 2, index: 256 }]), true;
        }
        restoreBgColor(e4) {
          return this._onColor.fire([{ type: 2, index: 257 }]), true;
        }
        restoreCursorColor(e4) {
          return this._onColor.fire([{ type: 2, index: 258 }]), true;
        }
        nextLine() {
          return this._activeBuffer.x = 0, this.index(), true;
        }
        keypadApplicationMode() {
          return this._logService.debug("Serial port requested application keypad."), this._coreService.decPrivateModes.applicationKeypad = true, this._onRequestSyncScrollBar.fire(), true;
        }
        keypadNumericMode() {
          return this._logService.debug("Switching back to normal keypad."), this._coreService.decPrivateModes.applicationKeypad = false, this._onRequestSyncScrollBar.fire(), true;
        }
        selectDefaultCharset() {
          return this._charsetService.setgLevel(0), this._charsetService.setgCharset(0, o2.DEFAULT_CHARSET), true;
        }
        selectCharset(e4) {
          return 2 !== e4.length ? (this.selectDefaultCharset(), true) : ("/" === e4[0] || this._charsetService.setgCharset(C2[e4[0]], o2.CHARSETS[e4[1]] || o2.DEFAULT_CHARSET), true);
        }
        index() {
          return this._restrictCursor(), this._activeBuffer.y++, this._activeBuffer.y === this._activeBuffer.scrollBottom + 1 ? (this._activeBuffer.y--, this._bufferService.scroll(this._eraseAttrData())) : this._activeBuffer.y >= this._bufferService.rows && (this._activeBuffer.y = this._bufferService.rows - 1), this._restrictCursor(), true;
        }
        tabSet() {
          return this._activeBuffer.tabs[this._activeBuffer.x] = true, true;
        }
        reverseIndex() {
          if (this._restrictCursor(), this._activeBuffer.y === this._activeBuffer.scrollTop) {
            const e4 = this._activeBuffer.scrollBottom - this._activeBuffer.scrollTop;
            this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase + this._activeBuffer.y, e4, 1), this._activeBuffer.lines.set(this._activeBuffer.ybase + this._activeBuffer.y, this._activeBuffer.getBlankLine(this._eraseAttrData())), this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom);
          } else this._activeBuffer.y--, this._restrictCursor();
          return true;
        }
        fullReset() {
          return this._parser.reset(), this._onRequestReset.fire(), true;
        }
        reset() {
          this._curAttrData = l2.DEFAULT_ATTR_DATA.clone(), this._eraseAttrDataInternal = l2.DEFAULT_ATTR_DATA.clone();
        }
        _eraseAttrData() {
          return this._eraseAttrDataInternal.bg &= -67108864, this._eraseAttrDataInternal.bg |= 67108863 & this._curAttrData.bg, this._eraseAttrDataInternal;
        }
        setgLevel(e4) {
          return this._charsetService.setgLevel(e4), true;
        }
        screenAlignmentPattern() {
          const e4 = new u2.CellData();
          e4.content = 1 << 22 | "E".charCodeAt(0), e4.fg = this._curAttrData.fg, e4.bg = this._curAttrData.bg, this._setCursor(0, 0);
          for (let t4 = 0; t4 < this._bufferService.rows; ++t4) {
            const i4 = this._activeBuffer.ybase + this._activeBuffer.y + t4, s4 = this._activeBuffer.lines.get(i4);
            s4 && (s4.fill(e4), s4.isWrapped = false);
          }
          return this._dirtyRowTracker.markAllDirty(), this._setCursor(0, 0), true;
        }
        requestStatusString(e4, t4) {
          const i4 = this._bufferService.buffer, s4 = this._optionsService.rawOptions;
          return ((e5) => (this._coreService.triggerDataEvent(`${n2.C0.ESC}${e5}${n2.C0.ESC}\\`), true))('"q' === e4 ? `P1$r${this._curAttrData.isProtected() ? 1 : 0}"q` : '"p' === e4 ? 'P1$r61;1"p' : "r" === e4 ? `P1$r${i4.scrollTop + 1};${i4.scrollBottom + 1}r` : "m" === e4 ? "P1$r0m" : " q" === e4 ? `P1$r${{ block: 2, underline: 4, bar: 6 }[s4.cursorStyle] - (s4.cursorBlink ? 1 : 0)} q` : "P0$r");
        }
        markRangeDirty(e4, t4) {
          this._dirtyRowTracker.markRangeDirty(e4, t4);
        }
      }
      t3.InputHandler = k2;
      let L2 = class {
        static {
          __name(this, "L");
        }
        constructor(e4) {
          this._bufferService = e4, this.clearRange();
        }
        clearRange() {
          this.start = this._bufferService.buffer.y, this.end = this._bufferService.buffer.y;
        }
        markDirty(e4) {
          e4 < this.start ? this.start = e4 : e4 > this.end && (this.end = e4);
        }
        markRangeDirty(e4, t4) {
          e4 > t4 && (E = e4, e4 = t4, t4 = E), e4 < this.start && (this.start = e4), t4 > this.end && (this.end = t4);
        }
        markAllDirty() {
          this.markRangeDirty(0, this._bufferService.rows - 1);
        }
      };
      function D2(e4) {
        return 0 <= e4 && e4 < 256;
      }
      __name(D2, "D");
      L2 = s3([r2(0, v2.IBufferService)], L2);
    }, 844: (e3, t3) => {
      function i3(e4) {
        for (const t4 of e4) t4.dispose();
        e4.length = 0;
      }
      __name(i3, "i");
      Object.defineProperty(t3, "__esModule", { value: true }), t3.getDisposeArrayDisposable = t3.disposeArray = t3.toDisposable = t3.MutableDisposable = t3.Disposable = void 0, t3.Disposable = class {
        constructor() {
          this._disposables = [], this._isDisposed = false;
        }
        dispose() {
          this._isDisposed = true;
          for (const e4 of this._disposables) e4.dispose();
          this._disposables.length = 0;
        }
        register(e4) {
          return this._disposables.push(e4), e4;
        }
        unregister(e4) {
          const t4 = this._disposables.indexOf(e4);
          -1 !== t4 && this._disposables.splice(t4, 1);
        }
      }, t3.MutableDisposable = class {
        constructor() {
          this._isDisposed = false;
        }
        get value() {
          return this._isDisposed ? void 0 : this._value;
        }
        set value(e4) {
          this._isDisposed || e4 === this._value || (this._value?.dispose(), this._value = e4);
        }
        clear() {
          this.value = void 0;
        }
        dispose() {
          this._isDisposed = true, this._value?.dispose(), this._value = void 0;
        }
      }, t3.toDisposable = function(e4) {
        return { dispose: e4 };
      }, t3.disposeArray = i3, t3.getDisposeArrayDisposable = function(e4) {
        return { dispose: /* @__PURE__ */ __name(() => i3(e4), "dispose") };
      };
    }, 1505: (e3, t3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.FourKeyMap = t3.TwoKeyMap = void 0;
      class i3 {
        static {
          __name(this, "i");
        }
        constructor() {
          this._data = {};
        }
        set(e4, t4, i4) {
          this._data[e4] || (this._data[e4] = {}), this._data[e4][t4] = i4;
        }
        get(e4, t4) {
          return this._data[e4] ? this._data[e4][t4] : void 0;
        }
        clear() {
          this._data = {};
        }
      }
      t3.TwoKeyMap = i3, t3.FourKeyMap = class {
        constructor() {
          this._data = new i3();
        }
        set(e4, t4, s3, r2, n2) {
          this._data.get(e4, t4) || this._data.set(e4, t4, new i3()), this._data.get(e4, t4).set(s3, r2, n2);
        }
        get(e4, t4, i4, s3) {
          return this._data.get(e4, t4)?.get(i4, s3);
        }
        clear() {
          this._data.clear();
        }
      };
    }, 6114: (e3, t3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.isChromeOS = t3.isLinux = t3.isWindows = t3.isIphone = t3.isIpad = t3.isMac = t3.getSafariVersion = t3.isSafari = t3.isLegacyEdge = t3.isFirefox = t3.isNode = void 0, t3.isNode = "undefined" != typeof process && "title" in process;
      const i3 = t3.isNode ? "node" : navigator.userAgent, s3 = t3.isNode ? "node" : navigator.platform;
      t3.isFirefox = i3.includes("Firefox"), t3.isLegacyEdge = i3.includes("Edge"), t3.isSafari = /^((?!chrome|android).)*safari/i.test(i3), t3.getSafariVersion = function() {
        if (!t3.isSafari) return 0;
        const e4 = i3.match(/Version\/(\d+)/);
        return null === e4 || e4.length < 2 ? 0 : parseInt(e4[1]);
      }, t3.isMac = ["Macintosh", "MacIntel", "MacPPC", "Mac68K"].includes(s3), t3.isIpad = "iPad" === s3, t3.isIphone = "iPhone" === s3, t3.isWindows = ["Windows", "Win16", "Win32", "WinCE"].includes(s3), t3.isLinux = s3.indexOf("Linux") >= 0, t3.isChromeOS = /\bCrOS\b/.test(i3);
    }, 6106: (e3, t3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.SortedList = void 0;
      let i3 = 0;
      t3.SortedList = class {
        constructor(e4) {
          this._getKey = e4, this._array = [];
        }
        clear() {
          this._array.length = 0;
        }
        insert(e4) {
          0 !== this._array.length ? (i3 = this._search(this._getKey(e4)), this._array.splice(i3, 0, e4)) : this._array.push(e4);
        }
        delete(e4) {
          if (0 === this._array.length) return false;
          const t4 = this._getKey(e4);
          if (void 0 === t4) return false;
          if (i3 = this._search(t4), -1 === i3) return false;
          if (this._getKey(this._array[i3]) !== t4) return false;
          do {
            if (this._array[i3] === e4) return this._array.splice(i3, 1), true;
          } while (++i3 < this._array.length && this._getKey(this._array[i3]) === t4);
          return false;
        }
        *getKeyIterator(e4) {
          if (0 !== this._array.length && (i3 = this._search(e4), !(i3 < 0 || i3 >= this._array.length) && this._getKey(this._array[i3]) === e4)) do {
            yield this._array[i3];
          } while (++i3 < this._array.length && this._getKey(this._array[i3]) === e4);
        }
        forEachByKey(e4, t4) {
          if (0 !== this._array.length && (i3 = this._search(e4), !(i3 < 0 || i3 >= this._array.length) && this._getKey(this._array[i3]) === e4)) do {
            t4(this._array[i3]);
          } while (++i3 < this._array.length && this._getKey(this._array[i3]) === e4);
        }
        values() {
          return [...this._array].values();
        }
        _search(e4) {
          let t4 = 0, i4 = this._array.length - 1;
          for (; i4 >= t4; ) {
            let s3 = t4 + i4 >> 1;
            const r2 = this._getKey(this._array[s3]);
            if (r2 > e4) i4 = s3 - 1;
            else {
              if (!(r2 < e4)) {
                for (; s3 > 0 && this._getKey(this._array[s3 - 1]) === e4; ) s3--;
                return s3;
              }
              t4 = s3 + 1;
            }
          }
          return t4;
        }
      };
    }, 7226: (e3, t3, i3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.DebouncedIdleTask = t3.IdleTaskQueue = t3.PriorityTaskQueue = void 0;
      const s3 = i3(6114);
      class r2 {
        static {
          __name(this, "r");
        }
        constructor() {
          this._tasks = [], this._i = 0;
        }
        enqueue(e4) {
          this._tasks.push(e4), this._start();
        }
        flush() {
          for (; this._i < this._tasks.length; ) this._tasks[this._i]() || this._i++;
          this.clear();
        }
        clear() {
          this._idleCallback && (this._cancelCallback(this._idleCallback), this._idleCallback = void 0), this._i = 0, this._tasks.length = 0;
        }
        _start() {
          this._idleCallback || (this._idleCallback = this._requestCallback(this._process.bind(this)));
        }
        _process(e4) {
          this._idleCallback = void 0;
          let t4 = 0, i4 = 0, s4 = e4.timeRemaining(), r3 = 0;
          for (; this._i < this._tasks.length; ) {
            if (t4 = Date.now(), this._tasks[this._i]() || this._i++, t4 = Math.max(1, Date.now() - t4), i4 = Math.max(t4, i4), r3 = e4.timeRemaining(), 1.5 * i4 > r3) return s4 - t4 < -20 && console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(s4 - t4))}ms`), void this._start();
            s4 = r3;
          }
          this.clear();
        }
      }
      class n2 extends r2 {
        static {
          __name(this, "n");
        }
        _requestCallback(e4) {
          return setTimeout(() => e4(this._createDeadline(16)));
        }
        _cancelCallback(e4) {
          clearTimeout(e4);
        }
        _createDeadline(e4) {
          const t4 = Date.now() + e4;
          return { timeRemaining: /* @__PURE__ */ __name(() => Math.max(0, t4 - Date.now()), "timeRemaining") };
        }
      }
      t3.PriorityTaskQueue = n2, t3.IdleTaskQueue = !s3.isNode && "requestIdleCallback" in window ? class extends r2 {
        _requestCallback(e4) {
          return requestIdleCallback(e4);
        }
        _cancelCallback(e4) {
          cancelIdleCallback(e4);
        }
      } : n2, t3.DebouncedIdleTask = class {
        constructor() {
          this._queue = new t3.IdleTaskQueue();
        }
        set(e4) {
          this._queue.clear(), this._queue.enqueue(e4);
        }
        flush() {
          this._queue.flush();
        }
      };
    }, 9282: (e3, t3, i3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.updateWindowsModeWrappedState = void 0;
      const s3 = i3(643);
      t3.updateWindowsModeWrappedState = function(e4) {
        const t4 = e4.buffer.lines.get(e4.buffer.ybase + e4.buffer.y - 1), i4 = t4?.get(e4.cols - 1), r2 = e4.buffer.lines.get(e4.buffer.ybase + e4.buffer.y);
        r2 && i4 && (r2.isWrapped = i4[s3.CHAR_DATA_CODE_INDEX] !== s3.NULL_CELL_CODE && i4[s3.CHAR_DATA_CODE_INDEX] !== s3.WHITESPACE_CELL_CODE);
      };
    }, 3734: (e3, t3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.ExtendedAttrs = t3.AttributeData = void 0;
      class i3 {
        static {
          __name(this, "i");
        }
        constructor() {
          this.fg = 0, this.bg = 0, this.extended = new s3();
        }
        static toColorRGB(e4) {
          return [e4 >>> 16 & 255, e4 >>> 8 & 255, 255 & e4];
        }
        static fromColorRGB(e4) {
          return (255 & e4[0]) << 16 | (255 & e4[1]) << 8 | 255 & e4[2];
        }
        clone() {
          const e4 = new i3();
          return e4.fg = this.fg, e4.bg = this.bg, e4.extended = this.extended.clone(), e4;
        }
        isInverse() {
          return 67108864 & this.fg;
        }
        isBold() {
          return 134217728 & this.fg;
        }
        isUnderline() {
          return this.hasExtendedAttrs() && 0 !== this.extended.underlineStyle ? 1 : 268435456 & this.fg;
        }
        isBlink() {
          return 536870912 & this.fg;
        }
        isInvisible() {
          return 1073741824 & this.fg;
        }
        isItalic() {
          return 67108864 & this.bg;
        }
        isDim() {
          return 134217728 & this.bg;
        }
        isStrikethrough() {
          return 2147483648 & this.fg;
        }
        isProtected() {
          return 536870912 & this.bg;
        }
        isOverline() {
          return 1073741824 & this.bg;
        }
        getFgColorMode() {
          return 50331648 & this.fg;
        }
        getBgColorMode() {
          return 50331648 & this.bg;
        }
        isFgRGB() {
          return 50331648 == (50331648 & this.fg);
        }
        isBgRGB() {
          return 50331648 == (50331648 & this.bg);
        }
        isFgPalette() {
          return 16777216 == (50331648 & this.fg) || 33554432 == (50331648 & this.fg);
        }
        isBgPalette() {
          return 16777216 == (50331648 & this.bg) || 33554432 == (50331648 & this.bg);
        }
        isFgDefault() {
          return 0 == (50331648 & this.fg);
        }
        isBgDefault() {
          return 0 == (50331648 & this.bg);
        }
        isAttributeDefault() {
          return 0 === this.fg && 0 === this.bg;
        }
        getFgColor() {
          switch (50331648 & this.fg) {
            case 16777216:
            case 33554432:
              return 255 & this.fg;
            case 50331648:
              return 16777215 & this.fg;
            default:
              return -1;
          }
        }
        getBgColor() {
          switch (50331648 & this.bg) {
            case 16777216:
            case 33554432:
              return 255 & this.bg;
            case 50331648:
              return 16777215 & this.bg;
            default:
              return -1;
          }
        }
        hasExtendedAttrs() {
          return 268435456 & this.bg;
        }
        updateExtended() {
          this.extended.isEmpty() ? this.bg &= -268435457 : this.bg |= 268435456;
        }
        getUnderlineColor() {
          if (268435456 & this.bg && ~this.extended.underlineColor) switch (50331648 & this.extended.underlineColor) {
            case 16777216:
            case 33554432:
              return 255 & this.extended.underlineColor;
            case 50331648:
              return 16777215 & this.extended.underlineColor;
            default:
              return this.getFgColor();
          }
          return this.getFgColor();
        }
        getUnderlineColorMode() {
          return 268435456 & this.bg && ~this.extended.underlineColor ? 50331648 & this.extended.underlineColor : this.getFgColorMode();
        }
        isUnderlineColorRGB() {
          return 268435456 & this.bg && ~this.extended.underlineColor ? 50331648 == (50331648 & this.extended.underlineColor) : this.isFgRGB();
        }
        isUnderlineColorPalette() {
          return 268435456 & this.bg && ~this.extended.underlineColor ? 16777216 == (50331648 & this.extended.underlineColor) || 33554432 == (50331648 & this.extended.underlineColor) : this.isFgPalette();
        }
        isUnderlineColorDefault() {
          return 268435456 & this.bg && ~this.extended.underlineColor ? 0 == (50331648 & this.extended.underlineColor) : this.isFgDefault();
        }
        getUnderlineStyle() {
          return 268435456 & this.fg ? 268435456 & this.bg ? this.extended.underlineStyle : 1 : 0;
        }
        getUnderlineVariantOffset() {
          return this.extended.underlineVariantOffset;
        }
      }
      t3.AttributeData = i3;
      class s3 {
        static {
          __name(this, "s");
        }
        get ext() {
          return this._urlId ? -469762049 & this._ext | this.underlineStyle << 26 : this._ext;
        }
        set ext(e4) {
          this._ext = e4;
        }
        get underlineStyle() {
          return this._urlId ? 5 : (469762048 & this._ext) >> 26;
        }
        set underlineStyle(e4) {
          this._ext &= -469762049, this._ext |= e4 << 26 & 469762048;
        }
        get underlineColor() {
          return 67108863 & this._ext;
        }
        set underlineColor(e4) {
          this._ext &= -67108864, this._ext |= 67108863 & e4;
        }
        get urlId() {
          return this._urlId;
        }
        set urlId(e4) {
          this._urlId = e4;
        }
        get underlineVariantOffset() {
          const e4 = (3758096384 & this._ext) >> 29;
          return e4 < 0 ? 4294967288 ^ e4 : e4;
        }
        set underlineVariantOffset(e4) {
          this._ext &= 536870911, this._ext |= e4 << 29 & 3758096384;
        }
        constructor(e4 = 0, t4 = 0) {
          this._ext = 0, this._urlId = 0, this._ext = e4, this._urlId = t4;
        }
        clone() {
          return new s3(this._ext, this._urlId);
        }
        isEmpty() {
          return 0 === this.underlineStyle && 0 === this._urlId;
        }
      }
      t3.ExtendedAttrs = s3;
    }, 9092: (e3, t3, i3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.Buffer = t3.MAX_BUFFER_SIZE = void 0;
      const s3 = i3(6349), r2 = i3(7226), n2 = i3(3734), o2 = i3(8437), a2 = i3(4634), h2 = i3(511), c2 = i3(643), l2 = i3(4863), d2 = i3(7116);
      t3.MAX_BUFFER_SIZE = 4294967295, t3.Buffer = class {
        constructor(e4, t4, i4) {
          this._hasScrollback = e4, this._optionsService = t4, this._bufferService = i4, this.ydisp = 0, this.ybase = 0, this.y = 0, this.x = 0, this.tabs = {}, this.savedY = 0, this.savedX = 0, this.savedCurAttrData = o2.DEFAULT_ATTR_DATA.clone(), this.savedCharset = d2.DEFAULT_CHARSET, this.markers = [], this._nullCell = h2.CellData.fromCharData([0, c2.NULL_CELL_CHAR, c2.NULL_CELL_WIDTH, c2.NULL_CELL_CODE]), this._whitespaceCell = h2.CellData.fromCharData([0, c2.WHITESPACE_CELL_CHAR, c2.WHITESPACE_CELL_WIDTH, c2.WHITESPACE_CELL_CODE]), this._isClearing = false, this._memoryCleanupQueue = new r2.IdleTaskQueue(), this._memoryCleanupPosition = 0, this._cols = this._bufferService.cols, this._rows = this._bufferService.rows, this.lines = new s3.CircularList(this._getCorrectBufferLength(this._rows)), this.scrollTop = 0, this.scrollBottom = this._rows - 1, this.setupTabStops();
        }
        getNullCell(e4) {
          return e4 ? (this._nullCell.fg = e4.fg, this._nullCell.bg = e4.bg, this._nullCell.extended = e4.extended) : (this._nullCell.fg = 0, this._nullCell.bg = 0, this._nullCell.extended = new n2.ExtendedAttrs()), this._nullCell;
        }
        getWhitespaceCell(e4) {
          return e4 ? (this._whitespaceCell.fg = e4.fg, this._whitespaceCell.bg = e4.bg, this._whitespaceCell.extended = e4.extended) : (this._whitespaceCell.fg = 0, this._whitespaceCell.bg = 0, this._whitespaceCell.extended = new n2.ExtendedAttrs()), this._whitespaceCell;
        }
        getBlankLine(e4, t4) {
          return new o2.BufferLine(this._bufferService.cols, this.getNullCell(e4), t4);
        }
        get hasScrollback() {
          return this._hasScrollback && this.lines.maxLength > this._rows;
        }
        get isCursorInViewport() {
          const e4 = this.ybase + this.y - this.ydisp;
          return e4 >= 0 && e4 < this._rows;
        }
        _getCorrectBufferLength(e4) {
          if (!this._hasScrollback) return e4;
          const i4 = e4 + this._optionsService.rawOptions.scrollback;
          return i4 > t3.MAX_BUFFER_SIZE ? t3.MAX_BUFFER_SIZE : i4;
        }
        fillViewportRows(e4) {
          if (0 === this.lines.length) {
            void 0 === e4 && (e4 = o2.DEFAULT_ATTR_DATA);
            let t4 = this._rows;
            for (; t4--; ) this.lines.push(this.getBlankLine(e4));
          }
        }
        clear() {
          this.ydisp = 0, this.ybase = 0, this.y = 0, this.x = 0, this.lines = new s3.CircularList(this._getCorrectBufferLength(this._rows)), this.scrollTop = 0, this.scrollBottom = this._rows - 1, this.setupTabStops();
        }
        resize(e4, t4) {
          const i4 = this.getNullCell(o2.DEFAULT_ATTR_DATA);
          let s4 = 0;
          const r3 = this._getCorrectBufferLength(t4);
          if (r3 > this.lines.maxLength && (this.lines.maxLength = r3), this.lines.length > 0) {
            if (this._cols < e4) for (let t5 = 0; t5 < this.lines.length; t5++) s4 += +this.lines.get(t5).resize(e4, i4);
            let n3 = 0;
            if (this._rows < t4) for (let s5 = this._rows; s5 < t4; s5++) this.lines.length < t4 + this.ybase && (this._optionsService.rawOptions.windowsMode || void 0 !== this._optionsService.rawOptions.windowsPty.backend || void 0 !== this._optionsService.rawOptions.windowsPty.buildNumber ? this.lines.push(new o2.BufferLine(e4, i4)) : this.ybase > 0 && this.lines.length <= this.ybase + this.y + n3 + 1 ? (this.ybase--, n3++, this.ydisp > 0 && this.ydisp--) : this.lines.push(new o2.BufferLine(e4, i4)));
            else for (let e5 = this._rows; e5 > t4; e5--) this.lines.length > t4 + this.ybase && (this.lines.length > this.ybase + this.y + 1 ? this.lines.pop() : (this.ybase++, this.ydisp++));
            if (r3 < this.lines.maxLength) {
              const e5 = this.lines.length - r3;
              e5 > 0 && (this.lines.trimStart(e5), this.ybase = Math.max(this.ybase - e5, 0), this.ydisp = Math.max(this.ydisp - e5, 0), this.savedY = Math.max(this.savedY - e5, 0)), this.lines.maxLength = r3;
            }
            this.x = Math.min(this.x, e4 - 1), this.y = Math.min(this.y, t4 - 1), n3 && (this.y += n3), this.savedX = Math.min(this.savedX, e4 - 1), this.scrollTop = 0;
          }
          if (this.scrollBottom = t4 - 1, this._isReflowEnabled && (this._reflow(e4, t4), this._cols > e4)) for (let t5 = 0; t5 < this.lines.length; t5++) s4 += +this.lines.get(t5).resize(e4, i4);
          this._cols = e4, this._rows = t4, this._memoryCleanupQueue.clear(), s4 > 0.1 * this.lines.length && (this._memoryCleanupPosition = 0, this._memoryCleanupQueue.enqueue(() => this._batchedMemoryCleanup()));
        }
        _batchedMemoryCleanup() {
          let e4 = true;
          this._memoryCleanupPosition >= this.lines.length && (this._memoryCleanupPosition = 0, e4 = false);
          let t4 = 0;
          for (; this._memoryCleanupPosition < this.lines.length; ) if (t4 += this.lines.get(this._memoryCleanupPosition++).cleanupMemory(), t4 > 100) return true;
          return e4;
        }
        get _isReflowEnabled() {
          const e4 = this._optionsService.rawOptions.windowsPty;
          return e4 && e4.buildNumber ? this._hasScrollback && "conpty" === e4.backend && e4.buildNumber >= 21376 : this._hasScrollback && !this._optionsService.rawOptions.windowsMode;
        }
        _reflow(e4, t4) {
          this._cols !== e4 && (e4 > this._cols ? this._reflowLarger(e4, t4) : this._reflowSmaller(e4, t4));
        }
        _reflowLarger(e4, t4) {
          const i4 = (0, a2.reflowLargerGetLinesToRemove)(this.lines, this._cols, e4, this.ybase + this.y, this.getNullCell(o2.DEFAULT_ATTR_DATA));
          if (i4.length > 0) {
            const s4 = (0, a2.reflowLargerCreateNewLayout)(this.lines, i4);
            (0, a2.reflowLargerApplyNewLayout)(this.lines, s4.layout), this._reflowLargerAdjustViewport(e4, t4, s4.countRemoved);
          }
        }
        _reflowLargerAdjustViewport(e4, t4, i4) {
          const s4 = this.getNullCell(o2.DEFAULT_ATTR_DATA);
          let r3 = i4;
          for (; r3-- > 0; ) 0 === this.ybase ? (this.y > 0 && this.y--, this.lines.length < t4 && this.lines.push(new o2.BufferLine(e4, s4))) : (this.ydisp === this.ybase && this.ydisp--, this.ybase--);
          this.savedY = Math.max(this.savedY - i4, 0);
        }
        _reflowSmaller(e4, t4) {
          const i4 = this.getNullCell(o2.DEFAULT_ATTR_DATA), s4 = [];
          let r3 = 0;
          for (let n3 = this.lines.length - 1; n3 >= 0; n3--) {
            let h3 = this.lines.get(n3);
            if (!h3 || !h3.isWrapped && h3.getTrimmedLength() <= e4) continue;
            const c3 = [h3];
            for (; h3.isWrapped && n3 > 0; ) h3 = this.lines.get(--n3), c3.unshift(h3);
            const l3 = this.ybase + this.y;
            if (l3 >= n3 && l3 < n3 + c3.length) continue;
            const d3 = c3[c3.length - 1].getTrimmedLength(), _2 = (0, a2.reflowSmallerGetNewLineLengths)(c3, this._cols, e4), u2 = _2.length - c3.length;
            let f2;
            f2 = 0 === this.ybase && this.y !== this.lines.length - 1 ? Math.max(0, this.y - this.lines.maxLength + u2) : Math.max(0, this.lines.length - this.lines.maxLength + u2);
            const v2 = [];
            for (let e5 = 0; e5 < u2; e5++) {
              const e6 = this.getBlankLine(o2.DEFAULT_ATTR_DATA, true);
              v2.push(e6);
            }
            v2.length > 0 && (s4.push({ start: n3 + c3.length + r3, newLines: v2 }), r3 += v2.length), c3.push(...v2);
            let p2 = _2.length - 1, g2 = _2[p2];
            0 === g2 && (p2--, g2 = _2[p2]);
            let m2 = c3.length - u2 - 1, S2 = d3;
            for (; m2 >= 0; ) {
              const e5 = Math.min(S2, g2);
              if (void 0 === c3[p2]) break;
              if (c3[p2].copyCellsFrom(c3[m2], S2 - e5, g2 - e5, e5, true), g2 -= e5, 0 === g2 && (p2--, g2 = _2[p2]), S2 -= e5, 0 === S2) {
                m2--;
                const e6 = Math.max(m2, 0);
                S2 = (0, a2.getWrappedLineTrimmedLength)(c3, e6, this._cols);
              }
            }
            for (let t5 = 0; t5 < c3.length; t5++) _2[t5] < e4 && c3[t5].setCell(_2[t5], i4);
            let C2 = u2 - f2;
            for (; C2-- > 0; ) 0 === this.ybase ? this.y < t4 - 1 ? (this.y++, this.lines.pop()) : (this.ybase++, this.ydisp++) : this.ybase < Math.min(this.lines.maxLength, this.lines.length + r3) - t4 && (this.ybase === this.ydisp && this.ydisp++, this.ybase++);
            this.savedY = Math.min(this.savedY + u2, this.ybase + t4 - 1);
          }
          if (s4.length > 0) {
            const e5 = [], t5 = [];
            for (let e6 = 0; e6 < this.lines.length; e6++) t5.push(this.lines.get(e6));
            const i5 = this.lines.length;
            let n3 = i5 - 1, o3 = 0, a3 = s4[o3];
            this.lines.length = Math.min(this.lines.maxLength, this.lines.length + r3);
            let h3 = 0;
            for (let c4 = Math.min(this.lines.maxLength - 1, i5 + r3 - 1); c4 >= 0; c4--) if (a3 && a3.start > n3 + h3) {
              for (let e6 = a3.newLines.length - 1; e6 >= 0; e6--) this.lines.set(c4--, a3.newLines[e6]);
              c4++, e5.push({ index: n3 + 1, amount: a3.newLines.length }), h3 += a3.newLines.length, a3 = s4[++o3];
            } else this.lines.set(c4, t5[n3--]);
            let c3 = 0;
            for (let t6 = e5.length - 1; t6 >= 0; t6--) e5[t6].index += c3, this.lines.onInsertEmitter.fire(e5[t6]), c3 += e5[t6].amount;
            const l3 = Math.max(0, i5 + r3 - this.lines.maxLength);
            l3 > 0 && this.lines.onTrimEmitter.fire(l3);
          }
        }
        translateBufferLineToString(e4, t4, i4 = 0, s4) {
          const r3 = this.lines.get(e4);
          return r3 ? r3.translateToString(t4, i4, s4) : "";
        }
        getWrappedRangeForLine(e4) {
          let t4 = e4, i4 = e4;
          for (; t4 > 0 && this.lines.get(t4).isWrapped; ) t4--;
          for (; i4 + 1 < this.lines.length && this.lines.get(i4 + 1).isWrapped; ) i4++;
          return { first: t4, last: i4 };
        }
        setupTabStops(e4) {
          for (null != e4 ? this.tabs[e4] || (e4 = this.prevStop(e4)) : (this.tabs = {}, e4 = 0); e4 < this._cols; e4 += this._optionsService.rawOptions.tabStopWidth) this.tabs[e4] = true;
        }
        prevStop(e4) {
          for (null == e4 && (e4 = this.x); !this.tabs[--e4] && e4 > 0; ) ;
          return e4 >= this._cols ? this._cols - 1 : e4 < 0 ? 0 : e4;
        }
        nextStop(e4) {
          for (null == e4 && (e4 = this.x); !this.tabs[++e4] && e4 < this._cols; ) ;
          return e4 >= this._cols ? this._cols - 1 : e4 < 0 ? 0 : e4;
        }
        clearMarkers(e4) {
          this._isClearing = true;
          for (let t4 = 0; t4 < this.markers.length; t4++) this.markers[t4].line === e4 && (this.markers[t4].dispose(), this.markers.splice(t4--, 1));
          this._isClearing = false;
        }
        clearAllMarkers() {
          this._isClearing = true;
          for (let e4 = 0; e4 < this.markers.length; e4++) this.markers[e4].dispose(), this.markers.splice(e4--, 1);
          this._isClearing = false;
        }
        addMarker(e4) {
          const t4 = new l2.Marker(e4);
          return this.markers.push(t4), t4.register(this.lines.onTrim((e5) => {
            t4.line -= e5, t4.line < 0 && t4.dispose();
          })), t4.register(this.lines.onInsert((e5) => {
            t4.line >= e5.index && (t4.line += e5.amount);
          })), t4.register(this.lines.onDelete((e5) => {
            t4.line >= e5.index && t4.line < e5.index + e5.amount && t4.dispose(), t4.line > e5.index && (t4.line -= e5.amount);
          })), t4.register(t4.onDispose(() => this._removeMarker(t4))), t4;
        }
        _removeMarker(e4) {
          this._isClearing || this.markers.splice(this.markers.indexOf(e4), 1);
        }
      };
    }, 8437: (e3, t3, i3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.BufferLine = t3.DEFAULT_ATTR_DATA = void 0;
      const s3 = i3(3734), r2 = i3(511), n2 = i3(643), o2 = i3(482);
      t3.DEFAULT_ATTR_DATA = Object.freeze(new s3.AttributeData());
      let a2 = 0;
      class h2 {
        static {
          __name(this, "h");
        }
        constructor(e4, t4, i4 = false) {
          this.isWrapped = i4, this._combined = {}, this._extendedAttrs = {}, this._data = new Uint32Array(3 * e4);
          const s4 = t4 || r2.CellData.fromCharData([0, n2.NULL_CELL_CHAR, n2.NULL_CELL_WIDTH, n2.NULL_CELL_CODE]);
          for (let t5 = 0; t5 < e4; ++t5) this.setCell(t5, s4);
          this.length = e4;
        }
        get(e4) {
          const t4 = this._data[3 * e4 + 0], i4 = 2097151 & t4;
          return [this._data[3 * e4 + 1], 2097152 & t4 ? this._combined[e4] : i4 ? (0, o2.stringFromCodePoint)(i4) : "", t4 >> 22, 2097152 & t4 ? this._combined[e4].charCodeAt(this._combined[e4].length - 1) : i4];
        }
        set(e4, t4) {
          this._data[3 * e4 + 1] = t4[n2.CHAR_DATA_ATTR_INDEX], t4[n2.CHAR_DATA_CHAR_INDEX].length > 1 ? (this._combined[e4] = t4[1], this._data[3 * e4 + 0] = 2097152 | e4 | t4[n2.CHAR_DATA_WIDTH_INDEX] << 22) : this._data[3 * e4 + 0] = t4[n2.CHAR_DATA_CHAR_INDEX].charCodeAt(0) | t4[n2.CHAR_DATA_WIDTH_INDEX] << 22;
        }
        getWidth(e4) {
          return this._data[3 * e4 + 0] >> 22;
        }
        hasWidth(e4) {
          return 12582912 & this._data[3 * e4 + 0];
        }
        getFg(e4) {
          return this._data[3 * e4 + 1];
        }
        getBg(e4) {
          return this._data[3 * e4 + 2];
        }
        hasContent(e4) {
          return 4194303 & this._data[3 * e4 + 0];
        }
        getCodePoint(e4) {
          const t4 = this._data[3 * e4 + 0];
          return 2097152 & t4 ? this._combined[e4].charCodeAt(this._combined[e4].length - 1) : 2097151 & t4;
        }
        isCombined(e4) {
          return 2097152 & this._data[3 * e4 + 0];
        }
        getString(e4) {
          const t4 = this._data[3 * e4 + 0];
          return 2097152 & t4 ? this._combined[e4] : 2097151 & t4 ? (0, o2.stringFromCodePoint)(2097151 & t4) : "";
        }
        isProtected(e4) {
          return 536870912 & this._data[3 * e4 + 2];
        }
        loadCell(e4, t4) {
          return a2 = 3 * e4, t4.content = this._data[a2 + 0], t4.fg = this._data[a2 + 1], t4.bg = this._data[a2 + 2], 2097152 & t4.content && (t4.combinedData = this._combined[e4]), 268435456 & t4.bg && (t4.extended = this._extendedAttrs[e4]), t4;
        }
        setCell(e4, t4) {
          2097152 & t4.content && (this._combined[e4] = t4.combinedData), 268435456 & t4.bg && (this._extendedAttrs[e4] = t4.extended), this._data[3 * e4 + 0] = t4.content, this._data[3 * e4 + 1] = t4.fg, this._data[3 * e4 + 2] = t4.bg;
        }
        setCellFromCodepoint(e4, t4, i4, s4) {
          268435456 & s4.bg && (this._extendedAttrs[e4] = s4.extended), this._data[3 * e4 + 0] = t4 | i4 << 22, this._data[3 * e4 + 1] = s4.fg, this._data[3 * e4 + 2] = s4.bg;
        }
        addCodepointToCell(e4, t4, i4) {
          let s4 = this._data[3 * e4 + 0];
          2097152 & s4 ? this._combined[e4] += (0, o2.stringFromCodePoint)(t4) : 2097151 & s4 ? (this._combined[e4] = (0, o2.stringFromCodePoint)(2097151 & s4) + (0, o2.stringFromCodePoint)(t4), s4 &= -2097152, s4 |= 2097152) : s4 = t4 | 1 << 22, i4 && (s4 &= -12582913, s4 |= i4 << 22), this._data[3 * e4 + 0] = s4;
        }
        insertCells(e4, t4, i4) {
          if ((e4 %= this.length) && 2 === this.getWidth(e4 - 1) && this.setCellFromCodepoint(e4 - 1, 0, 1, i4), t4 < this.length - e4) {
            const s4 = new r2.CellData();
            for (let i5 = this.length - e4 - t4 - 1; i5 >= 0; --i5) this.setCell(e4 + t4 + i5, this.loadCell(e4 + i5, s4));
            for (let s5 = 0; s5 < t4; ++s5) this.setCell(e4 + s5, i4);
          } else for (let t5 = e4; t5 < this.length; ++t5) this.setCell(t5, i4);
          2 === this.getWidth(this.length - 1) && this.setCellFromCodepoint(this.length - 1, 0, 1, i4);
        }
        deleteCells(e4, t4, i4) {
          if (e4 %= this.length, t4 < this.length - e4) {
            const s4 = new r2.CellData();
            for (let i5 = 0; i5 < this.length - e4 - t4; ++i5) this.setCell(e4 + i5, this.loadCell(e4 + t4 + i5, s4));
            for (let e5 = this.length - t4; e5 < this.length; ++e5) this.setCell(e5, i4);
          } else for (let t5 = e4; t5 < this.length; ++t5) this.setCell(t5, i4);
          e4 && 2 === this.getWidth(e4 - 1) && this.setCellFromCodepoint(e4 - 1, 0, 1, i4), 0 !== this.getWidth(e4) || this.hasContent(e4) || this.setCellFromCodepoint(e4, 0, 1, i4);
        }
        replaceCells(e4, t4, i4, s4 = false) {
          if (s4) for (e4 && 2 === this.getWidth(e4 - 1) && !this.isProtected(e4 - 1) && this.setCellFromCodepoint(e4 - 1, 0, 1, i4), t4 < this.length && 2 === this.getWidth(t4 - 1) && !this.isProtected(t4) && this.setCellFromCodepoint(t4, 0, 1, i4); e4 < t4 && e4 < this.length; ) this.isProtected(e4) || this.setCell(e4, i4), e4++;
          else for (e4 && 2 === this.getWidth(e4 - 1) && this.setCellFromCodepoint(e4 - 1, 0, 1, i4), t4 < this.length && 2 === this.getWidth(t4 - 1) && this.setCellFromCodepoint(t4, 0, 1, i4); e4 < t4 && e4 < this.length; ) this.setCell(e4++, i4);
        }
        resize(e4, t4) {
          if (e4 === this.length) return 4 * this._data.length * 2 < this._data.buffer.byteLength;
          const i4 = 3 * e4;
          if (e4 > this.length) {
            if (this._data.buffer.byteLength >= 4 * i4) this._data = new Uint32Array(this._data.buffer, 0, i4);
            else {
              const e5 = new Uint32Array(i4);
              e5.set(this._data), this._data = e5;
            }
            for (let i5 = this.length; i5 < e4; ++i5) this.setCell(i5, t4);
          } else {
            this._data = this._data.subarray(0, i4);
            const t5 = Object.keys(this._combined);
            for (let i5 = 0; i5 < t5.length; i5++) {
              const s5 = parseInt(t5[i5], 10);
              s5 >= e4 && delete this._combined[s5];
            }
            const s4 = Object.keys(this._extendedAttrs);
            for (let t6 = 0; t6 < s4.length; t6++) {
              const i5 = parseInt(s4[t6], 10);
              i5 >= e4 && delete this._extendedAttrs[i5];
            }
          }
          return this.length = e4, 4 * i4 * 2 < this._data.buffer.byteLength;
        }
        cleanupMemory() {
          if (4 * this._data.length * 2 < this._data.buffer.byteLength) {
            const e4 = new Uint32Array(this._data.length);
            return e4.set(this._data), this._data = e4, 1;
          }
          return 0;
        }
        fill(e4, t4 = false) {
          if (t4) for (let t5 = 0; t5 < this.length; ++t5) this.isProtected(t5) || this.setCell(t5, e4);
          else {
            this._combined = {}, this._extendedAttrs = {};
            for (let t5 = 0; t5 < this.length; ++t5) this.setCell(t5, e4);
          }
        }
        copyFrom(e4) {
          this.length !== e4.length ? this._data = new Uint32Array(e4._data) : this._data.set(e4._data), this.length = e4.length, this._combined = {};
          for (const t4 in e4._combined) this._combined[t4] = e4._combined[t4];
          this._extendedAttrs = {};
          for (const t4 in e4._extendedAttrs) this._extendedAttrs[t4] = e4._extendedAttrs[t4];
          this.isWrapped = e4.isWrapped;
        }
        clone() {
          const e4 = new h2(0);
          e4._data = new Uint32Array(this._data), e4.length = this.length;
          for (const t4 in this._combined) e4._combined[t4] = this._combined[t4];
          for (const t4 in this._extendedAttrs) e4._extendedAttrs[t4] = this._extendedAttrs[t4];
          return e4.isWrapped = this.isWrapped, e4;
        }
        getTrimmedLength() {
          for (let e4 = this.length - 1; e4 >= 0; --e4) if (4194303 & this._data[3 * e4 + 0]) return e4 + (this._data[3 * e4 + 0] >> 22);
          return 0;
        }
        getNoBgTrimmedLength() {
          for (let e4 = this.length - 1; e4 >= 0; --e4) if (4194303 & this._data[3 * e4 + 0] || 50331648 & this._data[3 * e4 + 2]) return e4 + (this._data[3 * e4 + 0] >> 22);
          return 0;
        }
        copyCellsFrom(e4, t4, i4, s4, r3) {
          const n3 = e4._data;
          if (r3) for (let r4 = s4 - 1; r4 >= 0; r4--) {
            for (let e5 = 0; e5 < 3; e5++) this._data[3 * (i4 + r4) + e5] = n3[3 * (t4 + r4) + e5];
            268435456 & n3[3 * (t4 + r4) + 2] && (this._extendedAttrs[i4 + r4] = e4._extendedAttrs[t4 + r4]);
          }
          else for (let r4 = 0; r4 < s4; r4++) {
            for (let e5 = 0; e5 < 3; e5++) this._data[3 * (i4 + r4) + e5] = n3[3 * (t4 + r4) + e5];
            268435456 & n3[3 * (t4 + r4) + 2] && (this._extendedAttrs[i4 + r4] = e4._extendedAttrs[t4 + r4]);
          }
          const o3 = Object.keys(e4._combined);
          for (let s5 = 0; s5 < o3.length; s5++) {
            const r4 = parseInt(o3[s5], 10);
            r4 >= t4 && (this._combined[r4 - t4 + i4] = e4._combined[r4]);
          }
        }
        translateToString(e4, t4, i4, s4) {
          t4 = t4 ?? 0, i4 = i4 ?? this.length, e4 && (i4 = Math.min(i4, this.getTrimmedLength())), s4 && (s4.length = 0);
          let r3 = "";
          for (; t4 < i4; ) {
            const e5 = this._data[3 * t4 + 0], i5 = 2097151 & e5, a3 = 2097152 & e5 ? this._combined[t4] : i5 ? (0, o2.stringFromCodePoint)(i5) : n2.WHITESPACE_CELL_CHAR;
            if (r3 += a3, s4) for (let e6 = 0; e6 < a3.length; ++e6) s4.push(t4);
            t4 += e5 >> 22 || 1;
          }
          return s4 && s4.push(t4), r3;
        }
      }
      t3.BufferLine = h2;
    }, 4841: (e3, t3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.getRangeLength = void 0, t3.getRangeLength = function(e4, t4) {
        if (e4.start.y > e4.end.y) throw new Error(`Buffer range end (${e4.end.x}, ${e4.end.y}) cannot be before start (${e4.start.x}, ${e4.start.y})`);
        return t4 * (e4.end.y - e4.start.y) + (e4.end.x - e4.start.x + 1);
      };
    }, 4634: (e3, t3) => {
      function i3(e4, t4, i4) {
        if (t4 === e4.length - 1) return e4[t4].getTrimmedLength();
        const s3 = !e4[t4].hasContent(i4 - 1) && 1 === e4[t4].getWidth(i4 - 1), r2 = 2 === e4[t4 + 1].getWidth(0);
        return s3 && r2 ? i4 - 1 : i4;
      }
      __name(i3, "i");
      Object.defineProperty(t3, "__esModule", { value: true }), t3.getWrappedLineTrimmedLength = t3.reflowSmallerGetNewLineLengths = t3.reflowLargerApplyNewLayout = t3.reflowLargerCreateNewLayout = t3.reflowLargerGetLinesToRemove = void 0, t3.reflowLargerGetLinesToRemove = function(e4, t4, s3, r2, n2) {
        const o2 = [];
        for (let a2 = 0; a2 < e4.length - 1; a2++) {
          let h2 = a2, c2 = e4.get(++h2);
          if (!c2.isWrapped) continue;
          const l2 = [e4.get(a2)];
          for (; h2 < e4.length && c2.isWrapped; ) l2.push(c2), c2 = e4.get(++h2);
          if (r2 >= a2 && r2 < h2) {
            a2 += l2.length - 1;
            continue;
          }
          let d2 = 0, _2 = i3(l2, d2, t4), u2 = 1, f2 = 0;
          for (; u2 < l2.length; ) {
            const e5 = i3(l2, u2, t4), r3 = e5 - f2, o3 = s3 - _2, a3 = Math.min(r3, o3);
            l2[d2].copyCellsFrom(l2[u2], f2, _2, a3, false), _2 += a3, _2 === s3 && (d2++, _2 = 0), f2 += a3, f2 === e5 && (u2++, f2 = 0), 0 === _2 && 0 !== d2 && 2 === l2[d2 - 1].getWidth(s3 - 1) && (l2[d2].copyCellsFrom(l2[d2 - 1], s3 - 1, _2++, 1, false), l2[d2 - 1].setCell(s3 - 1, n2));
          }
          l2[d2].replaceCells(_2, s3, n2);
          let v2 = 0;
          for (let e5 = l2.length - 1; e5 > 0 && (e5 > d2 || 0 === l2[e5].getTrimmedLength()); e5--) v2++;
          v2 > 0 && (o2.push(a2 + l2.length - v2), o2.push(v2)), a2 += l2.length - 1;
        }
        return o2;
      }, t3.reflowLargerCreateNewLayout = function(e4, t4) {
        const i4 = [];
        let s3 = 0, r2 = t4[s3], n2 = 0;
        for (let o2 = 0; o2 < e4.length; o2++) if (r2 === o2) {
          const i5 = t4[++s3];
          e4.onDeleteEmitter.fire({ index: o2 - n2, amount: i5 }), o2 += i5 - 1, n2 += i5, r2 = t4[++s3];
        } else i4.push(o2);
        return { layout: i4, countRemoved: n2 };
      }, t3.reflowLargerApplyNewLayout = function(e4, t4) {
        const i4 = [];
        for (let s3 = 0; s3 < t4.length; s3++) i4.push(e4.get(t4[s3]));
        for (let t5 = 0; t5 < i4.length; t5++) e4.set(t5, i4[t5]);
        e4.length = t4.length;
      }, t3.reflowSmallerGetNewLineLengths = function(e4, t4, s3) {
        const r2 = [], n2 = e4.map((s4, r3) => i3(e4, r3, t4)).reduce((e5, t5) => e5 + t5);
        let o2 = 0, a2 = 0, h2 = 0;
        for (; h2 < n2; ) {
          if (n2 - h2 < s3) {
            r2.push(n2 - h2);
            break;
          }
          o2 += s3;
          const c2 = i3(e4, a2, t4);
          o2 > c2 && (o2 -= c2, a2++);
          const l2 = 2 === e4[a2].getWidth(o2 - 1);
          l2 && o2--;
          const d2 = l2 ? s3 - 1 : s3;
          r2.push(d2), h2 += d2;
        }
        return r2;
      }, t3.getWrappedLineTrimmedLength = i3;
    }, 5295: (e3, t3, i3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.BufferSet = void 0;
      const s3 = i3(8460), r2 = i3(844), n2 = i3(9092);
      class o2 extends r2.Disposable {
        static {
          __name(this, "o");
        }
        constructor(e4, t4) {
          super(), this._optionsService = e4, this._bufferService = t4, this._onBufferActivate = this.register(new s3.EventEmitter()), this.onBufferActivate = this._onBufferActivate.event, this.reset(), this.register(this._optionsService.onSpecificOptionChange("scrollback", () => this.resize(this._bufferService.cols, this._bufferService.rows))), this.register(this._optionsService.onSpecificOptionChange("tabStopWidth", () => this.setupTabStops()));
        }
        reset() {
          this._normal = new n2.Buffer(true, this._optionsService, this._bufferService), this._normal.fillViewportRows(), this._alt = new n2.Buffer(false, this._optionsService, this._bufferService), this._activeBuffer = this._normal, this._onBufferActivate.fire({ activeBuffer: this._normal, inactiveBuffer: this._alt }), this.setupTabStops();
        }
        get alt() {
          return this._alt;
        }
        get active() {
          return this._activeBuffer;
        }
        get normal() {
          return this._normal;
        }
        activateNormalBuffer() {
          this._activeBuffer !== this._normal && (this._normal.x = this._alt.x, this._normal.y = this._alt.y, this._alt.clearAllMarkers(), this._alt.clear(), this._activeBuffer = this._normal, this._onBufferActivate.fire({ activeBuffer: this._normal, inactiveBuffer: this._alt }));
        }
        activateAltBuffer(e4) {
          this._activeBuffer !== this._alt && (this._alt.fillViewportRows(e4), this._alt.x = this._normal.x, this._alt.y = this._normal.y, this._activeBuffer = this._alt, this._onBufferActivate.fire({ activeBuffer: this._alt, inactiveBuffer: this._normal }));
        }
        resize(e4, t4) {
          this._normal.resize(e4, t4), this._alt.resize(e4, t4), this.setupTabStops(e4);
        }
        setupTabStops(e4) {
          this._normal.setupTabStops(e4), this._alt.setupTabStops(e4);
        }
      }
      t3.BufferSet = o2;
    }, 511: (e3, t3, i3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.CellData = void 0;
      const s3 = i3(482), r2 = i3(643), n2 = i3(3734);
      class o2 extends n2.AttributeData {
        static {
          __name(this, "o");
        }
        constructor() {
          super(...arguments), this.content = 0, this.fg = 0, this.bg = 0, this.extended = new n2.ExtendedAttrs(), this.combinedData = "";
        }
        static fromCharData(e4) {
          const t4 = new o2();
          return t4.setFromCharData(e4), t4;
        }
        isCombined() {
          return 2097152 & this.content;
        }
        getWidth() {
          return this.content >> 22;
        }
        getChars() {
          return 2097152 & this.content ? this.combinedData : 2097151 & this.content ? (0, s3.stringFromCodePoint)(2097151 & this.content) : "";
        }
        getCode() {
          return this.isCombined() ? this.combinedData.charCodeAt(this.combinedData.length - 1) : 2097151 & this.content;
        }
        setFromCharData(e4) {
          this.fg = e4[r2.CHAR_DATA_ATTR_INDEX], this.bg = 0;
          let t4 = false;
          if (e4[r2.CHAR_DATA_CHAR_INDEX].length > 2) t4 = true;
          else if (2 === e4[r2.CHAR_DATA_CHAR_INDEX].length) {
            const i4 = e4[r2.CHAR_DATA_CHAR_INDEX].charCodeAt(0);
            if (55296 <= i4 && i4 <= 56319) {
              const s4 = e4[r2.CHAR_DATA_CHAR_INDEX].charCodeAt(1);
              56320 <= s4 && s4 <= 57343 ? this.content = 1024 * (i4 - 55296) + s4 - 56320 + 65536 | e4[r2.CHAR_DATA_WIDTH_INDEX] << 22 : t4 = true;
            } else t4 = true;
          } else this.content = e4[r2.CHAR_DATA_CHAR_INDEX].charCodeAt(0) | e4[r2.CHAR_DATA_WIDTH_INDEX] << 22;
          t4 && (this.combinedData = e4[r2.CHAR_DATA_CHAR_INDEX], this.content = 2097152 | e4[r2.CHAR_DATA_WIDTH_INDEX] << 22);
        }
        getAsCharData() {
          return [this.fg, this.getChars(), this.getWidth(), this.getCode()];
        }
      }
      t3.CellData = o2;
    }, 643: (e3, t3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.WHITESPACE_CELL_CODE = t3.WHITESPACE_CELL_WIDTH = t3.WHITESPACE_CELL_CHAR = t3.NULL_CELL_CODE = t3.NULL_CELL_WIDTH = t3.NULL_CELL_CHAR = t3.CHAR_DATA_CODE_INDEX = t3.CHAR_DATA_WIDTH_INDEX = t3.CHAR_DATA_CHAR_INDEX = t3.CHAR_DATA_ATTR_INDEX = t3.DEFAULT_EXT = t3.DEFAULT_ATTR = t3.DEFAULT_COLOR = void 0, t3.DEFAULT_COLOR = 0, t3.DEFAULT_ATTR = 256 | t3.DEFAULT_COLOR << 9, t3.DEFAULT_EXT = 0, t3.CHAR_DATA_ATTR_INDEX = 0, t3.CHAR_DATA_CHAR_INDEX = 1, t3.CHAR_DATA_WIDTH_INDEX = 2, t3.CHAR_DATA_CODE_INDEX = 3, t3.NULL_CELL_CHAR = "", t3.NULL_CELL_WIDTH = 1, t3.NULL_CELL_CODE = 0, t3.WHITESPACE_CELL_CHAR = " ", t3.WHITESPACE_CELL_WIDTH = 1, t3.WHITESPACE_CELL_CODE = 32;
    }, 4863: (e3, t3, i3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.Marker = void 0;
      const s3 = i3(8460), r2 = i3(844);
      class n2 {
        static {
          __name(this, "n");
        }
        get id() {
          return this._id;
        }
        constructor(e4) {
          this.line = e4, this.isDisposed = false, this._disposables = [], this._id = n2._nextId++, this._onDispose = this.register(new s3.EventEmitter()), this.onDispose = this._onDispose.event;
        }
        dispose() {
          this.isDisposed || (this.isDisposed = true, this.line = -1, this._onDispose.fire(), (0, r2.disposeArray)(this._disposables), this._disposables.length = 0);
        }
        register(e4) {
          return this._disposables.push(e4), e4;
        }
      }
      t3.Marker = n2, n2._nextId = 1;
    }, 7116: (e3, t3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.DEFAULT_CHARSET = t3.CHARSETS = void 0, t3.CHARSETS = {}, t3.DEFAULT_CHARSET = t3.CHARSETS.B, t3.CHARSETS[0] = { "`": "◆", a: "▒", b: "␉", c: "␌", d: "␍", e: "␊", f: "°", g: "±", h: "␤", i: "␋", j: "┘", k: "┐", l: "┌", m: "└", n: "┼", o: "⎺", p: "⎻", q: "─", r: "⎼", s: "⎽", t: "├", u: "┤", v: "┴", w: "┬", x: "│", y: "≤", z: "≥", "{": "π", "|": "≠", "}": "£", "~": "·" }, t3.CHARSETS.A = { "#": "£" }, t3.CHARSETS.B = void 0, t3.CHARSETS[4] = { "#": "£", "@": "¾", "[": "ij", "\\": "½", "]": "|", "{": "¨", "|": "f", "}": "¼", "~": "´" }, t3.CHARSETS.C = t3.CHARSETS[5] = { "[": "Ä", "\\": "Ö", "]": "Å", "^": "Ü", "`": "é", "{": "ä", "|": "ö", "}": "å", "~": "ü" }, t3.CHARSETS.R = { "#": "£", "@": "à", "[": "°", "\\": "ç", "]": "§", "{": "é", "|": "ù", "}": "è", "~": "¨" }, t3.CHARSETS.Q = { "@": "à", "[": "â", "\\": "ç", "]": "ê", "^": "î", "`": "ô", "{": "é", "|": "ù", "}": "è", "~": "û" }, t3.CHARSETS.K = { "@": "§", "[": "Ä", "\\": "Ö", "]": "Ü", "{": "ä", "|": "ö", "}": "ü", "~": "ß" }, t3.CHARSETS.Y = { "#": "£", "@": "§", "[": "°", "\\": "ç", "]": "é", "`": "ù", "{": "à", "|": "ò", "}": "è", "~": "ì" }, t3.CHARSETS.E = t3.CHARSETS[6] = { "@": "Ä", "[": "Æ", "\\": "Ø", "]": "Å", "^": "Ü", "`": "ä", "{": "æ", "|": "ø", "}": "å", "~": "ü" }, t3.CHARSETS.Z = { "#": "£", "@": "§", "[": "¡", "\\": "Ñ", "]": "¿", "{": "°", "|": "ñ", "}": "ç" }, t3.CHARSETS.H = t3.CHARSETS[7] = { "@": "É", "[": "Ä", "\\": "Ö", "]": "Å", "^": "Ü", "`": "é", "{": "ä", "|": "ö", "}": "å", "~": "ü" }, t3.CHARSETS["="] = { "#": "ù", "@": "à", "[": "é", "\\": "ç", "]": "ê", "^": "î", _: "è", "`": "ô", "{": "ä", "|": "ö", "}": "ü", "~": "û" };
    }, 2584: (e3, t3) => {
      var i3, s3, r2;
      Object.defineProperty(t3, "__esModule", { value: true }), t3.C1_ESCAPED = t3.C1 = t3.C0 = void 0, function(e4) {
        e4.NUL = "\0", e4.SOH = "", e4.STX = "", e4.ETX = "", e4.EOT = "", e4.ENQ = "", e4.ACK = "", e4.BEL = "\x07", e4.BS = "\b", e4.HT = "	", e4.LF = "\n", e4.VT = "\v", e4.FF = "\f", e4.CR = "\r", e4.SO = "", e4.SI = "", e4.DLE = "", e4.DC1 = "", e4.DC2 = "", e4.DC3 = "", e4.DC4 = "", e4.NAK = "", e4.SYN = "", e4.ETB = "", e4.CAN = "", e4.EM = "", e4.SUB = "", e4.ESC = "\x1B", e4.FS = "", e4.GS = "", e4.RS = "", e4.US = "", e4.SP = " ", e4.DEL = "";
      }(i3 || (t3.C0 = i3 = {})), function(e4) {
        e4.PAD = "", e4.HOP = "", e4.BPH = "", e4.NBH = "", e4.IND = "", e4.NEL = "", e4.SSA = "", e4.ESA = "", e4.HTS = "", e4.HTJ = "", e4.VTS = "", e4.PLD = "", e4.PLU = "", e4.RI = "", e4.SS2 = "", e4.SS3 = "", e4.DCS = "", e4.PU1 = "", e4.PU2 = "", e4.STS = "", e4.CCH = "", e4.MW = "", e4.SPA = "", e4.EPA = "", e4.SOS = "", e4.SGCI = "", e4.SCI = "", e4.CSI = "", e4.ST = "", e4.OSC = "", e4.PM = "", e4.APC = "";
      }(s3 || (t3.C1 = s3 = {})), function(e4) {
        e4.ST = `${i3.ESC}\\`;
      }(r2 || (t3.C1_ESCAPED = r2 = {}));
    }, 7399: (e3, t3, i3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.evaluateKeyboardEvent = void 0;
      const s3 = i3(2584), r2 = { 48: ["0", ")"], 49: ["1", "!"], 50: ["2", "@"], 51: ["3", "#"], 52: ["4", "$"], 53: ["5", "%"], 54: ["6", "^"], 55: ["7", "&"], 56: ["8", "*"], 57: ["9", "("], 186: [";", ":"], 187: ["=", "+"], 188: [",", "<"], 189: ["-", "_"], 190: [".", ">"], 191: ["/", "?"], 192: ["`", "~"], 219: ["[", "{"], 220: ["\\", "|"], 221: ["]", "}"], 222: ["'", '"'] };
      t3.evaluateKeyboardEvent = function(e4, t4, i4, n2) {
        const o2 = { type: 0, cancel: false, key: void 0 }, a2 = (e4.shiftKey ? 1 : 0) | (e4.altKey ? 2 : 0) | (e4.ctrlKey ? 4 : 0) | (e4.metaKey ? 8 : 0);
        switch (e4.keyCode) {
          case 0:
            "UIKeyInputUpArrow" === e4.key ? o2.key = t4 ? s3.C0.ESC + "OA" : s3.C0.ESC + "[A" : "UIKeyInputLeftArrow" === e4.key ? o2.key = t4 ? s3.C0.ESC + "OD" : s3.C0.ESC + "[D" : "UIKeyInputRightArrow" === e4.key ? o2.key = t4 ? s3.C0.ESC + "OC" : s3.C0.ESC + "[C" : "UIKeyInputDownArrow" === e4.key && (o2.key = t4 ? s3.C0.ESC + "OB" : s3.C0.ESC + "[B");
            break;
          case 8:
            o2.key = e4.ctrlKey ? "\b" : s3.C0.DEL, e4.altKey && (o2.key = s3.C0.ESC + o2.key);
            break;
          case 9:
            if (e4.shiftKey) {
              o2.key = s3.C0.ESC + "[Z";
              break;
            }
            o2.key = s3.C0.HT, o2.cancel = true;
            break;
          case 13:
            o2.key = e4.altKey ? s3.C0.ESC + s3.C0.CR : s3.C0.CR, o2.cancel = true;
            break;
          case 27:
            o2.key = s3.C0.ESC, e4.altKey && (o2.key = s3.C0.ESC + s3.C0.ESC), o2.cancel = true;
            break;
          case 37:
            if (e4.metaKey) break;
            a2 ? (o2.key = s3.C0.ESC + "[1;" + (a2 + 1) + "D", o2.key === s3.C0.ESC + "[1;3D" && (o2.key = s3.C0.ESC + (i4 ? "b" : "[1;5D"))) : o2.key = t4 ? s3.C0.ESC + "OD" : s3.C0.ESC + "[D";
            break;
          case 39:
            if (e4.metaKey) break;
            a2 ? (o2.key = s3.C0.ESC + "[1;" + (a2 + 1) + "C", o2.key === s3.C0.ESC + "[1;3C" && (o2.key = s3.C0.ESC + (i4 ? "f" : "[1;5C"))) : o2.key = t4 ? s3.C0.ESC + "OC" : s3.C0.ESC + "[C";
            break;
          case 38:
            if (e4.metaKey) break;
            a2 ? (o2.key = s3.C0.ESC + "[1;" + (a2 + 1) + "A", i4 || o2.key !== s3.C0.ESC + "[1;3A" || (o2.key = s3.C0.ESC + "[1;5A")) : o2.key = t4 ? s3.C0.ESC + "OA" : s3.C0.ESC + "[A";
            break;
          case 40:
            if (e4.metaKey) break;
            a2 ? (o2.key = s3.C0.ESC + "[1;" + (a2 + 1) + "B", i4 || o2.key !== s3.C0.ESC + "[1;3B" || (o2.key = s3.C0.ESC + "[1;5B")) : o2.key = t4 ? s3.C0.ESC + "OB" : s3.C0.ESC + "[B";
            break;
          case 45:
            e4.shiftKey || e4.ctrlKey || (o2.key = s3.C0.ESC + "[2~");
            break;
          case 46:
            o2.key = a2 ? s3.C0.ESC + "[3;" + (a2 + 1) + "~" : s3.C0.ESC + "[3~";
            break;
          case 36:
            o2.key = a2 ? s3.C0.ESC + "[1;" + (a2 + 1) + "H" : t4 ? s3.C0.ESC + "OH" : s3.C0.ESC + "[H";
            break;
          case 35:
            o2.key = a2 ? s3.C0.ESC + "[1;" + (a2 + 1) + "F" : t4 ? s3.C0.ESC + "OF" : s3.C0.ESC + "[F";
            break;
          case 33:
            e4.shiftKey ? o2.type = 2 : e4.ctrlKey ? o2.key = s3.C0.ESC + "[5;" + (a2 + 1) + "~" : o2.key = s3.C0.ESC + "[5~";
            break;
          case 34:
            e4.shiftKey ? o2.type = 3 : e4.ctrlKey ? o2.key = s3.C0.ESC + "[6;" + (a2 + 1) + "~" : o2.key = s3.C0.ESC + "[6~";
            break;
          case 112:
            o2.key = a2 ? s3.C0.ESC + "[1;" + (a2 + 1) + "P" : s3.C0.ESC + "OP";
            break;
          case 113:
            o2.key = a2 ? s3.C0.ESC + "[1;" + (a2 + 1) + "Q" : s3.C0.ESC + "OQ";
            break;
          case 114:
            o2.key = a2 ? s3.C0.ESC + "[1;" + (a2 + 1) + "R" : s3.C0.ESC + "OR";
            break;
          case 115:
            o2.key = a2 ? s3.C0.ESC + "[1;" + (a2 + 1) + "S" : s3.C0.ESC + "OS";
            break;
          case 116:
            o2.key = a2 ? s3.C0.ESC + "[15;" + (a2 + 1) + "~" : s3.C0.ESC + "[15~";
            break;
          case 117:
            o2.key = a2 ? s3.C0.ESC + "[17;" + (a2 + 1) + "~" : s3.C0.ESC + "[17~";
            break;
          case 118:
            o2.key = a2 ? s3.C0.ESC + "[18;" + (a2 + 1) + "~" : s3.C0.ESC + "[18~";
            break;
          case 119:
            o2.key = a2 ? s3.C0.ESC + "[19;" + (a2 + 1) + "~" : s3.C0.ESC + "[19~";
            break;
          case 120:
            o2.key = a2 ? s3.C0.ESC + "[20;" + (a2 + 1) + "~" : s3.C0.ESC + "[20~";
            break;
          case 121:
            o2.key = a2 ? s3.C0.ESC + "[21;" + (a2 + 1) + "~" : s3.C0.ESC + "[21~";
            break;
          case 122:
            o2.key = a2 ? s3.C0.ESC + "[23;" + (a2 + 1) + "~" : s3.C0.ESC + "[23~";
            break;
          case 123:
            o2.key = a2 ? s3.C0.ESC + "[24;" + (a2 + 1) + "~" : s3.C0.ESC + "[24~";
            break;
          default:
            if (!e4.ctrlKey || e4.shiftKey || e4.altKey || e4.metaKey) if (i4 && !n2 || !e4.altKey || e4.metaKey) !i4 || e4.altKey || e4.ctrlKey || e4.shiftKey || !e4.metaKey ? e4.key && !e4.ctrlKey && !e4.altKey && !e4.metaKey && e4.keyCode >= 48 && 1 === e4.key.length ? o2.key = e4.key : e4.key && e4.ctrlKey && ("_" === e4.key && (o2.key = s3.C0.US), "@" === e4.key && (o2.key = s3.C0.NUL)) : 65 === e4.keyCode && (o2.type = 1);
            else {
              const t5 = r2[e4.keyCode], i5 = t5?.[e4.shiftKey ? 1 : 0];
              if (i5) o2.key = s3.C0.ESC + i5;
              else if (e4.keyCode >= 65 && e4.keyCode <= 90) {
                const t6 = e4.ctrlKey ? e4.keyCode - 64 : e4.keyCode + 32;
                let i6 = String.fromCharCode(t6);
                e4.shiftKey && (i6 = i6.toUpperCase()), o2.key = s3.C0.ESC + i6;
              } else if (32 === e4.keyCode) o2.key = s3.C0.ESC + (e4.ctrlKey ? s3.C0.NUL : " ");
              else if ("Dead" === e4.key && e4.code.startsWith("Key")) {
                let t6 = e4.code.slice(3, 4);
                e4.shiftKey || (t6 = t6.toLowerCase()), o2.key = s3.C0.ESC + t6, o2.cancel = true;
              }
            }
            else e4.keyCode >= 65 && e4.keyCode <= 90 ? o2.key = String.fromCharCode(e4.keyCode - 64) : 32 === e4.keyCode ? o2.key = s3.C0.NUL : e4.keyCode >= 51 && e4.keyCode <= 55 ? o2.key = String.fromCharCode(e4.keyCode - 51 + 27) : 56 === e4.keyCode ? o2.key = s3.C0.DEL : 219 === e4.keyCode ? o2.key = s3.C0.ESC : 220 === e4.keyCode ? o2.key = s3.C0.FS : 221 === e4.keyCode && (o2.key = s3.C0.GS);
        }
        return o2;
      };
    }, 482: (e3, t3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.Utf8ToUtf32 = t3.StringToUtf32 = t3.utf32ToString = t3.stringFromCodePoint = void 0, t3.stringFromCodePoint = function(e4) {
        return e4 > 65535 ? (e4 -= 65536, String.fromCharCode(55296 + (e4 >> 10)) + String.fromCharCode(e4 % 1024 + 56320)) : String.fromCharCode(e4);
      }, t3.utf32ToString = function(e4, t4 = 0, i3 = e4.length) {
        let s3 = "";
        for (let r2 = t4; r2 < i3; ++r2) {
          let t5 = e4[r2];
          t5 > 65535 ? (t5 -= 65536, s3 += String.fromCharCode(55296 + (t5 >> 10)) + String.fromCharCode(t5 % 1024 + 56320)) : s3 += String.fromCharCode(t5);
        }
        return s3;
      }, t3.StringToUtf32 = class {
        constructor() {
          this._interim = 0;
        }
        clear() {
          this._interim = 0;
        }
        decode(e4, t4) {
          const i3 = e4.length;
          if (!i3) return 0;
          let s3 = 0, r2 = 0;
          if (this._interim) {
            const i4 = e4.charCodeAt(r2++);
            56320 <= i4 && i4 <= 57343 ? t4[s3++] = 1024 * (this._interim - 55296) + i4 - 56320 + 65536 : (t4[s3++] = this._interim, t4[s3++] = i4), this._interim = 0;
          }
          for (let n2 = r2; n2 < i3; ++n2) {
            const r3 = e4.charCodeAt(n2);
            if (55296 <= r3 && r3 <= 56319) {
              if (++n2 >= i3) return this._interim = r3, s3;
              const o2 = e4.charCodeAt(n2);
              56320 <= o2 && o2 <= 57343 ? t4[s3++] = 1024 * (r3 - 55296) + o2 - 56320 + 65536 : (t4[s3++] = r3, t4[s3++] = o2);
            } else 65279 !== r3 && (t4[s3++] = r3);
          }
          return s3;
        }
      }, t3.Utf8ToUtf32 = class {
        constructor() {
          this.interim = new Uint8Array(3);
        }
        clear() {
          this.interim.fill(0);
        }
        decode(e4, t4) {
          const i3 = e4.length;
          if (!i3) return 0;
          let s3, r2, n2, o2, a2 = 0, h2 = 0, c2 = 0;
          if (this.interim[0]) {
            let s4 = false, r3 = this.interim[0];
            r3 &= 192 == (224 & r3) ? 31 : 224 == (240 & r3) ? 15 : 7;
            let n3, o3 = 0;
            for (; (n3 = 63 & this.interim[++o3]) && o3 < 4; ) r3 <<= 6, r3 |= n3;
            const h3 = 192 == (224 & this.interim[0]) ? 2 : 224 == (240 & this.interim[0]) ? 3 : 4, l3 = h3 - o3;
            for (; c2 < l3; ) {
              if (c2 >= i3) return 0;
              if (n3 = e4[c2++], 128 != (192 & n3)) {
                c2--, s4 = true;
                break;
              }
              this.interim[o3++] = n3, r3 <<= 6, r3 |= 63 & n3;
            }
            s4 || (2 === h3 ? r3 < 128 ? c2-- : t4[a2++] = r3 : 3 === h3 ? r3 < 2048 || r3 >= 55296 && r3 <= 57343 || 65279 === r3 || (t4[a2++] = r3) : r3 < 65536 || r3 > 1114111 || (t4[a2++] = r3)), this.interim.fill(0);
          }
          const l2 = i3 - 4;
          let d2 = c2;
          for (; d2 < i3; ) {
            for (; !(!(d2 < l2) || 128 & (s3 = e4[d2]) || 128 & (r2 = e4[d2 + 1]) || 128 & (n2 = e4[d2 + 2]) || 128 & (o2 = e4[d2 + 3])); ) t4[a2++] = s3, t4[a2++] = r2, t4[a2++] = n2, t4[a2++] = o2, d2 += 4;
            if (s3 = e4[d2++], s3 < 128) t4[a2++] = s3;
            else if (192 == (224 & s3)) {
              if (d2 >= i3) return this.interim[0] = s3, a2;
              if (r2 = e4[d2++], 128 != (192 & r2)) {
                d2--;
                continue;
              }
              if (h2 = (31 & s3) << 6 | 63 & r2, h2 < 128) {
                d2--;
                continue;
              }
              t4[a2++] = h2;
            } else if (224 == (240 & s3)) {
              if (d2 >= i3) return this.interim[0] = s3, a2;
              if (r2 = e4[d2++], 128 != (192 & r2)) {
                d2--;
                continue;
              }
              if (d2 >= i3) return this.interim[0] = s3, this.interim[1] = r2, a2;
              if (n2 = e4[d2++], 128 != (192 & n2)) {
                d2--;
                continue;
              }
              if (h2 = (15 & s3) << 12 | (63 & r2) << 6 | 63 & n2, h2 < 2048 || h2 >= 55296 && h2 <= 57343 || 65279 === h2) continue;
              t4[a2++] = h2;
            } else if (240 == (248 & s3)) {
              if (d2 >= i3) return this.interim[0] = s3, a2;
              if (r2 = e4[d2++], 128 != (192 & r2)) {
                d2--;
                continue;
              }
              if (d2 >= i3) return this.interim[0] = s3, this.interim[1] = r2, a2;
              if (n2 = e4[d2++], 128 != (192 & n2)) {
                d2--;
                continue;
              }
              if (d2 >= i3) return this.interim[0] = s3, this.interim[1] = r2, this.interim[2] = n2, a2;
              if (o2 = e4[d2++], 128 != (192 & o2)) {
                d2--;
                continue;
              }
              if (h2 = (7 & s3) << 18 | (63 & r2) << 12 | (63 & n2) << 6 | 63 & o2, h2 < 65536 || h2 > 1114111) continue;
              t4[a2++] = h2;
            }
          }
          return a2;
        }
      };
    }, 225: (e3, t3, i3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.UnicodeV6 = void 0;
      const s3 = i3(1480), r2 = [[768, 879], [1155, 1158], [1160, 1161], [1425, 1469], [1471, 1471], [1473, 1474], [1476, 1477], [1479, 1479], [1536, 1539], [1552, 1557], [1611, 1630], [1648, 1648], [1750, 1764], [1767, 1768], [1770, 1773], [1807, 1807], [1809, 1809], [1840, 1866], [1958, 1968], [2027, 2035], [2305, 2306], [2364, 2364], [2369, 2376], [2381, 2381], [2385, 2388], [2402, 2403], [2433, 2433], [2492, 2492], [2497, 2500], [2509, 2509], [2530, 2531], [2561, 2562], [2620, 2620], [2625, 2626], [2631, 2632], [2635, 2637], [2672, 2673], [2689, 2690], [2748, 2748], [2753, 2757], [2759, 2760], [2765, 2765], [2786, 2787], [2817, 2817], [2876, 2876], [2879, 2879], [2881, 2883], [2893, 2893], [2902, 2902], [2946, 2946], [3008, 3008], [3021, 3021], [3134, 3136], [3142, 3144], [3146, 3149], [3157, 3158], [3260, 3260], [3263, 3263], [3270, 3270], [3276, 3277], [3298, 3299], [3393, 3395], [3405, 3405], [3530, 3530], [3538, 3540], [3542, 3542], [3633, 3633], [3636, 3642], [3655, 3662], [3761, 3761], [3764, 3769], [3771, 3772], [3784, 3789], [3864, 3865], [3893, 3893], [3895, 3895], [3897, 3897], [3953, 3966], [3968, 3972], [3974, 3975], [3984, 3991], [3993, 4028], [4038, 4038], [4141, 4144], [4146, 4146], [4150, 4151], [4153, 4153], [4184, 4185], [4448, 4607], [4959, 4959], [5906, 5908], [5938, 5940], [5970, 5971], [6002, 6003], [6068, 6069], [6071, 6077], [6086, 6086], [6089, 6099], [6109, 6109], [6155, 6157], [6313, 6313], [6432, 6434], [6439, 6440], [6450, 6450], [6457, 6459], [6679, 6680], [6912, 6915], [6964, 6964], [6966, 6970], [6972, 6972], [6978, 6978], [7019, 7027], [7616, 7626], [7678, 7679], [8203, 8207], [8234, 8238], [8288, 8291], [8298, 8303], [8400, 8431], [12330, 12335], [12441, 12442], [43014, 43014], [43019, 43019], [43045, 43046], [64286, 64286], [65024, 65039], [65056, 65059], [65279, 65279], [65529, 65531]], n2 = [[68097, 68099], [68101, 68102], [68108, 68111], [68152, 68154], [68159, 68159], [119143, 119145], [119155, 119170], [119173, 119179], [119210, 119213], [119362, 119364], [917505, 917505], [917536, 917631], [917760, 917999]];
      let o2;
      t3.UnicodeV6 = class {
        constructor() {
          if (this.version = "6", !o2) {
            o2 = new Uint8Array(65536), o2.fill(1), o2[0] = 0, o2.fill(0, 1, 32), o2.fill(0, 127, 160), o2.fill(2, 4352, 4448), o2[9001] = 2, o2[9002] = 2, o2.fill(2, 11904, 42192), o2[12351] = 1, o2.fill(2, 44032, 55204), o2.fill(2, 63744, 64256), o2.fill(2, 65040, 65050), o2.fill(2, 65072, 65136), o2.fill(2, 65280, 65377), o2.fill(2, 65504, 65511);
            for (let e4 = 0; e4 < r2.length; ++e4) o2.fill(0, r2[e4][0], r2[e4][1] + 1);
          }
        }
        wcwidth(e4) {
          return e4 < 32 ? 0 : e4 < 127 ? 1 : e4 < 65536 ? o2[e4] : function(e5, t4) {
            let i4, s4 = 0, r3 = t4.length - 1;
            if (e5 < t4[0][0] || e5 > t4[r3][1]) return false;
            for (; r3 >= s4; ) if (i4 = s4 + r3 >> 1, e5 > t4[i4][1]) s4 = i4 + 1;
            else {
              if (!(e5 < t4[i4][0])) return true;
              r3 = i4 - 1;
            }
            return false;
          }(e4, n2) ? 0 : e4 >= 131072 && e4 <= 196605 || e4 >= 196608 && e4 <= 262141 ? 2 : 1;
        }
        charProperties(e4, t4) {
          let i4 = this.wcwidth(e4), r3 = 0 === i4 && 0 !== t4;
          if (r3) {
            const e5 = s3.UnicodeService.extractWidth(t4);
            0 === e5 ? r3 = false : e5 > i4 && (i4 = e5);
          }
          return s3.UnicodeService.createPropertyValue(0, i4, r3);
        }
      };
    }, 5981: (e3, t3, i3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.WriteBuffer = void 0;
      const s3 = i3(8460), r2 = i3(844);
      class n2 extends r2.Disposable {
        static {
          __name(this, "n");
        }
        constructor(e4) {
          super(), this._action = e4, this._writeBuffer = [], this._callbacks = [], this._pendingData = 0, this._bufferOffset = 0, this._isSyncWriting = false, this._syncCalls = 0, this._didUserInput = false, this._onWriteParsed = this.register(new s3.EventEmitter()), this.onWriteParsed = this._onWriteParsed.event;
        }
        handleUserInput() {
          this._didUserInput = true;
        }
        writeSync(e4, t4) {
          if (void 0 !== t4 && this._syncCalls > t4) return void (this._syncCalls = 0);
          if (this._pendingData += e4.length, this._writeBuffer.push(e4), this._callbacks.push(void 0), this._syncCalls++, this._isSyncWriting) return;
          let i4;
          for (this._isSyncWriting = true; i4 = this._writeBuffer.shift(); ) {
            this._action(i4);
            const e5 = this._callbacks.shift();
            e5 && e5();
          }
          this._pendingData = 0, this._bufferOffset = 2147483647, this._isSyncWriting = false, this._syncCalls = 0;
        }
        write(e4, t4) {
          if (this._pendingData > 5e7) throw new Error("write data discarded, use flow control to avoid losing data");
          if (!this._writeBuffer.length) {
            if (this._bufferOffset = 0, this._didUserInput) return this._didUserInput = false, this._pendingData += e4.length, this._writeBuffer.push(e4), this._callbacks.push(t4), void this._innerWrite();
            setTimeout(() => this._innerWrite());
          }
          this._pendingData += e4.length, this._writeBuffer.push(e4), this._callbacks.push(t4);
        }
        _innerWrite(e4 = 0, t4 = true) {
          const i4 = e4 || Date.now();
          for (; this._writeBuffer.length > this._bufferOffset; ) {
            const e5 = this._writeBuffer[this._bufferOffset], s4 = this._action(e5, t4);
            if (s4) {
              const e6 = /* @__PURE__ */ __name((e7) => Date.now() - i4 >= 12 ? setTimeout(() => this._innerWrite(0, e7)) : this._innerWrite(i4, e7), "e");
              return void s4.catch((e7) => (queueMicrotask(() => {
                throw e7;
              }), Promise.resolve(false))).then(e6);
            }
            const r3 = this._callbacks[this._bufferOffset];
            if (r3 && r3(), this._bufferOffset++, this._pendingData -= e5.length, Date.now() - i4 >= 12) break;
          }
          this._writeBuffer.length > this._bufferOffset ? (this._bufferOffset > 50 && (this._writeBuffer = this._writeBuffer.slice(this._bufferOffset), this._callbacks = this._callbacks.slice(this._bufferOffset), this._bufferOffset = 0), setTimeout(() => this._innerWrite())) : (this._writeBuffer.length = 0, this._callbacks.length = 0, this._pendingData = 0, this._bufferOffset = 0), this._onWriteParsed.fire();
        }
      }
      t3.WriteBuffer = n2;
    }, 5941: (e3, t3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.toRgbString = t3.parseColor = void 0;
      const i3 = /^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/, s3 = /^[\da-f]+$/;
      function r2(e4, t4) {
        const i4 = e4.toString(16), s4 = i4.length < 2 ? "0" + i4 : i4;
        switch (t4) {
          case 4:
            return i4[0];
          case 8:
            return s4;
          case 12:
            return (s4 + s4).slice(0, 3);
          default:
            return s4 + s4;
        }
      }
      __name(r2, "r");
      t3.parseColor = function(e4) {
        if (!e4) return;
        let t4 = e4.toLowerCase();
        if (0 === t4.indexOf("rgb:")) {
          t4 = t4.slice(4);
          const e5 = i3.exec(t4);
          if (e5) {
            const t5 = e5[1] ? 15 : e5[4] ? 255 : e5[7] ? 4095 : 65535;
            return [Math.round(parseInt(e5[1] || e5[4] || e5[7] || e5[10], 16) / t5 * 255), Math.round(parseInt(e5[2] || e5[5] || e5[8] || e5[11], 16) / t5 * 255), Math.round(parseInt(e5[3] || e5[6] || e5[9] || e5[12], 16) / t5 * 255)];
          }
        } else if (0 === t4.indexOf("#") && (t4 = t4.slice(1), s3.exec(t4) && [3, 6, 9, 12].includes(t4.length))) {
          const e5 = t4.length / 3, i4 = [0, 0, 0];
          for (let s4 = 0; s4 < 3; ++s4) {
            const r3 = parseInt(t4.slice(e5 * s4, e5 * s4 + e5), 16);
            i4[s4] = 1 === e5 ? r3 << 4 : 2 === e5 ? r3 : 3 === e5 ? r3 >> 4 : r3 >> 8;
          }
          return i4;
        }
      }, t3.toRgbString = function(e4, t4 = 16) {
        const [i4, s4, n2] = e4;
        return `rgb:${r2(i4, t4)}/${r2(s4, t4)}/${r2(n2, t4)}`;
      };
    }, 5770: (e3, t3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.PAYLOAD_LIMIT = void 0, t3.PAYLOAD_LIMIT = 1e7;
    }, 6351: (e3, t3, i3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.DcsHandler = t3.DcsParser = void 0;
      const s3 = i3(482), r2 = i3(8742), n2 = i3(5770), o2 = [];
      t3.DcsParser = class {
        constructor() {
          this._handlers = /* @__PURE__ */ Object.create(null), this._active = o2, this._ident = 0, this._handlerFb = () => {
          }, this._stack = { paused: false, loopPosition: 0, fallThrough: false };
        }
        dispose() {
          this._handlers = /* @__PURE__ */ Object.create(null), this._handlerFb = () => {
          }, this._active = o2;
        }
        registerHandler(e4, t4) {
          void 0 === this._handlers[e4] && (this._handlers[e4] = []);
          const i4 = this._handlers[e4];
          return i4.push(t4), { dispose: /* @__PURE__ */ __name(() => {
            const e5 = i4.indexOf(t4);
            -1 !== e5 && i4.splice(e5, 1);
          }, "dispose") };
        }
        clearHandler(e4) {
          this._handlers[e4] && delete this._handlers[e4];
        }
        setHandlerFallback(e4) {
          this._handlerFb = e4;
        }
        reset() {
          if (this._active.length) for (let e4 = this._stack.paused ? this._stack.loopPosition - 1 : this._active.length - 1; e4 >= 0; --e4) this._active[e4].unhook(false);
          this._stack.paused = false, this._active = o2, this._ident = 0;
        }
        hook(e4, t4) {
          if (this.reset(), this._ident = e4, this._active = this._handlers[e4] || o2, this._active.length) for (let e5 = this._active.length - 1; e5 >= 0; e5--) this._active[e5].hook(t4);
          else this._handlerFb(this._ident, "HOOK", t4);
        }
        put(e4, t4, i4) {
          if (this._active.length) for (let s4 = this._active.length - 1; s4 >= 0; s4--) this._active[s4].put(e4, t4, i4);
          else this._handlerFb(this._ident, "PUT", (0, s3.utf32ToString)(e4, t4, i4));
        }
        unhook(e4, t4 = true) {
          if (this._active.length) {
            let i4 = false, s4 = this._active.length - 1, r3 = false;
            if (this._stack.paused && (s4 = this._stack.loopPosition - 1, i4 = t4, r3 = this._stack.fallThrough, this._stack.paused = false), !r3 && false === i4) {
              for (; s4 >= 0 && (i4 = this._active[s4].unhook(e4), true !== i4); s4--) if (i4 instanceof Promise) return this._stack.paused = true, this._stack.loopPosition = s4, this._stack.fallThrough = false, i4;
              s4--;
            }
            for (; s4 >= 0; s4--) if (i4 = this._active[s4].unhook(false), i4 instanceof Promise) return this._stack.paused = true, this._stack.loopPosition = s4, this._stack.fallThrough = true, i4;
          } else this._handlerFb(this._ident, "UNHOOK", e4);
          this._active = o2, this._ident = 0;
        }
      };
      const a2 = new r2.Params();
      a2.addParam(0), t3.DcsHandler = class {
        constructor(e4) {
          this._handler = e4, this._data = "", this._params = a2, this._hitLimit = false;
        }
        hook(e4) {
          this._params = e4.length > 1 || e4.params[0] ? e4.clone() : a2, this._data = "", this._hitLimit = false;
        }
        put(e4, t4, i4) {
          this._hitLimit || (this._data += (0, s3.utf32ToString)(e4, t4, i4), this._data.length > n2.PAYLOAD_LIMIT && (this._data = "", this._hitLimit = true));
        }
        unhook(e4) {
          let t4 = false;
          if (this._hitLimit) t4 = false;
          else if (e4 && (t4 = this._handler(this._data, this._params), t4 instanceof Promise)) return t4.then((e5) => (this._params = a2, this._data = "", this._hitLimit = false, e5));
          return this._params = a2, this._data = "", this._hitLimit = false, t4;
        }
      };
    }, 2015: (e3, t3, i3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.EscapeSequenceParser = t3.VT500_TRANSITION_TABLE = t3.TransitionTable = void 0;
      const s3 = i3(844), r2 = i3(8742), n2 = i3(6242), o2 = i3(6351);
      class a2 {
        static {
          __name(this, "a");
        }
        constructor(e4) {
          this.table = new Uint8Array(e4);
        }
        setDefault(e4, t4) {
          this.table.fill(e4 << 4 | t4);
        }
        add(e4, t4, i4, s4) {
          this.table[t4 << 8 | e4] = i4 << 4 | s4;
        }
        addMany(e4, t4, i4, s4) {
          for (let r3 = 0; r3 < e4.length; r3++) this.table[t4 << 8 | e4[r3]] = i4 << 4 | s4;
        }
      }
      t3.TransitionTable = a2;
      const h2 = 160;
      t3.VT500_TRANSITION_TABLE = function() {
        const e4 = new a2(4095), t4 = Array.apply(null, Array(256)).map((e5, t5) => t5), i4 = /* @__PURE__ */ __name((e5, i5) => t4.slice(e5, i5), "i"), s4 = i4(32, 127), r3 = i4(0, 24);
        r3.push(25), r3.push.apply(r3, i4(28, 32));
        const n3 = i4(0, 14);
        let o3;
        for (o3 in e4.setDefault(1, 0), e4.addMany(s4, 0, 2, 0), n3) e4.addMany([24, 26, 153, 154], o3, 3, 0), e4.addMany(i4(128, 144), o3, 3, 0), e4.addMany(i4(144, 152), o3, 3, 0), e4.add(156, o3, 0, 0), e4.add(27, o3, 11, 1), e4.add(157, o3, 4, 8), e4.addMany([152, 158, 159], o3, 0, 7), e4.add(155, o3, 11, 3), e4.add(144, o3, 11, 9);
        return e4.addMany(r3, 0, 3, 0), e4.addMany(r3, 1, 3, 1), e4.add(127, 1, 0, 1), e4.addMany(r3, 8, 0, 8), e4.addMany(r3, 3, 3, 3), e4.add(127, 3, 0, 3), e4.addMany(r3, 4, 3, 4), e4.add(127, 4, 0, 4), e4.addMany(r3, 6, 3, 6), e4.addMany(r3, 5, 3, 5), e4.add(127, 5, 0, 5), e4.addMany(r3, 2, 3, 2), e4.add(127, 2, 0, 2), e4.add(93, 1, 4, 8), e4.addMany(s4, 8, 5, 8), e4.add(127, 8, 5, 8), e4.addMany([156, 27, 24, 26, 7], 8, 6, 0), e4.addMany(i4(28, 32), 8, 0, 8), e4.addMany([88, 94, 95], 1, 0, 7), e4.addMany(s4, 7, 0, 7), e4.addMany(r3, 7, 0, 7), e4.add(156, 7, 0, 0), e4.add(127, 7, 0, 7), e4.add(91, 1, 11, 3), e4.addMany(i4(64, 127), 3, 7, 0), e4.addMany(i4(48, 60), 3, 8, 4), e4.addMany([60, 61, 62, 63], 3, 9, 4), e4.addMany(i4(48, 60), 4, 8, 4), e4.addMany(i4(64, 127), 4, 7, 0), e4.addMany([60, 61, 62, 63], 4, 0, 6), e4.addMany(i4(32, 64), 6, 0, 6), e4.add(127, 6, 0, 6), e4.addMany(i4(64, 127), 6, 0, 0), e4.addMany(i4(32, 48), 3, 9, 5), e4.addMany(i4(32, 48), 5, 9, 5), e4.addMany(i4(48, 64), 5, 0, 6), e4.addMany(i4(64, 127), 5, 7, 0), e4.addMany(i4(32, 48), 4, 9, 5), e4.addMany(i4(32, 48), 1, 9, 2), e4.addMany(i4(32, 48), 2, 9, 2), e4.addMany(i4(48, 127), 2, 10, 0), e4.addMany(i4(48, 80), 1, 10, 0), e4.addMany(i4(81, 88), 1, 10, 0), e4.addMany([89, 90, 92], 1, 10, 0), e4.addMany(i4(96, 127), 1, 10, 0), e4.add(80, 1, 11, 9), e4.addMany(r3, 9, 0, 9), e4.add(127, 9, 0, 9), e4.addMany(i4(28, 32), 9, 0, 9), e4.addMany(i4(32, 48), 9, 9, 12), e4.addMany(i4(48, 60), 9, 8, 10), e4.addMany([60, 61, 62, 63], 9, 9, 10), e4.addMany(r3, 11, 0, 11), e4.addMany(i4(32, 128), 11, 0, 11), e4.addMany(i4(28, 32), 11, 0, 11), e4.addMany(r3, 10, 0, 10), e4.add(127, 10, 0, 10), e4.addMany(i4(28, 32), 10, 0, 10), e4.addMany(i4(48, 60), 10, 8, 10), e4.addMany([60, 61, 62, 63], 10, 0, 11), e4.addMany(i4(32, 48), 10, 9, 12), e4.addMany(r3, 12, 0, 12), e4.add(127, 12, 0, 12), e4.addMany(i4(28, 32), 12, 0, 12), e4.addMany(i4(32, 48), 12, 9, 12), e4.addMany(i4(48, 64), 12, 0, 11), e4.addMany(i4(64, 127), 12, 12, 13), e4.addMany(i4(64, 127), 10, 12, 13), e4.addMany(i4(64, 127), 9, 12, 13), e4.addMany(r3, 13, 13, 13), e4.addMany(s4, 13, 13, 13), e4.add(127, 13, 0, 13), e4.addMany([27, 156, 24, 26], 13, 14, 0), e4.add(h2, 0, 2, 0), e4.add(h2, 8, 5, 8), e4.add(h2, 6, 0, 6), e4.add(h2, 11, 0, 11), e4.add(h2, 13, 13, 13), e4;
      }();
      class c2 extends s3.Disposable {
        static {
          __name(this, "c");
        }
        constructor(e4 = t3.VT500_TRANSITION_TABLE) {
          super(), this._transitions = e4, this._parseStack = { state: 0, handlers: [], handlerPos: 0, transition: 0, chunkPos: 0 }, this.initialState = 0, this.currentState = this.initialState, this._params = new r2.Params(), this._params.addParam(0), this._collect = 0, this.precedingJoinState = 0, this._printHandlerFb = (e5, t4, i4) => {
          }, this._executeHandlerFb = (e5) => {
          }, this._csiHandlerFb = (e5, t4) => {
          }, this._escHandlerFb = (e5) => {
          }, this._errorHandlerFb = (e5) => e5, this._printHandler = this._printHandlerFb, this._executeHandlers = /* @__PURE__ */ Object.create(null), this._csiHandlers = /* @__PURE__ */ Object.create(null), this._escHandlers = /* @__PURE__ */ Object.create(null), this.register((0, s3.toDisposable)(() => {
            this._csiHandlers = /* @__PURE__ */ Object.create(null), this._executeHandlers = /* @__PURE__ */ Object.create(null), this._escHandlers = /* @__PURE__ */ Object.create(null);
          })), this._oscParser = this.register(new n2.OscParser()), this._dcsParser = this.register(new o2.DcsParser()), this._errorHandler = this._errorHandlerFb, this.registerEscHandler({ final: "\\" }, () => true);
        }
        _identifier(e4, t4 = [64, 126]) {
          let i4 = 0;
          if (e4.prefix) {
            if (e4.prefix.length > 1) throw new Error("only one byte as prefix supported");
            if (i4 = e4.prefix.charCodeAt(0), i4 && 60 > i4 || i4 > 63) throw new Error("prefix must be in range 0x3c .. 0x3f");
          }
          if (e4.intermediates) {
            if (e4.intermediates.length > 2) throw new Error("only two bytes as intermediates are supported");
            for (let t5 = 0; t5 < e4.intermediates.length; ++t5) {
              const s5 = e4.intermediates.charCodeAt(t5);
              if (32 > s5 || s5 > 47) throw new Error("intermediate must be in range 0x20 .. 0x2f");
              i4 <<= 8, i4 |= s5;
            }
          }
          if (1 !== e4.final.length) throw new Error("final must be a single byte");
          const s4 = e4.final.charCodeAt(0);
          if (t4[0] > s4 || s4 > t4[1]) throw new Error(`final must be in range ${t4[0]} .. ${t4[1]}`);
          return i4 <<= 8, i4 |= s4, i4;
        }
        identToString(e4) {
          const t4 = [];
          for (; e4; ) t4.push(String.fromCharCode(255 & e4)), e4 >>= 8;
          return t4.reverse().join("");
        }
        setPrintHandler(e4) {
          this._printHandler = e4;
        }
        clearPrintHandler() {
          this._printHandler = this._printHandlerFb;
        }
        registerEscHandler(e4, t4) {
          const i4 = this._identifier(e4, [48, 126]);
          void 0 === this._escHandlers[i4] && (this._escHandlers[i4] = []);
          const s4 = this._escHandlers[i4];
          return s4.push(t4), { dispose: /* @__PURE__ */ __name(() => {
            const e5 = s4.indexOf(t4);
            -1 !== e5 && s4.splice(e5, 1);
          }, "dispose") };
        }
        clearEscHandler(e4) {
          this._escHandlers[this._identifier(e4, [48, 126])] && delete this._escHandlers[this._identifier(e4, [48, 126])];
        }
        setEscHandlerFallback(e4) {
          this._escHandlerFb = e4;
        }
        setExecuteHandler(e4, t4) {
          this._executeHandlers[e4.charCodeAt(0)] = t4;
        }
        clearExecuteHandler(e4) {
          this._executeHandlers[e4.charCodeAt(0)] && delete this._executeHandlers[e4.charCodeAt(0)];
        }
        setExecuteHandlerFallback(e4) {
          this._executeHandlerFb = e4;
        }
        registerCsiHandler(e4, t4) {
          const i4 = this._identifier(e4);
          void 0 === this._csiHandlers[i4] && (this._csiHandlers[i4] = []);
          const s4 = this._csiHandlers[i4];
          return s4.push(t4), { dispose: /* @__PURE__ */ __name(() => {
            const e5 = s4.indexOf(t4);
            -1 !== e5 && s4.splice(e5, 1);
          }, "dispose") };
        }
        clearCsiHandler(e4) {
          this._csiHandlers[this._identifier(e4)] && delete this._csiHandlers[this._identifier(e4)];
        }
        setCsiHandlerFallback(e4) {
          this._csiHandlerFb = e4;
        }
        registerDcsHandler(e4, t4) {
          return this._dcsParser.registerHandler(this._identifier(e4), t4);
        }
        clearDcsHandler(e4) {
          this._dcsParser.clearHandler(this._identifier(e4));
        }
        setDcsHandlerFallback(e4) {
          this._dcsParser.setHandlerFallback(e4);
        }
        registerOscHandler(e4, t4) {
          return this._oscParser.registerHandler(e4, t4);
        }
        clearOscHandler(e4) {
          this._oscParser.clearHandler(e4);
        }
        setOscHandlerFallback(e4) {
          this._oscParser.setHandlerFallback(e4);
        }
        setErrorHandler(e4) {
          this._errorHandler = e4;
        }
        clearErrorHandler() {
          this._errorHandler = this._errorHandlerFb;
        }
        reset() {
          this.currentState = this.initialState, this._oscParser.reset(), this._dcsParser.reset(), this._params.reset(), this._params.addParam(0), this._collect = 0, this.precedingJoinState = 0, 0 !== this._parseStack.state && (this._parseStack.state = 2, this._parseStack.handlers = []);
        }
        _preserveStack(e4, t4, i4, s4, r3) {
          this._parseStack.state = e4, this._parseStack.handlers = t4, this._parseStack.handlerPos = i4, this._parseStack.transition = s4, this._parseStack.chunkPos = r3;
        }
        parse(e4, t4, i4) {
          let s4, r3 = 0, n3 = 0, o3 = 0;
          if (this._parseStack.state) if (2 === this._parseStack.state) this._parseStack.state = 0, o3 = this._parseStack.chunkPos + 1;
          else {
            if (void 0 === i4 || 1 === this._parseStack.state) throw this._parseStack.state = 1, new Error("improper continuation due to previous async handler, giving up parsing");
            const t5 = this._parseStack.handlers;
            let n4 = this._parseStack.handlerPos - 1;
            switch (this._parseStack.state) {
              case 3:
                if (false === i4 && n4 > -1) {
                  for (; n4 >= 0 && (s4 = t5[n4](this._params), true !== s4); n4--) if (s4 instanceof Promise) return this._parseStack.handlerPos = n4, s4;
                }
                this._parseStack.handlers = [];
                break;
              case 4:
                if (false === i4 && n4 > -1) {
                  for (; n4 >= 0 && (s4 = t5[n4](), true !== s4); n4--) if (s4 instanceof Promise) return this._parseStack.handlerPos = n4, s4;
                }
                this._parseStack.handlers = [];
                break;
              case 6:
                if (r3 = e4[this._parseStack.chunkPos], s4 = this._dcsParser.unhook(24 !== r3 && 26 !== r3, i4), s4) return s4;
                27 === r3 && (this._parseStack.transition |= 1), this._params.reset(), this._params.addParam(0), this._collect = 0;
                break;
              case 5:
                if (r3 = e4[this._parseStack.chunkPos], s4 = this._oscParser.end(24 !== r3 && 26 !== r3, i4), s4) return s4;
                27 === r3 && (this._parseStack.transition |= 1), this._params.reset(), this._params.addParam(0), this._collect = 0;
            }
            this._parseStack.state = 0, o3 = this._parseStack.chunkPos + 1, this.precedingJoinState = 0, this.currentState = 15 & this._parseStack.transition;
          }
          for (let i5 = o3; i5 < t4; ++i5) {
            switch (r3 = e4[i5], n3 = this._transitions.table[this.currentState << 8 | (r3 < 160 ? r3 : h2)], n3 >> 4) {
              case 2:
                for (let s5 = i5 + 1; ; ++s5) {
                  if (s5 >= t4 || (r3 = e4[s5]) < 32 || r3 > 126 && r3 < h2) {
                    this._printHandler(e4, i5, s5), i5 = s5 - 1;
                    break;
                  }
                  if (++s5 >= t4 || (r3 = e4[s5]) < 32 || r3 > 126 && r3 < h2) {
                    this._printHandler(e4, i5, s5), i5 = s5 - 1;
                    break;
                  }
                  if (++s5 >= t4 || (r3 = e4[s5]) < 32 || r3 > 126 && r3 < h2) {
                    this._printHandler(e4, i5, s5), i5 = s5 - 1;
                    break;
                  }
                  if (++s5 >= t4 || (r3 = e4[s5]) < 32 || r3 > 126 && r3 < h2) {
                    this._printHandler(e4, i5, s5), i5 = s5 - 1;
                    break;
                  }
                }
                break;
              case 3:
                this._executeHandlers[r3] ? this._executeHandlers[r3]() : this._executeHandlerFb(r3), this.precedingJoinState = 0;
                break;
              case 0:
                break;
              case 1:
                if (this._errorHandler({ position: i5, code: r3, currentState: this.currentState, collect: this._collect, params: this._params, abort: false }).abort) return;
                break;
              case 7:
                const o4 = this._csiHandlers[this._collect << 8 | r3];
                let a3 = o4 ? o4.length - 1 : -1;
                for (; a3 >= 0 && (s4 = o4[a3](this._params), true !== s4); a3--) if (s4 instanceof Promise) return this._preserveStack(3, o4, a3, n3, i5), s4;
                a3 < 0 && this._csiHandlerFb(this._collect << 8 | r3, this._params), this.precedingJoinState = 0;
                break;
              case 8:
                do {
                  switch (r3) {
                    case 59:
                      this._params.addParam(0);
                      break;
                    case 58:
                      this._params.addSubParam(-1);
                      break;
                    default:
                      this._params.addDigit(r3 - 48);
                  }
                } while (++i5 < t4 && (r3 = e4[i5]) > 47 && r3 < 60);
                i5--;
                break;
              case 9:
                this._collect <<= 8, this._collect |= r3;
                break;
              case 10:
                const c3 = this._escHandlers[this._collect << 8 | r3];
                let l2 = c3 ? c3.length - 1 : -1;
                for (; l2 >= 0 && (s4 = c3[l2](), true !== s4); l2--) if (s4 instanceof Promise) return this._preserveStack(4, c3, l2, n3, i5), s4;
                l2 < 0 && this._escHandlerFb(this._collect << 8 | r3), this.precedingJoinState = 0;
                break;
              case 11:
                this._params.reset(), this._params.addParam(0), this._collect = 0;
                break;
              case 12:
                this._dcsParser.hook(this._collect << 8 | r3, this._params);
                break;
              case 13:
                for (let s5 = i5 + 1; ; ++s5) if (s5 >= t4 || 24 === (r3 = e4[s5]) || 26 === r3 || 27 === r3 || r3 > 127 && r3 < h2) {
                  this._dcsParser.put(e4, i5, s5), i5 = s5 - 1;
                  break;
                }
                break;
              case 14:
                if (s4 = this._dcsParser.unhook(24 !== r3 && 26 !== r3), s4) return this._preserveStack(6, [], 0, n3, i5), s4;
                27 === r3 && (n3 |= 1), this._params.reset(), this._params.addParam(0), this._collect = 0, this.precedingJoinState = 0;
                break;
              case 4:
                this._oscParser.start();
                break;
              case 5:
                for (let s5 = i5 + 1; ; s5++) if (s5 >= t4 || (r3 = e4[s5]) < 32 || r3 > 127 && r3 < h2) {
                  this._oscParser.put(e4, i5, s5), i5 = s5 - 1;
                  break;
                }
                break;
              case 6:
                if (s4 = this._oscParser.end(24 !== r3 && 26 !== r3), s4) return this._preserveStack(5, [], 0, n3, i5), s4;
                27 === r3 && (n3 |= 1), this._params.reset(), this._params.addParam(0), this._collect = 0, this.precedingJoinState = 0;
            }
            this.currentState = 15 & n3;
          }
        }
      }
      t3.EscapeSequenceParser = c2;
    }, 6242: (e3, t3, i3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.OscHandler = t3.OscParser = void 0;
      const s3 = i3(5770), r2 = i3(482), n2 = [];
      t3.OscParser = class {
        constructor() {
          this._state = 0, this._active = n2, this._id = -1, this._handlers = /* @__PURE__ */ Object.create(null), this._handlerFb = () => {
          }, this._stack = { paused: false, loopPosition: 0, fallThrough: false };
        }
        registerHandler(e4, t4) {
          void 0 === this._handlers[e4] && (this._handlers[e4] = []);
          const i4 = this._handlers[e4];
          return i4.push(t4), { dispose: /* @__PURE__ */ __name(() => {
            const e5 = i4.indexOf(t4);
            -1 !== e5 && i4.splice(e5, 1);
          }, "dispose") };
        }
        clearHandler(e4) {
          this._handlers[e4] && delete this._handlers[e4];
        }
        setHandlerFallback(e4) {
          this._handlerFb = e4;
        }
        dispose() {
          this._handlers = /* @__PURE__ */ Object.create(null), this._handlerFb = () => {
          }, this._active = n2;
        }
        reset() {
          if (2 === this._state) for (let e4 = this._stack.paused ? this._stack.loopPosition - 1 : this._active.length - 1; e4 >= 0; --e4) this._active[e4].end(false);
          this._stack.paused = false, this._active = n2, this._id = -1, this._state = 0;
        }
        _start() {
          if (this._active = this._handlers[this._id] || n2, this._active.length) for (let e4 = this._active.length - 1; e4 >= 0; e4--) this._active[e4].start();
          else this._handlerFb(this._id, "START");
        }
        _put(e4, t4, i4) {
          if (this._active.length) for (let s4 = this._active.length - 1; s4 >= 0; s4--) this._active[s4].put(e4, t4, i4);
          else this._handlerFb(this._id, "PUT", (0, r2.utf32ToString)(e4, t4, i4));
        }
        start() {
          this.reset(), this._state = 1;
        }
        put(e4, t4, i4) {
          if (3 !== this._state) {
            if (1 === this._state) for (; t4 < i4; ) {
              const i5 = e4[t4++];
              if (59 === i5) {
                this._state = 2, this._start();
                break;
              }
              if (i5 < 48 || 57 < i5) return void (this._state = 3);
              -1 === this._id && (this._id = 0), this._id = 10 * this._id + i5 - 48;
            }
            2 === this._state && i4 - t4 > 0 && this._put(e4, t4, i4);
          }
        }
        end(e4, t4 = true) {
          if (0 !== this._state) {
            if (3 !== this._state) if (1 === this._state && this._start(), this._active.length) {
              let i4 = false, s4 = this._active.length - 1, r3 = false;
              if (this._stack.paused && (s4 = this._stack.loopPosition - 1, i4 = t4, r3 = this._stack.fallThrough, this._stack.paused = false), !r3 && false === i4) {
                for (; s4 >= 0 && (i4 = this._active[s4].end(e4), true !== i4); s4--) if (i4 instanceof Promise) return this._stack.paused = true, this._stack.loopPosition = s4, this._stack.fallThrough = false, i4;
                s4--;
              }
              for (; s4 >= 0; s4--) if (i4 = this._active[s4].end(false), i4 instanceof Promise) return this._stack.paused = true, this._stack.loopPosition = s4, this._stack.fallThrough = true, i4;
            } else this._handlerFb(this._id, "END", e4);
            this._active = n2, this._id = -1, this._state = 0;
          }
        }
      }, t3.OscHandler = class {
        constructor(e4) {
          this._handler = e4, this._data = "", this._hitLimit = false;
        }
        start() {
          this._data = "", this._hitLimit = false;
        }
        put(e4, t4, i4) {
          this._hitLimit || (this._data += (0, r2.utf32ToString)(e4, t4, i4), this._data.length > s3.PAYLOAD_LIMIT && (this._data = "", this._hitLimit = true));
        }
        end(e4) {
          let t4 = false;
          if (this._hitLimit) t4 = false;
          else if (e4 && (t4 = this._handler(this._data), t4 instanceof Promise)) return t4.then((e5) => (this._data = "", this._hitLimit = false, e5));
          return this._data = "", this._hitLimit = false, t4;
        }
      };
    }, 8742: (e3, t3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.Params = void 0;
      const i3 = 2147483647;
      class s3 {
        static {
          __name(this, "s");
        }
        static fromArray(e4) {
          const t4 = new s3();
          if (!e4.length) return t4;
          for (let i4 = Array.isArray(e4[0]) ? 1 : 0; i4 < e4.length; ++i4) {
            const s4 = e4[i4];
            if (Array.isArray(s4)) for (let e5 = 0; e5 < s4.length; ++e5) t4.addSubParam(s4[e5]);
            else t4.addParam(s4);
          }
          return t4;
        }
        constructor(e4 = 32, t4 = 32) {
          if (this.maxLength = e4, this.maxSubParamsLength = t4, t4 > 256) throw new Error("maxSubParamsLength must not be greater than 256");
          this.params = new Int32Array(e4), this.length = 0, this._subParams = new Int32Array(t4), this._subParamsLength = 0, this._subParamsIdx = new Uint16Array(e4), this._rejectDigits = false, this._rejectSubDigits = false, this._digitIsSub = false;
        }
        clone() {
          const e4 = new s3(this.maxLength, this.maxSubParamsLength);
          return e4.params.set(this.params), e4.length = this.length, e4._subParams.set(this._subParams), e4._subParamsLength = this._subParamsLength, e4._subParamsIdx.set(this._subParamsIdx), e4._rejectDigits = this._rejectDigits, e4._rejectSubDigits = this._rejectSubDigits, e4._digitIsSub = this._digitIsSub, e4;
        }
        toArray() {
          const e4 = [];
          for (let t4 = 0; t4 < this.length; ++t4) {
            e4.push(this.params[t4]);
            const i4 = this._subParamsIdx[t4] >> 8, s4 = 255 & this._subParamsIdx[t4];
            s4 - i4 > 0 && e4.push(Array.prototype.slice.call(this._subParams, i4, s4));
          }
          return e4;
        }
        reset() {
          this.length = 0, this._subParamsLength = 0, this._rejectDigits = false, this._rejectSubDigits = false, this._digitIsSub = false;
        }
        addParam(e4) {
          if (this._digitIsSub = false, this.length >= this.maxLength) this._rejectDigits = true;
          else {
            if (e4 < -1) throw new Error("values lesser than -1 are not allowed");
            this._subParamsIdx[this.length] = this._subParamsLength << 8 | this._subParamsLength, this.params[this.length++] = e4 > i3 ? i3 : e4;
          }
        }
        addSubParam(e4) {
          if (this._digitIsSub = true, this.length) if (this._rejectDigits || this._subParamsLength >= this.maxSubParamsLength) this._rejectSubDigits = true;
          else {
            if (e4 < -1) throw new Error("values lesser than -1 are not allowed");
            this._subParams[this._subParamsLength++] = e4 > i3 ? i3 : e4, this._subParamsIdx[this.length - 1]++;
          }
        }
        hasSubParams(e4) {
          return (255 & this._subParamsIdx[e4]) - (this._subParamsIdx[e4] >> 8) > 0;
        }
        getSubParams(e4) {
          const t4 = this._subParamsIdx[e4] >> 8, i4 = 255 & this._subParamsIdx[e4];
          return i4 - t4 > 0 ? this._subParams.subarray(t4, i4) : null;
        }
        getSubParamsAll() {
          const e4 = {};
          for (let t4 = 0; t4 < this.length; ++t4) {
            const i4 = this._subParamsIdx[t4] >> 8, s4 = 255 & this._subParamsIdx[t4];
            s4 - i4 > 0 && (e4[t4] = this._subParams.slice(i4, s4));
          }
          return e4;
        }
        addDigit(e4) {
          let t4;
          if (this._rejectDigits || !(t4 = this._digitIsSub ? this._subParamsLength : this.length) || this._digitIsSub && this._rejectSubDigits) return;
          const s4 = this._digitIsSub ? this._subParams : this.params, r2 = s4[t4 - 1];
          s4[t4 - 1] = ~r2 ? Math.min(10 * r2 + e4, i3) : e4;
        }
      }
      t3.Params = s3;
    }, 5741: (e3, t3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.AddonManager = void 0, t3.AddonManager = class {
        constructor() {
          this._addons = [];
        }
        dispose() {
          for (let e4 = this._addons.length - 1; e4 >= 0; e4--) this._addons[e4].instance.dispose();
        }
        loadAddon(e4, t4) {
          const i3 = { instance: t4, dispose: t4.dispose, isDisposed: false };
          this._addons.push(i3), t4.dispose = () => this._wrappedAddonDispose(i3), t4.activate(e4);
        }
        _wrappedAddonDispose(e4) {
          if (e4.isDisposed) return;
          let t4 = -1;
          for (let i3 = 0; i3 < this._addons.length; i3++) if (this._addons[i3] === e4) {
            t4 = i3;
            break;
          }
          if (-1 === t4) throw new Error("Could not dispose an addon that has not been loaded");
          e4.isDisposed = true, e4.dispose.apply(e4.instance), this._addons.splice(t4, 1);
        }
      };
    }, 8771: (e3, t3, i3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.BufferApiView = void 0;
      const s3 = i3(3785), r2 = i3(511);
      t3.BufferApiView = class {
        constructor(e4, t4) {
          this._buffer = e4, this.type = t4;
        }
        init(e4) {
          return this._buffer = e4, this;
        }
        get cursorY() {
          return this._buffer.y;
        }
        get cursorX() {
          return this._buffer.x;
        }
        get viewportY() {
          return this._buffer.ydisp;
        }
        get baseY() {
          return this._buffer.ybase;
        }
        get length() {
          return this._buffer.lines.length;
        }
        getLine(e4) {
          const t4 = this._buffer.lines.get(e4);
          if (t4) return new s3.BufferLineApiView(t4);
        }
        getNullCell() {
          return new r2.CellData();
        }
      };
    }, 3785: (e3, t3, i3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.BufferLineApiView = void 0;
      const s3 = i3(511);
      t3.BufferLineApiView = class {
        constructor(e4) {
          this._line = e4;
        }
        get isWrapped() {
          return this._line.isWrapped;
        }
        get length() {
          return this._line.length;
        }
        getCell(e4, t4) {
          if (!(e4 < 0 || e4 >= this._line.length)) return t4 ? (this._line.loadCell(e4, t4), t4) : this._line.loadCell(e4, new s3.CellData());
        }
        translateToString(e4, t4, i4) {
          return this._line.translateToString(e4, t4, i4);
        }
      };
    }, 8285: (e3, t3, i3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.BufferNamespaceApi = void 0;
      const s3 = i3(8771), r2 = i3(8460), n2 = i3(844);
      class o2 extends n2.Disposable {
        static {
          __name(this, "o");
        }
        constructor(e4) {
          super(), this._core = e4, this._onBufferChange = this.register(new r2.EventEmitter()), this.onBufferChange = this._onBufferChange.event, this._normal = new s3.BufferApiView(this._core.buffers.normal, "normal"), this._alternate = new s3.BufferApiView(this._core.buffers.alt, "alternate"), this._core.buffers.onBufferActivate(() => this._onBufferChange.fire(this.active));
        }
        get active() {
          if (this._core.buffers.active === this._core.buffers.normal) return this.normal;
          if (this._core.buffers.active === this._core.buffers.alt) return this.alternate;
          throw new Error("Active buffer is neither normal nor alternate");
        }
        get normal() {
          return this._normal.init(this._core.buffers.normal);
        }
        get alternate() {
          return this._alternate.init(this._core.buffers.alt);
        }
      }
      t3.BufferNamespaceApi = o2;
    }, 7975: (e3, t3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.ParserApi = void 0, t3.ParserApi = class {
        constructor(e4) {
          this._core = e4;
        }
        registerCsiHandler(e4, t4) {
          return this._core.registerCsiHandler(e4, (e5) => t4(e5.toArray()));
        }
        addCsiHandler(e4, t4) {
          return this.registerCsiHandler(e4, t4);
        }
        registerDcsHandler(e4, t4) {
          return this._core.registerDcsHandler(e4, (e5, i3) => t4(e5, i3.toArray()));
        }
        addDcsHandler(e4, t4) {
          return this.registerDcsHandler(e4, t4);
        }
        registerEscHandler(e4, t4) {
          return this._core.registerEscHandler(e4, t4);
        }
        addEscHandler(e4, t4) {
          return this.registerEscHandler(e4, t4);
        }
        registerOscHandler(e4, t4) {
          return this._core.registerOscHandler(e4, t4);
        }
        addOscHandler(e4, t4) {
          return this.registerOscHandler(e4, t4);
        }
      };
    }, 7090: (e3, t3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.UnicodeApi = void 0, t3.UnicodeApi = class {
        constructor(e4) {
          this._core = e4;
        }
        register(e4) {
          this._core.unicodeService.register(e4);
        }
        get versions() {
          return this._core.unicodeService.versions;
        }
        get activeVersion() {
          return this._core.unicodeService.activeVersion;
        }
        set activeVersion(e4) {
          this._core.unicodeService.activeVersion = e4;
        }
      };
    }, 744: function(e3, t3, i3) {
      var s3 = this && this.__decorate || function(e4, t4, i4, s4) {
        var r3, n3 = arguments.length, o3 = n3 < 3 ? t4 : null === s4 ? s4 = Object.getOwnPropertyDescriptor(t4, i4) : s4;
        if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) o3 = Reflect.decorate(e4, t4, i4, s4);
        else for (var a3 = e4.length - 1; a3 >= 0; a3--) (r3 = e4[a3]) && (o3 = (n3 < 3 ? r3(o3) : n3 > 3 ? r3(t4, i4, o3) : r3(t4, i4)) || o3);
        return n3 > 3 && o3 && Object.defineProperty(t4, i4, o3), o3;
      }, r2 = this && this.__param || function(e4, t4) {
        return function(i4, s4) {
          t4(i4, s4, e4);
        };
      };
      Object.defineProperty(t3, "__esModule", { value: true }), t3.BufferService = t3.MINIMUM_ROWS = t3.MINIMUM_COLS = void 0;
      const n2 = i3(8460), o2 = i3(844), a2 = i3(5295), h2 = i3(2585);
      t3.MINIMUM_COLS = 2, t3.MINIMUM_ROWS = 1;
      let c2 = t3.BufferService = class extends o2.Disposable {
        get buffer() {
          return this.buffers.active;
        }
        constructor(e4) {
          super(), this.isUserScrolling = false, this._onResize = this.register(new n2.EventEmitter()), this.onResize = this._onResize.event, this._onScroll = this.register(new n2.EventEmitter()), this.onScroll = this._onScroll.event, this.cols = Math.max(e4.rawOptions.cols || 0, t3.MINIMUM_COLS), this.rows = Math.max(e4.rawOptions.rows || 0, t3.MINIMUM_ROWS), this.buffers = this.register(new a2.BufferSet(e4, this));
        }
        resize(e4, t4) {
          this.cols = e4, this.rows = t4, this.buffers.resize(e4, t4), this._onResize.fire({ cols: e4, rows: t4 });
        }
        reset() {
          this.buffers.reset(), this.isUserScrolling = false;
        }
        scroll(e4, t4 = false) {
          const i4 = this.buffer;
          let s4;
          s4 = this._cachedBlankLine, s4 && s4.length === this.cols && s4.getFg(0) === e4.fg && s4.getBg(0) === e4.bg || (s4 = i4.getBlankLine(e4, t4), this._cachedBlankLine = s4), s4.isWrapped = t4;
          const r3 = i4.ybase + i4.scrollTop, n3 = i4.ybase + i4.scrollBottom;
          if (0 === i4.scrollTop) {
            const e5 = i4.lines.isFull;
            n3 === i4.lines.length - 1 ? e5 ? i4.lines.recycle().copyFrom(s4) : i4.lines.push(s4.clone()) : i4.lines.splice(n3 + 1, 0, s4.clone()), e5 ? this.isUserScrolling && (i4.ydisp = Math.max(i4.ydisp - 1, 0)) : (i4.ybase++, this.isUserScrolling || i4.ydisp++);
          } else {
            const e5 = n3 - r3 + 1;
            i4.lines.shiftElements(r3 + 1, e5 - 1, -1), i4.lines.set(n3, s4.clone());
          }
          this.isUserScrolling || (i4.ydisp = i4.ybase), this._onScroll.fire(i4.ydisp);
        }
        scrollLines(e4, t4, i4) {
          const s4 = this.buffer;
          if (e4 < 0) {
            if (0 === s4.ydisp) return;
            this.isUserScrolling = true;
          } else e4 + s4.ydisp >= s4.ybase && (this.isUserScrolling = false);
          const r3 = s4.ydisp;
          s4.ydisp = Math.max(Math.min(s4.ydisp + e4, s4.ybase), 0), r3 !== s4.ydisp && (t4 || this._onScroll.fire(s4.ydisp));
        }
      };
      t3.BufferService = c2 = s3([r2(0, h2.IOptionsService)], c2);
    }, 7994: (e3, t3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.CharsetService = void 0, t3.CharsetService = class {
        constructor() {
          this.glevel = 0, this._charsets = [];
        }
        reset() {
          this.charset = void 0, this._charsets = [], this.glevel = 0;
        }
        setgLevel(e4) {
          this.glevel = e4, this.charset = this._charsets[e4];
        }
        setgCharset(e4, t4) {
          this._charsets[e4] = t4, this.glevel === e4 && (this.charset = t4);
        }
      };
    }, 1753: function(e3, t3, i3) {
      var s3 = this && this.__decorate || function(e4, t4, i4, s4) {
        var r3, n3 = arguments.length, o3 = n3 < 3 ? t4 : null === s4 ? s4 = Object.getOwnPropertyDescriptor(t4, i4) : s4;
        if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) o3 = Reflect.decorate(e4, t4, i4, s4);
        else for (var a3 = e4.length - 1; a3 >= 0; a3--) (r3 = e4[a3]) && (o3 = (n3 < 3 ? r3(o3) : n3 > 3 ? r3(t4, i4, o3) : r3(t4, i4)) || o3);
        return n3 > 3 && o3 && Object.defineProperty(t4, i4, o3), o3;
      }, r2 = this && this.__param || function(e4, t4) {
        return function(i4, s4) {
          t4(i4, s4, e4);
        };
      };
      Object.defineProperty(t3, "__esModule", { value: true }), t3.CoreMouseService = void 0;
      const n2 = i3(2585), o2 = i3(8460), a2 = i3(844), h2 = { NONE: { events: 0, restrict: /* @__PURE__ */ __name(() => false, "restrict") }, X10: { events: 1, restrict: /* @__PURE__ */ __name((e4) => 4 !== e4.button && 1 === e4.action && (e4.ctrl = false, e4.alt = false, e4.shift = false, true), "restrict") }, VT200: { events: 19, restrict: /* @__PURE__ */ __name((e4) => 32 !== e4.action, "restrict") }, DRAG: { events: 23, restrict: /* @__PURE__ */ __name((e4) => 32 !== e4.action || 3 !== e4.button, "restrict") }, ANY: { events: 31, restrict: /* @__PURE__ */ __name((e4) => true, "restrict") } };
      function c2(e4, t4) {
        let i4 = (e4.ctrl ? 16 : 0) | (e4.shift ? 4 : 0) | (e4.alt ? 8 : 0);
        return 4 === e4.button ? (i4 |= 64, i4 |= e4.action) : (i4 |= 3 & e4.button, 4 & e4.button && (i4 |= 64), 8 & e4.button && (i4 |= 128), 32 === e4.action ? i4 |= 32 : 0 !== e4.action || t4 || (i4 |= 3)), i4;
      }
      __name(c2, "c");
      const l2 = String.fromCharCode, d2 = { DEFAULT: /* @__PURE__ */ __name((e4) => {
        const t4 = [c2(e4, false) + 32, e4.col + 32, e4.row + 32];
        return t4[0] > 255 || t4[1] > 255 || t4[2] > 255 ? "" : `\x1B[M${l2(t4[0])}${l2(t4[1])}${l2(t4[2])}`;
      }, "DEFAULT"), SGR: /* @__PURE__ */ __name((e4) => {
        const t4 = 0 === e4.action && 4 !== e4.button ? "m" : "M";
        return `\x1B[<${c2(e4, true)};${e4.col};${e4.row}${t4}`;
      }, "SGR"), SGR_PIXELS: /* @__PURE__ */ __name((e4) => {
        const t4 = 0 === e4.action && 4 !== e4.button ? "m" : "M";
        return `\x1B[<${c2(e4, true)};${e4.x};${e4.y}${t4}`;
      }, "SGR_PIXELS") };
      let _2 = t3.CoreMouseService = class extends a2.Disposable {
        constructor(e4, t4) {
          super(), this._bufferService = e4, this._coreService = t4, this._protocols = {}, this._encodings = {}, this._activeProtocol = "", this._activeEncoding = "", this._lastEvent = null, this._onProtocolChange = this.register(new o2.EventEmitter()), this.onProtocolChange = this._onProtocolChange.event;
          for (const e5 of Object.keys(h2)) this.addProtocol(e5, h2[e5]);
          for (const e5 of Object.keys(d2)) this.addEncoding(e5, d2[e5]);
          this.reset();
        }
        addProtocol(e4, t4) {
          this._protocols[e4] = t4;
        }
        addEncoding(e4, t4) {
          this._encodings[e4] = t4;
        }
        get activeProtocol() {
          return this._activeProtocol;
        }
        get areMouseEventsActive() {
          return 0 !== this._protocols[this._activeProtocol].events;
        }
        set activeProtocol(e4) {
          if (!this._protocols[e4]) throw new Error(`unknown protocol "${e4}"`);
          this._activeProtocol = e4, this._onProtocolChange.fire(this._protocols[e4].events);
        }
        get activeEncoding() {
          return this._activeEncoding;
        }
        set activeEncoding(e4) {
          if (!this._encodings[e4]) throw new Error(`unknown encoding "${e4}"`);
          this._activeEncoding = e4;
        }
        reset() {
          this.activeProtocol = "NONE", this.activeEncoding = "DEFAULT", this._lastEvent = null;
        }
        triggerMouseEvent(e4) {
          if (e4.col < 0 || e4.col >= this._bufferService.cols || e4.row < 0 || e4.row >= this._bufferService.rows) return false;
          if (4 === e4.button && 32 === e4.action) return false;
          if (3 === e4.button && 32 !== e4.action) return false;
          if (4 !== e4.button && (2 === e4.action || 3 === e4.action)) return false;
          if (e4.col++, e4.row++, 32 === e4.action && this._lastEvent && this._equalEvents(this._lastEvent, e4, "SGR_PIXELS" === this._activeEncoding)) return false;
          if (!this._protocols[this._activeProtocol].restrict(e4)) return false;
          const t4 = this._encodings[this._activeEncoding](e4);
          return t4 && ("DEFAULT" === this._activeEncoding ? this._coreService.triggerBinaryEvent(t4) : this._coreService.triggerDataEvent(t4, true)), this._lastEvent = e4, true;
        }
        explainEvents(e4) {
          return { down: !!(1 & e4), up: !!(2 & e4), drag: !!(4 & e4), move: !!(8 & e4), wheel: !!(16 & e4) };
        }
        _equalEvents(e4, t4, i4) {
          if (i4) {
            if (e4.x !== t4.x) return false;
            if (e4.y !== t4.y) return false;
          } else {
            if (e4.col !== t4.col) return false;
            if (e4.row !== t4.row) return false;
          }
          return e4.button === t4.button && e4.action === t4.action && e4.ctrl === t4.ctrl && e4.alt === t4.alt && e4.shift === t4.shift;
        }
      };
      t3.CoreMouseService = _2 = s3([r2(0, n2.IBufferService), r2(1, n2.ICoreService)], _2);
    }, 6975: function(e3, t3, i3) {
      var s3 = this && this.__decorate || function(e4, t4, i4, s4) {
        var r3, n3 = arguments.length, o3 = n3 < 3 ? t4 : null === s4 ? s4 = Object.getOwnPropertyDescriptor(t4, i4) : s4;
        if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) o3 = Reflect.decorate(e4, t4, i4, s4);
        else for (var a3 = e4.length - 1; a3 >= 0; a3--) (r3 = e4[a3]) && (o3 = (n3 < 3 ? r3(o3) : n3 > 3 ? r3(t4, i4, o3) : r3(t4, i4)) || o3);
        return n3 > 3 && o3 && Object.defineProperty(t4, i4, o3), o3;
      }, r2 = this && this.__param || function(e4, t4) {
        return function(i4, s4) {
          t4(i4, s4, e4);
        };
      };
      Object.defineProperty(t3, "__esModule", { value: true }), t3.CoreService = void 0;
      const n2 = i3(1439), o2 = i3(8460), a2 = i3(844), h2 = i3(2585), c2 = Object.freeze({ insertMode: false }), l2 = Object.freeze({ applicationCursorKeys: false, applicationKeypad: false, bracketedPasteMode: false, origin: false, reverseWraparound: false, sendFocus: false, wraparound: true });
      let d2 = t3.CoreService = class extends a2.Disposable {
        constructor(e4, t4, i4) {
          super(), this._bufferService = e4, this._logService = t4, this._optionsService = i4, this.isCursorInitialized = false, this.isCursorHidden = false, this._onData = this.register(new o2.EventEmitter()), this.onData = this._onData.event, this._onUserInput = this.register(new o2.EventEmitter()), this.onUserInput = this._onUserInput.event, this._onBinary = this.register(new o2.EventEmitter()), this.onBinary = this._onBinary.event, this._onRequestScrollToBottom = this.register(new o2.EventEmitter()), this.onRequestScrollToBottom = this._onRequestScrollToBottom.event, this.modes = (0, n2.clone)(c2), this.decPrivateModes = (0, n2.clone)(l2);
        }
        reset() {
          this.modes = (0, n2.clone)(c2), this.decPrivateModes = (0, n2.clone)(l2);
        }
        triggerDataEvent(e4, t4 = false) {
          if (this._optionsService.rawOptions.disableStdin) return;
          const i4 = this._bufferService.buffer;
          t4 && this._optionsService.rawOptions.scrollOnUserInput && i4.ybase !== i4.ydisp && this._onRequestScrollToBottom.fire(), t4 && this._onUserInput.fire(), this._logService.debug(`sending data "${e4}"`, () => e4.split("").map((e5) => e5.charCodeAt(0))), this._onData.fire(e4);
        }
        triggerBinaryEvent(e4) {
          this._optionsService.rawOptions.disableStdin || (this._logService.debug(`sending binary "${e4}"`, () => e4.split("").map((e5) => e5.charCodeAt(0))), this._onBinary.fire(e4));
        }
      };
      t3.CoreService = d2 = s3([r2(0, h2.IBufferService), r2(1, h2.ILogService), r2(2, h2.IOptionsService)], d2);
    }, 9074: (e3, t3, i3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.DecorationService = void 0;
      const s3 = i3(8055), r2 = i3(8460), n2 = i3(844), o2 = i3(6106);
      let a2 = 0, h2 = 0;
      class c2 extends n2.Disposable {
        static {
          __name(this, "c");
        }
        get decorations() {
          return this._decorations.values();
        }
        constructor() {
          super(), this._decorations = new o2.SortedList((e4) => e4?.marker.line), this._onDecorationRegistered = this.register(new r2.EventEmitter()), this.onDecorationRegistered = this._onDecorationRegistered.event, this._onDecorationRemoved = this.register(new r2.EventEmitter()), this.onDecorationRemoved = this._onDecorationRemoved.event, this.register((0, n2.toDisposable)(() => this.reset()));
        }
        registerDecoration(e4) {
          if (e4.marker.isDisposed) return;
          const t4 = new l2(e4);
          if (t4) {
            const e5 = t4.marker.onDispose(() => t4.dispose());
            t4.onDispose(() => {
              t4 && (this._decorations.delete(t4) && this._onDecorationRemoved.fire(t4), e5.dispose());
            }), this._decorations.insert(t4), this._onDecorationRegistered.fire(t4);
          }
          return t4;
        }
        reset() {
          for (const e4 of this._decorations.values()) e4.dispose();
          this._decorations.clear();
        }
        *getDecorationsAtCell(e4, t4, i4) {
          let s4 = 0, r3 = 0;
          for (const n3 of this._decorations.getKeyIterator(t4)) s4 = n3.options.x ?? 0, r3 = s4 + (n3.options.width ?? 1), e4 >= s4 && e4 < r3 && (!i4 || (n3.options.layer ?? "bottom") === i4) && (yield n3);
        }
        forEachDecorationAtCell(e4, t4, i4, s4) {
          this._decorations.forEachByKey(t4, (t5) => {
            a2 = t5.options.x ?? 0, h2 = a2 + (t5.options.width ?? 1), e4 >= a2 && e4 < h2 && (!i4 || (t5.options.layer ?? "bottom") === i4) && s4(t5);
          });
        }
      }
      t3.DecorationService = c2;
      class l2 extends n2.Disposable {
        static {
          __name(this, "l");
        }
        get isDisposed() {
          return this._isDisposed;
        }
        get backgroundColorRGB() {
          return null === this._cachedBg && (this.options.backgroundColor ? this._cachedBg = s3.css.toColor(this.options.backgroundColor) : this._cachedBg = void 0), this._cachedBg;
        }
        get foregroundColorRGB() {
          return null === this._cachedFg && (this.options.foregroundColor ? this._cachedFg = s3.css.toColor(this.options.foregroundColor) : this._cachedFg = void 0), this._cachedFg;
        }
        constructor(e4) {
          super(), this.options = e4, this.onRenderEmitter = this.register(new r2.EventEmitter()), this.onRender = this.onRenderEmitter.event, this._onDispose = this.register(new r2.EventEmitter()), this.onDispose = this._onDispose.event, this._cachedBg = null, this._cachedFg = null, this.marker = e4.marker, this.options.overviewRulerOptions && !this.options.overviewRulerOptions.position && (this.options.overviewRulerOptions.position = "full");
        }
        dispose() {
          this._onDispose.fire(), super.dispose();
        }
      }
    }, 4348: (e3, t3, i3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.InstantiationService = t3.ServiceCollection = void 0;
      const s3 = i3(2585), r2 = i3(8343);
      class n2 {
        static {
          __name(this, "n");
        }
        constructor(...e4) {
          this._entries = /* @__PURE__ */ new Map();
          for (const [t4, i4] of e4) this.set(t4, i4);
        }
        set(e4, t4) {
          const i4 = this._entries.get(e4);
          return this._entries.set(e4, t4), i4;
        }
        forEach(e4) {
          for (const [t4, i4] of this._entries.entries()) e4(t4, i4);
        }
        has(e4) {
          return this._entries.has(e4);
        }
        get(e4) {
          return this._entries.get(e4);
        }
      }
      t3.ServiceCollection = n2, t3.InstantiationService = class {
        constructor() {
          this._services = new n2(), this._services.set(s3.IInstantiationService, this);
        }
        setService(e4, t4) {
          this._services.set(e4, t4);
        }
        getService(e4) {
          return this._services.get(e4);
        }
        createInstance(e4, ...t4) {
          const i4 = (0, r2.getServiceDependencies)(e4).sort((e5, t5) => e5.index - t5.index), s4 = [];
          for (const t5 of i4) {
            const i5 = this._services.get(t5.id);
            if (!i5) throw new Error(`[createInstance] ${e4.name} depends on UNKNOWN service ${t5.id}.`);
            s4.push(i5);
          }
          const n3 = i4.length > 0 ? i4[0].index : t4.length;
          if (t4.length !== n3) throw new Error(`[createInstance] First service dependency of ${e4.name} at position ${n3 + 1} conflicts with ${t4.length} static arguments`);
          return new e4(...[...t4, ...s4]);
        }
      };
    }, 7866: function(e3, t3, i3) {
      var s3 = this && this.__decorate || function(e4, t4, i4, s4) {
        var r3, n3 = arguments.length, o3 = n3 < 3 ? t4 : null === s4 ? s4 = Object.getOwnPropertyDescriptor(t4, i4) : s4;
        if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) o3 = Reflect.decorate(e4, t4, i4, s4);
        else for (var a3 = e4.length - 1; a3 >= 0; a3--) (r3 = e4[a3]) && (o3 = (n3 < 3 ? r3(o3) : n3 > 3 ? r3(t4, i4, o3) : r3(t4, i4)) || o3);
        return n3 > 3 && o3 && Object.defineProperty(t4, i4, o3), o3;
      }, r2 = this && this.__param || function(e4, t4) {
        return function(i4, s4) {
          t4(i4, s4, e4);
        };
      };
      Object.defineProperty(t3, "__esModule", { value: true }), t3.traceCall = t3.setTraceLogger = t3.LogService = void 0;
      const n2 = i3(844), o2 = i3(2585), a2 = { trace: o2.LogLevelEnum.TRACE, debug: o2.LogLevelEnum.DEBUG, info: o2.LogLevelEnum.INFO, warn: o2.LogLevelEnum.WARN, error: o2.LogLevelEnum.ERROR, off: o2.LogLevelEnum.OFF };
      let h2, c2 = t3.LogService = class extends n2.Disposable {
        get logLevel() {
          return this._logLevel;
        }
        constructor(e4) {
          super(), this._optionsService = e4, this._logLevel = o2.LogLevelEnum.OFF, this._updateLogLevel(), this.register(this._optionsService.onSpecificOptionChange("logLevel", () => this._updateLogLevel())), h2 = this;
        }
        _updateLogLevel() {
          this._logLevel = a2[this._optionsService.rawOptions.logLevel];
        }
        _evalLazyOptionalParams(e4) {
          for (let t4 = 0; t4 < e4.length; t4++) "function" == typeof e4[t4] && (e4[t4] = e4[t4]());
        }
        _log(e4, t4, i4) {
          this._evalLazyOptionalParams(i4), e4.call(console, (this._optionsService.options.logger ? "" : "xterm.js: ") + t4, ...i4);
        }
        trace(e4, ...t4) {
          this._logLevel <= o2.LogLevelEnum.TRACE && this._log(this._optionsService.options.logger?.trace.bind(this._optionsService.options.logger) ?? console.log, e4, t4);
        }
        debug(e4, ...t4) {
          this._logLevel <= o2.LogLevelEnum.DEBUG && this._log(this._optionsService.options.logger?.debug.bind(this._optionsService.options.logger) ?? console.log, e4, t4);
        }
        info(e4, ...t4) {
          this._logLevel <= o2.LogLevelEnum.INFO && this._log(this._optionsService.options.logger?.info.bind(this._optionsService.options.logger) ?? console.info, e4, t4);
        }
        warn(e4, ...t4) {
          this._logLevel <= o2.LogLevelEnum.WARN && this._log(this._optionsService.options.logger?.warn.bind(this._optionsService.options.logger) ?? console.warn, e4, t4);
        }
        error(e4, ...t4) {
          this._logLevel <= o2.LogLevelEnum.ERROR && this._log(this._optionsService.options.logger?.error.bind(this._optionsService.options.logger) ?? console.error, e4, t4);
        }
      };
      t3.LogService = c2 = s3([r2(0, o2.IOptionsService)], c2), t3.setTraceLogger = function(e4) {
        h2 = e4;
      }, t3.traceCall = function(e4, t4, i4) {
        if ("function" != typeof i4.value) throw new Error("not supported");
        const s4 = i4.value;
        i4.value = function(...e5) {
          if (h2.logLevel !== o2.LogLevelEnum.TRACE) return s4.apply(this, e5);
          h2.trace(`GlyphRenderer#${s4.name}(${e5.map((e6) => JSON.stringify(e6)).join(", ")})`);
          const t5 = s4.apply(this, e5);
          return h2.trace(`GlyphRenderer#${s4.name} return`, t5), t5;
        };
      };
    }, 7302: (e3, t3, i3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.OptionsService = t3.DEFAULT_OPTIONS = void 0;
      const s3 = i3(8460), r2 = i3(844), n2 = i3(6114);
      t3.DEFAULT_OPTIONS = { cols: 80, rows: 24, cursorBlink: false, cursorStyle: "block", cursorWidth: 1, cursorInactiveStyle: "outline", customGlyphs: true, drawBoldTextInBrightColors: true, documentOverride: null, fastScrollModifier: "alt", fastScrollSensitivity: 5, fontFamily: "courier-new, courier, monospace", fontSize: 15, fontWeight: "normal", fontWeightBold: "bold", ignoreBracketedPasteMode: false, lineHeight: 1, letterSpacing: 0, linkHandler: null, logLevel: "info", logger: null, scrollback: 1e3, scrollOnUserInput: true, scrollSensitivity: 1, screenReaderMode: false, smoothScrollDuration: 0, macOptionIsMeta: false, macOptionClickForcesSelection: false, minimumContrastRatio: 1, disableStdin: false, allowProposedApi: false, allowTransparency: false, tabStopWidth: 8, theme: {}, rescaleOverlappingGlyphs: false, rightClickSelectsWord: n2.isMac, windowOptions: {}, windowsMode: false, windowsPty: {}, wordSeparator: " ()[]{}',\"`", altClickMovesCursor: true, convertEol: false, termName: "xterm", cancelEvents: false, overviewRulerWidth: 0 };
      const o2 = ["normal", "bold", "100", "200", "300", "400", "500", "600", "700", "800", "900"];
      class a2 extends r2.Disposable {
        static {
          __name(this, "a");
        }
        constructor(e4) {
          super(), this._onOptionChange = this.register(new s3.EventEmitter()), this.onOptionChange = this._onOptionChange.event;
          const i4 = { ...t3.DEFAULT_OPTIONS };
          for (const t4 in e4) if (t4 in i4) try {
            const s4 = e4[t4];
            i4[t4] = this._sanitizeAndValidateOption(t4, s4);
          } catch (e5) {
            console.error(e5);
          }
          this.rawOptions = i4, this.options = { ...i4 }, this._setupOptions(), this.register((0, r2.toDisposable)(() => {
            this.rawOptions.linkHandler = null, this.rawOptions.documentOverride = null;
          }));
        }
        onSpecificOptionChange(e4, t4) {
          return this.onOptionChange((i4) => {
            i4 === e4 && t4(this.rawOptions[e4]);
          });
        }
        onMultipleOptionChange(e4, t4) {
          return this.onOptionChange((i4) => {
            -1 !== e4.indexOf(i4) && t4();
          });
        }
        _setupOptions() {
          const e4 = /* @__PURE__ */ __name((e5) => {
            if (!(e5 in t3.DEFAULT_OPTIONS)) throw new Error(`No option with key "${e5}"`);
            return this.rawOptions[e5];
          }, "e"), i4 = /* @__PURE__ */ __name((e5, i5) => {
            if (!(e5 in t3.DEFAULT_OPTIONS)) throw new Error(`No option with key "${e5}"`);
            i5 = this._sanitizeAndValidateOption(e5, i5), this.rawOptions[e5] !== i5 && (this.rawOptions[e5] = i5, this._onOptionChange.fire(e5));
          }, "i");
          for (const t4 in this.rawOptions) {
            const s4 = { get: e4.bind(this, t4), set: i4.bind(this, t4) };
            Object.defineProperty(this.options, t4, s4);
          }
        }
        _sanitizeAndValidateOption(e4, i4) {
          switch (e4) {
            case "cursorStyle":
              if (i4 || (i4 = t3.DEFAULT_OPTIONS[e4]), !/* @__PURE__ */ function(e5) {
                return "block" === e5 || "underline" === e5 || "bar" === e5;
              }(i4)) throw new Error(`"${i4}" is not a valid value for ${e4}`);
              break;
            case "wordSeparator":
              i4 || (i4 = t3.DEFAULT_OPTIONS[e4]);
              break;
            case "fontWeight":
            case "fontWeightBold":
              if ("number" == typeof i4 && 1 <= i4 && i4 <= 1e3) break;
              i4 = o2.includes(i4) ? i4 : t3.DEFAULT_OPTIONS[e4];
              break;
            case "cursorWidth":
              i4 = Math.floor(i4);
            case "lineHeight":
            case "tabStopWidth":
              if (i4 < 1) throw new Error(`${e4} cannot be less than 1, value: ${i4}`);
              break;
            case "minimumContrastRatio":
              i4 = Math.max(1, Math.min(21, Math.round(10 * i4) / 10));
              break;
            case "scrollback":
              if ((i4 = Math.min(i4, 4294967295)) < 0) throw new Error(`${e4} cannot be less than 0, value: ${i4}`);
              break;
            case "fastScrollSensitivity":
            case "scrollSensitivity":
              if (i4 <= 0) throw new Error(`${e4} cannot be less than or equal to 0, value: ${i4}`);
              break;
            case "rows":
            case "cols":
              if (!i4 && 0 !== i4) throw new Error(`${e4} must be numeric, value: ${i4}`);
              break;
            case "windowsPty":
              i4 = i4 ?? {};
          }
          return i4;
        }
      }
      t3.OptionsService = a2;
    }, 2660: function(e3, t3, i3) {
      var s3 = this && this.__decorate || function(e4, t4, i4, s4) {
        var r3, n3 = arguments.length, o3 = n3 < 3 ? t4 : null === s4 ? s4 = Object.getOwnPropertyDescriptor(t4, i4) : s4;
        if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) o3 = Reflect.decorate(e4, t4, i4, s4);
        else for (var a2 = e4.length - 1; a2 >= 0; a2--) (r3 = e4[a2]) && (o3 = (n3 < 3 ? r3(o3) : n3 > 3 ? r3(t4, i4, o3) : r3(t4, i4)) || o3);
        return n3 > 3 && o3 && Object.defineProperty(t4, i4, o3), o3;
      }, r2 = this && this.__param || function(e4, t4) {
        return function(i4, s4) {
          t4(i4, s4, e4);
        };
      };
      Object.defineProperty(t3, "__esModule", { value: true }), t3.OscLinkService = void 0;
      const n2 = i3(2585);
      let o2 = t3.OscLinkService = class {
        constructor(e4) {
          this._bufferService = e4, this._nextId = 1, this._entriesWithId = /* @__PURE__ */ new Map(), this._dataByLinkId = /* @__PURE__ */ new Map();
        }
        registerLink(e4) {
          const t4 = this._bufferService.buffer;
          if (void 0 === e4.id) {
            const i5 = t4.addMarker(t4.ybase + t4.y), s5 = { data: e4, id: this._nextId++, lines: [i5] };
            return i5.onDispose(() => this._removeMarkerFromLink(s5, i5)), this._dataByLinkId.set(s5.id, s5), s5.id;
          }
          const i4 = e4, s4 = this._getEntryIdKey(i4), r3 = this._entriesWithId.get(s4);
          if (r3) return this.addLineToLink(r3.id, t4.ybase + t4.y), r3.id;
          const n3 = t4.addMarker(t4.ybase + t4.y), o3 = { id: this._nextId++, key: this._getEntryIdKey(i4), data: i4, lines: [n3] };
          return n3.onDispose(() => this._removeMarkerFromLink(o3, n3)), this._entriesWithId.set(o3.key, o3), this._dataByLinkId.set(o3.id, o3), o3.id;
        }
        addLineToLink(e4, t4) {
          const i4 = this._dataByLinkId.get(e4);
          if (i4 && i4.lines.every((e5) => e5.line !== t4)) {
            const e5 = this._bufferService.buffer.addMarker(t4);
            i4.lines.push(e5), e5.onDispose(() => this._removeMarkerFromLink(i4, e5));
          }
        }
        getLinkData(e4) {
          return this._dataByLinkId.get(e4)?.data;
        }
        _getEntryIdKey(e4) {
          return `${e4.id};;${e4.uri}`;
        }
        _removeMarkerFromLink(e4, t4) {
          const i4 = e4.lines.indexOf(t4);
          -1 !== i4 && (e4.lines.splice(i4, 1), 0 === e4.lines.length && (void 0 !== e4.data.id && this._entriesWithId.delete(e4.key), this._dataByLinkId.delete(e4.id)));
        }
      };
      t3.OscLinkService = o2 = s3([r2(0, n2.IBufferService)], o2);
    }, 8343: (e3, t3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.createDecorator = t3.getServiceDependencies = t3.serviceRegistry = void 0;
      const i3 = "di$target", s3 = "di$dependencies";
      t3.serviceRegistry = /* @__PURE__ */ new Map(), t3.getServiceDependencies = function(e4) {
        return e4[s3] || [];
      }, t3.createDecorator = function(e4) {
        if (t3.serviceRegistry.has(e4)) return t3.serviceRegistry.get(e4);
        const r2 = /* @__PURE__ */ __name(function(e5, t4, n2) {
          if (3 !== arguments.length) throw new Error("@IServiceName-decorator can only be used to decorate a parameter");
          !function(e6, t5, r3) {
            t5[i3] === t5 ? t5[s3].push({ id: e6, index: r3 }) : (t5[s3] = [{ id: e6, index: r3 }], t5[i3] = t5);
          }(r2, e5, n2);
        }, "r");
        return r2.toString = () => e4, t3.serviceRegistry.set(e4, r2), r2;
      };
    }, 2585: (e3, t3, i3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.IDecorationService = t3.IUnicodeService = t3.IOscLinkService = t3.IOptionsService = t3.ILogService = t3.LogLevelEnum = t3.IInstantiationService = t3.ICharsetService = t3.ICoreService = t3.ICoreMouseService = t3.IBufferService = void 0;
      const s3 = i3(8343);
      var r2;
      t3.IBufferService = (0, s3.createDecorator)("BufferService"), t3.ICoreMouseService = (0, s3.createDecorator)("CoreMouseService"), t3.ICoreService = (0, s3.createDecorator)("CoreService"), t3.ICharsetService = (0, s3.createDecorator)("CharsetService"), t3.IInstantiationService = (0, s3.createDecorator)("InstantiationService"), function(e4) {
        e4[e4.TRACE = 0] = "TRACE", e4[e4.DEBUG = 1] = "DEBUG", e4[e4.INFO = 2] = "INFO", e4[e4.WARN = 3] = "WARN", e4[e4.ERROR = 4] = "ERROR", e4[e4.OFF = 5] = "OFF";
      }(r2 || (t3.LogLevelEnum = r2 = {})), t3.ILogService = (0, s3.createDecorator)("LogService"), t3.IOptionsService = (0, s3.createDecorator)("OptionsService"), t3.IOscLinkService = (0, s3.createDecorator)("OscLinkService"), t3.IUnicodeService = (0, s3.createDecorator)("UnicodeService"), t3.IDecorationService = (0, s3.createDecorator)("DecorationService");
    }, 1480: (e3, t3, i3) => {
      Object.defineProperty(t3, "__esModule", { value: true }), t3.UnicodeService = void 0;
      const s3 = i3(8460), r2 = i3(225);
      class n2 {
        static {
          __name(this, "n");
        }
        static extractShouldJoin(e4) {
          return 0 != (1 & e4);
        }
        static extractWidth(e4) {
          return e4 >> 1 & 3;
        }
        static extractCharKind(e4) {
          return e4 >> 3;
        }
        static createPropertyValue(e4, t4, i4 = false) {
          return (16777215 & e4) << 3 | (3 & t4) << 1 | (i4 ? 1 : 0);
        }
        constructor() {
          this._providers = /* @__PURE__ */ Object.create(null), this._active = "", this._onChange = new s3.EventEmitter(), this.onChange = this._onChange.event;
          const e4 = new r2.UnicodeV6();
          this.register(e4), this._active = e4.version, this._activeProvider = e4;
        }
        dispose() {
          this._onChange.dispose();
        }
        get versions() {
          return Object.keys(this._providers);
        }
        get activeVersion() {
          return this._active;
        }
        set activeVersion(e4) {
          if (!this._providers[e4]) throw new Error(`unknown Unicode version "${e4}"`);
          this._active = e4, this._activeProvider = this._providers[e4], this._onChange.fire(e4);
        }
        register(e4) {
          this._providers[e4.version] = e4;
        }
        wcwidth(e4) {
          return this._activeProvider.wcwidth(e4);
        }
        getStringCellWidth(e4) {
          let t4 = 0, i4 = 0;
          const s4 = e4.length;
          for (let r3 = 0; r3 < s4; ++r3) {
            let o2 = e4.charCodeAt(r3);
            if (55296 <= o2 && o2 <= 56319) {
              if (++r3 >= s4) return t4 + this.wcwidth(o2);
              const i5 = e4.charCodeAt(r3);
              56320 <= i5 && i5 <= 57343 ? o2 = 1024 * (o2 - 55296) + i5 - 56320 + 65536 : t4 += this.wcwidth(i5);
            }
            const a2 = this.charProperties(o2, i4);
            let h2 = n2.extractWidth(a2);
            n2.extractShouldJoin(a2) && (h2 -= n2.extractWidth(i4)), t4 += h2, i4 = a2;
          }
          return t4;
        }
        charProperties(e4, t4) {
          return this._activeProvider.charProperties(e4, t4);
        }
      }
      t3.UnicodeService = n2;
    } }, t2 = {};
    function i2(s3) {
      var r2 = t2[s3];
      if (void 0 !== r2) return r2.exports;
      var n2 = t2[s3] = { exports: {} };
      return e2[s3].call(n2.exports, n2, n2.exports, i2), n2.exports;
    }
    __name(i2, "i");
    var s2 = {};
    return (() => {
      var e3 = s2;
      Object.defineProperty(e3, "__esModule", { value: true }), e3.Terminal = void 0;
      const t3 = i2(9042), r2 = i2(3236), n2 = i2(844), o2 = i2(5741), a2 = i2(8285), h2 = i2(7975), c2 = i2(7090), l2 = ["cols", "rows"];
      class d2 extends n2.Disposable {
        static {
          __name(this, "d");
        }
        constructor(e4) {
          super(), this._core = this.register(new r2.Terminal(e4)), this._addonManager = this.register(new o2.AddonManager()), this._publicOptions = { ...this._core.options };
          const t4 = /* @__PURE__ */ __name((e5) => this._core.options[e5], "t"), i3 = /* @__PURE__ */ __name((e5, t5) => {
            this._checkReadonlyOptions(e5), this._core.options[e5] = t5;
          }, "i");
          for (const e5 in this._core.options) {
            const s3 = { get: t4.bind(this, e5), set: i3.bind(this, e5) };
            Object.defineProperty(this._publicOptions, e5, s3);
          }
        }
        _checkReadonlyOptions(e4) {
          if (l2.includes(e4)) throw new Error(`Option "${e4}" can only be set in the constructor`);
        }
        _checkProposedApi() {
          if (!this._core.optionsService.rawOptions.allowProposedApi) throw new Error("You must set the allowProposedApi option to true to use proposed API");
        }
        get onBell() {
          return this._core.onBell;
        }
        get onBinary() {
          return this._core.onBinary;
        }
        get onCursorMove() {
          return this._core.onCursorMove;
        }
        get onData() {
          return this._core.onData;
        }
        get onKey() {
          return this._core.onKey;
        }
        get onLineFeed() {
          return this._core.onLineFeed;
        }
        get onRender() {
          return this._core.onRender;
        }
        get onResize() {
          return this._core.onResize;
        }
        get onScroll() {
          return this._core.onScroll;
        }
        get onSelectionChange() {
          return this._core.onSelectionChange;
        }
        get onTitleChange() {
          return this._core.onTitleChange;
        }
        get onWriteParsed() {
          return this._core.onWriteParsed;
        }
        get element() {
          return this._core.element;
        }
        get parser() {
          return this._parser || (this._parser = new h2.ParserApi(this._core)), this._parser;
        }
        get unicode() {
          return this._checkProposedApi(), new c2.UnicodeApi(this._core);
        }
        get textarea() {
          return this._core.textarea;
        }
        get rows() {
          return this._core.rows;
        }
        get cols() {
          return this._core.cols;
        }
        get buffer() {
          return this._buffer || (this._buffer = this.register(new a2.BufferNamespaceApi(this._core))), this._buffer;
        }
        get markers() {
          return this._checkProposedApi(), this._core.markers;
        }
        get modes() {
          const e4 = this._core.coreService.decPrivateModes;
          let t4 = "none";
          switch (this._core.coreMouseService.activeProtocol) {
            case "X10":
              t4 = "x10";
              break;
            case "VT200":
              t4 = "vt200";
              break;
            case "DRAG":
              t4 = "drag";
              break;
            case "ANY":
              t4 = "any";
          }
          return { applicationCursorKeysMode: e4.applicationCursorKeys, applicationKeypadMode: e4.applicationKeypad, bracketedPasteMode: e4.bracketedPasteMode, insertMode: this._core.coreService.modes.insertMode, mouseTrackingMode: t4, originMode: e4.origin, reverseWraparoundMode: e4.reverseWraparound, sendFocusMode: e4.sendFocus, wraparoundMode: e4.wraparound };
        }
        get options() {
          return this._publicOptions;
        }
        set options(e4) {
          for (const t4 in e4) this._publicOptions[t4] = e4[t4];
        }
        blur() {
          this._core.blur();
        }
        focus() {
          this._core.focus();
        }
        input(e4, t4 = true) {
          this._core.input(e4, t4);
        }
        resize(e4, t4) {
          this._verifyIntegers(e4, t4), this._core.resize(e4, t4);
        }
        open(e4) {
          this._core.open(e4);
        }
        attachCustomKeyEventHandler(e4) {
          this._core.attachCustomKeyEventHandler(e4);
        }
        attachCustomWheelEventHandler(e4) {
          this._core.attachCustomWheelEventHandler(e4);
        }
        registerLinkProvider(e4) {
          return this._core.registerLinkProvider(e4);
        }
        registerCharacterJoiner(e4) {
          return this._checkProposedApi(), this._core.registerCharacterJoiner(e4);
        }
        deregisterCharacterJoiner(e4) {
          this._checkProposedApi(), this._core.deregisterCharacterJoiner(e4);
        }
        registerMarker(e4 = 0) {
          return this._verifyIntegers(e4), this._core.registerMarker(e4);
        }
        registerDecoration(e4) {
          return this._checkProposedApi(), this._verifyPositiveIntegers(e4.x ?? 0, e4.width ?? 0, e4.height ?? 0), this._core.registerDecoration(e4);
        }
        hasSelection() {
          return this._core.hasSelection();
        }
        select(e4, t4, i3) {
          this._verifyIntegers(e4, t4, i3), this._core.select(e4, t4, i3);
        }
        getSelection() {
          return this._core.getSelection();
        }
        getSelectionPosition() {
          return this._core.getSelectionPosition();
        }
        clearSelection() {
          this._core.clearSelection();
        }
        selectAll() {
          this._core.selectAll();
        }
        selectLines(e4, t4) {
          this._verifyIntegers(e4, t4), this._core.selectLines(e4, t4);
        }
        dispose() {
          super.dispose();
        }
        scrollLines(e4) {
          this._verifyIntegers(e4), this._core.scrollLines(e4);
        }
        scrollPages(e4) {
          this._verifyIntegers(e4), this._core.scrollPages(e4);
        }
        scrollToTop() {
          this._core.scrollToTop();
        }
        scrollToBottom() {
          this._core.scrollToBottom();
        }
        scrollToLine(e4) {
          this._verifyIntegers(e4), this._core.scrollToLine(e4);
        }
        clear() {
          this._core.clear();
        }
        write(e4, t4) {
          this._core.write(e4, t4);
        }
        writeln(e4, t4) {
          this._core.write(e4), this._core.write("\r\n", t4);
        }
        paste(e4) {
          this._core.paste(e4);
        }
        refresh(e4, t4) {
          this._verifyIntegers(e4, t4), this._core.refresh(e4, t4);
        }
        reset() {
          this._core.reset();
        }
        clearTextureAtlas() {
          this._core.clearTextureAtlas();
        }
        loadAddon(e4) {
          this._addonManager.loadAddon(this, e4);
        }
        static get strings() {
          return t3;
        }
        _verifyIntegers(...e4) {
          for (const t4 of e4) if (t4 === 1 / 0 || isNaN(t4) || t4 % 1 != 0) throw new Error("This API only accepts integers");
        }
        _verifyPositiveIntegers(...e4) {
          for (const t4 of e4) if (t4 && (t4 === 1 / 0 || isNaN(t4) || t4 % 1 != 0 || t4 < 0)) throw new Error("This API only accepts positive integers");
        }
      }
      e3.Terminal = d2;
    })(), s2;
  })());
})(xterm$2, xterm$2.exports);
var xtermExports = xterm$2.exports;
const xterm$1 = /* @__PURE__ */ getDefaultExportFromCjs(xtermExports);
function useTerminal(element) {
  const fitAddon = new addonFitExports.FitAddon();
  const terminal = markRaw(
    new xtermExports.Terminal({
      convertEol: true
    })
  );
  terminal.loadAddon(fitAddon);
  terminal.attachCustomKeyEventHandler((event) => {
    if (event.type === "keydown" && (event.ctrlKey || event.metaKey) && (event.key === "c" && terminal.hasSelection() || event.key === "v")) {
      return false;
    }
    return true;
  });
  onMounted(async () => {
    if (element.value) {
      terminal.open(element.value);
    }
  });
  onUnmounted(() => {
    terminal.dispose();
  });
  return {
    terminal,
    useAutoSize({
      root: root2,
      autoRows = true,
      autoCols = true,
      minCols = Number.NEGATIVE_INFINITY,
      minRows = Number.NEGATIVE_INFINITY,
      onResize
    }) {
      const ensureValidRows = /* @__PURE__ */ __name((rows) => {
        if (rows == null || isNaN(rows)) {
          return (root2.value?.clientHeight ?? 80) / 20;
        }
        return rows;
      }, "ensureValidRows");
      const ensureValidCols = /* @__PURE__ */ __name((cols) => {
        if (cols == null || isNaN(cols)) {
          return (root2.value?.clientWidth ?? 80) / 8;
        }
        return cols;
      }, "ensureValidCols");
      const resize = /* @__PURE__ */ __name(() => {
        const dims = fitAddon.proposeDimensions();
        terminal.resize(
          Math.max(
            autoCols ? ensureValidCols(dims?.cols) : terminal.cols,
            minCols
          ),
          Math.max(
            autoRows ? ensureValidRows(dims?.rows) : terminal.rows,
            minRows
          )
        );
        onResize?.();
      }, "resize");
      const resizeObserver = new ResizeObserver(lodashExports.debounce(resize, 25));
      onMounted(async () => {
        if (root2.value) {
          resizeObserver.observe(root2.value);
          resize();
        }
      });
      onUnmounted(() => {
        resizeObserver.disconnect();
      });
      return { resize };
    }
  };
}
__name(useTerminal, "useTerminal");
const _hoisted_1$y = { class: "p-terminal rounded-none h-full w-full p-2" };
const _sfc_main$I = /* @__PURE__ */ defineComponent({
  __name: "BaseTerminal",
  emits: ["created", "unmounted"],
  setup(__props, { emit: __emit }) {
    const emit = __emit;
    const terminalEl = ref$3();
    const rootEl = ref$3();
    emit("created", useTerminal(terminalEl), rootEl);
    onUnmounted(() => emit("unmounted"));
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", {
        ref_key: "rootEl",
        ref: rootEl,
        class: "relative overflow-hidden h-full w-full bg-black"
      }, [
        createBaseVNode("div", _hoisted_1$y, [
          createBaseVNode("div", {
            ref_key: "terminalEl",
            ref: terminalEl,
            class: "h-full terminal-host"
          }, null, 512)
        ])
      ], 512);
    };
  }
});
const BaseTerminal = /* @__PURE__ */ _export_sfc(_sfc_main$I, [["__scopeId", "data-v-a98b5a60"]]);
const _sfc_main$H = /* @__PURE__ */ defineComponent({
  __name: "CommandTerminal",
  setup(__props) {
    const terminalCreated = /* @__PURE__ */ __name(({ terminal, useAutoSize }, root2) => {
      const terminalApi = electronAPI().Terminal;
      let offData;
      let offOutput;
      useAutoSize({
        root: root2,
        autoRows: true,
        autoCols: true,
        onResize: /* @__PURE__ */ __name(async () => {
          if (!terminal.element?.offsetParent) return;
          await terminalApi.resize(terminal.cols, terminal.rows);
        }, "onResize")
      });
      onMounted(async () => {
        offData = terminal.onData(async (message) => {
          await terminalApi.write(message);
        });
        offOutput = terminalApi.onOutput((message) => {
          terminal.write(message);
        });
        const restore = await terminalApi.restore();
        setTimeout(() => {
          if (restore.buffer.length) {
            terminal.resize(restore.size.cols, restore.size.rows);
            terminal.write(restore.buffer.join(""));
          }
        }, 500);
      });
      onUnmounted(() => {
        offData?.dispose();
        offOutput?.();
      });
    }, "terminalCreated");
    return (_ctx, _cache) => {
      return openBlock(), createBlock(BaseTerminal, { onCreated: terminalCreated });
    };
  }
});
const CommandTerminal = /* @__PURE__ */ _export_sfc(_sfc_main$H, [["__scopeId", "data-v-b55e84e3"]]);
const _hoisted_1$x = { class: "relative w-full text-xs min-h-[28px] max-h-[200px] rounded-lg px-4 py-2 overflow-y-auto" };
const _hoisted_2$r = { class: "flex items-center gap-2" };
const _hoisted_3$e = { class: "flex-1 break-all flex items-center gap-2" };
const _hoisted_4$6 = ["innerHTML"];
const _sfc_main$G = /* @__PURE__ */ defineComponent({
  __name: "TextPreviewWidget",
  props: /* @__PURE__ */ mergeModels({
    widget: {}
  }, {
    "modelValue": { required: true },
    "modelModifiers": {}
  }),
  emits: ["update:modelValue"],
  setup(__props) {
    const modelValue = useModel(__props, "modelValue");
    const executionStore = useExecutionStore();
    const isParentNodeExecuting = ref$3(true);
    const formattedText = computed(() => nl2br(linkifyHtml(modelValue.value)));
    let executingNodeId = null;
    onMounted(() => {
      executingNodeId = executionStore.executingNodeId;
    });
    const stopWatching = watch(
      [() => executionStore.executingNode, () => executionStore.isIdle],
      () => {
        if (executionStore.isIdle || executionStore.executingNode && executionStore.executingNode.id !== executingNodeId) {
          isParentNodeExecuting.value = false;
          stopWatching();
        }
        if (!executingNodeId) {
          executingNodeId = executionStore.executingNodeId;
        }
      }
    );
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", _hoisted_1$x, [
        createBaseVNode("div", _hoisted_2$r, [
          createBaseVNode("div", _hoisted_3$e, [
            createBaseVNode("span", { innerHTML: formattedText.value }, null, 8, _hoisted_4$6),
            isParentNodeExecuting.value ? (openBlock(), createBlock(unref(script$y), {
              key: 0,
              class: "!flex-1 !h-4"
            })) : createCommentVNode("", true)
          ])
        ])
      ]);
    };
  }
});
const PADDING = 16;
const useTextPreviewWidget = /* @__PURE__ */ __name(() => {
  const widgetConstructor = /* @__PURE__ */ __name((node2, inputSpec) => {
    const widgetValue = ref$3("");
    const widget = new ComponentWidgetImpl({
      node: node2,
      name: inputSpec.name,
      component: _sfc_main$G,
      inputSpec,
      options: {
        getValue: /* @__PURE__ */ __name(() => widgetValue.value, "getValue"),
        setValue: /* @__PURE__ */ __name((value) => {
          widgetValue.value = typeof value === "string" ? value : String(value);
        }, "setValue"),
        getMinHeight: /* @__PURE__ */ __name(() => 42 + PADDING, "getMinHeight")
      }
    });
    addWidget(node2, widget);
    return widget;
  }, "widgetConstructor");
  return widgetConstructor;
}, "useTextPreviewWidget");
const TEXT_PREVIEW_WIDGET_NAME = "$$node-text-preview";
function useNodeProgressText() {
  const textPreviewWidget = useTextPreviewWidget();
  const findTextPreviewWidget = /* @__PURE__ */ __name((node2) => node2.widgets?.find((w2) => w2.name === TEXT_PREVIEW_WIDGET_NAME), "findTextPreviewWidget");
  const addTextPreviewWidget = /* @__PURE__ */ __name((node2) => textPreviewWidget(node2, {
    name: TEXT_PREVIEW_WIDGET_NAME,
    type: "progressText"
  }), "addTextPreviewWidget");
  function showTextPreview(node2, text2) {
    const widget = findTextPreviewWidget(node2) ?? addTextPreviewWidget(node2);
    widget.value = text2;
    node2.setDirtyCanvas?.(true);
  }
  __name(showTextPreview, "showTextPreview");
  function removeTextPreview(node2) {
    if (!node2.widgets) return;
    const widgetIdx = node2.widgets.findIndex(
      (w2) => w2.name === TEXT_PREVIEW_WIDGET_NAME
    );
    if (widgetIdx > -1) {
      node2.widgets[widgetIdx].onRemove?.();
      node2.widgets.splice(widgetIdx, 1);
    }
  }
  __name(removeTextPreview, "removeTextPreview");
  return {
    showTextPreview,
    removeTextPreview
  };
}
__name(useNodeProgressText, "useNodeProgressText");
const useExecutionStore = /* @__PURE__ */ defineStore("execution", () => {
  const clientId = ref$3(null);
  const activePromptId = ref$3(null);
  const queuedPrompts = ref$3({});
  const lastNodeErrors = ref$3(null);
  const lastExecutionError = ref$3(null);
  const executingNodeId = ref$3(null);
  const executingNode = computed(() => {
    if (!executingNodeId.value) return null;
    const workflow = activePrompt.value?.workflow;
    if (!workflow) return null;
    const canvasState = workflow.changeTracker?.activeState ?? null;
    if (!canvasState) return null;
    return canvasState.nodes.find(
      (n2) => String(n2.id) === executingNodeId.value
    ) ?? null;
  });
  const _executingNodeProgress = ref$3(null);
  const executingNodeProgress = computed(
    () => _executingNodeProgress.value ? _executingNodeProgress.value.value / _executingNodeProgress.value.max : null
  );
  const activePrompt = computed(
    () => queuedPrompts.value[activePromptId.value ?? ""]
  );
  const totalNodesToExecute = computed(() => {
    if (!activePrompt.value) return 0;
    return Object.values(activePrompt.value.nodes).length;
  });
  const isIdle = computed(() => !activePromptId.value);
  const nodesExecuted = computed(() => {
    if (!activePrompt.value) return 0;
    return Object.values(activePrompt.value.nodes).filter(Boolean).length;
  });
  const executionProgress = computed(() => {
    if (!activePrompt.value) return 0;
    const total = totalNodesToExecute.value;
    const done = nodesExecuted.value;
    return done / total;
  });
  function bindExecutionEvents() {
    api.addEventListener(
      "execution_start",
      handleExecutionStart
    );
    api.addEventListener(
      "execution_cached",
      handleExecutionCached
    );
    api.addEventListener("executed", handleExecuted);
    api.addEventListener("executing", handleExecuting);
    api.addEventListener("progress", handleProgress);
    api.addEventListener("status", handleStatus);
    api.addEventListener(
      "execution_error",
      handleExecutionError
    );
  }
  __name(bindExecutionEvents, "bindExecutionEvents");
  api.addEventListener("progress_text", handleProgressText);
  function unbindExecutionEvents() {
    api.removeEventListener(
      "execution_start",
      handleExecutionStart
    );
    api.removeEventListener(
      "execution_cached",
      handleExecutionCached
    );
    api.removeEventListener("executed", handleExecuted);
    api.removeEventListener("executing", handleExecuting);
    api.removeEventListener("progress", handleProgress);
    api.removeEventListener("status", handleStatus);
    api.removeEventListener(
      "execution_error",
      handleExecutionError
    );
    api.removeEventListener(
      "progress_text",
      handleProgressText
    );
  }
  __name(unbindExecutionEvents, "unbindExecutionEvents");
  function handleExecutionStart(e2) {
    lastExecutionError.value = null;
    activePromptId.value = e2.detail.prompt_id;
    queuedPrompts.value[activePromptId.value] ??= { nodes: {} };
  }
  __name(handleExecutionStart, "handleExecutionStart");
  function handleExecutionCached(e2) {
    if (!activePrompt.value) return;
    for (const n2 of e2.detail.nodes) {
      activePrompt.value.nodes[n2] = true;
    }
  }
  __name(handleExecutionCached, "handleExecutionCached");
  function handleExecuted(e2) {
    if (!activePrompt.value) return;
    activePrompt.value.nodes[e2.detail.node] = true;
  }
  __name(handleExecuted, "handleExecuted");
  function handleExecuting(e2) {
    _executingNodeProgress.value = null;
    if (!activePrompt.value) return;
    if (executingNodeId.value && activePrompt.value) {
      activePrompt.value.nodes[executingNodeId.value] = true;
    }
    executingNodeId.value = e2.detail;
    if (executingNodeId.value === null) {
      if (activePromptId.value) {
        delete queuedPrompts.value[activePromptId.value];
      }
      activePromptId.value = null;
    }
  }
  __name(handleExecuting, "handleExecuting");
  function handleProgress(e2) {
    _executingNodeProgress.value = e2.detail;
  }
  __name(handleProgress, "handleProgress");
  function handleStatus() {
    if (api.clientId) {
      clientId.value = api.clientId;
      api.removeEventListener("status", handleStatus);
    }
  }
  __name(handleStatus, "handleStatus");
  function handleExecutionError(e2) {
    lastExecutionError.value = e2.detail;
  }
  __name(handleExecutionError, "handleExecutionError");
  function handleProgressText(e2) {
    const { nodeId, text: text2 } = e2.detail;
    if (!text2 || !nodeId) return;
    const node2 = app$1.graph.getNodeById(nodeId);
    if (!node2) return;
    useNodeProgressText().showTextPreview(node2, text2);
  }
  __name(handleProgressText, "handleProgressText");
  function storePrompt({
    nodes,
    id: id2,
    workflow
  }) {
    queuedPrompts.value[id2] ??= { nodes: {} };
    const queuedPrompt = queuedPrompts.value[id2];
    queuedPrompt.nodes = {
      ...nodes.reduce((p2, n2) => {
        p2[n2] = false;
        return p2;
      }, {}),
      ...queuedPrompt.nodes
    };
    queuedPrompt.workflow = workflow;
    console.debug(
      `queued task ${id2} with ${Object.values(queuedPrompt.nodes).length} nodes`
    );
  }
  __name(storePrompt, "storePrompt");
  return {
    isIdle,
    clientId,
    /**
     * The id of the prompt that is currently being executed
     */
    activePromptId,
    /**
     * The queued prompts
     */
    queuedPrompts,
    /**
     * The node errors from the previous execution.
     */
    lastNodeErrors,
    /**
     * The error from the previous execution.
     */
    lastExecutionError,
    /**
     * The id of the node that is currently being executed
     */
    executingNodeId,
    /**
     * The prompt that is currently being executed
     */
    activePrompt,
    /**
     * The total number of nodes to execute
     */
    totalNodesToExecute,
    /**
     * The number of nodes that have been executed
     */
    nodesExecuted,
    /**
     * The progress of the execution
     */
    executionProgress,
    /**
     * The node that is currently being executed
     */
    executingNode,
    /**
     * The progress of the executing node (if the node reports progress)
     */
    executingNodeProgress,
    bindExecutionEvents,
    unbindExecutionEvents,
    storePrompt,
    // Raw executing progress data for backward compatibility in ComfyApp.
    _executingNodeProgress
  };
});
const _hoisted_1$w = { class: "bg-black h-full w-full" };
const _hoisted_2$q = {
  key: 0,
  class: "p-4 text-center"
};
const _sfc_main$F = /* @__PURE__ */ defineComponent({
  __name: "LogsTerminal",
  setup(__props) {
    const errorMessage = ref$3("");
    const loading = ref$3(true);
    const terminalCreated = /* @__PURE__ */ __name(({ terminal, useAutoSize }, root2) => {
      useAutoSize({ root: root2, autoRows: true, autoCols: false, minCols: 80 });
      const update2 = /* @__PURE__ */ __name((entries, size) => {
        if (size) {
          terminal.resize(size.cols, terminal.rows);
        }
        terminal.write(entries.map((e2) => e2.m).join(""));
      }, "update");
      const logReceived = /* @__PURE__ */ __name((e2) => {
        update2(e2.detail.entries, e2.detail.size);
      }, "logReceived");
      const loadLogEntries = /* @__PURE__ */ __name(async () => {
        const logs = await api.getRawLogs();
        update2(logs.entries, logs.size);
      }, "loadLogEntries");
      const watchLogs = /* @__PURE__ */ __name(async () => {
        const { clientId } = storeToRefs(useExecutionStore());
        if (!clientId.value) {
          await until(clientId).not.toBeNull();
        }
        await api.subscribeLogs(true);
        api.addEventListener("logs", logReceived);
      }, "watchLogs");
      onMounted(async () => {
        try {
          await loadLogEntries();
        } catch (err) {
          console.error("Error loading logs", err);
          errorMessage.value = "Unable to load logs, please ensure you have updated your ComfyUI backend.";
          return;
        }
        await watchLogs();
        loading.value = false;
      });
      onUnmounted(async () => {
        if (api.clientId) {
          await api.subscribeLogs(false);
        }
        api.removeEventListener("logs", logReceived);
      });
    }, "terminalCreated");
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", _hoisted_1$w, [
        errorMessage.value ? (openBlock(), createElementBlock("p", _hoisted_2$q, toDisplayString(errorMessage.value), 1)) : loading.value ? (openBlock(), createBlock(unref(script$x), {
          key: 1,
          class: "relative inset-0 flex justify-center items-center h-full z-10"
        })) : createCommentVNode("", true),
        withDirectives(createVNode(BaseTerminal, { onCreated: terminalCreated }, null, 512), [
          [vShow, !loading.value]
        ])
      ]);
    };
  }
});
const LogsTerminal = /* @__PURE__ */ _export_sfc(_sfc_main$F, [["__scopeId", "data-v-4ecd1948"]]);
const useLogsTerminalTab = /* @__PURE__ */ __name(() => {
  const { t: t2 } = useI18n();
  return {
    id: "logs-terminal",
    title: t2("g.logs"),
    component: markRaw(LogsTerminal),
    type: "vue"
  };
}, "useLogsTerminalTab");
const useCommandTerminalTab = /* @__PURE__ */ __name(() => {
  const { t: t2 } = useI18n();
  return {
    id: "command-terminal",
    title: t2("g.terminal"),
    component: markRaw(CommandTerminal),
    type: "vue"
  };
}, "useCommandTerminalTab");
const useBottomPanelStore = /* @__PURE__ */ defineStore("bottomPanel", () => {
  const bottomPanelVisible = ref$3(false);
  const toggleBottomPanel = /* @__PURE__ */ __name(() => {
    if (bottomPanelTabs.value.length === 0) {
      return;
    }
    bottomPanelVisible.value = !bottomPanelVisible.value;
  }, "toggleBottomPanel");
  const bottomPanelTabs = ref$3([]);
  const activeBottomPanelTabId = ref$3("");
  const activeBottomPanelTab = computed(() => {
    return bottomPanelTabs.value.find(
      (tab) => tab.id === activeBottomPanelTabId.value
    ) ?? null;
  });
  const setActiveTab = /* @__PURE__ */ __name((tabId) => {
    activeBottomPanelTabId.value = tabId;
  }, "setActiveTab");
  const toggleBottomPanelTab = /* @__PURE__ */ __name((tabId) => {
    if (activeBottomPanelTabId.value === tabId && bottomPanelVisible.value) {
      bottomPanelVisible.value = false;
    } else {
      activeBottomPanelTabId.value = tabId;
      bottomPanelVisible.value = true;
    }
  }, "toggleBottomPanelTab");
  const registerBottomPanelTab = /* @__PURE__ */ __name((tab) => {
    bottomPanelTabs.value = [...bottomPanelTabs.value, tab];
    if (bottomPanelTabs.value.length === 1) {
      activeBottomPanelTabId.value = tab.id;
    }
    useCommandStore().registerCommand({
      id: `Workspace.ToggleBottomPanelTab.${tab.id}`,
      icon: "pi pi-list",
      label: `Toggle ${tab.title} Bottom Panel`,
      function: /* @__PURE__ */ __name(() => toggleBottomPanelTab(tab.id), "function"),
      source: "System"
    });
  }, "registerBottomPanelTab");
  const registerCoreBottomPanelTabs = /* @__PURE__ */ __name(() => {
    registerBottomPanelTab(useLogsTerminalTab());
    if (isElectron()) {
      registerBottomPanelTab(useCommandTerminalTab());
    }
  }, "registerCoreBottomPanelTabs");
  const registerExtensionBottomPanelTabs = /* @__PURE__ */ __name((extension) => {
    if (extension.bottomPanelTabs) {
      extension.bottomPanelTabs.forEach(registerBottomPanelTab);
    }
  }, "registerExtensionBottomPanelTabs");
  return {
    bottomPanelVisible,
    toggleBottomPanel,
    bottomPanelTabs,
    activeBottomPanelTab,
    activeBottomPanelTabId,
    setActiveTab,
    toggleBottomPanelTab,
    registerBottomPanelTab,
    registerCoreBottomPanelTabs,
    registerExtensionBottomPanelTabs
  };
});
const useExtensionService = /* @__PURE__ */ __name(() => {
  const extensionStore = useExtensionStore();
  const settingStore = useSettingStore();
  const keybindingStore = useKeybindingStore();
  const { wrapWithErrorHandling } = useErrorHandling();
  const loadExtensions = /* @__PURE__ */ __name(async () => {
    extensionStore.loadDisabledExtensionNames(
      settingStore.get("Comfy.Extension.Disabled")
    );
    const extensions = await api.getExtensions();
    await __vitePreload(() => import("./index-DCPa4E5D.js"), true ? __vite__mapDeps([36,13,1,3,2,37]) : void 0, import.meta.url);
    extensionStore.captureCoreExtensions();
    await Promise.all(
      extensions.filter((extension) => !extension.includes("extensions/core")).map(async (ext) => {
        try {
          await import(
            /* @vite-ignore */
            api.fileURL(ext)
          );
        } catch (error2) {
          console.error("Error loading extension", ext, error2);
        }
      })
    );
  }, "loadExtensions");
  const registerExtension = /* @__PURE__ */ __name((extension) => {
    extensionStore.registerExtension(extension);
    const addKeybinding = wrapWithErrorHandling(
      keybindingStore.addDefaultKeybinding
    );
    const addSetting = wrapWithErrorHandling(settingStore.addSetting);
    extension.keybindings?.forEach((keybinding) => {
      addKeybinding(new KeybindingImpl(keybinding));
    });
    useCommandStore().loadExtensionCommands(extension);
    useMenuItemStore().loadExtensionMenuCommands(extension);
    extension.settings?.forEach(addSetting);
    useBottomPanelStore().registerExtensionBottomPanelTabs(extension);
    if (extension.getCustomWidgets) {
      void (async () => {
        if (extension.getCustomWidgets) {
          const widgets = await extension.getCustomWidgets(app$1);
          useWidgetStore().registerCustomWidgets(widgets);
        }
      })();
    }
  }, "registerExtension");
  const invokeExtensions = /* @__PURE__ */ __name((method, ...args) => {
    const results = [];
    for (const ext of extensionStore.enabledExtensions) {
      if (method in ext) {
        try {
          results.push(ext[method](...args, app$1));
        } catch (error2) {
          console.error(
            `Error calling extension '${ext.name}' method '${method}'`,
            { error: error2 },
            { extension: ext },
            { args }
          );
        }
      }
    }
    return results;
  }, "invokeExtensions");
  const invokeExtensionsAsync = /* @__PURE__ */ __name(async (method, ...args) => {
    return await Promise.all(
      extensionStore.enabledExtensions.map(async (ext) => {
        if (method in ext) {
          try {
            return await ext[method](...args, app$1);
          } catch (error2) {
            console.error(
              `Error calling extension '${ext.name}' method '${method}'`,
              { error: error2 },
              { extension: ext },
              { args }
            );
          }
        }
      })
    );
  }, "invokeExtensionsAsync");
  return {
    loadExtensions,
    registerExtension,
    invokeExtensions,
    invokeExtensionsAsync
  };
}, "useExtensionService");
const CONFIG = Symbol();
const GET_CONFIG = Symbol();
const useLitegraphService = /* @__PURE__ */ __name(() => {
  const extensionService = useExtensionService();
  const toastStore = useToastStore();
  const widgetStore = useWidgetStore();
  const canvasStore = useCanvasStore();
  async function registerNodeDef(nodeId, nodeDefV1) {
    const node2 = class ComfyNode extends LGraphNode {
      static {
        __name(this, "ComfyNode");
      }
      static comfyClass;
      static title;
      static category;
      static nodeData;
      /**
       * @internal The initial minimum size of the node.
       */
      #initialMinSize = { width: 1, height: 1 };
      /**
       * @internal The key for the node definition in the i18n file.
       */
      get #nodeKey() {
        return `nodeDefs.${normalizeI18nKey(ComfyNode.nodeData.name)}`;
      }
      constructor(title) {
        super(title);
        this.#setupStrokeStyles();
        this.#addInputs(ComfyNode.nodeData.inputs);
        this.#addOutputs(ComfyNode.nodeData.outputs);
        this.#setInitialSize();
        this.serialize_widgets = true;
        if (ComfyNode.nodeData.api_node) {
          this.color = LGraphCanvas.node_colors.yellow.color;
          this.bgcolor = LGraphCanvas.node_colors.yellow.bgcolor;
        }
        void extensionService.invokeExtensionsAsync("nodeCreated", this);
      }
      /**
       * @internal Setup stroke styles for the node under various conditions.
       */
      #setupStrokeStyles() {
        this.strokeStyles["running"] = function() {
          if (this.id == app$1.runningNodeId) {
            return { color: "#0f0" };
          }
        };
        this.strokeStyles["nodeError"] = function() {
          if (app$1.lastNodeErrors?.[this.id]?.errors) {
            return { color: "red" };
          }
        };
        this.strokeStyles["dragOver"] = function() {
          if (app$1.dragOverNode?.id == this.id) {
            return { color: "dodgerblue" };
          }
        };
        this.strokeStyles["executionError"] = function() {
          if (app$1.lastExecutionError?.node_id == this.id) {
            return { color: "#f0f", lineWidth: 2 };
          }
        };
      }
      /**
       * @internal Add input sockets to the node. (No widget)
       */
      #addInputSocket(inputSpec) {
        const inputName = inputSpec.name;
        const nameKey = `${this.#nodeKey}.inputs.${normalizeI18nKey(inputName)}.name`;
        const widgetConstructor = widgetStore.widgets.get(
          inputSpec.widgetType ?? inputSpec.type
        );
        if (widgetConstructor && !inputSpec.forceInput) return;
        this.addInput(inputName, inputSpec.type, {
          shape: inputSpec.isOptional ? RenderShape.HollowCircle : void 0,
          localized_name: st(nameKey, inputName)
        });
      }
      /**
       * @internal Add a widget to the node. For both primitive types and custom widgets
       * (unless `socketless`), an input socket is also added.
       */
      #addInputWidget(inputSpec) {
        const widgetInputSpec = { ...inputSpec };
        if (inputSpec.widgetType) {
          widgetInputSpec.type = inputSpec.widgetType;
        }
        const inputName = inputSpec.name;
        const nameKey = `${this.#nodeKey}.inputs.${normalizeI18nKey(inputName)}.name`;
        const widgetConstructor = widgetStore.widgets.get(widgetInputSpec.type);
        if (!widgetConstructor || inputSpec.forceInput) return;
        const {
          widget,
          minWidth = 1,
          minHeight = 1
        } = widgetConstructor(
          this,
          inputName,
          transformInputSpecV2ToV1(widgetInputSpec),
          app$1
        ) ?? {};
        if (widget) {
          widget.label = st(nameKey, widget.label ?? inputName);
          widget.options ??= {};
          Object.assign(widget.options, {
            advanced: inputSpec.advanced,
            hidden: inputSpec.hidden
          });
        }
        if (!widget?.options?.socketless) {
          const inputSpecV1 = transformInputSpecV2ToV1(widgetInputSpec);
          this.addInput(inputName, inputSpec.type, {
            shape: inputSpec.isOptional ? RenderShape.HollowCircle : void 0,
            localized_name: st(nameKey, inputName),
            widget: { name: inputName, [GET_CONFIG]: () => inputSpecV1 }
          });
        }
        this.#initialMinSize.width = Math.max(
          this.#initialMinSize.width,
          minWidth
        );
        this.#initialMinSize.height = Math.max(
          this.#initialMinSize.height,
          minHeight
        );
      }
      /**
       * @internal Add inputs to the node.
       */
      #addInputs(inputs) {
        for (const inputSpec of Object.values(inputs))
          this.#addInputSocket(inputSpec);
        for (const inputSpec of Object.values(inputs))
          this.#addInputWidget(inputSpec);
      }
      /**
       * @internal Add outputs to the node.
       */
      #addOutputs(outputs) {
        for (const output of outputs) {
          const { name: name2, type, is_list } = output;
          const shapeOptions = is_list ? { shape: LiteGraph.GRID_SHAPE } : {};
          const nameKey = `${this.#nodeKey}.outputs.${output.index}.name`;
          const typeKey = `dataTypes.${normalizeI18nKey(type)}`;
          const outputOptions = {
            ...shapeOptions,
            // If the output name is different from the output type, use the output name.
            // e.g.
            // - type ("INT"); name ("Positive") => translate name
            // - type ("FLOAT"); name ("FLOAT") => translate type
            localized_name: type !== name2 ? st(nameKey, name2) : st(typeKey, name2)
          };
          this.addOutput(name2, type, outputOptions);
        }
      }
      /**
       * @internal Set the initial size of the node.
       */
      #setInitialSize() {
        const s2 = this.computeSize();
        const pad2 = this.widgets?.length && !useSettingStore().get("LiteGraph.Node.DefaultPadding");
        s2[0] = Math.max(this.#initialMinSize.width, s2[0] + (pad2 ? 60 : 0));
        s2[1] = Math.max(this.#initialMinSize.height, s2[1]);
        this.setSize(s2);
      }
      /**
       * Configure the node from a serialised node. Keep 'name', 'type', 'shape',
       * and 'localized_name' information from the original node definition.
       */
      configure(data) {
        const RESERVED_KEYS = ["name", "type", "shape", "localized_name"];
        const inputByName = new Map(
          data.inputs?.map((input) => [input.name, input]) ?? []
        );
        const definedInputNames = new Set(
          this.inputs.map((input) => input.name)
        );
        const definedInputs = this.inputs.map((input) => {
          const inputData = inputByName.get(input.name);
          return inputData ? {
            ...inputData,
            // Whether the input has associated widget follows the
            // original node definition.
            ..._.pick(input, RESERVED_KEYS.concat("widget"))
          } : input;
        });
        const extraInputs = data.inputs?.filter(
          (input) => !definedInputNames.has(input.name)
        );
        data.inputs = [...definedInputs, ...extraInputs ?? []];
        data.outputs = _.zip(this.outputs, data.outputs).map(
          ([output, outputData]) => {
            if (!output) return outputData;
            return outputData ? {
              ...outputData,
              ..._.pick(output, RESERVED_KEYS)
            } : output;
          }
        );
        data.widgets_values = migrateWidgetsValues(
          ComfyNode.nodeData.inputs,
          this.widgets ?? [],
          data.widgets_values ?? []
        );
        super.configure(data);
      }
    };
    addNodeContextMenuHandler(node2);
    addDrawBackgroundHandler(node2);
    addNodeKeyHandler(node2);
    node2.prototype.comfyClass = nodeDefV1.name;
    node2.comfyClass = nodeDefV1.name;
    await extensionService.invokeExtensionsAsync(
      "beforeRegisterNodeDef",
      node2,
      nodeDefV1
      // Receives V1 NodeDef, and potentially make modifications to it
    );
    const nodeDef = new ComfyNodeDefImpl(nodeDefV1);
    node2.nodeData = nodeDef;
    LiteGraph.registerNodeType(nodeId, node2);
    node2.category = nodeDef.category;
    node2.title = nodeDef.display_name || nodeDef.name;
  }
  __name(registerNodeDef, "registerNodeDef");
  function addNodeContextMenuHandler(node2) {
    function getCopyImageOption(img) {
      if (typeof window.ClipboardItem === "undefined") return [];
      return [
        {
          content: "Copy Image",
          // @ts-expect-error: async callback is not accepted by litegraph
          callback: /* @__PURE__ */ __name(async () => {
            const url = new URL(img.src);
            url.searchParams.delete("preview");
            const writeImage = /* @__PURE__ */ __name(async (blob) => {
              await navigator.clipboard.write([
                new ClipboardItem({
                  [blob.type]: blob
                })
              ]);
            }, "writeImage");
            try {
              const data = await fetch(url);
              const blob = await data.blob();
              try {
                await writeImage(blob);
              } catch (error2) {
                if (blob.type !== "image/png") {
                  const canvas2 = $el("canvas", {
                    width: img.naturalWidth,
                    height: img.naturalHeight
                  });
                  const ctx = canvas2.getContext("2d");
                  let image2;
                  if (typeof window.createImageBitmap === "undefined") {
                    image2 = new Image();
                    const p2 = new Promise((resolve2, reject) => {
                      image2.onload = resolve2;
                      image2.onerror = reject;
                    }).finally(() => {
                      URL.revokeObjectURL(image2.src);
                    });
                    image2.src = URL.createObjectURL(blob);
                    await p2;
                  } else {
                    image2 = await createImageBitmap(blob);
                  }
                  try {
                    ctx.drawImage(image2, 0, 0);
                    canvas2.toBlob(writeImage, "image/png");
                  } finally {
                    if (typeof image2.close === "function") {
                      image2.close();
                    }
                  }
                  return;
                }
                throw error2;
              }
            } catch (error2) {
              toastStore.addAlert(
                t("toastMessages.errorCopyImage", {
                  // @ts-expect-error fixme ts strict error
                  error: error2.message ?? error2
                })
              );
            }
          }, "callback")
        }
      ];
    }
    __name(getCopyImageOption, "getCopyImageOption");
    node2.prototype.getExtraMenuOptions = function(_2, options2) {
      if (this.imgs) {
        let img;
        if (this.imageIndex != null) {
          img = this.imgs[this.imageIndex];
        } else if (this.overIndex != null) {
          img = this.imgs[this.overIndex];
        }
        if (img) {
          options2.unshift(
            {
              content: "Open Image",
              callback: /* @__PURE__ */ __name(() => {
                const url = new URL(img.src);
                url.searchParams.delete("preview");
                window.open(url, "_blank");
              }, "callback")
            },
            ...getCopyImageOption(img),
            {
              content: "Save Image",
              callback: /* @__PURE__ */ __name(() => {
                const a2 = document.createElement("a");
                const url = new URL(img.src);
                url.searchParams.delete("preview");
                a2.href = url.toString();
                a2.setAttribute(
                  "download",
                  // @ts-expect-error fixme ts strict error
                  new URLSearchParams(url.search).get("filename")
                );
                document.body.append(a2);
                a2.click();
                requestAnimationFrame(() => a2.remove());
              }, "callback")
            }
          );
        }
      }
      options2.push({
        content: "Bypass",
        callback: /* @__PURE__ */ __name(() => {
          const mode = this.mode === LGraphEventMode.BYPASS ? LGraphEventMode.ALWAYS : LGraphEventMode.BYPASS;
          for (const item of app$1.canvas.selectedItems) {
            if (item instanceof LGraphNode) item.mode = mode;
          }
          this.graph.change();
        }, "callback")
      });
      if (!ComfyApp.clipspace_return_node) {
        options2.push({
          content: "Copy (Clipspace)",
          callback: /* @__PURE__ */ __name(() => {
            ComfyApp.copyToClipspace(this);
          }, "callback")
        });
        if (ComfyApp.clipspace != null) {
          options2.push({
            content: "Paste (Clipspace)",
            callback: /* @__PURE__ */ __name(() => {
              ComfyApp.pasteFromClipspace(this);
            }, "callback")
          });
        }
        if (isImageNode(this)) {
          options2.push({
            content: "Open in MaskEditor",
            callback: /* @__PURE__ */ __name(() => {
              ComfyApp.copyToClipspace(this);
              ComfyApp.clipspace_return_node = this;
              ComfyApp.open_maskeditor();
            }, "callback")
          });
        }
      }
      return [];
    };
  }
  __name(addNodeContextMenuHandler, "addNodeContextMenuHandler");
  function addDrawBackgroundHandler(node2) {
    node2.prototype.setSizeForImage = function() {
      console.warn(
        "node.setSizeForImage is deprecated. Now it has no effect. Please remove the call to it."
      );
    };
    function unsafeDrawBackground() {
      if (this.flags.collapsed) return;
      const nodeOutputStore = useNodeOutputStore();
      const { showAnimatedPreview, removeAnimatedPreview } = useNodeAnimatedImage();
      const { showCanvasImagePreview, removeCanvasImagePreview } = useNodeCanvasImagePreview();
      const output = nodeOutputStore.getNodeOutputs(this);
      const preview = nodeOutputStore.getNodePreviews(this);
      const isNewOutput = output && this.images !== output.images;
      const isNewPreview = preview && this.preview !== preview;
      if (isNewPreview) this.preview = preview;
      if (isNewOutput) this.images = output.images;
      if (isNewOutput || isNewPreview) {
        this.animatedImages = output?.animated?.find(Boolean);
        const isAnimatedWebp = this.animatedImages && // @ts-expect-error fixme ts strict error
        output.images.some((img) => img.filename?.includes("webp"));
        const isVideo = this.animatedImages && !isAnimatedWebp || isVideoNode(this);
        if (isVideo) {
          useNodeVideo(this).showPreview();
        } else {
          useNodeImage(this).showPreview();
        }
      }
      if (!this.imgs?.length) return;
      if (this.animatedImages) {
        removeCanvasImagePreview(this);
        showAnimatedPreview(this);
      } else {
        removeAnimatedPreview(this);
        showCanvasImagePreview(this);
      }
    }
    __name(unsafeDrawBackground, "unsafeDrawBackground");
    node2.prototype.onDrawBackground = function() {
      try {
        unsafeDrawBackground.call(this);
      } catch (error2) {
        console.error("Error drawing node background", error2);
      }
    };
  }
  __name(addDrawBackgroundHandler, "addDrawBackgroundHandler");
  function addNodeKeyHandler(node2) {
    const origNodeOnKeyDown = node2.prototype.onKeyDown;
    node2.prototype.onKeyDown = function(e2) {
      if (origNodeOnKeyDown && origNodeOnKeyDown.apply(this, e2) === false) {
        return false;
      }
      if (this.flags.collapsed || !this.imgs || this.imageIndex === null) {
        return;
      }
      let handled = false;
      if (e2.key === "ArrowLeft" || e2.key === "ArrowRight") {
        if (e2.key === "ArrowLeft") {
          this.imageIndex -= 1;
        } else if (e2.key === "ArrowRight") {
          this.imageIndex += 1;
        }
        this.imageIndex %= this.imgs.length;
        if (this.imageIndex < 0) {
          this.imageIndex = this.imgs.length + this.imageIndex;
        }
        handled = true;
      } else if (e2.key === "Escape") {
        this.imageIndex = null;
        handled = true;
      }
      if (handled === true) {
        e2.preventDefault();
        e2.stopImmediatePropagation();
        return false;
      }
    };
  }
  __name(addNodeKeyHandler, "addNodeKeyHandler");
  function addNodeOnGraph(nodeDef, options2 = {}) {
    options2.pos ??= getCanvasCenter();
    const node2 = LiteGraph.createNode(
      nodeDef.name,
      nodeDef.display_name,
      options2
    );
    app$1.graph.add(node2);
    return node2;
  }
  __name(addNodeOnGraph, "addNodeOnGraph");
  function getCanvasCenter() {
    const dpi = Math.max(window.devicePixelRatio ?? 1, 1);
    const [x2, y2, w2, h2] = app$1.canvas.ds.visible_area;
    return [x2 + w2 / dpi / 2, y2 + h2 / dpi / 2];
  }
  __name(getCanvasCenter, "getCanvasCenter");
  function goToNode(nodeId) {
    const graphNode = app$1.graph.getNodeById(nodeId);
    if (!graphNode) return;
    app$1.canvas.animateToBounds(graphNode.boundingRect);
  }
  __name(goToNode, "goToNode");
  function resetView() {
    const canvas2 = canvasStore.canvas;
    if (!canvas2) return;
    canvas2.ds.scale = 1;
    canvas2.ds.offset = [0, 0];
    canvas2.setDirty(true, true);
  }
  __name(resetView, "resetView");
  function fitView() {
    const canvas2 = canvasStore.canvas;
    if (!canvas2) return;
    const bounds = createBounds(app$1.graph.nodes);
    if (!bounds) return;
    canvas2.ds.fitToBounds(bounds);
    canvas2.setDirty(true, true);
  }
  __name(fitView, "fitView");
  return {
    registerNodeDef,
    addNodeOnGraph,
    getCanvasCenter,
    goToNode,
    resetView,
    fitView
  };
}, "useLitegraphService");
let ComfyDialog$1 = class ComfyDialog2 extends EventTarget {
  static {
    __name(this, "ComfyDialog");
  }
  element;
  // @ts-expect-error fixme ts strict error
  textElement;
  #buttons;
  constructor(type = "div", buttons = null) {
    super();
    this.#buttons = buttons;
    this.element = $el(type + ".comfy-modal", { parent: document.body }, [
      $el("div.comfy-modal-content", [
        $el("p", { $: /* @__PURE__ */ __name((p2) => this.textElement = p2, "$") }),
        ...this.createButtons()
      ])
    ]);
  }
  createButtons() {
    return this.#buttons ?? [
      $el("button", {
        type: "button",
        textContent: "Close",
        onclick: /* @__PURE__ */ __name(() => this.close(), "onclick")
      })
    ];
  }
  close() {
    this.element.style.display = "none";
  }
  // @ts-expect-error fixme ts strict error
  show(html) {
    if (typeof html === "string") {
      this.textElement.innerHTML = html;
    } else {
      this.textElement.replaceChildren(
        ...html instanceof Array ? html : [html]
      );
    }
    this.element.style.display = "flex";
  }
};
window.comfyAPI = window.comfyAPI || {};
window.comfyAPI.dialog = window.comfyAPI.dialog || {};
window.comfyAPI.dialog.ComfyDialog = ComfyDialog$1;
class ComfySettingsDialog extends ComfyDialog$1 {
  static {
    __name(this, "ComfySettingsDialog");
  }
  app;
  constructor(app2) {
    super();
    this.app = app2;
  }
  dispatchChange(id2, value, oldValue) {
    this.dispatchEvent(
      new CustomEvent(id2 + ".change", {
        detail: {
          value,
          oldValue
        }
      })
    );
  }
  /**
   * @deprecated Use `settingStore.settingValues` instead.
   */
  get settingsValues() {
    return useSettingStore().settingValues;
  }
  /**
   * @deprecated Use `settingStore.settingsById` instead.
   */
  get settingsLookup() {
    return useSettingStore().settingsById;
  }
  /**
   * @deprecated Use `settingStore.settingsById` instead.
   */
  get settingsParamLookup() {
    return useSettingStore().settingsById;
  }
  /**
   * @deprecated Use `settingStore.get` instead.
   */
  getSettingValue(id2, defaultValue) {
    if (defaultValue !== void 0) {
      console.warn(
        `Parameter defaultValue is deprecated. The default value in settings definition will be used instead.`
      );
    }
    return useSettingStore().get(id2);
  }
  /**
   * @deprecated Use `settingStore.getDefaultValue` instead.
   */
  getSettingDefaultValue(id2) {
    return useSettingStore().getDefaultValue(id2);
  }
  /**
   * @deprecated Use `settingStore.set` instead.
   */
  async setSettingValueAsync(id2, value) {
    await useSettingStore().set(id2, value);
  }
  /**
   * @deprecated Use `settingStore.set` instead.
   */
  setSettingValue(id2, value) {
    useSettingStore().set(id2, value).catch((err) => {
      useToastStore().addAlert(
        t("toastMessages.errorSaveSetting", { id: id2, err })
      );
    });
  }
  /**
   * @deprecated Deprecated for external callers/extensions. Use
   * `ComfyExtension.settings` field instead.
   *
   * Example:
   * ```ts
   * app.registerExtension({
   *   name: 'My Extension',
   *   settings: [
   *     {
   *       id: 'My.Setting',
   *       name: 'My Setting',
   *       type: 'text',
   *       defaultValue: 'Hello, world!'
   *     }
   *   ]
   * })
   * ```
   */
  addSetting(params) {
    const settingStore = useSettingStore();
    settingStore.addSetting(params);
    return {
      get value() {
        return settingStore.get(params.id);
      },
      set value(v2) {
        settingStore.set(params.id, v2);
      }
    };
  }
}
window.comfyAPI = window.comfyAPI || {};
window.comfyAPI.settings = window.comfyAPI.settings || {};
window.comfyAPI.settings.ComfySettingsDialog = ComfySettingsDialog;
function toggleSwitch(name2, items, e2) {
  const onChange2 = e2?.onChange;
  let selectedIndex;
  let elements;
  function updateSelected(index2) {
    if (selectedIndex != null) {
      elements[selectedIndex].classList.remove("comfy-toggle-selected");
    }
    onChange2?.({
      item: items[index2],
      // @ts-expect-error fixme ts strict error
      prev: selectedIndex == null ? void 0 : items[selectedIndex]
    });
    selectedIndex = index2;
    elements[selectedIndex].classList.add("comfy-toggle-selected");
  }
  __name(updateSelected, "updateSelected");
  elements = items.map((item, i2) => {
    if (typeof item === "string") item = { text: item };
    if (!item.value) item.value = item.text;
    const toggle = $el(
      "label",
      {
        textContent: item.text,
        title: item.tooltip ?? ""
      },
      $el("input", {
        name: name2,
        type: "radio",
        value: item.value ?? item.text,
        checked: item.selected,
        onchange: /* @__PURE__ */ __name(() => {
          updateSelected(i2);
        }, "onchange")
      })
    );
    if (item.selected) {
      updateSelected(i2);
    }
    return toggle;
  });
  const container = $el("div.comfy-toggle-switch", elements);
  if (selectedIndex == null) {
    elements[0].children[0].checked = true;
    updateSelected(0);
  }
  return container;
}
__name(toggleSwitch, "toggleSwitch");
window.comfyAPI = window.comfyAPI || {};
window.comfyAPI.toggleSwitch = window.comfyAPI.toggleSwitch || {};
window.comfyAPI.toggleSwitch.toggleSwitch = toggleSwitch;
const ComfyDialog = ComfyDialog$1;
function $el(tag, propsOrChildren, children) {
  const split2 = tag.split(".");
  const element = document.createElement(split2.shift());
  if (split2.length > 0) {
    element.classList.add(...split2);
  }
  if (propsOrChildren) {
    if (typeof propsOrChildren === "string") {
      propsOrChildren = { textContent: propsOrChildren };
    } else if (propsOrChildren instanceof Element) {
      propsOrChildren = [propsOrChildren];
    }
    if (Array.isArray(propsOrChildren)) {
      element.append(...propsOrChildren);
    } else {
      const {
        parent: parent2,
        $: cb,
        dataset,
        style: style2,
        ...rest
      } = propsOrChildren;
      if (rest.for) {
        element.setAttribute("for", rest.for);
      }
      if (style2) {
        Object.assign(element.style, style2);
      }
      if (dataset) {
        Object.assign(element.dataset, dataset);
      }
      Object.assign(element, rest);
      if (children) {
        element.append(...Array.isArray(children) ? children : [children]);
      }
      if (parent2) {
        parent2.append(element);
      }
      if (cb) {
        cb(element);
      }
    }
  }
  return element;
}
__name($el, "$el");
function dragElement(dragEl) {
  var posDiffX = 0, posDiffY = 0, posStartX = 0, posStartY = 0, newPosX = 0, newPosY = 0;
  if (dragEl.getElementsByClassName("drag-handle")[0]) {
    dragEl.getElementsByClassName("drag-handle")[0].onmousedown = dragMouseDown;
  } else {
    dragEl.onmousedown = dragMouseDown;
  }
  new ResizeObserver(() => {
    ensureInBounds();
  }).observe(dragEl);
  function ensureInBounds() {
    try {
      newPosX = Math.min(
        document.body.clientWidth - dragEl.clientWidth,
        Math.max(0, dragEl.offsetLeft)
      );
      newPosY = Math.min(
        document.body.clientHeight - dragEl.clientHeight,
        Math.max(0, dragEl.offsetTop)
      );
      positionElement();
    } catch (exception) {
    }
  }
  __name(ensureInBounds, "ensureInBounds");
  function positionElement() {
    if (dragEl.style.display === "none") return;
    const halfWidth = document.body.clientWidth / 2;
    const anchorRight = newPosX + dragEl.clientWidth / 2 > halfWidth;
    if (anchorRight) {
      dragEl.style.left = "unset";
      dragEl.style.right = document.body.clientWidth - newPosX - dragEl.clientWidth + "px";
    } else {
      dragEl.style.left = newPosX + "px";
      dragEl.style.right = "unset";
    }
    dragEl.style.top = newPosY + "px";
    dragEl.style.bottom = "unset";
    if (savePos) {
      localStorage.setItem(
        "Comfy.MenuPosition",
        JSON.stringify({
          x: dragEl.offsetLeft,
          y: dragEl.offsetTop
        })
      );
    }
  }
  __name(positionElement, "positionElement");
  function restorePos() {
    let posString = localStorage.getItem("Comfy.MenuPosition");
    if (posString) {
      const pos = JSON.parse(posString);
      newPosX = pos.x;
      newPosY = pos.y;
      positionElement();
      ensureInBounds();
    }
  }
  __name(restorePos, "restorePos");
  let savePos = void 0;
  restorePos();
  savePos = true;
  function dragMouseDown(e2) {
    e2 = e2 || window.event;
    e2.preventDefault();
    posStartX = e2.clientX;
    posStartY = e2.clientY;
    document.onmouseup = closeDragElement;
    document.onmousemove = elementDrag;
  }
  __name(dragMouseDown, "dragMouseDown");
  function elementDrag(e2) {
    e2 = e2 || window.event;
    e2.preventDefault();
    dragEl.classList.add("comfy-menu-manual-pos");
    posDiffX = e2.clientX - posStartX;
    posDiffY = e2.clientY - posStartY;
    posStartX = e2.clientX;
    posStartY = e2.clientY;
    newPosX = Math.min(
      document.body.clientWidth - dragEl.clientWidth,
      Math.max(0, dragEl.offsetLeft + posDiffX)
    );
    newPosY = Math.min(
      document.body.clientHeight - dragEl.clientHeight,
      Math.max(0, dragEl.offsetTop + posDiffY)
    );
    positionElement();
  }
  __name(elementDrag, "elementDrag");
  window.addEventListener("resize", () => {
    ensureInBounds();
  });
  function closeDragElement() {
    document.onmouseup = null;
    document.onmousemove = null;
  }
  __name(closeDragElement, "closeDragElement");
  return restorePos;
}
__name(dragElement, "dragElement");
class ComfyList {
  static {
    __name(this, "ComfyList");
  }
  #type;
  #text;
  #reverse;
  element;
  button;
  // @ts-expect-error fixme ts strict error
  constructor(text2, type, reverse2) {
    this.#text = text2;
    this.#type = type || text2.toLowerCase();
    this.#reverse = reverse2 || false;
    this.element = $el("div.comfy-list");
    this.element.style.display = "none";
  }
  get visible() {
    return this.element.style.display !== "none";
  }
  async load() {
    const items = await api.getItems(this.#type);
    this.element.replaceChildren(
      ...Object.keys(items).flatMap((section) => [
        $el("h4", {
          textContent: section
        }),
        $el("div.comfy-list-items", [
          // @ts-expect-error fixme ts strict error
          ...(this.#reverse ? items[section].reverse() : items[section]).map(
            (item) => {
              const removeAction = "remove" in item ? item.remove : {
                name: "Delete",
                cb: /* @__PURE__ */ __name(() => api.deleteItem(this.#type, item.prompt[1]), "cb")
              };
              return $el("div", { textContent: item.prompt[0] + ": " }, [
                $el("button", {
                  textContent: "Load",
                  onclick: /* @__PURE__ */ __name(async () => {
                    await app$1.loadGraphData(
                      // @ts-expect-error fixme ts strict error
                      item.prompt[3].extra_pnginfo.workflow,
                      true,
                      false
                    );
                    if ("outputs" in item) {
                      app$1.nodeOutputs = {};
                      for (const [key, value] of Object.entries(item.outputs)) {
                        const realKey = item["meta"]?.[key]?.display_node ?? key;
                        app$1.nodeOutputs[realKey] = value;
                      }
                    }
                  }, "onclick")
                }),
                $el("button", {
                  textContent: removeAction.name,
                  onclick: /* @__PURE__ */ __name(async () => {
                    await removeAction.cb();
                    await this.update();
                  }, "onclick")
                })
              ]);
            }
          )
        ])
      ]),
      $el("div.comfy-list-actions", [
        $el("button", {
          textContent: "Clear " + this.#text,
          onclick: /* @__PURE__ */ __name(async () => {
            await api.clearItems(this.#type);
            await this.load();
          }, "onclick")
        }),
        $el("button", { textContent: "Refresh", onclick: /* @__PURE__ */ __name(() => this.load(), "onclick") })
      ])
    );
  }
  async update() {
    if (this.visible) {
      await this.load();
    }
  }
  async show() {
    this.element.style.display = "block";
    this.button.textContent = "Close";
    await this.load();
  }
  hide() {
    this.element.style.display = "none";
    this.button.textContent = "View " + this.#text;
  }
  toggle() {
    if (this.visible) {
      this.hide();
      return false;
    } else {
      this.show();
      return true;
    }
  }
}
class ComfyUI {
  static {
    __name(this, "ComfyUI");
  }
  app;
  dialog;
  settings;
  batchCount;
  lastQueueSize;
  queue;
  history;
  // @ts-expect-error fixme ts strict error
  autoQueueMode;
  // @ts-expect-error fixme ts strict error
  graphHasChanged;
  // @ts-expect-error fixme ts strict error
  autoQueueEnabled;
  // @ts-expect-error fixme ts strict error
  menuContainer;
  // @ts-expect-error fixme ts strict error
  queueSize;
  // @ts-expect-error fixme ts strict error
  restoreMenuPosition;
  // @ts-expect-error fixme ts strict error
  loadFile;
  // @ts-expect-error fixme ts strict error
  constructor(app2) {
    this.app = app2;
    this.dialog = new ComfyDialog();
    this.settings = new ComfySettingsDialog(app2);
    this.batchCount = 1;
    this.lastQueueSize = 0;
    this.queue = new ComfyList("Queue");
    this.history = new ComfyList("History", "history", true);
    api.addEventListener("status", () => {
      this.queue.update();
      this.history.update();
    });
    this.setup(document.body);
  }
  setup(containerElement) {
    const fileInput2 = $el("input", {
      id: "comfy-file-input",
      type: "file",
      accept: ".json,image/png,.latent,.safetensors,image/webp,audio/flac",
      style: { display: "none" },
      parent: document.body,
      onchange: /* @__PURE__ */ __name(async () => {
        await app$1.handleFile(fileInput2.files[0]);
        fileInput2.value = "";
      }, "onchange")
    });
    this.loadFile = () => fileInput2.click();
    const autoQueueModeEl = toggleSwitch(
      "autoQueueMode",
      [
        {
          text: "instant",
          tooltip: "A new prompt will be queued as soon as the queue reaches 0"
        },
        {
          text: "change",
          tooltip: "A new prompt will be queued when the queue is at 0 and the graph is/has changed"
        }
      ],
      {
        // @ts-expect-error fixme ts strict error
        onChange: /* @__PURE__ */ __name((value) => {
          this.autoQueueMode = value.item.value;
        }, "onChange")
      }
    );
    autoQueueModeEl.style.display = "none";
    api.addEventListener("graphChanged", () => {
      if (this.autoQueueMode === "change" && this.autoQueueEnabled === true) {
        if (this.lastQueueSize === 0) {
          this.graphHasChanged = false;
          app$1.queuePrompt(0, this.batchCount);
        } else {
          this.graphHasChanged = true;
        }
      }
    });
    this.menuContainer = $el(
      "div.comfy-menu.no-drag",
      { parent: containerElement },
      [
        $el(
          "div.drag-handle.comfy-menu-header",
          {
            style: {
              overflow: "hidden",
              position: "relative",
              width: "100%",
              cursor: "default"
            }
          },
          [
            $el("span.drag-handle"),
            $el("span.comfy-menu-queue-size", {
              $: /* @__PURE__ */ __name((q2) => this.queueSize = q2, "$")
            }),
            $el("div.comfy-menu-actions", [
              $el("button.comfy-settings-btn", {
                textContent: "⚙️",
                onclick: /* @__PURE__ */ __name(() => {
                  useDialogService().showSettingsDialog();
                }, "onclick")
              }),
              $el("button.comfy-close-menu-btn", {
                textContent: "×",
                onclick: /* @__PURE__ */ __name(() => {
                  useWorkspaceStore().focusMode = true;
                }, "onclick")
              })
            ])
          ]
        ),
        $el("button.comfy-queue-btn", {
          id: "queue-button",
          textContent: "Queue Prompt",
          onclick: /* @__PURE__ */ __name(() => app$1.queuePrompt(0, this.batchCount), "onclick")
        }),
        $el("div", {}, [
          $el("label", { innerHTML: "Extra options" }, [
            $el("input", {
              type: "checkbox",
              // @ts-expect-error fixme ts strict error
              onchange: /* @__PURE__ */ __name((i2) => {
                document.getElementById("extraOptions").style.display = i2.srcElement.checked ? "block" : "none";
                this.batchCount = i2.srcElement.checked ? Number.parseInt(
                  document.getElementById(
                    "batchCountInputRange"
                  ).value
                ) : 1;
                document.getElementById(
                  "autoQueueCheckbox"
                ).checked = false;
                this.autoQueueEnabled = false;
              }, "onchange")
            })
          ])
        ]),
        $el(
          "div",
          { id: "extraOptions", style: { width: "100%", display: "none" } },
          [
            $el("div", [
              $el("label", { innerHTML: "Batch count" }),
              $el("input", {
                id: "batchCountInputNumber",
                type: "number",
                value: this.batchCount,
                min: "1",
                style: { width: "35%", marginLeft: "0.4em" },
                // @ts-expect-error fixme ts strict error
                oninput: /* @__PURE__ */ __name((i2) => {
                  this.batchCount = i2.target.value;
                  document.getElementById(
                    "batchCountInputRange"
                  ).value = this.batchCount.toString();
                }, "oninput")
              }),
              $el("input", {
                id: "batchCountInputRange",
                type: "range",
                min: "1",
                max: "100",
                value: this.batchCount,
                // @ts-expect-error fixme ts strict error
                oninput: /* @__PURE__ */ __name((i2) => {
                  this.batchCount = i2.srcElement.value;
                  document.getElementById(
                    "batchCountInputNumber"
                  ).value = i2.srcElement.value;
                }, "oninput")
              })
            ]),
            $el("div", [
              $el("label", {
                for: "autoQueueCheckbox",
                innerHTML: "Auto Queue"
              }),
              $el("input", {
                id: "autoQueueCheckbox",
                type: "checkbox",
                checked: false,
                title: "Automatically queue prompt when the queue size hits 0",
                // @ts-expect-error fixme ts strict error
                onchange: /* @__PURE__ */ __name((e2) => {
                  this.autoQueueEnabled = e2.target.checked;
                  autoQueueModeEl.style.display = this.autoQueueEnabled ? "" : "none";
                }, "onchange")
              }),
              autoQueueModeEl
            ])
          ]
        ),
        $el("div.comfy-menu-btns", [
          $el("button", {
            id: "queue-front-button",
            textContent: "Queue Front",
            onclick: /* @__PURE__ */ __name(() => app$1.queuePrompt(-1, this.batchCount), "onclick")
          }),
          $el("button", {
            $: /* @__PURE__ */ __name((b2) => this.queue.button = b2, "$"),
            id: "comfy-view-queue-button",
            textContent: "View Queue",
            onclick: /* @__PURE__ */ __name(() => {
              this.history.hide();
              this.queue.toggle();
            }, "onclick")
          }),
          $el("button", {
            $: /* @__PURE__ */ __name((b2) => this.history.button = b2, "$"),
            id: "comfy-view-history-button",
            textContent: "View History",
            onclick: /* @__PURE__ */ __name(() => {
              this.queue.hide();
              this.history.toggle();
            }, "onclick")
          })
        ]),
        this.queue.element,
        this.history.element,
        $el("button", {
          id: "comfy-save-button",
          textContent: "Save",
          onclick: /* @__PURE__ */ __name(() => {
            useCommandStore().execute("Comfy.ExportWorkflow");
          }, "onclick")
        }),
        $el("button", {
          id: "comfy-dev-save-api-button",
          textContent: "Save (API Format)",
          style: { width: "100%", display: "none" },
          onclick: /* @__PURE__ */ __name(() => {
            useCommandStore().execute("Comfy.ExportWorkflowAPI");
          }, "onclick")
        }),
        $el("button", {
          id: "comfy-load-button",
          textContent: "Load",
          onclick: /* @__PURE__ */ __name(() => fileInput2.click(), "onclick")
        }),
        $el("button", {
          id: "comfy-refresh-button",
          textContent: "Refresh",
          onclick: /* @__PURE__ */ __name(() => app$1.refreshComboInNodes(), "onclick")
        }),
        $el("button", {
          id: "comfy-clipspace-button",
          textContent: "Clipspace",
          onclick: /* @__PURE__ */ __name(() => app$1.openClipspace(), "onclick")
        }),
        $el("button", {
          id: "comfy-clear-button",
          textContent: "Clear",
          onclick: /* @__PURE__ */ __name(() => {
            if (!useSettingStore().get("Comfy.ConfirmClear") || confirm("Clear workflow?")) {
              app$1.clean();
              app$1.graph.clear();
              useLitegraphService().resetView();
              api.dispatchCustomEvent("graphCleared");
            }
          }, "onclick")
        }),
        $el("button", {
          id: "comfy-load-default-button",
          textContent: "Load Default",
          onclick: /* @__PURE__ */ __name(async () => {
            if (!useSettingStore().get("Comfy.ConfirmClear") || confirm("Load default workflow?")) {
              useLitegraphService().resetView();
              await app$1.loadGraphData();
            }
          }, "onclick")
        }),
        $el("button", {
          id: "comfy-reset-view-button",
          textContent: "Reset View",
          onclick: /* @__PURE__ */ __name(async () => {
            useLitegraphService().resetView();
          }, "onclick")
        })
      ]
    );
    this.menuContainer.style.display = "none";
    this.restoreMenuPosition = dragElement(this.menuContainer);
    this.setStatus({ exec_info: { queue_remaining: "X" } });
  }
  setStatus(status) {
    this.queueSize.textContent = "Queue size: " + (status ? status.exec_info.queue_remaining : "ERR");
    if (status) {
      if (this.lastQueueSize != 0 && status.exec_info.queue_remaining == 0 && this.autoQueueEnabled && (this.autoQueueMode === "instant" || this.graphHasChanged) && !app$1.lastExecutionError) {
        app$1.queuePrompt(0, this.batchCount);
        status.exec_info.queue_remaining += this.batchCount;
        this.graphHasChanged = false;
      }
      this.lastQueueSize = status.exec_info.queue_remaining;
    }
  }
}
window.comfyAPI = window.comfyAPI || {};
window.comfyAPI.ui = window.comfyAPI.ui || {};
window.comfyAPI.ui.ComfyDialog = ComfyDialog;
window.comfyAPI.ui.$el = $el;
window.comfyAPI.ui.ComfyUI = ComfyUI;
function clone$3(obj) {
  try {
    if (typeof structuredClone !== "undefined") {
      return structuredClone(obj);
    }
  } catch (error2) {
  }
  return JSON.parse(JSON.stringify(obj));
}
__name(clone$3, "clone$3");
function applyTextReplacements(app2, value) {
  return applyTextReplacements$1(app2.graph.nodes, value);
}
__name(applyTextReplacements, "applyTextReplacements");
async function addStylesheet(urlOrFile, relativeTo) {
  return new Promise((res, rej) => {
    let url;
    if (urlOrFile.endsWith(".js")) {
      url = urlOrFile.substr(0, urlOrFile.length - 2) + "css";
    } else {
      url = new URL(
        urlOrFile,
        relativeTo ?? `${window.location.protocol}//${window.location.host}`
      ).toString();
    }
    $el("link", {
      parent: document.head,
      rel: "stylesheet",
      type: "text/css",
      href: url,
      onload: res,
      onerror: rej
    });
  });
}
__name(addStylesheet, "addStylesheet");
function downloadBlob(filename, blob) {
  const url = URL.createObjectURL(blob);
  const a2 = $el("a", {
    href: url,
    download: filename,
    style: { display: "none" },
    parent: document.body
  });
  a2.click();
  setTimeout(function() {
    a2.remove();
    window.URL.revokeObjectURL(url);
  }, 0);
}
__name(downloadBlob, "downloadBlob");
function uploadFile(accept) {
  return new Promise((resolve2, reject) => {
    const input = document.createElement("input");
    input.type = "file";
    input.accept = accept;
    input.onchange = (e2) => {
      const file = e2.target.files?.[0];
      if (!file) return reject(new Error("No file selected"));
      resolve2(file);
    };
    input.click();
  });
}
__name(uploadFile, "uploadFile");
function prop(target, name2, defaultValue, onChanged) {
  let currentValue;
  Object.defineProperty(target, name2, {
    get() {
      return currentValue;
    },
    set(newValue2) {
      const prevValue = currentValue;
      currentValue = newValue2;
      onChanged?.(currentValue, prevValue, target, name2);
    }
  });
  return defaultValue;
}
__name(prop, "prop");
function getStorageValue(id2) {
  const clientId = api.clientId ?? api.initialClientId;
  return (clientId && sessionStorage.getItem(`${id2}:${clientId}`)) ?? localStorage.getItem(id2);
}
__name(getStorageValue, "getStorageValue");
function setStorageValue(id2, value) {
  const clientId = api.clientId ?? api.initialClientId;
  if (clientId) {
    sessionStorage.setItem(`${id2}:${clientId}`, value);
  }
  localStorage.setItem(id2, value);
}
__name(setStorageValue, "setStorageValue");
window.comfyAPI = window.comfyAPI || {};
window.comfyAPI.utils = window.comfyAPI.utils || {};
window.comfyAPI.utils.clone = clone$3;
window.comfyAPI.utils.applyTextReplacements = applyTextReplacements;
window.comfyAPI.utils.addStylesheet = addStylesheet;
window.comfyAPI.utils.downloadBlob = downloadBlob;
window.comfyAPI.utils.uploadFile = uploadFile;
window.comfyAPI.utils.prop = prop;
window.comfyAPI.utils.getStorageValue = getStorageValue;
window.comfyAPI.utils.setStorageValue = setStorageValue;
class Processor {
  static {
    __name(this, "Processor");
  }
  constructor(options2) {
    this.selfOptions = options2 || {};
    this.pipes = {};
  }
  options(options2) {
    if (options2) {
      this.selfOptions = options2;
    }
    return this.selfOptions;
  }
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  pipe(name2, pipeArg) {
    let pipe = pipeArg;
    if (typeof name2 === "string") {
      if (typeof pipe === "undefined") {
        return this.pipes[name2];
      } else {
        this.pipes[name2] = pipe;
      }
    }
    if (name2 && name2.name) {
      pipe = name2;
      if (pipe.processor === this) {
        return pipe;
      }
      this.pipes[pipe.name] = pipe;
    }
    pipe.processor = this;
    return pipe;
  }
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  process(input, pipe) {
    let context = input;
    context.options = this.options();
    let nextPipe = pipe || input.pipe || "default";
    let lastPipe;
    while (nextPipe) {
      if (typeof context.nextAfterChildren !== "undefined") {
        context.next = context.nextAfterChildren;
        context.nextAfterChildren = null;
      }
      if (typeof nextPipe === "string") {
        nextPipe = this.pipe(nextPipe);
      }
      nextPipe.process(context);
      lastPipe = nextPipe;
      nextPipe = null;
      if (context) {
        if (context.next) {
          context = context.next;
          nextPipe = context.pipe || lastPipe;
        }
      }
    }
    return context.hasResult ? context.result : void 0;
  }
}
class Pipe {
  static {
    __name(this, "Pipe");
  }
  constructor(name2) {
    this.name = name2;
    this.filters = [];
  }
  process(input) {
    if (!this.processor) {
      throw new Error("add this pipe to a processor before using it");
    }
    const debug = this.debug;
    const length = this.filters.length;
    const context = input;
    for (let index2 = 0; index2 < length; index2++) {
      const filter3 = this.filters[index2];
      if (debug) {
        this.log(`filter: ${filter3.filterName}`);
      }
      filter3(context);
      if (typeof context === "object" && context.exiting) {
        context.exiting = false;
        break;
      }
    }
    if (!context.next && this.resultCheck) {
      this.resultCheck(context);
    }
  }
  log(msg) {
    console.log(`[jsondiffpatch] ${this.name} pipe, ${msg}`);
  }
  append(...args) {
    this.filters.push(...args);
    return this;
  }
  prepend(...args) {
    this.filters.unshift(...args);
    return this;
  }
  indexOf(filterName) {
    if (!filterName) {
      throw new Error("a filter name is required");
    }
    for (let index2 = 0; index2 < this.filters.length; index2++) {
      const filter3 = this.filters[index2];
      if (filter3.filterName === filterName) {
        return index2;
      }
    }
    throw new Error(`filter not found: ${filterName}`);
  }
  list() {
    return this.filters.map((f2) => f2.filterName);
  }
  after(filterName, ...params) {
    const index2 = this.indexOf(filterName);
    this.filters.splice(index2 + 1, 0, ...params);
    return this;
  }
  before(filterName, ...params) {
    const index2 = this.indexOf(filterName);
    this.filters.splice(index2, 0, ...params);
    return this;
  }
  replace(filterName, ...params) {
    const index2 = this.indexOf(filterName);
    this.filters.splice(index2, 1, ...params);
    return this;
  }
  remove(filterName) {
    const index2 = this.indexOf(filterName);
    this.filters.splice(index2, 1);
    return this;
  }
  clear() {
    this.filters.length = 0;
    return this;
  }
  shouldHaveResult(should) {
    if (should === false) {
      this.resultCheck = null;
      return;
    }
    if (this.resultCheck) {
      return;
    }
    this.resultCheck = (context) => {
      if (!context.hasResult) {
        console.log(context);
        const error2 = new Error(`${this.name} failed`);
        error2.noResult = true;
        throw error2;
      }
    };
    return this;
  }
}
class Context {
  static {
    __name(this, "Context");
  }
  setResult(result) {
    this.result = result;
    this.hasResult = true;
    return this;
  }
  exit() {
    this.exiting = true;
    return this;
  }
  push(child2, name2) {
    child2.parent = this;
    if (typeof name2 !== "undefined") {
      child2.childName = name2;
    }
    child2.root = this.root || this;
    child2.options = child2.options || this.options;
    if (!this.children) {
      this.children = [child2];
      this.nextAfterChildren = this.next || null;
      this.next = child2;
    } else {
      this.children[this.children.length - 1].next = child2;
      this.children.push(child2);
    }
    child2.next = this;
    return this;
  }
}
function cloneRegExp(re2) {
  const regexMatch = /^\/(.*)\/([gimyu]*)$/.exec(re2.toString());
  return new RegExp(regexMatch[1], regexMatch[2]);
}
__name(cloneRegExp, "cloneRegExp");
function clone$2(arg) {
  if (typeof arg !== "object") {
    return arg;
  }
  if (arg === null) {
    return null;
  }
  if (Array.isArray(arg)) {
    return arg.map(clone$2);
  }
  if (arg instanceof Date) {
    return new Date(arg.getTime());
  }
  if (arg instanceof RegExp) {
    return cloneRegExp(arg);
  }
  const cloned = {};
  for (const name2 in arg) {
    if (Object.prototype.hasOwnProperty.call(arg, name2)) {
      cloned[name2] = clone$2(arg[name2]);
    }
  }
  return cloned;
}
__name(clone$2, "clone$2");
class DiffContext extends Context {
  static {
    __name(this, "DiffContext");
  }
  constructor(left, right) {
    super();
    this.left = left;
    this.right = right;
    this.pipe = "diff";
  }
  setResult(result) {
    if (this.options.cloneDiffValues && typeof result === "object") {
      const clone2 = typeof this.options.cloneDiffValues === "function" ? this.options.cloneDiffValues : clone$2;
      if (typeof result[0] === "object") {
        result[0] = clone2(result[0]);
      }
      if (typeof result[1] === "object") {
        result[1] = clone2(result[1]);
      }
    }
    return super.setResult(result);
  }
}
class PatchContext extends Context {
  static {
    __name(this, "PatchContext");
  }
  constructor(left, delta2) {
    super();
    this.left = left;
    this.delta = delta2;
    this.pipe = "patch";
  }
}
class ReverseContext extends Context {
  static {
    __name(this, "ReverseContext");
  }
  constructor(delta2) {
    super();
    this.delta = delta2;
    this.pipe = "reverse";
  }
}
const diffFilter$3 = /* @__PURE__ */ __name(function trivialMatchesDiffFilter(context) {
  if (context.left === context.right) {
    context.setResult(void 0).exit();
    return;
  }
  if (typeof context.left === "undefined") {
    if (typeof context.right === "function") {
      throw new Error("functions are not supported");
    }
    context.setResult([context.right]).exit();
    return;
  }
  if (typeof context.right === "undefined") {
    context.setResult([context.left, 0, 0]).exit();
    return;
  }
  if (typeof context.left === "function" || typeof context.right === "function") {
    throw new Error("functions are not supported");
  }
  context.leftType = context.left === null ? "null" : typeof context.left;
  context.rightType = context.right === null ? "null" : typeof context.right;
  if (context.leftType !== context.rightType) {
    context.setResult([context.left, context.right]).exit();
    return;
  }
  if (context.leftType === "boolean" || context.leftType === "number") {
    context.setResult([context.left, context.right]).exit();
    return;
  }
  if (context.leftType === "object") {
    context.leftIsArray = Array.isArray(context.left);
  }
  if (context.rightType === "object") {
    context.rightIsArray = Array.isArray(context.right);
  }
  if (context.leftIsArray !== context.rightIsArray) {
    context.setResult([context.left, context.right]).exit();
    return;
  }
  if (context.left instanceof RegExp) {
    if (context.right instanceof RegExp) {
      context.setResult([context.left.toString(), context.right.toString()]).exit();
    } else {
      context.setResult([context.left, context.right]).exit();
    }
  }
}, "trivialMatchesDiffFilter");
diffFilter$3.filterName = "trivial";
const patchFilter$3 = /* @__PURE__ */ __name(function trivialMatchesPatchFilter(context) {
  if (typeof context.delta === "undefined") {
    context.setResult(context.left).exit();
    return;
  }
  context.nested = !Array.isArray(context.delta);
  if (context.nested) {
    return;
  }
  const nonNestedDelta = context.delta;
  if (nonNestedDelta.length === 1) {
    context.setResult(nonNestedDelta[0]).exit();
    return;
  }
  if (nonNestedDelta.length === 2) {
    if (context.left instanceof RegExp) {
      const regexArgs = /^\/(.*)\/([gimyu]+)$/.exec(nonNestedDelta[1]);
      if (regexArgs) {
        context.setResult(new RegExp(regexArgs[1], regexArgs[2])).exit();
        return;
      }
    }
    context.setResult(nonNestedDelta[1]).exit();
    return;
  }
  if (nonNestedDelta.length === 3 && nonNestedDelta[2] === 0) {
    context.setResult(void 0).exit();
  }
}, "trivialMatchesPatchFilter");
patchFilter$3.filterName = "trivial";
const reverseFilter$3 = /* @__PURE__ */ __name(function trivialReferseFilter(context) {
  if (typeof context.delta === "undefined") {
    context.setResult(context.delta).exit();
    return;
  }
  context.nested = !Array.isArray(context.delta);
  if (context.nested) {
    return;
  }
  const nonNestedDelta = context.delta;
  if (nonNestedDelta.length === 1) {
    context.setResult([nonNestedDelta[0], 0, 0]).exit();
    return;
  }
  if (nonNestedDelta.length === 2) {
    context.setResult([nonNestedDelta[1], nonNestedDelta[0]]).exit();
    return;
  }
  if (nonNestedDelta.length === 3 && nonNestedDelta[2] === 0) {
    context.setResult([nonNestedDelta[0]]).exit();
  }
}, "trivialReferseFilter");
reverseFilter$3.filterName = "trivial";
const collectChildrenDiffFilter = /* @__PURE__ */ __name((context) => {
  if (!context || !context.children) {
    return;
  }
  const length = context.children.length;
  let child2;
  let result = context.result;
  for (let index2 = 0; index2 < length; index2++) {
    child2 = context.children[index2];
    if (typeof child2.result === "undefined") {
      continue;
    }
    result = result || {};
    result[child2.childName] = child2.result;
  }
  if (result && context.leftIsArray) {
    result._t = "a";
  }
  context.setResult(result).exit();
}, "collectChildrenDiffFilter");
collectChildrenDiffFilter.filterName = "collectChildren";
const objectsDiffFilter = /* @__PURE__ */ __name((context) => {
  if (context.leftIsArray || context.leftType !== "object") {
    return;
  }
  const left = context.left;
  const right = context.right;
  let name2;
  let child2;
  const propertyFilter = context.options.propertyFilter;
  for (name2 in left) {
    if (!Object.prototype.hasOwnProperty.call(left, name2)) {
      continue;
    }
    if (propertyFilter && !propertyFilter(name2, context)) {
      continue;
    }
    child2 = new DiffContext(left[name2], right[name2]);
    context.push(child2, name2);
  }
  for (name2 in right) {
    if (!Object.prototype.hasOwnProperty.call(right, name2)) {
      continue;
    }
    if (propertyFilter && !propertyFilter(name2, context)) {
      continue;
    }
    if (typeof left[name2] === "undefined") {
      child2 = new DiffContext(void 0, right[name2]);
      context.push(child2, name2);
    }
  }
  if (!context.children || context.children.length === 0) {
    context.setResult(void 0).exit();
    return;
  }
  context.exit();
}, "objectsDiffFilter");
objectsDiffFilter.filterName = "objects";
const patchFilter$2 = /* @__PURE__ */ __name(function nestedPatchFilter(context) {
  if (!context.nested) {
    return;
  }
  const nestedDelta = context.delta;
  if (nestedDelta._t) {
    return;
  }
  const objectDelta = nestedDelta;
  let name2;
  let child2;
  for (name2 in objectDelta) {
    child2 = new PatchContext(context.left[name2], objectDelta[name2]);
    context.push(child2, name2);
  }
  context.exit();
}, "nestedPatchFilter");
patchFilter$2.filterName = "objects";
const collectChildrenPatchFilter$1 = /* @__PURE__ */ __name(function collectChildrenPatchFilter2(context) {
  if (!context || !context.children) {
    return;
  }
  const deltaWithChildren = context.delta;
  if (deltaWithChildren._t) {
    return;
  }
  const object = context.left;
  const length = context.children.length;
  let child2;
  for (let index2 = 0; index2 < length; index2++) {
    child2 = context.children[index2];
    const property = child2.childName;
    if (Object.prototype.hasOwnProperty.call(context.left, property) && child2.result === void 0) {
      delete object[property];
    } else if (object[property] !== child2.result) {
      object[property] = child2.result;
    }
  }
  context.setResult(object).exit();
}, "collectChildrenPatchFilter");
collectChildrenPatchFilter$1.filterName = "collectChildren";
const reverseFilter$2 = /* @__PURE__ */ __name(function nestedReverseFilter(context) {
  if (!context.nested) {
    return;
  }
  const nestedDelta = context.delta;
  if (nestedDelta._t) {
    return;
  }
  const objectDelta = context.delta;
  let name2;
  let child2;
  for (name2 in objectDelta) {
    child2 = new ReverseContext(objectDelta[name2]);
    context.push(child2, name2);
  }
  context.exit();
}, "nestedReverseFilter");
reverseFilter$2.filterName = "objects";
const collectChildrenReverseFilter$1 = /* @__PURE__ */ __name((context) => {
  if (!context || !context.children) {
    return;
  }
  const deltaWithChildren = context.delta;
  if (deltaWithChildren._t) {
    return;
  }
  const length = context.children.length;
  let child2;
  const delta2 = {};
  for (let index2 = 0; index2 < length; index2++) {
    child2 = context.children[index2];
    const property = child2.childName;
    if (delta2[property] !== child2.result) {
      delta2[property] = child2.result;
    }
  }
  context.setResult(delta2).exit();
}, "collectChildrenReverseFilter$1");
collectChildrenReverseFilter$1.filterName = "collectChildren";
const defaultMatch = /* @__PURE__ */ __name(function(array1, array2, index1, index2) {
  return array1[index1] === array2[index2];
}, "defaultMatch");
const lengthMatrix = /* @__PURE__ */ __name(function(array1, array2, match2, context) {
  const len1 = array1.length;
  const len2 = array2.length;
  let x2, y2;
  const matrix = new Array(len1 + 1);
  for (x2 = 0; x2 < len1 + 1; x2++) {
    matrix[x2] = new Array(len2 + 1);
    for (y2 = 0; y2 < len2 + 1; y2++) {
      matrix[x2][y2] = 0;
    }
  }
  matrix.match = match2;
  for (x2 = 1; x2 < len1 + 1; x2++) {
    for (y2 = 1; y2 < len2 + 1; y2++) {
      if (match2(array1, array2, x2 - 1, y2 - 1, context)) {
        matrix[x2][y2] = matrix[x2 - 1][y2 - 1] + 1;
      } else {
        matrix[x2][y2] = Math.max(matrix[x2 - 1][y2], matrix[x2][y2 - 1]);
      }
    }
  }
  return matrix;
}, "lengthMatrix");
const backtrack = /* @__PURE__ */ __name(function(matrix, array1, array2, context) {
  let index1 = array1.length;
  let index2 = array2.length;
  const subsequence = {
    sequence: [],
    indices1: [],
    indices2: []
  };
  while (index1 !== 0 && index2 !== 0) {
    const sameLetter = matrix.match(array1, array2, index1 - 1, index2 - 1, context);
    if (sameLetter) {
      subsequence.sequence.unshift(array1[index1 - 1]);
      subsequence.indices1.unshift(index1 - 1);
      subsequence.indices2.unshift(index2 - 1);
      --index1;
      --index2;
    } else {
      const valueAtMatrixAbove = matrix[index1][index2 - 1];
      const valueAtMatrixLeft = matrix[index1 - 1][index2];
      if (valueAtMatrixAbove > valueAtMatrixLeft) {
        --index2;
      } else {
        --index1;
      }
    }
  }
  return subsequence;
}, "backtrack");
const get = /* @__PURE__ */ __name(function(array1, array2, match2, context) {
  const innerContext = context || {};
  const matrix = lengthMatrix(array1, array2, match2 || defaultMatch, innerContext);
  return backtrack(matrix, array1, array2, innerContext);
}, "get");
const lcs = {
  get
};
const ARRAY_MOVE = 3;
function arraysHaveMatchByRef(array1, array2, len1, len2) {
  for (let index1 = 0; index1 < len1; index1++) {
    const val1 = array1[index1];
    for (let index2 = 0; index2 < len2; index2++) {
      const val2 = array2[index2];
      if (index1 !== index2 && val1 === val2) {
        return true;
      }
    }
  }
}
__name(arraysHaveMatchByRef, "arraysHaveMatchByRef");
function matchItems(array1, array2, index1, index2, context) {
  const value1 = array1[index1];
  const value2 = array2[index2];
  if (value1 === value2) {
    return true;
  }
  if (typeof value1 !== "object" || typeof value2 !== "object") {
    return false;
  }
  const objectHash = context.objectHash;
  if (!objectHash) {
    return context.matchByPosition && index1 === index2;
  }
  context.hashCache1 = context.hashCache1 || [];
  let hash1 = context.hashCache1[index1];
  if (typeof hash1 === "undefined") {
    context.hashCache1[index1] = hash1 = objectHash(value1, index1);
  }
  if (typeof hash1 === "undefined") {
    return false;
  }
  context.hashCache2 = context.hashCache2 || [];
  let hash2 = context.hashCache2[index2];
  if (typeof hash2 === "undefined") {
    context.hashCache2[index2] = hash2 = objectHash(value2, index2);
  }
  if (typeof hash2 === "undefined") {
    return false;
  }
  return hash1 === hash2;
}
__name(matchItems, "matchItems");
const diffFilter$2 = /* @__PURE__ */ __name(function arraysDiffFilter(context) {
  if (!context.leftIsArray) {
    return;
  }
  const matchContext = {
    objectHash: context.options && context.options.objectHash,
    matchByPosition: context.options && context.options.matchByPosition
  };
  let commonHead = 0;
  let commonTail = 0;
  let index2;
  let index1;
  let index22;
  const array1 = context.left;
  const array2 = context.right;
  const len1 = array1.length;
  const len2 = array2.length;
  let child2;
  if (len1 > 0 && len2 > 0 && !matchContext.objectHash && typeof matchContext.matchByPosition !== "boolean") {
    matchContext.matchByPosition = !arraysHaveMatchByRef(array1, array2, len1, len2);
  }
  while (commonHead < len1 && commonHead < len2 && matchItems(array1, array2, commonHead, commonHead, matchContext)) {
    index2 = commonHead;
    child2 = new DiffContext(array1[index2], array2[index2]);
    context.push(child2, index2);
    commonHead++;
  }
  while (commonTail + commonHead < len1 && commonTail + commonHead < len2 && matchItems(array1, array2, len1 - 1 - commonTail, len2 - 1 - commonTail, matchContext)) {
    index1 = len1 - 1 - commonTail;
    index22 = len2 - 1 - commonTail;
    child2 = new DiffContext(array1[index1], array2[index22]);
    context.push(child2, index22);
    commonTail++;
  }
  let result;
  if (commonHead + commonTail === len1) {
    if (len1 === len2) {
      context.setResult(void 0).exit();
      return;
    }
    result = result || {
      _t: "a"
    };
    for (index2 = commonHead; index2 < len2 - commonTail; index2++) {
      result[index2] = [array2[index2]];
    }
    context.setResult(result).exit();
    return;
  }
  if (commonHead + commonTail === len2) {
    result = result || {
      _t: "a"
    };
    for (index2 = commonHead; index2 < len1 - commonTail; index2++) {
      result[`_${index2}`] = [array1[index2], 0, 0];
    }
    context.setResult(result).exit();
    return;
  }
  delete matchContext.hashCache1;
  delete matchContext.hashCache2;
  const trimmed1 = array1.slice(commonHead, len1 - commonTail);
  const trimmed2 = array2.slice(commonHead, len2 - commonTail);
  const seq = lcs.get(trimmed1, trimmed2, matchItems, matchContext);
  const removedItems = [];
  result = result || {
    _t: "a"
  };
  for (index2 = commonHead; index2 < len1 - commonTail; index2++) {
    if (seq.indices1.indexOf(index2 - commonHead) < 0) {
      result[`_${index2}`] = [array1[index2], 0, 0];
      removedItems.push(index2);
    }
  }
  let detectMove = true;
  if (context.options && context.options.arrays && context.options.arrays.detectMove === false) {
    detectMove = false;
  }
  let includeValueOnMove = false;
  if (context.options && context.options.arrays && context.options.arrays.includeValueOnMove) {
    includeValueOnMove = true;
  }
  const removedItemsLength = removedItems.length;
  for (index2 = commonHead; index2 < len2 - commonTail; index2++) {
    const indexOnArray2 = seq.indices2.indexOf(index2 - commonHead);
    if (indexOnArray2 < 0) {
      let isMove = false;
      if (detectMove && removedItemsLength > 0) {
        for (let removeItemIndex1 = 0; removeItemIndex1 < removedItemsLength; removeItemIndex1++) {
          index1 = removedItems[removeItemIndex1];
          if (matchItems(trimmed1, trimmed2, index1 - commonHead, index2 - commonHead, matchContext)) {
            result[`_${index1}`].splice(1, 2, index2, ARRAY_MOVE);
            if (!includeValueOnMove) {
              result[`_${index1}`][0] = "";
            }
            index22 = index2;
            child2 = new DiffContext(array1[index1], array2[index22]);
            context.push(child2, index22);
            removedItems.splice(removeItemIndex1, 1);
            isMove = true;
            break;
          }
        }
      }
      if (!isMove) {
        result[index2] = [array2[index2]];
      }
    } else {
      index1 = seq.indices1[indexOnArray2] + commonHead;
      index22 = seq.indices2[indexOnArray2] + commonHead;
      child2 = new DiffContext(array1[index1], array2[index22]);
      context.push(child2, index22);
    }
  }
  context.setResult(result).exit();
}, "arraysDiffFilter");
diffFilter$2.filterName = "arrays";
const compare = {
  numerically(a2, b2) {
    return a2 - b2;
  },
  numericallyBy(name2) {
    return (a2, b2) => a2[name2] - b2[name2];
  }
};
const patchFilter$1 = /* @__PURE__ */ __name(function nestedPatchFilter2(context) {
  if (!context.nested) {
    return;
  }
  const nestedDelta = context.delta;
  if (nestedDelta._t !== "a") {
    return;
  }
  let index2;
  let index1;
  const delta2 = nestedDelta;
  const array = context.left;
  let toRemove = [];
  let toInsert = [];
  const toModify = [];
  for (index2 in delta2) {
    if (index2 !== "_t") {
      if (index2[0] === "_") {
        const removedOrMovedIndex = index2;
        if (delta2[removedOrMovedIndex][2] === 0 || delta2[removedOrMovedIndex][2] === ARRAY_MOVE) {
          toRemove.push(parseInt(index2.slice(1), 10));
        } else {
          throw new Error(`only removal or move can be applied at original array indices, invalid diff type: ${delta2[removedOrMovedIndex][2]}`);
        }
      } else {
        const numberIndex = index2;
        if (delta2[numberIndex].length === 1) {
          toInsert.push({
            index: parseInt(numberIndex, 10),
            value: delta2[numberIndex][0]
          });
        } else {
          toModify.push({
            index: parseInt(numberIndex, 10),
            delta: delta2[numberIndex]
          });
        }
      }
    }
  }
  toRemove = toRemove.sort(compare.numerically);
  for (index2 = toRemove.length - 1; index2 >= 0; index2--) {
    index1 = toRemove[index2];
    const indexDiff = delta2[`_${index1}`];
    const removedValue = array.splice(index1, 1)[0];
    if (indexDiff[2] === ARRAY_MOVE) {
      toInsert.push({
        index: indexDiff[1],
        value: removedValue
      });
    }
  }
  toInsert = toInsert.sort(compare.numericallyBy("index"));
  const toInsertLength = toInsert.length;
  for (index2 = 0; index2 < toInsertLength; index2++) {
    const insertion = toInsert[index2];
    array.splice(insertion.index, 0, insertion.value);
  }
  const toModifyLength = toModify.length;
  let child2;
  if (toModifyLength > 0) {
    for (index2 = 0; index2 < toModifyLength; index2++) {
      const modification = toModify[index2];
      child2 = new PatchContext(array[modification.index], modification.delta);
      context.push(child2, modification.index);
    }
  }
  if (!context.children) {
    context.setResult(array).exit();
    return;
  }
  context.exit();
}, "nestedPatchFilter");
patchFilter$1.filterName = "arrays";
const collectChildrenPatchFilter = /* @__PURE__ */ __name(function collectChildrenPatchFilter3(context) {
  if (!context || !context.children) {
    return;
  }
  const deltaWithChildren = context.delta;
  if (deltaWithChildren._t !== "a") {
    return;
  }
  const array = context.left;
  const length = context.children.length;
  let child2;
  for (let index2 = 0; index2 < length; index2++) {
    child2 = context.children[index2];
    const arrayIndex = child2.childName;
    array[arrayIndex] = child2.result;
  }
  context.setResult(array).exit();
}, "collectChildrenPatchFilter");
collectChildrenPatchFilter.filterName = "arraysCollectChildren";
const reverseFilter$1 = /* @__PURE__ */ __name(function arraysReverseFilter(context) {
  if (!context.nested) {
    const nonNestedDelta = context.delta;
    if (nonNestedDelta[2] === ARRAY_MOVE) {
      const arrayMoveDelta = nonNestedDelta;
      context.newName = `_${arrayMoveDelta[1]}`;
      context.setResult([
        arrayMoveDelta[0],
        parseInt(context.childName.substring(1), 10),
        ARRAY_MOVE
      ]).exit();
    }
    return;
  }
  const nestedDelta = context.delta;
  if (nestedDelta._t !== "a") {
    return;
  }
  const arrayDelta = nestedDelta;
  let name2;
  let child2;
  for (name2 in arrayDelta) {
    if (name2 === "_t") {
      continue;
    }
    child2 = new ReverseContext(arrayDelta[name2]);
    context.push(child2, name2);
  }
  context.exit();
}, "arraysReverseFilter");
reverseFilter$1.filterName = "arrays";
const reverseArrayDeltaIndex = /* @__PURE__ */ __name((delta2, index2, itemDelta) => {
  if (typeof index2 === "string" && index2[0] === "_") {
    return parseInt(index2.substring(1), 10);
  } else if (Array.isArray(itemDelta) && itemDelta[2] === 0) {
    return `_${index2}`;
  }
  let reverseIndex = +index2;
  for (const deltaIndex in delta2) {
    const deltaItem = delta2[deltaIndex];
    if (Array.isArray(deltaItem)) {
      if (deltaItem[2] === ARRAY_MOVE) {
        const moveFromIndex = parseInt(deltaIndex.substring(1), 10);
        const moveToIndex = deltaItem[1];
        if (moveToIndex === +index2) {
          return moveFromIndex;
        }
        if (moveFromIndex <= reverseIndex && moveToIndex > reverseIndex) {
          reverseIndex++;
        } else if (moveFromIndex >= reverseIndex && moveToIndex < reverseIndex) {
          reverseIndex--;
        }
      } else if (deltaItem[2] === 0) {
        const deleteIndex = parseInt(deltaIndex.substring(1), 10);
        if (deleteIndex <= reverseIndex) {
          reverseIndex++;
        }
      } else if (deltaItem.length === 1 && parseInt(deltaIndex, 10) <= reverseIndex) {
        reverseIndex--;
      }
    }
  }
  return reverseIndex;
}, "reverseArrayDeltaIndex");
const collectChildrenReverseFilter = /* @__PURE__ */ __name((context) => {
  if (!context || !context.children) {
    return;
  }
  const deltaWithChildren = context.delta;
  if (deltaWithChildren._t !== "a") {
    return;
  }
  const arrayDelta = deltaWithChildren;
  const length = context.children.length;
  let child2;
  const delta2 = {
    _t: "a"
  };
  for (let index2 = 0; index2 < length; index2++) {
    child2 = context.children[index2];
    let name2 = child2.newName;
    if (typeof name2 === "undefined") {
      name2 = reverseArrayDeltaIndex(arrayDelta, child2.childName, child2.result);
    }
    if (delta2[name2] !== child2.result) {
      delta2[name2] = child2.result;
    }
  }
  context.setResult(delta2).exit();
}, "collectChildrenReverseFilter");
collectChildrenReverseFilter.filterName = "arraysCollectChildren";
const diffFilter$1 = /* @__PURE__ */ __name(function datesDiffFilter(context) {
  if (context.left instanceof Date) {
    if (context.right instanceof Date) {
      if (context.left.getTime() !== context.right.getTime()) {
        context.setResult([context.left, context.right]);
      } else {
        context.setResult(void 0);
      }
    } else {
      context.setResult([context.left, context.right]);
    }
    context.exit();
  } else if (context.right instanceof Date) {
    context.setResult([context.left, context.right]).exit();
  }
}, "datesDiffFilter");
diffFilter$1.filterName = "dates";
const TEXT_DIFF = 2;
const DEFAULT_MIN_LENGTH = 60;
let cachedDiffPatch = null;
function getDiffMatchPatch(options2, required) {
  var _a2;
  if (!cachedDiffPatch) {
    let instance;
    if ((_a2 = options2 === null || options2 === void 0 ? void 0 : options2.textDiff) === null || _a2 === void 0 ? void 0 : _a2.diffMatchPatch) {
      instance = new options2.textDiff.diffMatchPatch();
    } else {
      if (!required) {
        return null;
      }
      const error2 = new Error("The diff-match-patch library was not provided. Pass the library in through the options or use the `jsondiffpatch/with-text-diffs` entry-point.");
      error2.diff_match_patch_not_found = true;
      throw error2;
    }
    cachedDiffPatch = {
      diff: /* @__PURE__ */ __name(function(txt1, txt2) {
        return instance.patch_toText(instance.patch_make(txt1, txt2));
      }, "diff"),
      patch: /* @__PURE__ */ __name(function(txt1, patch2) {
        const results = instance.patch_apply(instance.patch_fromText(patch2), txt1);
        for (let i2 = 0; i2 < results[1].length; i2++) {
          if (!results[1][i2]) {
            const error2 = new Error("text patch failed");
            error2.textPatchFailed = true;
          }
        }
        return results[0];
      }, "patch")
    };
  }
  return cachedDiffPatch;
}
__name(getDiffMatchPatch, "getDiffMatchPatch");
const diffFilter = /* @__PURE__ */ __name(function textsDiffFilter(context) {
  if (context.leftType !== "string") {
    return;
  }
  const left = context.left;
  const right = context.right;
  const minLength = context.options && context.options.textDiff && context.options.textDiff.minLength || DEFAULT_MIN_LENGTH;
  if (left.length < minLength || right.length < minLength) {
    context.setResult([left, right]).exit();
    return;
  }
  const diffMatchPatch = getDiffMatchPatch(context.options);
  if (!diffMatchPatch) {
    context.setResult([left, right]).exit();
    return;
  }
  const diff2 = diffMatchPatch.diff;
  context.setResult([diff2(left, right), 0, TEXT_DIFF]).exit();
}, "textsDiffFilter");
diffFilter.filterName = "texts";
const patchFilter = /* @__PURE__ */ __name(function textsPatchFilter(context) {
  if (context.nested) {
    return;
  }
  const nonNestedDelta = context.delta;
  if (nonNestedDelta[2] !== TEXT_DIFF) {
    return;
  }
  const textDiffDelta = nonNestedDelta;
  const patch2 = getDiffMatchPatch(context.options, true).patch;
  context.setResult(patch2(context.left, textDiffDelta[0])).exit();
}, "textsPatchFilter");
patchFilter.filterName = "texts";
const textDeltaReverse = /* @__PURE__ */ __name(function(delta2) {
  let i2;
  let l2;
  let line;
  let lineTmp;
  let header = null;
  const headerRegex = /^@@ +-(\d+),(\d+) +\+(\d+),(\d+) +@@$/;
  let lineHeader;
  const lines = delta2.split("\n");
  for (i2 = 0, l2 = lines.length; i2 < l2; i2++) {
    line = lines[i2];
    const lineStart = line.slice(0, 1);
    if (lineStart === "@") {
      header = headerRegex.exec(line);
      lineHeader = i2;
      lines[lineHeader] = "@@ -" + header[3] + "," + header[4] + " +" + header[1] + "," + header[2] + " @@";
    } else if (lineStart === "+") {
      lines[i2] = "-" + lines[i2].slice(1);
      if (lines[i2 - 1].slice(0, 1) === "+") {
        lineTmp = lines[i2];
        lines[i2] = lines[i2 - 1];
        lines[i2 - 1] = lineTmp;
      }
    } else if (lineStart === "-") {
      lines[i2] = "+" + lines[i2].slice(1);
    }
  }
  return lines.join("\n");
}, "textDeltaReverse");
const reverseFilter = /* @__PURE__ */ __name(function textsReverseFilter(context) {
  if (context.nested) {
    return;
  }
  const nonNestedDelta = context.delta;
  if (nonNestedDelta[2] !== TEXT_DIFF) {
    return;
  }
  const textDiffDelta = nonNestedDelta;
  context.setResult([textDeltaReverse(textDiffDelta[0]), 0, TEXT_DIFF]).exit();
}, "textsReverseFilter");
reverseFilter.filterName = "texts";
class DiffPatcher {
  static {
    __name(this, "DiffPatcher");
  }
  constructor(options2) {
    this.processor = new Processor(options2);
    this.processor.pipe(new Pipe("diff").append(collectChildrenDiffFilter, diffFilter$3, diffFilter$1, diffFilter, objectsDiffFilter, diffFilter$2).shouldHaveResult());
    this.processor.pipe(new Pipe("patch").append(collectChildrenPatchFilter$1, collectChildrenPatchFilter, patchFilter$3, patchFilter, patchFilter$2, patchFilter$1).shouldHaveResult());
    this.processor.pipe(new Pipe("reverse").append(collectChildrenReverseFilter$1, collectChildrenReverseFilter, reverseFilter$3, reverseFilter, reverseFilter$2, reverseFilter$1).shouldHaveResult());
  }
  options(options2) {
    return this.processor.options(options2);
  }
  diff(left, right) {
    return this.processor.process(new DiffContext(left, right));
  }
  patch(left, delta2) {
    return this.processor.process(new PatchContext(left, delta2));
  }
  reverse(delta2) {
    return this.processor.process(new ReverseContext(delta2));
  }
  unpatch(right, delta2) {
    return this.patch(right, this.reverse(delta2));
  }
  clone(value) {
    return clone$2(value);
  }
}
function dateReviver(key, value) {
  let parts2;
  if (typeof value === "string") {
    parts2 = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d*))?(Z|([+-])(\d{2}):(\d{2}))$/.exec(value);
    if (parts2) {
      return new Date(Date.UTC(+parts2[1], +parts2[2] - 1, +parts2[3], +parts2[4], +parts2[5], +parts2[6], +(parts2[7] || 0)));
    }
  }
  return value;
}
__name(dateReviver, "dateReviver");
function create(options2) {
  return new DiffPatcher(options2);
}
__name(create, "create");
let defaultInstance;
function diff(left, right) {
  if (!defaultInstance) {
    defaultInstance = new DiffPatcher();
  }
  return defaultInstance.diff(left, right);
}
__name(diff, "diff");
function patch(left, delta2) {
  if (!defaultInstance) {
    defaultInstance = new DiffPatcher();
  }
  return defaultInstance.patch(left, delta2);
}
__name(patch, "patch");
function unpatch(right, delta2) {
  if (!defaultInstance) {
    defaultInstance = new DiffPatcher();
  }
  return defaultInstance.unpatch(right, delta2);
}
__name(unpatch, "unpatch");
function reverse(delta2) {
  if (!defaultInstance) {
    defaultInstance = new DiffPatcher();
  }
  return defaultInstance.reverse(delta2);
}
__name(reverse, "reverse");
function clone$1(value) {
  if (!defaultInstance) {
    defaultInstance = new DiffPatcher();
  }
  return defaultInstance.clone(value);
}
__name(clone$1, "clone$1");
var loglevel$1 = { exports: {} };
var loglevel = loglevel$1.exports;
(function(module2) {
  (function(root2, definition) {
    "use strict";
    if (false) {
      (void 0)(definition);
    } else if (module2.exports) {
      module2.exports = definition();
    } else {
      root2.log = definition();
    }
  })(commonjsGlobal, function() {
    "use strict";
    var noop2 = /* @__PURE__ */ __name(function() {
    }, "noop");
    var undefinedType2 = "undefined";
    var isIE2 = typeof window !== undefinedType2 && typeof window.navigator !== undefinedType2 && /Trident\/|MSIE /.test(window.navigator.userAgent);
    var logMethods = [
      "trace",
      "debug",
      "info",
      "warn",
      "error"
    ];
    var _loggersByName = {};
    var defaultLogger = null;
    function bindMethod(obj, methodName) {
      var method = obj[methodName];
      if (typeof method.bind === "function") {
        return method.bind(obj);
      } else {
        try {
          return Function.prototype.bind.call(method, obj);
        } catch (e2) {
          return function() {
            return Function.prototype.apply.apply(method, [obj, arguments]);
          };
        }
      }
    }
    __name(bindMethod, "bindMethod");
    function traceForIE() {
      if (console.log) {
        if (console.log.apply) {
          console.log.apply(console, arguments);
        } else {
          Function.prototype.apply.apply(console.log, [console, arguments]);
        }
      }
      if (console.trace) console.trace();
    }
    __name(traceForIE, "traceForIE");
    function realMethod(methodName) {
      if (methodName === "debug") {
        methodName = "log";
      }
      if (typeof console === undefinedType2) {
        return false;
      } else if (methodName === "trace" && isIE2) {
        return traceForIE;
      } else if (console[methodName] !== void 0) {
        return bindMethod(console, methodName);
      } else if (console.log !== void 0) {
        return bindMethod(console, "log");
      } else {
        return noop2;
      }
    }
    __name(realMethod, "realMethod");
    function replaceLoggingMethods() {
      var level = this.getLevel();
      for (var i2 = 0; i2 < logMethods.length; i2++) {
        var methodName = logMethods[i2];
        this[methodName] = i2 < level ? noop2 : this.methodFactory(methodName, level, this.name);
      }
      this.log = this.debug;
      if (typeof console === undefinedType2 && level < this.levels.SILENT) {
        return "No console available for logging";
      }
    }
    __name(replaceLoggingMethods, "replaceLoggingMethods");
    function enableLoggingWhenConsoleArrives(methodName) {
      return function() {
        if (typeof console !== undefinedType2) {
          replaceLoggingMethods.call(this);
          this[methodName].apply(this, arguments);
        }
      };
    }
    __name(enableLoggingWhenConsoleArrives, "enableLoggingWhenConsoleArrives");
    function defaultMethodFactory(methodName, _level, _loggerName) {
      return realMethod(methodName) || enableLoggingWhenConsoleArrives.apply(this, arguments);
    }
    __name(defaultMethodFactory, "defaultMethodFactory");
    function Logger2(name2, factory2) {
      var self2 = this;
      var inheritedLevel;
      var defaultLevel;
      var userLevel;
      var storageKey = "loglevel";
      if (typeof name2 === "string") {
        storageKey += ":" + name2;
      } else if (typeof name2 === "symbol") {
        storageKey = void 0;
      }
      function persistLevelIfPossible(levelNum) {
        var levelName = (logMethods[levelNum] || "silent").toUpperCase();
        if (typeof window === undefinedType2 || !storageKey) return;
        try {
          window.localStorage[storageKey] = levelName;
          return;
        } catch (ignore) {
        }
        try {
          window.document.cookie = encodeURIComponent(storageKey) + "=" + levelName + ";";
        } catch (ignore) {
        }
      }
      __name(persistLevelIfPossible, "persistLevelIfPossible");
      function getPersistedLevel() {
        var storedLevel;
        if (typeof window === undefinedType2 || !storageKey) return;
        try {
          storedLevel = window.localStorage[storageKey];
        } catch (ignore) {
        }
        if (typeof storedLevel === undefinedType2) {
          try {
            var cookie = window.document.cookie;
            var cookieName = encodeURIComponent(storageKey);
            var location2 = cookie.indexOf(cookieName + "=");
            if (location2 !== -1) {
              storedLevel = /^([^;]+)/.exec(
                cookie.slice(location2 + cookieName.length + 1)
              )[1];
            }
          } catch (ignore) {
          }
        }
        if (self2.levels[storedLevel] === void 0) {
          storedLevel = void 0;
        }
        return storedLevel;
      }
      __name(getPersistedLevel, "getPersistedLevel");
      function clearPersistedLevel() {
        if (typeof window === undefinedType2 || !storageKey) return;
        try {
          window.localStorage.removeItem(storageKey);
        } catch (ignore) {
        }
        try {
          window.document.cookie = encodeURIComponent(storageKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
        } catch (ignore) {
        }
      }
      __name(clearPersistedLevel, "clearPersistedLevel");
      function normalizeLevel(input) {
        var level = input;
        if (typeof level === "string" && self2.levels[level.toUpperCase()] !== void 0) {
          level = self2.levels[level.toUpperCase()];
        }
        if (typeof level === "number" && level >= 0 && level <= self2.levels.SILENT) {
          return level;
        } else {
          throw new TypeError("log.setLevel() called with invalid level: " + input);
        }
      }
      __name(normalizeLevel, "normalizeLevel");
      self2.name = name2;
      self2.levels = {
        "TRACE": 0,
        "DEBUG": 1,
        "INFO": 2,
        "WARN": 3,
        "ERROR": 4,
        "SILENT": 5
      };
      self2.methodFactory = factory2 || defaultMethodFactory;
      self2.getLevel = function() {
        if (userLevel != null) {
          return userLevel;
        } else if (defaultLevel != null) {
          return defaultLevel;
        } else {
          return inheritedLevel;
        }
      };
      self2.setLevel = function(level, persist) {
        userLevel = normalizeLevel(level);
        if (persist !== false) {
          persistLevelIfPossible(userLevel);
        }
        return replaceLoggingMethods.call(self2);
      };
      self2.setDefaultLevel = function(level) {
        defaultLevel = normalizeLevel(level);
        if (!getPersistedLevel()) {
          self2.setLevel(level, false);
        }
      };
      self2.resetLevel = function() {
        userLevel = null;
        clearPersistedLevel();
        replaceLoggingMethods.call(self2);
      };
      self2.enableAll = function(persist) {
        self2.setLevel(self2.levels.TRACE, persist);
      };
      self2.disableAll = function(persist) {
        self2.setLevel(self2.levels.SILENT, persist);
      };
      self2.rebuild = function() {
        if (defaultLogger !== self2) {
          inheritedLevel = normalizeLevel(defaultLogger.getLevel());
        }
        replaceLoggingMethods.call(self2);
        if (defaultLogger === self2) {
          for (var childName in _loggersByName) {
            _loggersByName[childName].rebuild();
          }
        }
      };
      inheritedLevel = normalizeLevel(
        defaultLogger ? defaultLogger.getLevel() : "WARN"
      );
      var initialLevel = getPersistedLevel();
      if (initialLevel != null) {
        userLevel = normalizeLevel(initialLevel);
      }
      replaceLoggingMethods.call(self2);
    }
    __name(Logger2, "Logger");
    defaultLogger = new Logger2();
    defaultLogger.getLogger = /* @__PURE__ */ __name(function getLogger(name2) {
      if (typeof name2 !== "symbol" && typeof name2 !== "string" || name2 === "") {
        throw new TypeError("You must supply a name when creating a logger.");
      }
      var logger2 = _loggersByName[name2];
      if (!logger2) {
        logger2 = _loggersByName[name2] = new Logger2(
          name2,
          defaultLogger.methodFactory
        );
      }
      return logger2;
    }, "getLogger");
    var _log = typeof window !== undefinedType2 ? window.log : void 0;
    defaultLogger.noConflict = function() {
      if (typeof window !== undefinedType2 && window.log === defaultLogger) {
        window.log = _log;
      }
      return defaultLogger;
    };
    defaultLogger.getLoggers = /* @__PURE__ */ __name(function getLoggers() {
      return _loggersByName;
    }, "getLoggers");
    defaultLogger["default"] = defaultLogger;
    return defaultLogger;
  });
})(loglevel$1);
var loglevelExports = loglevel$1.exports;
const log = /* @__PURE__ */ getDefaultExportFromCjs(loglevelExports);
function clone(obj) {
  return JSON.parse(JSON.stringify(obj));
}
__name(clone, "clone");
const logger = log.getLogger("ChangeTracker");
logger.setLevel("info");
class ChangeTracker {
  static {
    __name(this, "ChangeTracker");
  }
  constructor(workflow, initialState) {
    this.workflow = workflow;
    this.initialState = initialState;
    this.activeState = initialState;
  }
  static MAX_HISTORY = 50;
  /**
   * The active state of the workflow.
   */
  activeState;
  undoQueue = [];
  redoQueue = [];
  changeCount = 0;
  /**
   * Whether the redo/undo restoring is in progress.
   */
  restoringState = false;
  ds;
  nodeOutputs;
  /**
   * Save the current state as the initial state.
   */
  reset(state) {
    if (this.restoringState) return;
    logger.debug("Reset State");
    if (state) this.activeState = clone(state);
    this.initialState = clone(this.activeState);
  }
  store() {
    this.ds = {
      scale: app$1.canvas.ds.scale,
      offset: [app$1.canvas.ds.offset[0], app$1.canvas.ds.offset[1]]
    };
  }
  restore() {
    if (this.ds) {
      app$1.canvas.ds.scale = this.ds.scale;
      app$1.canvas.ds.offset = this.ds.offset;
    }
    if (this.nodeOutputs) {
      app$1.nodeOutputs = this.nodeOutputs;
    }
  }
  updateModified() {
    api.dispatchCustomEvent("graphChanged", this.activeState);
    const workflow = useWorkflowStore().getWorkflowByPath(this.workflow.path);
    if (workflow) {
      workflow.isModified = !ChangeTracker.graphEqual(
        this.initialState,
        this.activeState
      );
      if (logger.getLevel() <= logger.levels.DEBUG && workflow.isModified) {
        const diff2 = ChangeTracker.graphDiff(
          this.initialState,
          this.activeState
        );
        logger.debug("Graph diff:", diff2);
      }
    }
  }
  checkState() {
    if (!app$1.graph || this.changeCount) return;
    const currentState = clone(app$1.graph.serialize());
    if (!this.activeState) {
      this.activeState = currentState;
      return;
    }
    if (!ChangeTracker.graphEqual(this.activeState, currentState)) {
      this.undoQueue.push(this.activeState);
      if (this.undoQueue.length > ChangeTracker.MAX_HISTORY) {
        this.undoQueue.shift();
      }
      logger.debug("Diff detected. Undo queue length:", this.undoQueue.length);
      this.activeState = currentState;
      this.redoQueue.length = 0;
      this.updateModified();
    }
  }
  async updateState(source, target) {
    const prevState = source.pop();
    if (prevState) {
      target.push(this.activeState);
      this.restoringState = true;
      try {
        await app$1.loadGraphData(prevState, false, false, this.workflow, {
          showMissingModelsDialog: false,
          showMissingNodesDialog: false,
          checkForRerouteMigration: false
        });
        this.activeState = prevState;
        this.updateModified();
      } finally {
        this.restoringState = false;
      }
    }
  }
  async undo() {
    await this.updateState(this.undoQueue, this.redoQueue);
    logger.debug(
      "Undo. Undo queue length:",
      this.undoQueue.length,
      "Redo queue length:",
      this.redoQueue.length
    );
  }
  async redo() {
    await this.updateState(this.redoQueue, this.undoQueue);
    logger.debug(
      "Redo. Undo queue length:",
      this.undoQueue.length,
      "Redo queue length:",
      this.redoQueue.length
    );
  }
  async undoRedo(e2) {
    if ((e2.ctrlKey || e2.metaKey) && !e2.altKey) {
      const key = e2.key.toUpperCase();
      if (key === "Y" && !e2.shiftKey || key == "Z" && e2.shiftKey) {
        await this.redo();
        return true;
      } else if (key === "Z" && !e2.shiftKey) {
        await this.undo();
        return true;
      }
    }
  }
  beforeChange() {
    this.changeCount++;
  }
  afterChange() {
    if (!--this.changeCount) {
      this.checkState();
    }
  }
  static init() {
    const getCurrentChangeTracker = /* @__PURE__ */ __name(() => useWorkflowStore().activeWorkflow?.changeTracker, "getCurrentChangeTracker");
    const checkState = /* @__PURE__ */ __name(() => getCurrentChangeTracker()?.checkState(), "checkState");
    let keyIgnored = false;
    window.addEventListener(
      "keydown",
      (e2) => {
        if (e2.repeat) return;
        const comfyApp = app$1.constructor;
        if (comfyApp.maskeditor_is_opended?.()) return;
        const activeEl = document.activeElement;
        requestAnimationFrame(async () => {
          let bindInputEl = null;
          if (!app$1.ui.autoQueueEnabled || app$1.ui.autoQueueMode === "instant") {
            if (activeEl?.tagName === "INPUT" || activeEl && "type" in activeEl && activeEl.type === "textarea") {
              return;
            }
            bindInputEl = activeEl;
          }
          keyIgnored = e2.key === "Control" || e2.key === "Shift" || e2.key === "Alt" || e2.key === "Meta";
          if (keyIgnored) return;
          const changeTracker = getCurrentChangeTracker();
          if (!changeTracker) return;
          if (await changeTracker.undoRedo(e2)) return;
          if (ChangeTracker.bindInput(bindInputEl)) return;
          logger.debug("checkState on keydown");
          changeTracker.checkState();
        });
      },
      true
    );
    window.addEventListener("keyup", () => {
      if (keyIgnored) {
        keyIgnored = false;
        logger.debug("checkState on keyup");
        checkState();
      }
    });
    window.addEventListener("mouseup", () => {
      logger.debug("checkState on mouseup");
      checkState();
    });
    api.addEventListener("promptQueued", () => {
      logger.debug("checkState on promptQueued");
      checkState();
    });
    api.addEventListener("graphCleared", () => {
      logger.debug("checkState on graphCleared");
      checkState();
    });
    const processMouseUp = LGraphCanvas.prototype.processMouseUp;
    LGraphCanvas.prototype.processMouseUp = function(e2) {
      const v2 = processMouseUp.apply(this, [e2]);
      logger.debug("checkState on processMouseUp");
      checkState();
      return v2;
    };
    const prompt = LGraphCanvas.prototype.prompt;
    LGraphCanvas.prototype.prompt = function(title, value, callback, event) {
      const extendedCallback = /* @__PURE__ */ __name((v2) => {
        callback(v2);
        checkState();
      }, "extendedCallback");
      logger.debug("checkState on prompt");
      return prompt.apply(this, [title, value, extendedCallback, event]);
    };
    const close2 = LiteGraph.ContextMenu.prototype.close;
    LiteGraph.ContextMenu.prototype.close = function(e2) {
      const v2 = close2.apply(this, [e2]);
      logger.debug("checkState on contextMenuClose");
      checkState();
      return v2;
    };
    document.addEventListener("litegraph:canvas", (e2) => {
      const detail = e2.detail;
      if (detail.subType === "before-change") {
        getCurrentChangeTracker()?.beforeChange();
      } else if (detail.subType === "after-change") {
        getCurrentChangeTracker()?.afterChange();
      }
    });
    api.addEventListener("executed", (e2) => {
      const detail = e2.detail;
      const workflow = useExecutionStore().queuedPrompts[detail.prompt_id]?.workflow;
      const changeTracker = workflow?.changeTracker;
      if (!changeTracker) return;
      changeTracker.nodeOutputs ??= {};
      const nodeOutputs = changeTracker.nodeOutputs;
      const output = nodeOutputs[detail.node];
      if (detail.merge && output) {
        for (const k2 in detail.output ?? {}) {
          const v2 = output[k2];
          if (v2 instanceof Array) {
            output[k2] = v2.concat(detail.output[k2]);
          } else {
            output[k2] = detail.output[k2];
          }
        }
      } else {
        nodeOutputs[detail.node] = detail.output;
      }
    });
  }
  static bindInput(activeEl) {
    if (!activeEl || activeEl.tagName === "CANVAS" || activeEl.tagName === "BODY") {
      return false;
    }
    for (const evt of ["change", "input", "blur"]) {
      const htmlElement = activeEl;
      if (`on${evt}` in htmlElement) {
        const listener = /* @__PURE__ */ __name(() => {
          useWorkflowStore().activeWorkflow?.changeTracker?.checkState?.();
          htmlElement.removeEventListener(evt, listener);
        }, "listener");
        htmlElement.addEventListener(evt, listener);
        return true;
      }
    }
    return false;
  }
  static graphEqual(a2, b2) {
    if (a2 === b2) return true;
    if (typeof a2 == "object" && a2 && typeof b2 == "object" && b2) {
      if (!_.isEqualWith(a2.nodes, b2.nodes, (arrA, arrB) => {
        if (Array.isArray(arrA) && Array.isArray(arrB)) {
          return _.isEqual(new Set(arrA), new Set(arrB));
        }
      })) {
        return false;
      }
      if (!_.isEqual(_.omit(a2.extra ?? {}, ["ds"]), _.omit(b2.extra ?? {}, ["ds"])))
        return false;
      for (const key of ["links", "floatingLinks", "reroutes", "groups"]) {
        if (!_.isEqual(a2[key], b2[key])) {
          return false;
        }
      }
      return true;
    }
    return false;
  }
  static graphDiff(a2, b2) {
    function sortGraphNodes(graph) {
      return {
        links: graph.links,
        groups: graph.groups,
        nodes: graph.nodes.sort((a22, b22) => {
          if (typeof a22.id === "number" && typeof b22.id === "number") {
            return a22.id - b22.id;
          }
          return 0;
        })
      };
    }
    __name(sortGraphNodes, "sortGraphNodes");
    return diff(sortGraphNodes(a2), sortGraphNodes(b2));
  }
}
window.comfyAPI = window.comfyAPI || {};
window.comfyAPI.changeTracker = window.comfyAPI.changeTracker || {};
window.comfyAPI.changeTracker.ChangeTracker = ChangeTracker;
async function syncEntities(dir, entityByPath, createEntity, updateEntity, exclude = () => false) {
  const files = (await api.listUserDataFullInfo(dir)).map((file) => ({
    ...file,
    path: dir ? `${dir}/${file.path}` : file.path
  }));
  for (const file of files) {
    const existingEntity = entityByPath[file.path];
    if (!existingEntity) {
      entityByPath[file.path] = createEntity(file);
    } else if (exclude(existingEntity)) {
      continue;
    } else {
      updateEntity(existingEntity, file);
    }
  }
  for (const [path, entity2] of Object.entries(entityByPath)) {
    if (exclude(entity2)) continue;
    if (!files.some((file) => file.path === path)) {
      delete entityByPath[path];
    }
  }
}
__name(syncEntities, "syncEntities");
class UserFile {
  static {
    __name(this, "UserFile");
  }
  constructor(path, lastModified, size) {
    this.path = path;
    this.lastModified = lastModified;
    this.size = size;
    const details = getPathDetails(path);
    this.path = path;
    this.directory = details.directory;
    this.fullFilename = details.fullFilename;
    this.filename = details.filename;
    this.suffix = details.suffix;
  }
  /**
   * Various path components.
   * Example:
   * - path: 'dir/file.txt'
   * - directory: 'dir'
   * - fullFilename: 'file.txt'
   * - filename: 'file'
   * - suffix: 'txt'
   */
  directory;
  fullFilename;
  filename;
  suffix;
  isLoading = false;
  content = null;
  originalContent = null;
  updatePath(newPath) {
    const details = getPathDetails(newPath);
    this.path = newPath;
    this.directory = details.directory;
    this.fullFilename = details.fullFilename;
    this.filename = details.filename;
    this.suffix = details.suffix;
  }
  static createTemporary(path) {
    return new UserFile(path, Date.now(), -1);
  }
  get isTemporary() {
    return this.size === -1;
  }
  get isPersisted() {
    return !this.isTemporary;
  }
  get key() {
    return this.path;
  }
  get isLoaded() {
    return this.content !== null;
  }
  get isModified() {
    return this.content !== this.originalContent;
  }
  /**
   * Loads the file content from the remote storage.
   */
  async load({
    force = false
  } = {}) {
    if (this.isTemporary || !force && this.isLoaded)
      return this;
    this.isLoading = true;
    const resp = await api.getUserData(this.path);
    if (resp.status !== 200) {
      throw new Error(
        `Failed to load file '${this.path}': ${resp.status} ${resp.statusText}`
      );
    }
    this.content = await resp.text();
    this.originalContent = this.content;
    this.isLoading = false;
    return this;
  }
  /**
   * Unloads the file content from memory
   */
  unload() {
    this.content = null;
    this.originalContent = null;
    this.isLoading = false;
  }
  async saveAs(newPath) {
    const tempFile = this.isTemporary ? this : UserFile.createTemporary(newPath);
    tempFile.content = this.content;
    await tempFile.save();
    return tempFile;
  }
  /**
   * Saves the file to the remote storage.
   * @param force Whether to force the save even if the file is not modified.
   */
  async save({ force = false } = {}) {
    if (this.isPersisted && !this.isModified && !force) return this;
    const resp = await api.storeUserData(this.path, this.content, {
      overwrite: this.isPersisted,
      throwOnError: true,
      full_info: true
    });
    const updatedFile = await resp.json();
    if (typeof updatedFile === "object") {
      this.lastModified = updatedFile.modified;
      this.size = updatedFile.size;
    }
    this.originalContent = this.content;
    return this;
  }
  async delete() {
    if (this.isTemporary) return;
    const resp = await api.deleteUserData(this.path);
    if (resp.status !== 204) {
      throw new Error(
        `Failed to delete file '${this.path}': ${resp.status} ${resp.statusText}`
      );
    }
  }
  async rename(newPath) {
    if (this.isTemporary) {
      this.updatePath(newPath);
      return this;
    }
    const resp = await api.moveUserData(this.path, newPath);
    if (resp.status !== 200) {
      throw new Error(
        `Failed to rename file '${this.path}': ${resp.status} ${resp.statusText}`
      );
    }
    this.updatePath(newPath);
    const updatedFile = await resp.json();
    if (typeof updatedFile === "object") {
      this.lastModified = updatedFile.modified;
      this.size = updatedFile.size;
    }
    return this;
  }
}
const useUserFileStore = /* @__PURE__ */ defineStore("userFile", () => {
  const userFilesByPath = ref$3({});
  const userFiles = computed(() => Object.values(userFilesByPath.value));
  const modifiedFiles = computed(
    () => userFiles.value.filter((file) => file.isModified)
  );
  const loadedFiles = computed(
    () => userFiles.value.filter((file) => file.isLoaded)
  );
  const fileTree = computed(
    () => buildTree$1(
      userFiles.value,
      (userFile) => userFile.path.split("/")
    )
  );
  const syncFiles = /* @__PURE__ */ __name(async (dir = "") => {
    await syncEntities(
      dir,
      userFilesByPath.value,
      (file) => new UserFile(file.path, file.modified, file.size),
      (existingFile, file) => {
        existingFile.lastModified = file.modified;
        existingFile.size = file.size;
        existingFile.unload();
      }
    );
  }, "syncFiles");
  return {
    userFiles,
    modifiedFiles,
    loadedFiles,
    fileTree,
    syncFiles
  };
});
class ComfyWorkflow extends UserFile {
  static {
    __name(this, "ComfyWorkflow");
  }
  static basePath = "workflows/";
  /**
   * The change tracker for the workflow. Non-reactive raw object.
   */
  changeTracker = null;
  /**
   * Whether the workflow has been modified comparing to the initial state.
   */
  _isModified = false;
  /**
   * @param options The path, modified, and size of the workflow.
   * Note: path is the full path, including the 'workflows/' prefix.
   */
  constructor(options2) {
    super(options2.path, options2.modified, options2.size);
  }
  get key() {
    return this.path.substring(ComfyWorkflow.basePath.length);
  }
  get activeState() {
    return this.changeTracker?.activeState ?? null;
  }
  get initialState() {
    return this.changeTracker?.initialState ?? null;
  }
  get isLoaded() {
    return this.changeTracker !== null;
  }
  get isModified() {
    return this._isModified;
  }
  set isModified(value) {
    this._isModified = value;
  }
  /**
   * Load the workflow content from remote storage. Directly returns the loaded
   * workflow if the content is already loaded.
   *
   * @param force Whether to force loading the content even if it is already loaded.
   * @returns this
   */
  async load({
    force = false
  } = {}) {
    await super.load({ force });
    if (!force && this.isLoaded) return this;
    if (!this.originalContent) {
      throw new Error("[ASSERT] Workflow content should be loaded");
    }
    console.debug("load and start tracking of workflow", this.path);
    this.changeTracker = markRaw(
      new ChangeTracker(
        this,
        /* initialState= */
        JSON.parse(this.originalContent)
      )
    );
    return this;
  }
  unload() {
    console.debug("unload workflow", this.path);
    this.changeTracker = null;
    super.unload();
  }
  async save() {
    this.content = JSON.stringify(this.activeState);
    const ret = await super.save({ force: true });
    this.changeTracker?.reset();
    this.isModified = false;
    return ret;
  }
  /**
   * Save the workflow as a new file.
   * @param path The path to save the workflow to. Note: with 'workflows/' prefix.
   * @returns this
   */
  async saveAs(path) {
    this.content = JSON.stringify(this.activeState);
    return await super.saveAs(path);
  }
}
const useWorkflowStore = /* @__PURE__ */ defineStore("workflow", () => {
  const detachWorkflow = /* @__PURE__ */ __name((workflow) => {
    delete workflowLookup.value[workflow.path];
    const index2 = openWorkflowPaths.value.indexOf(workflow.path);
    if (index2 !== -1) {
      openWorkflowPaths.value = openWorkflowPaths.value.filter(
        (path) => path !== workflow.path
      );
    }
    return index2;
  }, "detachWorkflow");
  const attachWorkflow = /* @__PURE__ */ __name((workflow, openIndex = -1) => {
    workflowLookup.value[workflow.path] = workflow;
    if (openIndex !== -1) {
      openWorkflowPaths.value.splice(openIndex, 0, workflow.path);
    }
  }, "attachWorkflow");
  const activeWorkflow = ref$3(null);
  const isActive2 = /* @__PURE__ */ __name((workflow) => activeWorkflow.value?.path === workflow.path, "isActive");
  const workflowLookup = ref$3({});
  const workflows = computed(
    () => Object.values(workflowLookup.value)
  );
  const getWorkflowByPath = /* @__PURE__ */ __name((path) => workflowLookup.value[path] ?? null, "getWorkflowByPath");
  const openWorkflowPaths = ref$3([]);
  const openWorkflowPathSet = computed(() => new Set(openWorkflowPaths.value));
  const openWorkflows = computed(
    () => openWorkflowPaths.value.map((path) => workflowLookup.value[path])
  );
  const reorderWorkflows = /* @__PURE__ */ __name((from2, to) => {
    const movedTab = openWorkflowPaths.value[from2];
    openWorkflowPaths.value.splice(from2, 1);
    openWorkflowPaths.value.splice(to, 0, movedTab);
  }, "reorderWorkflows");
  const isOpen = /* @__PURE__ */ __name((workflow) => openWorkflowPathSet.value.has(workflow.path), "isOpen");
  const openWorkflowsInBackground = /* @__PURE__ */ __name((paths) => {
    const { left = [], right = [] } = paths;
    if (!left.length && !right.length) return;
    const isValidPath = /* @__PURE__ */ __name((path) => typeof path === "string" && path in workflowLookup.value, "isValidPath");
    openWorkflowPaths.value = _.union(
      left,
      openWorkflowPaths.value,
      right
    ).filter(isValidPath);
  }, "openWorkflowsInBackground");
  const openWorkflow = /* @__PURE__ */ __name(async (workflow) => {
    if (isActive2(workflow)) return workflow;
    if (!openWorkflowPaths.value.includes(workflow.path)) {
      openWorkflowPaths.value.push(workflow.path);
    }
    const loadedWorkflow = await workflow.load();
    activeWorkflow.value = loadedWorkflow;
    console.debug("[workflowStore] open workflow", workflow.path);
    return loadedWorkflow;
  }, "openWorkflow");
  const getUnconflictedPath = /* @__PURE__ */ __name((basePath2) => {
    const { directory, filename, suffix } = getPathDetails(basePath2);
    let counter = 2;
    let newPath = basePath2;
    while (workflowLookup.value[newPath]) {
      newPath = `${directory}/${filename} (${counter}).${suffix}`;
      counter++;
    }
    return newPath;
  }, "getUnconflictedPath");
  const createTemporary = /* @__PURE__ */ __name((path, workflowData) => {
    const fullPath = getUnconflictedPath(
      ComfyWorkflow.basePath + (path ?? "Unsaved Workflow.json")
    );
    const workflow = new ComfyWorkflow({
      path: fullPath,
      modified: Date.now(),
      size: -1
    });
    workflow.originalContent = workflow.content = workflowData ? JSON.stringify(workflowData) : defaultGraphJSON;
    workflowLookup.value[workflow.path] = workflow;
    return workflow;
  }, "createTemporary");
  const closeWorkflow = /* @__PURE__ */ __name(async (workflow) => {
    openWorkflowPaths.value = openWorkflowPaths.value.filter(
      (path) => path !== workflow.path
    );
    if (workflow.isTemporary) {
      delete workflowLookup.value[workflow.path];
    } else {
      workflow.unload();
    }
    console.debug("[workflowStore] close workflow", workflow.path);
  }, "closeWorkflow");
  const openedWorkflowIndexShift = /* @__PURE__ */ __name((shift2) => {
    const index2 = openWorkflowPaths.value.indexOf(
      activeWorkflow.value?.path ?? ""
    );
    if (index2 !== -1) {
      const length = openWorkflows.value.length;
      const nextIndex = (index2 + shift2 + length) % length;
      const nextWorkflow = openWorkflows.value[nextIndex];
      return nextWorkflow ?? null;
    }
    return null;
  }, "openedWorkflowIndexShift");
  const persistedWorkflows = computed(
    () => Array.from(workflows.value).filter((workflow) => workflow.isPersisted)
  );
  const syncWorkflows = /* @__PURE__ */ __name(async (dir = "") => {
    await syncEntities(
      dir ? "workflows/" + dir : "workflows",
      workflowLookup.value,
      (file) => new ComfyWorkflow({
        path: file.path,
        modified: file.modified,
        size: file.size
      }),
      (existingWorkflow, file) => {
        existingWorkflow.lastModified = file.modified;
        existingWorkflow.size = file.size;
        existingWorkflow.unload();
      },
      /* exclude */
      (workflow) => workflow.isTemporary
    );
  }, "syncWorkflows");
  const bookmarkStore = useWorkflowBookmarkStore();
  const bookmarkedWorkflows = computed(
    () => workflows.value.filter(
      (workflow) => bookmarkStore.isBookmarked(workflow.path)
    )
  );
  const modifiedWorkflows = computed(
    () => workflows.value.filter((workflow) => workflow.isModified)
  );
  const isBusy = ref$3(false);
  const renameWorkflow = /* @__PURE__ */ __name(async (workflow, newPath) => {
    isBusy.value = true;
    try {
      const oldPath = workflow.path;
      const wasBookmarked = bookmarkStore.isBookmarked(oldPath);
      const openIndex = detachWorkflow(workflow);
      try {
        await workflow.rename(newPath);
      } finally {
        attachWorkflow(workflow, openIndex);
      }
      if (wasBookmarked) {
        await bookmarkStore.setBookmarked(oldPath, false);
        await bookmarkStore.setBookmarked(newPath, true);
      }
    } finally {
      isBusy.value = false;
    }
  }, "renameWorkflow");
  const deleteWorkflow = /* @__PURE__ */ __name(async (workflow) => {
    isBusy.value = true;
    try {
      await workflow.delete();
      if (bookmarkStore.isBookmarked(workflow.path)) {
        await bookmarkStore.setBookmarked(workflow.path, false);
      }
      delete workflowLookup.value[workflow.path];
    } finally {
      isBusy.value = false;
    }
  }, "deleteWorkflow");
  const saveWorkflow = /* @__PURE__ */ __name(async (workflow) => {
    isBusy.value = true;
    try {
      const openIndex = detachWorkflow(workflow);
      try {
        await workflow.save();
      } finally {
        attachWorkflow(workflow, openIndex);
      }
    } finally {
      isBusy.value = false;
    }
  }, "saveWorkflow");
  const subgraphNamePath = ref$3([]);
  const isSubgraphActive = ref$3(false);
  const updateActiveGraph = /* @__PURE__ */ __name(() => {
    if (!app$1.canvas) return;
    const { subgraph } = app$1.canvas;
    isSubgraphActive.value = isSubgraph(subgraph);
    if (subgraph) {
      const [, ...pathFromRoot] = subgraph.pathToRootGraph;
      subgraphNamePath.value = pathFromRoot.map((graph) => graph.name);
    } else {
      subgraphNamePath.value = [];
    }
  }, "updateActiveGraph");
  watch(activeWorkflow, updateActiveGraph);
  return {
    activeWorkflow,
    isActive: isActive2,
    openWorkflows,
    openedWorkflowIndexShift,
    openWorkflow,
    openWorkflowsInBackground,
    isOpen,
    isBusy,
    closeWorkflow,
    createTemporary,
    renameWorkflow,
    deleteWorkflow,
    saveWorkflow,
    reorderWorkflows,
    workflows,
    bookmarkedWorkflows,
    persistedWorkflows,
    modifiedWorkflows,
    getWorkflowByPath,
    syncWorkflows,
    subgraphNamePath,
    isSubgraphActive,
    updateActiveGraph
  };
});
const useWorkflowBookmarkStore = /* @__PURE__ */ defineStore("workflowBookmark", () => {
  const bookmarks = ref$3(/* @__PURE__ */ new Set());
  const isBookmarked = /* @__PURE__ */ __name((path) => bookmarks.value.has(path), "isBookmarked");
  const loadBookmarks = /* @__PURE__ */ __name(async () => {
    const resp = await api.getUserData("workflows/.index.json");
    if (resp.status === 200) {
      const info = await resp.json();
      bookmarks.value = new Set(info?.favorites ?? []);
    }
  }, "loadBookmarks");
  const saveBookmarks = /* @__PURE__ */ __name(async () => {
    await api.storeUserData("workflows/.index.json", {
      favorites: Array.from(bookmarks.value)
    });
  }, "saveBookmarks");
  const setBookmarked = /* @__PURE__ */ __name(async (path, value) => {
    if (bookmarks.value.has(path) === value) return;
    if (value) {
      bookmarks.value.add(path);
    } else {
      bookmarks.value.delete(path);
    }
    await saveBookmarks();
  }, "setBookmarked");
  const toggleBookmarked = /* @__PURE__ */ __name(async (path) => {
    await setBookmarked(path, !bookmarks.value.has(path));
  }, "toggleBookmarked");
  return {
    isBookmarked,
    loadBookmarks,
    saveBookmarks,
    setBookmarked,
    toggleBookmarked
  };
});
const useWorkflowService = /* @__PURE__ */ __name(() => {
  const settingStore = useSettingStore();
  const workflowStore = useWorkflowStore();
  const toastStore = useToastStore();
  const dialogService = useDialogService();
  async function getFilename(defaultName) {
    if (settingStore.get("Comfy.PromptFilename")) {
      let filename = await dialogService.prompt({
        title: t("workflowService.exportWorkflow"),
        message: t("workflowService.enterFilename") + ":",
        defaultValue: defaultName
      });
      if (!filename) return null;
      if (!filename.toLowerCase().endsWith(".json")) {
        filename += ".json";
      }
      return filename;
    }
    return defaultName;
  }
  __name(getFilename, "getFilename");
  function addViewRestore(workflow) {
    if (!settingStore.get("Comfy.EnableWorkflowViewRestore")) return;
    const { offset, scale } = app$1.canvas.ds;
    const [x2, y2] = offset;
    workflow.extra ??= {};
    workflow.extra.ds = { scale, offset: [x2, y2] };
  }
  __name(addViewRestore, "addViewRestore");
  const exportWorkflow = /* @__PURE__ */ __name(async (filename, promptProperty) => {
    const workflow = workflowStore.activeWorkflow;
    if (workflow?.path) {
      filename = workflow.filename;
    }
    const p2 = await app$1.graphToPrompt();
    addViewRestore(p2.workflow);
    const json = JSON.stringify(p2[promptProperty], null, 2);
    const blob = new Blob([json], { type: "application/json" });
    const file = await getFilename(filename);
    if (!file) return;
    downloadBlob(file, blob);
  }, "exportWorkflow");
  const saveWorkflowAs = /* @__PURE__ */ __name(async (workflow) => {
    const newFilename = await dialogService.prompt({
      title: t("workflowService.saveWorkflow"),
      message: t("workflowService.enterFilename") + ":",
      defaultValue: workflow.filename
    });
    if (!newFilename) return;
    const newPath = workflow.directory + "/" + appendJsonExt(newFilename);
    const newKey = newPath.substring(ComfyWorkflow.basePath.length);
    const existingWorkflow = workflowStore.getWorkflowByPath(newPath);
    if (existingWorkflow && !existingWorkflow.isTemporary) {
      const res = await dialogService.confirm({
        title: t("sideToolbar.workflowTab.confirmOverwriteTitle"),
        type: "overwrite",
        message: t("sideToolbar.workflowTab.confirmOverwrite"),
        itemList: [newPath]
      });
      if (res !== true) return;
      if (existingWorkflow.path === workflow.path) {
        await saveWorkflow(workflow);
        return;
      }
      const deleted = await deleteWorkflow(existingWorkflow, true);
      if (!deleted) return;
    }
    if (workflow.isTemporary) {
      await renameWorkflow(workflow, newPath);
      await workflowStore.saveWorkflow(workflow);
    } else {
      const id2 = generateUUID();
      const state = JSON.parse(
        JSON.stringify(workflow.activeState)
      );
      state.id = id2;
      const tempWorkflow = workflowStore.createTemporary(newKey, state);
      await openWorkflow(tempWorkflow);
      await workflowStore.saveWorkflow(tempWorkflow);
    }
  }, "saveWorkflowAs");
  const saveWorkflow = /* @__PURE__ */ __name(async (workflow) => {
    if (workflow.isTemporary) {
      await saveWorkflowAs(workflow);
    } else {
      await workflowStore.saveWorkflow(workflow);
    }
  }, "saveWorkflow");
  const loadDefaultWorkflow = /* @__PURE__ */ __name(async () => {
    await app$1.loadGraphData(defaultGraph);
  }, "loadDefaultWorkflow");
  const loadBlankWorkflow = /* @__PURE__ */ __name(async () => {
    await app$1.loadGraphData(blankGraph);
  }, "loadBlankWorkflow");
  const reloadCurrentWorkflow = /* @__PURE__ */ __name(async () => {
    const workflow = workflowStore.activeWorkflow;
    if (workflow) {
      await openWorkflow(workflow, { force: true });
    }
  }, "reloadCurrentWorkflow");
  const openWorkflow = /* @__PURE__ */ __name(async (workflow, options2 = { force: false }) => {
    if (workflowStore.isActive(workflow) && !options2.force) return;
    const loadFromRemote = !workflow.isLoaded;
    if (loadFromRemote) {
      await workflow.load();
    }
    await app$1.loadGraphData(
      toRaw(workflow.activeState),
      /* clean=*/
      true,
      /* restore_view=*/
      true,
      workflow,
      {
        showMissingModelsDialog: loadFromRemote,
        showMissingNodesDialog: loadFromRemote,
        checkForRerouteMigration: false
      }
    );
  }, "openWorkflow");
  const closeWorkflow = /* @__PURE__ */ __name(async (workflow, options2 = {
    warnIfUnsaved: true
  }) => {
    if (workflow.isModified && options2.warnIfUnsaved) {
      const confirmed = await dialogService.confirm({
        title: t("sideToolbar.workflowTab.dirtyCloseTitle"),
        type: "dirtyClose",
        message: t("sideToolbar.workflowTab.dirtyClose"),
        itemList: [workflow.path],
        hint: options2.hint
      });
      if (confirmed === null) return false;
      if (confirmed === true) {
        await saveWorkflow(workflow);
      }
    }
    if (workflowStore.openWorkflows.length === 1) {
      await loadDefaultWorkflow();
    }
    if (workflowStore.isActive(workflow)) {
      await loadNextOpenedWorkflow();
    }
    await workflowStore.closeWorkflow(workflow);
    return true;
  }, "closeWorkflow");
  const renameWorkflow = /* @__PURE__ */ __name(async (workflow, newPath) => {
    await workflowStore.renameWorkflow(workflow, newPath);
  }, "renameWorkflow");
  const deleteWorkflow = /* @__PURE__ */ __name(async (workflow, silent = false) => {
    const bypassConfirm = !settingStore.get("Comfy.Workflow.ConfirmDelete");
    let confirmed = bypassConfirm || silent;
    if (!confirmed) {
      confirmed = await dialogService.confirm({
        title: t("sideToolbar.workflowTab.confirmDeleteTitle"),
        type: "delete",
        message: t("sideToolbar.workflowTab.confirmDelete"),
        itemList: [workflow.path]
      });
      if (!confirmed) return false;
    }
    if (workflowStore.isOpen(workflow)) {
      const closed = await closeWorkflow(workflow, {
        warnIfUnsaved: !confirmed
      });
      if (!closed) return false;
    }
    await workflowStore.deleteWorkflow(workflow);
    if (!silent) {
      toastStore.add({
        severity: "info",
        summary: t("sideToolbar.workflowTab.deleted"),
        life: 1e3
      });
    }
    return true;
  }, "deleteWorkflow");
  const beforeLoadNewGraph = /* @__PURE__ */ __name(() => {
    const workflowStore2 = useWorkspaceStore().workflow;
    const activeWorkflow = workflowStore2.activeWorkflow;
    if (activeWorkflow) {
      activeWorkflow.changeTracker.store();
    }
  }, "beforeLoadNewGraph");
  const afterLoadNewGraph = /* @__PURE__ */ __name(async (value, workflowData) => {
    const workflowStore2 = useWorkspaceStore().workflow;
    if (typeof value === "string") {
      const workflow = workflowStore2.getWorkflowByPath(
        ComfyWorkflow.basePath + appendJsonExt(value)
      );
      if (workflow?.isPersisted) {
        const loadedWorkflow2 = await workflowStore2.openWorkflow(workflow);
        loadedWorkflow2.changeTracker.restore();
        loadedWorkflow2.changeTracker.reset(workflowData);
        return;
      }
    }
    if (value === null || typeof value === "string") {
      const path = value;
      const tempWorkflow = workflowStore2.createTemporary(
        path ? appendJsonExt(path) : void 0,
        workflowData
      );
      await workflowStore2.openWorkflow(tempWorkflow);
      return;
    }
    const loadedWorkflow = await workflowStore2.openWorkflow(value);
    loadedWorkflow.changeTracker.reset(workflowData);
    loadedWorkflow.changeTracker.restore();
  }, "afterLoadNewGraph");
  const insertWorkflow = /* @__PURE__ */ __name(async (workflow, options2 = {}) => {
    const loadedWorkflow = await workflow.load();
    const data = loadedWorkflow.initialState;
    const workflowJSON = data;
    const old = localStorage.getItem("litegrapheditor_clipboard");
    const graph = new LGraph(workflowJSON);
    const canvasElement = document.createElement("canvas");
    const canvas2 = new LGraphCanvas(canvasElement, graph, {
      skip_events: true,
      skip_render: true
    });
    canvas2.selectItems();
    canvas2.copyToClipboard();
    app$1.canvas.pasteFromClipboard(options2);
    if (old !== null) {
      localStorage.setItem("litegrapheditor_clipboard", old);
    }
  }, "insertWorkflow");
  const loadNextOpenedWorkflow = /* @__PURE__ */ __name(async () => {
    const nextWorkflow = workflowStore.openedWorkflowIndexShift(1);
    if (nextWorkflow) {
      await openWorkflow(nextWorkflow);
    }
  }, "loadNextOpenedWorkflow");
  const loadPreviousOpenedWorkflow = /* @__PURE__ */ __name(async () => {
    const previousWorkflow = workflowStore.openedWorkflowIndexShift(-1);
    if (previousWorkflow) {
      await openWorkflow(previousWorkflow);
    }
  }, "loadPreviousOpenedWorkflow");
  const duplicateWorkflow = /* @__PURE__ */ __name(async (workflow) => {
    const state = JSON.parse(JSON.stringify(workflow.activeState));
    const suffix = workflow.isPersisted ? " (Copy)" : "";
    const filename = workflow.filename.replace(/\s*\(\d+\)$/, "") + suffix;
    await app$1.loadGraphData(state, true, true, filename);
  }, "duplicateWorkflow");
  return {
    exportWorkflow,
    saveWorkflowAs,
    saveWorkflow,
    loadDefaultWorkflow,
    loadBlankWorkflow,
    reloadCurrentWorkflow,
    openWorkflow,
    closeWorkflow,
    renameWorkflow,
    deleteWorkflow,
    insertWorkflow,
    loadNextOpenedWorkflow,
    loadPreviousOpenedWorkflow,
    duplicateWorkflow,
    afterLoadNewGraph,
    beforeLoadNewGraph
  };
}, "useWorkflowService");
const _hoisted_1$v = { class: "justify-center text-sm font-bold leading-none" };
const _hoisted_2$p = { class: "flex items-center" };
const _hoisted_3$d = { class: "leading-none" };
const _hoisted_4$5 = { class: "flex items-center gap-4" };
const _hoisted_5$5 = {
  key: 0,
  class: "text-xs font-bold text-neutral-600"
};
const _hoisted_6$4 = { class: "flex items-center" };
const _sfc_main$E = /* @__PURE__ */ defineComponent({
  __name: "ManagerProgressFooter",
  setup(__props) {
    const { t: t2 } = useI18n();
    const dialogStore = useDialogStore();
    const progressDialogContent = useManagerProgressDialogStore();
    const comfyManagerStore = useComfyManagerStore();
    const isInProgress = computed(() => comfyManagerStore.uncompletedCount > 0);
    const closeDialog = /* @__PURE__ */ __name(() => {
      dialogStore.closeDialog({ key: "global-manager-progress-dialog" });
    }, "closeDialog");
    const fallbackTaskName = t2("g.installing");
    const currentTaskName = computed(() => {
      if (!comfyManagerStore.taskLogs.length) return fallbackTaskName;
      const task = comfyManagerStore.taskLogs.at(-1);
      return task?.taskName ?? fallbackTaskName;
    });
    const handleRestart = /* @__PURE__ */ __name(async () => {
      const onReconnect = /* @__PURE__ */ __name(async () => {
        comfyManagerStore.clearLogs();
        comfyManagerStore.setStale();
        await useCommandStore().execute("Comfy.RefreshNodeDefinitions");
        await useWorkflowService().reloadCurrentWorkflow();
      }, "onReconnect");
      useEventListener(api, "reconnected", onReconnect, { once: true });
      await useComfyManagerService().rebootComfyUI();
      closeDialog();
    }, "handleRestart");
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", {
        class: normalizeClass(["w-full px-6 py-4 shadow-lg flex items-center justify-between", {
          "rounded-t-none": unref(progressDialogContent).isExpanded,
          "rounded-lg": !unref(progressDialogContent).isExpanded
        }])
      }, [
        createBaseVNode("div", _hoisted_1$v, [
          createBaseVNode("div", _hoisted_2$p, [
            isInProgress.value ? (openBlock(), createElementBlock(Fragment$1, { key: 0 }, [
              _cache[0] || (_cache[0] = createBaseVNode("i", { class: "pi pi-spin pi-spinner mr-2 text-3xl" }, null, -1)),
              createBaseVNode("span", null, toDisplayString(currentTaskName.value), 1)
            ], 64)) : (openBlock(), createElementBlock(Fragment$1, { key: 1 }, [
              _cache[1] || (_cache[1] = createBaseVNode("i", { class: "pi pi-check-circle mr-2 text-green-500" }, null, -1)),
              createBaseVNode("span", _hoisted_3$d, toDisplayString(_ctx.$t("manager.restartToApplyChanges")), 1)
            ], 64))
          ])
        ]),
        createBaseVNode("div", _hoisted_4$5, [
          isInProgress.value ? (openBlock(), createElementBlock("span", _hoisted_5$5, toDisplayString(unref(comfyManagerStore).uncompletedCount) + " of " + toDisplayString(unref(comfyManagerStore).taskLogs.length), 1)) : createCommentVNode("", true),
          createBaseVNode("div", _hoisted_6$4, [
            !isInProgress.value ? (openBlock(), createBlock(unref(script$6), {
              key: 0,
              rounded: "",
              outlined: "",
              class: "px-4 py-2 rounded-md mr-4",
              onClick: handleRestart
            }, {
              default: withCtx(() => [
                createTextVNode(toDisplayString(_ctx.$t("g.restart")), 1)
              ]),
              _: 1
            })) : createCommentVNode("", true),
            createVNode(unref(script$6), {
              icon: unref(progressDialogContent).isExpanded ? "pi pi-chevron-up" : "pi pi-chevron-right",
              text: "",
              rounded: "",
              size: "small",
              severity: "secondary",
              "aria-label": unref(progressDialogContent).isExpanded ? "Collapse" : "Expand",
              onClick: withModifiers(unref(progressDialogContent).toggle, ["stop"])
            }, null, 8, ["icon", "aria-label", "onClick"]),
            createVNode(unref(script$6), {
              icon: "pi pi-times",
              text: "",
              rounded: "",
              size: "small",
              severity: "secondary",
              "aria-label": "Close",
              onClick: withModifiers(closeDialog, ["stop"])
            })
          ])
        ])
      ], 2);
    };
  }
});
const _imports_0 = "" + new URL("images/comfy-logo-single.svg", import.meta.url).href;
const _sfc_main$D = {};
const _hoisted_1$u = { class: "px-2 py-4" };
function _sfc_render$1(_ctx, _cache) {
  return openBlock(), createElementBlock("div", _hoisted_1$u, _cache[0] || (_cache[0] = [
    createBaseVNode("img", {
      src: _imports_0,
      alt: "ComfyOrg Logo",
      width: "32",
      height: "32"
    }, null, -1)
  ]));
}
__name(_sfc_render$1, "_sfc_render$1");
const ComfyOrgHeader = /* @__PURE__ */ _export_sfc(_sfc_main$D, [["render", _sfc_render$1]]);
const _hoisted_1$t = {
  key: 0,
  class: "px-4 py-2 flex items-center"
};
const _sfc_main$C = /* @__PURE__ */ defineComponent({
  __name: "ManagerProgressHeader",
  setup(__props) {
    const progressDialogContent = useManagerProgressDialogStore();
    const activeTabIndex = ref$3(0);
    const { t: t2 } = useI18n();
    const tabs = [
      { label: t2("manager.installationQueue") },
      { label: t2("manager.failed", { count: 0 }) }
    ];
    return (_ctx, _cache) => {
      return unref(progressDialogContent).isExpanded ? (openBlock(), createElementBlock("div", _hoisted_1$t, [
        createVNode(unref(script$E), {
          activeIndex: activeTabIndex.value,
          "onUpdate:activeIndex": _cache[0] || (_cache[0] = ($event) => activeTabIndex.value = $event),
          model: tabs,
          class: "w-full border-none",
          pt: {
            menu: { class: "border-none" },
            menuitem: { class: "font-medium" },
            action: { class: "px-4 py-2" }
          }
        }, null, 8, ["activeIndex"])
      ])) : createCommentVNode("", true);
    };
  }
});
const _hoisted_1$s = { class: "px-4" };
const _sfc_main$B = /* @__PURE__ */ defineComponent({
  __name: "SettingDialogHeader",
  setup(__props) {
    const isStaging = false;
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", null, [
        createBaseVNode("h2", _hoisted_1$s, [
          _cache[0] || (_cache[0] = createBaseVNode("i", { class: "pi pi-cog" }, null, -1)),
          createBaseVNode("span", null, toDisplayString(_ctx.$t("g.settings")), 1),
          isStaging ? (openBlock(), createBlock(unref(script$5), {
            key: 0,
            value: "staging",
            severity: "warn",
            class: "ml-2 text-xs"
          })) : createCommentVNode("", true)
        ])
      ]);
    };
  }
});
const SettingDialogHeader = /* @__PURE__ */ _export_sfc(_sfc_main$B, [["__scopeId", "data-v-45e39e74"]]);
const _hoisted_1$r = { class: "relative w-64 h-64 rounded-t-lg overflow-hidden select-none" };
const _hoisted_2$o = {
  key: 1,
  class: "w-full h-full flex items-center justify-center"
};
const _sfc_main$A = /* @__PURE__ */ defineComponent({
  __name: "BaseThumbnail",
  props: {
    hoverZoom: { default: 4 },
    isHovered: { type: Boolean }
  },
  setup(__props) {
    const error2 = ref$3(false);
    const contentRef = ref$3(null);
    onMounted(() => {
      const images = Array.from(contentRef.value?.getElementsByTagName("img") ?? []);
      images.forEach((img) => {
        useEventListener(img, "error", () => {
          error2.value = true;
        });
      });
    });
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", _hoisted_1$r, [
        !error2.value ? (openBlock(), createElementBlock("div", {
          key: 0,
          ref_key: "contentRef",
          ref: contentRef,
          class: "w-64 h-64 object-cover transform-gpu transition-transform duration-1000 ease-out",
          style: normalizeStyle(
            _ctx.isHovered ? { transform: `scale(${1 + _ctx.hoverZoom / 100})` } : void 0
          )
        }, [
          renderSlot(_ctx.$slots, "default", {}, void 0, true)
        ], 4)) : (openBlock(), createElementBlock("div", _hoisted_2$o, _cache[0] || (_cache[0] = [
          createBaseVNode("i", { class: "pi pi-file text-4xl" }, null, -1)
        ])))
      ]);
    };
  }
});
const BaseThumbnail = /* @__PURE__ */ _export_sfc(_sfc_main$A, [["__scopeId", "data-v-f11fbe4f"]]);
const _hoisted_1$q = { class: "w-64 h-64 flex items-center justify-center p-4" };
const _hoisted_2$n = ["src"];
const _sfc_main$z = /* @__PURE__ */ defineComponent({
  __name: "AudioThumbnail",
  props: {
    src: {}
  },
  setup(__props) {
    return (_ctx, _cache) => {
      return openBlock(), createBlock(BaseThumbnail, null, {
        default: withCtx(() => [
          createBaseVNode("div", _hoisted_1$q, [
            createBaseVNode("audio", {
              controls: "",
              class: "w-full relative",
              src: _ctx.src,
              onClick: _cache[0] || (_cache[0] = withModifiers(() => {
              }, ["stop"]))
            }, null, 8, _hoisted_2$n)
          ])
        ]),
        _: 1
      });
    };
  }
});
const _hoisted_1$p = ["src", "alt"];
const _hoisted_2$m = ["src", "alt"];
const SLIDER_START_POSITION = 21;
const _sfc_main$y = /* @__PURE__ */ defineComponent({
  __name: "CompareSliderThumbnail",
  props: {
    baseImageSrc: {},
    overlayImageSrc: {},
    alt: {},
    isHovered: { type: Boolean }
  },
  setup(__props) {
    const sliderPosition = ref$3(SLIDER_START_POSITION);
    const containerRef = ref$3(null);
    const { elementX, elementWidth, isOutside } = useMouseInElement(containerRef);
    watch(
      [() => __props.isHovered, elementX, elementWidth, isOutside],
      ([isHovered, x2, width2, outside]) => {
        if (!isHovered) return;
        if (!outside) {
          sliderPosition.value = x2 / width2 * 100;
        }
      }
    );
    return (_ctx, _cache) => {
      return openBlock(), createBlock(BaseThumbnail, { "is-hovered": _ctx.isHovered }, {
        default: withCtx(() => [
          createBaseVNode("img", {
            src: _ctx.baseImageSrc,
            alt: _ctx.alt,
            class: "w-full h-full object-cover"
          }, null, 8, _hoisted_1$p),
          createBaseVNode("div", {
            ref_key: "containerRef",
            ref: containerRef,
            class: "absolute inset-0"
          }, [
            createBaseVNode("img", {
              src: _ctx.overlayImageSrc,
              alt: _ctx.alt,
              class: "w-full h-full object-cover",
              style: normalizeStyle({
                clipPath: `inset(0 ${100 - sliderPosition.value}% 0 0)`
              })
            }, null, 12, _hoisted_2$m),
            createBaseVNode("div", {
              class: "absolute inset-y-0 w-0.5 bg-white/30 backdrop-blur-sm z-10 pointer-events-none",
              style: normalizeStyle({
                left: `${sliderPosition.value}%`
              })
            }, null, 4)
          ], 512)
        ]),
        _: 1
      }, 8, ["is-hovered"]);
    };
  }
});
const _hoisted_1$o = { class: "overflow-hidden" };
const _hoisted_2$l = ["src", "alt"];
const _sfc_main$x = /* @__PURE__ */ defineComponent({
  __name: "DefaultThumbnail",
  props: {
    src: {},
    alt: {},
    hoverZoom: {},
    isHovered: { type: Boolean }
  },
  setup(__props) {
    return (_ctx, _cache) => {
      return openBlock(), createBlock(BaseThumbnail, {
        "hover-zoom": _ctx.hoverZoom,
        "is-hovered": _ctx.isHovered
      }, {
        default: withCtx(() => [
          createBaseVNode("div", _hoisted_1$o, [
            createBaseVNode("img", {
              src: _ctx.src,
              alt: _ctx.alt,
              draggable: "false",
              class: "w-64 h-64 object-cover transform-gpu transition-transform duration-300 ease-out",
              style: normalizeStyle(
                _ctx.isHovered ? { transform: `scale(${1 + _ctx.hoverZoom / 100})` } : void 0
              )
            }, null, 12, _hoisted_2$l)
          ])
        ]),
        _: 1
      }, 8, ["hover-zoom", "is-hovered"]);
    };
  }
});
const _hoisted_1$n = { class: "relative w-full h-full" };
const _hoisted_2$k = ["src", "alt"];
const _hoisted_3$c = ["src", "alt"];
const _sfc_main$w = /* @__PURE__ */ defineComponent({
  __name: "HoverDissolveThumbnail",
  props: {
    baseImageSrc: {},
    overlayImageSrc: {},
    alt: {},
    isHovered: { type: Boolean }
  },
  setup(__props) {
    return (_ctx, _cache) => {
      return openBlock(), createBlock(BaseThumbnail, { "is-hovered": _ctx.isHovered }, {
        default: withCtx(() => [
          createBaseVNode("div", _hoisted_1$n, [
            createBaseVNode("img", {
              src: _ctx.baseImageSrc,
              alt: _ctx.alt,
              draggable: "false",
              class: "absolute inset-0 w-64 h-64 object-cover"
            }, null, 8, _hoisted_2$k),
            createBaseVNode("img", {
              src: _ctx.overlayImageSrc,
              alt: _ctx.alt,
              draggable: "false",
              class: normalizeClass(["absolute inset-0 w-64 h-64 object-cover transition-opacity duration-300", { "opacity-100": _ctx.isHovered, "opacity-0": !_ctx.isHovered }])
            }, null, 10, _hoisted_3$c)
          ])
        ]),
        _: 1
      }, 8, ["is-hovered"]);
    };
  }
});
const _hoisted_1$m = { class: "flex items-center justify-center" };
const _hoisted_2$j = { class: "relative overflow-hidden rounded-t-lg" };
const _hoisted_3$b = { class: "flex items-center px-4 py-3" };
const _hoisted_4$4 = { class: "flex-1 flex flex-col" };
const _hoisted_5$4 = ["title"];
const _hoisted_6$3 = ["title"];
const UPSCALE_ZOOM_SCALE = 16;
const DEFAULT_ZOOM_SCALE = 5;
const _sfc_main$v = /* @__PURE__ */ defineComponent({
  __name: "TemplateWorkflowCard",
  props: {
    sourceModule: {},
    categoryTitle: {},
    loading: { type: Boolean },
    template: {}
  },
  emits: ["loadWorkflow"],
  setup(__props) {
    const cardRef = ref$3(null);
    const isHovered = useElementHover(cardRef);
    const getThumbnailUrl = /* @__PURE__ */ __name((index2 = "") => {
      const basePath2 = __props.sourceModule === "default" ? api.fileURL(`/templates/${__props.template.name}`) : api.apiURL(`/workflow_templates/${__props.sourceModule}/${__props.template.name}`);
      const indexSuffix = __props.sourceModule === "default" && index2 ? `-${index2}` : "";
      return `${basePath2}${indexSuffix}.${__props.template.mediaSubtype}`;
    }, "getThumbnailUrl");
    const baseThumbnailSrc = computed(
      () => getThumbnailUrl(__props.sourceModule === "default" ? "1" : "")
    );
    const overlayThumbnailSrc = computed(
      () => getThumbnailUrl(__props.sourceModule === "default" ? "2" : "")
    );
    const description = computed(() => {
      return __props.sourceModule === "default" ? __props.template.localizedDescription ?? "" : __props.template.description.replace(/[-_]/g, " ").trim();
    });
    const title = computed(() => {
      return __props.sourceModule === "default" ? __props.template.localizedTitle ?? "" : __props.template.name;
    });
    return (_ctx, _cache) => {
      return openBlock(), createBlock(unref(script$9), {
        ref_key: "cardRef",
        ref: cardRef,
        "data-testid": `template-workflow-${_ctx.template.name}`,
        class: "w-64 template-card rounded-2xl overflow-hidden cursor-pointer shadow-elevation-2 dark-theme:bg-dark-elevation-1 h-full",
        pt: {
          body: { class: "p-0 h-full flex flex-col" }
        },
        onClick: _cache[0] || (_cache[0] = ($event) => _ctx.$emit("loadWorkflow", _ctx.template.name))
      }, {
        header: withCtx(() => [
          createBaseVNode("div", _hoisted_1$m, [
            createBaseVNode("div", _hoisted_2$j, [
              _ctx.template.mediaType === "audio" ? (openBlock(), createBlock(_sfc_main$z, {
                key: 0,
                src: baseThumbnailSrc.value
              }, null, 8, ["src"])) : _ctx.template.thumbnailVariant === "compareSlider" ? (openBlock(), createBlock(_sfc_main$y, {
                key: 1,
                "base-image-src": baseThumbnailSrc.value,
                "overlay-image-src": overlayThumbnailSrc.value,
                alt: title.value,
                "is-hovered": unref(isHovered)
              }, null, 8, ["base-image-src", "overlay-image-src", "alt", "is-hovered"])) : _ctx.template.thumbnailVariant === "hoverDissolve" ? (openBlock(), createBlock(_sfc_main$w, {
                key: 2,
                "base-image-src": baseThumbnailSrc.value,
                "overlay-image-src": overlayThumbnailSrc.value,
                alt: title.value,
                "is-hovered": unref(isHovered)
              }, null, 8, ["base-image-src", "overlay-image-src", "alt", "is-hovered"])) : (openBlock(), createBlock(_sfc_main$x, {
                key: 3,
                src: baseThumbnailSrc.value,
                alt: title.value,
                "is-hovered": unref(isHovered),
                "hover-zoom": _ctx.template.thumbnailVariant === "zoomHover" ? UPSCALE_ZOOM_SCALE : DEFAULT_ZOOM_SCALE
              }, null, 8, ["src", "alt", "is-hovered", "hover-zoom"])),
              _ctx.loading ? (openBlock(), createBlock(unref(script$x), {
                key: 4,
                class: "absolute inset-0 z-1 w-3/12 h-full"
              })) : createCommentVNode("", true)
            ])
          ])
        ]),
        content: withCtx(() => [
          createBaseVNode("div", _hoisted_3$b, [
            createBaseVNode("div", _hoisted_4$4, [
              createBaseVNode("h3", {
                class: "line-clamp-2 text-lg font-normal mb-0 h-12",
                title: title.value
              }, toDisplayString(title.value), 9, _hoisted_5$4),
              createBaseVNode("p", {
                class: "line-clamp-2 text-sm text-muted grow",
                title: description.value
              }, toDisplayString(description.value), 9, _hoisted_6$3)
            ]),
            _cache[1] || (_cache[1] = createBaseVNode("div", { class: "flex md:hidden xl:flex items-center justify-center ml-4 w-10 h-10 rounded-full" }, [
              createBaseVNode("i", { class: "pi pi-angle-right text-2xl" })
            ], -1))
          ])
        ]),
        _: 1
      }, 8, ["data-testid"]);
    };
  }
});
const _hoisted_1$l = ["title"];
const _hoisted_2$i = ["title"];
const _sfc_main$u = /* @__PURE__ */ defineComponent({
  __name: "TemplateWorkflowList",
  props: {
    sourceModule: {},
    categoryTitle: {},
    loading: {},
    templates: {}
  },
  emits: ["loadWorkflow"],
  setup(__props, { emit: __emit }) {
    const selectedTemplate = ref$3(null);
    const emit = __emit;
    const getTemplateTitle = /* @__PURE__ */ __name((template) => {
      const fallback = template.title ?? template.name ?? `${__props.sourceModule} Template`;
      return __props.sourceModule === "default" ? template.localizedTitle ?? fallback : fallback;
    }, "getTemplateTitle");
    const getTemplateDescription = /* @__PURE__ */ __name((template) => {
      return __props.sourceModule === "default" ? template.localizedDescription ?? "" : template.description.replace(/[-_]/g, " ").trim();
    }, "getTemplateDescription");
    return (_ctx, _cache) => {
      return openBlock(), createBlock(unref(script$F), {
        selection: selectedTemplate.value,
        "onUpdate:selection": _cache[0] || (_cache[0] = ($event) => selectedTemplate.value = $event),
        value: _ctx.templates,
        "striped-rows": "",
        "selection-mode": "single"
      }, {
        default: withCtx(() => [
          createVNode(unref(script$G), {
            field: "title",
            header: _ctx.$t("g.title")
          }, {
            body: withCtx((slotProps) => [
              createBaseVNode("span", {
                title: getTemplateTitle(slotProps.data)
              }, toDisplayString(getTemplateTitle(slotProps.data)), 9, _hoisted_1$l)
            ]),
            _: 1
          }, 8, ["header"]),
          createVNode(unref(script$G), {
            field: "description",
            header: _ctx.$t("g.description")
          }, {
            body: withCtx((slotProps) => [
              createBaseVNode("span", {
                title: getTemplateDescription(slotProps.data)
              }, toDisplayString(getTemplateDescription(slotProps.data)), 9, _hoisted_2$i)
            ]),
            _: 1
          }, 8, ["header"]),
          createVNode(unref(script$G), {
            field: "actions",
            header: "",
            class: "w-12"
          }, {
            body: withCtx((slotProps) => [
              createVNode(unref(script$6), {
                icon: "pi pi-arrow-right",
                text: "",
                rounded: "",
                size: "small",
                loading: _ctx.loading === slotProps.data.name,
                onClick: /* @__PURE__ */ __name(($event) => emit("loadWorkflow", slotProps.data.name), "onClick")
              }, null, 8, ["loading", "onClick"])
            ]),
            _: 1
          })
        ]),
        _: 1
      }, 8, ["selection", "value"]);
    };
  }
});
const _hoisted_1$k = { class: "flex justify-between items-center" };
const _hoisted_2$h = { class: "text-lg" };
const _hoisted_3$a = { class: "grid grid-cols-[repeat(auto-fill,minmax(16rem,1fr))] auto-rows-fr gap-8 justify-items-center" };
const _sfc_main$t = /* @__PURE__ */ defineComponent({
  __name: "TemplateWorkflowView",
  props: {
    title: {},
    sourceModule: {},
    categoryTitle: {},
    loading: {},
    templates: {}
  },
  emits: ["loadWorkflow"],
  setup(__props, { emit: __emit }) {
    const layout = useLocalStorage(
      "Comfy.TemplateWorkflow.Layout",
      "grid"
    );
    const emit = __emit;
    const onLoadWorkflow = /* @__PURE__ */ __name((name2) => {
      emit("loadWorkflow", name2);
    }, "onLoadWorkflow");
    return (_ctx, _cache) => {
      return openBlock(), createBlock(unref(script$H), {
        value: _ctx.templates,
        layout: unref(layout),
        "data-key": "name",
        lazy: true,
        "pt:root": "h-full grid grid-rows-[auto_1fr]",
        "pt:content": "p-2 overflow-auto"
      }, {
        header: withCtx(() => [
          createBaseVNode("div", _hoisted_1$k, [
            createBaseVNode("h2", _hoisted_2$h, toDisplayString(_ctx.title), 1),
            createVNode(unref(script$I), {
              modelValue: unref(layout),
              "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => isRef(layout) ? layout.value = $event : null),
              options: ["grid", "list"],
              "allow-empty": false
            }, {
              option: withCtx(({ option }) => [
                createBaseVNode("i", {
                  class: normalizeClass([option === "list" ? "pi pi-bars" : "pi pi-table"])
                }, null, 2)
              ]),
              _: 1
            }, 8, ["modelValue"])
          ])
        ]),
        list: withCtx(({ items }) => [
          createVNode(_sfc_main$u, {
            "source-module": _ctx.sourceModule,
            templates: items,
            loading: _ctx.loading,
            "category-title": _ctx.categoryTitle,
            onLoadWorkflow
          }, null, 8, ["source-module", "templates", "loading", "category-title"])
        ]),
        grid: withCtx(({ items }) => [
          createBaseVNode("div", _hoisted_3$a, [
            (openBlock(true), createElementBlock(Fragment$1, null, renderList(items, (template) => {
              return openBlock(), createBlock(_sfc_main$v, {
                key: template.name,
                "source-module": _ctx.sourceModule,
                template,
                loading: _ctx.loading === template.name,
                "category-title": _ctx.categoryTitle,
                onLoadWorkflow
              }, null, 8, ["source-module", "template", "loading", "category-title"]);
            }), 128))
          ])
        ]),
        _: 1
      }, 8, ["value", "layout"]);
    };
  }
});
const _hoisted_1$j = { class: "text-left py-3 px-12" };
const _hoisted_2$g = { class: "text-lg" };
const _sfc_main$s = /* @__PURE__ */ defineComponent({
  __name: "TemplateWorkflowsSideNav",
  props: {
    tabs: {},
    selectedTab: {}
  },
  emits: ["update:selectedTab"],
  setup(__props, { emit: __emit }) {
    const emit = __emit;
    const handleTabSelection = /* @__PURE__ */ __name((tab) => {
      emit("update:selectedTab", tab);
    }, "handleTabSelection");
    return (_ctx, _cache) => {
      return openBlock(), createBlock(unref(script$7), {
        class: "w-80",
        style: { "height": "calc(83vh - 48px)" }
      }, {
        default: withCtx(() => [
          createVNode(unref(script$g), {
            "model-value": _ctx.selectedTab,
            options: _ctx.tabs,
            "option-group-label": "label",
            "option-label": "localizedTitle",
            "option-group-children": "modules",
            class: "w-full border-0 bg-transparent shadow-none",
            pt: {
              list: { class: "p-0" },
              option: { class: "px-12 py-3 text-lg" },
              optionGroup: { class: "p-0 text-left text-inherit" }
            },
            "list-style": "max-height:unset",
            "onUpdate:modelValue": handleTabSelection
          }, {
            optiongroup: withCtx((slotProps) => [
              createBaseVNode("div", _hoisted_1$j, [
                createBaseVNode("h2", _hoisted_2$g, toDisplayString(slotProps.option.label), 1)
              ])
            ]),
            _: 1
          }, 8, ["model-value", "options"])
        ]),
        _: 1
      });
    };
  }
});
const SHOULD_SORT_CATEGORIES = /* @__PURE__ */ new Set([
  // API Node templates should be strictly sorted by name to avoid any
  // favoritism or bias towards a particular API. Other categories can
  // have their ordering specified in index.json freely.
  "Image API",
  "Video API"
]);
const useWorkflowTemplatesStore = /* @__PURE__ */ defineStore(
  "workflowTemplates",
  () => {
    const customTemplates = shallowRef({});
    const coreTemplates = shallowRef([]);
    const isLoaded = ref$3(false);
    const sortTemplateList = /* @__PURE__ */ __name((templates) => templates.sort((a2, b2) => {
      const aName = st(
        `templateWorkflows.name.${normalizeI18nKey(a2.name)}`,
        a2.title ?? a2.name
      );
      const bName = st(
        `templateWorkflows.name.${normalizeI18nKey(b2.name)}`,
        b2.name
      );
      return aName.localeCompare(bName);
    }), "sortTemplateList");
    const sortCategoryTemplates = /* @__PURE__ */ __name((categories) => categories.map((category) => {
      if (SHOULD_SORT_CATEGORIES.has(category.title)) {
        return {
          ...category,
          templates: sortTemplateList(category.templates)
        };
      }
      return category;
    }), "sortCategoryTemplates");
    const addLocalizedFieldsToTemplate = /* @__PURE__ */ __name((template, categoryTitle) => ({
      ...template,
      localizedTitle: st(
        `templateWorkflows.template.${normalizeI18nKey(categoryTitle)}.${normalizeI18nKey(template.name)}`,
        template.title ?? template.name
      ),
      localizedDescription: st(
        `templateWorkflows.templateDescription.${normalizeI18nKey(categoryTitle)}.${normalizeI18nKey(template.name)}`,
        template.description
      )
    }), "addLocalizedFieldsToTemplate");
    const localizeTemplateList = /* @__PURE__ */ __name((templates, categoryTitle) => templates.map(
      (template) => addLocalizedFieldsToTemplate(template, categoryTitle)
    ), "localizeTemplateList");
    const localizeTemplateCategory = /* @__PURE__ */ __name((templateCategory) => ({
      ...templateCategory,
      localizedTitle: st(
        `templateWorkflows.category.${normalizeI18nKey(templateCategory.title)}`,
        templateCategory.title ?? templateCategory.moduleName
      ),
      templates: localizeTemplateList(
        templateCategory.templates,
        templateCategory.title
      )
    }), "localizeTemplateCategory");
    const groupedTemplates = computed(() => {
      const allTemplates = [
        ...sortCategoryTemplates(coreTemplates.value).map(
          localizeTemplateCategory
        ),
        ...Object.entries(customTemplates.value).map(
          ([moduleName, templates]) => ({
            moduleName,
            title: moduleName,
            localizedTitle: st(
              `templateWorkflows.category.${normalizeI18nKey(moduleName)}`,
              moduleName
            ),
            templates: templates.map((name2) => ({
              name: name2,
              mediaType: "image",
              mediaSubtype: "jpg",
              description: name2
            }))
          })
        )
      ];
      return Object.entries(
        lodashExports.groupBy(
          allTemplates,
          (template) => template.moduleName === "default" ? st(
            "templateWorkflows.category.ComfyUI Examples",
            "ComfyUI Examples"
          ) : st("templateWorkflows.category.Custom Nodes", "Custom Nodes")
        )
      ).map(([label, modules]) => ({ label, modules }));
    });
    async function loadWorkflowTemplates() {
      try {
        if (!isLoaded.value) {
          customTemplates.value = await api.getWorkflowTemplates();
          coreTemplates.value = await api.getCoreWorkflowTemplates();
          isLoaded.value = true;
        }
      } catch (error2) {
        console.error("Error fetching workflow templates:", error2);
      }
    }
    __name(loadWorkflowTemplates, "loadWorkflowTemplates");
    return {
      groupedTemplates,
      isLoaded,
      loadWorkflowTemplates
    };
  }
);
const _hoisted_1$i = {
  class: "flex flex-col h-[83vh] w-[90vw] relative pb-6",
  "data-testid": "template-workflows-content"
};
const _hoisted_2$f = { class: "flex flex-1 relative overflow-hidden" };
const _hoisted_3$9 = {
  key: 0,
  class: "absolute translate-x-0 top-0 left-0 h-full w-80 shadow-md z-5 transition-transform duration-300 ease-in-out"
};
const _sfc_main$r = /* @__PURE__ */ defineComponent({
  __name: "TemplateWorkflowsContent",
  setup(__props) {
    const { t: t2 } = useI18n();
    const {
      isSmallScreen,
      isOpen: isSideNavOpen,
      toggle: toggleSideNav
    } = useResponsiveCollapse();
    const workflowTemplatesStore = useWorkflowTemplatesStore();
    const { isReady } = useAsyncState(
      workflowTemplatesStore.loadWorkflowTemplates,
      null
    );
    const selectedTab = ref$3(null);
    const selectFirstTab = /* @__PURE__ */ __name(() => {
      const firstTab = workflowTemplatesStore.groupedTemplates[0].modules[0];
      handleTabSelection(firstTab);
    }, "selectFirstTab");
    watch(isReady, selectFirstTab, { once: true });
    const workflowLoading = ref$3(null);
    const tabs = computed(() => workflowTemplatesStore.groupedTemplates);
    const handleTabSelection = /* @__PURE__ */ __name((selection) => {
      if (selection !== selectedTab.value && selection !== null) {
        selectedTab.value = selection;
        if (isSmallScreen.value) {
          isSideNavOpen.value = false;
        }
      }
    }, "handleTabSelection");
    const loadWorkflow = /* @__PURE__ */ __name(async (id2) => {
      if (!isReady.value) return;
      workflowLoading.value = id2;
      let json;
      if (selectedTab.value?.moduleName === "default") {
        json = await fetch(api.fileURL(`/templates/${id2}.json`)).then(
          (r2) => r2.json()
        );
      } else {
        json = await fetch(
          api.apiURL(
            `/workflow_templates/${selectedTab.value?.moduleName}/${id2}.json`
          )
        ).then((r2) => r2.json());
      }
      useDialogStore().closeDialog();
      const workflowName = selectedTab.value?.moduleName === "default" ? t2(`templateWorkflows.template.${id2}`, id2) : id2;
      await app$1.loadGraphData(json, true, true, workflowName);
      return false;
    }, "loadWorkflow");
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", _hoisted_1$i, [
        unref(isSmallScreen) ? (openBlock(), createBlock(unref(script$6), {
          key: 0,
          icon: unref(isSideNavOpen) ? "pi pi-chevron-left" : "pi pi-chevron-right",
          text: "",
          class: normalizeClass(["absolute top-1/2 -translate-y-1/2 z-10", unref(isSideNavOpen) ? "left-[19rem]" : "left-2"]),
          onClick: unref(toggleSideNav)
        }, null, 8, ["icon", "class", "onClick"])) : createCommentVNode("", true),
        createVNode(unref(script$f), { class: "m-0 [&::before]:border-surface-border/70 [&::before]:border-t-2" }),
        createBaseVNode("div", _hoisted_2$f, [
          unref(isSideNavOpen) ? (openBlock(), createElementBlock("aside", _hoisted_3$9, [
            !unref(workflowTemplatesStore).isLoaded || !unref(isReady) ? (openBlock(), createBlock(unref(script$x), {
              key: 0,
              class: "absolute w-8 h-full inset-0"
            })) : createCommentVNode("", true),
            createVNode(_sfc_main$s, {
              tabs: tabs.value,
              "selected-tab": selectedTab.value,
              "onUpdate:selectedTab": handleTabSelection
            }, null, 8, ["tabs", "selected-tab"])
          ])) : createCommentVNode("", true),
          createBaseVNode("div", {
            class: normalizeClass(["flex-1 transition-all duration-300", {
              "pl-80": unref(isSideNavOpen) || !unref(isSmallScreen),
              "pl-8": !unref(isSideNavOpen) && unref(isSmallScreen)
            }])
          }, [
            unref(isReady) && selectedTab.value ? (openBlock(), createBlock(_sfc_main$t, {
              key: 0,
              class: "px-12 py-4",
              title: selectedTab.value.title,
              "source-module": selectedTab.value.moduleName,
              templates: selectedTab.value.templates,
              loading: workflowLoading.value,
              "category-title": selectedTab.value.title,
              onLoadWorkflow: loadWorkflow
            }, null, 8, ["title", "source-module", "templates", "loading", "category-title"])) : createCommentVNode("", true)
          ], 2)
        ])
      ]);
    };
  }
});
const _sfc_main$q = {};
const _hoisted_1$h = { class: "px-4" };
function _sfc_render(_ctx, _cache) {
  return openBlock(), createElementBlock("div", null, [
    createBaseVNode("h3", _hoisted_1$h, [
      createBaseVNode("span", null, toDisplayString(_ctx.$t("templateWorkflows.title")), 1)
    ])
  ]);
}
__name(_sfc_render, "_sfc_render");
const TemplateWorkflowsDialogHeader = /* @__PURE__ */ _export_sfc(_sfc_main$q, [["render", _sfc_render]]);
const useDialogService = /* @__PURE__ */ __name(() => {
  const dialogStore = useDialogStore();
  function showLoadWorkflowWarning(props) {
    dialogStore.showDialog({
      key: "global-load-workflow-warning",
      component: LoadWorkflowWarning,
      props
    });
  }
  __name(showLoadWorkflowWarning, "showLoadWorkflowWarning");
  function showMissingModelsWarning(props) {
    dialogStore.showDialog({
      key: "global-missing-models-warning",
      component: MissingModelsWarning,
      props
    });
  }
  __name(showMissingModelsWarning, "showMissingModelsWarning");
  function showSettingsDialog(panel) {
    const props = panel ? { props: { defaultPanel: panel } } : void 0;
    dialogStore.showDialog({
      key: "global-settings",
      headerComponent: SettingDialogHeader,
      component: SettingDialogContent,
      ...props
    });
  }
  __name(showSettingsDialog, "showSettingsDialog");
  function showAboutDialog() {
    dialogStore.showDialog({
      key: "global-settings",
      headerComponent: SettingDialogHeader,
      component: SettingDialogContent,
      props: {
        defaultPanel: "about"
      }
    });
  }
  __name(showAboutDialog, "showAboutDialog");
  function showExecutionErrorDialog(executionError) {
    const props = {
      error: {
        exceptionType: executionError.exception_type,
        exceptionMessage: executionError.exception_message,
        nodeId: executionError.node_id?.toString(),
        nodeType: executionError.node_type,
        traceback: executionError.traceback.join("\n"),
        reportType: "graphExecutionError"
      }
    };
    dialogStore.showDialog({
      key: "global-execution-error",
      component: _sfc_main$1K,
      props
    });
  }
  __name(showExecutionErrorDialog, "showExecutionErrorDialog");
  function showTemplateWorkflowsDialog(props = {}) {
    dialogStore.showDialog({
      key: "global-template-workflows",
      title: t("templateWorkflows.title"),
      component: _sfc_main$r,
      headerComponent: TemplateWorkflowsDialogHeader,
      dialogComponentProps: {
        pt: {
          content: { class: "!px-0 overflow-y-hidden" }
        }
      },
      props
    });
  }
  __name(showTemplateWorkflowsDialog, "showTemplateWorkflowsDialog");
  function showIssueReportDialog(props) {
    dialogStore.showDialog({
      key: "global-issue-report",
      component: _sfc_main$1J,
      props
    });
  }
  __name(showIssueReportDialog, "showIssueReportDialog");
  function showManagerDialog(props = {
    initialTab: ManagerTab.All
  }) {
    dialogStore.showDialog({
      key: "global-manager",
      component: _sfc_main$K,
      headerComponent: _sfc_main$J,
      dialogComponentProps: {
        closable: false,
        pt: {
          header: { class: "!p-0 !m-0" },
          content: { class: "!px-0 h-[83vh] w-[90vw] overflow-y-hidden" }
        }
      },
      props
    });
  }
  __name(showManagerDialog, "showManagerDialog");
  function showManagerProgressDialog(options2) {
    return dialogStore.showDialog({
      key: "global-manager-progress-dialog",
      component: _sfc_main$1H,
      headerComponent: _sfc_main$C,
      footerComponent: _sfc_main$E,
      props: options2?.props,
      dialogComponentProps: {
        closable: false,
        modal: false,
        position: "bottom",
        pt: {
          root: { class: "w-[80%] max-w-2xl mx-auto border-none" },
          content: { class: "!p-0" },
          header: { class: "!p-0 border-none" },
          footer: { class: "!p-0 border-none" }
        }
      }
    });
  }
  __name(showManagerProgressDialog, "showManagerProgressDialog");
  function parseError(error2) {
    const filename = "fileName" in error2 ? error2.fileName : error2.stack?.match(/(\/extensions\/.*\.js)/)?.[1];
    const extensionFile = filename ? filename.substring(filename.indexOf("/extensions/")) : void 0;
    return {
      errorMessage: error2.toString(),
      stackTrace: error2.stack,
      extensionFile
    };
  }
  __name(parseError, "parseError");
  function showErrorDialog(error2, options2 = {}) {
    const errorProps = error2 instanceof Error ? parseError(error2) : {
      errorMessage: String(error2)
    };
    const props = {
      error: {
        exceptionType: options2.title ?? "Unknown Error",
        exceptionMessage: errorProps.errorMessage,
        traceback: errorProps.stackTrace ?? t("errorDialog.noStackTrace"),
        reportType: options2.reportType
      }
    };
    dialogStore.showDialog({
      key: "global-error",
      component: _sfc_main$1K,
      props
    });
  }
  __name(showErrorDialog, "showErrorDialog");
  async function showApiNodesSignInDialog(apiNodeNames) {
    return new Promise((resolve2) => {
      dialogStore.showDialog({
        key: "api-nodes-signin",
        component: _sfc_main$1P,
        props: {
          apiNodeNames,
          onLogin: /* @__PURE__ */ __name(() => showSignInDialog().then((result) => resolve2(result)), "onLogin"),
          onCancel: /* @__PURE__ */ __name(() => resolve2(false), "onCancel")
        },
        headerComponent: ComfyOrgHeader,
        dialogComponentProps: {
          closable: false,
          onClose: /* @__PURE__ */ __name(() => resolve2(false), "onClose")
        }
      });
    }).then((result) => {
      dialogStore.closeDialog({ key: "api-nodes-signin" });
      return result;
    });
  }
  __name(showApiNodesSignInDialog, "showApiNodesSignInDialog");
  async function showSignInDialog() {
    return new Promise((resolve2) => {
      dialogStore.showDialog({
        key: "global-signin",
        component: _sfc_main$1h,
        headerComponent: ComfyOrgHeader,
        props: {
          onSuccess: /* @__PURE__ */ __name(() => resolve2(true), "onSuccess")
        },
        dialogComponentProps: {
          closable: false,
          onClose: /* @__PURE__ */ __name(() => resolve2(false), "onClose")
        }
      });
    }).then((result) => {
      dialogStore.closeDialog({ key: "global-signin" });
      return result;
    });
  }
  __name(showSignInDialog, "showSignInDialog");
  async function prompt({
    title,
    message,
    defaultValue = ""
  }) {
    return new Promise((resolve2) => {
      dialogStore.showDialog({
        key: "global-prompt",
        title,
        component: _sfc_main$1D,
        props: {
          message,
          defaultValue,
          onConfirm: /* @__PURE__ */ __name((value) => {
            resolve2(value);
          }, "onConfirm")
        },
        dialogComponentProps: {
          onClose: /* @__PURE__ */ __name(() => {
            resolve2(null);
          }, "onClose")
        }
      });
    });
  }
  __name(prompt, "prompt");
  async function confirm2({
    title,
    message,
    type = "default",
    itemList = [],
    hint
  }) {
    return new Promise((resolve2) => {
      const options2 = {
        key: "global-prompt",
        title,
        component: ConfirmationDialogContent,
        props: {
          message,
          type,
          itemList,
          onConfirm: resolve2,
          hint
        },
        dialogComponentProps: {
          onClose: /* @__PURE__ */ __name(() => resolve2(null), "onClose")
        }
      };
      dialogStore.showDialog(options2);
    });
  }
  __name(confirm2, "confirm");
  function showTopUpCreditsDialog(options2) {
    return dialogStore.showDialog({
      key: "top-up-credits",
      component: _sfc_main$1e,
      headerComponent: ComfyOrgHeader,
      props: options2,
      dialogComponentProps: {
        pt: {
          header: { class: "!p-3" }
        }
      }
    });
  }
  __name(showTopUpCreditsDialog, "showTopUpCreditsDialog");
  function showUpdatePasswordDialog() {
    return dialogStore.showDialog({
      key: "global-update-password",
      component: _sfc_main$1d,
      headerComponent: ComfyOrgHeader,
      props: {
        onSuccess: /* @__PURE__ */ __name(() => dialogStore.closeDialog({ key: "global-update-password" }), "onSuccess")
      }
    });
  }
  __name(showUpdatePasswordDialog, "showUpdatePasswordDialog");
  function showApiNodesNewsDialog() {
    if (localStorage.getItem("api-nodes-news-seen") === "true") {
      return;
    }
    return dialogStore.showDialog({
      key: "api-nodes-news",
      component: _sfc_main$1R,
      props: {
        dismissableMask: true,
        onClose: /* @__PURE__ */ __name(() => {
          dialogStore.closeDialog({ key: "api-nodes-news" });
          localStorage.setItem("api-nodes-news-seen", "true");
        }, "onClose")
      },
      dialogComponentProps: {
        closable: false,
        position: "bottomright"
      }
    });
  }
  __name(showApiNodesNewsDialog, "showApiNodesNewsDialog");
  return {
    showLoadWorkflowWarning,
    showMissingModelsWarning,
    showSettingsDialog,
    showAboutDialog,
    showExecutionErrorDialog,
    showTemplateWorkflowsDialog,
    showIssueReportDialog,
    showManagerDialog,
    showManagerProgressDialog,
    showErrorDialog,
    showApiNodesSignInDialog,
    showSignInDialog,
    showTopUpCreditsDialog,
    showUpdatePasswordDialog,
    showApiNodesNewsDialog,
    prompt,
    confirm: confirm2
  };
}, "useDialogService");
function _findInMetadata(metadata, ...keys2) {
  for (const key of keys2) {
    if (key in metadata) {
      return metadata[key];
    }
    for (const k2 in metadata) {
      if (k2.endsWith(key)) {
        return metadata[k2];
      }
    }
  }
  return null;
}
__name(_findInMetadata, "_findInMetadata");
class ComfyModelDef {
  static {
    __name(this, "ComfyModelDef");
  }
  /** Path to the model */
  path_index;
  /** Proper filename of the model */
  file_name;
  /** Normalized filename of the model, with all backslashes replaced with forward slashes */
  normalized_file_name;
  /** Directory containing the model, eg 'checkpoints' */
  directory;
  /** Simplified copy of name, used as a default title. Excludes the directory and the '.safetensors' file extension */
  simplified_file_name;
  /** Key for the model, used to uniquely identify the model. */
  key;
  /** Title / display name of the model, sometimes same as the name but not always */
  title;
  /** Metadata: architecture ID for the model, such as 'stable-diffusion-xl-v1-base' */
  architecture_id = "";
  /** Metadata: author of the model */
  author = "";
  /** Metadata: resolution of the model, eg '1024x1024' */
  resolution = "";
  /** Metadata: description of the model */
  description = "";
  /** Metadata: usage hint for the model */
  usage_hint = "";
  /** Metadata: trigger phrase for the model */
  trigger_phrase = "";
  /** Metadata: tags list for the model */
  tags = [];
  /** Metadata: image for the model */
  image = "";
  /** Whether the model metadata has been loaded from the server, used for `load()` */
  has_loaded_metadata = false;
  /** If true, a metadata load request has been triggered, but may or may not yet have finished loading */
  is_load_requested = false;
  /** A string full of auto-computed lowercase-only searchable text for this model */
  searchable = "";
  constructor(name2, directory, pathIndex) {
    this.path_index = pathIndex;
    this.file_name = name2;
    this.normalized_file_name = name2.replaceAll("\\", "/");
    this.simplified_file_name = this.normalized_file_name.split("/").pop() ?? "";
    if (this.simplified_file_name.endsWith(".safetensors")) {
      this.simplified_file_name = this.simplified_file_name.slice(
        0,
        -".safetensors".length
      );
    }
    this.title = this.simplified_file_name;
    this.directory = directory;
    this.key = `${directory}/${this.normalized_file_name}`;
    this.updateSearchable();
  }
  updateSearchable() {
    this.searchable = [
      this.file_name,
      this.title,
      this.author,
      this.description,
      this.trigger_phrase,
      this.tags.join(", ")
    ].join("\n").toLowerCase();
  }
  /** Loads the model metadata from the server, filling in this object if data is available */
  async load() {
    if (this.has_loaded_metadata || this.is_load_requested) {
      return;
    }
    this.is_load_requested = true;
    try {
      const metadata = await api.viewMetadata(this.directory, this.file_name);
      if (!metadata) {
        return;
      }
      this.title = _findInMetadata(
        metadata,
        "modelspec.title",
        "title",
        "display_name",
        "name"
      ) || this.title;
      this.architecture_id = _findInMetadata(metadata, "modelspec.architecture", "architecture") || "";
      this.author = _findInMetadata(metadata, "modelspec.author", "author") || "";
      this.description = _findInMetadata(metadata, "modelspec.description", "description") || "";
      this.resolution = _findInMetadata(metadata, "modelspec.resolution", "resolution") || "";
      this.usage_hint = _findInMetadata(metadata, "modelspec.usage_hint", "usage_hint") || "";
      this.trigger_phrase = _findInMetadata(
        metadata,
        "modelspec.trigger_phrase",
        "trigger_phrase"
      ) || "";
      this.image = _findInMetadata(
        metadata,
        "modelspec.thumbnail",
        "thumbnail",
        "image",
        "icon"
      ) || "";
      const tagsCommaSeparated = _findInMetadata(metadata, "modelspec.tags", "tags") || "";
      this.tags = tagsCommaSeparated.split(",").map((tag) => tag.trim());
      this.has_loaded_metadata = true;
      this.updateSearchable();
    } catch (error2) {
      console.error("Error loading model metadata", this.file_name, this, error2);
    }
  }
}
var ResourceState = /* @__PURE__ */ ((ResourceState2) => {
  ResourceState2[ResourceState2["Uninitialized"] = 0] = "Uninitialized";
  ResourceState2[ResourceState2["Loading"] = 1] = "Loading";
  ResourceState2[ResourceState2["Loaded"] = 2] = "Loaded";
  return ResourceState2;
})(ResourceState || {});
class ModelFolder {
  static {
    __name(this, "ModelFolder");
  }
  constructor(directory) {
    this.directory = directory;
  }
  /** Models in this folder */
  models = {};
  state = 0;
  get key() {
    return this.directory + "/";
  }
  /**
   * Loads the models in this folder from the server
   */
  async load() {
    if (this.state !== 0) {
      return this;
    }
    this.state = 1;
    const models = await api.getModels(this.directory);
    for (const model of models) {
      this.models[`${model.pathIndex}/${model.name}`] = new ComfyModelDef(
        model.name,
        this.directory,
        model.pathIndex
      );
    }
    this.state = 2;
    return this;
  }
}
const useModelStore = /* @__PURE__ */ defineStore("models", () => {
  const modelFolderNames = ref$3([]);
  const modelFolderByName = ref$3({});
  const modelFolders = computed(
    () => modelFolderNames.value.map(
      (folderName) => modelFolderByName.value[folderName]
    )
  );
  const models = computed(
    () => modelFolders.value.flatMap((folder) => Object.values(folder.models))
  );
  async function loadModelFolders() {
    const resData = await api.getModelFolders();
    modelFolderNames.value = resData.map((folder) => folder.name);
    modelFolderByName.value = {};
    for (const folderName of modelFolderNames.value) {
      modelFolderByName.value[folderName] = new ModelFolder(folderName);
    }
  }
  __name(loadModelFolders, "loadModelFolders");
  async function getLoadedModelFolder(folderName) {
    const folder = modelFolderByName.value[folderName];
    return folder ? await folder.load() : null;
  }
  __name(getLoadedModelFolder, "getLoadedModelFolder");
  async function loadModels() {
    return Promise.all(modelFolders.value.map((folder) => folder.load()));
  }
  __name(loadModels, "loadModels");
  return {
    models,
    modelFolders,
    loadModelFolders,
    loadModels,
    getLoadedModelFolder
  };
});
function rgbToHsl({ r: r2, g: g2, b: b2 }) {
  r2 /= 255;
  g2 /= 255;
  b2 /= 255;
  const max = Math.max(r2, g2, b2), min = Math.min(r2, g2, b2);
  let h2 = 0, s2 = 0;
  const l2 = (max + min) / 2;
  if (max !== min) {
    const d2 = max - min;
    s2 = l2 > 0.5 ? d2 / (2 - max - min) : d2 / (max + min);
    switch (max) {
      case r2:
        h2 = (g2 - b2) / d2 + (g2 < b2 ? 6 : 0);
        break;
      case g2:
        h2 = (b2 - r2) / d2 + 2;
        break;
      case b2:
        h2 = (r2 - g2) / d2 + 4;
        break;
    }
    h2 /= 6;
  }
  return { h: h2, s: s2, l: l2 };
}
__name(rgbToHsl, "rgbToHsl");
function hexToRgb(hex) {
  let r2 = 0, g2 = 0, b2 = 0;
  if (hex.length == 4) {
    r2 = parseInt(hex[1] + hex[1], 16);
    g2 = parseInt(hex[2] + hex[2], 16);
    b2 = parseInt(hex[3] + hex[3], 16);
  } else if (hex.length == 7) {
    r2 = parseInt(hex.slice(1, 3), 16);
    g2 = parseInt(hex.slice(3, 5), 16);
    b2 = parseInt(hex.slice(5, 7), 16);
  }
  return { r: r2, g: g2, b: b2 };
}
__name(hexToRgb, "hexToRgb");
const identifyColorFormat = /* @__PURE__ */ __name((color2) => {
  if (!color2) return null;
  if (color2.startsWith("#") && (color2.length === 4 || color2.length === 7))
    return "hex";
  if (/rgba?\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*/.test(color2))
    return color2.includes("rgba") ? "rgba" : "rgb";
  if (/hsla?\(\s*\d+(\.\d+)?\s*,\s*\d+(\.\d+)?%\s*,\s*\d+(\.\d+)?%/.test(color2))
    return color2.includes("hsla") ? "hsla" : "hsl";
  return null;
}, "identifyColorFormat");
const isHSLA = /* @__PURE__ */ __name((color2) => {
  if (typeof color2 !== "object" || color2 === null) return false;
  return ["h", "s", "l", "a"].every(
    (key) => typeof color2[key] === "number" && !isNaN(color2[key])
  );
}, "isHSLA");
function parseToHSLA(color2, format2) {
  let match2;
  switch (format2) {
    case "hex": {
      const hsl = rgbToHsl(hexToRgb(color2));
      return {
        h: Math.round(hsl.h * 360),
        s: +(hsl.s * 100).toFixed(1),
        l: +(hsl.l * 100).toFixed(1),
        a: 1
      };
    }
    case "rgb":
    case "rgba": {
      match2 = color2.match(/\d+(\.\d+)?/g);
      if (!match2 || match2.length < 3) return null;
      const [r2, g2, b2] = match2.map(Number);
      const hsl = rgbToHsl({ r: r2, g: g2, b: b2 });
      const a2 = format2 === "rgba" && match2[3] ? parseFloat(match2[3]) : 1;
      return {
        h: Math.round(hsl.h * 360),
        s: +(hsl.s * 100).toFixed(1),
        l: +(hsl.l * 100).toFixed(1),
        a: a2
      };
    }
    case "hsl":
    case "hsla": {
      match2 = color2.match(/\d+(\.\d+)?/g);
      if (!match2 || match2.length < 3) return null;
      const [h2, s2, l2] = match2.map(Number);
      const a2 = format2 === "hsla" && match2[3] ? parseFloat(match2[3]) : 1;
      return { h: h2, s: s2, l: l2, a: a2 };
    }
    default:
      return null;
  }
}
__name(parseToHSLA, "parseToHSLA");
const applyColorAdjustments = /* @__PURE__ */ __name((color2, options2) => {
  if (!Object.keys(options2).length) return color2;
  const format2 = identifyColorFormat(color2);
  if (!format2) {
    console.warn(`Unsupported color format in color palette: ${color2}`);
    return color2;
  }
  const hsla = parseToHSLA(color2, format2);
  if (!isHSLA(hsla)) {
    console.warn(`Invalid color values in color palette: ${color2}`);
    return color2;
  }
  if (options2.lightness) {
    hsla.l = Math.max(0, Math.min(100, hsla.l + options2.lightness * 100));
  }
  if (options2.opacity) {
    hsla.a = Math.max(0, Math.min(1, options2.opacity));
  }
  return `hsla(${hsla.h}, ${hsla.s}%, ${hsla.l}%, ${hsla.a})`;
}, "applyColorAdjustments");
const adjustColor = lodashExports.memoize(
  applyColorAdjustments,
  (color2, options2) => `${color2}-${JSON.stringify(options2)}`
);
function recursiveAddNodes(nodeId, oldOutput, newOutput) {
  const currentId = String(nodeId);
  const currentNode = oldOutput[currentId];
  if (newOutput[currentId] == null) {
    newOutput[currentId] = currentNode;
    for (const inputValue of Object.values(currentNode.inputs || [])) {
      if (Array.isArray(inputValue)) {
        recursiveAddNodes(inputValue[0], oldOutput, newOutput);
      }
    }
  }
  return newOutput;
}
__name(recursiveAddNodes, "recursiveAddNodes");
const graphToPrompt = /* @__PURE__ */ __name(async (graph, options2 = {}) => {
  const { sortNodes = false, queueNodeIds } = options2;
  for (const node2 of graph.computeExecutionOrder(false)) {
    const innerNodes = node2.getInnerNodes ? node2.getInnerNodes() : [node2];
    for (const innerNode of innerNodes) {
      if (innerNode.isVirtualNode) {
        innerNode.applyToGraph?.();
      }
    }
  }
  const workflow = graph.serialize({ sortNodes });
  for (const node2 of workflow.nodes) {
    for (const slot of node2.inputs ?? []) {
      delete slot.localized_name;
    }
    for (const slot of node2.outputs ?? []) {
      delete slot.localized_name;
    }
  }
  compressWidgetInputSlots(workflow);
  workflow.extra ??= {};
  workflow.extra.frontendVersion = "1.20.0";
  let output = {};
  for (const outerNode of graph.computeExecutionOrder(false)) {
    const skipNode = outerNode.mode === LGraphEventMode.NEVER || outerNode.mode === LGraphEventMode.BYPASS;
    const innerNodes = !skipNode && outerNode.getInnerNodes ? outerNode.getInnerNodes() : [outerNode];
    for (const node2 of innerNodes) {
      if (node2.isVirtualNode || // Don't serialize muted nodes
      node2.mode === LGraphEventMode.NEVER || node2.mode === LGraphEventMode.BYPASS) {
        continue;
      }
      const inputs = {};
      const { widgets } = node2;
      if (widgets) {
        for (const [i2, widget] of widgets.entries()) {
          if (!widget.name || widget.options?.serialize === false) continue;
          const widgetValue = widget.serializeValue ? await widget.serializeValue(node2, i2) : widget.value;
          inputs[widget.name] = Array.isArray(widgetValue) ? {
            __value__: widgetValue
          } : widgetValue;
        }
      }
      for (const [i2, input] of node2.inputs.entries()) {
        let parent2 = node2.getInputNode(i2);
        if (!parent2) continue;
        let link2 = node2.getInputLink(i2);
        while (parent2?.mode === LGraphEventMode.BYPASS || parent2?.isVirtualNode) {
          if (!link2) break;
          if (parent2.isVirtualNode) {
            link2 = parent2.getInputLink(link2.origin_slot);
            if (!link2) break;
            parent2 = parent2.getInputNode(link2.target_slot);
            if (!parent2) break;
          } else if (!parent2.inputs) {
            break;
          } else if (parent2.mode === LGraphEventMode.BYPASS) {
            const parentInputIndexes = Object.keys(parent2.inputs).map(Number);
            const indexes = [link2.origin_slot].concat(parentInputIndexes);
            const matchingIndex = indexes.find(
              (index2) => parent2?.inputs[index2]?.type === input.type
            );
            if (matchingIndex === void 0) break;
            link2 = parent2.getInputLink(matchingIndex);
            if (link2) parent2 = parent2.getInputNode(matchingIndex);
          }
        }
        if (link2) {
          if (parent2?.updateLink) {
            link2 = parent2.updateLink(link2);
          }
          if (link2) {
            inputs[input.name] = [
              String(link2.origin_id),
              // @ts-expect-error link.origin_slot is already number.
              parseInt(link2.origin_slot)
            ];
          }
        }
      }
      output[String(node2.id)] = {
        inputs,
        // TODO(huchenlei): Filter out all nodes that cannot be mapped to a
        // comfyClass.
        class_type: node2.comfyClass,
        // Ignored by the backend.
        _meta: {
          title: node2.title
        }
      };
    }
  }
  for (const { inputs } of Object.values(output)) {
    for (const [i2, input] of Object.entries(inputs)) {
      if (Array.isArray(input) && input.length === 2 && !output[input[0]]) {
        delete inputs[i2];
      }
    }
  }
  if (queueNodeIds?.length) {
    const newOutput = {};
    for (const queueNodeId of queueNodeIds) {
      recursiveAddNodes(queueNodeId, output, newOutput);
    }
    output = newOutput;
  }
  return { workflow, output };
}, "graphToPrompt");
function findLegacyRerouteNodes(workflow) {
  return workflow.nodes.filter(
    (node2) => node2.type === "Reroute"
  );
}
__name(findLegacyRerouteNodes, "findLegacyRerouteNodes");
function noNativeReroutes(workflow) {
  return !workflow.extra?.reroutes?.length && !workflow.extra?.linkExtensions?.length;
}
__name(noNativeReroutes, "noNativeReroutes");
function getNodeCenter(node2) {
  return [node2.pos[0] + node2.size[0] / 2, node2.pos[1] + node2.size[1] / 2];
}
__name(getNodeCenter, "getNodeCenter");
class ConversionContext {
  static {
    __name(this, "ConversionContext");
  }
  constructor(workflow) {
    this.workflow = workflow;
    this.nodeById = _.keyBy(workflow.nodes.map(_.cloneDeep), "id");
    this.linkById = _.keyBy(
      workflow.links.map((l2) => ({
        id: l2[0],
        origin_id: l2[1],
        origin_slot: l2[2],
        target_id: l2[3],
        target_slot: l2[4],
        type: l2[5]
      })),
      "id"
    );
    const reroutes = findLegacyRerouteNodes(workflow).map((node2, index2) => ({
      nodeId: node2.id,
      id: index2 + 1,
      pos: getNodeCenter(node2),
      linkIds: []
    }));
    this.#rerouteIdCounter = reroutes.length + 1;
    this.rerouteByNodeId = _.keyBy(reroutes, "nodeId");
    this.rerouteById = _.keyBy(reroutes, "id");
    this.linkExtensions = [];
    this.validReroutes = /* @__PURE__ */ new Set();
  }
  nodeById;
  linkById;
  rerouteById;
  rerouteByNodeId;
  linkExtensions;
  /** Reroutes that has at least a valid link pass through it */
  validReroutes;
  #rerouteIdCounter = 0;
  /**
   * Gets the chain of reroute nodes leading to the given node
   */
  #getRerouteChain(node2) {
    const nodes = [];
    let currentNode = node2;
    while (currentNode?.type === "Reroute") {
      nodes.push(currentNode);
      const inputLink = this.linkById[currentNode.inputs?.[0]?.link ?? 0];
      if (!inputLink) {
        break;
      }
      currentNode = this.nodeById[inputLink.origin_id];
    }
    return nodes;
  }
  #connectRerouteChain(rerouteNodes) {
    const reroutes = rerouteNodes.map((node2) => this.rerouteByNodeId[node2.id]);
    for (const reroute of reroutes) {
      this.validReroutes.add(reroute);
    }
    for (let i2 = 0; i2 < rerouteNodes.length - 1; i2++) {
      const to = reroutes[i2];
      const from2 = reroutes[i2 + 1];
      to.parentId = from2.id;
    }
    return reroutes;
  }
  #createNewLink(startingLink, endingLink, rerouteNodes) {
    if (rerouteNodes.length === 0) {
      throw new Error("No reroute nodes found");
    }
    const reroute = this.rerouteByNodeId[rerouteNodes[0].id];
    this.linkExtensions.push({
      id: endingLink.id,
      parentId: reroute.id
    });
    const reroutes = this.#connectRerouteChain(rerouteNodes);
    for (const reroute2 of reroutes) {
      reroute2.linkIds ??= [];
      reroute2.linkIds.push(endingLink.id);
      delete reroute2.floating;
    }
    return {
      id: endingLink.id,
      origin_id: startingLink.origin_id,
      origin_slot: startingLink.origin_slot,
      target_id: endingLink.target_id,
      target_slot: endingLink.target_slot,
      type: endingLink.type
    };
  }
  #createNewInputFloatingLink(endingLink, rerouteNodes) {
    const reroutes = this.#connectRerouteChain(rerouteNodes);
    for (const reroute of reroutes) {
      if (!reroute.linkIds?.length) {
        reroute.floating = {
          slotType: "input"
        };
      }
    }
    return {
      id: this.#rerouteIdCounter++,
      origin_id: -1,
      origin_slot: -1,
      target_id: endingLink.target_id,
      target_slot: endingLink.target_slot,
      type: endingLink.type,
      parentId: reroutes[0].id
    };
  }
  #createNewOutputFloatingLink(startingLink, rerouteNodes) {
    const reroutes = this.#connectRerouteChain(rerouteNodes);
    for (const reroute of reroutes) {
      if (!reroute.linkIds?.length) {
        reroute.floating = {
          slotType: "output"
        };
      }
    }
    return {
      id: this.#rerouteIdCounter++,
      origin_id: startingLink.origin_id,
      origin_slot: startingLink.origin_slot,
      target_id: -1,
      target_slot: -1,
      type: startingLink.type,
      parentId: reroutes[0].id
    };
  }
  #reconnectLinks(nodes, links) {
    for (const node2 of nodes) {
      for (const input of node2.inputs ?? []) {
        input.link = null;
      }
      for (const output of node2.outputs ?? []) {
        output.links = [];
      }
    }
    const nodesById = _.keyBy(nodes, "id");
    for (const link2 of links) {
      const sourceNode = nodesById[link2.origin_id];
      sourceNode.outputs[link2.origin_slot].links.push(link2.id);
      const targetNode = nodesById[link2.target_id];
      targetNode.inputs[link2.target_slot].link = link2.id;
    }
  }
  migrateReroutes() {
    const links = [];
    const floatingLinks = [];
    const endingLinks = [];
    for (const link2 of Object.values(this.linkById)) {
      const sourceIsReroute = !!this.rerouteByNodeId[link2.origin_id];
      const targetIsReroute = !!this.rerouteByNodeId[link2.target_id];
      if (!sourceIsReroute && !targetIsReroute) {
        links.push(link2);
      } else if (sourceIsReroute && !targetIsReroute) {
        endingLinks.push(link2);
      }
    }
    for (const endingLink of endingLinks) {
      const endingRerouteNode = this.nodeById[endingLink.origin_id];
      const rerouteNodes = this.#getRerouteChain(endingRerouteNode);
      const startingLink = this.linkById[rerouteNodes[rerouteNodes.length - 1]?.inputs?.[0]?.link ?? -1];
      if (startingLink) {
        links.push(this.#createNewLink(startingLink, endingLink, rerouteNodes));
      } else {
        floatingLinks.push(
          this.#createNewInputFloatingLink(endingLink, rerouteNodes)
        );
      }
    }
    const floatingEndingRerouteNodes = Object.keys(this.rerouteByNodeId).map((nodeId) => this.nodeById[nodeId]).filter((rerouteNode) => {
      const output = rerouteNode.outputs?.[0];
      if (!output) return false;
      return !output.links?.length;
    });
    for (const rerouteNode of floatingEndingRerouteNodes) {
      const rerouteNodes = this.#getRerouteChain(rerouteNode);
      const startingLink = this.linkById[rerouteNodes[rerouteNodes.length - 1]?.inputs?.[0]?.link ?? -1];
      if (startingLink) {
        floatingLinks.push(
          this.#createNewOutputFloatingLink(startingLink, rerouteNodes)
        );
      }
    }
    const nodes = Object.values(this.nodeById).filter(
      (node2) => node2.type !== "Reroute"
    );
    this.#reconnectLinks(nodes, links);
    return {
      ...this.workflow,
      nodes,
      links: links.map((link2) => [
        link2.id,
        link2.origin_id,
        link2.origin_slot,
        link2.target_id,
        link2.target_slot,
        link2.type
      ]),
      floatingLinks: floatingLinks.length > 0 ? floatingLinks : void 0,
      extra: {
        ...this.workflow.extra,
        reroutes: Array.from(this.validReroutes).map(
          (reroute) => _.omit(reroute, "nodeId")
        ),
        linkExtensions: this.linkExtensions
      }
    };
  }
}
const migrateLegacyRerouteNodes = /* @__PURE__ */ __name((workflow) => {
  const legacyRerouteNodes = findLegacyRerouteNodes(workflow);
  if (legacyRerouteNodes.length === 0) {
    return workflow;
  }
  const newWorkflow = JSON.parse(JSON.stringify(workflow));
  if (!newWorkflow.extra) {
    newWorkflow.extra = {};
  }
  const context = new ConversionContext(newWorkflow);
  return context.migrateReroutes();
}, "migrateLegacyRerouteNodes");
function serialise(nodes, graph) {
  const serialisable = {
    nodes: [],
    links: []
  };
  let index2 = 0;
  const cloneable = [];
  for (const node2 of nodes) {
    if (node2.clonable === false) continue;
    node2._relative_id = index2++;
    cloneable.push(node2);
  }
  for (const node2 of cloneable) {
    const cloned = node2.clone();
    if (!cloned) {
      console.warn("node type not found: " + node2.type);
      continue;
    }
    serialisable.nodes.push(cloned.serialize());
    if (!node2.inputs?.length) continue;
    for (const input of node2.inputs) {
      if (!input || input.link == null) continue;
      const link2 = graph.links.get(input.link);
      if (!link2) continue;
      const outNode = graph.getNodeById(link2.origin_id);
      if (!outNode) continue;
      serialisable.links.push([
        outNode._relative_id,
        link2.origin_slot,
        node2._relative_id,
        link2.target_slot,
        outNode.id
      ]);
    }
  }
  return JSON.stringify(serialisable);
}
__name(serialise, "serialise");
function deserialiseAndCreate(data, canvas2) {
  if (!data) return;
  const { graph, graph_mouse } = canvas2;
  canvas2.emitBeforeChange();
  try {
    graph.beforeChange();
    const deserialised = JSON.parse(data);
    const topLeft = [Infinity, Infinity];
    for (const { pos } of deserialised.nodes) {
      if (topLeft[0] > pos[0]) topLeft[0] = pos[0];
      if (topLeft[1] > pos[1]) topLeft[1] = pos[1];
    }
    if (!Number.isFinite(topLeft[0]) || !Number.isFinite(topLeft[1])) {
      topLeft[0] = graph_mouse[0];
      topLeft[1] = graph_mouse[1];
    }
    const nodes = [];
    for (const info of deserialised.nodes) {
      const node2 = LiteGraph.createNode(info.type);
      if (!node2) continue;
      node2.configure(info);
      node2.pos[0] += graph_mouse[0] - topLeft[0];
      node2.pos[1] += graph_mouse[1] - topLeft[1];
      graph.add(node2, true);
      nodes.push(node2);
    }
    for (const info of deserialised.links) {
      const relativeId = info[0];
      const outNode = relativeId != null ? nodes[relativeId] : void 0;
      const inNode = nodes[info[2]];
      if (outNode && inNode) outNode.connect(info[1], inNode, info[3]);
      else console.warn("Warning, nodes missing on pasting");
    }
    canvas2.selectNodes(nodes);
    graph.afterChange();
  } finally {
    canvas2.emitAfterChange();
  }
}
__name(deserialiseAndCreate, "deserialiseAndCreate");
function getFromFlacBuffer(buffer) {
  const dataView = new DataView(buffer);
  const signature = String.fromCharCode(...new Uint8Array(buffer, 0, 4));
  if (signature !== "fLaC") {
    console.error("Not a valid FLAC file");
    return;
  }
  let offset = 4;
  let vorbisComment = null;
  while (offset < dataView.byteLength) {
    const isLastBlock = dataView.getUint8(offset) & 128;
    const blockType = dataView.getUint8(offset) & 127;
    const blockSize = dataView.getUint32(offset, false) & 16777215;
    offset += 4;
    if (blockType === 4) {
      vorbisComment = parseVorbisComment(
        new DataView(buffer, offset, blockSize)
      );
    }
    offset += blockSize;
    if (isLastBlock) break;
  }
  return vorbisComment;
}
__name(getFromFlacBuffer, "getFromFlacBuffer");
function getFromFlacFile(file) {
  return new Promise((r2) => {
    const reader = new FileReader();
    reader.onload = function(event) {
      const arrayBuffer = event.target.result;
      r2(getFromFlacBuffer(arrayBuffer));
    };
    reader.readAsArrayBuffer(file);
  });
}
__name(getFromFlacFile, "getFromFlacFile");
function parseVorbisComment(dataView) {
  let offset = 0;
  const vendorLength = dataView.getUint32(offset, true);
  offset += 4;
  const vendorString = getString(dataView, offset, vendorLength);
  offset += vendorLength;
  const userCommentListLength = dataView.getUint32(offset, true);
  offset += 4;
  const comments = {};
  for (let i2 = 0; i2 < userCommentListLength; i2++) {
    const commentLength = dataView.getUint32(offset, true);
    offset += 4;
    const comment2 = getString(dataView, offset, commentLength);
    offset += commentLength;
    const ind = comment2.indexOf("=");
    const key = comment2.substring(0, ind);
    comments[key] = comment2.substring(ind + 1);
  }
  return comments;
}
__name(parseVorbisComment, "parseVorbisComment");
function getString(dataView, offset, length) {
  let string = "";
  for (let i2 = 0; i2 < length; i2++) {
    string += String.fromCharCode(dataView.getUint8(offset + i2));
  }
  return string;
}
__name(getString, "getString");
window.comfyAPI = window.comfyAPI || {};
window.comfyAPI.flac = window.comfyAPI.flac || {};
window.comfyAPI.flac.getFromFlacBuffer = getFromFlacBuffer;
window.comfyAPI.flac.getFromFlacFile = getFromFlacFile;
function getFromPngBuffer(buffer) {
  const pngData = new Uint8Array(buffer);
  const dataView = new DataView(pngData.buffer);
  if (dataView.getUint32(0) !== 2303741511) {
    console.error("Not a valid PNG file");
    return;
  }
  let offset = 8;
  let txt_chunks = {};
  while (offset < pngData.length) {
    const length = dataView.getUint32(offset);
    const type = String.fromCharCode(...pngData.slice(offset + 4, offset + 8));
    if (type === "tEXt" || type == "comf" || type === "iTXt") {
      let keyword_end = offset + 8;
      while (pngData[keyword_end] !== 0) {
        keyword_end++;
      }
      const keyword = String.fromCharCode(
        ...pngData.slice(offset + 8, keyword_end)
      );
      const contentArraySegment = pngData.slice(
        keyword_end + 1,
        offset + 8 + length
      );
      const contentJson = new TextDecoder("utf-8").decode(contentArraySegment);
      txt_chunks[keyword] = contentJson;
    }
    offset += 12 + length;
  }
  return txt_chunks;
}
__name(getFromPngBuffer, "getFromPngBuffer");
function getFromPngFile(file) {
  return new Promise((r2) => {
    const reader = new FileReader();
    reader.onload = (event) => {
      r2(getFromPngBuffer(event.target.result));
    };
    reader.readAsArrayBuffer(file);
  });
}
__name(getFromPngFile, "getFromPngFile");
window.comfyAPI = window.comfyAPI || {};
window.comfyAPI.png = window.comfyAPI.png || {};
window.comfyAPI.png.getFromPngBuffer = getFromPngBuffer;
window.comfyAPI.png.getFromPngFile = getFromPngFile;
function getPngMetadata(file) {
  return getFromPngFile(file);
}
__name(getPngMetadata, "getPngMetadata");
function getFlacMetadata(file) {
  return getFromFlacFile(file);
}
__name(getFlacMetadata, "getFlacMetadata");
function parseExifData(exifData) {
  const isLittleEndian = String.fromCharCode(...exifData.slice(0, 2)) === "II";
  function readInt(offset, isLittleEndian2, length) {
    let arr = exifData.slice(offset, offset + length);
    if (length === 2) {
      return new DataView(arr.buffer, arr.byteOffset, arr.byteLength).getUint16(
        0,
        isLittleEndian2
      );
    } else if (length === 4) {
      return new DataView(arr.buffer, arr.byteOffset, arr.byteLength).getUint32(
        0,
        isLittleEndian2
      );
    }
  }
  __name(readInt, "readInt");
  const ifdOffset = readInt(4, isLittleEndian, 4);
  function parseIFD(offset) {
    const numEntries = readInt(offset, isLittleEndian, 2);
    const result = {};
    for (let i2 = 0; i2 < numEntries; i2++) {
      const entryOffset = offset + 2 + i2 * 12;
      const tag = readInt(entryOffset, isLittleEndian, 2);
      const type = readInt(entryOffset + 2, isLittleEndian, 2);
      const numValues = readInt(entryOffset + 4, isLittleEndian, 4);
      const valueOffset = readInt(entryOffset + 8, isLittleEndian, 4);
      let value;
      if (type === 2) {
        value = new TextDecoder("utf-8").decode(
          // @ts-expect-error fixme ts strict error
          exifData.subarray(valueOffset, valueOffset + numValues - 1)
        );
      }
      result[tag] = value;
    }
    return result;
  }
  __name(parseIFD, "parseIFD");
  const ifdData = parseIFD(ifdOffset);
  return ifdData;
}
__name(parseExifData, "parseExifData");
function getWebpMetadata(file) {
  return new Promise((r2) => {
    const reader = new FileReader();
    reader.onload = (event) => {
      const webp = new Uint8Array(event.target.result);
      const dataView = new DataView(webp.buffer);
      if (dataView.getUint32(0) !== 1380533830 || dataView.getUint32(8) !== 1464156752) {
        console.error("Not a valid WEBP file");
        r2({});
        return;
      }
      let offset = 12;
      let txt_chunks = {};
      while (offset < webp.length) {
        const chunk_length = dataView.getUint32(offset + 4, true);
        const chunk_type = String.fromCharCode(
          ...webp.slice(offset, offset + 4)
        );
        if (chunk_type === "EXIF") {
          if (String.fromCharCode(...webp.slice(offset + 8, offset + 8 + 6)) == "Exif\0\0") {
            offset += 6;
          }
          let data = parseExifData(
            webp.slice(offset + 8, offset + 8 + chunk_length)
          );
          for (var key in data) {
            const value = data[key];
            if (typeof value === "string") {
              const index2 = value.indexOf(":");
              txt_chunks[value.slice(0, index2)] = value.slice(index2 + 1);
            }
          }
          break;
        }
        offset += 8 + chunk_length;
      }
      r2(txt_chunks);
    };
    reader.readAsArrayBuffer(file);
  });
}
__name(getWebpMetadata, "getWebpMetadata");
function getLatentMetadata(file) {
  return new Promise((r2) => {
    const reader = new FileReader();
    reader.onload = (event) => {
      const safetensorsData = new Uint8Array(event.target.result);
      const dataView = new DataView(safetensorsData.buffer);
      let header_size = dataView.getUint32(0, true);
      let offset = 8;
      let header = JSON.parse(
        new TextDecoder().decode(
          safetensorsData.slice(offset, offset + header_size)
        )
      );
      r2(header.__metadata__);
    };
    var slice2 = file.slice(0, 1024 * 1024 * 4);
    reader.readAsArrayBuffer(slice2);
  });
}
__name(getLatentMetadata, "getLatentMetadata");
async function importA1111(graph, parameters) {
  const p2 = parameters.lastIndexOf("\nSteps:");
  if (p2 > -1) {
    const embeddings = await api.getEmbeddings();
    const opts = parameters.substr(p2).split("\n")[1].match(
      new RegExp('\\s*([^:]+:\\s*([^"\\{].*?|".*?"|\\{.*?\\}))\\s*(,|$)', "g")
    ).reduce((p3, n2) => {
      const s2 = n2.split(":");
      if (s2[1].endsWith(",")) {
        s2[1] = s2[1].substr(0, s2[1].length - 1);
      }
      p3[s2[0].trim().toLowerCase()] = s2[1].trim();
      return p3;
    }, {});
    const p22 = parameters.lastIndexOf("\nNegative prompt:", p2);
    if (p22 > -1) {
      let positive = parameters.substr(0, p22).trim();
      let negative = parameters.substring(p22 + 18, p2).trim();
      const ckptNode = LiteGraph.createNode("CheckpointLoaderSimple");
      const clipSkipNode = LiteGraph.createNode("CLIPSetLastLayer");
      const positiveNode = LiteGraph.createNode("CLIPTextEncode");
      const negativeNode = LiteGraph.createNode("CLIPTextEncode");
      const samplerNode = LiteGraph.createNode("KSampler");
      const imageNode = LiteGraph.createNode("EmptyLatentImage");
      const vaeNode = LiteGraph.createNode("VAEDecode");
      const saveNode = LiteGraph.createNode("SaveImage");
      let hrSamplerNode = null;
      let hrSteps = null;
      const ceil64 = /* @__PURE__ */ __name((v2) => Math.ceil(v2 / 64) * 64, "ceil64");
      const getWidget = /* @__PURE__ */ __name((node2, name2) => {
        return node2.widgets.find((w2) => w2.name === name2);
      }, "getWidget");
      const setWidgetValue = /* @__PURE__ */ __name((node2, name2, value, isOptionPrefix) => {
        const w2 = getWidget(node2, name2);
        if (isOptionPrefix) {
          const o2 = w2.options.values.find((w22) => w22.startsWith(value));
          if (o2) {
            w2.value = o2;
          } else {
            console.warn(`Unknown value '${value}' for widget '${name2}'`, node2);
            w2.value = value;
          }
        } else {
          w2.value = value;
        }
      }, "setWidgetValue");
      const createLoraNodes = /* @__PURE__ */ __name((clipNode, text2, prevClip, prevModel) => {
        const loras = [];
        text2 = text2.replace(/<lora:([^:]+:[^>]+)>/g, function(m2, c2) {
          const s2 = c2.split(":");
          const weight = parseFloat(s2[1]);
          if (isNaN(weight)) {
            console.warn("Invalid LORA", m2);
          } else {
            loras.push({ name: s2[0], weight });
          }
          return "";
        });
        for (const l2 of loras) {
          const loraNode = LiteGraph.createNode("LoraLoader");
          graph.add(loraNode);
          setWidgetValue(loraNode, "lora_name", l2.name, true);
          setWidgetValue(loraNode, "strength_model", l2.weight);
          setWidgetValue(loraNode, "strength_clip", l2.weight);
          prevModel.node.connect(prevModel.index, loraNode, 0);
          prevClip.node.connect(prevClip.index, loraNode, 1);
          prevModel = { node: loraNode, index: 0 };
          prevClip = { node: loraNode, index: 1 };
        }
        prevClip.node.connect(1, clipNode, 0);
        prevModel.node.connect(0, samplerNode, 0);
        if (hrSamplerNode) {
          prevModel.node.connect(0, hrSamplerNode, 0);
        }
        return { text: text2, prevModel, prevClip };
      }, "createLoraNodes");
      const replaceEmbeddings = /* @__PURE__ */ __name((text2) => {
        if (!embeddings.length) return text2;
        return text2.replaceAll(
          new RegExp(
            "\\b(" + embeddings.map((e2) => e2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("\\b|\\b") + ")\\b",
            "ig"
          ),
          "embedding:$1"
        );
      }, "replaceEmbeddings");
      const popOpt = /* @__PURE__ */ __name((name2) => {
        const v2 = opts[name2];
        delete opts[name2];
        return v2;
      }, "popOpt");
      graph.clear();
      graph.add(ckptNode);
      graph.add(clipSkipNode);
      graph.add(positiveNode);
      graph.add(negativeNode);
      graph.add(samplerNode);
      graph.add(imageNode);
      graph.add(vaeNode);
      graph.add(saveNode);
      ckptNode.connect(1, clipSkipNode, 0);
      clipSkipNode.connect(0, positiveNode, 0);
      clipSkipNode.connect(0, negativeNode, 0);
      ckptNode.connect(0, samplerNode, 0);
      positiveNode.connect(0, samplerNode, 1);
      negativeNode.connect(0, samplerNode, 2);
      imageNode.connect(0, samplerNode, 3);
      vaeNode.connect(0, saveNode, 0);
      samplerNode.connect(0, vaeNode, 0);
      ckptNode.connect(2, vaeNode, 1);
      const handlers2 = {
        // @ts-expect-error fixme ts strict error
        model(v2) {
          setWidgetValue(ckptNode, "ckpt_name", v2, true);
        },
        vae() {
        },
        // @ts-expect-error fixme ts strict error
        "cfg scale"(v2) {
          setWidgetValue(samplerNode, "cfg", +v2);
        },
        // @ts-expect-error fixme ts strict error
        "clip skip"(v2) {
          setWidgetValue(clipSkipNode, "stop_at_clip_layer", -v2);
        },
        // @ts-expect-error fixme ts strict error
        sampler(v2) {
          let name2 = v2.toLowerCase().replace("++", "pp").replaceAll(" ", "_");
          if (name2.includes("karras")) {
            name2 = name2.replace("karras", "").replace(/_+$/, "");
            setWidgetValue(samplerNode, "scheduler", "karras");
          } else {
            setWidgetValue(samplerNode, "scheduler", "normal");
          }
          const w2 = getWidget(samplerNode, "sampler_name");
          const o2 = w2.options.values.find(
            // @ts-expect-error fixme ts strict error
            (w22) => w22 === name2 || w22 === "sample_" + name2
          );
          if (o2) {
            setWidgetValue(samplerNode, "sampler_name", o2);
          }
        },
        // @ts-expect-error fixme ts strict error
        size(v2) {
          const wxh = v2.split("x");
          const w2 = ceil64(+wxh[0]);
          const h2 = ceil64(+wxh[1]);
          const hrUp = popOpt("hires upscale");
          const hrSz = popOpt("hires resize");
          hrSteps = popOpt("hires steps");
          let hrMethod = popOpt("hires upscaler");
          setWidgetValue(imageNode, "width", w2);
          setWidgetValue(imageNode, "height", h2);
          if (hrUp || hrSz) {
            let uw, uh;
            if (hrUp) {
              uw = w2 * hrUp;
              uh = h2 * hrUp;
            } else {
              const s2 = hrSz.split("x");
              uw = +s2[0];
              uh = +s2[1];
            }
            let upscaleNode;
            let latentNode;
            if (hrMethod.startsWith("Latent")) {
              latentNode = upscaleNode = LiteGraph.createNode("LatentUpscale");
              graph.add(upscaleNode);
              samplerNode.connect(0, upscaleNode, 0);
              switch (hrMethod) {
                case "Latent (nearest-exact)":
                  hrMethod = "nearest-exact";
                  break;
              }
              setWidgetValue(upscaleNode, "upscale_method", hrMethod, true);
            } else {
              const decode2 = LiteGraph.createNode("VAEDecodeTiled");
              graph.add(decode2);
              samplerNode.connect(0, decode2, 0);
              ckptNode.connect(2, decode2, 1);
              const upscaleLoaderNode = LiteGraph.createNode("UpscaleModelLoader");
              graph.add(upscaleLoaderNode);
              setWidgetValue(upscaleLoaderNode, "model_name", hrMethod, true);
              const modelUpscaleNode = LiteGraph.createNode(
                "ImageUpscaleWithModel"
              );
              graph.add(modelUpscaleNode);
              decode2.connect(0, modelUpscaleNode, 1);
              upscaleLoaderNode.connect(0, modelUpscaleNode, 0);
              upscaleNode = LiteGraph.createNode("ImageScale");
              graph.add(upscaleNode);
              modelUpscaleNode.connect(0, upscaleNode, 0);
              const vaeEncodeNode = latentNode = LiteGraph.createNode("VAEEncodeTiled");
              graph.add(vaeEncodeNode);
              upscaleNode.connect(0, vaeEncodeNode, 0);
              ckptNode.connect(2, vaeEncodeNode, 1);
            }
            setWidgetValue(upscaleNode, "width", ceil64(uw));
            setWidgetValue(upscaleNode, "height", ceil64(uh));
            hrSamplerNode = LiteGraph.createNode("KSampler");
            graph.add(hrSamplerNode);
            ckptNode.connect(0, hrSamplerNode, 0);
            positiveNode.connect(0, hrSamplerNode, 1);
            negativeNode.connect(0, hrSamplerNode, 2);
            latentNode.connect(0, hrSamplerNode, 3);
            hrSamplerNode.connect(0, vaeNode, 0);
          }
        },
        // @ts-expect-error fixme ts strict error
        steps(v2) {
          setWidgetValue(samplerNode, "steps", +v2);
        },
        // @ts-expect-error fixme ts strict error
        seed(v2) {
          setWidgetValue(samplerNode, "seed", +v2);
        }
      };
      for (const opt in opts) {
        if (opt in handlers2) {
          handlers2[opt](popOpt(opt));
        }
      }
      if (hrSamplerNode) {
        setWidgetValue(
          hrSamplerNode,
          "steps",
          hrSteps ? +hrSteps : getWidget(samplerNode, "steps").value
        );
        setWidgetValue(
          hrSamplerNode,
          "cfg",
          getWidget(samplerNode, "cfg").value
        );
        setWidgetValue(
          hrSamplerNode,
          "scheduler",
          getWidget(samplerNode, "scheduler").value
        );
        setWidgetValue(
          hrSamplerNode,
          "sampler_name",
          getWidget(samplerNode, "sampler_name").value
        );
        setWidgetValue(
          hrSamplerNode,
          "denoise",
          +(popOpt("denoising strength") || "1")
        );
      }
      let n2 = createLoraNodes(
        positiveNode,
        positive,
        { node: clipSkipNode, index: 0 },
        { node: ckptNode, index: 0 }
      );
      positive = n2.text;
      n2 = createLoraNodes(negativeNode, negative, n2.prevClip, n2.prevModel);
      negative = n2.text;
      setWidgetValue(positiveNode, "text", replaceEmbeddings(positive));
      setWidgetValue(negativeNode, "text", replaceEmbeddings(negative));
      graph.arrange();
      for (const opt of [
        "model hash",
        "ensd",
        "version",
        "vae hash",
        "ti hashes",
        "lora hashes",
        "hashes"
      ]) {
        delete opts[opt];
      }
      console.warn("Unhandled parameters:", opts);
    }
  }
}
__name(importA1111, "importA1111");
window.comfyAPI = window.comfyAPI || {};
window.comfyAPI.pnginfo = window.comfyAPI.pnginfo || {};
window.comfyAPI.pnginfo.getPngMetadata = getPngMetadata;
window.comfyAPI.pnginfo.getFlacMetadata = getFlacMetadata;
window.comfyAPI.pnginfo.getWebpMetadata = getWebpMetadata;
window.comfyAPI.pnginfo.getLatentMetadata = getLatentMetadata;
window.comfyAPI.pnginfo.importA1111 = importA1111;
class ComfyButtonGroup {
  static {
    __name(this, "ComfyButtonGroup");
  }
  element = $el("div.comfyui-button-group");
  buttons;
  constructor(...buttons) {
    this.buttons = prop(this, "buttons", buttons, () => this.update());
  }
  insert(button, index2) {
    this.buttons.splice(index2, 0, button);
    this.update();
  }
  append(button) {
    this.buttons.push(button);
    this.update();
  }
  remove(indexOrButton) {
    if (typeof indexOrButton !== "number") {
      indexOrButton = this.buttons.indexOf(indexOrButton);
    }
    if (indexOrButton > -1) {
      const r2 = this.buttons.splice(indexOrButton, 1);
      this.update();
      return r2;
    }
  }
  update() {
    this.element.replaceChildren(...this.buttons.map((b2) => b2["element"] ?? b2));
  }
}
window.comfyAPI = window.comfyAPI || {};
window.comfyAPI.buttonGroup = window.comfyAPI.buttonGroup || {};
window.comfyAPI.buttonGroup.ComfyButtonGroup = ComfyButtonGroup;
function applyClasses(element, classList, ...requiredClasses) {
  classList ??= "";
  let str;
  if (typeof classList === "string") {
    str = classList;
  } else if (classList instanceof Array) {
    str = classList.join(" ");
  } else {
    str = Object.entries(classList).reduce((p2, c2) => {
      if (c2[1]) {
        p2 += (p2.length ? " " : "") + c2[0];
      }
      return p2;
    }, "");
  }
  element.className = str;
  if (requiredClasses) {
    element.classList.add(...requiredClasses);
  }
}
__name(applyClasses, "applyClasses");
function toggleElement(element, {
  onHide,
  onShow
} = {}) {
  let placeholder;
  let hidden;
  return (value) => {
    if (value) {
      if (hidden) {
        hidden = false;
        placeholder.replaceWith(element);
      }
      onShow?.(element, value);
    } else {
      if (!placeholder) {
        placeholder = document.createComment("");
      }
      hidden = true;
      element.replaceWith(placeholder);
      onHide?.(element);
    }
  };
}
__name(toggleElement, "toggleElement");
window.comfyAPI = window.comfyAPI || {};
window.comfyAPI.utils = window.comfyAPI.utils || {};
window.comfyAPI.utils.applyClasses = applyClasses;
window.comfyAPI.utils.toggleElement = toggleElement;
class ComfyButton {
  static {
    __name(this, "ComfyButton");
  }
  #over = 0;
  #popupOpen = false;
  isOver = false;
  iconElement = $el("i.mdi");
  contentElement = $el("span");
  // @ts-expect-error fixme ts strict error
  popup;
  element;
  overIcon;
  iconSize;
  content;
  icon;
  tooltip;
  classList;
  hidden;
  enabled;
  action;
  constructor({
    icon: icon2,
    overIcon,
    iconSize,
    content,
    tooltip,
    action,
    classList = "comfyui-button",
    visibilitySetting,
    app: app2,
    enabled = true
  }) {
    this.element = $el(
      "button",
      {
        onmouseenter: /* @__PURE__ */ __name(() => {
          this.isOver = true;
          if (this.overIcon) {
            this.updateIcon();
          }
        }, "onmouseenter"),
        onmouseleave: /* @__PURE__ */ __name(() => {
          this.isOver = false;
          if (this.overIcon) {
            this.updateIcon();
          }
        }, "onmouseleave")
      },
      [this.iconElement, this.contentElement]
    );
    this.icon = prop(
      this,
      "icon",
      icon2,
      toggleElement(this.iconElement, { onShow: this.updateIcon })
    );
    this.overIcon = prop(this, "overIcon", overIcon, () => {
      if (this.isOver) {
        this.updateIcon();
      }
    });
    this.iconSize = prop(this, "iconSize", iconSize, this.updateIcon);
    this.content = prop(
      this,
      "content",
      content,
      toggleElement(this.contentElement, {
        onShow: /* @__PURE__ */ __name((el, v2) => {
          if (typeof v2 === "string") {
            el.textContent = v2;
          } else {
            el.replaceChildren(v2);
          }
        }, "onShow")
      })
    );
    this.tooltip = prop(this, "tooltip", tooltip, (v2) => {
      if (v2) {
        this.element.title = v2;
      } else {
        this.element.removeAttribute("title");
      }
    });
    if (tooltip !== void 0) {
      this.element.setAttribute("aria-label", tooltip);
    }
    this.classList = prop(this, "classList", classList, this.updateClasses);
    this.hidden = prop(this, "hidden", false, this.updateClasses);
    this.enabled = prop(this, "enabled", enabled, () => {
      this.updateClasses();
      this.element.disabled = !this.enabled;
    });
    this.action = prop(this, "action", action);
    this.element.addEventListener("click", (e2) => {
      if (this.popup) {
        if (!this.#over) {
          this.popup.toggle();
        }
      }
      this.action?.(e2, this);
    });
    if (visibilitySetting?.id) {
      const settingUpdated = /* @__PURE__ */ __name(() => {
        this.hidden = // @ts-expect-error fixme ts strict error
        app2.ui.settings.getSettingValue(visibilitySetting.id) !== visibilitySetting.showValue;
      }, "settingUpdated");
      app2.ui.settings.addEventListener(
        visibilitySetting.id + ".change",
        settingUpdated
      );
      settingUpdated();
    }
  }
  updateIcon = /* @__PURE__ */ __name(() => this.iconElement.className = `mdi mdi-${this.isOver && this.overIcon || this.icon}${this.iconSize ? " mdi-" + this.iconSize + "px" : ""}`, "updateIcon");
  updateClasses = /* @__PURE__ */ __name(() => {
    const internalClasses = [];
    if (this.hidden) {
      internalClasses.push("hidden");
    }
    if (!this.enabled) {
      internalClasses.push("disabled");
    }
    if (this.popup) {
      if (this.#popupOpen) {
        internalClasses.push("popup-open");
      } else {
        internalClasses.push("popup-closed");
      }
    }
    applyClasses(this.element, this.classList, ...internalClasses);
  }, "updateClasses");
  withPopup(popup, mode = "click") {
    this.popup = popup;
    if (mode === "hover") {
      for (const el of [this.element, this.popup.element]) {
        el.addEventListener("mouseenter", () => {
          this.popup.open = !!++this.#over;
        });
        el.addEventListener("mouseleave", () => {
          this.popup.open = !!--this.#over;
        });
      }
    }
    popup.addEventListener("change", () => {
      this.#popupOpen = popup.open;
      this.updateClasses();
    });
    return this;
  }
}
window.comfyAPI = window.comfyAPI || {};
window.comfyAPI.button = window.comfyAPI.button || {};
window.comfyAPI.button.ComfyButton = ComfyButton;
class ComfyPopup extends EventTarget {
  static {
    __name(this, "ComfyPopup");
  }
  element = $el("div.comfyui-popup");
  open;
  children;
  target;
  ignoreTarget;
  container;
  position;
  closeOnEscape;
  horizontal;
  classList;
  constructor({
    target,
    container = document.body,
    classList = "",
    ignoreTarget = true,
    closeOnEscape = true,
    position = "absolute",
    horizontal = "left"
  }, ...children) {
    super();
    this.target = target;
    this.ignoreTarget = ignoreTarget;
    this.container = container;
    this.position = position;
    this.closeOnEscape = closeOnEscape;
    this.horizontal = horizontal;
    container.append(this.element);
    this.children = prop(this, "children", children, () => {
      this.element.replaceChildren(...this.children);
      this.update();
    });
    this.classList = prop(
      this,
      "classList",
      classList,
      () => applyClasses(this.element, this.classList, "comfyui-popup", horizontal)
    );
    this.open = prop(this, "open", false, (v2, o2) => {
      if (v2 === o2) return;
      if (v2) {
        this.#show();
      } else {
        this.#hide();
      }
    });
  }
  toggle() {
    this.open = !this.open;
  }
  #hide() {
    this.element.classList.remove("open");
    window.removeEventListener("resize", this.update);
    window.removeEventListener("click", this.#clickHandler, { capture: true });
    window.removeEventListener("keydown", this.#escHandler, { capture: true });
    this.dispatchEvent(new CustomEvent("close"));
    this.dispatchEvent(new CustomEvent("change"));
  }
  #show() {
    this.element.classList.add("open");
    this.update();
    window.addEventListener("resize", this.update);
    window.addEventListener("click", this.#clickHandler, { capture: true });
    if (this.closeOnEscape) {
      window.addEventListener("keydown", this.#escHandler, { capture: true });
    }
    this.dispatchEvent(new CustomEvent("open"));
    this.dispatchEvent(new CustomEvent("change"));
  }
  // @ts-expect-error fixme ts strict error
  #escHandler = /* @__PURE__ */ __name((e2) => {
    if (e2.key === "Escape") {
      this.open = false;
      e2.preventDefault();
      e2.stopImmediatePropagation();
    }
  }, "#escHandler");
  // @ts-expect-error fixme ts strict error
  #clickHandler = /* @__PURE__ */ __name((e2) => {
    const target = e2.target;
    if (!this.element.contains(target) && this.ignoreTarget && !this.target.contains(target)) {
      this.open = false;
    }
  }, "#clickHandler");
  update = /* @__PURE__ */ __name(() => {
    const rect = this.target.getBoundingClientRect();
    this.element.style.setProperty("--bottom", "unset");
    if (this.position === "absolute") {
      if (this.horizontal === "left") {
        this.element.style.setProperty("--left", rect.left + "px");
      } else {
        this.element.style.setProperty(
          "--left",
          rect.right - this.element.clientWidth + "px"
        );
      }
      this.element.style.setProperty("--top", rect.bottom + "px");
      this.element.style.setProperty("--limit", rect.bottom + "px");
    } else {
      this.element.style.setProperty("--left", "0px");
      this.element.style.setProperty("--top", rect.height + "px");
      this.element.style.setProperty("--limit", rect.height + "px");
    }
    const thisRect = this.element.getBoundingClientRect();
    if (thisRect.height < 30) {
      this.element.style.setProperty("--top", "unset");
      this.element.style.setProperty("--bottom", rect.height + 5 + "px");
      this.element.style.setProperty("--limit", rect.height + 5 + "px");
    }
  }, "update");
}
window.comfyAPI = window.comfyAPI || {};
window.comfyAPI.popup = window.comfyAPI.popup || {};
window.comfyAPI.popup.ComfyPopup = ComfyPopup;
class ComfySplitButton {
  static {
    __name(this, "ComfySplitButton");
  }
  arrow;
  element;
  popup;
  items;
  constructor({
    primary,
    mode,
    horizontal = "left",
    position = "relative"
  }, ...items) {
    this.arrow = new ComfyButton({
      icon: "chevron-down"
    });
    this.element = $el(
      "div.comfyui-split-button" + (mode === "hover" ? ".hover" : ""),
      [
        $el(
          "div.comfyui-split-primary",
          {
            ariaLabel: "Queue current workflow"
          },
          primary.element
        ),
        $el(
          "div.comfyui-split-arrow",
          {
            ariaLabel: "Open extra opens",
            ariaHasPopup: "true"
          },
          this.arrow.element
        )
      ]
    );
    this.popup = new ComfyPopup({
      target: this.element,
      container: position === "relative" ? this.element : document.body,
      classList: "comfyui-split-button-popup" + (mode === "hover" ? " hover" : ""),
      closeOnEscape: mode === "click",
      position,
      horizontal
    });
    this.arrow.withPopup(this.popup, mode);
    this.items = prop(this, "items", items, () => this.update());
  }
  update() {
    this.popup.element.replaceChildren(
      ...this.items.map((b2) => "element" in b2 ? b2.element : b2)
    );
  }
}
window.comfyAPI = window.comfyAPI || {};
window.comfyAPI.splitButton = window.comfyAPI.splitButton || {};
window.comfyAPI.splitButton.ComfySplitButton = ComfySplitButton;
class ComfyAsyncDialog extends ComfyDialog$1 {
  static {
    __name(this, "ComfyAsyncDialog");
  }
  // @ts-expect-error fixme ts strict error
  #resolve;
  constructor(actions) {
    super(
      "dialog.comfy-dialog.comfyui-dialog",
      // @ts-expect-error fixme ts strict error
      actions?.map((opt) => {
        if (typeof opt === "string") {
          opt = { text: opt };
        }
        return $el("button.comfyui-button", {
          type: "button",
          textContent: opt.text,
          onclick: /* @__PURE__ */ __name(() => this.close(opt.value ?? opt.text), "onclick")
        });
      })
    );
  }
  show(html) {
    this.element.addEventListener("close", () => {
      this.close();
    });
    super.show(html);
    return new Promise((resolve2) => {
      this.#resolve = resolve2;
    });
  }
  showModal(html) {
    this.element.addEventListener("close", () => {
      this.close();
    });
    super.show(html);
    this.element.showModal();
    return new Promise((resolve2) => {
      this.#resolve = resolve2;
    });
  }
  close(result = null) {
    this.#resolve(result);
    this.element.close();
    super.close();
  }
  static async prompt({
    title = null,
    message,
    actions
  }) {
    const dialog = new ComfyAsyncDialog(actions);
    const content = [$el("span", message)];
    if (title) {
      content.unshift($el("h3", title));
    }
    const res = await dialog.showModal(content);
    dialog.element.remove();
    return res;
  }
}
window.comfyAPI = window.comfyAPI || {};
window.comfyAPI.asyncDialog = window.comfyAPI.asyncDialog || {};
window.comfyAPI.asyncDialog.ComfyAsyncDialog = ComfyAsyncDialog;
$el("style", {
  parent: document.head,
  textContent: `
        .draggable-item {
            position: relative;
            will-change: transform;
            user-select: none;
        }
        .draggable-item.is-idle {
            transition: 0.25s ease transform;
        }
        .draggable-item.is-draggable {
            z-index: 10;
        }
    `
});
class DraggableList extends EventTarget {
  static {
    __name(this, "DraggableList");
  }
  listContainer;
  // @ts-expect-error fixme ts strict error
  draggableItem;
  // @ts-expect-error fixme ts strict error
  pointerStartX;
  // @ts-expect-error fixme ts strict error
  pointerStartY;
  // @ts-expect-error fixme ts strict error
  scrollYMax;
  itemsGap = 0;
  items = [];
  itemSelector;
  handleClass = "drag-handle";
  off = [];
  offDrag = [];
  // @ts-expect-error fixme ts strict error
  constructor(element, itemSelector) {
    super();
    this.listContainer = element;
    this.itemSelector = itemSelector;
    if (!this.listContainer) return;
    this.off.push(this.on(this.listContainer, "mousedown", this.dragStart));
    this.off.push(this.on(this.listContainer, "touchstart", this.dragStart));
    this.off.push(this.on(document, "mouseup", this.dragEnd));
    this.off.push(this.on(document, "touchend", this.dragEnd));
  }
  getAllItems() {
    if (!this.items?.length) {
      this.items = Array.from(
        this.listContainer.querySelectorAll(this.itemSelector)
      );
      this.items.forEach((element) => {
        element.classList.add("is-idle");
      });
    }
    return this.items;
  }
  getIdleItems() {
    return this.getAllItems().filter(
      (item) => (
        // @ts-expect-error fixme ts strict error
        item.classList.contains("is-idle")
      )
    );
  }
  // @ts-expect-error fixme ts strict error
  isItemAbove(item) {
    return item.hasAttribute("data-is-above");
  }
  // @ts-expect-error fixme ts strict error
  isItemToggled(item) {
    return item.hasAttribute("data-is-toggled");
  }
  // @ts-expect-error fixme ts strict error
  on(source, event, listener, options2) {
    listener = listener.bind(this);
    source.addEventListener(event, listener, options2);
    return () => source.removeEventListener(event, listener);
  }
  // @ts-expect-error fixme ts strict error
  dragStart(e2) {
    if (e2.target.classList.contains(this.handleClass)) {
      this.draggableItem = e2.target.closest(this.itemSelector);
    }
    if (!this.draggableItem) return;
    this.pointerStartX = e2.clientX || e2.touches[0].clientX;
    this.pointerStartY = e2.clientY || e2.touches[0].clientY;
    this.scrollYMax = this.listContainer.scrollHeight - this.listContainer.clientHeight;
    this.setItemsGap();
    this.initDraggableItem();
    this.initItemsState();
    this.offDrag.push(this.on(document, "mousemove", this.drag));
    this.offDrag.push(
      // @ts-expect-error fixme ts strict error
      this.on(document, "touchmove", this.drag, { passive: false })
    );
    this.dispatchEvent(
      new CustomEvent("dragstart", {
        detail: {
          element: this.draggableItem,
          // @ts-expect-error fixme ts strict error
          position: this.getAllItems().indexOf(this.draggableItem)
        }
      })
    );
  }
  setItemsGap() {
    if (this.getIdleItems().length <= 1) {
      this.itemsGap = 0;
      return;
    }
    const item1 = this.getIdleItems()[0];
    const item2 = this.getIdleItems()[1];
    const item1Rect = item1.getBoundingClientRect();
    const item2Rect = item2.getBoundingClientRect();
    this.itemsGap = Math.abs(item1Rect.bottom - item2Rect.top);
  }
  initItemsState() {
    this.getIdleItems().forEach((item, i2) => {
      if (this.getAllItems().indexOf(this.draggableItem) > i2) {
        item.dataset.isAbove = "";
      }
    });
  }
  initDraggableItem() {
    this.draggableItem.classList.remove("is-idle");
    this.draggableItem.classList.add("is-draggable");
  }
  // @ts-expect-error fixme ts strict error
  drag(e2) {
    if (!this.draggableItem) return;
    e2.preventDefault();
    const clientX = e2.clientX || e2.touches[0].clientX;
    const clientY = e2.clientY || e2.touches[0].clientY;
    const listRect = this.listContainer.getBoundingClientRect();
    if (clientY > listRect.bottom) {
      if (this.listContainer.scrollTop < this.scrollYMax) {
        this.listContainer.scrollBy(0, 10);
        this.pointerStartY -= 10;
      }
    } else if (clientY < listRect.top && this.listContainer.scrollTop > 0) {
      this.pointerStartY += 10;
      this.listContainer.scrollBy(0, -10);
    }
    const pointerOffsetX = clientX - this.pointerStartX;
    const pointerOffsetY = clientY - this.pointerStartY;
    this.updateIdleItemsStateAndPosition();
    this.draggableItem.style.transform = `translate(${pointerOffsetX}px, ${pointerOffsetY}px)`;
  }
  updateIdleItemsStateAndPosition() {
    const draggableItemRect = this.draggableItem.getBoundingClientRect();
    const draggableItemY = draggableItemRect.top + draggableItemRect.height / 2;
    this.getIdleItems().forEach((item) => {
      const itemRect = item.getBoundingClientRect();
      const itemY = itemRect.top + itemRect.height / 2;
      if (this.isItemAbove(item)) {
        if (draggableItemY <= itemY) {
          item.dataset.isToggled = "";
        } else {
          delete item.dataset.isToggled;
        }
      } else {
        if (draggableItemY >= itemY) {
          item.dataset.isToggled = "";
        } else {
          delete item.dataset.isToggled;
        }
      }
    });
    this.getIdleItems().forEach((item) => {
      if (this.isItemToggled(item)) {
        const direction = this.isItemAbove(item) ? 1 : -1;
        item.style.transform = `translateY(${direction * (draggableItemRect.height + this.itemsGap)}px)`;
      } else {
        item.style.transform = "";
      }
    });
  }
  dragEnd() {
    if (!this.draggableItem) return;
    this.applyNewItemsOrder();
    this.cleanup();
  }
  applyNewItemsOrder() {
    const reorderedItems = [];
    let oldPosition = -1;
    this.getAllItems().forEach((item, index2) => {
      if (item === this.draggableItem) {
        oldPosition = index2;
        return;
      }
      if (!this.isItemToggled(item)) {
        reorderedItems[index2] = item;
        return;
      }
      const newIndex = this.isItemAbove(item) ? index2 + 1 : index2 - 1;
      reorderedItems[newIndex] = item;
    });
    for (let index2 = 0; index2 < this.getAllItems().length; index2++) {
      const item = reorderedItems[index2];
      if (typeof item === "undefined") {
        reorderedItems[index2] = this.draggableItem;
      }
    }
    reorderedItems.forEach((item) => {
      this.listContainer.appendChild(item);
    });
    this.items = reorderedItems;
    this.dispatchEvent(
      new CustomEvent("dragend", {
        detail: {
          element: this.draggableItem,
          oldPosition,
          newPosition: reorderedItems.indexOf(this.draggableItem)
        }
      })
    );
  }
  cleanup() {
    this.itemsGap = 0;
    this.items = [];
    this.unsetDraggableItem();
    this.unsetItemState();
    this.offDrag.forEach((f2) => f2());
    this.offDrag = [];
  }
  unsetDraggableItem() {
    this.draggableItem.style = null;
    this.draggableItem.classList.remove("is-draggable");
    this.draggableItem.classList.add("is-idle");
    this.draggableItem = null;
  }
  unsetItemState() {
    this.getIdleItems().forEach((item) => {
      delete item.dataset.isAbove;
      delete item.dataset.isToggled;
      item.style.transform = "";
    });
  }
  dispose() {
    this.off.forEach((f2) => f2());
  }
}
window.comfyAPI = window.comfyAPI || {};
window.comfyAPI.draggableList = window.comfyAPI.draggableList || {};
window.comfyAPI.draggableList.DraggableList = DraggableList;
class ComfyAppMenu {
  static {
    __name(this, "ComfyAppMenu");
  }
  app;
  actionsGroup;
  settingsGroup;
  viewGroup;
  element;
  constructor(app2) {
    this.app = app2;
    this.actionsGroup = new ComfyButtonGroup();
    this.settingsGroup = new ComfyButtonGroup();
    this.viewGroup = new ComfyButtonGroup();
    this.element = $el("div.flex.gap-2.mx-2", [
      this.actionsGroup.element,
      this.settingsGroup.element,
      this.viewGroup.element
    ]);
  }
}
window.comfyAPI = window.comfyAPI || {};
window.comfyAPI.index = window.comfyAPI.index || {};
window.comfyAPI.index.ComfyAppMenu = ComfyAppMenu;
const ANIM_PREVIEW_WIDGET = "$$comfy_animation_preview";
function sanitizeNodeName(string) {
  let entityMap = {
    "&": "",
    "<": "",
    ">": "",
    '"': "",
    "'": "",
    "`": "",
    "=": ""
  };
  return String(string).replace(/[&<>"'`=]/g, /* @__PURE__ */ __name(function fromEntityMap(s2) {
    return entityMap[s2];
  }, "fromEntityMap"));
}
__name(sanitizeNodeName, "sanitizeNodeName");
class ComfyApp {
  static {
    __name(this, "ComfyApp");
  }
  /**
   * List of entries to queue
   */
  #queueItems = [];
  /**
   * If the queue is currently being processed
   */
  #processingQueue = false;
  /**
   * Content Clipboard
   * @type {serialized node object}
   */
  static clipspace = null;
  static clipspace_invalidate_handler = null;
  static open_maskeditor = null;
  static maskeditor_is_opended = null;
  static clipspace_return_node = null;
  vueAppReady;
  api;
  ui;
  // @ts-expect-error fixme ts strict error
  extensionManager;
  // @ts-expect-error fixme ts strict error
  _nodeOutputs;
  nodePreviewImages;
  // @ts-expect-error fixme ts strict error
  graph;
  // @ts-expect-error fixme ts strict error
  canvas;
  dragOverNode = null;
  // @ts-expect-error fixme ts strict error
  canvasEl;
  configuringGraph = false;
  // @ts-expect-error fixme ts strict error
  ctx;
  bodyTop;
  bodyLeft;
  bodyRight;
  bodyBottom;
  canvasContainer;
  menu;
  bypassBgColor;
  // Set by Comfy.Clipspace extension
  openClipspace = /* @__PURE__ */ __name(() => {
  }, "openClipspace");
  #positionConversion;
  /**
   * The node errors from the previous execution.
   * @deprecated Use useExecutionStore().lastNodeErrors instead
   */
  get lastNodeErrors() {
    return useExecutionStore().lastNodeErrors;
  }
  /**
   * The error from the previous execution.
   * @deprecated Use useExecutionStore().lastExecutionError instead
   */
  get lastExecutionError() {
    return useExecutionStore().lastExecutionError;
  }
  /**
   * @deprecated Use useExecutionStore().executingNodeId instead
   */
  get runningNodeId() {
    return useExecutionStore().executingNodeId;
  }
  /**
   * @deprecated Use useWorkspaceStore().shiftDown instead
   */
  get shiftDown() {
    return useWorkspaceStore().shiftDown;
  }
  /**
   * @deprecated Use useWidgetStore().widgets instead
   */
  get widgets() {
    return Object.fromEntries(useWidgetStore().widgets.entries());
  }
  /**
   * @deprecated storageLocation is always 'server' since
   * https://github.com/comfyanonymous/ComfyUI/commit/53c8a99e6c00b5e20425100f6680cd9ea2652218
   */
  get storageLocation() {
    return "server";
  }
  /**
   * @deprecated storage migration is no longer needed.
   */
  get isNewUserSession() {
    return false;
  }
  /**
   * @deprecated Use useExtensionStore().extensions instead
   */
  get extensions() {
    return useExtensionStore().extensions;
  }
  /**
   * The progress on the current executing node, if the node reports any.
   * @deprecated Use useExecutionStore().executingNodeProgress instead
   */
  get progress() {
    return useExecutionStore()._executingNodeProgress;
  }
  /**
   * @deprecated Use {@link isImageNode} from @/utils/litegraphUtil instead
   */
  static isImageNode(node2) {
    return isImageNode(node2);
  }
  /**
   * Resets the canvas view to the default
   * @deprecated Use {@link useLitegraphService().resetView} instead
   */
  resetView() {
    useLitegraphService().resetView();
  }
  constructor() {
    this.vueAppReady = false;
    this.ui = new ComfyUI(this);
    this.api = api;
    this.bodyTop = $el("div.comfyui-body-top");
    this.bodyLeft = $el("div.comfyui-body-left");
    this.bodyRight = $el("div.comfyui-body-right");
    this.bodyBottom = $el("div.comfyui-body-bottom");
    this.canvasContainer = $el("div.graph-canvas-container");
    this.menu = new ComfyAppMenu(this);
    this.bypassBgColor = "#FF00FF";
    this.nodeOutputs = {};
    this.nodePreviewImages = {};
  }
  get nodeOutputs() {
    return this._nodeOutputs;
  }
  set nodeOutputs(value) {
    this._nodeOutputs = value;
    if (this.vueAppReady)
      useExtensionService().invokeExtensions("onNodeOutputsUpdated", value);
  }
  /**
   * If the user has specified a preferred format to receive preview images in,
   * this function will return that format as a url query param.
   * If the node's outputs are not images, this param should not be used, as it will
   * force the server to load the output file as an image.
   */
  getPreviewFormatParam() {
    let preview_format = useSettingStore().get("Comfy.PreviewFormat");
    if (preview_format) return `&preview=${preview_format}`;
    else return "";
  }
  getRandParam() {
    return "&rand=" + Math.random();
  }
  static onClipspaceEditorSave() {
    if (ComfyApp.clipspace_return_node) {
      ComfyApp.pasteFromClipspace(ComfyApp.clipspace_return_node);
    }
  }
  static onClipspaceEditorClosed() {
    ComfyApp.clipspace_return_node = null;
  }
  static copyToClipspace(node2) {
    var widgets = null;
    if (node2.widgets) {
      widgets = node2.widgets.map(({ type, name: name2, value }) => ({
        type,
        name: name2,
        value
      }));
    }
    var imgs = void 0;
    var orig_imgs = void 0;
    if (node2.imgs != void 0) {
      imgs = [];
      orig_imgs = [];
      for (let i2 = 0; i2 < node2.imgs.length; i2++) {
        imgs[i2] = new Image();
        imgs[i2].src = node2.imgs[i2].src;
        orig_imgs[i2] = imgs[i2];
      }
    }
    var selectedIndex = 0;
    if (node2.imageIndex) {
      selectedIndex = node2.imageIndex;
    }
    ComfyApp.clipspace = {
      widgets,
      imgs,
      original_imgs: orig_imgs,
      images: node2.images,
      selectedIndex,
      img_paste_mode: "selected"
      // reset to default im_paste_mode state on copy action
    };
    ComfyApp.clipspace_return_node = null;
    if (ComfyApp.clipspace_invalidate_handler) {
      ComfyApp.clipspace_invalidate_handler();
    }
  }
  static pasteFromClipspace(node2) {
    if (ComfyApp.clipspace) {
      if (ComfyApp.clipspace.imgs && node2.imgs) {
        if (node2.images && ComfyApp.clipspace.images) {
          if (ComfyApp.clipspace["img_paste_mode"] == "selected") {
            node2.images = [
              ComfyApp.clipspace.images[ComfyApp.clipspace["selectedIndex"]]
            ];
          } else {
            node2.images = ComfyApp.clipspace.images;
          }
          if (app$1.nodeOutputs[node2.id + ""])
            app$1.nodeOutputs[node2.id + ""].images = node2.images;
        }
        if (ComfyApp.clipspace.imgs) {
          if (ComfyApp.clipspace["img_paste_mode"] == "selected") {
            const img = new Image();
            img.src = ComfyApp.clipspace.imgs[ComfyApp.clipspace["selectedIndex"]].src;
            node2.imgs = [img];
            node2.imageIndex = 0;
          } else {
            const imgs = [];
            for (let i2 = 0; i2 < ComfyApp.clipspace.imgs.length; i2++) {
              imgs[i2] = new Image();
              imgs[i2].src = ComfyApp.clipspace.imgs[i2].src;
              node2.imgs = imgs;
            }
          }
        }
      }
      if (node2.widgets) {
        if (ComfyApp.clipspace.images) {
          const clip_image = ComfyApp.clipspace.images[ComfyApp.clipspace["selectedIndex"]];
          const index2 = node2.widgets.findIndex((obj) => obj.name === "image");
          if (index2 >= 0) {
            if (node2.widgets[index2].type != "image" && typeof node2.widgets[index2].value == "string" && clip_image.filename) {
              node2.widgets[index2].value = (clip_image.subfolder ? clip_image.subfolder + "/" : "") + clip_image.filename + (clip_image.type ? ` [${clip_image.type}]` : "");
            } else {
              node2.widgets[index2].value = clip_image;
            }
          }
        }
        if (ComfyApp.clipspace.widgets) {
          ComfyApp.clipspace.widgets.forEach(({ type, name: name2, value }) => {
            const prop2 = Object.values(node2.widgets).find(
              (obj) => obj.type === type && obj.name === name2
            );
            if (prop2 && prop2.type != "button") {
              if (prop2.type != "image" && typeof prop2.value == "string" && // @ts-expect-error Custom widget value
              value.filename) {
                const resultItem = value;
                prop2.value = (resultItem.subfolder ? resultItem.subfolder + "/" : "") + resultItem.filename + (resultItem.type ? ` [${resultItem.type}]` : "");
              } else {
                prop2.value = value;
                prop2.callback?.(value);
              }
            }
          });
        }
      }
      app$1.graph.setDirtyCanvas(true);
    }
  }
  /**
   * Adds a handler allowing drag+drop of files onto the window to load workflows
   */
  #addDropHandler() {
    document.addEventListener("drop", async (event) => {
      try {
        event.preventDefault();
        event.stopPropagation();
        const n2 = this.dragOverNode;
        this.dragOverNode = null;
        if (n2 && n2.onDragDrop && await n2.onDragDrop(event)) {
          return;
        }
        if (!event.dataTransfer) return;
        if (event.dataTransfer.files.length && event.dataTransfer.files[0].type !== "image/bmp") {
          await this.handleFile(event.dataTransfer.files[0]);
        } else {
          const validTypes = ["text/uri-list", "text/x-moz-url"];
          const match2 = [...event.dataTransfer.types].find(
            (t2) => validTypes.find((v2) => t2 === v2)
          );
          if (match2) {
            const uri = event.dataTransfer.getData(match2)?.split("\n")?.[0];
            if (uri) {
              const blob = await (await fetch(uri)).blob();
              await this.handleFile(new File([blob], uri, { type: blob.type }));
            }
          }
        }
      } catch (err) {
        useToastStore().addAlert(
          t("toastMessages.dropFileError", { error: err })
        );
      }
    });
    this.canvasEl.addEventListener("dragleave", async () => {
      if (this.dragOverNode) {
        this.dragOverNode = null;
        this.graph.setDirtyCanvas(false, true);
      }
    });
    this.canvasEl.addEventListener(
      "dragover",
      (e2) => {
        this.canvas.adjustMouseEvent(e2);
        const node2 = this.graph.getNodeOnPos(e2.canvasX, e2.canvasY);
        if (node2) {
          if (node2.onDragOver && node2.onDragOver(e2)) {
            this.dragOverNode = node2;
            requestAnimationFrame(() => {
              this.graph.setDirtyCanvas(false, true);
            });
            return;
          }
        }
        this.dragOverNode = null;
      },
      false
    );
  }
  /**
   * Handle keypress
   */
  #addProcessKeyHandler() {
    const origProcessKey = LGraphCanvas.prototype.processKey;
    LGraphCanvas.prototype.processKey = function(e2) {
      if (!this.graph) return;
      if (e2.target instanceof Element && e2.target.localName == "input") {
        return;
      }
      if (e2.type == "keydown" && !e2.repeat) {
        const keyCombo = KeyComboImpl.fromEvent(e2);
        const keybindingStore = useKeybindingStore();
        const keybinding = keybindingStore.getKeybinding(keyCombo);
        if (keybinding && keybinding.targetElementId === "graph-canvas") {
          useCommandStore().execute(keybinding.commandId);
          this.graph.change();
          e2.preventDefault();
          e2.stopImmediatePropagation();
          return;
        }
        if (e2.key === "c" && (e2.metaKey || e2.ctrlKey)) {
          return;
        }
        if ((e2.key === "v" || e2.key == "V") && (e2.metaKey || e2.ctrlKey) && !e2.shiftKey) {
          return;
        }
      }
      return origProcessKey.apply(this, arguments);
    };
  }
  #addDrawNodeHandler() {
    const origDrawNode = LGraphCanvas.prototype.drawNode;
    LGraphCanvas.prototype.drawNode = function(node2) {
      const editor_alpha = this.editor_alpha;
      const old_color = node2.color;
      const old_bgcolor = node2.bgcolor;
      if (node2.mode === LGraphEventMode.NEVER) {
        this.editor_alpha = 0.4;
      }
      let bgColor;
      if (node2.mode === LGraphEventMode.BYPASS) {
        bgColor = app$1.bypassBgColor;
        this.editor_alpha = 0.2;
      } else {
        bgColor = old_bgcolor || LiteGraph.NODE_DEFAULT_BGCOLOR;
      }
      const adjustments = {};
      const opacity = useSettingStore().get("Comfy.Node.Opacity");
      if (opacity) adjustments.opacity = opacity;
      if (useColorPaletteStore().completedActivePalette.light_theme) {
        adjustments.lightness = 0.5;
        if (old_color) {
          node2.color = adjustColor(old_color, { lightness: 0.5 });
        }
      }
      node2.bgcolor = adjustColor(bgColor, adjustments);
      const res = origDrawNode.apply(this, arguments);
      this.editor_alpha = editor_alpha;
      node2.color = old_color;
      node2.bgcolor = old_bgcolor;
      return res;
    };
  }
  /**
   * Handles updates from the API socket
   */
  #addApiUpdateHandlers() {
    api.addEventListener("status", ({ detail }) => {
      this.ui.setStatus(detail);
    });
    api.addEventListener("progress", () => {
      this.graph.setDirtyCanvas(true, false);
    });
    api.addEventListener("executing", () => {
      this.graph.setDirtyCanvas(true, false);
      this.revokePreviews(this.runningNodeId);
      delete this.nodePreviewImages[this.runningNodeId];
    });
    api.addEventListener("executed", ({ detail }) => {
      const output = this.nodeOutputs[detail.display_node || detail.node];
      if (detail.merge && output) {
        for (const k2 in detail.output ?? {}) {
          const v2 = output[k2];
          if (v2 instanceof Array) {
            output[k2] = v2.concat(detail.output[k2]);
          } else {
            output[k2] = detail.output[k2];
          }
        }
      } else {
        this.nodeOutputs[detail.display_node || detail.node] = detail.output;
      }
      const node2 = this.graph.getNodeById(detail.display_node || detail.node);
      if (node2) {
        if (node2.onExecuted) node2.onExecuted(detail.output);
      }
    });
    api.addEventListener("execution_start", () => {
      this.graph.nodes.forEach((node2) => {
        if (node2.onExecutionStart) node2.onExecutionStart();
      });
    });
    api.addEventListener("execution_error", ({ detail }) => {
      if (detail.exception_message === "Unauthorized: Please login first to use this node.") {
        useDialogService().showApiNodesSignInDialog([detail.node_type]);
      } else if (detail.exception_message === "Payment Required: Please add credits to your account to use this node.") {
        useDialogService().showTopUpCreditsDialog({
          isInsufficientCredits: true
        });
      } else {
        useDialogService().showExecutionErrorDialog(detail);
      }
      this.canvas.draw(true, true);
    });
    api.addEventListener("b_preview", ({ detail }) => {
      const id2 = this.runningNodeId;
      if (id2 == null) return;
      const blob = detail;
      const blobUrl = URL.createObjectURL(blob);
      this.revokePreviews(id2);
      this.nodePreviewImages[id2] = [blobUrl];
    });
    api.init();
  }
  #addConfigureHandler() {
    const app2 = this;
    const configure = LGraph.prototype.configure;
    LGraph.prototype.configure = function() {
      app2.configuringGraph = true;
      try {
        return configure.apply(this, arguments);
      } finally {
        app2.configuringGraph = false;
      }
    };
  }
  #addAfterConfigureHandler() {
    const app2 = this;
    const onConfigure = app2.graph.onConfigure;
    app2.graph.onConfigure = function(...args) {
      fixLinkInputSlots(this);
      for (const node2 of app2.graph.nodes) {
        node2.onGraphConfigured?.();
      }
      const r2 = onConfigure?.apply(this, args);
      for (const node2 of app2.graph.nodes) {
        node2.onAfterGraphConfigured?.();
      }
      pruneWidgets(this.nodes);
      return r2;
    };
  }
  /**
   * Set up the app on the page
   */
  async setup(canvasEl) {
    this.bodyTop = document.getElementById("comfyui-body-top");
    this.bodyLeft = document.getElementById("comfyui-body-left");
    this.bodyRight = document.getElementById("comfyui-body-right");
    this.bodyBottom = document.getElementById("comfyui-body-bottom");
    this.canvasContainer = document.getElementById("graph-canvas-container");
    this.canvasEl = canvasEl;
    this.resizeCanvas();
    await useWorkspaceStore().workflow.syncWorkflows();
    await useExtensionService().loadExtensions();
    this.#addProcessKeyHandler();
    this.#addConfigureHandler();
    this.#addApiUpdateHandlers();
    this.graph = new LGraph();
    this.#addAfterConfigureHandler();
    this.canvas = new LGraphCanvas(canvasEl, this.graph);
    this.canvas.state = reactive(this.canvas.state);
    this.canvas.ds.state = reactive(this.canvas.ds.state);
    this.ctx = canvasEl.getContext("2d");
    LiteGraph.alt_drag_do_clone_nodes = true;
    LiteGraph.macGesturesRequireMac = false;
    this.graph.start();
    this.resizeCanvas();
    window.addEventListener("resize", () => this.resizeCanvas());
    const ro = new ResizeObserver(() => this.resizeCanvas());
    ro.observe(this.bodyTop);
    ro.observe(this.bodyLeft);
    ro.observe(this.bodyRight);
    ro.observe(this.bodyBottom);
    await useExtensionService().invokeExtensionsAsync("init");
    await this.registerNodes();
    this.#addDrawNodeHandler();
    this.#addDropHandler();
    await useExtensionService().invokeExtensionsAsync("setup");
    this.#positionConversion = useCanvasPositionConversion(
      this.canvasContainer,
      this.canvas
    );
  }
  resizeCanvas() {
    const scale = Math.max(window.devicePixelRatio, 1);
    this.canvasEl.height = this.canvasEl.width = NaN;
    const { width: width2, height } = this.canvasEl.getBoundingClientRect();
    this.canvasEl.width = Math.round(width2 * scale);
    this.canvasEl.height = Math.round(height * scale);
    this.canvasEl.getContext("2d").scale(scale, scale);
    this.canvas?.draw(true, true);
  }
  updateVueAppNodeDefs(defs) {
    const rawDefs = Object.fromEntries(
      Object.entries(LiteGraph.registered_node_types).map(([name2, node2]) => [
        name2,
        {
          name: name2,
          display_name: name2,
          category: node2.category || "__frontend_only__",
          input: { required: {}, optional: {} },
          output: [],
          output_name: [],
          output_is_list: [],
          output_node: false,
          python_module: "custom_nodes.frontend_only",
          description: `Frontend only node for ${name2}`
        }
      ])
    );
    const allNodeDefs = {
      ...rawDefs,
      ...defs,
      ...SYSTEM_NODE_DEFS
    };
    const nodeDefStore = useNodeDefStore();
    const nodeDefArray = Object.values(allNodeDefs);
    useExtensionService().invokeExtensions(
      "beforeRegisterVueAppNodeDefs",
      nodeDefArray,
      this
    );
    nodeDefStore.updateNodeDefs(nodeDefArray);
  }
  async #getNodeDefs() {
    const translateNodeDef = /* @__PURE__ */ __name((def) => ({
      ...def,
      display_name: st(
        `nodeDefs.${def.name}.display_name`,
        def.display_name ?? def.name
      ),
      description: def.description ? st(`nodeDefs.${def.name}.description`, def.description) : "",
      category: def.category.split("/").map((category) => st(`nodeCategories.${category}`, category)).join("/")
    }), "translateNodeDef");
    return _.mapValues(
      await api.getNodeDefs({
        validate: useSettingStore().get("Comfy.Validation.NodeDefs")
      }),
      (def) => translateNodeDef(def)
    );
  }
  /**
   * Registers nodes with the graph
   */
  async registerNodes() {
    const defs = await this.#getNodeDefs();
    await this.registerNodesFromDefs(defs);
    await useExtensionService().invokeExtensionsAsync("registerCustomNodes");
    if (this.vueAppReady) {
      this.updateVueAppNodeDefs(defs);
    }
  }
  async registerNodeDef(nodeId, nodeDef) {
    return await useLitegraphService().registerNodeDef(nodeId, nodeDef);
  }
  async registerNodesFromDefs(defs) {
    await useExtensionService().invokeExtensionsAsync("addCustomNodeDefs", defs);
    for (const nodeId in defs) {
      this.registerNodeDef(nodeId, defs[nodeId]);
    }
  }
  // @ts-expect-error fixme ts strict error
  loadTemplateData(templateData) {
    if (!templateData?.templates) {
      return;
    }
    const old = localStorage.getItem("litegrapheditor_clipboard");
    var maxY, nodeBottom, node2;
    for (const template of templateData.templates) {
      if (!template?.data) {
        continue;
      }
      const data = JSON.parse(template.data);
      if (!data.reroutes) {
        deserialiseAndCreate(template.data, app$1.canvas);
      } else {
        localStorage.setItem("litegrapheditor_clipboard", template.data);
        app$1.canvas.pasteFromClipboard();
      }
      maxY = false;
      for (const i2 in app$1.canvas.selected_nodes) {
        node2 = app$1.canvas.selected_nodes[i2];
        nodeBottom = node2.pos[1] + node2.size[1];
        if (maxY === false || nodeBottom > maxY) {
          maxY = nodeBottom;
        }
      }
      app$1.canvas.graph_mouse[1] = maxY + 50;
    }
    localStorage.setItem("litegrapheditor_clipboard", old);
  }
  #showMissingNodesError(missingNodeTypes) {
    if (useSettingStore().get("Comfy.Workflow.ShowMissingNodesWarning")) {
      useDialogService().showLoadWorkflowWarning({ missingNodeTypes });
    }
  }
  // @ts-expect-error fixme ts strict error
  #showMissingModelsError(missingModels, paths) {
    if (useSettingStore().get("Comfy.Workflow.ShowMissingModelsWarning")) {
      useDialogService().showMissingModelsWarning({
        missingModels,
        paths
      });
    }
  }
  async loadGraphData(graphData, clean = true, restore_view = true, workflow = null, {
    showMissingNodesDialog = true,
    showMissingModelsDialog = true,
    checkForRerouteMigration = false
  } = {}) {
    if (clean !== false) {
      this.clean();
    }
    let reset_invalid_values = false;
    if (!graphData) {
      graphData = defaultGraph;
      reset_invalid_values = true;
    }
    graphData = clone$3(graphData);
    if (useSettingStore().get("Comfy.Validation.Workflows")) {
      const { graphData: validatedGraphData } = await useWorkflowValidation().validateWorkflow(graphData);
      graphData = validatedGraphData ?? graphData;
    }
    if (checkForRerouteMigration && graphData.version === 0.4 && findLegacyRerouteNodes(graphData).length && noNativeReroutes(graphData)) {
      useToastStore().add({
        group: "reroute-migration",
        severity: "warn"
      });
    }
    useWorkflowService().beforeLoadNewGraph();
    const missingNodeTypes = [];
    const missingModels = [];
    await useExtensionService().invokeExtensionsAsync(
      "beforeConfigureGraph",
      graphData,
      missingNodeTypes
    );
    const embeddedModels = [];
    for (let n2 of graphData.nodes) {
      if (n2.type == "T2IAdapterLoader") n2.type = "ControlNetLoader";
      if (n2.type == "ConditioningAverage ") n2.type = "ConditioningAverage";
      if (n2.type == "SDV_img2vid_Conditioning")
        n2.type = "SVD_img2vid_Conditioning";
      if (!(n2.type in LiteGraph.registered_node_types)) {
        missingNodeTypes.push(n2.type);
        n2.type = sanitizeNodeName(n2.type);
      }
      if (n2.properties?.models?.length)
        embeddedModels.push(...n2.properties.models);
    }
    const workflowSchemaV1Models = graphData.models;
    if (workflowSchemaV1Models?.length)
      embeddedModels.push(...workflowSchemaV1Models);
    const getModelKey = /* @__PURE__ */ __name((model) => model.url || model.hash, "getModelKey");
    const validModels = embeddedModels.filter(getModelKey);
    const uniqueModels = _.uniqBy(validModels, getModelKey);
    if (uniqueModels.length && useSettingStore().get("Comfy.Workflow.ShowMissingModelsWarning")) {
      const modelStore = useModelStore();
      await modelStore.loadModelFolders();
      for (const m2 of uniqueModels) {
        const modelFolder = await modelStore.getLoadedModelFolder(m2.directory);
        if (!modelFolder) m2.directory_invalid = true;
        const modelsAvailable = modelFolder?.models;
        const modelExists = modelsAvailable && Object.values(modelsAvailable).some(
          (model) => model.file_name === m2.name
        );
        if (!modelExists) missingModels.push(m2);
      }
    }
    try {
      this.graph.configure(graphData);
      if (restore_view) {
        if (useSettingStore().get("Comfy.EnableWorkflowViewRestore") && graphData.extra?.ds) {
          this.canvas.ds.offset = graphData.extra.ds.offset;
          this.canvas.ds.scale = graphData.extra.ds.scale;
        } else {
          requestAnimationFrame(() => {
            useLitegraphService().fitView();
          });
        }
      }
    } catch (error2) {
      useDialogService().showErrorDialog(error2, {
        title: t("errorDialog.loadWorkflowTitle"),
        reportType: "loadWorkflowError"
      });
      return;
    }
    for (const node2 of this.graph.nodes) {
      const size = node2.computeSize();
      size[0] = Math.max(node2.size[0], size[0]);
      size[1] = Math.max(node2.size[1], size[1]);
      node2.setSize(size);
      if (node2.widgets) {
        for (let widget of node2.widgets) {
          if (node2.type == "KSampler" || node2.type == "KSamplerAdvanced") {
            if (widget.name == "sampler_name") {
              if (typeof widget.value === "string" && widget.value.startsWith("sample_")) {
                widget.value = widget.value.slice(7);
              }
            }
          }
          if (node2.type == "KSampler" || node2.type == "KSamplerAdvanced" || node2.type == "PrimitiveNode") {
            if (widget.name == "control_after_generate") {
              if (widget.value === true) {
                widget.value = "randomize";
              } else if (widget.value === false) {
                widget.value = "fixed";
              }
            }
          }
          if (reset_invalid_values) {
            if (widget.type == "combo") {
              if (
                // @ts-expect-error fixme ts strict error
                !widget.options.values.includes(widget.value) && // @ts-expect-error fixme ts strict error
                widget.options.values.length > 0
              ) {
                widget.value = widget.options.values[0];
              }
            }
          }
        }
      }
      useExtensionService().invokeExtensions("loadedGraphNode", node2);
    }
    if (missingNodeTypes.length && showMissingNodesDialog) {
      this.#showMissingNodesError(missingNodeTypes);
    }
    if (missingModels.length && showMissingModelsDialog) {
      const paths = await api.getFolderPaths();
      this.#showMissingModelsError(missingModels, paths);
    }
    await useExtensionService().invokeExtensionsAsync(
      "afterConfigureGraph",
      missingNodeTypes
    );
    await useWorkflowService().afterLoadNewGraph(
      workflow,
      this.graph.serialize()
    );
    requestAnimationFrame(() => {
      this.graph.setDirtyCanvas(true, true);
    });
  }
  async graphToPrompt(graph = this.graph, options2 = {}) {
    return graphToPrompt(graph, {
      sortNodes: useSettingStore().get("Comfy.Workflow.SortNodeIdOnSave"),
      queueNodeIds: options2.queueNodeIds
    });
  }
  async queuePrompt(number, batchCount = 1, queueNodeIds) {
    this.#queueItems.push({ number, batchCount, queueNodeIds });
    if (this.#processingQueue) {
      return false;
    }
    this.#processingQueue = true;
    const executionStore = useExecutionStore();
    executionStore.lastNodeErrors = null;
    let comfyOrgAuthToken = await useFirebaseAuthStore().getIdToken() ?? void 0;
    let comfyOrgApiKey = useApiKeyAuthStore().getApiKey();
    try {
      while (this.#queueItems.length) {
        const { number: number2, batchCount: batchCount2, queueNodeIds: queueNodeIds2 } = this.#queueItems.pop();
        for (let i2 = 0; i2 < batchCount2; i2++) {
          executeWidgetsCallback(this.graph.nodes, "beforeQueued");
          const p2 = await this.graphToPrompt(this.graph, { queueNodeIds: queueNodeIds2 });
          try {
            api.authToken = comfyOrgAuthToken;
            api.apiKey = comfyOrgApiKey ?? void 0;
            const res = await api.queuePrompt(number2, p2);
            delete api.authToken;
            delete api.apiKey;
            executionStore.lastNodeErrors = res.node_errors ?? null;
            if (executionStore.lastNodeErrors?.length) {
              this.canvas.draw(true, true);
            } else {
              try {
                if (res.prompt_id) {
                  executionStore.storePrompt({
                    id: res.prompt_id,
                    nodes: Object.keys(p2.output),
                    workflow: useWorkspaceStore().workflow.activeWorkflow
                  });
                }
              } catch (error2) {
              }
            }
          } catch (error2) {
            useDialogService().showErrorDialog(error2, {
              title: t("errorDialog.promptExecutionError"),
              reportType: "promptExecutionError"
            });
            if (error2 instanceof PromptExecutionError) {
              executionStore.lastNodeErrors = error2.response.node_errors ?? null;
              this.canvas.draw(true, true);
            }
            break;
          }
          executeWidgetsCallback(
            p2.workflow.nodes.map((n2) => this.graph.getNodeById(n2.id)).filter((n2) => !!n2),
            "afterQueued"
          );
          this.canvas.draw(true, true);
          await this.ui.queue.update();
        }
      }
    } finally {
      this.#processingQueue = false;
    }
    api.dispatchCustomEvent("promptQueued", { number, batchCount });
    return !executionStore.lastNodeErrors;
  }
  showErrorOnFileLoad(file) {
    useToastStore().addAlert(
      t("toastMessages.fileLoadError", { fileName: file.name })
    );
  }
  /**
   * Loads workflow data from the specified file
   * @param {File} file
   */
  async handleFile(file) {
    const removeExt = /* @__PURE__ */ __name((f2) => {
      if (!f2) return f2;
      const p2 = f2.lastIndexOf(".");
      if (p2 === -1) return f2;
      return f2.substring(0, p2);
    }, "removeExt");
    const fileName = removeExt(file.name);
    if (file.type === "image/png") {
      const pngInfo = await getPngMetadata(file);
      if (pngInfo?.workflow) {
        await this.loadGraphData(
          JSON.parse(pngInfo.workflow),
          true,
          true,
          fileName
        );
      } else if (pngInfo?.prompt) {
        this.loadApiJson(JSON.parse(pngInfo.prompt), fileName);
      } else if (pngInfo?.parameters) {
        useWorkflowService().beforeLoadNewGraph();
        importA1111(this.graph, pngInfo.parameters);
        useWorkflowService().afterLoadNewGraph(
          fileName,
          this.graph.serialize()
        );
      } else {
        this.showErrorOnFileLoad(file);
      }
    } else if (file.type === "image/webp") {
      const pngInfo = await getWebpMetadata(file);
      const workflow = pngInfo?.workflow || pngInfo?.Workflow;
      const prompt = pngInfo?.prompt || pngInfo?.Prompt;
      if (workflow) {
        this.loadGraphData(JSON.parse(workflow), true, true, fileName);
      } else if (prompt) {
        this.loadApiJson(JSON.parse(prompt), fileName);
      } else {
        this.showErrorOnFileLoad(file);
      }
    } else if (file.type === "audio/mpeg") {
      const { workflow, prompt } = await getMp3Metadata(file);
      if (workflow) {
        this.loadGraphData(workflow, true, true, fileName);
      } else if (prompt) {
        this.loadApiJson(prompt, fileName);
      } else {
        this.showErrorOnFileLoad(file);
      }
    } else if (file.type === "audio/ogg") {
      const { workflow, prompt } = await getOggMetadata(file);
      if (workflow) {
        this.loadGraphData(workflow, true, true, fileName);
      } else if (prompt) {
        this.loadApiJson(prompt, fileName);
      } else {
        this.showErrorOnFileLoad(file);
      }
    } else if (file.type === "audio/flac" || file.type === "audio/x-flac") {
      const pngInfo = await getFlacMetadata(file);
      const workflow = pngInfo?.workflow || pngInfo?.Workflow;
      const prompt = pngInfo?.prompt || pngInfo?.Prompt;
      if (workflow) {
        this.loadGraphData(JSON.parse(workflow), true, true, fileName);
      } else if (prompt) {
        this.loadApiJson(JSON.parse(prompt), fileName);
      } else {
        this.showErrorOnFileLoad(file);
      }
    } else if (file.type === "video/webm") {
      const webmInfo = await getFromWebmFile(file);
      if (webmInfo.workflow) {
        this.loadGraphData(webmInfo.workflow, true, true, fileName);
      } else if (webmInfo.prompt) {
        this.loadApiJson(webmInfo.prompt, fileName);
      } else {
        this.showErrorOnFileLoad(file);
      }
    } else if (file.type === "video/mp4" || file.name?.endsWith(".mp4") || file.name?.endsWith(".mov") || file.name?.endsWith(".m4v") || file.type === "video/quicktime" || file.type === "video/x-m4v") {
      const mp4Info = await getFromIsobmffFile(file);
      if (mp4Info.workflow) {
        this.loadGraphData(mp4Info.workflow, true, true, fileName);
      } else if (mp4Info.prompt) {
        this.loadApiJson(mp4Info.prompt, fileName);
      }
    } else if (file.type === "image/svg+xml" || file.name?.endsWith(".svg")) {
      const svgInfo = await getSvgMetadata(file);
      if (svgInfo.workflow) {
        this.loadGraphData(svgInfo.workflow, true, true, fileName);
      } else if (svgInfo.prompt) {
        this.loadApiJson(svgInfo.prompt, fileName);
      } else {
        this.showErrorOnFileLoad(file);
      }
    } else if (file.type === "model/gltf-binary" || file.name?.endsWith(".glb")) {
      const gltfInfo = await getGltfBinaryMetadata(file);
      if (gltfInfo.workflow) {
        this.loadGraphData(gltfInfo.workflow, true, true, fileName);
      } else if (gltfInfo.prompt) {
        this.loadApiJson(gltfInfo.prompt, fileName);
      } else {
        this.showErrorOnFileLoad(file);
      }
    } else if (file.type === "application/json" || file.name?.endsWith(".json")) {
      const reader = new FileReader();
      reader.onload = async () => {
        const readerResult = reader.result;
        const jsonContent = JSON.parse(readerResult);
        if (jsonContent?.templates) {
          this.loadTemplateData(jsonContent);
        } else if (this.isApiJson(jsonContent)) {
          this.loadApiJson(jsonContent, fileName);
        } else {
          await this.loadGraphData(
            JSON.parse(readerResult),
            true,
            true,
            fileName
          );
        }
      };
      reader.readAsText(file);
    } else if (file.name?.endsWith(".latent") || file.name?.endsWith(".safetensors")) {
      const info = await getLatentMetadata(file);
      if (info.workflow) {
        await this.loadGraphData(
          // @ts-expect-error
          JSON.parse(info.workflow),
          true,
          true,
          fileName
        );
      } else if (info.prompt) {
        this.loadApiJson(JSON.parse(info.prompt));
      } else {
        this.showErrorOnFileLoad(file);
      }
    } else {
      this.showErrorOnFileLoad(file);
    }
  }
  isApiJson(data) {
    return _.isObject(data) && Object.values(data).every((v2) => v2.class_type);
  }
  loadApiJson(apiData, fileName) {
    useWorkflowService().beforeLoadNewGraph();
    const missingNodeTypes = Object.values(apiData).filter(
      (n2) => !LiteGraph.registered_node_types[n2.class_type]
    );
    if (missingNodeTypes.length) {
      this.#showMissingNodesError(missingNodeTypes.map((t2) => t2.class_type));
      return;
    }
    const ids = Object.keys(apiData);
    app$1.graph.clear();
    for (const id2 of ids) {
      const data = apiData[id2];
      const node2 = LiteGraph.createNode(data.class_type);
      if (!node2) continue;
      node2.id = isNaN(+id2) ? id2 : +id2;
      node2.title = data._meta?.title ?? node2.title;
      app$1.graph.add(node2);
    }
    for (const id2 of ids) {
      const data = apiData[id2];
      const node2 = app$1.graph.getNodeById(id2);
      for (const input in data.inputs ?? {}) {
        const value = data.inputs[input];
        if (value instanceof Array) {
          const [fromId, fromSlot] = value;
          const fromNode = app$1.graph.getNodeById(fromId);
          let toSlot = node2.inputs?.findIndex((inp) => inp.name === input);
          if (toSlot == null || toSlot === -1) {
            try {
              const widget = node2.widgets?.find((w2) => w2.name === input);
              if (widget && node2.convertWidgetToInput?.(widget)) {
                toSlot = node2.inputs?.length - 1;
              }
            } catch (error2) {
            }
          }
          if (toSlot != null || toSlot !== -1) {
            fromNode.connect(fromSlot, node2, toSlot);
          }
        } else {
          const widget = node2.widgets?.find((w2) => w2.name === input);
          if (widget) {
            widget.value = value;
            widget.callback?.(value);
          }
        }
      }
    }
    app$1.graph.arrange();
    for (const id2 of ids) {
      const data = apiData[id2];
      const node2 = app$1.graph.getNodeById(id2);
      for (const input in data.inputs ?? {}) {
        const value = data.inputs[input];
        if (value instanceof Array) {
          const [fromId, fromSlot] = value;
          const fromNode = app$1.graph.getNodeById(fromId);
          let toSlot = node2.inputs?.findIndex((inp) => inp.name === input);
          if (toSlot == null || toSlot === -1) {
            try {
              const widget = node2.widgets?.find((w2) => w2.name === input);
              if (widget && node2.convertWidgetToInput?.(widget)) {
                toSlot = node2.inputs?.length - 1;
              }
            } catch (error2) {
            }
          }
          if (toSlot != null || toSlot !== -1) {
            fromNode.connect(fromSlot, node2, toSlot);
          }
        } else {
          const widget = node2.widgets?.find((w2) => w2.name === input);
          if (widget) {
            widget.value = value;
            widget.callback?.(value);
          }
        }
      }
    }
    app$1.graph.arrange();
    useWorkflowService().afterLoadNewGraph(
      fileName,
      this.graph.serialize()
    );
  }
  /**
   * Registers a Comfy web extension with the app
   * @param {ComfyExtension} extension
   * @deprecated Use useExtensionService().registerExtension instead
   */
  registerExtension(extension) {
    useExtensionService().registerExtension(extension);
  }
  /**
   * Refresh combo list on whole nodes
   */
  async refreshComboInNodes() {
    const requestToastMessage = {
      severity: "info",
      summary: t("g.update"),
      detail: t("toastMessages.updateRequested")
    };
    if (this.vueAppReady) {
      useToastStore().add(requestToastMessage);
    }
    const defs = await this.#getNodeDefs();
    for (const nodeId in defs) {
      this.registerNodeDef(nodeId, defs[nodeId]);
    }
    for (const node2 of this.graph.nodes) {
      const def = defs[node2.type];
      node2.refreshComboInNode?.(defs);
      if (!def?.input) continue;
      if (node2.widgets) {
        const nodeInputs = def.input;
        for (const widget of node2.widgets) {
          if (widget.type === "combo") {
            let inputType;
            if (nodeInputs.required?.[widget.name] !== void 0) {
              inputType = "required";
            } else if (nodeInputs.optional?.[widget.name] !== void 0) {
              inputType = "optional";
            }
            if (inputType !== void 0) {
              const inputSpec = nodeInputs[inputType]?.[widget.name];
              if (inputSpec) {
                if (isComboInputSpecV2(inputSpec)) {
                  widget.options.values = inputSpec[1]?.options;
                } else if (isComboInputSpecV1(inputSpec)) {
                  widget.options.values = inputSpec[0];
                }
              }
            }
          }
        }
      }
    }
    await useExtensionService().invokeExtensionsAsync(
      "refreshComboInNodes",
      defs
    );
    if (this.vueAppReady) {
      this.updateVueAppNodeDefs(defs);
      useToastStore().remove(requestToastMessage);
      useToastStore().add({
        severity: "success",
        summary: t("g.updated"),
        detail: t("toastMessages.nodeDefinitionsUpdated"),
        life: 1e3
      });
    }
  }
  /**
   * Frees memory allocated to image preview blobs for a specific node, by revoking the URLs associated with them.
   * @param nodeId ID of the node to revoke all preview images of
   */
  revokePreviews(nodeId) {
    if (!this.nodePreviewImages[nodeId]?.[Symbol.iterator]) return;
    for (const url of this.nodePreviewImages[nodeId]) {
      URL.revokeObjectURL(url);
    }
  }
  /**
   * Clean current state
   */
  clean() {
    this.nodeOutputs = {};
    for (const id2 of Object.keys(this.nodePreviewImages)) {
      this.revokePreviews(id2);
    }
    this.nodePreviewImages = {};
    const executionStore = useExecutionStore();
    executionStore.lastNodeErrors = null;
    executionStore.lastExecutionError = null;
  }
  clientPosToCanvasPos(pos) {
    if (!this.#positionConversion) {
      throw new Error("clientPosToCanvasPos called before setup");
    }
    return this.#positionConversion.clientPosToCanvasPos(pos);
  }
  canvasPosToClientPos(pos) {
    if (!this.#positionConversion) {
      throw new Error("canvasPosToClientPos called before setup");
    }
    return this.#positionConversion.canvasPosToClientPos(pos);
  }
}
const app$1 = new ComfyApp();
window.comfyAPI = window.comfyAPI || {};
window.comfyAPI.app = window.comfyAPI.app || {};
window.comfyAPI.app.ANIM_PREVIEW_WIDGET = ANIM_PREVIEW_WIDGET;
window.comfyAPI.app.ComfyApp = ComfyApp;
window.comfyAPI.app.app = app$1;
const useColorPaletteService = /* @__PURE__ */ __name(() => {
  const colorPaletteStore = useColorPaletteStore();
  const settingStore = useSettingStore();
  const nodeDefStore = useNodeDefStore();
  const { wrapWithErrorHandling, wrapWithErrorHandlingAsync } = useErrorHandling();
  const validateColorPalette = /* @__PURE__ */ __name((data) => {
    const result = paletteSchema.safeParse(data);
    if (result.success) return result.data;
    const error2 = fromZodError(result.error);
    throw new Error(`Invalid color palette against zod schema:
${error2}`);
  }, "validateColorPalette");
  const persistCustomColorPalettes = /* @__PURE__ */ __name(async () => {
    await settingStore.set(
      "Comfy.CustomColorPalettes",
      colorPaletteStore.customPalettes
    );
  }, "persistCustomColorPalettes");
  const deleteCustomColorPalette = /* @__PURE__ */ __name(async (colorPaletteId) => {
    colorPaletteStore.deleteCustomPalette(colorPaletteId);
    await persistCustomColorPalettes();
  }, "deleteCustomColorPalette");
  const addCustomColorPalette = /* @__PURE__ */ __name(async (colorPalette) => {
    validateColorPalette(colorPalette);
    colorPaletteStore.addCustomPalette(colorPalette);
    await persistCustomColorPalettes();
  }, "addCustomColorPalette");
  const loadLinkColorPalette = /* @__PURE__ */ __name((linkColorPalette) => {
    const types = Object.fromEntries(
      Array.from(nodeDefStore.nodeDataTypes).map((type) => [type, ""])
    );
    Object.assign(
      app$1.canvas.default_connection_color_byType,
      types,
      linkColorPalette
    );
    Object.assign(LGraphCanvas.link_type_colors, types, linkColorPalette);
  }, "loadLinkColorPalette");
  const loadLiteGraphColorPalette = /* @__PURE__ */ __name((palette) => {
    app$1.bypassBgColor = palette.NODE_BYPASS_BGCOLOR;
    app$1.canvas.node_title_color = palette.NODE_TITLE_COLOR;
    app$1.canvas.default_link_color = palette.LINK_COLOR;
    app$1.canvas.background_image = palette.BACKGROUND_IMAGE;
    app$1.canvas.clear_background_color = palette.CLEAR_BACKGROUND_COLOR;
    app$1.canvas._pattern = void 0;
    for (const [key, value] of Object.entries(palette)) {
      if (Object.prototype.hasOwnProperty.call(LiteGraph, key)) {
        if (key === "NODE_DEFAULT_SHAPE" && typeof value === "string") {
          console.warn(
            `litegraph_base.NODE_DEFAULT_SHAPE only accepts [${[
              LiteGraph.BOX_SHAPE,
              LiteGraph.ROUND_SHAPE,
              LiteGraph.CARD_SHAPE
            ].join(", ")}] but got ${value}`
          );
          LiteGraph.NODE_DEFAULT_SHAPE = LiteGraph.ROUND_SHAPE;
        } else {
          ;
          LiteGraph[key] = value;
        }
      }
    }
  }, "loadLiteGraphColorPalette");
  const loadComfyColorPalette = /* @__PURE__ */ __name((comfyColorPalette) => {
    if (comfyColorPalette) {
      const rootStyle = document.documentElement.style;
      for (const [key, value] of Object.entries(comfyColorPalette)) {
        rootStyle.setProperty("--" + key, value);
      }
    }
  }, "loadComfyColorPalette");
  const loadColorPalette = /* @__PURE__ */ __name(async (colorPaletteId) => {
    const colorPalette = colorPaletteStore.palettesLookup[colorPaletteId];
    if (!colorPalette) {
      throw new Error(`Color palette ${colorPaletteId} not found`);
    }
    const completedPalette = colorPaletteStore.completePalette(colorPalette);
    loadLinkColorPalette(completedPalette.colors.node_slot);
    loadLiteGraphColorPalette(completedPalette.colors.litegraph_base);
    loadComfyColorPalette(completedPalette.colors.comfy_base);
    app$1.canvas.setDirty(true, true);
    colorPaletteStore.activePaletteId = colorPaletteId;
  }, "loadColorPalette");
  const exportColorPalette = /* @__PURE__ */ __name((colorPaletteId) => {
    const colorPalette = colorPaletteStore.palettesLookup[colorPaletteId];
    if (!colorPalette) {
      throw new Error(`Color palette ${colorPaletteId} not found`);
    }
    downloadBlob(
      colorPalette.id + ".json",
      new Blob([JSON.stringify(toRaw(colorPalette), null, 2)], {
        type: "application/json"
      })
    );
  }, "exportColorPalette");
  const importColorPalette = /* @__PURE__ */ __name(async () => {
    const file = await uploadFile("application/json");
    const text2 = await file.text();
    const palette = JSON.parse(text2);
    await addCustomColorPalette(palette);
    return palette;
  }, "importColorPalette");
  return {
    getActiveColorPalette: /* @__PURE__ */ __name(() => colorPaletteStore.completedActivePalette, "getActiveColorPalette"),
    addCustomColorPalette: wrapWithErrorHandlingAsync(addCustomColorPalette),
    deleteCustomColorPalette: wrapWithErrorHandlingAsync(
      deleteCustomColorPalette
    ),
    loadColorPalette: wrapWithErrorHandlingAsync(loadColorPalette),
    exportColorPalette: wrapWithErrorHandling(exportColorPalette),
    importColorPalette: wrapWithErrorHandlingAsync(importColorPalette)
  };
}, "useColorPaletteService");
var TaskItemDisplayStatus = /* @__PURE__ */ ((TaskItemDisplayStatus2) => {
  TaskItemDisplayStatus2["Running"] = "Running";
  TaskItemDisplayStatus2["Pending"] = "Pending";
  TaskItemDisplayStatus2["Completed"] = "Completed";
  TaskItemDisplayStatus2["Failed"] = "Failed";
  TaskItemDisplayStatus2["Cancelled"] = "Cancelled";
  return TaskItemDisplayStatus2;
})(TaskItemDisplayStatus || {});
class ResultItemImpl {
  static {
    __name(this, "ResultItemImpl");
  }
  filename;
  subfolder;
  type;
  nodeId;
  // 'audio' | 'images' | ...
  mediaType;
  // VHS output specific fields
  format;
  frame_rate;
  constructor(obj) {
    this.filename = obj.filename ?? "";
    this.subfolder = obj.subfolder ?? "";
    this.type = obj.type ?? "";
    this.nodeId = obj.nodeId;
    this.mediaType = obj.mediaType;
    this.format = obj.format;
    this.frame_rate = obj.frame_rate;
  }
  get urlParams() {
    const params = new URLSearchParams();
    params.set("filename", this.filename);
    params.set("type", this.type);
    params.set("subfolder", this.subfolder);
    if (this.format) {
      params.set("format", this.format);
    }
    if (this.frame_rate) {
      params.set("frame_rate", this.frame_rate.toString());
    }
    return params;
  }
  /**
   * VHS advanced preview URL. `/viewvideo` endpoint is provided by VHS node.
   *
   * `/viewvideo` always returns a webm file.
   */
  get vhsAdvancedPreviewUrl() {
    return api.apiURL("/viewvideo?" + this.urlParams);
  }
  get url() {
    return api.apiURL("/view?" + this.urlParams);
  }
  get urlWithTimestamp() {
    return `${this.url}&t=${+/* @__PURE__ */ new Date()}`;
  }
  get isVhsFormat() {
    return !!this.format && !!this.frame_rate;
  }
  get htmlVideoType() {
    if (this.isWebm) {
      return "video/webm";
    }
    if (this.isMp4) {
      return "video/mp4";
    }
    if (this.isVhsFormat) {
      if (this.format?.endsWith("webm")) {
        return "video/webm";
      }
      if (this.format?.endsWith("mp4")) {
        return "video/mp4";
      }
    }
    return void 0;
  }
  get isGif() {
    return this.filename.endsWith(".gif");
  }
  get isWebp() {
    return this.filename.endsWith(".webp");
  }
  get isWebm() {
    return this.filename.endsWith(".webm");
  }
  get isMp4() {
    return this.filename.endsWith(".mp4");
  }
  get isVideoBySuffix() {
    return this.isWebm || this.isMp4;
  }
  get isImageBySuffix() {
    return this.isGif || this.isWebp;
  }
  get isVideo() {
    const isVideoByType = this.mediaType === "video" || !!this.format?.startsWith("video/");
    return this.isVideoBySuffix || isVideoByType && !this.isImageBySuffix;
  }
  get isImage() {
    return this.isImageBySuffix || this.mediaType === "images" && !this.isVideoBySuffix;
  }
  get supportsPreview() {
    return this.isImage || this.isVideo;
  }
}
class TaskItemImpl {
  static {
    __name(this, "TaskItemImpl");
  }
  taskType;
  prompt;
  status;
  outputs;
  flatOutputs;
  constructor(taskType, prompt, status, outputs, flatOutputs) {
    this.taskType = taskType;
    this.prompt = prompt;
    this.status = status;
    this.outputs = _.mapValues(
      outputs ?? {},
      (nodeOutputs) => _.omit(nodeOutputs, "animated")
    );
    this.flatOutputs = flatOutputs ?? this.calculateFlatOutputs();
  }
  calculateFlatOutputs() {
    if (!this.outputs) {
      return [];
    }
    return Object.entries(this.outputs).flatMap(
      ([nodeId, nodeOutputs]) => Object.entries(nodeOutputs).flatMap(
        ([mediaType, items]) => items.map(
          (item) => new ResultItemImpl({
            ...item,
            nodeId,
            mediaType
          })
        )
      )
    );
  }
  get previewOutput() {
    return this.flatOutputs.find(
      // Prefer saved media files over the temp previews
      (output) => output.type === "output" && output.supportsPreview
    ) ?? this.flatOutputs.find((output) => output.supportsPreview);
  }
  get apiTaskType() {
    switch (this.taskType) {
      case "Running":
      case "Pending":
        return "queue";
      case "History":
        return "history";
    }
  }
  get key() {
    return this.promptId + this.displayStatus;
  }
  get queueIndex() {
    return this.prompt[0];
  }
  get promptId() {
    return this.prompt[1];
  }
  get promptInputs() {
    return this.prompt[2];
  }
  get extraData() {
    return this.prompt[3];
  }
  get outputsToExecute() {
    return this.prompt[4];
  }
  get extraPngInfo() {
    return this.extraData.extra_pnginfo;
  }
  get clientId() {
    return this.extraData.client_id;
  }
  get workflow() {
    return this.extraPngInfo?.workflow;
  }
  get messages() {
    return this.status?.messages || [];
  }
  get interrupted() {
    return _.some(
      this.messages,
      (message) => message[0] === "execution_interrupted"
    );
  }
  get isHistory() {
    return this.taskType === "History";
  }
  get isRunning() {
    return this.taskType === "Running";
  }
  get displayStatus() {
    switch (this.taskType) {
      case "Running":
        return "Running";
      case "Pending":
        return "Pending";
      case "History":
        if (this.interrupted) return "Cancelled";
        switch (this.status.status_str) {
          case "success":
            return "Completed";
          case "error":
            return "Failed";
        }
    }
  }
  get executionStartTimestamp() {
    const message = this.messages.find(
      (message2) => message2[0] === "execution_start"
    );
    return message ? message[1].timestamp : void 0;
  }
  get executionEndTimestamp() {
    const messages2 = this.messages.filter(
      (message) => [
        "execution_success",
        "execution_interrupted",
        "execution_error"
      ].includes(message[0])
    );
    if (!messages2.length) {
      return void 0;
    }
    return _.max(messages2.map((message) => message[1].timestamp));
  }
  get executionTime() {
    if (!this.executionStartTimestamp || !this.executionEndTimestamp) {
      return void 0;
    }
    return this.executionEndTimestamp - this.executionStartTimestamp;
  }
  get executionTimeInSeconds() {
    return this.executionTime !== void 0 ? this.executionTime / 1e3 : void 0;
  }
  async loadWorkflow(app2) {
    if (!this.workflow) {
      return;
    }
    await app2.loadGraphData(toRaw(this.workflow));
    if (this.outputs) {
      app2.nodeOutputs = toRaw(this.outputs);
    }
  }
  flatten() {
    if (this.displayStatus !== "Completed") {
      return [this];
    }
    return this.flatOutputs.map(
      (output, i2) => new TaskItemImpl(
        this.taskType,
        [
          this.queueIndex,
          `${this.promptId}-${i2}`,
          this.promptInputs,
          this.extraData,
          this.outputsToExecute
        ],
        this.status,
        {
          [output.nodeId]: {
            [output.mediaType]: [output]
          }
        },
        [output]
      )
    );
  }
}
const useQueueStore = /* @__PURE__ */ defineStore("queue", () => {
  const runningTasks = ref$3([]);
  const pendingTasks = ref$3([]);
  const historyTasks = ref$3([]);
  const maxHistoryItems = ref$3(64);
  const isLoading = ref$3(false);
  const tasks = computed(
    () => [
      ...pendingTasks.value,
      ...runningTasks.value,
      ...historyTasks.value
    ]
  );
  const flatTasks = computed(
    () => tasks.value.flatMap((task) => task.flatten())
  );
  const lastHistoryQueueIndex = computed(
    () => historyTasks.value.length ? historyTasks.value[0].queueIndex : -1
  );
  const hasPendingTasks = computed(() => pendingTasks.value.length > 0);
  const update2 = /* @__PURE__ */ __name(async () => {
    isLoading.value = true;
    try {
      const [queue, history2] = await Promise.all([
        api.getQueue(),
        api.getHistory(maxHistoryItems.value)
      ]);
      const toClassAll = /* @__PURE__ */ __name((tasks2) => tasks2.map(
        (task) => new TaskItemImpl(
          task.taskType,
          task.prompt,
          // status and outputs only exist on history tasks
          "status" in task ? task.status : void 0,
          "outputs" in task ? task.outputs : void 0
        )
      ).sort((a2, b2) => b2.queueIndex - a2.queueIndex), "toClassAll");
      runningTasks.value = toClassAll(queue.Running);
      pendingTasks.value = toClassAll(queue.Pending);
      const allIndex = new Set(
        history2.History.map((item) => item.prompt[0])
      );
      const newHistoryItems = toClassAll(
        history2.History.filter(
          (item) => item.prompt[0] > lastHistoryQueueIndex.value
        )
      );
      const existingHistoryItems = historyTasks.value.filter(
        (item) => allIndex.has(item.queueIndex)
      );
      historyTasks.value = [...newHistoryItems, ...existingHistoryItems].slice(0, maxHistoryItems.value).sort((a2, b2) => b2.queueIndex - a2.queueIndex);
    } finally {
      isLoading.value = false;
    }
  }, "update");
  const clear = /* @__PURE__ */ __name(async (targets = ["queue", "history"]) => {
    if (targets.length === 0) {
      return;
    }
    await Promise.all(targets.map((type) => api.clearItems(type)));
    await update2();
  }, "clear");
  const deleteTask = /* @__PURE__ */ __name(async (task) => {
    await api.deleteItem(task.apiTaskType, task.promptId);
    await update2();
  }, "deleteTask");
  return {
    runningTasks,
    pendingTasks,
    historyTasks,
    maxHistoryItems,
    isLoading,
    tasks,
    flatTasks,
    lastHistoryQueueIndex,
    hasPendingTasks,
    update: update2,
    clear,
    delete: deleteTask
  };
});
const useQueuePendingTaskCountStore = /* @__PURE__ */ defineStore(
  "queuePendingTaskCount",
  {
    state: /* @__PURE__ */ __name(() => ({
      count: 0
    }), "state"),
    actions: {
      update(e2) {
        this.count = e2.detail?.exec_info?.queue_remaining || 0;
      }
    }
  }
);
const useQueueSettingsStore = /* @__PURE__ */ defineStore("queueSettingsStore", {
  state: /* @__PURE__ */ __name(() => ({
    mode: "disabled",
    batchCount: 1
  }), "state")
});
function _arrayWithHoles(r2) {
  if (Array.isArray(r2)) return r2;
}
__name(_arrayWithHoles, "_arrayWithHoles");
function _iterableToArrayLimit(r2, l2) {
  var t2 = null == r2 ? null : "undefined" != typeof Symbol && r2[Symbol.iterator] || r2["@@iterator"];
  if (null != t2) {
    var e2, n2, i2, u2, a2 = [], f2 = true, o2 = false;
    try {
      if (i2 = (t2 = t2.call(r2)).next, 0 === l2) {
        if (Object(t2) !== t2) return;
        f2 = false;
      } else for (; !(f2 = (e2 = i2.call(t2)).done) && (a2.push(e2.value), a2.length !== l2); f2 = true) ;
    } catch (r3) {
      o2 = true, n2 = r3;
    } finally {
      try {
        if (!f2 && null != t2["return"] && (u2 = t2["return"](), Object(u2) !== u2)) return;
      } finally {
        if (o2) throw n2;
      }
    }
    return a2;
  }
}
__name(_iterableToArrayLimit, "_iterableToArrayLimit");
function _arrayLikeToArray$2(r2, a2) {
  (null == a2 || a2 > r2.length) && (a2 = r2.length);
  for (var e2 = 0, n2 = Array(a2); e2 < a2; e2++) n2[e2] = r2[e2];
  return n2;
}
__name(_arrayLikeToArray$2, "_arrayLikeToArray$2");
function _unsupportedIterableToArray$2(r2, a2) {
  if (r2) {
    if ("string" == typeof r2) return _arrayLikeToArray$2(r2, a2);
    var t2 = {}.toString.call(r2).slice(8, -1);
    return "Object" === t2 && r2.constructor && (t2 = r2.constructor.name), "Map" === t2 || "Set" === t2 ? Array.from(r2) : "Arguments" === t2 || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t2) ? _arrayLikeToArray$2(r2, a2) : void 0;
  }
}
__name(_unsupportedIterableToArray$2, "_unsupportedIterableToArray$2");
function _nonIterableRest() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
__name(_nonIterableRest, "_nonIterableRest");
function _slicedToArray(r2, e2) {
  return _arrayWithHoles(r2) || _iterableToArrayLimit(r2, e2) || _unsupportedIterableToArray$2(r2, e2) || _nonIterableRest();
}
__name(_slicedToArray, "_slicedToArray");
var dist = {};
var bind$1 = {};
"use strict";
Object.defineProperty(bind$1, "__esModule", { value: true });
var bind_2 = bind$1.bind = void 0;
function bind(target, _a2) {
  var type = _a2.type, listener = _a2.listener, options2 = _a2.options;
  target.addEventListener(type, listener, options2);
  return /* @__PURE__ */ __name(function unbind() {
    target.removeEventListener(type, listener, options2);
  }, "unbind");
}
__name(bind, "bind");
bind_2 = bind$1.bind = bind;
var bindAll$1 = {};
"use strict";
var __assign = commonjsGlobal && commonjsGlobal.__assign || function() {
  __assign = Object.assign || function(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);
};
Object.defineProperty(bindAll$1, "__esModule", { value: true });
var bindAll_2 = bindAll$1.bindAll = void 0;
var bind_1 = bind$1;
function toOptions(value) {
  if (typeof value === "undefined") {
    return void 0;
  }
  if (typeof value === "boolean") {
    return {
      capture: value
    };
  }
  return value;
}
__name(toOptions, "toOptions");
function getBinding(original, sharedOptions) {
  if (sharedOptions == null) {
    return original;
  }
  var binding = __assign(__assign({}, original), { options: __assign(__assign({}, toOptions(sharedOptions)), toOptions(original.options)) });
  return binding;
}
__name(getBinding, "getBinding");
function bindAll(target, bindings, sharedOptions) {
  var unbinds = bindings.map(function(original) {
    var binding = getBinding(original, sharedOptions);
    return (0, bind_1.bind)(target, binding);
  });
  return /* @__PURE__ */ __name(function unbindAll() {
    unbinds.forEach(function(unbind) {
      return unbind();
    });
  }, "unbindAll");
}
__name(bindAll, "bindAll");
bindAll_2 = bindAll$1.bindAll = bindAll;
(function(exports) {
  "use strict";
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.bindAll = exports.bind = void 0;
  var bind_12 = bind$1;
  Object.defineProperty(exports, "bind", { enumerable: true, get: /* @__PURE__ */ __name(function() {
    return bind_12.bind;
  }, "get") });
  var bind_all_1 = bindAll$1;
  Object.defineProperty(exports, "bindAll", { enumerable: true, get: /* @__PURE__ */ __name(function() {
    return bind_all_1.bindAll;
  }, "get") });
})(dist);
const index = /* @__PURE__ */ getDefaultExportFromCjs(dist);
var honeyPotDataAttribute = "data-pdnd-honey-pot";
function isHoneyPotElement(target) {
  return target instanceof Element && target.hasAttribute(honeyPotDataAttribute);
}
__name(isHoneyPotElement, "isHoneyPotElement");
function getElementFromPointWithoutHoneypot(client) {
  var _document$elementsFro = document.elementsFromPoint(client.x, client.y), _document$elementsFro2 = _slicedToArray(_document$elementsFro, 2), top = _document$elementsFro2[0], second = _document$elementsFro2[1];
  if (!top) {
    return null;
  }
  if (isHoneyPotElement(top)) {
    return second !== null && second !== void 0 ? second : null;
  }
  return top;
}
__name(getElementFromPointWithoutHoneypot, "getElementFromPointWithoutHoneypot");
function _typeof(o2) {
  "@babel/helpers - typeof";
  return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o3) {
    return typeof o3;
  } : function(o3) {
    return o3 && "function" == typeof Symbol && o3.constructor === Symbol && o3 !== Symbol.prototype ? "symbol" : typeof o3;
  }, _typeof(o2);
}
__name(_typeof, "_typeof");
function toPrimitive(t2, r2) {
  if ("object" != _typeof(t2) || !t2) return t2;
  var e2 = t2[Symbol.toPrimitive];
  if (void 0 !== e2) {
    var i2 = e2.call(t2, r2 || "default");
    if ("object" != _typeof(i2)) return i2;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return ("string" === r2 ? String : Number)(t2);
}
__name(toPrimitive, "toPrimitive");
function toPropertyKey(t2) {
  var i2 = toPrimitive(t2, "string");
  return "symbol" == _typeof(i2) ? i2 : i2 + "";
}
__name(toPropertyKey, "toPropertyKey");
function _defineProperty(e2, r2, t2) {
  return (r2 = toPropertyKey(r2)) in e2 ? Object.defineProperty(e2, r2, {
    value: t2,
    enumerable: true,
    configurable: true,
    writable: true
  }) : e2[r2] = t2, e2;
}
__name(_defineProperty, "_defineProperty");
var maxZIndex = 2147483647;
function ownKeys$2(e2, r2) {
  var t2 = Object.keys(e2);
  if (Object.getOwnPropertySymbols) {
    var o2 = Object.getOwnPropertySymbols(e2);
    r2 && (o2 = o2.filter(function(r3) {
      return Object.getOwnPropertyDescriptor(e2, r3).enumerable;
    })), t2.push.apply(t2, o2);
  }
  return t2;
}
__name(ownKeys$2, "ownKeys$2");
function _objectSpread$2(e2) {
  for (var r2 = 1; r2 < arguments.length; r2++) {
    var t2 = null != arguments[r2] ? arguments[r2] : {};
    r2 % 2 ? ownKeys$2(Object(t2), true).forEach(function(r3) {
      _defineProperty(e2, r3, t2[r3]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e2, Object.getOwnPropertyDescriptors(t2)) : ownKeys$2(Object(t2)).forEach(function(r3) {
      Object.defineProperty(e2, r3, Object.getOwnPropertyDescriptor(t2, r3));
    });
  }
  return e2;
}
__name(_objectSpread$2, "_objectSpread$2");
var honeyPotSize = 2;
var halfHoneyPotSize = honeyPotSize / 2;
function floorToClosestPixel(point) {
  return {
    x: Math.floor(point.x),
    y: Math.floor(point.y)
  };
}
__name(floorToClosestPixel, "floorToClosestPixel");
function pullBackByHalfHoneyPotSize(point) {
  return {
    x: point.x - halfHoneyPotSize,
    y: point.y - halfHoneyPotSize
  };
}
__name(pullBackByHalfHoneyPotSize, "pullBackByHalfHoneyPotSize");
function preventGoingBackwardsOffScreen(point) {
  return {
    x: Math.max(point.x, 0),
    y: Math.max(point.y, 0)
  };
}
__name(preventGoingBackwardsOffScreen, "preventGoingBackwardsOffScreen");
function preventGoingForwardsOffScreen(point) {
  return {
    x: Math.min(point.x, window.innerWidth - honeyPotSize),
    y: Math.min(point.y, window.innerHeight - honeyPotSize)
  };
}
__name(preventGoingForwardsOffScreen, "preventGoingForwardsOffScreen");
function getHoneyPotRectFor(_ref) {
  var client = _ref.client;
  var point = preventGoingForwardsOffScreen(preventGoingBackwardsOffScreen(pullBackByHalfHoneyPotSize(floorToClosestPixel(client))));
  return DOMRect.fromRect({
    x: point.x,
    y: point.y,
    width: honeyPotSize,
    height: honeyPotSize
  });
}
__name(getHoneyPotRectFor, "getHoneyPotRectFor");
function getRectStyles(_ref2) {
  var clientRect2 = _ref2.clientRect;
  return {
    left: "".concat(clientRect2.left, "px"),
    top: "".concat(clientRect2.top, "px"),
    width: "".concat(clientRect2.width, "px"),
    height: "".concat(clientRect2.height, "px")
  };
}
__name(getRectStyles, "getRectStyles");
function isWithin(_ref3) {
  var client = _ref3.client, clientRect2 = _ref3.clientRect;
  return (
    // is within horizontal bounds
    client.x >= clientRect2.x && client.x <= clientRect2.x + clientRect2.width && // is within vertical bounds
    client.y >= clientRect2.y && client.y <= clientRect2.y + clientRect2.height
  );
}
__name(isWithin, "isWithin");
function mountHoneyPot(_ref4) {
  var initial = _ref4.initial;
  var element = document.createElement("div");
  element.setAttribute(honeyPotDataAttribute, "true");
  var clientRect2 = getHoneyPotRectFor({
    client: initial
  });
  Object.assign(element.style, _objectSpread$2(_objectSpread$2({
    // Setting a background color explicitly to avoid any inherited styles.
    // Looks like this could be `opacity: 0`, but worried that _might_
    // cause the element to be ignored on some platforms.
    // When debugging, set backgroundColor to something like "red".
    backgroundColor: "transparent",
    position: "fixed",
    // Being explicit to avoid inheriting styles
    padding: 0,
    margin: 0,
    boxSizing: "border-box"
  }, getRectStyles({
    clientRect: clientRect2
  })), {}, {
    // We want this element to absorb pointer events,
    // it's kind of the whole point 😉
    pointerEvents: "auto",
    // Want to make sure the honey pot is top of everything else.
    // Don't need to worry about native drag previews, as they will
    // have been rendered (and removed) before the honey pot is rendered
    zIndex: maxZIndex
  }));
  document.body.appendChild(element);
  var unbindPointerMove = dist.bind(window, {
    type: "pointermove",
    listener: /* @__PURE__ */ __name(function listener(event) {
      var client = {
        x: event.clientX,
        y: event.clientY
      };
      clientRect2 = getHoneyPotRectFor({
        client
      });
      Object.assign(element.style, getRectStyles({
        clientRect: clientRect2
      }));
    }, "listener"),
    // using capture so we are less likely to be impacted by event stopping
    options: {
      capture: true
    }
  });
  return /* @__PURE__ */ __name(function finish(_ref5) {
    var current = _ref5.current;
    unbindPointerMove();
    if (isWithin({
      client: current,
      clientRect: clientRect2
    })) {
      element.remove();
      return;
    }
    function cleanup() {
      unbindPostDragEvents();
      element.remove();
    }
    __name(cleanup, "cleanup");
    var unbindPostDragEvents = dist.bindAll(window, [
      {
        type: "pointerdown",
        listener: cleanup
      },
      {
        type: "pointermove",
        listener: cleanup
      },
      {
        type: "focusin",
        listener: cleanup
      },
      {
        type: "focusout",
        listener: cleanup
      },
      // a 'pointerdown' should happen before 'dragstart', but just being super safe
      {
        type: "dragstart",
        listener: cleanup
      },
      // if the user has dragged something out of the window
      // and then is dragging something back into the window
      // the first events we will see are "dragenter" (and then "dragover").
      // So if we see any of these we need to clear the post drag fix.
      {
        type: "dragenter",
        listener: cleanup
      },
      {
        type: "dragover",
        listener: cleanup
      }
      // Not adding a "wheel" event listener, as "wheel" by itself does not
      // resolve the bug.
    ], {
      // Using `capture` so less likely to be impacted by other code stopping events
      capture: true
    });
  }, "finish");
}
__name(mountHoneyPot, "mountHoneyPot");
function makeHoneyPotFix() {
  var latestPointerMove = null;
  function bindEvents() {
    latestPointerMove = null;
    return dist.bind(window, {
      type: "pointermove",
      listener: /* @__PURE__ */ __name(function listener(event) {
        latestPointerMove = {
          x: event.clientX,
          y: event.clientY
        };
      }, "listener"),
      // listening for pointer move in capture phase
      // so we are less likely to be impacted by events being stopped.
      options: {
        capture: true
      }
    });
  }
  __name(bindEvents, "bindEvents");
  function getOnPostDispatch() {
    var finish = null;
    return /* @__PURE__ */ __name(function onPostEvent(_ref6) {
      var eventName = _ref6.eventName, payload = _ref6.payload;
      if (eventName === "onDragStart") {
        var _latestPointerMove;
        var input = payload.location.initial.input;
        var initial = (_latestPointerMove = latestPointerMove) !== null && _latestPointerMove !== void 0 ? _latestPointerMove : {
          x: input.clientX,
          y: input.clientY
        };
        finish = mountHoneyPot({
          initial
        });
      }
      if (eventName === "onDrop") {
        var _finish;
        var _input = payload.location.current.input;
        (_finish = finish) === null || _finish === void 0 || _finish({
          current: {
            x: _input.clientX,
            y: _input.clientY
          }
        });
        finish = null;
        latestPointerMove = null;
      }
    }, "onPostEvent");
  }
  __name(getOnPostDispatch, "getOnPostDispatch");
  return {
    bindEvents,
    getOnPostDispatch
  };
}
__name(makeHoneyPotFix, "makeHoneyPotFix");
function _arrayWithoutHoles(r2) {
  if (Array.isArray(r2)) return _arrayLikeToArray$2(r2);
}
__name(_arrayWithoutHoles, "_arrayWithoutHoles");
function _iterableToArray(r2) {
  if ("undefined" != typeof Symbol && null != r2[Symbol.iterator] || null != r2["@@iterator"]) return Array.from(r2);
}
__name(_iterableToArray, "_iterableToArray");
function _nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
__name(_nonIterableSpread, "_nonIterableSpread");
function _toConsumableArray(r2) {
  return _arrayWithoutHoles(r2) || _iterableToArray(r2) || _unsupportedIterableToArray$2(r2) || _nonIterableSpread();
}
__name(_toConsumableArray, "_toConsumableArray");
function once(fn) {
  var cache = null;
  return /* @__PURE__ */ __name(function wrapped() {
    if (!cache) {
      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }
      var result = fn.apply(this, args);
      cache = {
        result
      };
    }
    return cache.result;
  }, "wrapped");
}
__name(once, "once");
var isFirefox = once(/* @__PURE__ */ __name(function isFirefox2() {
  if (false) {
    return false;
  }
  return navigator.userAgent.includes("Firefox");
}, "isFirefox2"));
var isSafari = once(/* @__PURE__ */ __name(function isSafari2() {
  if (false) {
    return false;
  }
  var _navigator2 = navigator, userAgent = _navigator2.userAgent;
  return userAgent.includes("AppleWebKit") && !userAgent.includes("Chrome");
}, "isSafari2"));
var symbols = {
  isLeavingWindow: Symbol("leaving"),
  isEnteringWindow: Symbol("entering")
};
function isEnteringWindowInSafari(_ref) {
  var dragEnter = _ref.dragEnter;
  if (!isSafari()) {
    return false;
  }
  return dragEnter.hasOwnProperty(symbols.isEnteringWindow);
}
__name(isEnteringWindowInSafari, "isEnteringWindowInSafari");
function isLeavingWindowInSafari(_ref2) {
  var dragLeave = _ref2.dragLeave;
  if (!isSafari()) {
    return false;
  }
  return dragLeave.hasOwnProperty(symbols.isLeavingWindow);
}
__name(isLeavingWindowInSafari, "isLeavingWindowInSafari");
(/* @__PURE__ */ __name(function fixSafari() {
  if (typeof window === "undefined") {
    return;
  }
  if (false) {
    return;
  }
  if (!isSafari()) {
    return;
  }
  function getInitialState() {
    return {
      enterCount: 0,
      isOverWindow: false
    };
  }
  __name(getInitialState, "getInitialState");
  var state = getInitialState();
  function resetState() {
    state = getInitialState();
  }
  __name(resetState, "resetState");
  dist.bindAll(
    window,
    [{
      type: "dragstart",
      listener: /* @__PURE__ */ __name(function listener() {
        state.enterCount = 0;
        state.isOverWindow = true;
      }, "listener")
    }, {
      type: "drop",
      listener: resetState
    }, {
      type: "dragend",
      listener: resetState
    }, {
      type: "dragenter",
      listener: /* @__PURE__ */ __name(function listener(event) {
        if (!state.isOverWindow && state.enterCount === 0) {
          event[symbols.isEnteringWindow] = true;
        }
        state.isOverWindow = true;
        state.enterCount++;
      }, "listener")
    }, {
      type: "dragleave",
      listener: /* @__PURE__ */ __name(function listener(event) {
        state.enterCount--;
        if (state.isOverWindow && state.enterCount === 0) {
          event[symbols.isLeavingWindow] = true;
          state.isOverWindow = false;
        }
      }, "listener")
    }],
    // using `capture: true` so that adding event listeners
    // in bubble phase will have the correct symbols
    {
      capture: true
    }
  );
}, "fixSafari"))();
function isNodeLike(target) {
  return "nodeName" in target;
}
__name(isNodeLike, "isNodeLike");
function isFromAnotherWindow(eventTarget) {
  return isNodeLike(eventTarget) && eventTarget.ownerDocument !== document;
}
__name(isFromAnotherWindow, "isFromAnotherWindow");
function isLeavingWindow(_ref) {
  var dragLeave = _ref.dragLeave;
  var type = dragLeave.type, relatedTarget = dragLeave.relatedTarget;
  if (type !== "dragleave") {
    return false;
  }
  if (isSafari()) {
    return isLeavingWindowInSafari({
      dragLeave
    });
  }
  if (relatedTarget == null) {
    return true;
  }
  if (isFirefox()) {
    return isFromAnotherWindow(relatedTarget);
  }
  return relatedTarget instanceof HTMLIFrameElement;
}
__name(isLeavingWindow, "isLeavingWindow");
function getBindingsForBrokenDrags(_ref) {
  var onDragEnd = _ref.onDragEnd;
  return [
    // ## Detecting drag ending for removed draggables
    //
    // If a draggable element is removed during a drag and the user drops:
    // 1. if over a valid drop target: we get a "drop" event to know the drag is finished
    // 2. if not over a valid drop target (or cancelled): we get nothing
    // The "dragend" event will not fire on the source draggable if it has been
    // removed from the DOM.
    // So we need to figure out if a drag operation has finished by looking at other events
    // We can do this by looking at other events
    // ### First detection: "pointermove" events
    // 1. "pointermove" events cannot fire during a drag and drop operation
    // according to the spec. So if we get a "pointermove" it means that
    // the drag and drop operations has finished. So if we get a "pointermove"
    // we know that the drag is over
    // 2. 🦊😤 Drag and drop operations are _supposed_ to suppress
    // other pointer events. However, firefox will allow a few
    // pointer event to get through after a drag starts.
    // The most I've seen is 3
    {
      type: "pointermove",
      listener: /* @__PURE__ */ function() {
        var callCount = 0;
        return /* @__PURE__ */ __name(function listener() {
          if (callCount < 20) {
            callCount++;
            return;
          }
          onDragEnd();
        }, "listener");
      }()
    },
    // ### Second detection: "pointerdown" events
    // If we receive this event then we know that a drag operation has finished
    // and potentially another one is about to start.
    // Note: `pointerdown` fires on all browsers / platforms before "dragstart"
    {
      type: "pointerdown",
      listener: onDragEnd
    }
  ];
}
__name(getBindingsForBrokenDrags, "getBindingsForBrokenDrags");
function getInput(event) {
  return {
    altKey: event.altKey,
    button: event.button,
    buttons: event.buttons,
    ctrlKey: event.ctrlKey,
    metaKey: event.metaKey,
    shiftKey: event.shiftKey,
    clientX: event.clientX,
    clientY: event.clientY,
    pageX: event.pageX,
    pageY: event.pageY
  };
}
__name(getInput, "getInput");
var rafSchd = /* @__PURE__ */ __name(function rafSchd2(fn) {
  var lastArgs = [];
  var frameId = null;
  var wrapperFn = /* @__PURE__ */ __name(function wrapperFn2() {
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    lastArgs = args;
    if (frameId) {
      return;
    }
    frameId = requestAnimationFrame(function() {
      frameId = null;
      fn.apply(void 0, lastArgs);
    });
  }, "wrapperFn");
  wrapperFn.cancel = function() {
    if (!frameId) {
      return;
    }
    cancelAnimationFrame(frameId);
    frameId = null;
  };
  return wrapperFn;
}, "rafSchd");
var scheduleOnDrag = rafSchd(function(fn) {
  return fn();
});
var dragStart = /* @__PURE__ */ function() {
  var scheduled = null;
  function schedule(fn) {
    var frameId = requestAnimationFrame(function() {
      scheduled = null;
      fn();
    });
    scheduled = {
      frameId,
      fn
    };
  }
  __name(schedule, "schedule");
  function flush2() {
    if (scheduled) {
      cancelAnimationFrame(scheduled.frameId);
      scheduled.fn();
      scheduled = null;
    }
  }
  __name(flush2, "flush");
  return {
    schedule,
    flush: flush2
  };
}();
function makeDispatch(_ref) {
  var source = _ref.source, initial = _ref.initial, dispatchEvent2 = _ref.dispatchEvent;
  var previous = {
    dropTargets: []
  };
  function safeDispatch(args) {
    dispatchEvent2(args);
    previous = {
      dropTargets: args.payload.location.current.dropTargets
    };
  }
  __name(safeDispatch, "safeDispatch");
  var dispatch = {
    start: /* @__PURE__ */ __name(function start2(_ref2) {
      var nativeSetDragImage = _ref2.nativeSetDragImage;
      var location2 = {
        current: initial,
        previous,
        initial
      };
      safeDispatch({
        eventName: "onGenerateDragPreview",
        payload: {
          source,
          location: location2,
          nativeSetDragImage
        }
      });
      dragStart.schedule(function() {
        safeDispatch({
          eventName: "onDragStart",
          payload: {
            source,
            location: location2
          }
        });
      });
    }, "start"),
    dragUpdate: /* @__PURE__ */ __name(function dragUpdate(_ref3) {
      var current = _ref3.current;
      dragStart.flush();
      scheduleOnDrag.cancel();
      safeDispatch({
        eventName: "onDropTargetChange",
        payload: {
          source,
          location: {
            initial,
            previous,
            current
          }
        }
      });
    }, "dragUpdate"),
    drag: /* @__PURE__ */ __name(function drag(_ref4) {
      var current = _ref4.current;
      scheduleOnDrag(function() {
        dragStart.flush();
        var location2 = {
          initial,
          previous,
          current
        };
        safeDispatch({
          eventName: "onDrag",
          payload: {
            source,
            location: location2
          }
        });
      });
    }, "drag"),
    drop: /* @__PURE__ */ __name(function drop(_ref5) {
      var current = _ref5.current, updatedSourcePayload = _ref5.updatedSourcePayload;
      dragStart.flush();
      scheduleOnDrag.cancel();
      safeDispatch({
        eventName: "onDrop",
        payload: {
          source: updatedSourcePayload !== null && updatedSourcePayload !== void 0 ? updatedSourcePayload : source,
          location: {
            current,
            previous,
            initial
          }
        }
      });
    }, "drop")
  };
  return dispatch;
}
__name(makeDispatch, "makeDispatch");
var globalState = {
  isActive: false
};
function canStart() {
  return !globalState.isActive;
}
__name(canStart, "canStart");
function getNativeSetDragImage(event) {
  if (event.dataTransfer) {
    return event.dataTransfer.setDragImage.bind(event.dataTransfer);
  }
  return null;
}
__name(getNativeSetDragImage, "getNativeSetDragImage");
function hasHierarchyChanged(_ref) {
  var current = _ref.current, next = _ref.next;
  if (current.length !== next.length) {
    return true;
  }
  for (var i2 = 0; i2 < current.length; i2++) {
    if (current[i2].element !== next[i2].element) {
      return true;
    }
  }
  return false;
}
__name(hasHierarchyChanged, "hasHierarchyChanged");
function start(_ref2) {
  var event = _ref2.event, dragType = _ref2.dragType, getDropTargetsOver = _ref2.getDropTargetsOver, dispatchEvent2 = _ref2.dispatchEvent;
  if (!canStart()) {
    return;
  }
  var initial = getStartLocation({
    event,
    dragType,
    getDropTargetsOver
  });
  globalState.isActive = true;
  var state = {
    current: initial
  };
  setDropEffectOnEvent({
    event,
    current: initial.dropTargets
  });
  var dispatch = makeDispatch({
    source: dragType.payload,
    dispatchEvent: dispatchEvent2,
    initial
  });
  function updateState(next) {
    var hasChanged = hasHierarchyChanged({
      current: state.current.dropTargets,
      next: next.dropTargets
    });
    state.current = next;
    if (hasChanged) {
      dispatch.dragUpdate({
        current: state.current
      });
    }
  }
  __name(updateState, "updateState");
  function onUpdateEvent(event2) {
    var input = getInput(event2);
    var target = isHoneyPotElement(event2.target) ? getElementFromPointWithoutHoneypot({
      x: input.clientX,
      y: input.clientY
    }) : event2.target;
    var nextDropTargets = getDropTargetsOver({
      target,
      input,
      source: dragType.payload,
      current: state.current.dropTargets
    });
    if (nextDropTargets.length) {
      event2.preventDefault();
      setDropEffectOnEvent({
        event: event2,
        current: nextDropTargets
      });
    }
    updateState({
      dropTargets: nextDropTargets,
      input
    });
  }
  __name(onUpdateEvent, "onUpdateEvent");
  function cancel() {
    if (state.current.dropTargets.length) {
      updateState({
        dropTargets: [],
        input: state.current.input
      });
    }
    dispatch.drop({
      current: state.current,
      updatedSourcePayload: null
    });
    finish();
  }
  __name(cancel, "cancel");
  function finish() {
    globalState.isActive = false;
    unbindEvents();
  }
  __name(finish, "finish");
  var unbindEvents = dist.bindAll(
    window,
    [{
      // 👋 Note: we are repurposing the `dragover` event as our `drag` event
      // this is because firefox does not publish pointer coordinates during
      // a `drag` event, but does for every other type of drag event
      // `dragover` fires on all elements that are being dragged over
      // Because we are binding to `window` - our `dragover` is effectively the same as a `drag`
      // 🦊😤
      type: "dragover",
      listener: /* @__PURE__ */ __name(function listener(event2) {
        onUpdateEvent(event2);
        dispatch.drag({
          current: state.current
        });
      }, "listener")
    }, {
      type: "dragenter",
      listener: onUpdateEvent
    }, {
      type: "dragleave",
      listener: /* @__PURE__ */ __name(function listener(event2) {
        if (!isLeavingWindow({
          dragLeave: event2
        })) {
          return;
        }
        updateState({
          input: state.current.input,
          dropTargets: []
        });
        if (dragType.startedFrom === "external") {
          cancel();
        }
      }, "listener")
    }, {
      // A "drop" can only happen if the browser allowed the drop
      type: "drop",
      listener: /* @__PURE__ */ __name(function listener(event2) {
        state.current = {
          dropTargets: state.current.dropTargets,
          input: getInput(event2)
        };
        if (!state.current.dropTargets.length) {
          cancel();
          return;
        }
        event2.preventDefault();
        setDropEffectOnEvent({
          event: event2,
          current: state.current.dropTargets
        });
        dispatch.drop({
          current: state.current,
          // When dropping something native, we need to extract the latest
          // `.items` from the "drop" event as it is now accessible
          updatedSourcePayload: dragType.type === "external" ? dragType.getDropPayload(event2) : null
        });
        finish();
      }, "listener")
    }, {
      // "dragend" fires when on the drag source (eg a draggable element)
      // when the drag is finished.
      // "dragend" will fire after "drop" (if there was a successful drop)
      // "dragend" does not fire if the draggable source has been removed during the drag
      // or for external drag sources (eg files)
      // This "dragend" listener will not fire if there was a successful drop
      // as we will have already removed the event listener
      type: "dragend",
      listener: /* @__PURE__ */ __name(function listener(event2) {
        state.current = {
          dropTargets: state.current.dropTargets,
          input: getInput(event2)
        };
        cancel();
      }, "listener")
    }].concat(_toConsumableArray(getBindingsForBrokenDrags({
      onDragEnd: cancel
    }))),
    // Once we have started a managed drag operation it is important that we see / own all drag events
    // We got one adoption bug pop up where some code was stopping (`event.stopPropagation()`)
    // all "drop" events in the bubble phase on the `document.body`.
    // This meant that we never saw the "drop" event.
    {
      capture: true
    }
  );
  dispatch.start({
    nativeSetDragImage: getNativeSetDragImage(event)
  });
}
__name(start, "start");
function setDropEffectOnEvent(_ref3) {
  var _current$;
  var event = _ref3.event, current = _ref3.current;
  var innerMost = (_current$ = current[0]) === null || _current$ === void 0 ? void 0 : _current$.dropEffect;
  if (innerMost != null && event.dataTransfer) {
    event.dataTransfer.dropEffect = innerMost;
  }
}
__name(setDropEffectOnEvent, "setDropEffectOnEvent");
function getStartLocation(_ref4) {
  var event = _ref4.event, dragType = _ref4.dragType, getDropTargetsOver = _ref4.getDropTargetsOver;
  var input = getInput(event);
  if (dragType.startedFrom === "external") {
    return {
      input,
      dropTargets: []
    };
  }
  var dropTargets = getDropTargetsOver({
    input,
    source: dragType.payload,
    target: event.target,
    current: []
  });
  return {
    input,
    dropTargets
  };
}
__name(getStartLocation, "getStartLocation");
var lifecycle = {
  canStart,
  start
};
var ledger = /* @__PURE__ */ new Map();
function registerUsage(_ref) {
  var typeKey = _ref.typeKey, mount2 = _ref.mount;
  var entry = ledger.get(typeKey);
  if (entry) {
    entry.usageCount++;
    return entry;
  }
  var initial = {
    typeKey,
    unmount: mount2(),
    usageCount: 1
  };
  ledger.set(typeKey, initial);
  return initial;
}
__name(registerUsage, "registerUsage");
function register(args) {
  var entry = registerUsage(args);
  return /* @__PURE__ */ __name(function unregister() {
    entry.usageCount--;
    if (entry.usageCount > 0) {
      return;
    }
    entry.unmount();
    ledger.delete(args.typeKey);
  }, "unregister");
}
__name(register, "register");
function combine() {
  for (var _len = arguments.length, fns = new Array(_len), _key = 0; _key < _len; _key++) {
    fns[_key] = arguments[_key];
  }
  return /* @__PURE__ */ __name(function cleanup() {
    fns.forEach(function(fn) {
      return fn();
    });
  }, "cleanup");
}
__name(combine, "combine");
function addAttribute(element, _ref) {
  var attribute2 = _ref.attribute, value = _ref.value;
  element.setAttribute(attribute2, value);
  return function() {
    return element.removeAttribute(attribute2);
  };
}
__name(addAttribute, "addAttribute");
function ownKeys$1(e2, r2) {
  var t2 = Object.keys(e2);
  if (Object.getOwnPropertySymbols) {
    var o2 = Object.getOwnPropertySymbols(e2);
    r2 && (o2 = o2.filter(function(r22) {
      return Object.getOwnPropertyDescriptor(e2, r22).enumerable;
    })), t2.push.apply(t2, o2);
  }
  return t2;
}
__name(ownKeys$1, "ownKeys$1");
function _objectSpread$1(e2) {
  for (var r2 = 1; r2 < arguments.length; r2++) {
    var t2 = null != arguments[r2] ? arguments[r2] : {};
    r2 % 2 ? ownKeys$1(Object(t2), true).forEach(function(r22) {
      _defineProperty(e2, r22, t2[r22]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e2, Object.getOwnPropertyDescriptors(t2)) : ownKeys$1(Object(t2)).forEach(function(r22) {
      Object.defineProperty(e2, r22, Object.getOwnPropertyDescriptor(t2, r22));
    });
  }
  return e2;
}
__name(_objectSpread$1, "_objectSpread$1");
function _createForOfIteratorHelper$1(r2, e2) {
  var t2 = "undefined" != typeof Symbol && r2[Symbol.iterator] || r2["@@iterator"];
  if (!t2) {
    if (Array.isArray(r2) || (t2 = _unsupportedIterableToArray$1(r2)) || e2 && r2 && "number" == typeof r2.length) {
      t2 && (r2 = t2);
      var _n2 = 0, F2 = /* @__PURE__ */ __name(function F22() {
      }, "F2");
      return { s: F2, n: /* @__PURE__ */ __name(function n2() {
        return _n2 >= r2.length ? { done: true } : { done: false, value: r2[_n2++] };
      }, "n"), e: /* @__PURE__ */ __name(function e22(r22) {
        throw r22;
      }, "e2"), f: F2 };
    }
    throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  }
  var o2, a2 = true, u2 = false;
  return { s: /* @__PURE__ */ __name(function s2() {
    t2 = t2.call(r2);
  }, "s"), n: /* @__PURE__ */ __name(function n2() {
    var r22 = t2.next();
    return a2 = r22.done, r22;
  }, "n"), e: /* @__PURE__ */ __name(function e22(r22) {
    u2 = true, o2 = r22;
  }, "e2"), f: /* @__PURE__ */ __name(function f2() {
    try {
      a2 || null == t2.return || t2.return();
    } finally {
      if (u2) throw o2;
    }
  }, "f") };
}
__name(_createForOfIteratorHelper$1, "_createForOfIteratorHelper$1");
function _unsupportedIterableToArray$1(r2, a2) {
  if (r2) {
    if ("string" == typeof r2) return _arrayLikeToArray$1(r2, a2);
    var t2 = {}.toString.call(r2).slice(8, -1);
    return "Object" === t2 && r2.constructor && (t2 = r2.constructor.name), "Map" === t2 || "Set" === t2 ? Array.from(r2) : "Arguments" === t2 || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t2) ? _arrayLikeToArray$1(r2, a2) : void 0;
  }
}
__name(_unsupportedIterableToArray$1, "_unsupportedIterableToArray$1");
function _arrayLikeToArray$1(r2, a2) {
  (null == a2 || a2 > r2.length) && (a2 = r2.length);
  for (var e2 = 0, n2 = Array(a2); e2 < a2; e2++) n2[e2] = r2[e2];
  return n2;
}
__name(_arrayLikeToArray$1, "_arrayLikeToArray$1");
function copyReverse(array) {
  return array.slice(0).reverse();
}
__name(copyReverse, "copyReverse");
function makeDropTarget(_ref) {
  var typeKey = _ref.typeKey, defaultDropEffect = _ref.defaultDropEffect;
  var registry = /* @__PURE__ */ new WeakMap();
  var dropTargetDataAtt = "data-drop-target-for-".concat(typeKey);
  var dropTargetSelector = "[".concat(dropTargetDataAtt, "]");
  function addToRegistry2(args) {
    registry.set(args.element, args);
    return function() {
      return registry.delete(args.element);
    };
  }
  __name(addToRegistry2, "addToRegistry");
  function dropTargetForConsumers(args) {
    if (false) {
      var existing = registry.get(args.element);
      if (existing) {
        console.warn("You have already registered a [".concat(typeKey, "] dropTarget on the same element"), {
          existing,
          proposed: args
        });
      }
      if (args.element instanceof HTMLIFrameElement) {
        console.warn("\n            We recommend not registering <iframe> elements as drop targets\n            as it can result in some strange browser event ordering.\n          ".replace(/\s{2,}/g, " ").trim());
      }
    }
    return combine(addAttribute(args.element, {
      attribute: dropTargetDataAtt,
      value: "true"
    }), addToRegistry2(args));
  }
  __name(dropTargetForConsumers, "dropTargetForConsumers");
  function getActualDropTargets(_ref2) {
    var _args$getData, _args$getData2, _args$getDropEffect, _args$getDropEffect2;
    var source = _ref2.source, target = _ref2.target, input = _ref2.input, _ref2$result = _ref2.result, result = _ref2$result === void 0 ? [] : _ref2$result;
    if (target == null) {
      return result;
    }
    if (!(target instanceof Element)) {
      if (target instanceof Node) {
        return getActualDropTargets({
          source,
          target: target.parentElement,
          input,
          result
        });
      }
      return result;
    }
    var closest = target.closest(dropTargetSelector);
    if (closest == null) {
      return result;
    }
    var args = registry.get(closest);
    if (args == null) {
      return result;
    }
    var feedback = {
      input,
      source,
      element: args.element
    };
    if (args.canDrop && !args.canDrop(feedback)) {
      return getActualDropTargets({
        source,
        target: args.element.parentElement,
        input,
        result
      });
    }
    var data = (_args$getData = (_args$getData2 = args.getData) === null || _args$getData2 === void 0 ? void 0 : _args$getData2.call(args, feedback)) !== null && _args$getData !== void 0 ? _args$getData : {};
    var dropEffect = (_args$getDropEffect = (_args$getDropEffect2 = args.getDropEffect) === null || _args$getDropEffect2 === void 0 ? void 0 : _args$getDropEffect2.call(args, feedback)) !== null && _args$getDropEffect !== void 0 ? _args$getDropEffect : defaultDropEffect;
    var record2 = {
      data,
      element: args.element,
      dropEffect,
      // we are collecting _actual_ drop targets, so these are
      // being applied _not_ due to stickiness
      isActiveDueToStickiness: false
    };
    return getActualDropTargets({
      source,
      target: args.element.parentElement,
      input,
      // Using bubble ordering. Same ordering as `event.getPath()`
      result: [].concat(_toConsumableArray(result), [record2])
    });
  }
  __name(getActualDropTargets, "getActualDropTargets");
  function notifyCurrent(_ref3) {
    var eventName = _ref3.eventName, payload = _ref3.payload;
    var _iterator = _createForOfIteratorHelper$1(payload.location.current.dropTargets), _step;
    try {
      for (_iterator.s(); !(_step = _iterator.n()).done; ) {
        var _entry$eventName;
        var record2 = _step.value;
        var entry = registry.get(record2.element);
        var args = _objectSpread$1(_objectSpread$1({}, payload), {}, {
          self: record2
        });
        entry === null || entry === void 0 || (_entry$eventName = entry[eventName]) === null || _entry$eventName === void 0 || _entry$eventName.call(
          entry,
          // I cannot seem to get the types right here.
          // TS doesn't seem to like that one event can need `nativeSetDragImage`
          // @ts-expect-error
          args
        );
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }
  }
  __name(notifyCurrent, "notifyCurrent");
  var actions = {
    onGenerateDragPreview: notifyCurrent,
    onDrag: notifyCurrent,
    onDragStart: notifyCurrent,
    onDrop: notifyCurrent,
    onDropTargetChange: /* @__PURE__ */ __name(function onDropTargetChange(_ref4) {
      var payload = _ref4.payload;
      var isCurrent = new Set(payload.location.current.dropTargets.map(function(record22) {
        return record22.element;
      }));
      var visited = /* @__PURE__ */ new Set();
      var _iterator2 = _createForOfIteratorHelper$1(payload.location.previous.dropTargets), _step2;
      try {
        for (_iterator2.s(); !(_step2 = _iterator2.n()).done; ) {
          var _entry$onDropTargetCh;
          var record2 = _step2.value;
          visited.add(record2.element);
          var entry = registry.get(record2.element);
          var isOver = isCurrent.has(record2.element);
          var args = _objectSpread$1(_objectSpread$1({}, payload), {}, {
            self: record2
          });
          entry === null || entry === void 0 || (_entry$onDropTargetCh = entry.onDropTargetChange) === null || _entry$onDropTargetCh === void 0 || _entry$onDropTargetCh.call(entry, args);
          if (!isOver) {
            var _entry$onDragLeave;
            entry === null || entry === void 0 || (_entry$onDragLeave = entry.onDragLeave) === null || _entry$onDragLeave === void 0 || _entry$onDragLeave.call(entry, args);
          }
        }
      } catch (err) {
        _iterator2.e(err);
      } finally {
        _iterator2.f();
      }
      var _iterator3 = _createForOfIteratorHelper$1(payload.location.current.dropTargets), _step3;
      try {
        for (_iterator3.s(); !(_step3 = _iterator3.n()).done; ) {
          var _entry$onDropTargetCh2, _entry$onDragEnter;
          var _record = _step3.value;
          if (visited.has(_record.element)) {
            continue;
          }
          var _args = _objectSpread$1(_objectSpread$1({}, payload), {}, {
            self: _record
          });
          var _entry = registry.get(_record.element);
          _entry === null || _entry === void 0 || (_entry$onDropTargetCh2 = _entry.onDropTargetChange) === null || _entry$onDropTargetCh2 === void 0 || _entry$onDropTargetCh2.call(_entry, _args);
          _entry === null || _entry === void 0 || (_entry$onDragEnter = _entry.onDragEnter) === null || _entry$onDragEnter === void 0 || _entry$onDragEnter.call(_entry, _args);
        }
      } catch (err) {
        _iterator3.e(err);
      } finally {
        _iterator3.f();
      }
    }, "onDropTargetChange")
  };
  function dispatchEvent2(args) {
    actions[args.eventName](args);
  }
  __name(dispatchEvent2, "dispatchEvent");
  function getIsOver(_ref5) {
    var source = _ref5.source, target = _ref5.target, input = _ref5.input, current = _ref5.current;
    var actual = getActualDropTargets({
      source,
      target,
      input
    });
    if (actual.length >= current.length) {
      return actual;
    }
    var lastCaptureOrdered = copyReverse(current);
    var actualCaptureOrdered = copyReverse(actual);
    var resultCaptureOrdered = [];
    for (var index2 = 0; index2 < lastCaptureOrdered.length; index2++) {
      var _argsForLast$getIsSti;
      var last = lastCaptureOrdered[index2];
      var fresh = actualCaptureOrdered[index2];
      if (fresh != null) {
        resultCaptureOrdered.push(fresh);
        continue;
      }
      var parent2 = resultCaptureOrdered[index2 - 1];
      var lastParent = lastCaptureOrdered[index2 - 1];
      if ((parent2 === null || parent2 === void 0 ? void 0 : parent2.element) !== (lastParent === null || lastParent === void 0 ? void 0 : lastParent.element)) {
        break;
      }
      var argsForLast = registry.get(last.element);
      if (!argsForLast) {
        break;
      }
      var feedback = {
        input,
        source,
        element: argsForLast.element
      };
      if (argsForLast.canDrop && !argsForLast.canDrop(feedback)) {
        break;
      }
      if (!((_argsForLast$getIsSti = argsForLast.getIsSticky) !== null && _argsForLast$getIsSti !== void 0 && _argsForLast$getIsSti.call(argsForLast, feedback))) {
        break;
      }
      resultCaptureOrdered.push(_objectSpread$1(_objectSpread$1({}, last), {}, {
        // making it clear to consumers this drop target is active due to stickiness
        isActiveDueToStickiness: true
      }));
    }
    return copyReverse(resultCaptureOrdered);
  }
  __name(getIsOver, "getIsOver");
  return {
    dropTargetForConsumers,
    getIsOver,
    dispatchEvent: dispatchEvent2
  };
}
__name(makeDropTarget, "makeDropTarget");
function _createForOfIteratorHelper(r2, e2) {
  var t2 = "undefined" != typeof Symbol && r2[Symbol.iterator] || r2["@@iterator"];
  if (!t2) {
    if (Array.isArray(r2) || (t2 = _unsupportedIterableToArray(r2)) || e2 && r2 && "number" == typeof r2.length) {
      t2 && (r2 = t2);
      var _n2 = 0, F2 = /* @__PURE__ */ __name(function F3() {
      }, "F");
      return { s: F2, n: /* @__PURE__ */ __name(function n2() {
        return _n2 >= r2.length ? { done: true } : { done: false, value: r2[_n2++] };
      }, "n"), e: /* @__PURE__ */ __name(function e3(r3) {
        throw r3;
      }, "e"), f: F2 };
    }
    throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  }
  var o2, a2 = true, u2 = false;
  return { s: /* @__PURE__ */ __name(function s2() {
    t2 = t2.call(r2);
  }, "s"), n: /* @__PURE__ */ __name(function n2() {
    var r3 = t2.next();
    return a2 = r3.done, r3;
  }, "n"), e: /* @__PURE__ */ __name(function e3(r3) {
    u2 = true, o2 = r3;
  }, "e"), f: /* @__PURE__ */ __name(function f2() {
    try {
      a2 || null == t2.return || t2.return();
    } finally {
      if (u2) throw o2;
    }
  }, "f") };
}
__name(_createForOfIteratorHelper, "_createForOfIteratorHelper");
function _unsupportedIterableToArray(r2, a2) {
  if (r2) {
    if ("string" == typeof r2) return _arrayLikeToArray(r2, a2);
    var t2 = {}.toString.call(r2).slice(8, -1);
    return "Object" === t2 && r2.constructor && (t2 = r2.constructor.name), "Map" === t2 || "Set" === t2 ? Array.from(r2) : "Arguments" === t2 || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t2) ? _arrayLikeToArray(r2, a2) : void 0;
  }
}
__name(_unsupportedIterableToArray, "_unsupportedIterableToArray");
function _arrayLikeToArray(r2, a2) {
  (null == a2 || a2 > r2.length) && (a2 = r2.length);
  for (var e2 = 0, n2 = Array(a2); e2 < a2; e2++) n2[e2] = r2[e2];
  return n2;
}
__name(_arrayLikeToArray, "_arrayLikeToArray");
function ownKeys(e2, r2) {
  var t2 = Object.keys(e2);
  if (Object.getOwnPropertySymbols) {
    var o2 = Object.getOwnPropertySymbols(e2);
    r2 && (o2 = o2.filter(function(r3) {
      return Object.getOwnPropertyDescriptor(e2, r3).enumerable;
    })), t2.push.apply(t2, o2);
  }
  return t2;
}
__name(ownKeys, "ownKeys");
function _objectSpread(e2) {
  for (var r2 = 1; r2 < arguments.length; r2++) {
    var t2 = null != arguments[r2] ? arguments[r2] : {};
    r2 % 2 ? ownKeys(Object(t2), true).forEach(function(r3) {
      _defineProperty(e2, r3, t2[r3]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e2, Object.getOwnPropertyDescriptors(t2)) : ownKeys(Object(t2)).forEach(function(r3) {
      Object.defineProperty(e2, r3, Object.getOwnPropertyDescriptor(t2, r3));
    });
  }
  return e2;
}
__name(_objectSpread, "_objectSpread");
function makeMonitor() {
  var registry = /* @__PURE__ */ new Set();
  var dragging = null;
  function tryAddToActive(monitor) {
    if (!dragging) {
      return;
    }
    if (!monitor.canMonitor || monitor.canMonitor(dragging.canMonitorArgs)) {
      dragging.active.add(monitor);
    }
  }
  __name(tryAddToActive, "tryAddToActive");
  function monitorForConsumers(args) {
    var entry = _objectSpread({}, args);
    registry.add(entry);
    tryAddToActive(entry);
    return /* @__PURE__ */ __name(function cleanup() {
      registry.delete(entry);
      if (dragging) {
        dragging.active.delete(entry);
      }
    }, "cleanup");
  }
  __name(monitorForConsumers, "monitorForConsumers");
  function dispatchEvent2(_ref) {
    var eventName = _ref.eventName, payload = _ref.payload;
    if (eventName === "onGenerateDragPreview") {
      dragging = {
        canMonitorArgs: {
          initial: payload.location.initial,
          source: payload.source
        },
        active: /* @__PURE__ */ new Set()
      };
      var _iterator = _createForOfIteratorHelper(registry), _step;
      try {
        for (_iterator.s(); !(_step = _iterator.n()).done; ) {
          var monitor = _step.value;
          tryAddToActive(monitor);
        }
      } catch (err) {
        _iterator.e(err);
      } finally {
        _iterator.f();
      }
    }
    if (!dragging) {
      return;
    }
    var active = Array.from(dragging.active);
    for (var _i = 0, _active = active; _i < _active.length; _i++) {
      var _monitor = _active[_i];
      if (dragging.active.has(_monitor)) {
        var _monitor$eventName;
        (_monitor$eventName = _monitor[eventName]) === null || _monitor$eventName === void 0 || _monitor$eventName.call(_monitor, payload);
      }
    }
    if (eventName === "onDrop") {
      dragging.active.clear();
      dragging = null;
    }
  }
  __name(dispatchEvent2, "dispatchEvent");
  return {
    dispatchEvent: dispatchEvent2,
    monitorForConsumers
  };
}
__name(makeMonitor, "makeMonitor");
function makeAdapter(_ref) {
  var typeKey = _ref.typeKey, mount2 = _ref.mount, dispatchEventToSource2 = _ref.dispatchEventToSource, onPostDispatch = _ref.onPostDispatch, defaultDropEffect = _ref.defaultDropEffect;
  var monitorAPI = makeMonitor();
  var dropTargetAPI = makeDropTarget({
    typeKey,
    defaultDropEffect
  });
  function dispatchEvent2(args) {
    dispatchEventToSource2 === null || dispatchEventToSource2 === void 0 || dispatchEventToSource2(args);
    dropTargetAPI.dispatchEvent(args);
    monitorAPI.dispatchEvent(args);
    onPostDispatch === null || onPostDispatch === void 0 || onPostDispatch(args);
  }
  __name(dispatchEvent2, "dispatchEvent");
  function start2(_ref2) {
    var event = _ref2.event, dragType = _ref2.dragType;
    lifecycle.start({
      event,
      dragType,
      getDropTargetsOver: dropTargetAPI.getIsOver,
      dispatchEvent: dispatchEvent2
    });
  }
  __name(start2, "start");
  function registerUsage2() {
    function mountAdapter() {
      var api2 = {
        canStart: lifecycle.canStart,
        start: start2
      };
      return mount2(api2);
    }
    __name(mountAdapter, "mountAdapter");
    return register({
      typeKey,
      mount: mountAdapter
    });
  }
  __name(registerUsage2, "registerUsage");
  return {
    registerUsage: registerUsage2,
    dropTarget: dropTargetAPI.dropTargetForConsumers,
    monitor: monitorAPI.monitorForConsumers
  };
}
__name(makeAdapter, "makeAdapter");
var isAndroid = once(/* @__PURE__ */ __name(function isAndroid2() {
  return navigator.userAgent.toLocaleLowerCase().includes("android");
}, "isAndroid"));
var androidFallbackText = "pdnd:android-fallback";
var textMediaType = "text/plain";
var URLMediaType = "text/uri-list";
var elementAdapterNativeDataKey = "application/vnd.pdnd";
var draggableRegistry = /* @__PURE__ */ new WeakMap();
function addToRegistry(args) {
  draggableRegistry.set(args.element, args);
  return /* @__PURE__ */ __name(function cleanup() {
    draggableRegistry.delete(args.element);
  }, "cleanup");
}
__name(addToRegistry, "addToRegistry");
var honeyPotFix = makeHoneyPotFix();
var adapter = makeAdapter({
  typeKey: "element",
  defaultDropEffect: "move",
  mount: /* @__PURE__ */ __name(function mount(api2) {
    return combine(honeyPotFix.bindEvents(), dist.bind(document, {
      type: "dragstart",
      listener: /* @__PURE__ */ __name(function listener(event) {
        var _entry$dragHandle, _entry$getInitialData, _entry$getInitialData2, _entry$dragHandle2, _entry$getInitialData3, _entry$getInitialData4;
        if (!api2.canStart(event)) {
          return;
        }
        if (event.defaultPrevented) {
          return;
        }
        if (!event.dataTransfer) {
          if (false) {
            console.warn("\n              It appears as though you have are not testing DragEvents correctly.\n\n              - If you are unit testing, ensure you have polyfilled DragEvent.\n              - If you are browser testing, ensure you are dispatching drag events correctly.\n\n              Please see our testing guides for more information:\n              https://atlassian.design/components/pragmatic-drag-and-drop/core-package/testing\n            ".replace(/ {2}/g, ""));
          }
          return;
        }
        var target = event.target;
        if (!(target instanceof HTMLElement)) {
          return null;
        }
        var entry = draggableRegistry.get(target);
        if (!entry) {
          return null;
        }
        var input = getInput(event);
        var feedback = {
          element: entry.element,
          dragHandle: (_entry$dragHandle = entry.dragHandle) !== null && _entry$dragHandle !== void 0 ? _entry$dragHandle : null,
          input
        };
        if (entry.canDrag && !entry.canDrag(feedback)) {
          event.preventDefault();
          return null;
        }
        if (entry.dragHandle) {
          var over = getElementFromPointWithoutHoneypot({
            x: input.clientX,
            y: input.clientY
          });
          if (!entry.dragHandle.contains(over)) {
            event.preventDefault();
            return null;
          }
        }
        var nativeData = (_entry$getInitialData = (_entry$getInitialData2 = entry.getInitialDataForExternal) === null || _entry$getInitialData2 === void 0 ? void 0 : _entry$getInitialData2.call(entry, feedback)) !== null && _entry$getInitialData !== void 0 ? _entry$getInitialData : null;
        if (nativeData) {
          for (var _i = 0, _Object$entries = Object.entries(nativeData); _i < _Object$entries.length; _i++) {
            var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2), key = _Object$entries$_i[0], data = _Object$entries$_i[1];
            event.dataTransfer.setData(key, data !== null && data !== void 0 ? data : "");
          }
        }
        if (isAndroid() && !event.dataTransfer.types.includes(textMediaType) && !event.dataTransfer.types.includes(URLMediaType)) {
          event.dataTransfer.setData(textMediaType, androidFallbackText);
        }
        event.dataTransfer.setData(elementAdapterNativeDataKey, "");
        var payload = {
          element: entry.element,
          dragHandle: (_entry$dragHandle2 = entry.dragHandle) !== null && _entry$dragHandle2 !== void 0 ? _entry$dragHandle2 : null,
          data: (_entry$getInitialData3 = (_entry$getInitialData4 = entry.getInitialData) === null || _entry$getInitialData4 === void 0 ? void 0 : _entry$getInitialData4.call(entry, feedback)) !== null && _entry$getInitialData3 !== void 0 ? _entry$getInitialData3 : {}
        };
        var dragType = {
          type: "element",
          payload,
          startedFrom: "internal"
        };
        api2.start({
          event,
          dragType
        });
      }, "listener")
    }));
  }, "mount"),
  dispatchEventToSource: /* @__PURE__ */ __name(function dispatchEventToSource(_ref) {
    var _draggableRegistry$ge, _draggableRegistry$ge2;
    var eventName = _ref.eventName, payload = _ref.payload;
    (_draggableRegistry$ge = draggableRegistry.get(payload.source.element)) === null || _draggableRegistry$ge === void 0 || (_draggableRegistry$ge2 = _draggableRegistry$ge[eventName]) === null || _draggableRegistry$ge2 === void 0 || _draggableRegistry$ge2.call(
      _draggableRegistry$ge,
      // I cannot seem to get the types right here.
      // TS doesn't seem to like that one event can need `nativeSetDragImage`
      // @ts-expect-error
      payload
    );
  }, "dispatchEventToSource"),
  onPostDispatch: honeyPotFix.getOnPostDispatch()
});
var dropTargetForElements = adapter.dropTarget;
var monitorForElements = adapter.monitor;
function draggable(args) {
  if (false) {
    if (args.dragHandle && !args.element.contains(args.dragHandle)) {
      console.warn("Drag handle element must be contained in draggable element", {
        element: args.element,
        dragHandle: args.dragHandle
      });
    }
  }
  if (false) {
    var existing = draggableRegistry.get(args.element);
    if (existing) {
      console.warn("You have already registered a `draggable` on the same element", {
        existing,
        proposed: args
      });
    }
  }
  return combine(
    // making the draggable register the adapter rather than drop targets
    // this is because you *must* have a draggable element to start a drag
    // but you _might_ not have any drop targets immediately
    // (You might create drop targets async)
    adapter.registerUsage(),
    addToRegistry(args),
    addAttribute(args.element, {
      attribute: "draggable",
      value: "true"
    })
  );
}
__name(draggable, "draggable");
function defaultOffset() {
  return {
    x: 0,
    y: 0
  };
}
__name(defaultOffset, "defaultOffset");
function setCustomNativeDragPreview(_ref) {
  var render2 = _ref.render, nativeSetDragImage = _ref.nativeSetDragImage, _ref$getOffset = _ref.getOffset, getOffset2 = _ref$getOffset === void 0 ? defaultOffset : _ref$getOffset;
  var container = document.createElement("div");
  Object.assign(container.style, {
    // Ensuring we don't cause reflow when adding the element to the page
    // Using `position:fixed` rather than `position:absolute` so we are
    // positioned on the current viewport.
    // `position:fixed` also creates a new stacking context, so we don't need to do that here
    position: "fixed",
    // According to `mdn`, the element can be offscreen:
    // https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer/setDragImage#imgelement
    //
    // However, that  information does not appear in the specs:
    // https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransfer-setdragimage-dev
    //
    // If the element is _completely_ offscreen, Safari@17.1 will cancel the drag
    top: 0,
    left: 0,
    // Using maximum possible z-index so that this element will always be on top
    // https://stackoverflow.com/questions/491052/minimum-and-maximum-value-of-z-index
    // Did not use `layers` in `@atlaskit/theme` because:
    // 1. This element is not a 'layer' in the conventional sense, as this element
    //    is only created for a single frame for the browser to take a photo of it,
    //    and then it is destroyed
    // 2. Did not want to add a dependency onto `@atlaskit/theme`
    // 3. Want to always be on top of product UI which might have higher z-index's
    zIndex: maxZIndex,
    // Avoiding any additional events caused by the new element (being super safe)
    pointerEvents: "none"
  });
  document.body.append(container);
  var unmount = render2({
    container
  });
  queueMicrotask(function() {
    var previewOffset = getOffset2({
      container
    });
    if (isSafari()) {
      var rect = container.getBoundingClientRect();
      if (rect.width === 0) {
        return;
      }
      container.style.left = "-".concat(rect.width - 1e-4, "px");
    }
    nativeSetDragImage === null || nativeSetDragImage === void 0 || nativeSetDragImage(container, previewOffset.x, previewOffset.y);
  });
  function cleanup() {
    unbindMonitor();
    unmount === null || unmount === void 0 || unmount();
    document.body.removeChild(container);
  }
  __name(cleanup, "cleanup");
  var unbindMonitor = monitorForElements({
    // Remove portal in the dragstart event so that the user will never see it
    onDragStart: cleanup,
    // Backup: remove portal when the drop finishes (this would be an error case)
    onDrop: cleanup
  });
}
__name(setCustomNativeDragPreview, "setCustomNativeDragPreview");
const _hoisted_1$g = { class: "editable-text" };
const _hoisted_2$e = { key: 0 };
const _sfc_main$p = /* @__PURE__ */ defineComponent({
  __name: "EditableText",
  props: {
    modelValue: {},
    isEditing: { type: Boolean, default: false }
  },
  emits: ["update:modelValue", "edit"],
  setup(__props, { emit: __emit }) {
    const emit = __emit;
    const inputValue = ref$3(__props.modelValue);
    const inputRef = ref$3();
    const blurInputElement = /* @__PURE__ */ __name(() => {
      inputRef.value?.$el.blur();
    }, "blurInputElement");
    const finishEditing = /* @__PURE__ */ __name(() => {
      emit("edit", inputValue.value);
    }, "finishEditing");
    watch(
      () => __props.isEditing,
      async (newVal) => {
        if (newVal) {
          inputValue.value = __props.modelValue;
          await nextTick(() => {
            if (!inputRef.value) return;
            const fileName = inputValue.value.includes(".") ? inputValue.value.split(".").slice(0, -1).join(".") : inputValue.value;
            const start2 = 0;
            const end = fileName.length;
            const inputElement = inputRef.value.$el;
            inputElement.setSelectionRange?.(start2, end);
          });
        }
      },
      { immediate: true }
    );
    const vFocus = {
      mounted: /* @__PURE__ */ __name((el) => el.focus(), "mounted")
    };
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", _hoisted_1$g, [
        !_ctx.isEditing ? (openBlock(), createElementBlock("span", _hoisted_2$e, toDisplayString(_ctx.modelValue), 1)) : withDirectives((openBlock(), createBlock(unref(script$b), {
          key: 1,
          ref_key: "inputRef",
          ref: inputRef,
          modelValue: inputValue.value,
          "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => inputValue.value = $event),
          type: "text",
          size: "small",
          fluid: "",
          pt: {
            root: {
              onBlur: finishEditing
            }
          },
          onKeyup: withKeys(blurInputElement, ["enter"]),
          onClick: _cache[1] || (_cache[1] = withModifiers(() => {
          }, ["stop"]))
        }, null, 8, ["modelValue", "pt"])), [
          [vFocus]
        ])
      ]);
    };
  }
});
const EditableText = /* @__PURE__ */ _export_sfc(_sfc_main$p, [["__scopeId", "data-v-be8a3bfc"]]);
function usePragmaticDroppable(dropTargetElement, options2) {
  let cleanup = /* @__PURE__ */ __name(() => {
  }, "cleanup");
  onMounted(() => {
    const element = typeof dropTargetElement === "function" ? dropTargetElement() : dropTargetElement;
    if (!element) {
      return;
    }
    cleanup = dropTargetForElements({
      element,
      ...options2
    });
  });
  onBeforeUnmount(() => {
    cleanup();
  });
}
__name(usePragmaticDroppable, "usePragmaticDroppable");
function usePragmaticDraggable(draggableElement, options2) {
  let cleanup = /* @__PURE__ */ __name(() => {
  }, "cleanup");
  onMounted(() => {
    const element = typeof draggableElement === "function" ? draggableElement() : draggableElement;
    if (!element) {
      return;
    }
    cleanup = draggable({
      element,
      ...options2
    });
  });
  onBeforeUnmount(() => {
    cleanup();
  });
}
__name(usePragmaticDraggable, "usePragmaticDraggable");
const InjectKeyHandleEditLabelFunction = Symbol();
const InjectKeyExpandedKeys = Symbol();
const _hoisted_1$f = { class: "node-content" };
const _hoisted_2$d = { class: "node-label" };
const _hoisted_3$8 = { class: "node-actions motion-safe:opacity-0 motion-safe:group-hover/tree-node:opacity-100" };
const _sfc_main$o = /* @__PURE__ */ defineComponent({
  __name: "TreeExplorerTreeNode",
  props: {
    node: {}
  },
  emits: ["itemDropped", "dragStart", "dragEnd"],
  setup(__props, { emit: __emit }) {
    const props = __props;
    const emit = __emit;
    const nodeBadgeText = computed(() => {
      if (props.node.leaf) {
        return "";
      }
      if (props.node.badgeText !== void 0 && props.node.badgeText !== null) {
        return props.node.badgeText;
      }
      return props.node.totalLeaves.toString();
    });
    const showNodeBadgeText = computed(() => nodeBadgeText.value !== "");
    const isEditing = computed(() => props.node.isEditingLabel ?? false);
    const handleEditLabel = inject(InjectKeyHandleEditLabelFunction);
    const handleRename = /* @__PURE__ */ __name((newName) => {
      handleEditLabel?.(props.node, newName);
    }, "handleRename");
    const container = ref$3(null);
    const canDrop = ref$3(false);
    const treeNodeElementGetter = /* @__PURE__ */ __name(() => container.value?.closest(".p-tree-node-content"), "treeNodeElementGetter");
    if (props.node.draggable) {
      usePragmaticDraggable(treeNodeElementGetter, {
        getInitialData: /* @__PURE__ */ __name(() => {
          return {
            type: "tree-explorer-node",
            data: props.node
          };
        }, "getInitialData"),
        onDragStart: /* @__PURE__ */ __name(() => emit("dragStart", props.node), "onDragStart"),
        onDrop: /* @__PURE__ */ __name(() => emit("dragEnd", props.node), "onDrop"),
        onGenerateDragPreview: props.node.renderDragPreview ? ({ nativeSetDragImage }) => {
          setCustomNativeDragPreview({
            render: /* @__PURE__ */ __name(({ container: container2 }) => {
              return props.node.renderDragPreview?.(container2);
            }, "render"),
            nativeSetDragImage
          });
        } : void 0
      });
    }
    if (props.node.droppable) {
      usePragmaticDroppable(treeNodeElementGetter, {
        onDrop: /* @__PURE__ */ __name(async (event) => {
          const dndData = event.source.data;
          if (dndData.type === "tree-explorer-node") {
            await props.node.handleDrop?.(dndData);
            canDrop.value = false;
            emit("itemDropped", props.node, dndData.data);
          }
        }, "onDrop"),
        onDragEnter: /* @__PURE__ */ __name((event) => {
          const dndData = event.source.data;
          if (dndData.type === "tree-explorer-node") {
            canDrop.value = true;
          }
        }, "onDragEnter"),
        onDragLeave: /* @__PURE__ */ __name(() => {
          canDrop.value = false;
        }, "onDragLeave")
      });
    }
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", {
        ref_key: "container",
        ref: container,
        class: normalizeClass([
          "tree-node",
          {
            "can-drop": canDrop.value,
            "tree-folder": !props.node.leaf,
            "tree-leaf": props.node.leaf
          }
        ])
      }, [
        createBaseVNode("div", _hoisted_1$f, [
          createBaseVNode("span", _hoisted_2$d, [
            renderSlot(_ctx.$slots, "before-label", {
              node: props.node
            }, void 0, true),
            createVNode(EditableText, {
              "model-value": _ctx.node.label,
              "is-editing": isEditing.value,
              onEdit: handleRename
            }, null, 8, ["model-value", "is-editing"]),
            renderSlot(_ctx.$slots, "after-label", {
              node: props.node
            }, void 0, true)
          ]),
          showNodeBadgeText.value ? (openBlock(), createBlock(unref(script$j), {
            key: 0,
            value: nodeBadgeText.value,
            severity: "secondary",
            class: "leaf-count-badge"
          }, null, 8, ["value"])) : createCommentVNode("", true)
        ]),
        createBaseVNode("div", _hoisted_3$8, [
          renderSlot(_ctx.$slots, "actions", {
            node: props.node
          }, void 0, true)
        ])
      ], 2);
    };
  }
});
const TreeExplorerTreeNode = /* @__PURE__ */ _export_sfc(_sfc_main$o, [["__scopeId", "data-v-24d44014"]]);
function useTreeFolderOperations(expandNode) {
  const { t: t2 } = useI18n();
  const newFolderNode = ref$3(null);
  const addFolderTargetNode = ref$3(null);
  const generateTempKey = /* @__PURE__ */ __name((parentKey) => {
    return `${parentKey}/new_folder_${Date.now()}`;
  }, "generateTempKey");
  const handleFolderCreation = /* @__PURE__ */ __name(async (newName) => {
    if (!newFolderNode.value || !addFolderTargetNode.value) return;
    try {
      await addFolderTargetNode.value?.handleAddFolder?.(newName);
    } finally {
      newFolderNode.value = null;
      addFolderTargetNode.value = null;
    }
  }, "handleFolderCreation");
  const addFolderCommand = /* @__PURE__ */ __name((targetNode) => {
    expandNode(targetNode);
    newFolderNode.value = {
      key: generateTempKey(targetNode.key),
      label: "",
      leaf: false,
      children: [],
      icon: "pi pi-folder",
      type: "folder",
      totalLeaves: 0,
      badgeText: "",
      isEditingLabel: true
    };
    addFolderTargetNode.value = targetNode;
  }, "addFolderCommand");
  const getAddFolderMenuItem = /* @__PURE__ */ __name((targetNode) => {
    return {
      label: t2("g.newFolder"),
      icon: "pi pi-folder-plus",
      command: /* @__PURE__ */ __name(() => {
        if (targetNode) addFolderCommand(targetNode);
      }, "command"),
      visible: !!targetNode && !targetNode.leaf && !!targetNode.handleAddFolder,
      isAsync: false
    };
  }, "getAddFolderMenuItem");
  return {
    newFolderNode,
    addFolderCommand,
    getAddFolderMenuItem,
    handleFolderCreation
  };
}
__name(useTreeFolderOperations, "useTreeFolderOperations");
const _sfc_main$n = /* @__PURE__ */ defineComponent({
  __name: "TreeExplorer",
  props: /* @__PURE__ */ mergeModels({
    root: {},
    class: {}
  }, {
    "expandedKeys": {
      required: true
    },
    "expandedKeysModifiers": {},
    "selectionKeys": {},
    "selectionKeysModifiers": {}
  }),
  emits: /* @__PURE__ */ mergeModels(["nodeClick", "nodeDelete", "contextMenu"], ["update:expandedKeys", "update:selectionKeys"]),
  setup(__props, { expose: __expose, emit: __emit }) {
    const expandedKeys = useModel(__props, "expandedKeys");
    provide(InjectKeyExpandedKeys, expandedKeys);
    const selectionKeys = useModel(__props, "selectionKeys");
    const storeSelectionKeys = selectionKeys.value !== void 0;
    const props = __props;
    const emit = __emit;
    const {
      newFolderNode,
      getAddFolderMenuItem,
      handleFolderCreation,
      addFolderCommand
    } = useTreeFolderOperations(
      /* expandNode */
      (node2) => {
        expandedKeys.value[node2.key] = true;
      }
    );
    const renderedRoot = computed(() => {
      const renderedRoot2 = fillNodeInfo(props.root);
      return newFolderNode.value ? combineTrees(renderedRoot2, newFolderNode.value) : renderedRoot2;
    });
    const getTreeNodeIcon = /* @__PURE__ */ __name((node2) => {
      if (node2.getIcon) {
        const icon2 = node2.getIcon();
        if (icon2) {
          return icon2;
        }
      } else if (node2.icon) {
        return node2.icon;
      }
      if (node2.leaf) {
        return "pi pi-file";
      }
      const isExpanded = expandedKeys.value?.[node2.key] ?? false;
      return isExpanded ? "pi pi-folder-open" : "pi pi-folder";
    }, "getTreeNodeIcon");
    const fillNodeInfo = /* @__PURE__ */ __name((node2) => {
      const children = node2.children?.map(fillNodeInfo) ?? [];
      const totalLeaves = node2.leaf ? 1 : children.reduce((acc, child2) => acc + child2.totalLeaves, 0);
      return {
        ...node2,
        icon: getTreeNodeIcon(node2),
        children,
        type: node2.leaf ? "node" : "folder",
        totalLeaves,
        badgeText: node2.getBadgeText ? node2.getBadgeText() : void 0,
        isEditingLabel: node2.key === renameEditingNode.value?.key
      };
    }, "fillNodeInfo");
    const onNodeContentClick = /* @__PURE__ */ __name(async (e2, node2) => {
      if (!storeSelectionKeys) {
        selectionKeys.value = {};
      }
      if (node2.handleClick) {
        await node2.handleClick(e2);
      }
      emit("nodeClick", node2, e2);
    }, "onNodeContentClick");
    const menu2 = ref$3(null);
    const menuTargetNode = ref$3(null);
    const extraMenuItems = computed(() => {
      return menuTargetNode.value?.contextMenuItems ? typeof menuTargetNode.value.contextMenuItems === "function" ? menuTargetNode.value.contextMenuItems(menuTargetNode.value) : menuTargetNode.value.contextMenuItems : [];
    });
    const renameEditingNode = ref$3(null);
    const errorHandling = useErrorHandling();
    const handleNodeLabelEdit = /* @__PURE__ */ __name(async (node2, newName) => {
      await errorHandling.wrapWithErrorHandlingAsync(
        async () => {
          if (node2.key === newFolderNode.value?.key) {
            await handleFolderCreation(newName);
          } else {
            await node2.handleRename?.(newName);
          }
        },
        node2.handleError,
        () => {
          renameEditingNode.value = null;
        }
      )();
    }, "handleNodeLabelEdit");
    provide(InjectKeyHandleEditLabelFunction, handleNodeLabelEdit);
    const { t: t2 } = useI18n();
    const renameCommand = /* @__PURE__ */ __name((node2) => {
      renameEditingNode.value = node2;
    }, "renameCommand");
    const deleteCommand = /* @__PURE__ */ __name(async (node2) => {
      await node2.handleDelete?.();
      emit("nodeDelete", node2);
    }, "deleteCommand");
    const menuItems = computed(
      () => [
        getAddFolderMenuItem(menuTargetNode.value),
        {
          label: t2("g.rename"),
          icon: "pi pi-file-edit",
          command: /* @__PURE__ */ __name(() => {
            if (menuTargetNode.value) {
              renameCommand(menuTargetNode.value);
            }
          }, "command"),
          visible: menuTargetNode.value?.handleRename !== void 0
        },
        {
          label: t2("g.delete"),
          icon: "pi pi-trash",
          command: /* @__PURE__ */ __name(async () => {
            if (menuTargetNode.value) {
              await deleteCommand(menuTargetNode.value);
            }
          }, "command"),
          visible: menuTargetNode.value?.handleDelete !== void 0,
          isAsync: true
          // The delete command can be async
        },
        ...extraMenuItems.value
      ].map((menuItem) => ({
        ...menuItem,
        command: menuItem.command ? wrapCommandWithErrorHandler(menuItem.command, {
          isAsync: menuItem.isAsync ?? false
        }) : void 0
      }))
    );
    const handleContextMenu = /* @__PURE__ */ __name((e2, node2) => {
      menuTargetNode.value = node2;
      emit("contextMenu", node2, e2);
      if (menuItems.value.filter((item) => item.visible).length > 0) {
        menu2.value?.show(e2);
      }
    }, "handleContextMenu");
    const wrapCommandWithErrorHandler = /* @__PURE__ */ __name((command2, { isAsync: isAsync2 = false }) => {
      return isAsync2 ? errorHandling.wrapWithErrorHandlingAsync(
        command2,
        menuTargetNode.value?.handleError
      ) : errorHandling.wrapWithErrorHandling(
        command2,
        menuTargetNode.value?.handleError
      );
    }, "wrapCommandWithErrorHandler");
    __expose({
      /**
       * The command to add a folder to a node via the context menu
       * @param targetNodeKey - The key of the node where the folder will be added under
       */
      addFolderCommand: /* @__PURE__ */ __name((targetNodeKey) => {
        const targetNode = findNodeByKey(renderedRoot.value, targetNodeKey);
        if (targetNode) {
          addFolderCommand(targetNode);
        }
      }, "addFolderCommand")
    });
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock(Fragment$1, null, [
        createVNode(unref(script$J), {
          expandedKeys: expandedKeys.value,
          "onUpdate:expandedKeys": _cache[0] || (_cache[0] = ($event) => expandedKeys.value = $event),
          selectionKeys: selectionKeys.value,
          "onUpdate:selectionKeys": _cache[1] || (_cache[1] = ($event) => selectionKeys.value = $event),
          class: normalizeClass(["tree-explorer py-0 px-2 2xl:px-4", props.class]),
          value: renderedRoot.value.children,
          "selection-mode": "single",
          pt: {
            nodeLabel: "tree-explorer-node-label",
            nodeContent: /* @__PURE__ */ __name(({ context }) => ({
              class: "group/tree-node",
              onClick: /* @__PURE__ */ __name((e2) => onNodeContentClick(e2, context.node), "onClick"),
              onContextmenu: /* @__PURE__ */ __name((e2) => handleContextMenu(e2, context.node), "onContextmenu")
            }), "nodeContent"),
            nodeToggleButton: /* @__PURE__ */ __name(() => ({
              onClick: /* @__PURE__ */ __name((e2) => {
                e2.stopImmediatePropagation();
              }, "onClick")
            }), "nodeToggleButton")
          }
        }, {
          folder: withCtx(({ node: node2 }) => [
            renderSlot(_ctx.$slots, "folder", { node: node2 }, () => [
              createVNode(TreeExplorerTreeNode, { node: node2 }, null, 8, ["node"])
            ], true)
          ]),
          node: withCtx(({ node: node2 }) => [
            renderSlot(_ctx.$slots, "node", { node: node2 }, () => [
              createVNode(TreeExplorerTreeNode, { node: node2 }, null, 8, ["node"])
            ], true)
          ]),
          _: 3
        }, 8, ["expandedKeys", "selectionKeys", "class", "value", "pt"]),
        createVNode(unref(script$K), {
          ref_key: "menu",
          ref: menu2,
          model: menuItems.value
        }, null, 8, ["model"])
      ], 64);
    };
  }
});
const TreeExplorer = /* @__PURE__ */ _export_sfc(_sfc_main$n, [["__scopeId", "data-v-57e059d6"]]);
const _hoisted_1$e = { class: "comfy-vue-side-bar-header" };
const _hoisted_2$c = ["title"];
const _hoisted_3$7 = { class: "flex flex-row motion-safe:w-0 motion-safe:opacity-0 motion-safe:group-hover/sidebar-tab:w-auto motion-safe:group-hover/sidebar-tab:opacity-100 motion-safe:group-focus-within/sidebar-tab:w-auto motion-safe:group-focus-within/sidebar-tab:opacity-100 touch:w-auto touch:opacity-100 transition-all duration-200" };
const _sfc_main$m = /* @__PURE__ */ defineComponent({
  __name: "SidebarTabTemplate",
  props: {
    title: {},
    class: {}
  },
  setup(__props) {
    const props = __props;
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", {
        class: normalizeClass(["comfy-vue-side-bar-container flex flex-col h-full group/sidebar-tab", props.class])
      }, [
        createBaseVNode("div", _hoisted_1$e, [
          createVNode(unref(script$L), { class: "border-x-0 border-t-0 rounded-none px-2 py-1 min-h-8" }, {
            start: withCtx(() => [
              createBaseVNode("span", {
                class: "text-xs 2xl:text-sm truncate",
                title: props.title
              }, toDisplayString(props.title.toUpperCase()), 9, _hoisted_2$c)
            ]),
            end: withCtx(() => [
              createBaseVNode("div", _hoisted_3$7, [
                renderSlot(_ctx.$slots, "tool-buttons", {}, void 0, true)
              ])
            ]),
            _: 3
          }),
          renderSlot(_ctx.$slots, "header", {}, void 0, true)
        ]),
        createVNode(unref(script$7), { class: "comfy-vue-side-bar-body flex-grow h-0" }, {
          default: withCtx(() => [
            renderSlot(_ctx.$slots, "body", {}, void 0, true)
          ]),
          _: 3
        })
      ], 2);
    };
  }
});
const SidebarTabTemplate = /* @__PURE__ */ _export_sfc(_sfc_main$m, [["__scopeId", "data-v-432f0956"]]);
const _hoisted_1$d = { class: "flex flex-col" };
const _hoisted_2$b = { key: 0 };
const _hoisted_3$6 = {
  key: 1,
  class: "mt-2 flex flex-row items-center gap-2"
};
const _sfc_main$l = /* @__PURE__ */ defineComponent({
  __name: "DownloadItem",
  props: {
    download: {}
  },
  setup(__props) {
    const { t: t2 } = useI18n();
    const electronDownloadStore = useElectronDownloadStore();
    const props = __props;
    const getDownloadLabel = /* @__PURE__ */ __name((savePath) => {
      let parts2 = savePath.split("/");
      parts2 = parts2.length === 1 ? parts2[0].split("\\") : parts2;
      const name2 = parts2.pop();
      const dir = parts2.pop();
      return `${dir}/${name2}`;
    }, "getDownloadLabel");
    const triggerCancelDownload = /* @__PURE__ */ __name(() => electronDownloadStore.cancel(props.download.url), "triggerCancelDownload");
    const triggerPauseDownload = /* @__PURE__ */ __name(() => electronDownloadStore.pause(props.download.url), "triggerPauseDownload");
    const triggerResumeDownload = /* @__PURE__ */ __name(() => electronDownloadStore.resume(props.download.url), "triggerResumeDownload");
    const handleRemoveDownload = /* @__PURE__ */ __name(() => {
      electronDownloadStore.$patch((state) => {
        state.downloads = state.downloads.filter(
          ({ url }) => url !== props.download.url
        );
      });
    }, "handleRemoveDownload");
    return (_ctx, _cache) => {
      const _directive_tooltip = resolveDirective("tooltip");
      return openBlock(), createElementBlock("div", _hoisted_1$d, [
        createBaseVNode("div", null, toDisplayString(getDownloadLabel(_ctx.download.savePath ?? "")), 1),
        ["cancelled", "error"].includes(_ctx.download.status ?? "") ? (openBlock(), createElementBlock("div", _hoisted_2$b, [
          createVNode(unref(script$k), {
            class: "h-6 text-sm font-light bg-red-700 mt-2",
            removable: "",
            onRemove: handleRemoveDownload
          }, {
            default: withCtx(() => [
              createTextVNode(toDisplayString(unref(t2)("electronFileDownload.cancelled")), 1)
            ]),
            _: 1
          })
        ])) : createCommentVNode("", true),
        ["in_progress", "paused", "completed"].includes(_ctx.download.status ?? "") ? (openBlock(), createElementBlock("div", _hoisted_3$6, [
          createVNode(unref(script$h), {
            class: "flex-1",
            value: Number(((_ctx.download.progress ?? 0) * 100).toFixed(1)),
            "show-value": (_ctx.download.progress ?? 0) > 0.1
          }, null, 8, ["value", "show-value"]),
          _ctx.download.status === "in_progress" ? withDirectives((openBlock(), createBlock(unref(script$6), {
            key: 0,
            class: "file-action-button w-[22px] h-[22px]",
            size: "small",
            rounded: "",
            icon: "pi pi-pause",
            onClick: triggerPauseDownload
          }, null, 512)), [
            [
              _directive_tooltip,
              unref(t2)("electronFileDownload.pause"),
              void 0,
              { top: true }
            ]
          ]) : createCommentVNode("", true),
          _ctx.download.status === "paused" ? withDirectives((openBlock(), createBlock(unref(script$6), {
            key: 1,
            class: "file-action-button w-[22px] h-[22px]",
            size: "small",
            rounded: "",
            icon: "pi pi-play",
            onClick: triggerResumeDownload
          }, null, 512)), [
            [
              _directive_tooltip,
              unref(t2)("electronFileDownload.resume"),
              void 0,
              { top: true }
            ]
          ]) : createCommentVNode("", true),
          ["in_progress", "paused"].includes(_ctx.download.status ?? "") ? withDirectives((openBlock(), createBlock(unref(script$6), {
            key: 2,
            class: "file-action-button w-[22px] h-[22px] p-red",
            size: "small",
            rounded: "",
            severity: "danger",
            icon: "pi pi-times-circle",
            onClick: triggerCancelDownload
          }, null, 512)), [
            [
              _directive_tooltip,
              unref(t2)("electronFileDownload.cancel"),
              void 0,
              { top: true }
            ]
          ]) : createCommentVNode("", true)
        ])) : createCommentVNode("", true)
      ]);
    };
  }
});
const _hoisted_1$c = {
  key: 0,
  class: "mx-6 mb-4"
};
const _hoisted_2$a = { class: "text-lg my-4" };
const _sfc_main$k = /* @__PURE__ */ defineComponent({
  __name: "ElectronDownloadItems",
  setup(__props) {
    const electronDownloadStore = useElectronDownloadStore();
    const { inProgressDownloads } = storeToRefs(electronDownloadStore);
    return (_ctx, _cache) => {
      return unref(inProgressDownloads).length > 0 ? (openBlock(), createElementBlock("div", _hoisted_1$c, [
        createBaseVNode("div", _hoisted_2$a, toDisplayString(_ctx.$t("electronFileDownload.inProgress")), 1),
        (openBlock(true), createElementBlock(Fragment$1, null, renderList(unref(inProgressDownloads), (download2) => {
          return openBlock(), createBlock(_sfc_main$l, {
            key: download2.url,
            download: download2
          }, null, 8, ["download"]);
        }), 128))
      ])) : createCommentVNode("", true);
    };
  }
});
const _hoisted_1$b = { class: "model_preview" };
const _hoisted_2$9 = { class: "model_preview_title" };
const _hoisted_3$5 = { class: "model_preview_top_container" };
const _hoisted_4$3 = { class: "model_preview_filename" };
const _hoisted_5$3 = {
  key: 0,
  class: "model_preview_architecture"
};
const _hoisted_6$2 = {
  key: 1,
  class: "model_preview_author"
};
const _hoisted_7$1 = {
  key: 0,
  class: "model_preview_image"
};
const _hoisted_8$1 = ["src"];
const _hoisted_9$1 = {
  key: 1,
  class: "model_preview_usage_hint"
};
const _hoisted_10$1 = {
  key: 2,
  class: "model_preview_trigger_phrase"
};
const _hoisted_11$1 = {
  key: 3,
  class: "model_preview_description"
};
const _sfc_main$j = /* @__PURE__ */ defineComponent({
  __name: "ModelPreview",
  props: {
    modelDef: {
      type: ComfyModelDef,
      required: true
    }
  },
  setup(__props) {
    const props = __props;
    const modelDef = props.modelDef;
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", _hoisted_1$b, [
        createBaseVNode("div", _hoisted_2$9, toDisplayString(unref(modelDef).title), 1),
        createBaseVNode("div", _hoisted_3$5, [
          createBaseVNode("div", _hoisted_4$3, toDisplayString(unref(modelDef).file_name), 1),
          unref(modelDef).architecture_id ? (openBlock(), createElementBlock("div", _hoisted_5$3, [
            _cache[0] || (_cache[0] = createBaseVNode("span", { class: "model_preview_prefix" }, "Architecture: ", -1)),
            createTextVNode(" " + toDisplayString(unref(modelDef).architecture_id), 1)
          ])) : createCommentVNode("", true),
          unref(modelDef).author ? (openBlock(), createElementBlock("div", _hoisted_6$2, [
            _cache[1] || (_cache[1] = createBaseVNode("span", { class: "model_preview_prefix" }, "Author: ", -1)),
            createTextVNode(" " + toDisplayString(unref(modelDef).author), 1)
          ])) : createCommentVNode("", true)
        ]),
        unref(modelDef).image ? (openBlock(), createElementBlock("div", _hoisted_7$1, [
          createBaseVNode("img", {
            src: unref(modelDef).image
          }, null, 8, _hoisted_8$1)
        ])) : createCommentVNode("", true),
        unref(modelDef).usage_hint ? (openBlock(), createElementBlock("div", _hoisted_9$1, [
          _cache[2] || (_cache[2] = createBaseVNode("span", { class: "model_preview_prefix" }, "Usage hint: ", -1)),
          createTextVNode(" " + toDisplayString(unref(modelDef).usage_hint), 1)
        ])) : createCommentVNode("", true),
        unref(modelDef).trigger_phrase ? (openBlock(), createElementBlock("div", _hoisted_10$1, [
          _cache[3] || (_cache[3] = createBaseVNode("span", { class: "model_preview_prefix" }, "Trigger phrase: ", -1)),
          createTextVNode(" " + toDisplayString(unref(modelDef).trigger_phrase), 1)
        ])) : createCommentVNode("", true),
        unref(modelDef).description ? (openBlock(), createElementBlock("div", _hoisted_11$1, [
          _cache[4] || (_cache[4] = createBaseVNode("span", { class: "model_preview_prefix" }, "Description: ", -1)),
          createTextVNode(" " + toDisplayString(unref(modelDef).description), 1)
        ])) : createCommentVNode("", true)
      ]);
    };
  }
});
const ModelPreview = /* @__PURE__ */ _export_sfc(_sfc_main$j, [["__scopeId", "data-v-80dc402b"]]);
const _hoisted_1$a = {
  key: 0,
  class: "model-lib-model-icon-container"
};
const _sfc_main$i = /* @__PURE__ */ defineComponent({
  __name: "ModelTreeLeaf",
  props: {
    node: {}
  },
  setup(__props) {
    const props = __props;
    const modelDef = computed(() => props.node.data);
    const modelPreviewUrl = computed(() => {
      if (modelDef.value.image) {
        return modelDef.value.image;
      }
      const folder = modelDef.value.directory;
      const path_index = modelDef.value.path_index;
      const extension = modelDef.value.file_name.split(".").pop();
      const filename = modelDef.value.file_name.replace(`.${extension}`, ".webp");
      const encodedFilename = encodeURIComponent(filename).replace(/%2F/g, "/");
      return `/api/experiment/models/preview/${folder}/${path_index}/${encodedFilename}`;
    });
    const previewRef = ref$3(null);
    const modelPreviewStyle = ref$3({
      position: "absolute",
      top: "0px",
      left: "0px"
    });
    const settingStore = useSettingStore();
    const sidebarLocation = computed(
      () => settingStore.get("Comfy.Sidebar.Location")
    );
    const handleModelHover = /* @__PURE__ */ __name(async () => {
      const hoverTarget = modelContentElement.value;
      if (!hoverTarget) return;
      const targetRect = hoverTarget.getBoundingClientRect();
      const previewHeight = previewRef.value?.$el.offsetHeight || 0;
      const availableSpaceBelow = window.innerHeight - targetRect.bottom;
      modelPreviewStyle.value.top = previewHeight > availableSpaceBelow ? `${Math.max(0, targetRect.top - (previewHeight - availableSpaceBelow) - 20)}px` : `${targetRect.top - 40}px`;
      if (sidebarLocation.value === "left") {
        modelPreviewStyle.value.left = `${targetRect.right}px`;
      } else {
        modelPreviewStyle.value.left = `${targetRect.left - 400}px`;
      }
      await modelDef.value.load();
    }, "handleModelHover");
    const container = ref$3();
    const modelContentElement = ref$3();
    const isHovered = ref$3(false);
    const showPreview = computed(() => {
      return isHovered.value && modelDef.value && modelDef.value.has_loaded_metadata && (modelDef.value.author || modelDef.value.simplified_file_name != modelDef.value.title || modelDef.value.description || modelDef.value.usage_hint || modelDef.value.trigger_phrase || modelDef.value.image);
    });
    const handleMouseEnter = /* @__PURE__ */ __name(async () => {
      isHovered.value = true;
      await nextTick();
      await handleModelHover();
    }, "handleMouseEnter");
    const handleMouseLeave2 = /* @__PURE__ */ __name(() => {
      isHovered.value = false;
    }, "handleMouseLeave");
    onMounted(async () => {
      modelContentElement.value = container.value?.closest(".p-tree-node-content") ?? void 0;
      modelContentElement.value?.addEventListener("mouseenter", handleMouseEnter);
      modelContentElement.value?.addEventListener("mouseleave", handleMouseLeave2);
      await modelDef.value.load();
    });
    onUnmounted(() => {
      modelContentElement.value?.removeEventListener("mouseenter", handleMouseEnter);
      modelContentElement.value?.removeEventListener("mouseleave", handleMouseLeave2);
    });
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", {
        ref_key: "container",
        ref: container,
        class: "model-lib-node-container h-full w-full"
      }, [
        createVNode(TreeExplorerTreeNode, { node: _ctx.node }, {
          "before-label": withCtx(() => [
            modelPreviewUrl.value ? (openBlock(), createElementBlock("span", _hoisted_1$a, [
              createBaseVNode("span", {
                class: "model-lib-model-icon",
                style: normalizeStyle({ backgroundImage: `url(${modelPreviewUrl.value})` })
              }, null, 4)
            ])) : createCommentVNode("", true)
          ]),
          _: 1
        }, 8, ["node"]),
        showPreview.value ? (openBlock(), createBlock(Teleport, {
          key: 0,
          to: "#model-library-model-preview-container"
        }, [
          createBaseVNode("div", {
            class: "model-lib-model-preview",
            style: normalizeStyle(modelPreviewStyle.value)
          }, [
            createVNode(ModelPreview, {
              ref_key: "previewRef",
              ref: previewRef,
              "model-def": modelDef.value
            }, null, 8, ["model-def"])
          ], 4)
        ])) : createCommentVNode("", true)
      ], 512);
    };
  }
});
const ModelTreeLeaf = /* @__PURE__ */ _export_sfc(_sfc_main$i, [["__scopeId", "data-v-d71bb40d"]]);
function useTreeExpansion(expandedKeys) {
  const toggleNode2 = /* @__PURE__ */ __name((node2) => {
    if (node2.key && typeof node2.key === "string") {
      if (node2.key in expandedKeys.value) {
        delete expandedKeys.value[node2.key];
      } else {
        expandedKeys.value[node2.key] = true;
      }
    }
  }, "toggleNode");
  const toggleNodeRecursive = /* @__PURE__ */ __name((node2) => {
    if (node2.key && typeof node2.key === "string") {
      if (node2.key in expandedKeys.value) {
        collapseNode(node2);
      } else {
        expandNode(node2);
      }
    }
  }, "toggleNodeRecursive");
  const expandNode = /* @__PURE__ */ __name((node2) => {
    if (node2.key && typeof node2.key === "string" && !node2.leaf) {
      expandedKeys.value[node2.key] = true;
      for (const child2 of node2.children ?? []) {
        expandNode(child2);
      }
    }
  }, "expandNode");
  const collapseNode = /* @__PURE__ */ __name((node2) => {
    if (node2.key && typeof node2.key === "string" && !node2.leaf) {
      delete expandedKeys.value[node2.key];
      for (const child2 of node2.children ?? []) {
        collapseNode(child2);
      }
    }
  }, "collapseNode");
  const toggleNodeOnEvent = /* @__PURE__ */ __name((e2, node2) => {
    if (e2.ctrlKey) {
      toggleNodeRecursive(node2);
    } else {
      toggleNode2(node2);
    }
  }, "toggleNodeOnEvent");
  return {
    toggleNode: toggleNode2,
    toggleNodeRecursive,
    expandNode,
    collapseNode,
    toggleNodeOnEvent
  };
}
__name(useTreeExpansion, "useTreeExpansion");
class ModelNodeProvider {
  static {
    __name(this, "ModelNodeProvider");
  }
  /** The node definition to use for this model. */
  nodeDef;
  /** The node input key for where to inside the model name. */
  key;
  constructor(nodeDef, key) {
    this.nodeDef = nodeDef;
    this.key = key;
  }
}
const useModelToNodeStore = /* @__PURE__ */ defineStore("modelToNode", () => {
  const modelToNodeMap = ref$3({});
  const nodeDefStore = useNodeDefStore();
  const haveDefaultsLoaded = ref$3(false);
  function getNodeProvider(modelType) {
    registerDefaults();
    return modelToNodeMap.value[modelType]?.[0];
  }
  __name(getNodeProvider, "getNodeProvider");
  function getAllNodeProviders(modelType) {
    registerDefaults();
    return modelToNodeMap.value[modelType] ?? [];
  }
  __name(getAllNodeProviders, "getAllNodeProviders");
  function registerNodeProvider(modelType, nodeProvider) {
    registerDefaults();
    if (!modelToNodeMap.value[modelType]) {
      modelToNodeMap.value[modelType] = [];
    }
    modelToNodeMap.value[modelType].push(nodeProvider);
  }
  __name(registerNodeProvider, "registerNodeProvider");
  function quickRegister(modelType, nodeClass, key) {
    registerNodeProvider(
      modelType,
      new ModelNodeProvider(nodeDefStore.nodeDefsByName[nodeClass], key)
    );
  }
  __name(quickRegister, "quickRegister");
  function registerDefaults() {
    if (haveDefaultsLoaded.value) {
      return;
    }
    if (Object.keys(nodeDefStore.nodeDefsByName).length === 0) {
      return;
    }
    haveDefaultsLoaded.value = true;
    quickRegister("checkpoints", "CheckpointLoaderSimple", "ckpt_name");
    quickRegister("checkpoints", "ImageOnlyCheckpointLoader", "ckpt_name");
    quickRegister("loras", "LoraLoader", "lora_name");
    quickRegister("loras", "LoraLoaderModelOnly", "lora_name");
    quickRegister("vae", "VAELoader", "vae_name");
    quickRegister("controlnet", "ControlNetLoader", "control_net_name");
  }
  __name(registerDefaults, "registerDefaults");
  return {
    modelToNodeMap,
    getNodeProvider,
    getAllNodeProviders,
    registerNodeProvider,
    quickRegister,
    registerDefaults
  };
});
const _sfc_main$h = /* @__PURE__ */ defineComponent({
  __name: "ModelLibrarySidebarTab",
  setup(__props) {
    const modelStore = useModelStore();
    const modelToNodeStore = useModelToNodeStore();
    const settingStore = useSettingStore();
    const searchQuery = ref$3("");
    const expandedKeys = ref$3({});
    const { expandNode, toggleNodeOnEvent } = useTreeExpansion(expandedKeys);
    const filteredModels = ref$3([]);
    const handleSearch = /* @__PURE__ */ __name(async (query2) => {
      if (!query2) {
        filteredModels.value = [];
        expandedKeys.value = {};
        return;
      }
      await modelStore.loadModels();
      const search2 = query2.toLocaleLowerCase();
      filteredModels.value = modelStore.models.filter((model) => {
        return model.searchable.includes(search2);
      });
      await nextTick();
      expandNode(root2.value);
    }, "handleSearch");
    const root2 = computed(() => {
      const allNodes = searchQuery.value ? filteredModels.value : [...modelStore.modelFolders, ...modelStore.models];
      return buildTree$1(
        allNodes,
        (modelOrFolder) => modelOrFolder.key.split("/")
      );
    });
    const renderedRoot = computed(() => {
      const nameFormat = settingStore.get("Comfy.ModelLibrary.NameFormat");
      const fillNodeInfo = /* @__PURE__ */ __name((node2) => {
        const children = node2.children?.map(fillNodeInfo);
        const model = node2.leaf && node2.data ? node2.data : null;
        const folder = !node2.leaf && node2.data ? node2.data : null;
        return {
          key: node2.key,
          label: model ? nameFormat === "title" ? model.title : model.simplified_file_name : node2.label,
          leaf: node2.leaf,
          data: node2.data,
          getIcon() {
            if (model) {
              return model.image ? "pi pi-image" : "pi pi-file";
            }
            if (folder) {
              return folder.state === ResourceState.Loading ? "pi pi-spin pi-spinner" : "pi pi-folder";
            }
            return "pi pi-folder";
          },
          getBadgeText() {
            if (!folder) {
              return;
            }
            return folder.state === ResourceState.Loaded ? void 0 : "";
          },
          children,
          draggable: node2.leaf,
          handleClick(e2) {
            if (this.leaf) {
              const provider = modelToNodeStore.getNodeProvider(model.directory);
              if (provider) {
                const node22 = useLitegraphService().addNodeOnGraph(provider.nodeDef);
                const widget = node22.widgets.find(
                  (widget2) => widget2.name === provider.key
                );
                if (widget) {
                  widget.value = model.file_name;
                }
              }
            } else {
              toggleNodeOnEvent(e2, node2);
            }
          }
        };
      }, "fillNodeInfo");
      return fillNodeInfo(root2.value);
    });
    watch(
      toRef$1(expandedKeys, "value"),
      (newExpandedKeys) => {
        Object.entries(newExpandedKeys).forEach(([key, isExpanded]) => {
          if (isExpanded) {
            const folderPath = key.split("/").slice(1).join("/");
            if (folderPath && !folderPath.includes("/")) {
              void modelStore.getLoadedModelFolder(folderPath);
            }
          }
        });
      },
      { deep: true }
    );
    onMounted(async () => {
      if (settingStore.get("Comfy.ModelLibrary.AutoLoadAll")) {
        await modelStore.loadModels();
      }
    });
    return (_ctx, _cache) => {
      const _directive_tooltip = resolveDirective("tooltip");
      return openBlock(), createElementBlock(Fragment$1, null, [
        createVNode(SidebarTabTemplate, {
          title: _ctx.$t("sideToolbar.modelLibrary"),
          class: "bg-[var(--p-tree-background)]"
        }, {
          "tool-buttons": withCtx(() => [
            withDirectives(createVNode(unref(script$6), {
              icon: "pi pi-refresh",
              severity: "secondary",
              text: "",
              onClick: unref(modelStore).loadModelFolders
            }, null, 8, ["onClick"]), [
              [
                _directive_tooltip,
                _ctx.$t("g.refresh"),
                void 0,
                { bottom: true }
              ]
            ]),
            withDirectives(createVNode(unref(script$6), {
              icon: "pi pi-cloud-download",
              severity: "secondary",
              text: "",
              onClick: unref(modelStore).loadModels
            }, null, 8, ["onClick"]), [
              [
                _directive_tooltip,
                _ctx.$t("g.loadAllFolders"),
                void 0,
                { bottom: true }
              ]
            ])
          ]),
          header: withCtx(() => [
            createVNode(SearchBox, {
              modelValue: searchQuery.value,
              "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => searchQuery.value = $event),
              class: "model-lib-search-box p-2 2xl:p-4",
              placeholder: _ctx.$t("g.searchModels") + "...",
              onSearch: handleSearch
            }, null, 8, ["modelValue", "placeholder"])
          ]),
          body: withCtx(() => [
            unref(isElectron)() ? (openBlock(), createBlock(_sfc_main$k, { key: 0 })) : createCommentVNode("", true),
            createVNode(TreeExplorer, {
              expandedKeys: expandedKeys.value,
              "onUpdate:expandedKeys": _cache[1] || (_cache[1] = ($event) => expandedKeys.value = $event),
              class: "model-lib-tree-explorer",
              root: renderedRoot.value
            }, {
              node: withCtx(({ node: node2 }) => [
                createVNode(ModelTreeLeaf, { node: node2 }, null, 8, ["node"])
              ]),
              _: 1
            }, 8, ["expandedKeys", "root"])
          ]),
          _: 1
        }, 8, ["title"]),
        _cache[2] || (_cache[2] = createBaseVNode("div", { id: "model-library-model-preview-container" }, null, -1))
      ], 64);
    };
  }
});
const ModelLibrarySidebarTab = /* @__PURE__ */ _export_sfc(_sfc_main$h, [["__scopeId", "data-v-9f54e9f7"]]);
const useModelLibrarySidebarTab = /* @__PURE__ */ __name(() => {
  const { t: t2 } = useI18n();
  return {
    id: "model-library",
    icon: "pi pi-box",
    title: t2("sideToolbar.modelLibrary"),
    tooltip: t2("sideToolbar.modelLibrary"),
    component: markRaw(ModelLibrarySidebarTab),
    type: "vue",
    iconBadge: /* @__PURE__ */ __name(() => {
      if (isElectron()) {
        const electronDownloadStore = useElectronDownloadStore();
        if (electronDownloadStore.inProgressDownloads.length > 0) {
          return electronDownloadStore.inProgressDownloads.length.toString();
        }
      }
      return null;
    }, "iconBadge")
  };
}, "useModelLibrarySidebarTab");
const _hoisted_1$9 = { class: "_content" };
const _hoisted_2$8 = { class: "_footer" };
const _sfc_main$g = /* @__PURE__ */ defineComponent({
  __name: "NodeSearchFilter",
  emits: ["addFilter"],
  setup(__props, { emit: __emit }) {
    const filters = computed(() => nodeDefStore.nodeSearchService.nodeFilters);
    const selectedFilter = ref$3();
    const filterValues = computed(() => selectedFilter.value?.fuseSearch.data ?? []);
    const selectedFilterValue = ref$3("");
    const nodeDefStore = useNodeDefStore();
    onMounted(() => {
      selectedFilter.value = nodeDefStore.nodeSearchService.nodeFilters[0];
      updateSelectedFilterValue();
    });
    const emit = __emit;
    const updateSelectedFilterValue = /* @__PURE__ */ __name(() => {
      if (filterValues.value.includes(selectedFilterValue.value)) {
        return;
      }
      selectedFilterValue.value = filterValues.value[0];
    }, "updateSelectedFilterValue");
    const submit = /* @__PURE__ */ __name(() => {
      if (!selectedFilter.value) {
        return;
      }
      emit("addFilter", {
        filterDef: selectedFilter.value,
        value: selectedFilterValue.value
      });
    }, "submit");
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock(Fragment$1, null, [
        createBaseVNode("div", _hoisted_1$9, [
          createVNode(unref(script$I), {
            modelValue: selectedFilter.value,
            "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => selectedFilter.value = $event),
            class: "filter-type-select",
            options: filters.value,
            "allow-empty": false,
            "option-label": "name",
            onChange: updateSelectedFilterValue
          }, null, 8, ["modelValue", "options"]),
          createVNode(unref(script$n), {
            modelValue: selectedFilterValue.value,
            "onUpdate:modelValue": _cache[1] || (_cache[1] = ($event) => selectedFilterValue.value = $event),
            class: "filter-value-select",
            options: filterValues.value,
            filter: "",
            "auto-filter-focus": ""
          }, null, 8, ["modelValue", "options"])
        ]),
        createBaseVNode("div", _hoisted_2$8, [
          createVNode(unref(script$6), {
            type: "button",
            label: _ctx.$t("g.add"),
            onClick: submit
          }, null, 8, ["label"])
        ])
      ], 64);
    };
  }
});
const NodeSearchFilter = /* @__PURE__ */ _export_sfc(_sfc_main$g, [["__scopeId", "data-v-4cebfadd"]]);
const BOOKMARK_SETTING_ID = "Comfy.NodeLibrary.Bookmarks.V2";
const useNodeBookmarkStore = /* @__PURE__ */ defineStore("nodeBookmark", () => {
  const settingStore = useSettingStore();
  const nodeDefStore = useNodeDefStore();
  const bookmarks = computed(
    () => settingStore.get(BOOKMARK_SETTING_ID)
  );
  const bookmarksSet = computed(() => new Set(bookmarks.value));
  const bookmarkedRoot = computed(
    () => buildBookmarkTree(bookmarks.value)
  );
  const isBookmarked = /* @__PURE__ */ __name((node2) => bookmarksSet.value.has(node2.nodePath) || bookmarksSet.value.has(node2.name), "isBookmarked");
  const toggleBookmark = /* @__PURE__ */ __name(async (node2) => {
    if (isBookmarked(node2)) {
      await deleteBookmark(node2.nodePath);
      await deleteBookmark(node2.name);
    } else {
      await addBookmark(node2.name);
    }
  }, "toggleBookmark");
  const buildBookmarkTree = /* @__PURE__ */ __name((bookmarks2) => {
    const bookmarkNodes = bookmarks2.map((bookmark) => {
      if (bookmark.endsWith("/")) return createDummyFolderNodeDef(bookmark);
      const parts2 = bookmark.split("/");
      const name2 = parts2.pop() ?? "";
      const category = parts2.join("/");
      const srcNodeDef = nodeDefStore.nodeDefsByName[name2];
      if (!srcNodeDef) {
        return null;
      }
      const nodeDef = _.clone(srcNodeDef);
      nodeDef.category = category;
      return nodeDef;
    }).filter((nodeDef) => nodeDef !== null);
    return buildNodeDefTree(bookmarkNodes);
  }, "buildBookmarkTree");
  const addBookmark = /* @__PURE__ */ __name(async (nodePath) => {
    await settingStore.set(BOOKMARK_SETTING_ID, [...bookmarks.value, nodePath]);
  }, "addBookmark");
  const deleteBookmark = /* @__PURE__ */ __name(async (nodePath) => {
    await settingStore.set(
      BOOKMARK_SETTING_ID,
      bookmarks.value.filter((b2) => b2 !== nodePath)
    );
  }, "deleteBookmark");
  const addNewBookmarkFolder = /* @__PURE__ */ __name(async (parent2, folderName) => {
    const parentPath = parent2 ? parent2.nodePath : "";
    const newFolderPath = parentPath + folderName + "/";
    await addBookmark(newFolderPath);
    return newFolderPath;
  }, "addNewBookmarkFolder");
  const renameBookmarkFolder = /* @__PURE__ */ __name(async (folderNode, newName) => {
    if (!folderNode.isDummyFolder) {
      throw new Error("Cannot rename non-folder node");
    }
    if (newName.includes("/")) {
      throw new Error('Folder name cannot contain "/"');
    }
    const newNodePath = folderNode.category.split("/").slice(0, -1).concat(newName).join("/") + "/";
    if (newNodePath === folderNode.nodePath) {
      return;
    }
    if (bookmarks.value.some((b2) => b2.startsWith(newNodePath))) {
      throw new Error(`Folder name "${newNodePath}" already exists`);
    }
    await settingStore.set(
      BOOKMARK_SETTING_ID,
      bookmarks.value.map(
        (b2) => b2.startsWith(folderNode.nodePath) ? b2.replace(folderNode.nodePath, newNodePath) : b2
      )
    );
    await renameBookmarkCustomization(folderNode.nodePath, newNodePath);
  }, "renameBookmarkFolder");
  const deleteBookmarkFolder = /* @__PURE__ */ __name(async (folderNode) => {
    if (!folderNode.isDummyFolder) {
      throw new Error("Cannot delete non-folder node");
    }
    await settingStore.set(
      BOOKMARK_SETTING_ID,
      bookmarks.value.filter(
        (b2) => b2 !== folderNode.nodePath && !b2.startsWith(folderNode.nodePath)
      )
    );
    await deleteBookmarkCustomization(folderNode.nodePath);
  }, "deleteBookmarkFolder");
  const bookmarksCustomization = computed(() => settingStore.get("Comfy.NodeLibrary.BookmarksCustomization"));
  const updateBookmarkCustomization = /* @__PURE__ */ __name(async (nodePath, customization) => {
    const currentCustomization = bookmarksCustomization.value[nodePath] || {};
    const newCustomization = { ...currentCustomization, ...customization };
    if (newCustomization.icon === defaultBookmarkIcon) {
      delete newCustomization.icon;
    }
    if (newCustomization.color === defaultBookmarkColor) {
      delete newCustomization.color;
    }
    if (Object.keys(newCustomization).length === 0) {
      await deleteBookmarkCustomization(nodePath);
    } else {
      await settingStore.set("Comfy.NodeLibrary.BookmarksCustomization", {
        ...bookmarksCustomization.value,
        [nodePath]: newCustomization
      });
    }
  }, "updateBookmarkCustomization");
  const deleteBookmarkCustomization = /* @__PURE__ */ __name(async (nodePath) => {
    await settingStore.set("Comfy.NodeLibrary.BookmarksCustomization", {
      ...bookmarksCustomization.value,
      [nodePath]: void 0
    });
  }, "deleteBookmarkCustomization");
  const renameBookmarkCustomization = /* @__PURE__ */ __name(async (oldNodePath, newNodePath) => {
    const updatedCustomization = { ...bookmarksCustomization.value };
    if (updatedCustomization[oldNodePath]) {
      updatedCustomization[newNodePath] = updatedCustomization[oldNodePath];
      delete updatedCustomization[oldNodePath];
    }
    await settingStore.set(
      "Comfy.NodeLibrary.BookmarksCustomization",
      updatedCustomization
    );
  }, "renameBookmarkCustomization");
  const defaultBookmarkIcon = "pi-bookmark-fill";
  const defaultBookmarkColor = "#a1a1aa";
  return {
    bookmarks,
    bookmarkedRoot,
    isBookmarked,
    toggleBookmark,
    addBookmark,
    addNewBookmarkFolder,
    renameBookmarkFolder,
    deleteBookmarkFolder,
    bookmarksCustomization,
    updateBookmarkCustomization,
    deleteBookmarkCustomization,
    renameBookmarkCustomization,
    defaultBookmarkIcon,
    defaultBookmarkColor
  };
});
const _sfc_main$f = /* @__PURE__ */ defineComponent({
  __name: "NodeTreeLeaf",
  props: {
    node: {}
  },
  setup(__props) {
    const props = __props;
    const nodeDef = computed(() => props.node.data);
    const nodeBookmarkStore = useNodeBookmarkStore();
    const isBookmarked = computed(
      () => nodeBookmarkStore.isBookmarked(nodeDef.value)
    );
    const settingStore = useSettingStore();
    const sidebarLocation = computed(
      () => settingStore.get("Comfy.Sidebar.Location")
    );
    const toggleBookmark = /* @__PURE__ */ __name(async () => {
      await nodeBookmarkStore.toggleBookmark(nodeDef.value);
    }, "toggleBookmark");
    const previewRef = ref$3(null);
    const nodePreviewStyle = ref$3({
      position: "absolute",
      top: "0px",
      left: "0px"
    });
    const handleNodeHover = /* @__PURE__ */ __name(async () => {
      const hoverTarget = nodeContentElement.value;
      if (!hoverTarget) return;
      const targetRect = hoverTarget.getBoundingClientRect();
      const previewHeight = previewRef.value?.$el.offsetHeight || 0;
      const availableSpaceBelow = window.innerHeight - targetRect.bottom;
      nodePreviewStyle.value.top = previewHeight > availableSpaceBelow ? `${Math.max(0, targetRect.top - (previewHeight - availableSpaceBelow) - 20)}px` : `${targetRect.top - 40}px`;
      if (sidebarLocation.value === "left") {
        nodePreviewStyle.value.left = `${targetRect.right}px`;
      } else {
        nodePreviewStyle.value.left = `${targetRect.left - 400}px`;
      }
    }, "handleNodeHover");
    const container = ref$3(null);
    const nodeContentElement = ref$3(null);
    const isHovered = ref$3(false);
    const handleMouseEnter = /* @__PURE__ */ __name(async () => {
      isHovered.value = true;
      await nextTick();
      await handleNodeHover();
    }, "handleMouseEnter");
    const handleMouseLeave2 = /* @__PURE__ */ __name(() => {
      isHovered.value = false;
    }, "handleMouseLeave");
    onMounted(() => {
      nodeContentElement.value = container.value?.closest(".p-tree-node-content") ?? null;
      nodeContentElement.value?.addEventListener("mouseenter", handleMouseEnter);
      nodeContentElement.value?.addEventListener("mouseleave", handleMouseLeave2);
    });
    onUnmounted(() => {
      nodeContentElement.value?.removeEventListener("mouseenter", handleMouseEnter);
      nodeContentElement.value?.removeEventListener("mouseleave", handleMouseLeave2);
    });
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", {
        ref_key: "container",
        ref: container,
        class: "node-lib-node-container"
      }, [
        createVNode(TreeExplorerTreeNode, { node: _ctx.node }, {
          "before-label": withCtx(() => [
            nodeDef.value.experimental ? (openBlock(), createBlock(unref(script$5), {
              key: 0,
              value: _ctx.$t("g.experimental"),
              severity: "primary"
            }, null, 8, ["value"])) : createCommentVNode("", true),
            nodeDef.value.deprecated ? (openBlock(), createBlock(unref(script$5), {
              key: 1,
              value: _ctx.$t("g.deprecated"),
              severity: "danger"
            }, null, 8, ["value"])) : createCommentVNode("", true)
          ]),
          actions: withCtx(() => [
            createVNode(unref(script$6), {
              class: "bookmark-button",
              size: "small",
              icon: isBookmarked.value ? "pi pi-bookmark-fill" : "pi pi-bookmark",
              text: "",
              severity: "secondary",
              onClick: withModifiers(toggleBookmark, ["stop"])
            }, null, 8, ["icon"])
          ]),
          _: 1
        }, 8, ["node"]),
        isHovered.value ? (openBlock(), createBlock(Teleport, {
          key: 0,
          to: "#node-library-node-preview-container"
        }, [
          createBaseVNode("div", {
            class: "node-lib-node-preview",
            style: normalizeStyle(nodePreviewStyle.value)
          }, [
            createVNode(NodePreview, {
              ref_key: "previewRef",
              ref: previewRef,
              "node-def": nodeDef.value
            }, null, 8, ["node-def"])
          ], 4)
        ])) : createCommentVNode("", true)
      ], 512);
    };
  }
});
const NodeTreeLeaf = /* @__PURE__ */ _export_sfc(_sfc_main$f, [["__scopeId", "data-v-9c454a41"]]);
const _hoisted_1$8 = { class: "color-customization-selector-container flex flex-row items-center gap-2" };
const _hoisted_2$7 = {
  key: 1,
  class: "pi pi-palette text-lg"
};
const _sfc_main$e = /* @__PURE__ */ defineComponent({
  __name: "ColorCustomizationSelector",
  props: {
    modelValue: {},
    colorOptions: {},
    allowCustom: { type: Boolean, default: true }
  },
  emits: ["update:modelValue"],
  setup(__props, { emit: __emit }) {
    const customColorOption = { name: "_custom", value: "" };
    const colorOptionsWithCustom = computed(() => [
      ...__props.colorOptions,
      ...__props.allowCustom ? [customColorOption] : []
    ]);
    const emit = __emit;
    const selectedColorOption = ref$3(customColorOption);
    const customColorValue = ref$3("");
    onMounted(() => {
      if (__props.modelValue) {
        const predefinedColor = __props.colorOptions.find((opt) => opt.value === __props.modelValue);
        if (predefinedColor) {
          selectedColorOption.value = predefinedColor;
        } else {
          selectedColorOption.value = customColorOption;
          customColorValue.value = __props.modelValue.replace("#", "");
        }
      }
    });
    watch(selectedColorOption, (newOption, oldOption) => {
      if (newOption.name === "_custom") {
        customColorValue.value = oldOption.value.replace("#", "");
      } else {
        emit("update:modelValue", newOption.value);
      }
    });
    watch(customColorValue, (newValue2) => {
      if (selectedColorOption.value.name === "_custom") {
        emit("update:modelValue", newValue2 ? `#${newValue2}` : null);
      }
    });
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", _hoisted_1$8, [
        createVNode(unref(script$I), {
          modelValue: selectedColorOption.value,
          "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => selectedColorOption.value = $event),
          options: colorOptionsWithCustom.value,
          "option-label": "name",
          "data-key": "value",
          "allow-empty": false
        }, {
          option: withCtx((slotProps) => [
            slotProps.option.name !== "_custom" ? (openBlock(), createElementBlock("div", {
              key: 0,
              style: normalizeStyle({
                width: "20px",
                height: "20px",
                backgroundColor: slotProps.option.value,
                borderRadius: "50%"
              })
            }, null, 4)) : (openBlock(), createElementBlock("i", _hoisted_2$7))
          ]),
          _: 1
        }, 8, ["modelValue", "options"]),
        selectedColorOption.value.name === "_custom" ? (openBlock(), createBlock(unref(script$p), {
          key: 0,
          modelValue: customColorValue.value,
          "onUpdate:modelValue": _cache[1] || (_cache[1] = ($event) => customColorValue.value = $event)
        }, null, 8, ["modelValue"])) : createCommentVNode("", true)
      ]);
    };
  }
});
const _hoisted_1$7 = { class: "p-fluid" };
const _hoisted_2$6 = { class: "field icon-field" };
const _hoisted_3$4 = { for: "icon" };
const _hoisted_4$2 = { class: "field color-field" };
const _hoisted_5$2 = { for: "color" };
const _sfc_main$d = /* @__PURE__ */ defineComponent({
  __name: "CustomizationDialog",
  props: {
    modelValue: { type: Boolean },
    initialIcon: {},
    initialColor: {}
  },
  emits: ["update:modelValue", "confirm"],
  setup(__props, { emit: __emit }) {
    const { t: t2 } = useI18n();
    const props = __props;
    const emit = __emit;
    const visible = computed({
      get: /* @__PURE__ */ __name(() => props.modelValue, "get"),
      set: /* @__PURE__ */ __name((value) => emit("update:modelValue", value), "set")
    });
    const nodeBookmarkStore = useNodeBookmarkStore();
    const iconOptions = [
      { name: t2("icon.bookmark"), value: nodeBookmarkStore.defaultBookmarkIcon },
      { name: t2("icon.folder"), value: "pi-folder" },
      { name: t2("icon.star"), value: "pi-star" },
      { name: t2("icon.heart"), value: "pi-heart" },
      { name: t2("icon.file"), value: "pi-file" },
      { name: t2("icon.inbox"), value: "pi-inbox" },
      { name: t2("icon.box"), value: "pi-box" },
      { name: t2("icon.briefcase"), value: "pi-briefcase" }
    ];
    const colorOptions = [
      { name: t2("color.default"), value: nodeBookmarkStore.defaultBookmarkColor },
      { name: t2("color.blue"), value: "#007bff" },
      { name: t2("color.green"), value: "#28a745" },
      { name: t2("color.red"), value: "#dc3545" },
      { name: t2("color.pink"), value: "#e83e8c" },
      { name: t2("color.yellow"), value: "#ffc107" }
    ];
    const defaultIcon = iconOptions.find(
      (option) => option.value === nodeBookmarkStore.defaultBookmarkIcon
    );
    const selectedIcon = ref$3(defaultIcon);
    const finalColor = ref$3(
      props.initialColor || nodeBookmarkStore.defaultBookmarkColor
    );
    const resetCustomization = /* @__PURE__ */ __name(() => {
      selectedIcon.value = iconOptions.find((option) => option.value === props.initialIcon) || defaultIcon;
      finalColor.value = props.initialColor || nodeBookmarkStore.defaultBookmarkColor;
    }, "resetCustomization");
    const confirmCustomization = /* @__PURE__ */ __name(() => {
      emit("confirm", selectedIcon.value.value, finalColor.value);
      closeDialog();
    }, "confirmCustomization");
    const closeDialog = /* @__PURE__ */ __name(() => {
      visible.value = false;
    }, "closeDialog");
    watch(
      () => props.modelValue,
      (newValue2) => {
        if (newValue2) {
          resetCustomization();
        }
      },
      { immediate: true }
    );
    return (_ctx, _cache) => {
      return openBlock(), createBlock(unref(script$4), {
        visible: visible.value,
        "onUpdate:visible": _cache[2] || (_cache[2] = ($event) => visible.value = $event),
        header: _ctx.$t("g.customizeFolder")
      }, {
        footer: withCtx(() => [
          createVNode(unref(script$6), {
            label: _ctx.$t("g.reset"),
            icon: "pi pi-refresh",
            class: "p-button-text",
            onClick: resetCustomization
          }, null, 8, ["label"]),
          createVNode(unref(script$6), {
            label: _ctx.$t("g.confirm"),
            icon: "pi pi-check",
            autofocus: "",
            onClick: confirmCustomization
          }, null, 8, ["label"])
        ]),
        default: withCtx(() => [
          createBaseVNode("div", _hoisted_1$7, [
            createBaseVNode("div", _hoisted_2$6, [
              createBaseVNode("label", _hoisted_3$4, toDisplayString(_ctx.$t("g.icon")), 1),
              createVNode(unref(script$I), {
                modelValue: selectedIcon.value,
                "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => selectedIcon.value = $event),
                options: iconOptions,
                "option-label": "name",
                "data-key": "value"
              }, {
                option: withCtx((slotProps) => [
                  createBaseVNode("i", {
                    class: normalizeClass(["pi", slotProps.option.value, "mr-2"]),
                    style: normalizeStyle({ color: finalColor.value })
                  }, null, 6)
                ]),
                _: 1
              }, 8, ["modelValue"])
            ]),
            createVNode(unref(script$f)),
            createBaseVNode("div", _hoisted_4$2, [
              createBaseVNode("label", _hoisted_5$2, toDisplayString(_ctx.$t("g.color")), 1),
              createVNode(_sfc_main$e, {
                modelValue: finalColor.value,
                "onUpdate:modelValue": _cache[1] || (_cache[1] = ($event) => finalColor.value = $event),
                "color-options": colorOptions
              }, null, 8, ["modelValue"])
            ])
          ])
        ]),
        _: 1
      }, 8, ["visible", "header"]);
    };
  }
});
const FolderCustomizationDialog = /* @__PURE__ */ _export_sfc(_sfc_main$d, [["__scopeId", "data-v-1d16d52b"]]);
const _sfc_main$c = /* @__PURE__ */ defineComponent({
  __name: "NodeTreeFolder",
  props: {
    node: {}
  },
  setup(__props) {
    const nodeBookmarkStore = useNodeBookmarkStore();
    const customization = computed(() => {
      const nodeDef = __props.node.data;
      return nodeDef ? nodeBookmarkStore.bookmarksCustomization[nodeDef.nodePath] : void 0;
    });
    const treeNodeElement = ref$3(null);
    const iconElement = ref$3(null);
    let stopWatchCustomization = null;
    const container = ref$3(null);
    onMounted(() => {
      treeNodeElement.value = container.value?.closest(
        ".p-tree-node-content"
      );
      iconElement.value = treeNodeElement.value.querySelector(
        ":scope > .p-tree-node-icon"
      );
      updateIconColor();
      stopWatchCustomization = watch(customization, updateIconColor, { deep: true });
    });
    const updateIconColor = /* @__PURE__ */ __name(() => {
      if (iconElement.value && customization.value) {
        iconElement.value.style.color = customization.value.color ?? "";
      }
    }, "updateIconColor");
    onUnmounted(() => {
      if (stopWatchCustomization) {
        stopWatchCustomization();
      }
    });
    const expandedKeys = inject(InjectKeyExpandedKeys);
    const handleItemDrop = /* @__PURE__ */ __name((node2) => {
      if (!expandedKeys) return;
      expandedKeys.value[node2.key] = true;
    }, "handleItemDrop");
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", {
        ref_key: "container",
        ref: container,
        class: "node-lib-node-container"
      }, [
        createVNode(TreeExplorerTreeNode, {
          node: _ctx.node,
          onItemDropped: handleItemDrop
        }, null, 8, ["node"])
      ], 512);
    };
  }
});
const _sfc_main$b = /* @__PURE__ */ defineComponent({
  __name: "NodeBookmarkTreeExplorer",
  props: {
    filteredNodeDefs: {}
  },
  setup(__props, { expose: __expose }) {
    const props = __props;
    const expandedKeys = ref$3({});
    const { expandNode, toggleNodeOnEvent } = useTreeExpansion(expandedKeys);
    const nodeBookmarkStore = useNodeBookmarkStore();
    const bookmarkedRoot = computed(() => {
      const filterTree = /* @__PURE__ */ __name((node2) => {
        if (node2.leaf) {
          return props.filteredNodeDefs.some((def) => def.name === node2.data.name) ? node2 : null;
        }
        const filteredChildren = node2.children?.map(filterTree).filter((child2) => child2 !== null);
        if (filteredChildren && filteredChildren.length > 0) {
          return {
            ...node2,
            children: filteredChildren
          };
        }
        return null;
      }, "filterTree");
      return props.filteredNodeDefs.length ? filterTree(nodeBookmarkStore.bookmarkedRoot) || {
        key: "root",
        label: "Root",
        children: []
      } : nodeBookmarkStore.bookmarkedRoot;
    });
    watch(
      () => props.filteredNodeDefs,
      async (newValue2) => {
        if (newValue2.length) {
          await nextTick();
          expandNode(bookmarkedRoot.value);
        }
      }
    );
    const { t: t2 } = useI18n();
    const extraMenuItems = /* @__PURE__ */ __name((menuTargetNode) => [
      {
        label: t2("g.customize"),
        icon: "pi pi-palette",
        command: /* @__PURE__ */ __name(() => {
          if (!menuTargetNode.data) return;
          const customization = nodeBookmarkStore.bookmarksCustomization[menuTargetNode.data.nodePath];
          initialIcon.value = customization?.icon || nodeBookmarkStore.defaultBookmarkIcon;
          initialColor.value = customization?.color || nodeBookmarkStore.defaultBookmarkColor;
          showCustomizationDialog.value = true;
          customizationTargetNodePath.value = menuTargetNode.data.nodePath;
        }, "command"),
        visible: !menuTargetNode?.leaf
      }
    ], "extraMenuItems");
    const renderedBookmarkedRoot = computed(
      () => {
        const fillNodeInfo = /* @__PURE__ */ __name((node2) => {
          const children = node2.children?.map(fillNodeInfo);
          const sortedChildren = children?.sort((a2, b2) => {
            if (a2.leaf === b2.leaf) {
              return a2.label.localeCompare(b2.label);
            }
            return a2.leaf ? 1 : -1;
          });
          return {
            key: node2.key,
            label: node2.leaf ? node2.data.display_name : node2.label,
            leaf: node2.leaf,
            data: node2.data,
            getIcon() {
              if (this.leaf) {
                return "pi pi-circle-fill";
              }
              const customization = nodeBookmarkStore.bookmarksCustomization[node2.data?.nodePath];
              return customization?.icon ? "pi " + customization.icon : "pi pi-bookmark-fill";
            },
            children: sortedChildren,
            draggable: node2.leaf,
            async handleAddFolder(newName) {
              if (newName !== "") {
                await nodeBookmarkStore.addNewBookmarkFolder(this.data, newName);
              }
            },
            renderDragPreview(container) {
              const vnode = h$2(NodePreview, { nodeDef: node2.data });
              render$3(vnode, container);
              return () => {
                render$3(null, container);
              };
            },
            droppable: !node2.leaf,
            async handleDrop(data) {
              const nodeDefToAdd = data.data.data;
              if (nodeBookmarkStore.isBookmarked(nodeDefToAdd)) {
                await nodeBookmarkStore.toggleBookmark(nodeDefToAdd);
              }
              const folderNodeDef = node2.data;
              const nodePath = folderNodeDef.category + "/" + nodeDefToAdd.name;
              await nodeBookmarkStore.addBookmark(nodePath);
            },
            handleClick(e2) {
              if (this.leaf) {
                useLitegraphService().addNodeOnGraph(this.data);
              } else {
                toggleNodeOnEvent(e2, node2);
              }
            },
            contextMenuItems: extraMenuItems,
            ...node2.leaf ? {} : {
              async handleRename(newName) {
                if (this.data && this.data.isDummyFolder) {
                  await nodeBookmarkStore.renameBookmarkFolder(
                    this.data,
                    newName
                  );
                }
              },
              async handleDelete() {
                await nodeBookmarkStore.deleteBookmarkFolder(this.data);
              }
            }
          };
        }, "fillNodeInfo");
        return fillNodeInfo(bookmarkedRoot.value);
      }
    );
    const treeExplorerRef = ref$3(null);
    __expose({
      addNewBookmarkFolder: /* @__PURE__ */ __name(() => treeExplorerRef.value?.addFolderCommand("root"), "addNewBookmarkFolder")
    });
    const showCustomizationDialog = ref$3(false);
    const initialIcon = ref$3(nodeBookmarkStore.defaultBookmarkIcon);
    const initialColor = ref$3(nodeBookmarkStore.defaultBookmarkColor);
    const customizationTargetNodePath = ref$3("");
    const updateCustomization = /* @__PURE__ */ __name(async (icon2, color2) => {
      if (customizationTargetNodePath.value) {
        await nodeBookmarkStore.updateBookmarkCustomization(
          customizationTargetNodePath.value,
          { icon: icon2, color: color2 }
        );
      }
    }, "updateCustomization");
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock(Fragment$1, null, [
        createVNode(TreeExplorer, {
          ref_key: "treeExplorerRef",
          ref: treeExplorerRef,
          class: "node-lib-bookmark-tree-explorer",
          root: renderedBookmarkedRoot.value,
          "expanded-keys": expandedKeys.value
        }, {
          folder: withCtx(({ node: node2 }) => [
            createVNode(_sfc_main$c, { node: node2 }, null, 8, ["node"])
          ]),
          node: withCtx(({ node: node2 }) => [
            createVNode(NodeTreeLeaf, { node: node2 }, null, 8, ["node"])
          ]),
          _: 1
        }, 8, ["root", "expanded-keys"]),
        createVNode(FolderCustomizationDialog, {
          modelValue: showCustomizationDialog.value,
          "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => showCustomizationDialog.value = $event),
          "initial-icon": initialIcon.value,
          "initial-color": initialColor.value,
          onConfirm: updateCustomization
        }, null, 8, ["modelValue", "initial-icon", "initial-color"])
      ], 64);
    };
  }
});
const _sfc_main$a = /* @__PURE__ */ defineComponent({
  __name: "NodeLibrarySidebarTab",
  setup(__props) {
    const nodeDefStore = useNodeDefStore();
    const nodeBookmarkStore = useNodeBookmarkStore();
    const expandedKeys = ref$3({});
    const { expandNode, toggleNodeOnEvent } = useTreeExpansion(expandedKeys);
    const nodeBookmarkTreeExplorerRef = ref$3(null);
    const searchFilter = ref$3(null);
    const alphabeticalSort = ref$3(false);
    const searchQuery = ref$3("");
    const root2 = computed(() => {
      const root22 = filteredRoot.value || nodeDefStore.nodeTree;
      return alphabeticalSort.value ? sortedTree(root22, { groupLeaf: true }) : root22;
    });
    const renderedRoot = computed(() => {
      const fillNodeInfo = /* @__PURE__ */ __name((node2) => {
        const children = node2.children?.map(fillNodeInfo);
        return {
          key: node2.key,
          label: node2.leaf ? node2.data.display_name : node2.label,
          leaf: node2.leaf,
          data: node2.data,
          getIcon() {
            if (this.leaf) {
              return "pi pi-circle-fill";
            }
          },
          children,
          draggable: node2.leaf,
          renderDragPreview(container) {
            const vnode = h$2(NodePreview, { nodeDef: node2.data });
            render$3(vnode, container);
            return () => {
              render$3(null, container);
            };
          },
          handleClick(e2) {
            if (this.leaf) {
              useLitegraphService().addNodeOnGraph(this.data);
            } else {
              toggleNodeOnEvent(e2, this);
            }
          }
        };
      }, "fillNodeInfo");
      return fillNodeInfo(root2.value);
    });
    const filteredNodeDefs = ref$3([]);
    const filteredRoot = computed(() => {
      if (!filteredNodeDefs.value.length) {
        return null;
      }
      return buildNodeDefTree(filteredNodeDefs.value);
    });
    const filters = ref$3([]);
    const handleSearch = /* @__PURE__ */ __name(async (query2) => {
      if (query2.length === 0 && !filters.value.length) {
        filteredNodeDefs.value = [];
        expandedKeys.value = {};
        return;
      }
      const f2 = filters.value.map((f22) => f22.filter);
      filteredNodeDefs.value = nodeDefStore.nodeSearchService.searchNode(
        query2,
        f2,
        {
          limit: 64
        },
        {
          matchWildcards: false
        }
      );
      await nextTick();
      expandNode(filteredRoot.value);
    }, "handleSearch");
    const onAddFilter = /* @__PURE__ */ __name(async (filterAndValue) => {
      filters.value.push({
        filter: filterAndValue,
        badge: filterAndValue.filterDef.invokeSequence.toUpperCase(),
        badgeClass: filterAndValue.filterDef.invokeSequence + "-badge",
        text: filterAndValue.value,
        id: +/* @__PURE__ */ new Date()
      });
      await handleSearch(searchQuery.value);
    }, "onAddFilter");
    const onRemoveFilter = /* @__PURE__ */ __name(async (filterAndValue) => {
      const index2 = filters.value.findIndex((f2) => f2 === filterAndValue);
      if (index2 !== -1) {
        filters.value.splice(index2, 1);
      }
      await handleSearch(searchQuery.value);
    }, "onRemoveFilter");
    return (_ctx, _cache) => {
      const _directive_tooltip = resolveDirective("tooltip");
      return openBlock(), createElementBlock(Fragment$1, null, [
        createVNode(SidebarTabTemplate, {
          title: _ctx.$t("sideToolbar.nodeLibrary"),
          class: "bg-[var(--p-tree-background)]"
        }, {
          "tool-buttons": withCtx(() => [
            withDirectives(createVNode(unref(script$6), {
              class: "new-folder-button",
              icon: "pi pi-folder-plus",
              text: "",
              severity: "secondary",
              onClick: _cache[0] || (_cache[0] = ($event) => nodeBookmarkTreeExplorerRef.value?.addNewBookmarkFolder())
            }, null, 512), [
              [
                _directive_tooltip,
                _ctx.$t("g.newFolder"),
                void 0,
                { bottom: true }
              ]
            ]),
            withDirectives(createVNode(unref(script$6), {
              class: "sort-button",
              icon: alphabeticalSort.value ? "pi pi-sort-alpha-down" : "pi pi-sort-alt",
              text: "",
              severity: "secondary",
              onClick: _cache[1] || (_cache[1] = ($event) => alphabeticalSort.value = !alphabeticalSort.value)
            }, null, 8, ["icon"]), [
              [
                _directive_tooltip,
                _ctx.$t("sideToolbar.nodeLibraryTab.sortOrder"),
                void 0,
                { bottom: true }
              ]
            ])
          ]),
          header: withCtx(() => [
            createVNode(SearchBox, {
              modelValue: searchQuery.value,
              "onUpdate:modelValue": _cache[2] || (_cache[2] = ($event) => searchQuery.value = $event),
              class: "node-lib-search-box p-2 2xl:p-4",
              placeholder: _ctx.$t("g.searchNodes") + "...",
              "filter-icon": "pi pi-filter",
              filters: filters.value,
              onSearch: handleSearch,
              onShowFilter: _cache[3] || (_cache[3] = ($event) => searchFilter.value?.toggle($event)),
              onRemoveFilter
            }, null, 8, ["modelValue", "placeholder", "filters"]),
            createVNode(unref(script$z), {
              ref_key: "searchFilter",
              ref: searchFilter,
              class: "ml-[-13px]"
            }, {
              default: withCtx(() => [
                createVNode(NodeSearchFilter, { onAddFilter })
              ]),
              _: 1
            }, 512)
          ]),
          body: withCtx(() => [
            createVNode(_sfc_main$b, {
              ref_key: "nodeBookmarkTreeExplorerRef",
              ref: nodeBookmarkTreeExplorerRef,
              "filtered-node-defs": filteredNodeDefs.value
            }, null, 8, ["filtered-node-defs"]),
            withDirectives(createVNode(unref(script$f), {
              type: "dashed",
              class: "m-2"
            }, null, 512), [
              [vShow, unref(nodeBookmarkStore).bookmarks.length > 0]
            ]),
            createVNode(TreeExplorer, {
              expandedKeys: expandedKeys.value,
              "onUpdate:expandedKeys": _cache[4] || (_cache[4] = ($event) => expandedKeys.value = $event),
              class: "node-lib-tree-explorer",
              root: renderedRoot.value
            }, {
              node: withCtx(({ node: node2 }) => [
                createVNode(NodeTreeLeaf, { node: node2 }, null, 8, ["node"])
              ]),
              _: 1
            }, 8, ["expandedKeys", "root"])
          ]),
          _: 1
        }, 8, ["title"]),
        _cache[5] || (_cache[5] = createBaseVNode("div", { id: "node-library-node-preview-container" }, null, -1))
      ], 64);
    };
  }
});
const useNodeLibrarySidebarTab = /* @__PURE__ */ __name(() => {
  const { t: t2 } = useI18n();
  return {
    id: "node-library",
    icon: "pi pi-book",
    title: t2("sideToolbar.nodeLibrary"),
    tooltip: t2("sideToolbar.nodeLibrary"),
    component: markRaw(_sfc_main$a),
    type: "vue"
  };
}, "useNodeLibrarySidebarTab");
const _hoisted_1$6 = ["src", "data-test", "alt"];
const _hoisted_2$5 = ["src", "alt"];
const _hoisted_3$3 = {
  key: 1,
  class: "broken-image-placeholder"
};
const _sfc_main$9 = /* @__PURE__ */ defineComponent({
  __name: "ComfyImage",
  props: {
    src: {},
    class: {},
    contain: { type: Boolean, default: false },
    alt: { default: "Image content" }
  },
  setup(__props) {
    const imageBroken = ref$3(false);
    const handleImageError = /* @__PURE__ */ __name(() => {
      imageBroken.value = true;
    }, "handleImageError");
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock(Fragment$1, null, [
        !imageBroken.value ? (openBlock(), createElementBlock("span", {
          key: 0,
          class: normalizeClass(["comfy-image-wrap", [{ contain: _ctx.contain }]])
        }, [
          _ctx.contain ? (openBlock(), createElementBlock("img", {
            key: 0,
            src: _ctx.src,
            "data-test": _ctx.src,
            class: "comfy-image-blur",
            style: normalizeStyle({ "background-image": `url(${_ctx.src})` }),
            alt: _ctx.alt,
            onError: handleImageError
          }, null, 44, _hoisted_1$6)) : createCommentVNode("", true),
          createBaseVNode("img", {
            src: _ctx.src,
            class: normalizeClass(["comfy-image-main", __props.class]),
            alt: _ctx.alt,
            onError: handleImageError
          }, null, 42, _hoisted_2$5)
        ], 2)) : createCommentVNode("", true),
        imageBroken.value ? (openBlock(), createElementBlock("div", _hoisted_3$3, [
          _cache[0] || (_cache[0] = createBaseVNode("i", { class: "pi pi-image" }, null, -1)),
          createBaseVNode("span", null, toDisplayString(_ctx.$t("g.imageFailedToLoad")), 1)
        ])) : createCommentVNode("", true)
      ], 64);
    };
  }
});
const ComfyImage = /* @__PURE__ */ _export_sfc(_sfc_main$9, [["__scopeId", "data-v-8b2eb5c8"]]);
const _hoisted_1$5 = {
  controls: "",
  width: "100%",
  height: "100%"
};
const _hoisted_2$4 = ["src", "type"];
const _sfc_main$8 = /* @__PURE__ */ defineComponent({
  __name: "ResultVideo",
  props: {
    result: {}
  },
  setup(__props) {
    const props = __props;
    const settingStore = useSettingStore();
    const { isExtensionInstalled, isExtensionEnabled } = useExtensionStore();
    const vhsAdvancedPreviews = computed(() => {
      return isExtensionInstalled("VideoHelperSuite.Core") && isExtensionEnabled("VideoHelperSuite.Core") && settingStore.get("VHS.AdvancedPreviews") && settingStore.get("VHS.AdvancedPreviews") !== "Never";
    });
    const url = computed(
      () => vhsAdvancedPreviews.value ? props.result.vhsAdvancedPreviewUrl : props.result.url
    );
    const htmlVideoType = computed(
      () => vhsAdvancedPreviews.value ? "video/webm" : props.result.htmlVideoType
    );
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("video", _hoisted_1$5, [
        createBaseVNode("source", {
          src: url.value,
          type: htmlVideoType.value
        }, null, 8, _hoisted_2$4),
        createTextVNode(" " + toDisplayString(_ctx.$t("g.videoFailedToLoad")), 1)
      ]);
    };
  }
});
const _sfc_main$7 = /* @__PURE__ */ defineComponent({
  __name: "ResultGallery",
  props: {
    allGalleryItems: {},
    activeIndex: {}
  },
  emits: ["update:activeIndex"],
  setup(__props, { emit: __emit }) {
    const galleryVisible = ref$3(false);
    const emit = __emit;
    const props = __props;
    let maskMouseDownTarget = null;
    const onMaskMouseDown = /* @__PURE__ */ __name((event) => {
      maskMouseDownTarget = event.target;
    }, "onMaskMouseDown");
    const onMaskMouseUp = /* @__PURE__ */ __name((event) => {
      const maskEl = document.querySelector("[data-mask]");
      if (galleryVisible.value && maskMouseDownTarget === event.target && maskMouseDownTarget === maskEl) {
        galleryVisible.value = false;
        handleVisibilityChange(false);
      }
    }, "onMaskMouseUp");
    watch(
      () => props.activeIndex,
      (index2) => {
        if (index2 !== -1) {
          galleryVisible.value = true;
        }
      }
    );
    const handleVisibilityChange = /* @__PURE__ */ __name((visible) => {
      if (!visible) {
        emit("update:activeIndex", -1);
      }
    }, "handleVisibilityChange");
    const handleActiveIndexChange = /* @__PURE__ */ __name((index2) => {
      emit("update:activeIndex", index2);
    }, "handleActiveIndexChange");
    const handleKeyDown2 = /* @__PURE__ */ __name((event) => {
      if (!galleryVisible.value) return;
      switch (event.key) {
        case "ArrowLeft":
          navigateImage(-1);
          break;
        case "ArrowRight":
          navigateImage(1);
          break;
        case "Escape":
          galleryVisible.value = false;
          handleVisibilityChange(false);
          break;
      }
    }, "handleKeyDown");
    const navigateImage = /* @__PURE__ */ __name((direction) => {
      const newIndex = (props.activeIndex + direction + props.allGalleryItems.length) % props.allGalleryItems.length;
      emit("update:activeIndex", newIndex);
    }, "navigateImage");
    onMounted(() => {
      window.addEventListener("keydown", handleKeyDown2);
    });
    onUnmounted(() => {
      window.removeEventListener("keydown", handleKeyDown2);
    });
    return (_ctx, _cache) => {
      return openBlock(), createBlock(unref(script$M), {
        visible: galleryVisible.value,
        "onUpdate:visible": [
          _cache[0] || (_cache[0] = ($event) => galleryVisible.value = $event),
          handleVisibilityChange
        ],
        "active-index": _ctx.activeIndex,
        value: _ctx.allGalleryItems,
        "show-indicators": false,
        "change-item-on-indicator-hover": "",
        "show-item-navigators": "",
        "full-screen": "",
        circular: "",
        "show-thumbnails": false,
        pt: {
          mask: {
            onMousedown: onMaskMouseDown,
            onMouseup: onMaskMouseUp,
            "data-mask": true
          },
          prevButton: {
            style: "position: fixed !important"
          },
          nextButton: {
            style: "position: fixed !important"
          }
        },
        "onUpdate:activeIndex": handleActiveIndexChange
      }, {
        item: withCtx(({ item }) => [
          item.isImage ? (openBlock(), createBlock(ComfyImage, {
            key: item.url,
            src: item.url,
            contain: false,
            alt: item.filename,
            class: "galleria-image"
          }, null, 8, ["src", "alt"])) : item.isVideo ? (openBlock(), createBlock(_sfc_main$8, {
            key: 1,
            result: item
          }, null, 8, ["result"])) : createCommentVNode("", true)
        ]),
        _: 1
      }, 8, ["visible", "active-index", "value", "pt"]);
    };
  }
});
const _hoisted_1$4 = {
  key: 2,
  class: "task-result-preview"
};
const _sfc_main$6 = /* @__PURE__ */ defineComponent({
  __name: "ResultItem",
  props: {
    result: {}
  },
  emits: ["preview"],
  setup(__props, { emit: __emit }) {
    const props = __props;
    const emit = __emit;
    const resultContainer = ref$3(null);
    const settingStore = useSettingStore();
    const imageFit = computed(
      () => settingStore.get("Comfy.Queue.ImageFit")
    );
    const handlePreviewClick = /* @__PURE__ */ __name(() => {
      if (props.result.supportsPreview) {
        emit("preview", props.result);
      }
    }, "handlePreviewClick");
    onMounted(() => {
      if (props.result.mediaType === "images") {
        resultContainer.value?.querySelectorAll("img").forEach((img) => {
          img.draggable = true;
        });
      }
    });
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", {
        ref_key: "resultContainer",
        ref: resultContainer,
        class: "result-container",
        onClick: handlePreviewClick
      }, [
        _ctx.result.isImage ? (openBlock(), createBlock(ComfyImage, {
          key: 0,
          src: _ctx.result.url,
          class: "task-output-image",
          contain: imageFit.value === "contain",
          alt: _ctx.result.filename
        }, null, 8, ["src", "contain", "alt"])) : _ctx.result.isVideo ? (openBlock(), createBlock(_sfc_main$8, {
          key: 1,
          result: _ctx.result
        }, null, 8, ["result"])) : (openBlock(), createElementBlock("div", _hoisted_1$4, [
          _cache[0] || (_cache[0] = createBaseVNode("i", { class: "pi pi-file" }, null, -1)),
          createBaseVNode("span", null, toDisplayString(_ctx.result.mediaType), 1)
        ]))
      ], 512);
    };
  }
});
const ResultItem = /* @__PURE__ */ _export_sfc(_sfc_main$6, [["__scopeId", "data-v-8b4b25ad"]]);
const _hoisted_1$3 = { class: "task-result-preview" };
const _hoisted_2$3 = {
  key: 0,
  class: "pi pi-spin pi-spinner"
};
const _hoisted_3$2 = ["src"];
const _hoisted_4$1 = { key: 2 };
const _hoisted_5$1 = {
  key: 3,
  class: "pi pi-exclamation-triangle"
};
const _hoisted_6$1 = {
  key: 4,
  class: "pi pi-exclamation-circle"
};
const _hoisted_7 = { class: "task-item-details" };
const _hoisted_8 = { class: "tag-wrapper status-tag-group" };
const _hoisted_9 = ["innerHTML"];
const _hoisted_10 = {
  key: 0,
  class: "task-time"
};
const _hoisted_11 = {
  key: 1,
  class: "task-prompt-id"
};
const _hoisted_12 = { class: "tag-wrapper" };
const _hoisted_13 = { style: { "font-weight": "bold" } };
const _sfc_main$5 = /* @__PURE__ */ defineComponent({
  __name: "TaskItem",
  props: {
    task: {},
    isFlatTask: { type: Boolean }
  },
  emits: ["contextmenu", "preview", "task-output-length-clicked"],
  setup(__props, { emit: __emit }) {
    const props = __props;
    const litegraphService = useLitegraphService();
    const flatOutputs = props.task.flatOutputs;
    const coverResult = flatOutputs.length ? props.task.previewOutput || flatOutputs[0] : null;
    const node2 = flatOutputs.length && props.task.workflow ? props.task.workflow.nodes.find(
      (n2) => n2.id == coverResult?.nodeId
    ) ?? null : null;
    const progressPreviewBlobUrl = ref$3("");
    const emit = __emit;
    onMounted(() => {
      api.addEventListener("b_preview", onProgressPreviewReceived);
    });
    onUnmounted(() => {
      if (progressPreviewBlobUrl.value) {
        URL.revokeObjectURL(progressPreviewBlobUrl.value);
      }
      api.removeEventListener("b_preview", onProgressPreviewReceived);
    });
    const handleContextMenu = /* @__PURE__ */ __name((e2) => {
      emit("contextmenu", { task: props.task, event: e2, node: node2 });
    }, "handleContextMenu");
    const handlePreview = /* @__PURE__ */ __name(() => {
      emit("preview", props.task);
    }, "handlePreview");
    const handleOutputLengthClick = /* @__PURE__ */ __name(() => {
      emit("task-output-length-clicked", props.task);
    }, "handleOutputLengthClick");
    const taskTagSeverity = /* @__PURE__ */ __name((status) => {
      switch (status) {
        case TaskItemDisplayStatus.Pending:
          return "secondary";
        case TaskItemDisplayStatus.Running:
          return "info";
        case TaskItemDisplayStatus.Completed:
          return "success";
        case TaskItemDisplayStatus.Failed:
          return "danger";
        case TaskItemDisplayStatus.Cancelled:
          return "warn";
      }
    }, "taskTagSeverity");
    const taskStatusText = /* @__PURE__ */ __name((status) => {
      switch (status) {
        case TaskItemDisplayStatus.Pending:
          return "Pending";
        case TaskItemDisplayStatus.Running:
          return '<i class="pi pi-spin pi-spinner" style="font-weight: bold"></i> Running';
        case TaskItemDisplayStatus.Completed:
          return '<i class="pi pi-check" style="font-weight: bold"></i>';
        case TaskItemDisplayStatus.Failed:
          return "Failed";
        case TaskItemDisplayStatus.Cancelled:
          return "Cancelled";
      }
    }, "taskStatusText");
    const formatTime = /* @__PURE__ */ __name((time) => {
      if (time === void 0) {
        return "";
      }
      return `${time.toFixed(2)}s`;
    }, "formatTime");
    const onProgressPreviewReceived = /* @__PURE__ */ __name(async ({ detail }) => {
      if (props.task.displayStatus === TaskItemDisplayStatus.Running) {
        if (progressPreviewBlobUrl.value) {
          URL.revokeObjectURL(progressPreviewBlobUrl.value);
        }
        progressPreviewBlobUrl.value = URL.createObjectURL(detail);
      }
    }, "onProgressPreviewReceived");
    const cancelledWithResults = computed(() => {
      return props.task.displayStatus === TaskItemDisplayStatus.Cancelled && flatOutputs.length;
    });
    const cancelledWithoutResults = computed(() => {
      return props.task.displayStatus === TaskItemDisplayStatus.Cancelled && flatOutputs.length === 0;
    });
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", {
        class: "task-item",
        onContextmenu: handleContextMenu
      }, [
        createBaseVNode("div", _hoisted_1$3, [
          _ctx.task.displayStatus === unref(TaskItemDisplayStatus).Completed || cancelledWithResults.value ? (openBlock(), createElementBlock(Fragment$1, { key: 0 }, [
            unref(flatOutputs).length && unref(coverResult) ? (openBlock(), createBlock(ResultItem, {
              key: 0,
              result: unref(coverResult),
              onPreview: handlePreview
            }, null, 8, ["result"])) : createCommentVNode("", true)
          ], 64)) : createCommentVNode("", true),
          _ctx.task.displayStatus === unref(TaskItemDisplayStatus).Running ? (openBlock(), createElementBlock(Fragment$1, { key: 1 }, [
            !progressPreviewBlobUrl.value ? (openBlock(), createElementBlock("i", _hoisted_2$3)) : (openBlock(), createElementBlock("img", {
              key: 1,
              src: progressPreviewBlobUrl.value,
              class: "progress-preview-img"
            }, null, 8, _hoisted_3$2))
          ], 64)) : _ctx.task.displayStatus === unref(TaskItemDisplayStatus).Pending ? (openBlock(), createElementBlock("span", _hoisted_4$1, "...")) : cancelledWithoutResults.value ? (openBlock(), createElementBlock("i", _hoisted_5$1)) : _ctx.task.displayStatus === unref(TaskItemDisplayStatus).Failed ? (openBlock(), createElementBlock("i", _hoisted_6$1)) : createCommentVNode("", true)
        ]),
        createBaseVNode("div", _hoisted_7, [
          createBaseVNode("div", _hoisted_8, [
            _ctx.isFlatTask && _ctx.task.isHistory ? (openBlock(), createBlock(unref(script$5), {
              key: 0,
              class: "node-name-tag"
            }, {
              default: withCtx(() => [
                createVNode(unref(script$6), {
                  class: "task-node-link",
                  label: `${unref(node2)?.type} (#${unref(node2)?.id})`,
                  link: "",
                  size: "small",
                  onClick: _cache[0] || (_cache[0] = () => {
                    if (!unref(node2)) return;
                    unref(litegraphService).goToNode(unref(node2).id);
                  })
                }, null, 8, ["label"])
              ]),
              _: 1
            })) : createCommentVNode("", true),
            createVNode(unref(script$5), {
              severity: taskTagSeverity(_ctx.task.displayStatus)
            }, {
              default: withCtx(() => [
                createBaseVNode("span", {
                  innerHTML: taskStatusText(_ctx.task.displayStatus)
                }, null, 8, _hoisted_9),
                _ctx.task.isHistory ? (openBlock(), createElementBlock("span", _hoisted_10, toDisplayString(formatTime(_ctx.task.executionTimeInSeconds)), 1)) : createCommentVNode("", true),
                _ctx.isFlatTask ? (openBlock(), createElementBlock("span", _hoisted_11, toDisplayString(_ctx.task.promptId.split("-")[0]), 1)) : createCommentVNode("", true)
              ]),
              _: 1
            }, 8, ["severity"])
          ]),
          createBaseVNode("div", _hoisted_12, [
            _ctx.task.isHistory && unref(flatOutputs).length > 1 ? (openBlock(), createBlock(unref(script$6), {
              key: 0,
              outlined: "",
              onClick: handleOutputLengthClick
            }, {
              default: withCtx(() => [
                createBaseVNode("span", _hoisted_13, toDisplayString(unref(flatOutputs).length), 1)
              ]),
              _: 1
            })) : createCommentVNode("", true)
          ])
        ])
      ], 32);
    };
  }
});
const TaskItem = /* @__PURE__ */ _export_sfc(_sfc_main$5, [["__scopeId", "data-v-96916e5f"]]);
const _hoisted_1$2 = { key: 1 };
const _hoisted_2$2 = { key: 2 };
const IMAGE_FIT = "Comfy.Queue.ImageFit";
const _sfc_main$4 = /* @__PURE__ */ defineComponent({
  __name: "QueueSidebarTab",
  setup(__props) {
    const confirm2 = useConfirm();
    const toast = useToast();
    const queueStore = useQueueStore();
    const settingStore = useSettingStore();
    const commandStore = useCommandStore();
    const { t: t2 } = useI18n();
    const isExpanded = ref$3(false);
    const galleryActiveIndex = ref$3(-1);
    const allGalleryItems = shallowRef([]);
    const folderTask = ref$3(null);
    const isInFolderView = computed(() => folderTask.value !== null);
    const imageFit = computed(() => settingStore.get(IMAGE_FIT));
    const allTasks = computed(
      () => isInFolderView.value ? folderTask.value ? folderTask.value.flatten() : [] : isExpanded.value ? queueStore.flatTasks : queueStore.tasks
    );
    const updateGalleryItems = /* @__PURE__ */ __name(() => {
      allGalleryItems.value = allTasks.value.flatMap((task) => {
        const previewOutput = task.previewOutput;
        return previewOutput ? [previewOutput] : [];
      });
    }, "updateGalleryItems");
    const toggleExpanded = /* @__PURE__ */ __name(() => {
      isExpanded.value = !isExpanded.value;
    }, "toggleExpanded");
    const removeTask = /* @__PURE__ */ __name(async (task) => {
      if (task.isRunning) {
        await api.interrupt();
      }
      await queueStore.delete(task);
    }, "removeTask");
    const removeAllTasks = /* @__PURE__ */ __name(async () => {
      await queueStore.clear();
    }, "removeAllTasks");
    const confirmRemoveAll = /* @__PURE__ */ __name((event) => {
      confirm2.require({
        target: event.currentTarget,
        message: "Do you want to delete all tasks?",
        icon: "pi pi-info-circle",
        rejectProps: {
          label: "Cancel",
          severity: "secondary",
          outlined: true
        },
        acceptProps: {
          label: "Delete",
          severity: "danger"
        },
        accept: /* @__PURE__ */ __name(async () => {
          await removeAllTasks();
          toast.add({
            severity: "info",
            summary: "Confirmed",
            detail: "Tasks deleted",
            life: 3e3
          });
        }, "accept")
      });
    }, "confirmRemoveAll");
    const menu2 = ref$3(null);
    const menuTargetTask = ref$3(null);
    const menuTargetNode = ref$3(null);
    const menuItems = computed(() => [
      {
        label: t2("g.delete"),
        icon: "pi pi-trash",
        command: /* @__PURE__ */ __name(() => menuTargetTask.value && removeTask(menuTargetTask.value), "command"),
        disabled: isExpanded.value || isInFolderView.value
      },
      {
        label: t2("g.loadWorkflow"),
        icon: "pi pi-file-export",
        command: /* @__PURE__ */ __name(() => menuTargetTask.value?.loadWorkflow(app$1), "command"),
        disabled: !menuTargetTask.value?.workflow
      },
      {
        label: t2("g.goToNode"),
        icon: "pi pi-arrow-circle-right",
        command: /* @__PURE__ */ __name(() => {
          if (!menuTargetNode.value) return;
          useLitegraphService().goToNode(menuTargetNode.value.id);
        }, "command"),
        visible: !!menuTargetNode.value
      }
    ]);
    const handleContextMenu = /* @__PURE__ */ __name(({
      task,
      event,
      node: node2
    }) => {
      menuTargetTask.value = task;
      menuTargetNode.value = node2;
      menu2.value?.show(event);
    }, "handleContextMenu");
    const handlePreview = /* @__PURE__ */ __name((task) => {
      updateGalleryItems();
      galleryActiveIndex.value = allGalleryItems.value.findIndex(
        (item) => item.url === task.previewOutput?.url
      );
    }, "handlePreview");
    const enterFolderView = /* @__PURE__ */ __name((task) => {
      folderTask.value = task;
    }, "enterFolderView");
    const exitFolderView = /* @__PURE__ */ __name(() => {
      folderTask.value = null;
    }, "exitFolderView");
    const toggleImageFit = /* @__PURE__ */ __name(async () => {
      await settingStore.set(
        IMAGE_FIT,
        imageFit.value === "cover" ? "contain" : "cover"
      );
    }, "toggleImageFit");
    watch(allTasks, () => {
      const isGalleryOpen = galleryActiveIndex.value !== -1;
      if (!isGalleryOpen) return;
      const prevLength = allGalleryItems.value.length;
      updateGalleryItems();
      const lengthChange = allGalleryItems.value.length - prevLength;
      if (!lengthChange) return;
      const newIndex = galleryActiveIndex.value + lengthChange;
      galleryActiveIndex.value = Math.max(0, newIndex);
    });
    return (_ctx, _cache) => {
      const _directive_tooltip = resolveDirective("tooltip");
      return openBlock(), createElementBlock(Fragment$1, null, [
        createVNode(SidebarTabTemplate, {
          title: _ctx.$t("sideToolbar.queue")
        }, {
          "tool-buttons": withCtx(() => [
            withDirectives(createVNode(unref(script$6), {
              icon: imageFit.value === "cover" ? "pi pi-arrow-down-left-and-arrow-up-right-to-center" : "pi pi-arrow-up-right-and-arrow-down-left-from-center",
              text: "",
              severity: "secondary",
              class: "toggle-expanded-button",
              onClick: toggleImageFit
            }, null, 8, ["icon"]), [
              [
                _directive_tooltip,
                _ctx.$t(`sideToolbar.queueTab.${imageFit.value}ImagePreview`),
                void 0,
                { bottom: true }
              ]
            ]),
            isInFolderView.value ? withDirectives((openBlock(), createBlock(unref(script$6), {
              key: 0,
              icon: "pi pi-arrow-left",
              text: "",
              severity: "secondary",
              class: "back-button",
              onClick: exitFolderView
            }, null, 512)), [
              [
                _directive_tooltip,
                _ctx.$t("sideToolbar.queueTab.backToAllTasks"),
                void 0,
                { bottom: true }
              ]
            ]) : (openBlock(), createElementBlock(Fragment$1, { key: 1 }, [
              withDirectives(createVNode(unref(script$6), {
                icon: isExpanded.value ? "pi pi-images" : "pi pi-image",
                text: "",
                severity: "secondary",
                class: "toggle-expanded-button",
                onClick: toggleExpanded
              }, null, 8, ["icon"]), [
                [_directive_tooltip, _ctx.$t("sideToolbar.queueTab.showFlatList")]
              ]),
              unref(queueStore).hasPendingTasks ? withDirectives((openBlock(), createBlock(unref(script$6), {
                key: 0,
                icon: "pi pi-stop",
                severity: "danger",
                text: "",
                onClick: _cache[0] || (_cache[0] = () => unref(commandStore).execute("Comfy.ClearPendingTasks"))
              }, null, 512)), [
                [
                  _directive_tooltip,
                  _ctx.$t("sideToolbar.queueTab.clearPendingTasks"),
                  void 0,
                  { bottom: true }
                ]
              ]) : createCommentVNode("", true),
              createVNode(unref(script$6), {
                icon: "pi pi-trash",
                text: "",
                severity: "primary",
                class: "clear-all-button",
                onClick: _cache[1] || (_cache[1] = ($event) => confirmRemoveAll($event))
              })
            ], 64))
          ]),
          body: withCtx(() => [
            allTasks.value?.length ? (openBlock(), createBlock(VirtualGrid, {
              key: 0,
              items: allTasks.value,
              "grid-style": {
                display: "grid",
                gridTemplateColumns: "repeat(auto-fill, minmax(200px, 1fr))",
                padding: "0.5rem",
                gap: "0.5rem"
              }
            }, {
              item: withCtx(({ item }) => [
                createVNode(TaskItem, {
                  task: item,
                  "is-flat-task": isExpanded.value || isInFolderView.value,
                  onContextmenu: handleContextMenu,
                  onPreview: handlePreview,
                  onTaskOutputLengthClicked: _cache[2] || (_cache[2] = ($event) => enterFolderView($event))
                }, null, 8, ["task", "is-flat-task"])
              ]),
              _: 1
            }, 8, ["items"])) : unref(queueStore).isLoading ? (openBlock(), createElementBlock("div", _hoisted_1$2, [
              createVNode(unref(script$x), { style: { "width": "50px", "left": "50%", "transform": "translateX(-50%)" } })
            ])) : (openBlock(), createElementBlock("div", _hoisted_2$2, [
              createVNode(NoResultsPlaceholder, {
                icon: "pi pi-info-circle",
                title: _ctx.$t("g.noTasksFound"),
                message: _ctx.$t("g.noTasksFoundMessage")
              }, null, 8, ["title", "message"])
            ]))
          ]),
          _: 1
        }, 8, ["title"]),
        createVNode(unref(script$N)),
        createVNode(unref(script$K), {
          ref_key: "menu",
          ref: menu2,
          model: menuItems.value
        }, null, 8, ["model"]),
        createVNode(_sfc_main$7, {
          activeIndex: galleryActiveIndex.value,
          "onUpdate:activeIndex": _cache[3] || (_cache[3] = ($event) => galleryActiveIndex.value = $event),
          "all-gallery-items": allGalleryItems.value
        }, null, 8, ["activeIndex", "all-gallery-items"])
      ], 64);
    };
  }
});
const useQueueSidebarTab = /* @__PURE__ */ __name(() => {
  const { t: t2 } = useI18n();
  const queuePendingTaskCountStore = useQueuePendingTaskCountStore();
  return {
    id: "queue",
    icon: "pi pi-history",
    iconBadge: /* @__PURE__ */ __name(() => {
      const value = queuePendingTaskCountStore.count.toString();
      return value === "0" ? null : value;
    }, "iconBadge"),
    title: t2("sideToolbar.queue"),
    tooltip: t2("sideToolbar.queue"),
    component: markRaw(_sfc_main$4),
    type: "vue"
  };
}, "useQueueSidebarTab");
const _hoisted_1$1 = { class: "flex items-center" };
const _hoisted_2$1 = {
  key: 0,
  class: "mr-2 shrink-0"
};
const _hoisted_3$1 = {
  key: 1,
  class: "ml-2 shrink-0"
};
const _sfc_main$3 = /* @__PURE__ */ defineComponent({
  __name: "TextDivider",
  props: {
    text: {},
    position: { default: "left" },
    align: { default: "center" },
    type: { default: "solid" },
    layout: { default: "horizontal" }
  },
  setup(__props) {
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", _hoisted_1$1, [
        _ctx.position === "left" ? (openBlock(), createElementBlock("span", _hoisted_2$1, toDisplayString(_ctx.text), 1)) : createCommentVNode("", true),
        createVNode(unref(script$f), {
          align: _ctx.align,
          type: _ctx.type,
          layout: _ctx.layout,
          class: "flex-grow"
        }, null, 8, ["align", "type", "layout"]),
        _ctx.position === "right" ? (openBlock(), createElementBlock("span", _hoisted_3$1, toDisplayString(_ctx.text), 1)) : createCommentVNode("", true)
      ]);
    };
  }
});
const _sfc_main$2 = /* @__PURE__ */ defineComponent({
  __name: "WorkflowTreeLeaf",
  props: {
    node: {}
  },
  setup(__props) {
    const workflowBookmarkStore = useWorkflowBookmarkStore();
    const isBookmarked = computed(
      () => __props.node.data && workflowBookmarkStore.isBookmarked(__props.node.data.path)
    );
    const handleBookmarkClick = /* @__PURE__ */ __name(async () => {
      if (__props.node.data) {
        await workflowBookmarkStore.toggleBookmarked(__props.node.data.path);
      }
    }, "handleBookmarkClick");
    return (_ctx, _cache) => {
      return openBlock(), createBlock(TreeExplorerTreeNode, { node: _ctx.node }, {
        actions: withCtx(() => [
          createVNode(unref(script$6), {
            icon: isBookmarked.value ? "pi pi-bookmark-fill" : "pi pi-bookmark",
            text: "",
            severity: "secondary",
            size: "small",
            onClick: withModifiers(handleBookmarkClick, ["stop"])
          }, null, 8, ["icon"])
        ]),
        _: 1
      }, 8, ["node"]);
    };
  }
});
const _hoisted_1 = {
  key: 0,
  class: "comfyui-workflows-panel"
};
const _hoisted_2 = {
  key: 0,
  class: "comfyui-workflows-open"
};
const _hoisted_3 = { key: 0 };
const _hoisted_4 = { class: "comfyui-workflows-bookmarks" };
const _hoisted_5 = { class: "comfyui-workflows-browse" };
const _hoisted_6 = {
  key: 1,
  class: "comfyui-workflows-search-panel"
};
var WorkflowTreeType = /* @__PURE__ */ ((WorkflowTreeType2) => {
  WorkflowTreeType2["Open"] = "Open";
  WorkflowTreeType2["Bookmarks"] = "Bookmarks";
  WorkflowTreeType2["Browse"] = "Browse";
  return WorkflowTreeType2;
})(WorkflowTreeType || {});
const _sfc_main$1 = /* @__PURE__ */ defineComponent({
  __name: "WorkflowsSidebarTab",
  setup(__props) {
    const settingStore = useSettingStore();
    const workflowTabsPosition = computed(
      () => settingStore.get("Comfy.Workflow.WorkflowTabsPosition")
    );
    const searchQuery = ref$3("");
    const isSearching = computed(() => searchQuery.value.length > 0);
    const filteredWorkflows = ref$3([]);
    const filteredRoot = computed(() => {
      return buildWorkflowTree(filteredWorkflows.value);
    });
    const handleSearch = /* @__PURE__ */ __name(async (query2) => {
      if (query2.length === 0) {
        filteredWorkflows.value = [];
        expandedKeys.value = {};
        return;
      }
      const lowerQuery = query2.toLocaleLowerCase();
      filteredWorkflows.value = workflowStore.workflows.filter((workflow) => {
        return workflow.path.toLocaleLowerCase().includes(lowerQuery);
      });
      await nextTick();
      expandNode(filteredRoot.value);
    }, "handleSearch");
    const workflowStore = useWorkflowStore();
    const workflowService2 = useWorkflowService();
    const workspaceStore = useWorkspaceStore();
    const { t: t2 } = useI18n();
    const expandedKeys = ref$3({});
    const { expandNode, toggleNodeOnEvent } = useTreeExpansion(expandedKeys);
    const dummyExpandedKeys = ref$3({});
    const handleCloseWorkflow = /* @__PURE__ */ __name(async (workflow) => {
      if (workflow) {
        await workflowService2.closeWorkflow(workflow, {
          warnIfUnsaved: !workspaceStore.shiftDown
        });
      }
    }, "handleCloseWorkflow");
    const buildWorkflowTree = /* @__PURE__ */ __name((workflows) => {
      return buildTree$1(
        workflows,
        (workflow) => workflow.key.split("/")
      );
    }, "buildWorkflowTree");
    const workflowsTree = computed(
      () => sortedTree(buildWorkflowTree(workflowStore.persistedWorkflows), {
        groupLeaf: true
      })
    );
    const bookmarkedWorkflowsTree = computed(
      () => buildTree$1(workflowStore.bookmarkedWorkflows, (workflow) => [workflow.key])
    );
    const openWorkflowsTree = computed(
      () => buildTree$1(workflowStore.openWorkflows, (workflow) => [workflow.key])
    );
    const renderTreeNode = /* @__PURE__ */ __name((node2, type) => {
      const children = node2.children?.map((child2) => renderTreeNode(child2, type));
      const workflow = node2.data;
      async function handleClick2(e2) {
        if (this.leaf) {
          await workflowService2.openWorkflow(workflow);
        } else {
          toggleNodeOnEvent(e2, this);
        }
      }
      __name(handleClick2, "handleClick");
      const actions = node2.leaf ? {
        handleClick: handleClick2,
        async handleRename(newName) {
          const newPath = type === "Browse" ? workflow.directory + "/" + appendJsonExt(newName) : ComfyWorkflow.basePath + appendJsonExt(newName);
          await workflowService2.renameWorkflow(workflow, newPath);
        },
        handleDelete: workflow.isTemporary ? void 0 : async function() {
          await workflowService2.deleteWorkflow(workflow);
        },
        contextMenuItems() {
          return [
            {
              label: t2("g.insert"),
              icon: "pi pi-file-export",
              command: /* @__PURE__ */ __name(async () => {
                const workflow2 = node2.data;
                await workflowService2.insertWorkflow(workflow2);
              }, "command")
            }
          ];
        },
        draggable: true
      } : { handleClick: handleClick2 };
      return {
        key: node2.key,
        label: node2.label,
        leaf: node2.leaf,
        data: node2.data,
        children,
        ...actions
      };
    }, "renderTreeNode");
    const selectionKeys = computed(() => ({
      [`root/${workflowStore.activeWorkflow?.key}`]: true
    }));
    const workflowBookmarkStore = useWorkflowBookmarkStore();
    onMounted(async () => {
      await workflowBookmarkStore.loadBookmarks();
    });
    return (_ctx, _cache) => {
      const _directive_tooltip = resolveDirective("tooltip");
      return openBlock(), createElementBlock(Fragment$1, null, [
        createVNode(SidebarTabTemplate, {
          title: _ctx.$t("sideToolbar.workflows"),
          class: "workflows-sidebar-tab bg-[var(--p-tree-background)]"
        }, {
          "tool-buttons": withCtx(() => [
            withDirectives(createVNode(unref(script$6), {
              icon: "pi pi-refresh",
              severity: "secondary",
              text: "",
              onClick: _cache[0] || (_cache[0] = ($event) => unref(workflowStore).syncWorkflows())
            }, null, 512), [
              [
                _directive_tooltip,
                _ctx.$t("g.refresh"),
                void 0,
                { bottom: true }
              ]
            ])
          ]),
          header: withCtx(() => [
            createVNode(SearchBox, {
              modelValue: searchQuery.value,
              "onUpdate:modelValue": _cache[1] || (_cache[1] = ($event) => searchQuery.value = $event),
              class: "workflows-search-box p-2 2xl:p-4",
              placeholder: _ctx.$t("g.searchWorkflows") + "...",
              onSearch: handleSearch
            }, null, 8, ["modelValue", "placeholder"])
          ]),
          body: withCtx(() => [
            !isSearching.value ? (openBlock(), createElementBlock("div", _hoisted_1, [
              workflowTabsPosition.value === "Sidebar" ? (openBlock(), createElementBlock("div", _hoisted_2, [
                createVNode(_sfc_main$3, {
                  text: unref(t2)("sideToolbar.workflowTab.workflowTreeType.open"),
                  type: "dashed",
                  class: "ml-2"
                }, null, 8, ["text"]),
                createVNode(TreeExplorer, {
                  expandedKeys: dummyExpandedKeys.value,
                  "onUpdate:expandedKeys": _cache[2] || (_cache[2] = ($event) => dummyExpandedKeys.value = $event),
                  root: renderTreeNode(
                    openWorkflowsTree.value,
                    "Open"
                    /* Open */
                  ),
                  "selection-keys": selectionKeys.value
                }, {
                  node: withCtx(({ node: node2 }) => [
                    createVNode(TreeExplorerTreeNode, { node: node2 }, {
                      "before-label": withCtx(({ node: treeNode }) => [
                        treeNode.data?.isModified || !treeNode.data?.isPersisted ? (openBlock(), createElementBlock("span", _hoisted_3, "*")) : createCommentVNode("", true)
                      ]),
                      actions: withCtx(({ node: treeNode }) => [
                        createVNode(unref(script$6), {
                          class: "close-workflow-button",
                          icon: "pi pi-times",
                          text: "",
                          severity: unref(workspaceStore).shiftDown ? "danger" : "secondary",
                          size: "small",
                          onClick: withModifiers(($event) => handleCloseWorkflow(treeNode.data), ["stop"])
                        }, null, 8, ["severity", "onClick"])
                      ]),
                      _: 2
                    }, 1032, ["node"])
                  ]),
                  _: 1
                }, 8, ["expandedKeys", "root", "selection-keys"])
              ])) : createCommentVNode("", true),
              withDirectives(createBaseVNode("div", _hoisted_4, [
                createVNode(_sfc_main$3, {
                  text: unref(t2)("sideToolbar.workflowTab.workflowTreeType.bookmarks"),
                  type: "dashed",
                  class: "ml-2"
                }, null, 8, ["text"]),
                createVNode(TreeExplorer, {
                  expandedKeys: dummyExpandedKeys.value,
                  "onUpdate:expandedKeys": _cache[3] || (_cache[3] = ($event) => dummyExpandedKeys.value = $event),
                  root: renderTreeNode(
                    bookmarkedWorkflowsTree.value,
                    "Bookmarks"
                    /* Bookmarks */
                  ),
                  "selection-keys": selectionKeys.value
                }, {
                  node: withCtx(({ node: node2 }) => [
                    createVNode(_sfc_main$2, { node: node2 }, null, 8, ["node"])
                  ]),
                  _: 1
                }, 8, ["expandedKeys", "root", "selection-keys"])
              ], 512), [
                [vShow, unref(workflowStore).bookmarkedWorkflows.length > 0]
              ]),
              createBaseVNode("div", _hoisted_5, [
                createVNode(_sfc_main$3, {
                  text: unref(t2)("sideToolbar.workflowTab.workflowTreeType.browse"),
                  type: "dashed",
                  class: "ml-2"
                }, null, 8, ["text"]),
                unref(workflowStore).persistedWorkflows.length > 0 ? (openBlock(), createBlock(TreeExplorer, {
                  key: 0,
                  expandedKeys: expandedKeys.value,
                  "onUpdate:expandedKeys": _cache[4] || (_cache[4] = ($event) => expandedKeys.value = $event),
                  root: renderTreeNode(
                    workflowsTree.value,
                    "Browse"
                    /* Browse */
                  ),
                  "selection-keys": selectionKeys.value
                }, {
                  node: withCtx(({ node: node2 }) => [
                    createVNode(_sfc_main$2, { node: node2 }, null, 8, ["node"])
                  ]),
                  _: 1
                }, 8, ["expandedKeys", "root", "selection-keys"])) : (openBlock(), createBlock(NoResultsPlaceholder, {
                  key: 1,
                  icon: "pi pi-folder",
                  title: _ctx.$t("g.empty"),
                  message: _ctx.$t("g.noWorkflowsFound")
                }, null, 8, ["title", "message"]))
              ])
            ])) : (openBlock(), createElementBlock("div", _hoisted_6, [
              createVNode(TreeExplorer, {
                expandedKeys: expandedKeys.value,
                "onUpdate:expandedKeys": _cache[5] || (_cache[5] = ($event) => expandedKeys.value = $event),
                root: renderTreeNode(
                  filteredRoot.value,
                  "Browse"
                  /* Browse */
                )
              }, {
                node: withCtx(({ node: node2 }) => [
                  createVNode(_sfc_main$2, { node: node2 }, null, 8, ["node"])
                ]),
                _: 1
              }, 8, ["expandedKeys", "root"])
            ]))
          ]),
          _: 1
        }, 8, ["title"]),
        createVNode(unref(script$O))
      ], 64);
    };
  }
});
const useWorkflowsSidebarTab = /* @__PURE__ */ __name(() => {
  const { t: t2 } = useI18n();
  const settingStore = useSettingStore();
  const workflowStore = useWorkflowStore();
  return {
    id: "workflows",
    icon: "pi pi-folder-open",
    iconBadge: /* @__PURE__ */ __name(() => {
      if (settingStore.get("Comfy.Workflow.WorkflowTabsPosition") !== "Sidebar") {
        return null;
      }
      const value = workflowStore.openWorkflows.length.toString();
      return value === "0" ? null : value;
    }, "iconBadge"),
    title: t2("sideToolbar.workflows"),
    tooltip: t2("sideToolbar.workflows"),
    component: markRaw(_sfc_main$1),
    type: "vue"
  };
}, "useWorkflowsSidebarTab");
const useSidebarTabStore = /* @__PURE__ */ defineStore("sidebarTab", () => {
  const sidebarTabs = ref$3([]);
  const activeSidebarTabId = ref$3(null);
  const activeSidebarTab = computed(() => {
    return sidebarTabs.value.find((tab) => tab.id === activeSidebarTabId.value) ?? null;
  });
  const toggleSidebarTab = /* @__PURE__ */ __name((tabId) => {
    activeSidebarTabId.value = activeSidebarTabId.value === tabId ? null : tabId;
  }, "toggleSidebarTab");
  const registerSidebarTab = /* @__PURE__ */ __name((tab) => {
    sidebarTabs.value = [...sidebarTabs.value, tab];
    useCommandStore().registerCommand({
      id: `Workspace.ToggleSidebarTab.${tab.id}`,
      icon: tab.icon,
      label: `Toggle ${tab.title} Sidebar`,
      tooltip: tab.tooltip,
      versionAdded: "1.3.9",
      function: /* @__PURE__ */ __name(() => {
        toggleSidebarTab(tab.id);
      }, "function"),
      source: "System"
    });
  }, "registerSidebarTab");
  const unregisterSidebarTab = /* @__PURE__ */ __name((id2) => {
    const index2 = sidebarTabs.value.findIndex((tab) => tab.id === id2);
    if (index2 !== -1) {
      const tab = sidebarTabs.value[index2];
      if (tab.type === "custom" && tab.destroy) {
        tab.destroy();
      }
      const newSidebarTabs = [...sidebarTabs.value];
      newSidebarTabs.splice(index2, 1);
      sidebarTabs.value = newSidebarTabs;
    }
  }, "unregisterSidebarTab");
  const registerCoreSidebarTabs = /* @__PURE__ */ __name(() => {
    registerSidebarTab(useQueueSidebarTab());
    registerSidebarTab(useNodeLibrarySidebarTab());
    registerSidebarTab(useModelLibrarySidebarTab());
    registerSidebarTab(useWorkflowsSidebarTab());
  }, "registerCoreSidebarTabs");
  return {
    sidebarTabs,
    activeSidebarTabId,
    activeSidebarTab,
    toggleSidebarTab,
    registerSidebarTab,
    unregisterSidebarTab,
    registerCoreSidebarTabs
  };
});
const useWorkspaceStore = /* @__PURE__ */ defineStore("workspace", () => {
  const spinner = ref$3(false);
  const shiftDown = ref$3(false);
  const focusMode = ref$3(false);
  const toast = computed(() => useToastStore());
  const queueSettings = computed(() => useQueueSettingsStore());
  const command2 = computed(() => ({
    commands: useCommandStore().commands,
    execute: useCommandStore().execute
  }));
  const sidebarTab = computed(() => useSidebarTabStore());
  const setting = computed(() => ({
    settings: useSettingStore().settingsById,
    // Allow generic key access to settings as custom nodes may add their
    // own settings which is not tracked by the `Setting` schema.
    get: /* @__PURE__ */ __name((key) => useSettingStore().get(key), "get"),
    set: /* @__PURE__ */ __name((key, value) => useSettingStore().set(key, value), "set")
  }));
  const workflow = computed(() => useWorkflowStore());
  const colorPalette = useColorPaletteService();
  const dialog = useDialogService();
  const bottomPanel = useBottomPanelStore();
  const authStore = useFirebaseAuthStore();
  const apiKeyStore = useApiKeyAuthStore();
  const firebaseUser = computed(() => authStore.currentUser);
  const isApiKeyLogin = computed(() => apiKeyStore.isAuthenticated);
  const isLoggedIn = computed(
    () => !!isApiKeyLogin.value || firebaseUser.value !== null
  );
  const partialUserStore = {
    isLoggedIn
  };
  function registerSidebarTab(tab) {
    sidebarTab.value.registerSidebarTab(tab);
  }
  __name(registerSidebarTab, "registerSidebarTab");
  function unregisterSidebarTab(id2) {
    sidebarTab.value.unregisterSidebarTab(id2);
  }
  __name(unregisterSidebarTab, "unregisterSidebarTab");
  function getSidebarTabs() {
    return sidebarTab.value.sidebarTabs;
  }
  __name(getSidebarTabs, "getSidebarTabs");
  return {
    spinner,
    shiftDown,
    focusMode,
    toggleFocusMode: /* @__PURE__ */ __name(() => {
      focusMode.value = !focusMode.value;
    }, "toggleFocusMode"),
    toast,
    queueSettings,
    command: command2,
    sidebarTab,
    setting,
    workflow,
    colorPalette,
    dialog,
    bottomPanel,
    user: partialUserStore,
    registerSidebarTab,
    unregisterSidebarTab,
    getSidebarTabs
  };
});
const _sfc_main = /* @__PURE__ */ defineComponent({
  __name: "App",
  setup(__props) {
    const workspaceStore = useWorkspaceStore();
    const isLoading = computed(() => workspaceStore.spinner);
    const handleKey = /* @__PURE__ */ __name((e2) => {
      workspaceStore.shiftDown = e2.shiftKey;
    }, "handleKey");
    useEventListener(window, "keydown", handleKey);
    useEventListener(window, "keyup", handleKey);
    const showContextMenu = /* @__PURE__ */ __name((event) => {
      const { target } = event;
      switch (true) {
        case target instanceof HTMLTextAreaElement:
        case (target instanceof HTMLInputElement && target.type === "text"):
          electronAPI()?.showContextMenu({ type: "text" });
          return;
      }
    }, "showContextMenu");
    onMounted(() => {
      window["__COMFYUI_FRONTEND_VERSION__"] = config$1.app_version;
      console.log("ComfyUI Front-end version:", config$1.app_version);
      if (isElectron()) {
        document.addEventListener("contextmenu", showContextMenu);
      }
    });
    return (_ctx, _cache) => {
      const _component_router_view = resolveComponent("router-view");
      return openBlock(), createElementBlock(Fragment$1, null, [
        createVNode(_component_router_view),
        isLoading.value ? (openBlock(), createBlock(unref(script$x), {
          key: 0,
          class: "absolute inset-0 flex justify-center items-center h-[unset]"
        })) : createCommentVNode("", true),
        createVNode(_sfc_main$1S),
        createVNode(unref(script$P), {
          "full-screen": "",
          blocked: isLoading.value
        }, null, 8, ["blocked"])
      ], 64);
    };
  }
});
const ComfyUIPreset = definePreset$1(index$2, {
  semantic: {
    // @ts-expect-error fixme ts strict error
    primary: index$2["primitive"].blue
  }
});
const firebaseApp = initializeApp(FIREBASE_CONFIG);
const app = createApp(_sfc_main);
const pinia = createPinia();
init$3({
  app,
  dsn: "https://e2d0c0bd392ffdce48e856c2a055f437@o4507954455314432.ingest.us.sentry.io/4508621568475136",
  enabled: true,
  release: "1.20.0",
  integrations: [],
  autoSessionTracking: false,
  defaultIntegrations: false,
  normalizeDepth: 8,
  tracesSampleRate: 0
});
app.directive("tooltip", Tooltip);
app.use(router).use(PrimeVue, {
  theme: {
    preset: ComfyUIPreset,
    options: {
      prefix: "p",
      cssLayer: {
        name: "primevue",
        order: "primevue, tailwind-utilities"
      },
      // This is a workaround for the issue with the dark mode selector
      // https://github.com/primefaces/primevue/issues/5515
      darkModeSelector: ".dark-theme, :root:has(.dark-theme)"
    }
  }
}).use(ConfirmationService).use(ToastService).use(pinia).use(i18n).use(VueFire, {
  firebaseApp,
  modules: [VueFireAuth()]
}).mount("#vue-app");
export {
  $el,
  BadgePosition,
  BaseTerminal,
  CONFIG,
  CanvasPointer,
  ChangeTracker,
  ComfyApp,
  ComfyDialog,
  ComfyModelDef,
  ComfyNodeDefImpl,
  ComfyWidgets,
  ComfyWorkflow,
  ComponentWidgetImpl,
  ContextMenu,
  DEFAULT_DARK_COLOR_PALETTE,
  DEFAULT_LIGHT_COLOR_PALETTE,
  DragAndScale,
  DraggableList,
  EditableText,
  FormItem,
  GET_CONFIG,
  IS_CONTROL_WIDGET,
  KeyComboImpl,
  KeybindingImpl,
  LGraph,
  LGraphBadge,
  LGraphCanvas,
  LGraphEventMode,
  LGraphGroup,
  LGraphNode,
  LLink,
  LinkMarkerShape,
  LiteGraph,
  MigrationItems,
  NodeBadgeMode,
  NodePreview,
  NodeSearchFilter,
  NodeSourceType,
  ProgressStatus,
  SearchBox,
  SearchFilterChip,
  SettingDialogContent,
  SettingDialogHeader,
  TorchMirrorUrl,
  UnauthorizedError,
  ValidationState,
  _,
  _export_sfc,
  _imports_0$1 as _imports_0,
  _sfc_main$1g as _sfc_main,
  _sfc_main$1r as _sfc_main$1,
  _sfc_main$1x as _sfc_main$2,
  addValueControlWidgets,
  addWidget,
  adjustColor,
  api,
  app$1 as app,
  applyTextReplacements$1 as applyTextReplacements,
  checkMirrorReachable,
  commonjsGlobal,
  createBounds,
  defineStore,
  deserialiseAndCreate,
  electronAPI,
  formatMetronomeCurrency,
  formatNumberWithSuffix,
  formatSize,
  getComboSpecComboOptions,
  getDefaultExportFromCjs,
  getInputSpecType,
  getItemsColorOption,
  getStorageValue,
  highlightQuery,
  i18n,
  isAudioNode,
  isColorable,
  isComboInputSpec$1 as isComboInputSpec,
  isComboInputSpecV1,
  isComboWidget,
  isComponentWidget,
  isDOMWidget,
  isElectron,
  isFloatInputSpec$1 as isFloatInputSpec,
  isImageNode,
  isInChina,
  isIntInputSpec$1 as isIntInputSpec,
  isLGraphGroup,
  isLGraphNode,
  isNativeWindow,
  isOverNodeInput,
  isOverNodeOutput,
  isPrimitiveNode,
  isVideoNode,
  lodashExports,
  log,
  mergeValidationStates,
  migrateLegacyRerouteNodes,
  normalizeI18nKey,
  processDynamicPrompt,
  serialise,
  setStorageValue,
  showNativeSystemMenu,
  st,
  storeToRefs,
  t,
  te,
  updateControlWidgetLabel,
  useBottomPanelStore,
  useCanvasPositionConversion,
  useCanvasStore,
  useChainCallback,
  useColorPaletteService,
  useColorPaletteStore,
  useCommandStore,
  useCopyToClipboard,
  useCurrentUser,
  useDialogService,
  useDialogStore,
  useDomWidgetStore,
  useDraggable,
  useElementBounding,
  useErrorHandling,
  useEventBus,
  useEventListener,
  useExecutionStore,
  useExtensionService,
  useExtensionStore,
  useFavicon,
  useFirebaseAuthActions,
  useFirebaseAuthStore,
  useKeybindingStore,
  useLitegraphService,
  useLocalStorage,
  useMenuItemStore,
  useModelStore,
  useModelToNodeStore,
  useNodeBookmarkStore,
  useNodeDefStore,
  useNodeDragAndDrop,
  useNodeFileInput,
  useNodeFrequencyStore,
  useNodePaste,
  usePragmaticDraggable,
  usePragmaticDroppable,
  useQueuePendingTaskCountStore,
  useQueueSettingsStore,
  useQueueStore,
  useRouter,
  useSettingStore,
  useSidebarTabStore,
  useSystemStatsStore,
  useTimeout,
  useTitle,
  useTitleEditorStore,
  useToastStore,
  useUserStore,
  useWidgetStore,
  useWorkflowBookmarkStore,
  useWorkflowService,
  useWorkflowStore,
  useWorkspaceStore,
  watchDebounced,
  whenever,
  xtermExports
};
//# sourceMappingURL=index-BKCJpyD3.js.map
